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

1.17      albertel    1: # The LearningOnline Network with CAPA
1.13      albertel    2: # The LON-CAPA Grading handler
1.17      albertel    3: #
1.736   ! damieng     4: # $Id: grades.pm,v 1.735 2015/03/18 12:53:24 raeburn Exp $
1.17      albertel    5: #
                      6: # Copyright Michigan State University Board of Trustees
                      7: #
                      8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
                      9: #
                     10: # LON-CAPA is free software; you can redistribute it and/or modify
                     11: # it under the terms of the GNU General Public License as published by
                     12: # the Free Software Foundation; either version 2 of the License, or
                     13: # (at your option) any later version.
                     14: #
                     15: # LON-CAPA is distributed in the hope that it will be useful,
                     16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
                     17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
                     18: # GNU General Public License for more details.
                     19: #
                     20: # You should have received a copy of the GNU General Public License
                     21: # along with LON-CAPA; if not, write to the Free Software
                     22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
                     23: #
                     24: # /home/httpd/html/adm/gpl.txt
                     25: #
                     26: # http://www.lon-capa.org/
                     27: #
1.1       albertel   28: 
1.529     jms        29: 
                     30: 
1.1       albertel   31: package Apache::grades;
                     32: use strict;
                     33: use Apache::style;
                     34: use Apache::lonxml;
                     35: use Apache::lonnet;
1.3       albertel   36: use Apache::loncommon;
1.112     ng         37: use Apache::lonhtmlcommon;
1.68      ng         38: use Apache::lonnavmaps;
1.1       albertel   39: use Apache::lonhomework;
1.456     banghart   40: use Apache::lonpickcode;
1.55      matthew    41: use Apache::loncoursedata;
1.362     albertel   42: use Apache::lonmsg();
1.646     raeburn    43: use Apache::Constants qw(:common :http);
1.167     sakharuk   44: use Apache::lonlocal;
1.386     raeburn    45: use Apache::lonenc;
1.622     www        46: use Apache::lonstathelpers;
1.639     www        47: use Apache::lonquickgrades;
1.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.674     raeburn    57: my %old_essays=();
1.447     foxr       58: 
1.513     foxr       59: #  These variables are used to recover from ssi errors
                     60: 
                     61: my $ssi_retries = 5;
                     62: my $ssi_error;
                     63: my $ssi_error_resource;
                     64: my $ssi_error_message;
                     65: 
                     66: 
                     67: sub ssi_with_retries {
                     68:     my ($resource, $retries, %form) = @_;
                     69:     my ($content, $response) = &Apache::loncommon::ssi_with_retries($resource, $retries, %form);
                     70:     if ($response->is_error) {
                     71: 	$ssi_error          = 1;
                     72: 	$ssi_error_resource = $resource;
                     73: 	$ssi_error_message  = $response->code . " " . $response->message;
                     74:     }
                     75: 
                     76:     return $content;
                     77: 
                     78: }
                     79: #
                     80: #  Prodcuces an ssi retry failure error message to the user:
                     81: #
                     82: 
                     83: sub ssi_print_error {
                     84:     my ($r) = @_;
1.516     raeburn    85:     my $helpurl = &Apache::loncommon::top_nav_help('Helpdesk');
                     86:     $r->print('
                     87: <br />
                     88: <h2>'.&mt('An unrecoverable network error occurred:').'</h2>
                     89: <p>
                     90: '.&mt('Unable to retrieve a resource from a server:').'<br />
                     91: '.&mt('Resource:').' '.$ssi_error_resource.'<br />
                     92: '.&mt('Error:').' '.$ssi_error_message.'
                     93: </p>
                     94: <p>'.
                     95: &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 />'.
                     96: &mt('If the error persists, please contact the [_1] for assistance.',$helpurl).
                     97: '</p>');
                     98:     return;
1.513     foxr       99: }
                    100: 
1.44      ng        101: #
1.146     albertel  102: # --- Retrieve the parts from the metadata file.---
1.598     www       103: # Returns an array of everything that the resources stores away
                    104: #
                    105: 
1.44      ng        106: sub getpartlist {
1.582     raeburn   107:     my ($symb,$errorref) = @_;
1.439     albertel  108: 
                    109:     my $navmap   = Apache::lonnavmaps::navmap->new();
1.582     raeburn   110:     unless (ref($navmap)) {
                    111:         if (ref($errorref)) { 
                    112:             $$errorref = 'navmap';
                    113:             return;
                    114:         }
                    115:     }
1.439     albertel  116:     my $res      = $navmap->getBySymb($symb);
                    117:     my $partlist = $res->parts();
                    118:     my $url      = $res->src();
                    119:     my @metakeys = split(/,/,&Apache::lonnet::metadata($url,'keys'));
                    120: 
1.146     albertel  121:     my @stores;
1.439     albertel  122:     foreach my $part (@{ $partlist }) {
1.146     albertel  123: 	foreach my $key (@metakeys) {
                    124: 	    if ($key =~ m/^stores_\Q$part\E_/) { push(@stores,$key); }
                    125: 	}
                    126:     }
                    127:     return @stores;
1.2       albertel  128: }
                    129: 
1.129     ng        130: #--- Format fullname, username:domain if different for display
                    131: #--- Use anywhere where the student names are listed
                    132: sub nameUserString {
                    133:     my ($type,$fullname,$uname,$udom) = @_;
                    134:     if ($type eq 'header') {
1.485     albertel  135: 	return '<b>&nbsp;'.&mt('Fullname').'&nbsp;</b><span class="LC_internal_info">('.&mt('Username').')</span>';
1.129     ng        136:     } else {
1.398     albertel  137: 	return '&nbsp;'.$fullname.'<span class="LC_internal_info">&nbsp;('.$uname.
                    138: 	    ($env{'user.domain'} eq $udom ? '' : ' ('.$udom.')').')</span>';
1.129     ng        139:     }
                    140: }
                    141: 
1.44      ng        142: #--- Get the partlist and the response type for a given problem. ---
                    143: #--- Indicate if a response type is coded handgraded or not. ---
1.623     www       144: #--- Sets response_error pointer to "1" if navmaps object broken ---
1.39      ng        145: sub response_type {
1.582     raeburn   146:     my ($symb,$response_error) = @_;
1.377     albertel  147: 
                    148:     my $navmap = Apache::lonnavmaps::navmap->new();
1.582     raeburn   149:     unless (ref($navmap)) {
                    150:         if (ref($response_error)) {
                    151:             $$response_error = 1;
                    152:         }
                    153:         return;
                    154:     }
1.377     albertel  155:     my $res = $navmap->getBySymb($symb);
1.593     raeburn   156:     unless (ref($res)) {
                    157:         $$response_error = 1;
                    158:         return;
                    159:     }
1.377     albertel  160:     my $partlist = $res->parts();
1.392     albertel  161:     my %vPart = 
                    162: 	map { $_ => 1 } (&Apache::loncommon::get_env_multiple('form.vPart'));
1.377     albertel  163:     my (%response_types,%handgrade);
                    164:     foreach my $part (@{ $partlist }) {
1.392     albertel  165: 	next if (%vPart && !exists($vPart{$part}));
                    166: 
1.377     albertel  167: 	my @types = $res->responseType($part);
                    168: 	my @ids = $res->responseIds($part);
                    169: 	for (my $i=0; $i < scalar(@ids); $i++) {
                    170: 	    $response_types{$part}{$ids[$i]} = $types[$i];
                    171: 	    $handgrade{$part.'_'.$ids[$i]} = 
                    172: 		&Apache::lonnet::EXT('resource.'.$part.'_'.$ids[$i].
                    173: 				     '.handgrade',$symb);
1.41      ng        174: 	}
                    175:     }
1.377     albertel  176:     return ($partlist,\%handgrade,\%response_types);
1.39      ng        177: }
                    178: 
1.375     albertel  179: sub flatten_responseType {
                    180:     my ($responseType) = @_;
                    181:     my @part_response_id =
                    182: 	map { 
                    183: 	    my $part = $_;
                    184: 	    map {
                    185: 		[$part,$_]
                    186: 		} sort(keys(%{ $responseType->{$part} }));
                    187: 	} sort(keys(%$responseType));
                    188:     return @part_response_id;
                    189: }
                    190: 
1.207     albertel  191: sub get_display_part {
1.324     albertel  192:     my ($partID,$symb)=@_;
1.207     albertel  193:     my $display=&Apache::lonnet::EXT('resource.'.$partID.'.display',$symb);
                    194:     if (defined($display) and $display ne '') {
1.577     bisitz    195:         $display.= ' (<span class="LC_internal_info">'
                    196:                   .&mt('Part ID: [_1]',$partID).'</span>)';
1.207     albertel  197:     } else {
                    198: 	$display=$partID;
                    199:     }
                    200:     return $display;
                    201: }
1.269     raeburn   202: 
1.434     albertel  203: sub reset_caches {
                    204:     &reset_analyze_cache();
                    205:     &reset_perm();
1.674     raeburn   206:     &reset_old_essays();
1.434     albertel  207: }
                    208: 
                    209: {
                    210:     my %analyze_cache;
1.557     raeburn   211:     my %analyze_cache_formkeys;
1.148     albertel  212: 
1.434     albertel  213:     sub reset_analyze_cache {
                    214: 	undef(%analyze_cache);
1.557     raeburn   215:         undef(%analyze_cache_formkeys);
1.434     albertel  216:     }
                    217: 
                    218:     sub get_analyze {
1.649     raeburn   219: 	my ($symb,$uname,$udom,$no_increment,$add_to_hash,$type,$trial,$rndseed,$bubbles_per_row)=@_;
1.434     albertel  220: 	my $key = "$symb\0$uname\0$udom";
1.640     raeburn   221:         if ($type eq 'randomizetry') {
                    222:             if ($trial ne '') {
                    223:                 $key .= "\0".$trial;
                    224:             }
                    225:         }
1.557     raeburn   226: 	if (exists($analyze_cache{$key})) {
                    227:             my $getupdate = 0;
                    228:             if (ref($add_to_hash) eq 'HASH') {
                    229:                 foreach my $item (keys(%{$add_to_hash})) {
                    230:                     if (ref($analyze_cache_formkeys{$key}) eq 'HASH') {
                    231:                         if (!exists($analyze_cache_formkeys{$key}{$item})) {
                    232:                             $getupdate = 1;
                    233:                             last;
                    234:                         }
                    235:                     } else {
                    236:                         $getupdate = 1;
                    237:                     }
                    238:                 }
                    239:             }
                    240:             if (!$getupdate) {
                    241:                 return $analyze_cache{$key};
                    242:             }
                    243:         }
1.434     albertel  244: 
                    245: 	my (undef,undef,$url)=&Apache::lonnet::decode_symb($symb);
                    246: 	$url=&Apache::lonnet::clutter($url);
1.557     raeburn   247:         my %form = ('grade_target'      => 'analyze',
                    248:                     'grade_domain'      => $udom,
                    249:                     'grade_symb'        => $symb,
                    250:                     'grade_courseid'    =>  $env{'request.course.id'},
                    251:                     'grade_username'    => $uname,
                    252:                     'grade_noincrement' => $no_increment);
1.649     raeburn   253:         if ($bubbles_per_row ne '') {
                    254:             $form{'bubbles_per_row'} = $bubbles_per_row;
                    255:         }
1.640     raeburn   256:         if ($type eq 'randomizetry') {
                    257:             $form{'grade_questiontype'} = $type;
                    258:             if ($rndseed ne '') {
                    259:                 $form{'grade_rndseed'} = $rndseed;
                    260:             }
                    261:         }
1.557     raeburn   262:         if (ref($add_to_hash)) {
                    263:             %form = (%form,%{$add_to_hash});
1.640     raeburn   264:         }
1.557     raeburn   265: 	my $subresult=&ssi_with_retries($url, $ssi_retries,%form);
1.434     albertel  266: 	(undef,$subresult)=split(/_HASH_REF__/,$subresult,2);
                    267: 	my %analyze=&Apache::lonnet::str2hash($subresult);
1.557     raeburn   268:         if (ref($add_to_hash) eq 'HASH') {
                    269:             $analyze_cache_formkeys{$key} = $add_to_hash;
                    270:         } else {
                    271:             $analyze_cache_formkeys{$key} = {};
                    272:         }
1.434     albertel  273: 	return $analyze_cache{$key} = \%analyze;
                    274:     }
                    275: 
                    276:     sub get_order {
1.640     raeburn   277: 	my ($partid,$respid,$symb,$uname,$udom,$no_increment,$type,$trial,$rndseed)=@_;
                    278: 	my $analyze = &get_analyze($symb,$uname,$udom,$no_increment,undef,$type,$trial,$rndseed);
1.434     albertel  279: 	return $analyze->{"$partid.$respid.shown"};
                    280:     }
                    281: 
                    282:     sub get_radiobutton_correct_foil {
1.640     raeburn   283: 	my ($partid,$respid,$symb,$uname,$udom,$type,$trial,$rndseed)=@_;
                    284: 	my $analyze = &get_analyze($symb,$uname,$udom,undef,undef,$type,$trial,$rndseed);
                    285:         my $foils = &get_order($partid,$respid,$symb,$uname,$udom,undef,$type,$trial,$rndseed);
1.555     raeburn   286:         if (ref($foils) eq 'ARRAY') {
                    287: 	    foreach my $foil (@{$foils}) {
                    288: 	        if ($analyze->{"$partid.$respid.foil.value.$foil"} eq 'true') {
                    289: 		    return $foil;
                    290: 	        }
1.434     albertel  291: 	    }
                    292: 	}
                    293:     }
1.554     raeburn   294: 
                    295:     sub scantron_partids_tograde {
1.649     raeburn   296:         my ($resource,$cid,$uname,$udom,$check_for_randomlist,$bubbles_per_row) = @_;
1.554     raeburn   297:         my (%analysis,@parts);
                    298:         if (ref($resource)) {
                    299:             my $symb = $resource->symb();
1.557     raeburn   300:             my $add_to_form;
                    301:             if ($check_for_randomlist) {
                    302:                 $add_to_form = { 'check_parts_withrandomlist' => 1,};
                    303:             }
1.649     raeburn   304:             my $analyze = 
                    305:                 &get_analyze($symb,$uname,$udom,undef,$add_to_form,
                    306:                              undef,undef,undef,$bubbles_per_row);
1.554     raeburn   307:             if (ref($analyze) eq 'HASH') {
                    308:                 %analysis = %{$analyze};
                    309:             }
                    310:             if (ref($analysis{'parts'}) eq 'ARRAY') {
                    311:                 foreach my $part (@{$analysis{'parts'}}) {
                    312:                     my ($id,$respid) = split(/\./,$part);
                    313:                     if (!&Apache::loncommon::check_if_partid_hidden($id,$symb,$udom,$uname)) {
                    314:                         push(@parts,$part);
                    315:                     }
                    316:                 }
                    317:             }
                    318:         }
                    319:         return (\%analysis,\@parts);
                    320:     }
                    321: 
1.148     albertel  322: }
1.434     albertel  323: 
1.118     ng        324: #--- Clean response type for display
1.335     albertel  325: #--- Currently filters option/rank/radiobutton/match/essay/Task
                    326: #        response types only.
1.118     ng        327: sub cleanRecord {
1.336     albertel  328:     my ($answer,$response,$symb,$partid,$respid,$record,$order,$version,
1.640     raeburn   329: 	$uname,$udom,$type,$trial,$rndseed) = @_;
1.398     albertel  330:     my $grayFont = '<span class="LC_internal_info">';
1.148     albertel  331:     if ($response =~ /^(option|rank)$/) {
                    332: 	my %answer=&Apache::lonnet::str2hash($answer);
1.720     kruse     333:         my @answer = %answer;
                    334:         %answer = map {&HTML::Entities::encode($_, '"<>&')}  @answer;
1.148     albertel  335: 	my %grading=&Apache::lonnet::str2hash($record->{$version."resource.$partid.$respid.submissiongrading"});
                    336: 	my ($toprow,$bottomrow);
                    337: 	foreach my $foil (@$order) {
                    338: 	    if ($grading{$foil} == 1) {
                    339: 		$toprow.='<td><b>'.$answer{$foil}.'&nbsp;</b></td>';
                    340: 	    } else {
                    341: 		$toprow.='<td><i>'.$answer{$foil}.'&nbsp;</i></td>';
                    342: 	    }
1.398     albertel  343: 	    $bottomrow.='<td>'.$grayFont.$foil.'</span>&nbsp;</td>';
1.148     albertel  344: 	}
                    345: 	return '<blockquote><table border="1">'.
1.466     albertel  346: 	    '<tr valign="top"><td>'.&mt('Answer').'</td>'.$toprow.'</tr>'.
                    347: 	    '<tr valign="top"><td>'.$grayFont.&mt('Option ID').'</span></td>'.
1.660     raeburn   348: 	    $bottomrow.'</tr></table></blockquote>';
1.148     albertel  349:     } elsif ($response eq 'match') {
                    350: 	my %answer=&Apache::lonnet::str2hash($answer);
1.720     kruse     351:         my @answer = %answer;
                    352:         %answer = map {&HTML::Entities::encode($_, '"<>&')}  @answer;
1.148     albertel  353: 	my %grading=&Apache::lonnet::str2hash($record->{$version."resource.$partid.$respid.submissiongrading"});
                    354: 	my @items=&Apache::lonnet::str2array($record->{$version."resource.$partid.$respid.submissionitems"});
                    355: 	my ($toprow,$middlerow,$bottomrow);
                    356: 	foreach my $foil (@$order) {
                    357: 	    my $item=shift(@items);
                    358: 	    if ($grading{$foil} == 1) {
                    359: 		$toprow.='<td><b>'.$item.'&nbsp;</b></td>';
1.398     albertel  360: 		$middlerow.='<td><b>'.$grayFont.$answer{$foil}.'&nbsp;</span></b></td>';
1.148     albertel  361: 	    } else {
                    362: 		$toprow.='<td><i>'.$item.'&nbsp;</i></td>';
1.398     albertel  363: 		$middlerow.='<td><i>'.$grayFont.$answer{$foil}.'&nbsp;</span></i></td>';
1.148     albertel  364: 	    }
1.398     albertel  365: 	    $bottomrow.='<td>'.$grayFont.$foil.'</span>&nbsp;</td>';
1.118     ng        366: 	}
1.126     ng        367: 	return '<blockquote><table border="1">'.
1.466     albertel  368: 	    '<tr valign="top"><td>'.&mt('Answer').'</td>'.$toprow.'</tr>'.
                    369: 	    '<tr valign="top"><td>'.$grayFont.&mt('Item ID').'</span></td>'.
1.148     albertel  370: 	    $middlerow.'</tr>'.
1.466     albertel  371: 	    '<tr valign="top"><td>'.$grayFont.&mt('Option ID').'</span></td>'.
1.660     raeburn   372: 	    $bottomrow.'</tr></table></blockquote>';
1.148     albertel  373:     } elsif ($response eq 'radiobutton') {
                    374: 	my %answer=&Apache::lonnet::str2hash($answer);
1.720     kruse     375:         my @answer = %answer;
                    376:         %answer = map {&HTML::Entities::encode($_, '"<>&')}  @answer;
1.148     albertel  377: 	my ($toprow,$bottomrow);
1.434     albertel  378: 	my $correct = 
1.640     raeburn   379: 	    &get_radiobutton_correct_foil($partid,$respid,$symb,$uname,$udom,$type,$trial,$rndseed);
1.434     albertel  380: 	foreach my $foil (@$order) {
1.148     albertel  381: 	    if (exists($answer{$foil})) {
1.434     albertel  382: 		if ($foil eq $correct) {
1.466     albertel  383: 		    $toprow.='<td><b>'.&mt('true').'</b></td>';
1.148     albertel  384: 		} else {
1.466     albertel  385: 		    $toprow.='<td><i>'.&mt('true').'</i></td>';
1.148     albertel  386: 		}
                    387: 	    } else {
1.466     albertel  388: 		$toprow.='<td>'.&mt('false').'</td>';
1.148     albertel  389: 	    }
1.398     albertel  390: 	    $bottomrow.='<td>'.$grayFont.$foil.'</span>&nbsp;</td>';
1.148     albertel  391: 	}
                    392: 	return '<blockquote><table border="1">'.
1.466     albertel  393: 	    '<tr valign="top"><td>'.&mt('Answer').'</td>'.$toprow.'</tr>'.
                    394: 	    '<tr valign="top"><td>'.$grayFont.&mt('Option ID').'</span></td>'.
1.660     raeburn   395: 	    $bottomrow.'</tr></table></blockquote>';
1.148     albertel  396:     } elsif ($response eq 'essay') {
1.257     albertel  397: 	if (! exists ($env{'form.'.$symb})) {
1.122     ng        398: 	    my (%keyhash) = &Apache::lonnet::dump('nohist_handgrade',
1.257     albertel  399: 						  $env{'course.'.$env{'request.course.id'}.'.domain'},
                    400: 						  $env{'course.'.$env{'request.course.id'}.'.num'});
1.122     ng        401: 
1.257     albertel  402: 	    my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
                    403: 	    $env{'form.keywords'} = $keyhash{$symb.'_keywords'} ne '' ? $keyhash{$symb.'_keywords'} : '';
                    404: 	    $env{'form.kwclr'}    = $keyhash{$loginuser.'_kwclr'} ne '' ? $keyhash{$loginuser.'_kwclr'} : 'red';
                    405: 	    $env{'form.kwsize'}   = $keyhash{$loginuser.'_kwsize'} ne '' ? $keyhash{$loginuser.'_kwsize'} : '0';
                    406: 	    $env{'form.kwstyle'}  = $keyhash{$loginuser.'_kwstyle'} ne '' ? $keyhash{$loginuser.'_kwstyle'} : '';
                    407: 	    $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        408: 	}
1.730     kruse     409: 	return '<br /><br /><blockquote><tt>'.&keywords_highlight($answer).'</tt></blockquote>';
1.720     kruse     410: 
1.268     albertel  411:     } elsif ( $response eq 'organic') {
1.721     bisitz    412:         my $result=&mt('Smile representation: [_1]',
                    413:                            '"<tt>'.&HTML::Entities::encode($answer, '"<>&').'</tt>"');
1.268     albertel  414: 	my $jme=$record->{$version."resource.$partid.$respid.molecule"};
                    415: 	$result.=&Apache::chemresponse::jme_img($jme,$answer,400);
                    416: 	return $result;
1.335     albertel  417:     } elsif ( $response eq 'Task') {
                    418: 	if ( $answer eq 'SUBMITTED') {
                    419: 	    my $files = $record->{$version."resource.$respid.$partid.bridgetask.portfiles"};
1.336     albertel  420: 	    my $result = &Apache::bridgetask::file_list($files,$uname,$udom);
1.335     albertel  421: 	    return $result;
                    422: 	} elsif ( grep(/^\Q$version\E.*?\.instance$/, keys(%{$record})) ) {
                    423: 	    my @matches = grep(/^\Q$version\E.*?\.instance$/,
                    424: 			       keys(%{$record}));
                    425: 	    return join('<br />',($version,@matches));
                    426: 			       
                    427: 			       
                    428: 	} else {
                    429: 	    my $result =
                    430: 		'<p>'
                    431: 		.&mt('Overall result: [_1]',
                    432: 		     $record->{$version."resource.$respid.$partid.status"})
                    433: 		.'</p>';
                    434: 	    
                    435: 	    $result .= '<ul>';
                    436: 	    my @grade = grep(/^\Q${version}resource.$respid.$partid.\E[^.]*[.]status$/,
                    437: 			     keys(%{$record}));
                    438: 	    foreach my $grade (sort(@grade)) {
                    439: 		my ($dim) = ($grade =~/[.]([^.]+)[.]status$/);
                    440: 		$result.= '<li>'.&mt("Dimension: [_1], status [_2] ",
                    441: 				     $dim, $record->{$grade}).
                    442: 			  '</li>';
                    443: 	    }
                    444: 	    $result.='</ul>';
                    445: 	    return $result;
                    446: 	}
1.716     bisitz    447:     } elsif ( $response =~ m/(?:numerical|formula|custom)/) {
                    448:         # Respect multiple input fields, see Bug #5409
1.440     albertel  449: 	$answer = 
                    450: 	    &Apache::loncommon::format_previous_attempt_value('submission',
                    451: 							      $answer);
1.720     kruse     452: 	return $answer;
1.122     ng        453:     }
1.720     kruse     454:     return &HTML::Entities::encode($answer, '"<>&');
1.118     ng        455: }
                    456: 
                    457: #-- A couple of common js functions
                    458: sub commonJSfunctions {
                    459:     my $request = shift;
1.597     wenzelju  460:     $request->print(&Apache::lonhtmlcommon::scripttag(<<COMMONJSFUNCTIONS));
1.118     ng        461:     function radioSelection(radioButton) {
                    462: 	var selection=null;
                    463: 	if (radioButton.length > 1) {
                    464: 	    for (var i=0; i<radioButton.length; i++) {
                    465: 		if (radioButton[i].checked) {
                    466: 		    return radioButton[i].value;
                    467: 		}
                    468: 	    }
                    469: 	} else {
                    470: 	    if (radioButton.checked) return radioButton.value;
                    471: 	}
                    472: 	return selection;
                    473:     }
                    474: 
                    475:     function pullDownSelection(selectOne) {
                    476: 	var selection="";
                    477: 	if (selectOne.length > 1) {
                    478: 	    for (var i=0; i<selectOne.length; i++) {
                    479: 		if (selectOne[i].selected) {
                    480: 		    return selectOne[i].value;
                    481: 		}
                    482: 	    }
                    483: 	} else {
1.138     albertel  484:             // only one value it must be the selected one
                    485: 	    return selectOne.value;
1.118     ng        486: 	}
                    487:     }
                    488: COMMONJSFUNCTIONS
                    489: }
                    490: 
1.44      ng        491: #--- Dumps the class list with usernames,list of sections,
                    492: #--- section, ids and fullnames for each user.
                    493: sub getclasslist {
1.449     banghart  494:     my ($getsec,$filterlist,$getgroup) = @_;
1.291     albertel  495:     my @getsec;
1.450     banghart  496:     my @getgroup;
1.442     banghart  497:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
1.291     albertel  498:     if (!ref($getsec)) {
                    499: 	if ($getsec ne '' && $getsec ne 'all') {
                    500: 	    @getsec=($getsec);
                    501: 	}
                    502:     } else {
                    503: 	@getsec=@{$getsec};
                    504:     }
                    505:     if (grep(/^all$/,@getsec)) { undef(@getsec); }
1.450     banghart  506:     if (!ref($getgroup)) {
                    507: 	if ($getgroup ne '' && $getgroup ne 'all') {
                    508: 	    @getgroup=($getgroup);
                    509: 	}
                    510:     } else {
                    511: 	@getgroup=@{$getgroup};
                    512:     }
                    513:     if (grep(/^all$/,@getgroup)) { undef(@getgroup); }
1.291     albertel  514: 
1.449     banghart  515:     my ($classlist,$keylist)=&Apache::loncoursedata::get_classlist();
1.49      albertel  516:     # Bail out if we were unable to get the classlist
1.56      matthew   517:     return if (! defined($classlist));
1.449     banghart  518:     &Apache::loncoursedata::get_group_memberships($classlist,$keylist);
1.56      matthew   519:     #
                    520:     my %sections;
                    521:     my %fullnames;
1.205     matthew   522:     foreach my $student (keys(%$classlist)) {
                    523:         my $end      = 
                    524:             $classlist->{$student}->[&Apache::loncoursedata::CL_END()];
                    525:         my $start    = 
                    526:             $classlist->{$student}->[&Apache::loncoursedata::CL_START()];
                    527:         my $id       = 
                    528:             $classlist->{$student}->[&Apache::loncoursedata::CL_ID()];
                    529:         my $section  = 
                    530:             $classlist->{$student}->[&Apache::loncoursedata::CL_SECTION()];
                    531:         my $fullname = 
                    532:             $classlist->{$student}->[&Apache::loncoursedata::CL_FULLNAME()];
                    533:         my $status   = 
                    534:             $classlist->{$student}->[&Apache::loncoursedata::CL_STATUS()];
1.449     banghart  535:         my $group   = 
                    536:             $classlist->{$student}->[&Apache::loncoursedata::CL_GROUP()];
1.76      ng        537: 	# filter students according to status selected
1.442     banghart  538: 	if ($filterlist && (!($stu_status =~ /Any/))) {
                    539: 	    if (!($stu_status =~ $status)) {
1.450     banghart  540: 		delete($classlist->{$student});
1.76      ng        541: 		next;
                    542: 	    }
                    543: 	}
1.450     banghart  544: 	# filter students according to groups selected
1.453     banghart  545: 	my @stu_groups = split(/,/,$group);
1.450     banghart  546: 	if (@getgroup) {
                    547: 	    my $exclude = 1;
1.454     banghart  548: 	    foreach my $grp (@getgroup) {
                    549: 	        foreach my $stu_group (@stu_groups) {
1.453     banghart  550: 	            if ($stu_group eq $grp) {
                    551: 	                $exclude = 0;
                    552:     	            } 
1.450     banghart  553: 	        }
1.453     banghart  554:     	        if (($grp eq 'none') && !$group) {
                    555:         	        $exclude = 0;
                    556:         	}
1.450     banghart  557: 	    }
                    558: 	    if ($exclude) {
                    559: 	        delete($classlist->{$student});
                    560: 	    }
                    561: 	}
1.205     matthew   562: 	$section = ($section ne '' ? $section : 'none');
1.106     albertel  563: 	if (&canview($section)) {
1.291     albertel  564: 	    if (!@getsec || grep(/^\Q$section\E$/,@getsec)) {
1.103     albertel  565: 		$sections{$section}++;
1.450     banghart  566: 		if ($classlist->{$student}) {
                    567: 		    $fullnames{$student}=$fullname;
                    568: 		}
1.103     albertel  569: 	    } else {
1.205     matthew   570: 		delete($classlist->{$student});
1.103     albertel  571: 	    }
                    572: 	} else {
1.205     matthew   573: 	    delete($classlist->{$student});
1.103     albertel  574: 	}
1.44      ng        575:     }
                    576:     my %seen = ();
1.56      matthew   577:     my @sections = sort(keys(%sections));
                    578:     return ($classlist,\@sections,\%fullnames);
1.44      ng        579: }
                    580: 
1.103     albertel  581: sub canmodify {
                    582:     my ($sec)=@_;
                    583:     if ($perm{'mgr'}) {
                    584: 	if (!defined($perm{'mgr_section'})) {
                    585: 	    # can modify whole class
                    586: 	    return 1;
                    587: 	} else {
                    588: 	    if ($sec eq $perm{'mgr_section'}) {
                    589: 		#can modify the requested section
                    590: 		return 1;
                    591: 	    } else {
                    592: 		# can't modify the request section
                    593: 		return 0;
                    594: 	    }
                    595: 	}
                    596:     }
                    597:     #can't modify
                    598:     return 0;
                    599: }
                    600: 
                    601: sub canview {
                    602:     my ($sec)=@_;
                    603:     if ($perm{'vgr'}) {
                    604: 	if (!defined($perm{'vgr_section'})) {
                    605: 	    # can modify whole class
                    606: 	    return 1;
                    607: 	} else {
                    608: 	    if ($sec eq $perm{'vgr_section'}) {
                    609: 		#can modify the requested section
                    610: 		return 1;
                    611: 	    } else {
                    612: 		# can't modify the request section
                    613: 		return 0;
                    614: 	    }
                    615: 	}
                    616:     }
                    617:     #can't modify
                    618:     return 0;
                    619: }
                    620: 
1.44      ng        621: #--- Retrieve the grade status of a student for all the parts
                    622: sub student_gradeStatus {
1.324     albertel  623:     my ($symb,$udom,$uname,$partlist) = @_;
1.257     albertel  624:     my %record     = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
1.44      ng        625:     my %partstatus = ();
                    626:     foreach (@$partlist) {
1.128     ng        627: 	my ($status,undef)   = split(/_/,$record{"resource.$_.solved"},2);
1.44      ng        628: 	$status              = 'nothing' if ($status eq '');
                    629: 	$partstatus{$_}      = $status;
                    630: 	my $subkey           = "resource.$_.submitted_by";
                    631: 	$partstatus{$subkey} = $record{$subkey} if ($record{$subkey} ne '');
                    632:     }
                    633:     return %partstatus;
                    634: }
                    635: 
1.45      ng        636: # hidden form and javascript that calls the form
                    637: # Use by verifyscript and viewgrades
                    638: # Shows a student's view of problem and submission
                    639: sub jscriptNform {
1.324     albertel  640:     my ($symb) = @_;
1.442     banghart  641:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
1.597     wenzelju  642:     my $jscript= &Apache::lonhtmlcommon::scripttag(
1.45      ng        643: 	'    function viewOneStudent(user,domain) {'."\n".
                    644: 	'	document.onestudent.student.value = user;'."\n".
                    645: 	'	document.onestudent.userdom.value = domain;'."\n".
                    646: 	'	document.onestudent.submit();'."\n".
                    647: 	'    }'."\n".
1.597     wenzelju  648: 	"\n");
1.45      ng        649:     $jscript.= '<form action="/adm/grades" method="post" name="onestudent">'."\n".
1.418     albertel  650: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.442     banghart  651: 	'<input type="hidden" name="Status"  value="'.$stu_status.'" />'."\n".
1.45      ng        652: 	'<input type="hidden" name="command" value="submission" />'."\n".
                    653: 	'<input type="hidden" name="student" value="" />'."\n".
                    654: 	'<input type="hidden" name="userdom" value="" />'."\n".
                    655: 	'</form>'."\n";
                    656:     return $jscript;
                    657: }
1.39      ng        658: 
1.447     foxr      659: 
                    660: 
1.315     bowersj2  661: # Given the score (as a number [0-1] and the weight) what is the final
                    662: # point value? This function will round to the nearest tenth, third,
                    663: # or quarter if one of those is within the tolerance of .00001.
1.316     albertel  664: sub compute_points {
1.315     bowersj2  665:     my ($score, $weight) = @_;
                    666:     
                    667:     my $tolerance = .00001;
                    668:     my $points = $score * $weight;
                    669: 
                    670:     # Check for nearness to 1/x.
                    671:     my $check_for_nearness = sub {
                    672:         my ($factor) = @_;
                    673:         my $num = ($points * $factor) + $tolerance;
                    674:         my $floored_num = floor($num);
1.316     albertel  675:         if ($num - $floored_num < 2 * $tolerance * $factor) {
1.315     bowersj2  676:             return $floored_num / $factor;
                    677:         }
                    678:         return $points;
                    679:     };
                    680: 
                    681:     $points = $check_for_nearness->(10);
                    682:     $points = $check_for_nearness->(3);
                    683:     $points = $check_for_nearness->(4);
                    684:     
                    685:     return $points;
                    686: }
                    687: 
1.44      ng        688: #------------------ End of general use routines --------------------
1.87      www       689: 
                    690: #
                    691: # Find most similar essay
                    692: #
                    693: 
                    694: sub most_similar {
1.674     raeburn   695:     my ($uname,$udom,$symb,$uessay)=@_;
                    696: 
                    697:     unless ($symb) { return ''; }
                    698: 
                    699:     unless (ref($old_essays{$symb}) eq 'HASH') { return ''; }
1.87      www       700: 
                    701: # ignore spaces and punctuation
                    702: 
                    703:     $uessay=~s/\W+/ /gs;
                    704: 
1.282     www       705: # ignore empty submissions (occuring when only files are sent)
                    706: 
1.598     www       707:     unless ($uessay=~/\w+/s) { return ''; }
1.282     www       708: 
1.87      www       709: # these will be returned. Do not care if not at least 50 percent similar
1.88      www       710:     my $limit=0.6;
1.87      www       711:     my $sname='';
                    712:     my $sdom='';
                    713:     my $scrsid='';
                    714:     my $sessay='';
                    715: # go through all essays ...
1.674     raeburn   716:     foreach my $tkey (keys(%{$old_essays{$symb}})) {
1.426     albertel  717: 	my ($tname,$tdom,$tcrsid)=map {&unescape($_)} (split(/\./,$tkey));
1.87      www       718: # ... except the same student
1.426     albertel  719:         next if (($tname eq $uname) && ($tdom eq $udom));
1.674     raeburn   720: 	my $tessay=$old_essays{$symb}{$tkey};
1.426     albertel  721: 	$tessay=~s/\W+/ /gs;
1.87      www       722: # String similarity gives up if not even limit
1.426     albertel  723: 	my $tsimilar=&String::Similarity::similarity($uessay,$tessay,$limit);
1.87      www       724: # Found one
1.426     albertel  725: 	if ($tsimilar>$limit) {
                    726: 	    $limit=$tsimilar;
                    727: 	    $sname=$tname;
                    728: 	    $sdom=$tdom;
                    729: 	    $scrsid=$tcrsid;
1.674     raeburn   730: 	    $sessay=$old_essays{$symb}{$tkey};
1.426     albertel  731: 	}
1.87      www       732:     }
1.88      www       733:     if ($limit>0.6) {
1.87      www       734:        return ($sname,$sdom,$scrsid,$sessay,$limit);
                    735:     } else {
                    736:        return ('','','','',0);
                    737:     }
                    738: }
                    739: 
1.44      ng        740: #-------------------------------------------------------------------
                    741: 
                    742: #------------------------------------ Receipt Verification Routines
1.45      ng        743: #
1.602     www       744: 
                    745: sub initialverifyreceipt {
1.608     www       746:    my ($request,$symb) = @_;
1.602     www       747:    &commonJSfunctions($request);
1.694     bisitz    748:    return '<form name="gradingMenu" action=""><input type="submit" value="'.&mt('Verify Receipt Number.').'" />'.
1.602     www       749:         &Apache::lonnet::recprefix($env{'request.course.id'}).
                    750:         '-<input type="text" name="receipt" size="4" />'.
1.603     www       751:         '<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
                    752:         '<input type="hidden" name="command" value="verify" />'.
                    753:         "</form>\n";
1.602     www       754: }
                    755: 
1.44      ng        756: #--- Check whether a receipt number is valid.---
                    757: sub verifyreceipt {
1.608     www       758:     my ($request,$symb)  = @_;
1.44      ng        759: 
1.257     albertel  760:     my $courseid = $env{'request.course.id'};
1.184     www       761:     my $receipt  = &Apache::lonnet::recprefix($courseid).'-'.
1.257     albertel  762: 	$env{'form.receipt'};
1.44      ng        763:     $receipt     =~ s/[^\-\d]//g;
                    764: 
1.487     albertel  765:     my $title.=
                    766: 	'<h3><span class="LC_info">'.
1.605     www       767: 	&mt('Verifying Receipt Number [_1]',$receipt).
                    768: 	'</span></h3>'."\n";
1.44      ng        769: 
                    770:     my ($string,$contents,$matches) = ('','',0);
1.56      matthew   771:     my (undef,undef,$fullname) = &getclasslist('all','0');
1.177     albertel  772:     
                    773:     my $receiptparts=0;
1.390     albertel  774:     if ($env{"course.$courseid.receiptalg"} eq 'receipt2' ||
                    775: 	$env{"course.$courseid.receiptalg"} eq 'receipt3') { $receiptparts=1; }
1.177     albertel  776:     my $parts=['0'];
1.582     raeburn   777:     if ($receiptparts) {
                    778:         my $res_error; 
                    779:         ($parts)=&response_type($symb,\$res_error);
                    780:         if ($res_error) {
                    781:             return &navmap_errormsg();
                    782:         } 
                    783:     }
1.486     albertel  784:     
                    785:     my $header = 
                    786: 	&Apache::loncommon::start_data_table().
                    787: 	&Apache::loncommon::start_data_table_header_row().
1.487     albertel  788: 	'<th>&nbsp;'.&mt('Fullname').'&nbsp;</th>'."\n".
                    789: 	'<th>&nbsp;'.&mt('Username').'&nbsp;</th>'."\n".
                    790: 	'<th>&nbsp;'.&mt('Domain').'&nbsp;</th>';
1.486     albertel  791:     if ($receiptparts) {
1.487     albertel  792: 	$header.='<th>&nbsp;'.&mt('Problem Part').'&nbsp;</th>';
1.486     albertel  793:     }
                    794:     $header.=
                    795: 	&Apache::loncommon::end_data_table_header_row();
                    796: 
1.294     albertel  797:     foreach (sort 
                    798: 	     {
                    799: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                    800: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                    801: 		 }
                    802: 		 return $a cmp $b;
                    803: 	     } (keys(%$fullname))) {
1.44      ng        804: 	my ($uname,$udom)=split(/\:/);
1.177     albertel  805: 	foreach my $part (@$parts) {
                    806: 	    if ($receipt eq &Apache::lonnet::ireceipt($uname,$udom,$courseid,$symb,$part)) {
1.486     albertel  807: 		$contents.=
                    808: 		    &Apache::loncommon::start_data_table_row().
                    809: 		    '<td>&nbsp;'."\n".
1.177     albertel  810: 		    '<a href="javascript:viewOneStudent(\''.$uname.'\',\''.$udom.
1.417     albertel  811: 		    '\');" target="_self">'.$$fullname{$_}.'</a>&nbsp;</td>'."\n".
1.177     albertel  812: 		    '<td>&nbsp;'.$uname.'&nbsp;</td>'.
                    813: 		    '<td>&nbsp;'.$udom.'&nbsp;</td>';
                    814: 		if ($receiptparts) {
                    815: 		    $contents.='<td>&nbsp;'.$part.'&nbsp;</td>';
                    816: 		}
1.486     albertel  817: 		$contents.= 
                    818: 		    &Apache::loncommon::end_data_table_row()."\n";
1.177     albertel  819: 		
                    820: 		$matches++;
                    821: 	    }
1.44      ng        822: 	}
                    823:     }
                    824:     if ($matches == 0) {
1.584     bisitz    825:         $string = $title
                    826:                  .'<p class="LC_warning">'
                    827:                  .&mt('No match found for the above receipt number.')
                    828:                  .'</p>';
1.44      ng        829:     } else {
1.324     albertel  830: 	$string = &jscriptNform($symb).$title.
1.487     albertel  831: 	    '<p>'.
1.584     bisitz    832: 	    &mt('The above receipt number matches the following [quant,_1,student].',$matches).
1.487     albertel  833: 	    '</p>'.
1.486     albertel  834: 	    $header.
                    835: 	    $contents.
                    836: 	    &Apache::loncommon::end_data_table()."\n";
1.44      ng        837:     }
1.614     www       838:     return $string;
1.44      ng        839: }
                    840: 
                    841: #--- This is called by a number of programs.
                    842: #--- Called from the Grading Menu - View/Grade an individual student
                    843: #--- Also called directly when one clicks on the subm button 
                    844: #    on the problem page.
1.30      ng        845: sub listStudents {
1.617     www       846:     my ($request,$symb,$submitonly) = @_;
1.49      albertel  847: 
1.257     albertel  848:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
                    849:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
                    850:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
1.449     banghart  851:     my $getgroup  = $env{'form.group'} eq '' ? 'all' : $env{'form.group'};
1.617     www       852:     unless ($submitonly) {
                    853:        $submitonly= $env{'form.submitonly'} eq '' ? 'all' : $env{'form.submitonly'};
                    854:     }
1.49      albertel  855: 
1.632     www       856:     my $result='';
1.623     www       857:     my $res_error;
                    858:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
1.49      albertel  859: 
1.736   ! damieng   860:     my %js_lt = &Apache::lonlocal::texthash (
1.559     raeburn   861: 		'multiple' => 'Please select a student or group of students before clicking on the Next button.',
                    862: 		'single'   => 'Please select the student before clicking on the Next button.',
                    863: 	     );
1.736   ! damieng   864:     &js_escape(\%js_lt);
1.597     wenzelju  865:     $request->print(&Apache::lonhtmlcommon::scripttag(<<LISTJAVASCRIPT));
1.110     ng        866:     function checkSelect(checkBox) {
                    867: 	var ctr=0;
                    868: 	var sense="";
                    869: 	if (checkBox.length > 1) {
                    870: 	    for (var i=0; i<checkBox.length; i++) {
                    871: 		if (checkBox[i].checked) {
                    872: 		    ctr++;
                    873: 		}
                    874: 	    }
1.736   ! damieng   875: 	    sense = '$js_lt{'multiple'}';
1.110     ng        876: 	} else {
                    877: 	    if (checkBox.checked) {
                    878: 		ctr = 1;
                    879: 	    }
1.736   ! damieng   880: 	    sense = '$js_lt{'single'}';
1.110     ng        881: 	}
                    882: 	if (ctr == 0) {
1.485     albertel  883: 	    alert(sense);
1.110     ng        884: 	    return false;
                    885: 	}
                    886: 	document.gradesub.submit();
                    887:     }
                    888: 
                    889:     function reLoadList(formname) {
1.112     ng        890: 	if (formname.saveStatusOld.value == pullDownSelection(formname.Status)) {return;}
1.110     ng        891: 	formname.command.value = 'submission';
                    892: 	formname.submit();
                    893:     }
1.45      ng        894: LISTJAVASCRIPT
                    895: 
1.118     ng        896:     &commonJSfunctions($request);
1.41      ng        897:     $request->print($result);
1.39      ng        898: 
1.154     albertel  899:     my $gradeTable='<form action="/adm/grades" method="post" name="gradesub">'.
1.598     www       900: 	"\n";
1.485     albertel  901: 	
1.561     bisitz    902:     $gradeTable .= &Apache::lonhtmlcommon::start_pick_box();
                    903:     $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('View Problem Text'))
                    904:                   .'<label><input type="radio" name="vProb" value="no" checked="checked" /> '.&mt('no').' </label>'."\n"
                    905:                   .'<label><input type="radio" name="vProb" value="yes" /> '.&mt('one student').' </label>'."\n"
                    906:                   .'<label><input type="radio" name="vProb" value="all" /> '.&mt('all students').' </label><br />'."\n"
                    907:                   .&Apache::lonhtmlcommon::row_closure();
                    908:     $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('View Answer'))
                    909:                   .'<label><input type="radio" name="vAns" value="no"  /> '.&mt('no').' </label>'."\n"
                    910:                   .'<label><input type="radio" name="vAns" value="yes" /> '.&mt('one student').' </label>'."\n"
                    911:                   .'<label><input type="radio" name="vAns" value="all" checked="checked" /> '.&mt('all students').' </label><br />'."\n"
                    912:                   .&Apache::lonhtmlcommon::row_closure();
1.485     albertel  913: 
                    914:     my $submission_options;
1.442     banghart  915:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
                    916:     my $saveStatus = $stu_status eq '' ? 'Active' : $stu_status;
1.257     albertel  917:     $env{'form.Status'} = $saveStatus;
1.485     albertel  918:     $submission_options.=
1.592     bisitz    919:         '<span class="LC_nobreak">'.
1.624     www       920:         '<label><input type="radio" name="lastSub" value="lastonly" /> '.
1.699     kruse     921:         &mt('last submission').' </label></span>'."\n".
1.592     bisitz    922:         '<span class="LC_nobreak">'.
                    923:         '<label><input type="radio" name="lastSub" value="last" /> '.
1.699     kruse     924:         &mt('last submission with details').' </label></span>'."\n".
1.592     bisitz    925:         '<span class="LC_nobreak">'.
1.628     www       926:         '<label><input type="radio" name="lastSub" value="datesub" checked="checked" /> '.
1.699     kruse     927:         &mt('all submissions').'</label></span>'."\n".
1.592     bisitz    928:         '<span class="LC_nobreak">'.
                    929:         '<label><input type="radio" name="lastSub" value="all" /> '.
1.699     kruse     930:         &mt('all submissions with details').'</label></span>';
                    931:     $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('View Submissions'))
1.561     bisitz    932:                   .$submission_options
                    933:                   .&Apache::lonhtmlcommon::row_closure();
                    934: 
                    935:     $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('Grading Increments'))
                    936:                   .'<select name="increment">'
                    937:                   .'<option value="1">'.&mt('Whole Points').'</option>'
                    938:                   .'<option value=".5">'.&mt('Half Points').'</option>'
                    939:                   .'<option value=".25">'.&mt('Quarter Points').'</option>'
                    940:                   .'<option value=".1">'.&mt('Tenths of a Point').'</option>'
                    941:                   .'</select>'
                    942:                   .&Apache::lonhtmlcommon::row_closure();
1.485     albertel  943: 
                    944:     $gradeTable .= 
1.432     banghart  945:         &build_section_inputs().
1.45      ng        946: 	'<input type="hidden" name="submitonly"  value="'.$submitonly.'" />'."\n".
1.418     albertel  947: 	'<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.110     ng        948: 	'<input type="hidden" name="saveStatusOld" value="'.$saveStatus.'" />'."\n";
                    949: 
1.618     www       950:     if (exists($env{'form.Status'})) {
1.561     bisitz    951: 	$gradeTable .= '<input type="hidden" name="Status" value="'.$stu_status.'" />'."\n";
1.124     ng        952:     } else {
1.561     bisitz    953:         $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('Student Status'))
                    954:                       .&Apache::lonhtmlcommon::StatusOptions(
                    955:                            $saveStatus,undef,1,'javascript:reLoadList(this.form);')
                    956:                       .&Apache::lonhtmlcommon::row_closure();
1.124     ng        957:     }
1.112     ng        958: 
1.561     bisitz    959:     $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('Check For Plagiarism'))
                    960:                   .'<input type="checkbox" name="checkPlag" checked="checked" />'
                    961:                   .&Apache::lonhtmlcommon::row_closure(1)
                    962:                   .&Apache::lonhtmlcommon::end_pick_box();
                    963: 
                    964:     $gradeTable .= '<p>'
1.618     www       965:                   .&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    966:                   .'<input type="hidden" name="command" value="processGroup" />'
                    967:                   .'</p>';
1.249     albertel  968: 
                    969: # checkall buttons
                    970:     $gradeTable.=&check_script('gradesub', 'stuinfo');
1.110     ng        971:     $gradeTable.='<input type="button" '."\n".
1.589     bisitz    972:         'onclick="javascript:checkSelect(this.form.stuinfo);" '."\n".
                    973:         'value="'.&mt('Next').' &rarr;" /> <br />'."\n";
1.249     albertel  974:     $gradeTable.=&check_buttons();
1.450     banghart  975:     my ($classlist, undef, $fullname) = &getclasslist($getsec,'1',$getgroup);
1.474     albertel  976:     $gradeTable.= &Apache::loncommon::start_data_table().
                    977: 	&Apache::loncommon::start_data_table_header_row();
1.110     ng        978:     my $loop = 0;
                    979:     while ($loop < 2) {
1.485     albertel  980: 	$gradeTable.='<th>'.&mt('No.').'</th><th>'.&mt('Select').'</th>'.
                    981: 	    '<th>'.&nameUserString('header').'&nbsp;'.&mt('Section/Group').'</th>';
1.618     www       982: 	if (($submitonly ne 'queued') && ($submitonly ne 'all')) {
1.485     albertel  983: 	    foreach my $part (sort(@$partlist)) {
                    984: 		my $display_part=
                    985: 		    &get_display_part((split(/_/,$part))[0],$symb);
                    986: 		$gradeTable.=
                    987: 		    '<th>'.&mt('Part: [_1] Status',$display_part).'</th>';
1.110     ng        988: 	    }
1.301     albertel  989: 	} elsif ($submitonly eq 'queued') {
1.474     albertel  990: 	    $gradeTable.='<th>'.&mt('Queue Status').'&nbsp;</th>';
1.110     ng        991: 	}
                    992: 	$loop++;
1.126     ng        993: #	$gradeTable.='<td></td>' if ($loop%2 ==1);
1.41      ng        994:     }
1.474     albertel  995:     $gradeTable.=&Apache::loncommon::end_data_table_header_row()."\n";
1.41      ng        996: 
1.45      ng        997:     my $ctr = 0;
1.294     albertel  998:     foreach my $student (sort 
                    999: 			 {
                   1000: 			     if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                   1001: 				 return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                   1002: 			     }
                   1003: 			     return $a cmp $b;
                   1004: 			 }
                   1005: 			 (keys(%$fullname))) {
1.41      ng       1006: 	my ($uname,$udom) = split(/:/,$student);
1.301     albertel 1007: 
1.110     ng       1008: 	my %status = ();
1.301     albertel 1009: 
                   1010: 	if ($submitonly eq 'queued') {
                   1011: 	    my %queue_status = 
                   1012: 		&Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
                   1013: 							$udom,$uname);
                   1014: 	    next if (!defined($queue_status{'gradingqueue'}));
                   1015: 	    $status{'gradingqueue'} = $queue_status{'gradingqueue'};
                   1016: 	}
                   1017: 
1.618     www      1018: 	if (($submitonly ne 'queued') && ($submitonly ne 'all')) {
1.324     albertel 1019: 	    (%status) =&student_gradeStatus($symb,$udom,$uname,$partlist);
1.145     albertel 1020: 	    my $submitted = 0;
1.164     albertel 1021: 	    my $graded = 0;
1.248     albertel 1022: 	    my $incorrect = 0;
1.110     ng       1023: 	    foreach (keys(%status)) {
1.145     albertel 1024: 		$submitted = 1 if ($status{$_} ne 'nothing');
1.248     albertel 1025: 		$graded = 1 if ($status{$_} =~ /^ungraded/);
                   1026: 		$incorrect = 1 if ($status{$_} =~ /^incorrect/);
                   1027: 		
1.110     ng       1028: 		my ($foo,$partid,$foo1) = split(/\./,$_);
                   1029: 		if ($status{'resource.'.$partid.'.submitted_by'} ne '') {
1.145     albertel 1030: 		    $submitted = 0;
1.150     albertel 1031: 		    my ($part)=split(/\./,$partid);
1.110     ng       1032: 		    $gradeTable.='<input type="hidden" name="'.
1.150     albertel 1033: 			$student.':'.$part.':submitted_by" value="'.
1.110     ng       1034: 			$status{'resource.'.$partid.'.submitted_by'}.'" />';
                   1035: 		}
1.41      ng       1036: 	    }
1.248     albertel 1037: 	    
1.156     albertel 1038: 	    next if (!$submitted && ($submitonly eq 'yes' ||
                   1039: 				     $submitonly eq 'incorrect' ||
                   1040: 				     $submitonly eq 'graded'));
1.248     albertel 1041: 	    next if (!$graded && ($submitonly eq 'graded'));
                   1042: 	    next if (!$incorrect && $submitonly eq 'incorrect');
1.41      ng       1043: 	}
1.34      ng       1044: 
1.45      ng       1045: 	$ctr++;
1.249     albertel 1046: 	my $section = $classlist->{$student}->[&Apache::loncoursedata::CL_SECTION()];
1.452     banghart 1047:         my $group = $classlist->{$student}->[&Apache::loncoursedata::CL_GROUP()];
1.104     albertel 1048: 	if ( $perm{'vgr'} eq 'F' ) {
1.474     albertel 1049: 	    if ($ctr%2 ==1) {
                   1050: 		$gradeTable.= &Apache::loncommon::start_data_table_row();
                   1051: 	    }
1.126     ng       1052: 	    $gradeTable.='<td align="right">'.$ctr.'&nbsp;</td>'.
1.563     bisitz   1053:                '<td align="center"><label><input type="checkbox" name="stuinfo" value="'.
1.249     albertel 1054:                $student.':'.$$fullname{$student}.':::SECTION'.$section.
                   1055: 	       ')&nbsp;" />&nbsp;&nbsp;</label></td>'."\n".'<td>'.
                   1056: 	       &nameUserString(undef,$$fullname{$student},$uname,$udom).
1.474     albertel 1057: 	       '&nbsp;'.$section.($group ne '' ?'/'.$group:'').'</td>'."\n";
1.110     ng       1058: 
1.618     www      1059: 	    if ($submitonly ne 'all') {
1.524     raeburn  1060: 		foreach (sort(keys(%status))) {
1.485     albertel 1061: 		    next if ($_ =~ /^resource.*?submitted_by$/);
                   1062: 		    $gradeTable.='<td align="center">&nbsp;'.&mt($status{$_}).'&nbsp;</td>'."\n";
1.110     ng       1063: 		}
1.41      ng       1064: 	    }
1.126     ng       1065: #	    $gradeTable.='<td></td>' if ($ctr%2 ==1);
1.474     albertel 1066: 	    if ($ctr%2 ==0) {
                   1067: 		$gradeTable.=&Apache::loncommon::end_data_table_row()."\n";
                   1068: 	    }
1.41      ng       1069: 	}
                   1070:     }
1.110     ng       1071:     if ($ctr%2 ==1) {
1.126     ng       1072: 	$gradeTable.='<td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td>';
1.618     www      1073: 	    if (($submitonly ne 'queued') && ($submitonly ne 'all')) {
1.110     ng       1074: 		foreach (@$partlist) {
                   1075: 		    $gradeTable.='<td>&nbsp;</td>';
                   1076: 		}
1.301     albertel 1077: 	    } elsif ($submitonly eq 'queued') {
                   1078: 		$gradeTable.='<td>&nbsp;</td>';
1.110     ng       1079: 	    }
1.474     albertel 1080: 	$gradeTable.=&Apache::loncommon::end_data_table_row();
1.110     ng       1081:     }
                   1082: 
1.474     albertel 1083:     $gradeTable.=&Apache::loncommon::end_data_table()."\n".
1.589     bisitz   1084:         '<input type="button" '.
                   1085:         'onclick="javascript:checkSelect(this.form.stuinfo);" '.
                   1086:         'value="'.&mt('Next').' &rarr;" /></form>'."\n";
1.45      ng       1087:     if ($ctr == 0) {
1.96      albertel 1088: 	my $num_students=(scalar(keys(%$fullname)));
                   1089: 	if ($num_students eq 0) {
1.485     albertel 1090: 	    $gradeTable='<br />&nbsp;<span class="LC_warning">'.&mt('There are no students currently enrolled.').'</span>';
1.96      albertel 1091: 	} else {
1.171     albertel 1092: 	    my $submissions='submissions';
                   1093: 	    if ($submitonly eq 'incorrect') { $submissions = 'incorrect submissions'; }
                   1094: 	    if ($submitonly eq 'graded'   ) { $submissions = 'ungraded submissions'; }
1.301     albertel 1095: 	    if ($submitonly eq 'queued'   ) { $submissions = 'queued submissions'; }
1.398     albertel 1096: 	    $gradeTable='<br />&nbsp;<span class="LC_warning">'.
1.709     bisitz   1097: 		&mt('No '.$submissions.' found for this resource for any students. ([quant,_1,student] checked for '.$submissions.')',
1.485     albertel 1098: 		    $num_students).
                   1099: 		'</span><br />';
1.96      albertel 1100: 	}
1.46      ng       1101:     } elsif ($ctr == 1) {
1.474     albertel 1102: 	$gradeTable =~ s/type="checkbox"/type="checkbox" checked="checked"/;
1.45      ng       1103:     }
                   1104:     $request->print($gradeTable);
1.44      ng       1105:     return '';
1.10      ng       1106: }
                   1107: 
1.44      ng       1108: #---- Called from the listStudents routine
1.249     albertel 1109: 
                   1110: sub check_script {
                   1111:     my ($form, $type)=@_;
1.597     wenzelju 1112:     my $chkallscript= &Apache::lonhtmlcommon::scripttag('
1.249     albertel 1113:     function checkall() {
                   1114:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
                   1115:             ele = document.forms.'.$form.'.elements[i];
                   1116:             if (ele.name == "'.$type.'") {
                   1117:             document.forms.'.$form.'.elements[i].checked=true;
                   1118:                                        }
                   1119:         }
                   1120:     }
                   1121: 
                   1122:     function checksec() {
                   1123:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
                   1124:             ele = document.forms.'.$form.'.elements[i];
                   1125:            string = document.forms.'.$form.'.chksec.value;
                   1126:            if
                   1127:           (ele.value.indexOf(":::SECTION"+string)>0) {
                   1128:               document.forms.'.$form.'.elements[i].checked=true;
                   1129:             }
                   1130:         }
                   1131:     }
                   1132: 
                   1133: 
                   1134:     function uncheckall() {
                   1135:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
                   1136:             ele = document.forms.'.$form.'.elements[i];
                   1137:             if (ele.name == "'.$type.'") {
                   1138:             document.forms.'.$form.'.elements[i].checked=false;
                   1139:                                        }
                   1140:         }
                   1141:     }
                   1142: 
1.597     wenzelju 1143: '."\n");
1.249     albertel 1144:     return $chkallscript;
                   1145: }
                   1146: 
                   1147: sub check_buttons {
1.485     albertel 1148:     my $buttons.='<input type="button" onclick="checkall()" value="'.&mt('Check All').'" />';
                   1149:     $buttons.='<input type="button" onclick="uncheckall()" value="'.&mt('Uncheck All').'" />&nbsp;';
                   1150:     $buttons.='<input type="button" onclick="checksec()" value="'.&mt('Check Section/Group').'" />';
1.249     albertel 1151:     $buttons.='<input type="text" size="5" name="chksec" />&nbsp;';
                   1152:     return $buttons;
                   1153: }
                   1154: 
1.44      ng       1155: #     Displays the submissions for one student or a group of students
1.34      ng       1156: sub processGroup {
1.619     www      1157:     my ($request,$symb)  = @_;
1.41      ng       1158:     my $ctr        = 0;
1.155     albertel 1159:     my @stuchecked = &Apache::loncommon::get_env_multiple('form.stuinfo');
1.41      ng       1160:     my $total      = scalar(@stuchecked)-1;
1.45      ng       1161: 
1.396     banghart 1162:     foreach my $student (@stuchecked) {
                   1163: 	my ($uname,$udom,$fullname) = split(/:/,$student);
1.257     albertel 1164: 	$env{'form.student'}        = $uname;
                   1165: 	$env{'form.userdom'}        = $udom;
                   1166: 	$env{'form.fullname'}       = $fullname;
1.619     www      1167: 	&submission($request,$ctr,$total,$symb);
1.41      ng       1168: 	$ctr++;
                   1169:     }
                   1170:     return '';
1.35      ng       1171: }
1.34      ng       1172: 
1.44      ng       1173: #------------------------------------------------------------------------------------
                   1174: #
                   1175: #-------------------------- Next few routines handles grading by student, essentially
                   1176: #                           handles essay response type problem/part
                   1177: #
                   1178: #--- Javascript to handle the submission page functionality ---
                   1179: sub sub_page_js {
                   1180:     my $request = shift;
1.736   ! damieng  1181:     my $alertmsg = &mt('A number equal or greater than 0 is expected. Entered value = ');
        !          1182:     &js_escape(\$alertmsg);
1.597     wenzelju 1183:     $request->print(&Apache::lonhtmlcommon::scripttag(<<SUBJAVASCRIPT));
1.71      ng       1184:     function updateRadio(formname,id,weight) {
1.125     ng       1185: 	var gradeBox = formname["GD_BOX"+id];
                   1186: 	var radioButton = formname["RADVAL"+id];
                   1187: 	var oldpts = formname["oldpts"+id].value;
1.72      ng       1188: 	var pts = checkSolved(formname,id) == 'update' ? gradeBox.value : oldpts;
1.71      ng       1189: 	gradeBox.value = pts;
                   1190: 	var resetbox = false;
                   1191: 	if (isNaN(pts) || pts < 0) {
1.539     riegler  1192: 	    alert("$alertmsg"+pts);
1.71      ng       1193: 	    for (var i=0; i<radioButton.length; i++) {
                   1194: 		if (radioButton[i].checked) {
                   1195: 		    gradeBox.value = i;
                   1196: 		    resetbox = true;
                   1197: 		}
                   1198: 	    }
                   1199: 	    if (!resetbox) {
                   1200: 		formtextbox.value = "";
                   1201: 	    }
                   1202: 	    return;
1.44      ng       1203: 	}
1.71      ng       1204: 
                   1205: 	if (pts > weight) {
                   1206: 	    var resp = confirm("You entered a value ("+pts+
                   1207: 			       ") greater than the weight for the part. Accept?");
                   1208: 	    if (resp == false) {
1.125     ng       1209: 		gradeBox.value = oldpts;
1.71      ng       1210: 		return;
                   1211: 	    }
1.44      ng       1212: 	}
1.13      albertel 1213: 
1.71      ng       1214: 	for (var i=0; i<radioButton.length; i++) {
                   1215: 	    radioButton[i].checked=false;
                   1216: 	    if (pts == i && pts != "") {
                   1217: 		radioButton[i].checked=true;
                   1218: 	    }
                   1219: 	}
                   1220: 	updateSelect(formname,id);
1.125     ng       1221: 	formname["stores"+id].value = "0";
1.41      ng       1222:     }
1.5       albertel 1223: 
1.72      ng       1224:     function writeBox(formname,id,pts) {
1.125     ng       1225: 	var gradeBox = formname["GD_BOX"+id];
1.71      ng       1226: 	if (checkSolved(formname,id) == 'update') {
                   1227: 	    gradeBox.value = pts;
                   1228: 	} else {
1.125     ng       1229: 	    var oldpts = formname["oldpts"+id].value;
1.72      ng       1230: 	    gradeBox.value = oldpts;
1.125     ng       1231: 	    var radioButton = formname["RADVAL"+id];
1.71      ng       1232: 	    for (var i=0; i<radioButton.length; i++) {
                   1233: 		radioButton[i].checked=false;
1.72      ng       1234: 		if (i == oldpts) {
1.71      ng       1235: 		    radioButton[i].checked=true;
                   1236: 		}
                   1237: 	    }
1.41      ng       1238: 	}
1.125     ng       1239: 	formname["stores"+id].value = "0";
1.71      ng       1240: 	updateSelect(formname,id);
                   1241: 	return;
1.41      ng       1242:     }
1.44      ng       1243: 
1.71      ng       1244:     function clearRadBox(formname,id) {
                   1245: 	if (checkSolved(formname,id) == 'noupdate') {
                   1246: 	    updateSelect(formname,id);
                   1247: 	    return;
                   1248: 	}
1.125     ng       1249: 	gradeSelect = formname["GD_SEL"+id];
1.71      ng       1250: 	for (var i=0; i<gradeSelect.length; i++) {
                   1251: 	    if (gradeSelect[i].selected) {
                   1252: 		var selectx=i;
                   1253: 	    }
                   1254: 	}
1.125     ng       1255: 	var stores = formname["stores"+id];
1.71      ng       1256: 	if (selectx == stores.value) { return };
1.125     ng       1257: 	var gradeBox = formname["GD_BOX"+id];
1.71      ng       1258: 	gradeBox.value = "";
1.125     ng       1259: 	var radioButton = formname["RADVAL"+id];
1.71      ng       1260: 	for (var i=0; i<radioButton.length; i++) {
                   1261: 	    radioButton[i].checked=false;
                   1262: 	}
                   1263: 	stores.value = selectx;
                   1264:     }
1.5       albertel 1265: 
1.71      ng       1266:     function checkSolved(formname,id) {
1.125     ng       1267: 	if (formname["solved"+id].value == "correct_by_student" && formname.overRideScore.value == 'no') {
1.118     ng       1268: 	    var reply = confirm("This problem has been graded correct by the computer. Do you want to change the score?");
                   1269: 	    if (!reply) {return "noupdate";}
1.120     ng       1270: 	    formname.overRideScore.value = 'yes';
1.41      ng       1271: 	}
1.71      ng       1272: 	return "update";
1.13      albertel 1273:     }
1.71      ng       1274: 
                   1275:     function updateSelect(formname,id) {
1.125     ng       1276: 	formname["GD_SEL"+id][0].selected = true;
1.71      ng       1277: 	return;
1.41      ng       1278:     }
1.33      ng       1279: 
1.121     ng       1280: //=========== Check that a point is assigned for all the parts  ============
1.71      ng       1281:     function checksubmit(formname,val,total,parttot) {
1.121     ng       1282: 	formname.gradeOpt.value = val;
1.71      ng       1283: 	if (val == "Save & Next") {
                   1284: 	    for (i=0;i<=total;i++) {
                   1285: 		for (j=0;j<parttot;j++) {
1.125     ng       1286: 		    var partid = formname["partid"+i+"_"+j].value;
1.127     ng       1287: 		    if (formname["GD_SEL"+i+"_"+partid][0].selected) {
1.125     ng       1288: 			var points = formname["GD_BOX"+i+"_"+partid].value;
1.71      ng       1289: 			if (points == "") {
1.125     ng       1290: 			    var name = formname["name"+i].value;
1.129     ng       1291: 			    var studentID = (name != '' ? name : formname["unamedom"+i].value);
                   1292: 			    var resp = confirm("You did not assign a score for "+studentID+
                   1293: 					       ", part "+partid+". Continue?");
1.71      ng       1294: 			    if (resp == false) {
1.125     ng       1295: 				formname["GD_BOX"+i+"_"+partid].focus();
1.71      ng       1296: 				return false;
                   1297: 			    }
                   1298: 			}
                   1299: 		    }
                   1300: 		}
                   1301: 	    }
                   1302: 	}
1.120     ng       1303: 	formname.submit();
                   1304:     }
                   1305: 
1.71      ng       1306: //======= Check that a score is assigned for all the problems (page/sequence grading only) =========
                   1307:     function checkSubmitPage(formname,total) {
                   1308: 	noscore = new Array(100);
                   1309: 	var ptr = 0;
                   1310: 	for (i=1;i<total;i++) {
1.125     ng       1311: 	    var partid = formname["q_"+i].value;
1.127     ng       1312: 	    if (formname["GD_SEL"+i+"_"+partid][0].selected) {
1.125     ng       1313: 		var points = formname["GD_BOX"+i+"_"+partid].value;
                   1314: 		var status = formname["solved"+i+"_"+partid].value;
1.71      ng       1315: 		if (points == "" && status != "correct_by_student") {
                   1316: 		    noscore[ptr] = i;
                   1317: 		    ptr++;
                   1318: 		}
                   1319: 	    }
                   1320: 	}
                   1321: 	if (ptr != 0) {
                   1322: 	    var sense = ptr == 1 ? ": " : "s: ";
                   1323: 	    var prolist = "";
                   1324: 	    if (ptr == 1) {
                   1325: 		prolist = noscore[0];
                   1326: 	    } else {
                   1327: 		var i = 0;
                   1328: 		while (i < ptr-1) {
                   1329: 		    prolist += noscore[i]+", ";
                   1330: 		    i++;
                   1331: 		}
                   1332: 		prolist += "and "+noscore[i];
                   1333: 	    }
                   1334: 	    var resp = confirm("You did not assign any score for the following problem"+sense+prolist+". Continue?");
                   1335: 	    if (resp == false) {
                   1336: 		return false;
                   1337: 	    }
                   1338: 	}
1.45      ng       1339: 
1.71      ng       1340: 	formname.submit();
                   1341:     }
                   1342: SUBJAVASCRIPT
                   1343: }
1.45      ng       1344: 
1.71      ng       1345: #--- javascript for essay type problem --
                   1346: sub sub_page_kw_js {
                   1347:     my $request = shift;
1.80      ng       1348:     my $iconpath = $request->dir_config('lonIconsURL');
1.118     ng       1349:     &commonJSfunctions($request);
1.350     albertel 1350: 
1.629     www      1351:     my $inner_js_msg_central= (<<INNERJS);
                   1352: <script type="text/javascript">
1.350     albertel 1353:     function checkInput() {
                   1354:       opener.document.SCORE.msgsub.value = opener.checkEntities(document.msgcenter.msgsub.value);
                   1355:       var nmsg   = opener.document.SCORE.savemsgN.value;
                   1356:       var usrctr = document.msgcenter.usrctr.value;
                   1357:       var newval = opener.document.SCORE["newmsg"+usrctr];
                   1358:       newval.value = opener.checkEntities(document.msgcenter.newmsg.value);
                   1359: 
                   1360:       var msgchk = "";
                   1361:       if (document.msgcenter.subchk.checked) {
                   1362:          msgchk = "msgsub,";
                   1363:       }
                   1364:       var includemsg = 0;
                   1365:       for (var i=1; i<=nmsg; i++) {
                   1366:           var opnmsg = opener.document.SCORE["savemsg"+i];
                   1367:           var frmmsg = document.msgcenter["msg"+i];
                   1368:           opnmsg.value = opener.checkEntities(frmmsg.value);
                   1369:           var showflg = opener.document.SCORE["shownOnce"+i];
                   1370:           showflg.value = "1";
                   1371:           var chkbox = document.msgcenter["msgn"+i];
                   1372:           if (chkbox.checked) {
                   1373:              msgchk += "savemsg"+i+",";
                   1374:              includemsg = 1;
                   1375:           }
                   1376:       }
                   1377:       if (document.msgcenter.newmsgchk.checked) {
                   1378:          msgchk += "newmsg"+usrctr;
                   1379:          includemsg = 1;
                   1380:       }
                   1381:       imgformname = opener.document.SCORE["mailicon"+usrctr];
                   1382:       imgformname.src = "$iconpath/"+((includemsg) ? "mailto.gif" : "mailbkgrd.gif");
                   1383:       var includemsg = opener.document.SCORE["includemsg"+usrctr];
                   1384:       includemsg.value = msgchk;
                   1385: 
                   1386:       self.close()
                   1387: 
                   1388:     }
1.629     www      1389: </script>
1.350     albertel 1390: INNERJS
                   1391: 
1.629     www      1392:     my $inner_js_highlight_central= (<<INNERJS);
                   1393: <script type="text/javascript">
1.351     albertel 1394:     function updateChoice(flag) {
                   1395:       opener.document.SCORE.kwclr.value = opener.radioSelection(document.hlCenter.kwdclr);
                   1396:       opener.document.SCORE.kwsize.value = opener.radioSelection(document.hlCenter.kwdsize);
                   1397:       opener.document.SCORE.kwstyle.value = opener.radioSelection(document.hlCenter.kwdstyle);
                   1398:       opener.document.SCORE.refresh.value = "on";
                   1399:       if (opener.document.SCORE.keywords.value!=""){
                   1400:          opener.document.SCORE.submit();
                   1401:       }
                   1402:       self.close()
                   1403:     }
1.629     www      1404: </script>
1.351     albertel 1405: INNERJS
                   1406: 
                   1407:     my $start_page_msg_central = 
                   1408:         &Apache::loncommon::start_page('Message Central',$inner_js_msg_central,
                   1409: 				       {'js_ready'  => 1,
                   1410: 					'only_body' => 1,
                   1411: 					'bgcolor'   =>'#FFFFFF',});
                   1412:     my $end_page_msg_central = 
                   1413: 	&Apache::loncommon::end_page({'js_ready' => 1});
                   1414: 
                   1415: 
                   1416:     my $start_page_highlight_central = 
                   1417:         &Apache::loncommon::start_page('Highlight Central',
                   1418: 				       $inner_js_highlight_central,
1.350     albertel 1419: 				       {'js_ready'  => 1,
                   1420: 					'only_body' => 1,
                   1421: 					'bgcolor'   =>'#FFFFFF',});
1.351     albertel 1422:     my $end_page_highlight_central = 
1.350     albertel 1423: 	&Apache::loncommon::end_page({'js_ready' => 1});
                   1424: 
1.219     www      1425:     my $docopen=&Apache::lonhtmlcommon::javascript_docopen();
1.236     albertel 1426:     $docopen=~s/^document\.//;
1.736   ! damieng  1427:     my %js_lt = &Apache::lonlocal::texthash(
1.652     raeburn  1428:                 keyw => 'Keywords list, separated by a space. Add/delete to list if desired.',
                   1429:                 plse => 'Please select a word or group of words from document and then click this link.',
                   1430:                 adds => 'Add selection to keyword list? Edit if desired.',
1.736   ! damieng  1431:                 col1 => 'red',
        !          1432:                 col2 => 'green',
        !          1433:                 col3 => 'blue',
        !          1434:                 siz1 => 'normal',
        !          1435:                 siz2 => '+1',
        !          1436:                 siz3 => '+2',
        !          1437:                 sty1 => 'normal',
        !          1438:                 sty2 => 'italic',
        !          1439:                 sty3 => 'bold',
        !          1440:              );
        !          1441:     my %html_js_lt = &Apache::lonlocal::texthash(
1.652     raeburn  1442:                 comp => 'Compose Message for: ',
                   1443:                 incl => 'Include',
1.656     raeburn  1444:                 type => 'Type',
1.652     raeburn  1445:                 subj => 'Subject',
                   1446:                 mesa => 'Message',
                   1447:                 new  => 'New',
                   1448:                 save => 'Save',
                   1449:                 canc => 'Cancel',
                   1450:                 kehi => 'Keyword Highlight Options',
                   1451:                 txtc => 'Text Color',
                   1452:                 font => 'Font Size',
1.656     raeburn  1453:                 fnst => 'Font Style',
1.652     raeburn  1454:              );
1.736   ! damieng  1455:     &js_escape(\%js_lt);
        !          1456:     &html_escape(\%html_js_lt);
        !          1457:     &js_escape(\%html_js_lt);
1.597     wenzelju 1458:     $request->print(&Apache::lonhtmlcommon::scripttag(<<SUBJAVASCRIPT));
1.45      ng       1459: 
1.44      ng       1460: //===================== Show list of keywords ====================
1.122     ng       1461:   function keywords(formname) {
1.736   ! damieng  1462:     var nret = prompt("$js_lt{'keyw'}",formname.keywords.value);
1.44      ng       1463:     if (nret==null) return;
1.122     ng       1464:     formname.keywords.value = nret;
1.44      ng       1465: 
1.122     ng       1466:     if (formname.keywords.value != "") {
1.128     ng       1467: 	formname.refresh.value = "on";
1.122     ng       1468: 	formname.submit();
1.44      ng       1469:     }
                   1470:     return;
                   1471:   }
                   1472: 
                   1473: //===================== Script to view submitted by ==================
                   1474:   function viewSubmitter(submitter) {
                   1475:     document.SCORE.refresh.value = "on";
                   1476:     document.SCORE.NCT.value = "1";
                   1477:     document.SCORE.unamedom0.value = submitter;
                   1478:     document.SCORE.submit();
                   1479:     return;
                   1480:   }
                   1481: 
                   1482: //===================== Script to add keyword(s) ==================
                   1483:   function getSel() {
                   1484:     if (document.getSelection) txt = document.getSelection();
                   1485:     else if (document.selection) txt = document.selection.createRange().text;
                   1486:     else return;
                   1487:     var cleantxt = txt.replace(new RegExp('([\\f\\n\\r\\t\\v ])+', 'g')," ");
                   1488:     if (cleantxt=="") {
1.736   ! damieng  1489: 	alert("$js_lt{'plse'}");
1.44      ng       1490: 	return;
                   1491:     }
1.736   ! damieng  1492:     var nret = prompt("$js_lt{'adds'}",cleantxt);
1.44      ng       1493:     if (nret==null) return;
1.127     ng       1494:     document.SCORE.keywords.value = document.SCORE.keywords.value+" "+nret;
1.44      ng       1495:     if (document.SCORE.keywords.value != "") {
1.127     ng       1496: 	document.SCORE.refresh.value = "on";
1.44      ng       1497: 	document.SCORE.submit();
                   1498:     }
                   1499:     return;
                   1500:   }
                   1501: 
                   1502: //====================== Script for composing message ==============
1.80      ng       1503:    // preload images
                   1504:    img1 = new Image();
                   1505:    img1.src = "$iconpath/mailbkgrd.gif";
                   1506:    img2 = new Image();
                   1507:    img2.src = "$iconpath/mailto.gif";
                   1508: 
1.44      ng       1509:   function msgCenter(msgform,usrctr,fullname) {
                   1510:     var Nmsg  = msgform.savemsgN.value;
                   1511:     savedMsgHeader(Nmsg,usrctr,fullname);
                   1512:     var subject = msgform.msgsub.value;
1.127     ng       1513:     var msgchk = document.SCORE["includemsg"+usrctr].value;
1.44      ng       1514:     re = /msgsub/;
                   1515:     var shwsel = "";
                   1516:     if (re.test(msgchk)) { shwsel = "checked" }
1.123     ng       1517:     subject = (document.SCORE.shownSub.value == 0 ? checkEntities(subject) : subject);
                   1518:     displaySubject(checkEntities(subject),shwsel);
1.44      ng       1519:     for (var i=1; i<=Nmsg; i++) {
1.123     ng       1520: 	var testmsg = "savemsg"+i+",";
                   1521: 	re = new RegExp(testmsg,"g");
1.44      ng       1522: 	shwsel = "";
                   1523: 	if (re.test(msgchk)) { shwsel = "checked" }
1.125     ng       1524: 	var message = document.SCORE["savemsg"+i].value;
1.126     ng       1525: 	message = (document.SCORE["shownOnce"+i].value == 0 ? checkEntities(message) : message);
1.123     ng       1526: 	displaySavedMsg(i,message,shwsel); //I do not get it. w/o checkEntities on saved messages,
                   1527: 	                                   //any &lt; is already converted to <, etc. However, only once!!
1.44      ng       1528:     }
1.125     ng       1529:     newmsg = document.SCORE["newmsg"+usrctr].value;
1.44      ng       1530:     shwsel = "";
                   1531:     re = /newmsg/;
                   1532:     if (re.test(msgchk)) { shwsel = "checked" }
                   1533:     newMsg(newmsg,shwsel);
                   1534:     msgTail(); 
                   1535:     return;
                   1536:   }
                   1537: 
1.123     ng       1538:   function checkEntities(strx) {
                   1539:     if (strx.length == 0) return strx;
                   1540:     var orgStr = ["&", "<", ">", '"']; 
                   1541:     var newStr = ["&amp;", "&lt;", "&gt;", "&quot;"];
                   1542:     var counter = 0;
                   1543:     while (counter < 4) {
                   1544: 	strx = strReplace(strx,orgStr[counter],newStr[counter]);
                   1545: 	counter++;
                   1546:     }
                   1547:     return strx;
                   1548:   }
                   1549: 
                   1550:   function strReplace(strx, orgStr, newStr) {
                   1551:     return strx.split(orgStr).join(newStr);
                   1552:   }
                   1553: 
1.44      ng       1554:   function savedMsgHeader(Nmsg,usrctr,fullname) {
1.76      ng       1555:     var height = 70*Nmsg+250;
1.44      ng       1556:     if (height > 600) {
                   1557: 	height = 600;
                   1558:     }
1.118     ng       1559:     var xpos = (screen.width-600)/2;
                   1560:     xpos = (xpos < 0) ? '0' : xpos;
                   1561:     var ypos = (screen.height-height)/2-30;
                   1562:     ypos = (ypos < 0) ? '0' : ypos;
                   1563: 
1.668     www      1564:     pWin = window.open('', 'MessageCenter', 'resizable=yes,toolbar=no,location=no,scrollbars=yes,screenx='+xpos+',screeny='+ypos+',width=700,height='+height);
1.76      ng       1565:     pWin.focus();
                   1566:     pDoc = pWin.document;
1.219     www      1567:     pDoc.$docopen;
1.351     albertel 1568:     pDoc.write('$start_page_msg_central');
1.76      ng       1569: 
                   1570:     pDoc.write("<form action=\\"inactive\\" name=\\"msgcenter\\">");
                   1571:     pDoc.write("<input value=\\""+usrctr+"\\" name=\\"usrctr\\" type=\\"hidden\\">");
1.736   ! damieng  1572:     pDoc.write("<h1>&nbsp;$html_js_lt{'comp'}\"+fullname+\"<\\/h1>");
1.76      ng       1573: 
1.676     golterma 1574:     pDoc.write('<table style="border:1px solid black;"><tr>');
1.736   ! damieng  1575:     pDoc.write("<td><b>$html_js_lt{'incl'}<\\/b><\\/td><td><b>$html_js_lt{'type'}<\\/b><\\/td><td><b>$html_js_lt{'mesa'}<\\/td><\\/tr>");
1.44      ng       1576: }
                   1577:     function displaySubject(msg,shwsel) {
1.76      ng       1578:     pDoc = pWin.document;
1.676     golterma 1579:     pDoc.write("<tr>");
                   1580:     pDoc.write("<td align=\\"center\\"><input name=\\"subchk\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
1.736   ! damieng  1581:     pDoc.write("<td>$html_js_lt{'subj'}<\\/td>");
1.676     golterma 1582:     pDoc.write("<td><input name=\\"msgsub\\" type=\\"text\\" value=\\""+msg+"\\"size=\\"40\\" maxlength=\\"80\\"><\\/td><\\/tr>");
1.44      ng       1583: }
                   1584: 
1.72      ng       1585:   function displaySavedMsg(ctr,msg,shwsel) {
1.76      ng       1586:     pDoc = pWin.document;
1.676     golterma 1587:     pDoc.write("<tr>");
                   1588:     pDoc.write("<td align=\\"center\\"><input name=\\"msgn"+ctr+"\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
1.465     albertel 1589:     pDoc.write("<td align=\\"center\\">"+ctr+"<\\/td>");
                   1590:     pDoc.write("<td><textarea name=\\"msg"+ctr+"\\" cols=\\"60\\" rows=\\"3\\">"+msg+"<\\/textarea><\\/td><\\/tr>");
1.44      ng       1591: }
                   1592: 
                   1593:   function newMsg(newmsg,shwsel) {
1.76      ng       1594:     pDoc = pWin.document;
1.676     golterma 1595:     pDoc.write("<tr>");
                   1596:     pDoc.write("<td align=\\"center\\"><input name=\\"newmsgchk\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
1.736   ! damieng  1597:     pDoc.write("<td align=\\"center\\">$html_js_lt{'new'}<\\/td>");
1.465     albertel 1598:     pDoc.write("<td><textarea name=\\"newmsg\\" cols=\\"60\\" rows=\\"3\\" onchange=\\"javascript:this.form.newmsgchk.checked=true\\" >"+newmsg+"<\\/textarea><\\/td><\\/tr>");
1.44      ng       1599: }
                   1600: 
                   1601:   function msgTail() {
1.76      ng       1602:     pDoc = pWin.document;
1.676     golterma 1603:     //pDoc.write("<\\/table>");
1.465     albertel 1604:     pDoc.write("<\\/td><\\/tr><\\/table>&nbsp;");
1.736   ! damieng  1605:     pDoc.write("<input type=\\"button\\" value=\\"$html_js_lt{'save'}\\" onclick=\\"javascript:checkInput()\\">&nbsp;&nbsp;");
        !          1606:     pDoc.write("<input type=\\"button\\" value=\\"$html_js_lt{'canc'}\\" onclick=\\"self.close()\\"><br /><br />");
1.465     albertel 1607:     pDoc.write("<\\/form>");
1.351     albertel 1608:     pDoc.write('$end_page_msg_central');
1.128     ng       1609:     pDoc.close();
1.44      ng       1610: }
                   1611: 
                   1612: //====================== Script for keyword highlight options ==============
                   1613:   function kwhighlight() {
                   1614:     var kwclr    = document.SCORE.kwclr.value;
                   1615:     var kwsize   = document.SCORE.kwsize.value;
                   1616:     var kwstyle  = document.SCORE.kwstyle.value;
                   1617:     var redsel = "";
                   1618:     var grnsel = "";
                   1619:     var blusel = "";
1.736   ! damieng  1620:     var txtcol1 = "$js_lt{'col1'}";
        !          1621:     var txtcol2 = "$js_lt{'col2'}";
        !          1622:     var txtcol3 = "$js_lt{'col3'}";
        !          1623:     var txtsiz1 = "$js_lt{'siz1'}";
        !          1624:     var txtsiz2 = "$js_lt{'siz2'}";
        !          1625:     var txtsiz3 = "$js_lt{'siz3'}";
        !          1626:     var txtsty1 = "$js_lt{'sty1'}";
        !          1627:     var txtsty2 = "$js_lt{'sty2'}";
        !          1628:     var txtsty3 = "$js_lt{'sty3'}";
1.718     bisitz   1629:     if (kwclr=="red")   {var redsel="checked='checked'"};
                   1630:     if (kwclr=="green") {var grnsel="checked='checked'"};
                   1631:     if (kwclr=="blue")  {var blusel="checked='checked'"};
1.44      ng       1632:     var sznsel = "";
                   1633:     var sz1sel = "";
                   1634:     var sz2sel = "";
1.718     bisitz   1635:     if (kwsize=="0")  {var sznsel="checked='checked'"};
                   1636:     if (kwsize=="+1") {var sz1sel="checked='checked'"};
                   1637:     if (kwsize=="+2") {var sz2sel="checked='checked'"};
1.44      ng       1638:     var synsel = "";
                   1639:     var syisel = "";
                   1640:     var sybsel = "";
1.718     bisitz   1641:     if (kwstyle=="")    {var synsel="checked='checked'"};
                   1642:     if (kwstyle=="<i>") {var syisel="checked='checked'"};
                   1643:     if (kwstyle=="<b>") {var sybsel="checked='checked'"};
1.44      ng       1644:     highlightCentral();
1.718     bisitz   1645:     highlightbody('red',txtcol1,redsel,'0',txtsiz1,sznsel,'',txtsty1,synsel);
                   1646:     highlightbody('green',txtcol2,grnsel,'+1',txtsiz2,sz1sel,'<i>',txtsty2,syisel);
                   1647:     highlightbody('blue',txtcol3,blusel,'+2',txtsiz3,sz2sel,'<b>',txtsty3,sybsel);
1.44      ng       1648:     highlightend();
                   1649:     return;
                   1650:   }
                   1651: 
                   1652:   function highlightCentral() {
1.76      ng       1653: //    if (window.hwdWin) window.hwdWin.close();
1.118     ng       1654:     var xpos = (screen.width-400)/2;
                   1655:     xpos = (xpos < 0) ? '0' : xpos;
                   1656:     var ypos = (screen.height-330)/2-30;
                   1657:     ypos = (ypos < 0) ? '0' : ypos;
                   1658: 
1.206     albertel 1659:     hwdWin = window.open('', 'KeywordHighlightCentral', 'resizeable=yes,toolbar=no,location=no,scrollbars=no,width=400,height=300,screenx='+xpos+',screeny='+ypos);
1.76      ng       1660:     hwdWin.focus();
                   1661:     var hDoc = hwdWin.document;
1.219     www      1662:     hDoc.$docopen;
1.351     albertel 1663:     hDoc.write('$start_page_highlight_central');
1.76      ng       1664:     hDoc.write("<form action=\\"inactive\\" name=\\"hlCenter\\">");
1.736   ! damieng  1665:     hDoc.write("<h1>$html_js_lt{'kehi'}<\\/h1>");
1.76      ng       1666: 
1.718     bisitz   1667:     hDoc.write('<table border="0" width="100%"><tr style="background-color:#A1D676">');
1.736   ! damieng  1668:     hDoc.write("<th>$html_js_lt{'txtc'}<\\/th><th>$html_js_lt{'font'}<\\/th><th>$html_js_lt{'fnst'}<\\/th><\\/tr>");
1.44      ng       1669:   }
                   1670: 
                   1671:   function highlightbody(clrval,clrtxt,clrsel,szval,sztxt,szsel,syval,sytxt,sysel) { 
1.76      ng       1672:     var hDoc = hwdWin.document;
1.718     bisitz   1673:     hDoc.write("<tr>");
1.76      ng       1674:     hDoc.write("<td align=\\"left\\">");
1.718     bisitz   1675:     hDoc.write("<input name=\\"kwdclr\\" type=\\"radio\\" value=\\""+clrval+"\\" "+clrsel+" \\/>&nbsp;"+clrtxt+"<\\/td>");
1.76      ng       1676:     hDoc.write("<td align=\\"left\\">");
1.718     bisitz   1677:     hDoc.write("<input name=\\"kwdsize\\" type=\\"radio\\" value=\\""+szval+"\\" "+szsel+" \\/>&nbsp;"+sztxt+"<\\/td>");
1.76      ng       1678:     hDoc.write("<td align=\\"left\\">");
1.718     bisitz   1679:     hDoc.write("<input name=\\"kwdstyle\\" type=\\"radio\\" value=\\""+syval+"\\" "+sysel+" \\/>&nbsp;"+sytxt+"<\\/td>");
1.465     albertel 1680:     hDoc.write("<\\/tr>");
1.44      ng       1681:   }
                   1682: 
                   1683:   function highlightend() { 
1.76      ng       1684:     var hDoc = hwdWin.document;
1.718     bisitz   1685:     hDoc.write("<\\/table><br \\/>");
1.736   ! damieng  1686:     hDoc.write("<input type=\\"button\\" value=\\"$html_js_lt{'save'}\\" onclick=\\"javascript:updateChoice(1)\\" \\/>&nbsp;&nbsp;");
        !          1687:     hDoc.write("<input type=\\"button\\" value=\\"$html_js_lt{'canc'}\\" onclick=\\"self.close()\\" \\/><br /><br />");
1.465     albertel 1688:     hDoc.write("<\\/form>");
1.351     albertel 1689:     hDoc.write('$end_page_highlight_central');
1.128     ng       1690:     hDoc.close();
1.44      ng       1691:   }
                   1692: 
                   1693: SUBJAVASCRIPT
                   1694: }
                   1695: 
1.349     albertel 1696: sub get_increment {
1.348     bowersj2 1697:     my $increment = $env{'form.increment'};
                   1698:     if ($increment != 1 && $increment != .5 && $increment != .25 &&
                   1699:         $increment != .1) {
                   1700:         $increment = 1;
                   1701:     }
                   1702:     return $increment;
                   1703: }
                   1704: 
1.585     bisitz   1705: sub gradeBox_start {
                   1706:     return (
                   1707:         &Apache::loncommon::start_data_table()
                   1708:        .&Apache::loncommon::start_data_table_header_row()
                   1709:        .'<th>'.&mt('Part').'</th>'
                   1710:        .'<th>'.&mt('Points').'</th>'
                   1711:        .'<th>&nbsp;</th>'
                   1712:        .'<th>'.&mt('Assign Grade').'</th>'
                   1713:        .'<th>'.&mt('Weight').'</th>'
                   1714:        .'<th>'.&mt('Grade Status').'</th>'
                   1715:        .&Apache::loncommon::end_data_table_header_row()
                   1716:     );
                   1717: }
                   1718: 
                   1719: sub gradeBox_end {
                   1720:     return (
                   1721:         &Apache::loncommon::end_data_table()
                   1722:     );
                   1723: }
1.71      ng       1724: #--- displays the grading box, used in essay type problem and grading by page/sequence
                   1725: sub gradeBox {
1.322     albertel 1726:     my ($request,$symb,$uname,$udom,$counter,$partid,$record) = @_;
1.381     albertel 1727:     my $checkIcon = '<img alt="'.&mt('Check Mark').
1.485     albertel 1728: 	'" src="'.&Apache::loncommon::lonhttpdurl($request->dir_config('lonIconsURL').'/check.gif').'" height="16" border="0" />';
1.71      ng       1729:     my $wgt    = &Apache::lonnet::EXT('resource.'.$partid.'.weight',$symb,$udom,$uname);
1.466     albertel 1730:     my $wgtmsg = ($wgt > 0) ? &mt('(problem weight)') 
                   1731:                            : '<span class="LC_info">'.&mt('problem weight assigned by computer').'</span>';
1.71      ng       1732:     $wgt       = ($wgt > 0 ? $wgt : '1');
                   1733:     my $score  = ($$record{'resource.'.$partid.'.awarded'} eq '' ?
1.320     albertel 1734: 		  '' : &compute_points($$record{'resource.'.$partid.'.awarded'},$wgt));
1.695     bisitz   1735:     my $data_WGT='<input type="hidden" name="WGT'.$counter.'_'.$partid.'" value="'.$wgt.'" />'."\n";
1.466     albertel 1736:     my $display_part= &get_display_part($partid,$symb);
1.270     albertel 1737:     my %last_resets = &get_last_resets($symb,$env{'request.course.id'},
                   1738: 				       [$partid]);
                   1739:     my $aggtries = $$record{'resource.'.$partid.'.tries'};
1.269     raeburn  1740:     if ($last_resets{$partid}) {
                   1741:         $aggtries = &get_num_tries($record,$last_resets{$partid},$partid);
                   1742:     }
1.695     bisitz   1743:     my $result=&Apache::loncommon::start_data_table_row();
1.71      ng       1744:     my $ctr = 0;
1.348     bowersj2 1745:     my $thisweight = 0;
1.349     albertel 1746:     my $increment = &get_increment();
1.485     albertel 1747: 
                   1748:     my $radio.='<table border="0"><tr>'."\n";  # display radio buttons in a nice table 10 across
1.348     bowersj2 1749:     while ($thisweight<=$wgt) {
1.532     bisitz   1750: 	$radio.= '<td><span class="LC_nobreak"><label><input type="radio" name="RADVAL'.$counter.'_'.$partid.'" '.
1.589     bisitz   1751:         'onclick="javascript:writeBox(this.form,\''.$counter.'_'.$partid.'\','.
1.348     bowersj2 1752: 	    $thisweight.')" value="'.$thisweight.'" '.
1.401     albertel 1753: 	    ($score eq $thisweight ? 'checked="checked"':'').' /> '.$thisweight."</label></span></td>\n";
1.485     albertel 1754: 	$radio.=(($ctr+1)%10 == 0 ? '</tr><tr>' : '');
1.348     bowersj2 1755:         $thisweight += $increment;
1.71      ng       1756: 	$ctr++;
                   1757:     }
1.485     albertel 1758:     $radio.='</tr></table>';
                   1759: 
                   1760:     my $line.='<input type="text" name="GD_BOX'.$counter.'_'.$partid.'"'.
1.71      ng       1761: 	($score ne ''? ' value = "'.$score.'"':'').' size="4" '.
1.589     bisitz   1762: 	'onchange="javascript:updateRadio(this.form,\''.$counter.'_'.$partid.'\','.
1.71      ng       1763: 	$wgt.')" /></td>'."\n";
1.485     albertel 1764:     $line.='<td>/'.$wgt.' '.$wgtmsg.
1.71      ng       1765: 	($$record{'resource.'.$partid.'.solved'} eq 'correct_by_student' ? '&nbsp;'.$checkIcon : '').
1.585     bisitz   1766: 	' </td>'."\n";
                   1767:     $line.='<td><select name="GD_SEL'.$counter.'_'.$partid.'" '.
1.589     bisitz   1768: 	'onchange="javascript:clearRadBox(this.form,\''.$counter.'_'.$partid.'\')" >'."\n";
1.71      ng       1769:     if ($$record{'resource.'.$partid.'.solved'} eq 'excused') {
1.485     albertel 1770: 	$line.='<option></option>'.
                   1771: 	    '<option value="excused" selected="selected">'.&mt('excused').'</option>';
1.71      ng       1772:     } else {
1.485     albertel 1773: 	$line.='<option selected="selected"></option>'.
                   1774: 	    '<option value="excused" >'.&mt('excused').'</option>';
1.71      ng       1775:     }
1.485     albertel 1776:     $line.='<option value="reset status">'.&mt('reset status').'</option></select>'."\n";
                   1777: 
                   1778: 
                   1779:     $result .= 
1.695     bisitz   1780: 	    '<td>'.$data_WGT.$display_part.'</td><td>'.$radio.'</td><td>'.&mt('or').'</td><td>'.$line.'</td>';
1.585     bisitz   1781:     $result.=&Apache::loncommon::end_data_table_row();
1.695     bisitz   1782:     $result.=&Apache::loncommon::start_data_table_row().'<td colspan="6">';
1.71      ng       1783:     $result.='<input type="hidden" name="stores'.$counter.'_'.$partid.'" value="" />'."\n".
                   1784: 	'<input type="hidden" name="oldpts'.$counter.'_'.$partid.'" value="'.$score.'" />'."\n".
                   1785: 	'<input type="hidden" name="solved'.$counter.'_'.$partid.'" value="'.
1.269     raeburn  1786: 	$$record{'resource.'.$partid.'.solved'}.'" />'."\n".
                   1787:         '<input type="hidden" name="totaltries'.$counter.'_'.$partid.'" value="'.
                   1788:         $$record{'resource.'.$partid.'.tries'}.'" />'."\n".
                   1789:         '<input type="hidden" name="aggtries'.$counter.'_'.$partid.'" value="'.
                   1790:         $aggtries.'" />'."\n";
1.582     raeburn  1791:     my $res_error;
                   1792:     $result.=&handback_box($symb,$uname,$udom,$counter,$partid,$record,\$res_error);
1.695     bisitz   1793:     $result.='</td>'.&Apache::loncommon::end_data_table_row();
1.582     raeburn  1794:     if ($res_error) {
                   1795:         return &navmap_errormsg();
                   1796:     }
1.318     banghart 1797:     return $result;
                   1798: }
1.322     albertel 1799: 
                   1800: sub handback_box {
1.623     www      1801:     my ($symb,$uname,$udom,$counter,$partid,$record,$res_error_pointer) = @_;
                   1802:     my ($partlist,$handgrade,$responseType) = &response_type($symb,$res_error_pointer);
1.323     banghart 1803:     my (@respids);
1.652     raeburn  1804:     my @part_response_id = &flatten_responseType($responseType);
1.375     albertel 1805:     foreach my $part_response_id (@part_response_id) {
                   1806:     	my ($part,$resp) = @{ $part_response_id };
1.323     banghart 1807:         if ($part eq $partid) {
1.375     albertel 1808:             push(@respids,$resp);
1.323     banghart 1809:         }
                   1810:     }
1.318     banghart 1811:     my $result;
1.323     banghart 1812:     foreach my $respid (@respids) {
1.322     albertel 1813: 	my $prefix = $counter.'_'.$partid.'_'.$respid.'_';
                   1814: 	my $files=&get_submitted_files($udom,$uname,$partid,$respid,$record);
                   1815: 	next if (!@$files);
1.654     raeburn  1816: 	my $file_counter = 0;
1.313     banghart 1817: 	foreach my $file (@$files) {
1.368     banghart 1818: 	    if ($file =~ /\/portfolio\//) {
1.654     raeburn  1819:                 $file_counter++;
1.368     banghart 1820:     	        my ($file_path, $file_disp) = ($file =~ m|(.+/)(.+)$|);
1.729     raeburn  1821:     	        my ($name,$version,$ext) = &Apache::lonnet::file_name_version_ext($file_disp);
1.368     banghart 1822:     	        $file_disp = "$name.$ext";
                   1823:     	        $file = $file_path.$file_disp;
                   1824:     	        $result.=&mt('Return commented version of [_1] to student.',
                   1825:     			 '<span class="LC_filename">'.$file_disp.'</span>');
                   1826:     	        $result.='<input type="file"   name="'.$prefix.'returndoc'.$file_counter.'" />'."\n";
1.654     raeburn  1827:     	        $result.='<input type="hidden" name="'.$prefix.'origdoc'.$file_counter.'" value="'.$file.'" /><br />'."\n";
1.368     banghart 1828: 	    }
1.322     albertel 1829: 	}
1.654     raeburn  1830:         if ($file_counter) {
                   1831:             $result .= '<input type="hidden" name="'.$prefix.'countreturndoc" value="'.$file_counter.'" />'."\n".
                   1832:                        '<span class="LC_info">'.
                   1833:                        '('.&mt('File(s) will be uploaded when you click on Save &amp; Next below.',$file_counter).')</span><br /><br />';
                   1834:         }
1.313     banghart 1835:     }
1.318     banghart 1836:     return $result;    
1.71      ng       1837: }
1.44      ng       1838: 
1.58      albertel 1839: sub show_problem {
1.382     albertel 1840:     my ($request,$symb,$uname,$udom,$removeform,$viewon,$mode,$form) = @_;
1.144     albertel 1841:     my $rendered;
1.382     albertel 1842:     my %form = ((ref($form) eq 'HASH')? %{$form} : ());
1.329     albertel 1843:     &Apache::lonxml::remember_problem_counter();
1.144     albertel 1844:     if ($mode eq 'both' or $mode eq 'text') {
                   1845: 	$rendered=&Apache::loncommon::get_student_view($symb,$uname,$udom,
1.382     albertel 1846: 						       $env{'request.course.id'},
                   1847: 						       undef,\%form);
1.144     albertel 1848:     }
1.58      albertel 1849:     if ($removeform) {
                   1850: 	$rendered=~s|<form(.*?)>||g;
                   1851: 	$rendered=~s|</form>||g;
1.374     albertel 1852: 	$rendered=~s|(<input[^>]*name\s*=\s*"?)(\w+)("?)|$1would_have_been_$2$3|g;
1.58      albertel 1853:     }
1.144     albertel 1854:     my $companswer;
                   1855:     if ($mode eq 'both' or $mode eq 'answer') {
1.329     albertel 1856: 	&Apache::lonxml::restore_problem_counter();
1.382     albertel 1857: 	$companswer=
                   1858: 	    &Apache::loncommon::get_student_answers($symb,$uname,$udom,
                   1859: 						    $env{'request.course.id'},
                   1860: 						    %form);
1.144     albertel 1861:     }
1.58      albertel 1862:     if ($removeform) {
                   1863: 	$companswer=~s|<form(.*?)>||g;
                   1864: 	$companswer=~s|</form>||g;
1.144     albertel 1865: 	$companswer=~s|name="submit"|name="would_have_been_submit"|g;
1.58      albertel 1866:     }
1.671     raeburn  1867:     my $renderheading = &mt('View of the problem');
                   1868:     my $answerheading = &mt('Correct answer');
                   1869:     if (($uname ne $env{'user.name'}) || ($udom ne $env{'user.domain'})) {
                   1870:         my $stu_fullname = $env{'form.fullname'};
                   1871:         if ($stu_fullname eq '') {
                   1872:             $stu_fullname = &Apache::loncommon::plainname($uname,$udom,'lastname');
                   1873:         }
                   1874:         my $forwhom = &nameUserString(undef,$stu_fullname,$uname,$udom);
                   1875:         if ($forwhom ne '') {
                   1876:             $renderheading = &mt('View of the problem for[_1]',$forwhom);
                   1877:             $answerheading = &mt('Correct answer for[_1]',$forwhom);
                   1878:         }
                   1879:     }
1.468     albertel 1880:     $rendered=
1.588     bisitz   1881:         '<div class="LC_Box">'
1.671     raeburn  1882:        .'<h3 class="LC_hcell">'.$renderheading.'</h3>'
1.588     bisitz   1883:        .$rendered
                   1884:        .'</div>';
1.468     albertel 1885:     $companswer=
1.588     bisitz   1886:         '<div class="LC_Box">'
1.671     raeburn  1887:        .'<h3 class="LC_hcell">'.$answerheading.'</h3>'
1.588     bisitz   1888:        .$companswer
                   1889:        .'</div>';
1.468     albertel 1890:     my $result;
1.144     albertel 1891:     if ($mode eq 'both') {
1.588     bisitz   1892:         $result=$rendered.$companswer;
1.144     albertel 1893:     } elsif ($mode eq 'text') {
1.588     bisitz   1894:         $result=$rendered;
1.144     albertel 1895:     } elsif ($mode eq 'answer') {
1.588     bisitz   1896:         $result=$companswer;
1.144     albertel 1897:     }
1.71      ng       1898:     return $result;
1.58      albertel 1899: }
1.397     albertel 1900: 
1.396     banghart 1901: sub files_exist {
                   1902:     my ($r, $symb) = @_;
                   1903:     my @students = &Apache::loncommon::get_env_multiple('form.stuinfo');
1.397     albertel 1904: 
1.396     banghart 1905:     foreach my $student (@students) {
                   1906:         my ($uname,$udom,$fullname) = split(/:/,$student);
1.397     albertel 1907:         my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},
                   1908: 					      $udom,$uname);
1.396     banghart 1909:         my ($string,$timestamp)= &get_last_submission(\%record);
1.397     albertel 1910:         foreach my $submission (@$string) {
                   1911:             my ($partid,$respid) =
                   1912: 		($submission =~ /^resource\.([^\.]*)\.([^\.]*)\.submission/);
                   1913:             my $files=&get_submitted_files($udom,$uname,$partid,$respid,
                   1914: 					   \%record);
                   1915:             return 1 if (@$files);
1.396     banghart 1916:         }
                   1917:     }
1.397     albertel 1918:     return 0;
1.396     banghart 1919: }
1.397     albertel 1920: 
1.394     banghart 1921: sub download_all_link {
                   1922:     my ($r,$symb) = @_;
1.621     www      1923:     unless (&files_exist($r, $symb)) {
                   1924:        $r->print(&mt('There are currently no submitted documents.'));
                   1925:        return;
                   1926:     }
                   1927: 
1.395     albertel 1928:     my $all_students = 
                   1929: 	join("\n", &Apache::loncommon::get_env_multiple('form.stuinfo'));
                   1930: 
                   1931:     my $parts =
                   1932: 	join("\n",&Apache::loncommon::get_env_multiple('form.vPart'));
                   1933: 
1.394     banghart 1934:     my $identifier = &Apache::loncommon::get_cgi_id();
1.514     raeburn  1935:     &Apache::lonnet::appenv({'cgi.'.$identifier.'.students' => $all_students,
                   1936:                              'cgi.'.$identifier.'.symb' => $symb,
                   1937:                              'cgi.'.$identifier.'.parts' => $parts,});
1.395     albertel 1938:     $r->print('<a href="/cgi-bin/multidownload.pl?'.$identifier.'">'.
                   1939: 	      &mt('Download All Submitted Documents').'</a>');
1.621     www      1940:     return;
                   1941: }
                   1942: 
                   1943: sub submit_download_link {
                   1944:     my ($request,$symb) = @_;
                   1945:     if (!$symb) { return ''; }
                   1946: #FIXME: Figure out which type of problem this is and provide appropriate download
                   1947:     &download_all_link($request,$symb);
1.394     banghart 1948: }
1.395     albertel 1949: 
1.432     banghart 1950: sub build_section_inputs {
                   1951:     my $section_inputs;
                   1952:     if ($env{'form.section'} eq '') {
                   1953:         $section_inputs .= '<input type="hidden" name="section" value="all" />'."\n";
                   1954:     } else {
                   1955:         my @sections = &Apache::loncommon::get_env_multiple('form.section');
1.434     albertel 1956:         foreach my $section (@sections) {
1.432     banghart 1957:             $section_inputs .= '<input type="hidden" name="section" value="'.$section.'" />'."\n";
                   1958:         }
                   1959:     }
                   1960:     return $section_inputs;
                   1961: }
                   1962: 
1.44      ng       1963: # --------------------------- show submissions of a student, option to grade 
                   1964: sub submission {
1.608     www      1965:     my ($request,$counter,$total,$symb) = @_;
1.257     albertel 1966:     my ($uname,$udom)     = ($env{'form.student'},$env{'form.userdom'});
                   1967:     $udom = ($udom eq '' ? $env{'user.domain'} : $udom); #has form.userdom changed for a student?
                   1968:     my $usec = &Apache::lonnet::getsection($udom,$uname,$env{'request.course.id'});
                   1969:     $env{'form.fullname'} = &Apache::loncommon::plainname($uname,$udom,'lastname') if $env{'form.fullname'} eq '';
1.608     www      1970: 
1.605     www      1971:     my $probtitle=&Apache::lonnet::gettitle($symb); 
1.324     albertel 1972:     if ($symb eq '') { $request->print("Unable to handle ambiguous references:."); return ''; }
1.104     albertel 1973: 
                   1974:     if (!&canview($usec)) {
1.712     bisitz   1975:         $request->print(
                   1976:             '<span class="LC_warning">'.
1.713     bisitz   1977:             &mt('Unable to view requested student.').
1.712     bisitz   1978:             ' '.&mt('([_1] in section [_2] in course id [_3])',
                   1979:                         $uname.':'.$udom,$usec,$env{'request.course.id'}).
                   1980:             '</span>');
1.104     albertel 1981: 	return;
                   1982:     }
                   1983: 
1.257     albertel 1984:     if (!$env{'form.lastSub'}) { $env{'form.lastSub'} = 'datesub'; }
                   1985:     if (!$env{'form.vProb'}) { $env{'form.vProb'} = 'yes'; }
                   1986:     if (!$env{'form.vAns'}) { $env{'form.vAns'} = 'yes'; }
                   1987:     my $last = ($env{'form.lastSub'} eq 'last' ? 'last' : '');
1.381     albertel 1988:     my $checkIcon = '<img alt="'.&mt('Check Mark').
                   1989: 	'" src="'.$request->dir_config('lonIconsURL').
1.122     ng       1990: 	'/check.gif" height="16" border="0" />';
1.41      ng       1991: 
                   1992:     # header info
                   1993:     if ($counter == 0) {
                   1994: 	&sub_page_js($request);
1.621     www      1995: 	&sub_page_kw_js($request);
1.118     ng       1996: 
1.44      ng       1997: 	# option to display problem, only once else it cause problems 
                   1998:         # with the form later since the problem has a form.
1.257     albertel 1999: 	if ($env{'form.vProb'} eq 'yes' or $env{'form.vAns'} eq 'yes') {
1.144     albertel 2000: 	    my $mode;
1.257     albertel 2001: 	    if ($env{'form.vProb'} eq 'yes' && $env{'form.vAns'} eq 'yes') {
1.144     albertel 2002: 		$mode='both';
1.257     albertel 2003: 	    } elsif ($env{'form.vProb'} eq 'yes') {
1.144     albertel 2004: 		$mode='text';
1.257     albertel 2005: 	    } elsif ($env{'form.vAns'} eq 'yes') {
1.144     albertel 2006: 		$mode='answer';
                   2007: 	    }
1.329     albertel 2008: 	    &Apache::lonxml::clear_problem_counter();
1.144     albertel 2009: 	    $request->print(&show_problem($request,$symb,$uname,$udom,0,1,$mode));
1.41      ng       2010: 	}
1.441     www      2011: 
1.704     raeburn  2012: 	# kwclr is the only variable that is guaranteed not to be blank 
1.44      ng       2013:         # if this subroutine has been called once.
1.41      ng       2014: 	my %keyhash = ();
1.624     www      2015: #	if ($env{'form.kwclr'} eq '' && $env{'form.handgrade'} eq 'yes') {
                   2016:         if (1) {
1.41      ng       2017: 	    %keyhash = &Apache::lonnet::dump('nohist_handgrade',
1.257     albertel 2018: 					     $env{'course.'.$env{'request.course.id'}.'.domain'},
                   2019: 					     $env{'course.'.$env{'request.course.id'}.'.num'});
1.41      ng       2020: 
1.257     albertel 2021: 	    my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
                   2022: 	    $env{'form.keywords'} = $keyhash{$symb.'_keywords'} ne '' ? $keyhash{$symb.'_keywords'} : '';
                   2023: 	    $env{'form.kwclr'}    = $keyhash{$loginuser.'_kwclr'} ne '' ? $keyhash{$loginuser.'_kwclr'} : 'red';
                   2024: 	    $env{'form.kwsize'}   = $keyhash{$loginuser.'_kwsize'} ne '' ? $keyhash{$loginuser.'_kwsize'} : '0';
                   2025: 	    $env{'form.kwstyle'}  = $keyhash{$loginuser.'_kwstyle'} ne '' ? $keyhash{$loginuser.'_kwstyle'} : '';
                   2026: 	    $env{'form.msgsub'}   = $keyhash{$symb.'_subject'} ne '' ? 
1.605     www      2027: 		$keyhash{$symb.'_subject'} : $probtitle;
1.257     albertel 2028: 	    $env{'form.savemsgN'} = $keyhash{$symb.'_savemsgN'} ne '' ? $keyhash{$symb.'_savemsgN'} : '0';
1.41      ng       2029: 	}
1.257     albertel 2030: 	my $overRideScore = $env{'form.overRideScore'} eq '' ? 'no' : $env{'form.overRideScore'};
1.442     banghart 2031: 	my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
1.303     banghart 2032: 	$request->print('<form action="/adm/grades" method="post" name="SCORE" enctype="multipart/form-data">'."\n".
1.41      ng       2033: 			'<input type="hidden" name="command"    value="handgrade" />'."\n".
1.442     banghart 2034: 			'<input type="hidden" name="Status"     value="'.$stu_status.'" />'."\n".
1.120     ng       2035: 			'<input type="hidden" name="overRideScore" value="'.$overRideScore.'" />'."\n".
1.41      ng       2036: 			'<input type="hidden" name="refresh"    value="off" />'."\n".
1.120     ng       2037: 			'<input type="hidden" name="studentNo"  value="" />'."\n".
                   2038: 			'<input type="hidden" name="gradeOpt"   value="" />'."\n".
1.418     albertel 2039: 			'<input type="hidden" name="symb"       value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.257     albertel 2040: 			'<input type="hidden" name="vProb"      value="'.$env{'form.vProb'}.'" />'."\n".
                   2041: 			'<input type="hidden" name="vAns"       value="'.$env{'form.vAns'}.'" />'."\n".
                   2042: 			'<input type="hidden" name="lastSub"    value="'.$env{'form.lastSub'}.'" />'."\n".
1.432     banghart 2043: 			&build_section_inputs().
1.326     albertel 2044: 			'<input type="hidden" name="submitonly" value="'.$env{'form.submitonly'}.'" />'."\n".
1.41      ng       2045: 			'<input type="hidden" name="NCT"'.
1.257     albertel 2046: 			' value="'.($env{'form.NTSTU'} ne '' ? $env{'form.NTSTU'} : $total+1).'" />'."\n");
1.624     www      2047: #	if ($env{'form.handgrade'} eq 'yes') {
                   2048:         if (1) {
1.257     albertel 2049: 	    $request->print('<input type="hidden" name="keywords" value="'.$env{'form.keywords'}.'" />'."\n".
                   2050: 			    '<input type="hidden" name="kwclr"    value="'.$env{'form.kwclr'}.'" />'."\n".
                   2051: 			    '<input type="hidden" name="kwsize"   value="'.$env{'form.kwsize'}.'" />'."\n".
                   2052: 			    '<input type="hidden" name="kwstyle"  value="'.$env{'form.kwstyle'}.'" />'."\n".
                   2053: 			    '<input type="hidden" name="msgsub"   value="'.$env{'form.msgsub'}.'" />'."\n".
1.123     ng       2054: 			    '<input type="hidden" name="shownSub" value="0" />'."\n".
1.257     albertel 2055: 			    '<input type="hidden" name="savemsgN" value="'.$env{'form.savemsgN'}.'" />'."\n");
1.154     albertel 2056: 	    foreach my $partid (&Apache::loncommon::get_env_multiple('form.vPart')) {
                   2057: 		$request->print('<input type="hidden" name="vPart" value="'.$partid.'" />'."\n");
                   2058: 	    }
1.123     ng       2059: 	}
1.41      ng       2060: 	
                   2061: 	my ($cts,$prnmsg) = (1,'');
1.257     albertel 2062: 	while ($cts <= $env{'form.savemsgN'}) {
1.41      ng       2063: 	    $prnmsg.='<input type="hidden" name="savemsg'.$cts.'" value="'.
1.123     ng       2064: 		(!exists($keyhash{$symb.'_savemsg'.$cts}) ? 
1.257     albertel 2065: 		 &Apache::lonfeedback::clear_out_html($env{'form.savemsg'.$cts}) :
1.80      ng       2066: 		 &Apache::lonfeedback::clear_out_html($keyhash{$symb.'_savemsg'.$cts})).
1.123     ng       2067: 		'" />'."\n".
                   2068: 		'<input type="hidden" name="shownOnce'.$cts.'" value="0" />'."\n";
1.41      ng       2069: 	    $cts++;
                   2070: 	}
                   2071: 	$request->print($prnmsg);
1.32      ng       2072: 
1.624     www      2073: #	if ($env{'form.handgrade'} eq 'yes') {
                   2074:         if (1) {
1.652     raeburn  2075: 
                   2076:             my %lt = &Apache::lonlocal::texthash(
1.719     bisitz   2077:                           keyh => 'Keyword Highlighting for Essays',
1.652     raeburn  2078:                           keyw => 'Keyword Options',
1.655     raeburn  2079:                           list => 'List',
1.652     raeburn  2080:                           past => 'Paste Selection to List',
1.661     www      2081:                           high => 'Highlight Attribute',
1.652     raeburn  2082:                      );    
1.88      www      2083: #
                   2084: # Print out the keyword options line
                   2085: #
1.718     bisitz   2086: 	    $request->print(
                   2087:                 '<div class="LC_columnSection">'
                   2088:                .'<fieldset><legend>'.$lt{'keyh'}.'</legend>'
                   2089:                .&Apache::lonhtmlcommon::funclist_from_array(
                   2090:                     ['<a href="javascript:keywords(document.SCORE);" target="_self">'.$lt{'list'}.'</a>',
                   2091:                      '<a href="#" onmousedown="javascript:getSel(); return false"
                   2092:  class="page">'.$lt{'past'}.'</a>',
                   2093:                      '<a href="javascript:kwhighlight();" target="_self">'.$lt{'high'}.'</a>'],
                   2094:                     {legend => $lt{'keyw'}})
                   2095:                .'</fieldset></div>'
                   2096:             );
                   2097: 
1.88      www      2098: #
                   2099: # Load the other essays for similarity check
                   2100: #
1.324     albertel 2101:             my (undef,undef,$essayurl) = &Apache::lonnet::decode_symb($symb);
1.384     albertel 2102: 	    my ($adom,$aname,$apath)=($essayurl=~/^($LONCAPA::domain_re)\/($LONCAPA::username_re)\/(.*)$/);
1.359     www      2103: 	    $apath=&escape($apath);
1.88      www      2104: 	    $apath=~s/\W/\_/gs;
1.674     raeburn  2105:             &init_old_essays($symb,$apath,$adom,$aname);
1.41      ng       2106:         }
                   2107:     }
1.44      ng       2108: 
1.441     www      2109: # This is where output for one specific student would start
1.592     bisitz   2110:     my $add_class = ($counter%2) ? ' LC_grade_show_user_odd_row' : '';
                   2111:     $request->print(
                   2112:         "\n\n"
                   2113:        .'<div class="LC_grade_show_user'.$add_class.'">'
                   2114:        .'<h2>'.&nameUserString(undef,$env{'form.fullname'},$uname,$udom).'</h2>'
                   2115:        ."\n"
                   2116:     );
1.441     www      2117: 
1.592     bisitz   2118:     # Show additional functions if allowed
                   2119:     if ($perm{'vgr'}) {
                   2120:         $request->print(
                   2121:             &Apache::loncommon::track_student_link(
1.708     bisitz   2122:                 'View recent activity',
1.592     bisitz   2123:                 $uname,$udom,'check')
                   2124:            .' '
                   2125:         );
                   2126:     }
                   2127:     if ($perm{'opa'}) {
                   2128:         $request->print(
                   2129:             &Apache::loncommon::pprmlink(
                   2130:                 &mt('Set/Change parameters'),
                   2131:                 $uname,$udom,$symb,'check'));
                   2132:     }
                   2133: 
                   2134:     # Show Problem
1.257     albertel 2135:     if ($env{'form.vProb'} eq 'all' or $env{'form.vAns'} eq 'all') {
1.144     albertel 2136: 	my $mode;
1.257     albertel 2137: 	if ($env{'form.vProb'} eq 'all' && $env{'form.vAns'} eq 'all') {
1.144     albertel 2138: 	    $mode='both';
1.257     albertel 2139: 	} elsif ($env{'form.vProb'} eq 'all' ) {
1.144     albertel 2140: 	    $mode='text';
1.257     albertel 2141: 	} elsif ($env{'form.vAns'} eq 'all') {
1.144     albertel 2142: 	    $mode='answer';
                   2143: 	}
1.329     albertel 2144: 	&Apache::lonxml::clear_problem_counter();
1.475     albertel 2145: 	$request->print(&show_problem($request,$symb,$uname,$udom,1,1,$mode,{'request.prefix' => 'ctr'.$counter}));
1.58      albertel 2146:     }
1.144     albertel 2147: 
1.257     albertel 2148:     my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
1.582     raeburn  2149:     my $res_error;
                   2150:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
                   2151:     if ($res_error) {
                   2152:         $request->print(&navmap_errormsg());
                   2153:         return;
                   2154:     }
1.41      ng       2155: 
1.44      ng       2156:     # Display student info
1.41      ng       2157:     $request->print(($counter == 0 ? '' : '<br />'));
1.590     bisitz   2158: 
                   2159:     my $result='<div class="LC_Box">'
                   2160:               .'<h3 class="LC_hcell">'.&mt('Submissions').'</h3>';
1.45      ng       2161:     $result.='<input type="hidden" name="name'.$counter.
1.588     bisitz   2162:              '" value="'.$env{'form.fullname'}.'" />'."\n";
1.624     www      2163: #    if ($env{'form.handgrade'} eq 'no') {
                   2164:     if (1) {
1.588     bisitz   2165:         $result.='<p class="LC_info">'
                   2166:                 .&mt('Part(s) graded correct by the computer is marked with a [_1] symbol.',$checkIcon)
                   2167:                 ."</p>\n";
1.469     albertel 2168:     }
                   2169: 
1.118     ng       2170:     # If any part of the problem is an essay-response (handgraded), then check for collaborators
1.464     albertel 2171:     my $fullname;
                   2172:     my $col_fullnames = [];
1.624     www      2173: #    if ($env{'form.handgrade'} eq 'yes') {
                   2174:     if (1) {
1.464     albertel 2175: 	(my $sub_result,$fullname,$col_fullnames)=
                   2176: 	    &check_collaborators($symb,$uname,$udom,\%record,$handgrade,
                   2177: 				 $counter);
                   2178: 	$result.=$sub_result;
1.41      ng       2179:     }
1.44      ng       2180:     $request->print($result."\n");
1.702     kruse    2181:     
1.44      ng       2182:     # print student answer/submission
1.588     bisitz   2183:     # Options are (1) Handgraded submission only
1.44      ng       2184:     #             (2) Last submission, includes submission that is not handgraded 
                   2185:     #                  (for multi-response type part)
                   2186:     #             (3) Last submission plus the parts info
                   2187:     #             (4) The whole record for this student
1.702     kruse    2188:     
                   2189:     my ($string,$timestamp)= &get_last_submission(\%record);
1.468     albertel 2190: 	
1.702     kruse    2191:     my $lastsubonly;
1.468     albertel 2192: 
1.702     kruse    2193:     if ($$timestamp eq '') {
                   2194:         $lastsubonly.='<div class="LC_grade_submissions_body">'.$$string[0].'</div>'; 
                   2195:     } else {
                   2196:         $lastsubonly =
                   2197:             '<div class="LC_grade_submissions_body">'
                   2198:            .'<b>'.&mt('Date Submitted:').'</b> '.$$timestamp."\n";
                   2199: 
                   2200: 	my %seenparts;
                   2201: 	my @part_response_id = &flatten_responseType($responseType);
                   2202: 	foreach my $part (@part_response_id) {
                   2203: 	    next if ($env{'form.lastSub'} eq 'hdgrade' 
1.393     albertel 2204: 			 && $$handgrade{$$part[0].'_'.$$part[1]} ne 'yes');
                   2205: 
1.702     kruse    2206: 	    my ($partid,$respid) = @{ $part };
                   2207: 	    my $display_part=&get_display_part($partid,$symb);
                   2208: 	    if ($env{"form.$uname:$udom:$partid:submitted_by"}) {
                   2209: 		if (exists($seenparts{$partid})) { next; }
                   2210: 		$seenparts{$partid}=1;
                   2211:                 $request->print(
                   2212:                     '<b>'.&mt('Part: [_1]',$display_part).'</b>'.
                   2213:                     ' <b>'.&mt('Collaborative submission by: [_1]',
                   2214:                                '<a href="javascript:viewSubmitter(\''.
                   2215:                                $env{"form.$uname:$udom:$partid:submitted_by"}.
                   2216:                                '\');" target="_self">'.
                   2217:                                $$fullname{$env{"form.$uname:$udom:$partid:submitted_by"}}.'</a>').
                   2218:                     '<br />');
                   2219: 		next;
                   2220: 		}
                   2221: 	    my $responsetype = $responseType->{$partid}->{$respid};
                   2222: 	    if (!exists($record{"resource.$partid.$respid.submission"})) {
                   2223:                 $lastsubonly.="\n".'<div class="LC_grade_submission_part">'.
                   2224:                     '<b>'.&mt('Part: [_1]',$display_part).'</b>'.
                   2225:                     ' <span class="LC_internal_info">'.
                   2226:                     '('.&mt('Response ID: [_1]',$respid).')'.
                   2227:                     '</span>&nbsp; &nbsp;'.
                   2228: 	       	    '<span class="LC_warning">'.&mt('Nothing submitted - no attempts.').'</span><br /><br /></div>';
                   2229: 		next;
                   2230: 	    }
                   2231: 	    foreach my $submission (@$string) {
                   2232: 		my ($partid,$respid) = ($submission =~ /^resource\.([^\.]*)\.([^\.]*)\.submission/);
                   2233: 		if (join('_',@{$part}) ne ($partid.'_'.$respid)) { next; }
1.724     raeburn  2234: 		my ($ressub,$hide,$draft,$subval) = split(/:/,$submission,4);
1.702     kruse    2235: 		# Similarity check
                   2236:                 my $similar='';
                   2237:                 my ($type,$trial,$rndseed);
                   2238:                 if ($hide eq 'rand') {
                   2239:                     $type = 'randomizetry';
                   2240:                     $trial = $record{"resource.$partid.tries"};
1.733     raeburn  2241:                     $rndseed = $record{"resource.$partid.rndseed"};
1.702     kruse    2242:                 }
                   2243: 	        if ($env{'form.checkPlag'}) {
                   2244:     		    my ($oname,$odom,$ocrsid,$oessay,$osim)=
                   2245: 		        &most_similar($uname,$udom,$symb,$subval);
                   2246: 		    if ($osim) {
                   2247: 			$osim=int($osim*100.0);
                   2248: 			my %old_course_desc = 
                   2249: 			    &Apache::lonnet::coursedescription($ocrsid,
                   2250: 							{'one_time' => 1});
                   2251: 
                   2252:                         if ($hide eq 'anon') {
                   2253:                             $similar='<hr /><span class="LC_warning">'.&mt("Essay was found to be similar to another essay submitted for this assignment.").'<br />'.
                   2254:                                      &mt('As the current submission is for an anonymous survey, no other details are available.').'</span><hr />';
                   2255:                         } else {
                   2256: 			    $similar="<hr /><h3><span class=\"LC_warning\">".
                   2257: 				&mt('Essay is [_1]% similar to an essay by [_2] in course [_3] (course id [_4]:[_5])',
                   2258: 				    $osim,
                   2259: 				    &Apache::loncommon::plainname($oname,$odom).' ('.$oname.':'.$odom.')',
1.596     raeburn  2260: 				        $old_course_desc{'description'},
                   2261: 				        $old_course_desc{'num'},
                   2262: 				        $old_course_desc{'domain'}).
                   2263: 				    '</span></h3><blockquote><i>'.
                   2264: 				    &keywords_highlight($oessay).
                   2265: 				    '</i></blockquote><hr />';
1.702     kruse    2266:                         }
                   2267: 	            }
                   2268: 		}
                   2269: 		my $order=&get_order($partid,$respid,$symb,$uname,$udom,
                   2270:                                      undef,$type,$trial,$rndseed);
                   2271:                 if ($env{'form.lastSub'} eq 'lastonly' || $env{'form.lastSub'} eq 'datesub' || $env{'form.lastSub'} =~ /^(last|all)$/ || ($env{'form.lastSub'} eq 'hdgrade' && 
1.377     albertel 2272: 			 $$handgrade{$$part[0].'_'.$$part[1]} eq 'yes')) {
1.702     kruse    2273: 		    my $display_part=&get_display_part($partid,$symb);
                   2274:                     $lastsubonly.='<div class="LC_grade_submission_part">'.
                   2275:                         '<b>'.&mt('Part: [_1]',$display_part).'</b>'.
                   2276:                         ' <span class="LC_internal_info">'.
                   2277:                         '('.&mt('Response ID: [_1]',$respid).')'.
                   2278:                         '</span>&nbsp; &nbsp;';
                   2279: 		    my $files=&get_submitted_files($udom,$uname,$partid,$respid,\%record);
                   2280:                         
                   2281: 		    if (@$files) {
                   2282:                         if ($hide eq 'anon') {
                   2283:                             $lastsubonly.='<br />'.&mt('[quant,_1,file] uploaded to this anonymous survey',scalar(@{$files}));
                   2284:                         } else {
                   2285:                             $lastsubonly.='<br /><br />'.'<b>'.&mt('Submitted Files:').'</b>'
                   2286:                                         .'<br /><span class="LC_warning">';
                   2287:                             if(@$files == 1) {
                   2288:                                 $lastsubonly .= &mt('Like all files provided by users, this file may contain viruses!');
1.596     raeburn  2289:                             } else {
1.702     kruse    2290:                                 $lastsubonly .= &mt('Like all files provided by users, these files may contain viruses!');
                   2291:                             }
                   2292:                             $lastsubonly .= '</span>';                         
                   2293:                             foreach my $file (@$files) {
                   2294:                                 &Apache::lonnet::allowuploaded('/adm/grades',$file);
                   2295:                                 $lastsubonly.='<br /><a href="'.$file.'?rawmode=1" target="lonGRDs"><img src="'.&Apache::loncommon::icon($file).'" border="0" alt="" /> '.$file.'</a>';
1.596     raeburn  2296:                             }
                   2297:                         }
1.702     kruse    2298: 			$lastsubonly.='<br />';
                   2299:                     }
                   2300:                     if ($hide eq 'anon') {
                   2301:                         $lastsubonly.='<br /><b>'.&mt('Anonymous Survey').'</b>'; 
                   2302:                     } else {
1.724     raeburn  2303:              	        $lastsubonly.='<br /><b>'.&mt('Submitted Answer:').' </b>';
                   2304:                         if ($draft) {
                   2305:                             $lastsubonly.= ' <span class="LC_warning">'.&mt('Draft Copy').'</span>';
                   2306:                         }
                   2307:                         $subval =
1.702     kruse    2308: 			    &cleanRecord($subval,$responsetype,$symb,$partid,
                   2309: 					 $respid,\%record,$order,undef,$uname,$udom,$type,$trial,$rndseed);
1.724     raeburn  2310:                         if ($responsetype eq 'essay') {
                   2311:                             $subval =~ s{\n}{<br />}g;
                   2312:                         }
                   2313:                         $lastsubonly.=$subval."\n";
1.702     kruse    2314:                     }
                   2315: 	            if ($similar) {$lastsubonly.="<br /><br />$similar\n";}
                   2316: 		    $lastsubonly.='</div>';
1.41      ng       2317: 		}
1.702     kruse    2318:             }
1.151     albertel 2319: 	}
1.702     kruse    2320: 	$lastsubonly.='</div>'."\n"; # End: LC_grade_submissions_body
                   2321:     }
                   2322:     $request->print($lastsubonly);
                   2323:     if ($env{'form.lastSub'} eq 'datesub') {
1.623     www      2324:         my ($parts,$handgrade,$responseType) = &response_type($symb,\$res_error);
1.148     albertel 2325: 	$request->print(&displaySubByDates($symb,\%record,$parts,$responseType,$checkIcon,$uname,$udom));
1.720     kruse    2326:   
1.702     kruse    2327:     } 
                   2328:     if ($env{'form.lastSub'} =~ /^(last|all)$/) {
1.726     raeburn  2329:         my $identifier = (&canmodify($usec)? $counter : '');
1.702     kruse    2330:         $request->print(&Apache::loncommon::get_previous_attempt($symb,$uname,$udom,
1.257     albertel 2331: 								 $env{'request.course.id'},
1.44      ng       2332: 								 $last,'.submission',
1.726     raeburn  2333: 								 'Apache::grades::keywords_highlight',
                   2334:                                                                  $usec,$identifier));
1.41      ng       2335:     }
1.121     ng       2336:     $request->print('<input type="hidden" name="unamedom'.$counter.'" value="'.$uname.':'
                   2337: 	.$udom.'" />'."\n");
1.44      ng       2338:     # return if view submission with no grading option
1.618     www      2339:     if (!&canmodify($usec)) {
1.633     www      2340: 	$request->print('<p><span class="LC_warning">'.&mt('No grading privileges').'</span></p></div>');
1.41      ng       2341: 	return;
1.180     albertel 2342:     } else {
1.468     albertel 2343: 	$request->print('</div>'."\n");
1.41      ng       2344:     }
1.33      ng       2345: 
1.121     ng       2346:     # essay grading message center
1.624     www      2347: #    if ($env{'form.handgrade'} eq 'yes') {
                   2348:     if (1) {
1.468     albertel 2349: 	my $result='<div class="LC_grade_message_center">';
                   2350:     
                   2351: 	$result.='<div class="LC_grade_message_center_header">'.
                   2352: 	    &mt('Send Message').'</div><div class="LC_grade_message_center_body">';
1.257     albertel 2353: 	my ($lastname,$givenn) = split(/,/,$env{'form.fullname'});
1.118     ng       2354: 	my $msgfor = $givenn.' '.$lastname;
1.464     albertel 2355: 	if (scalar(@$col_fullnames) > 0) {
                   2356: 	    my $lastone = pop(@$col_fullnames);
                   2357: 	    $msgfor .= ', '.(join ', ',@$col_fullnames).' and '.$lastone.'.';
1.118     ng       2358: 	}
                   2359: 	$msgfor =~ s/\'/\\'/g; #' stupid emacs - no! javascript
1.468     albertel 2360: 	$result.='<input type="hidden" name="includemsg'.$counter.'" value="" />'."\n".
1.121     ng       2361: 	    '<input type="hidden" name="newmsg'.$counter.'" value="" />'."\n";
                   2362: 	$result.='&nbsp;<a href="javascript:msgCenter(document.SCORE,'.$counter.
1.417     albertel 2363: 	    ',\''.$msgfor.'\');" target="_self">'.
1.695     bisitz   2364: 	    &mt('Compose message to student'.(scalar(@$col_fullnames) >= 1 ? 's' : '')).'</a><label> ('.
1.350     albertel 2365: 	    &mt('incl. grades').' <input type="checkbox" name="withgrades'.$counter.'" /></label>)'.
1.695     bisitz   2366: 	    ' <img src="'.$request->dir_config('lonIconsURL').
                   2367: 	    '/mailbkgrd.gif" width="14" height="10" alt="" name="mailicon'.$counter.'" />'."\n".
1.298     www      2368: 	    '<br />&nbsp;('.
1.468     albertel 2369: 	    &mt('Message will be sent when you click on Save &amp; Next below.').")\n";
                   2370: 	$result.='</div></div>';
1.121     ng       2371: 	$request->print($result);
1.118     ng       2372:     }
1.41      ng       2373: 
                   2374:     my %seen = ();
                   2375:     my @partlist;
1.129     ng       2376:     my @gradePartRespid;
1.375     albertel 2377:     my @part_response_id = &flatten_responseType($responseType);
1.585     bisitz   2378:     $request->print(
1.588     bisitz   2379:         '<div class="LC_Box">'
                   2380:        .'<h3 class="LC_hcell">'.&mt('Assign Grades').'</h3>'
1.585     bisitz   2381:     );
1.592     bisitz   2382:     $request->print(&gradeBox_start());
1.375     albertel 2383:     foreach my $part_response_id (@part_response_id) {
                   2384:     	my ($partid,$respid) = @{ $part_response_id };
                   2385: 	my $part_resp = join('_',@{ $part_response_id });
1.322     albertel 2386: 	next if ($seen{$partid} > 0);
1.41      ng       2387: 	$seen{$partid}++;
1.393     albertel 2388: 	next if ($$handgrade{$part_resp} ne 'yes' 
                   2389: 		 && $env{'form.lastSub'} eq 'hdgrade');
1.524     raeburn  2390: 	push(@partlist,$partid);
                   2391: 	push(@gradePartRespid,$partid.'.'.$respid);
1.322     albertel 2392: 	$request->print(&gradeBox($request,$symb,$uname,$udom,$counter,$partid,\%record));
1.41      ng       2393:     }
1.585     bisitz   2394:     $request->print(&gradeBox_end()); # </div>
                   2395:     $request->print('</div>');
1.468     albertel 2396: 
                   2397:     $request->print('<div class="LC_grade_info_links">');
                   2398:     $request->print('</div>');
                   2399: 
1.45      ng       2400:     $result='<input type="hidden" name="partlist'.$counter.
                   2401: 	'" value="'.(join ":",@partlist).'" />'."\n";
1.129     ng       2402:     $result.='<input type="hidden" name="gradePartRespid'.
                   2403: 	'" value="'.(join ":",@gradePartRespid).'" />'."\n" if ($counter == 0);
1.45      ng       2404:     my $ctr = 0;
                   2405:     while ($ctr < scalar(@partlist)) {
                   2406: 	$result.='<input type="hidden" name="partid'.$counter.'_'.$ctr.'" value="'.
                   2407: 	    $partlist[$ctr].'" />'."\n";
                   2408: 	$ctr++;
                   2409:     }
1.468     albertel 2410:     $request->print($result.''."\n");
1.41      ng       2411: 
1.441     www      2412: # Done with printing info for one student
                   2413: 
1.468     albertel 2414:     $request->print('</div>');#LC_grade_show_user
1.441     www      2415: 
                   2416: 
1.41      ng       2417:     # print end of form
                   2418:     if ($counter == $total) {
1.592     bisitz   2419:         my $endform='<br /><hr /><table border="0"><tr><td>'."\n";
1.485     albertel 2420: 	$endform.='<input type="button" value="'.&mt('Save &amp; Next').'" '.
1.589     bisitz   2421: 	    'onclick="javascript:checksubmit(this.form,\'Save & Next\','.
1.417     albertel 2422: 	    $total.','.scalar(@partlist).');" target="_self" /> &nbsp;'."\n";
1.119     ng       2423: 	my $ntstu ='<select name="NTSTU">'.
                   2424: 	    '<option>1</option><option>2</option>'.
                   2425: 	    '<option>3</option><option>5</option>'.
                   2426: 	    '<option>7</option><option>10</option></select>'."\n";
1.257     albertel 2427: 	my $nsel = ($env{'form.NTSTU'} ne '' ? $env{'form.NTSTU'} : '1');
1.401     albertel 2428: 	$ntstu =~ s/<option>$nsel</<option selected="selected">$nsel</;
1.578     raeburn  2429:         $endform.=&mt('[_1]student(s)',$ntstu);
1.485     albertel 2430: 	$endform.='&nbsp;&nbsp;<input type="button" value="'.&mt('Previous').'" '.
1.589     bisitz   2431: 	    'onclick="javascript:checksubmit(this.form,\'Previous\');" target="_self" /> &nbsp;'."\n".
1.485     albertel 2432: 	    '<input type="button" value="'.&mt('Next').'" '.
1.589     bisitz   2433: 	    'onclick="javascript:checksubmit(this.form,\'Next\');" target="_self" /> &nbsp;';
1.592     bisitz   2434:         $endform.='<span class="LC_warning">'.
                   2435:                   &mt('(Next and Previous (student) do not save the scores.)').
                   2436:                   '</span>'."\n" ;
1.349     albertel 2437:         $endform.="<input type='hidden' value='".&get_increment().
1.348     bowersj2 2438:             "' name='increment' />";
1.485     albertel 2439: 	$endform.='</td></tr></table></form>';
1.41      ng       2440: 	$request->print($endform);
                   2441:     }
                   2442:     return '';
1.38      ng       2443: }
                   2444: 
1.464     albertel 2445: sub check_collaborators {
                   2446:     my ($symb,$uname,$udom,$record,$handgrade,$counter) = @_;
                   2447:     my ($result,@col_fullnames);
                   2448:     my ($classlist,undef,$fullname) = &getclasslist('all','0');
                   2449:     foreach my $part (keys(%$handgrade)) {
                   2450: 	my $ncol = &Apache::lonnet::EXT('resource.'.$part.
                   2451: 					'.maxcollaborators',
                   2452: 					$symb,$udom,$uname);
                   2453: 	next if ($ncol <= 0);
                   2454: 	$part =~ s/\_/\./g;
                   2455: 	next if ($record->{'resource.'.$part.'.collaborators'} eq '');
                   2456: 	my (@good_collaborators, @bad_collaborators);
                   2457: 	foreach my $possible_collaborator
1.630     www      2458: 	    (split(/[,;\s]+/,$record->{'resource.'.$part.'.collaborators'})) { 
1.464     albertel 2459: 	    $possible_collaborator =~ s/[\$\^\(\)]//g;
                   2460: 	    next if ($possible_collaborator eq '');
1.631     www      2461: 	    my ($co_name,$co_dom) = split(/:/,$possible_collaborator);
1.464     albertel 2462: 	    $co_dom = $udom if (! defined($co_dom) || $co_dom =~ /^domain$/i);
                   2463: 	    next if ($co_name eq $uname && $co_dom eq $udom);
                   2464: 	    # Doing this grep allows 'fuzzy' specification
                   2465: 	    my @matches = grep(/^\Q$co_name\E:\Q$co_dom\E$/i, 
                   2466: 			       keys(%$classlist));
                   2467: 	    if (! scalar(@matches)) {
                   2468: 		push(@bad_collaborators, $possible_collaborator);
                   2469: 	    } else {
                   2470: 		push(@good_collaborators, @matches);
                   2471: 	    }
                   2472: 	}
                   2473: 	if (scalar(@good_collaborators) != 0) {
1.630     www      2474: 	    $result.='<br />'.&mt('Collaborators:').'<ol>';
1.464     albertel 2475: 	    foreach my $name (@good_collaborators) {
                   2476: 		my ($lastname,$givenn) = split(/,/,$$fullname{$name});
                   2477: 		push(@col_fullnames, $givenn.' '.$lastname);
1.630     www      2478: 		$result.='<li>'.$fullname->{$name}.'</li>';
1.464     albertel 2479: 	    }
1.630     www      2480: 	    $result.='</ol><br />'."\n";
1.466     albertel 2481: 	    my ($part)=split(/\./,$part);
1.464     albertel 2482: 	    $result.='<input type="hidden" name="collaborator'.$counter.
                   2483: 		'" value="'.$part.':'.(join ':',@good_collaborators).'" />'.
                   2484: 		"\n";
                   2485: 	}
                   2486: 	if (scalar(@bad_collaborators) > 0) {
1.466     albertel 2487: 	    $result.='<div class="LC_warning">';
1.464     albertel 2488: 	    $result.=&mt('This student has submitted [quant,_1,invalid collaborator]: [_2]',scalar(@bad_collaborators),join(', ',@bad_collaborators));
                   2489: 	    $result .= '</div>';
                   2490: 	}         
                   2491: 	if (scalar(@bad_collaborators > $ncol)) {
1.466     albertel 2492: 	    $result .= '<div class="LC_warning">';
1.464     albertel 2493: 	    $result .= &mt('This student has submitted too many '.
                   2494: 		'collaborators.  Maximum is [_1].',$ncol);
                   2495: 	    $result .= '</div>';
                   2496: 	}
                   2497:     }
                   2498:     return ($result,$fullname,\@col_fullnames);
                   2499: }
                   2500: 
1.44      ng       2501: #--- Retrieve the last submission for all the parts
1.38      ng       2502: sub get_last_submission {
1.119     ng       2503:     my ($returnhash)=@_;
1.596     raeburn  2504:     my (@string,$timestamp,%lasthidden);
1.119     ng       2505:     if ($$returnhash{'version'}) {
1.46      ng       2506: 	my %lasthash=();
                   2507: 	my ($version);
1.119     ng       2508: 	for ($version=1;$version<=$$returnhash{'version'};$version++) {
1.397     albertel 2509: 	    foreach my $key (sort(split(/\:/,
                   2510: 					$$returnhash{$version.':keys'}))) {
                   2511: 		$lasthash{$key}=$$returnhash{$version.':'.$key};
                   2512: 		$timestamp = 
1.545     raeburn  2513: 		    &Apache::lonlocal::locallocaltime($$returnhash{$version.':timestamp'});
1.46      ng       2514: 	    }
                   2515: 	}
1.640     raeburn  2516:         my (%typeparts,%randombytry);
1.596     raeburn  2517:         my $showsurv = 
                   2518:             &Apache::lonnet::allowed('vas',$env{'request.course.id'});
                   2519:         foreach my $key (sort(keys(%lasthash))) {
                   2520:             if ($key =~ /\.type$/) {
                   2521:                 if (($lasthash{$key} eq 'anonsurvey') || 
1.640     raeburn  2522:                     ($lasthash{$key} eq 'anonsurveycred') ||
                   2523:                     ($lasthash{$key} eq 'randomizetry')) {
1.596     raeburn  2524:                     my ($ign,@parts) = split(/\./,$key);
                   2525:                     pop(@parts);
1.641     raeburn  2526:                     my $id = join('.',@parts);
1.640     raeburn  2527:                     if ($lasthash{$key} eq 'randomizetry') {
                   2528:                         $randombytry{$ign.'.'.$id} = $lasthash{$key};
                   2529:                     } else {
                   2530:                         unless ($showsurv) {
                   2531:                             $typeparts{$ign.'.'.$id} = $lasthash{$key};
                   2532:                         }
1.596     raeburn  2533:                     }
                   2534:                     delete($lasthash{$key});
                   2535:                 }
                   2536:             }
                   2537:         }
                   2538:         my @hidden = keys(%typeparts);
1.640     raeburn  2539:         my @randomize = keys(%randombytry);
1.397     albertel 2540: 	foreach my $key (keys(%lasthash)) {
                   2541: 	    next if ($key !~ /\.submission$/);
1.596     raeburn  2542:             my $hide;
                   2543:             if (@hidden) {
                   2544:                 foreach my $id (@hidden) {
                   2545:                     if ($key =~ /^\Q$id\E/) {
1.640     raeburn  2546:                         $hide = 'anon';
1.596     raeburn  2547:                         last;
                   2548:                     }
                   2549:                 }
                   2550:             }
1.640     raeburn  2551:             unless ($hide) {
                   2552:                 if (@randomize) {
1.732     raeburn  2553:                     foreach my $id (@randomize) {
1.640     raeburn  2554:                         if ($key =~ /^\Q$id\E/) {
                   2555:                             $hide = 'rand';
                   2556:                             last;
                   2557:                         }
                   2558:                     }
                   2559:                 }
                   2560:             }
1.397     albertel 2561: 	    my ($partid,$foo) = split(/submission$/,$key);
1.724     raeburn  2562: 	    my $draft  = $lasthash{$partid.'awarddetail'} eq 'DRAFT' ? 1 : 0;
                   2563:             push(@string, join(':', $key, $hide, $draft, (
1.716     bisitz   2564:                 ref($lasthash{$key}) eq 'ARRAY' ?
                   2565:                     join(',', @{$lasthash{$key}}) : $lasthash{$key}) ));
1.41      ng       2566: 	}
                   2567:     }
1.397     albertel 2568:     if (!@string) {
                   2569: 	$string[0] =
1.539     riegler  2570: 	    '<span class="LC_warning">'.&mt('Nothing submitted - no attempts.').'</span>';
1.397     albertel 2571:     }
                   2572:     return (\@string,\$timestamp);
1.38      ng       2573: }
1.35      ng       2574: 
1.44      ng       2575: #--- High light keywords, with style choosen by user.
1.38      ng       2576: sub keywords_highlight {
1.44      ng       2577:     my $string    = shift;
1.257     albertel 2578:     my $size      = $env{'form.kwsize'} eq '0' ? '' : 'size='.$env{'form.kwsize'};
                   2579:     my $styleon   = $env{'form.kwstyle'} eq ''  ? '' : $env{'form.kwstyle'};
1.41      ng       2580:     (my $styleoff = $styleon) =~ s/\</\<\//;
1.257     albertel 2581:     my @keylist   = split(/[,\s+]/,$env{'form.keywords'});
1.398     albertel 2582:     foreach my $keyword (@keylist) {
                   2583: 	$string =~ s/\b\Q$keyword\E(\b|\.)/<font color\=$env{'form.kwclr'} $size\>$styleon$keyword$styleoff<\/font>/gi;
1.41      ng       2584:     }
                   2585:     return $string;
1.38      ng       2586: }
1.36      ng       2587: 
1.671     raeburn  2588: # For Tasks provide a mechanism to display previous version for one specific student
                   2589: 
                   2590: sub show_previous_task_version {
                   2591:     my ($request,$symb) = @_;
                   2592:     if ($symb eq '') {
1.717     bisitz   2593:         $request->print(
                   2594:             '<span class="LC_error">'.
                   2595:             &mt('Unable to handle ambiguous references.').
                   2596:             '</span>');
1.671     raeburn  2597:         return '';
                   2598:     }
                   2599:     my ($uname,$udom) = ($env{'form.student'},$env{'form.userdom'});
                   2600:     my $usec = &Apache::lonnet::getsection($udom,$uname,$env{'request.course.id'});
                   2601:     if (!&canview($usec)) {
1.712     bisitz   2602:         $request->print(
                   2603:             '<span class="LC_warning">'.
1.713     bisitz   2604:             &mt('Unable to view previous version for requested student.').
1.712     bisitz   2605:             ' '.&mt('([_1] in section [_2] in course id [_3])',
                   2606:                     $uname.':'.$udom,$usec,$env{'request.course.id'}).
                   2607:             '</span>');
1.671     raeburn  2608:         return;
                   2609:     }
                   2610:     my $mode = 'both';
                   2611:     my $isTask = ($symb =~/\.task$/);
                   2612:     if ($isTask) {
                   2613:         if ($env{'form.previousversion'} =~ /^\d+$/) {
                   2614:             if ($env{'form.fullname'} eq '') {
                   2615:                 $env{'form.fullname'} =
                   2616:                     &Apache::loncommon::plainname($uname,$udom,'lastname');
                   2617:             }
                   2618:             my $probtitle=&Apache::lonnet::gettitle($symb);
                   2619:             $request->print("\n\n".
                   2620:                             '<div class="LC_grade_show_user">'.
                   2621:                             '<h2>'.&nameUserString(undef,$env{'form.fullname'},$uname,$udom).
                   2622:                             '</h2>'."\n");
                   2623:             &Apache::lonxml::clear_problem_counter();
                   2624:             $request->print(&show_problem($request,$symb,$uname,$udom,1,1,$mode,
                   2625:                             {'previousversion' => $env{'form.previousversion'} }));
                   2626:             $request->print("\n</div>");
                   2627:         }
                   2628:     }
                   2629:     return;
                   2630: }
                   2631: 
                   2632: sub choose_task_version_form {
                   2633:     my ($symb,$uname,$udom,$nomenu) = @_;
                   2634:     my $isTask = ($symb =~/\.task$/);
                   2635:     my ($current,$version,$result,$js,$displayed,$rowtitle);
                   2636:     if ($isTask) {
                   2637:         my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},
                   2638:                                               $udom,$uname);
                   2639:         if (($record{'resource.0.version'} eq '') ||
                   2640:             ($record{'resource.0.version'} < 2)) {
                   2641:             return ($record{'resource.0.version'},
                   2642:                     $record{'resource.0.version'},$result,$js);
                   2643:         } else {
                   2644:             $current = $record{'resource.0.version'};
                   2645:         }
                   2646:         if ($env{'form.previousversion'}) {
                   2647:             $displayed = $env{'form.previousversion'};
                   2648:             $rowtitle = &mt('Choose another version:')
                   2649:         } else {
                   2650:             $displayed = $current;
                   2651:             $rowtitle = &mt('Show earlier version:');
                   2652:         }
                   2653:         $result = '<div class="LC_left_float">';
                   2654:         my $list;
                   2655:         my $numversions = 0;
                   2656:         for (my $i=1; $i<=$record{'resource.0.version'}; $i++) {
                   2657:             if ($i == $current) {
                   2658:                 if (!$env{'form.previousversion'} || $nomenu) {
                   2659:                     next;
                   2660:                 } else {
                   2661:                     $list .= '<option value="'.$i.'">'.&mt('Current').'</option>'."\n";
                   2662:                     $numversions ++;
                   2663:                 }
                   2664:             } elsif (defined($record{'resource.'.$i.'.0.status'})) {
                   2665:                 unless ($i == $env{'form.previousversion'}) {
                   2666:                     $numversions ++;
                   2667:                 }
                   2668:                 $list .= '<option value="'.$i.'">'.$i.'</option>'."\n";
                   2669:             }
                   2670:         }
                   2671:         if ($numversions) {
                   2672:             $symb = &HTML::Entities::encode($symb,'<>"&');
                   2673:             $result .=
                   2674:                 '<form name="getprev" method="post" action=""'.
                   2675:                 ' onsubmit="return previousVersion('."'$uname','$udom','$symb','$displayed'".');">'.
                   2676:                 &Apache::loncommon::start_data_table().
                   2677:                 &Apache::loncommon::start_data_table_row().
                   2678:                 '<th align="left">'.$rowtitle.'</th>'.
                   2679:                 '<td><select name="version">'.
                   2680:                 '<option>'.&mt('Select').'</option>'.
                   2681:                 $list.
                   2682:                 '</select></td>'.
                   2683:                 &Apache::loncommon::end_data_table_row();
                   2684:             unless ($nomenu) {
                   2685:                 $result .= &Apache::loncommon::start_data_table_row().
                   2686:                 '<th align="left">'.&mt('Open in new window').'</th>'.
                   2687:                 '<td><span class="LC_nobreak">'.
                   2688:                 '<label><input type="radio" name="prevwin" value="1" />'.
                   2689:                 &mt('Yes').'</label>'.
                   2690:                 '<label><input type="radio" name="prevwin" value="0" checked="checked" />'.&mt('No').'</label>'.
                   2691:                 '</span></td>'.
                   2692:                 &Apache::loncommon::end_data_table_row();
                   2693:             }
                   2694:             $result .=
                   2695:                 &Apache::loncommon::start_data_table_row().
                   2696:                 '<th align="left">&nbsp;</th>'.
                   2697:                 '<td>'.
                   2698:                 '<input type="submit" name="prevsub" value="'.&mt('Display').'" />'.
                   2699:                 '</td>'.
                   2700:                 &Apache::loncommon::end_data_table_row().
                   2701:                 &Apache::loncommon::end_data_table().
                   2702:                 '</form>';
                   2703:             $js = &previous_display_javascript($nomenu,$current);
                   2704:         } elsif ($displayed && $nomenu) {
                   2705:             $result .= '<a href="javascript:window.close()">'.&mt('Close window').'</a>';
                   2706:         } else {
                   2707:             $result .= &mt('No previous versions to show for this student');
                   2708:         }
                   2709:         $result .= '</div>';
                   2710:     }
                   2711:     return ($current,$displayed,$result,$js);
                   2712: }
                   2713: 
                   2714: sub previous_display_javascript {
                   2715:     my ($nomenu,$current) = @_;
                   2716:     my $js = <<"JSONE";
                   2717: <script type="text/javascript">
                   2718: // <![CDATA[
                   2719: function previousVersion(uname,udom,symb) {
                   2720:     var current = '$current';
                   2721:     var version = document.getprev.version.options[document.getprev.version.selectedIndex].value;
                   2722:     var prevstr = new RegExp("^\\\\d+\$");
                   2723:     if (!prevstr.test(version)) {
                   2724:         return false;
                   2725:     }
                   2726:     var url = '';
                   2727:     if (version == current) {
                   2728:         url = '/adm/grades?student='+uname+'&userdom='+udom+'&symb='+symb+'&command=submission';
                   2729:     } else {
                   2730:         url = '/adm/grades?student='+uname+'&userdom='+udom+'&symb='+symb+'&command=versionsub&previousversion='+version;
                   2731:     }
                   2732: JSONE
                   2733:     if ($nomenu) {
                   2734:         $js .= <<"JSTWO";
                   2735:     document.location.href = url;
                   2736: JSTWO
                   2737:     } else {
                   2738:         $js .= <<"JSTHREE";
                   2739:     var newwin = 0;
                   2740:     for (var i=0; i<document.getprev.prevwin.length; i++) {
                   2741:         if (document.getprev.prevwin[i].checked == true) {
                   2742:             newwin = document.getprev.prevwin[i].value;
                   2743:         }
                   2744:     }
                   2745:     if (newwin == 1) {
                   2746:         var options = 'height=600,width=800,resizable=yes,scrollbars=yes,location=no,menubar=no,toolbar=no';
                   2747:         url = url+'&inhibitmenu=yes';
                   2748:         if (typeof(previousWin) == 'undefined' || previousWin.closed) {
                   2749:             previousWin = window.open(url,'',options,1);
                   2750:         } else {
                   2751:             previousWin.location.href = url;
                   2752:         }
                   2753:         previousWin.focus();
                   2754:         return false;
                   2755:     } else {
                   2756:         document.location.href = url;
                   2757:         return false;
                   2758:     }
                   2759: JSTHREE
                   2760:     }
                   2761:     $js .= <<"ENDJS";
                   2762:     return false;
                   2763: }
                   2764: // ]]>
                   2765: </script>
                   2766: ENDJS
                   2767: 
                   2768: }
                   2769: 
1.44      ng       2770: #--- Called from submission routine
1.38      ng       2771: sub processHandGrade {
1.608     www      2772:     my ($request,$symb) = @_;
1.324     albertel 2773:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
1.257     albertel 2774:     my $button = $env{'form.gradeOpt'};
                   2775:     my $ngrade = $env{'form.NCT'};
                   2776:     my $ntstu  = $env{'form.NTSTU'};
1.301     albertel 2777:     my $cdom   = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   2778:     my $cnum   = $env{'course.'.$env{'request.course.id'}.'.num'};
                   2779: 
1.44      ng       2780:     if ($button eq 'Save & Next') {
                   2781: 	my $ctr = 0;
                   2782: 	while ($ctr < $ngrade) {
1.257     albertel 2783: 	    my ($uname,$udom) = split(/:/,$env{'form.unamedom'.$ctr});
1.726     raeburn  2784: 	    my ($errorflag,$pts,$wgt,$numhidden) = 
                   2785:                 &saveHandGrade($request,$symb,$uname,$udom,$ctr);
1.71      ng       2786: 	    if ($errorflag eq 'no_score') {
                   2787: 		$ctr++;
                   2788: 		next;
                   2789: 	    }
1.104     albertel 2790: 	    if ($errorflag eq 'not_allowed') {
1.721     bisitz   2791: 		$request->print(
                   2792:                     '<span class="LC_error">'
                   2793:                    .&mt('Not allowed to modify grades for [_1]',"$uname:$udom")
                   2794:                    .'</span>');
1.104     albertel 2795: 		$ctr++;
                   2796: 		next;
                   2797: 	    }
1.726     raeburn  2798:             if ($numhidden) {
                   2799:                 $request->print(
                   2800:                     '<span class="LC_info">'
                   2801:                    .&mt('For [_1]: [quant,_2,transaction] hidden',"$uname:$udom",$numhidden)
                   2802:                    .'</span><br />');
                   2803:             }
1.257     albertel 2804: 	    my $includemsg = $env{'form.includemsg'.$ctr};
1.44      ng       2805: 	    my ($subject,$message,$msgstatus) = ('','','');
1.418     albertel 2806: 	    my $restitle = &Apache::lonnet::gettitle($symb);
                   2807:             my ($feedurl,$showsymb) =
                   2808: 		&get_feedurl_and_symb($symb,$uname,$udom);
                   2809: 	    my $messagetail;
1.62      albertel 2810: 	    if ($includemsg =~ /savemsg|newmsg\Q$ctr\E/) {
1.298     www      2811: 		$subject = $env{'form.msgsub'} if ($includemsg =~ /msgsub/);
1.295     www      2812: 		unless ($subject=~/\w/) { $subject=&mt('Grading Feedback'); }
1.386     raeburn  2813: 		$subject.=' ['.$restitle.']';
1.44      ng       2814: 		my (@msgnum) = split(/,/,$includemsg);
                   2815: 		foreach (@msgnum) {
1.257     albertel 2816: 		    $message.=$env{'form.'.$_} if ($_ =~ /savemsg|newmsg/ && $_ ne '');
1.44      ng       2817: 		}
1.80      ng       2818: 		$message =&Apache::lonfeedback::clear_out_html($message);
1.298     www      2819: 		if ($env{'form.withgrades'.$ctr}) {
                   2820: 		    $message.="\n\nPoint".($pts > 1 ? 's':'').' awarded = '.$pts.' out of '.$wgt;
1.386     raeburn  2821: 		    $messagetail = " for <a href=\"".
1.605     www      2822: 		                   $feedurl."?symb=$showsymb\">$restitle</a>";
1.386     raeburn  2823: 		}
                   2824: 		$msgstatus = 
                   2825:                     &Apache::lonmsg::user_normal_msg($uname,$udom,$subject,
                   2826: 						     $message.$messagetail,
1.418     albertel 2827:                                                      undef,$feedurl,undef,
1.386     raeburn  2828:                                                      undef,undef,$showsymb,
                   2829:                                                      $restitle);
1.574     bisitz   2830: 		$request->print('<br />'.&mt('Sending message to [_1]',$uname.':'.$udom).': '.
1.652     raeburn  2831: 				$msgstatus.'<br />');
1.44      ng       2832: 	    }
1.257     albertel 2833: 	    if ($env{'form.collaborator'.$ctr}) {
1.155     albertel 2834: 		my @collabstrs=&Apache::loncommon::get_env_multiple("form.collaborator$ctr");
1.150     albertel 2835: 		foreach my $collabstr (@collabstrs) {
                   2836: 		    my ($part,@collaborators) = split(/:/,$collabstr);
1.310     banghart 2837: 		    foreach my $collaborator (@collaborators) {
1.150     albertel 2838: 			my ($errorflag,$pts,$wgt) = 
1.324     albertel 2839: 			    &saveHandGrade($request,$symb,$collaborator,$udom,$ctr,
1.257     albertel 2840: 					   $env{'form.unamedom'.$ctr},$part);
1.150     albertel 2841: 			if ($errorflag eq 'not_allowed') {
1.362     albertel 2842: 			    $request->print("<span class=\"LC_error\">".&mt('Not allowed to modify grades for [_1]',"$collaborator:$udom")."</span>");
1.150     albertel 2843: 			    next;
1.418     albertel 2844: 			} elsif ($message ne '') {
                   2845: 			    my ($baseurl,$showsymb) = 
                   2846: 				&get_feedurl_and_symb($symb,$collaborator,
                   2847: 						      $udom);
                   2848: 			    if ($env{'form.withgrades'.$ctr}) {
                   2849: 				$messagetail = " for <a href=\"".
1.605     www      2850:                                     $baseurl."?symb=$showsymb\">$restitle</a>";
1.150     albertel 2851: 			    }
1.418     albertel 2852: 			    $msgstatus = 
                   2853: 				&Apache::lonmsg::user_normal_msg($collaborator,$udom,$subject,$message.$messagetail,undef,$baseurl,undef,undef,undef,$showsymb,$restitle);
1.104     albertel 2854: 			}
1.44      ng       2855: 		    }
                   2856: 		}
                   2857: 	    }
                   2858: 	    $ctr++;
                   2859: 	}
                   2860:     }
                   2861: 
1.624     www      2862: #    if ($env{'form.handgrade'} eq 'yes') {
                   2863:     if (1) {
1.119     ng       2864: 	# Keywords sorted in alphabatical order
1.257     albertel 2865: 	my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
1.119     ng       2866: 	my %keyhash = ();
1.257     albertel 2867: 	$env{'form.keywords'}           =~ s/,\s{0,}|\s+/ /g;
                   2868: 	$env{'form.keywords'}           =~ s/^\s+|\s+$//;
                   2869: 	my (@keywords) = sort(split(/\s+/,$env{'form.keywords'}));
                   2870: 	$env{'form.keywords'} = join(' ',@keywords);
                   2871: 	$keyhash{$symb.'_keywords'}     = $env{'form.keywords'};
                   2872: 	$keyhash{$symb.'_subject'}      = $env{'form.msgsub'};
                   2873: 	$keyhash{$loginuser.'_kwclr'}   = $env{'form.kwclr'};
                   2874: 	$keyhash{$loginuser.'_kwsize'}  = $env{'form.kwsize'};
                   2875: 	$keyhash{$loginuser.'_kwstyle'} = $env{'form.kwstyle'};
1.119     ng       2876: 
                   2877: 	# message center - Order of message gets changed. Blank line is eliminated.
1.257     albertel 2878: 	# New messages are saved in env for the next student.
1.119     ng       2879: 	# All messages are saved in nohist_handgrade.db
                   2880: 	my ($ctr,$idx) = (1,1);
1.257     albertel 2881: 	while ($ctr <= $env{'form.savemsgN'}) {
                   2882: 	    if ($env{'form.savemsg'.$ctr} ne '') {
                   2883: 		$keyhash{$symb.'_savemsg'.$idx} = $env{'form.savemsg'.$ctr};
1.119     ng       2884: 		$idx++;
                   2885: 	    }
                   2886: 	    $ctr++;
1.41      ng       2887: 	}
1.119     ng       2888: 	$ctr = 0;
                   2889: 	while ($ctr < $ngrade) {
1.257     albertel 2890: 	    if ($env{'form.newmsg'.$ctr} ne '') {
                   2891: 		$keyhash{$symb.'_savemsg'.$idx} = $env{'form.newmsg'.$ctr};
                   2892: 		$env{'form.savemsg'.$idx} = $env{'form.newmsg'.$ctr};
1.119     ng       2893: 		$idx++;
                   2894: 	    }
                   2895: 	    $ctr++;
1.41      ng       2896: 	}
1.257     albertel 2897: 	$env{'form.savemsgN'} = --$idx;
                   2898: 	$keyhash{$symb.'_savemsgN'} = $env{'form.savemsgN'};
1.119     ng       2899: 	my $putresult = &Apache::lonnet::put
1.301     albertel 2900: 	    ('nohist_handgrade',\%keyhash,$cdom,$cnum);
1.41      ng       2901:     }
1.44      ng       2902:     # Called by Save & Refresh from Highlight Attribute Window
1.257     albertel 2903:     my (undef,undef,$fullname) = &getclasslist($env{'form.section'},'1');
                   2904:     if ($env{'form.refresh'} eq 'on') {
1.86      ng       2905: 	my ($ctr,$total) = (0,0);
                   2906: 	while ($ctr < $ngrade) {
1.257     albertel 2907: 	    $total++ if  $env{'form.unamedom'.$ctr} ne '';
1.86      ng       2908: 	    $ctr++;
                   2909: 	}
1.257     albertel 2910: 	$env{'form.NTSTU'}=$ngrade;
1.86      ng       2911: 	$ctr = 0;
                   2912: 	while ($ctr < $total) {
1.257     albertel 2913: 	    my $processUser = $env{'form.unamedom'.$ctr};
                   2914: 	    ($env{'form.student'},$env{'form.userdom'}) = split(/:/,$processUser);
                   2915: 	    $env{'form.fullname'} = $$fullname{$processUser};
1.625     www      2916: 	    &submission($request,$ctr,$total-1,$symb);
1.41      ng       2917: 	    $ctr++;
                   2918: 	}
                   2919: 	return '';
                   2920:     }
1.36      ng       2921: 
1.44      ng       2922:     # Get the next/previous one or group of students
1.257     albertel 2923:     my $firststu = $env{'form.unamedom0'};
                   2924:     my $laststu = $env{'form.unamedom'.($ngrade-1)};
1.119     ng       2925:     my $ctr = 2;
1.41      ng       2926:     while ($laststu eq '') {
1.257     albertel 2927: 	$laststu  = $env{'form.unamedom'.($ngrade-$ctr)};
1.41      ng       2928: 	$ctr++;
                   2929: 	$laststu = $firststu if ($ctr > $ngrade);
                   2930:     }
1.44      ng       2931: 
1.41      ng       2932:     my (@parsedlist,@nextlist);
                   2933:     my ($nextflg) = 0;
1.524     raeburn  2934:     foreach my $item (sort 
1.294     albertel 2935: 	     {
                   2936: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                   2937: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                   2938: 		 }
                   2939: 		 return $a cmp $b;
                   2940: 	     } (keys(%$fullname))) {
1.605     www      2941: # FIXME: this is fishy, looks like the button label
1.41      ng       2942: 	if ($nextflg == 1 && $button =~ /Next$/) {
1.524     raeburn  2943: 	    push(@parsedlist,$item);
1.41      ng       2944: 	}
1.524     raeburn  2945: 	$nextflg = 1 if ($item eq $laststu);
1.41      ng       2946: 	if ($button eq 'Previous') {
1.524     raeburn  2947: 	    last if ($item eq $firststu);
                   2948: 	    push(@parsedlist,$item);
1.41      ng       2949: 	}
                   2950:     }
                   2951:     $ctr = 0;
1.605     www      2952: # FIXME: this is fishy, looks like the button label
1.41      ng       2953:     @parsedlist = reverse @parsedlist if ($button eq 'Previous');
1.582     raeburn  2954:     my $res_error;
                   2955:     my ($partlist) = &response_type($symb,\$res_error);
                   2956:     if ($res_error) {
                   2957:         $request->print(&navmap_errormsg());
                   2958:         return;
                   2959:     }
1.41      ng       2960:     foreach my $student (@parsedlist) {
1.257     albertel 2961: 	my $submitonly=$env{'form.submitonly'};
1.41      ng       2962: 	my ($uname,$udom) = split(/:/,$student);
1.301     albertel 2963: 	
                   2964: 	if ($submitonly eq 'queued') {
                   2965: 	    my %queue_status = 
                   2966: 		&Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
                   2967: 							$udom,$uname);
                   2968: 	    next if (!defined($queue_status{'gradingqueue'}));
                   2969: 	}
                   2970: 
1.156     albertel 2971: 	if ($submitonly =~ /^(yes|graded|incorrect)$/) {
1.257     albertel 2972: #	    my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
1.324     albertel 2973: 	    my %status=&student_gradeStatus($symb,$udom,$uname,$partlist);
1.145     albertel 2974: 	    my $submitted = 0;
1.248     albertel 2975: 	    my $ungraded = 0;
                   2976: 	    my $incorrect = 0;
1.524     raeburn  2977: 	    foreach my $item (keys(%status)) {
                   2978: 		$submitted = 1 if ($status{$item} ne 'nothing');
                   2979: 		$ungraded = 1 if ($status{$item} =~ /^ungraded/);
                   2980: 		$incorrect = 1 if ($status{$item} =~ /^incorrect/);
                   2981: 		my ($foo,$partid,$foo1) = split(/\./,$item);
1.145     albertel 2982: 		if ($status{'resource.'.$partid.'.submitted_by'} ne '') {
                   2983: 		    $submitted = 0;
                   2984: 		}
1.41      ng       2985: 	    }
1.156     albertel 2986: 	    next if (!$submitted && ($submitonly eq 'yes' ||
                   2987: 				     $submitonly eq 'incorrect' ||
                   2988: 				     $submitonly eq 'graded'));
1.248     albertel 2989: 	    next if (!$ungraded && ($submitonly eq 'graded'));
                   2990: 	    next if (!$incorrect && $submitonly eq 'incorrect');
1.41      ng       2991: 	}
1.524     raeburn  2992: 	push(@nextlist,$student) if ($ctr < $ntstu);
1.129     ng       2993: 	last if ($ctr == $ntstu);
1.41      ng       2994: 	$ctr++;
                   2995:     }
1.36      ng       2996: 
1.41      ng       2997:     $ctr = 0;
                   2998:     my $total = scalar(@nextlist)-1;
1.39      ng       2999: 
1.524     raeburn  3000:     foreach (sort(@nextlist)) {
1.41      ng       3001: 	my ($uname,$udom,$submitter) = split(/:/);
1.257     albertel 3002: 	$env{'form.student'}  = $uname;
                   3003: 	$env{'form.userdom'}  = $udom;
                   3004: 	$env{'form.fullname'} = $$fullname{$_};
1.625     www      3005: 	&submission($request,$ctr,$total,$symb);
1.41      ng       3006: 	$ctr++;
                   3007:     }
                   3008:     if ($total < 0) {
1.653     raeburn  3009: 	my $the_end.='<p>'.&mt('[_1]Message:[_2] No more students for this section or class.','<b>','</b>').'</p>'."\n";
1.41      ng       3010: 	$request->print($the_end);
                   3011:     }
                   3012:     return '';
1.38      ng       3013: }
1.36      ng       3014: 
1.44      ng       3015: #---- Save the score and award for each student, if changed
1.38      ng       3016: sub saveHandGrade {
1.324     albertel 3017:     my ($request,$symb,$stuname,$domain,$newflg,$submitter,$part) = @_;
1.342     banghart 3018:     my @version_parts;
1.104     albertel 3019:     my $usec = &Apache::lonnet::getsection($domain,$stuname,
1.257     albertel 3020: 					   $env{'request.course.id'});
1.104     albertel 3021:     if (!&canmodify($usec)) { return('not_allowed'); }
1.337     banghart 3022:     my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$domain,$stuname);
1.251     banghart 3023:     my @parts_graded;
1.77      ng       3024:     my %newrecord  = ();
1.726     raeburn  3025:     my ($pts,$wgt,$totchg) = ('','',0);
1.269     raeburn  3026:     my %aggregate = ();
                   3027:     my $aggregateflag = 0;
1.726     raeburn  3028:     if ($env{'form.HIDE'.$newflg}) {
1.727     raeburn  3029:         my ($version,$parts) = split(/:/,$env{'form.HIDE'.$newflg},2);
1.728     raeburn  3030:         my $numchgs = &makehidden($version,$parts,\%record,$symb,$domain,$stuname,1);
1.726     raeburn  3031:         $totchg += $numchgs;
                   3032:     }
1.301     albertel 3033:     my @parts = split(/:/,$env{'form.partlist'.$newflg});
                   3034:     foreach my $new_part (@parts) {
1.337     banghart 3035: 	#collaborator ($submi may vary for different parts
1.259     banghart 3036: 	if ($submitter && $new_part ne $part) { next; }
                   3037: 	my $dropMenu = $env{'form.GD_SEL'.$newflg.'_'.$new_part};
1.125     ng       3038: 	if ($dropMenu eq 'excused') {
1.259     banghart 3039: 	    if ($record{'resource.'.$new_part.'.solved'} ne 'excused') {
                   3040: 		$newrecord{'resource.'.$new_part.'.solved'} = 'excused';
                   3041: 		if (exists($record{'resource.'.$new_part.'.awarded'})) {
                   3042: 		    $newrecord{'resource.'.$new_part.'.awarded'} = '';
1.58      albertel 3043: 		}
1.364     banghart 3044: 	        $newrecord{'resource.'.$new_part.'.regrader'}="$env{'user.name'}:$env{'user.domain'}";
1.58      albertel 3045: 	    }
1.125     ng       3046: 	} elsif ($dropMenu eq 'reset status'
1.259     banghart 3047: 		 && exists($record{'resource.'.$new_part.'.solved'})) { #don't bother if no old records -> no attempts
1.524     raeburn  3048: 	    foreach my $key (keys(%record)) {
1.259     banghart 3049: 		if ($key=~/^resource\.\Q$new_part\E\./) { $newrecord{$key} = ''; }
1.197     albertel 3050: 	    }
1.259     banghart 3051: 	    $newrecord{'resource.'.$new_part.'.regrader'}=
1.257     albertel 3052: 		"$env{'user.name'}:$env{'user.domain'}";
1.270     albertel 3053:             my $totaltries = $record{'resource.'.$part.'.tries'};
                   3054: 
                   3055:             my %last_resets = &get_last_resets($symb,$env{'request.course.id'},
                   3056: 					       [$new_part]);
                   3057:             my $aggtries =$totaltries;
1.269     raeburn  3058:             if ($last_resets{$new_part}) {
1.270     albertel 3059:                 $aggtries = &get_num_tries(\%record,$last_resets{$new_part},
                   3060: 					   $new_part);
1.269     raeburn  3061:             }
1.270     albertel 3062: 
                   3063:             my $solvedstatus = $record{'resource.'.$new_part.'.solved'};
1.269     raeburn  3064:             if ($aggtries > 0) {
1.327     albertel 3065:                 &decrement_aggs($symb,$new_part,\%aggregate,$aggtries,$totaltries,$solvedstatus);
1.269     raeburn  3066:                 $aggregateflag = 1;
                   3067:             }
1.125     ng       3068: 	} elsif ($dropMenu eq '') {
1.259     banghart 3069: 	    $pts = ($env{'form.GD_BOX'.$newflg.'_'.$new_part} ne '' ? 
                   3070: 		    $env{'form.GD_BOX'.$newflg.'_'.$new_part} : 
                   3071: 		    $env{'form.RADVAL'.$newflg.'_'.$new_part});
                   3072: 	    if ($pts eq '' && $env{'form.GD_SEL'.$newflg.'_'.$new_part} eq '') {
1.153     albertel 3073: 		next;
                   3074: 	    }
1.259     banghart 3075: 	    $wgt = $env{'form.WGT'.$newflg.'_'.$new_part} eq '' ? 1 : 
                   3076: 		$env{'form.WGT'.$newflg.'_'.$new_part};
1.41      ng       3077: 	    my $partial= $pts/$wgt;
1.259     banghart 3078: 	    if ($partial eq $record{'resource.'.$new_part.'.awarded'}) {
1.153     albertel 3079: 		#do not update score for part if not changed.
1.346     banghart 3080:                 &handback_files($request,$symb,$stuname,$domain,$newflg,$new_part,\%newrecord);
1.153     albertel 3081: 		next;
1.251     banghart 3082: 	    } else {
1.524     raeburn  3083: 	        push(@parts_graded,$new_part);
1.153     albertel 3084: 	    }
1.259     banghart 3085: 	    if ($record{'resource.'.$new_part.'.awarded'} ne $partial) {
                   3086: 		$newrecord{'resource.'.$new_part.'.awarded'}  = $partial;
1.153     albertel 3087: 	    }
1.259     banghart 3088: 	    my $reckey = 'resource.'.$new_part.'.solved';
1.41      ng       3089: 	    if ($partial == 0) {
1.153     albertel 3090: 		if ($record{$reckey} ne 'incorrect_by_override') {
                   3091: 		    $newrecord{$reckey} = 'incorrect_by_override';
                   3092: 		}
1.41      ng       3093: 	    } else {
1.153     albertel 3094: 		if ($record{$reckey} ne 'correct_by_override') {
                   3095: 		    $newrecord{$reckey} = 'correct_by_override';
                   3096: 		}
                   3097: 	    }	    
                   3098: 	    if ($submitter && 
1.259     banghart 3099: 		($record{'resource.'.$new_part.'.submitted_by'} ne $submitter)) {
                   3100: 		$newrecord{'resource.'.$new_part.'.submitted_by'} = $submitter;
1.41      ng       3101: 	    }
1.259     banghart 3102: 	    $newrecord{'resource.'.$new_part.'.regrader'}=
1.257     albertel 3103: 		"$env{'user.name'}:$env{'user.domain'}";
1.41      ng       3104: 	}
1.259     banghart 3105: 	# unless problem has been graded, set flag to version the submitted files
1.305     banghart 3106: 	unless ($record{'resource.'.$new_part.'.solved'} =~ /^correct_/  || 
                   3107: 	        $record{'resource.'.$new_part.'.solved'} eq 'incorrect_by_override' ||
                   3108: 	        $dropMenu eq 'reset status')
                   3109: 	   {
1.524     raeburn  3110: 	    push(@version_parts,$new_part);
1.259     banghart 3111: 	}
1.41      ng       3112:     }
1.301     albertel 3113:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   3114:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   3115: 
1.344     albertel 3116:     if (%newrecord) {
                   3117:         if (@version_parts) {
1.364     banghart 3118:             my @changed_keys = &version_portfiles(\%record, \@parts_graded, 
                   3119:                                 $env{'request.course.id'}, $symb, $domain, $stuname, \@version_parts);
1.344     albertel 3120: 	    @newrecord{@changed_keys} = @record{@changed_keys};
1.367     albertel 3121: 	    foreach my $new_part (@version_parts) {
                   3122: 		&handback_files($request,$symb,$stuname,$domain,$newflg,
                   3123: 				$new_part,\%newrecord);
                   3124: 	    }
1.259     banghart 3125:         }
1.44      ng       3126: 	&Apache::lonnet::cstore(\%newrecord,$symb,
1.257     albertel 3127: 				$env{'request.course.id'},$domain,$stuname);
1.380     albertel 3128: 	&check_and_remove_from_queue(\@parts,\%record,\%newrecord,$symb,
                   3129: 				     $cdom,$cnum,$domain,$stuname);
1.41      ng       3130:     }
1.269     raeburn  3131:     if ($aggregateflag) {
                   3132:         &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
1.301     albertel 3133: 			      $cdom,$cnum);
1.269     raeburn  3134:     }
1.726     raeburn  3135:     return ('',$pts,$wgt,$totchg);
                   3136: }
                   3137: 
                   3138: sub makehidden {
1.728     raeburn  3139:     my ($version,$parts,$record,$symb,$domain,$stuname,$tolog) = @_;
1.726     raeburn  3140:     return unless (ref($record) eq 'HASH');
                   3141:     my %modified;
                   3142:     my $numchanged = 0;
                   3143:     if (exists($record->{$version.':keys'})) {
                   3144:         my $partsregexp = $parts;
                   3145:         $partsregexp =~ s/,/|/g;
                   3146:         foreach my $key (split(/\:/,$record->{$version.':keys'})) {
                   3147:             if ($key =~ /^resource\.(?:$partsregexp)\.([^\.]+)$/) {
                   3148:                  my $item = $1;
                   3149:                  unless (($item eq 'solved') || ($item =~ /^award(|msg|ed)$/)) {
                   3150:                      $modified{$key} = $record->{$version.':'.$key};
                   3151:                  }
                   3152:             } elsif ($key =~ m{^(resource\.(?:$partsregexp)\.[^\.]+\.)(.+)$}) {
                   3153:                 $modified{$1.'hidden'.$2} = $record->{$version.':'.$key};
                   3154:             } elsif ($key =~ /^(ip|timestamp|host)$/) {
                   3155:                 $modified{$key} = $record->{$version.':'.$key};
                   3156:             }
                   3157:         }
                   3158:         if (keys(%modified)) {
                   3159:             if (&Apache::lonnet::putstore($env{'request.course.id'},$symb,$version,\%modified,
1.728     raeburn  3160:                                           $domain,$stuname,$tolog) eq 'ok') {
1.726     raeburn  3161:                 $numchanged ++;
                   3162:             }
                   3163:         }
                   3164:     }
                   3165:     return $numchanged;
1.36      ng       3166: }
1.322     albertel 3167: 
1.380     albertel 3168: sub check_and_remove_from_queue {
                   3169:     my ($parts,$record,$newrecord,$symb,$cdom,$cnum,$domain,$stuname) = @_;
                   3170:     my @ungraded_parts;
                   3171:     foreach my $part (@{$parts}) {
                   3172: 	if (    $record->{   'resource.'.$part.'.awarded'} eq ''
                   3173: 	     && $record->{   'resource.'.$part.'.solved' } ne 'excused'
                   3174: 	     && $newrecord->{'resource.'.$part.'.awarded'} eq ''
                   3175: 	     && $newrecord->{'resource.'.$part.'.solved' } ne 'excused'
                   3176: 		) {
                   3177: 	    push(@ungraded_parts, $part);
                   3178: 	}
                   3179:     }
                   3180:     if ( !@ungraded_parts ) {
                   3181: 	&Apache::bridgetask::remove_from_queue('gradingqueue',$symb,$cdom,
                   3182: 					       $cnum,$domain,$stuname);
                   3183:     }
                   3184: }
                   3185: 
1.337     banghart 3186: sub handback_files {
                   3187:     my ($request,$symb,$stuname,$domain,$newflg,$new_part,$newrecord) = @_;
1.517     raeburn  3188:     my $portfolio_root = '/userfiles/portfolio';
1.582     raeburn  3189:     my $res_error;
                   3190:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
                   3191:     if ($res_error) {
                   3192:         $request->print('<br />'.&navmap_errormsg().'<br />');
                   3193:         return;
                   3194:     }
1.654     raeburn  3195:     my @handedback;
                   3196:     my $file_msg;
1.375     albertel 3197:     my @part_response_id = &flatten_responseType($responseType);
                   3198:     foreach my $part_response_id (@part_response_id) {
                   3199:     	my ($part_id,$resp_id) = @{ $part_response_id };
                   3200: 	my $part_resp = join('_',@{ $part_response_id });
1.654     raeburn  3201:         if (($env{'form.'.$newflg.'_'.$part_resp.'_countreturndoc'} =~ /^\d+$/) & ($new_part eq $part_id)) {
                   3202:             for (my $counter=1; $counter<=$env{'form.'.$newflg.'_'.$part_resp.'_countreturndoc'}; $counter++) {
                   3203:                 # if multiple files are uploaded names will be 'returndoc2','returndoc3' 
                   3204:                 if ($env{'form.'.$newflg.'_'.$part_resp.'_returndoc'.$counter}) {
                   3205:                     my $fname=$env{'form.'.$newflg.'_'.$part_resp.'_returndoc'.$counter.'.filename'};
1.338     banghart 3206:                     my ($directory,$answer_file) = 
1.654     raeburn  3207:                         ($env{'form.'.$newflg.'_'.$part_resp.'_origdoc'.$counter} =~ /^(.*?)([^\/]*)$/);
1.338     banghart 3208:                     my ($answer_name,$answer_ver,$answer_ext) =
1.729     raeburn  3209: 		        &Apache::lonnet::file_name_version_ext($answer_file);
1.355     banghart 3210: 		    my ($portfolio_path) = ($directory =~ /^.+$stuname\/portfolio(.*)/);
1.517     raeburn  3211:                     my $getpropath = 1;
1.662     raeburn  3212:                     my ($dir_list,$listerror) = 
                   3213:                         &Apache::lonnet::dirlist($portfolio_root.$portfolio_path,
                   3214:                                                  $domain,$stuname,$getpropath);
1.729     raeburn  3215: 		    my $version = &Apache::lonnet::get_next_version($answer_name,$answer_ext,$dir_list);
1.686     bisitz   3216:                     # fix filename
1.355     banghart 3217:                     my ($save_file_name) = (($directory.$answer_name.".$version.".$answer_ext) =~ /^.+\/${stuname}\/(.*)/);
                   3218:                     my $result=&Apache::lonnet::finishuserfileupload($stuname,$domain,
1.654     raeburn  3219:             	                                $newflg.'_'.$part_resp.'_returndoc'.$counter,
1.355     banghart 3220:             	                                $save_file_name);
1.337     banghart 3221:                     if ($result !~ m|^/uploaded/|) {
1.536     raeburn  3222:                         $request->print('<br /><span class="LC_error">'.
                   3223:                             &mt('An error occurred ([_1]) while trying to upload [_2].',
1.654     raeburn  3224:                                 $result,$newflg.'_'.$part_resp.'_returndoc'.$counter).
1.536     raeburn  3225:                                         '</span>');
1.356     banghart 3226:                     } else {
1.360     banghart 3227:                         # mark the file as read only
1.654     raeburn  3228:                         push(@handedback,$save_file_name);
1.367     albertel 3229: 			if (exists($$newrecord{"resource.$new_part.$resp_id.handback"})) {
                   3230: 			    $$newrecord{"resource.$new_part.$resp_id.handback"}.=',';
                   3231: 			}
                   3232:                         $$newrecord{"resource.$new_part.$resp_id.handback"} .= $save_file_name;
1.654     raeburn  3233: 			$file_msg.= '<span class="LC_filename"><a href="/uploaded/'."$domain/$stuname/".$save_file_name.'">'.$save_file_name."</a></span> <br />";
1.337     banghart 3234:                     }
1.686     bisitz   3235:                     $request->print('<br />'.&mt('[_1] will be the uploaded filename [_2]','<span class="LC_info">'.$fname.'</span>','<span class="LC_filename">'.$env{'form.'.$newflg.'_'.$part_resp.'_origdoc'.$counter}.'</span>'));
1.337     banghart 3236:                 }
                   3237:             }
                   3238:         }
1.654     raeburn  3239:     }
                   3240:     if (@handedback > 0) {
                   3241:         $request->print('<br />');
                   3242:         my @what = ($symb,$env{'request.course.id'},'handback');
                   3243:         &Apache::lonnet::mark_as_readonly($domain,$stuname,\@handedback,\@what);
                   3244:         my $user_lh = &Apache::loncommon::user_lang($stuname,$domain,$env{'request.course.id'});    
                   3245:         my ($subject,$message);
                   3246:         if (scalar(@handedback) == 1) {
                   3247:             $subject = &mt_user($user_lh,'File Handed Back by Instructor');
                   3248:             $message = &mt_user($user_lh,'A file has been returned that was originally submitted in response to: ');
                   3249:         } else {
                   3250:             $subject = &mt_user($user_lh,'Files Handed Back by Instructor');
                   3251:             $message = &mt_user($user_lh,'Files have been returned that were originally submitted in response to: ');
                   3252:         }
                   3253:         $message .= "<p><strong>".&Apache::lonnet::gettitle($symb)." </strong></p>";
                   3254:         $message .= &mt_user($user_lh,'The returned file(s) are named: [_1]',"<br />$file_msg <br />").
                   3255:                     &mt_user($user_lh,'The file(s) can be found in your [_1]portfolio[_2].','<a href="/adm/portfolio">','</a>');
                   3256:         my ($feedurl,$showsymb) =
                   3257:             &get_feedurl_and_symb($symb,$domain,$stuname);
                   3258:         my $restitle = &Apache::lonnet::gettitle($symb);
                   3259:         $subject .= ' '.&mt_user($user_lh,'(File Returned)').' ['.$restitle.']';
                   3260:         my $msgstatus =
                   3261:              &Apache::lonmsg::user_normal_msg($stuname,$domain,$subject,
                   3262:                  $message,undef,$feedurl,undef,undef,undef,$showsymb,
                   3263:                  $restitle);
                   3264:         if ($msgstatus) {
                   3265:             $request->print(&mt('Notification message status: [_1]','<span class="LC_info">'.$msgstatus.'</span>').'<br />');
                   3266:         }
                   3267:     }
1.338     banghart 3268:     return;
1.337     banghart 3269: }
                   3270: 
1.418     albertel 3271: sub get_feedurl_and_symb {
                   3272:     my ($symb,$uname,$udom) = @_;
                   3273:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
                   3274:     $url = &Apache::lonnet::clutter($url);
                   3275:     my $encrypturl=&Apache::lonnet::EXT('resource.0.encrypturl',
                   3276: 					$symb,$udom,$uname);
                   3277:     if ($encrypturl =~ /^yes$/i) {
                   3278: 	&Apache::lonenc::encrypted(\$url,1);
                   3279: 	&Apache::lonenc::encrypted(\$symb,1);
                   3280:     }
                   3281:     return ($url,$symb);
                   3282: }
                   3283: 
1.313     banghart 3284: sub get_submitted_files {
                   3285:     my ($udom,$uname,$partid,$respid,$record) = @_;
                   3286:     my @files;
                   3287:     if ($$record{"resource.$partid.$respid.portfiles"}) {
                   3288:         my $file_url = '/uploaded/'.$udom.'/'.$uname.'/portfolio';
                   3289:         foreach my $file (split(',',$$record{"resource.$partid.$respid.portfiles"})) {
                   3290:     	    push(@files,$file_url.$file);
                   3291:         }
                   3292:     }
                   3293:     if ($$record{"resource.$partid.$respid.uploadedurl"}) {
                   3294:         push(@files,$$record{"resource.$partid.$respid.uploadedurl"});
                   3295:     }
                   3296:     return (\@files);
                   3297: }
1.322     albertel 3298: 
1.269     raeburn  3299: # ----------- Provides number of tries since last reset.
                   3300: sub get_num_tries {
                   3301:     my ($record,$last_reset,$part) = @_;
                   3302:     my $timestamp = '';
                   3303:     my $num_tries = 0;
                   3304:     if ($$record{'version'}) {
                   3305:         for (my $version=$$record{'version'};$version>=1;$version--) {
                   3306:             if (exists($$record{$version.':resource.'.$part.'.solved'})) {
                   3307:                 $timestamp = $$record{$version.':timestamp'};
                   3308:                 if ($timestamp > $last_reset) {
                   3309:                     $num_tries ++;
                   3310:                 } else {
                   3311:                     last;
                   3312:                 }
                   3313:             }
                   3314:         }
                   3315:     }
                   3316:     return $num_tries;
                   3317: }
                   3318: 
                   3319: # ----------- Determine decrements required in aggregate totals 
                   3320: sub decrement_aggs {
                   3321:     my ($symb,$part,$aggregate,$aggtries,$totaltries,$solvedstatus) = @_;
                   3322:     my %decrement = (
                   3323:                         attempts => 0,
                   3324:                         users => 0,
                   3325:                         correct => 0
                   3326:                     );
                   3327:     $decrement{'attempts'} = $aggtries;
                   3328:     if ($solvedstatus =~ /^correct/) {
                   3329:         $decrement{'correct'} = 1;
                   3330:     }
                   3331:     if ($aggtries == $totaltries) {
                   3332:         $decrement{'users'} = 1;
                   3333:     }
1.524     raeburn  3334:     foreach my $type (keys(%decrement)) {
1.269     raeburn  3335:         $$aggregate{$symb."\0".$part."\0".$type} = -$decrement{$type};
                   3336:     }
                   3337:     return;
                   3338: }
                   3339: 
                   3340: # ----------- Determine timestamps for last reset of aggregate totals for parts  
                   3341: sub get_last_resets {
1.270     albertel 3342:     my ($symb,$courseid,$partids) =@_;
                   3343:     my %last_resets;
1.269     raeburn  3344:     my $cdom = $env{'course.'.$courseid.'.domain'};
                   3345:     my $cname = $env{'course.'.$courseid.'.num'};
1.271     albertel 3346:     my @keys;
                   3347:     foreach my $part (@{$partids}) {
                   3348: 	push(@keys,"$symb\0$part\0resettime");
                   3349:     }
                   3350:     my %results=&Apache::lonnet::get('nohist_resourcetracker',\@keys,
                   3351: 				     $cdom,$cname);
                   3352:     foreach my $part (@{$partids}) {
                   3353: 	$last_resets{$part}=$results{"$symb\0$part\0resettime"};
1.269     raeburn  3354:     }
1.270     albertel 3355:     return %last_resets;
1.269     raeburn  3356: }
                   3357: 
1.251     banghart 3358: # ----------- Handles creating versions for portfolio files as answers
                   3359: sub version_portfiles {
1.343     banghart 3360:     my ($record, $parts_graded, $courseid, $symb, $domain, $stu_name, $v_flag) = @_;
1.263     banghart 3361:     my $version_parts = join('|',@$v_flag);
1.343     banghart 3362:     my @returned_keys;
1.255     banghart 3363:     my $parts = join('|', @$parts_graded);
1.277     albertel 3364:     foreach my $key (keys(%$record)) {
1.259     banghart 3365:         my $new_portfiles;
1.263     banghart 3366:         if ($key =~ /^resource\.($version_parts)\./ && $key =~ /\.portfiles$/ ) {
1.342     banghart 3367:             my @versioned_portfiles;
1.367     albertel 3368:             my @portfiles = split(/\s*,\s*/,$$record{$key});
1.729     raeburn  3369:             if (@portfiles) {
                   3370:                 &Apache::lonnet::portfiles_versioning($symb,$domain,$stu_name,\@portfiles,
                   3371:                                                       \@versioned_portfiles);
1.252     banghart 3372:             }
1.343     banghart 3373:             $$record{$key} = join(',',@versioned_portfiles);
                   3374:             push(@returned_keys,$key);
1.251     banghart 3375:         }
                   3376:     } 
1.343     banghart 3377:     return (@returned_keys);   
1.305     banghart 3378: }
                   3379: 
1.44      ng       3380: #--------------------------------------------------------------------------------------
                   3381: #
                   3382: #-------------------------- Next few routines handles grading by section or whole class
                   3383: #
                   3384: #--- Javascript to handle grading by section or whole class
1.42      ng       3385: sub viewgrades_js {
                   3386:     my ($request) = shift;
                   3387: 
1.539     riegler  3388:     my $alertmsg = &mt('A number equal or greater than 0 is expected. Entered value = ');
1.736   ! damieng  3389:     &js_escape(\$alertmsg);
1.597     wenzelju 3390:     $request->print(&Apache::lonhtmlcommon::scripttag(<<VIEWJAVASCRIPT));
1.45      ng       3391:    function writePoint(partid,weight,point) {
1.125     ng       3392: 	var radioButton = document.classgrade["RADVAL_"+partid];
                   3393: 	var textbox = document.classgrade["TEXTVAL_"+partid];
1.42      ng       3394: 	if (point == "textval") {
1.125     ng       3395: 	    point = document.classgrade["TEXTVAL_"+partid].value;
1.109     matthew  3396: 	    if (isNaN(point) || parseFloat(point) < 0) {
1.539     riegler  3397: 		alert("$alertmsg"+parseFloat(point));
1.42      ng       3398: 		var resetbox = false;
                   3399: 		for (var i=0; i<radioButton.length; i++) {
                   3400: 		    if (radioButton[i].checked) {
                   3401: 			textbox.value = i;
                   3402: 			resetbox = true;
                   3403: 		    }
                   3404: 		}
                   3405: 		if (!resetbox) {
                   3406: 		    textbox.value = "";
                   3407: 		}
                   3408: 		return;
                   3409: 	    }
1.109     matthew  3410: 	    if (parseFloat(point) > parseFloat(weight)) {
                   3411: 		var resp = confirm("You entered a value ("+parseFloat(point)+
1.44      ng       3412: 				   ") greater than the weight for the part. Accept?");
                   3413: 		if (resp == false) {
                   3414: 		    textbox.value = "";
                   3415: 		    return;
                   3416: 		}
                   3417: 	    }
1.42      ng       3418: 	    for (var i=0; i<radioButton.length; i++) {
                   3419: 		radioButton[i].checked=false;
1.109     matthew  3420: 		if (parseFloat(point) == i) {
1.42      ng       3421: 		    radioButton[i].checked=true;
                   3422: 		}
                   3423: 	    }
1.41      ng       3424: 
1.42      ng       3425: 	} else {
1.125     ng       3426: 	    textbox.value = parseFloat(point);
1.42      ng       3427: 	}
1.41      ng       3428: 	for (i=0;i<document.classgrade.total.value;i++) {
1.125     ng       3429: 	    var user = document.classgrade["ctr"+i].value;
1.289     albertel 3430: 	    user = user.replace(new RegExp(':', 'g'),"_");
1.125     ng       3431: 	    var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
                   3432: 	    var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
                   3433: 	    var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
1.42      ng       3434: 	    if (saveval != "correct") {
                   3435: 		scorename.value = point;
1.43      ng       3436: 		if (selname[0].selected != true) {
                   3437: 		    selname[0].selected = true;
                   3438: 		}
1.42      ng       3439: 	    }
                   3440: 	}
1.125     ng       3441: 	document.classgrade["SELVAL_"+partid][0].selected = true;
1.42      ng       3442:     }
                   3443: 
                   3444:     function writeRadText(partid,weight) {
1.125     ng       3445: 	var selval   = document.classgrade["SELVAL_"+partid];
                   3446: 	var radioButton = document.classgrade["RADVAL_"+partid];
1.265     www      3447:         var override = document.classgrade["FORCE_"+partid].checked;
1.125     ng       3448: 	var textbox = document.classgrade["TEXTVAL_"+partid];
                   3449: 	if (selval[1].selected || selval[2].selected) {
1.42      ng       3450: 	    for (var i=0; i<radioButton.length; i++) {
                   3451: 		radioButton[i].checked=false;
                   3452: 
                   3453: 	    }
                   3454: 	    textbox.value = "";
                   3455: 
                   3456: 	    for (i=0;i<document.classgrade.total.value;i++) {
1.125     ng       3457: 		var user = document.classgrade["ctr"+i].value;
1.289     albertel 3458: 		user = user.replace(new RegExp(':', 'g'),"_");
1.125     ng       3459: 		var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
                   3460: 		var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
                   3461: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
1.265     www      3462: 		if ((saveval != "correct") || override) {
1.42      ng       3463: 		    scorename.value = "";
1.125     ng       3464: 		    if (selval[1].selected) {
                   3465: 			selname[1].selected = true;
                   3466: 		    } else {
                   3467: 			selname[2].selected = true;
                   3468: 			if (Number(document.classgrade["GD_"+user+"_"+partid+"_tries"].value)) 
                   3469: 			{document.classgrade["GD_"+user+"_"+partid+"_tries"].value = '0';}
                   3470: 		    }
1.42      ng       3471: 		}
                   3472: 	    }
1.43      ng       3473: 	} else {
                   3474: 	    for (i=0;i<document.classgrade.total.value;i++) {
1.125     ng       3475: 		var user = document.classgrade["ctr"+i].value;
1.289     albertel 3476: 		user = user.replace(new RegExp(':', 'g'),"_");
1.125     ng       3477: 		var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
                   3478: 		var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
                   3479: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
1.265     www      3480: 		if ((saveval != "correct") || override) {
1.125     ng       3481: 		    scorename.value = document.classgrade["GD_"+user+"_"+partid+"_awarded_s"].value;
1.43      ng       3482: 		    selname[0].selected = true;
                   3483: 		}
                   3484: 	    }
                   3485: 	}	    
1.42      ng       3486:     }
                   3487: 
                   3488:     function changeSelect(partid,user) {
1.125     ng       3489: 	var selval = document.classgrade["GD_"+user+'_'+partid+"_solved"];
                   3490: 	var textbox = document.classgrade["GD_"+user+'_'+partid+"_awarded"];
1.44      ng       3491: 	var point  = textbox.value;
1.125     ng       3492: 	var weight = document.classgrade["weight_"+partid].value;
1.44      ng       3493: 
1.109     matthew  3494: 	if (isNaN(point) || parseFloat(point) < 0) {
1.539     riegler  3495: 	    alert("$alertmsg"+parseFloat(point));
1.44      ng       3496: 	    textbox.value = "";
                   3497: 	    return;
                   3498: 	}
1.109     matthew  3499: 	if (parseFloat(point) > parseFloat(weight)) {
                   3500: 	    var resp = confirm("You entered a value ("+parseFloat(point)+
1.44      ng       3501: 			       ") greater than the weight of the part. Accept?");
                   3502: 	    if (resp == false) {
                   3503: 		textbox.value = "";
                   3504: 		return;
                   3505: 	    }
                   3506: 	}
1.42      ng       3507: 	selval[0].selected = true;
                   3508:     }
                   3509: 
                   3510:     function changeOneScore(partid,user) {
1.125     ng       3511: 	var selval = document.classgrade["GD_"+user+'_'+partid+"_solved"];
                   3512: 	if (selval[1].selected || selval[2].selected) {
                   3513: 	    document.classgrade["GD_"+user+'_'+partid+"_awarded"].value = "";
                   3514: 	    if (selval[2].selected) {
                   3515: 		document.classgrade["GD_"+user+'_'+partid+"_tries"].value = "0";
                   3516: 	    }
1.269     raeburn  3517:         }
1.42      ng       3518:     }
                   3519: 
                   3520:     function resetEntry(numpart) {
                   3521: 	for (ctpart=0;ctpart<numpart;ctpart++) {
1.125     ng       3522: 	    var partid = document.classgrade["partid_"+ctpart].value;
                   3523: 	    var radioButton = document.classgrade["RADVAL_"+partid];
                   3524: 	    var textbox = document.classgrade["TEXTVAL_"+partid];
                   3525: 	    var selval  = document.classgrade["SELVAL_"+partid];
1.42      ng       3526: 	    for (var i=0; i<radioButton.length; i++) {
                   3527: 		radioButton[i].checked=false;
                   3528: 
                   3529: 	    }
                   3530: 	    textbox.value = "";
                   3531: 	    selval[0].selected = true;
                   3532: 
                   3533: 	    for (i=0;i<document.classgrade.total.value;i++) {
1.125     ng       3534: 		var user = document.classgrade["ctr"+i].value;
1.289     albertel 3535: 		user = user.replace(new RegExp(':', 'g'),"_");
1.125     ng       3536: 		var resetscore = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
                   3537: 		resetscore.value = document.classgrade["GD_"+user+"_"+partid+"_awarded_s"].value;
                   3538: 		var resettries = document.classgrade["GD_"+user+"_"+partid+"_tries"];
                   3539: 		resettries.value = document.classgrade["GD_"+user+"_"+partid+"_tries_s"].value;
                   3540: 		var saveselval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
                   3541: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
1.42      ng       3542: 		if (saveselval == "excused") {
1.43      ng       3543: 		    if (selname[1].selected == false) { selname[1].selected = true;}
1.42      ng       3544: 		} else {
1.43      ng       3545: 		    if (selname[0].selected == false) {selname[0].selected = true};
1.42      ng       3546: 		}
                   3547: 	    }
1.41      ng       3548: 	}
1.42      ng       3549:     }
                   3550: 
1.41      ng       3551: VIEWJAVASCRIPT
1.42      ng       3552: }
                   3553: 
1.44      ng       3554: #--- show scores for a section or whole class w/ option to change/update a score
1.42      ng       3555: sub viewgrades {
1.608     www      3556:     my ($request,$symb) = @_;
1.42      ng       3557:     &viewgrades_js($request);
1.41      ng       3558: 
1.168     albertel 3559:     #need to make sure we have the correct data for later EXT calls, 
                   3560:     #thus invalidate the cache
                   3561:     &Apache::lonnet::devalidatecourseresdata(
1.257     albertel 3562:                  $env{'course.'.$env{'request.course.id'}.'.num'},
                   3563:                  $env{'course.'.$env{'request.course.id'}.'.domain'});
1.168     albertel 3564:     &Apache::lonnet::clear_EXT_cache_status();
                   3565: 
1.398     albertel 3566:     my $result='<h3><span class="LC_info">'.&mt('Manual Grading').'</span></h3>';
1.41      ng       3567: 
                   3568:     #view individual student submission form - called using Javascript viewOneStudent
1.324     albertel 3569:     $result.=&jscriptNform($symb);
1.41      ng       3570: 
1.44      ng       3571:     #beginning of class grading form
1.442     banghart 3572:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
1.41      ng       3573:     $result.= '<form action="/adm/grades" method="post" name="classgrade">'."\n".
1.418     albertel 3574: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.38      ng       3575: 	'<input type="hidden" name="command" value="editgrades" />'."\n".
1.432     banghart 3576: 	&build_section_inputs().
1.442     banghart 3577: 	'<input type="hidden" name="Status" value="'.$env{'stu_status'}.'" />'."\n".
1.72      ng       3578: 
1.560     raeburn  3579:     my ($common_header,$specific_header);
1.257     albertel 3580:     if ($env{'form.section'} eq 'all') {
1.560     raeburn  3581: 	$common_header = &mt('Assign Common Grade to Class');
                   3582:         $specific_header = &mt('Assign Grade to Specific Students in Class');
1.257     albertel 3583:     } elsif ($env{'form.section'} eq 'none') {
1.560     raeburn  3584:         $common_header = &mt('Assign Common Grade to Students in no Section');
                   3585: 	$specific_header = &mt('Assign Grade to Specific Students in no Section');
1.52      albertel 3586:     } else {
1.560     raeburn  3587:         my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
                   3588:         $common_header = &mt('Assign Common Grade to Students in Section(s) [_1]',$section_display);
                   3589: 	$specific_header = &mt('Assign Grade to Specific Students in Section(s) [_1]',$section_display);
1.52      albertel 3590:     }
1.560     raeburn  3591:     $result.= '<h3>'.$common_header.'</h3>'.&Apache::loncommon::start_data_table();
1.44      ng       3592:     #radio buttons/text box for assigning points for a section or class.
                   3593:     #handles different parts of a problem
1.582     raeburn  3594:     my $res_error;
                   3595:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
                   3596:     if ($res_error) {
                   3597:         return &navmap_errormsg();
                   3598:     }
1.42      ng       3599:     my %weight = ();
                   3600:     my $ctsparts = 0;
1.45      ng       3601:     my %seen = ();
1.375     albertel 3602:     my @part_response_id = &flatten_responseType($responseType);
                   3603:     foreach my $part_response_id (@part_response_id) {
                   3604:     	my ($partid,$respid) = @{ $part_response_id };
                   3605: 	my $part_resp = join('_',@{ $part_response_id });
1.45      ng       3606: 	next if $seen{$partid};
                   3607: 	$seen{$partid}++;
1.375     albertel 3608: 	my $handgrade=$$handgrade{$part_resp};
1.42      ng       3609: 	my $wgt = &Apache::lonnet::EXT('resource.'.$partid.'.weight',$symb);
                   3610: 	$weight{$partid} = $wgt eq '' ? '1' : $wgt;
                   3611: 
1.324     albertel 3612: 	my $display_part=&get_display_part($partid,$symb);
1.485     albertel 3613: 	my $radio.='<table border="0"><tr>';  
1.41      ng       3614: 	my $ctr = 0;
1.42      ng       3615: 	while ($ctr<=$weight{$partid}) { # display radio buttons in a nice table 10 across
1.485     albertel 3616: 	    $radio.= '<td><label><input type="radio" name="RADVAL_'.$partid.'" '.
1.54      albertel 3617: 		'onclick="javascript:writePoint(\''.$partid.'\','.$weight{$partid}.
1.288     albertel 3618: 		','.$ctr.')" />'.$ctr."</label></td>\n";
1.41      ng       3619: 	    $result.=(($ctr+1)%10 == 0 ? '</tr><tr>' : '');
                   3620: 	    $ctr++;
                   3621: 	}
1.485     albertel 3622: 	$radio.='</tr></table>';
                   3623: 	my $line = '<input type="text" name="TEXTVAL_'.
1.589     bisitz   3624: 	    $partid.'" size="4" '.'onchange="javascript:writePoint(\''.
1.54      albertel 3625: 		$partid.'\','.$weight{$partid}.',\'textval\')" /> /'.
1.539     riegler  3626: 	    $weight{$partid}.' '.&mt('(problem weight)').'</td>'."\n";
1.701     bisitz   3627:         $line.= '<td><b>'.&mt('Grade Status').':</b>'.
                   3628:             '<select name="SELVAL_'.$partid.'" '.
                   3629:             'onchange="javascript:writeRadText(\''.$partid.'\','.
                   3630:                 $weight{$partid}.')"> '.
1.401     albertel 3631: 	    '<option selected="selected"> </option>'.
1.485     albertel 3632: 	    '<option value="excused">'.&mt('excused').'</option>'.
                   3633: 	    '<option value="reset status">'.&mt('reset status').'</option>'.
                   3634: 	    '</select></td>'.
                   3635:             '<td><label><input type="checkbox" name="FORCE_'.$partid.'" />'.&mt('Override "Correct"').'</label>';
                   3636: 	$line.='<input type="hidden" name="partid_'.
                   3637: 	    $ctsparts.'" value="'.$partid.'" />'."\n";
                   3638: 	$line.='<input type="hidden" name="weight_'.
                   3639: 	    $partid.'" value="'.$weight{$partid}.'" />'."\n";
                   3640: 
                   3641: 	$result.=
                   3642: 	    &Apache::loncommon::start_data_table_row()."\n".
1.577     bisitz   3643: 	    '<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 3644: 	    &Apache::loncommon::end_data_table_row()."\n";
1.42      ng       3645: 	$ctsparts++;
1.41      ng       3646:     }
1.474     albertel 3647:     $result.=&Apache::loncommon::end_data_table()."\n".
1.52      albertel 3648: 	'<input type="hidden" name="totalparts" value="'.$ctsparts.'" />';
1.485     albertel 3649:     $result.='<input type="button" value="'.&mt('Revert to Default').'" '.
1.589     bisitz   3650: 	'onclick="javascript:resetEntry('.$ctsparts.');" />';
1.41      ng       3651: 
1.44      ng       3652:     #table listing all the students in a section/class
                   3653:     #header of table
1.560     raeburn  3654:     $result.= '<h3>'.$specific_header.'</h3>'.
                   3655:               &Apache::loncommon::start_data_table().
                   3656: 	      &Apache::loncommon::start_data_table_header_row().
                   3657: 	      '<th>'.&mt('No.').'</th>'.
                   3658: 	      '<th>'.&nameUserString('header')."</th>\n";
1.582     raeburn  3659:     my $partserror;
                   3660:     my (@parts) = sort(&getpartlist($symb,\$partserror));
                   3661:     if ($partserror) {
                   3662:         return &navmap_errormsg();
                   3663:     }
1.324     albertel 3664:     my (undef,undef,$url)=&Apache::lonnet::decode_symb($symb);
1.269     raeburn  3665:     my @partids = ();
1.41      ng       3666:     foreach my $part (@parts) {
                   3667: 	my $display=&Apache::lonnet::metadata($url,$part.'.display');
1.539     riegler  3668:         my $narrowtext = &mt('Tries');
                   3669: 	$display =~ s|^Number of Attempts|$narrowtext <br />|; # makes the column narrower
1.41      ng       3670: 	if  (!$display) { $display = &Apache::lonnet::metadata($url,$part.'.name'); }
1.207     albertel 3671: 	my ($partid) = &split_part_type($part);
1.524     raeburn  3672:         push(@partids,$partid);
1.628     www      3673: #
                   3674: # FIXME: Looks like $display looks at English text
                   3675: #
1.324     albertel 3676: 	my $display_part=&get_display_part($partid,$symb);
1.41      ng       3677: 	if ($display =~ /^Partial Credit Factor/) {
1.485     albertel 3678: 	    $result.='<th>'.
1.697     bisitz   3679: 		&mt('Score Part: [_1][_2](weight = [_3])',
                   3680: 		    $display_part,'<br />',$weight{$partid}).'</th>'."\n";
1.41      ng       3681: 	    next;
1.485     albertel 3682: 	    
1.207     albertel 3683: 	} else {
1.485     albertel 3684: 	    if ($display =~ /Problem Status/) {
                   3685: 		my $grade_status_mt = &mt('Grade Status');
                   3686: 		$display =~ s{Problem Status}{$grade_status_mt<br />};
                   3687: 	    }
                   3688: 	    my $part_mt = &mt('Part:');
                   3689: 	    $display =~s{\[Part: \Q$partid\E\]}{$part_mt $display_part};
1.41      ng       3690: 	}
1.485     albertel 3691: 
1.474     albertel 3692: 	$result.='<th>'.$display.'</th>'."\n";
1.41      ng       3693:     }
1.474     albertel 3694:     $result.=&Apache::loncommon::end_data_table_header_row();
1.44      ng       3695: 
1.270     albertel 3696:     my %last_resets = 
                   3697: 	&get_last_resets($symb,$env{'request.course.id'},\@partids);
1.269     raeburn  3698: 
1.41      ng       3699:     #get info for each student
1.44      ng       3700:     #list all the students - with points and grade status
1.257     albertel 3701:     my (undef,undef,$fullname) = &getclasslist($env{'form.section'},'1');
1.41      ng       3702:     my $ctr = 0;
1.294     albertel 3703:     foreach (sort 
                   3704: 	     {
                   3705: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                   3706: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                   3707: 		 }
                   3708: 		 return $a cmp $b;
                   3709: 	     } (keys(%$fullname))) {
1.126     ng       3710: 	$ctr++;
1.324     albertel 3711: 	$result.=&viewstudentgrade($symb,$env{'request.course.id'},
1.269     raeburn  3712: 				   $_,$$fullname{$_},\@parts,\%weight,$ctr,\%last_resets);
1.41      ng       3713:     }
1.474     albertel 3714:     $result.=&Apache::loncommon::end_data_table();
1.41      ng       3715:     $result.='<input type="hidden" name="total" value="'.$ctr.'" />'."\n";
1.485     albertel 3716:     $result.='<input type="button" value="'.&mt('Save').'" '.
1.589     bisitz   3717: 	'onclick="javascript:submit();" target="_self" /></form>'."\n";
1.96      albertel 3718:     if (scalar(%$fullname) eq 0) {
                   3719: 	my $colspan=3+scalar(@parts);
1.433     banghart 3720: 	my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
1.442     banghart 3721:         my $stu_status = join(' or ',&Apache::loncommon::get_env_multiple('form.Status'));
1.433     banghart 3722: 	$result='<span class="LC_warning">'.
1.485     albertel 3723: 	    &mt('There are no students in section(s) [_1] with enrollment status [_2] to modify or grade.',
1.442     banghart 3724: 	        $section_display, $stu_status).
1.433     banghart 3725: 	    '</span>';
1.96      albertel 3726:     }
1.41      ng       3727:     return $result;
                   3728: }
                   3729: 
1.44      ng       3730: #--- call by previous routine to display each student
1.41      ng       3731: sub viewstudentgrade {
1.324     albertel 3732:     my ($symb,$courseid,$student,$fullname,$parts,$weight,$ctr,$last_resets) = @_;
1.44      ng       3733:     my ($uname,$udom) = split(/:/,$student);
                   3734:     my %record=&Apache::lonnet::restore($symb,$courseid,$udom,$uname);
1.269     raeburn  3735:     my %aggregates = (); 
1.474     albertel 3736:     my $result=&Apache::loncommon::start_data_table_row().'<td align="right">'.
1.233     albertel 3737: 	'<input type="hidden" name="ctr'.($ctr-1).'" value="'.$student.'" />'.
                   3738: 	"\n".$ctr.'&nbsp;</td><td>&nbsp;'.
1.44      ng       3739: 	'<a href="javascript:viewOneStudent(\''.$uname.'\',\''.$udom.
1.417     albertel 3740: 	'\');" target="_self">'.$fullname.'</a> '.
1.398     albertel 3741: 	'<span class="LC_internal_info">('.$uname.($env{'user.domain'} eq $udom ? '' : ':'.$udom).')</span></td>'."\n";
1.281     albertel 3742:     $student=~s/:/_/; # colon doen't work in javascript for names
1.63      albertel 3743:     foreach my $apart (@$parts) {
                   3744: 	my ($part,$type) = &split_part_type($apart);
1.41      ng       3745: 	my $score=$record{"resource.$part.$type"};
1.276     albertel 3746:         $result.='<td align="center">';
1.269     raeburn  3747:         my ($aggtries,$totaltries);
                   3748:         unless (exists($aggregates{$part})) {
1.270     albertel 3749: 	    $totaltries = $record{'resource.'.$part.'.tries'};
                   3750: 
                   3751: 	    $aggtries = $totaltries;
1.269     raeburn  3752:             if ($$last_resets{$part}) {  
1.270     albertel 3753:                 $aggtries = &get_num_tries(\%record,$$last_resets{$part},
                   3754: 					   $part);
                   3755:             }
1.269     raeburn  3756:             $result.='<input type="hidden" name="'.
                   3757:                 'GD_'.$student.'_'.$part.'_aggtries" value="'.$aggtries.'" />'."\n";
                   3758:             $result.='<input type="hidden" name="'.
                   3759:                 'GD_'.$student.'_'.$part.'_totaltries" value="'.$totaltries.'" />'."\n";
                   3760:             $aggregates{$part} = 1;
                   3761:         }
1.41      ng       3762: 	if ($type eq 'awarded') {
1.320     albertel 3763: 	    my $pts = $score eq '' ? '' : &compute_points($score,$$weight{$part});
1.42      ng       3764: 	    $result.='<input type="hidden" name="'.
1.89      albertel 3765: 		'GD_'.$student.'_'.$part.'_awarded_s" value="'.$pts.'" />'."\n";
1.233     albertel 3766: 	    $result.='<input type="text" name="'.
1.89      albertel 3767: 		'GD_'.$student.'_'.$part.'_awarded" '.
1.589     bisitz   3768:                 'onchange="javascript:changeSelect(\''.$part.'\',\''.$student.
1.44      ng       3769: 		'\')" value="'.$pts.'" size="4" /></td>'."\n";
1.41      ng       3770: 	} elsif ($type eq 'solved') {
                   3771: 	    my ($status,$foo)=split(/_/,$score,2);
                   3772: 	    $status = 'nothing' if ($status eq '');
1.89      albertel 3773: 	    $result.='<input type="hidden" name="'.'GD_'.$student.'_'.
1.54      albertel 3774: 		$part.'_solved_s" value="'.$status.'" />'."\n";
1.233     albertel 3775: 	    $result.='&nbsp;<select name="'.
1.89      albertel 3776: 		'GD_'.$student.'_'.$part.'_solved" '.
1.589     bisitz   3777:                 'onchange="javascript:changeOneScore(\''.$part.'\',\''.$student.'\')" >'."\n";
1.485     albertel 3778: 	    $result.= (($status eq 'excused') ? '<option> </option><option selected="selected" value="excused">'.&mt('excused').'</option>' 
                   3779: 		: '<option selected="selected"> </option><option value="excused">'.&mt('excused').'</option>')."\n";
                   3780: 	    $result.='<option value="reset status">'.&mt('reset status').'</option>';
1.126     ng       3781: 	    $result.="</select>&nbsp;</td>\n";
1.122     ng       3782: 	} else {
                   3783: 	    $result.='<input type="hidden" name="'.
                   3784: 		'GD_'.$student.'_'.$part.'_'.$type.'_s" value="'.$score.'" />'.
                   3785: 		    "\n";
1.233     albertel 3786: 	    $result.='<input type="text" name="'.
1.122     ng       3787: 		'GD_'.$student.'_'.$part.'_'.$type.'" '.
                   3788: 		'value="'.$score.'" size="4" /></td>'."\n";
1.41      ng       3789: 	}
                   3790:     }
1.474     albertel 3791:     $result.=&Apache::loncommon::end_data_table_row();
1.41      ng       3792:     return $result;
1.38      ng       3793: }
                   3794: 
1.44      ng       3795: #--- change scores for all the students in a section/class
                   3796: #    record does not get update if unchanged
1.38      ng       3797: sub editgrades {
1.608     www      3798:     my ($request,$symb) = @_;
1.41      ng       3799: 
1.433     banghart 3800:     my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
1.477     albertel 3801:     my $title='<h2>'.&mt('Current Grade Status').'</h2>';
1.433     banghart 3802:     $title.='<h4>'.&mt('<b>Section: </b>[_1]',$section_display).'</h4>'."\n";
1.126     ng       3803: 
1.477     albertel 3804:     my $result= &Apache::loncommon::start_data_table().
                   3805: 	&Apache::loncommon::start_data_table_header_row().
                   3806: 	'<th rowspan="2" valign="middle">'.&mt('No.').'</th>'.
                   3807: 	'<th rowspan="2" valign="middle">'.&nameUserString('header')."</th>\n";
1.43      ng       3808:     my %scoreptr = (
                   3809: 		    'correct'  =>'correct_by_override',
                   3810: 		    'incorrect'=>'incorrect_by_override',
                   3811: 		    'excused'  =>'excused',
                   3812: 		    'ungraded' =>'ungraded_attempted',
1.596     raeburn  3813:                     'credited' =>'credit_attempted',
1.43      ng       3814: 		    'nothing'  => '',
                   3815: 		    );
1.257     albertel 3816:     my ($classlist,undef,$fullname) = &getclasslist($env{'form.section'},'0');
1.34      ng       3817: 
1.44      ng       3818:     my (@partid);
                   3819:     my %weight = ();
1.54      albertel 3820:     my %columns = ();
1.44      ng       3821:     my ($i,$ctr,$count,$rec_update) = (0,0,0,0);
1.54      albertel 3822: 
1.582     raeburn  3823:     my $partserror;
                   3824:     my (@parts) = sort(&getpartlist($symb,\$partserror));
                   3825:     if ($partserror) {
                   3826:         return &navmap_errormsg();
                   3827:     }
1.54      albertel 3828:     my $header;
1.257     albertel 3829:     while ($ctr < $env{'form.totalparts'}) {
                   3830: 	my $partid = $env{'form.partid_'.$ctr};
1.524     raeburn  3831: 	push(@partid,$partid);
1.257     albertel 3832: 	$weight{$partid} = $env{'form.weight_'.$partid};
1.44      ng       3833: 	$ctr++;
1.54      albertel 3834:     }
1.324     albertel 3835:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
1.54      albertel 3836:     foreach my $partid (@partid) {
1.478     albertel 3837: 	$header .= '<th align="center">'.&mt('Old Score').'</th>'.
                   3838: 	    '<th align="center">'.&mt('New Score').'</th>';
1.54      albertel 3839: 	$columns{$partid}=2;
                   3840: 	foreach my $stores (@parts) {
                   3841: 	    my ($part,$type) = &split_part_type($stores);
                   3842: 	    if ($part !~ m/^\Q$partid\E/) { next;}
                   3843: 	    if ($type eq 'awarded' || $type eq 'solved') { next; }
                   3844: 	    my $display=&Apache::lonnet::metadata($url,$stores.'.display');
1.551     raeburn  3845: 	    $display =~ s/\[Part: \Q$part\E\]//;
1.539     riegler  3846:             my $narrowtext = &mt('Tries');
                   3847: 	    $display =~ s/Number of Attempts/$narrowtext/;
                   3848: 	    $header .= '<th align="center">'.&mt('Old').' '.$display.'</th>'.
                   3849: 		'<th align="center">'.&mt('New').' '.$display.'</th>';
1.54      albertel 3850: 	    $columns{$partid}+=2;
                   3851: 	}
                   3852:     }
                   3853:     foreach my $partid (@partid) {
1.324     albertel 3854: 	my $display_part=&get_display_part($partid,$symb);
1.478     albertel 3855: 	$result .= '<th colspan="'.$columns{$partid}.'" align="center">'.
                   3856: 	    &mt('Part: [_1] (Weight = [_2])',$display_part,$weight{$partid}).
                   3857: 	    '</th>';
1.54      albertel 3858: 
1.44      ng       3859:     }
1.477     albertel 3860:     $result .= &Apache::loncommon::end_data_table_header_row().
                   3861: 	&Apache::loncommon::start_data_table_header_row().
                   3862: 	$header.
                   3863: 	&Apache::loncommon::end_data_table_header_row();
                   3864:     my @noupdate;
1.126     ng       3865:     my ($updateCtr,$noupdateCtr) = (1,1);
1.257     albertel 3866:     for ($i=0; $i<$env{'form.total'}; $i++) {
1.93      albertel 3867: 	my $line;
1.257     albertel 3868: 	my $user = $env{'form.ctr'.$i};
1.281     albertel 3869: 	my ($uname,$udom)=split(/:/,$user);
1.44      ng       3870: 	my %newrecord;
                   3871: 	my $updateflag = 0;
1.281     albertel 3872: 	$line .= '<td>'.&nameUserString(undef,$$fullname{$user},$uname,$udom).'</td>';
1.108     albertel 3873: 	my $usec=$classlist->{"$uname:$udom"}[5];
1.105     albertel 3874: 	if (!&canmodify($usec)) {
1.126     ng       3875: 	    my $numcols=scalar(@partid)*4+2;
1.477     albertel 3876: 	    push(@noupdate,
1.478     albertel 3877: 		 $line."<td colspan=\"$numcols\"><span class=\"LC_warning\">".
                   3878: 		 &mt('Not allowed to modify student')."</span></td></tr>");
1.105     albertel 3879: 	    next;
                   3880: 	}
1.269     raeburn  3881:         my %aggregate = ();
                   3882:         my $aggregateflag = 0;
1.281     albertel 3883: 	$user=~s/:/_/; # colon doen't work in javascript for names
1.44      ng       3884: 	foreach (@partid) {
1.257     albertel 3885: 	    my $old_aw    = $env{'form.GD_'.$user.'_'.$_.'_awarded_s'};
1.54      albertel 3886: 	    my $old_part_pcr = $old_aw/($weight{$_} ne '0' ? $weight{$_}:1);
                   3887: 	    my $old_part  = $old_aw eq '' ? '' : $old_part_pcr;
1.257     albertel 3888: 	    my $old_score = $scoreptr{$env{'form.GD_'.$user.'_'.$_.'_solved_s'}};
                   3889: 	    my $awarded   = $env{'form.GD_'.$user.'_'.$_.'_awarded'};
1.54      albertel 3890: 	    my $pcr       = $awarded/($weight{$_} ne '0' ? $weight{$_} : 1);
                   3891: 	    my $partial   = $awarded eq '' ? '' : $pcr;
1.44      ng       3892: 	    my $score;
                   3893: 	    if ($partial eq '') {
1.257     albertel 3894: 		$score = $scoreptr{$env{'form.GD_'.$user.'_'.$_.'_solved_s'}};
1.44      ng       3895: 	    } elsif ($partial > 0) {
                   3896: 		$score = 'correct_by_override';
                   3897: 	    } elsif ($partial == 0) {
                   3898: 		$score = 'incorrect_by_override';
                   3899: 	    }
1.257     albertel 3900: 	    my $dropMenu = $env{'form.GD_'.$user.'_'.$_.'_solved'};
1.125     ng       3901: 	    $score = 'excused' if (($dropMenu eq 'excused') && ($score ne 'excused'));
                   3902: 
1.292     albertel 3903: 	    $newrecord{'resource.'.$_.'.regrader'}=
                   3904: 		"$env{'user.name'}:$env{'user.domain'}";
1.125     ng       3905: 	    if ($dropMenu eq 'reset status' &&
                   3906: 		$old_score ne '') { # ignore if no previous attempts => nothing to reset
1.299     albertel 3907: 		$newrecord{'resource.'.$_.'.tries'} = '';
1.125     ng       3908: 		$newrecord{'resource.'.$_.'.solved'} = '';
                   3909: 		$newrecord{'resource.'.$_.'.award'} = '';
1.299     albertel 3910: 		$newrecord{'resource.'.$_.'.awarded'} = '';
1.125     ng       3911: 		$updateflag = 1;
1.269     raeburn  3912:                 if ($env{'form.GD_'.$user.'_'.$_.'_aggtries'} > 0) {
                   3913:                     my $aggtries = $env{'form.GD_'.$user.'_'.$_.'_aggtries'};
                   3914:                     my $totaltries = $env{'form.GD_'.$user.'_'.$_.'_totaltries'};
                   3915:                     my $solvedstatus = $env{'form.GD_'.$user.'_'.$_.'_solved_s'};
                   3916:                     &decrement_aggs($symb,$_,\%aggregate,$aggtries,$totaltries,$solvedstatus);
                   3917:                     $aggregateflag = 1;
                   3918:                 }
1.139     albertel 3919: 	    } elsif (!($old_part eq $partial && $old_score eq $score)) {
                   3920: 		$updateflag = 1;
                   3921: 		$newrecord{'resource.'.$_.'.awarded'}  = $partial if $partial ne '';
                   3922: 		$newrecord{'resource.'.$_.'.solved'}   = $score;
                   3923: 		$rec_update++;
1.125     ng       3924: 	    }
                   3925: 
1.93      albertel 3926: 	    $line .= '<td align="center">'.$old_aw.'&nbsp;</td>'.
1.44      ng       3927: 		'<td align="center">'.$awarded.
                   3928: 		($score eq 'excused' ? $score : '').'&nbsp;</td>';
1.5       albertel 3929: 
1.54      albertel 3930: 
                   3931: 	    my $partid=$_;
                   3932: 	    foreach my $stores (@parts) {
                   3933: 		my ($part,$type) = &split_part_type($stores);
                   3934: 		if ($part !~ m/^\Q$partid\E/) { next;}
                   3935: 		if ($type eq 'awarded' || $type eq 'solved') { next; }
1.257     albertel 3936: 		my $old_aw    = $env{'form.GD_'.$user.'_'.$part.'_'.$type.'_s'};
                   3937: 		my $awarded   = $env{'form.GD_'.$user.'_'.$part.'_'.$type};
1.54      albertel 3938: 		if ($awarded ne '' && $awarded ne $old_aw) {
                   3939: 		    $newrecord{'resource.'.$part.'.'.$type}= $awarded;
1.257     albertel 3940: 		    $newrecord{'resource.'.$part.'.regrader'}="$env{'user.name'}:$env{'user.domain'}";
1.54      albertel 3941: 		    $updateflag=1;
                   3942: 		}
1.93      albertel 3943: 		$line .= '<td align="center">'.$old_aw.'&nbsp;</td>'.
1.54      albertel 3944: 		    '<td align="center">'.$awarded.'&nbsp;</td>';
                   3945: 	    }
1.44      ng       3946: 	}
1.477     albertel 3947: 	$line.="\n";
1.301     albertel 3948: 
                   3949: 	my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   3950: 	my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   3951: 
1.44      ng       3952: 	if ($updateflag) {
                   3953: 	    $count++;
1.257     albertel 3954: 	    &Apache::lonnet::cstore(\%newrecord,$symb,$env{'request.course.id'},
1.89      albertel 3955: 				    $udom,$uname);
1.301     albertel 3956: 
                   3957: 	    if (&Apache::bridgetask::in_queue('gradingqueue',$symb,$cdom,
                   3958: 					      $cnum,$udom,$uname)) {
                   3959: 		# need to figure out if should be in queue.
                   3960: 		my %record =  
                   3961: 		    &Apache::lonnet::restore($symb,$env{'request.course.id'},
                   3962: 					     $udom,$uname);
                   3963: 		my $all_graded = 1;
                   3964: 		my $none_graded = 1;
                   3965: 		foreach my $part (@parts) {
                   3966: 		    if ( $record{'resource.'.$part.'.awarded'} eq '' ) {
                   3967: 			$all_graded = 0;
                   3968: 		    } else {
                   3969: 			$none_graded = 0;
                   3970: 		    }
                   3971: 		}
                   3972: 
                   3973: 		if ($all_graded || $none_graded) {
                   3974: 		    &Apache::bridgetask::remove_from_queue('gradingqueue',
                   3975: 							   $symb,$cdom,$cnum,
                   3976: 							   $udom,$uname);
                   3977: 		}
                   3978: 	    }
                   3979: 
1.477     albertel 3980: 	    $result.=&Apache::loncommon::start_data_table_row().
                   3981: 		'<td align="right">&nbsp;'.$updateCtr.'&nbsp;</td>'.$line.
                   3982: 		&Apache::loncommon::end_data_table_row();
1.126     ng       3983: 	    $updateCtr++;
1.93      albertel 3984: 	} else {
1.477     albertel 3985: 	    push(@noupdate,
                   3986: 		 '<td align="right">&nbsp;'.$noupdateCtr.'&nbsp;</td>'.$line);
1.126     ng       3987: 	    $noupdateCtr++;
1.44      ng       3988: 	}
1.269     raeburn  3989:         if ($aggregateflag) {
                   3990:             &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
1.301     albertel 3991: 				  $cdom,$cnum);
1.269     raeburn  3992:         }
1.93      albertel 3993:     }
1.477     albertel 3994:     if (@noupdate) {
1.126     ng       3995: #	my $numcols=(scalar(@partid)*(scalar(@parts)-1)*2)+3;
                   3996: 	my $numcols=scalar(@partid)*4+2;
1.477     albertel 3997: 	$result .= &Apache::loncommon::start_data_table_row('LC_empty_row').
1.478     albertel 3998: 	    '<td align="center" colspan="'.$numcols.'">'.
                   3999: 	    &mt('No Changes Occurred For the Students Below').
                   4000: 	    '</td>'.
1.477     albertel 4001: 	    &Apache::loncommon::end_data_table_row();
                   4002: 	foreach my $line (@noupdate) {
                   4003: 	    $result.=
                   4004: 		&Apache::loncommon::start_data_table_row().
                   4005: 		$line.
                   4006: 		&Apache::loncommon::end_data_table_row();
                   4007: 	}
1.44      ng       4008:     }
1.614     www      4009:     $result .= &Apache::loncommon::end_data_table();
1.478     albertel 4010:     my $msg = '<p><b>'.
                   4011: 	&mt('Number of records updated = [_1] for [quant,_2,student].',
                   4012: 	    $rec_update,$count).'</b><br />'.
                   4013: 	'<b>'.&mt('Total number of students = [_1]',$env{'form.total'}).
                   4014: 	'</b></p>';
1.44      ng       4015:     return $title.$msg.$result;
1.5       albertel 4016: }
1.54      albertel 4017: 
                   4018: sub split_part_type {
                   4019:     my ($partstr) = @_;
                   4020:     my ($temp,@allparts)=split(/_/,$partstr);
                   4021:     my $type=pop(@allparts);
1.439     albertel 4022:     my $part=join('_',@allparts);
1.54      albertel 4023:     return ($part,$type);
                   4024: }
                   4025: 
1.44      ng       4026: #------------- end of section for handling grading by section/class ---------
                   4027: #
                   4028: #----------------------------------------------------------------------------
                   4029: 
1.5       albertel 4030: 
1.44      ng       4031: #----------------------------------------------------------------------------
                   4032: #
                   4033: #-------------------------- Next few routines handles grading by csv upload
                   4034: #
                   4035: #--- Javascript to handle csv upload
1.27      albertel 4036: sub csvupload_javascript_reverse_associate {
1.573     bisitz   4037:     my $error1=&mt('You need to specify the username or the student/employee ID');
1.246     albertel 4038:     my $error2=&mt('You need to specify at least one grading field');
1.736   ! damieng  4039:   &js_escape(\$error1);
        !          4040:   &js_escape(\$error2);
1.27      albertel 4041:   return(<<ENDPICK);
                   4042:   function verify(vf) {
                   4043:     var foundsomething=0;
                   4044:     var founduname=0;
1.243     albertel 4045:     var foundID=0;
1.27      albertel 4046:     for (i=0;i<=vf.nfields.value;i++) {
                   4047:       tw=eval('vf.f'+i+'.selectedIndex');
1.243     albertel 4048:       if (i==0 && tw!=0) { foundID=1; }
                   4049:       if (i==1 && tw!=0) { founduname=1; }
                   4050:       if (i!=0 && i!=1 && i!=2 && tw!=0) { foundsomething=1; }
1.27      albertel 4051:     }
1.246     albertel 4052:     if (founduname==0 && foundID==0) {
                   4053: 	alert('$error1');
                   4054: 	return;
1.27      albertel 4055:     }
                   4056:     if (foundsomething==0) {
1.246     albertel 4057: 	alert('$error2');
                   4058: 	return;
1.27      albertel 4059:     }
                   4060:     vf.submit();
                   4061:   }
                   4062:   function flip(vf,tf) {
                   4063:     var nw=eval('vf.f'+tf+'.selectedIndex');
                   4064:     var i;
                   4065:     for (i=0;i<=vf.nfields.value;i++) {
                   4066:       //can not pick the same destination field for both name and domain
                   4067:       if (((i ==0)||(i ==1)) && 
                   4068:           ((tf==0)||(tf==1)) && 
                   4069:           (i!=tf) &&
                   4070:           (eval('vf.f'+i+'.selectedIndex')==nw)) {
                   4071:         eval('vf.f'+i+'.selectedIndex=0;')
                   4072:       }
                   4073:     }
                   4074:   }
                   4075: ENDPICK
                   4076: }
                   4077: 
                   4078: sub csvupload_javascript_forward_associate {
1.573     bisitz   4079:     my $error1=&mt('You need to specify the username or the student/employee ID');
1.246     albertel 4080:     my $error2=&mt('You need to specify at least one grading field');
1.736   ! damieng  4081:   &js_escape(\$error1);
        !          4082:   &js_escape(\$error2);
1.27      albertel 4083:   return(<<ENDPICK);
                   4084:   function verify(vf) {
                   4085:     var foundsomething=0;
                   4086:     var founduname=0;
1.243     albertel 4087:     var foundID=0;
1.27      albertel 4088:     for (i=0;i<=vf.nfields.value;i++) {
                   4089:       tw=eval('vf.f'+i+'.selectedIndex');
1.243     albertel 4090:       if (tw==1) { foundID=1; }
                   4091:       if (tw==2) { founduname=1; }
                   4092:       if (tw>3) { foundsomething=1; }
1.27      albertel 4093:     }
1.246     albertel 4094:     if (founduname==0 && foundID==0) {
                   4095: 	alert('$error1');
                   4096: 	return;
1.27      albertel 4097:     }
                   4098:     if (foundsomething==0) {
1.246     albertel 4099: 	alert('$error2');
                   4100: 	return;
1.27      albertel 4101:     }
                   4102:     vf.submit();
                   4103:   }
                   4104:   function flip(vf,tf) {
                   4105:     var nw=eval('vf.f'+tf+'.selectedIndex');
                   4106:     var i;
                   4107:     //can not pick the same destination field twice
                   4108:     for (i=0;i<=vf.nfields.value;i++) {
                   4109:       if ((i!=tf) && (eval('vf.f'+i+'.selectedIndex')==nw)) {
                   4110:         eval('vf.f'+i+'.selectedIndex=0;')
                   4111:       }
                   4112:     }
                   4113:   }
                   4114: ENDPICK
                   4115: }
                   4116: 
1.26      albertel 4117: sub csvuploadmap_header {
1.324     albertel 4118:     my ($request,$symb,$datatoken,$distotal)= @_;
1.41      ng       4119:     my $javascript;
1.257     albertel 4120:     if ($env{'form.upfile_associate'} eq 'reverse') {
1.41      ng       4121: 	$javascript=&csvupload_javascript_reverse_associate();
                   4122:     } else {
                   4123: 	$javascript=&csvupload_javascript_forward_associate();
                   4124:     }
1.45      ng       4125: 
1.418     albertel 4126:     $symb = &Apache::lonenc::check_encrypt($symb);
1.632     www      4127:     $request->print('<form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">'.
                   4128:                     &mt('Total number of records found in file: [_1]',$distotal).'<hr />'.
                   4129:                     &mt('Associate entries from the uploaded file with as many fields as you can.'));
                   4130:     my $reverse=&mt("Reverse Association");
1.41      ng       4131:     $request->print(<<ENDPICK);
1.632     www      4132: <br />
                   4133: <input type="button" value="$reverse" onclick="javascript:this.form.associate.value='Reverse Association';submit(this.form);" />
1.26      albertel 4134: <input type="hidden" name="associate"  value="" />
                   4135: <input type="hidden" name="phase"      value="three" />
                   4136: <input type="hidden" name="datatoken"  value="$datatoken" />
1.257     albertel 4137: <input type="hidden" name="fileupload" value="$env{'form.fileupload'}" />
                   4138: <input type="hidden" name="upfiletype" value="$env{'form.upfiletype'}" />
1.26      albertel 4139: <input type="hidden" name="upfile_associate" 
1.257     albertel 4140:                                        value="$env{'form.upfile_associate'}" />
1.26      albertel 4141: <input type="hidden" name="symb"       value="$symb" />
1.246     albertel 4142: <input type="hidden" name="command"    value="csvuploadoptions" />
1.26      albertel 4143: <hr />
                   4144: ENDPICK
1.597     wenzelju 4145:     $request->print(&Apache::lonhtmlcommon::scripttag($javascript));
1.118     ng       4146:     return '';
1.26      albertel 4147: 
                   4148: }
                   4149: 
                   4150: sub csvupload_fields {
1.582     raeburn  4151:     my ($symb,$errorref) = @_;
                   4152:     my (@parts) = &getpartlist($symb,$errorref);
                   4153:     if (ref($errorref)) {
                   4154:         if ($$errorref) {
                   4155:             return;
                   4156:         }
                   4157:     }
                   4158: 
1.556     weissno  4159:     my @fields=(['ID','Student/Employee ID'],
1.243     albertel 4160: 		['username','Student Username'],
                   4161: 		['domain','Student Domain']);
1.324     albertel 4162:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
1.41      ng       4163:     foreach my $part (sort(@parts)) {
                   4164: 	my @datum;
                   4165: 	my $display=&Apache::lonnet::metadata($url,$part.'.display');
                   4166: 	my $name=$part;
                   4167: 	if  (!$display) { $display = $name; }
                   4168: 	@datum=($name,$display);
1.244     albertel 4169: 	if ($name=~/^stores_(.*)_awarded/) {
                   4170: 	    push(@fields,['stores_'.$1.'_points',"Points [Part: $1]"]);
                   4171: 	}
1.41      ng       4172: 	push(@fields,\@datum);
                   4173:     }
                   4174:     return (@fields);
1.26      albertel 4175: }
                   4176: 
                   4177: sub csvuploadmap_footer {
1.41      ng       4178:     my ($request,$i,$keyfields) =@_;
1.703     bisitz   4179:     my $buttontext = &mt('Assign Grades');
1.41      ng       4180:     $request->print(<<ENDPICK);
1.26      albertel 4181: </table>
                   4182: <input type="hidden" name="nfields" value="$i" />
                   4183: <input type="hidden" name="keyfields" value="$keyfields" />
1.703     bisitz   4184: <input type="button" onclick="javascript:verify(this.form)" value="$buttontext" /><br />
1.26      albertel 4185: </form>
                   4186: ENDPICK
                   4187: }
                   4188: 
1.283     albertel 4189: sub checkforfile_js {
1.638     www      4190:     my $alertmsg = &mt('Please use the browse button to select a file from your local directory.');
1.736   ! damieng  4191:     &js_escape(\$alertmsg);
1.597     wenzelju 4192:     my $result = &Apache::lonhtmlcommon::scripttag(<<CSVFORMJS);
1.86      ng       4193:     function checkUpload(formname) {
                   4194: 	if (formname.upfile.value == "") {
1.539     riegler  4195: 	    alert("$alertmsg");
1.86      ng       4196: 	    return false;
                   4197: 	}
                   4198: 	formname.submit();
                   4199:     }
                   4200: CSVFORMJS
1.283     albertel 4201:     return $result;
                   4202: }
                   4203: 
                   4204: sub upcsvScores_form {
1.608     www      4205:     my ($request,$symb) = @_;
1.283     albertel 4206:     if (!$symb) {return '';}
                   4207:     my $result=&checkforfile_js();
1.632     www      4208:     $result.=&Apache::loncommon::start_data_table().
                   4209:              &Apache::loncommon::start_data_table_header_row().
                   4210:              '<th>'.&mt('Specify a file containing the class scores for current resource.').'</th>'.
                   4211:              &Apache::loncommon::end_data_table_header_row().
                   4212:              &Apache::loncommon::start_data_table_row().'<td>';
1.370     www      4213:     my $upload=&mt("Upload Scores");
1.86      ng       4214:     my $upfile_select=&Apache::loncommon::upfile_select_html();
1.245     albertel 4215:     my $ignore=&mt('Ignore First Line');
1.418     albertel 4216:     $symb = &Apache::lonenc::check_encrypt($symb);
1.86      ng       4217:     $result.=<<ENDUPFORM;
1.106     albertel 4218: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
1.86      ng       4219: <input type="hidden" name="symb" value="$symb" />
                   4220: <input type="hidden" name="command" value="csvuploadmap" />
                   4221: $upfile_select
1.589     bisitz   4222: <br /><input type="button" onclick="javascript:checkUpload(this.form);" value="$upload" />
1.86      ng       4223: </form>
                   4224: ENDUPFORM
1.370     www      4225:     $result.=&Apache::loncommon::help_open_topic("Course_Convert_To_CSV",
1.632     www      4226:                            &mt("How do I create a CSV file from a spreadsheet")).
                   4227:              '</td>'.
                   4228:             &Apache::loncommon::end_data_table_row().
                   4229:             &Apache::loncommon::end_data_table();
1.86      ng       4230:     return $result;
                   4231: }
                   4232: 
                   4233: 
1.26      albertel 4234: sub csvuploadmap {
1.608     www      4235:     my ($request,$symb)= @_;
1.41      ng       4236:     if (!$symb) {return '';}
1.72      ng       4237: 
1.41      ng       4238:     my $datatoken;
1.257     albertel 4239:     if (!$env{'form.datatoken'}) {
1.41      ng       4240: 	$datatoken=&Apache::loncommon::upfile_store($request);
1.26      albertel 4241:     } else {
1.257     albertel 4242: 	$datatoken=$env{'form.datatoken'};
1.41      ng       4243: 	&Apache::loncommon::load_tmp_file($request);
1.26      albertel 4244:     }
1.41      ng       4245:     my @records=&Apache::loncommon::upfile_record_sep();
1.324     albertel 4246:     &csvuploadmap_header($request,$symb,$datatoken,$#records+1);
1.41      ng       4247:     my ($i,$keyfields);
                   4248:     if (@records) {
1.582     raeburn  4249:         my $fieldserror;
                   4250: 	my @fields=&csvupload_fields($symb,\$fieldserror);
                   4251:         if ($fieldserror) {
                   4252:             $request->print(&navmap_errormsg());
                   4253:             return;
                   4254:         }
1.257     albertel 4255: 	if ($env{'form.upfile_associate'} eq 'reverse') {	
1.41      ng       4256: 	    &Apache::loncommon::csv_print_samples($request,\@records);
                   4257: 	    $i=&Apache::loncommon::csv_print_select_table($request,\@records,
                   4258: 							  \@fields);
                   4259: 	    foreach (@fields) { $keyfields.=$_->[0].','; }
                   4260: 	    chop($keyfields);
                   4261: 	} else {
                   4262: 	    unshift(@fields,['none','']);
                   4263: 	    $i=&Apache::loncommon::csv_samples_select_table($request,\@records,
                   4264: 							    \@fields);
1.311     banghart 4265:             foreach my $rec (@records) {
                   4266:                 my %temp = &Apache::loncommon::record_sep($rec);
                   4267:                 if (%temp) {
                   4268:                     $keyfields=join(',',sort(keys(%temp)));
                   4269:                     last;
                   4270:                 }
                   4271:             }
1.41      ng       4272: 	}
                   4273:     }
                   4274:     &csvuploadmap_footer($request,$i,$keyfields);
1.72      ng       4275: 
1.41      ng       4276:     return '';
1.27      albertel 4277: }
                   4278: 
1.246     albertel 4279: sub csvuploadoptions {
1.608     www      4280:     my ($request,$symb)= @_;
1.632     www      4281:     my $overwrite=&mt('Overwrite any existing score');
1.246     albertel 4282:     $request->print(<<ENDPICK);
                   4283: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
                   4284: <input type="hidden" name="command"    value="csvuploadassign" />
                   4285: <p>
                   4286: <label>
                   4287:    <input type="checkbox" name="overwite_scores" checked="checked" />
1.632     www      4288:    $overwrite
1.246     albertel 4289: </label>
                   4290: </p>
                   4291: ENDPICK
                   4292:     my %fields=&get_fields();
                   4293:     if (!defined($fields{'domain'})) {
1.257     albertel 4294: 	my $domform = &Apache::loncommon::select_dom_form($env{'request.role.domain'},'default_domain');
1.632     www      4295: 	$request->print("\n<p>".&mt('Users are in domain: [_1]',$domform)."</p>\n");
1.246     albertel 4296:     }
1.257     albertel 4297:     foreach my $key (sort(keys(%env))) {
1.246     albertel 4298: 	if ($key !~ /^form\.(.*)$/) { next; }
                   4299: 	my $cleankey=$1;
                   4300: 	if ($cleankey eq 'command') { next; }
                   4301: 	$request->print('<input type="hidden" name="'.$cleankey.
1.257     albertel 4302: 			'"  value="'.$env{$key}.'" />'."\n");
1.246     albertel 4303:     }
                   4304:     # FIXME do a check for any duplicated user ids...
                   4305:     # FIXME do a check for any invalid user ids?...
1.703     bisitz   4306:     $request->print('<input type="submit" value="'.&mt('Assign Grades').'" /><br />
1.290     albertel 4307: <hr /></form>'."\n");
1.246     albertel 4308:     return '';
                   4309: }
                   4310: 
                   4311: sub get_fields {
                   4312:     my %fields;
1.257     albertel 4313:     my @keyfields = split(/\,/,$env{'form.keyfields'});
                   4314:     for (my $i=0; $i<=$env{'form.nfields'}; $i++) {
                   4315: 	if ($env{'form.upfile_associate'} eq 'reverse') {
                   4316: 	    if ($env{'form.f'.$i} ne 'none') {
                   4317: 		$fields{$keyfields[$i]}=$env{'form.f'.$i};
1.41      ng       4318: 	    }
                   4319: 	} else {
1.257     albertel 4320: 	    if ($env{'form.f'.$i} ne 'none') {
                   4321: 		$fields{$env{'form.f'.$i}}=$keyfields[$i];
1.41      ng       4322: 	    }
                   4323: 	}
1.27      albertel 4324:     }
1.246     albertel 4325:     return %fields;
                   4326: }
                   4327: 
                   4328: sub csvuploadassign {
1.608     www      4329:     my ($request,$symb)= @_;
1.246     albertel 4330:     if (!$symb) {return '';}
1.345     bowersj2 4331:     my $error_msg = '';
1.246     albertel 4332:     &Apache::loncommon::load_tmp_file($request);
                   4333:     my @gradedata = &Apache::loncommon::upfile_record_sep();
                   4334:     my %fields=&get_fields();
1.257     albertel 4335:     my $courseid=$env{'request.course.id'};
1.97      albertel 4336:     my ($classlist) = &getclasslist('all',0);
1.106     albertel 4337:     my @notallowed;
1.41      ng       4338:     my @skipped;
1.657     raeburn  4339:     my @warnings;
1.41      ng       4340:     my $countdone=0;
                   4341:     foreach my $grade (@gradedata) {
                   4342: 	my %entries=&Apache::loncommon::record_sep($grade);
1.246     albertel 4343: 	my $domain;
                   4344: 	if ($entries{$fields{'domain'}}) {
                   4345: 	    $domain=$entries{$fields{'domain'}};
                   4346: 	} else {
1.257     albertel 4347: 	    $domain=$env{'form.default_domain'};
1.246     albertel 4348: 	}
1.243     albertel 4349: 	$domain=~s/\s//g;
1.41      ng       4350: 	my $username=$entries{$fields{'username'}};
1.160     albertel 4351: 	$username=~s/\s//g;
1.243     albertel 4352: 	if (!$username) {
                   4353: 	    my $id=$entries{$fields{'ID'}};
1.247     albertel 4354: 	    $id=~s/\s//g;
1.243     albertel 4355: 	    my %ids=&Apache::lonnet::idget($domain,$id);
                   4356: 	    $username=$ids{$id};
                   4357: 	}
1.41      ng       4358: 	if (!exists($$classlist{"$username:$domain"})) {
1.247     albertel 4359: 	    my $id=$entries{$fields{'ID'}};
                   4360: 	    $id=~s/\s//g;
                   4361: 	    if ($id) {
                   4362: 		push(@skipped,"$id:$domain");
                   4363: 	    } else {
                   4364: 		push(@skipped,"$username:$domain");
                   4365: 	    }
1.41      ng       4366: 	    next;
                   4367: 	}
1.108     albertel 4368: 	my $usec=$classlist->{"$username:$domain"}[5];
1.106     albertel 4369: 	if (!&canmodify($usec)) {
                   4370: 	    push(@notallowed,"$username:$domain");
                   4371: 	    next;
                   4372: 	}
1.244     albertel 4373: 	my %points;
1.41      ng       4374: 	my %grades;
                   4375: 	foreach my $dest (keys(%fields)) {
1.244     albertel 4376: 	    if ($dest eq 'ID' || $dest eq 'username' ||
                   4377: 		$dest eq 'domain') { next; }
                   4378: 	    if ($entries{$fields{$dest}} =~ /^\s*$/) { next; }
                   4379: 	    if ($dest=~/stores_(.*)_points/) {
                   4380: 		my $part=$1;
                   4381: 		my $wgt =&Apache::lonnet::EXT('resource.'.$part.'.weight',
                   4382: 					      $symb,$domain,$username);
1.345     bowersj2 4383:                 if ($wgt) {
                   4384:                     $entries{$fields{$dest}}=~s/\s//g;
                   4385:                     my $pcr=$entries{$fields{$dest}} / $wgt;
1.463     albertel 4386:                     my $award=($pcr == 0) ? 'incorrect_by_override'
                   4387:                                           : 'correct_by_override';
1.638     www      4388:                     if ($pcr>1) {
1.657     raeburn  4389:                        push(@warnings,&mt("[_1]: point value larger than weight","$username:$domain"));
1.638     www      4390:                     }
1.345     bowersj2 4391:                     $grades{"resource.$part.awarded"}=$pcr;
                   4392:                     $grades{"resource.$part.solved"}=$award;
                   4393:                     $points{$part}=1;
                   4394:                 } else {
                   4395:                     $error_msg = "<br />" .
                   4396:                         &mt("Some point values were assigned"
                   4397:                             ." for problems with a weight "
                   4398:                             ."of zero. These values were "
                   4399:                             ."ignored.");
                   4400:                 }
1.244     albertel 4401: 	    } else {
                   4402: 		if ($dest=~/stores_(.*)_awarded/) { if ($points{$1}) {next;} }
                   4403: 		if ($dest=~/stores_(.*)_solved/)  { if ($points{$1}) {next;} }
                   4404: 		my $store_key=$dest;
                   4405: 		$store_key=~s/^stores/resource/;
                   4406: 		$store_key=~s/_/\./g;
                   4407: 		$grades{$store_key}=$entries{$fields{$dest}};
                   4408: 	    }
1.41      ng       4409: 	}
1.508     www      4410: 	if (! %grades) { 
                   4411:            push(@skipped,&mt("[_1]: no data to save","$username:$domain")); 
                   4412:         } else {
                   4413: 	   $grades{"resource.regrader"}="$env{'user.name'}:$env{'user.domain'}";
                   4414: 	   my $result=&Apache::lonnet::cstore(\%grades,$symb,
1.302     albertel 4415: 					   $env{'request.course.id'},
                   4416: 					   $domain,$username);
1.508     www      4417: 	   if ($result eq 'ok') {
1.627     www      4418: # Successfully stored
1.508     www      4419: 	      $request->print('.');
1.627     www      4420: # Remove from grading queue
                   4421:               &Apache::bridgetask::remove_from_queue('gradingqueue',$symb,
                   4422:                                              $env{'course.'.$env{'request.course.id'}.'.domain'},
                   4423:                                              $env{'course.'.$env{'request.course.id'}.'.num'},
                   4424:                                              $domain,$username);
                   4425:               $countdone++;
                   4426:            } else {
1.508     www      4427: 	      $request->print("<p><span class=\"LC_error\">".
                   4428:                               &mt("Failed to save data for student [_1]. Message when trying to save was: [_2]",
                   4429:                                   "$username:$domain",$result)."</span></p>");
                   4430: 	   }
                   4431: 	   $request->rflush();
                   4432:         }
1.41      ng       4433:     }
1.570     www      4434:     $request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt("Saved scores for [quant,_1,student]",$countdone),$countdone==0));
1.657     raeburn  4435:     if (@warnings) {
                   4436:         $request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt('Warnings generated for the following saved scores:'),1).'<br />');
                   4437:         $request->print(join(', ',@warnings));
                   4438:     }
1.41      ng       4439:     if (@skipped) {
1.571     www      4440: 	$request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt('No scores stored for the following username(s):'),1).'<br />');
                   4441:         $request->print(join(', ',@skipped));
1.106     albertel 4442:     }
                   4443:     if (@notallowed) {
1.571     www      4444: 	$request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt('Modification of scores not allowed for the following username(s):'),1).'<br />');
                   4445: 	$request->print(join(', ',@notallowed));
1.41      ng       4446:     }
1.106     albertel 4447:     $request->print("<br />\n");
1.345     bowersj2 4448:     return $error_msg;
1.26      albertel 4449: }
1.44      ng       4450: #------------- end of section for handling csv file upload ---------
                   4451: #
                   4452: #-------------------------------------------------------------------
                   4453: #
1.122     ng       4454: #-------------- Next few routines handle grading by page/sequence
1.72      ng       4455: #
                   4456: #--- Select a page/sequence and a student to grade
1.68      ng       4457: sub pickStudentPage {
1.608     www      4458:     my ($request,$symb) = @_;
1.68      ng       4459: 
1.539     riegler  4460:     my $alertmsg = &mt('Please select the student you wish to grade.');
1.736   ! damieng  4461:     &js_escape(\$alertmsg);
1.597     wenzelju 4462:     $request->print(&Apache::lonhtmlcommon::scripttag(<<LISTJAVASCRIPT));
1.68      ng       4463: 
                   4464: function checkPickOne(formname) {
1.76      ng       4465:     if (radioSelection(formname.student) == null) {
1.539     riegler  4466: 	alert("$alertmsg");
1.68      ng       4467: 	return;
                   4468:     }
1.125     ng       4469:     ptr = pullDownSelection(formname.selectpage);
                   4470:     formname.page.value = formname["page"+ptr].value;
                   4471:     formname.title.value = formname["title"+ptr].value;
1.68      ng       4472:     formname.submit();
                   4473: }
                   4474: 
                   4475: LISTJAVASCRIPT
1.118     ng       4476:     &commonJSfunctions($request);
1.608     www      4477: 
1.257     albertel 4478:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
                   4479:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
                   4480:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
1.68      ng       4481: 
1.398     albertel 4482:     my $result='<h3><span class="LC_info">&nbsp;'.
1.485     albertel 4483: 	&mt('Manual Grading by Page or Sequence').'</span></h3>';
1.68      ng       4484: 
1.80      ng       4485:     $result.='<form action="/adm/grades" method="post" name="displayPage">'."\n";
1.582     raeburn  4486:     my $map_error;
                   4487:     my ($titles,$symbx) = &getSymbMap($map_error);
                   4488:     if ($map_error) {
                   4489:         $request->print(&navmap_errormsg());
                   4490:         return; 
                   4491:     }
1.137     albertel 4492:     my ($curpage) =&Apache::lonnet::decode_symb($symb); 
                   4493: #    my ($curpage,$mapId) =&Apache::lonnet::decode_symb($symb); 
                   4494: #    my $type=($curpage =~ /\.(page|sequence)/);
1.700     bisitz   4495: 
                   4496:     # Collection of hidden fields
1.70      ng       4497:     my $ctr=0;
1.68      ng       4498:     foreach (@$titles) {
1.700     bisitz   4499:         my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
                   4500:         $result.='<input type="hidden" name="page'.$ctr.'" value="'.$$symbx{$_}.'" />'."\n";
                   4501:         $result.='<input type="hidden" name="title'.$ctr.'" value="'.$showtitle.'" />'."\n";
                   4502:         $ctr++;
1.68      ng       4503:     }
1.700     bisitz   4504:     $result.='<input type="hidden" name="page" />'."\n".
                   4505:         '<input type="hidden" name="title" />'."\n";
                   4506: 
                   4507:     $result.=&build_section_inputs();
                   4508:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
                   4509:     $result.='<input type="hidden" name="Status"  value="'.$stu_status.'" />'."\n".
                   4510: 	'<input type="hidden" name="command" value="displayPage" />'."\n".
                   4511: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
1.485     albertel 4512: 
1.700     bisitz   4513:     # Show grading options
                   4514:     $result.=&Apache::lonhtmlcommon::start_pick_box();
                   4515:     my $select = '<select name="selectpage">'."\n";
1.70      ng       4516:     $ctr=0;
                   4517:     foreach (@$titles) {
                   4518: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
1.700     bisitz   4519: 	$select.='<option value="'.$ctr.'"'.
                   4520: 	    ($$symbx{$_} =~ /$curpage$/ ? ' selected="selected"' : '').
                   4521: 	    '>'.$showtitle.'</option>'."\n";
1.70      ng       4522: 	$ctr++;
                   4523:     }
1.700     bisitz   4524:     $select.= '</select>';
1.68      ng       4525: 
1.700     bisitz   4526:     $result.=
                   4527:         &Apache::lonhtmlcommon::row_title(&mt('Problems from'))
                   4528:        .$select
                   4529:        .&Apache::lonhtmlcommon::row_closure();
                   4530: 
                   4531:     $result.=
                   4532:         &Apache::lonhtmlcommon::row_title(&mt('View Problem Text'))
                   4533:        .'<label><input type="radio" name="vProb" value="no"'
                   4534:            .' checked="checked" /> '.&mt('no').' </label>'."\n"
                   4535:        .'<label><input type="radio" name="vProb" value="yes" />'
                   4536:            .&mt('yes').'</label>'."\n"
                   4537:        .&Apache::lonhtmlcommon::row_closure();
                   4538: 
                   4539:     $result.=
                   4540:         &Apache::lonhtmlcommon::row_title(&mt('View Submissions'))
                   4541:        .'<label><input type="radio" name="lastSub" value="none" /> '
                   4542:            .&mt('none').' </label>'."\n"
                   4543:        .'<label><input type="radio" name="lastSub" value="datesub"'
                   4544:            .' checked="checked" /> '.&mt('all submissions').'</label>'."\n"
                   4545:        .'<label><input type="radio" name="lastSub" value="all" /> '
                   4546:            .&mt('all submissions with details').' </label>'
                   4547:        .&Apache::lonhtmlcommon::row_closure();
1.432     banghart 4548:     
1.700     bisitz   4549:     $result.=
                   4550:         &Apache::lonhtmlcommon::row_title(&mt('Use CODE'))
                   4551:        .'<input type="text" name="CODE" value="" />'
                   4552:        .&Apache::lonhtmlcommon::row_closure(1)
                   4553:        .&Apache::lonhtmlcommon::end_pick_box();
1.382     albertel 4554: 
1.700     bisitz   4555:     # Show list of students to select for grading
                   4556:     $result.='<br /><input type="button" '.
1.589     bisitz   4557:              'onclick="javascript:checkPickOne(this.form);" value="'.&mt('Next').' &rarr;" /><br />'."\n";
1.72      ng       4558: 
1.68      ng       4559:     $request->print($result);
                   4560: 
1.485     albertel 4561:     my $studentTable.='&nbsp;<b>'.&mt('Select a student you wish to grade and then click on the Next button.').'</b><br />'.
1.484     albertel 4562: 	&Apache::loncommon::start_data_table().
                   4563: 	&Apache::loncommon::start_data_table_header_row().
1.485     albertel 4564: 	'<th align="right">&nbsp;'.&mt('No.').'</th>'.
1.484     albertel 4565: 	'<th>'.&nameUserString('header').'</th>'.
1.485     albertel 4566: 	'<th align="right">&nbsp;'.&mt('No.').'</th>'.
1.484     albertel 4567: 	'<th>'.&nameUserString('header').'</th>'.
                   4568: 	&Apache::loncommon::end_data_table_header_row();
1.68      ng       4569:  
1.76      ng       4570:     my (undef,undef,$fullname) = &getclasslist($getsec,'1');
1.68      ng       4571:     my $ptr = 1;
1.294     albertel 4572:     foreach my $student (sort 
                   4573: 			 {
                   4574: 			     if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                   4575: 				 return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                   4576: 			     }
                   4577: 			     return $a cmp $b;
                   4578: 			 } (keys(%$fullname))) {
1.68      ng       4579: 	my ($uname,$udom) = split(/:/,$student);
1.484     albertel 4580: 	$studentTable.=($ptr%2==1 ? &Apache::loncommon::start_data_table_row()
                   4581:                                   : '</td>');
1.126     ng       4582: 	$studentTable.='<td align="right">'.$ptr.'&nbsp;</td>';
1.288     albertel 4583: 	$studentTable.='<td>&nbsp;<label><input type="radio" name="student" value="'.$student.'" /> '
                   4584: 	    .&nameUserString(undef,$$fullname{$student},$uname,$udom)."</label>\n";
1.484     albertel 4585: 	$studentTable.=
                   4586: 	    ($ptr%2 == 0 ? '</td>'.&Apache::loncommon::end_data_table_row() 
                   4587:                          : '');
1.68      ng       4588: 	$ptr++;
                   4589:     }
1.484     albertel 4590:     if ($ptr%2 == 0) {
                   4591: 	$studentTable.='</td><td>&nbsp;</td><td>&nbsp;</td>'.
                   4592: 	    &Apache::loncommon::end_data_table_row();
                   4593:     }
                   4594:     $studentTable.=&Apache::loncommon::end_data_table()."\n";
1.126     ng       4595:     $studentTable.='<input type="button" '.
1.589     bisitz   4596:                    'onclick="javascript:checkPickOne(this.form);" value="'.&mt('Next').' &rarr;" /></form>'."\n";
1.68      ng       4597: 
                   4598:     $request->print($studentTable);
                   4599: 
                   4600:     return '';
                   4601: }
                   4602: 
                   4603: sub getSymbMap {
1.582     raeburn  4604:     my ($map_error) = @_;
1.132     bowersj2 4605:     my $navmap = Apache::lonnavmaps::navmap->new();
1.582     raeburn  4606:     unless (ref($navmap)) {
                   4607:         if (ref($map_error)) {
                   4608:             $$map_error = 'navmap';
                   4609:         }
                   4610:         return;
                   4611:     }
1.68      ng       4612:     my %symbx = ();
                   4613:     my @titles = ();
1.117     bowersj2 4614:     my $minder = 0;
                   4615: 
                   4616:     # Gather every sequence that has problems.
1.240     albertel 4617:     my @sequences = $navmap->retrieveResources(undef, sub { shift->is_map(); },
                   4618: 					       1,0,1);
1.117     bowersj2 4619:     for my $sequence ($navmap->getById('0.0'), @sequences) {
1.241     albertel 4620: 	if ($navmap->hasResource($sequence, sub { shift->is_problem(); }, 0) ) {
1.381     albertel 4621: 	    my $title = $minder.'.'.
                   4622: 		&HTML::Entities::encode($sequence->compTitle(),'"\'&');
                   4623: 	    push(@titles, $title); # minder in case two titles are identical
                   4624: 	    $symbx{$title} = &HTML::Entities::encode($sequence->symb(),'"\'&');
1.117     bowersj2 4625: 	    $minder++;
1.241     albertel 4626: 	}
1.68      ng       4627:     }
                   4628:     return \@titles,\%symbx;
                   4629: }
                   4630: 
1.72      ng       4631: #
                   4632: #--- Displays a page/sequence w/wo problems, w/wo submissions
1.68      ng       4633: sub displayPage {
1.608     www      4634:     my ($request,$symb) = @_;
1.257     albertel 4635:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
                   4636:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
                   4637:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
                   4638:     my $pageTitle = $env{'form.page'};
1.103     albertel 4639:     my ($classlist,undef,$fullname) = &getclasslist($getsec,'1');
1.257     albertel 4640:     my ($uname,$udom) = split(/:/,$env{'form.student'});
                   4641:     my $usec=$classlist->{$env{'form.student'}}[5];
1.168     albertel 4642: 
                   4643:     #need to make sure we have the correct data for later EXT calls, 
                   4644:     #thus invalidate the cache
                   4645:     &Apache::lonnet::devalidatecourseresdata(
1.257     albertel 4646:                  $env{'course.'.$env{'request.course.id'}.'.num'},
                   4647:                  $env{'course.'.$env{'request.course.id'}.'.domain'});
1.168     albertel 4648:     &Apache::lonnet::clear_EXT_cache_status();
                   4649: 
1.103     albertel 4650:     if (!&canview($usec)) {
1.712     bisitz   4651:         $request->print(
                   4652:             '<span class="LC_warning">'.
                   4653:             &mt('Unable to view requested student. ([_1])',
                   4654:                     $env{'form.student'}).
                   4655:             '</span>');
                   4656:         return;
1.103     albertel 4657:     }
1.398     albertel 4658:     my $result='<h3><span class="LC_info">&nbsp;'.$env{'form.title'}.'</span></h3>';
1.485     albertel 4659:     $result.='<h3>&nbsp;'.&mt('Student: [_1]',&nameUserString(undef,$$fullname{$env{'form.student'}},$uname,$udom)).
1.129     ng       4660: 	'</h3>'."\n";
1.500     albertel 4661:     $env{'form.CODE'} = uc($env{'form.CODE'});
1.501     foxr     4662:     if (&Apache::lonnet::validCODE(uc($env{'form.CODE'}))) {
1.485     albertel 4663: 	$result.='<h3>&nbsp;'.&mt('CODE: [_1]',$env{'form.CODE'}).'</h3>'."\n";
1.382     albertel 4664:     } else {
                   4665: 	delete($env{'form.CODE'});
                   4666:     }
1.71      ng       4667:     &sub_page_js($request);
                   4668:     $request->print($result);
                   4669: 
1.132     bowersj2 4670:     my $navmap = Apache::lonnavmaps::navmap->new();
1.582     raeburn  4671:     unless (ref($navmap)) {
                   4672:         $request->print(&navmap_errormsg());
                   4673:         return;
                   4674:     }
1.257     albertel 4675:     my ($mapUrl, $id, $resUrl)=&Apache::lonnet::decode_symb($env{'form.page'});
1.68      ng       4676:     my $map = $navmap->getResourceByUrl($resUrl); # add to navmaps
1.288     albertel 4677:     if (!$map) {
1.485     albertel 4678: 	$request->print('<span class="LC_warning">'.&mt('Unable to view requested sequence. ([_1])',$resUrl).'</span>');
1.288     albertel 4679: 	return; 
                   4680:     }
1.68      ng       4681:     my $iterator = $navmap->getIterator($map->map_start(),
                   4682: 					$map->map_finish());
                   4683: 
1.71      ng       4684:     my $studentTable='<form action="/adm/grades" method="post" name="gradePage">'."\n".
1.72      ng       4685: 	'<input type="hidden" name="command" value="gradeByPage" />'."\n".
1.257     albertel 4686: 	'<input type="hidden" name="fullname" value="'.$$fullname{$env{'form.student'}}.'" />'."\n".
                   4687: 	'<input type="hidden" name="student" value="'.$env{'form.student'}.'" />'."\n".
1.72      ng       4688: 	'<input type="hidden" name="page"    value="'.$pageTitle.'" />'."\n".
1.257     albertel 4689: 	'<input type="hidden" name="title"   value="'.$env{'form.title'}.'" />'."\n".
1.418     albertel 4690: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.613     www      4691: 	'<input type="hidden" name="overRideScore" value="no" />'."\n";
1.71      ng       4692: 
1.382     albertel 4693:     if (defined($env{'form.CODE'})) {
                   4694: 	$studentTable.=
                   4695: 	    '<input type="hidden" name="CODE" value="'.$env{'form.CODE'}.'" />'."\n";
                   4696:     }
1.381     albertel 4697:     my $checkIcon = '<img alt="'.&mt('Check Mark').
1.485     albertel 4698: 	'" src="'.&Apache::loncommon::lonhttpdurl($request->dir_config('lonIconsURL').'/check.gif').'" height="16" border="0" />';
1.71      ng       4699: 
1.594     bisitz   4700:     $studentTable.='&nbsp;<span class="LC_info">'.
                   4701:         &mt('Problems graded correct by the computer are marked with a [_1] symbol.',$checkIcon).
                   4702:         '</span>'."\n".
1.484     albertel 4703: 	&Apache::loncommon::start_data_table().
                   4704: 	&Apache::loncommon::start_data_table_header_row().
1.700     bisitz   4705: 	'<th>'.&mt('Prob.').'</th>'.
1.485     albertel 4706: 	'<th>&nbsp;'.($env{'form.vProb'} eq 'no' ? &mt('Title') : &mt('Problem Text')).'/'.&mt('Grade').'</th>'.
1.484     albertel 4707: 	&Apache::loncommon::end_data_table_header_row();
1.71      ng       4708: 
1.329     albertel 4709:     &Apache::lonxml::clear_problem_counter();
1.196     albertel 4710:     my ($depth,$question,$prob) = (1,1,1);
1.68      ng       4711:     $iterator->next(); # skip the first BEGIN_MAP
                   4712:     my $curRes = $iterator->next(); # for "current resource"
1.101     albertel 4713:     while ($depth > 0) {
1.68      ng       4714:         if($curRes == $iterator->BEGIN_MAP) { $depth++; }
1.100     bowersj2 4715:         if($curRes == $iterator->END_MAP) { $depth--; }
1.68      ng       4716: 
1.385     albertel 4717:         if (ref($curRes) && $curRes->is_problem()) {
1.91      albertel 4718: 	    my $parts = $curRes->parts();
1.68      ng       4719:             my $title = $curRes->compTitle();
1.71      ng       4720: 	    my $symbx = $curRes->symb();
1.484     albertel 4721: 	    $studentTable.=
                   4722: 		&Apache::loncommon::start_data_table_row().
                   4723: 		'<td align="center" valign="top" >'.$prob.
1.485     albertel 4724: 		(scalar(@{$parts}) == 1 ? '' 
1.681     raeburn  4725: 		                        : '<br />('.&mt('[_1]parts',
                   4726: 							scalar(@{$parts}).'&nbsp;').')'
1.485     albertel 4727: 		 ).
                   4728: 		 '</td>';
1.71      ng       4729: 	    $studentTable.='<td valign="top">';
1.382     albertel 4730: 	    my %form = ('CODE' => $env{'form.CODE'},);
1.257     albertel 4731: 	    if ($env{'form.vProb'} eq 'yes' ) {
1.144     albertel 4732: 		$studentTable.=&show_problem($request,$symbx,$uname,$udom,1,
1.383     albertel 4733: 					     undef,'both',\%form);
1.71      ng       4734: 	    } else {
1.382     albertel 4735: 		my $companswer = &Apache::loncommon::get_student_answers($symbx,$uname,$udom,$env{'request.course.id'},%form);
1.80      ng       4736: 		$companswer =~ s|<form(.*?)>||g;
                   4737: 		$companswer =~ s|</form>||g;
1.71      ng       4738: #		while ($companswer =~ /(<a href\=\"javascript:newWindow.*?Script Vars<\/a>)/s) { #<a href="javascript:newWindow</a>
1.116     ng       4739: #		    $companswer =~ s/$1/ /ms;
1.326     albertel 4740: #		    $request->print('match='.$1."<br />\n");
1.71      ng       4741: #		}
1.116     ng       4742: #		$companswer =~ s|<table border=\"1\">|<table border=\"0\">|g;
1.539     riegler  4743: 		$studentTable.='&nbsp;<b>'.$title.'</b>&nbsp;<br />&nbsp;<b>'.&mt('Correct answer').':</b><br />'.$companswer;
1.71      ng       4744: 	    }
                   4745: 
1.257     albertel 4746: 	    my %record = &Apache::lonnet::restore($symbx,$env{'request.course.id'},$udom,$uname);
1.125     ng       4747: 
1.257     albertel 4748: 	    if ($env{'form.lastSub'} eq 'datesub') {
1.71      ng       4749: 		if ($record{'version'} eq '') {
1.485     albertel 4750: 		    $studentTable.='<br />&nbsp;<span class="LC_warning">'.&mt('No recorded submission for this problem.').'</span><br />';
1.71      ng       4751: 		} else {
1.116     ng       4752: 		    my %responseType = ();
                   4753: 		    foreach my $partid (@{$parts}) {
1.147     albertel 4754: 			my @responseIds =$curRes->responseIds($partid);
                   4755: 			my @responseType =$curRes->responseType($partid);
                   4756: 			my %responseIds;
                   4757: 			for (my $i=0;$i<=$#responseIds;$i++) {
                   4758: 			    $responseIds{$responseIds[$i]}=$responseType[$i];
                   4759: 			}
                   4760: 			$responseType{$partid} = \%responseIds;
1.116     ng       4761: 		    }
1.148     albertel 4762: 		    $studentTable.= &displaySubByDates($symbx,\%record,$parts,\%responseType,$checkIcon,$uname,$udom);
1.147     albertel 4763: 
1.71      ng       4764: 		}
1.257     albertel 4765: 	    } elsif ($env{'form.lastSub'} eq 'all') {
                   4766: 		my $last = ($env{'form.lastSub'} eq 'last' ? 'last' : '');
1.726     raeburn  4767:                 my $identifier = (&canmodify($usec)? $prob : ''); 
1.71      ng       4768: 		$studentTable.=&Apache::loncommon::get_previous_attempt($symbx,$uname,$udom,
1.257     albertel 4769: 									$env{'request.course.id'},
1.726     raeburn  4770: 									'','.submission',undef,
                   4771:                                                                         $usec,$identifier);
1.71      ng       4772:  
                   4773: 	    }
1.103     albertel 4774: 	    if (&canmodify($usec)) {
1.585     bisitz   4775:             $studentTable.=&gradeBox_start();
1.103     albertel 4776: 		foreach my $partid (@{$parts}) {
                   4777: 		    $studentTable.=&gradeBox($request,$symbx,$uname,$udom,$question,$partid,\%record);
                   4778: 		    $studentTable.='<input type="hidden" name="q_'.$question.'" value="'.$partid.'" />'."\n";
                   4779: 		    $question++;
                   4780: 		}
1.585     bisitz   4781:             $studentTable.=&gradeBox_end();
1.196     albertel 4782: 		$prob++;
1.71      ng       4783: 	    }
                   4784: 	    $studentTable.='</td></tr>';
1.68      ng       4785: 
1.103     albertel 4786: 	}
1.68      ng       4787:         $curRes = $iterator->next();
                   4788:     }
                   4789: 
1.589     bisitz   4790:     $studentTable.=
                   4791:         '</table>'."\n".
                   4792:         '<input type="button" value="'.&mt('Save').'" '.
                   4793:         'onclick="javascript:checkSubmitPage(this.form,'.$question.');" />'.
                   4794:         '</form>'."\n";
1.71      ng       4795:     $request->print($studentTable);
                   4796: 
                   4797:     return '';
1.119     ng       4798: }
                   4799: 
                   4800: sub displaySubByDates {
1.148     albertel 4801:     my ($symb,$record,$parts,$responseType,$checkIcon,$uname,$udom) = @_;
1.224     albertel 4802:     my $isCODE=0;
1.335     albertel 4803:     my $isTask = ($symb =~/\.task$/);
1.224     albertel 4804:     if (exists($record->{'resource.CODE'})) { $isCODE=1; }
1.467     albertel 4805:     my $studentTable=&Apache::loncommon::start_data_table().
                   4806: 	&Apache::loncommon::start_data_table_header_row().
                   4807: 	'<th>'.&mt('Date/Time').'</th>'.
                   4808: 	($isCODE?'<th>'.&mt('CODE').'</th>':'').
1.671     raeburn  4809:         ($isTask?'<th>'.&mt('Version').'</th>':'').
1.467     albertel 4810: 	'<th>'.&mt('Submission').'</th>'.
                   4811: 	'<th>'.&mt('Status').'</th>'.
                   4812: 	&Apache::loncommon::end_data_table_header_row();
1.119     ng       4813:     my ($version);
                   4814:     my %mark;
1.148     albertel 4815:     my %orders;
1.119     ng       4816:     $mark{'correct_by_student'} = $checkIcon;
1.147     albertel 4817:     if (!exists($$record{'1:timestamp'})) {
1.539     riegler  4818: 	return '<br />&nbsp;<span class="LC_warning">'.&mt('Nothing submitted - no attempts.').'</span><br />';
1.147     albertel 4819:     }
1.335     albertel 4820: 
                   4821:     my $interaction;
1.525     raeburn  4822:     my $no_increment = 1;
1.735     raeburn  4823:     my (%lastrndseed,%lasttype);
1.119     ng       4824:     for ($version=1;$version<=$$record{'version'};$version++) {
1.467     albertel 4825: 	my $timestamp = 
                   4826: 	    &Apache::lonlocal::locallocaltime($$record{$version.':timestamp'});
1.335     albertel 4827: 	if (exists($$record{$version.':resource.0.version'})) {
                   4828: 	    $interaction = $$record{$version.':resource.0.version'};
                   4829: 	}
1.671     raeburn  4830:         if ($isTask && $env{'form.previousversion'}) {
                   4831:             next unless ($interaction == $env{'form.previousversion'});
                   4832:         }
1.335     albertel 4833: 	my $where = ($isTask ? "$version:resource.$interaction"
                   4834: 		             : "$version:resource");
1.467     albertel 4835: 	$studentTable.=&Apache::loncommon::start_data_table_row().
                   4836: 	    '<td>'.$timestamp.'</td>';
1.224     albertel 4837: 	if ($isCODE) {
                   4838: 	    $studentTable.='<td>'.$record->{$version.':resource.CODE'}.'</td>';
                   4839: 	}
1.671     raeburn  4840:         if ($isTask) {
                   4841:             $studentTable.='<td>'.$interaction.'</td>';
                   4842:         }
1.119     ng       4843: 	my @versionKeys = split(/\:/,$$record{$version.':keys'});
                   4844: 	my @displaySub = ();
                   4845: 	foreach my $partid (@{$parts}) {
1.640     raeburn  4846:             my ($hidden,$type);
                   4847:             $type = $$record{$version.':resource.'.$partid.'.type'};
                   4848:             if (($type eq 'anonsurvey') || ($type eq 'anonsurveycred')) {
1.596     raeburn  4849:                 $hidden = 1;
                   4850:             }
1.335     albertel 4851: 	    my @matchKey = ($isTask ? sort(grep /^resource\.\d+\.\Q$partid\E\.award$/,@versionKeys)
                   4852: 			            : sort(grep /^resource\.\Q$partid\E\..*?\.submission$/,@versionKeys));
                   4853: 	    
1.122     ng       4854: #	    next if ($$record{"$version:resource.$partid.solved"} eq '');
1.324     albertel 4855: 	    my $display_part=&get_display_part($partid,$symb);
1.147     albertel 4856: 	    foreach my $matchKey (@matchKey) {
1.198     albertel 4857: 		if (exists($$record{$version.':'.$matchKey}) &&
                   4858: 		    $$record{$version.':'.$matchKey} ne '') {
1.596     raeburn  4859:                     
1.335     albertel 4860: 		    my ($responseId)= ($isTask ? ($matchKey=~ /^resource\.(.*?)\.\Q$partid\E\.award$/)
                   4861: 				               : ($matchKey=~ /^resource\.\Q$partid\E\.(.*?)\.submission$/));
1.670     raeburn  4862:                     $displaySub[0].='<span class="LC_nobreak">';
1.577     bisitz   4863:                     $displaySub[0].='<b>'.&mt('Part: [_1]',$display_part).'</b>'
                   4864:                                    .' <span class="LC_internal_info">'
1.625     www      4865:                                    .'('.&mt('Response ID: [_1]',$responseId).')'
1.577     bisitz   4866:                                    .'</span>'
                   4867:                                    .' <b>';
1.596     raeburn  4868:                     if ($hidden) {
                   4869:                         $displaySub[0].= &mt('Anonymous Survey').'</b>';
                   4870:                     } else {
1.640     raeburn  4871:                         my ($trial,$rndseed,$newvariation);
                   4872:                         if ($type eq 'randomizetry') {
                   4873:                             $trial = $$record{"$where.$partid.tries"};
1.733     raeburn  4874:                             $rndseed = $$record{"$where.$partid.rndseed"};
1.640     raeburn  4875:                         }
1.596     raeburn  4876: 		        if ($$record{"$where.$partid.tries"} eq '') {
                   4877: 			    $displaySub[0].=&mt('Trial not counted');
                   4878: 		        } else {
                   4879: 			    $displaySub[0].=&mt('Trial: [_1]',
1.467     albertel 4880: 					    $$record{"$where.$partid.tries"});
1.734     raeburn  4881:                             if (($rndseed ne '') && ($lastrndseed{$partid} ne '')) {
1.735     raeburn  4882:                                 if (($rndseed ne $lastrndseed{$partid}) &&
                   4883:                                     (($type eq 'randomizetry') || ($lasttype{$partid} eq 'randomizetry'))) {
1.640     raeburn  4884:                                     $newvariation = '&nbsp;('.&mt('New variation this try').')';
                   4885:                                 }
                   4886:                             }
                   4887:                             $lastrndseed{$partid} = $rndseed;
1.735     raeburn  4888:                             $lasttype{$partid} = $type;
1.596     raeburn  4889: 		        }
                   4890: 		        my $responseType=($isTask ? 'Task'
1.335     albertel 4891:                                               : $responseType->{$partid}->{$responseId});
1.596     raeburn  4892: 		        if (!exists($orders{$partid})) { $orders{$partid}={}; }
1.640     raeburn  4893: 		        if ((!exists($orders{$partid}->{$responseId})) || ($trial)) {
1.596     raeburn  4894: 			    $orders{$partid}->{$responseId}=
                   4895: 			        &get_order($partid,$responseId,$symb,$uname,$udom,
1.640     raeburn  4896:                                            $no_increment,$type,$trial,$rndseed);
1.596     raeburn  4897: 		        }
1.640     raeburn  4898: 		        $displaySub[0].='</b>'.$newvariation.'</span>'; # /nobreak
1.596     raeburn  4899: 		        $displaySub[0].='&nbsp; '.
1.640     raeburn  4900: 			    &cleanRecord($$record{$version.':'.$matchKey},$responseType,$symb,$partid,$responseId,$record,$orders{$partid}->{$responseId},"$version:",$uname,$udom,$type,$trial,$rndseed).'<br />';
1.596     raeburn  4901:                     }
1.147     albertel 4902: 		}
                   4903: 	    }
1.335     albertel 4904: 	    if (exists($$record{"$where.$partid.checkedin"})) {
1.485     albertel 4905: 		$displaySub[1].=&mt('Checked in by [_1] into slot [_2]',
                   4906: 				    $$record{"$where.$partid.checkedin"},
                   4907: 				    $$record{"$where.$partid.checkedin.slot"}).
                   4908: 					'<br />';
1.335     albertel 4909: 	    }
                   4910: 	    if (exists $$record{"$where.$partid.award"}) {
1.485     albertel 4911: 		$displaySub[1].='<b>'.&mt('Part:').'</b>&nbsp;'.$display_part.' &nbsp;'.
1.335     albertel 4912: 		    lc($$record{"$where.$partid.award"}).' '.
                   4913: 		    $mark{$$record{"$where.$partid.solved"}}.
1.147     albertel 4914: 		    '<br />';
                   4915: 	    }
1.335     albertel 4916: 	    if (exists $$record{"$where.$partid.regrader"}) {
                   4917: 		$displaySub[2].=$$record{"$where.$partid.regrader"}.
                   4918: 		    ' (<b>'.&mt('Part').':</b> '.$display_part.')';
                   4919: 	    } elsif ($$record{"$version:resource.$partid.regrader"} =~ /\S/) {
                   4920: 		$displaySub[2].=
                   4921: 		    $$record{"$version:resource.$partid.regrader"}.
1.207     albertel 4922: 		    ' (<b>'.&mt('Part').':</b> '.$display_part.')';
1.147     albertel 4923: 	    }
                   4924: 	}
                   4925: 	# needed because old essay regrader has not parts info
                   4926: 	if (exists $$record{"$version:resource.regrader"}) {
                   4927: 	    $displaySub[2].=$$record{"$version:resource.regrader"};
                   4928: 	}
                   4929: 	$studentTable.='<td>'.$displaySub[0].'&nbsp;</td><td>'.$displaySub[1];
                   4930: 	if ($displaySub[2]) {
1.467     albertel 4931: 	    $studentTable.=&mt('Manually graded by [_1]',$displaySub[2]);
1.147     albertel 4932: 	}
1.467     albertel 4933: 	$studentTable.='&nbsp;</td>'.
                   4934: 	    &Apache::loncommon::end_data_table_row();
1.119     ng       4935:     }
1.467     albertel 4936:     $studentTable.=&Apache::loncommon::end_data_table();
1.119     ng       4937:     return $studentTable;
1.71      ng       4938: }
                   4939: 
                   4940: sub updateGradeByPage {
1.608     www      4941:     my ($request,$symb) = @_;
1.71      ng       4942: 
1.257     albertel 4943:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
                   4944:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
                   4945:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
                   4946:     my $pageTitle = $env{'form.page'};
1.103     albertel 4947:     my ($classlist,undef,$fullname) = &getclasslist($getsec,'1');
1.257     albertel 4948:     my ($uname,$udom) = split(/:/,$env{'form.student'});
                   4949:     my $usec=$classlist->{$env{'form.student'}}[5];
1.103     albertel 4950:     if (!&canmodify($usec)) {
1.526     raeburn  4951: 	$request->print('<span class="LC_warning">'.&mt('Unable to modify requested student ([_1])',$env{'form.student'}).'</span>');
1.103     albertel 4952: 	return;
                   4953:     }
1.398     albertel 4954:     my $result='<h3><span class="LC_info">&nbsp;'.$env{'form.title'}.'</span></h3>';
1.526     raeburn  4955:     $result.='<h3>&nbsp;'.&mt('Student: ').&nameUserString(undef,$env{'form.fullname'},$uname,$udom).
1.129     ng       4956: 	'</h3>'."\n";
1.70      ng       4957: 
1.68      ng       4958:     $request->print($result);
                   4959: 
1.582     raeburn  4960: 
1.132     bowersj2 4961:     my $navmap = Apache::lonnavmaps::navmap->new();
1.582     raeburn  4962:     unless (ref($navmap)) {
                   4963:         $request->print(&navmap_errormsg());
                   4964:         return;
                   4965:     }
1.257     albertel 4966:     my ($mapUrl, $id, $resUrl) = &Apache::lonnet::decode_symb( $env{'form.page'});
1.71      ng       4967:     my $map = $navmap->getResourceByUrl($resUrl); # add to navmaps
1.288     albertel 4968:     if (!$map) {
1.527     raeburn  4969: 	$request->print('<span class="LC_warning">'.&mt('Unable to grade requested sequence ([_1]).',$resUrl).'</span>');
1.288     albertel 4970: 	return; 
                   4971:     }
1.71      ng       4972:     my $iterator = $navmap->getIterator($map->map_start(),
                   4973: 					$map->map_finish());
1.70      ng       4974: 
1.484     albertel 4975:     my $studentTable=
                   4976: 	&Apache::loncommon::start_data_table().
                   4977: 	&Apache::loncommon::start_data_table_header_row().
1.485     albertel 4978: 	'<th align="center">&nbsp;'.&mt('Prob.').'&nbsp;</th>'.
                   4979: 	'<th>&nbsp;'.&mt('Title').'&nbsp;</th>'.
                   4980: 	'<th>&nbsp;'.&mt('Previous Score').'&nbsp;</th>'.
                   4981: 	'<th>&nbsp;'.&mt('New Score').'&nbsp;</th>'.
1.484     albertel 4982: 	&Apache::loncommon::end_data_table_header_row();
1.71      ng       4983: 
                   4984:     $iterator->next(); # skip the first BEGIN_MAP
                   4985:     my $curRes = $iterator->next(); # for "current resource"
1.726     raeburn  4986:     my ($depth,$question,$prob,$changeflag,$hideflag)= (1,1,1,0,0);
1.101     albertel 4987:     while ($depth > 0) {
1.71      ng       4988:         if($curRes == $iterator->BEGIN_MAP) { $depth++; }
1.100     bowersj2 4989:         if($curRes == $iterator->END_MAP) { $depth--; }
1.71      ng       4990: 
1.385     albertel 4991:         if (ref($curRes) && $curRes->is_problem()) {
1.91      albertel 4992: 	    my $parts = $curRes->parts();
1.71      ng       4993:             my $title = $curRes->compTitle();
                   4994: 	    my $symbx = $curRes->symb();
1.484     albertel 4995: 	    $studentTable.=
                   4996: 		&Apache::loncommon::start_data_table_row().
                   4997: 		'<td align="center" valign="top" >'.$prob.
1.485     albertel 4998: 		(scalar(@{$parts}) == 1 ? '' 
1.640     raeburn  4999:                                         : '<br />('.&mt('[quant,_1,part]',scalar(@{$parts}))
1.526     raeburn  5000: 		.')').'</td>';
1.71      ng       5001: 	    $studentTable.='<td valign="top">&nbsp;<b>'.$title.'</b>&nbsp;</td>';
                   5002: 
                   5003: 	    my %newrecord=();
                   5004: 	    my @displayPts=();
1.269     raeburn  5005:             my %aggregate = ();
                   5006:             my $aggregateflag = 0;
1.726     raeburn  5007:             if ($env{'form.HIDE'.$prob}) {
                   5008:                 my %record = &Apache::lonnet::restore($symbx,$env{'request.course.id'},$udom,$uname);
1.727     raeburn  5009:                 my ($version,$parts) = split(/:/,$env{'form.HIDE'.$prob},2);
1.728     raeburn  5010:                 my $numchgs = &makehidden($version,$parts,\%record,$symbx,$udom,$uname,1);
1.726     raeburn  5011:                 $hideflag += $numchgs;
                   5012:             }
1.71      ng       5013: 	    foreach my $partid (@{$parts}) {
1.257     albertel 5014: 		my $newpts = $env{'form.GD_BOX'.$question.'_'.$partid};
                   5015: 		my $oldpts = $env{'form.oldpts'.$question.'_'.$partid};
1.71      ng       5016: 
1.257     albertel 5017: 		my $wgt = $env{'form.WGT'.$question.'_'.$partid} != 0 ? 
                   5018: 		    $env{'form.WGT'.$question.'_'.$partid} : 1;
1.71      ng       5019: 		my $partial = $newpts/$wgt;
                   5020: 		my $score;
                   5021: 		if ($partial > 0) {
                   5022: 		    $score = 'correct_by_override';
1.125     ng       5023: 		} elsif ($newpts ne '') { #empty is taken as 0
1.71      ng       5024: 		    $score = 'incorrect_by_override';
                   5025: 		}
1.257     albertel 5026: 		my $dropMenu = $env{'form.GD_SEL'.$question.'_'.$partid};
1.125     ng       5027: 		if ($dropMenu eq 'excused') {
1.71      ng       5028: 		    $partial = '';
                   5029: 		    $score = 'excused';
1.125     ng       5030: 		} elsif ($dropMenu eq 'reset status'
1.257     albertel 5031: 			 && $env{'form.solved'.$question.'_'.$partid} ne '') { #update only if previous record exists
1.125     ng       5032: 		    $newrecord{'resource.'.$partid.'.tries'} = 0;
                   5033: 		    $newrecord{'resource.'.$partid.'.solved'} = '';
                   5034: 		    $newrecord{'resource.'.$partid.'.award'} = '';
                   5035: 		    $newrecord{'resource.'.$partid.'.awarded'} = 0;
1.257     albertel 5036: 		    $newrecord{'resource.'.$partid.'.regrader'} = "$env{'user.name'}:$env{'user.domain'}";
1.125     ng       5037: 		    $changeflag++;
                   5038: 		    $newpts = '';
1.269     raeburn  5039:                     
                   5040:                     my $aggtries =  $env{'form.aggtries'.$question.'_'.$partid};
                   5041:                     my $totaltries = $env{'form.totaltries'.$question.'_'.$partid};
                   5042:                     my $solvedstatus = $env{'form.solved'.$question.'_'.$partid};
                   5043:                     if ($aggtries > 0) {
                   5044:                         &decrement_aggs($symbx,$partid,\%aggregate,$aggtries,$totaltries,$solvedstatus);
                   5045:                         $aggregateflag = 1;
                   5046:                     }
1.71      ng       5047: 		}
1.324     albertel 5048: 		my $display_part=&get_display_part($partid,$curRes->symb());
1.257     albertel 5049: 		my $oldstatus = $env{'form.solved'.$question.'_'.$partid};
1.526     raeburn  5050: 		$displayPts[0].='&nbsp;<b>'.&mt('Part').':</b> '.$display_part.' = '.
1.71      ng       5051: 		    (($oldstatus eq 'excused') ? 'excused' : $oldpts).
1.326     albertel 5052: 		    '&nbsp;<br />';
1.526     raeburn  5053: 		$displayPts[1].='&nbsp;<b>'.&mt('Part').':</b> '.$display_part.' = '.
1.125     ng       5054: 		     (($score eq 'excused') ? 'excused' : $newpts).
1.326     albertel 5055: 		    '&nbsp;<br />';
1.71      ng       5056: 		$question++;
1.380     albertel 5057: 		next if ($dropMenu eq 'reset status' || ($newpts eq $oldpts && $score ne 'excused'));
1.125     ng       5058: 
1.71      ng       5059: 		$newrecord{'resource.'.$partid.'.awarded'}  = $partial if $partial ne '';
1.125     ng       5060: 		$newrecord{'resource.'.$partid.'.solved'}   = $score if $score ne '';
1.257     albertel 5061: 		$newrecord{'resource.'.$partid.'.regrader'} = "$env{'user.name'}:$env{'user.domain'}"
1.125     ng       5062: 		    if (scalar(keys(%newrecord)) > 0);
1.71      ng       5063: 
                   5064: 		$changeflag++;
                   5065: 	    }
                   5066: 	    if (scalar(keys(%newrecord)) > 0) {
1.382     albertel 5067: 		my %record = 
                   5068: 		    &Apache::lonnet::restore($symbx,$env{'request.course.id'},
                   5069: 					     $udom,$uname);
                   5070: 
                   5071: 		if (&Apache::lonnet::validCODE($env{'form.CODE'})) {
                   5072: 		    $newrecord{'resource.CODE'} = $env{'form.CODE'};
                   5073: 		} elsif (&Apache::lonnet::validCODE($record{'resource.CODE'})) {
                   5074: 		    $newrecord{'resource.CODE'} = '';
                   5075: 		}
1.257     albertel 5076: 		&Apache::lonnet::cstore(\%newrecord,$symbx,$env{'request.course.id'},
1.71      ng       5077: 					$udom,$uname);
1.382     albertel 5078: 		%record = &Apache::lonnet::restore($symbx,
                   5079: 						   $env{'request.course.id'},
                   5080: 						   $udom,$uname);
1.380     albertel 5081: 		&check_and_remove_from_queue($parts,\%record,undef,$symbx,
                   5082: 					     $cdom,$cnum,$udom,$uname);
1.71      ng       5083: 	    }
1.380     albertel 5084: 	    
1.269     raeburn  5085:             if ($aggregateflag) {
                   5086:                 &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
                   5087:                       $env{'course.'.$env{'request.course.id'}.'.domain'},
                   5088:                       $env{'course.'.$env{'request.course.id'}.'.num'});
                   5089:             }
1.125     ng       5090: 
1.71      ng       5091: 	    $studentTable.='<td valign="top">'.$displayPts[0].'</td>'.
                   5092: 		'<td valign="top">'.$displayPts[1].'</td>'.
1.484     albertel 5093: 		&Apache::loncommon::end_data_table_row();
1.68      ng       5094: 
1.196     albertel 5095: 	    $prob++;
1.68      ng       5096: 	}
1.71      ng       5097:         $curRes = $iterator->next();
1.68      ng       5098:     }
1.98      albertel 5099: 
1.484     albertel 5100:     $studentTable.=&Apache::loncommon::end_data_table();
1.526     raeburn  5101:     my $grademsg=($changeflag == 0 ? &mt('No score was changed or updated.') :
                   5102: 		  &mt('The scores were changed for [quant,_1,problem].',
1.726     raeburn  5103: 		  $changeflag).'<br />');
                   5104:     my $hidemsg=($hideflag == 0 ? '' :
                   5105:                  &mt('Submissions were marked "hidden" for [quant,_1,transaction].',
                   5106:                      $hideflag).'<br />');
                   5107:     $request->print($hidemsg.$grademsg.$studentTable);
1.68      ng       5108: 
1.70      ng       5109:     return '';
                   5110: }
                   5111: 
1.72      ng       5112: #-------- end of section for handling grading by page/sequence ---------
                   5113: #
                   5114: #-------------------------------------------------------------------
                   5115: 
1.581     www      5116: #-------------------- Bubblesheet (Scantron) Grading -------------------
1.75      albertel 5117: #
                   5118: #------ start of section for handling grading by page/sequence ---------
                   5119: 
1.423     albertel 5120: =pod
                   5121: 
                   5122: =head1 Bubble sheet grading routines
                   5123: 
1.424     albertel 5124:   For this documentation:
                   5125: 
                   5126:    'scanline' refers to the full line of characters
                   5127:    from the file that we are parsing that represents one entire sheet
                   5128: 
                   5129:    'bubble line' refers to the data
1.659     raeburn  5130:    representing the line of bubbles that are on the physical bubblesheet
1.424     albertel 5131: 
                   5132: 
1.659     raeburn  5133: The overall process is that a scanned in bubblesheet data is uploaded
1.424     albertel 5134: into a course. When a user wants to grade, they select a
1.659     raeburn  5135: sequence/folder of resources, a file of bubblesheet info, and pick
1.424     albertel 5136: one of the predefined configurations for what each scanline looks
                   5137: like.
                   5138: 
                   5139: Next each scanline is checked for any errors of either 'missing
1.435     foxr     5140: bubbles' (it's an error because it may have been mis-scanned
1.424     albertel 5141: because too light bubbling), 'double bubble' (each bubble line should
1.703     bisitz   5142: have no more than one letter picked), invalid or duplicated CODE,
1.556     weissno  5143: invalid student/employee ID
1.424     albertel 5144: 
                   5145: If the CODE option is used that determines the randomization of the
1.556     weissno  5146: homework problems, either way the student/employee ID is looked up into a
1.424     albertel 5147: username:domain.
                   5148: 
                   5149: During the validation phase the instructor can choose to skip scanlines. 
                   5150: 
1.659     raeburn  5151: After the validation phase, there are now 3 bubblesheet files
1.424     albertel 5152: 
                   5153:   scantron_original_filename (unmodified original file)
                   5154:   scantron_corrected_filename (file where the corrected information has replaced the original information)
                   5155:   scantron_skipped_filename (contains the exact text of scanlines that where skipped)
                   5156: 
                   5157: Also there is a separate hash nohist_scantrondata that contains extra
1.659     raeburn  5158: correction information that isn't representable in the bubblesheet
1.424     albertel 5159: file (see &scantron_getfile() for more information)
                   5160: 
                   5161: After all scanlines are either valid, marked as valid or skipped, then
                   5162: foreach line foreach problem in the picked sequence, an ssi request is
                   5163: made that simulates a user submitting their selected letter(s) against
                   5164: the homework problem.
1.423     albertel 5165: 
                   5166: =over 4
                   5167: 
                   5168: 
                   5169: 
                   5170: =item defaultFormData
                   5171: 
                   5172:   Returns html hidden inputs used to hold context/default values.
                   5173: 
                   5174:  Arguments:
                   5175:   $symb - $symb of the current resource 
                   5176: 
                   5177: =cut
1.422     foxr     5178: 
1.81      albertel 5179: sub defaultFormData {
1.324     albertel 5180:     my ($symb)=@_;
1.613     www      5181:     return '<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />';
1.81      albertel 5182: }
                   5183: 
1.447     foxr     5184: 
1.423     albertel 5185: =pod 
                   5186: 
                   5187: =item getSequenceDropDown
                   5188: 
                   5189:    Return html dropdown of possible sequences to grade
                   5190:  
                   5191:  Arguments:
1.582     raeburn  5192:    $symb - $symb of the current resource
                   5193:    $map_error - ref to scalar which will container error if
                   5194:                 $navmap object is unavailable in &getSymbMap().
1.423     albertel 5195: 
                   5196: =cut
1.422     foxr     5197: 
1.75      albertel 5198: sub getSequenceDropDown {
1.582     raeburn  5199:     my ($symb,$map_error)=@_;
1.75      albertel 5200:     my $result='<select name="selectpage">'."\n";
1.582     raeburn  5201:     my ($titles,$symbx) = &getSymbMap($map_error);
                   5202:     if (ref($map_error)) {
                   5203:         return if ($$map_error);
                   5204:     }
1.137     albertel 5205:     my ($curpage)=&Apache::lonnet::decode_symb($symb); 
1.75      albertel 5206:     my $ctr=0;
                   5207:     foreach (@$titles) {
                   5208: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
                   5209: 	$result.='<option value="'.$$symbx{$_}.'" '.
1.401     albertel 5210: 	    ($$symbx{$_} =~ /$curpage$/ ? 'selected="selected"' : '').
1.75      albertel 5211: 	    '>'.$showtitle.'</option>'."\n";
                   5212: 	$ctr++;
                   5213:     }
                   5214:     $result.= '</select>';
                   5215:     return $result;
                   5216: }
                   5217: 
1.495     albertel 5218: my %bubble_lines_per_response;     # no. bubble lines for each response.
1.554     raeburn  5219:                                    # key is zero-based index - 0, 1, 2 ...
1.495     albertel 5220: 
                   5221: my %first_bubble_line;             # First bubble line no. for each bubble.
                   5222: 
1.509     raeburn  5223: my %subdivided_bubble_lines;       # no. bubble lines for optionresponse, 
                   5224:                                    # matchresponse or rankresponse, where 
                   5225:                                    # an individual response can have multiple 
                   5226:                                    # lines
1.503     raeburn  5227: 
                   5228: my %responsetype_per_response;     # responsetype for each response
                   5229: 
1.691     raeburn  5230: my %masterseq_id_responsenum;      # src_id (e.g., 12.3_0.11 etc.) for each
                   5231:                                    # numbered response. Needed when randomorder
                   5232:                                    # or randompick are in use. Key is ID, value 
                   5233:                                    # is response number.
                   5234: 
1.495     albertel 5235: # Save and restore the bubble lines array to the form env.
                   5236: 
                   5237: 
                   5238: sub save_bubble_lines {
                   5239:     foreach my $line (keys(%bubble_lines_per_response)) {
                   5240: 	$env{"form.scantron.bubblelines.$line"}  = $bubble_lines_per_response{$line};
                   5241: 	$env{"form.scantron.first_bubble_line.$line"} =
                   5242: 	    $first_bubble_line{$line};
1.503     raeburn  5243:         $env{"form.scantron.sub_bubblelines.$line"} = 
                   5244:             $subdivided_bubble_lines{$line};
                   5245:         $env{"form.scantron.responsetype.$line"} =
                   5246:             $responsetype_per_response{$line};
1.495     albertel 5247:     }
1.691     raeburn  5248:     foreach my $resid (keys(%masterseq_id_responsenum)) {
                   5249:         my $line = $masterseq_id_responsenum{$resid};
                   5250:         $env{"form.scantron.residpart.$line"} = $resid;
                   5251:     }
1.495     albertel 5252: }
                   5253: 
                   5254: 
                   5255: sub restore_bubble_lines {
                   5256:     my $line = 0;
                   5257:     %bubble_lines_per_response = ();
1.691     raeburn  5258:     %masterseq_id_responsenum = ();
1.495     albertel 5259:     while ($env{"form.scantron.bubblelines.$line"}) {
                   5260: 	my $value = $env{"form.scantron.bubblelines.$line"};
                   5261: 	$bubble_lines_per_response{$line} = $value;
                   5262: 	$first_bubble_line{$line}  =
                   5263: 	    $env{"form.scantron.first_bubble_line.$line"};
1.503     raeburn  5264:         $subdivided_bubble_lines{$line} =
                   5265:             $env{"form.scantron.sub_bubblelines.$line"};
                   5266:         $responsetype_per_response{$line} =
                   5267:             $env{"form.scantron.responsetype.$line"};
1.691     raeburn  5268:         my $id = $env{"form.scantron.residpart.$line"};
                   5269:         $masterseq_id_responsenum{$id} = $line;
1.495     albertel 5270: 	$line++;
                   5271:     }
                   5272: }
                   5273: 
1.423     albertel 5274: =pod 
                   5275: 
                   5276: =item scantron_filenames
                   5277: 
                   5278:    Returns a list of the scantron files in the current course 
                   5279: 
                   5280: =cut
1.422     foxr     5281: 
1.202     albertel 5282: sub scantron_filenames {
1.257     albertel 5283:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   5284:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
1.517     raeburn  5285:     my $getpropath = 1;
1.662     raeburn  5286:     my ($dirlist,$listerror) = &Apache::lonnet::dirlist('userfiles',$cdom,
                   5287:                                                         $cname,$getpropath);
1.202     albertel 5288:     my @possiblenames;
1.662     raeburn  5289:     if (ref($dirlist) eq 'ARRAY') {
                   5290:         foreach my $filename (sort(@{$dirlist})) {
                   5291: 	    ($filename)=split(/&/,$filename);
                   5292: 	    if ($filename!~/^scantron_orig_/) { next ; }
                   5293: 	    $filename=~s/^scantron_orig_//;
                   5294: 	    push(@possiblenames,$filename);
                   5295:         }
1.202     albertel 5296:     }
                   5297:     return @possiblenames;
                   5298: }
                   5299: 
1.423     albertel 5300: =pod 
                   5301: 
                   5302: =item scantron_uploads
                   5303: 
                   5304:    Returns  html drop-down list of scantron files in current course.
                   5305: 
                   5306:  Arguments:
                   5307:    $file2grade - filename to set as selected in the dropdown
                   5308: 
                   5309: =cut
1.422     foxr     5310: 
1.202     albertel 5311: sub scantron_uploads {
1.209     ng       5312:     my ($file2grade) = @_;
1.202     albertel 5313:     my $result=	'<select name="scantron_selectfile">';
                   5314:     $result.="<option></option>";
                   5315:     foreach my $filename (sort(&scantron_filenames())) {
1.401     albertel 5316: 	$result.="<option".($filename eq $file2grade ? ' selected="selected"':'').">$filename</option>\n";
1.81      albertel 5317:     }
                   5318:     $result.="</select>";
                   5319:     return $result;
                   5320: }
                   5321: 
1.423     albertel 5322: =pod 
                   5323: 
                   5324: =item scantron_scantab
                   5325: 
                   5326:   Returns html drop down of the scantron formats in the scantronformat.tab
                   5327:   file.
                   5328: 
                   5329: =cut
1.422     foxr     5330: 
1.82      albertel 5331: sub scantron_scantab {
                   5332:     my $result='<select name="scantron_format">'."\n";
1.191     albertel 5333:     $result.='<option></option>'."\n";
1.518     raeburn  5334:     my @lines = &get_scantronformat_file();
                   5335:     if (@lines > 0) {
                   5336:         foreach my $line (@lines) {
                   5337:             next if (($line =~ /^\#/) || ($line eq ''));
                   5338: 	    my ($name,$descrip)=split(/:/,$line);
                   5339: 	    $result.='<option value="'.$name.'">'.$descrip.'</option>'."\n";
                   5340:         }
1.82      albertel 5341:     }
                   5342:     $result.='</select>'."\n";
1.518     raeburn  5343:     return $result;
                   5344: }
                   5345: 
                   5346: =pod
                   5347: 
                   5348: =item get_scantronformat_file
                   5349: 
                   5350:   Returns an array containing lines from the scantron format file for
                   5351:   the domain of the course.
                   5352: 
                   5353:   If a url for a custom.tab file is listed in domain's configuration.db, 
                   5354:   lines are from this file.
                   5355: 
                   5356:   Otherwise, if a default.tab has been published in RES space by the 
                   5357:   domainconfig user, lines are from this file.
                   5358: 
                   5359:   Otherwise, fall back to getting lines from the legacy file on the
1.519     raeburn  5360:   local server:  /home/httpd/lonTabs/default_scantronformat.tab    
1.82      albertel 5361: 
1.518     raeburn  5362: =cut
                   5363: 
                   5364: sub get_scantronformat_file {
                   5365:     my $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
                   5366:     my %domconfig = &Apache::lonnet::get_dom('configuration',['scantron'],$cdom);
                   5367:     my $gottab = 0;
                   5368:     my @lines;
                   5369:     if (ref($domconfig{'scantron'}) eq 'HASH') {
                   5370:         if ($domconfig{'scantron'}{'scantronformat'} ne '') {
                   5371:             my $formatfile = &Apache::lonnet::getfile($Apache::lonnet::perlvar{'lonDocRoot'}.$domconfig{'scantron'}{'scantronformat'});
                   5372:             if ($formatfile ne '-1') {
                   5373:                 @lines = split("\n",$formatfile,-1);
                   5374:                 $gottab = 1;
                   5375:             }
                   5376:         }
                   5377:     }
                   5378:     if (!$gottab) {
                   5379:         my $confname = $cdom.'-domainconfig';
                   5380:         my $default = $Apache::lonnet::perlvar{'lonDocRoot'}.'/res/'.$cdom.'/'.$confname.'/default.tab';
                   5381:         my $formatfile =  &Apache::lonnet::getfile($default);
                   5382:         if ($formatfile ne '-1') {
                   5383:             @lines = split("\n",$formatfile,-1);
                   5384:             $gottab = 1;
                   5385:         }
                   5386:     }
                   5387:     if (!$gottab) {
1.519     raeburn  5388:         my @domains = &Apache::lonnet::current_machine_domains();
                   5389:         if (grep(/^\Q$cdom\E$/,@domains)) {
                   5390:             my $fh=Apache::File->new($Apache::lonnet::perlvar{'lonTabDir'}.'/scantronformat.tab');
                   5391:             @lines = <$fh>;
                   5392:             close($fh);
                   5393:         } else {
                   5394:             my $fh=Apache::File->new($Apache::lonnet::perlvar{'lonTabDir'}.'/default_scantronformat.tab');
                   5395:             @lines = <$fh>;
                   5396:             close($fh);
                   5397:         }
1.518     raeburn  5398:     }
                   5399:     return @lines;
1.82      albertel 5400: }
                   5401: 
1.423     albertel 5402: =pod 
                   5403: 
                   5404: =item scantron_CODElist
                   5405: 
                   5406:   Returns html drop down of the saved CODE lists from current course,
                   5407:   generated from earlier printings.
                   5408: 
                   5409: =cut
1.422     foxr     5410: 
1.186     albertel 5411: sub scantron_CODElist {
1.257     albertel 5412:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   5413:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
1.186     albertel 5414:     my @names=&Apache::lonnet::getkeys('CODEs',$cdom,$cnum);
                   5415:     my $namechoice='<option></option>';
1.225     albertel 5416:     foreach my $name (sort {uc($a) cmp uc($b)} @names) {
1.191     albertel 5417: 	if ($name =~ /^error: 2 /) { next; }
1.278     albertel 5418: 	if ($name =~ /^type\0/) { next; }
1.186     albertel 5419: 	$namechoice.='<option value="'.$name.'">'.$name.'</option>';
                   5420:     }
                   5421:     $namechoice='<select name="scantron_CODElist">'.$namechoice.'</select>';
                   5422:     return $namechoice;
                   5423: }
                   5424: 
1.423     albertel 5425: =pod 
                   5426: 
                   5427: =item scantron_CODEunique
                   5428: 
                   5429:   Returns the html for "Each CODE to be used once" radio.
                   5430: 
                   5431: =cut
1.422     foxr     5432: 
1.186     albertel 5433: sub scantron_CODEunique {
1.532     bisitz   5434:     my $result='<span class="LC_nobreak">
1.272     albertel 5435:                  <label><input type="radio" name="scantron_CODEunique"
1.423     albertel 5436:                         value="yes" checked="checked" />'.&mt('Yes').' </label>
1.381     albertel 5437:                 </span>
1.532     bisitz   5438:                 <span class="LC_nobreak">
1.272     albertel 5439:                  <label><input type="radio" name="scantron_CODEunique"
1.423     albertel 5440:                         value="no" />'.&mt('No').' </label>
1.381     albertel 5441:                 </span>';
1.186     albertel 5442:     return $result;
                   5443: }
1.423     albertel 5444: 
                   5445: =pod 
                   5446: 
                   5447: =item scantron_selectphase
                   5448: 
1.659     raeburn  5449:   Generates the initial screen to start the bubblesheet process.
1.423     albertel 5450:   Allows for - starting a grading run.
1.424     albertel 5451:              - downloading existing scan data (original, corrected
1.423     albertel 5452:                                                 or skipped info)
                   5453: 
                   5454:              - uploading new scan data
                   5455: 
                   5456:  Arguments:
                   5457:   $r          - The Apache request object
                   5458:   $file2grade - name of the file that contain the scanned data to score
                   5459: 
                   5460: =cut
1.186     albertel 5461: 
1.75      albertel 5462: sub scantron_selectphase {
1.608     www      5463:     my ($r,$file2grade,$symb) = @_;
1.75      albertel 5464:     if (!$symb) {return '';}
1.582     raeburn  5465:     my $map_error;
                   5466:     my $sequence_selector=&getSequenceDropDown($symb,\$map_error);
                   5467:     if ($map_error) {
                   5468:         $r->print('<br />'.&navmap_errormsg().'<br />');
                   5469:         return;
                   5470:     }
1.324     albertel 5471:     my $default_form_data=&defaultFormData($symb);
1.209     ng       5472:     my $file_selector=&scantron_uploads($file2grade);
1.82      albertel 5473:     my $format_selector=&scantron_scantab();
1.186     albertel 5474:     my $CODE_selector=&scantron_CODElist();
                   5475:     my $CODE_unique=&scantron_CODEunique();
1.75      albertel 5476:     my $result;
1.422     foxr     5477: 
1.513     foxr     5478:     $ssi_error = 0;
                   5479: 
1.606     wenzelju 5480:     if (&Apache::lonnet::allowed('usc',$env{'request.role.domain'}) ||
                   5481:         &Apache::lonnet::allowed('usc',$env{'request.course.id'})) {
                   5482: 
                   5483: 	# Chunk of form to prompt for a scantron file upload.
                   5484: 
                   5485:         $r->print('
                   5486:     <br />
                   5487:     '.&Apache::loncommon::start_data_table('LC_scantron_action').'
                   5488:        '.&Apache::loncommon::start_data_table_header_row().'
                   5489:             <th>
                   5490:               &nbsp;'.&mt('Specify a bubblesheet data file to upload.').'
                   5491:             </th>
                   5492:        '.&Apache::loncommon::end_data_table_header_row().'
                   5493:        '.&Apache::loncommon::start_data_table_row().'
                   5494:             <td>
                   5495: ');
1.608     www      5496:     my $default_form_data=&defaultFormData($symb);
1.606     wenzelju 5497:     my $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
                   5498:     my $cnum= $env{'course.'.$env{'request.course.id'}.'.num'};
1.736   ! damieng  5499:     my $alertmsg = &mt('Please use the browse button to select a file from your local directory.');
        !          5500:     &js_escape(\$alertmsg);
1.606     wenzelju 5501:     $r->print(&Apache::lonhtmlcommon::scripttag('
                   5502:     function checkUpload(formname) {
                   5503: 	if (formname.upfile.value == "") {
1.736   ! damieng  5504: 	    alert("'.$alertmsg.'");
1.606     wenzelju 5505: 	    return false;
                   5506: 	}
                   5507: 	formname.submit();
                   5508:     }'));
                   5509:     $r->print('
                   5510:               <form enctype="multipart/form-data" action="/adm/grades" name="rules" method="post">
                   5511:                 '.$default_form_data.'
                   5512:                 <input name="courseid" type="hidden" value="'.$cnum.'" />
                   5513:                 <input name="domainid" type="hidden" value="'.$cdom.'" />
                   5514:                 <input name="command" value="scantronupload_save" type="hidden" />
                   5515:                 '.&mt('File to upload: [_1]','<input type="file" name="upfile" size="50" />').'
                   5516:                 <br />
                   5517:                 <input type="button" onclick="javascript:checkUpload(this.form);" value="'.&mt('Upload Bubblesheet Data').'" />
                   5518:               </form>
                   5519: ');
                   5520: 
                   5521:         $r->print('
                   5522:             </td>
                   5523:        '.&Apache::loncommon::end_data_table_row().'
                   5524:        '.&Apache::loncommon::end_data_table().'
                   5525: ');
                   5526:     }
                   5527: 
1.422     foxr     5528:     # Chunk of form to prompt for a file to grade and how:
                   5529: 
1.489     albertel 5530:     $result.= '
                   5531:     <br />
                   5532:     <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantron_process">
                   5533:     <input type="hidden" name="command" value="scantron_warning" />
                   5534:     '.$default_form_data.'
                   5535:     '.&Apache::loncommon::start_data_table('LC_scantron_action').'
                   5536:        '.&Apache::loncommon::start_data_table_header_row().'
                   5537:             <th colspan="2">
1.492     albertel 5538:               &nbsp;'.&mt('Specify file and which Folder/Sequence to grade').'
1.489     albertel 5539:             </th>
                   5540:        '.&Apache::loncommon::end_data_table_header_row().'
                   5541:        '.&Apache::loncommon::start_data_table_row().'
1.492     albertel 5542:             <td> '.&mt('Sequence to grade:').' </td><td> '.$sequence_selector.' </td>
1.489     albertel 5543:        '.&Apache::loncommon::end_data_table_row().'
                   5544:        '.&Apache::loncommon::start_data_table_row().'
1.572     www      5545:             <td> '.&mt('Filename of bubblesheet data file:').' </td><td> '.$file_selector.' </td>
1.489     albertel 5546:        '.&Apache::loncommon::end_data_table_row().'
                   5547:        '.&Apache::loncommon::start_data_table_row().'
1.572     www      5548:             <td> '.&mt('Format of bubblesheet data file:').' </td><td> '.$format_selector.' </td>
1.489     albertel 5549:        '.&Apache::loncommon::end_data_table_row().'
                   5550:        '.&Apache::loncommon::start_data_table_row().'
1.492     albertel 5551:             <td> '.&mt('Saved CODEs to validate against:').' </td><td> '.$CODE_selector.' </td>
1.489     albertel 5552:        '.&Apache::loncommon::end_data_table_row().'
                   5553:        '.&Apache::loncommon::start_data_table_row().'
1.492     albertel 5554:             <td> '.&mt('Each CODE is only to be used once:').'</td><td> '.$CODE_unique.' </td>
1.489     albertel 5555:        '.&Apache::loncommon::end_data_table_row().'
                   5556:        '.&Apache::loncommon::start_data_table_row().'
1.492     albertel 5557: 	    <td> '.&mt('Options:').' </td>
1.187     albertel 5558:             <td>
1.492     albertel 5559: 	       <label><input type="checkbox" name="scantron_options_redo" value="redo_skipped"/> '.&mt('Do only previously skipped records').'</label> <br />
                   5560:                <label><input type="checkbox" name="scantron_options_ignore" value="ignore_corrections"/> '.&mt('Remove all existing corrections').'</label> <br />
                   5561:                <label><input type="checkbox" name="scantron_options_hidden" value="ignore_hidden"/> '.&mt('Skip hidden resources when grading').'</label>
1.187     albertel 5562: 	    </td>
1.489     albertel 5563:        '.&Apache::loncommon::end_data_table_row().'
                   5564:        '.&Apache::loncommon::start_data_table_row().'
1.174     albertel 5565:             <td colspan="2">
1.572     www      5566:               <input type="submit" value="'.&mt('Grading: Validate Bubblesheet Records').'" />
1.162     albertel 5567:             </td>
1.489     albertel 5568:        '.&Apache::loncommon::end_data_table_row().'
                   5569:     '.&Apache::loncommon::end_data_table().'
                   5570:     </form>
                   5571: ';
1.162     albertel 5572:    
                   5573:     $r->print($result);
                   5574: 
1.422     foxr     5575: 
                   5576: 
                   5577:     # Chunk of the form that prompts to view a scoring office file,
                   5578:     # corrected file, skipped records in a file.
                   5579: 
1.489     albertel 5580:     $r->print('
                   5581:    <br />
                   5582:    <form action="/adm/grades" name="scantron_download">
                   5583:      '.$default_form_data.'
                   5584:      <input type="hidden" name="command" value="scantron_download" />
                   5585:      '.&Apache::loncommon::start_data_table('LC_scantron_action').'
                   5586:        '.&Apache::loncommon::start_data_table_header_row().'
                   5587:               <th>
1.492     albertel 5588:                 &nbsp;'.&mt('Download a scoring office file').'
1.489     albertel 5589:               </th>
                   5590:        '.&Apache::loncommon::end_data_table_header_row().'
                   5591:        '.&Apache::loncommon::start_data_table_row().'
1.492     albertel 5592:               <td> '.&mt('Filename of scoring office file: [_1]',$file_selector).' 
1.489     albertel 5593:                 <br />
1.492     albertel 5594:                 <input type="submit" value="'.&mt('Download: Show List of Associated Files').'" />
1.489     albertel 5595:        '.&Apache::loncommon::end_data_table_row().'
                   5596:      '.&Apache::loncommon::end_data_table().'
                   5597:    </form>
                   5598:    <br />
                   5599: ');
1.162     albertel 5600: 
1.457     banghart 5601:     &Apache::lonpickcode::code_list($r,2);
1.523     raeburn  5602: 
1.694     bisitz   5603:     $r->print('<br /><form method="post" name="checkscantron" action="">'.
1.523     raeburn  5604:              $default_form_data."\n".
                   5605:              &Apache::loncommon::start_data_table('LC_scantron_action')."\n".
                   5606:              &Apache::loncommon::start_data_table_header_row()."\n".
                   5607:              '<th colspan="2">
1.572     www      5608:               &nbsp;'.&mt('Review bubblesheet data and submissions for a previously graded folder/sequence')."\n".
1.523     raeburn  5609:              '</th>'."\n".
                   5610:               &Apache::loncommon::end_data_table_header_row()."\n".
                   5611:               &Apache::loncommon::start_data_table_row()."\n".
                   5612:               '<td> '.&mt('Graded folder/sequence:').' </td>'."\n".
                   5613:               '<td> '.$sequence_selector.' </td>'.
                   5614:               &Apache::loncommon::end_data_table_row()."\n".
                   5615:               &Apache::loncommon::start_data_table_row()."\n".
                   5616:               '<td> '.&mt('Filename of scoring office file:').' </td>'."\n".
                   5617:               '<td> '.$file_selector.' </td>'."\n".
                   5618:               &Apache::loncommon::end_data_table_row()."\n".
                   5619:               &Apache::loncommon::start_data_table_row()."\n".
                   5620:               '<td> '.&mt('Format of data file:').' </td>'."\n".
                   5621:               '<td> '.$format_selector.' </td>'."\n".
                   5622:               &Apache::loncommon::end_data_table_row()."\n".
                   5623:               &Apache::loncommon::start_data_table_row()."\n".
1.557     raeburn  5624:               '<td> '.&mt('Options').' </td>'."\n".
                   5625:               '<td> <label><input type="checkbox" name="scantron_options_hidden" value="ignore_hidden"/> '.&mt('Skip hidden resources').'</label></td>'.
                   5626:               &Apache::loncommon::end_data_table_row()."\n".
                   5627:               &Apache::loncommon::start_data_table_row()."\n".
1.523     raeburn  5628:               '<td colspan="2">'."\n".
                   5629:               '<input type="hidden" name="command" value="checksubmissions" />'."\n".
1.575     www      5630:               '<input type="submit" value="'.&mt('Review Bubblesheet Data and Submission Records').'" />'."\n".
1.523     raeburn  5631:               '</td>'."\n".
                   5632:               &Apache::loncommon::end_data_table_row()."\n".
                   5633:               &Apache::loncommon::end_data_table()."\n".
                   5634:               '</form><br />');
                   5635:     return;
1.75      albertel 5636: }
                   5637: 
1.423     albertel 5638: =pod
                   5639: 
                   5640: =item get_scantron_config
                   5641: 
1.711     bisitz   5642:    Parse and return the bubblesheet configuration line selected as a
1.423     albertel 5643:    hash of configuration file fields.
                   5644: 
                   5645:  Arguments:
                   5646:     which - the name of the configuration to parse from the file.
                   5647: 
                   5648: 
                   5649:  Returns:
                   5650:             If the named configuration is not in the file, an empty
                   5651:             hash is returned.
                   5652:     a hash with the fields
                   5653:       name         - internal name for the this configuration setup
                   5654:       description  - text to display to operator that describes this config
                   5655:       CODElocation - if 0 or the string 'none'
                   5656:                           - no CODE exists for this config
                   5657:                      if -1 || the string 'letter'
                   5658:                           - a CODE exists for this config and is
                   5659:                             a string of letters
                   5660:                      Unsupported value (but planned for future support)
                   5661:                           if a positive integer
                   5662:                                - The CODE exists as the first n items from
                   5663:                                  the question section of the form
                   5664:                           if the string 'number'
                   5665:                                - The CODE exists for this config and is
                   5666:                                  a string of numbers
                   5667:       CODEstart   - (only matter if a CODE exists) column in the line where
                   5668:                      the CODE starts
                   5669:       CODElength  - length of the CODE
1.573     bisitz   5670:       IDstart     - column where the student/employee ID starts
1.556     weissno  5671:       IDlength    - length of the student/employee ID info
1.423     albertel 5672:       Qstart      - column where the information from the bubbled
                   5673:                     'questions' start
                   5674:       Qlength     - number of columns comprising a single bubble line from
                   5675:                     the sheet. (usually either 1 or 10)
1.424     albertel 5676:       Qon         - either a single character representing the character used
1.423     albertel 5677:                     to signal a bubble was chosen in the positional setup, or
                   5678:                     the string 'letter' if the letter of the chosen bubble is
                   5679:                     in the final, or 'number' if a number representing the
                   5680:                     chosen bubble is in the file (1->A 0->J)
1.424     albertel 5681:       Qoff        - the character used to represent that a bubble was
                   5682:                     left blank
1.423     albertel 5683:       PaperID     - if the scanning process generates a unique number for each
                   5684:                     sheet scanned the column that this ID number starts in
                   5685:       PaperIDlength - number of columns that comprise the unique ID number
                   5686:                       for the sheet of paper
1.424     albertel 5687:       FirstName   - column that the first name starts in
1.423     albertel 5688:       FirstNameLength - number of columns that the first name spans
                   5689:  
                   5690:       LastName    - column that the last name starts in
                   5691:       LastNameLength - number of columns that the last name spans
1.649     raeburn  5692:       BubblesPerRow - number of bubbles available in each row used to 
                   5693:                       bubble an answer. (If not specified, 10 assumed).
1.671     raeburn  5694: 
1.423     albertel 5695: =cut
1.422     foxr     5696: 
1.82      albertel 5697: sub get_scantron_config {
                   5698:     my ($which) = @_;
1.518     raeburn  5699:     my @lines = &get_scantronformat_file();
1.82      albertel 5700:     my %config;
1.157     albertel 5701:     #FIXME probably should move to XML it has already gotten a bit much now
1.518     raeburn  5702:     foreach my $line (@lines) {
1.82      albertel 5703: 	my ($name,$descrip)=split(/:/,$line);
                   5704: 	if ($name ne $which ) { next; }
                   5705: 	chomp($line);
                   5706: 	my @config=split(/:/,$line);
                   5707: 	$config{'name'}=$config[0];
                   5708: 	$config{'description'}=$config[1];
                   5709: 	$config{'CODElocation'}=$config[2];
                   5710: 	$config{'CODEstart'}=$config[3];
                   5711: 	$config{'CODElength'}=$config[4];
                   5712: 	$config{'IDstart'}=$config[5];
                   5713: 	$config{'IDlength'}=$config[6];
                   5714: 	$config{'Qstart'}=$config[7];
1.497     foxr     5715:  	$config{'Qlength'}=$config[8];
1.82      albertel 5716: 	$config{'Qoff'}=$config[9];
                   5717: 	$config{'Qon'}=$config[10];
1.157     albertel 5718: 	$config{'PaperID'}=$config[11];
                   5719: 	$config{'PaperIDlength'}=$config[12];
                   5720: 	$config{'FirstName'}=$config[13];
                   5721: 	$config{'FirstNamelength'}=$config[14];
                   5722: 	$config{'LastName'}=$config[15];
                   5723: 	$config{'LastNamelength'}=$config[16];
1.649     raeburn  5724:         $config{'BubblesPerRow'}=$config[17];
1.82      albertel 5725: 	last;
                   5726:     }
                   5727:     return %config;
                   5728: }
                   5729: 
1.423     albertel 5730: =pod 
                   5731: 
                   5732: =item username_to_idmap
                   5733: 
1.556     weissno  5734:     creates a hash keyed by student/employee ID with values of the corresponding
1.731     raeburn  5735:     student username:domain. If a single ID occurs for more than one student,
                   5736:     the status of the student is checked, and if Active, the value in the hash
                   5737:     will be set to the Active student.
1.423     albertel 5738: 
                   5739:   Arguments:
                   5740: 
                   5741:     $classlist - reference to the class list hash. This is a hash
                   5742:                  keyed by student name:domain  whose elements are references
1.424     albertel 5743:                  to arrays containing various chunks of information
1.423     albertel 5744:                  about the student. (See loncoursedata for more info).
                   5745: 
                   5746:   Returns
                   5747:     %idmap - the constructed hash
                   5748: 
                   5749: =cut
                   5750: 
1.82      albertel 5751: sub username_to_idmap {
                   5752:     my ($classlist)= @_;
                   5753:     my %idmap;
                   5754:     foreach my $student (keys(%$classlist)) {
1.731     raeburn  5755:         my $id = $classlist->{$student}->[&Apache::loncoursedata::CL_ID];
                   5756:         unless ($id eq '') {
                   5757:             if (!exists($idmap{$id})) {
                   5758:                 $idmap{$id} = $student;
                   5759:             } else {
                   5760:                 my $status = $classlist->{$student}->[&Apache::loncoursedata::CL_STATUS];
                   5761:                 if ($status eq 'Active') {
                   5762:                     $idmap{$id} = $student;
                   5763:                 }
                   5764:             }
                   5765:         }
1.82      albertel 5766:     }
                   5767:     return %idmap;
                   5768: }
1.423     albertel 5769: 
                   5770: =pod
                   5771: 
1.424     albertel 5772: =item scantron_fixup_scanline
1.423     albertel 5773: 
                   5774:    Process a requested correction to a scanline.
                   5775: 
                   5776:   Arguments:
                   5777:     $scantron_config   - hash from &get_scantron_config()
                   5778:     $scan_data         - hash of correction information 
                   5779:                           (see &scantron_getfile())
                   5780:     $line              - existing scanline
                   5781:     $whichline         - line number of the passed in scanline
                   5782:     $field             - type of change to process 
                   5783:                          (either 
1.573     bisitz   5784:                           'ID'     -> correct the student/employee ID
1.423     albertel 5785:                           'CODE'   -> correct the CODE
                   5786:                           'answer' -> fixup the submitted answers)
                   5787:     
                   5788:    $args               - hash of additional info,
                   5789:                           - 'ID' 
                   5790:                                'newid' -> studentID to use in replacement
1.424     albertel 5791:                                           of existing one
1.423     albertel 5792:                           - 'CODE' 
                   5793:                                'CODE_ignore_dup' - set to true if duplicates
                   5794:                                                    should be ignored.
                   5795: 	                       'CODE' - is new code or 'use_unfound'
1.424     albertel 5796:                                         if the existing unfound code should
1.423     albertel 5797:                                         be used as is
                   5798:                           - 'answer'
                   5799:                                'response' - new answer or 'none' if blank
                   5800:                                'question' - the bubble line to change
1.503     raeburn  5801:                                'questionnum' - the question identifier,
                   5802:                                                may include subquestion. 
1.423     albertel 5803: 
                   5804:   Returns:
                   5805:     $line - the modified scanline
                   5806: 
                   5807:   Side effects: 
                   5808:     $scan_data - may be updated
                   5809: 
                   5810: =cut
                   5811: 
1.82      albertel 5812: 
1.157     albertel 5813: sub scantron_fixup_scanline {
                   5814:     my ($scantron_config,$scan_data,$line,$whichline,$field,$args)=@_;
                   5815:     if ($field eq 'ID') {
                   5816: 	if (length($args->{'newid'}) > $$scantron_config{'IDlength'}) {
1.186     albertel 5817: 	    return ($line,1,'New value too large');
1.157     albertel 5818: 	}
                   5819: 	if (length($args->{'newid'}) < $$scantron_config{'IDlength'}) {
                   5820: 	    $args->{'newid'}=sprintf('%-'.$$scantron_config{'IDlength'}.'s',
                   5821: 				     $args->{'newid'});
                   5822: 	}
                   5823: 	substr($line,$$scantron_config{'IDstart'}-1,
                   5824: 	       $$scantron_config{'IDlength'})=$args->{'newid'};
                   5825: 	if ($args->{'newid'}=~/^\s*$/) {
                   5826: 	    &scan_data($scan_data,"$whichline.user",
                   5827: 		       $args->{'username'}.':'.$args->{'domain'});
                   5828: 	}
1.186     albertel 5829:     } elsif ($field eq 'CODE') {
1.192     albertel 5830: 	if ($args->{'CODE_ignore_dup'}) {
                   5831: 	    &scan_data($scan_data,"$whichline.CODE_ignore_dup",'1');
                   5832: 	}
                   5833: 	&scan_data($scan_data,"$whichline.useCODE",'1');
                   5834: 	if ($args->{'CODE'} ne 'use_unfound') {
1.191     albertel 5835: 	    if (length($args->{'CODE'}) > $$scantron_config{'CODElength'}) {
                   5836: 		return ($line,1,'New CODE value too large');
                   5837: 	    }
                   5838: 	    if (length($args->{'CODE'}) < $$scantron_config{'CODElength'}) {
                   5839: 		$args->{'CODE'}=sprintf('%-'.$$scantron_config{'CODElength'}.'s',$args->{'CODE'});
                   5840: 	    }
                   5841: 	    substr($line,$$scantron_config{'CODEstart'}-1,
                   5842: 		   $$scantron_config{'CODElength'})=$args->{'CODE'};
1.186     albertel 5843: 	}
1.157     albertel 5844:     } elsif ($field eq 'answer') {
1.497     foxr     5845: 	my $length=$scantron_config->{'Qlength'};
1.157     albertel 5846: 	my $off=$scantron_config->{'Qoff'};
                   5847: 	my $on=$scantron_config->{'Qon'};
1.497     foxr     5848: 	my $answer=${off}x$length;
                   5849: 	if ($args->{'response'} eq 'none') {
                   5850: 	    &scan_data($scan_data,
1.503     raeburn  5851: 		       "$whichline.no_bubble.".$args->{'questionnum'},'1');
1.497     foxr     5852: 	} else {
                   5853: 	    if ($on eq 'letter') {
                   5854: 		my @alphabet=('A'..'Z');
                   5855: 		$answer=$alphabet[$args->{'response'}];
                   5856: 	    } elsif ($on eq 'number') {
                   5857: 		$answer=$args->{'response'}+1;
                   5858: 		if ($answer == 10) { $answer = '0'; }
1.274     albertel 5859: 	    } else {
1.497     foxr     5860: 		substr($answer,$args->{'response'},1)=$on;
1.274     albertel 5861: 	    }
1.497     foxr     5862: 	    &scan_data($scan_data,
1.503     raeburn  5863: 		       "$whichline.no_bubble.".$args->{'questionnum'},undef,'1');
1.157     albertel 5864: 	}
1.497     foxr     5865: 	my $where=$length*($args->{'question'}-1)+$scantron_config->{'Qstart'};
                   5866: 	substr($line,$where-1,$length)=$answer;
1.157     albertel 5867:     }
                   5868:     return $line;
                   5869: }
1.423     albertel 5870: 
                   5871: =pod
                   5872: 
                   5873: =item scan_data
                   5874: 
                   5875:     Edit or look up  an item in the scan_data hash.
                   5876: 
                   5877:   Arguments:
                   5878:     $scan_data  - The hash (see scantron_getfile)
                   5879:     $key        - shorthand of the key to edit (actual key is
1.424     albertel 5880:                   scantronfilename_key).
1.423     albertel 5881:     $data        - New value of the hash entry.
                   5882:     $delete      - If true, the entry is removed from the hash.
                   5883: 
                   5884:   Returns:
                   5885:     The new value of the hash table field (undefined if deleted).
                   5886: 
                   5887: =cut
                   5888: 
                   5889: 
1.157     albertel 5890: sub scan_data {
                   5891:     my ($scan_data,$key,$value,$delete)=@_;
1.257     albertel 5892:     my $filename=$env{'form.scantron_selectfile'};
1.157     albertel 5893:     if (defined($value)) {
                   5894: 	$scan_data->{$filename.'_'.$key} = $value;
                   5895:     }
                   5896:     if ($delete) { delete($scan_data->{$filename.'_'.$key}); }
                   5897:     return $scan_data->{$filename.'_'.$key};
                   5898: }
1.423     albertel 5899: 
1.495     albertel 5900: # ----- These first few routines are general use routines.----
                   5901: 
                   5902: # Return the number of occurences of a pattern in a string.
                   5903: 
                   5904: sub occurence_count {
                   5905:     my ($string, $pattern) = @_;
                   5906: 
                   5907:     my @matches = ($string =~ /$pattern/g);
                   5908: 
                   5909:     return scalar(@matches);
                   5910: }
                   5911: 
                   5912: 
                   5913: # Take a string known to have digits and convert all the
                   5914: # digits into letters in the range J,A..I.
                   5915: 
                   5916: sub digits_to_letters {
                   5917:     my ($input) = @_;
                   5918: 
                   5919:     my @alphabet = ('J', 'A'..'I');
                   5920: 
                   5921:     my @input    = split(//, $input);
                   5922:     my $output ='';
                   5923:     for (my $i = 0; $i < scalar(@input); $i++) {
                   5924: 	if ($input[$i] =~ /\d/) {
                   5925: 	    $output .= $alphabet[$input[$i]];
                   5926: 	} else {
                   5927: 	    $output .= $input[$i];
                   5928: 	}
                   5929:     }
                   5930:     return $output;
                   5931: }
                   5932: 
1.423     albertel 5933: =pod 
                   5934: 
                   5935: =item scantron_parse_scanline
                   5936: 
1.711     bisitz   5937:   Decodes a scanline from the selected bubblesheet file
1.423     albertel 5938: 
                   5939:  Arguments:
1.711     bisitz   5940:     line             - The text of the bubblesheet file line to process
1.423     albertel 5941:     whichline        - Line number
1.711     bisitz   5942:     scantron_config  - Hash describing the format of the bubblesheet lines.
1.423     albertel 5943:     scan_data        - Hash of extra information about the scanline
                   5944:                        (see scantron_getfile for more information)
                   5945:     just_header      - True if should not process question answers but only
                   5946:                        the stuff to the left of the answers.
1.691     raeburn  5947:     randomorder      - True if randomorder in use
                   5948:     randompick       - True if randompick in use
                   5949:     sequence         - Exam folder URL
                   5950:     master_seq       - Ref to array containing symbs in exam folder
                   5951:     symb_to_resource - Ref to hash of symbs for resources in exam folder
                   5952:                        (corresponding values are resource objects)
                   5953:     partids_by_symb  - Ref to hash of symb -> array ref of partIDs
                   5954:     orderedforcode   - Ref to hash of arrays. keys are CODEs and values
                   5955:                        are refs to an array of resource objects, ordered
                   5956:                        according to order used for CODE, when randomorder
                   5957:                        and or randompick are in use.
                   5958:     respnumlookup    - Ref to hash mapping question numbers in bubble lines
                   5959:                        for current line to question number used for same question
                   5960:                         in "Master Sequence" (as seen by Course Coordinator).
                   5961:     startline        - Ref to hash where key is question number (0 is first)
                   5962:                        and value is number of first bubble line for current 
                   5963:                        student or code-based randompick and/or randomorder.
                   5964:     totalref         - Ref of scalar used to score total number of bubble
                   5965:                        lines needed for responses in a scan line (used when
                   5966:                        randompick in use. 
                   5967:     
1.423     albertel 5968:  Returns:
                   5969:    Hash containing the result of parsing the scanline
                   5970: 
                   5971:    Keys are all proceeded by the string 'scantron.'
                   5972: 
                   5973:        CODE    - the CODE in use for this scanline
                   5974:        useCODE - 1 if the CODE is invalid but it usage has been forced
                   5975:                  by the operator
                   5976:        CODE_ignore_dup - 1 if the CODE is a duplicated use when unique
                   5977:                             CODEs were selected, but the usage has been
                   5978:                             forced by the operator
1.556     weissno  5979:        ID  - student/employee ID
1.423     albertel 5980:        PaperID - if used, the ID number printed on the sheet when the 
                   5981:                  paper was scanned
                   5982:        FirstName - first name from the sheet
                   5983:        LastName  - last name from the sheet
                   5984: 
                   5985:      if just_header was not true these key may also exist
                   5986: 
1.447     foxr     5987:        missingerror - a list of bubble ranges that are considered to be answers
                   5988:                       to a single question that don't have any bubbles filled in.
                   5989:                       Of the form questionnumber:firstbubblenumber:count.
                   5990:        doubleerror  - a list of bubble ranges that are considered to be answers
                   5991:                       to a single question that have more than one bubble filled in.
                   5992:                       Of the form questionnumber::firstbubblenumber:count
                   5993:    
                   5994:                 In the above, count is the number of bubble responses in the
                   5995:                 input line needed to represent the possible answers to the question.
                   5996:                 e.g. a radioresponse with 15 choices in an answer sheet with 10 choices
                   5997:                 per line would have count = 2.
                   5998: 
1.423     albertel 5999:        maxquest     - the number of the last bubble line that was parsed
                   6000: 
                   6001:        (<number> starts at 1)
                   6002:        <number>.answer - zero or more letters representing the selected
                   6003:                          letters from the scanline for the bubble line 
                   6004:                          <number>.
                   6005:                          if blank there was either no bubble or there where
                   6006:                          multiple bubbles, (consult the keys missingerror and
                   6007:                          doubleerror if this is an error condition)
                   6008: 
                   6009: =cut
                   6010: 
1.82      albertel 6011: sub scantron_parse_scanline {
1.691     raeburn  6012:     my ($line,$whichline,$scantron_config,$scan_data,$just_header,$idmap,
                   6013:         $randomorder,$randompick,$sequence,$master_seq,$symb_to_resource,
                   6014:         $partids_by_symb,$orderedforcode,$respnumlookup,$startline,$totalref)=@_;
1.470     foxr     6015: 
1.82      albertel 6016:     my %record;
1.691     raeburn  6017:     my $data=substr($line,0,$$scantron_config{'Qstart'}-1); # stuff before answers
1.278     albertel 6018:     if (!($$scantron_config{'CODElocation'} eq 0 ||
                   6019: 	  $$scantron_config{'CODElocation'} eq 'none')) {
                   6020: 	if ($$scantron_config{'CODElocation'} < 0 ||
                   6021: 	    $$scantron_config{'CODElocation'} eq 'letter' ||
                   6022: 	    $$scantron_config{'CODElocation'} eq 'number') {
1.191     albertel 6023: 	    $record{'scantron.CODE'}=substr($data,
                   6024: 					    $$scantron_config{'CODEstart'}-1,
1.83      albertel 6025: 					    $$scantron_config{'CODElength'});
1.191     albertel 6026: 	    if (&scan_data($scan_data,"$whichline.useCODE")) {
                   6027: 		$record{'scantron.useCODE'}=1;
                   6028: 	    }
1.192     albertel 6029: 	    if (&scan_data($scan_data,"$whichline.CODE_ignore_dup")) {
                   6030: 		$record{'scantron.CODE_ignore_dup'}=1;
                   6031: 	    }
1.82      albertel 6032: 	} else {
                   6033: 	    #FIXME interpret first N questions
                   6034: 	}
                   6035:     }
1.83      albertel 6036:     $record{'scantron.ID'}=substr($data,$$scantron_config{'IDstart'}-1,
                   6037: 				  $$scantron_config{'IDlength'});
1.157     albertel 6038:     $record{'scantron.PaperID'}=
                   6039: 	substr($data,$$scantron_config{'PaperID'}-1,
                   6040: 	       $$scantron_config{'PaperIDlength'});
                   6041:     $record{'scantron.FirstName'}=
                   6042: 	substr($data,$$scantron_config{'FirstName'}-1,
                   6043: 	       $$scantron_config{'FirstNamelength'});
                   6044:     $record{'scantron.LastName'}=
                   6045: 	substr($data,$$scantron_config{'LastName'}-1,
                   6046: 	       $$scantron_config{'LastNamelength'});
1.423     albertel 6047:     if ($just_header) { return \%record; }
1.194     albertel 6048: 
1.82      albertel 6049:     my @alphabet=('A'..'Z');
                   6050:     my $questnum=0;
1.447     foxr     6051:     my $ansnum  =1;		# Multiple 'answer lines'/question.
                   6052: 
1.691     raeburn  6053:     my $lastpos = $env{'form.scantron_maxbubble'}*$$scantron_config{'Qlength'};
                   6054:     if ($randompick || $randomorder) {
                   6055:         my $total = &get_respnum_lookups($sequence,$scan_data,$idmap,$line,\%record,
                   6056:                                          $master_seq,$symb_to_resource,
                   6057:                                          $partids_by_symb,$orderedforcode,
                   6058:                                          $respnumlookup,$startline);
                   6059:         if ($total) {
                   6060:             $lastpos = $total*$$scantron_config{'Qlength'}; 
                   6061:         }
                   6062:         if (ref($totalref)) {
                   6063:             $$totalref = $total;
                   6064:         }
                   6065:     }
                   6066:     my $questions=substr($line,$$scantron_config{'Qstart'}-1,$lastpos);  # Answers
1.470     foxr     6067:     chomp($questions);		# Get rid of any trailing \n.
                   6068:     $questions =~ s/\r$//;      # Get rid of trailing \r too (MAC or Win uploads).
                   6069:     while (length($questions)) {
1.691     raeburn  6070:         my $answers_needed;
                   6071:         if (($randompick || $randomorder) && (ref($respnumlookup) eq 'HASH')) {
                   6072:             $answers_needed = $bubble_lines_per_response{$respnumlookup->{$questnum}};
                   6073:         } else {
                   6074: 	    $answers_needed = $bubble_lines_per_response{$questnum};
                   6075:         }
1.503     raeburn  6076:         my $answer_length  = ($$scantron_config{'Qlength'} * $answers_needed)
                   6077:                              || 1;
                   6078:         $questnum++;
                   6079:         my $quest_id = $questnum;
                   6080:         my $currentquest = substr($questions,0,$answer_length);
                   6081:         $questions       = substr($questions,$answer_length);
                   6082:         if (length($currentquest) < $answer_length) { next; }
                   6083: 
1.691     raeburn  6084:         my $subdivided;
                   6085:         if (($randompick || $randomorder) && (ref($respnumlookup) eq 'HASH')) {
                   6086:             $subdivided = $subdivided_bubble_lines{$respnumlookup->{$questnum-1}};
                   6087:         } else {
                   6088:             $subdivided = $subdivided_bubble_lines{$questnum-1};
                   6089:         }
                   6090:         if ($subdivided =~ /,/) {
1.503     raeburn  6091:             my $subquestnum = 1;
                   6092:             my $subquestions = $currentquest;
1.691     raeburn  6093:             my @subanswers_needed = split(/,/,$subdivided);
1.503     raeburn  6094:             foreach my $subans (@subanswers_needed) {
                   6095:                 my $subans_length =
                   6096:                     ($$scantron_config{'Qlength'} * $subans)  || 1;
                   6097:                 my $currsubquest = substr($subquestions,0,$subans_length);
                   6098:                 $subquestions   = substr($subquestions,$subans_length);
                   6099:                 $quest_id = "$questnum.$subquestnum";
                   6100:                 if (($$scantron_config{'Qon'} eq 'letter') ||
                   6101:                     ($$scantron_config{'Qon'} eq 'number')) {
                   6102:                     $ansnum = &scantron_validator_lettnum($ansnum, 
                   6103:                         $questnum,$quest_id,$subans,$currsubquest,$whichline,
1.691     raeburn  6104:                         \@alphabet,\%record,$scantron_config,$scan_data,
                   6105:                         $randomorder,$randompick,$respnumlookup);
1.503     raeburn  6106:                 } else {
                   6107:                     $ansnum = &scantron_validator_positional($ansnum,
1.691     raeburn  6108:                         $questnum,$quest_id,$subans,$currsubquest,$whichline,
                   6109:                         \@alphabet,\%record,$scantron_config,$scan_data,
                   6110:                         $randomorder,$randompick,$respnumlookup);
1.503     raeburn  6111:                 }
                   6112:                 $subquestnum ++;
                   6113:             }
                   6114:         } else {
                   6115:             if (($$scantron_config{'Qon'} eq 'letter') ||
                   6116:                 ($$scantron_config{'Qon'} eq 'number')) {
                   6117:                 $ansnum = &scantron_validator_lettnum($ansnum,$questnum,
                   6118:                     $quest_id,$answers_needed,$currentquest,$whichline,
1.691     raeburn  6119:                     \@alphabet,\%record,$scantron_config,$scan_data,
                   6120:                     $randomorder,$randompick,$respnumlookup);
1.503     raeburn  6121:             } else {
                   6122:                 $ansnum = &scantron_validator_positional($ansnum,$questnum,
                   6123:                     $quest_id,$answers_needed,$currentquest,$whichline,
1.691     raeburn  6124:                     \@alphabet,\%record,$scantron_config,$scan_data,
                   6125:                     $randomorder,$randompick,$respnumlookup);
1.503     raeburn  6126:             }
                   6127:         }
                   6128:     }
                   6129:     $record{'scantron.maxquest'}=$questnum;
                   6130:     return \%record;
                   6131: }
1.447     foxr     6132: 
1.691     raeburn  6133: sub get_master_seq {
                   6134:     my ($resources,$master_seq,$symb_to_resource) = @_;
                   6135:     return unless ((ref($resources) eq 'ARRAY') && (ref($master_seq) eq 'ARRAY') && 
                   6136:                    (ref($symb_to_resource) eq 'HASH'));
                   6137:     my $resource_error;
                   6138:     foreach my $resource (@{$resources}) {
                   6139:         my $ressymb;
                   6140:         if (ref($resource)) {
                   6141:             $ressymb = $resource->symb();
                   6142:             push(@{$master_seq},$ressymb);
                   6143:             $symb_to_resource->{$ressymb} = $resource;
                   6144:         } else {
                   6145:             $resource_error = 1;
                   6146:             last;
                   6147:         }
                   6148:     }
                   6149:     return $resource_error;
                   6150: }
                   6151: 
                   6152: sub get_respnum_lookups {
                   6153:     my ($sequence,$scan_data,$idmap,$line,$record,$master_seq,$symb_to_resource,
                   6154:         $partids_by_symb,$orderedforcode,$respnumlookup,$startline) = @_;
                   6155:     return unless ((ref($record) eq 'HASH') && (ref($master_seq) eq 'ARRAY') &&
                   6156:                    (ref($symb_to_resource) eq 'HASH') && (ref($partids_by_symb) eq 'HASH') &&
                   6157:                    (ref($orderedforcode) eq 'HASH') && (ref($respnumlookup) eq 'HASH') &&
                   6158:                    (ref($startline) eq 'HASH'));
                   6159:     my ($user,$scancode);
                   6160:     if ((exists($record->{'scantron.CODE'})) &&
                   6161:         (&Apache::lonnet::validCODE($record->{'scantron.CODE'}))) {
                   6162:         $scancode = $record->{'scantron.CODE'};
                   6163:     } else {
                   6164:         $user = &scantron_find_student($record,$scan_data,$idmap,$line);
                   6165:     }
                   6166:     my @mapresources =
                   6167:         &users_order($user,$scancode,$sequence,$master_seq,$symb_to_resource,
                   6168:                      $orderedforcode);
                   6169:     my $total = 0;
                   6170:     my $count = 0;
                   6171:     foreach my $resource (@mapresources) {
                   6172:         my $id = $resource->id();
                   6173:         my $symb = $resource->symb();
                   6174:         if (ref($partids_by_symb->{$symb}) eq 'ARRAY') {
                   6175:             foreach my $partid (@{$partids_by_symb->{$symb}}) {
                   6176:                 my $respnum = $masterseq_id_responsenum{$id.'_'.$partid};
                   6177:                 if ($respnum ne '') {
                   6178:                     $respnumlookup->{$count} = $respnum;
                   6179:                     $startline->{$count} = $total;
                   6180:                     $total += $bubble_lines_per_response{$respnum};
                   6181:                     $count ++;
                   6182:                 }
                   6183:             }
                   6184:         }
                   6185:     }
                   6186:     return $total;
                   6187: }
                   6188: 
1.503     raeburn  6189: sub scantron_validator_lettnum {
                   6190:     my ($ansnum,$questnum,$quest_id,$answers_needed,$currquest,$whichline,
1.691     raeburn  6191:         $alphabet,$record,$scantron_config,$scan_data,$randomorder,
                   6192:         $randompick,$respnumlookup) = @_;
1.503     raeburn  6193: 
                   6194:     # Qon 'letter' implies for each slot in currquest we have:
                   6195:     #    ? or * for doubles, a letter in A-Z for a bubble, and
                   6196:     #    about anything else (esp. a value of Qoff) for missing
                   6197:     #    bubbles.
                   6198:     #
                   6199:     # Qon 'number' implies each slot gives a digit that indexes the
                   6200:     #    bubbles filled, or Qoff, or a non-number for unbubbled lines,
                   6201:     #    and * or ? for double bubbles on a single line.
                   6202:     #
1.447     foxr     6203: 
1.503     raeburn  6204:     my $matchon;
                   6205:     if ($$scantron_config{'Qon'} eq 'letter') {
                   6206:         $matchon = '[A-Z]';
                   6207:     } elsif ($$scantron_config{'Qon'} eq 'number') {
                   6208:         $matchon = '\d';
                   6209:     }
                   6210:     my $occurrences = 0;
1.691     raeburn  6211:     my $responsenum = $questnum-1;
                   6212:     if (($randompick || $randomorder) && (ref($respnumlookup) eq 'HASH')) {
                   6213:        $responsenum = $respnumlookup->{$questnum-1} 
                   6214:     }
                   6215:     if (($responsetype_per_response{$responsenum} eq 'essayresponse') ||
                   6216:         ($responsetype_per_response{$responsenum} eq 'formularesponse') ||
                   6217:         ($responsetype_per_response{$responsenum} eq 'stringresponse') ||
                   6218:         ($responsetype_per_response{$responsenum} eq 'imageresponse') ||
                   6219:         ($responsetype_per_response{$responsenum} eq 'reactionresponse') ||
                   6220:         ($responsetype_per_response{$responsenum} eq 'organicresponse')) {
1.503     raeburn  6221:         my @singlelines = split('',$currquest);
                   6222:         foreach my $entry (@singlelines) {
                   6223:             $occurrences = &occurence_count($entry,$matchon);
                   6224:             if ($occurrences > 1) {
                   6225:                 last;
                   6226:             }
1.691     raeburn  6227:         }
1.503     raeburn  6228:     } else {
                   6229:         $occurrences = &occurence_count($currquest,$matchon); 
                   6230:     }
                   6231:     if (($currquest =~ /\?/ || $currquest =~ /\*/) || ($occurrences > 1)) {
                   6232:         push(@{$record->{'scantron.doubleerror'}},$quest_id);
                   6233:         for (my $ans=0; $ans<$answers_needed; $ans++) {
                   6234:             my $bubble = substr($currquest,$ans,1);
                   6235:             if ($bubble =~ /$matchon/ ) {
                   6236:                 if ($$scantron_config{'Qon'} eq 'number') {
                   6237:                     if ($bubble == 0) {
                   6238:                         $bubble = 10; 
                   6239:                     }
                   6240:                     $record->{"scantron.$ansnum.answer"} = 
                   6241:                         $alphabet->[$bubble-1];
                   6242:                 } else {
                   6243:                     $record->{"scantron.$ansnum.answer"} = $bubble;
                   6244:                 }
                   6245:             } else {
                   6246:                 $record->{"scantron.$ansnum.answer"}='';
                   6247:             }
                   6248:             $ansnum++;
                   6249:         }
                   6250:     } elsif (!defined($currquest)
                   6251:             || (&occurence_count($currquest, $$scantron_config{'Qoff'}) == length($currquest))
                   6252:             || (&occurence_count($currquest,$matchon) == 0)) {
                   6253:         for (my $ans=0; $ans<$answers_needed; $ans++ ) {
                   6254:             $record->{"scantron.$ansnum.answer"}='';
                   6255:             $ansnum++;
                   6256:         }
                   6257:         if (!&scan_data($scan_data,"$whichline.no_bubble.$quest_id")) {
                   6258:             push(@{$record->{'scantron.missingerror'}},$quest_id);
                   6259:         }
                   6260:     } else {
                   6261:         if ($$scantron_config{'Qon'} eq 'number') {
                   6262:             $currquest = &digits_to_letters($currquest);            
                   6263:         }
                   6264:         for (my $ans=0; $ans<$answers_needed; $ans++) {
                   6265:             my $bubble = substr($currquest,$ans,1);
                   6266:             $record->{"scantron.$ansnum.answer"} = $bubble;
                   6267:             $ansnum++;
                   6268:         }
                   6269:     }
                   6270:     return $ansnum;
                   6271: }
1.447     foxr     6272: 
1.503     raeburn  6273: sub scantron_validator_positional {
                   6274:     my ($ansnum,$questnum,$quest_id,$answers_needed,$currquest,
1.691     raeburn  6275:         $whichline,$alphabet,$record,$scantron_config,$scan_data,
                   6276:         $randomorder,$randompick,$respnumlookup) = @_;
1.447     foxr     6277: 
1.503     raeburn  6278:     # Otherwise there's a positional notation;
                   6279:     # each bubble line requires Qlength items, and there are filled in
                   6280:     # bubbles for each case where there 'Qon' characters.
                   6281:     #
1.447     foxr     6282: 
1.503     raeburn  6283:     my @array=split($$scantron_config{'Qon'},$currquest,-1);
1.447     foxr     6284: 
1.503     raeburn  6285:     # If the split only gives us one element.. the full length of the
                   6286:     # answer string, no bubbles are filled in:
1.447     foxr     6287: 
1.507     raeburn  6288:     if ($answers_needed eq '') {
                   6289:         return;
                   6290:     }
                   6291: 
1.503     raeburn  6292:     if (length($array[0]) eq $$scantron_config{'Qlength'}*$answers_needed) {
                   6293:         for (my $ans=0; $ans<$answers_needed; $ans++ ) {
                   6294:             $record->{"scantron.$ansnum.answer"}='';
                   6295:             $ansnum++;
                   6296:         }
                   6297:         if (!&scan_data($scan_data,"$whichline.no_bubble.$quest_id")) {
                   6298:             push(@{$record->{"scantron.missingerror"}},$quest_id);
                   6299:         }
                   6300:     } elsif (scalar(@array) == 2) {
                   6301:         my $location = length($array[0]);
                   6302:         my $line_num = int($location / $$scantron_config{'Qlength'});
                   6303:         my $bubble   = $alphabet->[$location % $$scantron_config{'Qlength'}];
                   6304:         for (my $ans=0; $ans<$answers_needed; $ans++) {
                   6305:             if ($ans eq $line_num) {
                   6306:                 $record->{"scantron.$ansnum.answer"} = $bubble;
                   6307:             } else {
                   6308:                 $record->{"scantron.$ansnum.answer"} = ' ';
                   6309:             }
                   6310:             $ansnum++;
                   6311:          }
                   6312:     } else {
                   6313:         #  If there's more than one instance of a bubble character
                   6314:         #  That's a double bubble; with positional notation we can
                   6315:         #  record all the bubbles filled in as well as the
                   6316:         #  fact this response consists of multiple bubbles.
                   6317:         #
1.691     raeburn  6318:         my $responsenum = $questnum-1;
                   6319:         if (($randompick || $randomorder) && (ref($respnumlookup) eq 'HASH')) {
                   6320:             $responsenum = $respnumlookup->{$questnum-1}
                   6321:         }
                   6322:         if (($responsetype_per_response{$responsenum} eq 'essayresponse') ||
                   6323:             ($responsetype_per_response{$responsenum} eq 'formularesponse') ||
                   6324:             ($responsetype_per_response{$responsenum} eq 'stringresponse') ||
                   6325:             ($responsetype_per_response{$responsenum} eq 'imageresponse') ||
                   6326:             ($responsetype_per_response{$responsenum} eq 'reactionresponse') ||
                   6327:             ($responsetype_per_response{$responsenum} eq 'organicresponse')) {
1.503     raeburn  6328:             my $doubleerror = 0;
                   6329:             while (($currquest >= $$scantron_config{'Qlength'}) && 
                   6330:                    (!$doubleerror)) {
                   6331:                my $currline = substr($currquest,0,$$scantron_config{'Qlength'});
                   6332:                $currquest = substr($currquest,$$scantron_config{'Qlength'});
                   6333:                my @currarray = split($$scantron_config{'Qon'},$currline,-1);
                   6334:                if (length(@currarray) > 2) {
                   6335:                    $doubleerror = 1;
                   6336:                } 
                   6337:             }
                   6338:             if ($doubleerror) {
                   6339:                 push(@{$record->{'scantron.doubleerror'}},$quest_id);
                   6340:             }
                   6341:         } else {
                   6342:             push(@{$record->{'scantron.doubleerror'}},$quest_id);
                   6343:         }
                   6344:         my $item = $ansnum;
                   6345:         for (my $ans=0; $ans<$answers_needed; $ans++) {
                   6346:             $record->{"scantron.$item.answer"} = '';
                   6347:             $item ++;
                   6348:         }
1.447     foxr     6349: 
1.503     raeburn  6350:         my @ans=@array;
                   6351:         my $i=0;
                   6352:         my $increment = 0;
                   6353:         while ($#ans) {
                   6354:             $i+=length($ans[0]) + $increment;
                   6355:             my $line   = int($i/$$scantron_config{'Qlength'} + $ansnum);
                   6356:             my $bubble = $i%$$scantron_config{'Qlength'};
                   6357:             $record->{"scantron.$line.answer"}.=$alphabet->[$bubble];
                   6358:             shift(@ans);
                   6359:             $increment = 1;
                   6360:         }
                   6361:         $ansnum += $answers_needed;
1.82      albertel 6362:     }
1.503     raeburn  6363:     return $ansnum;
1.82      albertel 6364: }
                   6365: 
1.423     albertel 6366: =pod
                   6367: 
                   6368: =item scantron_add_delay
                   6369: 
                   6370:    Adds an error message that occurred during the grading phase to a
                   6371:    queue of messages to be shown after grading pass is complete
                   6372: 
                   6373:  Arguments:
1.424     albertel 6374:    $delayqueue  - arrary ref of hash ref of error messages
1.423     albertel 6375:    $scanline    - the scanline that caused the error
                   6376:    $errormesage - the error message
                   6377:    $errorcode   - a numeric code for the error
                   6378: 
                   6379:  Side Effects:
1.424     albertel 6380:    updates the $delayqueue to have a new hash ref of the error
1.423     albertel 6381: 
                   6382: =cut
                   6383: 
1.82      albertel 6384: sub scantron_add_delay {
1.140     albertel 6385:     my ($delayqueue,$scanline,$errormessage,$errorcode)=@_;
                   6386:     push(@$delayqueue,
                   6387: 	 {'line' => $scanline, 'emsg' => $errormessage,
                   6388: 	  'ecode' => $errorcode }
                   6389: 	 );
1.82      albertel 6390: }
                   6391: 
1.423     albertel 6392: =pod
                   6393: 
                   6394: =item scantron_find_student
                   6395: 
1.424     albertel 6396:    Finds the username for the current scanline
                   6397: 
                   6398:   Arguments:
                   6399:    $scantron_record - hash result from scantron_parse_scanline
                   6400:    $scan_data       - hash of correction information 
                   6401:                       (see &scantron_getfile() form more information)
                   6402:    $idmap           - hash from &username_to_idmap()
                   6403:    $line            - number of current scanline
                   6404:  
                   6405:   Returns:
                   6406:    Either 'username:domain' or undef if unknown
                   6407: 
1.423     albertel 6408: =cut
                   6409: 
1.82      albertel 6410: sub scantron_find_student {
1.157     albertel 6411:     my ($scantron_record,$scan_data,$idmap,$line)=@_;
1.83      albertel 6412:     my $scanID=$$scantron_record{'scantron.ID'};
1.157     albertel 6413:     if ($scanID =~ /^\s*$/) {
                   6414:  	return &scan_data($scan_data,"$line.user");
                   6415:     }
1.83      albertel 6416:     foreach my $id (keys(%$idmap)) {
1.157     albertel 6417:  	if (lc($id) eq lc($scanID)) {
                   6418:  	    return $$idmap{$id};
                   6419:  	}
1.83      albertel 6420:     }
                   6421:     return undef;
                   6422: }
                   6423: 
1.423     albertel 6424: =pod
                   6425: 
                   6426: =item scantron_filter
                   6427: 
1.424     albertel 6428:    Filter sub for lonnavmaps, filters out hidden resources if ignore
                   6429:    hidden resources was selected
                   6430: 
1.423     albertel 6431: =cut
                   6432: 
1.83      albertel 6433: sub scantron_filter {
                   6434:     my ($curres)=@_;
1.331     albertel 6435: 
                   6436:     if (ref($curres) && $curres->is_problem()) {
                   6437: 	# if the user has asked to not have either hidden
                   6438: 	# or 'randomout' controlled resources to be graded
                   6439: 	# don't include them
                   6440: 	if ($env{'form.scantron_options_hidden'} eq 'ignore_hidden'
                   6441: 	    && $curres->randomout) {
                   6442: 	    return 0;
                   6443: 	}
1.83      albertel 6444: 	return 1;
                   6445:     }
                   6446:     return 0;
1.82      albertel 6447: }
                   6448: 
1.423     albertel 6449: =pod
                   6450: 
                   6451: =item scantron_process_corrections
                   6452: 
1.424     albertel 6453:    Gets correction information out of submitted form data and corrects
                   6454:    the scanline
                   6455: 
1.423     albertel 6456: =cut
                   6457: 
1.157     albertel 6458: sub scantron_process_corrections {
                   6459:     my ($r) = @_;
1.257     albertel 6460:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.157     albertel 6461:     my ($scanlines,$scan_data)=&scantron_getfile();
                   6462:     my $classlist=&Apache::loncoursedata::get_classlist();
1.257     albertel 6463:     my $which=$env{'form.scantron_line'};
1.200     albertel 6464:     my $line=&scantron_get_line($scanlines,$scan_data,$which);
1.157     albertel 6465:     my ($skip,$err,$errmsg);
1.257     albertel 6466:     if ($env{'form.scantron_skip_record'}) {
1.157     albertel 6467: 	$skip=1;
1.257     albertel 6468:     } elsif ($env{'form.scantron_corrections'} =~ /^(duplicate|incorrect)ID$/) {
                   6469: 	my $newstudent=$env{'form.scantron_username'}.':'.
                   6470: 	    $env{'form.scantron_domain'};
1.157     albertel 6471: 	my $newid=$classlist->{$newstudent}->[&Apache::loncoursedata::CL_ID];
                   6472: 	($line,$err,$errmsg)=
                   6473: 	    &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,$which,
                   6474: 				     'ID',{'newid'=>$newid,
1.257     albertel 6475: 				    'username'=>$env{'form.scantron_username'},
                   6476: 				    'domain'=>$env{'form.scantron_domain'}});
                   6477:     } elsif ($env{'form.scantron_corrections'} =~ /^(duplicate|incorrect)CODE$/) {
                   6478: 	my $resolution=$env{'form.scantron_CODE_resolution'};
1.190     albertel 6479: 	my $newCODE;
1.192     albertel 6480: 	my %args;
1.190     albertel 6481: 	if      ($resolution eq 'use_unfound') {
1.191     albertel 6482: 	    $newCODE='use_unfound';
1.190     albertel 6483: 	} elsif ($resolution eq 'use_found') {
1.257     albertel 6484: 	    $newCODE=$env{'form.scantron_CODE_selectedvalue'};
1.190     albertel 6485: 	} elsif ($resolution eq 'use_typed') {
1.257     albertel 6486: 	    $newCODE=$env{'form.scantron_CODE_newvalue'};
1.194     albertel 6487: 	} elsif ($resolution =~ /^use_closest_(\d+)/) {
1.257     albertel 6488: 	    $newCODE=$env{"form.scantron_CODE_closest_$1"};
1.190     albertel 6489: 	}
1.257     albertel 6490: 	if ($env{'form.scantron_corrections'} eq 'duplicateCODE') {
1.192     albertel 6491: 	    $args{'CODE_ignore_dup'}=1;
                   6492: 	}
                   6493: 	$args{'CODE'}=$newCODE;
1.186     albertel 6494: 	($line,$err,$errmsg)=
                   6495: 	    &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,$which,
1.192     albertel 6496: 				     'CODE',\%args);
1.257     albertel 6497:     } elsif ($env{'form.scantron_corrections'} =~ /^(missing|double)bubble$/) {
                   6498: 	foreach my $question (split(',',$env{'form.scantron_questions'})) {
1.157     albertel 6499: 	    ($line,$err,$errmsg)=
                   6500: 		&scantron_fixup_scanline(\%scantron_config,$scan_data,$line,
                   6501: 					 $which,'answer',
                   6502: 					 { 'question'=>$question,
1.503     raeburn  6503: 		      		   'response'=>$env{"form.scantron_correct_Q_$question"},
                   6504:                                    'questionnum'=>$env{"form.scantron_questionnum_Q_$question"}});
1.157     albertel 6505: 	    if ($err) { last; }
                   6506: 	}
                   6507:     }
                   6508:     if ($err) {
1.703     bisitz   6509:         $r->print(
                   6510:             '<p class="LC_error">'
                   6511:            .&mt('Unable to accept last correction, an error occurred: [_1]',
                   6512:                 $errmsg)
1.704     raeburn  6513:            .'</p>');
1.157     albertel 6514:     } else {
1.200     albertel 6515: 	&scantron_put_line($scanlines,$scan_data,$which,$line,$skip);
1.157     albertel 6516: 	&scantron_putfile($scanlines,$scan_data);
                   6517:     }
                   6518: }
                   6519: 
1.423     albertel 6520: =pod
                   6521: 
                   6522: =item reset_skipping_status
                   6523: 
1.424     albertel 6524:    Forgets the current set of remember skipped scanlines (and thus
                   6525:    reverts back to considering all lines in the
                   6526:    scantron_skipped_<filename> file)
                   6527: 
1.423     albertel 6528: =cut
                   6529: 
1.200     albertel 6530: sub reset_skipping_status {
                   6531:     my ($scanlines,$scan_data)=&scantron_getfile();
                   6532:     &scan_data($scan_data,'remember_skipping',undef,1);
                   6533:     &scantron_putfile(undef,$scan_data);
                   6534: }
                   6535: 
1.423     albertel 6536: =pod
                   6537: 
                   6538: =item start_skipping
                   6539: 
1.424     albertel 6540:    Marks a scanline to be skipped. 
                   6541: 
1.423     albertel 6542: =cut
                   6543: 
1.376     albertel 6544: sub start_skipping {
1.200     albertel 6545:     my ($scan_data,$i)=@_;
                   6546:     my %remembered=split(':',&scan_data($scan_data,'remember_skipping'));
1.376     albertel 6547:     if ($env{'form.scantron_options_redo'} =~ /^redo_/) {
                   6548: 	$remembered{$i}=2;
                   6549:     } else {
                   6550: 	$remembered{$i}=1;
                   6551:     }
1.200     albertel 6552:     &scan_data($scan_data,'remember_skipping',join(':',%remembered));
                   6553: }
                   6554: 
1.423     albertel 6555: =pod
                   6556: 
                   6557: =item should_be_skipped
                   6558: 
1.424     albertel 6559:    Checks whether a scanline should be skipped.
                   6560: 
1.423     albertel 6561: =cut
                   6562: 
1.200     albertel 6563: sub should_be_skipped {
1.376     albertel 6564:     my ($scanlines,$scan_data,$i)=@_;
1.257     albertel 6565:     if ($env{'form.scantron_options_redo'} !~ /^redo_/) {
1.200     albertel 6566: 	# not redoing old skips
1.376     albertel 6567: 	if ($scanlines->{'skipped'}[$i]) { return 1; }
1.200     albertel 6568: 	return 0;
                   6569:     }
                   6570:     my %remembered=split(':',&scan_data($scan_data,'remember_skipping'));
1.376     albertel 6571: 
                   6572:     if (exists($remembered{$i}) && $remembered{$i} != 2 ) {
                   6573: 	return 0;
                   6574:     }
1.200     albertel 6575:     return 1;
                   6576: }
                   6577: 
1.423     albertel 6578: =pod
                   6579: 
                   6580: =item remember_current_skipped
                   6581: 
1.424     albertel 6582:    Discovers what scanlines are in the scantron_skipped_<filename>
                   6583:    file and remembers them into scan_data for later use.
                   6584: 
1.423     albertel 6585: =cut
                   6586: 
1.200     albertel 6587: sub remember_current_skipped {
                   6588:     my ($scanlines,$scan_data)=&scantron_getfile();
                   6589:     my %to_remember;
                   6590:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
                   6591: 	if ($scanlines->{'skipped'}[$i]) {
                   6592: 	    $to_remember{$i}=1;
                   6593: 	}
                   6594:     }
1.376     albertel 6595: 
1.200     albertel 6596:     &scan_data($scan_data,'remember_skipping',join(':',%to_remember));
                   6597:     &scantron_putfile(undef,$scan_data);
                   6598: }
                   6599: 
1.423     albertel 6600: =pod
                   6601: 
                   6602: =item check_for_error
                   6603: 
1.424     albertel 6604:     Checks if there was an error when attempting to remove a specific
1.659     raeburn  6605:     scantron_.. bubblesheet data file. Prints out an error if
1.424     albertel 6606:     something went wrong.
                   6607: 
1.423     albertel 6608: =cut
                   6609: 
1.200     albertel 6610: sub check_for_error {
                   6611:     my ($r,$result)=@_;
                   6612:     if ($result ne 'ok' && $result ne 'not_found' ) {
1.492     albertel 6613: 	$r->print(&mt("An error occurred ([_1]) when trying to remove the existing corrections.",$result));
1.200     albertel 6614:     }
                   6615: }
1.157     albertel 6616: 
1.423     albertel 6617: =pod
                   6618: 
                   6619: =item scantron_warning_screen
                   6620: 
1.424     albertel 6621:    Interstitial screen to make sure the operator has selected the
                   6622:    correct options before we start the validation phase.
                   6623: 
1.423     albertel 6624: =cut
                   6625: 
1.203     albertel 6626: sub scantron_warning_screen {
1.650     raeburn  6627:     my ($button_text,$symb)=@_;
1.257     albertel 6628:     my $title=&Apache::lonnet::gettitle($env{'form.selectpage'});
1.284     albertel 6629:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.373     albertel 6630:     my $CODElist;
1.284     albertel 6631:     if ($scantron_config{'CODElocation'} &&
                   6632: 	$scantron_config{'CODEstart'} &&
                   6633: 	$scantron_config{'CODElength'}) {
                   6634: 	$CODElist=$env{'form.scantron_CODElist'};
1.721     bisitz   6635: 	if ($env{'form.scantron_CODElist'} eq '') { $CODElist='<span class="LC_warning">'.&mt('None').'</span>'; }
1.284     albertel 6636: 	$CODElist=
1.492     albertel 6637: 	    '<tr><td><b>'.&mt('List of CODES to validate against:').'</b></td><td><tt>'.
1.373     albertel 6638: 	    $env{'form.scantron_CODElist'}.'</tt></td></tr>';
1.284     albertel 6639:     }
1.663     raeburn  6640:     my $lastbubblepoints;
                   6641:     if ($env{'form.scantron_lastbubblepoints'} ne '') {
                   6642:         $lastbubblepoints =
                   6643:             '<tr><td><b>'.&mt('Hand-graded items: points from last bubble in row').'</b></td><td><tt>'.
                   6644:             $env{'form.scantron_lastbubblepoints'}.'</tt></td></tr>';
                   6645:     }
1.492     albertel 6646:     return ('
1.203     albertel 6647: <p>
1.492     albertel 6648: <span class="LC_warning">
1.705     raeburn  6649: '.&mt("Please double check the information below before clicking on '[_1]'",&mt($button_text)).'</span>
1.203     albertel 6650: </p>
                   6651: <table>
1.492     albertel 6652: <tr><td><b>'.&mt('Sequence to be Graded:').'</b></td><td>'.$title.'</td></tr>
                   6653: <tr><td><b>'.&mt('Data File that will be used:').'</b></td><td><tt>'.$env{'form.scantron_selectfile'}.'</tt></td></tr>
1.663     raeburn  6654: '.$CODElist.$lastbubblepoints.'
1.203     albertel 6655: </table>
1.680     raeburn  6656: <p> '.&mt("If this information is correct, please click on '[_1]'.",&mt($button_text)).'<br />
1.650     raeburn  6657: '.&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 6658: 
                   6659: <br />
1.492     albertel 6660: ');
1.203     albertel 6661: }
                   6662: 
1.423     albertel 6663: =pod
                   6664: 
                   6665: =item scantron_do_warning
                   6666: 
1.424     albertel 6667:    Check if the operator has picked something for all required
                   6668:    fields. Error out if something is missing.
                   6669: 
1.423     albertel 6670: =cut
                   6671: 
1.203     albertel 6672: sub scantron_do_warning {
1.608     www      6673:     my ($r,$symb)=@_;
1.203     albertel 6674:     if (!$symb) {return '';}
1.324     albertel 6675:     my $default_form_data=&defaultFormData($symb);
1.203     albertel 6676:     $r->print(&scantron_form_start().$default_form_data);
1.257     albertel 6677:     if ( $env{'form.selectpage'} eq '' ||
                   6678: 	 $env{'form.scantron_selectfile'} eq '' ||
                   6679: 	 $env{'form.scantron_format'} eq '' ) {
1.642     raeburn  6680: 	$r->print("<p>".&mt('You have forgotten to specify some information. Please go Back and try again.')."</p>");
1.257     albertel 6681: 	if ( $env{'form.selectpage'} eq '') {
1.492     albertel 6682: 	    $r->print('<p><span class="LC_error">'.&mt('You have not selected a Sequence to grade').'</span></p>');
1.237     albertel 6683: 	} 
1.257     albertel 6684: 	if ( $env{'form.scantron_selectfile'} eq '') {
1.642     raeburn  6685: 	    $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 6686: 	} 
1.257     albertel 6687: 	if ( $env{'form.scantron_format'} eq '') {
1.642     raeburn  6688: 	    $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 6689: 	} 
                   6690:     } else {
1.650     raeburn  6691: 	my $warning=&scantron_warning_screen('Grading: Validate Records',$symb);
1.663     raeburn  6692:         my $bubbledbyhand=&hand_bubble_option();
1.492     albertel 6693: 	$r->print('
1.663     raeburn  6694: '.$warning.$bubbledbyhand.'
1.492     albertel 6695: <input type="submit" name="submit" value="'.&mt('Grading: Validate Records').'" />
1.203     albertel 6696: <input type="hidden" name="command" value="scantron_validate" />
1.492     albertel 6697: ');
1.237     albertel 6698:     }
1.614     www      6699:     $r->print("</form><br />");
1.203     albertel 6700:     return '';
                   6701: }
                   6702: 
1.423     albertel 6703: =pod
                   6704: 
                   6705: =item scantron_form_start
                   6706: 
1.424     albertel 6707:     html hidden input for remembering all selected grading options
                   6708: 
1.423     albertel 6709: =cut
                   6710: 
1.203     albertel 6711: sub scantron_form_start {
                   6712:     my ($max_bubble)=@_;
                   6713:     my $result= <<SCANTRONFORM;
                   6714: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantronupload">
1.257     albertel 6715:   <input type="hidden" name="selectpage" value="$env{'form.selectpage'}" />
                   6716:   <input type="hidden" name="scantron_format" value="$env{'form.scantron_format'}" />
                   6717:   <input type="hidden" name="scantron_selectfile" value="$env{'form.scantron_selectfile'}" />
1.218     albertel 6718:   <input type="hidden" name="scantron_maxbubble" value="$max_bubble" />
1.257     albertel 6719:   <input type="hidden" name="scantron_CODElist" value="$env{'form.scantron_CODElist'}" />
                   6720:   <input type="hidden" name="scantron_CODEunique" value="$env{'form.scantron_CODEunique'}" />
                   6721:   <input type="hidden" name="scantron_options_redo" value="$env{'form.scantron_options_redo'}" />
                   6722:   <input type="hidden" name="scantron_options_ignore" value="$env{'form.scantron_options_ignore'}" />
1.331     albertel 6723:   <input type="hidden" name="scantron_options_hidden" value="$env{'form.scantron_options_hidden'}" />
1.203     albertel 6724: SCANTRONFORM
1.447     foxr     6725: 
                   6726:   my $line = 0;
                   6727:     while (defined($env{"form.scantron.bubblelines.$line"})) {
                   6728:        my $chunk =
                   6729: 	   '<input type="hidden" name="scantron.bubblelines.'.$line.'" value="'.$env{"form.scantron.bubblelines.$line"}.'" />'."\n";
1.448     foxr     6730:        $chunk .=
                   6731: 	   '<input type="hidden" name="scantron.first_bubble_line.'.$line.'" value="'.$env{"form.scantron.first_bubble_line.$line"}.'" />'."\n";
1.503     raeburn  6732:        $chunk .= 
                   6733:            '<input type="hidden" name="scantron.sub_bubblelines.'.$line.'" value="'.$env{"form.scantron.sub_bubblelines.$line"}.'" />'."\n";
1.504     raeburn  6734:        $chunk .=
                   6735:            '<input type="hidden" name="scantron.responsetype.'.$line.'" value="'.$env{"form.scantron.responsetype.$line"}.'" />'."\n";
1.691     raeburn  6736:        $chunk .=
                   6737:            '<input type="hidden" name="scantron.residpart.'.$line.'" value="'.$env{"form.scantron.residpart.$line"}.'" />'."\n";
1.447     foxr     6738:        $result .= $chunk;
                   6739:        $line++;
1.691     raeburn  6740:     }
1.203     albertel 6741:     return $result;
                   6742: }
                   6743: 
1.423     albertel 6744: =pod
                   6745: 
                   6746: =item scantron_validate_file
                   6747: 
1.659     raeburn  6748:     Dispatch routine for doing validation of a bubblesheet data file.
1.424     albertel 6749: 
                   6750:     Also processes any necessary information resets that need to
                   6751:     occur before validation begins (ignore previous corrections,
                   6752:     restarting the skipped records processing)
                   6753: 
1.423     albertel 6754: =cut
                   6755: 
1.157     albertel 6756: sub scantron_validate_file {
1.608     www      6757:     my ($r,$symb) = @_;
1.157     albertel 6758:     if (!$symb) {return '';}
1.324     albertel 6759:     my $default_form_data=&defaultFormData($symb);
1.200     albertel 6760:     
1.703     bisitz   6761:     # do the detection of only doing skipped records first before we delete
1.424     albertel 6762:     # them when doing the corrections reset
1.257     albertel 6763:     if ($env{'form.scantron_options_redo'} ne 'redo_skipped_ready') {
1.200     albertel 6764: 	&reset_skipping_status();
                   6765:     }
1.257     albertel 6766:     if ($env{'form.scantron_options_redo'} eq 'redo_skipped') {
1.200     albertel 6767: 	&remember_current_skipped();
1.257     albertel 6768: 	$env{'form.scantron_options_redo'}='redo_skipped_ready';
1.200     albertel 6769:     }
                   6770: 
1.257     albertel 6771:     if ($env{'form.scantron_options_ignore'} eq 'ignore_corrections') {
1.200     albertel 6772: 	&check_for_error($r,&scantron_remove_file('corrected'));
                   6773: 	&check_for_error($r,&scantron_remove_file('skipped'));
                   6774: 	&check_for_error($r,&scantron_remove_scan_data());
1.257     albertel 6775: 	$env{'form.scantron_options_ignore'}='done';
1.192     albertel 6776:     }
1.200     albertel 6777: 
1.257     albertel 6778:     if ($env{'form.scantron_corrections'}) {
1.157     albertel 6779: 	&scantron_process_corrections($r);
                   6780:     }
1.503     raeburn  6781:     $r->print('<p>'.&mt('Gathering necessary information.').'</p>');$r->rflush();
1.157     albertel 6782:     #get the student pick code ready
                   6783:     $r->print(&Apache::loncommon::studentbrowser_javascript());
1.582     raeburn  6784:     my $nav_error;
1.649     raeburn  6785:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
                   6786:     my $max_bubble=&scantron_get_maxbubble(\$nav_error,\%scantron_config);
1.582     raeburn  6787:     if ($nav_error) {
                   6788:         $r->print(&navmap_errormsg());
                   6789:         return '';
                   6790:     }
1.203     albertel 6791:     my $result=&scantron_form_start($max_bubble).$default_form_data;
1.663     raeburn  6792:     if ($env{'form.scantron_lastbubblepoints'} ne '') {
                   6793:         $result .= '<input type="hidden" name="scantron_lastbubblepoints" value="'.$env{'form.scantron_lastbubblepoints'}.'" />';
                   6794:     }
1.157     albertel 6795:     $r->print($result);
                   6796:     
1.334     albertel 6797:     my @validate_phases=( 'sequence',
                   6798: 			  'ID',
1.157     albertel 6799: 			  'CODE',
                   6800: 			  'doublebubble',
                   6801: 			  'missingbubbles');
1.257     albertel 6802:     if (!$env{'form.validatepass'}) {
                   6803: 	$env{'form.validatepass'} = 0;
1.157     albertel 6804:     }
1.257     albertel 6805:     my $currentphase=$env{'form.validatepass'};
1.157     albertel 6806: 
1.448     foxr     6807: 
1.157     albertel 6808:     my $stop=0;
                   6809:     while (!$stop && $currentphase < scalar(@validate_phases)) {
1.503     raeburn  6810: 	$r->print(&mt('Validating '.$validate_phases[$currentphase]).'<br />');
1.157     albertel 6811: 	$r->rflush();
1.691     raeburn  6812:      
1.157     albertel 6813: 	my $which="scantron_validate_".$validate_phases[$currentphase];
                   6814: 	{
                   6815: 	    no strict 'refs';
                   6816: 	    ($stop,$currentphase)=&$which($r,$currentphase);
                   6817: 	}
                   6818:     }
                   6819:     if (!$stop) {
1.650     raeburn  6820: 	my $warning=&scantron_warning_screen('Start Grading',$symb);
1.542     raeburn  6821: 	$r->print(&mt('Validation process complete.').'<br />'.
                   6822:                   $warning.
                   6823:                   &mt('Perform verification for each student after storage of submissions?').
                   6824:                   '&nbsp;<span class="LC_nobreak"><label>'.
                   6825:                   '<input type="radio" name="verifyrecord" value="1" />'.&mt('Yes').'</label>'.
                   6826:                   ('&nbsp;'x3).'<label>'.
                   6827:                   '<input type="radio" name="verifyrecord" value="0" checked="checked" />'.&mt('No').
                   6828:                   '</label></span><br />'.
                   6829:                   &mt('Grading will take longer if you use verification.').'<br />'.
1.650     raeburn  6830:                   &mt('Otherwise, Grade/Manage/Review Bubblesheets [_1] Review bubblesheet data can be used once grading is complete.','&raquo;').'<br /><br />'.
1.542     raeburn  6831:                   '<input type="submit" name="submit" value="'.&mt('Start Grading').'" />'.
                   6832:                   '<input type="hidden" name="command" value="scantron_process" />'."\n");
1.157     albertel 6833:     } else {
                   6834: 	$r->print('<input type="hidden" name="command" value="scantron_validate" />');
                   6835: 	$r->print("<input type='hidden' name='validatepass' value='".$currentphase."' />");
                   6836:     }
                   6837:     if ($stop) {
1.334     albertel 6838: 	if ($validate_phases[$currentphase] eq 'sequence') {
1.539     riegler  6839: 	    $r->print('<input type="submit" name="submit" value="'.&mt('Ignore').' &rarr; " />');
1.492     albertel 6840: 	    $r->print(' '.&mt('this error').' <br />');
1.334     albertel 6841: 
1.650     raeburn  6842: 	    $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 6843: 	} else {
1.503     raeburn  6844:             if ($validate_phases[$currentphase] eq 'doublebubble' || $validate_phases[$currentphase] eq 'missingbubbles') {
1.539     riegler  6845: 	        $r->print('<input type="button" name="submitbutton" value="'.&mt('Continue').' &rarr;" onclick="javascript:verify_bubble_radio(this.form)" />');
1.503     raeburn  6846:             } else {
1.539     riegler  6847:                 $r->print('<input type="submit" name="submit" value="'.&mt('Continue').' &rarr;" />');
1.503     raeburn  6848:             }
1.492     albertel 6849: 	    $r->print(' '.&mt('using corrected info').' <br />');
                   6850: 	    $r->print("<input type='submit' value='".&mt("Skip")."' name='scantron_skip_record' />");
                   6851: 	    $r->print(" ".&mt("this scanline saving it for later."));
1.334     albertel 6852: 	}
1.157     albertel 6853:     }
1.614     www      6854:     $r->print(" </form><br />");
1.157     albertel 6855:     return '';
                   6856: }
                   6857: 
1.423     albertel 6858: 
                   6859: =pod
                   6860: 
                   6861: =item scantron_remove_file
                   6862: 
1.659     raeburn  6863:    Removes the requested bubblesheet data file, makes sure that
1.424     albertel 6864:    scantron_original_<filename> is never removed
                   6865: 
                   6866: 
1.423     albertel 6867: =cut
                   6868: 
1.200     albertel 6869: sub scantron_remove_file {
1.192     albertel 6870:     my ($which)=@_;
1.257     albertel 6871:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   6872:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.192     albertel 6873:     my $file='scantron_';
1.200     albertel 6874:     if ($which eq 'corrected' || $which eq 'skipped') {
                   6875: 	$file.=$which.'_';
1.192     albertel 6876:     } else {
                   6877: 	return 'refused';
                   6878:     }
1.257     albertel 6879:     $file.=$env{'form.scantron_selectfile'};
1.200     albertel 6880:     return &Apache::lonnet::removeuserfile($cname,$cdom,$file);
                   6881: }
                   6882: 
1.423     albertel 6883: 
                   6884: =pod
                   6885: 
                   6886: =item scantron_remove_scan_data
                   6887: 
1.659     raeburn  6888:    Removes all scan_data correction for the requested bubblesheet
1.424     albertel 6889:    data file.  (In the case that both the are doing skipped records we need
                   6890:    to remember the old skipped lines for the time being so that element
                   6891:    persists for a while.)
                   6892: 
1.423     albertel 6893: =cut
                   6894: 
1.200     albertel 6895: sub scantron_remove_scan_data {
1.257     albertel 6896:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   6897:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.192     albertel 6898:     my @keys=&Apache::lonnet::getkeys('nohist_scantrondata',$cdom,$cname);
                   6899:     my @todelete;
1.257     albertel 6900:     my $filename=$env{'form.scantron_selectfile'};
1.192     albertel 6901:     foreach my $key (@keys) {
                   6902: 	if ($key=~/^\Q$filename\E_/) {
1.257     albertel 6903: 	    if ($env{'form.scantron_options_redo'} eq 'redo_skipped_ready' &&
1.200     albertel 6904: 		$key=~/remember_skipping/) {
                   6905: 		next;
                   6906: 	    }
1.192     albertel 6907: 	    push(@todelete,$key);
                   6908: 	}
                   6909:     }
1.200     albertel 6910:     my $result;
1.192     albertel 6911:     if (@todelete) {
1.491     albertel 6912: 	$result = &Apache::lonnet::del('nohist_scantrondata',
                   6913: 				       \@todelete,$cdom,$cname);
                   6914:     } else {
                   6915: 	$result = 'ok';
1.192     albertel 6916:     }
                   6917:     return $result;
                   6918: }
                   6919: 
1.423     albertel 6920: 
                   6921: =pod
                   6922: 
                   6923: =item scantron_getfile
                   6924: 
1.659     raeburn  6925:     Fetches the requested bubblesheet data file (all 3 versions), and
1.424     albertel 6926:     the scan_data hash
                   6927:   
                   6928:   Arguments:
                   6929:     None
                   6930: 
                   6931:   Returns:
                   6932:     2 hash references
                   6933: 
                   6934:      - first one has 
                   6935:          orig      -
                   6936:          corrected -
                   6937:          skipped   -  each of which points to an array ref of the specified
                   6938:                       file broken up into individual lines
                   6939:          count     - number of scanlines
                   6940:  
                   6941:      - second is the scan_data hash possible keys are
1.425     albertel 6942:        ($number refers to scanline numbered $number and thus the key affects
                   6943:         only that scanline
                   6944:         $bubline refers to the specific bubble line element and the aspects
                   6945:         refers to that specific bubble line element)
                   6946: 
                   6947:        $number.user - username:domain to use
                   6948:        $number.CODE_ignore_dup 
                   6949:                     - ignore the duplicate CODE error 
                   6950:        $number.useCODE
                   6951:                     - use the CODE in the scanline as is
                   6952:        $number.no_bubble.$bubline
                   6953:                     - it is valid that there is no bubbled in bubble
                   6954:                       at $number $bubline
                   6955:        remember_skipping
                   6956:                     - a frozen hash containing keys of $number and values
                   6957:                       of either 
                   6958:                         1 - we are on a 'do skipped records pass' and plan
                   6959:                             on processing this line
                   6960:                         2 - we are on a 'do skipped records pass' and this
                   6961:                             scanline has been marked to skip yet again
1.424     albertel 6962: 
1.423     albertel 6963: =cut
                   6964: 
1.157     albertel 6965: sub scantron_getfile {
1.200     albertel 6966:     #FIXME really would prefer a scantron directory
1.257     albertel 6967:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   6968:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.157     albertel 6969:     my $lines;
                   6970:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
1.257     albertel 6971: 		       'scantron_orig_'.$env{'form.scantron_selectfile'});
1.157     albertel 6972:     my %scanlines;
                   6973:     $scanlines{'orig'}=[(split("\n",$lines,-1))];
                   6974:     my $temp=$scanlines{'orig'};
                   6975:     $scanlines{'count'}=$#$temp;
                   6976: 
                   6977:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
1.257     albertel 6978: 		       'scantron_corrected_'.$env{'form.scantron_selectfile'});
1.157     albertel 6979:     if ($lines eq '-1') {
                   6980: 	$scanlines{'corrected'}=[];
                   6981:     } else {
                   6982: 	$scanlines{'corrected'}=[(split("\n",$lines,-1))];
                   6983:     }
                   6984:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
1.257     albertel 6985: 		       'scantron_skipped_'.$env{'form.scantron_selectfile'});
1.157     albertel 6986:     if ($lines eq '-1') {
                   6987: 	$scanlines{'skipped'}=[];
                   6988:     } else {
                   6989: 	$scanlines{'skipped'}=[(split("\n",$lines,-1))];
                   6990:     }
1.175     albertel 6991:     my @tmp=&Apache::lonnet::dump('nohist_scantrondata',$cdom,$cname);
1.157     albertel 6992:     if ($tmp[0] =~ /^(error:|no_such_host)/) { @tmp=(); }
                   6993:     my %scan_data = @tmp;
                   6994:     return (\%scanlines,\%scan_data);
                   6995: }
                   6996: 
1.423     albertel 6997: =pod
                   6998: 
                   6999: =item lonnet_putfile
                   7000: 
1.424     albertel 7001:    Wrapper routine to call &Apache::lonnet::finishuserfileupload
                   7002: 
                   7003:  Arguments:
                   7004:    $contents - data to store
                   7005:    $filename - filename to store $contents into
                   7006: 
                   7007:  Returns:
                   7008:    result value from &Apache::lonnet::finishuserfileupload
                   7009: 
1.423     albertel 7010: =cut
                   7011: 
1.157     albertel 7012: sub lonnet_putfile {
                   7013:     my ($contents,$filename)=@_;
1.257     albertel 7014:     my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   7015:     my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   7016:     $env{'form.sillywaytopassafilearound'}=$contents;
1.275     albertel 7017:     &Apache::lonnet::finishuserfileupload($docuname,$docudom,'sillywaytopassafilearound',$filename);
1.157     albertel 7018: 
                   7019: }
                   7020: 
1.423     albertel 7021: =pod
                   7022: 
                   7023: =item scantron_putfile
                   7024: 
1.659     raeburn  7025:     Stores the current version of the bubblesheet data files, and the
1.424     albertel 7026:     scan_data hash. (Does not modify the original version only the
                   7027:     corrected and skipped versions.
                   7028: 
                   7029:  Arguments:
                   7030:     $scanlines - hash ref that looks like the first return value from
                   7031:                  &scantron_getfile()
                   7032:     $scan_data - hash ref that looks like the second return value from
                   7033:                  &scantron_getfile()
                   7034: 
1.423     albertel 7035: =cut
                   7036: 
1.157     albertel 7037: sub scantron_putfile {
                   7038:     my ($scanlines,$scan_data) = @_;
1.200     albertel 7039:     #FIXME really would prefer a scantron directory
1.257     albertel 7040:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   7041:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.200     albertel 7042:     if ($scanlines) {
                   7043: 	my $prefix='scantron_';
1.157     albertel 7044: # no need to update orig, shouldn't change
                   7045: #   &lonnet_putfile(join("\n",@{$scanlines->{'orig'}}),$prefix.'orig_'.
1.257     albertel 7046: #		    $env{'form.scantron_selectfile'});
1.200     albertel 7047: 	&lonnet_putfile(join("\n",@{$scanlines->{'corrected'}}),
                   7048: 			$prefix.'corrected_'.
1.257     albertel 7049: 			$env{'form.scantron_selectfile'});
1.200     albertel 7050: 	&lonnet_putfile(join("\n",@{$scanlines->{'skipped'}}),
                   7051: 			$prefix.'skipped_'.
1.257     albertel 7052: 			$env{'form.scantron_selectfile'});
1.200     albertel 7053:     }
1.175     albertel 7054:     &Apache::lonnet::put('nohist_scantrondata',$scan_data,$cdom,$cname);
1.157     albertel 7055: }
                   7056: 
1.423     albertel 7057: =pod
                   7058: 
                   7059: =item scantron_get_line
                   7060: 
1.424     albertel 7061:    Returns the correct version of the scanline
                   7062: 
                   7063:  Arguments:
                   7064:     $scanlines - hash ref that looks like the first return value from
                   7065:                  &scantron_getfile()
                   7066:     $scan_data - hash ref that looks like the second return value from
                   7067:                  &scantron_getfile()
                   7068:     $i         - number of the requested line (starts at 0)
                   7069: 
                   7070:  Returns:
                   7071:    A scanline, (either the original or the corrected one if it
                   7072:    exists), or undef if the requested scanline should be
                   7073:    skipped. (Either because it's an skipped scanline, or it's an
                   7074:    unskipped scanline and we are not doing a 'do skipped scanlines'
                   7075:    pass.
                   7076: 
1.423     albertel 7077: =cut
                   7078: 
1.157     albertel 7079: sub scantron_get_line {
1.200     albertel 7080:     my ($scanlines,$scan_data,$i)=@_;
1.376     albertel 7081:     if (&should_be_skipped($scanlines,$scan_data,$i)) { return undef; }
                   7082:     #if ($scanlines->{'skipped'}[$i]) { return undef; }
1.157     albertel 7083:     if ($scanlines->{'corrected'}[$i]) {return $scanlines->{'corrected'}[$i];}
                   7084:     return $scanlines->{'orig'}[$i]; 
                   7085: }
                   7086: 
1.423     albertel 7087: =pod
                   7088: 
                   7089: =item scantron_todo_count
                   7090: 
1.424     albertel 7091:     Counts the number of scanlines that need processing.
                   7092: 
                   7093:  Arguments:
                   7094:     $scanlines - hash ref that looks like the first return value from
                   7095:                  &scantron_getfile()
                   7096:     $scan_data - hash ref that looks like the second return value from
                   7097:                  &scantron_getfile()
                   7098: 
                   7099:  Returns:
                   7100:     $count - number of scanlines to process
                   7101: 
1.423     albertel 7102: =cut
                   7103: 
1.200     albertel 7104: sub get_todo_count {
                   7105:     my ($scanlines,$scan_data)=@_;
                   7106:     my $count=0;
                   7107:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
                   7108: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
                   7109: 	if ($line=~/^[\s\cz]*$/) { next; }
                   7110: 	$count++;
                   7111:     }
                   7112:     return $count;
                   7113: }
                   7114: 
1.423     albertel 7115: =pod
                   7116: 
                   7117: =item scantron_put_line
                   7118: 
1.659     raeburn  7119:     Updates the 'corrected' or 'skipped' versions of the bubblesheet
1.424     albertel 7120:     data file.
                   7121: 
                   7122:  Arguments:
                   7123:     $scanlines - hash ref that looks like the first return value from
                   7124:                  &scantron_getfile()
                   7125:     $scan_data - hash ref that looks like the second return value from
                   7126:                  &scantron_getfile()
                   7127:     $i         - line number to update
                   7128:     $newline   - contents of the updated scanline
                   7129:     $skip      - if true make the line for skipping and update the
                   7130:                  'skipped' file
                   7131: 
1.423     albertel 7132: =cut
                   7133: 
1.157     albertel 7134: sub scantron_put_line {
1.200     albertel 7135:     my ($scanlines,$scan_data,$i,$newline,$skip)=@_;
1.157     albertel 7136:     if ($skip) {
                   7137: 	$scanlines->{'skipped'}[$i]=$newline;
1.376     albertel 7138: 	&start_skipping($scan_data,$i);
1.157     albertel 7139: 	return;
                   7140:     }
                   7141:     $scanlines->{'corrected'}[$i]=$newline;
                   7142: }
                   7143: 
1.423     albertel 7144: =pod
                   7145: 
                   7146: =item scantron_clear_skip
                   7147: 
1.424     albertel 7148:    Remove a line from the 'skipped' file
                   7149: 
                   7150:  Arguments:
                   7151:     $scanlines - hash ref that looks like the first return value from
                   7152:                  &scantron_getfile()
                   7153:     $scan_data - hash ref that looks like the second return value from
                   7154:                  &scantron_getfile()
                   7155:     $i         - line number to update
                   7156: 
1.423     albertel 7157: =cut
                   7158: 
1.376     albertel 7159: sub scantron_clear_skip {
                   7160:     my ($scanlines,$scan_data,$i)=@_;
                   7161:     if (exists($scanlines->{'skipped'}[$i])) {
                   7162: 	undef($scanlines->{'skipped'}[$i]);
                   7163: 	return 1;
                   7164:     }
                   7165:     return 0;
                   7166: }
                   7167: 
1.423     albertel 7168: =pod
                   7169: 
                   7170: =item scantron_filter_not_exam
                   7171: 
1.424     albertel 7172:    Filter routine used by &Apache::lonnavmaps::retrieveResources(), to
                   7173:    filter out resources that are not marked as 'exam' mode
                   7174: 
1.423     albertel 7175: =cut
                   7176: 
1.334     albertel 7177: sub scantron_filter_not_exam {
                   7178:     my ($curres)=@_;
                   7179:     
                   7180:     if (ref($curres) && $curres->is_problem() && !$curres->is_exam()) {
                   7181: 	# if the user has asked to not have either hidden
                   7182: 	# or 'randomout' controlled resources to be graded
                   7183: 	# don't include them
                   7184: 	if ($env{'form.scantron_options_hidden'} eq 'ignore_hidden'
                   7185: 	    && $curres->randomout) {
                   7186: 	    return 0;
                   7187: 	}
                   7188: 	return 1;
                   7189:     }
                   7190:     return 0;
                   7191: }
                   7192: 
1.423     albertel 7193: =pod
                   7194: 
                   7195: =item scantron_validate_sequence
                   7196: 
1.424     albertel 7197:     Validates the selected sequence, checking for resource that are
                   7198:     not set to exam mode.
                   7199: 
1.423     albertel 7200: =cut
                   7201: 
1.334     albertel 7202: sub scantron_validate_sequence {
                   7203:     my ($r,$currentphase) = @_;
                   7204: 
                   7205:     my $navmap=Apache::lonnavmaps::navmap->new();
1.582     raeburn  7206:     unless (ref($navmap)) {
                   7207:         $r->print(&navmap_errormsg());
                   7208:         return (1,$currentphase);
                   7209:     }
1.334     albertel 7210:     my (undef,undef,$sequence)=
                   7211: 	&Apache::lonnet::decode_symb($env{'form.selectpage'});
                   7212: 
                   7213:     my $map=$navmap->getResourceByUrl($sequence);
                   7214: 
                   7215:     $r->print('<input type="hidden" name="validate_sequence_exam"
                   7216:                                     value="ignore" />');
                   7217:     if ($env{'form.validate_sequence_exam'} ne 'ignore') {
                   7218: 	my @resources=
                   7219: 	    $navmap->retrieveResources($map,\&scantron_filter_not_exam,1,0);
                   7220: 	if (@resources) {
1.675     bisitz   7221: 	    $r->print(
                   7222:                 '<p class="LC_warning">'
                   7223:                .&mt('Some resources in the sequence currently are not set to'
1.684     bisitz   7224:                    .' bubblesheet exam mode. Grading these resources currently may not'
1.675     bisitz   7225:                    .' work correctly.')
                   7226:                .'</p>'
                   7227:             );
1.334     albertel 7228: 	    return (1,$currentphase);
                   7229: 	}
                   7230:     }
                   7231: 
                   7232:     return (0,$currentphase+1);
                   7233: }
                   7234: 
1.423     albertel 7235: 
                   7236: 
1.157     albertel 7237: sub scantron_validate_ID {
                   7238:     my ($r,$currentphase) = @_;
                   7239:     
                   7240:     #get student info
                   7241:     my $classlist=&Apache::loncoursedata::get_classlist();
                   7242:     my %idmap=&username_to_idmap($classlist);
                   7243: 
                   7244:     #get scantron line setup
1.257     albertel 7245:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.157     albertel 7246:     my ($scanlines,$scan_data)=&scantron_getfile();
1.582     raeburn  7247: 
                   7248:     my $nav_error;
1.649     raeburn  7249:     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # parse needs the bubble_lines.. array.
1.582     raeburn  7250:     if ($nav_error) {
                   7251:         $r->print(&navmap_errormsg());
                   7252:         return(1,$currentphase);
                   7253:     }
1.157     albertel 7254: 
                   7255:     my %found=('ids'=>{},'usernames'=>{});
                   7256:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
1.200     albertel 7257: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.157     albertel 7258: 	if ($line=~/^[\s\cz]*$/) { next; }
                   7259: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
                   7260: 						 $scan_data);
                   7261: 	my $id=$$scan_record{'scantron.ID'};
                   7262: 	my $found;
                   7263: 	foreach my $checkid (keys(%idmap)) {
                   7264: 	    if (lc($checkid) eq lc($id)) { $found=$checkid;last; }
                   7265: 	}
                   7266: 	if ($found) {
                   7267: 	    my $username=$idmap{$found};
                   7268: 	    if ($found{'ids'}{$found}) {
                   7269: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
                   7270: 					 $line,'duplicateID',$found);
1.194     albertel 7271: 		return(1,$currentphase);
1.157     albertel 7272: 	    } elsif ($found{'usernames'}{$username}) {
                   7273: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
                   7274: 					 $line,'duplicateID',$username);
1.194     albertel 7275: 		return(1,$currentphase);
1.157     albertel 7276: 	    }
1.186     albertel 7277: 	    #FIXME store away line we previously saw the ID on to use above
1.157     albertel 7278: 	    $found{'ids'}{$found}++;
                   7279: 	    $found{'usernames'}{$username}++;
                   7280: 	} else {
                   7281: 	    if ($id =~ /^\s*$/) {
1.158     albertel 7282: 		my $username=&scan_data($scan_data,"$i.user");
1.157     albertel 7283: 		if (defined($username) && $found{'usernames'}{$username}) {
                   7284: 		    &scantron_get_correction($r,$i,$scan_record,
                   7285: 					     \%scantron_config,
                   7286: 					     $line,'duplicateID',$username);
1.194     albertel 7287: 		    return(1,$currentphase);
1.157     albertel 7288: 		} elsif (!defined($username)) {
                   7289: 		    &scantron_get_correction($r,$i,$scan_record,
                   7290: 					     \%scantron_config,
                   7291: 					     $line,'incorrectID');
1.194     albertel 7292: 		    return(1,$currentphase);
1.157     albertel 7293: 		}
                   7294: 		$found{'usernames'}{$username}++;
                   7295: 	    } else {
                   7296: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
                   7297: 					 $line,'incorrectID');
1.194     albertel 7298: 		return(1,$currentphase);
1.157     albertel 7299: 	    }
                   7300: 	}
                   7301:     }
                   7302: 
                   7303:     return (0,$currentphase+1);
                   7304: }
                   7305: 
1.423     albertel 7306: 
1.157     albertel 7307: sub scantron_get_correction {
1.691     raeburn  7308:     my ($r,$i,$scan_record,$scan_config,$line,$error,$arg,
                   7309:         $randomorder,$randompick,$respnumlookup,$startline)=@_;
1.454     banghart 7310: #FIXME in the case of a duplicated ID the previous line, probably need
1.157     albertel 7311: #to show both the current line and the previous one and allow skipping
                   7312: #the previous one or the current one
                   7313: 
1.333     albertel 7314:     if ( $$scan_record{'scantron.PaperID'} =~ /\S/) {
1.658     bisitz   7315:         $r->print(
                   7316:             '<p class="LC_warning">'
                   7317:            .&mt('An error was detected ([_1]) for PaperID [_2]',
                   7318:                 "<b>$error</b>",
                   7319:                 '<tt>'.$$scan_record{'scantron.PaperID'}.'</tt>')
                   7320:            ."</p> \n");
1.157     albertel 7321:     } else {
1.658     bisitz   7322:         $r->print(
                   7323:             '<p class="LC_warning">'
                   7324:            .&mt('An error was detected ([_1]) in scanline [_2] [_3]',
                   7325:                 "<b>$error</b>", $i, "<pre>$line</pre>")
                   7326:            ."</p> \n");
                   7327:     }
                   7328:     my $message =
                   7329:         '<p>'
                   7330:        .&mt('The ID on the form is [_1]',
                   7331:             "<tt>$$scan_record{'scantron.ID'}</tt>")
                   7332:        .'<br />'
1.665     raeburn  7333:        .&mt('The name on the paper is [_1], [_2]',
1.658     bisitz   7334:             $$scan_record{'scantron.LastName'},
                   7335:             $$scan_record{'scantron.FirstName'})
                   7336:        .'</p>';
1.242     albertel 7337: 
1.157     albertel 7338:     $r->print('<input type="hidden" name="scantron_corrections" value="'.$error.'" />'."\n");
                   7339:     $r->print('<input type="hidden" name="scantron_line" value="'.$i.'" />'."\n");
1.503     raeburn  7340:                            # Array populated for doublebubble or
                   7341:     my @lines_to_correct;  # missingbubble errors to build javascript
                   7342:                            # to validate radio button checking   
                   7343: 
1.157     albertel 7344:     if ($error =~ /ID$/) {
1.186     albertel 7345: 	if ($error eq 'incorrectID') {
1.658     bisitz   7346:             $r->print('<p class="LC_warning">'.&mt("The encoded ID is not in the classlist").
1.492     albertel 7347: 		      "</p>\n");
1.157     albertel 7348: 	} elsif ($error eq 'duplicateID') {
1.658     bisitz   7349:             $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 7350: 	}
1.242     albertel 7351: 	$r->print($message);
1.492     albertel 7352: 	$r->print("<p>".&mt("How should I handle this?")." <br /> \n");
1.157     albertel 7353: 	$r->print("\n<ul><li> ");
                   7354: 	#FIXME it would be nice if this sent back the user ID and
                   7355: 	#could do partial userID matches
                   7356: 	$r->print(&Apache::loncommon::selectstudent_link('scantronupload',
                   7357: 				       'scantron_username','scantron_domain'));
                   7358: 	$r->print(": <input type='text' name='scantron_username' value='' />");
1.685     bisitz   7359: 	$r->print("\n:\n".
1.257     albertel 7360: 		 &Apache::loncommon::select_dom_form($env{'request.role.domain'},'scantron_domain'));
1.157     albertel 7361: 
                   7362: 	$r->print('</li>');
1.186     albertel 7363:     } elsif ($error =~ /CODE$/) {
                   7364: 	if ($error eq 'incorrectCODE') {
1.658     bisitz   7365: 	    $r->print('<p class="LC_warning">'.&mt("The encoded CODE is not in the list of possible CODEs.")."</p>\n");
1.186     albertel 7366: 	} elsif ($error eq 'duplicateCODE') {
1.658     bisitz   7367: 	    $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 7368: 	}
1.658     bisitz   7369: 	$r->print("<p>".&mt('The CODE on the form is [_1]',
                   7370: 			    "<tt>'$$scan_record{'scantron.CODE'}'</tt>")
                   7371:                  ."</p>\n");
1.242     albertel 7372: 	$r->print($message);
1.658     bisitz   7373: 	$r->print("<p>".&mt("How should I handle this?")."</p>\n");
1.187     albertel 7374: 	$r->print("\n<br /> ");
1.194     albertel 7375: 	my $i=0;
1.273     albertel 7376: 	if ($error eq 'incorrectCODE' 
                   7377: 	    && $$scan_record{'scantron.CODE'}=~/\S/ ) {
1.194     albertel 7378: 	    my ($max,$closest)=&scantron_get_closely_matching_CODEs($arg,$$scan_record{'scantron.CODE'});
1.278     albertel 7379: 	    if ($closest > 0) {
                   7380: 		foreach my $testcode (@{$closest}) {
                   7381: 		    my $checked='';
1.569     bisitz   7382: 		    if (!$i) { $checked=' checked="checked"'; }
1.492     albertel 7383: 		    $r->print("
                   7384:    <label>
1.569     bisitz   7385:        <input type='radio' name='scantron_CODE_resolution' value='use_closest_$i'$checked />
1.492     albertel 7386:        ".&mt("Use the similar CODE [_1] instead.",
                   7387: 	    "<b><tt>".$testcode."</tt></b>")."
                   7388:     </label>
                   7389:     <input type='hidden' name='scantron_CODE_closest_$i' value='$testcode' />");
1.278     albertel 7390: 		    $r->print("\n<br />");
                   7391: 		    $i++;
                   7392: 		}
1.194     albertel 7393: 	    }
                   7394: 	}
1.273     albertel 7395: 	if ($$scan_record{'scantron.CODE'}=~/\S/ ) {
1.569     bisitz   7396: 	    my $checked; if (!$i) { $checked=' checked="checked"'; }
1.492     albertel 7397: 	    $r->print("
                   7398:     <label>
1.569     bisitz   7399:         <input type='radio' name='scantron_CODE_resolution' value='use_unfound'$checked />
1.659     raeburn  7400:        ".&mt("Use the CODE [_1] that was on the paper, ignoring the error.",
1.492     albertel 7401: 	     "<b><tt>".$$scan_record{'scantron.CODE'}."</tt></b>")."
                   7402:     </label>");
1.273     albertel 7403: 	    $r->print("\n<br />");
                   7404: 	}
1.194     albertel 7405: 
1.597     wenzelju 7406: 	$r->print(&Apache::lonhtmlcommon::scripttag(<<ENDSCRIPT));
1.188     albertel 7407: function change_radio(field) {
1.190     albertel 7408:     var slct=document.scantronupload.scantron_CODE_resolution;
1.188     albertel 7409:     var i;
                   7410:     for (i=0;i<slct.length;i++) {
                   7411:         if (slct[i].value==field) { slct[i].checked=true; }
                   7412:     }
                   7413: }
                   7414: ENDSCRIPT
1.187     albertel 7415: 	my $href="/adm/pickcode?".
1.359     www      7416: 	   "form=".&escape("scantronupload").
                   7417: 	   "&scantron_format=".&escape($env{'form.scantron_format'}).
                   7418: 	   "&scantron_CODElist=".&escape($env{'form.scantron_CODElist'}).
                   7419: 	   "&curCODE=".&escape($$scan_record{'scantron.CODE'}).
                   7420: 	   "&scantron_selectfile=".&escape($env{'form.scantron_selectfile'});
1.332     albertel 7421: 	if ($env{'form.scantron_CODElist'} =~ /\S/) { 
1.492     albertel 7422: 	    $r->print("
                   7423:     <label>
                   7424:        <input type='radio' name='scantron_CODE_resolution' value='use_found' />
                   7425:        ".&mt("[_1]Select[_2] a CODE from the list of all CODEs and use it.",
                   7426: 	     "<a target='_blank' href='$href'>","</a>")."
                   7427:     </label> 
1.558     bisitz   7428:     ".&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 7429: 	    $r->print("\n<br />");
                   7430: 	}
1.492     albertel 7431: 	$r->print("
                   7432:     <label>
                   7433:        <input type='radio' name='scantron_CODE_resolution' value='use_typed' />
                   7434:        ".&mt("Use [_1] as the CODE.",
                   7435: 	     "</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 7436: 	$r->print("\n<br /><br />");
1.157     albertel 7437:     } elsif ($error eq 'doublebubble') {
1.658     bisitz   7438: 	$r->print('<p class="LC_warning">'.&mt("There have been multiple bubbles scanned for some question(s)")."</p>\n");
1.497     foxr     7439: 
                   7440: 	# The form field scantron_questions is acutally a list of line numbers.
                   7441: 	# represented by this form so:
                   7442: 
1.691     raeburn  7443: 	my $line_list = &questions_to_line_list($arg,$randomorder,$randompick,
                   7444:                                                 $respnumlookup,$startline);
1.497     foxr     7445: 
1.157     albertel 7446: 	$r->print('<input type="hidden" name="scantron_questions" value="'.
1.497     foxr     7447: 		  $line_list.'" />');
1.242     albertel 7448: 	$r->print($message);
1.492     albertel 7449: 	$r->print("<p>".&mt("Please indicate which bubble should be used for grading")."</p>");
1.157     albertel 7450: 	foreach my $question (@{$arg}) {
1.503     raeburn  7451: 	    my @linenums = &prompt_for_corrections($r,$question,$scan_config,
1.691     raeburn  7452:                                                    $scan_record, $error,
                   7453:                                                    $randomorder,$randompick,
                   7454:                                                    $respnumlookup,$startline);
1.524     raeburn  7455:             push(@lines_to_correct,@linenums);
1.157     albertel 7456: 	}
1.503     raeburn  7457:         $r->print(&verify_bubbles_checked(@lines_to_correct));
1.157     albertel 7458:     } elsif ($error eq 'missingbubble') {
1.658     bisitz   7459: 	$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 7460: 	$r->print($message);
1.492     albertel 7461: 	$r->print("<p>".&mt("Please indicate which bubble should be used for grading.")."</p>");
1.503     raeburn  7462: 	$r->print(&mt("Some questions have no scanned bubbles.")."\n");
1.497     foxr     7463: 
1.503     raeburn  7464: 	# The form field scantron_questions is actually a list of line numbers not
1.497     foxr     7465: 	# a list of question numbers. Therefore:
                   7466: 	#
1.691     raeburn  7467: 
                   7468: 	my $line_list = &questions_to_line_list($arg,$randomorder,$randompick,
                   7469:                                                 $respnumlookup,$startline);
1.497     foxr     7470: 
1.157     albertel 7471: 	$r->print('<input type="hidden" name="scantron_questions" value="'.
1.497     foxr     7472: 		  $line_list.'" />');
1.157     albertel 7473: 	foreach my $question (@{$arg}) {
1.503     raeburn  7474: 	    my @linenums = &prompt_for_corrections($r,$question,$scan_config,
1.691     raeburn  7475:                                                    $scan_record, $error,
                   7476:                                                    $randomorder,$randompick,
                   7477:                                                    $respnumlookup,$startline);
1.524     raeburn  7478:             push(@lines_to_correct,@linenums);
1.157     albertel 7479: 	}
1.503     raeburn  7480:         $r->print(&verify_bubbles_checked(@lines_to_correct));
1.157     albertel 7481:     } else {
                   7482: 	$r->print("\n<ul>");
                   7483:     }
                   7484:     $r->print("\n</li></ul>");
1.497     foxr     7485: }
                   7486: 
1.503     raeburn  7487: sub verify_bubbles_checked {
                   7488:     my (@ansnums) = @_;
                   7489:     my $ansnumstr = join('","',@ansnums);
                   7490:     my $warning = &mt("A bubble or 'No bubble' selection has not been made for one or more lines.");
1.736   ! damieng  7491:     &js_escape(\$warning);
1.597     wenzelju 7492:     my $output = &Apache::lonhtmlcommon::scripttag((<<ENDSCRIPT));
1.503     raeburn  7493: function verify_bubble_radio(form) {
                   7494:     var ansnumArray = new Array ("$ansnumstr");
                   7495:     var need_bubble_count = 0;
                   7496:     for (var i=0; i<ansnumArray.length; i++) {
                   7497:         if (form.elements["scantron_correct_Q_"+ansnumArray[i]].length > 1) {
                   7498:             var bubble_picked = 0; 
                   7499:             for (var j=0; j<form.elements["scantron_correct_Q_"+ansnumArray[i]].length; j++) {
                   7500:                 if (form.elements["scantron_correct_Q_"+ansnumArray[i]][j].checked == true) {
                   7501:                     bubble_picked = 1;
                   7502:                 }
                   7503:             }
                   7504:             if (bubble_picked == 0) {
                   7505:                 need_bubble_count ++;
                   7506:             }
                   7507:         }
                   7508:     }
                   7509:     if (need_bubble_count) {
                   7510:         alert("$warning");
                   7511:         return;
                   7512:     }
                   7513:     form.submit(); 
                   7514: }
                   7515: ENDSCRIPT
                   7516:     return $output;
                   7517: }
                   7518: 
1.497     foxr     7519: =pod
                   7520: 
                   7521: =item  questions_to_line_list
1.157     albertel 7522: 
1.497     foxr     7523: Converts a list of questions into a string of comma separated
                   7524: line numbers in the answer sheet used by the questions.  This is
                   7525: used to fill in the scantron_questions form field.
                   7526: 
                   7527:   Arguments:
                   7528:      questions    - Reference to an array of questions.
1.691     raeburn  7529:      randomorder  - True if randomorder in use.
                   7530:      randompick   - True if randompick in use.
                   7531:      respnumlookup - Reference to HASH mapping question numbers in bubble lines
                   7532:                      for current line to question number used for same question
                   7533:                      in "Master Seqence" (as seen by Course Coordinator).
                   7534:      startline    - Reference to hash where key is question number (0 is first)
                   7535:                     and key is number of first bubble line for current student
                   7536:                     or code-based randompick and/or randomorder.
1.693     raeburn  7537: 
1.497     foxr     7538: =cut
                   7539: 
                   7540: 
                   7541: sub questions_to_line_list {
1.691     raeburn  7542:     my ($questions,$randomorder,$randompick,$respnumlookup,$startline) = @_;
1.497     foxr     7543:     my @lines;
                   7544: 
1.503     raeburn  7545:     foreach my $item (@{$questions}) {
                   7546:         my $question = $item;
                   7547:         my ($first,$count,$last);
                   7548:         if ($item =~ /^(\d+)\.(\d+)$/) {
                   7549:             $question = $1;
                   7550:             my $subquestion = $2;
1.691     raeburn  7551:             my $responsenum = $question-1;
                   7552:             if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH')) {
                   7553:                 $responsenum = $respnumlookup->{$question-1};
                   7554:                 if (ref($startline) eq 'HASH') {
                   7555:                     $first = $startline->{$question-1} + 1;
                   7556:                 }
                   7557:             } else {
                   7558:                 $first = $first_bubble_line{$responsenum} + 1;
                   7559:             }
                   7560:             my @subans = split(/,/,$subdivided_bubble_lines{$responsenum});
1.503     raeburn  7561:             my $subcount = 1;
                   7562:             while ($subcount<$subquestion) {
                   7563:                 $first += $subans[$subcount-1];
                   7564:                 $subcount ++;
                   7565:             }
                   7566:             $count = $subans[$subquestion-1];
                   7567:         } else {
1.691     raeburn  7568:             my $responsenum = $question-1;
                   7569:             if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH')) {
                   7570:                 $responsenum = $respnumlookup->{$question-1};
                   7571:                 if (ref($startline) eq 'HASH') {
                   7572:                     $first = $startline->{$question-1} + 1;
                   7573:                 }
                   7574:             } else {
                   7575:                 $first = $first_bubble_line{$responsenum} + 1;
                   7576:             }
                   7577: 	    $count   = $bubble_lines_per_response{$responsenum};
1.503     raeburn  7578:         }
1.506     raeburn  7579:         $last = $first+$count-1;
1.503     raeburn  7580:         push(@lines, ($first..$last));
1.497     foxr     7581:     }
                   7582:     return join(',', @lines);
                   7583: }
                   7584: 
                   7585: =pod 
                   7586: 
                   7587: =item prompt_for_corrections
                   7588: 
                   7589: Prompts for a potentially multiline correction to the
                   7590: user's bubbling (factors out common code from scantron_get_correction
                   7591: for multi and missing bubble cases).
                   7592: 
                   7593:  Arguments:
                   7594:    $r           - Apache request object.
                   7595:    $question    - The question number to prompt for.
                   7596:    $scan_config - The scantron file configuration hash.
                   7597:    $scan_record - Reference to the hash that has the the parsed scanlines.
1.503     raeburn  7598:    $error       - Type of error
1.691     raeburn  7599:    $randomorder - True if randomorder in use.
                   7600:    $randompick  - True if randompick in use.
                   7601:    $respnumlookup - Reference to HASH mapping question numbers in bubble lines
                   7602:                     for current line to question number used for same question
                   7603:                     in "Master Seqence" (as seen by Course Coordinator).
                   7604:    $startline   - Reference to hash where key is question number (0 is first)
                   7605:                   and value is number of first bubble line for current student
                   7606:                   or code-based randompick and/or randomorder.
                   7607: 
1.497     foxr     7608: 
                   7609:  Implicit inputs:
                   7610:    %bubble_lines_per_response   - Starting line numbers for each question.
                   7611:                                   Numbered from 0 (but question numbers are from
                   7612:                                   1.
                   7613:    %first_bubble_line           - Starting bubble line for each question.
1.509     raeburn  7614:    %subdivided_bubble_lines     - optionresponse, matchresponse and rankresponse 
                   7615:                                   type problems render as separate sub-questions, 
1.503     raeburn  7616:                                   in exam mode. This hash contains a 
                   7617:                                   comma-separated list of the lines per 
                   7618:                                   sub-question.
1.510     raeburn  7619:    %responsetype_per_response   - essayresponse, formularesponse,
                   7620:                                   stringresponse, imageresponse, reactionresponse,
                   7621:                                   and organicresponse type problem parts can have
1.503     raeburn  7622:                                   multiple lines per response if the weight
                   7623:                                   assigned exceeds 10.  In this case, only
                   7624:                                   one bubble per line is permitted, but more 
                   7625:                                   than one line might contain bubbles, e.g.
                   7626:                                   bubbling of: line 1 - J, line 2 - J, 
                   7627:                                   line 3 - B would assign 22 points.  
1.497     foxr     7628: 
                   7629: =cut
                   7630: 
                   7631: sub prompt_for_corrections {
1.691     raeburn  7632:     my ($r, $question, $scan_config, $scan_record, $error, $randomorder,
                   7633:         $randompick, $respnumlookup, $startline) = @_;
1.503     raeburn  7634:     my ($current_line,$lines);
                   7635:     my @linenums;
                   7636:     my $questionnum = $question;
1.691     raeburn  7637:     my ($first,$responsenum);
1.503     raeburn  7638:     if ($question =~ /^(\d+)\.(\d+)$/) {
                   7639:         $question = $1;
                   7640:         my $subquestion = $2;
1.691     raeburn  7641:         if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH')) {
                   7642:             $responsenum = $respnumlookup->{$question-1};
                   7643:             if (ref($startline) eq 'HASH') {
                   7644:                 $first = $startline->{$question-1};
                   7645:             }
                   7646:         } else {
                   7647:             $responsenum = $question-1;
1.714     raeburn  7648:             $first = $first_bubble_line{$responsenum};
1.691     raeburn  7649:         }
                   7650:         $current_line = $first + 1 ;
                   7651:         my @subans = split(/,/,$subdivided_bubble_lines{$responsenum});
1.503     raeburn  7652:         my $subcount = 1;
                   7653:         while ($subcount<$subquestion) {
                   7654:             $current_line += $subans[$subcount-1];
                   7655:             $subcount ++;
                   7656:         }
                   7657:         $lines = $subans[$subquestion-1];
                   7658:     } else {
1.691     raeburn  7659:         if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH')) {
                   7660:             $responsenum = $respnumlookup->{$question-1};
                   7661:             if (ref($startline) eq 'HASH') { 
                   7662:                 $first = $startline->{$question-1};
                   7663:             }
                   7664:         } else {
                   7665:             $responsenum = $question-1;
                   7666:             $first = $first_bubble_line{$responsenum};
                   7667:         }
                   7668:         $current_line = $first + 1;
                   7669:         $lines        = $bubble_lines_per_response{$responsenum};
1.503     raeburn  7670:     }
1.497     foxr     7671:     if ($lines > 1) {
1.503     raeburn  7672:         $r->print(&mt('The group of bubble lines below responds to a single question.').'<br />');
1.691     raeburn  7673:         if (($responsetype_per_response{$responsenum} eq 'essayresponse') ||
                   7674:             ($responsetype_per_response{$responsenum} eq 'formularesponse') ||
                   7675:             ($responsetype_per_response{$responsenum} eq 'stringresponse') ||
                   7676:             ($responsetype_per_response{$responsenum} eq 'imageresponse') ||
                   7677:             ($responsetype_per_response{$responsenum} eq 'reactionresponse') ||
                   7678:             ($responsetype_per_response{$responsenum} eq 'organicresponse')) {
1.684     bisitz   7679:             $r->print(
                   7680:                 &mt("Although this particular question type requires handgrading, the instructions for this question in the bubblesheet exam directed students to leave [quant,_1,line] blank on their bubblesheets.",$lines)
                   7681:                .'<br /><br />'
                   7682:                .&mt('A non-zero score can be assigned to the student during bubblesheet grading by selecting a bubble in at least one line.')
                   7683:                .'<br />'
                   7684:                .&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.')
                   7685:                .'<br />'
                   7686:                .&mt("To assign a score of zero for this question, mark all lines as 'No bubble'.")
                   7687:                .'<br /><br />'
                   7688:             );
1.503     raeburn  7689:         } else {
                   7690:             $r->print(&mt("Select at most one bubble in a single line and select 'No Bubble' in all the other lines. ")."<br />");
                   7691:         }
1.497     foxr     7692:     }
                   7693:     for (my $i =0; $i < $lines; $i++) {
1.503     raeburn  7694:         my $selected = $$scan_record{"scantron.$current_line.answer"};
1.691     raeburn  7695: 	&scantron_bubble_selector($r,$scan_config,$current_line,
1.503     raeburn  7696: 	        		  $questionnum,$error,split('', $selected));
1.524     raeburn  7697:         push(@linenums,$current_line);
1.497     foxr     7698: 	$current_line++;
                   7699:     }
                   7700:     if ($lines > 1) {
                   7701: 	$r->print("<hr /><br />");
                   7702:     }
1.503     raeburn  7703:     return @linenums;
1.157     albertel 7704: }
1.423     albertel 7705: 
                   7706: =pod
                   7707: 
                   7708: =item scantron_bubble_selector
                   7709:   
                   7710:    Generates the html radiobuttons to correct a single bubble line
1.424     albertel 7711:    possibly showing the existing the selected bubbles if known
1.423     albertel 7712: 
                   7713:  Arguments:
                   7714:     $r           - Apache request object
                   7715:     $scan_config - hash from &get_scantron_config()
1.497     foxr     7716:     $line        - Number of the line being displayed.
1.503     raeburn  7717:     $questionnum - Question number (may include subquestion)
                   7718:     $error       - Type of error.
1.497     foxr     7719:     @selected    - Array of bubbles picked on this line.
1.423     albertel 7720: 
                   7721: =cut
                   7722: 
1.157     albertel 7723: sub scantron_bubble_selector {
1.503     raeburn  7724:     my ($r,$scan_config,$line,$questionnum,$error,@selected)=@_;
1.157     albertel 7725:     my $max=$$scan_config{'Qlength'};
1.274     albertel 7726: 
                   7727:     my $scmode=$$scan_config{'Qon'};
1.649     raeburn  7728:     if ($scmode eq 'number' || $scmode eq 'letter') { 
                   7729:         if (($$scan_config{'BubblesPerRow'} =~ /^\d+$/) &&
                   7730:             ($$scan_config{'BubblesPerRow'} > 0)) {
                   7731:             $max=$$scan_config{'BubblesPerRow'};
                   7732:             if (($scmode eq 'number') && ($max > 10)) {
                   7733:                 $max = 10;
                   7734:             } elsif (($scmode eq 'letter') && $max > 26) {
                   7735:                 $max = 26;
                   7736:             }
                   7737:         } else {
                   7738:             $max = 10;
                   7739:         }
                   7740:     }
1.274     albertel 7741: 
1.157     albertel 7742:     my @alphabet=('A'..'Z');
1.503     raeburn  7743:     $r->print(&Apache::loncommon::start_data_table().
                   7744:               &Apache::loncommon::start_data_table_row());
                   7745:     $r->print('<td rowspan="2" class="LC_leftcol_header">'.$line.'</td>');
1.497     foxr     7746:     for (my $i=0;$i<$max+1;$i++) {
                   7747: 	$r->print("\n".'<td align="center">');
                   7748: 	if ($selected[0] eq $alphabet[$i]) { $r->print('X'); shift(@selected) }
                   7749: 	else { $r->print('&nbsp;'); }
                   7750: 	$r->print('</td>');
                   7751:     }
1.503     raeburn  7752:     $r->print(&Apache::loncommon::end_data_table_row().
                   7753:               &Apache::loncommon::start_data_table_row());
1.497     foxr     7754:     for (my $i=0;$i<$max;$i++) {
                   7755: 	$r->print("\n".
                   7756: 		  '<td><label><input type="radio" name="scantron_correct_Q_'.
                   7757: 		  $line.'" value="'.$i.'" />'.$alphabet[$i]."</label></td>");
                   7758:     }
1.503     raeburn  7759:     my $nobub_checked = ' ';
                   7760:     if ($error eq 'missingbubble') {
                   7761:         $nobub_checked = ' checked = "checked" ';
                   7762:     }
                   7763:     $r->print("\n".'<td><label><input type="radio" name="scantron_correct_Q_'.
                   7764: 	      $line.'" value="none"'.$nobub_checked.'/>'.&mt('No bubble').
                   7765:               '</label>'."\n".'<input type="hidden" name="scantron_questionnum_Q_'.
                   7766:               $line.'" value="'.$questionnum.'" /></td>');
                   7767:     $r->print(&Apache::loncommon::end_data_table_row().
                   7768:               &Apache::loncommon::end_data_table());
1.157     albertel 7769: }
                   7770: 
1.423     albertel 7771: =pod
                   7772: 
                   7773: =item num_matches
                   7774: 
1.424     albertel 7775:    Counts the number of characters that are the same between the two arguments.
                   7776: 
                   7777:  Arguments:
                   7778:    $orig - CODE from the scanline
                   7779:    $code - CODE to match against
                   7780: 
                   7781:  Returns:
                   7782:    $count - integer count of the number of same characters between the
                   7783:             two arguments
                   7784: 
1.423     albertel 7785: =cut
                   7786: 
1.194     albertel 7787: sub num_matches {
                   7788:     my ($orig,$code) = @_;
                   7789:     my @code=split(//,$code);
                   7790:     my @orig=split(//,$orig);
                   7791:     my $same=0;
                   7792:     for (my $i=0;$i<scalar(@code);$i++) {
                   7793: 	if ($code[$i] eq $orig[$i]) { $same++; }
                   7794:     }
                   7795:     return $same;
                   7796: }
                   7797: 
1.423     albertel 7798: =pod
                   7799: 
                   7800: =item scantron_get_closely_matching_CODEs
                   7801: 
1.424     albertel 7802:    Cycles through all CODEs and finds the set that has the greatest
                   7803:    number of same characters as the provided CODE
                   7804: 
                   7805:  Arguments:
                   7806:    $allcodes - hash ref returned by &get_codes()
                   7807:    $CODE     - CODE from the current scanline
                   7808: 
                   7809:  Returns:
                   7810:    2 element list
                   7811:     - first elements is number of how closely matching the best fit is 
                   7812:       (5 means best set has 5 matching characters)
                   7813:     - second element is an arrary ref containing the set of valid CODEs
                   7814:       that best fit the passed in CODE
                   7815: 
1.423     albertel 7816: =cut
                   7817: 
1.194     albertel 7818: sub scantron_get_closely_matching_CODEs {
                   7819:     my ($allcodes,$CODE)=@_;
                   7820:     my @CODEs;
                   7821:     foreach my $testcode (sort(keys(%{$allcodes}))) {
                   7822: 	push(@{$CODEs[&num_matches($CODE,$testcode)]},$testcode);
                   7823:     }
                   7824: 
                   7825:     return ($#CODEs,$CODEs[-1]);
                   7826: }
                   7827: 
1.423     albertel 7828: =pod
                   7829: 
                   7830: =item get_codes
                   7831: 
1.424     albertel 7832:    Builds a hash which has keys of all of the valid CODEs from the selected
                   7833:    set of remembered CODEs.
                   7834: 
                   7835:  Arguments:
                   7836:   $old_name - name of the set of remembered CODEs
                   7837:   $cdom     - domain of the course
                   7838:   $cnum     - internal course name
                   7839: 
                   7840:  Returns:
                   7841:   %allcodes - keys are the valid CODEs, values are all 1
                   7842: 
1.423     albertel 7843: =cut
                   7844: 
1.194     albertel 7845: sub get_codes {
1.280     foxr     7846:     my ($old_name, $cdom, $cnum) = @_;
                   7847:     if (!$old_name) {
                   7848: 	$old_name=$env{'form.scantron_CODElist'};
                   7849:     }
                   7850:     if (!$cdom) {
                   7851: 	$cdom =$env{'course.'.$env{'request.course.id'}.'.domain'};
                   7852:     }
                   7853:     if (!$cnum) {
                   7854: 	$cnum =$env{'course.'.$env{'request.course.id'}.'.num'};
                   7855:     }
1.278     albertel 7856:     my %result=&Apache::lonnet::get('CODEs',[$old_name,"type\0$old_name"],
                   7857: 				    $cdom,$cnum);
                   7858:     my %allcodes;
                   7859:     if ($result{"type\0$old_name"} eq 'number') {
                   7860: 	%allcodes=map {($_,1)} split(',',$result{$old_name});
                   7861:     } else {
                   7862: 	%allcodes=map {(&Apache::lonprintout::num_to_letters($_),1)} split(',',$result{$old_name});
                   7863:     }
1.194     albertel 7864:     return %allcodes;
                   7865: }
                   7866: 
1.423     albertel 7867: =pod
                   7868: 
                   7869: =item scantron_validate_CODE
                   7870: 
1.424     albertel 7871:    Validates all scanlines in the selected file to not have any
                   7872:    invalid or underspecified CODEs and that none of the codes are
                   7873:    duplicated if this was requested.
                   7874: 
1.423     albertel 7875: =cut
                   7876: 
1.157     albertel 7877: sub scantron_validate_CODE {
                   7878:     my ($r,$currentphase) = @_;
1.257     albertel 7879:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.186     albertel 7880:     if ($scantron_config{'CODElocation'} &&
                   7881: 	$scantron_config{'CODEstart'} &&
                   7882: 	$scantron_config{'CODElength'}) {
1.257     albertel 7883: 	if (!defined($env{'form.scantron_CODElist'})) {
1.186     albertel 7884: 	    &FIXME_blow_up()
                   7885: 	}
                   7886:     } else {
                   7887: 	return (0,$currentphase+1);
                   7888:     }
                   7889:     
                   7890:     my %usedCODEs;
                   7891: 
1.194     albertel 7892:     my %allcodes=&get_codes();
1.186     albertel 7893: 
1.582     raeburn  7894:     my $nav_error;
1.649     raeburn  7895:     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # parse needs the lines per response array.
1.582     raeburn  7896:     if ($nav_error) {
                   7897:         $r->print(&navmap_errormsg());
                   7898:         return(1,$currentphase);
                   7899:     }
1.447     foxr     7900: 
1.186     albertel 7901:     my ($scanlines,$scan_data)=&scantron_getfile();
                   7902:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
1.200     albertel 7903: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.186     albertel 7904: 	if ($line=~/^[\s\cz]*$/) { next; }
                   7905: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
                   7906: 						 $scan_data);
                   7907: 	my $CODE=$$scan_record{'scantron.CODE'};
                   7908: 	my $error=0;
1.224     albertel 7909: 	if (!&Apache::lonnet::validCODE($CODE)) {
                   7910: 	    &scantron_get_correction($r,$i,$scan_record,
                   7911: 				     \%scantron_config,
                   7912: 				     $line,'incorrectCODE',\%allcodes);
                   7913: 	    return(1,$currentphase);
                   7914: 	}
1.221     albertel 7915: 	if (%allcodes && !exists($allcodes{$CODE}) 
                   7916: 	    && !$$scan_record{'scantron.useCODE'}) {
1.186     albertel 7917: 	    &scantron_get_correction($r,$i,$scan_record,
                   7918: 				     \%scantron_config,
1.194     albertel 7919: 				     $line,'incorrectCODE',\%allcodes);
                   7920: 	    return(1,$currentphase);
1.186     albertel 7921: 	}
1.214     albertel 7922: 	if (exists($usedCODEs{$CODE}) 
1.257     albertel 7923: 	    && $env{'form.scantron_CODEunique'} eq 'yes'
1.192     albertel 7924: 	    && !$$scan_record{'scantron.CODE_ignore_dup'}) {
1.186     albertel 7925: 	    &scantron_get_correction($r,$i,$scan_record,
                   7926: 				     \%scantron_config,
1.194     albertel 7927: 				     $line,'duplicateCODE',$usedCODEs{$CODE});
                   7928: 	    return(1,$currentphase);
1.186     albertel 7929: 	}
1.524     raeburn  7930: 	push(@{$usedCODEs{$CODE}},$$scan_record{'scantron.PaperID'});
1.186     albertel 7931:     }
1.157     albertel 7932:     return (0,$currentphase+1);
                   7933: }
                   7934: 
1.423     albertel 7935: =pod
                   7936: 
                   7937: =item scantron_validate_doublebubble
                   7938: 
1.424     albertel 7939:    Validates all scanlines in the selected file to not have any
                   7940:    bubble lines with multiple bubbles marked.
                   7941: 
1.423     albertel 7942: =cut
                   7943: 
1.157     albertel 7944: sub scantron_validate_doublebubble {
                   7945:     my ($r,$currentphase) = @_;
                   7946:     #get student info
                   7947:     my $classlist=&Apache::loncoursedata::get_classlist();
                   7948:     my %idmap=&username_to_idmap($classlist);
1.691     raeburn  7949:     my (undef,undef,$sequence)=
                   7950:         &Apache::lonnet::decode_symb($env{'form.selectpage'});
1.157     albertel 7951: 
                   7952:     #get scantron line setup
1.257     albertel 7953:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.157     albertel 7954:     my ($scanlines,$scan_data)=&scantron_getfile();
1.691     raeburn  7955: 
                   7956:     my $navmap = Apache::lonnavmaps::navmap->new();
                   7957:     unless (ref($navmap)) {
                   7958:         $r->print(&navmap_errormsg());
                   7959:         return(1,$currentphase);
                   7960:     }
                   7961:     my $map=$navmap->getResourceByUrl($sequence);
                   7962:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
                   7963:     my ($randomorder,$randompick,@master_seq,%symb_to_resource,%grader_partids_by_symb,
                   7964:         %grader_randomlists_by_symb,%orderedforcode,%respnumlookup,%startline);
                   7965:     my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config);
                   7966: 
1.583     raeburn  7967:     my $nav_error;
1.691     raeburn  7968:     if (ref($map)) {
                   7969:         $randomorder = $map->randomorder();
                   7970:         $randompick = $map->randompick();
                   7971:         if ($randomorder || $randompick) {
                   7972:             $nav_error = &get_master_seq(\@resources,\@master_seq,\%symb_to_resource);
                   7973:             if ($nav_error) {
                   7974:                 $r->print(&navmap_errormsg());
                   7975:                 return(1,$currentphase);
                   7976:             }
                   7977:             &graders_resources_pass(\@resources,\%grader_partids_by_symb,
                   7978:                                     \%grader_randomlists_by_symb,$bubbles_per_row);
                   7979:         }
                   7980:     } else {
                   7981:         $r->print(&navmap_errormsg());
                   7982:         return(1,$currentphase);
                   7983:     }
                   7984: 
1.649     raeburn  7985:     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # parse needs the bubble line array.
1.583     raeburn  7986:     if ($nav_error) {
                   7987:         $r->print(&navmap_errormsg());
                   7988:         return(1,$currentphase);
                   7989:     }
1.447     foxr     7990: 
1.157     albertel 7991:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
1.200     albertel 7992: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.157     albertel 7993: 	if ($line=~/^[\s\cz]*$/) { next; }
                   7994: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
1.691     raeburn  7995: 						 $scan_data,undef,\%idmap,$randomorder,
                   7996:                                                  $randompick,$sequence,\@master_seq,
                   7997:                                                  \%symb_to_resource,\%grader_partids_by_symb,
                   7998:                                                  \%orderedforcode,\%respnumlookup,\%startline);
1.157     albertel 7999: 	if (!defined($$scan_record{'scantron.doubleerror'})) { next; }
                   8000: 	&scantron_get_correction($r,$i,$scan_record,\%scantron_config,$line,
                   8001: 				 'doublebubble',
1.691     raeburn  8002: 				 $$scan_record{'scantron.doubleerror'},
                   8003:                                  $randomorder,$randompick,\%respnumlookup,\%startline);
1.157     albertel 8004:     	return (1,$currentphase);
                   8005:     }
                   8006:     return (0,$currentphase+1);
                   8007: }
                   8008: 
1.423     albertel 8009: 
1.503     raeburn  8010: sub scantron_get_maxbubble {
1.649     raeburn  8011:     my ($nav_error,$scantron_config) = @_;
1.257     albertel 8012:     if (defined($env{'form.scantron_maxbubble'}) &&
                   8013: 	$env{'form.scantron_maxbubble'}) {
1.447     foxr     8014: 	&restore_bubble_lines();
1.257     albertel 8015: 	return $env{'form.scantron_maxbubble'};
1.191     albertel 8016:     }
1.330     albertel 8017: 
1.447     foxr     8018:     my (undef, undef, $sequence) =
1.257     albertel 8019: 	&Apache::lonnet::decode_symb($env{'form.selectpage'});
1.330     albertel 8020: 
1.447     foxr     8021:     my $navmap=Apache::lonnavmaps::navmap->new();
1.582     raeburn  8022:     unless (ref($navmap)) {
                   8023:         if (ref($nav_error)) {
                   8024:             $$nav_error = 1;
                   8025:         }
1.591     raeburn  8026:         return;
1.582     raeburn  8027:     }
1.191     albertel 8028:     my $map=$navmap->getResourceByUrl($sequence);
                   8029:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
1.649     raeburn  8030:     my $bubbles_per_row = &bubblesheet_bubbles_per_row($scantron_config);
1.330     albertel 8031: 
                   8032:     &Apache::lonxml::clear_problem_counter();
                   8033: 
1.557     raeburn  8034:     my $uname       = $env{'user.name'};
                   8035:     my $udom        = $env{'user.domain'};
1.435     foxr     8036:     my $cid         = $env{'request.course.id'};
                   8037:     my $total_lines = 0;
                   8038:     %bubble_lines_per_response = ();
1.447     foxr     8039:     %first_bubble_line         = ();
1.503     raeburn  8040:     %subdivided_bubble_lines   = ();
                   8041:     %responsetype_per_response = ();
1.691     raeburn  8042:     %masterseq_id_responsenum  = ();
1.554     raeburn  8043: 
1.447     foxr     8044:     my $response_number = 0;
                   8045:     my $bubble_line     = 0;
1.191     albertel 8046:     foreach my $resource (@resources) {
1.691     raeburn  8047:         my $resid = $resource->id(); 
1.672     raeburn  8048:         my ($analysis,$parts) = &scantron_partids_tograde($resource,$cid,$uname,
                   8049:                                                           $udom,undef,$bubbles_per_row);
1.542     raeburn  8050:         if ((ref($analysis) eq 'HASH') && (ref($parts) eq 'ARRAY')) {
                   8051: 	    foreach my $part_id (@{$parts}) {
                   8052:                 my $lines;
                   8053: 
                   8054: 	        # TODO - make this a persistent hash not an array.
                   8055: 
                   8056:                 # optionresponse, matchresponse and rankresponse type items 
                   8057:                 # render as separate sub-questions in exam mode.
                   8058:                 if (($analysis->{$part_id.'.type'} eq 'optionresponse') ||
                   8059:                     ($analysis->{$part_id.'.type'} eq 'matchresponse') ||
                   8060:                     ($analysis->{$part_id.'.type'} eq 'rankresponse')) {
                   8061:                     my ($numbub,$numshown);
                   8062:                     if ($analysis->{$part_id.'.type'} eq 'optionresponse') {
                   8063:                         if (ref($analysis->{$part_id.'.options'}) eq 'ARRAY') {
                   8064:                             $numbub = scalar(@{$analysis->{$part_id.'.options'}});
                   8065:                         }
                   8066:                     } elsif ($analysis->{$part_id.'.type'} eq 'matchresponse') {
                   8067:                         if (ref($analysis->{$part_id.'.items'}) eq 'ARRAY') {
                   8068:                             $numbub = scalar(@{$analysis->{$part_id.'.items'}});
                   8069:                         }
                   8070:                     } elsif ($analysis->{$part_id.'.type'} eq 'rankresponse') {
                   8071:                         if (ref($analysis->{$part_id.'.foils'}) eq 'ARRAY') {
                   8072:                             $numbub = scalar(@{$analysis->{$part_id.'.foils'}});
                   8073:                         }
                   8074:                     }
                   8075:                     if (ref($analysis->{$part_id.'.shown'}) eq 'ARRAY') {
                   8076:                         $numshown = scalar(@{$analysis->{$part_id.'.shown'}});
                   8077:                     }
1.649     raeburn  8078:                     my $bubbles_per_row =
                   8079:                         &bubblesheet_bubbles_per_row($scantron_config);
                   8080:                     my $inner_bubble_lines = int($numbub/$bubbles_per_row);
                   8081:                     if (($numbub % $bubbles_per_row) != 0) {
1.542     raeburn  8082:                         $inner_bubble_lines++;
                   8083:                     }
                   8084:                     for (my $i=0; $i<$numshown; $i++) {
                   8085:                         $subdivided_bubble_lines{$response_number} .= 
                   8086:                             $inner_bubble_lines.',';
                   8087:                     }
                   8088:                     $subdivided_bubble_lines{$response_number} =~ s/,$//;
                   8089:                     $lines = $numshown * $inner_bubble_lines;
                   8090:                 } else {
                   8091:                     $lines = $analysis->{"$part_id.bubble_lines"};
1.649     raeburn  8092:                 }
1.542     raeburn  8093: 
                   8094:                 $first_bubble_line{$response_number} = $bubble_line;
                   8095: 	        $bubble_lines_per_response{$response_number} = $lines;
                   8096:                 $responsetype_per_response{$response_number} = 
                   8097:                     $analysis->{$part_id.'.type'};
1.691     raeburn  8098:                 $masterseq_id_responsenum{$resid.'_'.$part_id} = $response_number;  
1.542     raeburn  8099: 	        $response_number++;
                   8100: 
                   8101: 	        $bubble_line +=  $lines;
                   8102: 	        $total_lines +=  $lines;
                   8103: 	    }
                   8104:         }
                   8105:     }
1.552     raeburn  8106:     &Apache::lonnet::delenv('scantron.');
1.542     raeburn  8107: 
                   8108:     &save_bubble_lines();
                   8109:     $env{'form.scantron_maxbubble'} =
                   8110: 	$total_lines;
                   8111:     return $env{'form.scantron_maxbubble'};
                   8112: }
1.523     raeburn  8113: 
1.649     raeburn  8114: sub bubblesheet_bubbles_per_row {
                   8115:     my ($scantron_config) = @_;
                   8116:     my $bubbles_per_row;
                   8117:     if (ref($scantron_config) eq 'HASH') {
                   8118:         $bubbles_per_row = $scantron_config->{'BubblesPerRow'};
                   8119:     }
                   8120:     if ((!$bubbles_per_row) || ($bubbles_per_row < 1)) {
                   8121:         $bubbles_per_row = 10;
                   8122:     }
                   8123:     return $bubbles_per_row;
                   8124: }
                   8125: 
1.157     albertel 8126: sub scantron_validate_missingbubbles {
                   8127:     my ($r,$currentphase) = @_;
                   8128:     #get student info
                   8129:     my $classlist=&Apache::loncoursedata::get_classlist();
                   8130:     my %idmap=&username_to_idmap($classlist);
1.691     raeburn  8131:     my (undef,undef,$sequence)=
                   8132:         &Apache::lonnet::decode_symb($env{'form.selectpage'});
1.157     albertel 8133: 
                   8134:     #get scantron line setup
1.257     albertel 8135:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.157     albertel 8136:     my ($scanlines,$scan_data)=&scantron_getfile();
1.691     raeburn  8137: 
                   8138:     my $navmap = Apache::lonnavmaps::navmap->new();
                   8139:     unless (ref($navmap)) {
                   8140:         $r->print(&navmap_errormsg());
                   8141:         return(1,$currentphase);
                   8142:     }
                   8143: 
                   8144:     my $map=$navmap->getResourceByUrl($sequence);
                   8145:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
                   8146:     my ($randomorder,$randompick,@master_seq,%symb_to_resource,%grader_partids_by_symb,
                   8147:         %grader_randomlists_by_symb,%orderedforcode,%respnumlookup,%startline);
                   8148:     my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config);
                   8149: 
1.582     raeburn  8150:     my $nav_error;
1.691     raeburn  8151:     if (ref($map)) {
                   8152:         $randomorder = $map->randomorder();
                   8153:         $randompick = $map->randompick();
                   8154:         if ($randomorder || $randompick) {
                   8155:             $nav_error = &get_master_seq(\@resources,\@master_seq,\%symb_to_resource);
                   8156:             if ($nav_error) {
                   8157:                 $r->print(&navmap_errormsg());
                   8158:                 return(1,$currentphase);
                   8159:             }
                   8160:             &graders_resources_pass(\@resources,\%grader_partids_by_symb,
                   8161:                                     \%grader_randomlists_by_symb,$bubbles_per_row);
                   8162:         }
                   8163:     } else {
                   8164:         $r->print(&navmap_errormsg());
                   8165:         return(1,$currentphase);
                   8166:     }
                   8167: 
                   8168: 
1.649     raeburn  8169:     my $max_bubble=&scantron_get_maxbubble(\$nav_error,\%scantron_config);
1.582     raeburn  8170:     if ($nav_error) {
1.691     raeburn  8171:         $r->print(&navmap_errormsg());
1.693     raeburn  8172:         return(1,$currentphase);
1.582     raeburn  8173:     }
1.691     raeburn  8174: 
1.157     albertel 8175:     if (!$max_bubble) { $max_bubble=2**31; }
                   8176:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
1.200     albertel 8177: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.157     albertel 8178: 	if ($line=~/^[\s\cz]*$/) { next; }
1.691     raeburn  8179: 	my $scan_record =
                   8180:             &scantron_parse_scanline($line,$i,\%scantron_config,$scan_data,undef,\%idmap,
                   8181: 				     $randomorder,$randompick,$sequence,\@master_seq,
                   8182:                                      \%symb_to_resource,\%grader_partids_by_symb,
                   8183:                                      \%orderedforcode,\%respnumlookup,\%startline);
1.157     albertel 8184: 	if (!defined($$scan_record{'scantron.missingerror'})) { next; }
                   8185: 	my @to_correct;
1.470     foxr     8186: 	
                   8187: 	# Probably here's where the error is...
                   8188: 
1.157     albertel 8189: 	foreach my $missing (@{$$scan_record{'scantron.missingerror'}}) {
1.505     raeburn  8190:             my $lastbubble;
                   8191:             if ($missing =~ /^(\d+)\.(\d+)$/) {
                   8192:                my $question = $1;
                   8193:                my $subquestion = $2;
1.691     raeburn  8194:                my ($first,$responsenum);
                   8195:                if ($randomorder || $randompick) {
                   8196:                    $responsenum = $respnumlookup{$question-1};
                   8197:                    $first = $startline{$question-1};
                   8198:                } else {
                   8199:                    $responsenum = $question-1; 
                   8200:                    $first = $first_bubble_line{$responsenum};
                   8201:                }
                   8202:                if (!defined($first)) { next; }
                   8203:                my @subans = split(/,/,$subdivided_bubble_lines{$responsenum});
1.505     raeburn  8204:                my $subcount = 1;
                   8205:                while ($subcount<$subquestion) {
                   8206:                    $first += $subans[$subcount-1];
                   8207:                    $subcount ++;
                   8208:                }
                   8209:                my $count = $subans[$subquestion-1];
                   8210:                $lastbubble = $first + $count;
                   8211:             } else {
1.691     raeburn  8212:                my ($first,$responsenum);
                   8213:                if ($randomorder || $randompick) {
                   8214:                    $responsenum = $respnumlookup{$missing-1};
                   8215:                    $first = $startline{$missing-1};
                   8216:                } else {
                   8217:                    $responsenum = $missing-1;
                   8218:                    $first = $first_bubble_line{$responsenum};
                   8219:                }
                   8220:                if (!defined($first)) { next; }
                   8221:                $lastbubble = $first + $bubble_lines_per_response{$responsenum};
1.505     raeburn  8222:             }
                   8223:             if ($lastbubble > $max_bubble) { next; }
1.157     albertel 8224: 	    push(@to_correct,$missing);
                   8225: 	}
                   8226: 	if (@to_correct) {
                   8227: 	    &scantron_get_correction($r,$i,$scan_record,\%scantron_config,
1.691     raeburn  8228: 				     $line,'missingbubble',\@to_correct,
                   8229:                                      $randomorder,$randompick,\%respnumlookup,
                   8230:                                      \%startline);
1.157     albertel 8231: 	    return (1,$currentphase);
                   8232: 	}
                   8233: 
                   8234:     }
                   8235:     return (0,$currentphase+1);
                   8236: }
                   8237: 
1.663     raeburn  8238: sub hand_bubble_option {
                   8239:     my (undef, undef, $sequence) =
                   8240:         &Apache::lonnet::decode_symb($env{'form.selectpage'});
                   8241:     return if ($sequence eq '');
                   8242:     my $navmap = Apache::lonnavmaps::navmap->new();
                   8243:     unless (ref($navmap)) {
                   8244:         return;
                   8245:     }
                   8246:     my $needs_hand_bubbles;
                   8247:     my $map=$navmap->getResourceByUrl($sequence);
                   8248:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
                   8249:     foreach my $res (@resources) {
                   8250:         if (ref($res)) {
                   8251:             if ($res->is_problem()) {
                   8252:                 my $partlist = $res->parts();
                   8253:                 foreach my $part (@{ $partlist }) {
                   8254:                     my @types = $res->responseType($part);
                   8255:                     if (grep(/^(chem|essay|image|formula|math|string|functionplot)$/,@types)) {
                   8256:                         $needs_hand_bubbles = 1;
                   8257:                         last;
                   8258:                     }
                   8259:                 }
                   8260:             }
                   8261:         }
                   8262:     }
                   8263:     if ($needs_hand_bubbles) {
                   8264:         my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
                   8265:         my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config);
                   8266:         return &mt('The sequence to be graded contains response types which are handgraded.').'<p>'.
                   8267:                &mt('If you have already graded these by bubbling sheets to indicate points awarded, [_1]what point value is assigned to a filled last bubble in each row?','<br />').
                   8268:                '<label><input type="radio" name="scantron_lastbubblepoints" value="'.$bubbles_per_row.'" checked="checked" />'.&mt('[quant,_1,point]',$bubbles_per_row).'</label>&nbsp;'.&mt('or').'&nbsp;'.
1.722     raeburn  8269:                '<label><input type="radio" name="scantron_lastbubblepoints" value="0" />'.&mt('0 points').'</label></p>';
1.663     raeburn  8270:     }
                   8271:     return;
                   8272: }
1.423     albertel 8273: 
1.82      albertel 8274: sub scantron_process_students {
1.608     www      8275:     my ($r,$symb) = @_;
1.513     foxr     8276: 
1.257     albertel 8277:     my (undef,undef,$sequence)=&Apache::lonnet::decode_symb($env{'form.selectpage'});
1.513     foxr     8278:     if (!$symb) {
                   8279: 	return '';
                   8280:     }
1.324     albertel 8281:     my $default_form_data=&defaultFormData($symb);
1.82      albertel 8282: 
1.257     albertel 8283:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.691     raeburn  8284:     my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config); 
1.157     albertel 8285:     my ($scanlines,$scan_data)=&scantron_getfile();
1.82      albertel 8286:     my $classlist=&Apache::loncoursedata::get_classlist();
                   8287:     my %idmap=&username_to_idmap($classlist);
1.132     bowersj2 8288:     my $navmap=Apache::lonnavmaps::navmap->new();
1.582     raeburn  8289:     unless (ref($navmap)) {
                   8290:         $r->print(&navmap_errormsg());
                   8291:         return '';
1.691     raeburn  8292:     }
1.83      albertel 8293:     my $map=$navmap->getResourceByUrl($sequence);
1.691     raeburn  8294:     my ($randomorder,$randompick,@master_seq,%symb_to_resource,%grader_partids_by_symb,
1.693     raeburn  8295:         %grader_randomlists_by_symb);
1.677     raeburn  8296:     if (ref($map)) {
                   8297:         $randomorder = $map->randomorder();
1.689     raeburn  8298:         $randompick = $map->randompick();
1.691     raeburn  8299:     } else {
                   8300:         $r->print(&navmap_errormsg());
                   8301:         return '';
1.677     raeburn  8302:     }
1.691     raeburn  8303:     my $nav_error;
1.83      albertel 8304:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
1.691     raeburn  8305:     if ($randomorder || $randompick) {
                   8306:         $nav_error = &get_master_seq(\@resources,\@master_seq,\%symb_to_resource);
                   8307:         if ($nav_error) {
                   8308:             $r->print(&navmap_errormsg());
                   8309:             return '';
                   8310:         }
                   8311:     }
1.557     raeburn  8312:     &graders_resources_pass(\@resources,\%grader_partids_by_symb,
1.649     raeburn  8313:                             \%grader_randomlists_by_symb,$bubbles_per_row);
1.557     raeburn  8314: 
1.554     raeburn  8315:     my ($uname,$udom);
1.82      albertel 8316:     my $result= <<SCANTRONFORM;
1.81      albertel 8317: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantronupload">
                   8318:   <input type="hidden" name="command" value="scantron_configphase" />
                   8319:   $default_form_data
                   8320: SCANTRONFORM
1.82      albertel 8321:     $r->print($result);
                   8322: 
                   8323:     my @delayqueue;
1.542     raeburn  8324:     my (%completedstudents,%scandata);
1.140     albertel 8325:     
1.520     www      8326:     my $lock=&Apache::lonnet::set_lock(&mt('Grading bubblesheet exam'));
1.200     albertel 8327:     my $count=&get_todo_count($scanlines,$scan_data);
1.667     www      8328:     my %prog_state=&Apache::lonhtmlcommon::Create_PrgWin($r,$count);
                   8329:     &Apache::lonhtmlcommon::Update_PrgWin($r,\%prog_state,'Processing first student');
1.542     raeburn  8330:     $r->print('<br />');
1.140     albertel 8331:     my $start=&Time::HiRes::time();
1.158     albertel 8332:     my $i=-1;
1.542     raeburn  8333:     my $started;
1.447     foxr     8334: 
1.649     raeburn  8335:     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # Need the bubble lines array to parse.
1.582     raeburn  8336:     if ($nav_error) {
                   8337:         $r->print(&navmap_errormsg());
                   8338:         return '';
                   8339:     }
                   8340: 
1.513     foxr     8341:     # If an ssi failed in scantron_get_maxbubble, put an error message out to
                   8342:     # the user and return.
                   8343: 
                   8344:     if ($ssi_error) {
                   8345: 	$r->print("</form>");
                   8346: 	&ssi_print_error($r);
1.520     www      8347:         &Apache::lonnet::remove_lock($lock);
1.513     foxr     8348: 	return '';		# Dunno why the other returns return '' rather than just returning.
                   8349:     }
1.447     foxr     8350: 
1.542     raeburn  8351:     my %lettdig = &letter_to_digits();
                   8352:     my $numletts = scalar(keys(%lettdig));
1.691     raeburn  8353:     my %orderedforcode;
1.542     raeburn  8354: 
1.157     albertel 8355:     while ($i<$scanlines->{'count'}) {
                   8356:  	($uname,$udom)=('','');
                   8357:  	$i++;
1.200     albertel 8358:  	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.157     albertel 8359:  	if ($line=~/^[\s\cz]*$/) { next; }
1.200     albertel 8360: 	if ($started) {
1.667     www      8361: 	    &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state,'last student');
1.200     albertel 8362: 	}
                   8363: 	$started=1;
1.691     raeburn  8364:         my %respnumlookup = ();
                   8365:         my %startline = ();
                   8366:         my $total;
1.157     albertel 8367:  	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
1.691     raeburn  8368:                                                  $scan_data,undef,\%idmap,$randomorder,
                   8369:                                                  $randompick,$sequence,\@master_seq,
                   8370:                                                  \%symb_to_resource,\%grader_partids_by_symb,
                   8371:                                                  \%orderedforcode,\%respnumlookup,\%startline,
                   8372:                                                  \$total);
1.157     albertel 8373:  	unless ($uname=&scantron_find_student($scan_record,$scan_data,
                   8374:  					      \%idmap,$i)) {
                   8375:   	    &scantron_add_delay(\@delayqueue,$line,
                   8376:  				'Unable to find a student that matches',1);
                   8377:  	    next;
                   8378:   	}
                   8379:  	if (exists $completedstudents{$uname}) {
                   8380:  	    &scantron_add_delay(\@delayqueue,$line,
                   8381:  				'Student '.$uname.' has multiple sheets',2);
                   8382:  	    next;
                   8383:  	}
1.677     raeburn  8384:         my $usec = $classlist->{$uname}->[&Apache::loncoursedata::CL_SECTION];
                   8385:         my $user = $uname.':'.$usec;
1.157     albertel 8386:   	($uname,$udom)=split(/:/,$uname);
1.330     albertel 8387: 
1.677     raeburn  8388:         my $scancode;
                   8389:         if ((exists($scan_record->{'scantron.CODE'})) &&
                   8390:             (&Apache::lonnet::validCODE($scan_record->{'scantron.CODE'}))) {
                   8391:             $scancode = $scan_record->{'scantron.CODE'};
                   8392:         } else {
                   8393:             $scancode = '';
                   8394:         }
                   8395: 
                   8396:         my @mapresources = @resources;
1.689     raeburn  8397:         if ($randomorder || $randompick) {
1.678     raeburn  8398:             @mapresources = 
1.691     raeburn  8399:                 &users_order($user,$scancode,$sequence,\@master_seq,\%symb_to_resource,
                   8400:                              \%orderedforcode);
1.677     raeburn  8401:         }
1.586     raeburn  8402:         my (%partids_by_symb,$res_error);
1.677     raeburn  8403:         foreach my $resource (@mapresources) {
1.586     raeburn  8404:             my $ressymb;
                   8405:             if (ref($resource)) {
                   8406:                 $ressymb = $resource->symb();
                   8407:             } else {
                   8408:                 $res_error = 1;
                   8409:                 last;
                   8410:             }
1.557     raeburn  8411:             if ((exists($grader_randomlists_by_symb{$ressymb})) ||
                   8412:                 (ref($grader_partids_by_symb{$ressymb}) ne 'ARRAY')) {
                   8413:                 my ($analysis,$parts) =
1.672     raeburn  8414:                     &scantron_partids_tograde($resource,$env{'request.course.id'},
                   8415:                                               $uname,$udom,undef,$bubbles_per_row);
1.557     raeburn  8416:                 $partids_by_symb{$ressymb} = $parts;
                   8417:             } else {
                   8418:                 $partids_by_symb{$ressymb} = $grader_partids_by_symb{$ressymb};
                   8419:             }
1.554     raeburn  8420:         }
                   8421: 
1.586     raeburn  8422:         if ($res_error) {
                   8423:             &scantron_add_delay(\@delayqueue,$line,
                   8424:                                 'An error occurred while grading student '.$uname,2);
                   8425:             next;
                   8426:         }
                   8427: 
1.330     albertel 8428: 	&Apache::lonxml::clear_problem_counter();
1.514     raeburn  8429:   	&Apache::lonnet::appenv($scan_record);
1.376     albertel 8430: 
                   8431: 	if (&scantron_clear_skip($scanlines,$scan_data,$i)) {
                   8432: 	    &scantron_putfile($scanlines,$scan_data);
                   8433: 	}
1.161     albertel 8434: 	
1.542     raeburn  8435:         if (&grade_student_bubbles($r,$uname,$udom,$scan_record,$scancode,
1.677     raeburn  8436:                                    \@mapresources,\%partids_by_symb,
1.691     raeburn  8437:                                    $bubbles_per_row,$randomorder,$randompick,
                   8438:                                    \%respnumlookup,\%startline) 
                   8439:             eq 'ssi_error') {
1.542     raeburn  8440:             $ssi_error = 0; # So end of handler error message does not trigger.
                   8441:             $r->print("</form>");
                   8442:             &ssi_print_error($r);
                   8443:             &Apache::lonnet::remove_lock($lock);
                   8444:             return '';      # Why return ''?  Beats me.
                   8445:         }
1.513     foxr     8446: 
1.692     raeburn  8447:         if (($scancode) && ($randomorder || $randompick)) {
                   8448:             my $parmresult =
                   8449:                 &Apache::lonparmset::storeparm_by_symb($symb,
                   8450:                                                        '0_examcode',2,$scancode,
                   8451:                                                        'string_examcode',$uname,
                   8452:                                                        $udom);
                   8453:         }
1.140     albertel 8454: 	$completedstudents{$uname}={'line'=>$line};
1.542     raeburn  8455:         if ($env{'form.verifyrecord'}) {
                   8456:             my $lastpos = $env{'form.scantron_maxbubble'}*$scantron_config{'Qlength'};
1.691     raeburn  8457:             if ($randompick) {
                   8458:                 if ($total) {
                   8459:                     $lastpos = $total*$scantron_config{'Qlength'};
                   8460:                 }
                   8461:             }
                   8462: 
1.542     raeburn  8463:             my $studentdata = substr($line,$scantron_config{'Qstart'}-1,$lastpos);
                   8464:             chomp($studentdata);
                   8465:             $studentdata =~ s/\r$//;
                   8466:             my $studentrecord = '';
                   8467:             my $counter = -1;
1.677     raeburn  8468:             foreach my $resource (@mapresources) {
1.554     raeburn  8469:                 my $ressymb = $resource->symb();
1.542     raeburn  8470:                 ($counter,my $recording) =
                   8471:                     &verify_scantron_grading($resource,$udom,$uname,$env{'request.course.id'},
1.554     raeburn  8472:                                              $counter,$studentdata,$partids_by_symb{$ressymb},
1.691     raeburn  8473:                                              \%scantron_config,\%lettdig,$numletts,$randomorder,
                   8474:                                              $randompick,\%respnumlookup,\%startline);
1.542     raeburn  8475:                 $studentrecord .= $recording;
                   8476:             }
                   8477:             if ($studentrecord ne $studentdata) {
1.554     raeburn  8478:                 &Apache::lonxml::clear_problem_counter();
                   8479:                 if (&grade_student_bubbles($r,$uname,$udom,$scan_record,$scancode,
1.677     raeburn  8480:                                            \@mapresources,\%partids_by_symb,
1.691     raeburn  8481:                                            $bubbles_per_row,$randomorder,$randompick,
                   8482:                                            \%respnumlookup,\%startline) 
                   8483:                     eq 'ssi_error') {
1.554     raeburn  8484:                     $ssi_error = 0; # So end of handler error message does not trigger.
                   8485:                     $r->print("</form>");
                   8486:                     &ssi_print_error($r);
                   8487:                     &Apache::lonnet::remove_lock($lock);
                   8488:                     delete($completedstudents{$uname});
                   8489:                     return '';
                   8490:                 }
1.542     raeburn  8491:                 $counter = -1;
                   8492:                 $studentrecord = '';
1.677     raeburn  8493:                 foreach my $resource (@mapresources) {
1.554     raeburn  8494:                     my $ressymb = $resource->symb();
1.542     raeburn  8495:                     ($counter,my $recording) =
                   8496:                         &verify_scantron_grading($resource,$udom,$uname,$env{'request.course.id'},
1.554     raeburn  8497:                                                  $counter,$studentdata,$partids_by_symb{$ressymb},
1.691     raeburn  8498:                                                  \%scantron_config,\%lettdig,$numletts,
                   8499:                                                  $randomorder,$randompick,\%respnumlookup,
                   8500:                                                  \%startline);
1.542     raeburn  8501:                     $studentrecord .= $recording;
                   8502:                 }
                   8503:                 if ($studentrecord ne $studentdata) {
1.658     bisitz   8504:                     $r->print('<p><span class="LC_warning">');
1.542     raeburn  8505:                     if ($scancode eq '') {
1.658     bisitz   8506:                         $r->print(&mt('Mismatch grading bubblesheet for user: [_1] with ID: [_2].',
1.542     raeburn  8507:                                   $uname.':'.$udom,$scan_record->{'scantron.ID'}));
                   8508:                     } else {
1.658     bisitz   8509:                         $r->print(&mt('Mismatch grading bubblesheet for user: [_1] with ID: [_2] and CODE: [_3].',
1.542     raeburn  8510:                                   $uname.':'.$udom,$scan_record->{'scantron.ID'},$scancode));
                   8511:                     }
                   8512:                     $r->print('</span><br />'.&Apache::loncommon::start_data_table()."\n".
                   8513:                               &Apache::loncommon::start_data_table_header_row()."\n".
                   8514:                               '<th>'.&mt('Source').'</th><th>'.&mt('Bubbled responses').'</th>'.
                   8515:                               &Apache::loncommon::end_data_table_header_row()."\n".
                   8516:                               &Apache::loncommon::start_data_table_row().
1.658     bisitz   8517:                               '<td>'.&mt('Bubblesheet').'</td>'.
1.707     bisitz   8518:                               '<td><span class="LC_nobreak" style="white-space: pre;"><tt>'.$studentdata.'</tt></span></td>'.
1.542     raeburn  8519:                               &Apache::loncommon::end_data_table_row().
                   8520:                               &Apache::loncommon::start_data_table_row().
1.658     bisitz   8521:                               '<td>'.&mt('Stored submissions').'</td>'.
1.707     bisitz   8522:                               '<td><span class="LC_nobreak" style="white-space: pre;"><tt>'.$studentrecord.'</tt></span></td>'."\n".
1.542     raeburn  8523:                               &Apache::loncommon::end_data_table_row().
                   8524:                               &Apache::loncommon::end_data_table().'</p>');
                   8525:                 } else {
                   8526:                     $r->print('<br /><span class="LC_warning">'.
                   8527:                              &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 />'.
                   8528:                              &mt("As a consequence, this user's submission history records two tries.").
                   8529:                                  '</span><br />');
                   8530:                 }
                   8531:             }
                   8532:         }
1.543     raeburn  8533:         if (&Apache::loncommon::connection_aborted($r)) { last; }
1.140     albertel 8534:     } continue {
1.330     albertel 8535: 	&Apache::lonxml::clear_problem_counter();
1.552     raeburn  8536: 	&Apache::lonnet::delenv('scantron.');
1.82      albertel 8537:     }
1.140     albertel 8538:     &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
1.520     www      8539:     &Apache::lonnet::remove_lock($lock);
1.172     albertel 8540: #    my $lasttime = &Time::HiRes::time()-$start;
                   8541: #    $r->print("<p>took $lasttime</p>");
1.140     albertel 8542: 
1.200     albertel 8543:     $r->print("</form>");
1.157     albertel 8544:     return '';
1.75      albertel 8545: }
1.157     albertel 8546: 
1.557     raeburn  8547: sub graders_resources_pass {
1.649     raeburn  8548:     my ($resources,$grader_partids_by_symb,$grader_randomlists_by_symb,
                   8549:         $bubbles_per_row) = @_;
1.557     raeburn  8550:     if ((ref($resources) eq 'ARRAY') && (ref($grader_partids_by_symb)) && 
                   8551:         (ref($grader_randomlists_by_symb) eq 'HASH')) {
                   8552:         foreach my $resource (@{$resources}) {
                   8553:             my $ressymb = $resource->symb();
                   8554:             my ($analysis,$parts) =
                   8555:                 &scantron_partids_tograde($resource,$env{'request.course.id'},
1.672     raeburn  8556:                                           $env{'user.name'},$env{'user.domain'},
                   8557:                                           1,$bubbles_per_row);
1.557     raeburn  8558:             $grader_partids_by_symb->{$ressymb} = $parts;
                   8559:             if (ref($analysis) eq 'HASH') {
                   8560:                 if (ref($analysis->{'parts_withrandomlist'}) eq 'ARRAY') {
                   8561:                     $grader_randomlists_by_symb->{$ressymb} =
                   8562:                         $analysis->{'parts_withrandomlist'};
                   8563:                 }
                   8564:             }
                   8565:         }
                   8566:     }
                   8567:     return;
                   8568: }
                   8569: 
1.678     raeburn  8570: =pod
                   8571: 
                   8572: =item users_order
                   8573: 
                   8574:   Returns array of resources in current map, ordered based on either CODE,
                   8575:   if this is a CODEd exam, or based on student's identity if this is a 
                   8576:   "NAMEd" exam.
                   8577: 
1.691     raeburn  8578:   Should be used when randomorder and/or randompick applied when the 
                   8579:   corresponding exam was printed, prior to students completing bubblesheets 
                   8580:   for the version of the exam the student received.
1.678     raeburn  8581: 
                   8582: =cut
                   8583: 
                   8584: sub users_order  {
1.691     raeburn  8585:     my ($user,$scancode,$mapurl,$master_seq,$symb_to_resource,$orderedforcode) = @_;
1.678     raeburn  8586:     my @mapresources;
1.691     raeburn  8587:     unless ((ref($master_seq) eq 'ARRAY') && (ref($symb_to_resource) eq 'HASH')) {
1.678     raeburn  8588:         return @mapresources;
1.691     raeburn  8589:     }
                   8590:     if ($scancode) {
                   8591:         if ((ref($orderedforcode) eq 'HASH') && (ref($orderedforcode->{$scancode}) eq 'ARRAY')) {
                   8592:             @mapresources = @{$orderedforcode->{$scancode}};
                   8593:         } else {
                   8594:             $env{'form.CODE'} = $scancode;
                   8595:             my $actual_seq =
                   8596:                 &Apache::lonprintout::master_seq_to_person_seq($mapurl,
                   8597:                                                                $master_seq,
                   8598:                                                                $user,$scancode,1);
                   8599:             if (ref($actual_seq) eq 'ARRAY') {
                   8600:                 @mapresources = map { $symb_to_resource->{$_}; } @{$actual_seq};
                   8601:                 if (ref($orderedforcode) eq 'HASH') {
                   8602:                     if (@mapresources > 0) { 
                   8603:                         $orderedforcode->{$scancode} = \@mapresources;
                   8604:                     }
                   8605:                 }
                   8606:             }
                   8607:             delete($env{'form.CODE'});
1.678     raeburn  8608:         }
                   8609:     } else {
                   8610:         my $actual_seq =
                   8611:             &Apache::lonprintout::master_seq_to_person_seq($mapurl,
                   8612:                                                            $master_seq,
1.688     raeburn  8613:                                                            $user,undef,1);
1.678     raeburn  8614:         if (ref($actual_seq) eq 'ARRAY') {
                   8615:             @mapresources = 
                   8616:                 map { $symb_to_resource->{$_}; } @{$actual_seq};
                   8617:         }
1.691     raeburn  8618:     }
                   8619:     return @mapresources;
1.678     raeburn  8620: }
                   8621: 
1.542     raeburn  8622: sub grade_student_bubbles {
1.691     raeburn  8623:     my ($r,$uname,$udom,$scan_record,$scancode,$resources,$parts,$bubbles_per_row,
                   8624:         $randomorder,$randompick,$respnumlookup,$startline) = @_;
                   8625:     my $uselookup = 0;
                   8626:     if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH') &&
                   8627:         (ref($startline) eq 'HASH')) {
                   8628:         $uselookup = 1;
                   8629:     }
                   8630: 
1.554     raeburn  8631:     if (ref($resources) eq 'ARRAY') {
                   8632:         my $count = 0;
                   8633:         foreach my $resource (@{$resources}) {
                   8634:             my $ressymb = $resource->symb();
                   8635:             my %form = ('submitted'      => 'scantron',
                   8636:                         'grade_target'   => 'grade',
                   8637:                         'grade_username' => $uname,
                   8638:                         'grade_domain'   => $udom,
                   8639:                         'grade_courseid' => $env{'request.course.id'},
                   8640:                         'grade_symb'     => $ressymb,
                   8641:                         'CODE'           => $scancode
                   8642:                        );
1.649     raeburn  8643:             if ($bubbles_per_row ne '') {
                   8644:                 $form{'bubbles_per_row'} = $bubbles_per_row;
                   8645:             }
1.663     raeburn  8646:             if ($env{'form.scantron_lastbubblepoints'} ne '') {
                   8647:                 $form{'scantron_lastbubblepoints'} = $env{'form.scantron_lastbubblepoints'};
                   8648:             }
1.554     raeburn  8649:             if (ref($parts) eq 'HASH') {
                   8650:                 if (ref($parts->{$ressymb}) eq 'ARRAY') {
                   8651:                     foreach my $part (@{$parts->{$ressymb}}) {
1.691     raeburn  8652:                         if ($uselookup) {
                   8653:                             $form{'scantron_questnum_start.'.$part} = $startline->{$count} + 1;
                   8654:                         } else {
                   8655:                             $form{'scantron_questnum_start.'.$part} =
                   8656:                                 1+$env{'form.scantron.first_bubble_line.'.$count};
                   8657:                         }
1.554     raeburn  8658:                         $count++;
                   8659:                     }
                   8660:                 }
                   8661:             }
                   8662:             my $result=&ssi_with_retries($resource->src(),$ssi_retries,%form);
                   8663:             return 'ssi_error' if ($ssi_error);
                   8664:             last if (&Apache::loncommon::connection_aborted($r));
                   8665:         }
1.542     raeburn  8666:     }
                   8667:     return;
                   8668: }
                   8669: 
1.157     albertel 8670: sub scantron_upload_scantron_data {
1.608     www      8671:     my ($r,$symb)=@_;
1.565     raeburn  8672:     my $dom = $env{'request.role.domain'};
                   8673:     my $domdesc = &Apache::lonnet::domain($dom,'description');
                   8674:     $r->print(&Apache::loncommon::coursebrowser_javascript($dom));
1.157     albertel 8675:     my $select_link=&Apache::loncommon::selectcourse_link('rules','courseid',
1.181     albertel 8676: 							  'domainid',
1.565     raeburn  8677: 							  'coursename',$dom);
                   8678:     my $syllabuslink = '<a href="javascript:ToSyllabus();">'.&mt('Syllabus').'</a>'.
                   8679:                        ('&nbsp'x2).&mt('(shows course personnel)'); 
1.608     www      8680:     my $default_form_data=&defaultFormData($symb);
1.579     raeburn  8681:     my $nofile_alert = &mt('Please use the browse button to select a file from your local directory.');
1.736   ! damieng  8682:     &js_escape(\$nofile_alert);
1.579     raeburn  8683:     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.736   ! damieng  8684:     &js_escape(\$nocourseid_alert);
1.597     wenzelju 8685:     $r->print(&Apache::lonhtmlcommon::scripttag('
1.157     albertel 8686:     function checkUpload(formname) {
                   8687: 	if (formname.upfile.value == "") {
1.579     raeburn  8688: 	    alert("'.$nofile_alert.'");
1.157     albertel 8689: 	    return false;
                   8690: 	}
1.565     raeburn  8691:         if (formname.courseid.value == "") {
1.579     raeburn  8692:             alert("'.$nocourseid_alert.'");
1.565     raeburn  8693:             return false;
                   8694:         }
1.157     albertel 8695: 	formname.submit();
                   8696:     }
1.565     raeburn  8697: 
                   8698:     function ToSyllabus() {
                   8699:         var cdom = '."'$dom'".';
                   8700:         var cnum = document.rules.courseid.value;
                   8701:         if (cdom == "" || cdom == null) {
                   8702:             return;
                   8703:         }
                   8704:         if (cnum == "" || cnum == null) {
                   8705:            return;
                   8706:         }
                   8707:         syllwin=window.open("/public/"+cdom+"/"+cnum+"/syllabus","LONCAPASyllabus",
                   8708:                             "height=350,width=350,scrollbars=yes,menubar=no");
                   8709:         return;
                   8710:     }
                   8711: 
1.597     wenzelju 8712: '));
                   8713:     $r->print('
1.648     bisitz   8714: <h3>'.&mt('Send bubblesheet data to a course').'</h3>
1.566     raeburn  8715: 
1.492     albertel 8716: <form enctype="multipart/form-data" action="/adm/grades" name="rules" method="post">
1.565     raeburn  8717: '.$default_form_data.
                   8718:   &Apache::lonhtmlcommon::start_pick_box().
                   8719:   &Apache::lonhtmlcommon::row_title(&mt('Course ID')).
                   8720:   '<input name="courseid" type="text" size="30" />'.$select_link.
                   8721:   &Apache::lonhtmlcommon::row_closure().
                   8722:   &Apache::lonhtmlcommon::row_title(&mt('Course Name')).
                   8723:   '<input name="coursename" type="text" size="30" />'.$syllabuslink.
                   8724:   &Apache::lonhtmlcommon::row_closure().
                   8725:   &Apache::lonhtmlcommon::row_title(&mt('Domain')).
                   8726:   '<input name="domainid" type="hidden" />'.$domdesc.
                   8727:   &Apache::lonhtmlcommon::row_closure().
                   8728:   &Apache::lonhtmlcommon::row_title(&mt('File to upload')).
                   8729:   '<input type="file" name="upfile" size="50" />'.
                   8730:   &Apache::lonhtmlcommon::row_closure(1).
                   8731:   &Apache::lonhtmlcommon::end_pick_box().'<br />
                   8732: 
1.492     albertel 8733: <input name="command" value="scantronupload_save" type="hidden" />
1.589     bisitz   8734: <input type="button" onclick="javascript:checkUpload(this.form);" value="'.&mt('Upload Bubblesheet Data').'" />
1.157     albertel 8735: </form>
1.492     albertel 8736: ');
1.157     albertel 8737:     return '';
                   8738: }
                   8739: 
1.423     albertel 8740: 
1.157     albertel 8741: sub scantron_upload_scantron_data_save {
1.608     www      8742:     my($r,$symb)=@_;
1.182     albertel 8743:     my $doanotherupload=
                   8744: 	'<br /><form action="/adm/grades" method="post">'."\n".
                   8745: 	'<input type="hidden" name="command" value="scantronupload" />'."\n".
1.492     albertel 8746: 	'<input type="submit" name="submit" value="'.&mt('Do Another Upload').'" />'."\n".
1.182     albertel 8747: 	'</form>'."\n";
1.257     albertel 8748:     if (!&Apache::lonnet::allowed('usc',$env{'form.domainid'}) &&
1.162     albertel 8749: 	!&Apache::lonnet::allowed('usc',
1.257     albertel 8750: 			    $env{'form.domainid'}.'_'.$env{'form.courseid'})) {
1.575     www      8751: 	$r->print(&mt("You are not allowed to upload bubblesheet data to the requested course.")."<br />");
1.614     www      8752: 	unless ($symb) {
1.182     albertel 8753: 	    $r->print($doanotherupload);
                   8754: 	}
1.162     albertel 8755: 	return '';
                   8756:     }
1.257     albertel 8757:     my %coursedata=&Apache::lonnet::coursedescription($env{'form.domainid'}.'_'.$env{'form.courseid'});
1.568     raeburn  8758:     my $uploadedfile;
1.710     bisitz   8759:     $r->print('<p>'.&mt('Uploading file to [_1]','"'.$coursedata{'description'}.'"').'</p>');
1.257     albertel 8760:     if (length($env{'form.upfile'}) < 2) {
1.710     bisitz   8761:         $r->print(
                   8762:             &Apache::lonhtmlcommon::confirm_success(
                   8763:                 &mt('The file: [_1] you attempted to upload contained no information. Please check that you entered the correct filename.',
                   8764:                         '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>'),1));
1.183     albertel 8765:     } else {
1.568     raeburn  8766:         my $result = 
                   8767:             &Apache::lonnet::userfileupload('upfile','','scantron','','','',
                   8768:                                             $env{'form.courseid'},$env{'form.domainid'});
1.710     bisitz   8769:         if ($result =~ m{^/uploaded/}) {
                   8770:             $r->print(
                   8771:                 &Apache::lonhtmlcommon::confirm_success(&mt('Upload successful')).'<br />'.
                   8772:                 &mt('Uploaded [_1] bytes of data into location: [_2]',
                   8773:                         (length($env{'form.upfile'})-1),
                   8774:                         '<span class="LC_filename">'.$result.'</span>'));
1.568     raeburn  8775:             ($uploadedfile) = ($result =~ m{/([^/]+)$});
1.567     raeburn  8776:             $r->print(&validate_uploaded_scantron_file($env{'form.domainid'},
1.568     raeburn  8777:                                                        $env{'form.courseid'},$uploadedfile));
1.710     bisitz   8778:         } else {
                   8779:             $r->print(
                   8780:                 &Apache::lonhtmlcommon::confirm_success(&mt('Upload failed'),1).'<br />'.
                   8781:                     &mt('An error ([_1]) occurred when attempting to upload the file: [_2]',
                   8782:                           $result,
1.568     raeburn  8783: 			  '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>'));
1.183     albertel 8784: 	}
                   8785:     }
1.174     albertel 8786:     if ($symb) {
1.612     www      8787: 	$r->print(&scantron_selectphase($r,$uploadedfile,$symb));
1.174     albertel 8788:     } else {
1.182     albertel 8789: 	$r->print($doanotherupload);
1.174     albertel 8790:     }
1.157     albertel 8791:     return '';
                   8792: }
                   8793: 
1.567     raeburn  8794: sub validate_uploaded_scantron_file {
                   8795:     my ($cdom,$cname,$fname) = @_;
                   8796:     my $scanlines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.$fname);
                   8797:     my @lines;
                   8798:     if ($scanlines ne '-1') {
                   8799:         @lines=split("\n",$scanlines,-1);
                   8800:     }
                   8801:     my $output;
                   8802:     if (@lines) {
                   8803:         my (%counts,$max_match_format);
1.710     bisitz   8804:         my ($found_match_count,$max_match_count,$max_match_pct) = (0,0,0);
1.567     raeburn  8805:         my $classlist = &Apache::loncoursedata::get_classlist($cdom,$cname);
                   8806:         my %idmap = &username_to_idmap($classlist);
                   8807:         foreach my $key (keys(%idmap)) {
                   8808:             my $lckey = lc($key);
                   8809:             $idmap{$lckey} = $idmap{$key};
                   8810:         }
                   8811:         my %unique_formats;
                   8812:         my @formatlines = &get_scantronformat_file();
                   8813:         foreach my $line (@formatlines) {
                   8814:             chomp($line);
                   8815:             my @config = split(/:/,$line);
                   8816:             my $idstart = $config[5];
                   8817:             my $idlength = $config[6];
                   8818:             if (($idstart ne '') && ($idlength > 0)) {
                   8819:                 if (ref($unique_formats{$idstart.':'.$idlength}) eq 'ARRAY') {
                   8820:                     push(@{$unique_formats{$idstart.':'.$idlength}},$config[0].':'.$config[1]); 
                   8821:                 } else {
                   8822:                     $unique_formats{$idstart.':'.$idlength} = [$config[0].':'.$config[1]];
                   8823:                 }
                   8824:             }
                   8825:         }
                   8826:         foreach my $key (keys(%unique_formats)) {
                   8827:             my ($idstart,$idlength) = split(':',$key);
                   8828:             %{$counts{$key}} = (
                   8829:                                'found'   => 0,
                   8830:                                'total'   => 0,
                   8831:                               );
                   8832:             foreach my $line (@lines) {
                   8833:                 next if ($line =~ /^#/);
                   8834:                 next if ($line =~ /^[\s\cz]*$/);
                   8835:                 my $id = substr($line,$idstart-1,$idlength);
                   8836:                 $id = lc($id);
                   8837:                 if (exists($idmap{$id})) {
                   8838:                     $counts{$key}{'found'} ++;
                   8839:                 }
                   8840:                 $counts{$key}{'total'} ++;
                   8841:             }
                   8842:             if ($counts{$key}{'total'}) {
                   8843:                 my $percent_match = (100*$counts{$key}{'found'})/($counts{$key}{'total'});
                   8844:                 if (($max_match_format eq '') || ($percent_match > $max_match_pct)) {
                   8845:                     $max_match_pct = $percent_match;
                   8846:                     $max_match_format = $key;
1.710     bisitz   8847:                     $found_match_count = $counts{$key}{'found'};
1.567     raeburn  8848:                     $max_match_count = $counts{$key}{'total'};
                   8849:                 }
                   8850:             }
                   8851:         }
                   8852:         if (ref($unique_formats{$max_match_format}) eq 'ARRAY') {
                   8853:             my $format_descs;
                   8854:             my $numwithformat = @{$unique_formats{$max_match_format}};
                   8855:             for (my $i=0; $i<$numwithformat; $i++) {
                   8856:                 my ($name,$desc) = split(':',$unique_formats{$max_match_format}[$i]);
                   8857:                 if ($i<$numwithformat-2) {
                   8858:                     $format_descs .= '"<i>'.$desc.'</i>", ';
                   8859:                 } elsif ($i==$numwithformat-2) {
                   8860:                     $format_descs .= '"<i>'.$desc.'</i>" '.&mt('and').' ';
                   8861:                 } elsif ($i==$numwithformat-1) {
                   8862:                     $format_descs .= '"<i>'.$desc.'</i>"';
                   8863:                 }
                   8864:             }
                   8865:             my $showpct = sprintf("%.0f",$max_match_pct).'%';
1.710     bisitz   8866:             $output .= '<br />';
                   8867:             if ($found_match_count == $max_match_count) {
                   8868:                 # 100% matching entries
                   8869:                 $output .= &Apache::lonhtmlcommon::confirm_success(
                   8870:                      &mt('Comparison of student IDs: [_1] matching ([quant,_2,entry,entries])',
                   8871:                             '<b>'.$showpct.'</b>',$found_match_count)).'<br />'.
                   8872:                 &mt('Comparison of student IDs in the uploaded file with'.
                   8873:                     ' the course roster found matches for [_1] of the [_2] entries'.
                   8874:                     ' in the file (for the format defined for [_3]).',
                   8875:                         '<b>'.$showpct.'</b>','<b>'.$max_match_count.'</b>',$format_descs);
                   8876:             } else {
                   8877:                 # Not all entries matching? -> Show warning and additional info
                   8878:                 $output .=
                   8879:                     &Apache::lonhtmlcommon::confirm_success(
                   8880:                         &mt('Comparison of student IDs: [_1] matching ([_2]/[quant,_3,entry,entries])',
                   8881:                                 '<b>'.$showpct.'</b>',$found_match_count,$max_match_count).'<br />'.
                   8882:                         &mt('Not all entries could be matched!'),1).'<br />'.
                   8883:                     &mt('Comparison of student IDs in the uploaded file with'.
                   8884:                         ' the course roster found matches for [_1] of the [_2] entries'.
                   8885:                         ' in the file (for the format defined for [_3]).',
                   8886:                             '<b>'.$showpct.'</b>','<b>'.$max_match_count.'</b>',$format_descs).
                   8887:                     '<p class="LC_info">'.
                   8888:                     &mt('A low percentage of matches results from one of the following:').
                   8889:                     '</p><ul>'.
                   8890:                     '<li>'.&mt('The file was uploaded to the wrong course.').'</li>'.
                   8891:                     '<li>'.&mt('The data is not in the format expected for the domain: [_1]',
                   8892:                                '<i>'.$cdom.'</i>').'</li>'.
                   8893:                     '<li>'.&mt('Students did not bubble their IDs, or mis-bubbled them').'</li>'.
                   8894:                     '<li>'.&mt('The course roster is not up to date.').'</li>'.
                   8895:                     '</ul>';
                   8896:             }
1.567     raeburn  8897:         }
                   8898:     } else {
1.710     bisitz   8899:         $output = '<p class="LC_warning">'.&mt('Uploaded file contained no data').'</p>';
1.567     raeburn  8900:     }
                   8901:     return $output;
                   8902: }
                   8903: 
1.202     albertel 8904: sub valid_file {
                   8905:     my ($requested_file)=@_;
                   8906:     foreach my $filename (sort(&scantron_filenames())) {
                   8907: 	if ($requested_file eq $filename) { return 1; }
                   8908:     }
                   8909:     return 0;
                   8910: }
                   8911: 
                   8912: sub scantron_download_scantron_data {
1.608     www      8913:     my ($r,$symb)=@_;
                   8914:     my $default_form_data=&defaultFormData($symb);
1.257     albertel 8915:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   8916:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   8917:     my $file=$env{'form.scantron_selectfile'};
1.202     albertel 8918:     if (! &valid_file($file)) {
1.492     albertel 8919: 	$r->print('
1.202     albertel 8920: 	<p>
1.686     bisitz   8921: 	    '.&mt('The requested filename was invalid.').'
1.202     albertel 8922:         </p>
1.492     albertel 8923: ');
1.202     albertel 8924: 	return;
                   8925:     }
                   8926:     my $orig='/uploaded/'.$cdom.'/'.$cname.'/scantron_orig_'.$file;
                   8927:     my $corrected='/uploaded/'.$cdom.'/'.$cname.'/scantron_corrected_'.$file;
                   8928:     my $skipped='/uploaded/'.$cdom.'/'.$cname.'/scantron_skipped_'.$file;
                   8929:     &Apache::lonnet::allowuploaded('/adm/grades',$orig);
                   8930:     &Apache::lonnet::allowuploaded('/adm/grades',$corrected);
                   8931:     &Apache::lonnet::allowuploaded('/adm/grades',$skipped);
1.492     albertel 8932:     $r->print('
1.202     albertel 8933:     <p>
1.723     raeburn  8934: 	'.&mt('[_1]Original[_2] file as uploaded by the bubblesheet scanning office.',
1.492     albertel 8935: 	      '<a href="'.$orig.'">','</a>').'
1.202     albertel 8936:     </p>
                   8937:     <p>
1.492     albertel 8938: 	'.&mt('[_1]Corrections[_2], a file of corrected records that were used in grading.',
                   8939: 	      '<a href="'.$corrected.'">','</a>').'
1.202     albertel 8940:     </p>
                   8941:     <p>
1.492     albertel 8942: 	'.&mt('[_1]Skipped[_2], a file of records that were skipped.',
                   8943: 	      '<a href="'.$skipped.'">','</a>').'
1.202     albertel 8944:     </p>
1.492     albertel 8945: ');
1.202     albertel 8946:     return '';
                   8947: }
1.157     albertel 8948: 
1.523     raeburn  8949: sub checkscantron_results {
1.608     www      8950:     my ($r,$symb) = @_;
1.523     raeburn  8951:     if (!$symb) {return '';}
                   8952:     my $cid = $env{'request.course.id'};
1.542     raeburn  8953:     my %lettdig = &letter_to_digits();
1.523     raeburn  8954:     my $numletts = scalar(keys(%lettdig));
                   8955:     my $cnum = $env{'course.'.$cid.'.num'};
                   8956:     my $cdom = $env{'course.'.$cid.'.domain'};
                   8957:     my (undef, undef, $sequence) = &Apache::lonnet::decode_symb($env{'form.selectpage'});
                   8958:     my %record;
                   8959:     my %scantron_config =
                   8960:         &Apache::grades::get_scantron_config($env{'form.scantron_format'});
1.649     raeburn  8961:     my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config);
1.523     raeburn  8962:     my ($scanlines,$scan_data)=&Apache::grades::scantron_getfile();
                   8963:     my $classlist=&Apache::loncoursedata::get_classlist();
                   8964:     my %idmap=&Apache::grades::username_to_idmap($classlist);
                   8965:     my $navmap=Apache::lonnavmaps::navmap->new();
1.582     raeburn  8966:     unless (ref($navmap)) {
                   8967:         $r->print(&navmap_errormsg());
                   8968:         return '';
                   8969:     }
1.523     raeburn  8970:     my $map=$navmap->getResourceByUrl($sequence);
1.691     raeburn  8971:     my ($randomorder,$randompick,@master_seq,%symb_to_resource,%grader_partids_by_symb,
                   8972:         %grader_randomlists_by_symb,%orderedforcode);
1.677     raeburn  8973:     if (ref($map)) { 
                   8974:         $randomorder=$map->randomorder();
1.689     raeburn  8975:         $randompick=$map->randompick();
1.677     raeburn  8976:     }
1.557     raeburn  8977:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
1.691     raeburn  8978:     my $nav_error = &get_master_seq(\@resources,\@master_seq,\%symb_to_resource);
                   8979:     if ($nav_error) {
                   8980:         $r->print(&navmap_errormsg());
                   8981:         return '';
1.678     raeburn  8982:     }
1.673     raeburn  8983:     &graders_resources_pass(\@resources,\%grader_partids_by_symb,
                   8984:                             \%grader_randomlists_by_symb,$bubbles_per_row);
1.554     raeburn  8985:     my ($uname,$udom);
1.523     raeburn  8986:     my (%scandata,%lastname,%bylast);
                   8987:     $r->print('
                   8988: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="checkscantron">'."\n");
                   8989: 
                   8990:     my @delayqueue;
                   8991:     my %completedstudents;
                   8992: 
1.691     raeburn  8993:     my $count=&get_todo_count($scanlines,$scan_data);
1.667     www      8994:     my %prog_state=&Apache::lonhtmlcommon::Create_PrgWin($r,$count);
1.706     raeburn  8995:     my ($username,$domain,$started);
1.649     raeburn  8996:     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # Need the bubble lines array to parse.
1.582     raeburn  8997:     if ($nav_error) {
                   8998:         $r->print(&navmap_errormsg());
                   8999:         return '';
                   9000:     }
1.523     raeburn  9001: 
1.667     www      9002:     &Apache::lonhtmlcommon::Update_PrgWin($r,\%prog_state,'Processing first student');
1.523     raeburn  9003:     my $start=&Time::HiRes::time();
                   9004:     my $i=-1;
                   9005: 
                   9006:     while ($i<$scanlines->{'count'}) {
                   9007:         ($username,$domain,$uname)=('','','');
                   9008:         $i++;
                   9009:         my $line=&Apache::grades::scantron_get_line($scanlines,$scan_data,$i);
                   9010:         if ($line=~/^[\s\cz]*$/) { next; }
                   9011:         if ($started) {
1.667     www      9012:             &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state,'last student');
1.523     raeburn  9013:         }
                   9014:         $started=1;
                   9015:         my $scan_record=
                   9016:             &Apache::grades::scantron_parse_scanline($line,$i,\%scantron_config,
                   9017:                                                      $scan_data);
1.693     raeburn  9018:         unless ($uname=&scantron_find_student($scan_record,$scan_data,
                   9019:                                               \%idmap,$i)) {
1.523     raeburn  9020:             &Apache::grades::scantron_add_delay(\@delayqueue,$line,
                   9021:                                 'Unable to find a student that matches',1);
                   9022:             next;
                   9023:         }
                   9024:         if (exists $completedstudents{$uname}) {
                   9025:             &Apache::grades::scantron_add_delay(\@delayqueue,$line,
                   9026:                                 'Student '.$uname.' has multiple sheets',2);
                   9027:             next;
                   9028:         }
                   9029:         my $pid = $scan_record->{'scantron.ID'};
                   9030:         $lastname{$pid} = $scan_record->{'scantron.LastName'};
                   9031:         push(@{$bylast{$lastname{$pid}}},$pid);
1.678     raeburn  9032:         my $usec = $classlist->{$uname}->[&Apache::loncoursedata::CL_SECTION];
                   9033:         my $user = $uname.':'.$usec;
1.523     raeburn  9034:         ($username,$domain)=split(/:/,$uname);
1.677     raeburn  9035: 
1.678     raeburn  9036:         my $scancode;
1.677     raeburn  9037:         if ((exists($scan_record->{'scantron.CODE'})) &&
                   9038:             (&Apache::lonnet::validCODE($scan_record->{'scantron.CODE'}))) {
                   9039:             $scancode = $scan_record->{'scantron.CODE'};
                   9040:         } else {
                   9041:             $scancode = '';
                   9042:         }
                   9043: 
                   9044:         my @mapresources = @resources;
1.691     raeburn  9045:         my $lastpos = $env{'form.scantron_maxbubble'}*$scantron_config{'Qlength'};
                   9046:         my %respnumlookup=();
                   9047:         my %startline=();
1.689     raeburn  9048:         if ($randomorder || $randompick) {
1.678     raeburn  9049:             @mapresources =
1.691     raeburn  9050:                 &users_order($user,$scancode,$sequence,\@master_seq,\%symb_to_resource,
                   9051:                              \%orderedforcode);
                   9052:             my $total = &get_respnum_lookups($sequence,$scan_data,\%idmap,$line,
                   9053:                                              $scan_record,\@master_seq,\%symb_to_resource,
                   9054:                                              \%grader_partids_by_symb,\%orderedforcode,
                   9055:                                              \%respnumlookup,\%startline);
                   9056:             if ($randompick && $total) {
                   9057:                 $lastpos = $total*$scantron_config{'Qlength'};
                   9058:             }
1.677     raeburn  9059:         }
1.691     raeburn  9060:         $scandata{$pid} = substr($line,$scantron_config{'Qstart'}-1,$lastpos);
                   9061:         chomp($scandata{$pid});
                   9062:         $scandata{$pid} =~ s/\r$//;
                   9063: 
1.523     raeburn  9064:         my $counter = -1;
1.677     raeburn  9065:         foreach my $resource (@mapresources) {
1.557     raeburn  9066:             my $parts;
1.554     raeburn  9067:             my $ressymb = $resource->symb();
1.557     raeburn  9068:             if ((exists($grader_randomlists_by_symb{$ressymb})) ||
                   9069:                 (ref($grader_partids_by_symb{$ressymb}) ne 'ARRAY')) {
                   9070:                 (my $analysis,$parts) =
1.672     raeburn  9071:                     &scantron_partids_tograde($resource,$env{'request.course.id'},
                   9072:                                               $username,$domain,undef,
                   9073:                                               $bubbles_per_row);
1.557     raeburn  9074:             } else {
                   9075:                 $parts = $grader_partids_by_symb{$ressymb};
                   9076:             }
1.542     raeburn  9077:             ($counter,my $recording) =
                   9078:                 &verify_scantron_grading($resource,$domain,$username,$cid,$counter,
1.554     raeburn  9079:                                          $scandata{$pid},$parts,
1.691     raeburn  9080:                                          \%scantron_config,\%lettdig,$numletts,
                   9081:                                          $randomorder,$randompick,
                   9082:                                          \%respnumlookup,\%startline);
1.542     raeburn  9083:             $record{$pid} .= $recording;
1.523     raeburn  9084:         }
                   9085:     }
                   9086:     &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
                   9087:     $r->print('<br />');
                   9088:     my ($okstudents,$badstudents,$numstudents,$passed,$failed);
                   9089:     $passed = 0;
                   9090:     $failed = 0;
                   9091:     $numstudents = 0;
                   9092:     foreach my $last (sort(keys(%bylast))) {
                   9093:         if (ref($bylast{$last}) eq 'ARRAY') {
                   9094:             foreach my $pid (sort(@{$bylast{$last}})) {
                   9095:                 my $showscandata = $scandata{$pid};
                   9096:                 my $showrecord = $record{$pid};
                   9097:                 $showscandata =~ s/\s/&nbsp;/g;
                   9098:                 $showrecord =~ s/\s/&nbsp;/g;
                   9099:                 if ($scandata{$pid} eq $record{$pid}) {
                   9100:                     my $css_class = ($passed % 2)?'LC_odd_row':'LC_even_row';
                   9101:                     $okstudents .= '<tr class="'.$css_class.'">'.
1.581     www      9102: '<td>'.&mt('Bubblesheet').'</td><td>'.$showscandata.'</td><td rowspan="2">'.$last.'</td><td rowspan="2">'.$pid.'</td>'."\n".
1.523     raeburn  9103: '</tr>'."\n".
                   9104: '<tr class="'.$css_class.'">'."\n".
1.721     bisitz   9105: '<td>'.&mt('Submissions').'</td><td>'.$showrecord.'</td></tr>'."\n";
1.523     raeburn  9106:                     $passed ++;
                   9107:                 } else {
                   9108:                     my $css_class = ($failed % 2)?'LC_odd_row':'LC_even_row';
1.581     www      9109:                     $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  9110: '</tr>'."\n".
                   9111: '<tr class="'.$css_class.'">'."\n".
1.721     bisitz   9112: '<td>'.&mt('Submissions').'</td><td><span class="LC_nobreak">'.$record{$pid}.'</span></td>'."\n".
1.523     raeburn  9113: '</tr>'."\n";
                   9114:                     $failed ++;
                   9115:                 }
                   9116:                 $numstudents ++;
                   9117:             }
                   9118:         }
                   9119:     }
1.648     bisitz   9120:     $r->print(
                   9121:         '<p>'
                   9122:        .&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).',
                   9123:             '<b>',
                   9124:             $numstudents,
                   9125:             '</b>',
                   9126:             $env{'form.scantron_maxbubble'})
                   9127:        .'</p>'
                   9128:     );
1.682     raeburn  9129:     $r->print('<p>'
1.683     raeburn  9130:              .&mt('Exact matches for [_1][quant,_2,student][_3].','<b>',$passed,'</b>')
1.682     raeburn  9131:              .'<br />'
                   9132:              .&mt('Discrepancies detected for [_1][quant,_2,student][_3].','<b>',$failed,'</b>')
                   9133:              .'</p>'
                   9134:     );
1.523     raeburn  9135:     if ($passed) {
1.572     www      9136:         $r->print(&mt('Students with exact correspondence between bubblesheet data and submissions are as follows:').'<br /><br />');
1.523     raeburn  9137:         $r->print(&Apache::loncommon::start_data_table()."\n".
                   9138:                  &Apache::loncommon::start_data_table_header_row()."\n".
                   9139:                  '<th>'.&mt('Source').'</th><th>'.&mt('Bubble records').'</th><th>'.&mt('Name').'</th><th>'.&mt('ID').'</th>'.
                   9140:                  &Apache::loncommon::end_data_table_header_row()."\n".
                   9141:                  $okstudents."\n".
                   9142:                  &Apache::loncommon::end_data_table().'<br />');
                   9143:     }
                   9144:     if ($failed) {
1.572     www      9145:         $r->print(&mt('Students with differences between bubblesheet data and submissions are as follows:').'<br /><br />');
1.523     raeburn  9146:         $r->print(&Apache::loncommon::start_data_table()."\n".
                   9147:                  &Apache::loncommon::start_data_table_header_row()."\n".
                   9148:                  '<th>'.&mt('Source').'</th><th>'.&mt('Bubble records').'</th><th>'.&mt('Name').'</th><th>'.&mt('ID').'</th>'.
                   9149:                  &Apache::loncommon::end_data_table_header_row()."\n".
                   9150:                  $badstudents."\n".
                   9151:                  &Apache::loncommon::end_data_table()).'<br />'.
1.572     www      9152:                  &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  9153:     }
1.614     www      9154:     $r->print('</form><br />');
1.523     raeburn  9155:     return;
                   9156: }
                   9157: 
1.542     raeburn  9158: sub verify_scantron_grading {
1.554     raeburn  9159:     my ($resource,$domain,$username,$cid,$counter,$scandata,$partids,
1.691     raeburn  9160:         $scantron_config,$lettdig,$numletts,$randomorder,$randompick,
                   9161:         $respnumlookup,$startline) = @_;
1.542     raeburn  9162:     my ($record,%expected,%startpos);
                   9163:     return ($counter,$record) if (!ref($resource));
                   9164:     return ($counter,$record) if (!$resource->is_problem());
                   9165:     my $symb = $resource->symb();
1.554     raeburn  9166:     return ($counter,$record) if (ref($partids) ne 'ARRAY');
                   9167:     foreach my $part_id (@{$partids}) {
1.542     raeburn  9168:         $counter ++;
                   9169:         $expected{$part_id} = 0;
1.691     raeburn  9170:         my $respnum = $counter;
                   9171:         if ($randomorder || $randompick) {
                   9172:             $respnum = $respnumlookup->{$counter};
                   9173:             $startpos{$part_id} = $startline->{$counter} + 1;
                   9174:         } else {
                   9175:             $startpos{$part_id} = $env{"form.scantron.first_bubble_line.$counter"};
                   9176:         }
                   9177:         if ($env{"form.scantron.sub_bubblelines.$respnum"}) {
                   9178:             my @sub_lines = split(/,/,$env{"form.scantron.sub_bubblelines.$respnum"});
1.542     raeburn  9179:             foreach my $item (@sub_lines) {
                   9180:                 $expected{$part_id} += $item;
                   9181:             }
                   9182:         } else {
1.691     raeburn  9183:             $expected{$part_id} = $env{"form.scantron.bubblelines.$respnum"};
1.542     raeburn  9184:         }
                   9185:     }
                   9186:     if ($symb) {
                   9187:         my %recorded;
                   9188:         my (%returnhash) = &Apache::lonnet::restore($symb,$cid,$domain,$username);
                   9189:         if ($returnhash{'version'}) {
                   9190:             my %lasthash=();
                   9191:             my $version;
                   9192:             for ($version=1;$version<=$returnhash{'version'};$version++) {
                   9193:                 foreach my $key (sort(split(/\:/,$returnhash{$version.':keys'}))) {
                   9194:                     $lasthash{$key}=$returnhash{$version.':'.$key};
                   9195:                 }
                   9196:             }
                   9197:             foreach my $key (keys(%lasthash)) {
                   9198:                 if ($key =~ /\.scantron$/) {
                   9199:                     my $value = &unescape($lasthash{$key});
                   9200:                     my ($part_id) = ($key =~ /^resource\.(.+)\.scantron$/);
                   9201:                     if ($value eq '') {
                   9202:                         for (my $i=0; $i<$expected{$part_id}; $i++) {
                   9203:                             for (my $j=0; $j<$scantron_config->{'length'}; $j++) {
                   9204:                                 $recorded{$part_id} .= $scantron_config->{'Qoff'};
                   9205:                             }
                   9206:                         }
                   9207:                     } else {
                   9208:                         my @tocheck;
                   9209:                         my @items = split(//,$value);
                   9210:                         if (($scantron_config->{'Qon'} eq 'letter') ||
                   9211:                             ($scantron_config->{'Qon'} eq 'number')) {
                   9212:                             if (@items < $expected{$part_id}) {
                   9213:                                 my $fragment = substr($scandata,$startpos{$part_id},$expected{$part_id});
                   9214:                                 my @singles = split(//,$fragment);
                   9215:                                 foreach my $pos (@singles) {
                   9216:                                     if ($pos eq ' ') {
                   9217:                                         push(@tocheck,$pos);
                   9218:                                     } else {
                   9219:                                         my $next = shift(@items);
                   9220:                                         push(@tocheck,$next);
                   9221:                                     }
                   9222:                                 }
                   9223:                             } else {
                   9224:                                 @tocheck = @items;
                   9225:                             }
                   9226:                             foreach my $letter (@tocheck) {
                   9227:                                 if ($scantron_config->{'Qon'} eq 'letter') {
                   9228:                                     if ($letter !~ /^[A-J]$/) {
                   9229:                                         $letter = $scantron_config->{'Qoff'};
                   9230:                                     }
                   9231:                                     $recorded{$part_id} .= $letter;
                   9232:                                 } elsif ($scantron_config->{'Qon'} eq 'number') {
                   9233:                                     my $digit;
                   9234:                                     if ($letter !~ /^[A-J]$/) {
                   9235:                                         $digit = $scantron_config->{'Qoff'};
                   9236:                                     } else {
                   9237:                                         $digit = $lettdig->{$letter};
                   9238:                                     }
                   9239:                                     $recorded{$part_id} .= $digit;
                   9240:                                 }
                   9241:                             }
                   9242:                         } else {
                   9243:                             @tocheck = @items;
                   9244:                             for (my $i=0; $i<$expected{$part_id}; $i++) {
                   9245:                                 my $curr_sub = shift(@tocheck);
                   9246:                                 my $digit;
                   9247:                                 if ($curr_sub =~ /^[A-J]$/) {
                   9248:                                     $digit = $lettdig->{$curr_sub}-1;
                   9249:                                 }
                   9250:                                 if ($curr_sub eq 'J') {
                   9251:                                     $digit += scalar($numletts);
                   9252:                                 }
                   9253:                                 for (my $j=0; $j<$scantron_config->{'Qlength'}; $j++) {
                   9254:                                     if ($j == $digit) {
                   9255:                                         $recorded{$part_id} .= $scantron_config->{'Qon'};
                   9256:                                     } else {
                   9257:                                         $recorded{$part_id} .= $scantron_config->{'Qoff'};
                   9258:                                     }
                   9259:                                 }
                   9260:                             }
                   9261:                         }
                   9262:                     }
                   9263:                 }
                   9264:             }
                   9265:         }
1.554     raeburn  9266:         foreach my $part_id (@{$partids}) {
1.542     raeburn  9267:             if ($recorded{$part_id} eq '') {
                   9268:                 for (my $i=0; $i<$expected{$part_id}; $i++) {
                   9269:                     for (my $j=0; $j<$scantron_config->{'Qlength'}; $j++) {
                   9270:                         $recorded{$part_id} .= $scantron_config->{'Qoff'};
                   9271:                     }
                   9272:                 }
                   9273:             }
                   9274:             $record .= $recorded{$part_id};
                   9275:         }
                   9276:     }
                   9277:     return ($counter,$record);
                   9278: }
                   9279: 
1.691     raeburn  9280: sub letter_to_digits {
1.542     raeburn  9281:     my %lettdig = (
                   9282:                     A => 1,
                   9283:                     B => 2,
                   9284:                     C => 3,
                   9285:                     D => 4,
                   9286:                     E => 5,
                   9287:                     F => 6,
                   9288:                     G => 7,
                   9289:                     H => 8,
                   9290:                     I => 9,
                   9291:                     J => 0,
                   9292:                   );
                   9293:     return %lettdig;
                   9294: }
                   9295: 
1.423     albertel 9296: 
1.75      albertel 9297: #-------- end of section for handling grading scantron forms -------
                   9298: #
                   9299: #-------------------------------------------------------------------
                   9300: 
1.72      ng       9301: #-------------------------- Menu interface -------------------------
                   9302: #
1.614     www      9303: #--- Href with symb and command ---
                   9304: 
                   9305: sub href_symb_cmd {
                   9306:     my ($symb,$cmd)=@_;
1.669     raeburn  9307:     return '/adm/grades?symb='.&HTML::Entities::encode(&Apache::lonenc::check_encrypt($symb),'<>&"').'&amp;command='.$cmd;
1.72      ng       9308: }
                   9309: 
1.443     banghart 9310: sub grading_menu {
1.608     www      9311:     my ($request,$symb) = @_;
1.443     banghart 9312:     if (!$symb) {return '';}
                   9313: 
                   9314:     my %fields = ('symb'=>&Apache::lonenc::check_encrypt($symb),
1.618     www      9315:                   'command'=>'individual');
1.538     schulted 9316:     
1.598     www      9317:     my $url1a = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   9318: 
                   9319:     $fields{'command'}='ungraded';
                   9320:     my $url1b=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   9321: 
                   9322:     $fields{'command'}='table';
                   9323:     my $url1c=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   9324: 
                   9325:     $fields{'command'}='all_for_one';
                   9326:     my $url1d=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   9327: 
1.621     www      9328:     $fields{'command'}='downloadfilesselect';
                   9329:     my $url1e=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   9330: 
1.443     banghart 9331:     $fields{'command'} = 'csvform';
1.538     schulted 9332:     my $url2 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   9333:     
1.443     banghart 9334:     $fields{'command'} = 'processclicker';
1.538     schulted 9335:     my $url3 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   9336:     
1.443     banghart 9337:     $fields{'command'} = 'scantron_selectphase';
1.538     schulted 9338:     my $url4 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
1.602     www      9339: 
                   9340:     $fields{'command'} = 'initialverifyreceipt';
                   9341:     my $url5 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
1.538     schulted 9342:     
1.598     www      9343:     my @menu = ({	categorytitle=>'Hand Grading',
1.538     schulted 9344:             items =>[
1.598     www      9345:                         {	linktext => 'Select individual students to grade',
                   9346:                     		url => $url1a,
1.538     schulted 9347:                     		permission => 'F',
1.636     wenzelju 9348:                     		icon => 'grade_students.png',
1.598     www      9349:                     		linktitle => 'Grade current resource for a selection of students.'
                   9350:                         }, 
                   9351:                         {       linktext => 'Grade ungraded submissions.',
                   9352:                                 url => $url1b,
                   9353:                                 permission => 'F',
1.636     wenzelju 9354:                                 icon => 'ungrade_sub.png',
1.598     www      9355:                                 linktitle => 'Grade all submissions that have not been graded yet.'
1.538     schulted 9356:                         },
1.598     www      9357: 
                   9358:                         {       linktext => 'Grading table',
                   9359:                                 url => $url1c,
                   9360:                                 permission => 'F',
1.636     wenzelju 9361:                                 icon => 'grading_table.png',
1.598     www      9362:                                 linktitle => 'Grade current resource for all students.'
                   9363:                         },
1.615     www      9364:                         {       linktext => 'Grade page/folder for one student',
1.598     www      9365:                                 url => $url1d,
                   9366:                                 permission => 'F',
1.636     wenzelju 9367:                                 icon => 'grade_PageFolder.png',
1.598     www      9368:                                 linktitle => 'Grade all resources in current page/sequence/folder for one student.'
1.621     www      9369:                         },
                   9370:                         {       linktext => 'Download submissions',
                   9371:                                 url => $url1e,
                   9372:                                 permission => 'F',
1.636     wenzelju 9373:                                 icon => 'download_sub.png',
1.621     www      9374:                                 linktitle => 'Download all students submissions.'
1.598     www      9375:                         }]},
                   9376:                          { categorytitle=>'Automated Grading',
                   9377:                items =>[
                   9378: 
1.538     schulted 9379:                 	    {	linktext => 'Upload Scores',
                   9380:                     		url => $url2,
                   9381:                     		permission => 'F',
                   9382:                     		icon => 'uploadscores.png',
                   9383:                     		linktitle => 'Specify a file containing the class scores for current resource.'
                   9384:                 	    },
                   9385:                 	    {	linktext => 'Process Clicker',
                   9386:                     		url => $url3,
                   9387:                     		permission => 'F',
                   9388:                     		icon => 'addClickerInfoFile.png',
                   9389:                     		linktitle => 'Specify a file containing the clicker information for this resource.'
                   9390:                 	    },
1.587     raeburn  9391:                 	    {	linktext => 'Grade/Manage/Review Bubblesheets',
1.538     schulted 9392:                     		url => $url4,
                   9393:                     		permission => 'F',
1.636     wenzelju 9394:                     		icon => 'bubblesheet.png',
1.648     bisitz   9395:                     		linktitle => 'Grade bubblesheet exams, upload/download bubblesheet data files, and review previously graded bubblesheet exams.'
1.602     www      9396:                 	    },
1.616     www      9397:                             {   linktext => 'Verify Receipt Number',
1.602     www      9398:                                 url => $url5,
                   9399:                                 permission => 'F',
1.636     wenzelju 9400:                                 icon => 'receipt_number.png',
1.602     www      9401:                                 linktitle => 'Verify a system-generated receipt number for correct problem solution.'
                   9402:                             }
                   9403: 
1.538     schulted 9404:                     ]
                   9405:             });
                   9406: 
1.443     banghart 9407:     # Create the menu
                   9408:     my $Str;
1.445     banghart 9409:     $Str .= '<form method="post" action="" name="gradingMenu">';
                   9410:     $Str .= '<input type="hidden" name="command" value="" />'.
1.618     www      9411:     	'<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
1.445     banghart 9412: 
1.602     www      9413:     $Str .= &Apache::lonhtmlcommon::generate_menu(@menu);
1.443     banghart 9414:     return $Str;    
                   9415: }
                   9416: 
1.598     www      9417: 
                   9418: sub ungraded {
                   9419:     my ($request)=@_;
                   9420:     &submit_options($request);
                   9421: }
                   9422: 
1.599     www      9423: sub submit_options_sequence {
1.608     www      9424:     my ($request,$symb) = @_;
1.599     www      9425:     if (!$symb) {return '';}
1.600     www      9426:     &commonJSfunctions($request);
                   9427:     my $result;
1.599     www      9428: 
1.600     www      9429:     $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
1.618     www      9430:         '<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
1.632     www      9431:     $result.=&selectfield(0).
1.601     www      9432:             '<input type="hidden" name="command" value="pickStudentPage" />
1.600     www      9433:             <div>
                   9434:               <input type="submit" value="'.&mt('Next').' &rarr;" />
                   9435:             </div>
                   9436:         </div>
                   9437:   </form>';
                   9438:     return $result;
                   9439: }
                   9440: 
                   9441: sub submit_options_table {
1.608     www      9442:     my ($request,$symb) = @_;
1.600     www      9443:     if (!$symb) {return '';}
1.599     www      9444:     &commonJSfunctions($request);
                   9445:     my $result;
                   9446: 
                   9447:     $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
1.618     www      9448:         '<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
1.599     www      9449: 
1.632     www      9450:     $result.=&selectfield(0).
1.601     www      9451:             '<input type="hidden" name="command" value="viewgrades" />
1.599     www      9452:             <div>
                   9453:               <input type="submit" value="'.&mt('Next').' &rarr;" />
                   9454:             </div>
                   9455:         </div>
                   9456:   </form>';
                   9457:     return $result;
                   9458: }
1.443     banghart 9459: 
1.621     www      9460: sub submit_options_download {
                   9461:     my ($request,$symb) = @_;
                   9462:     if (!$symb) {return '';}
                   9463: 
                   9464:     &commonJSfunctions($request);
                   9465: 
                   9466:     my $result='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
                   9467:         '<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
                   9468:     $result.='
                   9469: <h2>
                   9470:   '.&mt('Select Students for Which to Download Submissions').'
                   9471: </h2>'.&selectfield(1).'
                   9472:                 <input type="hidden" name="command" value="downloadfileslink" /> 
                   9473:               <input type="submit" value="'.&mt('Next').' &rarr;" />
                   9474:             </div>
                   9475:           </div>
1.600     www      9476: 
                   9477: 
1.621     www      9478:   </form>';
                   9479:     return $result;
                   9480: }
                   9481: 
1.443     banghart 9482: #--- Displays the submissions first page -------
                   9483: sub submit_options {
1.608     www      9484:     my ($request,$symb) = @_;
1.72      ng       9485:     if (!$symb) {return '';}
                   9486: 
1.118     ng       9487:     &commonJSfunctions($request);
1.473     albertel 9488:     my $result;
1.533     bisitz   9489: 
1.72      ng       9490:     $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
1.618     www      9491: 	'<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
1.632     www      9492:     $result.=&selectfield(1).'
1.601     www      9493:                 <input type="hidden" name="command" value="submission" /> 
                   9494: 	      <input type="submit" value="'.&mt('Next').' &rarr;" />
                   9495:             </div>
                   9496:           </div>
                   9497: 
                   9498: 
                   9499:   </form>';
                   9500:     return $result;
                   9501: }
1.533     bisitz   9502: 
1.601     www      9503: sub selectfield {
                   9504:    my ($full)=@_;
1.635     raeburn  9505:    my %options = 
                   9506:           (&Apache::lonlocal::texthash(
                   9507:              'yes'       => 'with submissions',
                   9508:              'queued'    => 'in grading queue',
                   9509:              'graded'    => 'with ungraded submissions',
                   9510:              'incorrect' => 'with incorrect submissions',
                   9511:              'all'       => 'with any status'),
                   9512:              'select_form_order' => ['yes','queued','graded','incorrect','all']);
1.601     www      9513:    my $result='<div class="LC_columnSection">
1.537     harmsja  9514:   
1.533     bisitz   9515:     <fieldset>
                   9516:       <legend>
                   9517:        '.&mt('Sections').'
                   9518:       </legend>
1.601     www      9519:       '.&Apache::lonstatistics::SectionSelect('section','multiple',5).'
1.533     bisitz   9520:     </fieldset>
1.537     harmsja  9521:   
1.533     bisitz   9522:     <fieldset>
                   9523:       <legend>
                   9524:         '.&mt('Groups').'
                   9525:       </legend>
                   9526:       '.&Apache::lonstatistics::GroupSelect('group','multiple',5).'
                   9527:     </fieldset>
1.537     harmsja  9528:   
1.533     bisitz   9529:     <fieldset>
                   9530:       <legend>
                   9531:         '.&mt('Access Status').'
                   9532:       </legend>
1.601     www      9533:       '.&Apache::lonhtmlcommon::StatusOptions(undef,undef,5,undef,'mult').'
                   9534:     </fieldset>';
                   9535:     if ($full) {
                   9536:        $result.='
1.533     bisitz   9537:     <fieldset>
                   9538:       <legend>
                   9539:         '.&mt('Submission Status').'
1.601     www      9540:       </legend>'.
1.635     raeburn  9541:        &Apache::loncommon::select_form('all','submitonly',\%options).
1.601     www      9542:    '</fieldset>';
                   9543:     }
                   9544:     $result.='</div><br />';
1.44      ng       9545:     return $result;
1.2       albertel 9546: }
                   9547: 
1.285     albertel 9548: sub reset_perm {
                   9549:     undef(%perm);
                   9550: }
                   9551: 
                   9552: sub init_perm {
                   9553:     &reset_perm();
1.300     albertel 9554:     foreach my $test_perm ('vgr','mgr','opa') {
                   9555: 
                   9556: 	my $scope = $env{'request.course.id'};
                   9557: 	if (!($perm{$test_perm}=&Apache::lonnet::allowed($test_perm,$scope))) {
                   9558: 
                   9559: 	    $scope .= '/'.$env{'request.course.sec'};
                   9560: 	    if ( $perm{$test_perm}=
                   9561: 		 &Apache::lonnet::allowed($test_perm,$scope)) {
                   9562: 		$perm{$test_perm.'_section'}=$env{'request.course.sec'};
                   9563: 	    } else {
                   9564: 		delete($perm{$test_perm});
                   9565: 	    }
1.285     albertel 9566: 	}
                   9567:     }
                   9568: }
                   9569: 
1.674     raeburn  9570: sub init_old_essays {
                   9571:     my ($symb,$apath,$adom,$aname) = @_;
                   9572:     if ($symb ne '') {
                   9573:         my %essays = &Apache::lonnet::dump('nohist_essay_'.$apath,$adom,$aname);
                   9574:         if (keys(%essays) > 0) {
                   9575:             $old_essays{$symb} = \%essays;
                   9576:         }
                   9577:     }
                   9578:     return;
                   9579: }
                   9580: 
                   9581: sub reset_old_essays {
                   9582:     undef(%old_essays);
                   9583: }
                   9584: 
1.400     www      9585: sub gather_clicker_ids {
1.408     albertel 9586:     my %clicker_ids;
1.400     www      9587: 
                   9588:     my $classlist = &Apache::loncoursedata::get_classlist();
                   9589: 
                   9590:     # Set up a couple variables.
1.407     albertel 9591:     my $username_idx = &Apache::loncoursedata::CL_SNAME();
                   9592:     my $domain_idx   = &Apache::loncoursedata::CL_SDOM();
1.438     www      9593:     my $status_idx   = &Apache::loncoursedata::CL_STATUS();
1.400     www      9594: 
1.407     albertel 9595:     foreach my $student (keys(%$classlist)) {
1.438     www      9596:         if ($classlist->{$student}->[$status_idx] ne 'Active') { next; }
1.407     albertel 9597:         my $username = $classlist->{$student}->[$username_idx];
                   9598:         my $domain   = $classlist->{$student}->[$domain_idx];
1.400     www      9599:         my $clickers =
1.408     albertel 9600: 	    (&Apache::lonnet::userenvironment($domain,$username,'clickers'))[1];
1.400     www      9601:         foreach my $id (split(/\,/,$clickers)) {
1.414     www      9602:             $id=~s/^[\#0]+//;
1.421     www      9603:             $id=~s/[\-\:]//g;
1.407     albertel 9604:             if (exists($clicker_ids{$id})) {
1.408     albertel 9605: 		$clicker_ids{$id}.=','.$username.':'.$domain;
1.400     www      9606:             } else {
1.408     albertel 9607: 		$clicker_ids{$id}=$username.':'.$domain;
1.400     www      9608:             }
                   9609:         }
                   9610:     }
1.407     albertel 9611:     return %clicker_ids;
1.400     www      9612: }
                   9613: 
1.402     www      9614: sub gather_adv_clicker_ids {
1.408     albertel 9615:     my %clicker_ids;
1.402     www      9616:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
                   9617:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   9618:     my %coursepersonnel=&Apache::lonnet::get_course_adv_roles($cdom.'/'.$cnum);
1.409     albertel 9619:     foreach my $element (sort(keys(%coursepersonnel))) {
1.402     www      9620:         foreach my $person (split(/\,/,$coursepersonnel{$element})) {
                   9621:             my ($puname,$pudom)=split(/\:/,$person);
                   9622:             my $clickers =
1.408     albertel 9623: 		(&Apache::lonnet::userenvironment($pudom,$puname,'clickers'))[1];
1.405     www      9624:             foreach my $id (split(/\,/,$clickers)) {
1.414     www      9625: 		$id=~s/^[\#0]+//;
1.421     www      9626:                 $id=~s/[\-\:]//g;
1.408     albertel 9627: 		if (exists($clicker_ids{$id})) {
                   9628: 		    $clicker_ids{$id}.=','.$puname.':'.$pudom;
                   9629: 		} else {
                   9630: 		    $clicker_ids{$id}=$puname.':'.$pudom;
                   9631: 		}
1.405     www      9632:             }
1.402     www      9633:         }
                   9634:     }
1.407     albertel 9635:     return %clicker_ids;
1.402     www      9636: }
                   9637: 
1.413     www      9638: sub clicker_grading_parameters {
                   9639:     return ('gradingmechanism' => 'scalar',
                   9640:             'upfiletype' => 'scalar',
                   9641:             'specificid' => 'scalar',
                   9642:             'pcorrect' => 'scalar',
                   9643:             'pincorrect' => 'scalar');
                   9644: }
                   9645: 
1.400     www      9646: sub process_clicker {
1.608     www      9647:     my ($r,$symb)=@_;
1.400     www      9648:     if (!$symb) {return '';}
                   9649:     my $result=&checkforfile_js();
1.632     www      9650:     $result.=&Apache::loncommon::start_data_table().
                   9651:              &Apache::loncommon::start_data_table_header_row().
                   9652:              '<th>'.&mt('Specify a file containing clicker information and set grading options.').'</th>'.
                   9653:              &Apache::loncommon::end_data_table_header_row().
                   9654:              &Apache::loncommon::start_data_table_row()."<td>\n";
1.413     www      9655: # Attempt to restore parameters from last session, set defaults if not present
                   9656:     my %Saveable_Parameters=&clicker_grading_parameters();
                   9657:     &Apache::loncommon::restore_course_settings('grades_clicker',
                   9658:                                                  \%Saveable_Parameters);
                   9659:     if (!$env{'form.pcorrect'}) { $env{'form.pcorrect'}=100; }
                   9660:     if (!$env{'form.pincorrect'}) { $env{'form.pincorrect'}=100; }
                   9661:     if (!$env{'form.gradingmechanism'}) { $env{'form.gradingmechanism'}='attendance'; }
                   9662:     if (!$env{'form.upfiletype'}) { $env{'form.upfiletype'}='iclicker'; }
                   9663: 
                   9664:     my %checked;
1.521     www      9665:     foreach my $gradingmechanism ('attendance','personnel','specific','given') {
1.413     www      9666:        if ($env{'form.gradingmechanism'} eq $gradingmechanism) {
1.569     bisitz   9667:           $checked{$gradingmechanism}=' checked="checked"';
1.413     www      9668:        }
                   9669:     }
                   9670: 
1.632     www      9671:     my $upload=&mt("Evaluate File");
1.400     www      9672:     my $type=&mt("Type");
1.402     www      9673:     my $attendance=&mt("Award points just for participation");
                   9674:     my $personnel=&mt("Correctness determined from response by course personnel");
1.414     www      9675:     my $specific=&mt("Correctness determined from response with clicker ID(s)"); 
1.521     www      9676:     my $given=&mt("Correctness determined from given list of answers").' '.
                   9677:               '<font size="-2"><tt>('.&mt("Provide comma-separated list. Use '*' for any answer correct, '-' for skip").')</tt></font>';
1.402     www      9678:     my $pcorrect=&mt("Percentage points for correct solution");
                   9679:     my $pincorrect=&mt("Percentage points for incorrect solution");
1.413     www      9680:     my $selectform=&Apache::loncommon::select_form($env{'form.upfiletype'},'upfiletype',
1.635     raeburn  9681: 						   {'iclicker' => 'i>clicker',
1.666     www      9682:                                                     'interwrite' => 'interwrite PRS',
                   9683:                                                     'turning' => 'Turning Technologies'});
1.418     albertel 9684:     $symb = &Apache::lonenc::check_encrypt($symb);
1.597     wenzelju 9685:     $result.= &Apache::lonhtmlcommon::scripttag(<<ENDUPFORM);
1.402     www      9686: function sanitycheck() {
                   9687: // Accept only integer percentages
                   9688:    document.forms.gradesupload.pcorrect.value=Math.round(document.forms.gradesupload.pcorrect.value);
                   9689:    document.forms.gradesupload.pincorrect.value=Math.round(document.forms.gradesupload.pincorrect.value);
                   9690: // Find out grading choice
                   9691:    for (i=0; i<document.forms.gradesupload.gradingmechanism.length; i++) {
                   9692:       if (document.forms.gradesupload.gradingmechanism[i].checked) {
                   9693:          gradingchoice=document.forms.gradesupload.gradingmechanism[i].value;
                   9694:       }
                   9695:    }
                   9696: // By default, new choice equals user selection
                   9697:    newgradingchoice=gradingchoice;
                   9698: // Not good to give more points for false answers than correct ones
                   9699:    if (Math.round(document.forms.gradesupload.pcorrect.value)<Math.round(document.forms.gradesupload.pincorrect.value)) {
                   9700:       document.forms.gradesupload.pcorrect.value=document.forms.gradesupload.pincorrect.value;
                   9701:    }
                   9702: // If new choice is attendance only, and old choice was correctness-based, restore defaults
                   9703:    if ((gradingchoice=='attendance') && (document.forms.gradesupload.waschecked.value!='attendance')) {
                   9704:       document.forms.gradesupload.pcorrect.value=100;
                   9705:       document.forms.gradesupload.pincorrect.value=100;
                   9706:    }
                   9707: // If the values are different, cannot be attendance only
                   9708:    if ((Math.round(document.forms.gradesupload.pcorrect.value)!=Math.round(document.forms.gradesupload.pincorrect.value)) &&
                   9709:        (gradingchoice=='attendance')) {
                   9710:        newgradingchoice='personnel';
                   9711:    }
                   9712: // Change grading choice to new one
                   9713:    for (i=0; i<document.forms.gradesupload.gradingmechanism.length; i++) {
                   9714:       if (document.forms.gradesupload.gradingmechanism[i].value==newgradingchoice) {
                   9715:          document.forms.gradesupload.gradingmechanism[i].checked=true;
                   9716:       } else {
                   9717:          document.forms.gradesupload.gradingmechanism[i].checked=false;
                   9718:       }
                   9719:    }
                   9720: // Remember the old state
                   9721:    document.forms.gradesupload.waschecked.value=newgradingchoice;
                   9722: }
1.597     wenzelju 9723: ENDUPFORM
                   9724:     $result.= <<ENDUPFORM;
1.400     www      9725: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
                   9726: <input type="hidden" name="symb" value="$symb" />
                   9727: <input type="hidden" name="command" value="processclickerfile" />
                   9728: <input type="file" name="upfile" size="50" />
                   9729: <br /><label>$type: $selectform</label>
1.632     www      9730: ENDUPFORM
                   9731:     $result.='</td>'.&Apache::loncommon::end_data_table_row().
                   9732:                      &Apache::loncommon::start_data_table_row().'<td>'.(<<ENDGRADINGFORM);
                   9733:       <label><input type="radio" name="gradingmechanism" value="attendance"$checked{'attendance'} onclick="sanitycheck()" />$attendance </label>
1.589     bisitz   9734: <br /><label><input type="radio" name="gradingmechanism" value="personnel"$checked{'personnel'} onclick="sanitycheck()" />$personnel</label>
                   9735: <br /><label><input type="radio" name="gradingmechanism" value="specific"$checked{'specific'} onclick="sanitycheck()" />$specific </label>
1.414     www      9736: <input type="text" name="specificid" value="$env{'form.specificid'}" size="20" />
1.589     bisitz   9737: <br /><label><input type="radio" name="gradingmechanism" value="given"$checked{'given'} onclick="sanitycheck()" />$given </label>
1.521     www      9738: <br />&nbsp;&nbsp;&nbsp;
                   9739: <input type="text" name="givenanswer" size="50" />
1.413     www      9740: <input type="hidden" name="waschecked" value="$env{'form.gradingmechanism'}" />
1.632     www      9741: ENDGRADINGFORM
                   9742:          $result.='</td>'.&Apache::loncommon::end_data_table_row().
                   9743:                      &Apache::loncommon::start_data_table_row().'<td>'.(<<ENDPERCFORM);
                   9744:       <label>$pcorrect: <input type="text" name="pcorrect" size="4" value="$env{'form.pcorrect'}" onchange="sanitycheck()" /></label>
1.589     bisitz   9745: <br /><label>$pincorrect: <input type="text" name="pincorrect" size="4" value="$env{'form.pincorrect'}" onchange="sanitycheck()" /></label>
                   9746: <br /><input type="button" onclick="javascript:checkUpload(this.form);" value="$upload" />
1.597     wenzelju 9747: </form>'
1.632     www      9748: ENDPERCFORM
                   9749:     $result.='</td>'.
                   9750:              &Apache::loncommon::end_data_table_row().
                   9751:              &Apache::loncommon::end_data_table();
1.400     www      9752:     return $result;
                   9753: }
                   9754: 
                   9755: sub process_clicker_file {
1.608     www      9756:     my ($r,$symb)=@_;
1.400     www      9757:     if (!$symb) {return '';}
1.413     www      9758: 
                   9759:     my %Saveable_Parameters=&clicker_grading_parameters();
                   9760:     &Apache::loncommon::store_course_settings('grades_clicker',
                   9761:                                               \%Saveable_Parameters);
1.598     www      9762:     my $result='';
1.404     www      9763:     if (($env{'form.gradingmechanism'} eq 'specific') && ($env{'form.specificid'}!~/\w/)) {
1.408     albertel 9764: 	$result.='<span class="LC_error">'.&mt('You need to specify a clicker ID for the correct answer').'</span>';
1.614     www      9765: 	return $result;
1.404     www      9766:     }
1.522     www      9767:     if (($env{'form.gradingmechanism'} eq 'given') && ($env{'form.givenanswer'}!~/\S/)) {
1.521     www      9768:         $result.='<span class="LC_error">'.&mt('You need to specify the correct answer').'</span>';
1.614     www      9769:         return $result;
1.521     www      9770:     }
1.522     www      9771:     my $foundgiven=0;
1.521     www      9772:     if ($env{'form.gradingmechanism'} eq 'given') {
                   9773:         $env{'form.givenanswer'}=~s/^\s*//gs;
                   9774:         $env{'form.givenanswer'}=~s/\s*$//gs;
1.644     www      9775:         $env{'form.givenanswer'}=~s/[^a-zA-Z0-9\.\*\-\+]+/\,/g;
1.521     www      9776:         $env{'form.givenanswer'}=uc($env{'form.givenanswer'});
1.522     www      9777:         my @answers=split(/\,/,$env{'form.givenanswer'});
                   9778:         $foundgiven=$#answers+1;
1.521     www      9779:     }
1.407     albertel 9780:     my %clicker_ids=&gather_clicker_ids();
1.408     albertel 9781:     my %correct_ids;
1.404     www      9782:     if ($env{'form.gradingmechanism'} eq 'personnel') {
1.408     albertel 9783: 	%correct_ids=&gather_adv_clicker_ids();
1.404     www      9784:     }
                   9785:     if ($env{'form.gradingmechanism'} eq 'specific') {
1.414     www      9786: 	foreach my $correct_id (split(/[\s\,]/,$env{'form.specificid'})) {;
                   9787: 	   $correct_id=~tr/a-z/A-Z/;
                   9788: 	   $correct_id=~s/\s//gs;
                   9789: 	   $correct_id=~s/^[\#0]+//;
1.421     www      9790:            $correct_id=~s/[\-\:]//g;
1.414     www      9791:            if ($correct_id) {
                   9792: 	      $correct_ids{$correct_id}='specified';
                   9793:            }
                   9794:         }
1.400     www      9795:     }
1.404     www      9796:     if ($env{'form.gradingmechanism'} eq 'attendance') {
1.408     albertel 9797: 	$result.=&mt('Score based on attendance only');
1.521     www      9798:     } elsif ($env{'form.gradingmechanism'} eq 'given') {
1.522     www      9799:         $result.=&mt('Score based on [_1] ([_2] answers)','<tt>'.$env{'form.givenanswer'}.'</tt>',$foundgiven);
1.404     www      9800:     } else {
1.408     albertel 9801: 	my $number=0;
1.411     www      9802: 	$result.='<p><b>'.&mt('Correctness determined by the following IDs').'</b>';
1.408     albertel 9803: 	foreach my $id (sort(keys(%correct_ids))) {
1.411     www      9804: 	    $result.='<br /><tt>'.$id.'</tt> - ';
1.408     albertel 9805: 	    if ($correct_ids{$id} eq 'specified') {
                   9806: 		$result.=&mt('specified');
                   9807: 	    } else {
                   9808: 		my ($uname,$udom)=split(/\:/,$correct_ids{$id});
                   9809: 		$result.=&Apache::loncommon::plainname($uname,$udom);
                   9810: 	    }
                   9811: 	    $number++;
                   9812: 	}
1.411     www      9813:         $result.="</p>\n";
1.710     bisitz   9814:         if ($number==0) {
                   9815:             $result .=
                   9816:                  &Apache::lonhtmlcommon::confirm_success(
                   9817:                      &mt('No IDs found to determine correct answer'),1);
                   9818:             return $result;
                   9819:         }
1.404     www      9820:     }
1.405     www      9821:     if (length($env{'form.upfile'}) < 2) {
1.710     bisitz   9822:         $result .=
                   9823:             &Apache::lonhtmlcommon::confirm_success(
                   9824:                 &mt('The file: [_1] you attempted to upload contained no information. Please check that you entered the correct filename.',
                   9825:                         '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>'),1);
1.614     www      9826:         return $result;
1.405     www      9827:     }
1.410     www      9828: 
                   9829: # Were able to get all the info needed, now analyze the file
                   9830: 
1.411     www      9831:     $result.=&Apache::loncommon::studentbrowser_javascript();
1.418     albertel 9832:     $symb = &Apache::lonenc::check_encrypt($symb);
1.632     www      9833:     $result.=&Apache::loncommon::start_data_table().
                   9834:              &Apache::loncommon::start_data_table_header_row().
                   9835:              '<th>'.&mt('Evaluate clicker file').'</th>'.
                   9836:              &Apache::loncommon::end_data_table_header_row().
                   9837:              &Apache::loncommon::start_data_table_row().(<<ENDHEADER);
                   9838: <td>
1.410     www      9839: <form method="post" action="/adm/grades" name="clickeranalysis">
                   9840: <input type="hidden" name="symb" value="$symb" />
                   9841: <input type="hidden" name="command" value="assignclickergrades" />
1.411     www      9842: <input type="hidden" name="gradingmechanism" value="$env{'form.gradingmechanism'}" />
                   9843: <input type="hidden" name="pcorrect" value="$env{'form.pcorrect'}" />
                   9844: <input type="hidden" name="pincorrect" value="$env{'form.pincorrect'}" />
1.410     www      9845: ENDHEADER
1.522     www      9846:     if ($env{'form.gradingmechanism'} eq 'given') {
                   9847:        $result.='<input type="hidden" name="correct:given" value="'.$env{'form.givenanswer'}.'" />';
                   9848:     } 
1.408     albertel 9849:     my %responses;
                   9850:     my @questiontitles;
1.405     www      9851:     my $errormsg='';
                   9852:     my $number=0;
                   9853:     if ($env{'form.upfiletype'} eq 'iclicker') {
1.408     albertel 9854: 	($errormsg,$number)=&iclicker_eval(\@questiontitles,\%responses);
1.406     www      9855:     }
1.419     www      9856:     if ($env{'form.upfiletype'} eq 'interwrite') {
                   9857:         ($errormsg,$number)=&interwrite_eval(\@questiontitles,\%responses);
                   9858:     }
1.666     www      9859:     if ($env{'form.upfiletype'} eq 'turning') {
                   9860:         ($errormsg,$number)=&turning_eval(\@questiontitles,\%responses);
                   9861:     }
1.411     www      9862:     $result.='<br />'.&mt('Found [_1] question(s)',$number).'<br />'.
                   9863:              '<input type="hidden" name="number" value="'.$number.'" />'.
                   9864:              &mt('Awarding [_1] percent for correct and [_2] percent for incorrect responses',
                   9865:                  $env{'form.pcorrect'},$env{'form.pincorrect'}).
                   9866:              '<br />';
1.522     www      9867:     if (($env{'form.gradingmechanism'} eq 'given') && ($number!=$foundgiven)) {
                   9868:        $result.='<span class="LC_error">'.&mt('Number of given answers does not agree with number of questions in file.').'</span>';
1.614     www      9869:        return $result;
1.522     www      9870:     } 
1.414     www      9871: # Remember Question Titles
                   9872: # FIXME: Possibly need delimiter other than ":"
                   9873:     for (my $i=0;$i<$number;$i++) {
                   9874:         $result.='<input type="hidden" name="question:'.$i.'" value="'.
                   9875:                  &HTML::Entities::encode($questiontitles[$i],'"&<>').'" />';
                   9876:     }
1.411     www      9877:     my $correct_count=0;
                   9878:     my $student_count=0;
                   9879:     my $unknown_count=0;
1.414     www      9880: # Match answers with usernames
                   9881: # FIXME: Possibly need delimiter other than ":"
1.409     albertel 9882:     foreach my $id (keys(%responses)) {
1.410     www      9883:        if ($correct_ids{$id}) {
1.414     www      9884:           $result.="\n".'<input type="hidden" name="correct:'.$correct_count.':'.$correct_ids{$id}.'" value="'.$responses{$id}.'" />';
1.411     www      9885:           $correct_count++;
1.410     www      9886:        } elsif ($clicker_ids{$id}) {
1.437     www      9887:           if ($clicker_ids{$id}=~/\,/) {
                   9888: # More than one user with the same clicker!
1.632     www      9889:              $result.="</td>".&Apache::loncommon::end_data_table_row().
                   9890:                            &Apache::loncommon::start_data_table_row()."<td>".
                   9891:                        &mt('Clicker registered more than once').": <tt>".$id."</tt><br />";
1.437     www      9892:              $result.="\n".'<input type="hidden" name="unknown:'.$id.'" value="'.$responses{$id}.'" />'.
                   9893:                            "<select name='multi".$id."'>";
                   9894:              foreach my $reguser (sort(split(/\,/,$clicker_ids{$id}))) {
                   9895:                  $result.="<option value='".$reguser."'>".&Apache::loncommon::plainname(split(/\:/,$reguser)).' ('.$reguser.')</option>';
                   9896:              }
                   9897:              $result.='</select>';
                   9898:              $unknown_count++;
                   9899:           } else {
                   9900: # Good: found one and only one user with the right clicker
                   9901:              $result.="\n".'<input type="hidden" name="student:'.$clicker_ids{$id}.'" value="'.$responses{$id}.'" />';
                   9902:              $student_count++;
                   9903:           }
1.410     www      9904:        } else {
1.632     www      9905:           $result.="</td>".&Apache::loncommon::end_data_table_row().
                   9906:                            &Apache::loncommon::start_data_table_row()."<td>".
                   9907:                     &mt('Unregistered Clicker')." <tt>".$id."</tt><br />";
1.411     www      9908:           $result.="\n".'<input type="hidden" name="unknown:'.$id.'" value="'.$responses{$id}.'" />'.
                   9909:                    "\n".&mt("Username").": <input type='text' name='uname".$id."' />&nbsp;".
                   9910:                    "\n".&mt("Domain").": ".
                   9911:                    &Apache::loncommon::select_dom_form($env{'course.'.$env{'request.course.id'}.'.domain'},'udom'.$id).'&nbsp;'.
1.643     www      9912:                    &Apache::loncommon::selectstudent_link('clickeranalysis','uname'.$id,'udom'.$id,0,$id);
1.411     www      9913:           $unknown_count++;
1.410     www      9914:        }
1.405     www      9915:     }
1.412     www      9916:     $result.='<hr />'.
                   9917:              &mt('Found [_1] registered and [_2] unregistered clickers.',$student_count,$unknown_count);
1.521     www      9918:     if (($env{'form.gradingmechanism'} ne 'attendance') && ($env{'form.gradingmechanism'} ne 'given')) {
1.412     www      9919:        if ($correct_count==0) {
1.696     bisitz   9920:           $errormsg.="Found no correct answers for grading!";
1.412     www      9921:        } elsif ($correct_count>1) {
1.414     www      9922:           $result.='<br /><span class="LC_warning">'.&mt("Found [_1] entries for grading!",$correct_count).'</span>';
1.412     www      9923:        }
                   9924:     }
1.428     www      9925:     if ($number<1) {
                   9926:        $errormsg.="Found no questions.";
                   9927:     }
1.412     www      9928:     if ($errormsg) {
                   9929:        $result.='<br /><span class="LC_error">'.&mt($errormsg).'</span>';
                   9930:     } else {
                   9931:        $result.='<br /><input type="submit" name="finalize" value="'.&mt('Finalize Grading').'" />';
                   9932:     }
1.632     www      9933:     $result.='</form></td>'.
                   9934:              &Apache::loncommon::end_data_table_row().
                   9935:              &Apache::loncommon::end_data_table();
1.614     www      9936:     return $result;
1.400     www      9937: }
                   9938: 
1.405     www      9939: sub iclicker_eval {
1.406     www      9940:     my ($questiontitles,$responses)=@_;
1.405     www      9941:     my $number=0;
                   9942:     my $errormsg='';
                   9943:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
1.410     www      9944:         my %components=&Apache::loncommon::record_sep($line);
                   9945:         my @entries=map {$components{$_}} (sort(keys(%components)));
1.408     albertel 9946: 	if ($entries[0] eq 'Question') {
                   9947: 	    for (my $i=3;$i<$#entries;$i+=6) {
                   9948: 		$$questiontitles[$number]=$entries[$i];
                   9949: 		$number++;
                   9950: 	    }
                   9951: 	}
                   9952: 	if ($entries[0]=~/^\#/) {
                   9953: 	    my $id=$entries[0];
                   9954: 	    my @idresponses;
                   9955: 	    $id=~s/^[\#0]+//;
                   9956: 	    for (my $i=0;$i<$number;$i++) {
                   9957: 		my $idx=3+$i*6;
1.644     www      9958:                 $entries[$idx]=~s/[^a-zA-Z0-9\.\*\-\+]+//g;
1.408     albertel 9959: 		push(@idresponses,$entries[$idx]);
                   9960: 	    }
                   9961: 	    $$responses{$id}=join(',',@idresponses);
                   9962: 	}
1.405     www      9963:     }
                   9964:     return ($errormsg,$number);
                   9965: }
                   9966: 
1.419     www      9967: sub interwrite_eval {
                   9968:     my ($questiontitles,$responses)=@_;
                   9969:     my $number=0;
                   9970:     my $errormsg='';
1.420     www      9971:     my $skipline=1;
                   9972:     my $questionnumber=0;
                   9973:     my %idresponses=();
1.419     www      9974:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
                   9975:         my %components=&Apache::loncommon::record_sep($line);
                   9976:         my @entries=map {$components{$_}} (sort(keys(%components)));
1.420     www      9977:         if ($entries[1] eq 'Time') { $skipline=0; next; }
                   9978:         if ($entries[1] eq 'Response') { $skipline=1; }
                   9979:         next if $skipline;
                   9980:         if ($entries[0]!=$questionnumber) {
                   9981:            $questionnumber=$entries[0];
                   9982:            $$questiontitles[$number]=&mt('Question [_1]',$questionnumber);
                   9983:            $number++;
1.419     www      9984:         }
1.420     www      9985:         my $id=$entries[4];
                   9986:         $id=~s/^[\#0]+//;
1.421     www      9987:         $id=~s/^v\d*\://i;
                   9988:         $id=~s/[\-\:]//g;
1.420     www      9989:         $idresponses{$id}[$number]=$entries[6];
                   9990:     }
1.524     raeburn  9991:     foreach my $id (keys(%idresponses)) {
1.420     www      9992:        $$responses{$id}=join(',',@{$idresponses{$id}});
                   9993:        $$responses{$id}=~s/^\s*\,//;
1.419     www      9994:     }
                   9995:     return ($errormsg,$number);
                   9996: }
                   9997: 
1.666     www      9998: sub turning_eval {
                   9999:     my ($questiontitles,$responses)=@_;
                   10000:     my $number=0;
                   10001:     my $errormsg='';
                   10002:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
                   10003:         my %components=&Apache::loncommon::record_sep($line);
                   10004:         my @entries=map {$components{$_}} (sort(keys(%components)));
                   10005:         if ($#entries>$number) { $number=$#entries; }
                   10006:         my $id=$entries[0];
                   10007:         my @idresponses;
                   10008:         $id=~s/^[\#0]+//;
                   10009:         unless ($id) { next; }
                   10010:         for (my $idx=1;$idx<=$#entries;$idx++) {
                   10011:             $entries[$idx]=~s/\,/\;/g;
                   10012:             $entries[$idx]=~s/[^a-zA-Z0-9\.\*\-\+\;]+//g;
                   10013:             push(@idresponses,$entries[$idx]);
                   10014:         }
                   10015:         $$responses{$id}=join(',',@idresponses);
                   10016:     }
                   10017:     for (my $i=1; $i<=$number; $i++) {
                   10018:         $$questiontitles[$i]=&mt('Question [_1]',$i);
                   10019:     }
                   10020:     return ($errormsg,$number);
                   10021: }
                   10022: 
                   10023: 
1.414     www      10024: sub assign_clicker_grades {
1.608     www      10025:     my ($r,$symb)=@_;
1.414     www      10026:     if (!$symb) {return '';}
1.416     www      10027: # See which part we are saving to
1.582     raeburn  10028:     my $res_error;
                   10029:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
                   10030:     if ($res_error) {
                   10031:         return &navmap_errormsg();
                   10032:     }
1.416     www      10033: # FIXME: This should probably look for the first handgradeable part
                   10034:     my $part=$$partlist[0];
                   10035: # Start screen output
1.632     www      10036:     my $result=&Apache::loncommon::start_data_table().
                   10037:              &Apache::loncommon::start_data_table_header_row().
                   10038:              '<th>'.&mt('Assigning grades based on clicker file').'</th>'.
                   10039:              &Apache::loncommon::end_data_table_header_row().
                   10040:              &Apache::loncommon::start_data_table_row().'<td>';
1.414     www      10041: # Get correct result
                   10042: # FIXME: Possibly need delimiter other than ":"
                   10043:     my @correct=();
1.415     www      10044:     my $gradingmechanism=$env{'form.gradingmechanism'};
                   10045:     my $number=$env{'form.number'};
                   10046:     if ($gradingmechanism ne 'attendance') {
1.414     www      10047:        foreach my $key (keys(%env)) {
                   10048:           if ($key=~/^form\.correct\:/) {
                   10049:              my @input=split(/\,/,$env{$key});
                   10050:              for (my $i=0;$i<=$#input;$i++) {
                   10051:                  if (($correct[$i]) && ($input[$i]) &&
                   10052:                      ($correct[$i] ne $input[$i])) {
                   10053:                     $result.='<br /><span class="LC_warning">'.
                   10054:                              &mt('More than one correct result given for question "[_1]": [_2] versus [_3].',
                   10055:                                  $env{'form.question:'.$i},$correct[$i],$input[$i]).'</span>';
1.644     www      10056:                  } elsif (($input[$i]) || ($input[$i] eq '0')) {
1.414     www      10057:                     $correct[$i]=$input[$i];
                   10058:                  }
                   10059:              }
                   10060:           }
                   10061:        }
1.415     www      10062:        for (my $i=0;$i<$number;$i++) {
1.644     www      10063:           if ((!$correct[$i]) && ($correct[$i] ne '0')) {
1.414     www      10064:              $result.='<br /><span class="LC_error">'.
                   10065:                       &mt('No correct result given for question "[_1]"!',
                   10066:                           $env{'form.question:'.$i}).'</span>';
                   10067:           }
                   10068:        }
1.644     www      10069:        $result.='<br />'.&mt("Correct answer: [_1]",join(', ',map { ((($_) || ($_ eq '0'))?$_:'-') } @correct));
1.414     www      10070:     }
                   10071: # Start grading
1.415     www      10072:     my $pcorrect=$env{'form.pcorrect'};
                   10073:     my $pincorrect=$env{'form.pincorrect'};
1.416     www      10074:     my $storecount=0;
1.632     www      10075:     my %users=();
1.415     www      10076:     foreach my $key (keys(%env)) {
1.420     www      10077:        my $user='';
1.415     www      10078:        if ($key=~/^form\.student\:(.*)$/) {
1.420     www      10079:           $user=$1;
                   10080:        }
                   10081:        if ($key=~/^form\.unknown\:(.*)$/) {
                   10082:           my $id=$1;
                   10083:           if (($env{'form.uname'.$id}) && ($env{'form.udom'.$id})) {
                   10084:              $user=$env{'form.uname'.$id}.':'.$env{'form.udom'.$id};
1.437     www      10085:           } elsif ($env{'form.multi'.$id}) {
                   10086:              $user=$env{'form.multi'.$id};
1.420     www      10087:           }
                   10088:        }
1.632     www      10089:        if ($user) {
                   10090:           if ($users{$user}) {
                   10091:              $result.='<br /><span class="LC_warning">'.
1.696     bisitz   10092:                       &mt('More than one entry found for [_1]!','<tt>'.$user.'</tt>').
1.632     www      10093:                       '</span><br />';
                   10094:           }
                   10095:           $users{$user}=1; 
1.415     www      10096:           my @answer=split(/\,/,$env{$key});
                   10097:           my $sum=0;
1.522     www      10098:           my $realnumber=$number;
1.415     www      10099:           for (my $i=0;$i<$number;$i++) {
1.576     www      10100:              if  ($correct[$i] eq '-') {
                   10101:                 $realnumber--;
1.644     www      10102:              } elsif (($answer[$i]) || ($answer[$i]=~/^[0\.]+$/))  {
1.415     www      10103:                 if ($gradingmechanism eq 'attendance') {
                   10104:                    $sum+=$pcorrect;
1.576     www      10105:                 } elsif ($correct[$i] eq '*') {
1.522     www      10106:                    $sum+=$pcorrect;
1.415     www      10107:                 } else {
1.644     www      10108: # We actually grade if correct or not
                   10109:                    my $increment=$pincorrect;
                   10110: # Special case: numerical answer "0"
                   10111:                    if ($correct[$i] eq '0') {
                   10112:                       if ($answer[$i]=~/^[0\.]+$/) {
                   10113:                          $increment=$pcorrect;
                   10114:                       }
                   10115: # General numerical answer, both evaluate to something non-zero
                   10116:                    } elsif ((1.0*$correct[$i]!=0) && (1.0*$answer[$i]!=0)) {
                   10117:                       if (1.0*$correct[$i]==1.0*$answer[$i]) {
                   10118:                          $increment=$pcorrect;
                   10119:                       }
                   10120: # Must be just alphanumeric
                   10121:                    } elsif ($answer[$i] eq $correct[$i]) {
                   10122:                       $increment=$pcorrect;
1.415     www      10123:                    }
1.644     www      10124:                    $sum+=$increment;
1.415     www      10125:                 }
                   10126:              }
                   10127:           }
1.522     www      10128:           my $ave=$sum/(100*$realnumber);
1.416     www      10129: # Store
                   10130:           my ($username,$domain)=split(/\:/,$user);
                   10131:           my %grades=();
                   10132:           $grades{"resource.$part.solved"}='correct_by_override';
                   10133:           $grades{"resource.$part.awarded"}=$ave;
                   10134:           $grades{"resource.regrader"}="$env{'user.name'}:$env{'user.domain'}";
                   10135:           my $returncode=&Apache::lonnet::cstore(\%grades,$symb,
                   10136:                                                  $env{'request.course.id'},
                   10137:                                                  $domain,$username);
                   10138:           if ($returncode ne 'ok') {
                   10139:              $result.="<br /><span class=\"LC_error\">Failed to save student $username:$domain. Message when trying to save was ($returncode)</span>";
                   10140:           } else {
                   10141:              $storecount++;
                   10142:           }
1.415     www      10143:        }
                   10144:     }
                   10145: # We are done
1.549     hauer    10146:     $result.='<br />'.&mt('Successfully stored grades for [quant,_1,student].',$storecount).
1.632     www      10147:              '</td>'.
                   10148:              &Apache::loncommon::end_data_table_row().
                   10149:              &Apache::loncommon::end_data_table();
1.614     www      10150:     return $result;
1.414     www      10151: }
                   10152: 
1.582     raeburn  10153: sub navmap_errormsg {
                   10154:     return '<div class="LC_error">'.
                   10155:            &mt('An error occurred retrieving information about resources in the course.').'<br />'.
1.595     raeburn  10156:            &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  10157:            '</div>';
                   10158: }
1.607     droeschl 10159: 
1.609     www      10160: sub startpage {
1.671     raeburn  10161:     my ($r,$symb,$crumbs,$onlyfolderflag,$nodisplayflag,$stuvcurrent,$stuvdisp,$nomenu,$js) = @_;
                   10162:     if ($nomenu) {
                   10163:         $r->print(&Apache::loncommon::start_page("Student's Version",$js,{'only_body' => '1'}));
                   10164:     } else {
                   10165:         unshift(@$crumbs,{href=>&href_symb_cmd($symb,'gradingmenu'),text=>"Grading"});
                   10166:         $r->print(&Apache::loncommon::start_page('Grading',$js,
                   10167:                                                  {'bread_crumbs' => $crumbs}));
                   10168:         &Apache::lonquickgrades::startGradeScreen($r,($env{'form.symb'}?'probgrading':'grading'));
                   10169:     }
1.613     www      10170:     unless ($nodisplayflag) {
1.671     raeburn  10171:        $r->print(&Apache::lonhtmlcommon::resource_info_box($symb,$onlyfolderflag,$stuvcurrent,$stuvdisp));
1.613     www      10172:     }
1.607     droeschl 10173: }
1.582     raeburn  10174: 
1.622     www      10175: sub select_problem {
                   10176:     my ($r)=@_;
1.632     www      10177:     $r->print('<h3>'.&mt('Select the problem or one of the problems you want to grade').'</h3><form action="/adm/grades">');
1.622     www      10178:     $r->print(&Apache::lonstathelpers::problem_selector('.',undef,1));
                   10179:     $r->print('<input type="hidden" name="command" value="gradingmenu" />');
                   10180:     $r->print('<input type="submit" value="'.&mt('Next').' &rarr;" /></form>');
                   10181: }
                   10182: 
1.1       albertel 10183: sub handler {
1.41      ng       10184:     my $request=$_[0];
1.434     albertel 10185:     &reset_caches();
1.646     raeburn  10186:     if ($request->header_only) {
                   10187:         &Apache::loncommon::content_type($request,'text/html');
                   10188:         $request->send_http_header;
                   10189:         return OK;
                   10190:     }
                   10191:     &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'});
                   10192: 
1.664     raeburn  10193: # see what command we need to execute
                   10194: 
                   10195:     my @commands=&Apache::loncommon::get_env_multiple('form.command');
                   10196:     my $command=$commands[0];
                   10197: 
1.646     raeburn  10198:     &init_perm();
                   10199:     if (!$env{'request.course.id'}) {
1.664     raeburn  10200:         unless ((&Apache::lonnet::allowed('usc',$env{'request.role.domain'})) &&
                   10201:                 ($command =~ /^scantronupload/)) {
                   10202:             # Not in a course.
                   10203:             $env{'user.error.msg'}="/adm/grades::vgr:0:0:Cannot display grades page outside course context";
                   10204:             return HTTP_NOT_ACCEPTABLE;
                   10205:         }
1.646     raeburn  10206:     } elsif (!%perm) {
                   10207:         $request->internal_redirect('/adm/quickgrades');
1.687     raeburn  10208:         return OK;
1.41      ng       10209:     }
1.646     raeburn  10210:     &Apache::loncommon::content_type($request,'text/html');
1.41      ng       10211:     $request->send_http_header;
1.646     raeburn  10212: 
1.160     albertel 10213:     if ($#commands > 0) {
                   10214: 	&Apache::lonnet::logthis("grades got multiple commands ".join(':',@commands));
                   10215:     }
1.608     www      10216: 
                   10217: # see what the symb is
                   10218: 
                   10219:     my $symb=$env{'form.symb'};
                   10220:     unless ($symb) {
                   10221:        (my $url=$env{'form.url'}) =~ s-^https*://($ENV{'SERVER_NAME'}|$ENV{'HTTP_HOST'})--;
                   10222:        $symb=&Apache::lonnet::symbread($url);
                   10223:     }
1.646     raeburn  10224:     &Apache::lonenc::check_decrypt(\$symb);
1.608     www      10225: 
1.513     foxr     10226:     $ssi_error = 0;
1.637     www      10227:     if (($symb eq '' || $command eq '') && ($env{'request.course.id'})) {
1.601     www      10228: #
1.637     www      10229: # Not called from a resource, but inside a course
1.601     www      10230: #    
1.622     www      10231:         &startpage($request,undef,[],1,1);
                   10232:         &select_problem($request);
1.41      ng       10233:     } else {
1.104     albertel 10234: 	if ($command eq 'submission' && $perm{'vgr'}) {
1.671     raeburn  10235:             my ($stuvcurrent,$stuvdisp,$versionform,$js);
                   10236:             if (($env{'form.student'} ne '') && ($env{'form.userdom'} ne '')) {
                   10237:                 ($stuvcurrent,$stuvdisp,$versionform,$js) =
                   10238:                     &choose_task_version_form($symb,$env{'form.student'},
                   10239:                                               $env{'form.userdom'});
                   10240:             }
                   10241:             &startpage($request,$symb,[{href=>"", text=>"Student Submissions"}],undef,undef,$stuvcurrent,$stuvdisp,undef,$js);
                   10242:             if ($versionform) {
                   10243:                 $request->print($versionform);
                   10244:             }
                   10245:             $request->print('<br clear="all" />');
1.611     www      10246: 	    ($env{'form.student'} eq '' ? &listStudents($request,$symb) : &submission($request,0,0,$symb));
1.671     raeburn  10247:         } elsif ($command eq 'versionsub' && $perm{'vgr'}) {
                   10248:             my ($stuvcurrent,$stuvdisp,$versionform,$js) =
                   10249:                 &choose_task_version_form($symb,$env{'form.student'},
                   10250:                                           $env{'form.userdom'},
                   10251:                                           $env{'form.inhibitmenu'});
                   10252:             &startpage($request,$symb,[{href=>"", text=>"Previous Student Version"}],undef,undef,$stuvcurrent,$stuvdisp,$env{'form.inhibitmenu'},$js);
                   10253:             if ($versionform) {
                   10254:                 $request->print($versionform);
                   10255:             }
                   10256:             $request->print('<br clear="all" />');
                   10257:             $request->print(&show_previous_task_version($request,$symb));
1.103     albertel 10258: 	} elsif ($command eq 'pickStudentPage' && $perm{'vgr'}) {
1.615     www      10259:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,'all_for_one'),text=>'Grade page/folder for one student'},
                   10260:                                        {href=>'',text=>'Select student'}],1,1);
1.608     www      10261: 	    &pickStudentPage($request,$symb);
1.103     albertel 10262: 	} elsif ($command eq 'displayPage' && $perm{'vgr'}) {
1.615     www      10263:             &startpage($request,$symb,
                   10264:                                       [{href=>&href_symb_cmd($symb,'all_for_one'),text=>'Grade page/folder for one student'},
                   10265:                                        {href=>'',text=>'Select student'},
                   10266:                                        {href=>'',text=>'Grade student'}],1,1);
1.608     www      10267: 	    &displayPage($request,$symb);
1.104     albertel 10268: 	} elsif ($command eq 'gradeByPage' && $perm{'mgr'}) {
1.616     www      10269:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,'all_for_one'),text=>'Grade page/folder for one student'},
                   10270:                                        {href=>'',text=>'Select student'},
                   10271:                                        {href=>'',text=>'Grade student'},
                   10272:                                        {href=>'',text=>'Store grades'}],1,1);
1.608     www      10273: 	    &updateGradeByPage($request,$symb);
1.104     albertel 10274: 	} elsif ($command eq 'processGroup' && $perm{'vgr'}) {
1.619     www      10275:             &startpage($request,$symb,[{href=>'',text=>'...'},
                   10276:                                        {href=>'',text=>'Modify grades'}]);
1.608     www      10277: 	    &processGroup($request,$symb);
1.104     albertel 10278: 	} elsif ($command eq 'gradingmenu' && $perm{'vgr'}) {
1.608     www      10279:             &startpage($request,$symb);
                   10280: 	    $request->print(&grading_menu($request,$symb));
1.598     www      10281: 	} elsif ($command eq 'individual' && $perm{'vgr'}) {
1.617     www      10282:             &startpage($request,$symb,[{href=>'',text=>'Select individual students to grade'}]);
1.608     www      10283: 	    $request->print(&submit_options($request,$symb));
1.598     www      10284:         } elsif ($command eq 'ungraded' && $perm{'vgr'}) {
1.617     www      10285:             &startpage($request,$symb,[{href=>'',text=>'Grade ungraded submissions'}]);
                   10286:             $request->print(&listStudents($request,$symb,'graded'));
1.598     www      10287:         } elsif ($command eq 'table' && $perm{'vgr'}) {
1.614     www      10288:             &startpage($request,$symb,[{href=>"", text=>"Grading table"}]);
1.611     www      10289:             $request->print(&submit_options_table($request,$symb));
1.598     www      10290:         } elsif ($command eq 'all_for_one' && $perm{'vgr'}) {
1.615     www      10291:             &startpage($request,$symb,[{href=>'',text=>'Grade page/folder for one student'}],1,1);
1.608     www      10292:             $request->print(&submit_options_sequence($request,$symb));
1.104     albertel 10293: 	} elsif ($command eq 'viewgrades' && $perm{'vgr'}) {
1.614     www      10294:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,"table"), text=>"Grading table"},{href=>'', text=>"Modify grades"}]);
1.608     www      10295: 	    $request->print(&viewgrades($request,$symb));
1.104     albertel 10296: 	} elsif ($command eq 'handgrade' && $perm{'mgr'}) {
1.620     www      10297:             &startpage($request,$symb,[{href=>'',text=>'...'},
                   10298:                                        {href=>'',text=>'Store grades'}]);
1.608     www      10299: 	    $request->print(&processHandGrade($request,$symb));
1.106     albertel 10300: 	} elsif ($command eq 'editgrades' && $perm{'mgr'}) {
1.614     www      10301:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,"table"), text=>"Grading table"},
                   10302:                                        {href=>&href_symb_cmd($symb,'viewgrades').'&group=all&section=all&Status=Active',
                   10303:                                                                              text=>"Modify grades"},
                   10304:                                        {href=>'', text=>"Store grades"}]);
1.608     www      10305: 	    $request->print(&editgrades($request,$symb));
1.602     www      10306:         } elsif ($command eq 'initialverifyreceipt' && $perm{'vgr'}) {
1.616     www      10307:             &startpage($request,$symb,[{href=>'',text=>'Verify Receipt Number'}]);
1.611     www      10308:             $request->print(&initialverifyreceipt($request,$symb));
1.106     albertel 10309: 	} elsif ($command eq 'verify' && $perm{'vgr'}) {
1.616     www      10310:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,"initialverifyreceipt"),text=>'Verify Receipt Number'},
                   10311:                                        {href=>'',text=>'Verification Result'}]);
1.608     www      10312: 	    $request->print(&verifyreceipt($request,$symb));
1.400     www      10313:         } elsif ($command eq 'processclicker' && $perm{'mgr'}) {
1.615     www      10314:             &startpage($request,$symb,[{href=>'', text=>'Process clicker'}]);
1.608     www      10315:             $request->print(&process_clicker($request,$symb));
1.400     www      10316:         } elsif ($command eq 'processclickerfile' && $perm{'mgr'}) {
1.615     www      10317:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,'processclicker'), text=>'Process clicker'},
                   10318:                                        {href=>'', text=>'Process clicker file'}]);
1.608     www      10319:             $request->print(&process_clicker_file($request,$symb));
1.414     www      10320:         } elsif ($command eq 'assignclickergrades' && $perm{'mgr'}) {
1.615     www      10321:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,'processclicker'), text=>'Process clicker'},
                   10322:                                        {href=>'', text=>'Process clicker file'},
                   10323:                                        {href=>'', text=>'Store grades'}]);
1.608     www      10324:             $request->print(&assign_clicker_grades($request,$symb));
1.106     albertel 10325: 	} elsif ($command eq 'csvform' && $perm{'mgr'}) {
1.627     www      10326:             &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
1.608     www      10327: 	    $request->print(&upcsvScores_form($request,$symb));
1.106     albertel 10328: 	} elsif ($command eq 'csvupload' && $perm{'mgr'}) {
1.627     www      10329:             &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
1.608     www      10330: 	    $request->print(&csvupload($request,$symb));
1.106     albertel 10331: 	} elsif ($command eq 'csvuploadmap' && $perm{'mgr'} ) {
1.627     www      10332:             &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
1.608     www      10333: 	    $request->print(&csvuploadmap($request,$symb));
1.246     albertel 10334: 	} elsif ($command eq 'csvuploadoptions' && $perm{'mgr'}) {
1.257     albertel 10335: 	    if ($env{'form.associate'} ne 'Reverse Association') {
1.627     www      10336:                 &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
1.608     www      10337: 		$request->print(&csvuploadoptions($request,$symb));
1.41      ng       10338: 	    } else {
1.257     albertel 10339: 		if ( $env{'form.upfile_associate'} ne 'reverse' ) {
                   10340: 		    $env{'form.upfile_associate'} = 'reverse';
1.41      ng       10341: 		} else {
1.257     albertel 10342: 		    $env{'form.upfile_associate'} = 'forward';
1.41      ng       10343: 		}
1.627     www      10344:                 &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
1.608     www      10345: 		$request->print(&csvuploadmap($request,$symb));
1.41      ng       10346: 	    }
1.246     albertel 10347: 	} elsif ($command eq 'csvuploadassign' && $perm{'mgr'} ) {
1.627     www      10348:             &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
1.608     www      10349: 	    $request->print(&csvuploadassign($request,$symb));
1.106     albertel 10350: 	} elsif ($command eq 'scantron_selectphase' && $perm{'mgr'}) {
1.616     www      10351:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
1.612     www      10352: 	    $request->print(&scantron_selectphase($request,undef,$symb));
1.203     albertel 10353:  	} elsif ($command eq 'scantron_warning' && $perm{'mgr'}) {
1.616     www      10354:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
1.608     www      10355:  	    $request->print(&scantron_do_warning($request,$symb));
1.142     albertel 10356: 	} elsif ($command eq 'scantron_validate' && $perm{'mgr'}) {
1.616     www      10357:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
1.608     www      10358: 	    $request->print(&scantron_validate_file($request,$symb));
1.106     albertel 10359: 	} elsif ($command eq 'scantron_process' && $perm{'mgr'}) {
1.616     www      10360:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
1.608     www      10361: 	    $request->print(&scantron_process_students($request,$symb));
1.157     albertel 10362:  	} elsif ($command eq 'scantronupload' && 
1.257     albertel 10363:  		 (&Apache::lonnet::allowed('usc',$env{'request.role.domain'})||
                   10364: 		  &Apache::lonnet::allowed('usc',$env{'request.course.id'}))) {
1.616     www      10365:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
1.608     www      10366:  	    $request->print(&scantron_upload_scantron_data($request,$symb)); 
1.157     albertel 10367:  	} elsif ($command eq 'scantronupload_save' &&
1.257     albertel 10368:  		 (&Apache::lonnet::allowed('usc',$env{'request.role.domain'})||
                   10369: 		  &Apache::lonnet::allowed('usc',$env{'request.course.id'}))) {
1.616     www      10370:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
1.608     www      10371:  	    $request->print(&scantron_upload_scantron_data_save($request,$symb));
1.202     albertel 10372:  	} elsif ($command eq 'scantron_download' &&
1.257     albertel 10373: 		 &Apache::lonnet::allowed('usc',$env{'request.course.id'})) {
1.616     www      10374:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
1.608     www      10375:  	    $request->print(&scantron_download_scantron_data($request,$symb));
1.523     raeburn  10376:         } elsif ($command eq 'checksubmissions' && $perm{'vgr'}) {
1.616     www      10377:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
1.621     www      10378:             $request->print(&checkscantron_results($request,$symb));
                   10379:         } elsif ($command eq 'downloadfilesselect' && $perm{'vgr'}) {
                   10380:             &startpage($request,$symb,[{href=>'', text=>'Select which submissions to download'}]);
                   10381:             $request->print(&submit_options_download($request,$symb));
                   10382:          } elsif ($command eq 'downloadfileslink' && $perm{'vgr'}) {
                   10383:             &startpage($request,$symb,
                   10384:    [{href=>&href_symb_cmd($symb,'downloadfilesselect'), text=>'Select which submissions to download'},
                   10385:     {href=>'', text=>'Download submissions'}]);
                   10386:             &submit_download_link($request,$symb);
1.106     albertel 10387: 	} elsif ($command) {
1.620     www      10388:             &startpage($request,$symb,[{href=>'', text=>'Access denied'}]);
1.562     bisitz   10389: 	    $request->print('<p class="LC_error">'.&mt('Access Denied ([_1])',$command).'</p>');
1.26      albertel 10390: 	}
1.2       albertel 10391:     }
1.513     foxr     10392:     if ($ssi_error) {
                   10393: 	&ssi_print_error($request);
                   10394:     }
1.671     raeburn  10395:     if ($env{'form.inhibitmenu'}) {
                   10396:         $request->print(&Apache::loncommon::end_page());
                   10397:     } else {
                   10398:         &Apache::lonquickgrades::endGradeScreen($request);
                   10399:     }
1.434     albertel 10400:     &reset_caches();
1.646     raeburn  10401:     return OK;
1.44      ng       10402: }
                   10403: 
1.1       albertel 10404: 1;
                   10405: 
1.13      albertel 10406: __END__;
1.531     jms      10407: 
                   10408: 
                   10409: =head1 NAME
                   10410: 
                   10411: Apache::grades
                   10412: 
                   10413: =head1 SYNOPSIS
                   10414: 
                   10415: Handles the viewing of grades.
                   10416: 
                   10417: This is part of the LearningOnline Network with CAPA project
                   10418: described at http://www.lon-capa.org.
                   10419: 
                   10420: =head1 OVERVIEW
                   10421: 
                   10422: Do an ssi with retries:
1.715     bisitz   10423: While I'd love to factor out this with the version in lonprintout,
1.531     jms      10424: 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
                   10425: I'm not quite ready to invent (e.g. an ssi_with_retry object).
                   10426: 
                   10427: At least the logic that drives this has been pulled out into loncommon.
                   10428: 
                   10429: 
                   10430: 
                   10431: ssi_with_retries - Does the server side include of a resource.
                   10432:                      if the ssi call returns an error we'll retry it up to
                   10433:                      the number of times requested by the caller.
1.715     bisitz   10434:                      If we still have a problem, no text is appended to the
1.531     jms      10435:                      output and we set some global variables.
                   10436:                      to indicate to the caller an SSI error occurred.  
                   10437:                      All of this is supposed to deal with the issues described
1.715     bisitz   10438:                      in LON-CAPA BZ 5631 see:
1.531     jms      10439:                      http://bugs.lon-capa.org/show_bug.cgi?id=5631
                   10440:                      by informing the user that this happened.
                   10441: 
                   10442: Parameters:
                   10443:   resource   - The resource to include.  This is passed directly, without
                   10444:                interpretation to lonnet::ssi.
                   10445:   form       - The form hash parameters that guide the interpretation of the resource
                   10446:                
                   10447:   retries    - Number of retries allowed before giving up completely.
                   10448: Returns:
                   10449:   On success, returns the rendered resource identified by the resource parameter.
                   10450: Side Effects:
                   10451:   The following global variables can be set:
                   10452:    ssi_error                - If an unrecoverable error occurred this becomes true.
                   10453:                               It is up to the caller to initialize this to false
                   10454:                               if desired.
                   10455:    ssi_error_resource  - If an unrecoverable error occurred, this is the value
                   10456:                               of the resource that could not be rendered by the ssi
                   10457:                               call.
                   10458:    ssi_error_message   - The error string fetched from the ssi response
                   10459:                               in the event of an error.
                   10460: 
                   10461: 
                   10462: =head1 HANDLER SUBROUTINE
                   10463: 
                   10464: ssi_with_retries()
                   10465: 
                   10466: =head1 SUBROUTINES
                   10467: 
                   10468: =over
                   10469: 
1.671     raeburn  10470: =head1 Routines to display previous version of a Task for a specific student
                   10471: 
                   10472: Tasks are graded pass/fail. Students who have yet to pass a particular Task
                   10473: can receive another opportunity. Access to tasks is slot-based. If a slot
                   10474: requires a proctor to check-in the student, a new version of the Task will
                   10475: be created when the student is checked in to the new opportunity.
                   10476: 
                   10477: If a particular student has tried two or more versions of a particular task,
                   10478: the submission screen provides a user with vgr privileges (e.g., a Course
                   10479: Coordinator) the ability to display a previous version worked on by the
                   10480: student.  By default, the current version is displayed. If a previous version
                   10481: has been selected for display, submission data are only shown that pertain
                   10482: to that particular version, and the interface to submit grades is not shown.
                   10483: 
                   10484: =over 4
                   10485: 
                   10486: =item show_previous_task_version()
                   10487: 
                   10488: Displays a specified version of a student's Task, as the student sees it.
                   10489: 
                   10490: Inputs: 2
                   10491:         request - request object
                   10492:         symb    - unique symb for current instance of resource
                   10493: 
                   10494: Output: None.
                   10495: 
                   10496: Side Effects: calls &show_problem() to print version of Task, with
                   10497:               version contained in form item: $env{'form.previousversion'}
                   10498: 
                   10499: =item choose_task_version_form()
                   10500: 
                   10501: Displays a web form used to select which version of a student's view of a
                   10502: Task should be displayed.  Either launches a pop-up window, or replaces
                   10503: content in existing pop-up, or replaces page in main window.
                   10504: 
                   10505: Inputs: 4
                   10506:         symb    - unique symb for current instance of resource
                   10507:         uname   - username of student
                   10508:         udom    - domain of student
                   10509:         nomenu  - 1 if display is in a pop-up window, and hence no menu
                   10510:                   breadcrumbs etc., are displayed
                   10511: 
                   10512: Output: 4
                   10513:         current   - student's current version
                   10514:         displayed - student's version being displayed
                   10515:         result    - scalar containing HTML for web form used to switch to
                   10516:                     a different version (or a link to close window, if pop-up).
                   10517:         js        - javascript for processing selection in versions web form
                   10518: 
                   10519: Side Effects: None.
                   10520: 
                   10521: =item previous_display_javascript()
                   10522: 
                   10523: Inputs: 2
                   10524:         nomenu  - 1 if display is in a pop-up window, and hence no menu
                   10525:                   breadcrumbs etc., are displayed.
                   10526:         current - student's current version number.
                   10527: 
                   10528: Output: 1
                   10529:         js      - javascript for processing selection in versions web form.
                   10530: 
                   10531: Side Effects: None.
                   10532: 
                   10533: =back
                   10534: 
                   10535: =head1 Routines to process bubblesheet data.
                   10536: 
                   10537: =over 4
                   10538: 
1.531     jms      10539: =item scantron_get_correction() : 
                   10540: 
                   10541:    Builds the interface screen to interact with the operator to fix a
                   10542:    specific error condition in a specific scanline
                   10543: 
                   10544:  Arguments:
                   10545:     $r           - Apache request object
                   10546:     $i           - number of the current scanline
                   10547:     $scan_record - hash ref as returned from &scantron_parse_scanline()
                   10548:     $scan_config - hash ref as returned from &get_scantron_config()
                   10549:     $line        - full contents of the current scanline
                   10550:     $error       - error condition, valid values are
                   10551:                    'incorrectCODE', 'duplicateCODE',
                   10552:                    'doublebubble', 'missingbubble',
                   10553:                    'duplicateID', 'incorrectID'
                   10554:     $arg         - extra information needed
                   10555:        For errors:
                   10556:          - duplicateID   - paper number that this studentID was seen before on
                   10557:          - duplicateCODE - array ref of the paper numbers this CODE was
                   10558:                            seen on before
                   10559:          - incorrectCODE - current incorrect CODE 
                   10560:          - doublebubble  - array ref of the bubble lines that have double
                   10561:                            bubble errors
                   10562:          - missingbubble - array ref of the bubble lines that have missing
                   10563:                            bubble errors
                   10564: 
1.691     raeburn  10565:    $randomorder - True if exam folder has randomorder set
                   10566:    $randompick  - True if exam folder has randompick set
                   10567:    $respnumlookup - Reference to HASH mapping question numbers in bubble lines
                   10568:                      for current line to question number used for same question
                   10569:                      in "Master Seqence" (as seen by Course Coordinator).
                   10570:    $startline   - Reference to hash where key is question number (0 is first)
                   10571:                   and value is number of first bubble line for current student
                   10572:                   or code-based randompick and/or randomorder.
                   10573: 
                   10574: 
                   10575: 
1.531     jms      10576: =item  scantron_get_maxbubble() : 
                   10577: 
1.582     raeburn  10578:    Arguments:
                   10579:        $nav_error  - Reference to scalar which is a flag to indicate a
                   10580:                       failure to retrieve a navmap object.
                   10581:        if $nav_error is set to 1 by scantron_get_maxbubble(), the 
                   10582:        calling routine should trap the error condition and display the warning
                   10583:        found in &navmap_errormsg().
                   10584: 
1.649     raeburn  10585:        $scantron_config - Reference to bubblesheet format configuration hash.
                   10586: 
1.531     jms      10587:    Returns the maximum number of bubble lines that are expected to
                   10588:    occur. Does this by walking the selected sequence rendering the
                   10589:    resource and then checking &Apache::lonxml::get_problem_counter()
                   10590:    for what the current value of the problem counter is.
                   10591: 
                   10592:    Caches the results to $env{'form.scantron_maxbubble'},
                   10593:    $env{'form.scantron.bubble_lines.n'}, 
                   10594:    $env{'form.scantron.first_bubble_line.n'} and
                   10595:    $env{"form.scantron.sub_bubblelines.n"}
1.691     raeburn  10596:    which are the total number of bubble lines, the number of bubble
1.531     jms      10597:    lines for response n and number of the first bubble line for response n,
                   10598:    and a comma separated list of numbers of bubble lines for sub-questions
                   10599:    (for optionresponse, matchresponse, and rankresponse items), for response n.  
                   10600: 
                   10601: 
                   10602: =item  scantron_validate_missingbubbles() : 
                   10603: 
                   10604:    Validates all scanlines in the selected file to not have any
                   10605:     answers that don't have bubbles that have not been verified
                   10606:     to be bubble free.
                   10607: 
                   10608: =item  scantron_process_students() : 
                   10609: 
1.659     raeburn  10610:    Routine that does the actual grading of the bubblesheet information.
1.531     jms      10611: 
                   10612:    The parsed scanline hash is added to %env 
                   10613: 
                   10614:    Then foreach unskipped scanline it does an &Apache::lonnet::ssi()
                   10615:    foreach resource , with the form data of
                   10616: 
                   10617: 	'submitted'     =>'scantron' 
                   10618: 	'grade_target'  =>'grade',
                   10619: 	'grade_username'=> username of student
                   10620: 	'grade_domain'  => domain of student
                   10621: 	'grade_courseid'=> of course
                   10622: 	'grade_symb'    => symb of resource to grade
                   10623: 
                   10624:     This triggers a grading pass. The problem grading code takes care
                   10625:     of converting the bubbled letter information (now in %env) into a
                   10626:     valid submission.
                   10627: 
                   10628: =item  scantron_upload_scantron_data() :
                   10629: 
1.659     raeburn  10630:     Creates the screen for adding a new bubblesheet data file to a course.
1.531     jms      10631: 
                   10632: =item  scantron_upload_scantron_data_save() : 
                   10633: 
                   10634:    Adds a provided bubble information data file to the course if user
                   10635:    has the correct privileges to do so. 
                   10636: 
                   10637: =item  valid_file() :
                   10638: 
                   10639:    Validates that the requested bubble data file exists in the course.
                   10640: 
                   10641: =item  scantron_download_scantron_data() : 
                   10642: 
                   10643:    Shows a list of the three internal files (original, corrected,
1.659     raeburn  10644:    skipped) for a specific bubblesheet data file that exists in the
1.531     jms      10645:    course.
                   10646: 
                   10647: =item  scantron_validate_ID() : 
                   10648: 
                   10649:    Validates all scanlines in the selected file to not have any
1.556     weissno  10650:    invalid or underspecified student/employee IDs
1.531     jms      10651: 
1.582     raeburn  10652: =item navmap_errormsg() :
                   10653: 
                   10654:    Returns HTML mark-up inside a <div></div> with a link to re-initialize the course.
1.671     raeburn  10655:    Should be called whenever the request to instantiate a navmap object fails.
                   10656: 
                   10657: =back
1.582     raeburn  10658: 
1.531     jms      10659: =back
                   10660: 
                   10661: =cut

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