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

1.17      albertel    1: # The LearningOnline Network with CAPA
1.13      albertel    2: # The LON-CAPA Grading handler
1.17      albertel    3: #
1.639   ! www         4: # $Id: grades.pm,v 1.638 2010/10/22 15:29:57 www Exp $
1.17      albertel    5: #
                      6: # Copyright Michigan State University Board of Trustees
                      7: #
                      8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
                      9: #
                     10: # LON-CAPA is free software; you can redistribute it and/or modify
                     11: # it under the terms of the GNU General Public License as published by
                     12: # the Free Software Foundation; either version 2 of the License, or
                     13: # (at your option) any later version.
                     14: #
                     15: # LON-CAPA is distributed in the hope that it will be useful,
                     16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
                     17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
                     18: # GNU General Public License for more details.
                     19: #
                     20: # You should have received a copy of the GNU General Public License
                     21: # along with LON-CAPA; if not, write to the Free Software
                     22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
                     23: #
                     24: # /home/httpd/html/adm/gpl.txt
                     25: #
                     26: # http://www.lon-capa.org/
                     27: #
1.1       albertel   28: 
1.529     jms        29: 
                     30: 
1.1       albertel   31: package Apache::grades;
                     32: use strict;
                     33: use Apache::style;
                     34: use Apache::lonxml;
                     35: use Apache::lonnet;
1.3       albertel   36: use Apache::loncommon;
1.112     ng         37: use Apache::lonhtmlcommon;
1.68      ng         38: use Apache::lonnavmaps;
1.1       albertel   39: use Apache::lonhomework;
1.456     banghart   40: use Apache::lonpickcode;
1.55      matthew    41: use Apache::loncoursedata;
1.362     albertel   42: use Apache::lonmsg();
1.1       albertel   43: use Apache::Constants qw(:common);
1.167     sakharuk   44: use Apache::lonlocal;
1.386     raeburn    45: use Apache::lonenc;
1.622     www        46: use Apache::lonstathelpers;
1.639   ! www        47: use Apache::lonquickgrades;
1.170     albertel   48: use String::Similarity;
1.359     www        49: use LONCAPA;
                     50: 
1.315     bowersj2   51: use POSIX qw(floor);
1.87      www        52: 
1.435     foxr       53: 
1.513     foxr       54: 
1.435     foxr       55: my %perm=();
1.447     foxr       56: 
1.513     foxr       57: #  These variables are used to recover from ssi errors
                     58: 
                     59: my $ssi_retries = 5;
                     60: my $ssi_error;
                     61: my $ssi_error_resource;
                     62: my $ssi_error_message;
                     63: 
                     64: 
                     65: sub ssi_with_retries {
                     66:     my ($resource, $retries, %form) = @_;
                     67:     my ($content, $response) = &Apache::loncommon::ssi_with_retries($resource, $retries, %form);
                     68:     if ($response->is_error) {
                     69: 	$ssi_error          = 1;
                     70: 	$ssi_error_resource = $resource;
                     71: 	$ssi_error_message  = $response->code . " " . $response->message;
                     72:     }
                     73: 
                     74:     return $content;
                     75: 
                     76: }
                     77: #
                     78: #  Prodcuces an ssi retry failure error message to the user:
                     79: #
                     80: 
                     81: sub ssi_print_error {
                     82:     my ($r) = @_;
1.516     raeburn    83:     my $helpurl = &Apache::loncommon::top_nav_help('Helpdesk');
                     84:     $r->print('
                     85: <br />
                     86: <h2>'.&mt('An unrecoverable network error occurred:').'</h2>
                     87: <p>
                     88: '.&mt('Unable to retrieve a resource from a server:').'<br />
                     89: '.&mt('Resource:').' '.$ssi_error_resource.'<br />
                     90: '.&mt('Error:').' '.$ssi_error_message.'
                     91: </p>
                     92: <p>'.
                     93: &mt('It is recommended that you try again later, as this error may mean the server was just temporarily unavailable, or is down for maintenance.').'<br />'.
                     94: &mt('If the error persists, please contact the [_1] for assistance.',$helpurl).
                     95: '</p>');
                     96:     return;
1.513     foxr       97: }
                     98: 
1.44      ng         99: #
1.146     albertel  100: # --- Retrieve the parts from the metadata file.---
1.598     www       101: # Returns an array of everything that the resources stores away
                    102: #
                    103: 
1.44      ng        104: sub getpartlist {
1.582     raeburn   105:     my ($symb,$errorref) = @_;
1.439     albertel  106: 
                    107:     my $navmap   = Apache::lonnavmaps::navmap->new();
1.582     raeburn   108:     unless (ref($navmap)) {
                    109:         if (ref($errorref)) { 
                    110:             $$errorref = 'navmap';
                    111:             return;
                    112:         }
                    113:     }
1.439     albertel  114:     my $res      = $navmap->getBySymb($symb);
                    115:     my $partlist = $res->parts();
                    116:     my $url      = $res->src();
                    117:     my @metakeys = split(/,/,&Apache::lonnet::metadata($url,'keys'));
                    118: 
1.146     albertel  119:     my @stores;
1.439     albertel  120:     foreach my $part (@{ $partlist }) {
1.146     albertel  121: 	foreach my $key (@metakeys) {
                    122: 	    if ($key =~ m/^stores_\Q$part\E_/) { push(@stores,$key); }
                    123: 	}
                    124:     }
                    125:     return @stores;
1.2       albertel  126: }
                    127: 
1.129     ng        128: #--- Format fullname, username:domain if different for display
                    129: #--- Use anywhere where the student names are listed
                    130: sub nameUserString {
                    131:     my ($type,$fullname,$uname,$udom) = @_;
                    132:     if ($type eq 'header') {
1.485     albertel  133: 	return '<b>&nbsp;'.&mt('Fullname').'&nbsp;</b><span class="LC_internal_info">('.&mt('Username').')</span>';
1.129     ng        134:     } else {
1.398     albertel  135: 	return '&nbsp;'.$fullname.'<span class="LC_internal_info">&nbsp;('.$uname.
                    136: 	    ($env{'user.domain'} eq $udom ? '' : ' ('.$udom.')').')</span>';
1.129     ng        137:     }
                    138: }
                    139: 
1.44      ng        140: #--- Get the partlist and the response type for a given problem. ---
                    141: #--- Indicate if a response type is coded handgraded or not. ---
1.623     www       142: #--- Sets response_error pointer to "1" if navmaps object broken ---
1.39      ng        143: sub response_type {
1.582     raeburn   144:     my ($symb,$response_error) = @_;
1.377     albertel  145: 
                    146:     my $navmap = Apache::lonnavmaps::navmap->new();
1.582     raeburn   147:     unless (ref($navmap)) {
                    148:         if (ref($response_error)) {
                    149:             $$response_error = 1;
                    150:         }
                    151:         return;
                    152:     }
1.377     albertel  153:     my $res = $navmap->getBySymb($symb);
1.593     raeburn   154:     unless (ref($res)) {
                    155:         $$response_error = 1;
                    156:         return;
                    157:     }
1.377     albertel  158:     my $partlist = $res->parts();
1.392     albertel  159:     my %vPart = 
                    160: 	map { $_ => 1 } (&Apache::loncommon::get_env_multiple('form.vPart'));
1.377     albertel  161:     my (%response_types,%handgrade);
                    162:     foreach my $part (@{ $partlist }) {
1.392     albertel  163: 	next if (%vPart && !exists($vPart{$part}));
                    164: 
1.377     albertel  165: 	my @types = $res->responseType($part);
                    166: 	my @ids = $res->responseIds($part);
                    167: 	for (my $i=0; $i < scalar(@ids); $i++) {
                    168: 	    $response_types{$part}{$ids[$i]} = $types[$i];
                    169: 	    $handgrade{$part.'_'.$ids[$i]} = 
                    170: 		&Apache::lonnet::EXT('resource.'.$part.'_'.$ids[$i].
                    171: 				     '.handgrade',$symb);
1.41      ng        172: 	}
                    173:     }
1.377     albertel  174:     return ($partlist,\%handgrade,\%response_types);
1.39      ng        175: }
                    176: 
1.375     albertel  177: sub flatten_responseType {
                    178:     my ($responseType) = @_;
                    179:     my @part_response_id =
                    180: 	map { 
                    181: 	    my $part = $_;
                    182: 	    map {
                    183: 		[$part,$_]
                    184: 		} sort(keys(%{ $responseType->{$part} }));
                    185: 	} sort(keys(%$responseType));
                    186:     return @part_response_id;
                    187: }
                    188: 
1.207     albertel  189: sub get_display_part {
1.324     albertel  190:     my ($partID,$symb)=@_;
1.207     albertel  191:     my $display=&Apache::lonnet::EXT('resource.'.$partID.'.display',$symb);
                    192:     if (defined($display) and $display ne '') {
1.577     bisitz    193:         $display.= ' (<span class="LC_internal_info">'
                    194:                   .&mt('Part ID: [_1]',$partID).'</span>)';
1.207     albertel  195:     } else {
                    196: 	$display=$partID;
                    197:     }
                    198:     return $display;
                    199: }
1.269     raeburn   200: 
1.434     albertel  201: sub reset_caches {
                    202:     &reset_analyze_cache();
                    203:     &reset_perm();
                    204: }
                    205: 
                    206: {
                    207:     my %analyze_cache;
1.557     raeburn   208:     my %analyze_cache_formkeys;
1.148     albertel  209: 
1.434     albertel  210:     sub reset_analyze_cache {
                    211: 	undef(%analyze_cache);
1.557     raeburn   212:         undef(%analyze_cache_formkeys);
1.434     albertel  213:     }
                    214: 
                    215:     sub get_analyze {
1.557     raeburn   216: 	my ($symb,$uname,$udom,$no_increment,$add_to_hash)=@_;
1.434     albertel  217: 	my $key = "$symb\0$uname\0$udom";
1.557     raeburn   218: 	if (exists($analyze_cache{$key})) {
                    219:             my $getupdate = 0;
                    220:             if (ref($add_to_hash) eq 'HASH') {
                    221:                 foreach my $item (keys(%{$add_to_hash})) {
                    222:                     if (ref($analyze_cache_formkeys{$key}) eq 'HASH') {
                    223:                         if (!exists($analyze_cache_formkeys{$key}{$item})) {
                    224:                             $getupdate = 1;
                    225:                             last;
                    226:                         }
                    227:                     } else {
                    228:                         $getupdate = 1;
                    229:                     }
                    230:                 }
                    231:             }
                    232:             if (!$getupdate) {
                    233:                 return $analyze_cache{$key};
                    234:             }
                    235:         }
1.434     albertel  236: 
                    237: 	my (undef,undef,$url)=&Apache::lonnet::decode_symb($symb);
                    238: 	$url=&Apache::lonnet::clutter($url);
1.557     raeburn   239:         my %form = ('grade_target'      => 'analyze',
                    240:                     'grade_domain'      => $udom,
                    241:                     'grade_symb'        => $symb,
                    242:                     'grade_courseid'    =>  $env{'request.course.id'},
                    243:                     'grade_username'    => $uname,
                    244:                     'grade_noincrement' => $no_increment);
                    245:         if (ref($add_to_hash)) {
                    246:             %form = (%form,%{$add_to_hash});
                    247:         } 
                    248: 	my $subresult=&ssi_with_retries($url, $ssi_retries,%form);
1.434     albertel  249: 	(undef,$subresult)=split(/_HASH_REF__/,$subresult,2);
                    250: 	my %analyze=&Apache::lonnet::str2hash($subresult);
1.557     raeburn   251:         if (ref($add_to_hash) eq 'HASH') {
                    252:             $analyze_cache_formkeys{$key} = $add_to_hash;
                    253:         } else {
                    254:             $analyze_cache_formkeys{$key} = {};
                    255:         }
1.434     albertel  256: 	return $analyze_cache{$key} = \%analyze;
                    257:     }
                    258: 
                    259:     sub get_order {
1.525     raeburn   260: 	my ($partid,$respid,$symb,$uname,$udom,$no_increment)=@_;
                    261: 	my $analyze = &get_analyze($symb,$uname,$udom,$no_increment);
1.434     albertel  262: 	return $analyze->{"$partid.$respid.shown"};
                    263:     }
                    264: 
                    265:     sub get_radiobutton_correct_foil {
                    266: 	my ($partid,$respid,$symb,$uname,$udom)=@_;
                    267: 	my $analyze = &get_analyze($symb,$uname,$udom);
1.555     raeburn   268:         my $foils = &get_order($partid,$respid,$symb,$uname,$udom);
                    269:         if (ref($foils) eq 'ARRAY') {
                    270: 	    foreach my $foil (@{$foils}) {
                    271: 	        if ($analyze->{"$partid.$respid.foil.value.$foil"} eq 'true') {
                    272: 		    return $foil;
                    273: 	        }
1.434     albertel  274: 	    }
                    275: 	}
                    276:     }
1.554     raeburn   277: 
                    278:     sub scantron_partids_tograde {
1.557     raeburn   279:         my ($resource,$cid,$uname,$udom,$check_for_randomlist) = @_;
1.554     raeburn   280:         my (%analysis,@parts);
                    281:         if (ref($resource)) {
                    282:             my $symb = $resource->symb();
1.557     raeburn   283:             my $add_to_form;
                    284:             if ($check_for_randomlist) {
                    285:                 $add_to_form = { 'check_parts_withrandomlist' => 1,};
                    286:             }
                    287:             my $analyze = &get_analyze($symb,$uname,$udom,undef,$add_to_form);
1.554     raeburn   288:             if (ref($analyze) eq 'HASH') {
                    289:                 %analysis = %{$analyze};
                    290:             }
                    291:             if (ref($analysis{'parts'}) eq 'ARRAY') {
                    292:                 foreach my $part (@{$analysis{'parts'}}) {
                    293:                     my ($id,$respid) = split(/\./,$part);
                    294:                     if (!&Apache::loncommon::check_if_partid_hidden($id,$symb,$udom,$uname)) {
                    295:                         push(@parts,$part);
                    296:                     }
                    297:                 }
                    298:             }
                    299:         }
                    300:         return (\%analysis,\@parts);
                    301:     }
                    302: 
1.148     albertel  303: }
1.434     albertel  304: 
1.118     ng        305: #--- Clean response type for display
1.335     albertel  306: #--- Currently filters option/rank/radiobutton/match/essay/Task
                    307: #        response types only.
1.118     ng        308: sub cleanRecord {
1.336     albertel  309:     my ($answer,$response,$symb,$partid,$respid,$record,$order,$version,
                    310: 	$uname,$udom) = @_;
1.398     albertel  311:     my $grayFont = '<span class="LC_internal_info">';
1.148     albertel  312:     if ($response =~ /^(option|rank)$/) {
                    313: 	my %answer=&Apache::lonnet::str2hash($answer);
                    314: 	my %grading=&Apache::lonnet::str2hash($record->{$version."resource.$partid.$respid.submissiongrading"});
                    315: 	my ($toprow,$bottomrow);
                    316: 	foreach my $foil (@$order) {
                    317: 	    if ($grading{$foil} == 1) {
                    318: 		$toprow.='<td><b>'.$answer{$foil}.'&nbsp;</b></td>';
                    319: 	    } else {
                    320: 		$toprow.='<td><i>'.$answer{$foil}.'&nbsp;</i></td>';
                    321: 	    }
1.398     albertel  322: 	    $bottomrow.='<td>'.$grayFont.$foil.'</span>&nbsp;</td>';
1.148     albertel  323: 	}
                    324: 	return '<blockquote><table border="1">'.
1.466     albertel  325: 	    '<tr valign="top"><td>'.&mt('Answer').'</td>'.$toprow.'</tr>'.
                    326: 	    '<tr valign="top"><td>'.$grayFont.&mt('Option ID').'</span></td>'.
1.148     albertel  327: 	    $grayFont.$bottomrow.'</tr>'.'</table></blockquote>';
                    328:     } elsif ($response eq 'match') {
                    329: 	my %answer=&Apache::lonnet::str2hash($answer);
                    330: 	my %grading=&Apache::lonnet::str2hash($record->{$version."resource.$partid.$respid.submissiongrading"});
                    331: 	my @items=&Apache::lonnet::str2array($record->{$version."resource.$partid.$respid.submissionitems"});
                    332: 	my ($toprow,$middlerow,$bottomrow);
                    333: 	foreach my $foil (@$order) {
                    334: 	    my $item=shift(@items);
                    335: 	    if ($grading{$foil} == 1) {
                    336: 		$toprow.='<td><b>'.$item.'&nbsp;</b></td>';
1.398     albertel  337: 		$middlerow.='<td><b>'.$grayFont.$answer{$foil}.'&nbsp;</span></b></td>';
1.148     albertel  338: 	    } else {
                    339: 		$toprow.='<td><i>'.$item.'&nbsp;</i></td>';
1.398     albertel  340: 		$middlerow.='<td><i>'.$grayFont.$answer{$foil}.'&nbsp;</span></i></td>';
1.148     albertel  341: 	    }
1.398     albertel  342: 	    $bottomrow.='<td>'.$grayFont.$foil.'</span>&nbsp;</td>';
1.118     ng        343: 	}
1.126     ng        344: 	return '<blockquote><table border="1">'.
1.466     albertel  345: 	    '<tr valign="top"><td>'.&mt('Answer').'</td>'.$toprow.'</tr>'.
                    346: 	    '<tr valign="top"><td>'.$grayFont.&mt('Item ID').'</span></td>'.
1.148     albertel  347: 	    $middlerow.'</tr>'.
1.466     albertel  348: 	    '<tr valign="top"><td>'.$grayFont.&mt('Option ID').'</span></td>'.
1.148     albertel  349: 	    $bottomrow.'</tr>'.'</table></blockquote>';
                    350:     } elsif ($response eq 'radiobutton') {
                    351: 	my %answer=&Apache::lonnet::str2hash($answer);
                    352: 	my ($toprow,$bottomrow);
1.434     albertel  353: 	my $correct = 
                    354: 	    &get_radiobutton_correct_foil($partid,$respid,$symb,$uname,$udom);
                    355: 	foreach my $foil (@$order) {
1.148     albertel  356: 	    if (exists($answer{$foil})) {
1.434     albertel  357: 		if ($foil eq $correct) {
1.466     albertel  358: 		    $toprow.='<td><b>'.&mt('true').'</b></td>';
1.148     albertel  359: 		} else {
1.466     albertel  360: 		    $toprow.='<td><i>'.&mt('true').'</i></td>';
1.148     albertel  361: 		}
                    362: 	    } else {
1.466     albertel  363: 		$toprow.='<td>'.&mt('false').'</td>';
1.148     albertel  364: 	    }
1.398     albertel  365: 	    $bottomrow.='<td>'.$grayFont.$foil.'</span>&nbsp;</td>';
1.148     albertel  366: 	}
                    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('Option ID').'</span></td>'.
1.597     wenzelju  370: 	    $bottomrow.'</tr>'.'</table></blockquote>';
1.148     albertel  371:     } elsif ($response eq 'essay') {
1.257     albertel  372: 	if (! exists ($env{'form.'.$symb})) {
1.122     ng        373: 	    my (%keyhash) = &Apache::lonnet::dump('nohist_handgrade',
1.257     albertel  374: 						  $env{'course.'.$env{'request.course.id'}.'.domain'},
                    375: 						  $env{'course.'.$env{'request.course.id'}.'.num'});
1.122     ng        376: 
1.257     albertel  377: 	    my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
                    378: 	    $env{'form.keywords'} = $keyhash{$symb.'_keywords'} ne '' ? $keyhash{$symb.'_keywords'} : '';
                    379: 	    $env{'form.kwclr'}    = $keyhash{$loginuser.'_kwclr'} ne '' ? $keyhash{$loginuser.'_kwclr'} : 'red';
                    380: 	    $env{'form.kwsize'}   = $keyhash{$loginuser.'_kwsize'} ne '' ? $keyhash{$loginuser.'_kwsize'} : '0';
                    381: 	    $env{'form.kwstyle'}  = $keyhash{$loginuser.'_kwstyle'} ne '' ? $keyhash{$loginuser.'_kwstyle'} : '';
                    382: 	    $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        383: 	}
1.166     albertel  384: 	$answer =~ s-\n-<br />-g;
                    385: 	return '<br /><br /><blockquote><tt>'.&keywords_highlight($answer).'</tt></blockquote>';
1.268     albertel  386:     } elsif ( $response eq 'organic') {
                    387: 	my $result='Smile representation: "<tt>'.$answer.'</tt>"';
                    388: 	my $jme=$record->{$version."resource.$partid.$respid.molecule"};
                    389: 	$result.=&Apache::chemresponse::jme_img($jme,$answer,400);
                    390: 	return $result;
1.335     albertel  391:     } elsif ( $response eq 'Task') {
                    392: 	if ( $answer eq 'SUBMITTED') {
                    393: 	    my $files = $record->{$version."resource.$respid.$partid.bridgetask.portfiles"};
1.336     albertel  394: 	    my $result = &Apache::bridgetask::file_list($files,$uname,$udom);
1.335     albertel  395: 	    return $result;
                    396: 	} elsif ( grep(/^\Q$version\E.*?\.instance$/, keys(%{$record})) ) {
                    397: 	    my @matches = grep(/^\Q$version\E.*?\.instance$/,
                    398: 			       keys(%{$record}));
                    399: 	    return join('<br />',($version,@matches));
                    400: 			       
                    401: 			       
                    402: 	} else {
                    403: 	    my $result =
                    404: 		'<p>'
                    405: 		.&mt('Overall result: [_1]',
                    406: 		     $record->{$version."resource.$respid.$partid.status"})
                    407: 		.'</p>';
                    408: 	    
                    409: 	    $result .= '<ul>';
                    410: 	    my @grade = grep(/^\Q${version}resource.$respid.$partid.\E[^.]*[.]status$/,
                    411: 			     keys(%{$record}));
                    412: 	    foreach my $grade (sort(@grade)) {
                    413: 		my ($dim) = ($grade =~/[.]([^.]+)[.]status$/);
                    414: 		$result.= '<li>'.&mt("Dimension: [_1], status [_2] ",
                    415: 				     $dim, $record->{$grade}).
                    416: 			  '</li>';
                    417: 	    }
                    418: 	    $result.='</ul>';
                    419: 	    return $result;
                    420: 	}
1.440     albertel  421:     } elsif ( $response =~ m/(?:numerical|formula)/) {
                    422: 	$answer = 
                    423: 	    &Apache::loncommon::format_previous_attempt_value('submission',
                    424: 							      $answer);
1.122     ng        425:     }
1.118     ng        426:     return $answer;
                    427: }
                    428: 
                    429: #-- A couple of common js functions
                    430: sub commonJSfunctions {
                    431:     my $request = shift;
1.597     wenzelju  432:     $request->print(&Apache::lonhtmlcommon::scripttag(<<COMMONJSFUNCTIONS));
1.118     ng        433:     function radioSelection(radioButton) {
                    434: 	var selection=null;
                    435: 	if (radioButton.length > 1) {
                    436: 	    for (var i=0; i<radioButton.length; i++) {
                    437: 		if (radioButton[i].checked) {
                    438: 		    return radioButton[i].value;
                    439: 		}
                    440: 	    }
                    441: 	} else {
                    442: 	    if (radioButton.checked) return radioButton.value;
                    443: 	}
                    444: 	return selection;
                    445:     }
                    446: 
                    447:     function pullDownSelection(selectOne) {
                    448: 	var selection="";
                    449: 	if (selectOne.length > 1) {
                    450: 	    for (var i=0; i<selectOne.length; i++) {
                    451: 		if (selectOne[i].selected) {
                    452: 		    return selectOne[i].value;
                    453: 		}
                    454: 	    }
                    455: 	} else {
1.138     albertel  456:             // only one value it must be the selected one
                    457: 	    return selectOne.value;
1.118     ng        458: 	}
                    459:     }
                    460: COMMONJSFUNCTIONS
                    461: }
                    462: 
1.44      ng        463: #--- Dumps the class list with usernames,list of sections,
                    464: #--- section, ids and fullnames for each user.
                    465: sub getclasslist {
1.449     banghart  466:     my ($getsec,$filterlist,$getgroup) = @_;
1.291     albertel  467:     my @getsec;
1.450     banghart  468:     my @getgroup;
1.442     banghart  469:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
1.291     albertel  470:     if (!ref($getsec)) {
                    471: 	if ($getsec ne '' && $getsec ne 'all') {
                    472: 	    @getsec=($getsec);
                    473: 	}
                    474:     } else {
                    475: 	@getsec=@{$getsec};
                    476:     }
                    477:     if (grep(/^all$/,@getsec)) { undef(@getsec); }
1.450     banghart  478:     if (!ref($getgroup)) {
                    479: 	if ($getgroup ne '' && $getgroup ne 'all') {
                    480: 	    @getgroup=($getgroup);
                    481: 	}
                    482:     } else {
                    483: 	@getgroup=@{$getgroup};
                    484:     }
                    485:     if (grep(/^all$/,@getgroup)) { undef(@getgroup); }
1.291     albertel  486: 
1.449     banghart  487:     my ($classlist,$keylist)=&Apache::loncoursedata::get_classlist();
1.49      albertel  488:     # Bail out if we were unable to get the classlist
1.56      matthew   489:     return if (! defined($classlist));
1.449     banghart  490:     &Apache::loncoursedata::get_group_memberships($classlist,$keylist);
1.56      matthew   491:     #
                    492:     my %sections;
                    493:     my %fullnames;
1.205     matthew   494:     foreach my $student (keys(%$classlist)) {
                    495:         my $end      = 
                    496:             $classlist->{$student}->[&Apache::loncoursedata::CL_END()];
                    497:         my $start    = 
                    498:             $classlist->{$student}->[&Apache::loncoursedata::CL_START()];
                    499:         my $id       = 
                    500:             $classlist->{$student}->[&Apache::loncoursedata::CL_ID()];
                    501:         my $section  = 
                    502:             $classlist->{$student}->[&Apache::loncoursedata::CL_SECTION()];
                    503:         my $fullname = 
                    504:             $classlist->{$student}->[&Apache::loncoursedata::CL_FULLNAME()];
                    505:         my $status   = 
                    506:             $classlist->{$student}->[&Apache::loncoursedata::CL_STATUS()];
1.449     banghart  507:         my $group   = 
                    508:             $classlist->{$student}->[&Apache::loncoursedata::CL_GROUP()];
1.76      ng        509: 	# filter students according to status selected
1.442     banghart  510: 	if ($filterlist && (!($stu_status =~ /Any/))) {
                    511: 	    if (!($stu_status =~ $status)) {
1.450     banghart  512: 		delete($classlist->{$student});
1.76      ng        513: 		next;
                    514: 	    }
                    515: 	}
1.450     banghart  516: 	# filter students according to groups selected
1.453     banghart  517: 	my @stu_groups = split(/,/,$group);
1.450     banghart  518: 	if (@getgroup) {
                    519: 	    my $exclude = 1;
1.454     banghart  520: 	    foreach my $grp (@getgroup) {
                    521: 	        foreach my $stu_group (@stu_groups) {
1.453     banghart  522: 	            if ($stu_group eq $grp) {
                    523: 	                $exclude = 0;
                    524:     	            } 
1.450     banghart  525: 	        }
1.453     banghart  526:     	        if (($grp eq 'none') && !$group) {
                    527:         	        $exclude = 0;
                    528:         	}
1.450     banghart  529: 	    }
                    530: 	    if ($exclude) {
                    531: 	        delete($classlist->{$student});
                    532: 	    }
                    533: 	}
1.205     matthew   534: 	$section = ($section ne '' ? $section : 'none');
1.106     albertel  535: 	if (&canview($section)) {
1.291     albertel  536: 	    if (!@getsec || grep(/^\Q$section\E$/,@getsec)) {
1.103     albertel  537: 		$sections{$section}++;
1.450     banghart  538: 		if ($classlist->{$student}) {
                    539: 		    $fullnames{$student}=$fullname;
                    540: 		}
1.103     albertel  541: 	    } else {
1.205     matthew   542: 		delete($classlist->{$student});
1.103     albertel  543: 	    }
                    544: 	} else {
1.205     matthew   545: 	    delete($classlist->{$student});
1.103     albertel  546: 	}
1.44      ng        547:     }
                    548:     my %seen = ();
1.56      matthew   549:     my @sections = sort(keys(%sections));
                    550:     return ($classlist,\@sections,\%fullnames);
1.44      ng        551: }
                    552: 
1.103     albertel  553: sub canmodify {
                    554:     my ($sec)=@_;
                    555:     if ($perm{'mgr'}) {
                    556: 	if (!defined($perm{'mgr_section'})) {
                    557: 	    # can modify whole class
                    558: 	    return 1;
                    559: 	} else {
                    560: 	    if ($sec eq $perm{'mgr_section'}) {
                    561: 		#can modify the requested section
                    562: 		return 1;
                    563: 	    } else {
                    564: 		# can't modify the request section
                    565: 		return 0;
                    566: 	    }
                    567: 	}
                    568:     }
                    569:     #can't modify
                    570:     return 0;
                    571: }
                    572: 
                    573: sub canview {
                    574:     my ($sec)=@_;
                    575:     if ($perm{'vgr'}) {
                    576: 	if (!defined($perm{'vgr_section'})) {
                    577: 	    # can modify whole class
                    578: 	    return 1;
                    579: 	} else {
                    580: 	    if ($sec eq $perm{'vgr_section'}) {
                    581: 		#can modify the requested section
                    582: 		return 1;
                    583: 	    } else {
                    584: 		# can't modify the request section
                    585: 		return 0;
                    586: 	    }
                    587: 	}
                    588:     }
                    589:     #can't modify
                    590:     return 0;
                    591: }
                    592: 
1.44      ng        593: #--- Retrieve the grade status of a student for all the parts
                    594: sub student_gradeStatus {
1.324     albertel  595:     my ($symb,$udom,$uname,$partlist) = @_;
1.257     albertel  596:     my %record     = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
1.44      ng        597:     my %partstatus = ();
                    598:     foreach (@$partlist) {
1.128     ng        599: 	my ($status,undef)   = split(/_/,$record{"resource.$_.solved"},2);
1.44      ng        600: 	$status              = 'nothing' if ($status eq '');
                    601: 	$partstatus{$_}      = $status;
                    602: 	my $subkey           = "resource.$_.submitted_by";
                    603: 	$partstatus{$subkey} = $record{$subkey} if ($record{$subkey} ne '');
                    604:     }
                    605:     return %partstatus;
                    606: }
                    607: 
1.45      ng        608: # hidden form and javascript that calls the form
                    609: # Use by verifyscript and viewgrades
                    610: # Shows a student's view of problem and submission
                    611: sub jscriptNform {
1.324     albertel  612:     my ($symb) = @_;
1.442     banghart  613:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
1.597     wenzelju  614:     my $jscript= &Apache::lonhtmlcommon::scripttag(
1.45      ng        615: 	'    function viewOneStudent(user,domain) {'."\n".
                    616: 	'	document.onestudent.student.value = user;'."\n".
                    617: 	'	document.onestudent.userdom.value = domain;'."\n".
                    618: 	'	document.onestudent.submit();'."\n".
                    619: 	'    }'."\n".
1.597     wenzelju  620: 	"\n");
1.45      ng        621:     $jscript.= '<form action="/adm/grades" method="post" name="onestudent">'."\n".
1.418     albertel  622: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.442     banghart  623: 	'<input type="hidden" name="Status"  value="'.$stu_status.'" />'."\n".
1.45      ng        624: 	'<input type="hidden" name="command" value="submission" />'."\n".
                    625: 	'<input type="hidden" name="student" value="" />'."\n".
                    626: 	'<input type="hidden" name="userdom" value="" />'."\n".
                    627: 	'</form>'."\n";
                    628:     return $jscript;
                    629: }
1.39      ng        630: 
1.447     foxr      631: 
                    632: 
1.315     bowersj2  633: # Given the score (as a number [0-1] and the weight) what is the final
                    634: # point value? This function will round to the nearest tenth, third,
                    635: # or quarter if one of those is within the tolerance of .00001.
1.316     albertel  636: sub compute_points {
1.315     bowersj2  637:     my ($score, $weight) = @_;
                    638:     
                    639:     my $tolerance = .00001;
                    640:     my $points = $score * $weight;
                    641: 
                    642:     # Check for nearness to 1/x.
                    643:     my $check_for_nearness = sub {
                    644:         my ($factor) = @_;
                    645:         my $num = ($points * $factor) + $tolerance;
                    646:         my $floored_num = floor($num);
1.316     albertel  647:         if ($num - $floored_num < 2 * $tolerance * $factor) {
1.315     bowersj2  648:             return $floored_num / $factor;
                    649:         }
                    650:         return $points;
                    651:     };
                    652: 
                    653:     $points = $check_for_nearness->(10);
                    654:     $points = $check_for_nearness->(3);
                    655:     $points = $check_for_nearness->(4);
                    656:     
                    657:     return $points;
                    658: }
                    659: 
1.44      ng        660: #------------------ End of general use routines --------------------
1.87      www       661: 
                    662: #
                    663: # Find most similar essay
                    664: #
                    665: 
                    666: sub most_similar {
1.426     albertel  667:     my ($uname,$udom,$uessay,$old_essays)=@_;
1.87      www       668: 
                    669: # ignore spaces and punctuation
                    670: 
                    671:     $uessay=~s/\W+/ /gs;
                    672: 
1.282     www       673: # ignore empty submissions (occuring when only files are sent)
                    674: 
1.598     www       675:     unless ($uessay=~/\w+/s) { return ''; }
1.282     www       676: 
1.87      www       677: # these will be returned. Do not care if not at least 50 percent similar
1.88      www       678:     my $limit=0.6;
1.87      www       679:     my $sname='';
                    680:     my $sdom='';
                    681:     my $scrsid='';
                    682:     my $sessay='';
                    683: # go through all essays ...
1.426     albertel  684:     foreach my $tkey (keys(%$old_essays)) {
                    685: 	my ($tname,$tdom,$tcrsid)=map {&unescape($_)} (split(/\./,$tkey));
1.87      www       686: # ... except the same student
1.426     albertel  687:         next if (($tname eq $uname) && ($tdom eq $udom));
                    688: 	my $tessay=$old_essays->{$tkey};
                    689: 	$tessay=~s/\W+/ /gs;
1.87      www       690: # String similarity gives up if not even limit
1.426     albertel  691: 	my $tsimilar=&String::Similarity::similarity($uessay,$tessay,$limit);
1.87      www       692: # Found one
1.426     albertel  693: 	if ($tsimilar>$limit) {
                    694: 	    $limit=$tsimilar;
                    695: 	    $sname=$tname;
                    696: 	    $sdom=$tdom;
                    697: 	    $scrsid=$tcrsid;
                    698: 	    $sessay=$old_essays->{$tkey};
                    699: 	}
1.87      www       700:     }
1.88      www       701:     if ($limit>0.6) {
1.87      www       702:        return ($sname,$sdom,$scrsid,$sessay,$limit);
                    703:     } else {
                    704:        return ('','','','',0);
                    705:     }
                    706: }
                    707: 
1.44      ng        708: #-------------------------------------------------------------------
                    709: 
                    710: #------------------------------------ Receipt Verification Routines
1.45      ng        711: #
1.602     www       712: 
                    713: sub initialverifyreceipt {
1.608     www       714:    my ($request,$symb) = @_;
1.602     www       715:    &commonJSfunctions($request);
1.605     www       716:    return '<form name="gradingMenu"><input type="submit" value="'.&mt('Verify Receipt Number.').'" />'.
1.602     www       717:         &Apache::lonnet::recprefix($env{'request.course.id'}).
                    718:         '-<input type="text" name="receipt" size="4" />'.
1.603     www       719:         '<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
                    720:         '<input type="hidden" name="command" value="verify" />'.
                    721:         "</form>\n";
1.602     www       722: }
                    723: 
1.44      ng        724: #--- Check whether a receipt number is valid.---
                    725: sub verifyreceipt {
1.608     www       726:     my ($request,$symb)  = @_;
1.44      ng        727: 
1.257     albertel  728:     my $courseid = $env{'request.course.id'};
1.184     www       729:     my $receipt  = &Apache::lonnet::recprefix($courseid).'-'.
1.257     albertel  730: 	$env{'form.receipt'};
1.44      ng        731:     $receipt     =~ s/[^\-\d]//g;
                    732: 
1.487     albertel  733:     my $title.=
                    734: 	'<h3><span class="LC_info">'.
1.605     www       735: 	&mt('Verifying Receipt Number [_1]',$receipt).
                    736: 	'</span></h3>'."\n";
1.44      ng        737: 
                    738:     my ($string,$contents,$matches) = ('','',0);
1.56      matthew   739:     my (undef,undef,$fullname) = &getclasslist('all','0');
1.177     albertel  740:     
                    741:     my $receiptparts=0;
1.390     albertel  742:     if ($env{"course.$courseid.receiptalg"} eq 'receipt2' ||
                    743: 	$env{"course.$courseid.receiptalg"} eq 'receipt3') { $receiptparts=1; }
1.177     albertel  744:     my $parts=['0'];
1.582     raeburn   745:     if ($receiptparts) {
                    746:         my $res_error; 
                    747:         ($parts)=&response_type($symb,\$res_error);
                    748:         if ($res_error) {
                    749:             return &navmap_errormsg();
                    750:         } 
                    751:     }
1.486     albertel  752:     
                    753:     my $header = 
                    754: 	&Apache::loncommon::start_data_table().
                    755: 	&Apache::loncommon::start_data_table_header_row().
1.487     albertel  756: 	'<th>&nbsp;'.&mt('Fullname').'&nbsp;</th>'."\n".
                    757: 	'<th>&nbsp;'.&mt('Username').'&nbsp;</th>'."\n".
                    758: 	'<th>&nbsp;'.&mt('Domain').'&nbsp;</th>';
1.486     albertel  759:     if ($receiptparts) {
1.487     albertel  760: 	$header.='<th>&nbsp;'.&mt('Problem Part').'&nbsp;</th>';
1.486     albertel  761:     }
                    762:     $header.=
                    763: 	&Apache::loncommon::end_data_table_header_row();
                    764: 
1.294     albertel  765:     foreach (sort 
                    766: 	     {
                    767: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                    768: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                    769: 		 }
                    770: 		 return $a cmp $b;
                    771: 	     } (keys(%$fullname))) {
1.44      ng        772: 	my ($uname,$udom)=split(/\:/);
1.177     albertel  773: 	foreach my $part (@$parts) {
                    774: 	    if ($receipt eq &Apache::lonnet::ireceipt($uname,$udom,$courseid,$symb,$part)) {
1.486     albertel  775: 		$contents.=
                    776: 		    &Apache::loncommon::start_data_table_row().
                    777: 		    '<td>&nbsp;'."\n".
1.177     albertel  778: 		    '<a href="javascript:viewOneStudent(\''.$uname.'\',\''.$udom.
1.417     albertel  779: 		    '\');" target="_self">'.$$fullname{$_}.'</a>&nbsp;</td>'."\n".
1.177     albertel  780: 		    '<td>&nbsp;'.$uname.'&nbsp;</td>'.
                    781: 		    '<td>&nbsp;'.$udom.'&nbsp;</td>';
                    782: 		if ($receiptparts) {
                    783: 		    $contents.='<td>&nbsp;'.$part.'&nbsp;</td>';
                    784: 		}
1.486     albertel  785: 		$contents.= 
                    786: 		    &Apache::loncommon::end_data_table_row()."\n";
1.177     albertel  787: 		
                    788: 		$matches++;
                    789: 	    }
1.44      ng        790: 	}
                    791:     }
                    792:     if ($matches == 0) {
1.584     bisitz    793:         $string = $title
                    794:                  .'<p class="LC_warning">'
                    795:                  .&mt('No match found for the above receipt number.')
                    796:                  .'</p>';
1.44      ng        797:     } else {
1.324     albertel  798: 	$string = &jscriptNform($symb).$title.
1.487     albertel  799: 	    '<p>'.
1.584     bisitz    800: 	    &mt('The above receipt number matches the following [quant,_1,student].',$matches).
1.487     albertel  801: 	    '</p>'.
1.486     albertel  802: 	    $header.
                    803: 	    $contents.
                    804: 	    &Apache::loncommon::end_data_table()."\n";
1.44      ng        805:     }
1.614     www       806:     return $string;
1.44      ng        807: }
                    808: 
                    809: #--- This is called by a number of programs.
                    810: #--- Called from the Grading Menu - View/Grade an individual student
                    811: #--- Also called directly when one clicks on the subm button 
                    812: #    on the problem page.
1.30      ng        813: sub listStudents {
1.617     www       814:     my ($request,$symb,$submitonly) = @_;
1.49      albertel  815: 
1.257     albertel  816:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
                    817:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
                    818:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
1.449     banghart  819:     my $getgroup  = $env{'form.group'} eq '' ? 'all' : $env{'form.group'};
1.617     www       820:     unless ($submitonly) {
                    821:        $submitonly= $env{'form.submitonly'} eq '' ? 'all' : $env{'form.submitonly'};
                    822:     }
1.49      albertel  823: 
1.632     www       824:     my $result='';
1.623     www       825:     my $res_error;
                    826:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
1.49      albertel  827: 
1.559     raeburn   828:     my %lt = &Apache::lonlocal::texthash (
                    829: 		'multiple' => 'Please select a student or group of students before clicking on the Next button.',
                    830: 		'single'   => 'Please select the student before clicking on the Next button.',
                    831: 	     );
1.597     wenzelju  832:     $request->print(&Apache::lonhtmlcommon::scripttag(<<LISTJAVASCRIPT));
1.110     ng        833:     function checkSelect(checkBox) {
                    834: 	var ctr=0;
                    835: 	var sense="";
                    836: 	if (checkBox.length > 1) {
                    837: 	    for (var i=0; i<checkBox.length; i++) {
                    838: 		if (checkBox[i].checked) {
                    839: 		    ctr++;
                    840: 		}
                    841: 	    }
1.485     albertel  842: 	    sense = '$lt{'multiple'}';
1.110     ng        843: 	} else {
                    844: 	    if (checkBox.checked) {
                    845: 		ctr = 1;
                    846: 	    }
1.485     albertel  847: 	    sense = '$lt{'single'}';
1.110     ng        848: 	}
                    849: 	if (ctr == 0) {
1.485     albertel  850: 	    alert(sense);
1.110     ng        851: 	    return false;
                    852: 	}
                    853: 	document.gradesub.submit();
                    854:     }
                    855: 
                    856:     function reLoadList(formname) {
1.112     ng        857: 	if (formname.saveStatusOld.value == pullDownSelection(formname.Status)) {return;}
1.110     ng        858: 	formname.command.value = 'submission';
                    859: 	formname.submit();
                    860:     }
1.45      ng        861: LISTJAVASCRIPT
                    862: 
1.118     ng        863:     &commonJSfunctions($request);
1.41      ng        864:     $request->print($result);
1.39      ng        865: 
1.154     albertel  866:     my $gradeTable='<form action="/adm/grades" method="post" name="gradesub">'.
1.598     www       867: 	"\n";
1.485     albertel  868: 	
1.561     bisitz    869:     $gradeTable .= &Apache::lonhtmlcommon::start_pick_box();
                    870:     $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('View Problem Text'))
                    871:                   .'<label><input type="radio" name="vProb" value="no" checked="checked" /> '.&mt('no').' </label>'."\n"
                    872:                   .'<label><input type="radio" name="vProb" value="yes" /> '.&mt('one student').' </label>'."\n"
                    873:                   .'<label><input type="radio" name="vProb" value="all" /> '.&mt('all students').' </label><br />'."\n"
                    874:                   .&Apache::lonhtmlcommon::row_closure();
                    875:     $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('View Answer'))
                    876:                   .'<label><input type="radio" name="vAns" value="no"  /> '.&mt('no').' </label>'."\n"
                    877:                   .'<label><input type="radio" name="vAns" value="yes" /> '.&mt('one student').' </label>'."\n"
                    878:                   .'<label><input type="radio" name="vAns" value="all" checked="checked" /> '.&mt('all students').' </label><br />'."\n"
                    879:                   .&Apache::lonhtmlcommon::row_closure();
1.485     albertel  880: 
                    881:     my $submission_options;
1.442     banghart  882:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
                    883:     my $saveStatus = $stu_status eq '' ? 'Active' : $stu_status;
1.257     albertel  884:     $env{'form.Status'} = $saveStatus;
1.485     albertel  885:     $submission_options.=
1.592     bisitz    886:         '<span class="LC_nobreak">'.
1.624     www       887:         '<label><input type="radio" name="lastSub" value="lastonly" /> '.
1.592     bisitz    888:         &mt('last submission only').' </label></span>'."\n".
                    889:         '<span class="LC_nobreak">'.
                    890:         '<label><input type="radio" name="lastSub" value="last" /> '.
                    891:         &mt('last submission &amp; parts info').' </label></span>'."\n".
                    892:         '<span class="LC_nobreak">'.
1.628     www       893:         '<label><input type="radio" name="lastSub" value="datesub" checked="checked" /> '.
1.592     bisitz    894:         &mt('by dates and submissions').'</label></span>'."\n".
                    895:         '<span class="LC_nobreak">'.
                    896:         '<label><input type="radio" name="lastSub" value="all" /> '.
                    897:         &mt('all details').'</label></span>';
1.561     bisitz    898:     $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('Submissions'))
                    899:                   .$submission_options
                    900:                   .&Apache::lonhtmlcommon::row_closure();
                    901: 
                    902:     $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('Grading Increments'))
                    903:                   .'<select name="increment">'
                    904:                   .'<option value="1">'.&mt('Whole Points').'</option>'
                    905:                   .'<option value=".5">'.&mt('Half Points').'</option>'
                    906:                   .'<option value=".25">'.&mt('Quarter Points').'</option>'
                    907:                   .'<option value=".1">'.&mt('Tenths of a Point').'</option>'
                    908:                   .'</select>'
                    909:                   .&Apache::lonhtmlcommon::row_closure();
1.485     albertel  910: 
                    911:     $gradeTable .= 
1.432     banghart  912:         &build_section_inputs().
1.45      ng        913: 	'<input type="hidden" name="submitonly"  value="'.$submitonly.'" />'."\n".
1.418     albertel  914: 	'<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.110     ng        915: 	'<input type="hidden" name="saveStatusOld" value="'.$saveStatus.'" />'."\n";
                    916: 
1.618     www       917:     if (exists($env{'form.Status'})) {
1.561     bisitz    918: 	$gradeTable .= '<input type="hidden" name="Status" value="'.$stu_status.'" />'."\n";
1.124     ng        919:     } else {
1.561     bisitz    920:         $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('Student Status'))
                    921:                       .&Apache::lonhtmlcommon::StatusOptions(
                    922:                            $saveStatus,undef,1,'javascript:reLoadList(this.form);')
                    923:                       .&Apache::lonhtmlcommon::row_closure();
1.124     ng        924:     }
1.112     ng        925: 
1.561     bisitz    926:     $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('Check For Plagiarism'))
                    927:                   .'<input type="checkbox" name="checkPlag" checked="checked" />'
                    928:                   .&Apache::lonhtmlcommon::row_closure(1)
                    929:                   .&Apache::lonhtmlcommon::end_pick_box();
                    930: 
                    931:     $gradeTable .= '<p>'
1.618     www       932:                   .&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    933:                   .'<input type="hidden" name="command" value="processGroup" />'
                    934:                   .'</p>';
1.249     albertel  935: 
                    936: # checkall buttons
                    937:     $gradeTable.=&check_script('gradesub', 'stuinfo');
1.110     ng        938:     $gradeTable.='<input type="button" '."\n".
1.589     bisitz    939:         'onclick="javascript:checkSelect(this.form.stuinfo);" '."\n".
                    940:         'value="'.&mt('Next').' &rarr;" /> <br />'."\n";
1.249     albertel  941:     $gradeTable.=&check_buttons();
1.450     banghart  942:     my ($classlist, undef, $fullname) = &getclasslist($getsec,'1',$getgroup);
1.474     albertel  943:     $gradeTable.= &Apache::loncommon::start_data_table().
                    944: 	&Apache::loncommon::start_data_table_header_row();
1.110     ng        945:     my $loop = 0;
                    946:     while ($loop < 2) {
1.485     albertel  947: 	$gradeTable.='<th>'.&mt('No.').'</th><th>'.&mt('Select').'</th>'.
                    948: 	    '<th>'.&nameUserString('header').'&nbsp;'.&mt('Section/Group').'</th>';
1.618     www       949: 	if (($submitonly ne 'queued') && ($submitonly ne 'all')) {
1.485     albertel  950: 	    foreach my $part (sort(@$partlist)) {
                    951: 		my $display_part=
                    952: 		    &get_display_part((split(/_/,$part))[0],$symb);
                    953: 		$gradeTable.=
                    954: 		    '<th>'.&mt('Part: [_1] Status',$display_part).'</th>';
1.110     ng        955: 	    }
1.301     albertel  956: 	} elsif ($submitonly eq 'queued') {
1.474     albertel  957: 	    $gradeTable.='<th>'.&mt('Queue Status').'&nbsp;</th>';
1.110     ng        958: 	}
                    959: 	$loop++;
1.126     ng        960: #	$gradeTable.='<td></td>' if ($loop%2 ==1);
1.41      ng        961:     }
1.474     albertel  962:     $gradeTable.=&Apache::loncommon::end_data_table_header_row()."\n";
1.41      ng        963: 
1.45      ng        964:     my $ctr = 0;
1.294     albertel  965:     foreach my $student (sort 
                    966: 			 {
                    967: 			     if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                    968: 				 return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                    969: 			     }
                    970: 			     return $a cmp $b;
                    971: 			 }
                    972: 			 (keys(%$fullname))) {
1.41      ng        973: 	my ($uname,$udom) = split(/:/,$student);
1.301     albertel  974: 
1.110     ng        975: 	my %status = ();
1.301     albertel  976: 
                    977: 	if ($submitonly eq 'queued') {
                    978: 	    my %queue_status = 
                    979: 		&Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
                    980: 							$udom,$uname);
                    981: 	    next if (!defined($queue_status{'gradingqueue'}));
                    982: 	    $status{'gradingqueue'} = $queue_status{'gradingqueue'};
                    983: 	}
                    984: 
1.618     www       985: 	if (($submitonly ne 'queued') && ($submitonly ne 'all')) {
1.324     albertel  986: 	    (%status) =&student_gradeStatus($symb,$udom,$uname,$partlist);
1.145     albertel  987: 	    my $submitted = 0;
1.164     albertel  988: 	    my $graded = 0;
1.248     albertel  989: 	    my $incorrect = 0;
1.110     ng        990: 	    foreach (keys(%status)) {
1.145     albertel  991: 		$submitted = 1 if ($status{$_} ne 'nothing');
1.248     albertel  992: 		$graded = 1 if ($status{$_} =~ /^ungraded/);
                    993: 		$incorrect = 1 if ($status{$_} =~ /^incorrect/);
                    994: 		
1.110     ng        995: 		my ($foo,$partid,$foo1) = split(/\./,$_);
                    996: 		if ($status{'resource.'.$partid.'.submitted_by'} ne '') {
1.145     albertel  997: 		    $submitted = 0;
1.150     albertel  998: 		    my ($part)=split(/\./,$partid);
1.110     ng        999: 		    $gradeTable.='<input type="hidden" name="'.
1.150     albertel 1000: 			$student.':'.$part.':submitted_by" value="'.
1.110     ng       1001: 			$status{'resource.'.$partid.'.submitted_by'}.'" />';
                   1002: 		}
1.41      ng       1003: 	    }
1.248     albertel 1004: 	    
1.156     albertel 1005: 	    next if (!$submitted && ($submitonly eq 'yes' ||
                   1006: 				     $submitonly eq 'incorrect' ||
                   1007: 				     $submitonly eq 'graded'));
1.248     albertel 1008: 	    next if (!$graded && ($submitonly eq 'graded'));
                   1009: 	    next if (!$incorrect && $submitonly eq 'incorrect');
1.41      ng       1010: 	}
1.34      ng       1011: 
1.45      ng       1012: 	$ctr++;
1.249     albertel 1013: 	my $section = $classlist->{$student}->[&Apache::loncoursedata::CL_SECTION()];
1.452     banghart 1014:         my $group = $classlist->{$student}->[&Apache::loncoursedata::CL_GROUP()];
1.104     albertel 1015: 	if ( $perm{'vgr'} eq 'F' ) {
1.474     albertel 1016: 	    if ($ctr%2 ==1) {
                   1017: 		$gradeTable.= &Apache::loncommon::start_data_table_row();
                   1018: 	    }
1.126     ng       1019: 	    $gradeTable.='<td align="right">'.$ctr.'&nbsp;</td>'.
1.563     bisitz   1020:                '<td align="center"><label><input type="checkbox" name="stuinfo" value="'.
1.249     albertel 1021:                $student.':'.$$fullname{$student}.':::SECTION'.$section.
                   1022: 	       ')&nbsp;" />&nbsp;&nbsp;</label></td>'."\n".'<td>'.
                   1023: 	       &nameUserString(undef,$$fullname{$student},$uname,$udom).
1.474     albertel 1024: 	       '&nbsp;'.$section.($group ne '' ?'/'.$group:'').'</td>'."\n";
1.110     ng       1025: 
1.618     www      1026: 	    if ($submitonly ne 'all') {
1.524     raeburn  1027: 		foreach (sort(keys(%status))) {
1.485     albertel 1028: 		    next if ($_ =~ /^resource.*?submitted_by$/);
                   1029: 		    $gradeTable.='<td align="center">&nbsp;'.&mt($status{$_}).'&nbsp;</td>'."\n";
1.110     ng       1030: 		}
1.41      ng       1031: 	    }
1.126     ng       1032: #	    $gradeTable.='<td></td>' if ($ctr%2 ==1);
1.474     albertel 1033: 	    if ($ctr%2 ==0) {
                   1034: 		$gradeTable.=&Apache::loncommon::end_data_table_row()."\n";
                   1035: 	    }
1.41      ng       1036: 	}
                   1037:     }
1.110     ng       1038:     if ($ctr%2 ==1) {
1.126     ng       1039: 	$gradeTable.='<td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td>';
1.618     www      1040: 	    if (($submitonly ne 'queued') && ($submitonly ne 'all')) {
1.110     ng       1041: 		foreach (@$partlist) {
                   1042: 		    $gradeTable.='<td>&nbsp;</td>';
                   1043: 		}
1.301     albertel 1044: 	    } elsif ($submitonly eq 'queued') {
                   1045: 		$gradeTable.='<td>&nbsp;</td>';
1.110     ng       1046: 	    }
1.474     albertel 1047: 	$gradeTable.=&Apache::loncommon::end_data_table_row();
1.110     ng       1048:     }
                   1049: 
1.474     albertel 1050:     $gradeTable.=&Apache::loncommon::end_data_table()."\n".
1.589     bisitz   1051:         '<input type="button" '.
                   1052:         'onclick="javascript:checkSelect(this.form.stuinfo);" '.
                   1053:         'value="'.&mt('Next').' &rarr;" /></form>'."\n";
1.45      ng       1054:     if ($ctr == 0) {
1.96      albertel 1055: 	my $num_students=(scalar(keys(%$fullname)));
                   1056: 	if ($num_students eq 0) {
1.485     albertel 1057: 	    $gradeTable='<br />&nbsp;<span class="LC_warning">'.&mt('There are no students currently enrolled.').'</span>';
1.96      albertel 1058: 	} else {
1.171     albertel 1059: 	    my $submissions='submissions';
                   1060: 	    if ($submitonly eq 'incorrect') { $submissions = 'incorrect submissions'; }
                   1061: 	    if ($submitonly eq 'graded'   ) { $submissions = 'ungraded submissions'; }
1.301     albertel 1062: 	    if ($submitonly eq 'queued'   ) { $submissions = 'queued submissions'; }
1.398     albertel 1063: 	    $gradeTable='<br />&nbsp;<span class="LC_warning">'.
1.485     albertel 1064: 		&mt('No '.$submissions.' found for this resource for any students. ([_1] students checked for '.$submissions.')',
                   1065: 		    $num_students).
                   1066: 		'</span><br />';
1.96      albertel 1067: 	}
1.46      ng       1068:     } elsif ($ctr == 1) {
1.474     albertel 1069: 	$gradeTable =~ s/type="checkbox"/type="checkbox" checked="checked"/;
1.45      ng       1070:     }
                   1071:     $request->print($gradeTable);
1.44      ng       1072:     return '';
1.10      ng       1073: }
                   1074: 
1.44      ng       1075: #---- Called from the listStudents routine
1.249     albertel 1076: 
                   1077: sub check_script {
                   1078:     my ($form, $type)=@_;
1.597     wenzelju 1079:     my $chkallscript= &Apache::lonhtmlcommon::scripttag('
1.249     albertel 1080:     function checkall() {
                   1081:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
                   1082:             ele = document.forms.'.$form.'.elements[i];
                   1083:             if (ele.name == "'.$type.'") {
                   1084:             document.forms.'.$form.'.elements[i].checked=true;
                   1085:                                        }
                   1086:         }
                   1087:     }
                   1088: 
                   1089:     function checksec() {
                   1090:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
                   1091:             ele = document.forms.'.$form.'.elements[i];
                   1092:            string = document.forms.'.$form.'.chksec.value;
                   1093:            if
                   1094:           (ele.value.indexOf(":::SECTION"+string)>0) {
                   1095:               document.forms.'.$form.'.elements[i].checked=true;
                   1096:             }
                   1097:         }
                   1098:     }
                   1099: 
                   1100: 
                   1101:     function uncheckall() {
                   1102:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
                   1103:             ele = document.forms.'.$form.'.elements[i];
                   1104:             if (ele.name == "'.$type.'") {
                   1105:             document.forms.'.$form.'.elements[i].checked=false;
                   1106:                                        }
                   1107:         }
                   1108:     }
                   1109: 
1.597     wenzelju 1110: '."\n");
1.249     albertel 1111:     return $chkallscript;
                   1112: }
                   1113: 
                   1114: sub check_buttons {
1.485     albertel 1115:     my $buttons.='<input type="button" onclick="checkall()" value="'.&mt('Check All').'" />';
                   1116:     $buttons.='<input type="button" onclick="uncheckall()" value="'.&mt('Uncheck All').'" />&nbsp;';
                   1117:     $buttons.='<input type="button" onclick="checksec()" value="'.&mt('Check Section/Group').'" />';
1.249     albertel 1118:     $buttons.='<input type="text" size="5" name="chksec" />&nbsp;';
                   1119:     return $buttons;
                   1120: }
                   1121: 
1.44      ng       1122: #     Displays the submissions for one student or a group of students
1.34      ng       1123: sub processGroup {
1.619     www      1124:     my ($request,$symb)  = @_;
1.41      ng       1125:     my $ctr        = 0;
1.155     albertel 1126:     my @stuchecked = &Apache::loncommon::get_env_multiple('form.stuinfo');
1.41      ng       1127:     my $total      = scalar(@stuchecked)-1;
1.45      ng       1128: 
1.396     banghart 1129:     foreach my $student (@stuchecked) {
                   1130: 	my ($uname,$udom,$fullname) = split(/:/,$student);
1.257     albertel 1131: 	$env{'form.student'}        = $uname;
                   1132: 	$env{'form.userdom'}        = $udom;
                   1133: 	$env{'form.fullname'}       = $fullname;
1.619     www      1134: 	&submission($request,$ctr,$total,$symb);
1.41      ng       1135: 	$ctr++;
                   1136:     }
                   1137:     return '';
1.35      ng       1138: }
1.34      ng       1139: 
1.44      ng       1140: #------------------------------------------------------------------------------------
                   1141: #
                   1142: #-------------------------- Next few routines handles grading by student, essentially
                   1143: #                           handles essay response type problem/part
                   1144: #
                   1145: #--- Javascript to handle the submission page functionality ---
                   1146: sub sub_page_js {
                   1147:     my $request = shift;
1.539     riegler  1148: 	    my $alertmsg = &mt('A number equal or greater than 0 is expected. Entered value = ');
1.597     wenzelju 1149:     $request->print(&Apache::lonhtmlcommon::scripttag(<<SUBJAVASCRIPT));
1.71      ng       1150:     function updateRadio(formname,id,weight) {
1.125     ng       1151: 	var gradeBox = formname["GD_BOX"+id];
                   1152: 	var radioButton = formname["RADVAL"+id];
                   1153: 	var oldpts = formname["oldpts"+id].value;
1.72      ng       1154: 	var pts = checkSolved(formname,id) == 'update' ? gradeBox.value : oldpts;
1.71      ng       1155: 	gradeBox.value = pts;
                   1156: 	var resetbox = false;
                   1157: 	if (isNaN(pts) || pts < 0) {
1.539     riegler  1158: 	    alert("$alertmsg"+pts);
1.71      ng       1159: 	    for (var i=0; i<radioButton.length; i++) {
                   1160: 		if (radioButton[i].checked) {
                   1161: 		    gradeBox.value = i;
                   1162: 		    resetbox = true;
                   1163: 		}
                   1164: 	    }
                   1165: 	    if (!resetbox) {
                   1166: 		formtextbox.value = "";
                   1167: 	    }
                   1168: 	    return;
1.44      ng       1169: 	}
1.71      ng       1170: 
                   1171: 	if (pts > weight) {
                   1172: 	    var resp = confirm("You entered a value ("+pts+
                   1173: 			       ") greater than the weight for the part. Accept?");
                   1174: 	    if (resp == false) {
1.125     ng       1175: 		gradeBox.value = oldpts;
1.71      ng       1176: 		return;
                   1177: 	    }
1.44      ng       1178: 	}
1.13      albertel 1179: 
1.71      ng       1180: 	for (var i=0; i<radioButton.length; i++) {
                   1181: 	    radioButton[i].checked=false;
                   1182: 	    if (pts == i && pts != "") {
                   1183: 		radioButton[i].checked=true;
                   1184: 	    }
                   1185: 	}
                   1186: 	updateSelect(formname,id);
1.125     ng       1187: 	formname["stores"+id].value = "0";
1.41      ng       1188:     }
1.5       albertel 1189: 
1.72      ng       1190:     function writeBox(formname,id,pts) {
1.125     ng       1191: 	var gradeBox = formname["GD_BOX"+id];
1.71      ng       1192: 	if (checkSolved(formname,id) == 'update') {
                   1193: 	    gradeBox.value = pts;
                   1194: 	} else {
1.125     ng       1195: 	    var oldpts = formname["oldpts"+id].value;
1.72      ng       1196: 	    gradeBox.value = oldpts;
1.125     ng       1197: 	    var radioButton = formname["RADVAL"+id];
1.71      ng       1198: 	    for (var i=0; i<radioButton.length; i++) {
                   1199: 		radioButton[i].checked=false;
1.72      ng       1200: 		if (i == oldpts) {
1.71      ng       1201: 		    radioButton[i].checked=true;
                   1202: 		}
                   1203: 	    }
1.41      ng       1204: 	}
1.125     ng       1205: 	formname["stores"+id].value = "0";
1.71      ng       1206: 	updateSelect(formname,id);
                   1207: 	return;
1.41      ng       1208:     }
1.44      ng       1209: 
1.71      ng       1210:     function clearRadBox(formname,id) {
                   1211: 	if (checkSolved(formname,id) == 'noupdate') {
                   1212: 	    updateSelect(formname,id);
                   1213: 	    return;
                   1214: 	}
1.125     ng       1215: 	gradeSelect = formname["GD_SEL"+id];
1.71      ng       1216: 	for (var i=0; i<gradeSelect.length; i++) {
                   1217: 	    if (gradeSelect[i].selected) {
                   1218: 		var selectx=i;
                   1219: 	    }
                   1220: 	}
1.125     ng       1221: 	var stores = formname["stores"+id];
1.71      ng       1222: 	if (selectx == stores.value) { return };
1.125     ng       1223: 	var gradeBox = formname["GD_BOX"+id];
1.71      ng       1224: 	gradeBox.value = "";
1.125     ng       1225: 	var radioButton = formname["RADVAL"+id];
1.71      ng       1226: 	for (var i=0; i<radioButton.length; i++) {
                   1227: 	    radioButton[i].checked=false;
                   1228: 	}
                   1229: 	stores.value = selectx;
                   1230:     }
1.5       albertel 1231: 
1.71      ng       1232:     function checkSolved(formname,id) {
1.125     ng       1233: 	if (formname["solved"+id].value == "correct_by_student" && formname.overRideScore.value == 'no') {
1.118     ng       1234: 	    var reply = confirm("This problem has been graded correct by the computer. Do you want to change the score?");
                   1235: 	    if (!reply) {return "noupdate";}
1.120     ng       1236: 	    formname.overRideScore.value = 'yes';
1.41      ng       1237: 	}
1.71      ng       1238: 	return "update";
1.13      albertel 1239:     }
1.71      ng       1240: 
                   1241:     function updateSelect(formname,id) {
1.125     ng       1242: 	formname["GD_SEL"+id][0].selected = true;
1.71      ng       1243: 	return;
1.41      ng       1244:     }
1.33      ng       1245: 
1.121     ng       1246: //=========== Check that a point is assigned for all the parts  ============
1.71      ng       1247:     function checksubmit(formname,val,total,parttot) {
1.121     ng       1248: 	formname.gradeOpt.value = val;
1.71      ng       1249: 	if (val == "Save & Next") {
                   1250: 	    for (i=0;i<=total;i++) {
                   1251: 		for (j=0;j<parttot;j++) {
1.125     ng       1252: 		    var partid = formname["partid"+i+"_"+j].value;
1.127     ng       1253: 		    if (formname["GD_SEL"+i+"_"+partid][0].selected) {
1.125     ng       1254: 			var points = formname["GD_BOX"+i+"_"+partid].value;
1.71      ng       1255: 			if (points == "") {
1.125     ng       1256: 			    var name = formname["name"+i].value;
1.129     ng       1257: 			    var studentID = (name != '' ? name : formname["unamedom"+i].value);
                   1258: 			    var resp = confirm("You did not assign a score for "+studentID+
                   1259: 					       ", part "+partid+". Continue?");
1.71      ng       1260: 			    if (resp == false) {
1.125     ng       1261: 				formname["GD_BOX"+i+"_"+partid].focus();
1.71      ng       1262: 				return false;
                   1263: 			    }
                   1264: 			}
                   1265: 		    }
                   1266: 		    
                   1267: 		}
                   1268: 	    }
                   1269: 	    
                   1270: 	}
1.120     ng       1271: 	formname.submit();
                   1272:     }
                   1273: 
1.71      ng       1274: //======= Check that a score is assigned for all the problems (page/sequence grading only) =========
                   1275:     function checkSubmitPage(formname,total) {
                   1276: 	noscore = new Array(100);
                   1277: 	var ptr = 0;
                   1278: 	for (i=1;i<total;i++) {
1.125     ng       1279: 	    var partid = formname["q_"+i].value;
1.127     ng       1280: 	    if (formname["GD_SEL"+i+"_"+partid][0].selected) {
1.125     ng       1281: 		var points = formname["GD_BOX"+i+"_"+partid].value;
                   1282: 		var status = formname["solved"+i+"_"+partid].value;
1.71      ng       1283: 		if (points == "" && status != "correct_by_student") {
                   1284: 		    noscore[ptr] = i;
                   1285: 		    ptr++;
                   1286: 		}
                   1287: 	    }
                   1288: 	}
                   1289: 	if (ptr != 0) {
                   1290: 	    var sense = ptr == 1 ? ": " : "s: ";
                   1291: 	    var prolist = "";
                   1292: 	    if (ptr == 1) {
                   1293: 		prolist = noscore[0];
                   1294: 	    } else {
                   1295: 		var i = 0;
                   1296: 		while (i < ptr-1) {
                   1297: 		    prolist += noscore[i]+", ";
                   1298: 		    i++;
                   1299: 		}
                   1300: 		prolist += "and "+noscore[i];
                   1301: 	    }
                   1302: 	    var resp = confirm("You did not assign any score for the following problem"+sense+prolist+". Continue?");
                   1303: 	    if (resp == false) {
                   1304: 		return false;
                   1305: 	    }
                   1306: 	}
1.45      ng       1307: 
1.71      ng       1308: 	formname.submit();
                   1309:     }
                   1310: SUBJAVASCRIPT
                   1311: }
1.45      ng       1312: 
1.71      ng       1313: #--- javascript for essay type problem --
                   1314: sub sub_page_kw_js {
                   1315:     my $request = shift;
1.80      ng       1316:     my $iconpath = $request->dir_config('lonIconsURL');
1.118     ng       1317:     &commonJSfunctions($request);
1.350     albertel 1318: 
1.629     www      1319:     my $inner_js_msg_central= (<<INNERJS);
                   1320: <script type="text/javascript">
1.350     albertel 1321:     function checkInput() {
                   1322:       opener.document.SCORE.msgsub.value = opener.checkEntities(document.msgcenter.msgsub.value);
                   1323:       var nmsg   = opener.document.SCORE.savemsgN.value;
                   1324:       var usrctr = document.msgcenter.usrctr.value;
                   1325:       var newval = opener.document.SCORE["newmsg"+usrctr];
                   1326:       newval.value = opener.checkEntities(document.msgcenter.newmsg.value);
                   1327: 
                   1328:       var msgchk = "";
                   1329:       if (document.msgcenter.subchk.checked) {
                   1330:          msgchk = "msgsub,";
                   1331:       }
                   1332:       var includemsg = 0;
                   1333:       for (var i=1; i<=nmsg; i++) {
                   1334:           var opnmsg = opener.document.SCORE["savemsg"+i];
                   1335:           var frmmsg = document.msgcenter["msg"+i];
                   1336:           opnmsg.value = opener.checkEntities(frmmsg.value);
                   1337:           var showflg = opener.document.SCORE["shownOnce"+i];
                   1338:           showflg.value = "1";
                   1339:           var chkbox = document.msgcenter["msgn"+i];
                   1340:           if (chkbox.checked) {
                   1341:              msgchk += "savemsg"+i+",";
                   1342:              includemsg = 1;
                   1343:           }
                   1344:       }
                   1345:       if (document.msgcenter.newmsgchk.checked) {
                   1346:          msgchk += "newmsg"+usrctr;
                   1347:          includemsg = 1;
                   1348:       }
                   1349:       imgformname = opener.document.SCORE["mailicon"+usrctr];
                   1350:       imgformname.src = "$iconpath/"+((includemsg) ? "mailto.gif" : "mailbkgrd.gif");
                   1351:       var includemsg = opener.document.SCORE["includemsg"+usrctr];
                   1352:       includemsg.value = msgchk;
                   1353: 
                   1354:       self.close()
                   1355: 
                   1356:     }
1.629     www      1357: </script>
1.350     albertel 1358: INNERJS
                   1359: 
1.629     www      1360:     my $inner_js_highlight_central= (<<INNERJS);
                   1361: <script type="text/javascript">
1.351     albertel 1362:     function updateChoice(flag) {
                   1363:       opener.document.SCORE.kwclr.value = opener.radioSelection(document.hlCenter.kwdclr);
                   1364:       opener.document.SCORE.kwsize.value = opener.radioSelection(document.hlCenter.kwdsize);
                   1365:       opener.document.SCORE.kwstyle.value = opener.radioSelection(document.hlCenter.kwdstyle);
                   1366:       opener.document.SCORE.refresh.value = "on";
                   1367:       if (opener.document.SCORE.keywords.value!=""){
                   1368:          opener.document.SCORE.submit();
                   1369:       }
                   1370:       self.close()
                   1371:     }
1.629     www      1372: </script>
1.351     albertel 1373: INNERJS
                   1374: 
                   1375:     my $start_page_msg_central = 
                   1376:         &Apache::loncommon::start_page('Message Central',$inner_js_msg_central,
                   1377: 				       {'js_ready'  => 1,
                   1378: 					'only_body' => 1,
                   1379: 					'bgcolor'   =>'#FFFFFF',});
                   1380:     my $end_page_msg_central = 
                   1381: 	&Apache::loncommon::end_page({'js_ready' => 1});
                   1382: 
                   1383: 
                   1384:     my $start_page_highlight_central = 
                   1385:         &Apache::loncommon::start_page('Highlight Central',
                   1386: 				       $inner_js_highlight_central,
1.350     albertel 1387: 				       {'js_ready'  => 1,
                   1388: 					'only_body' => 1,
                   1389: 					'bgcolor'   =>'#FFFFFF',});
1.351     albertel 1390:     my $end_page_highlight_central = 
1.350     albertel 1391: 	&Apache::loncommon::end_page({'js_ready' => 1});
                   1392: 
1.219     www      1393:     my $docopen=&Apache::lonhtmlcommon::javascript_docopen();
1.236     albertel 1394:     $docopen=~s/^document\.//;
1.539     riegler  1395:     my $alertmsg = &mt('Please select a word or group of words from document and then click this link.');
1.597     wenzelju 1396:     $request->print(&Apache::lonhtmlcommon::scripttag(<<SUBJAVASCRIPT));
1.45      ng       1397: 
1.44      ng       1398: //===================== Show list of keywords ====================
1.122     ng       1399:   function keywords(formname) {
                   1400:     var nret = prompt("Keywords list, separated by a space. Add/delete to list if desired.",formname.keywords.value);
1.44      ng       1401:     if (nret==null) return;
1.122     ng       1402:     formname.keywords.value = nret;
1.44      ng       1403: 
1.122     ng       1404:     if (formname.keywords.value != "") {
1.128     ng       1405: 	formname.refresh.value = "on";
1.122     ng       1406: 	formname.submit();
1.44      ng       1407:     }
                   1408:     return;
                   1409:   }
                   1410: 
                   1411: //===================== Script to view submitted by ==================
                   1412:   function viewSubmitter(submitter) {
                   1413:     document.SCORE.refresh.value = "on";
                   1414:     document.SCORE.NCT.value = "1";
                   1415:     document.SCORE.unamedom0.value = submitter;
                   1416:     document.SCORE.submit();
                   1417:     return;
                   1418:   }
                   1419: 
                   1420: //===================== Script to add keyword(s) ==================
                   1421:   function getSel() {
                   1422:     if (document.getSelection) txt = document.getSelection();
                   1423:     else if (document.selection) txt = document.selection.createRange().text;
                   1424:     else return;
                   1425:     var cleantxt = txt.replace(new RegExp('([\\f\\n\\r\\t\\v ])+', 'g')," ");
                   1426:     if (cleantxt=="") {
1.539     riegler  1427: 	alert("$alertmsg");
1.44      ng       1428: 	return;
                   1429:     }
                   1430:     var nret = prompt("Add selection to keyword list? Edit if desired.",cleantxt);
                   1431:     if (nret==null) return;
1.127     ng       1432:     document.SCORE.keywords.value = document.SCORE.keywords.value+" "+nret;
1.44      ng       1433:     if (document.SCORE.keywords.value != "") {
1.127     ng       1434: 	document.SCORE.refresh.value = "on";
1.44      ng       1435: 	document.SCORE.submit();
                   1436:     }
                   1437:     return;
                   1438:   }
                   1439: 
                   1440: //====================== Script for composing message ==============
1.80      ng       1441:    // preload images
                   1442:    img1 = new Image();
                   1443:    img1.src = "$iconpath/mailbkgrd.gif";
                   1444:    img2 = new Image();
                   1445:    img2.src = "$iconpath/mailto.gif";
                   1446: 
1.44      ng       1447:   function msgCenter(msgform,usrctr,fullname) {
                   1448:     var Nmsg  = msgform.savemsgN.value;
                   1449:     savedMsgHeader(Nmsg,usrctr,fullname);
                   1450:     var subject = msgform.msgsub.value;
1.127     ng       1451:     var msgchk = document.SCORE["includemsg"+usrctr].value;
1.44      ng       1452:     re = /msgsub/;
                   1453:     var shwsel = "";
                   1454:     if (re.test(msgchk)) { shwsel = "checked" }
1.123     ng       1455:     subject = (document.SCORE.shownSub.value == 0 ? checkEntities(subject) : subject);
                   1456:     displaySubject(checkEntities(subject),shwsel);
1.44      ng       1457:     for (var i=1; i<=Nmsg; i++) {
1.123     ng       1458: 	var testmsg = "savemsg"+i+",";
                   1459: 	re = new RegExp(testmsg,"g");
1.44      ng       1460: 	shwsel = "";
                   1461: 	if (re.test(msgchk)) { shwsel = "checked" }
1.125     ng       1462: 	var message = document.SCORE["savemsg"+i].value;
1.126     ng       1463: 	message = (document.SCORE["shownOnce"+i].value == 0 ? checkEntities(message) : message);
1.123     ng       1464: 	displaySavedMsg(i,message,shwsel); //I do not get it. w/o checkEntities on saved messages,
                   1465: 	                                   //any &lt; is already converted to <, etc. However, only once!!
1.44      ng       1466:     }
1.125     ng       1467:     newmsg = document.SCORE["newmsg"+usrctr].value;
1.44      ng       1468:     shwsel = "";
                   1469:     re = /newmsg/;
                   1470:     if (re.test(msgchk)) { shwsel = "checked" }
                   1471:     newMsg(newmsg,shwsel);
                   1472:     msgTail(); 
                   1473:     return;
                   1474:   }
                   1475: 
1.123     ng       1476:   function checkEntities(strx) {
                   1477:     if (strx.length == 0) return strx;
                   1478:     var orgStr = ["&", "<", ">", '"']; 
                   1479:     var newStr = ["&amp;", "&lt;", "&gt;", "&quot;"];
                   1480:     var counter = 0;
                   1481:     while (counter < 4) {
                   1482: 	strx = strReplace(strx,orgStr[counter],newStr[counter]);
                   1483: 	counter++;
                   1484:     }
                   1485:     return strx;
                   1486:   }
                   1487: 
                   1488:   function strReplace(strx, orgStr, newStr) {
                   1489:     return strx.split(orgStr).join(newStr);
                   1490:   }
                   1491: 
1.44      ng       1492:   function savedMsgHeader(Nmsg,usrctr,fullname) {
1.76      ng       1493:     var height = 70*Nmsg+250;
1.44      ng       1494:     var scrollbar = "no";
                   1495:     if (height > 600) {
                   1496: 	height = 600;
                   1497: 	scrollbar = "yes";
                   1498:     }
1.118     ng       1499:     var xpos = (screen.width-600)/2;
                   1500:     xpos = (xpos < 0) ? '0' : xpos;
                   1501:     var ypos = (screen.height-height)/2-30;
                   1502:     ypos = (ypos < 0) ? '0' : ypos;
                   1503: 
1.206     albertel 1504:     pWin = window.open('', 'MessageCenter', 'resizable=yes,toolbar=no,location=no,scrollbars='+scrollbar+',screenx='+xpos+',screeny='+ypos+',width=600,height='+height);
1.76      ng       1505:     pWin.focus();
                   1506:     pDoc = pWin.document;
1.219     www      1507:     pDoc.$docopen;
1.351     albertel 1508:     pDoc.write('$start_page_msg_central');
1.76      ng       1509: 
                   1510:     pDoc.write("<form action=\\"inactive\\" name=\\"msgcenter\\">");
                   1511:     pDoc.write("<input value=\\""+usrctr+"\\" name=\\"usrctr\\" type=\\"hidden\\">");
1.465     albertel 1512:     pDoc.write("<h3><span class=\\"LC_info\\">&nbsp;Compose Message for \"+fullname+\"<\\/span><\\/h3><br /><br />");
1.76      ng       1513: 
1.564     bisitz   1514:     pDoc.write('<table border="0" width="100%"><tr><td bgcolor="#777777">');
                   1515:     pDoc.write('<table border="0" width="100%"><tr bgcolor="#DDFFFF">');
1.465     albertel 1516:     pDoc.write("<td><b>Type<\\/b><\\/td><td><b>Include<\\/b><\\/td><td><b>Message<\\/td><\\/tr>");
1.44      ng       1517: }
                   1518:     function displaySubject(msg,shwsel) {
1.76      ng       1519:     pDoc = pWin.document;
                   1520:     pDoc.write("<tr bgcolor=\\"#ffffdd\\">");
1.465     albertel 1521:     pDoc.write("<td>Subject<\\/td>");
                   1522:     pDoc.write("<td align=\\"center\\"><input name=\\"subchk\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
                   1523:     pDoc.write("<td><input name=\\"msgsub\\" type=\\"text\\" value=\\""+msg+"\\"size=\\"60\\" maxlength=\\"80\\"><\\/td><\\/tr>");
1.44      ng       1524: }
                   1525: 
1.72      ng       1526:   function displaySavedMsg(ctr,msg,shwsel) {
1.76      ng       1527:     pDoc = pWin.document;
                   1528:     pDoc.write("<tr bgcolor=\\"#ffffdd\\">");
1.465     albertel 1529:     pDoc.write("<td align=\\"center\\">"+ctr+"<\\/td>");
                   1530:     pDoc.write("<td align=\\"center\\"><input name=\\"msgn"+ctr+"\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
                   1531:     pDoc.write("<td><textarea name=\\"msg"+ctr+"\\" cols=\\"60\\" rows=\\"3\\">"+msg+"<\\/textarea><\\/td><\\/tr>");
1.44      ng       1532: }
                   1533: 
                   1534:   function newMsg(newmsg,shwsel) {
1.76      ng       1535:     pDoc = pWin.document;
                   1536:     pDoc.write("<tr bgcolor=\\"#ffffdd\\">");
1.465     albertel 1537:     pDoc.write("<td align=\\"center\\">New<\\/td>");
                   1538:     pDoc.write("<td align=\\"center\\"><input name=\\"newmsgchk\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
                   1539:     pDoc.write("<td><textarea name=\\"newmsg\\" cols=\\"60\\" rows=\\"3\\" onchange=\\"javascript:this.form.newmsgchk.checked=true\\" >"+newmsg+"<\\/textarea><\\/td><\\/tr>");
1.44      ng       1540: }
                   1541: 
                   1542:   function msgTail() {
1.76      ng       1543:     pDoc = pWin.document;
1.465     albertel 1544:     pDoc.write("<\\/table>");
                   1545:     pDoc.write("<\\/td><\\/tr><\\/table>&nbsp;");
1.589     bisitz   1546:     pDoc.write("<input type=\\"button\\" value=\\"Save\\" onclick=\\"javascript:checkInput()\\">&nbsp;&nbsp;");
                   1547:     pDoc.write("<input type=\\"button\\" value=\\"Cancel\\" onclick=\\"self.close()\\"><br /><br />");
1.465     albertel 1548:     pDoc.write("<\\/form>");
1.351     albertel 1549:     pDoc.write('$end_page_msg_central');
1.128     ng       1550:     pDoc.close();
1.44      ng       1551: }
                   1552: 
                   1553: //====================== Script for keyword highlight options ==============
                   1554:   function kwhighlight() {
                   1555:     var kwclr    = document.SCORE.kwclr.value;
                   1556:     var kwsize   = document.SCORE.kwsize.value;
                   1557:     var kwstyle  = document.SCORE.kwstyle.value;
                   1558:     var redsel = "";
                   1559:     var grnsel = "";
                   1560:     var blusel = "";
                   1561:     if (kwclr=="red")   {var redsel="checked"};
                   1562:     if (kwclr=="green") {var grnsel="checked"};
                   1563:     if (kwclr=="blue")  {var blusel="checked"};
                   1564:     var sznsel = "";
                   1565:     var sz1sel = "";
                   1566:     var sz2sel = "";
                   1567:     if (kwsize=="0")  {var sznsel="checked"};
                   1568:     if (kwsize=="+1") {var sz1sel="checked"};
                   1569:     if (kwsize=="+2") {var sz2sel="checked"};
                   1570:     var synsel = "";
                   1571:     var syisel = "";
                   1572:     var sybsel = "";
                   1573:     if (kwstyle=="")    {var synsel="checked"};
                   1574:     if (kwstyle=="<i>") {var syisel="checked"};
                   1575:     if (kwstyle=="<b>") {var sybsel="checked"};
                   1576:     highlightCentral();
                   1577:     highlightbody('red','red',redsel,'0','normal',sznsel,'','normal',synsel);
                   1578:     highlightbody('green','green',grnsel,'+1','+1',sz1sel,'<i>','italic',syisel);
                   1579:     highlightbody('blue','blue',blusel,'+2','+2',sz2sel,'<b>','bold',sybsel);
                   1580:     highlightend();
                   1581:     return;
                   1582:   }
                   1583: 
                   1584:   function highlightCentral() {
1.76      ng       1585: //    if (window.hwdWin) window.hwdWin.close();
1.118     ng       1586:     var xpos = (screen.width-400)/2;
                   1587:     xpos = (xpos < 0) ? '0' : xpos;
                   1588:     var ypos = (screen.height-330)/2-30;
                   1589:     ypos = (ypos < 0) ? '0' : ypos;
                   1590: 
1.206     albertel 1591:     hwdWin = window.open('', 'KeywordHighlightCentral', 'resizeable=yes,toolbar=no,location=no,scrollbars=no,width=400,height=300,screenx='+xpos+',screeny='+ypos);
1.76      ng       1592:     hwdWin.focus();
                   1593:     var hDoc = hwdWin.document;
1.219     www      1594:     hDoc.$docopen;
1.351     albertel 1595:     hDoc.write('$start_page_highlight_central');
1.76      ng       1596:     hDoc.write("<form action=\\"inactive\\" name=\\"hlCenter\\">");
1.465     albertel 1597:     hDoc.write("<h3><span class=\\"LC_info\\">&nbsp;Keyword Highlight Options<\\/span><\\/h3><br /><br />");
1.76      ng       1598: 
1.564     bisitz   1599:     hDoc.write('<table border="0" width="100%"><tr><td bgcolor="#777777">');
                   1600:     hDoc.write('<table border="0" width="100%"><tr bgcolor="#DDFFFF">');
1.465     albertel 1601:     hDoc.write("<td><b>Text Color<\\/b><\\/td><td><b>Font Size<\\/b><\\/td><td><b>Font Style<\\/td><\\/tr>");
1.44      ng       1602:   }
                   1603: 
                   1604:   function highlightbody(clrval,clrtxt,clrsel,szval,sztxt,szsel,syval,sytxt,sysel) { 
1.76      ng       1605:     var hDoc = hwdWin.document;
                   1606:     hDoc.write("<tr bgcolor=\\"#ffffdd\\">");
                   1607:     hDoc.write("<td align=\\"left\\">");
1.465     albertel 1608:     hDoc.write("<input name=\\"kwdclr\\" type=\\"radio\\" value=\\""+clrval+"\\" "+clrsel+">&nbsp;"+clrtxt+"<\\/td>");
1.76      ng       1609:     hDoc.write("<td align=\\"left\\">");
1.465     albertel 1610:     hDoc.write("<input name=\\"kwdsize\\" type=\\"radio\\" value=\\""+szval+"\\" "+szsel+">&nbsp;"+sztxt+"<\\/td>");
1.76      ng       1611:     hDoc.write("<td align=\\"left\\">");
1.465     albertel 1612:     hDoc.write("<input name=\\"kwdstyle\\" type=\\"radio\\" value=\\""+syval+"\\" "+sysel+">&nbsp;"+sytxt+"<\\/td>");
                   1613:     hDoc.write("<\\/tr>");
1.44      ng       1614:   }
                   1615: 
                   1616:   function highlightend() { 
1.76      ng       1617:     var hDoc = hwdWin.document;
1.465     albertel 1618:     hDoc.write("<\\/table>");
                   1619:     hDoc.write("<\\/td><\\/tr><\\/table>&nbsp;");
1.589     bisitz   1620:     hDoc.write("<input type=\\"button\\" value=\\"Save\\" onclick=\\"javascript:updateChoice(1)\\">&nbsp;&nbsp;");
                   1621:     hDoc.write("<input type=\\"button\\" value=\\"Cancel\\" onclick=\\"self.close()\\"><br /><br />");
1.465     albertel 1622:     hDoc.write("<\\/form>");
1.351     albertel 1623:     hDoc.write('$end_page_highlight_central');
1.128     ng       1624:     hDoc.close();
1.44      ng       1625:   }
                   1626: 
                   1627: SUBJAVASCRIPT
                   1628: }
                   1629: 
1.349     albertel 1630: sub get_increment {
1.348     bowersj2 1631:     my $increment = $env{'form.increment'};
                   1632:     if ($increment != 1 && $increment != .5 && $increment != .25 &&
                   1633:         $increment != .1) {
                   1634:         $increment = 1;
                   1635:     }
                   1636:     return $increment;
                   1637: }
                   1638: 
1.585     bisitz   1639: sub gradeBox_start {
                   1640:     return (
                   1641:         &Apache::loncommon::start_data_table()
                   1642:        .&Apache::loncommon::start_data_table_header_row()
                   1643:        .'<th>'.&mt('Part').'</th>'
                   1644:        .'<th>'.&mt('Points').'</th>'
                   1645:        .'<th>&nbsp;</th>'
                   1646:        .'<th>'.&mt('Assign Grade').'</th>'
                   1647:        .'<th>'.&mt('Weight').'</th>'
                   1648:        .'<th>'.&mt('Grade Status').'</th>'
                   1649:        .&Apache::loncommon::end_data_table_header_row()
                   1650:     );
                   1651: }
                   1652: 
                   1653: sub gradeBox_end {
                   1654:     return (
                   1655:         &Apache::loncommon::end_data_table()
                   1656:     );
                   1657: }
1.71      ng       1658: #--- displays the grading box, used in essay type problem and grading by page/sequence
                   1659: sub gradeBox {
1.322     albertel 1660:     my ($request,$symb,$uname,$udom,$counter,$partid,$record) = @_;
1.381     albertel 1661:     my $checkIcon = '<img alt="'.&mt('Check Mark').
1.485     albertel 1662: 	'" src="'.&Apache::loncommon::lonhttpdurl($request->dir_config('lonIconsURL').'/check.gif').'" height="16" border="0" />';
1.71      ng       1663:     my $wgt    = &Apache::lonnet::EXT('resource.'.$partid.'.weight',$symb,$udom,$uname);
1.466     albertel 1664:     my $wgtmsg = ($wgt > 0) ? &mt('(problem weight)') 
                   1665:                            : '<span class="LC_info">'.&mt('problem weight assigned by computer').'</span>';
1.71      ng       1666:     $wgt       = ($wgt > 0 ? $wgt : '1');
                   1667:     my $score  = ($$record{'resource.'.$partid.'.awarded'} eq '' ?
1.320     albertel 1668: 		  '' : &compute_points($$record{'resource.'.$partid.'.awarded'},$wgt));
1.71      ng       1669:     my $result='<input type="hidden" name="WGT'.$counter.'_'.$partid.'" value="'.$wgt.'" />'."\n";
1.466     albertel 1670:     my $display_part= &get_display_part($partid,$symb);
1.270     albertel 1671:     my %last_resets = &get_last_resets($symb,$env{'request.course.id'},
                   1672: 				       [$partid]);
                   1673:     my $aggtries = $$record{'resource.'.$partid.'.tries'};
1.269     raeburn  1674:     if ($last_resets{$partid}) {
                   1675:         $aggtries = &get_num_tries($record,$last_resets{$partid},$partid);
                   1676:     }
1.585     bisitz   1677:     $result.=&Apache::loncommon::start_data_table_row();
1.71      ng       1678:     my $ctr = 0;
1.348     bowersj2 1679:     my $thisweight = 0;
1.349     albertel 1680:     my $increment = &get_increment();
1.485     albertel 1681: 
                   1682:     my $radio.='<table border="0"><tr>'."\n";  # display radio buttons in a nice table 10 across
1.348     bowersj2 1683:     while ($thisweight<=$wgt) {
1.532     bisitz   1684: 	$radio.= '<td><span class="LC_nobreak"><label><input type="radio" name="RADVAL'.$counter.'_'.$partid.'" '.
1.589     bisitz   1685:         'onclick="javascript:writeBox(this.form,\''.$counter.'_'.$partid.'\','.
1.348     bowersj2 1686: 	    $thisweight.')" value="'.$thisweight.'" '.
1.401     albertel 1687: 	    ($score eq $thisweight ? 'checked="checked"':'').' /> '.$thisweight."</label></span></td>\n";
1.485     albertel 1688: 	$radio.=(($ctr+1)%10 == 0 ? '</tr><tr>' : '');
1.348     bowersj2 1689:         $thisweight += $increment;
1.71      ng       1690: 	$ctr++;
                   1691:     }
1.485     albertel 1692:     $radio.='</tr></table>';
                   1693: 
                   1694:     my $line.='<input type="text" name="GD_BOX'.$counter.'_'.$partid.'"'.
1.71      ng       1695: 	($score ne ''? ' value = "'.$score.'"':'').' size="4" '.
1.589     bisitz   1696: 	'onchange="javascript:updateRadio(this.form,\''.$counter.'_'.$partid.'\','.
1.71      ng       1697: 	$wgt.')" /></td>'."\n";
1.485     albertel 1698:     $line.='<td>/'.$wgt.' '.$wgtmsg.
1.71      ng       1699: 	($$record{'resource.'.$partid.'.solved'} eq 'correct_by_student' ? '&nbsp;'.$checkIcon : '').
1.585     bisitz   1700: 	' </td>'."\n";
                   1701:     $line.='<td><select name="GD_SEL'.$counter.'_'.$partid.'" '.
1.589     bisitz   1702: 	'onchange="javascript:clearRadBox(this.form,\''.$counter.'_'.$partid.'\')" >'."\n";
1.71      ng       1703:     if ($$record{'resource.'.$partid.'.solved'} eq 'excused') {
1.485     albertel 1704: 	$line.='<option></option>'.
                   1705: 	    '<option value="excused" selected="selected">'.&mt('excused').'</option>';
1.71      ng       1706:     } else {
1.485     albertel 1707: 	$line.='<option selected="selected"></option>'.
                   1708: 	    '<option value="excused" >'.&mt('excused').'</option>';
1.71      ng       1709:     }
1.485     albertel 1710:     $line.='<option value="reset status">'.&mt('reset status').'</option></select>'."\n";
                   1711: 
                   1712: 
                   1713:     $result .= 
1.585     bisitz   1714: 	    '<td>'.$display_part.'</td><td>'.$radio.'</td><td>'.&mt('or').'</td><td>'.$line.'</td>';
                   1715:     $result.=&Apache::loncommon::end_data_table_row();
1.71      ng       1716:     $result.='<input type="hidden" name="stores'.$counter.'_'.$partid.'" value="" />'."\n".
                   1717: 	'<input type="hidden" name="oldpts'.$counter.'_'.$partid.'" value="'.$score.'" />'."\n".
                   1718: 	'<input type="hidden" name="solved'.$counter.'_'.$partid.'" value="'.
1.269     raeburn  1719: 	$$record{'resource.'.$partid.'.solved'}.'" />'."\n".
                   1720:         '<input type="hidden" name="totaltries'.$counter.'_'.$partid.'" value="'.
                   1721:         $$record{'resource.'.$partid.'.tries'}.'" />'."\n".
                   1722:         '<input type="hidden" name="aggtries'.$counter.'_'.$partid.'" value="'.
                   1723:         $aggtries.'" />'."\n";
1.582     raeburn  1724:     my $res_error;
                   1725:     $result.=&handback_box($symb,$uname,$udom,$counter,$partid,$record,\$res_error);
                   1726:     if ($res_error) {
                   1727:         return &navmap_errormsg();
                   1728:     }
1.318     banghart 1729:     return $result;
                   1730: }
1.322     albertel 1731: 
                   1732: sub handback_box {
1.623     www      1733:     my ($symb,$uname,$udom,$counter,$partid,$record,$res_error_pointer) = @_;
                   1734:     my ($partlist,$handgrade,$responseType) = &response_type($symb,$res_error_pointer);
1.323     banghart 1735:     my (@respids);
1.375     albertel 1736:      my @part_response_id = &flatten_responseType($responseType);
                   1737:     foreach my $part_response_id (@part_response_id) {
                   1738:     	my ($part,$resp) = @{ $part_response_id };
1.323     banghart 1739:         if ($part eq $partid) {
1.375     albertel 1740:             push(@respids,$resp);
1.323     banghart 1741:         }
                   1742:     }
1.318     banghart 1743:     my $result;
1.323     banghart 1744:     foreach my $respid (@respids) {
1.322     albertel 1745: 	my $prefix = $counter.'_'.$partid.'_'.$respid.'_';
                   1746: 	my $files=&get_submitted_files($udom,$uname,$partid,$respid,$record);
                   1747: 	next if (!@$files);
                   1748: 	my $file_counter = 1;
1.313     banghart 1749: 	foreach my $file (@$files) {
1.368     banghart 1750: 	    if ($file =~ /\/portfolio\//) {
                   1751:     	        my ($file_path, $file_disp) = ($file =~ m|(.+/)(.+)$|);
                   1752:     	        my ($name,$version,$ext) = &file_name_version_ext($file_disp);
                   1753:     	        $file_disp = "$name.$ext";
                   1754:     	        $file = $file_path.$file_disp;
                   1755:     	        $result.=&mt('Return commented version of [_1] to student.',
                   1756:     			 '<span class="LC_filename">'.$file_disp.'</span>');
                   1757:     	        $result.='<input type="file"   name="'.$prefix.'returndoc'.$file_counter.'" />'."\n";
                   1758:     	        $result.='<input type="hidden" name="'.$prefix.'origdoc'.$file_counter.'" value="'.$file.'" /><br />';
1.485     albertel 1759:     	        $result.='('.&mt('File will be uploaded when you click on Save &amp; Next below.').')<br />';
1.368     banghart 1760:     	        $file_counter++;
                   1761: 	    }
1.322     albertel 1762: 	}
1.313     banghart 1763:     }
1.318     banghart 1764:     return $result;    
1.71      ng       1765: }
1.44      ng       1766: 
1.58      albertel 1767: sub show_problem {
1.382     albertel 1768:     my ($request,$symb,$uname,$udom,$removeform,$viewon,$mode,$form) = @_;
1.144     albertel 1769:     my $rendered;
1.382     albertel 1770:     my %form = ((ref($form) eq 'HASH')? %{$form} : ());
1.329     albertel 1771:     &Apache::lonxml::remember_problem_counter();
1.144     albertel 1772:     if ($mode eq 'both' or $mode eq 'text') {
                   1773: 	$rendered=&Apache::loncommon::get_student_view($symb,$uname,$udom,
1.382     albertel 1774: 						       $env{'request.course.id'},
                   1775: 						       undef,\%form);
1.144     albertel 1776:     }
1.58      albertel 1777:     if ($removeform) {
                   1778: 	$rendered=~s|<form(.*?)>||g;
                   1779: 	$rendered=~s|</form>||g;
1.374     albertel 1780: 	$rendered=~s|(<input[^>]*name\s*=\s*"?)(\w+)("?)|$1would_have_been_$2$3|g;
1.58      albertel 1781:     }
1.144     albertel 1782:     my $companswer;
                   1783:     if ($mode eq 'both' or $mode eq 'answer') {
1.329     albertel 1784: 	&Apache::lonxml::restore_problem_counter();
1.382     albertel 1785: 	$companswer=
                   1786: 	    &Apache::loncommon::get_student_answers($symb,$uname,$udom,
                   1787: 						    $env{'request.course.id'},
                   1788: 						    %form);
1.144     albertel 1789:     }
1.58      albertel 1790:     if ($removeform) {
                   1791: 	$companswer=~s|<form(.*?)>||g;
                   1792: 	$companswer=~s|</form>||g;
1.144     albertel 1793: 	$companswer=~s|name="submit"|name="would_have_been_submit"|g;
1.58      albertel 1794:     }
1.468     albertel 1795:     $rendered=
1.588     bisitz   1796:         '<div class="LC_Box">'
                   1797:        .'<h3 class="LC_hcell">'.&mt('View of the problem').'</h3>'
                   1798:        .$rendered
                   1799:        .'</div>';
1.468     albertel 1800:     $companswer=
1.588     bisitz   1801:         '<div class="LC_Box">'
                   1802:        .'<h3 class="LC_hcell">'.&mt('Correct answer').'</h3>'
                   1803:        .$companswer
                   1804:        .'</div>';
1.468     albertel 1805:     my $result;
1.144     albertel 1806:     if ($mode eq 'both') {
1.588     bisitz   1807:         $result=$rendered.$companswer;
1.144     albertel 1808:     } elsif ($mode eq 'text') {
1.588     bisitz   1809:         $result=$rendered;
1.144     albertel 1810:     } elsif ($mode eq 'answer') {
1.588     bisitz   1811:         $result=$companswer;
1.144     albertel 1812:     }
1.71      ng       1813:     return $result;
1.58      albertel 1814: }
1.397     albertel 1815: 
1.396     banghart 1816: sub files_exist {
                   1817:     my ($r, $symb) = @_;
                   1818:     my @students = &Apache::loncommon::get_env_multiple('form.stuinfo');
1.397     albertel 1819: 
1.396     banghart 1820:     foreach my $student (@students) {
                   1821:         my ($uname,$udom,$fullname) = split(/:/,$student);
1.397     albertel 1822:         my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},
                   1823: 					      $udom,$uname);
1.396     banghart 1824:         my ($string,$timestamp)= &get_last_submission(\%record);
1.397     albertel 1825:         foreach my $submission (@$string) {
                   1826:             my ($partid,$respid) =
                   1827: 		($submission =~ /^resource\.([^\.]*)\.([^\.]*)\.submission/);
                   1828:             my $files=&get_submitted_files($udom,$uname,$partid,$respid,
                   1829: 					   \%record);
                   1830:             return 1 if (@$files);
1.396     banghart 1831:         }
                   1832:     }
1.397     albertel 1833:     return 0;
1.396     banghart 1834: }
1.397     albertel 1835: 
1.394     banghart 1836: sub download_all_link {
                   1837:     my ($r,$symb) = @_;
1.621     www      1838:     unless (&files_exist($r, $symb)) {
                   1839:        $r->print(&mt('There are currently no submitted documents.'));
                   1840:        return;
                   1841:     }
                   1842: 
1.395     albertel 1843:     my $all_students = 
                   1844: 	join("\n", &Apache::loncommon::get_env_multiple('form.stuinfo'));
                   1845: 
                   1846:     my $parts =
                   1847: 	join("\n",&Apache::loncommon::get_env_multiple('form.vPart'));
                   1848: 
1.394     banghart 1849:     my $identifier = &Apache::loncommon::get_cgi_id();
1.514     raeburn  1850:     &Apache::lonnet::appenv({'cgi.'.$identifier.'.students' => $all_students,
                   1851:                              'cgi.'.$identifier.'.symb' => $symb,
                   1852:                              'cgi.'.$identifier.'.parts' => $parts,});
1.395     albertel 1853:     $r->print('<a href="/cgi-bin/multidownload.pl?'.$identifier.'">'.
                   1854: 	      &mt('Download All Submitted Documents').'</a>');
1.621     www      1855:     return;
                   1856: }
                   1857: 
                   1858: sub submit_download_link {
                   1859:     my ($request,$symb) = @_;
                   1860:     if (!$symb) { return ''; }
                   1861: #FIXME: Figure out which type of problem this is and provide appropriate download
                   1862:     &download_all_link($request,$symb);
1.394     banghart 1863: }
1.395     albertel 1864: 
1.432     banghart 1865: sub build_section_inputs {
                   1866:     my $section_inputs;
                   1867:     if ($env{'form.section'} eq '') {
                   1868:         $section_inputs .= '<input type="hidden" name="section" value="all" />'."\n";
                   1869:     } else {
                   1870:         my @sections = &Apache::loncommon::get_env_multiple('form.section');
1.434     albertel 1871:         foreach my $section (@sections) {
1.432     banghart 1872:             $section_inputs .= '<input type="hidden" name="section" value="'.$section.'" />'."\n";
                   1873:         }
                   1874:     }
                   1875:     return $section_inputs;
                   1876: }
                   1877: 
1.44      ng       1878: # --------------------------- show submissions of a student, option to grade 
                   1879: sub submission {
1.608     www      1880:     my ($request,$counter,$total,$symb) = @_;
1.257     albertel 1881:     my ($uname,$udom)     = ($env{'form.student'},$env{'form.userdom'});
                   1882:     $udom = ($udom eq '' ? $env{'user.domain'} : $udom); #has form.userdom changed for a student?
                   1883:     my $usec = &Apache::lonnet::getsection($udom,$uname,$env{'request.course.id'});
                   1884:     $env{'form.fullname'} = &Apache::loncommon::plainname($uname,$udom,'lastname') if $env{'form.fullname'} eq '';
1.608     www      1885: 
1.605     www      1886:     my $probtitle=&Apache::lonnet::gettitle($symb); 
1.324     albertel 1887:     if ($symb eq '') { $request->print("Unable to handle ambiguous references:."); return ''; }
1.104     albertel 1888: 
                   1889:     if (!&canview($usec)) {
1.398     albertel 1890: 	$request->print('<span class="LC_warning">Unable to view requested student.('.
                   1891: 			$uname.':'.$udom.' in section '.$usec.' in course id '.
                   1892: 			$env{'request.course.id'}.')</span>');
1.104     albertel 1893: 	return;
                   1894:     }
                   1895: 
1.257     albertel 1896:     if (!$env{'form.lastSub'}) { $env{'form.lastSub'} = 'datesub'; }
                   1897:     if (!$env{'form.vProb'}) { $env{'form.vProb'} = 'yes'; }
                   1898:     if (!$env{'form.vAns'}) { $env{'form.vAns'} = 'yes'; }
                   1899:     my $last = ($env{'form.lastSub'} eq 'last' ? 'last' : '');
1.381     albertel 1900:     my $checkIcon = '<img alt="'.&mt('Check Mark').
                   1901: 	'" src="'.$request->dir_config('lonIconsURL').
1.122     ng       1902: 	'/check.gif" height="16" border="0" />';
1.41      ng       1903: 
1.426     albertel 1904:     my %old_essays;
1.41      ng       1905:     # header info
                   1906:     if ($counter == 0) {
                   1907: 	&sub_page_js($request);
1.621     www      1908: 	&sub_page_kw_js($request);
1.118     ng       1909: 
1.44      ng       1910: 	# option to display problem, only once else it cause problems 
                   1911:         # with the form later since the problem has a form.
1.257     albertel 1912: 	if ($env{'form.vProb'} eq 'yes' or $env{'form.vAns'} eq 'yes') {
1.144     albertel 1913: 	    my $mode;
1.257     albertel 1914: 	    if ($env{'form.vProb'} eq 'yes' && $env{'form.vAns'} eq 'yes') {
1.144     albertel 1915: 		$mode='both';
1.257     albertel 1916: 	    } elsif ($env{'form.vProb'} eq 'yes') {
1.144     albertel 1917: 		$mode='text';
1.257     albertel 1918: 	    } elsif ($env{'form.vAns'} eq 'yes') {
1.144     albertel 1919: 		$mode='answer';
                   1920: 	    }
1.329     albertel 1921: 	    &Apache::lonxml::clear_problem_counter();
1.144     albertel 1922: 	    $request->print(&show_problem($request,$symb,$uname,$udom,0,1,$mode));
1.41      ng       1923: 	}
1.441     www      1924: 
1.44      ng       1925: 	# kwclr is the only variable that is guaranteed to be non blank 
                   1926:         # if this subroutine has been called once.
1.41      ng       1927: 	my %keyhash = ();
1.624     www      1928: #	if ($env{'form.kwclr'} eq '' && $env{'form.handgrade'} eq 'yes') {
                   1929:         if (1) {
1.41      ng       1930: 	    %keyhash = &Apache::lonnet::dump('nohist_handgrade',
1.257     albertel 1931: 					     $env{'course.'.$env{'request.course.id'}.'.domain'},
                   1932: 					     $env{'course.'.$env{'request.course.id'}.'.num'});
1.41      ng       1933: 
1.257     albertel 1934: 	    my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
                   1935: 	    $env{'form.keywords'} = $keyhash{$symb.'_keywords'} ne '' ? $keyhash{$symb.'_keywords'} : '';
                   1936: 	    $env{'form.kwclr'}    = $keyhash{$loginuser.'_kwclr'} ne '' ? $keyhash{$loginuser.'_kwclr'} : 'red';
                   1937: 	    $env{'form.kwsize'}   = $keyhash{$loginuser.'_kwsize'} ne '' ? $keyhash{$loginuser.'_kwsize'} : '0';
                   1938: 	    $env{'form.kwstyle'}  = $keyhash{$loginuser.'_kwstyle'} ne '' ? $keyhash{$loginuser.'_kwstyle'} : '';
                   1939: 	    $env{'form.msgsub'}   = $keyhash{$symb.'_subject'} ne '' ? 
1.605     www      1940: 		$keyhash{$symb.'_subject'} : $probtitle;
1.257     albertel 1941: 	    $env{'form.savemsgN'} = $keyhash{$symb.'_savemsgN'} ne '' ? $keyhash{$symb.'_savemsgN'} : '0';
1.41      ng       1942: 	}
1.257     albertel 1943: 	my $overRideScore = $env{'form.overRideScore'} eq '' ? 'no' : $env{'form.overRideScore'};
1.442     banghart 1944: 	my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
1.303     banghart 1945: 	$request->print('<form action="/adm/grades" method="post" name="SCORE" enctype="multipart/form-data">'."\n".
1.41      ng       1946: 			'<input type="hidden" name="command"    value="handgrade" />'."\n".
1.442     banghart 1947: 			'<input type="hidden" name="Status"     value="'.$stu_status.'" />'."\n".
1.120     ng       1948: 			'<input type="hidden" name="overRideScore" value="'.$overRideScore.'" />'."\n".
1.41      ng       1949: 			'<input type="hidden" name="refresh"    value="off" />'."\n".
1.120     ng       1950: 			'<input type="hidden" name="studentNo"  value="" />'."\n".
                   1951: 			'<input type="hidden" name="gradeOpt"   value="" />'."\n".
1.418     albertel 1952: 			'<input type="hidden" name="symb"       value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.257     albertel 1953: 			'<input type="hidden" name="vProb"      value="'.$env{'form.vProb'}.'" />'."\n".
                   1954: 			'<input type="hidden" name="vAns"       value="'.$env{'form.vAns'}.'" />'."\n".
                   1955: 			'<input type="hidden" name="lastSub"    value="'.$env{'form.lastSub'}.'" />'."\n".
1.432     banghart 1956: 			&build_section_inputs().
1.326     albertel 1957: 			'<input type="hidden" name="submitonly" value="'.$env{'form.submitonly'}.'" />'."\n".
1.41      ng       1958: 			'<input type="hidden" name="NCT"'.
1.257     albertel 1959: 			' value="'.($env{'form.NTSTU'} ne '' ? $env{'form.NTSTU'} : $total+1).'" />'."\n");
1.624     www      1960: #	if ($env{'form.handgrade'} eq 'yes') {
                   1961:         if (1) {
1.257     albertel 1962: 	    $request->print('<input type="hidden" name="keywords" value="'.$env{'form.keywords'}.'" />'."\n".
                   1963: 			    '<input type="hidden" name="kwclr"    value="'.$env{'form.kwclr'}.'" />'."\n".
                   1964: 			    '<input type="hidden" name="kwsize"   value="'.$env{'form.kwsize'}.'" />'."\n".
                   1965: 			    '<input type="hidden" name="kwstyle"  value="'.$env{'form.kwstyle'}.'" />'."\n".
                   1966: 			    '<input type="hidden" name="msgsub"   value="'.$env{'form.msgsub'}.'" />'."\n".
1.123     ng       1967: 			    '<input type="hidden" name="shownSub" value="0" />'."\n".
1.257     albertel 1968: 			    '<input type="hidden" name="savemsgN" value="'.$env{'form.savemsgN'}.'" />'."\n");
1.154     albertel 1969: 	    foreach my $partid (&Apache::loncommon::get_env_multiple('form.vPart')) {
                   1970: 		$request->print('<input type="hidden" name="vPart" value="'.$partid.'" />'."\n");
                   1971: 	    }
1.123     ng       1972: 	}
1.41      ng       1973: 	
                   1974: 	my ($cts,$prnmsg) = (1,'');
1.257     albertel 1975: 	while ($cts <= $env{'form.savemsgN'}) {
1.41      ng       1976: 	    $prnmsg.='<input type="hidden" name="savemsg'.$cts.'" value="'.
1.123     ng       1977: 		(!exists($keyhash{$symb.'_savemsg'.$cts}) ? 
1.257     albertel 1978: 		 &Apache::lonfeedback::clear_out_html($env{'form.savemsg'.$cts}) :
1.80      ng       1979: 		 &Apache::lonfeedback::clear_out_html($keyhash{$symb.'_savemsg'.$cts})).
1.123     ng       1980: 		'" />'."\n".
                   1981: 		'<input type="hidden" name="shownOnce'.$cts.'" value="0" />'."\n";
1.41      ng       1982: 	    $cts++;
                   1983: 	}
                   1984: 	$request->print($prnmsg);
1.32      ng       1985: 
1.624     www      1986: #	if ($env{'form.handgrade'} eq 'yes') {
                   1987:         if (1) {
1.88      www      1988: #
                   1989: # Print out the keyword options line
                   1990: #
1.41      ng       1991: 	    $request->print(<<KEYWORDS);
1.38      ng       1992: &nbsp;<b>Keyword Options:</b>&nbsp;
1.417     albertel 1993: <a href="javascript:keywords(document.SCORE);" target="_self">List</a>&nbsp; &nbsp;
1.589     bisitz   1994: <a href="#" onmousedown="javascript:getSel(); return false"
1.38      ng       1995:  CLASS="page">Paste Selection to List</a>&nbsp; &nbsp;
1.417     albertel 1996: <a href="javascript:kwhighlight();" target="_self">Highlight Attribute</a><br /><br />
1.38      ng       1997: KEYWORDS
1.88      www      1998: #
                   1999: # Load the other essays for similarity check
                   2000: #
1.324     albertel 2001:             my (undef,undef,$essayurl) = &Apache::lonnet::decode_symb($symb);
1.384     albertel 2002: 	    my ($adom,$aname,$apath)=($essayurl=~/^($LONCAPA::domain_re)\/($LONCAPA::username_re)\/(.*)$/);
1.359     www      2003: 	    $apath=&escape($apath);
1.88      www      2004: 	    $apath=~s/\W/\_/gs;
1.426     albertel 2005: 	    %old_essays=&Apache::lonnet::dump('nohist_essay_'.$apath,$adom,$aname);
1.41      ng       2006:         }
                   2007:     }
1.44      ng       2008: 
1.441     www      2009: # This is where output for one specific student would start
1.592     bisitz   2010:     my $add_class = ($counter%2) ? ' LC_grade_show_user_odd_row' : '';
                   2011:     $request->print(
                   2012:         "\n\n"
                   2013:        .'<div class="LC_grade_show_user'.$add_class.'">'
                   2014:        .'<h2>'.&nameUserString(undef,$env{'form.fullname'},$uname,$udom).'</h2>'
                   2015:        ."\n"
                   2016:     );
1.441     www      2017: 
1.592     bisitz   2018:     # Show additional functions if allowed
                   2019:     if ($perm{'vgr'}) {
                   2020:         $request->print(
                   2021:             &Apache::loncommon::track_student_link(
                   2022:                 &mt('View recent activity'),
                   2023:                 $uname,$udom,'check')
                   2024:            .' '
                   2025:         );
                   2026:     }
                   2027:     if ($perm{'opa'}) {
                   2028:         $request->print(
                   2029:             &Apache::loncommon::pprmlink(
                   2030:                 &mt('Set/Change parameters'),
                   2031:                 $uname,$udom,$symb,'check'));
                   2032:     }
                   2033: 
                   2034:     # Show Problem
1.257     albertel 2035:     if ($env{'form.vProb'} eq 'all' or $env{'form.vAns'} eq 'all') {
1.144     albertel 2036: 	my $mode;
1.257     albertel 2037: 	if ($env{'form.vProb'} eq 'all' && $env{'form.vAns'} eq 'all') {
1.144     albertel 2038: 	    $mode='both';
1.257     albertel 2039: 	} elsif ($env{'form.vProb'} eq 'all' ) {
1.144     albertel 2040: 	    $mode='text';
1.257     albertel 2041: 	} elsif ($env{'form.vAns'} eq 'all') {
1.144     albertel 2042: 	    $mode='answer';
                   2043: 	}
1.329     albertel 2044: 	&Apache::lonxml::clear_problem_counter();
1.475     albertel 2045: 	$request->print(&show_problem($request,$symb,$uname,$udom,1,1,$mode,{'request.prefix' => 'ctr'.$counter}));
1.58      albertel 2046:     }
1.144     albertel 2047: 
1.257     albertel 2048:     my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
1.582     raeburn  2049:     my $res_error;
                   2050:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
                   2051:     if ($res_error) {
                   2052:         $request->print(&navmap_errormsg());
                   2053:         return;
                   2054:     }
1.41      ng       2055: 
1.44      ng       2056:     # Display student info
1.41      ng       2057:     $request->print(($counter == 0 ? '' : '<br />'));
1.590     bisitz   2058: 
                   2059:     my $result='<div class="LC_Box">'
                   2060:               .'<h3 class="LC_hcell">'.&mt('Submissions').'</h3>';
1.45      ng       2061:     $result.='<input type="hidden" name="name'.$counter.
1.588     bisitz   2062:              '" value="'.$env{'form.fullname'}.'" />'."\n";
1.624     www      2063: #    if ($env{'form.handgrade'} eq 'no') {
                   2064:     if (1) {
1.588     bisitz   2065:         $result.='<p class="LC_info">'
                   2066:                 .&mt('Part(s) graded correct by the computer is marked with a [_1] symbol.',$checkIcon)
                   2067:                 ."</p>\n";
1.469     albertel 2068:     }
                   2069: 
1.118     ng       2070:     # If any part of the problem is an essay-response (handgraded), then check for collaborators
1.464     albertel 2071:     my $fullname;
                   2072:     my $col_fullnames = [];
1.624     www      2073: #    if ($env{'form.handgrade'} eq 'yes') {
                   2074:     if (1) {
1.464     albertel 2075: 	(my $sub_result,$fullname,$col_fullnames)=
                   2076: 	    &check_collaborators($symb,$uname,$udom,\%record,$handgrade,
                   2077: 				 $counter);
                   2078: 	$result.=$sub_result;
1.41      ng       2079:     }
1.44      ng       2080:     $request->print($result."\n");
1.588     bisitz   2081: 
1.44      ng       2082:     # print student answer/submission
1.588     bisitz   2083:     # Options are (1) Handgraded submission only
1.44      ng       2084:     #             (2) Last submission, includes submission that is not handgraded 
                   2085:     #                  (for multi-response type part)
                   2086:     #             (3) Last submission plus the parts info
                   2087:     #             (4) The whole record for this student
1.257     albertel 2088:     if ($env{'form.lastSub'} =~ /^(lastonly|hdgrade)$/) {
1.151     albertel 2089: 	my ($string,$timestamp)= &get_last_submission(\%record);
1.468     albertel 2090: 	
                   2091: 	my $lastsubonly;
                   2092: 
1.588     bisitz   2093:         if ($$timestamp eq '') {
                   2094:             $lastsubonly.='<div class="LC_grade_submissions_body">'.$$string[0].'</div>'; 
                   2095:         } else {
1.592     bisitz   2096:             $lastsubonly =
                   2097:                 '<div class="LC_grade_submissions_body">'
                   2098:                .'<b>'.&mt('Date Submitted:').'</b> '.$$timestamp."\n";
1.468     albertel 2099: 
1.151     albertel 2100: 	    my %seenparts;
1.375     albertel 2101: 	    my @part_response_id = &flatten_responseType($responseType);
                   2102: 	    foreach my $part (@part_response_id) {
1.393     albertel 2103: 		next if ($env{'form.lastSub'} eq 'hdgrade' 
                   2104: 			 && $$handgrade{$$part[0].'_'.$$part[1]} ne 'yes');
                   2105: 
1.375     albertel 2106: 		my ($partid,$respid) = @{ $part };
1.324     albertel 2107: 		my $display_part=&get_display_part($partid,$symb);
1.257     albertel 2108: 		if ($env{"form.$uname:$udom:$partid:submitted_by"}) {
1.151     albertel 2109: 		    if (exists($seenparts{$partid})) { next; }
                   2110: 		    $seenparts{$partid}=1;
1.207     albertel 2111: 		    my $submitby='<b>Part:</b> '.$display_part.
                   2112: 			' <b>Collaborative submission by:</b> '.
1.151     albertel 2113: 			'<a href="javascript:viewSubmitter(\''.
1.257     albertel 2114: 			$env{"form.$uname:$udom:$partid:submitted_by"}.
1.417     albertel 2115: 			'\');" target="_self">'.
1.257     albertel 2116: 			$$fullname{$env{"form.$uname:$udom:$partid:submitted_by"}}.'</a><br />';
1.151     albertel 2117: 		    $request->print($submitby);
                   2118: 		    next;
                   2119: 		}
                   2120: 		my $responsetype = $responseType->{$partid}->{$respid};
                   2121: 		if (!exists($record{"resource.$partid.$respid.submission"})) {
1.577     bisitz   2122:                     $lastsubonly.="\n".'<div class="LC_grade_submission_part">'.
                   2123:                         '<b>'.&mt('Part: [_1]',$display_part).'</b>'.
                   2124:                         ' <span class="LC_internal_info">'.
1.623     www      2125:                         '('.&mt('Response ID: [_1]',$respid).')'.
1.577     bisitz   2126:                         '</span>&nbsp; &nbsp;'.
1.539     riegler  2127: 			'<span class="LC_warning">'.&mt('Nothing submitted - no attempts.').'</span><br /><br /></div>';
1.151     albertel 2128: 		    next;
                   2129: 		}
1.468     albertel 2130: 		foreach my $submission (@$string) {
                   2131: 		    my ($partid,$respid) = ($submission =~ /^resource\.([^\.]*)\.([^\.]*)\.submission/);
1.375     albertel 2132: 		    if (join('_',@{$part}) ne ($partid.'_'.$respid)) { next; }
1.596     raeburn  2133: 		    my ($ressub,$hide,$subval) = split(/:/,$submission,3);
1.151     albertel 2134: 		    # Similarity check
                   2135: 		    my $similar='';
1.257     albertel 2136: 		    if($env{'form.checkPlag'}){
1.151     albertel 2137: 			my ($oname,$odom,$ocrsid,$oessay,$osim)=
1.426     albertel 2138: 			    &most_similar($uname,$udom,$subval,\%old_essays);
1.151     albertel 2139: 			if ($osim) {
                   2140: 			    $osim=int($osim*100.0);
1.426     albertel 2141: 			    my %old_course_desc = 
                   2142: 				&Apache::lonnet::coursedescription($ocrsid,
                   2143: 								   {'one_time' => 1});
                   2144: 
1.596     raeburn  2145:                             if ($hide) {
                   2146:                                 $similar='<hr /><span class="LC_warning">'.&mt("Essay was found to be similar to another essay submitted for this assignment.").'<br />'.
                   2147:                                          &mt('As the current submission is for an anonymous survey, no other details are available.').'</span><hr />';
                   2148:                             } else {
                   2149: 			        $similar="<hr /><h3><span class=\"LC_warning\">".
                   2150: 				    &mt('Essay is [_1]% similar to an essay by [_2] in course [_3] (course id [_4]:[_5])',
                   2151: 				        $osim,
                   2152: 				        &Apache::loncommon::plainname($oname,$odom).' ('.$oname.':'.$odom.')',
                   2153: 				        $old_course_desc{'description'},
                   2154: 				        $old_course_desc{'num'},
                   2155: 				        $old_course_desc{'domain'}).
                   2156: 				    '</span></h3><blockquote><i>'.
                   2157: 				    &keywords_highlight($oessay).
                   2158: 				    '</i></blockquote><hr />';
                   2159:                             }
1.151     albertel 2160: 			}
1.150     albertel 2161: 		    }
1.151     albertel 2162: 		    my $order=&get_order($partid,$respid,$symb,$uname,$udom);
1.257     albertel 2163: 		    if ($env{'form.lastSub'} eq 'lastonly' || 
                   2164: 			($env{'form.lastSub'} eq 'hdgrade' && 
1.377     albertel 2165: 			 $$handgrade{$$part[0].'_'.$$part[1]} eq 'yes')) {
1.324     albertel 2166: 			my $display_part=&get_display_part($partid,$symb);
1.577     bisitz   2167:                         $lastsubonly.='<div class="LC_grade_submission_part">'.
                   2168:                             '<b>'.&mt('Part: [_1]',$display_part).'</b>'.
                   2169:                             ' <span class="LC_internal_info">'.
1.623     www      2170:                             '('.&mt('Response ID: [_1]',$respid).')'.
1.597     wenzelju 2171:                             '</span>&nbsp; &nbsp;';
1.313     banghart 2172: 			my $files=&get_submitted_files($udom,$uname,$partid,$respid,\%record);
                   2173: 			if (@$files) {
1.596     raeburn  2174:                             if ($hide) {
                   2175:                                 $lastsubonly.='<br />'.&mt('[quant,_1,file] uploaded to this anonymous survey',scalar(@{$files}));
                   2176:                             } else {
                   2177:                                 $lastsubonly.='<br /><span class="LC_warning">'.&mt('Like all files provided by users, this file may contain viruses').'</span><br />';
                   2178:                                 foreach my $file (@$files) {
                   2179:                                     &Apache::lonnet::allowuploaded('/adm/grades',$file);
                   2180:                                     $lastsubonly.='<br /><a href="'.$file.'?rawmode=1" target="lonGRDs"><img src="'.&Apache::loncommon::icon($file).'" border="0" /> '.$file.'</a>';
                   2181:                                 }
                   2182:                             }
1.236     albertel 2183: 			    $lastsubonly.='<br />';
1.41      ng       2184: 			}
1.596     raeburn  2185:                         if ($hide) {
                   2186:                             $lastsubonly.='<b>'.&mt('Anonymous Survey').'</b>'; 
                   2187:                         } else {
                   2188: 			    $lastsubonly.='<b>'.&mt('Submitted Answer:').' </b>'.
                   2189: 			        &cleanRecord($subval,$responsetype,$symb,$partid,
                   2190: 					     $respid,\%record,$order,undef,$uname,$udom);
                   2191:                         }
1.151     albertel 2192: 			if ($similar) {$lastsubonly.="<br /><br />$similar\n";}
1.468     albertel 2193: 			$lastsubonly.='</div>';
1.41      ng       2194: 		    }
                   2195: 		}
                   2196: 	    }
1.588     bisitz   2197: 	    $lastsubonly.='</div>'."\n"; # End: LC_grade_submissions_body
1.151     albertel 2198: 	}
                   2199: 	$request->print($lastsubonly);
1.468     albertel 2200:    } elsif ($env{'form.lastSub'} eq 'datesub') {
1.623     www      2201:         my ($parts,$handgrade,$responseType) = &response_type($symb,\$res_error);
1.148     albertel 2202: 	$request->print(&displaySubByDates($symb,\%record,$parts,$responseType,$checkIcon,$uname,$udom));
1.257     albertel 2203:     } elsif ($env{'form.lastSub'} =~ /^(last|all)$/) {
1.41      ng       2204: 	$request->print(&Apache::loncommon::get_previous_attempt($symb,$uname,$udom,
1.257     albertel 2205: 								 $env{'request.course.id'},
1.44      ng       2206: 								 $last,'.submission',
                   2207: 								 'Apache::grades::keywords_highlight'));
1.41      ng       2208:     }
1.121     ng       2209:     $request->print('<input type="hidden" name="unamedom'.$counter.'" value="'.$uname.':'
                   2210: 	.$udom.'" />'."\n");
1.44      ng       2211:     # return if view submission with no grading option
1.618     www      2212:     if (!&canmodify($usec)) {
1.633     www      2213: 	$request->print('<p><span class="LC_warning">'.&mt('No grading privileges').'</span></p></div>');
1.41      ng       2214: 	return;
1.180     albertel 2215:     } else {
1.468     albertel 2216: 	$request->print('</div>'."\n");
1.41      ng       2217:     }
1.33      ng       2218: 
1.121     ng       2219:     # essay grading message center
1.624     www      2220: #    if ($env{'form.handgrade'} eq 'yes') {
                   2221:     if (1) {
1.468     albertel 2222: 	my $result='<div class="LC_grade_message_center">';
                   2223:     
                   2224: 	$result.='<div class="LC_grade_message_center_header">'.
                   2225: 	    &mt('Send Message').'</div><div class="LC_grade_message_center_body">';
1.257     albertel 2226: 	my ($lastname,$givenn) = split(/,/,$env{'form.fullname'});
1.118     ng       2227: 	my $msgfor = $givenn.' '.$lastname;
1.464     albertel 2228: 	if (scalar(@$col_fullnames) > 0) {
                   2229: 	    my $lastone = pop(@$col_fullnames);
                   2230: 	    $msgfor .= ', '.(join ', ',@$col_fullnames).' and '.$lastone.'.';
1.118     ng       2231: 	}
                   2232: 	$msgfor =~ s/\'/\\'/g; #' stupid emacs - no! javascript
1.468     albertel 2233: 	$result.='<input type="hidden" name="includemsg'.$counter.'" value="" />'."\n".
1.121     ng       2234: 	    '<input type="hidden" name="newmsg'.$counter.'" value="" />'."\n";
                   2235: 	$result.='&nbsp;<a href="javascript:msgCenter(document.SCORE,'.$counter.
1.417     albertel 2236: 	    ',\''.$msgfor.'\');" target="_self">'.
1.464     albertel 2237: 	    &mt('Compose message to student').(scalar(@$col_fullnames) >= 1 ? 's' : '').'</a><label> ('.
1.350     albertel 2238: 	    &mt('incl. grades').' <input type="checkbox" name="withgrades'.$counter.'" /></label>)'.
1.118     ng       2239: 	    '<img src="'.$request->dir_config('lonIconsURL').
                   2240: 	    '/mailbkgrd.gif" width="14" height="10" name="mailicon'.$counter.'" />'."\n".
1.298     www      2241: 	    '<br />&nbsp;('.
1.468     albertel 2242: 	    &mt('Message will be sent when you click on Save &amp; Next below.').")\n";
                   2243: 	$result.='</div></div>';
1.121     ng       2244: 	$request->print($result);
1.118     ng       2245:     }
1.41      ng       2246: 
                   2247:     my %seen = ();
                   2248:     my @partlist;
1.129     ng       2249:     my @gradePartRespid;
1.375     albertel 2250:     my @part_response_id = &flatten_responseType($responseType);
1.585     bisitz   2251:     $request->print(
1.588     bisitz   2252:         '<div class="LC_Box">'
                   2253:        .'<h3 class="LC_hcell">'.&mt('Assign Grades').'</h3>'
1.585     bisitz   2254:     );
1.592     bisitz   2255:     $request->print(&gradeBox_start());
1.375     albertel 2256:     foreach my $part_response_id (@part_response_id) {
                   2257:     	my ($partid,$respid) = @{ $part_response_id };
                   2258: 	my $part_resp = join('_',@{ $part_response_id });
1.322     albertel 2259: 	next if ($seen{$partid} > 0);
1.41      ng       2260: 	$seen{$partid}++;
1.393     albertel 2261: 	next if ($$handgrade{$part_resp} ne 'yes' 
                   2262: 		 && $env{'form.lastSub'} eq 'hdgrade');
1.524     raeburn  2263: 	push(@partlist,$partid);
                   2264: 	push(@gradePartRespid,$partid.'.'.$respid);
1.322     albertel 2265: 	$request->print(&gradeBox($request,$symb,$uname,$udom,$counter,$partid,\%record));
1.41      ng       2266:     }
1.585     bisitz   2267:     $request->print(&gradeBox_end()); # </div>
                   2268:     $request->print('</div>');
1.468     albertel 2269: 
                   2270:     $request->print('<div class="LC_grade_info_links">');
                   2271:     $request->print('</div>');
                   2272: 
1.45      ng       2273:     $result='<input type="hidden" name="partlist'.$counter.
                   2274: 	'" value="'.(join ":",@partlist).'" />'."\n";
1.129     ng       2275:     $result.='<input type="hidden" name="gradePartRespid'.
                   2276: 	'" value="'.(join ":",@gradePartRespid).'" />'."\n" if ($counter == 0);
1.45      ng       2277:     my $ctr = 0;
                   2278:     while ($ctr < scalar(@partlist)) {
                   2279: 	$result.='<input type="hidden" name="partid'.$counter.'_'.$ctr.'" value="'.
                   2280: 	    $partlist[$ctr].'" />'."\n";
                   2281: 	$ctr++;
                   2282:     }
1.468     albertel 2283:     $request->print($result.''."\n");
1.41      ng       2284: 
1.441     www      2285: # Done with printing info for one student
                   2286: 
1.468     albertel 2287:     $request->print('</div>');#LC_grade_show_user
1.441     www      2288: 
                   2289: 
1.41      ng       2290:     # print end of form
                   2291:     if ($counter == $total) {
1.592     bisitz   2292:         my $endform='<br /><hr /><table border="0"><tr><td>'."\n";
1.485     albertel 2293: 	$endform.='<input type="button" value="'.&mt('Save &amp; Next').'" '.
1.589     bisitz   2294: 	    'onclick="javascript:checksubmit(this.form,\'Save & Next\','.
1.417     albertel 2295: 	    $total.','.scalar(@partlist).');" target="_self" /> &nbsp;'."\n";
1.119     ng       2296: 	my $ntstu ='<select name="NTSTU">'.
                   2297: 	    '<option>1</option><option>2</option>'.
                   2298: 	    '<option>3</option><option>5</option>'.
                   2299: 	    '<option>7</option><option>10</option></select>'."\n";
1.257     albertel 2300: 	my $nsel = ($env{'form.NTSTU'} ne '' ? $env{'form.NTSTU'} : '1');
1.401     albertel 2301: 	$ntstu =~ s/<option>$nsel</<option selected="selected">$nsel</;
1.578     raeburn  2302:         $endform.=&mt('[_1]student(s)',$ntstu);
1.485     albertel 2303: 	$endform.='&nbsp;&nbsp;<input type="button" value="'.&mt('Previous').'" '.
1.589     bisitz   2304: 	    'onclick="javascript:checksubmit(this.form,\'Previous\');" target="_self" /> &nbsp;'."\n".
1.485     albertel 2305: 	    '<input type="button" value="'.&mt('Next').'" '.
1.589     bisitz   2306: 	    'onclick="javascript:checksubmit(this.form,\'Next\');" target="_self" /> &nbsp;';
1.592     bisitz   2307:         $endform.='<span class="LC_warning">'.
                   2308:                   &mt('(Next and Previous (student) do not save the scores.)').
                   2309:                   '</span>'."\n" ;
1.349     albertel 2310:         $endform.="<input type='hidden' value='".&get_increment().
1.348     bowersj2 2311:             "' name='increment' />";
1.485     albertel 2312: 	$endform.='</td></tr></table></form>';
1.41      ng       2313: 	$request->print($endform);
                   2314:     }
                   2315:     return '';
1.38      ng       2316: }
                   2317: 
1.464     albertel 2318: sub check_collaborators {
                   2319:     my ($symb,$uname,$udom,$record,$handgrade,$counter) = @_;
                   2320:     my ($result,@col_fullnames);
                   2321:     my ($classlist,undef,$fullname) = &getclasslist('all','0');
                   2322:     foreach my $part (keys(%$handgrade)) {
                   2323: 	my $ncol = &Apache::lonnet::EXT('resource.'.$part.
                   2324: 					'.maxcollaborators',
                   2325: 					$symb,$udom,$uname);
                   2326: 	next if ($ncol <= 0);
                   2327: 	$part =~ s/\_/\./g;
                   2328: 	next if ($record->{'resource.'.$part.'.collaborators'} eq '');
                   2329: 	my (@good_collaborators, @bad_collaborators);
                   2330: 	foreach my $possible_collaborator
1.630     www      2331: 	    (split(/[,;\s]+/,$record->{'resource.'.$part.'.collaborators'})) { 
1.464     albertel 2332: 	    $possible_collaborator =~ s/[\$\^\(\)]//g;
                   2333: 	    next if ($possible_collaborator eq '');
1.631     www      2334: 	    my ($co_name,$co_dom) = split(/:/,$possible_collaborator);
1.464     albertel 2335: 	    $co_dom = $udom if (! defined($co_dom) || $co_dom =~ /^domain$/i);
                   2336: 	    next if ($co_name eq $uname && $co_dom eq $udom);
                   2337: 	    # Doing this grep allows 'fuzzy' specification
                   2338: 	    my @matches = grep(/^\Q$co_name\E:\Q$co_dom\E$/i, 
                   2339: 			       keys(%$classlist));
                   2340: 	    if (! scalar(@matches)) {
                   2341: 		push(@bad_collaborators, $possible_collaborator);
                   2342: 	    } else {
                   2343: 		push(@good_collaborators, @matches);
                   2344: 	    }
                   2345: 	}
                   2346: 	if (scalar(@good_collaborators) != 0) {
1.630     www      2347: 	    $result.='<br />'.&mt('Collaborators:').'<ol>';
1.464     albertel 2348: 	    foreach my $name (@good_collaborators) {
                   2349: 		my ($lastname,$givenn) = split(/,/,$$fullname{$name});
                   2350: 		push(@col_fullnames, $givenn.' '.$lastname);
1.630     www      2351: 		$result.='<li>'.$fullname->{$name}.'</li>';
1.464     albertel 2352: 	    }
1.630     www      2353: 	    $result.='</ol><br />'."\n";
1.466     albertel 2354: 	    my ($part)=split(/\./,$part);
1.464     albertel 2355: 	    $result.='<input type="hidden" name="collaborator'.$counter.
                   2356: 		'" value="'.$part.':'.(join ':',@good_collaborators).'" />'.
                   2357: 		"\n";
                   2358: 	}
                   2359: 	if (scalar(@bad_collaborators) > 0) {
1.466     albertel 2360: 	    $result.='<div class="LC_warning">';
1.464     albertel 2361: 	    $result.=&mt('This student has submitted [quant,_1,invalid collaborator]: [_2]',scalar(@bad_collaborators),join(', ',@bad_collaborators));
                   2362: 	    $result .= '</div>';
                   2363: 	}         
                   2364: 	if (scalar(@bad_collaborators > $ncol)) {
1.466     albertel 2365: 	    $result .= '<div class="LC_warning">';
1.464     albertel 2366: 	    $result .= &mt('This student has submitted too many '.
                   2367: 		'collaborators.  Maximum is [_1].',$ncol);
                   2368: 	    $result .= '</div>';
                   2369: 	}
                   2370:     }
                   2371:     return ($result,$fullname,\@col_fullnames);
                   2372: }
                   2373: 
1.44      ng       2374: #--- Retrieve the last submission for all the parts
1.38      ng       2375: sub get_last_submission {
1.119     ng       2376:     my ($returnhash)=@_;
1.596     raeburn  2377:     my (@string,$timestamp,%lasthidden);
1.119     ng       2378:     if ($$returnhash{'version'}) {
1.46      ng       2379: 	my %lasthash=();
                   2380: 	my ($version);
1.119     ng       2381: 	for ($version=1;$version<=$$returnhash{'version'};$version++) {
1.397     albertel 2382: 	    foreach my $key (sort(split(/\:/,
                   2383: 					$$returnhash{$version.':keys'}))) {
                   2384: 		$lasthash{$key}=$$returnhash{$version.':'.$key};
                   2385: 		$timestamp = 
1.545     raeburn  2386: 		    &Apache::lonlocal::locallocaltime($$returnhash{$version.':timestamp'});
1.46      ng       2387: 	    }
                   2388: 	}
1.596     raeburn  2389:         my %typeparts;
                   2390:         my $showsurv = 
                   2391:             &Apache::lonnet::allowed('vas',$env{'request.course.id'});
                   2392:         foreach my $key (sort(keys(%lasthash))) {
                   2393:             if ($key =~ /\.type$/) {
                   2394:                 if (($lasthash{$key} eq 'anonsurvey') || 
                   2395:                     ($lasthash{$key} eq 'anonsurveycred')) {
                   2396:                     my ($ign,@parts) = split(/\./,$key);
                   2397:                     pop(@parts);
                   2398:                     unless ($showsurv) {
                   2399:                         my $id = join(',',@parts);
                   2400:                         $typeparts{$ign.'.'.$id} = $lasthash{$key};
                   2401:                     }
                   2402:                     delete($lasthash{$key});
                   2403:                 }
                   2404:             }
                   2405:         }
                   2406:         my @hidden = keys(%typeparts);
1.397     albertel 2407: 	foreach my $key (keys(%lasthash)) {
                   2408: 	    next if ($key !~ /\.submission$/);
1.596     raeburn  2409:             my $hide;
                   2410:             if (@hidden) {
                   2411:                 foreach my $id (@hidden) {
                   2412:                     if ($key =~ /^\Q$id\E/) {
                   2413:                         $hide = 1;
                   2414:                         last;
                   2415:                     }
                   2416:                 }
                   2417:             }
1.397     albertel 2418: 	    my ($partid,$foo) = split(/submission$/,$key);
                   2419: 	    my $draft  = $lasthash{$partid.'awarddetail'} eq 'DRAFT' ?
1.398     albertel 2420: 		'<span class="LC_warning">Draft Copy</span> ' : '';
1.596     raeburn  2421: 	    push(@string, join(':', $key, $hide, $draft.$lasthash{$key}));
1.41      ng       2422: 	}
                   2423:     }
1.397     albertel 2424:     if (!@string) {
                   2425: 	$string[0] =
1.539     riegler  2426: 	    '<span class="LC_warning">'.&mt('Nothing submitted - no attempts.').'</span>';
1.397     albertel 2427:     }
                   2428:     return (\@string,\$timestamp);
1.38      ng       2429: }
1.35      ng       2430: 
1.44      ng       2431: #--- High light keywords, with style choosen by user.
1.38      ng       2432: sub keywords_highlight {
1.44      ng       2433:     my $string    = shift;
1.257     albertel 2434:     my $size      = $env{'form.kwsize'} eq '0' ? '' : 'size='.$env{'form.kwsize'};
                   2435:     my $styleon   = $env{'form.kwstyle'} eq ''  ? '' : $env{'form.kwstyle'};
1.41      ng       2436:     (my $styleoff = $styleon) =~ s/\</\<\//;
1.257     albertel 2437:     my @keylist   = split(/[,\s+]/,$env{'form.keywords'});
1.398     albertel 2438:     foreach my $keyword (@keylist) {
                   2439: 	$string =~ s/\b\Q$keyword\E(\b|\.)/<font color\=$env{'form.kwclr'} $size\>$styleon$keyword$styleoff<\/font>/gi;
1.41      ng       2440:     }
                   2441:     return $string;
1.38      ng       2442: }
1.36      ng       2443: 
1.44      ng       2444: #--- Called from submission routine
1.38      ng       2445: sub processHandGrade {
1.608     www      2446:     my ($request,$symb) = @_;
1.324     albertel 2447:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
1.257     albertel 2448:     my $button = $env{'form.gradeOpt'};
                   2449:     my $ngrade = $env{'form.NCT'};
                   2450:     my $ntstu  = $env{'form.NTSTU'};
1.301     albertel 2451:     my $cdom   = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   2452:     my $cnum   = $env{'course.'.$env{'request.course.id'}.'.num'};
                   2453: 
1.44      ng       2454:     if ($button eq 'Save & Next') {
                   2455: 	my $ctr = 0;
                   2456: 	while ($ctr < $ngrade) {
1.257     albertel 2457: 	    my ($uname,$udom) = split(/:/,$env{'form.unamedom'.$ctr});
1.324     albertel 2458: 	    my ($errorflag,$pts,$wgt) = &saveHandGrade($request,$symb,$uname,$udom,$ctr);
1.71      ng       2459: 	    if ($errorflag eq 'no_score') {
                   2460: 		$ctr++;
                   2461: 		next;
                   2462: 	    }
1.104     albertel 2463: 	    if ($errorflag eq 'not_allowed') {
1.398     albertel 2464: 		$request->print("<span class=\"LC_warning\">Not allowed to modify grades for $uname:$udom</span>");
1.104     albertel 2465: 		$ctr++;
                   2466: 		next;
                   2467: 	    }
1.257     albertel 2468: 	    my $includemsg = $env{'form.includemsg'.$ctr};
1.44      ng       2469: 	    my ($subject,$message,$msgstatus) = ('','','');
1.418     albertel 2470: 	    my $restitle = &Apache::lonnet::gettitle($symb);
                   2471:             my ($feedurl,$showsymb) =
                   2472: 		&get_feedurl_and_symb($symb,$uname,$udom);
                   2473: 	    my $messagetail;
1.62      albertel 2474: 	    if ($includemsg =~ /savemsg|newmsg\Q$ctr\E/) {
1.298     www      2475: 		$subject = $env{'form.msgsub'} if ($includemsg =~ /msgsub/);
1.295     www      2476: 		unless ($subject=~/\w/) { $subject=&mt('Grading Feedback'); }
1.386     raeburn  2477: 		$subject.=' ['.$restitle.']';
1.44      ng       2478: 		my (@msgnum) = split(/,/,$includemsg);
                   2479: 		foreach (@msgnum) {
1.257     albertel 2480: 		    $message.=$env{'form.'.$_} if ($_ =~ /savemsg|newmsg/ && $_ ne '');
1.44      ng       2481: 		}
1.80      ng       2482: 		$message =&Apache::lonfeedback::clear_out_html($message);
1.298     www      2483: 		if ($env{'form.withgrades'.$ctr}) {
                   2484: 		    $message.="\n\nPoint".($pts > 1 ? 's':'').' awarded = '.$pts.' out of '.$wgt;
1.386     raeburn  2485: 		    $messagetail = " for <a href=\"".
1.605     www      2486: 		                   $feedurl."?symb=$showsymb\">$restitle</a>";
1.386     raeburn  2487: 		}
                   2488: 		$msgstatus = 
                   2489:                     &Apache::lonmsg::user_normal_msg($uname,$udom,$subject,
                   2490: 						     $message.$messagetail,
1.418     albertel 2491:                                                      undef,$feedurl,undef,
1.386     raeburn  2492:                                                      undef,undef,$showsymb,
                   2493:                                                      $restitle);
1.574     bisitz   2494: 		$request->print('<br />'.&mt('Sending message to [_1]',$uname.':'.$udom).': '.
1.296     www      2495: 				$msgstatus);
1.44      ng       2496: 	    }
1.257     albertel 2497: 	    if ($env{'form.collaborator'.$ctr}) {
1.155     albertel 2498: 		my @collabstrs=&Apache::loncommon::get_env_multiple("form.collaborator$ctr");
1.150     albertel 2499: 		foreach my $collabstr (@collabstrs) {
                   2500: 		    my ($part,@collaborators) = split(/:/,$collabstr);
1.310     banghart 2501: 		    foreach my $collaborator (@collaborators) {
1.150     albertel 2502: 			my ($errorflag,$pts,$wgt) = 
1.324     albertel 2503: 			    &saveHandGrade($request,$symb,$collaborator,$udom,$ctr,
1.257     albertel 2504: 					   $env{'form.unamedom'.$ctr},$part);
1.150     albertel 2505: 			if ($errorflag eq 'not_allowed') {
1.362     albertel 2506: 			    $request->print("<span class=\"LC_error\">".&mt('Not allowed to modify grades for [_1]',"$collaborator:$udom")."</span>");
1.150     albertel 2507: 			    next;
1.418     albertel 2508: 			} elsif ($message ne '') {
                   2509: 			    my ($baseurl,$showsymb) = 
                   2510: 				&get_feedurl_and_symb($symb,$collaborator,
                   2511: 						      $udom);
                   2512: 			    if ($env{'form.withgrades'.$ctr}) {
                   2513: 				$messagetail = " for <a href=\"".
1.605     www      2514:                                     $baseurl."?symb=$showsymb\">$restitle</a>";
1.150     albertel 2515: 			    }
1.418     albertel 2516: 			    $msgstatus = 
                   2517: 				&Apache::lonmsg::user_normal_msg($collaborator,$udom,$subject,$message.$messagetail,undef,$baseurl,undef,undef,undef,$showsymb,$restitle);
1.104     albertel 2518: 			}
1.44      ng       2519: 		    }
                   2520: 		}
                   2521: 	    }
                   2522: 	    $ctr++;
                   2523: 	}
                   2524:     }
                   2525: 
1.624     www      2526: #    if ($env{'form.handgrade'} eq 'yes') {
                   2527:     if (1) {
1.119     ng       2528: 	# Keywords sorted in alphabatical order
1.257     albertel 2529: 	my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
1.119     ng       2530: 	my %keyhash = ();
1.257     albertel 2531: 	$env{'form.keywords'}           =~ s/,\s{0,}|\s+/ /g;
                   2532: 	$env{'form.keywords'}           =~ s/^\s+|\s+$//;
                   2533: 	my (@keywords) = sort(split(/\s+/,$env{'form.keywords'}));
                   2534: 	$env{'form.keywords'} = join(' ',@keywords);
                   2535: 	$keyhash{$symb.'_keywords'}     = $env{'form.keywords'};
                   2536: 	$keyhash{$symb.'_subject'}      = $env{'form.msgsub'};
                   2537: 	$keyhash{$loginuser.'_kwclr'}   = $env{'form.kwclr'};
                   2538: 	$keyhash{$loginuser.'_kwsize'}  = $env{'form.kwsize'};
                   2539: 	$keyhash{$loginuser.'_kwstyle'} = $env{'form.kwstyle'};
1.119     ng       2540: 
                   2541: 	# message center - Order of message gets changed. Blank line is eliminated.
1.257     albertel 2542: 	# New messages are saved in env for the next student.
1.119     ng       2543: 	# All messages are saved in nohist_handgrade.db
                   2544: 	my ($ctr,$idx) = (1,1);
1.257     albertel 2545: 	while ($ctr <= $env{'form.savemsgN'}) {
                   2546: 	    if ($env{'form.savemsg'.$ctr} ne '') {
                   2547: 		$keyhash{$symb.'_savemsg'.$idx} = $env{'form.savemsg'.$ctr};
1.119     ng       2548: 		$idx++;
                   2549: 	    }
                   2550: 	    $ctr++;
1.41      ng       2551: 	}
1.119     ng       2552: 	$ctr = 0;
                   2553: 	while ($ctr < $ngrade) {
1.257     albertel 2554: 	    if ($env{'form.newmsg'.$ctr} ne '') {
                   2555: 		$keyhash{$symb.'_savemsg'.$idx} = $env{'form.newmsg'.$ctr};
                   2556: 		$env{'form.savemsg'.$idx} = $env{'form.newmsg'.$ctr};
1.119     ng       2557: 		$idx++;
                   2558: 	    }
                   2559: 	    $ctr++;
1.41      ng       2560: 	}
1.257     albertel 2561: 	$env{'form.savemsgN'} = --$idx;
                   2562: 	$keyhash{$symb.'_savemsgN'} = $env{'form.savemsgN'};
1.119     ng       2563: 	my $putresult = &Apache::lonnet::put
1.301     albertel 2564: 	    ('nohist_handgrade',\%keyhash,$cdom,$cnum);
1.41      ng       2565:     }
1.44      ng       2566:     # Called by Save & Refresh from Highlight Attribute Window
1.257     albertel 2567:     my (undef,undef,$fullname) = &getclasslist($env{'form.section'},'1');
                   2568:     if ($env{'form.refresh'} eq 'on') {
1.86      ng       2569: 	my ($ctr,$total) = (0,0);
                   2570: 	while ($ctr < $ngrade) {
1.257     albertel 2571: 	    $total++ if  $env{'form.unamedom'.$ctr} ne '';
1.86      ng       2572: 	    $ctr++;
                   2573: 	}
1.257     albertel 2574: 	$env{'form.NTSTU'}=$ngrade;
1.86      ng       2575: 	$ctr = 0;
                   2576: 	while ($ctr < $total) {
1.257     albertel 2577: 	    my $processUser = $env{'form.unamedom'.$ctr};
                   2578: 	    ($env{'form.student'},$env{'form.userdom'}) = split(/:/,$processUser);
                   2579: 	    $env{'form.fullname'} = $$fullname{$processUser};
1.625     www      2580: 	    &submission($request,$ctr,$total-1,$symb);
1.41      ng       2581: 	    $ctr++;
                   2582: 	}
                   2583: 	return '';
                   2584:     }
1.36      ng       2585: 
1.44      ng       2586:     # Get the next/previous one or group of students
1.257     albertel 2587:     my $firststu = $env{'form.unamedom0'};
                   2588:     my $laststu = $env{'form.unamedom'.($ngrade-1)};
1.119     ng       2589:     my $ctr = 2;
1.41      ng       2590:     while ($laststu eq '') {
1.257     albertel 2591: 	$laststu  = $env{'form.unamedom'.($ngrade-$ctr)};
1.41      ng       2592: 	$ctr++;
                   2593: 	$laststu = $firststu if ($ctr > $ngrade);
                   2594:     }
1.44      ng       2595: 
1.41      ng       2596:     my (@parsedlist,@nextlist);
                   2597:     my ($nextflg) = 0;
1.524     raeburn  2598:     foreach my $item (sort 
1.294     albertel 2599: 	     {
                   2600: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                   2601: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                   2602: 		 }
                   2603: 		 return $a cmp $b;
                   2604: 	     } (keys(%$fullname))) {
1.605     www      2605: # FIXME: this is fishy, looks like the button label
1.41      ng       2606: 	if ($nextflg == 1 && $button =~ /Next$/) {
1.524     raeburn  2607: 	    push(@parsedlist,$item);
1.41      ng       2608: 	}
1.524     raeburn  2609: 	$nextflg = 1 if ($item eq $laststu);
1.41      ng       2610: 	if ($button eq 'Previous') {
1.524     raeburn  2611: 	    last if ($item eq $firststu);
                   2612: 	    push(@parsedlist,$item);
1.41      ng       2613: 	}
                   2614:     }
                   2615:     $ctr = 0;
1.605     www      2616: # FIXME: this is fishy, looks like the button label
1.41      ng       2617:     @parsedlist = reverse @parsedlist if ($button eq 'Previous');
1.582     raeburn  2618:     my $res_error;
                   2619:     my ($partlist) = &response_type($symb,\$res_error);
                   2620:     if ($res_error) {
                   2621:         $request->print(&navmap_errormsg());
                   2622:         return;
                   2623:     }
1.41      ng       2624:     foreach my $student (@parsedlist) {
1.257     albertel 2625: 	my $submitonly=$env{'form.submitonly'};
1.41      ng       2626: 	my ($uname,$udom) = split(/:/,$student);
1.301     albertel 2627: 	
                   2628: 	if ($submitonly eq 'queued') {
                   2629: 	    my %queue_status = 
                   2630: 		&Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
                   2631: 							$udom,$uname);
                   2632: 	    next if (!defined($queue_status{'gradingqueue'}));
                   2633: 	}
                   2634: 
1.156     albertel 2635: 	if ($submitonly =~ /^(yes|graded|incorrect)$/) {
1.257     albertel 2636: #	    my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
1.324     albertel 2637: 	    my %status=&student_gradeStatus($symb,$udom,$uname,$partlist);
1.145     albertel 2638: 	    my $submitted = 0;
1.248     albertel 2639: 	    my $ungraded = 0;
                   2640: 	    my $incorrect = 0;
1.524     raeburn  2641: 	    foreach my $item (keys(%status)) {
                   2642: 		$submitted = 1 if ($status{$item} ne 'nothing');
                   2643: 		$ungraded = 1 if ($status{$item} =~ /^ungraded/);
                   2644: 		$incorrect = 1 if ($status{$item} =~ /^incorrect/);
                   2645: 		my ($foo,$partid,$foo1) = split(/\./,$item);
1.145     albertel 2646: 		if ($status{'resource.'.$partid.'.submitted_by'} ne '') {
                   2647: 		    $submitted = 0;
                   2648: 		}
1.41      ng       2649: 	    }
1.156     albertel 2650: 	    next if (!$submitted && ($submitonly eq 'yes' ||
                   2651: 				     $submitonly eq 'incorrect' ||
                   2652: 				     $submitonly eq 'graded'));
1.248     albertel 2653: 	    next if (!$ungraded && ($submitonly eq 'graded'));
                   2654: 	    next if (!$incorrect && $submitonly eq 'incorrect');
1.41      ng       2655: 	}
1.524     raeburn  2656: 	push(@nextlist,$student) if ($ctr < $ntstu);
1.129     ng       2657: 	last if ($ctr == $ntstu);
1.41      ng       2658: 	$ctr++;
                   2659:     }
1.36      ng       2660: 
1.41      ng       2661:     $ctr = 0;
                   2662:     my $total = scalar(@nextlist)-1;
1.39      ng       2663: 
1.524     raeburn  2664:     foreach (sort(@nextlist)) {
1.41      ng       2665: 	my ($uname,$udom,$submitter) = split(/:/);
1.257     albertel 2666: 	$env{'form.student'}  = $uname;
                   2667: 	$env{'form.userdom'}  = $udom;
                   2668: 	$env{'form.fullname'} = $$fullname{$_};
1.625     www      2669: 	&submission($request,$ctr,$total,$symb);
1.41      ng       2670: 	$ctr++;
                   2671:     }
                   2672:     if ($total < 0) {
1.632     www      2673: 	my $the_end.=&mt('<b>Message: </b> No more students for this section or class.').'<br /><br />'."\n";
1.41      ng       2674: 	$request->print($the_end);
                   2675:     }
                   2676:     return '';
1.38      ng       2677: }
1.36      ng       2678: 
1.44      ng       2679: #---- Save the score and award for each student, if changed
1.38      ng       2680: sub saveHandGrade {
1.324     albertel 2681:     my ($request,$symb,$stuname,$domain,$newflg,$submitter,$part) = @_;
1.342     banghart 2682:     my @version_parts;
1.104     albertel 2683:     my $usec = &Apache::lonnet::getsection($domain,$stuname,
1.257     albertel 2684: 					   $env{'request.course.id'});
1.104     albertel 2685:     if (!&canmodify($usec)) { return('not_allowed'); }
1.337     banghart 2686:     my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$domain,$stuname);
1.251     banghart 2687:     my @parts_graded;
1.77      ng       2688:     my %newrecord  = ();
                   2689:     my ($pts,$wgt) = ('','');
1.269     raeburn  2690:     my %aggregate = ();
                   2691:     my $aggregateflag = 0;
1.301     albertel 2692:     my @parts = split(/:/,$env{'form.partlist'.$newflg});
                   2693:     foreach my $new_part (@parts) {
1.337     banghart 2694: 	#collaborator ($submi may vary for different parts
1.259     banghart 2695: 	if ($submitter && $new_part ne $part) { next; }
                   2696: 	my $dropMenu = $env{'form.GD_SEL'.$newflg.'_'.$new_part};
1.125     ng       2697: 	if ($dropMenu eq 'excused') {
1.259     banghart 2698: 	    if ($record{'resource.'.$new_part.'.solved'} ne 'excused') {
                   2699: 		$newrecord{'resource.'.$new_part.'.solved'} = 'excused';
                   2700: 		if (exists($record{'resource.'.$new_part.'.awarded'})) {
                   2701: 		    $newrecord{'resource.'.$new_part.'.awarded'} = '';
1.58      albertel 2702: 		}
1.364     banghart 2703: 	        $newrecord{'resource.'.$new_part.'.regrader'}="$env{'user.name'}:$env{'user.domain'}";
1.58      albertel 2704: 	    }
1.125     ng       2705: 	} elsif ($dropMenu eq 'reset status'
1.259     banghart 2706: 		 && exists($record{'resource.'.$new_part.'.solved'})) { #don't bother if no old records -> no attempts
1.524     raeburn  2707: 	    foreach my $key (keys(%record)) {
1.259     banghart 2708: 		if ($key=~/^resource\.\Q$new_part\E\./) { $newrecord{$key} = ''; }
1.197     albertel 2709: 	    }
1.259     banghart 2710: 	    $newrecord{'resource.'.$new_part.'.regrader'}=
1.257     albertel 2711: 		"$env{'user.name'}:$env{'user.domain'}";
1.270     albertel 2712:             my $totaltries = $record{'resource.'.$part.'.tries'};
                   2713: 
                   2714:             my %last_resets = &get_last_resets($symb,$env{'request.course.id'},
                   2715: 					       [$new_part]);
                   2716:             my $aggtries =$totaltries;
1.269     raeburn  2717:             if ($last_resets{$new_part}) {
1.270     albertel 2718:                 $aggtries = &get_num_tries(\%record,$last_resets{$new_part},
                   2719: 					   $new_part);
1.269     raeburn  2720:             }
1.270     albertel 2721: 
                   2722:             my $solvedstatus = $record{'resource.'.$new_part.'.solved'};
1.269     raeburn  2723:             if ($aggtries > 0) {
1.327     albertel 2724:                 &decrement_aggs($symb,$new_part,\%aggregate,$aggtries,$totaltries,$solvedstatus);
1.269     raeburn  2725:                 $aggregateflag = 1;
                   2726:             }
1.125     ng       2727: 	} elsif ($dropMenu eq '') {
1.259     banghart 2728: 	    $pts = ($env{'form.GD_BOX'.$newflg.'_'.$new_part} ne '' ? 
                   2729: 		    $env{'form.GD_BOX'.$newflg.'_'.$new_part} : 
                   2730: 		    $env{'form.RADVAL'.$newflg.'_'.$new_part});
                   2731: 	    if ($pts eq '' && $env{'form.GD_SEL'.$newflg.'_'.$new_part} eq '') {
1.153     albertel 2732: 		next;
                   2733: 	    }
1.259     banghart 2734: 	    $wgt = $env{'form.WGT'.$newflg.'_'.$new_part} eq '' ? 1 : 
                   2735: 		$env{'form.WGT'.$newflg.'_'.$new_part};
1.41      ng       2736: 	    my $partial= $pts/$wgt;
1.259     banghart 2737: 	    if ($partial eq $record{'resource.'.$new_part.'.awarded'}) {
1.153     albertel 2738: 		#do not update score for part if not changed.
1.346     banghart 2739:                 &handback_files($request,$symb,$stuname,$domain,$newflg,$new_part,\%newrecord);
1.153     albertel 2740: 		next;
1.251     banghart 2741: 	    } else {
1.524     raeburn  2742: 	        push(@parts_graded,$new_part);
1.153     albertel 2743: 	    }
1.259     banghart 2744: 	    if ($record{'resource.'.$new_part.'.awarded'} ne $partial) {
                   2745: 		$newrecord{'resource.'.$new_part.'.awarded'}  = $partial;
1.153     albertel 2746: 	    }
1.259     banghart 2747: 	    my $reckey = 'resource.'.$new_part.'.solved';
1.41      ng       2748: 	    if ($partial == 0) {
1.153     albertel 2749: 		if ($record{$reckey} ne 'incorrect_by_override') {
                   2750: 		    $newrecord{$reckey} = 'incorrect_by_override';
                   2751: 		}
1.41      ng       2752: 	    } else {
1.153     albertel 2753: 		if ($record{$reckey} ne 'correct_by_override') {
                   2754: 		    $newrecord{$reckey} = 'correct_by_override';
                   2755: 		}
                   2756: 	    }	    
                   2757: 	    if ($submitter && 
1.259     banghart 2758: 		($record{'resource.'.$new_part.'.submitted_by'} ne $submitter)) {
                   2759: 		$newrecord{'resource.'.$new_part.'.submitted_by'} = $submitter;
1.41      ng       2760: 	    }
1.259     banghart 2761: 	    $newrecord{'resource.'.$new_part.'.regrader'}=
1.257     albertel 2762: 		"$env{'user.name'}:$env{'user.domain'}";
1.41      ng       2763: 	}
1.259     banghart 2764: 	# unless problem has been graded, set flag to version the submitted files
1.305     banghart 2765: 	unless ($record{'resource.'.$new_part.'.solved'} =~ /^correct_/  || 
                   2766: 	        $record{'resource.'.$new_part.'.solved'} eq 'incorrect_by_override' ||
                   2767: 	        $dropMenu eq 'reset status')
                   2768: 	   {
1.524     raeburn  2769: 	    push(@version_parts,$new_part);
1.259     banghart 2770: 	}
1.41      ng       2771:     }
1.301     albertel 2772:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   2773:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   2774: 
1.344     albertel 2775:     if (%newrecord) {
                   2776:         if (@version_parts) {
1.364     banghart 2777:             my @changed_keys = &version_portfiles(\%record, \@parts_graded, 
                   2778:                                 $env{'request.course.id'}, $symb, $domain, $stuname, \@version_parts);
1.344     albertel 2779: 	    @newrecord{@changed_keys} = @record{@changed_keys};
1.367     albertel 2780: 	    foreach my $new_part (@version_parts) {
                   2781: 		&handback_files($request,$symb,$stuname,$domain,$newflg,
                   2782: 				$new_part,\%newrecord);
                   2783: 	    }
1.259     banghart 2784:         }
1.44      ng       2785: 	&Apache::lonnet::cstore(\%newrecord,$symb,
1.257     albertel 2786: 				$env{'request.course.id'},$domain,$stuname);
1.380     albertel 2787: 	&check_and_remove_from_queue(\@parts,\%record,\%newrecord,$symb,
                   2788: 				     $cdom,$cnum,$domain,$stuname);
1.41      ng       2789:     }
1.269     raeburn  2790:     if ($aggregateflag) {
                   2791:         &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
1.301     albertel 2792: 			      $cdom,$cnum);
1.269     raeburn  2793:     }
1.301     albertel 2794:     return ('',$pts,$wgt);
1.36      ng       2795: }
1.322     albertel 2796: 
1.380     albertel 2797: sub check_and_remove_from_queue {
                   2798:     my ($parts,$record,$newrecord,$symb,$cdom,$cnum,$domain,$stuname) = @_;
                   2799:     my @ungraded_parts;
                   2800:     foreach my $part (@{$parts}) {
                   2801: 	if (    $record->{   'resource.'.$part.'.awarded'} eq ''
                   2802: 	     && $record->{   'resource.'.$part.'.solved' } ne 'excused'
                   2803: 	     && $newrecord->{'resource.'.$part.'.awarded'} eq ''
                   2804: 	     && $newrecord->{'resource.'.$part.'.solved' } ne 'excused'
                   2805: 		) {
                   2806: 	    push(@ungraded_parts, $part);
                   2807: 	}
                   2808:     }
                   2809:     if ( !@ungraded_parts ) {
                   2810: 	&Apache::bridgetask::remove_from_queue('gradingqueue',$symb,$cdom,
                   2811: 					       $cnum,$domain,$stuname);
                   2812:     }
                   2813: }
                   2814: 
1.337     banghart 2815: sub handback_files {
                   2816:     my ($request,$symb,$stuname,$domain,$newflg,$new_part,$newrecord) = @_;
1.517     raeburn  2817:     my $portfolio_root = '/userfiles/portfolio';
1.582     raeburn  2818:     my $res_error;
                   2819:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
                   2820:     if ($res_error) {
                   2821:         $request->print('<br />'.&navmap_errormsg().'<br />');
                   2822:         return;
                   2823:     }
1.375     albertel 2824:     my @part_response_id = &flatten_responseType($responseType);
                   2825:     foreach my $part_response_id (@part_response_id) {
                   2826:     	my ($part_id,$resp_id) = @{ $part_response_id };
                   2827: 	my $part_resp = join('_',@{ $part_response_id });
1.337     banghart 2828:             if (($env{'form.'.$newflg.'_'.$part_resp.'_returndoc1'}) && ($new_part == $part_id)) {
                   2829:                 # if multiple files are uploaded names will be 'returndoc2','returndoc3'
                   2830:                 my $file_counter = 1;
1.367     albertel 2831: 		my $file_msg;
1.337     banghart 2832:                 while ($env{'form.'.$newflg.'_'.$part_resp.'_returndoc'.$file_counter}) {
                   2833:                     my $fname=$env{'form.'.$newflg.'_'.$part_resp.'_returndoc'.$file_counter.'.filename'};
1.338     banghart 2834:                     my ($directory,$answer_file) = 
                   2835:                         ($env{'form.'.$newflg.'_'.$part_resp.'_origdoc'.$file_counter} =~ /^(.*?)([^\/]*)$/);
                   2836:                     my ($answer_name,$answer_ver,$answer_ext) =
                   2837: 		        &file_name_version_ext($answer_file);
1.355     banghart 2838: 		    my ($portfolio_path) = ($directory =~ /^.+$stuname\/portfolio(.*)/);
1.517     raeburn  2839:                     my $getpropath = 1;
                   2840: 		    my @dir_list = &Apache::lonnet::dirlist($portfolio_root.$portfolio_path,$domain,$stuname,$getpropath);
1.338     banghart 2841: 		    my $version = &get_next_version($answer_name, $answer_ext, \@dir_list);
1.355     banghart 2842:                     # fix file name
                   2843:                     my ($save_file_name) = (($directory.$answer_name.".$version.".$answer_ext) =~ /^.+\/${stuname}\/(.*)/);
                   2844:                     my $result=&Apache::lonnet::finishuserfileupload($stuname,$domain,
                   2845:             	                                $newflg.'_'.$part_resp.'_returndoc'.$file_counter,
                   2846:             	                                $save_file_name);
1.337     banghart 2847:                     if ($result !~ m|^/uploaded/|) {
1.536     raeburn  2848:                         $request->print('<br /><span class="LC_error">'.
                   2849:                             &mt('An error occurred ([_1]) while trying to upload [_2].',
                   2850:                                 $result,$newflg.'_'.$part_resp.'_returndoc'.$file_counter).
                   2851:                                         '</span>');
1.356     banghart 2852:                     } else {
1.360     banghart 2853:                         # mark the file as read only
                   2854:                         my @files = ($save_file_name);
1.372     albertel 2855:                         my @what = ($symb,$env{'request.course.id'},'handback');
1.360     banghart 2856:                         &Apache::lonnet::mark_as_readonly($domain,$stuname,\@files,\@what);
1.367     albertel 2857: 			if (exists($$newrecord{"resource.$new_part.$resp_id.handback"})) {
                   2858: 			    $$newrecord{"resource.$new_part.$resp_id.handback"}.=',';
                   2859: 			}
                   2860:                         $$newrecord{"resource.$new_part.$resp_id.handback"} .= $save_file_name;
                   2861: 			$file_msg.= "\n".'<br /><span class="LC_filename"><a href="/uploaded/'."$domain/$stuname/".$save_file_name.'">'.$save_file_name."</a></span><br />";
                   2862: 
1.337     banghart 2863:                     }
                   2864:                     $request->print("<br />".$fname." will be the uploaded file name");
1.354     albertel 2865:                     $request->print(" ".$env{'form.'.$newflg.'_'.$part_resp.'_origdoc'.$file_counter});
1.337     banghart 2866:                     $file_counter++;
                   2867:                 }
1.367     albertel 2868: 		my $subject = "File Handed Back by Instructor ";
                   2869: 		my $message = "A file has been returned that was originally submitted in reponse to: <br />";
                   2870: 		$message .= "<strong>".&Apache::lonnet::gettitle($symb)."</strong><br />";
                   2871: 		$message .= ' The returned file(s) are named: '. $file_msg;
                   2872: 		$message .= " and can be found in your portfolio space.";
1.418     albertel 2873: 		my ($feedurl,$showsymb) = 
                   2874: 		    &get_feedurl_and_symb($symb,$domain,$stuname);
1.386     raeburn  2875:                 my $restitle = &Apache::lonnet::gettitle($symb);
                   2876: 		my $msgstatus = 
                   2877:                    &Apache::lonmsg::user_normal_msg($stuname,$domain,$subject.
                   2878: 			 ' (File Returned) ['.$restitle.']',$message,undef,
1.418     albertel 2879:                          $feedurl,undef,undef,undef,$showsymb,$restitle);
1.337     banghart 2880:             }
                   2881:         }
1.338     banghart 2882:     return;
1.337     banghart 2883: }
                   2884: 
1.418     albertel 2885: sub get_feedurl_and_symb {
                   2886:     my ($symb,$uname,$udom) = @_;
                   2887:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
                   2888:     $url = &Apache::lonnet::clutter($url);
                   2889:     my $encrypturl=&Apache::lonnet::EXT('resource.0.encrypturl',
                   2890: 					$symb,$udom,$uname);
                   2891:     if ($encrypturl =~ /^yes$/i) {
                   2892: 	&Apache::lonenc::encrypted(\$url,1);
                   2893: 	&Apache::lonenc::encrypted(\$symb,1);
                   2894:     }
                   2895:     return ($url,$symb);
                   2896: }
                   2897: 
1.313     banghart 2898: sub get_submitted_files {
                   2899:     my ($udom,$uname,$partid,$respid,$record) = @_;
                   2900:     my @files;
                   2901:     if ($$record{"resource.$partid.$respid.portfiles"}) {
                   2902:         my $file_url = '/uploaded/'.$udom.'/'.$uname.'/portfolio';
                   2903:         foreach my $file (split(',',$$record{"resource.$partid.$respid.portfiles"})) {
                   2904:     	    push(@files,$file_url.$file);
                   2905:         }
                   2906:     }
                   2907:     if ($$record{"resource.$partid.$respid.uploadedurl"}) {
                   2908:         push(@files,$$record{"resource.$partid.$respid.uploadedurl"});
                   2909:     }
                   2910:     return (\@files);
                   2911: }
1.322     albertel 2912: 
1.269     raeburn  2913: # ----------- Provides number of tries since last reset.
                   2914: sub get_num_tries {
                   2915:     my ($record,$last_reset,$part) = @_;
                   2916:     my $timestamp = '';
                   2917:     my $num_tries = 0;
                   2918:     if ($$record{'version'}) {
                   2919:         for (my $version=$$record{'version'};$version>=1;$version--) {
                   2920:             if (exists($$record{$version.':resource.'.$part.'.solved'})) {
                   2921:                 $timestamp = $$record{$version.':timestamp'};
                   2922:                 if ($timestamp > $last_reset) {
                   2923:                     $num_tries ++;
                   2924:                 } else {
                   2925:                     last;
                   2926:                 }
                   2927:             }
                   2928:         }
                   2929:     }
                   2930:     return $num_tries;
                   2931: }
                   2932: 
                   2933: # ----------- Determine decrements required in aggregate totals 
                   2934: sub decrement_aggs {
                   2935:     my ($symb,$part,$aggregate,$aggtries,$totaltries,$solvedstatus) = @_;
                   2936:     my %decrement = (
                   2937:                         attempts => 0,
                   2938:                         users => 0,
                   2939:                         correct => 0
                   2940:                     );
                   2941:     $decrement{'attempts'} = $aggtries;
                   2942:     if ($solvedstatus =~ /^correct/) {
                   2943:         $decrement{'correct'} = 1;
                   2944:     }
                   2945:     if ($aggtries == $totaltries) {
                   2946:         $decrement{'users'} = 1;
                   2947:     }
1.524     raeburn  2948:     foreach my $type (keys(%decrement)) {
1.269     raeburn  2949:         $$aggregate{$symb."\0".$part."\0".$type} = -$decrement{$type};
                   2950:     }
                   2951:     return;
                   2952: }
                   2953: 
                   2954: # ----------- Determine timestamps for last reset of aggregate totals for parts  
                   2955: sub get_last_resets {
1.270     albertel 2956:     my ($symb,$courseid,$partids) =@_;
                   2957:     my %last_resets;
1.269     raeburn  2958:     my $cdom = $env{'course.'.$courseid.'.domain'};
                   2959:     my $cname = $env{'course.'.$courseid.'.num'};
1.271     albertel 2960:     my @keys;
                   2961:     foreach my $part (@{$partids}) {
                   2962: 	push(@keys,"$symb\0$part\0resettime");
                   2963:     }
                   2964:     my %results=&Apache::lonnet::get('nohist_resourcetracker',\@keys,
                   2965: 				     $cdom,$cname);
                   2966:     foreach my $part (@{$partids}) {
                   2967: 	$last_resets{$part}=$results{"$symb\0$part\0resettime"};
1.269     raeburn  2968:     }
1.270     albertel 2969:     return %last_resets;
1.269     raeburn  2970: }
                   2971: 
1.251     banghart 2972: # ----------- Handles creating versions for portfolio files as answers
                   2973: sub version_portfiles {
1.343     banghart 2974:     my ($record, $parts_graded, $courseid, $symb, $domain, $stu_name, $v_flag) = @_;
1.263     banghart 2975:     my $version_parts = join('|',@$v_flag);
1.343     banghart 2976:     my @returned_keys;
1.255     banghart 2977:     my $parts = join('|', @$parts_graded);
1.517     raeburn  2978:     my $portfolio_root = '/userfiles/portfolio';
1.277     albertel 2979:     foreach my $key (keys(%$record)) {
1.259     banghart 2980:         my $new_portfiles;
1.263     banghart 2981:         if ($key =~ /^resource\.($version_parts)\./ && $key =~ /\.portfiles$/ ) {
1.342     banghart 2982:             my @versioned_portfiles;
1.367     albertel 2983:             my @portfiles = split(/\s*,\s*/,$$record{$key});
1.252     banghart 2984:             foreach my $file (@portfiles) {
1.306     banghart 2985:                 &Apache::lonnet::unmark_as_readonly($domain,$stu_name,[$symb,$env{'request.course.id'}],$file);
1.304     albertel 2986:                 my ($directory,$answer_file) =($file =~ /^(.*?)([^\/]*)$/);
                   2987: 		my ($answer_name,$answer_ver,$answer_ext) =
                   2988: 		    &file_name_version_ext($answer_file);
1.517     raeburn  2989:                 my $getpropath = 1;    
                   2990:                 my @dir_list = &Apache::lonnet::dirlist($portfolio_root.$directory,$domain,$stu_name,$getpropath);
1.342     banghart 2991:                 my $version = &get_next_version($answer_name, $answer_ext, \@dir_list);
1.306     banghart 2992:                 my $new_answer = &version_selected_portfile($domain, $stu_name, $directory, $answer_file, $version);
                   2993:                 if ($new_answer ne 'problem getting file') {
1.342     banghart 2994:                     push(@versioned_portfiles, $directory.$new_answer);
1.306     banghart 2995:                     &Apache::lonnet::mark_as_readonly($domain,$stu_name,
1.367     albertel 2996:                         [$directory.$new_answer],
1.306     banghart 2997:                         [$symb,$env{'request.course.id'},'graded']);
1.259     banghart 2998:                 }
1.252     banghart 2999:             }
1.343     banghart 3000:             $$record{$key} = join(',',@versioned_portfiles);
                   3001:             push(@returned_keys,$key);
1.251     banghart 3002:         }
                   3003:     } 
1.343     banghart 3004:     return (@returned_keys);   
1.305     banghart 3005: }
                   3006: 
1.307     banghart 3007: sub get_next_version {
1.341     banghart 3008:     my ($answer_name, $answer_ext, $dir_list) = @_;
1.307     banghart 3009:     my $version;
                   3010:     foreach my $row (@$dir_list) {
                   3011:         my ($file) = split(/\&/,$row,2);
                   3012:         my ($file_name,$file_version,$file_ext) =
                   3013: 	    &file_name_version_ext($file);
                   3014:         if (($file_name eq $answer_name) && 
                   3015: 	    ($file_ext eq $answer_ext)) {
                   3016:                 # gets here if filename and extension match, regardless of version
                   3017:                 if ($file_version ne '') {
                   3018:                 # a versioned file is found  so save it for later
                   3019:                 if ($file_version > $version) {
                   3020: 		    $version = $file_version;
                   3021: 	        }
                   3022:             }
                   3023:         }
                   3024:     } 
                   3025:     $version ++;
                   3026:     return($version);
                   3027: }
                   3028: 
1.305     banghart 3029: sub version_selected_portfile {
1.306     banghart 3030:     my ($domain,$stu_name,$directory,$file_name,$version) = @_;
                   3031:     my ($answer_name,$answer_ver,$answer_ext) =
                   3032:         &file_name_version_ext($file_name);
                   3033:     my $new_answer;
                   3034:     $env{'form.copy'} = &Apache::lonnet::getfile("/uploaded/$domain/$stu_name/portfolio$directory$file_name");
                   3035:     if($env{'form.copy'} eq '-1') {
                   3036:         $new_answer = 'problem getting file';
                   3037:     } else {
                   3038:         $new_answer = $answer_name.'.'.$version.'.'.$answer_ext;
                   3039:         my $copy_result = &Apache::lonnet::finishuserfileupload(
                   3040:                             $stu_name,$domain,'copy',
                   3041: 		        '/portfolio'.$directory.$new_answer);
                   3042:     }    
                   3043:     return ($new_answer);
1.251     banghart 3044: }
                   3045: 
1.304     albertel 3046: sub file_name_version_ext {
                   3047:     my ($file)=@_;
                   3048:     my @file_parts = split(/\./, $file);
                   3049:     my ($name,$version,$ext);
                   3050:     if (@file_parts > 1) {
                   3051: 	$ext=pop(@file_parts);
                   3052: 	if (@file_parts > 1 && $file_parts[-1] =~ /^\d+$/) {
                   3053: 	    $version=pop(@file_parts);
                   3054: 	}
                   3055: 	$name=join('.',@file_parts);
                   3056:     } else {
                   3057: 	$name=join('.',@file_parts);
                   3058:     }
                   3059:     return($name,$version,$ext);
                   3060: }
                   3061: 
1.44      ng       3062: #--------------------------------------------------------------------------------------
                   3063: #
                   3064: #-------------------------- Next few routines handles grading by section or whole class
                   3065: #
                   3066: #--- Javascript to handle grading by section or whole class
1.42      ng       3067: sub viewgrades_js {
                   3068:     my ($request) = shift;
                   3069: 
1.539     riegler  3070:     my $alertmsg = &mt('A number equal or greater than 0 is expected. Entered value = ');
1.597     wenzelju 3071:     $request->print(&Apache::lonhtmlcommon::scripttag(<<VIEWJAVASCRIPT));
1.45      ng       3072:    function writePoint(partid,weight,point) {
1.125     ng       3073: 	var radioButton = document.classgrade["RADVAL_"+partid];
                   3074: 	var textbox = document.classgrade["TEXTVAL_"+partid];
1.42      ng       3075: 	if (point == "textval") {
1.125     ng       3076: 	    point = document.classgrade["TEXTVAL_"+partid].value;
1.109     matthew  3077: 	    if (isNaN(point) || parseFloat(point) < 0) {
1.539     riegler  3078: 		alert("$alertmsg"+parseFloat(point));
1.42      ng       3079: 		var resetbox = false;
                   3080: 		for (var i=0; i<radioButton.length; i++) {
                   3081: 		    if (radioButton[i].checked) {
                   3082: 			textbox.value = i;
                   3083: 			resetbox = true;
                   3084: 		    }
                   3085: 		}
                   3086: 		if (!resetbox) {
                   3087: 		    textbox.value = "";
                   3088: 		}
                   3089: 		return;
                   3090: 	    }
1.109     matthew  3091: 	    if (parseFloat(point) > parseFloat(weight)) {
                   3092: 		var resp = confirm("You entered a value ("+parseFloat(point)+
1.44      ng       3093: 				   ") greater than the weight for the part. Accept?");
                   3094: 		if (resp == false) {
                   3095: 		    textbox.value = "";
                   3096: 		    return;
                   3097: 		}
                   3098: 	    }
1.42      ng       3099: 	    for (var i=0; i<radioButton.length; i++) {
                   3100: 		radioButton[i].checked=false;
1.109     matthew  3101: 		if (parseFloat(point) == i) {
1.42      ng       3102: 		    radioButton[i].checked=true;
                   3103: 		}
                   3104: 	    }
1.41      ng       3105: 
1.42      ng       3106: 	} else {
1.125     ng       3107: 	    textbox.value = parseFloat(point);
1.42      ng       3108: 	}
1.41      ng       3109: 	for (i=0;i<document.classgrade.total.value;i++) {
1.125     ng       3110: 	    var user = document.classgrade["ctr"+i].value;
1.289     albertel 3111: 	    user = user.replace(new RegExp(':', 'g'),"_");
1.125     ng       3112: 	    var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
                   3113: 	    var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
                   3114: 	    var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
1.42      ng       3115: 	    if (saveval != "correct") {
                   3116: 		scorename.value = point;
1.43      ng       3117: 		if (selname[0].selected != true) {
                   3118: 		    selname[0].selected = true;
                   3119: 		}
1.42      ng       3120: 	    }
                   3121: 	}
1.125     ng       3122: 	document.classgrade["SELVAL_"+partid][0].selected = true;
1.42      ng       3123:     }
                   3124: 
                   3125:     function writeRadText(partid,weight) {
1.125     ng       3126: 	var selval   = document.classgrade["SELVAL_"+partid];
                   3127: 	var radioButton = document.classgrade["RADVAL_"+partid];
1.265     www      3128:         var override = document.classgrade["FORCE_"+partid].checked;
1.125     ng       3129: 	var textbox = document.classgrade["TEXTVAL_"+partid];
                   3130: 	if (selval[1].selected || selval[2].selected) {
1.42      ng       3131: 	    for (var i=0; i<radioButton.length; i++) {
                   3132: 		radioButton[i].checked=false;
                   3133: 
                   3134: 	    }
                   3135: 	    textbox.value = "";
                   3136: 
                   3137: 	    for (i=0;i<document.classgrade.total.value;i++) {
1.125     ng       3138: 		var user = document.classgrade["ctr"+i].value;
1.289     albertel 3139: 		user = user.replace(new RegExp(':', 'g'),"_");
1.125     ng       3140: 		var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
                   3141: 		var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
                   3142: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
1.265     www      3143: 		if ((saveval != "correct") || override) {
1.42      ng       3144: 		    scorename.value = "";
1.125     ng       3145: 		    if (selval[1].selected) {
                   3146: 			selname[1].selected = true;
                   3147: 		    } else {
                   3148: 			selname[2].selected = true;
                   3149: 			if (Number(document.classgrade["GD_"+user+"_"+partid+"_tries"].value)) 
                   3150: 			{document.classgrade["GD_"+user+"_"+partid+"_tries"].value = '0';}
                   3151: 		    }
1.42      ng       3152: 		}
                   3153: 	    }
1.43      ng       3154: 	} else {
                   3155: 	    for (i=0;i<document.classgrade.total.value;i++) {
1.125     ng       3156: 		var user = document.classgrade["ctr"+i].value;
1.289     albertel 3157: 		user = user.replace(new RegExp(':', 'g'),"_");
1.125     ng       3158: 		var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
                   3159: 		var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
                   3160: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
1.265     www      3161: 		if ((saveval != "correct") || override) {
1.125     ng       3162: 		    scorename.value = document.classgrade["GD_"+user+"_"+partid+"_awarded_s"].value;
1.43      ng       3163: 		    selname[0].selected = true;
                   3164: 		}
                   3165: 	    }
                   3166: 	}	    
1.42      ng       3167:     }
                   3168: 
                   3169:     function changeSelect(partid,user) {
1.125     ng       3170: 	var selval = document.classgrade["GD_"+user+'_'+partid+"_solved"];
                   3171: 	var textbox = document.classgrade["GD_"+user+'_'+partid+"_awarded"];
1.44      ng       3172: 	var point  = textbox.value;
1.125     ng       3173: 	var weight = document.classgrade["weight_"+partid].value;
1.44      ng       3174: 
1.109     matthew  3175: 	if (isNaN(point) || parseFloat(point) < 0) {
1.539     riegler  3176: 	    alert("$alertmsg"+parseFloat(point));
1.44      ng       3177: 	    textbox.value = "";
                   3178: 	    return;
                   3179: 	}
1.109     matthew  3180: 	if (parseFloat(point) > parseFloat(weight)) {
                   3181: 	    var resp = confirm("You entered a value ("+parseFloat(point)+
1.44      ng       3182: 			       ") greater than the weight of the part. Accept?");
                   3183: 	    if (resp == false) {
                   3184: 		textbox.value = "";
                   3185: 		return;
                   3186: 	    }
                   3187: 	}
1.42      ng       3188: 	selval[0].selected = true;
                   3189:     }
                   3190: 
                   3191:     function changeOneScore(partid,user) {
1.125     ng       3192: 	var selval = document.classgrade["GD_"+user+'_'+partid+"_solved"];
                   3193: 	if (selval[1].selected || selval[2].selected) {
                   3194: 	    document.classgrade["GD_"+user+'_'+partid+"_awarded"].value = "";
                   3195: 	    if (selval[2].selected) {
                   3196: 		document.classgrade["GD_"+user+'_'+partid+"_tries"].value = "0";
                   3197: 	    }
1.269     raeburn  3198:         }
1.42      ng       3199:     }
                   3200: 
                   3201:     function resetEntry(numpart) {
                   3202: 	for (ctpart=0;ctpart<numpart;ctpart++) {
1.125     ng       3203: 	    var partid = document.classgrade["partid_"+ctpart].value;
                   3204: 	    var radioButton = document.classgrade["RADVAL_"+partid];
                   3205: 	    var textbox = document.classgrade["TEXTVAL_"+partid];
                   3206: 	    var selval  = document.classgrade["SELVAL_"+partid];
1.42      ng       3207: 	    for (var i=0; i<radioButton.length; i++) {
                   3208: 		radioButton[i].checked=false;
                   3209: 
                   3210: 	    }
                   3211: 	    textbox.value = "";
                   3212: 	    selval[0].selected = true;
                   3213: 
                   3214: 	    for (i=0;i<document.classgrade.total.value;i++) {
1.125     ng       3215: 		var user = document.classgrade["ctr"+i].value;
1.289     albertel 3216: 		user = user.replace(new RegExp(':', 'g'),"_");
1.125     ng       3217: 		var resetscore = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
                   3218: 		resetscore.value = document.classgrade["GD_"+user+"_"+partid+"_awarded_s"].value;
                   3219: 		var resettries = document.classgrade["GD_"+user+"_"+partid+"_tries"];
                   3220: 		resettries.value = document.classgrade["GD_"+user+"_"+partid+"_tries_s"].value;
                   3221: 		var saveselval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
                   3222: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
1.42      ng       3223: 		if (saveselval == "excused") {
1.43      ng       3224: 		    if (selname[1].selected == false) { selname[1].selected = true;}
1.42      ng       3225: 		} else {
1.43      ng       3226: 		    if (selname[0].selected == false) {selname[0].selected = true};
1.42      ng       3227: 		}
                   3228: 	    }
1.41      ng       3229: 	}
1.42      ng       3230:     }
                   3231: 
1.41      ng       3232: VIEWJAVASCRIPT
1.42      ng       3233: }
                   3234: 
1.44      ng       3235: #--- show scores for a section or whole class w/ option to change/update a score
1.42      ng       3236: sub viewgrades {
1.608     www      3237:     my ($request,$symb) = @_;
1.42      ng       3238:     &viewgrades_js($request);
1.41      ng       3239: 
1.168     albertel 3240:     #need to make sure we have the correct data for later EXT calls, 
                   3241:     #thus invalidate the cache
                   3242:     &Apache::lonnet::devalidatecourseresdata(
1.257     albertel 3243:                  $env{'course.'.$env{'request.course.id'}.'.num'},
                   3244:                  $env{'course.'.$env{'request.course.id'}.'.domain'});
1.168     albertel 3245:     &Apache::lonnet::clear_EXT_cache_status();
                   3246: 
1.398     albertel 3247:     my $result='<h3><span class="LC_info">'.&mt('Manual Grading').'</span></h3>';
1.41      ng       3248: 
                   3249:     #view individual student submission form - called using Javascript viewOneStudent
1.324     albertel 3250:     $result.=&jscriptNform($symb);
1.41      ng       3251: 
1.44      ng       3252:     #beginning of class grading form
1.442     banghart 3253:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
1.41      ng       3254:     $result.= '<form action="/adm/grades" method="post" name="classgrade">'."\n".
1.418     albertel 3255: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.38      ng       3256: 	'<input type="hidden" name="command" value="editgrades" />'."\n".
1.432     banghart 3257: 	&build_section_inputs().
1.442     banghart 3258: 	'<input type="hidden" name="Status" value="'.$env{'stu_status'}.'" />'."\n".
1.72      ng       3259: 
1.560     raeburn  3260:     my ($common_header,$specific_header);
1.257     albertel 3261:     if ($env{'form.section'} eq 'all') {
1.560     raeburn  3262: 	$common_header = &mt('Assign Common Grade to Class');
                   3263:         $specific_header = &mt('Assign Grade to Specific Students in Class');
1.257     albertel 3264:     } elsif ($env{'form.section'} eq 'none') {
1.560     raeburn  3265:         $common_header = &mt('Assign Common Grade to Students in no Section');
                   3266: 	$specific_header = &mt('Assign Grade to Specific Students in no Section');
1.52      albertel 3267:     } else {
1.560     raeburn  3268:         my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
                   3269:         $common_header = &mt('Assign Common Grade to Students in Section(s) [_1]',$section_display);
                   3270: 	$specific_header = &mt('Assign Grade to Specific Students in Section(s) [_1]',$section_display);
1.52      albertel 3271:     }
1.560     raeburn  3272:     $result.= '<h3>'.$common_header.'</h3>'.&Apache::loncommon::start_data_table();
1.44      ng       3273:     #radio buttons/text box for assigning points for a section or class.
                   3274:     #handles different parts of a problem
1.582     raeburn  3275:     my $res_error;
                   3276:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
                   3277:     if ($res_error) {
                   3278:         return &navmap_errormsg();
                   3279:     }
1.42      ng       3280:     my %weight = ();
                   3281:     my $ctsparts = 0;
1.45      ng       3282:     my %seen = ();
1.375     albertel 3283:     my @part_response_id = &flatten_responseType($responseType);
                   3284:     foreach my $part_response_id (@part_response_id) {
                   3285:     	my ($partid,$respid) = @{ $part_response_id };
                   3286: 	my $part_resp = join('_',@{ $part_response_id });
1.45      ng       3287: 	next if $seen{$partid};
                   3288: 	$seen{$partid}++;
1.375     albertel 3289: 	my $handgrade=$$handgrade{$part_resp};
1.42      ng       3290: 	my $wgt = &Apache::lonnet::EXT('resource.'.$partid.'.weight',$symb);
                   3291: 	$weight{$partid} = $wgt eq '' ? '1' : $wgt;
                   3292: 
1.324     albertel 3293: 	my $display_part=&get_display_part($partid,$symb);
1.485     albertel 3294: 	my $radio.='<table border="0"><tr>';  
1.41      ng       3295: 	my $ctr = 0;
1.42      ng       3296: 	while ($ctr<=$weight{$partid}) { # display radio buttons in a nice table 10 across
1.485     albertel 3297: 	    $radio.= '<td><label><input type="radio" name="RADVAL_'.$partid.'" '.
1.54      albertel 3298: 		'onclick="javascript:writePoint(\''.$partid.'\','.$weight{$partid}.
1.288     albertel 3299: 		','.$ctr.')" />'.$ctr."</label></td>\n";
1.41      ng       3300: 	    $result.=(($ctr+1)%10 == 0 ? '</tr><tr>' : '');
                   3301: 	    $ctr++;
                   3302: 	}
1.485     albertel 3303: 	$radio.='</tr></table>';
                   3304: 	my $line = '<input type="text" name="TEXTVAL_'.
1.589     bisitz   3305: 	    $partid.'" size="4" '.'onchange="javascript:writePoint(\''.
1.54      albertel 3306: 		$partid.'\','.$weight{$partid}.',\'textval\')" /> /'.
1.539     riegler  3307: 	    $weight{$partid}.' '.&mt('(problem weight)').'</td>'."\n";
                   3308: 	$line.= '<td><b>'.&mt('Grade Status').':</b><select name="SELVAL_'.$partid.'"'.
1.589     bisitz   3309: 	    'onchange="javascript:writeRadText(\''.$partid.'\','.
1.59      albertel 3310: 		$weight{$partid}.')"> '.
1.401     albertel 3311: 	    '<option selected="selected"> </option>'.
1.485     albertel 3312: 	    '<option value="excused">'.&mt('excused').'</option>'.
                   3313: 	    '<option value="reset status">'.&mt('reset status').'</option>'.
                   3314: 	    '</select></td>'.
                   3315:             '<td><label><input type="checkbox" name="FORCE_'.$partid.'" />'.&mt('Override "Correct"').'</label>';
                   3316: 	$line.='<input type="hidden" name="partid_'.
                   3317: 	    $ctsparts.'" value="'.$partid.'" />'."\n";
                   3318: 	$line.='<input type="hidden" name="weight_'.
                   3319: 	    $partid.'" value="'.$weight{$partid}.'" />'."\n";
                   3320: 
                   3321: 	$result.=
                   3322: 	    &Apache::loncommon::start_data_table_row()."\n".
1.577     bisitz   3323: 	    '<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 3324: 	    &Apache::loncommon::end_data_table_row()."\n";
1.42      ng       3325: 	$ctsparts++;
1.41      ng       3326:     }
1.474     albertel 3327:     $result.=&Apache::loncommon::end_data_table()."\n".
1.52      albertel 3328: 	'<input type="hidden" name="totalparts" value="'.$ctsparts.'" />';
1.485     albertel 3329:     $result.='<input type="button" value="'.&mt('Revert to Default').'" '.
1.589     bisitz   3330: 	'onclick="javascript:resetEntry('.$ctsparts.');" />';
1.41      ng       3331: 
1.44      ng       3332:     #table listing all the students in a section/class
                   3333:     #header of table
1.560     raeburn  3334:     $result.= '<h3>'.$specific_header.'</h3>'.
                   3335:               &Apache::loncommon::start_data_table().
                   3336: 	      &Apache::loncommon::start_data_table_header_row().
                   3337: 	      '<th>'.&mt('No.').'</th>'.
                   3338: 	      '<th>'.&nameUserString('header')."</th>\n";
1.582     raeburn  3339:     my $partserror;
                   3340:     my (@parts) = sort(&getpartlist($symb,\$partserror));
                   3341:     if ($partserror) {
                   3342:         return &navmap_errormsg();
                   3343:     }
1.324     albertel 3344:     my (undef,undef,$url)=&Apache::lonnet::decode_symb($symb);
1.269     raeburn  3345:     my @partids = ();
1.41      ng       3346:     foreach my $part (@parts) {
                   3347: 	my $display=&Apache::lonnet::metadata($url,$part.'.display');
1.539     riegler  3348:         my $narrowtext = &mt('Tries');
                   3349: 	$display =~ s|^Number of Attempts|$narrowtext <br />|; # makes the column narrower
1.41      ng       3350: 	if  (!$display) { $display = &Apache::lonnet::metadata($url,$part.'.name'); }
1.207     albertel 3351: 	my ($partid) = &split_part_type($part);
1.524     raeburn  3352:         push(@partids,$partid);
1.628     www      3353: #
                   3354: # FIXME: Looks like $display looks at English text
                   3355: #
1.324     albertel 3356: 	my $display_part=&get_display_part($partid,$symb);
1.41      ng       3357: 	if ($display =~ /^Partial Credit Factor/) {
1.485     albertel 3358: 	    $result.='<th>'.
                   3359: 		&mt('Score Part: [_1]<br /> (weight = [_2])',
                   3360: 		    $display_part,$weight{$partid}).'</th>'."\n";
1.41      ng       3361: 	    next;
1.485     albertel 3362: 	    
1.207     albertel 3363: 	} else {
1.485     albertel 3364: 	    if ($display =~ /Problem Status/) {
                   3365: 		my $grade_status_mt = &mt('Grade Status');
                   3366: 		$display =~ s{Problem Status}{$grade_status_mt<br />};
                   3367: 	    }
                   3368: 	    my $part_mt = &mt('Part:');
                   3369: 	    $display =~s{\[Part: \Q$partid\E\]}{$part_mt $display_part};
1.41      ng       3370: 	}
1.485     albertel 3371: 
1.474     albertel 3372: 	$result.='<th>'.$display.'</th>'."\n";
1.41      ng       3373:     }
1.474     albertel 3374:     $result.=&Apache::loncommon::end_data_table_header_row();
1.44      ng       3375: 
1.270     albertel 3376:     my %last_resets = 
                   3377: 	&get_last_resets($symb,$env{'request.course.id'},\@partids);
1.269     raeburn  3378: 
1.41      ng       3379:     #get info for each student
1.44      ng       3380:     #list all the students - with points and grade status
1.257     albertel 3381:     my (undef,undef,$fullname) = &getclasslist($env{'form.section'},'1');
1.41      ng       3382:     my $ctr = 0;
1.294     albertel 3383:     foreach (sort 
                   3384: 	     {
                   3385: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                   3386: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                   3387: 		 }
                   3388: 		 return $a cmp $b;
                   3389: 	     } (keys(%$fullname))) {
1.126     ng       3390: 	$ctr++;
1.324     albertel 3391: 	$result.=&viewstudentgrade($symb,$env{'request.course.id'},
1.269     raeburn  3392: 				   $_,$$fullname{$_},\@parts,\%weight,$ctr,\%last_resets);
1.41      ng       3393:     }
1.474     albertel 3394:     $result.=&Apache::loncommon::end_data_table();
1.41      ng       3395:     $result.='<input type="hidden" name="total" value="'.$ctr.'" />'."\n";
1.485     albertel 3396:     $result.='<input type="button" value="'.&mt('Save').'" '.
1.589     bisitz   3397: 	'onclick="javascript:submit();" target="_self" /></form>'."\n";
1.96      albertel 3398:     if (scalar(%$fullname) eq 0) {
                   3399: 	my $colspan=3+scalar(@parts);
1.433     banghart 3400: 	my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
1.442     banghart 3401:         my $stu_status = join(' or ',&Apache::loncommon::get_env_multiple('form.Status'));
1.433     banghart 3402: 	$result='<span class="LC_warning">'.
1.485     albertel 3403: 	    &mt('There are no students in section(s) [_1] with enrollment status [_2] to modify or grade.',
1.442     banghart 3404: 	        $section_display, $stu_status).
1.433     banghart 3405: 	    '</span>';
1.96      albertel 3406:     }
1.41      ng       3407:     return $result;
                   3408: }
                   3409: 
1.44      ng       3410: #--- call by previous routine to display each student
1.41      ng       3411: sub viewstudentgrade {
1.324     albertel 3412:     my ($symb,$courseid,$student,$fullname,$parts,$weight,$ctr,$last_resets) = @_;
1.44      ng       3413:     my ($uname,$udom) = split(/:/,$student);
                   3414:     my %record=&Apache::lonnet::restore($symb,$courseid,$udom,$uname);
1.269     raeburn  3415:     my %aggregates = (); 
1.474     albertel 3416:     my $result=&Apache::loncommon::start_data_table_row().'<td align="right">'.
1.233     albertel 3417: 	'<input type="hidden" name="ctr'.($ctr-1).'" value="'.$student.'" />'.
                   3418: 	"\n".$ctr.'&nbsp;</td><td>&nbsp;'.
1.44      ng       3419: 	'<a href="javascript:viewOneStudent(\''.$uname.'\',\''.$udom.
1.417     albertel 3420: 	'\');" target="_self">'.$fullname.'</a> '.
1.398     albertel 3421: 	'<span class="LC_internal_info">('.$uname.($env{'user.domain'} eq $udom ? '' : ':'.$udom).')</span></td>'."\n";
1.281     albertel 3422:     $student=~s/:/_/; # colon doen't work in javascript for names
1.63      albertel 3423:     foreach my $apart (@$parts) {
                   3424: 	my ($part,$type) = &split_part_type($apart);
1.41      ng       3425: 	my $score=$record{"resource.$part.$type"};
1.276     albertel 3426:         $result.='<td align="center">';
1.269     raeburn  3427:         my ($aggtries,$totaltries);
                   3428:         unless (exists($aggregates{$part})) {
1.270     albertel 3429: 	    $totaltries = $record{'resource.'.$part.'.tries'};
                   3430: 
                   3431: 	    $aggtries = $totaltries;
1.269     raeburn  3432:             if ($$last_resets{$part}) {  
1.270     albertel 3433:                 $aggtries = &get_num_tries(\%record,$$last_resets{$part},
                   3434: 					   $part);
                   3435:             }
1.269     raeburn  3436:             $result.='<input type="hidden" name="'.
                   3437:                 'GD_'.$student.'_'.$part.'_aggtries" value="'.$aggtries.'" />'."\n";
                   3438:             $result.='<input type="hidden" name="'.
                   3439:                 'GD_'.$student.'_'.$part.'_totaltries" value="'.$totaltries.'" />'."\n";
                   3440:             $aggregates{$part} = 1;
                   3441:         }
1.41      ng       3442: 	if ($type eq 'awarded') {
1.320     albertel 3443: 	    my $pts = $score eq '' ? '' : &compute_points($score,$$weight{$part});
1.42      ng       3444: 	    $result.='<input type="hidden" name="'.
1.89      albertel 3445: 		'GD_'.$student.'_'.$part.'_awarded_s" value="'.$pts.'" />'."\n";
1.233     albertel 3446: 	    $result.='<input type="text" name="'.
1.89      albertel 3447: 		'GD_'.$student.'_'.$part.'_awarded" '.
1.589     bisitz   3448:                 'onchange="javascript:changeSelect(\''.$part.'\',\''.$student.
1.44      ng       3449: 		'\')" value="'.$pts.'" size="4" /></td>'."\n";
1.41      ng       3450: 	} elsif ($type eq 'solved') {
                   3451: 	    my ($status,$foo)=split(/_/,$score,2);
                   3452: 	    $status = 'nothing' if ($status eq '');
1.89      albertel 3453: 	    $result.='<input type="hidden" name="'.'GD_'.$student.'_'.
1.54      albertel 3454: 		$part.'_solved_s" value="'.$status.'" />'."\n";
1.233     albertel 3455: 	    $result.='&nbsp;<select name="'.
1.89      albertel 3456: 		'GD_'.$student.'_'.$part.'_solved" '.
1.589     bisitz   3457:                 'onchange="javascript:changeOneScore(\''.$part.'\',\''.$student.'\')" >'."\n";
1.485     albertel 3458: 	    $result.= (($status eq 'excused') ? '<option> </option><option selected="selected" value="excused">'.&mt('excused').'</option>' 
                   3459: 		: '<option selected="selected"> </option><option value="excused">'.&mt('excused').'</option>')."\n";
                   3460: 	    $result.='<option value="reset status">'.&mt('reset status').'</option>';
1.126     ng       3461: 	    $result.="</select>&nbsp;</td>\n";
1.122     ng       3462: 	} else {
                   3463: 	    $result.='<input type="hidden" name="'.
                   3464: 		'GD_'.$student.'_'.$part.'_'.$type.'_s" value="'.$score.'" />'.
                   3465: 		    "\n";
1.233     albertel 3466: 	    $result.='<input type="text" name="'.
1.122     ng       3467: 		'GD_'.$student.'_'.$part.'_'.$type.'" '.
                   3468: 		'value="'.$score.'" size="4" /></td>'."\n";
1.41      ng       3469: 	}
                   3470:     }
1.474     albertel 3471:     $result.=&Apache::loncommon::end_data_table_row();
1.41      ng       3472:     return $result;
1.38      ng       3473: }
                   3474: 
1.44      ng       3475: #--- change scores for all the students in a section/class
                   3476: #    record does not get update if unchanged
1.38      ng       3477: sub editgrades {
1.608     www      3478:     my ($request,$symb) = @_;
1.41      ng       3479: 
1.433     banghart 3480:     my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
1.477     albertel 3481:     my $title='<h2>'.&mt('Current Grade Status').'</h2>';
1.433     banghart 3482:     $title.='<h4>'.&mt('<b>Section: </b>[_1]',$section_display).'</h4>'."\n";
1.126     ng       3483: 
1.477     albertel 3484:     my $result= &Apache::loncommon::start_data_table().
                   3485: 	&Apache::loncommon::start_data_table_header_row().
                   3486: 	'<th rowspan="2" valign="middle">'.&mt('No.').'</th>'.
                   3487: 	'<th rowspan="2" valign="middle">'.&nameUserString('header')."</th>\n";
1.43      ng       3488:     my %scoreptr = (
                   3489: 		    'correct'  =>'correct_by_override',
                   3490: 		    'incorrect'=>'incorrect_by_override',
                   3491: 		    'excused'  =>'excused',
                   3492: 		    'ungraded' =>'ungraded_attempted',
1.596     raeburn  3493:                     'credited' =>'credit_attempted',
1.43      ng       3494: 		    'nothing'  => '',
                   3495: 		    );
1.257     albertel 3496:     my ($classlist,undef,$fullname) = &getclasslist($env{'form.section'},'0');
1.34      ng       3497: 
1.44      ng       3498:     my (@partid);
                   3499:     my %weight = ();
1.54      albertel 3500:     my %columns = ();
1.44      ng       3501:     my ($i,$ctr,$count,$rec_update) = (0,0,0,0);
1.54      albertel 3502: 
1.582     raeburn  3503:     my $partserror;
                   3504:     my (@parts) = sort(&getpartlist($symb,\$partserror));
                   3505:     if ($partserror) {
                   3506:         return &navmap_errormsg();
                   3507:     }
1.54      albertel 3508:     my $header;
1.257     albertel 3509:     while ($ctr < $env{'form.totalparts'}) {
                   3510: 	my $partid = $env{'form.partid_'.$ctr};
1.524     raeburn  3511: 	push(@partid,$partid);
1.257     albertel 3512: 	$weight{$partid} = $env{'form.weight_'.$partid};
1.44      ng       3513: 	$ctr++;
1.54      albertel 3514:     }
1.324     albertel 3515:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
1.54      albertel 3516:     foreach my $partid (@partid) {
1.478     albertel 3517: 	$header .= '<th align="center">'.&mt('Old Score').'</th>'.
                   3518: 	    '<th align="center">'.&mt('New Score').'</th>';
1.54      albertel 3519: 	$columns{$partid}=2;
                   3520: 	foreach my $stores (@parts) {
                   3521: 	    my ($part,$type) = &split_part_type($stores);
                   3522: 	    if ($part !~ m/^\Q$partid\E/) { next;}
                   3523: 	    if ($type eq 'awarded' || $type eq 'solved') { next; }
                   3524: 	    my $display=&Apache::lonnet::metadata($url,$stores.'.display');
1.551     raeburn  3525: 	    $display =~ s/\[Part: \Q$part\E\]//;
1.539     riegler  3526:             my $narrowtext = &mt('Tries');
                   3527: 	    $display =~ s/Number of Attempts/$narrowtext/;
                   3528: 	    $header .= '<th align="center">'.&mt('Old').' '.$display.'</th>'.
                   3529: 		'<th align="center">'.&mt('New').' '.$display.'</th>';
1.54      albertel 3530: 	    $columns{$partid}+=2;
                   3531: 	}
                   3532:     }
                   3533:     foreach my $partid (@partid) {
1.324     albertel 3534: 	my $display_part=&get_display_part($partid,$symb);
1.478     albertel 3535: 	$result .= '<th colspan="'.$columns{$partid}.'" align="center">'.
                   3536: 	    &mt('Part: [_1] (Weight = [_2])',$display_part,$weight{$partid}).
                   3537: 	    '</th>';
1.54      albertel 3538: 
1.44      ng       3539:     }
1.477     albertel 3540:     $result .= &Apache::loncommon::end_data_table_header_row().
                   3541: 	&Apache::loncommon::start_data_table_header_row().
                   3542: 	$header.
                   3543: 	&Apache::loncommon::end_data_table_header_row();
                   3544:     my @noupdate;
1.126     ng       3545:     my ($updateCtr,$noupdateCtr) = (1,1);
1.257     albertel 3546:     for ($i=0; $i<$env{'form.total'}; $i++) {
1.93      albertel 3547: 	my $line;
1.257     albertel 3548: 	my $user = $env{'form.ctr'.$i};
1.281     albertel 3549: 	my ($uname,$udom)=split(/:/,$user);
1.44      ng       3550: 	my %newrecord;
                   3551: 	my $updateflag = 0;
1.281     albertel 3552: 	$line .= '<td>'.&nameUserString(undef,$$fullname{$user},$uname,$udom).'</td>';
1.108     albertel 3553: 	my $usec=$classlist->{"$uname:$udom"}[5];
1.105     albertel 3554: 	if (!&canmodify($usec)) {
1.126     ng       3555: 	    my $numcols=scalar(@partid)*4+2;
1.477     albertel 3556: 	    push(@noupdate,
1.478     albertel 3557: 		 $line."<td colspan=\"$numcols\"><span class=\"LC_warning\">".
                   3558: 		 &mt('Not allowed to modify student')."</span></td></tr>");
1.105     albertel 3559: 	    next;
                   3560: 	}
1.269     raeburn  3561:         my %aggregate = ();
                   3562:         my $aggregateflag = 0;
1.281     albertel 3563: 	$user=~s/:/_/; # colon doen't work in javascript for names
1.44      ng       3564: 	foreach (@partid) {
1.257     albertel 3565: 	    my $old_aw    = $env{'form.GD_'.$user.'_'.$_.'_awarded_s'};
1.54      albertel 3566: 	    my $old_part_pcr = $old_aw/($weight{$_} ne '0' ? $weight{$_}:1);
                   3567: 	    my $old_part  = $old_aw eq '' ? '' : $old_part_pcr;
1.257     albertel 3568: 	    my $old_score = $scoreptr{$env{'form.GD_'.$user.'_'.$_.'_solved_s'}};
                   3569: 	    my $awarded   = $env{'form.GD_'.$user.'_'.$_.'_awarded'};
1.54      albertel 3570: 	    my $pcr       = $awarded/($weight{$_} ne '0' ? $weight{$_} : 1);
                   3571: 	    my $partial   = $awarded eq '' ? '' : $pcr;
1.44      ng       3572: 	    my $score;
                   3573: 	    if ($partial eq '') {
1.257     albertel 3574: 		$score = $scoreptr{$env{'form.GD_'.$user.'_'.$_.'_solved_s'}};
1.44      ng       3575: 	    } elsif ($partial > 0) {
                   3576: 		$score = 'correct_by_override';
                   3577: 	    } elsif ($partial == 0) {
                   3578: 		$score = 'incorrect_by_override';
                   3579: 	    }
1.257     albertel 3580: 	    my $dropMenu = $env{'form.GD_'.$user.'_'.$_.'_solved'};
1.125     ng       3581: 	    $score = 'excused' if (($dropMenu eq 'excused') && ($score ne 'excused'));
                   3582: 
1.292     albertel 3583: 	    $newrecord{'resource.'.$_.'.regrader'}=
                   3584: 		"$env{'user.name'}:$env{'user.domain'}";
1.125     ng       3585: 	    if ($dropMenu eq 'reset status' &&
                   3586: 		$old_score ne '') { # ignore if no previous attempts => nothing to reset
1.299     albertel 3587: 		$newrecord{'resource.'.$_.'.tries'} = '';
1.125     ng       3588: 		$newrecord{'resource.'.$_.'.solved'} = '';
                   3589: 		$newrecord{'resource.'.$_.'.award'} = '';
1.299     albertel 3590: 		$newrecord{'resource.'.$_.'.awarded'} = '';
1.125     ng       3591: 		$updateflag = 1;
1.269     raeburn  3592:                 if ($env{'form.GD_'.$user.'_'.$_.'_aggtries'} > 0) {
                   3593:                     my $aggtries = $env{'form.GD_'.$user.'_'.$_.'_aggtries'};
                   3594:                     my $totaltries = $env{'form.GD_'.$user.'_'.$_.'_totaltries'};
                   3595:                     my $solvedstatus = $env{'form.GD_'.$user.'_'.$_.'_solved_s'};
                   3596:                     &decrement_aggs($symb,$_,\%aggregate,$aggtries,$totaltries,$solvedstatus);
                   3597:                     $aggregateflag = 1;
                   3598:                 }
1.139     albertel 3599: 	    } elsif (!($old_part eq $partial && $old_score eq $score)) {
                   3600: 		$updateflag = 1;
                   3601: 		$newrecord{'resource.'.$_.'.awarded'}  = $partial if $partial ne '';
                   3602: 		$newrecord{'resource.'.$_.'.solved'}   = $score;
                   3603: 		$rec_update++;
1.125     ng       3604: 	    }
                   3605: 
1.93      albertel 3606: 	    $line .= '<td align="center">'.$old_aw.'&nbsp;</td>'.
1.44      ng       3607: 		'<td align="center">'.$awarded.
                   3608: 		($score eq 'excused' ? $score : '').'&nbsp;</td>';
1.5       albertel 3609: 
1.54      albertel 3610: 
                   3611: 	    my $partid=$_;
                   3612: 	    foreach my $stores (@parts) {
                   3613: 		my ($part,$type) = &split_part_type($stores);
                   3614: 		if ($part !~ m/^\Q$partid\E/) { next;}
                   3615: 		if ($type eq 'awarded' || $type eq 'solved') { next; }
1.257     albertel 3616: 		my $old_aw    = $env{'form.GD_'.$user.'_'.$part.'_'.$type.'_s'};
                   3617: 		my $awarded   = $env{'form.GD_'.$user.'_'.$part.'_'.$type};
1.54      albertel 3618: 		if ($awarded ne '' && $awarded ne $old_aw) {
                   3619: 		    $newrecord{'resource.'.$part.'.'.$type}= $awarded;
1.257     albertel 3620: 		    $newrecord{'resource.'.$part.'.regrader'}="$env{'user.name'}:$env{'user.domain'}";
1.54      albertel 3621: 		    $updateflag=1;
                   3622: 		}
1.93      albertel 3623: 		$line .= '<td align="center">'.$old_aw.'&nbsp;</td>'.
1.54      albertel 3624: 		    '<td align="center">'.$awarded.'&nbsp;</td>';
                   3625: 	    }
1.44      ng       3626: 	}
1.477     albertel 3627: 	$line.="\n";
1.301     albertel 3628: 
                   3629: 	my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   3630: 	my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   3631: 
1.44      ng       3632: 	if ($updateflag) {
                   3633: 	    $count++;
1.257     albertel 3634: 	    &Apache::lonnet::cstore(\%newrecord,$symb,$env{'request.course.id'},
1.89      albertel 3635: 				    $udom,$uname);
1.301     albertel 3636: 
                   3637: 	    if (&Apache::bridgetask::in_queue('gradingqueue',$symb,$cdom,
                   3638: 					      $cnum,$udom,$uname)) {
                   3639: 		# need to figure out if should be in queue.
                   3640: 		my %record =  
                   3641: 		    &Apache::lonnet::restore($symb,$env{'request.course.id'},
                   3642: 					     $udom,$uname);
                   3643: 		my $all_graded = 1;
                   3644: 		my $none_graded = 1;
                   3645: 		foreach my $part (@parts) {
                   3646: 		    if ( $record{'resource.'.$part.'.awarded'} eq '' ) {
                   3647: 			$all_graded = 0;
                   3648: 		    } else {
                   3649: 			$none_graded = 0;
                   3650: 		    }
                   3651: 		}
                   3652: 
                   3653: 		if ($all_graded || $none_graded) {
                   3654: 		    &Apache::bridgetask::remove_from_queue('gradingqueue',
                   3655: 							   $symb,$cdom,$cnum,
                   3656: 							   $udom,$uname);
                   3657: 		}
                   3658: 	    }
                   3659: 
1.477     albertel 3660: 	    $result.=&Apache::loncommon::start_data_table_row().
                   3661: 		'<td align="right">&nbsp;'.$updateCtr.'&nbsp;</td>'.$line.
                   3662: 		&Apache::loncommon::end_data_table_row();
1.126     ng       3663: 	    $updateCtr++;
1.93      albertel 3664: 	} else {
1.477     albertel 3665: 	    push(@noupdate,
                   3666: 		 '<td align="right">&nbsp;'.$noupdateCtr.'&nbsp;</td>'.$line);
1.126     ng       3667: 	    $noupdateCtr++;
1.44      ng       3668: 	}
1.269     raeburn  3669:         if ($aggregateflag) {
                   3670:             &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
1.301     albertel 3671: 				  $cdom,$cnum);
1.269     raeburn  3672:         }
1.93      albertel 3673:     }
1.477     albertel 3674:     if (@noupdate) {
1.126     ng       3675: #	my $numcols=(scalar(@partid)*(scalar(@parts)-1)*2)+3;
                   3676: 	my $numcols=scalar(@partid)*4+2;
1.477     albertel 3677: 	$result .= &Apache::loncommon::start_data_table_row('LC_empty_row').
1.478     albertel 3678: 	    '<td align="center" colspan="'.$numcols.'">'.
                   3679: 	    &mt('No Changes Occurred For the Students Below').
                   3680: 	    '</td>'.
1.477     albertel 3681: 	    &Apache::loncommon::end_data_table_row();
                   3682: 	foreach my $line (@noupdate) {
                   3683: 	    $result.=
                   3684: 		&Apache::loncommon::start_data_table_row().
                   3685: 		$line.
                   3686: 		&Apache::loncommon::end_data_table_row();
                   3687: 	}
1.44      ng       3688:     }
1.614     www      3689:     $result .= &Apache::loncommon::end_data_table();
1.478     albertel 3690:     my $msg = '<p><b>'.
                   3691: 	&mt('Number of records updated = [_1] for [quant,_2,student].',
                   3692: 	    $rec_update,$count).'</b><br />'.
                   3693: 	'<b>'.&mt('Total number of students = [_1]',$env{'form.total'}).
                   3694: 	'</b></p>';
1.44      ng       3695:     return $title.$msg.$result;
1.5       albertel 3696: }
1.54      albertel 3697: 
                   3698: sub split_part_type {
                   3699:     my ($partstr) = @_;
                   3700:     my ($temp,@allparts)=split(/_/,$partstr);
                   3701:     my $type=pop(@allparts);
1.439     albertel 3702:     my $part=join('_',@allparts);
1.54      albertel 3703:     return ($part,$type);
                   3704: }
                   3705: 
1.44      ng       3706: #------------- end of section for handling grading by section/class ---------
                   3707: #
                   3708: #----------------------------------------------------------------------------
                   3709: 
1.5       albertel 3710: 
1.44      ng       3711: #----------------------------------------------------------------------------
                   3712: #
                   3713: #-------------------------- Next few routines handles grading by csv upload
                   3714: #
                   3715: #--- Javascript to handle csv upload
1.27      albertel 3716: sub csvupload_javascript_reverse_associate {
1.573     bisitz   3717:     my $error1=&mt('You need to specify the username or the student/employee ID');
1.246     albertel 3718:     my $error2=&mt('You need to specify at least one grading field');
1.27      albertel 3719:   return(<<ENDPICK);
                   3720:   function verify(vf) {
                   3721:     var foundsomething=0;
                   3722:     var founduname=0;
1.243     albertel 3723:     var foundID=0;
1.27      albertel 3724:     for (i=0;i<=vf.nfields.value;i++) {
                   3725:       tw=eval('vf.f'+i+'.selectedIndex');
1.243     albertel 3726:       if (i==0 && tw!=0) { foundID=1; }
                   3727:       if (i==1 && tw!=0) { founduname=1; }
                   3728:       if (i!=0 && i!=1 && i!=2 && tw!=0) { foundsomething=1; }
1.27      albertel 3729:     }
1.246     albertel 3730:     if (founduname==0 && foundID==0) {
                   3731: 	alert('$error1');
                   3732: 	return;
1.27      albertel 3733:     }
                   3734:     if (foundsomething==0) {
1.246     albertel 3735: 	alert('$error2');
                   3736: 	return;
1.27      albertel 3737:     }
                   3738:     vf.submit();
                   3739:   }
                   3740:   function flip(vf,tf) {
                   3741:     var nw=eval('vf.f'+tf+'.selectedIndex');
                   3742:     var i;
                   3743:     for (i=0;i<=vf.nfields.value;i++) {
                   3744:       //can not pick the same destination field for both name and domain
                   3745:       if (((i ==0)||(i ==1)) && 
                   3746:           ((tf==0)||(tf==1)) && 
                   3747:           (i!=tf) &&
                   3748:           (eval('vf.f'+i+'.selectedIndex')==nw)) {
                   3749:         eval('vf.f'+i+'.selectedIndex=0;')
                   3750:       }
                   3751:     }
                   3752:   }
                   3753: ENDPICK
                   3754: }
                   3755: 
                   3756: sub csvupload_javascript_forward_associate {
1.573     bisitz   3757:     my $error1=&mt('You need to specify the username or the student/employee ID');
1.246     albertel 3758:     my $error2=&mt('You need to specify at least one grading field');
1.27      albertel 3759:   return(<<ENDPICK);
                   3760:   function verify(vf) {
                   3761:     var foundsomething=0;
                   3762:     var founduname=0;
1.243     albertel 3763:     var foundID=0;
1.27      albertel 3764:     for (i=0;i<=vf.nfields.value;i++) {
                   3765:       tw=eval('vf.f'+i+'.selectedIndex');
1.243     albertel 3766:       if (tw==1) { foundID=1; }
                   3767:       if (tw==2) { founduname=1; }
                   3768:       if (tw>3) { foundsomething=1; }
1.27      albertel 3769:     }
1.246     albertel 3770:     if (founduname==0 && foundID==0) {
                   3771: 	alert('$error1');
                   3772: 	return;
1.27      albertel 3773:     }
                   3774:     if (foundsomething==0) {
1.246     albertel 3775: 	alert('$error2');
                   3776: 	return;
1.27      albertel 3777:     }
                   3778:     vf.submit();
                   3779:   }
                   3780:   function flip(vf,tf) {
                   3781:     var nw=eval('vf.f'+tf+'.selectedIndex');
                   3782:     var i;
                   3783:     //can not pick the same destination field twice
                   3784:     for (i=0;i<=vf.nfields.value;i++) {
                   3785:       if ((i!=tf) && (eval('vf.f'+i+'.selectedIndex')==nw)) {
                   3786:         eval('vf.f'+i+'.selectedIndex=0;')
                   3787:       }
                   3788:     }
                   3789:   }
                   3790: ENDPICK
                   3791: }
                   3792: 
1.26      albertel 3793: sub csvuploadmap_header {
1.324     albertel 3794:     my ($request,$symb,$datatoken,$distotal)= @_;
1.41      ng       3795:     my $javascript;
1.257     albertel 3796:     if ($env{'form.upfile_associate'} eq 'reverse') {
1.41      ng       3797: 	$javascript=&csvupload_javascript_reverse_associate();
                   3798:     } else {
                   3799: 	$javascript=&csvupload_javascript_forward_associate();
                   3800:     }
1.45      ng       3801: 
1.418     albertel 3802:     $symb = &Apache::lonenc::check_encrypt($symb);
1.632     www      3803:     $request->print('<form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">'.
                   3804:                     &mt('Total number of records found in file: [_1]',$distotal).'<hr />'.
                   3805:                     &mt('Associate entries from the uploaded file with as many fields as you can.'));
                   3806:     my $reverse=&mt("Reverse Association");
1.41      ng       3807:     $request->print(<<ENDPICK);
1.632     www      3808: <br />
                   3809: <input type="button" value="$reverse" onclick="javascript:this.form.associate.value='Reverse Association';submit(this.form);" />
1.26      albertel 3810: <input type="hidden" name="associate"  value="" />
                   3811: <input type="hidden" name="phase"      value="three" />
                   3812: <input type="hidden" name="datatoken"  value="$datatoken" />
1.257     albertel 3813: <input type="hidden" name="fileupload" value="$env{'form.fileupload'}" />
                   3814: <input type="hidden" name="upfiletype" value="$env{'form.upfiletype'}" />
1.26      albertel 3815: <input type="hidden" name="upfile_associate" 
1.257     albertel 3816:                                        value="$env{'form.upfile_associate'}" />
1.26      albertel 3817: <input type="hidden" name="symb"       value="$symb" />
1.246     albertel 3818: <input type="hidden" name="command"    value="csvuploadoptions" />
1.26      albertel 3819: <hr />
                   3820: ENDPICK
1.597     wenzelju 3821:     $request->print(&Apache::lonhtmlcommon::scripttag($javascript));
1.118     ng       3822:     return '';
1.26      albertel 3823: 
                   3824: }
                   3825: 
                   3826: sub csvupload_fields {
1.582     raeburn  3827:     my ($symb,$errorref) = @_;
                   3828:     my (@parts) = &getpartlist($symb,$errorref);
                   3829:     if (ref($errorref)) {
                   3830:         if ($$errorref) {
                   3831:             return;
                   3832:         }
                   3833:     }
                   3834: 
1.556     weissno  3835:     my @fields=(['ID','Student/Employee ID'],
1.243     albertel 3836: 		['username','Student Username'],
                   3837: 		['domain','Student Domain']);
1.324     albertel 3838:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
1.41      ng       3839:     foreach my $part (sort(@parts)) {
                   3840: 	my @datum;
                   3841: 	my $display=&Apache::lonnet::metadata($url,$part.'.display');
                   3842: 	my $name=$part;
                   3843: 	if  (!$display) { $display = $name; }
                   3844: 	@datum=($name,$display);
1.244     albertel 3845: 	if ($name=~/^stores_(.*)_awarded/) {
                   3846: 	    push(@fields,['stores_'.$1.'_points',"Points [Part: $1]"]);
                   3847: 	}
1.41      ng       3848: 	push(@fields,\@datum);
                   3849:     }
                   3850:     return (@fields);
1.26      albertel 3851: }
                   3852: 
                   3853: sub csvuploadmap_footer {
1.41      ng       3854:     my ($request,$i,$keyfields) =@_;
                   3855:     $request->print(<<ENDPICK);
1.26      albertel 3856: </table>
                   3857: <input type="hidden" name="nfields" value="$i" />
                   3858: <input type="hidden" name="keyfields" value="$keyfields" />
1.589     bisitz   3859: <input type="button" onclick="javascript:verify(this.form)" value="Assign Grades" /><br />
1.26      albertel 3860: </form>
                   3861: ENDPICK
                   3862: }
                   3863: 
1.283     albertel 3864: sub checkforfile_js {
1.638     www      3865:     my $alertmsg = &mt('Please use the browse button to select a file from your local directory.');
1.597     wenzelju 3866:     my $result = &Apache::lonhtmlcommon::scripttag(<<CSVFORMJS);
1.86      ng       3867:     function checkUpload(formname) {
                   3868: 	if (formname.upfile.value == "") {
1.539     riegler  3869: 	    alert("$alertmsg");
1.86      ng       3870: 	    return false;
                   3871: 	}
                   3872: 	formname.submit();
                   3873:     }
                   3874: CSVFORMJS
1.283     albertel 3875:     return $result;
                   3876: }
                   3877: 
                   3878: sub upcsvScores_form {
1.608     www      3879:     my ($request,$symb) = @_;
1.283     albertel 3880:     if (!$symb) {return '';}
                   3881:     my $result=&checkforfile_js();
1.632     www      3882:     $result.=&Apache::loncommon::start_data_table().
                   3883:              &Apache::loncommon::start_data_table_header_row().
                   3884:              '<th>'.&mt('Specify a file containing the class scores for current resource.').'</th>'.
                   3885:              &Apache::loncommon::end_data_table_header_row().
                   3886:              &Apache::loncommon::start_data_table_row().'<td>';
1.370     www      3887:     my $upload=&mt("Upload Scores");
1.86      ng       3888:     my $upfile_select=&Apache::loncommon::upfile_select_html();
1.245     albertel 3889:     my $ignore=&mt('Ignore First Line');
1.418     albertel 3890:     $symb = &Apache::lonenc::check_encrypt($symb);
1.86      ng       3891:     $result.=<<ENDUPFORM;
1.106     albertel 3892: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
1.86      ng       3893: <input type="hidden" name="symb" value="$symb" />
                   3894: <input type="hidden" name="command" value="csvuploadmap" />
                   3895: $upfile_select
1.589     bisitz   3896: <br /><input type="button" onclick="javascript:checkUpload(this.form);" value="$upload" />
1.86      ng       3897: </form>
                   3898: ENDUPFORM
1.370     www      3899:     $result.=&Apache::loncommon::help_open_topic("Course_Convert_To_CSV",
1.632     www      3900:                            &mt("How do I create a CSV file from a spreadsheet")).
                   3901:              '</td>'.
                   3902:             &Apache::loncommon::end_data_table_row().
                   3903:             &Apache::loncommon::end_data_table();
1.86      ng       3904:     return $result;
                   3905: }
                   3906: 
                   3907: 
1.26      albertel 3908: sub csvuploadmap {
1.608     www      3909:     my ($request,$symb)= @_;
1.41      ng       3910:     if (!$symb) {return '';}
1.72      ng       3911: 
1.41      ng       3912:     my $datatoken;
1.257     albertel 3913:     if (!$env{'form.datatoken'}) {
1.41      ng       3914: 	$datatoken=&Apache::loncommon::upfile_store($request);
1.26      albertel 3915:     } else {
1.257     albertel 3916: 	$datatoken=$env{'form.datatoken'};
1.41      ng       3917: 	&Apache::loncommon::load_tmp_file($request);
1.26      albertel 3918:     }
1.41      ng       3919:     my @records=&Apache::loncommon::upfile_record_sep();
1.324     albertel 3920:     &csvuploadmap_header($request,$symb,$datatoken,$#records+1);
1.41      ng       3921:     my ($i,$keyfields);
                   3922:     if (@records) {
1.582     raeburn  3923:         my $fieldserror;
                   3924: 	my @fields=&csvupload_fields($symb,\$fieldserror);
                   3925:         if ($fieldserror) {
                   3926:             $request->print(&navmap_errormsg());
                   3927:             return;
                   3928:         }
1.257     albertel 3929: 	if ($env{'form.upfile_associate'} eq 'reverse') {	
1.41      ng       3930: 	    &Apache::loncommon::csv_print_samples($request,\@records);
                   3931: 	    $i=&Apache::loncommon::csv_print_select_table($request,\@records,
                   3932: 							  \@fields);
                   3933: 	    foreach (@fields) { $keyfields.=$_->[0].','; }
                   3934: 	    chop($keyfields);
                   3935: 	} else {
                   3936: 	    unshift(@fields,['none','']);
                   3937: 	    $i=&Apache::loncommon::csv_samples_select_table($request,\@records,
                   3938: 							    \@fields);
1.311     banghart 3939:             foreach my $rec (@records) {
                   3940:                 my %temp = &Apache::loncommon::record_sep($rec);
                   3941:                 if (%temp) {
                   3942:                     $keyfields=join(',',sort(keys(%temp)));
                   3943:                     last;
                   3944:                 }
                   3945:             }
1.41      ng       3946: 	}
                   3947:     }
                   3948:     &csvuploadmap_footer($request,$i,$keyfields);
1.72      ng       3949: 
1.41      ng       3950:     return '';
1.27      albertel 3951: }
                   3952: 
1.246     albertel 3953: sub csvuploadoptions {
1.608     www      3954:     my ($request,$symb)= @_;
1.632     www      3955:     my $overwrite=&mt('Overwrite any existing score');
1.246     albertel 3956:     $request->print(<<ENDPICK);
                   3957: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
                   3958: <input type="hidden" name="command"    value="csvuploadassign" />
                   3959: <p>
                   3960: <label>
                   3961:    <input type="checkbox" name="overwite_scores" checked="checked" />
1.632     www      3962:    $overwrite
1.246     albertel 3963: </label>
                   3964: </p>
                   3965: ENDPICK
                   3966:     my %fields=&get_fields();
                   3967:     if (!defined($fields{'domain'})) {
1.257     albertel 3968: 	my $domform = &Apache::loncommon::select_dom_form($env{'request.role.domain'},'default_domain');
1.632     www      3969: 	$request->print("\n<p>".&mt('Users are in domain: [_1]',$domform)."</p>\n");
1.246     albertel 3970:     }
1.257     albertel 3971:     foreach my $key (sort(keys(%env))) {
1.246     albertel 3972: 	if ($key !~ /^form\.(.*)$/) { next; }
                   3973: 	my $cleankey=$1;
                   3974: 	if ($cleankey eq 'command') { next; }
                   3975: 	$request->print('<input type="hidden" name="'.$cleankey.
1.257     albertel 3976: 			'"  value="'.$env{$key}.'" />'."\n");
1.246     albertel 3977:     }
                   3978:     # FIXME do a check for any duplicated user ids...
                   3979:     # FIXME do a check for any invalid user ids?...
1.290     albertel 3980:     $request->print('<input type="submit" value="Assign Grades" /><br />
                   3981: <hr /></form>'."\n");
1.246     albertel 3982:     return '';
                   3983: }
                   3984: 
                   3985: sub get_fields {
                   3986:     my %fields;
1.257     albertel 3987:     my @keyfields = split(/\,/,$env{'form.keyfields'});
                   3988:     for (my $i=0; $i<=$env{'form.nfields'}; $i++) {
                   3989: 	if ($env{'form.upfile_associate'} eq 'reverse') {
                   3990: 	    if ($env{'form.f'.$i} ne 'none') {
                   3991: 		$fields{$keyfields[$i]}=$env{'form.f'.$i};
1.41      ng       3992: 	    }
                   3993: 	} else {
1.257     albertel 3994: 	    if ($env{'form.f'.$i} ne 'none') {
                   3995: 		$fields{$env{'form.f'.$i}}=$keyfields[$i];
1.41      ng       3996: 	    }
                   3997: 	}
1.27      albertel 3998:     }
1.246     albertel 3999:     return %fields;
                   4000: }
                   4001: 
                   4002: sub csvuploadassign {
1.608     www      4003:     my ($request,$symb)= @_;
1.246     albertel 4004:     if (!$symb) {return '';}
1.345     bowersj2 4005:     my $error_msg = '';
1.246     albertel 4006:     &Apache::loncommon::load_tmp_file($request);
                   4007:     my @gradedata = &Apache::loncommon::upfile_record_sep();
                   4008:     my %fields=&get_fields();
1.257     albertel 4009:     my $courseid=$env{'request.course.id'};
1.97      albertel 4010:     my ($classlist) = &getclasslist('all',0);
1.106     albertel 4011:     my @notallowed;
1.41      ng       4012:     my @skipped;
                   4013:     my $countdone=0;
                   4014:     foreach my $grade (@gradedata) {
                   4015: 	my %entries=&Apache::loncommon::record_sep($grade);
1.246     albertel 4016: 	my $domain;
                   4017: 	if ($entries{$fields{'domain'}}) {
                   4018: 	    $domain=$entries{$fields{'domain'}};
                   4019: 	} else {
1.257     albertel 4020: 	    $domain=$env{'form.default_domain'};
1.246     albertel 4021: 	}
1.243     albertel 4022: 	$domain=~s/\s//g;
1.41      ng       4023: 	my $username=$entries{$fields{'username'}};
1.160     albertel 4024: 	$username=~s/\s//g;
1.243     albertel 4025: 	if (!$username) {
                   4026: 	    my $id=$entries{$fields{'ID'}};
1.247     albertel 4027: 	    $id=~s/\s//g;
1.243     albertel 4028: 	    my %ids=&Apache::lonnet::idget($domain,$id);
                   4029: 	    $username=$ids{$id};
                   4030: 	}
1.41      ng       4031: 	if (!exists($$classlist{"$username:$domain"})) {
1.247     albertel 4032: 	    my $id=$entries{$fields{'ID'}};
                   4033: 	    $id=~s/\s//g;
                   4034: 	    if ($id) {
                   4035: 		push(@skipped,"$id:$domain");
                   4036: 	    } else {
                   4037: 		push(@skipped,"$username:$domain");
                   4038: 	    }
1.41      ng       4039: 	    next;
                   4040: 	}
1.108     albertel 4041: 	my $usec=$classlist->{"$username:$domain"}[5];
1.106     albertel 4042: 	if (!&canmodify($usec)) {
                   4043: 	    push(@notallowed,"$username:$domain");
                   4044: 	    next;
                   4045: 	}
1.244     albertel 4046: 	my %points;
1.41      ng       4047: 	my %grades;
                   4048: 	foreach my $dest (keys(%fields)) {
1.244     albertel 4049: 	    if ($dest eq 'ID' || $dest eq 'username' ||
                   4050: 		$dest eq 'domain') { next; }
                   4051: 	    if ($entries{$fields{$dest}} =~ /^\s*$/) { next; }
                   4052: 	    if ($dest=~/stores_(.*)_points/) {
                   4053: 		my $part=$1;
                   4054: 		my $wgt =&Apache::lonnet::EXT('resource.'.$part.'.weight',
                   4055: 					      $symb,$domain,$username);
1.345     bowersj2 4056:                 if ($wgt) {
                   4057:                     $entries{$fields{$dest}}=~s/\s//g;
                   4058:                     my $pcr=$entries{$fields{$dest}} / $wgt;
1.463     albertel 4059:                     my $award=($pcr == 0) ? 'incorrect_by_override'
                   4060:                                           : 'correct_by_override';
1.638     www      4061:                     if ($pcr>1) {
                   4062:                        push(@skipped,&mt("[_1]: point value larger than weight","$username:$domain"));
                   4063:                     }
1.345     bowersj2 4064:                     $grades{"resource.$part.awarded"}=$pcr;
                   4065:                     $grades{"resource.$part.solved"}=$award;
                   4066:                     $points{$part}=1;
                   4067:                 } else {
                   4068:                     $error_msg = "<br />" .
                   4069:                         &mt("Some point values were assigned"
                   4070:                             ." for problems with a weight "
                   4071:                             ."of zero. These values were "
                   4072:                             ."ignored.");
                   4073:                 }
1.244     albertel 4074: 	    } else {
                   4075: 		if ($dest=~/stores_(.*)_awarded/) { if ($points{$1}) {next;} }
                   4076: 		if ($dest=~/stores_(.*)_solved/)  { if ($points{$1}) {next;} }
                   4077: 		my $store_key=$dest;
                   4078: 		$store_key=~s/^stores/resource/;
                   4079: 		$store_key=~s/_/\./g;
                   4080: 		$grades{$store_key}=$entries{$fields{$dest}};
                   4081: 	    }
1.41      ng       4082: 	}
1.508     www      4083: 	if (! %grades) { 
                   4084:            push(@skipped,&mt("[_1]: no data to save","$username:$domain")); 
                   4085:         } else {
                   4086: 	   $grades{"resource.regrader"}="$env{'user.name'}:$env{'user.domain'}";
                   4087: 	   my $result=&Apache::lonnet::cstore(\%grades,$symb,
1.302     albertel 4088: 					   $env{'request.course.id'},
                   4089: 					   $domain,$username);
1.508     www      4090: 	   if ($result eq 'ok') {
1.627     www      4091: # Successfully stored
1.508     www      4092: 	      $request->print('.');
1.627     www      4093: # Remove from grading queue
                   4094:               &Apache::bridgetask::remove_from_queue('gradingqueue',$symb,
                   4095:                                              $env{'course.'.$env{'request.course.id'}.'.domain'},
                   4096:                                              $env{'course.'.$env{'request.course.id'}.'.num'},
                   4097:                                              $domain,$username);
                   4098:               $countdone++;
                   4099:            } else {
1.508     www      4100: 	      $request->print("<p><span class=\"LC_error\">".
                   4101:                               &mt("Failed to save data for student [_1]. Message when trying to save was: [_2]",
                   4102:                                   "$username:$domain",$result)."</span></p>");
                   4103: 	   }
                   4104: 	   $request->rflush();
                   4105:         }
1.41      ng       4106:     }
1.570     www      4107:     $request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt("Saved scores for [quant,_1,student]",$countdone),$countdone==0));
1.41      ng       4108:     if (@skipped) {
1.571     www      4109: 	$request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt('No scores stored for the following username(s):'),1).'<br />');
                   4110:         $request->print(join(', ',@skipped));
1.106     albertel 4111:     }
                   4112:     if (@notallowed) {
1.571     www      4113: 	$request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt('Modification of scores not allowed for the following username(s):'),1).'<br />');
                   4114: 	$request->print(join(', ',@notallowed));
1.41      ng       4115:     }
1.106     albertel 4116:     $request->print("<br />\n");
1.345     bowersj2 4117:     return $error_msg;
1.26      albertel 4118: }
1.44      ng       4119: #------------- end of section for handling csv file upload ---------
                   4120: #
                   4121: #-------------------------------------------------------------------
                   4122: #
1.122     ng       4123: #-------------- Next few routines handle grading by page/sequence
1.72      ng       4124: #
                   4125: #--- Select a page/sequence and a student to grade
1.68      ng       4126: sub pickStudentPage {
1.608     www      4127:     my ($request,$symb) = @_;
1.68      ng       4128: 
1.539     riegler  4129:     my $alertmsg = &mt('Please select the student you wish to grade.');
1.597     wenzelju 4130:     $request->print(&Apache::lonhtmlcommon::scripttag(<<LISTJAVASCRIPT));
1.68      ng       4131: 
                   4132: function checkPickOne(formname) {
1.76      ng       4133:     if (radioSelection(formname.student) == null) {
1.539     riegler  4134: 	alert("$alertmsg");
1.68      ng       4135: 	return;
                   4136:     }
1.125     ng       4137:     ptr = pullDownSelection(formname.selectpage);
                   4138:     formname.page.value = formname["page"+ptr].value;
                   4139:     formname.title.value = formname["title"+ptr].value;
1.68      ng       4140:     formname.submit();
                   4141: }
                   4142: 
                   4143: LISTJAVASCRIPT
1.118     ng       4144:     &commonJSfunctions($request);
1.608     www      4145: 
1.257     albertel 4146:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
                   4147:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
                   4148:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
1.68      ng       4149: 
1.398     albertel 4150:     my $result='<h3><span class="LC_info">&nbsp;'.
1.485     albertel 4151: 	&mt('Manual Grading by Page or Sequence').'</span></h3>';
1.68      ng       4152: 
1.80      ng       4153:     $result.='<form action="/adm/grades" method="post" name="displayPage">'."\n";
1.582     raeburn  4154:     my $map_error;
                   4155:     my ($titles,$symbx) = &getSymbMap($map_error);
                   4156:     if ($map_error) {
                   4157:         $request->print(&navmap_errormsg());
                   4158:         return; 
                   4159:     }
1.137     albertel 4160:     my ($curpage) =&Apache::lonnet::decode_symb($symb); 
                   4161: #    my ($curpage,$mapId) =&Apache::lonnet::decode_symb($symb); 
                   4162: #    my $type=($curpage =~ /\.(page|sequence)/);
1.485     albertel 4163:     my $select = '<select name="selectpage">'."\n";
1.70      ng       4164:     my $ctr=0;
1.68      ng       4165:     foreach (@$titles) {
                   4166: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
1.485     albertel 4167: 	$select.='<option value="'.$ctr.'" '.
1.401     albertel 4168: 	    ($$symbx{$_} =~ /$curpage$/ ? 'selected="selected"' : '').
1.71      ng       4169: 	    '>'.$showtitle.'</option>'."\n";
1.70      ng       4170: 	$ctr++;
1.68      ng       4171:     }
1.485     albertel 4172:     $select.= '</select>';
1.539     riegler  4173:     $result.='&nbsp;<b>'.&mt('Problems from').':</b> '.$select."<br />\n";
1.485     albertel 4174: 
1.70      ng       4175:     $ctr=0;
                   4176:     foreach (@$titles) {
                   4177: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
                   4178: 	$result.='<input type="hidden" name="page'.$ctr.'" value="'.$$symbx{$_}.'" />'."\n";
                   4179: 	$result.='<input type="hidden" name="title'.$ctr.'" value="'.$showtitle.'" />'."\n";
                   4180: 	$ctr++;
                   4181:     }
1.72      ng       4182:     $result.='<input type="hidden" name="page" />'."\n".
                   4183: 	'<input type="hidden" name="title" />'."\n";
1.68      ng       4184: 
1.485     albertel 4185:     my $options =
                   4186: 	'<label><input type="radio" name="vProb" value="no" checked="checked" /> '.&mt('no').' </label>'."\n".
                   4187: 	'<label><input type="radio" name="vProb" value="yes" /> '.&mt('yes').' </label>'."<br />\n";
1.539     riegler  4188:     $result.='&nbsp;<b>'.&mt('View Problem Text').': </b>'.$options;
1.485     albertel 4189: 
                   4190:     $options =
                   4191: 	'<label><input type="radio" name="lastSub" value="none" /> '.&mt('none').' </label>'."\n".
                   4192: 	'<label><input type="radio" name="lastSub" value="datesub" checked="checked" /> '.&mt('by dates and submissions').'</label>'."\n".
                   4193: 	'<label><input type="radio" name="lastSub" value="all" /> '.&mt('all details').' </label>'."\n";
1.539     riegler  4194:     $result.='&nbsp;<b>'.&mt('Submissions').': </b>'.$options;
1.432     banghart 4195:     
                   4196:     $result.=&build_section_inputs();
1.442     banghart 4197:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
                   4198:     $result.='<input type="hidden" name="Status"  value="'.$stu_status.'" />'."\n".
1.72      ng       4199: 	'<input type="hidden" name="command" value="displayPage" />'."\n".
1.613     www      4200: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."<br />\n";
1.72      ng       4201: 
1.539     riegler  4202:     $result.='&nbsp;<b>'.&mt('Use CODE').': </b> <input type="text" name="CODE" value="" /> <br />'."\n";
1.382     albertel 4203: 
1.80      ng       4204:     $result.='&nbsp;<input type="button" '.
1.589     bisitz   4205:              'onclick="javascript:checkPickOne(this.form);" value="'.&mt('Next').' &rarr;" /><br />'."\n";
1.72      ng       4206: 
1.68      ng       4207:     $request->print($result);
                   4208: 
1.485     albertel 4209:     my $studentTable.='&nbsp;<b>'.&mt('Select a student you wish to grade and then click on the Next button.').'</b><br />'.
1.484     albertel 4210: 	&Apache::loncommon::start_data_table().
                   4211: 	&Apache::loncommon::start_data_table_header_row().
1.485     albertel 4212: 	'<th align="right">&nbsp;'.&mt('No.').'</th>'.
1.484     albertel 4213: 	'<th>'.&nameUserString('header').'</th>'.
1.485     albertel 4214: 	'<th align="right">&nbsp;'.&mt('No.').'</th>'.
1.484     albertel 4215: 	'<th>'.&nameUserString('header').'</th>'.
                   4216: 	&Apache::loncommon::end_data_table_header_row();
1.68      ng       4217:  
1.76      ng       4218:     my (undef,undef,$fullname) = &getclasslist($getsec,'1');
1.68      ng       4219:     my $ptr = 1;
1.294     albertel 4220:     foreach my $student (sort 
                   4221: 			 {
                   4222: 			     if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                   4223: 				 return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                   4224: 			     }
                   4225: 			     return $a cmp $b;
                   4226: 			 } (keys(%$fullname))) {
1.68      ng       4227: 	my ($uname,$udom) = split(/:/,$student);
1.484     albertel 4228: 	$studentTable.=($ptr%2==1 ? &Apache::loncommon::start_data_table_row()
                   4229:                                   : '</td>');
1.126     ng       4230: 	$studentTable.='<td align="right">'.$ptr.'&nbsp;</td>';
1.288     albertel 4231: 	$studentTable.='<td>&nbsp;<label><input type="radio" name="student" value="'.$student.'" /> '
                   4232: 	    .&nameUserString(undef,$$fullname{$student},$uname,$udom)."</label>\n";
1.484     albertel 4233: 	$studentTable.=
                   4234: 	    ($ptr%2 == 0 ? '</td>'.&Apache::loncommon::end_data_table_row() 
                   4235:                          : '');
1.68      ng       4236: 	$ptr++;
                   4237:     }
1.484     albertel 4238:     if ($ptr%2 == 0) {
                   4239: 	$studentTable.='</td><td>&nbsp;</td><td>&nbsp;</td>'.
                   4240: 	    &Apache::loncommon::end_data_table_row();
                   4241:     }
                   4242:     $studentTable.=&Apache::loncommon::end_data_table()."\n";
1.126     ng       4243:     $studentTable.='<input type="button" '.
1.589     bisitz   4244:                    'onclick="javascript:checkPickOne(this.form);" value="'.&mt('Next').' &rarr;" /></form>'."\n";
1.68      ng       4245: 
                   4246:     $request->print($studentTable);
                   4247: 
                   4248:     return '';
                   4249: }
                   4250: 
                   4251: sub getSymbMap {
1.582     raeburn  4252:     my ($map_error) = @_;
1.132     bowersj2 4253:     my $navmap = Apache::lonnavmaps::navmap->new();
1.582     raeburn  4254:     unless (ref($navmap)) {
                   4255:         if (ref($map_error)) {
                   4256:             $$map_error = 'navmap';
                   4257:         }
                   4258:         return;
                   4259:     }
1.68      ng       4260:     my %symbx = ();
                   4261:     my @titles = ();
1.117     bowersj2 4262:     my $minder = 0;
                   4263: 
                   4264:     # Gather every sequence that has problems.
1.240     albertel 4265:     my @sequences = $navmap->retrieveResources(undef, sub { shift->is_map(); },
                   4266: 					       1,0,1);
1.117     bowersj2 4267:     for my $sequence ($navmap->getById('0.0'), @sequences) {
1.241     albertel 4268: 	if ($navmap->hasResource($sequence, sub { shift->is_problem(); }, 0) ) {
1.381     albertel 4269: 	    my $title = $minder.'.'.
                   4270: 		&HTML::Entities::encode($sequence->compTitle(),'"\'&');
                   4271: 	    push(@titles, $title); # minder in case two titles are identical
                   4272: 	    $symbx{$title} = &HTML::Entities::encode($sequence->symb(),'"\'&');
1.117     bowersj2 4273: 	    $minder++;
1.241     albertel 4274: 	}
1.68      ng       4275:     }
                   4276:     return \@titles,\%symbx;
                   4277: }
                   4278: 
1.72      ng       4279: #
                   4280: #--- Displays a page/sequence w/wo problems, w/wo submissions
1.68      ng       4281: sub displayPage {
1.608     www      4282:     my ($request,$symb) = @_;
1.257     albertel 4283:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
                   4284:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
                   4285:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
                   4286:     my $pageTitle = $env{'form.page'};
1.103     albertel 4287:     my ($classlist,undef,$fullname) = &getclasslist($getsec,'1');
1.257     albertel 4288:     my ($uname,$udom) = split(/:/,$env{'form.student'});
                   4289:     my $usec=$classlist->{$env{'form.student'}}[5];
1.168     albertel 4290: 
                   4291:     #need to make sure we have the correct data for later EXT calls, 
                   4292:     #thus invalidate the cache
                   4293:     &Apache::lonnet::devalidatecourseresdata(
1.257     albertel 4294:                  $env{'course.'.$env{'request.course.id'}.'.num'},
                   4295:                  $env{'course.'.$env{'request.course.id'}.'.domain'});
1.168     albertel 4296:     &Apache::lonnet::clear_EXT_cache_status();
                   4297: 
1.103     albertel 4298:     if (!&canview($usec)) {
1.485     albertel 4299: 	$request->print('<span class="LC_warning">'.&mt('Unable to view requested student. ([_1])',$env{'form.student'}).'</span>');
1.103     albertel 4300: 	return;
                   4301:     }
1.398     albertel 4302:     my $result='<h3><span class="LC_info">&nbsp;'.$env{'form.title'}.'</span></h3>';
1.485     albertel 4303:     $result.='<h3>&nbsp;'.&mt('Student: [_1]',&nameUserString(undef,$$fullname{$env{'form.student'}},$uname,$udom)).
1.129     ng       4304: 	'</h3>'."\n";
1.500     albertel 4305:     $env{'form.CODE'} = uc($env{'form.CODE'});
1.501     foxr     4306:     if (&Apache::lonnet::validCODE(uc($env{'form.CODE'}))) {
1.485     albertel 4307: 	$result.='<h3>&nbsp;'.&mt('CODE: [_1]',$env{'form.CODE'}).'</h3>'."\n";
1.382     albertel 4308:     } else {
                   4309: 	delete($env{'form.CODE'});
                   4310:     }
1.71      ng       4311:     &sub_page_js($request);
                   4312:     $request->print($result);
                   4313: 
1.132     bowersj2 4314:     my $navmap = Apache::lonnavmaps::navmap->new();
1.582     raeburn  4315:     unless (ref($navmap)) {
                   4316:         $request->print(&navmap_errormsg());
                   4317:         return;
                   4318:     }
1.257     albertel 4319:     my ($mapUrl, $id, $resUrl)=&Apache::lonnet::decode_symb($env{'form.page'});
1.68      ng       4320:     my $map = $navmap->getResourceByUrl($resUrl); # add to navmaps
1.288     albertel 4321:     if (!$map) {
1.485     albertel 4322: 	$request->print('<span class="LC_warning">'.&mt('Unable to view requested sequence. ([_1])',$resUrl).'</span>');
1.288     albertel 4323: 	return; 
                   4324:     }
1.68      ng       4325:     my $iterator = $navmap->getIterator($map->map_start(),
                   4326: 					$map->map_finish());
                   4327: 
1.71      ng       4328:     my $studentTable='<form action="/adm/grades" method="post" name="gradePage">'."\n".
1.72      ng       4329: 	'<input type="hidden" name="command" value="gradeByPage" />'."\n".
1.257     albertel 4330: 	'<input type="hidden" name="fullname" value="'.$$fullname{$env{'form.student'}}.'" />'."\n".
                   4331: 	'<input type="hidden" name="student" value="'.$env{'form.student'}.'" />'."\n".
1.72      ng       4332: 	'<input type="hidden" name="page"    value="'.$pageTitle.'" />'."\n".
1.257     albertel 4333: 	'<input type="hidden" name="title"   value="'.$env{'form.title'}.'" />'."\n".
1.418     albertel 4334: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.613     www      4335: 	'<input type="hidden" name="overRideScore" value="no" />'."\n";
1.71      ng       4336: 
1.382     albertel 4337:     if (defined($env{'form.CODE'})) {
                   4338: 	$studentTable.=
                   4339: 	    '<input type="hidden" name="CODE" value="'.$env{'form.CODE'}.'" />'."\n";
                   4340:     }
1.381     albertel 4341:     my $checkIcon = '<img alt="'.&mt('Check Mark').
1.485     albertel 4342: 	'" src="'.&Apache::loncommon::lonhttpdurl($request->dir_config('lonIconsURL').'/check.gif').'" height="16" border="0" />';
1.71      ng       4343: 
1.594     bisitz   4344:     $studentTable.='&nbsp;<span class="LC_info">'.
                   4345:         &mt('Problems graded correct by the computer are marked with a [_1] symbol.',$checkIcon).
                   4346:         '</span>'."\n".
1.484     albertel 4347: 	&Apache::loncommon::start_data_table().
                   4348: 	&Apache::loncommon::start_data_table_header_row().
                   4349: 	'<th align="center">&nbsp;Prob.&nbsp;</th>'.
1.485     albertel 4350: 	'<th>&nbsp;'.($env{'form.vProb'} eq 'no' ? &mt('Title') : &mt('Problem Text')).'/'.&mt('Grade').'</th>'.
1.484     albertel 4351: 	&Apache::loncommon::end_data_table_header_row();
1.71      ng       4352: 
1.329     albertel 4353:     &Apache::lonxml::clear_problem_counter();
1.196     albertel 4354:     my ($depth,$question,$prob) = (1,1,1);
1.68      ng       4355:     $iterator->next(); # skip the first BEGIN_MAP
                   4356:     my $curRes = $iterator->next(); # for "current resource"
1.101     albertel 4357:     while ($depth > 0) {
1.68      ng       4358:         if($curRes == $iterator->BEGIN_MAP) { $depth++; }
1.100     bowersj2 4359:         if($curRes == $iterator->END_MAP) { $depth--; }
1.68      ng       4360: 
1.385     albertel 4361:         if (ref($curRes) && $curRes->is_problem()) {
1.91      albertel 4362: 	    my $parts = $curRes->parts();
1.68      ng       4363:             my $title = $curRes->compTitle();
1.71      ng       4364: 	    my $symbx = $curRes->symb();
1.484     albertel 4365: 	    $studentTable.=
                   4366: 		&Apache::loncommon::start_data_table_row().
                   4367: 		'<td align="center" valign="top" >'.$prob.
1.485     albertel 4368: 		(scalar(@{$parts}) == 1 ? '' 
                   4369: 		                        : '<br />('.&mt('[_1]&nbsp;parts)',
                   4370: 							scalar(@{$parts}))
                   4371: 		 ).
                   4372: 		 '</td>';
1.71      ng       4373: 	    $studentTable.='<td valign="top">';
1.382     albertel 4374: 	    my %form = ('CODE' => $env{'form.CODE'},);
1.257     albertel 4375: 	    if ($env{'form.vProb'} eq 'yes' ) {
1.144     albertel 4376: 		$studentTable.=&show_problem($request,$symbx,$uname,$udom,1,
1.383     albertel 4377: 					     undef,'both',\%form);
1.71      ng       4378: 	    } else {
1.382     albertel 4379: 		my $companswer = &Apache::loncommon::get_student_answers($symbx,$uname,$udom,$env{'request.course.id'},%form);
1.80      ng       4380: 		$companswer =~ s|<form(.*?)>||g;
                   4381: 		$companswer =~ s|</form>||g;
1.71      ng       4382: #		while ($companswer =~ /(<a href\=\"javascript:newWindow.*?Script Vars<\/a>)/s) { #<a href="javascript:newWindow</a>
1.116     ng       4383: #		    $companswer =~ s/$1/ /ms;
1.326     albertel 4384: #		    $request->print('match='.$1."<br />\n");
1.71      ng       4385: #		}
1.116     ng       4386: #		$companswer =~ s|<table border=\"1\">|<table border=\"0\">|g;
1.539     riegler  4387: 		$studentTable.='&nbsp;<b>'.$title.'</b>&nbsp;<br />&nbsp;<b>'.&mt('Correct answer').':</b><br />'.$companswer;
1.71      ng       4388: 	    }
                   4389: 
1.257     albertel 4390: 	    my %record = &Apache::lonnet::restore($symbx,$env{'request.course.id'},$udom,$uname);
1.125     ng       4391: 
1.257     albertel 4392: 	    if ($env{'form.lastSub'} eq 'datesub') {
1.71      ng       4393: 		if ($record{'version'} eq '') {
1.485     albertel 4394: 		    $studentTable.='<br />&nbsp;<span class="LC_warning">'.&mt('No recorded submission for this problem.').'</span><br />';
1.71      ng       4395: 		} else {
1.116     ng       4396: 		    my %responseType = ();
                   4397: 		    foreach my $partid (@{$parts}) {
1.147     albertel 4398: 			my @responseIds =$curRes->responseIds($partid);
                   4399: 			my @responseType =$curRes->responseType($partid);
                   4400: 			my %responseIds;
                   4401: 			for (my $i=0;$i<=$#responseIds;$i++) {
                   4402: 			    $responseIds{$responseIds[$i]}=$responseType[$i];
                   4403: 			}
                   4404: 			$responseType{$partid} = \%responseIds;
1.116     ng       4405: 		    }
1.148     albertel 4406: 		    $studentTable.= &displaySubByDates($symbx,\%record,$parts,\%responseType,$checkIcon,$uname,$udom);
1.147     albertel 4407: 
1.71      ng       4408: 		}
1.257     albertel 4409: 	    } elsif ($env{'form.lastSub'} eq 'all') {
                   4410: 		my $last = ($env{'form.lastSub'} eq 'last' ? 'last' : '');
1.71      ng       4411: 		$studentTable.=&Apache::loncommon::get_previous_attempt($symbx,$uname,$udom,
1.257     albertel 4412: 									$env{'request.course.id'},
1.71      ng       4413: 									'','.submission');
                   4414:  
                   4415: 	    }
1.103     albertel 4416: 	    if (&canmodify($usec)) {
1.585     bisitz   4417:             $studentTable.=&gradeBox_start();
1.103     albertel 4418: 		foreach my $partid (@{$parts}) {
                   4419: 		    $studentTable.=&gradeBox($request,$symbx,$uname,$udom,$question,$partid,\%record);
                   4420: 		    $studentTable.='<input type="hidden" name="q_'.$question.'" value="'.$partid.'" />'."\n";
                   4421: 		    $question++;
                   4422: 		}
1.585     bisitz   4423:             $studentTable.=&gradeBox_end();
1.196     albertel 4424: 		$prob++;
1.71      ng       4425: 	    }
                   4426: 	    $studentTable.='</td></tr>';
1.68      ng       4427: 
1.103     albertel 4428: 	}
1.68      ng       4429:         $curRes = $iterator->next();
                   4430:     }
                   4431: 
1.589     bisitz   4432:     $studentTable.=
                   4433:         '</table>'."\n".
                   4434:         '<input type="button" value="'.&mt('Save').'" '.
                   4435:         'onclick="javascript:checkSubmitPage(this.form,'.$question.');" />'.
                   4436:         '</form>'."\n";
1.71      ng       4437:     $request->print($studentTable);
                   4438: 
                   4439:     return '';
1.119     ng       4440: }
                   4441: 
                   4442: sub displaySubByDates {
1.148     albertel 4443:     my ($symb,$record,$parts,$responseType,$checkIcon,$uname,$udom) = @_;
1.224     albertel 4444:     my $isCODE=0;
1.335     albertel 4445:     my $isTask = ($symb =~/\.task$/);
1.224     albertel 4446:     if (exists($record->{'resource.CODE'})) { $isCODE=1; }
1.467     albertel 4447:     my $studentTable=&Apache::loncommon::start_data_table().
                   4448: 	&Apache::loncommon::start_data_table_header_row().
                   4449: 	'<th>'.&mt('Date/Time').'</th>'.
                   4450: 	($isCODE?'<th>'.&mt('CODE').'</th>':'').
                   4451: 	'<th>'.&mt('Submission').'</th>'.
                   4452: 	'<th>'.&mt('Status').'</th>'.
                   4453: 	&Apache::loncommon::end_data_table_header_row();
1.119     ng       4454:     my ($version);
                   4455:     my %mark;
1.148     albertel 4456:     my %orders;
1.119     ng       4457:     $mark{'correct_by_student'} = $checkIcon;
1.147     albertel 4458:     if (!exists($$record{'1:timestamp'})) {
1.539     riegler  4459: 	return '<br />&nbsp;<span class="LC_warning">'.&mt('Nothing submitted - no attempts.').'</span><br />';
1.147     albertel 4460:     }
1.335     albertel 4461: 
                   4462:     my $interaction;
1.525     raeburn  4463:     my $no_increment = 1;
1.119     ng       4464:     for ($version=1;$version<=$$record{'version'};$version++) {
1.467     albertel 4465: 	my $timestamp = 
                   4466: 	    &Apache::lonlocal::locallocaltime($$record{$version.':timestamp'});
1.335     albertel 4467: 	if (exists($$record{$version.':resource.0.version'})) {
                   4468: 	    $interaction = $$record{$version.':resource.0.version'};
                   4469: 	}
                   4470: 
                   4471: 	my $where = ($isTask ? "$version:resource.$interaction"
                   4472: 		             : "$version:resource");
1.467     albertel 4473: 	$studentTable.=&Apache::loncommon::start_data_table_row().
                   4474: 	    '<td>'.$timestamp.'</td>';
1.224     albertel 4475: 	if ($isCODE) {
                   4476: 	    $studentTable.='<td>'.$record->{$version.':resource.CODE'}.'</td>';
                   4477: 	}
1.119     ng       4478: 	my @versionKeys = split(/\:/,$$record{$version.':keys'});
                   4479: 	my @displaySub = ();
                   4480: 	foreach my $partid (@{$parts}) {
1.596     raeburn  4481:             my $hidden;
                   4482:             if (($$record{$version.':resource.'.$partid.'.type'} eq 'anonsurvey') ||
                   4483:                 ($$record{$version.':resource.'.$partid.'.type'} eq 'anonsurveycred')) {
                   4484:                 $hidden = 1;
                   4485:             }
1.335     albertel 4486: 	    my @matchKey = ($isTask ? sort(grep /^resource\.\d+\.\Q$partid\E\.award$/,@versionKeys)
                   4487: 			            : sort(grep /^resource\.\Q$partid\E\..*?\.submission$/,@versionKeys));
                   4488: 	    
1.122     ng       4489: #	    next if ($$record{"$version:resource.$partid.solved"} eq '');
1.324     albertel 4490: 	    my $display_part=&get_display_part($partid,$symb);
1.147     albertel 4491: 	    foreach my $matchKey (@matchKey) {
1.198     albertel 4492: 		if (exists($$record{$version.':'.$matchKey}) &&
                   4493: 		    $$record{$version.':'.$matchKey} ne '') {
1.596     raeburn  4494:                     
1.335     albertel 4495: 		    my ($responseId)= ($isTask ? ($matchKey=~ /^resource\.(.*?)\.\Q$partid\E\.award$/)
                   4496: 				               : ($matchKey=~ /^resource\.\Q$partid\E\.(.*?)\.submission$/));
1.577     bisitz   4497:                     $displaySub[0].='<span class="LC_nobreak"';
                   4498:                     $displaySub[0].='<b>'.&mt('Part: [_1]',$display_part).'</b>'
                   4499:                                    .' <span class="LC_internal_info">'
1.625     www      4500:                                    .'('.&mt('Response ID: [_1]',$responseId).')'
1.577     bisitz   4501:                                    .'</span>'
                   4502:                                    .' <b>';
1.596     raeburn  4503:                     if ($hidden) {
                   4504:                         $displaySub[0].= &mt('Anonymous Survey').'</b>';
                   4505:                     } else {
                   4506: 		        if ($$record{"$where.$partid.tries"} eq '') {
                   4507: 			    $displaySub[0].=&mt('Trial not counted');
                   4508: 		        } else {
                   4509: 			    $displaySub[0].=&mt('Trial: [_1]',
1.467     albertel 4510: 					    $$record{"$where.$partid.tries"});
1.596     raeburn  4511: 		        }
                   4512: 		        my $responseType=($isTask ? 'Task'
1.335     albertel 4513:                                               : $responseType->{$partid}->{$responseId});
1.596     raeburn  4514: 		        if (!exists($orders{$partid})) { $orders{$partid}={}; }
                   4515: 		        if (!exists($orders{$partid}->{$responseId})) {
                   4516: 			    $orders{$partid}->{$responseId}=
                   4517: 			        &get_order($partid,$responseId,$symb,$uname,$udom,
                   4518:                                            $no_increment);
                   4519: 		        }
                   4520: 		        $displaySub[0].='</b></span>'; # /nobreak
                   4521: 		        $displaySub[0].='&nbsp; '.
                   4522: 			    &cleanRecord($$record{$version.':'.$matchKey},$responseType,$symb,$partid,$responseId,$record,$orders{$partid}->{$responseId},"$version:",$uname,$udom).'<br />';
                   4523:                     }
1.147     albertel 4524: 		}
                   4525: 	    }
1.335     albertel 4526: 	    if (exists($$record{"$where.$partid.checkedin"})) {
1.485     albertel 4527: 		$displaySub[1].=&mt('Checked in by [_1] into slot [_2]',
                   4528: 				    $$record{"$where.$partid.checkedin"},
                   4529: 				    $$record{"$where.$partid.checkedin.slot"}).
                   4530: 					'<br />';
1.335     albertel 4531: 	    }
                   4532: 	    if (exists $$record{"$where.$partid.award"}) {
1.485     albertel 4533: 		$displaySub[1].='<b>'.&mt('Part:').'</b>&nbsp;'.$display_part.' &nbsp;'.
1.335     albertel 4534: 		    lc($$record{"$where.$partid.award"}).' '.
                   4535: 		    $mark{$$record{"$where.$partid.solved"}}.
1.147     albertel 4536: 		    '<br />';
                   4537: 	    }
1.335     albertel 4538: 	    if (exists $$record{"$where.$partid.regrader"}) {
                   4539: 		$displaySub[2].=$$record{"$where.$partid.regrader"}.
                   4540: 		    ' (<b>'.&mt('Part').':</b> '.$display_part.')';
                   4541: 	    } elsif ($$record{"$version:resource.$partid.regrader"} =~ /\S/) {
                   4542: 		$displaySub[2].=
                   4543: 		    $$record{"$version:resource.$partid.regrader"}.
1.207     albertel 4544: 		    ' (<b>'.&mt('Part').':</b> '.$display_part.')';
1.147     albertel 4545: 	    }
                   4546: 	}
                   4547: 	# needed because old essay regrader has not parts info
                   4548: 	if (exists $$record{"$version:resource.regrader"}) {
                   4549: 	    $displaySub[2].=$$record{"$version:resource.regrader"};
                   4550: 	}
                   4551: 	$studentTable.='<td>'.$displaySub[0].'&nbsp;</td><td>'.$displaySub[1];
                   4552: 	if ($displaySub[2]) {
1.467     albertel 4553: 	    $studentTable.=&mt('Manually graded by [_1]',$displaySub[2]);
1.147     albertel 4554: 	}
1.467     albertel 4555: 	$studentTable.='&nbsp;</td>'.
                   4556: 	    &Apache::loncommon::end_data_table_row();
1.119     ng       4557:     }
1.467     albertel 4558:     $studentTable.=&Apache::loncommon::end_data_table();
1.119     ng       4559:     return $studentTable;
1.71      ng       4560: }
                   4561: 
                   4562: sub updateGradeByPage {
1.608     www      4563:     my ($request,$symb) = @_;
1.71      ng       4564: 
1.257     albertel 4565:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
                   4566:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
                   4567:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
                   4568:     my $pageTitle = $env{'form.page'};
1.103     albertel 4569:     my ($classlist,undef,$fullname) = &getclasslist($getsec,'1');
1.257     albertel 4570:     my ($uname,$udom) = split(/:/,$env{'form.student'});
                   4571:     my $usec=$classlist->{$env{'form.student'}}[5];
1.103     albertel 4572:     if (!&canmodify($usec)) {
1.526     raeburn  4573: 	$request->print('<span class="LC_warning">'.&mt('Unable to modify requested student ([_1])',$env{'form.student'}).'</span>');
1.103     albertel 4574: 	return;
                   4575:     }
1.398     albertel 4576:     my $result='<h3><span class="LC_info">&nbsp;'.$env{'form.title'}.'</span></h3>';
1.526     raeburn  4577:     $result.='<h3>&nbsp;'.&mt('Student: ').&nameUserString(undef,$env{'form.fullname'},$uname,$udom).
1.129     ng       4578: 	'</h3>'."\n";
1.70      ng       4579: 
1.68      ng       4580:     $request->print($result);
                   4581: 
1.582     raeburn  4582: 
1.132     bowersj2 4583:     my $navmap = Apache::lonnavmaps::navmap->new();
1.582     raeburn  4584:     unless (ref($navmap)) {
                   4585:         $request->print(&navmap_errormsg());
                   4586:         return;
                   4587:     }
1.257     albertel 4588:     my ($mapUrl, $id, $resUrl) = &Apache::lonnet::decode_symb( $env{'form.page'});
1.71      ng       4589:     my $map = $navmap->getResourceByUrl($resUrl); # add to navmaps
1.288     albertel 4590:     if (!$map) {
1.527     raeburn  4591: 	$request->print('<span class="LC_warning">'.&mt('Unable to grade requested sequence ([_1]).',$resUrl).'</span>');
1.288     albertel 4592: 	return; 
                   4593:     }
1.71      ng       4594:     my $iterator = $navmap->getIterator($map->map_start(),
                   4595: 					$map->map_finish());
1.70      ng       4596: 
1.484     albertel 4597:     my $studentTable=
                   4598: 	&Apache::loncommon::start_data_table().
                   4599: 	&Apache::loncommon::start_data_table_header_row().
1.485     albertel 4600: 	'<th align="center">&nbsp;'.&mt('Prob.').'&nbsp;</th>'.
                   4601: 	'<th>&nbsp;'.&mt('Title').'&nbsp;</th>'.
                   4602: 	'<th>&nbsp;'.&mt('Previous Score').'&nbsp;</th>'.
                   4603: 	'<th>&nbsp;'.&mt('New Score').'&nbsp;</th>'.
1.484     albertel 4604: 	&Apache::loncommon::end_data_table_header_row();
1.71      ng       4605: 
                   4606:     $iterator->next(); # skip the first BEGIN_MAP
                   4607:     my $curRes = $iterator->next(); # for "current resource"
1.196     albertel 4608:     my ($depth,$question,$prob,$changeflag)= (1,1,1,0);
1.101     albertel 4609:     while ($depth > 0) {
1.71      ng       4610:         if($curRes == $iterator->BEGIN_MAP) { $depth++; }
1.100     bowersj2 4611:         if($curRes == $iterator->END_MAP) { $depth--; }
1.71      ng       4612: 
1.385     albertel 4613:         if (ref($curRes) && $curRes->is_problem()) {
1.91      albertel 4614: 	    my $parts = $curRes->parts();
1.71      ng       4615:             my $title = $curRes->compTitle();
                   4616: 	    my $symbx = $curRes->symb();
1.484     albertel 4617: 	    $studentTable.=
                   4618: 		&Apache::loncommon::start_data_table_row().
                   4619: 		'<td align="center" valign="top" >'.$prob.
1.485     albertel 4620: 		(scalar(@{$parts}) == 1 ? '' 
1.526     raeburn  4621:                                         : '<br />('.&mt('[quant,_1,&nbsp;part]',scalar(@{$parts}))
                   4622: 		.')').'</td>';
1.71      ng       4623: 	    $studentTable.='<td valign="top">&nbsp;<b>'.$title.'</b>&nbsp;</td>';
                   4624: 
                   4625: 	    my %newrecord=();
                   4626: 	    my @displayPts=();
1.269     raeburn  4627:             my %aggregate = ();
                   4628:             my $aggregateflag = 0;
1.71      ng       4629: 	    foreach my $partid (@{$parts}) {
1.257     albertel 4630: 		my $newpts = $env{'form.GD_BOX'.$question.'_'.$partid};
                   4631: 		my $oldpts = $env{'form.oldpts'.$question.'_'.$partid};
1.71      ng       4632: 
1.257     albertel 4633: 		my $wgt = $env{'form.WGT'.$question.'_'.$partid} != 0 ? 
                   4634: 		    $env{'form.WGT'.$question.'_'.$partid} : 1;
1.71      ng       4635: 		my $partial = $newpts/$wgt;
                   4636: 		my $score;
                   4637: 		if ($partial > 0) {
                   4638: 		    $score = 'correct_by_override';
1.125     ng       4639: 		} elsif ($newpts ne '') { #empty is taken as 0
1.71      ng       4640: 		    $score = 'incorrect_by_override';
                   4641: 		}
1.257     albertel 4642: 		my $dropMenu = $env{'form.GD_SEL'.$question.'_'.$partid};
1.125     ng       4643: 		if ($dropMenu eq 'excused') {
1.71      ng       4644: 		    $partial = '';
                   4645: 		    $score = 'excused';
1.125     ng       4646: 		} elsif ($dropMenu eq 'reset status'
1.257     albertel 4647: 			 && $env{'form.solved'.$question.'_'.$partid} ne '') { #update only if previous record exists
1.125     ng       4648: 		    $newrecord{'resource.'.$partid.'.tries'} = 0;
                   4649: 		    $newrecord{'resource.'.$partid.'.solved'} = '';
                   4650: 		    $newrecord{'resource.'.$partid.'.award'} = '';
                   4651: 		    $newrecord{'resource.'.$partid.'.awarded'} = 0;
1.257     albertel 4652: 		    $newrecord{'resource.'.$partid.'.regrader'} = "$env{'user.name'}:$env{'user.domain'}";
1.125     ng       4653: 		    $changeflag++;
                   4654: 		    $newpts = '';
1.269     raeburn  4655:                     
                   4656:                     my $aggtries =  $env{'form.aggtries'.$question.'_'.$partid};
                   4657:                     my $totaltries = $env{'form.totaltries'.$question.'_'.$partid};
                   4658:                     my $solvedstatus = $env{'form.solved'.$question.'_'.$partid};
                   4659:                     if ($aggtries > 0) {
                   4660:                         &decrement_aggs($symbx,$partid,\%aggregate,$aggtries,$totaltries,$solvedstatus);
                   4661:                         $aggregateflag = 1;
                   4662:                     }
1.71      ng       4663: 		}
1.324     albertel 4664: 		my $display_part=&get_display_part($partid,$curRes->symb());
1.257     albertel 4665: 		my $oldstatus = $env{'form.solved'.$question.'_'.$partid};
1.526     raeburn  4666: 		$displayPts[0].='&nbsp;<b>'.&mt('Part').':</b> '.$display_part.' = '.
1.71      ng       4667: 		    (($oldstatus eq 'excused') ? 'excused' : $oldpts).
1.326     albertel 4668: 		    '&nbsp;<br />';
1.526     raeburn  4669: 		$displayPts[1].='&nbsp;<b>'.&mt('Part').':</b> '.$display_part.' = '.
1.125     ng       4670: 		     (($score eq 'excused') ? 'excused' : $newpts).
1.326     albertel 4671: 		    '&nbsp;<br />';
1.71      ng       4672: 		$question++;
1.380     albertel 4673: 		next if ($dropMenu eq 'reset status' || ($newpts eq $oldpts && $score ne 'excused'));
1.125     ng       4674: 
1.71      ng       4675: 		$newrecord{'resource.'.$partid.'.awarded'}  = $partial if $partial ne '';
1.125     ng       4676: 		$newrecord{'resource.'.$partid.'.solved'}   = $score if $score ne '';
1.257     albertel 4677: 		$newrecord{'resource.'.$partid.'.regrader'} = "$env{'user.name'}:$env{'user.domain'}"
1.125     ng       4678: 		    if (scalar(keys(%newrecord)) > 0);
1.71      ng       4679: 
                   4680: 		$changeflag++;
                   4681: 	    }
                   4682: 	    if (scalar(keys(%newrecord)) > 0) {
1.382     albertel 4683: 		my %record = 
                   4684: 		    &Apache::lonnet::restore($symbx,$env{'request.course.id'},
                   4685: 					     $udom,$uname);
                   4686: 
                   4687: 		if (&Apache::lonnet::validCODE($env{'form.CODE'})) {
                   4688: 		    $newrecord{'resource.CODE'} = $env{'form.CODE'};
                   4689: 		} elsif (&Apache::lonnet::validCODE($record{'resource.CODE'})) {
                   4690: 		    $newrecord{'resource.CODE'} = '';
                   4691: 		}
1.257     albertel 4692: 		&Apache::lonnet::cstore(\%newrecord,$symbx,$env{'request.course.id'},
1.71      ng       4693: 					$udom,$uname);
1.382     albertel 4694: 		%record = &Apache::lonnet::restore($symbx,
                   4695: 						   $env{'request.course.id'},
                   4696: 						   $udom,$uname);
1.380     albertel 4697: 		&check_and_remove_from_queue($parts,\%record,undef,$symbx,
                   4698: 					     $cdom,$cnum,$udom,$uname);
1.71      ng       4699: 	    }
1.380     albertel 4700: 	    
1.269     raeburn  4701:             if ($aggregateflag) {
                   4702:                 &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
                   4703:                       $env{'course.'.$env{'request.course.id'}.'.domain'},
                   4704:                       $env{'course.'.$env{'request.course.id'}.'.num'});
                   4705:             }
1.125     ng       4706: 
1.71      ng       4707: 	    $studentTable.='<td valign="top">'.$displayPts[0].'</td>'.
                   4708: 		'<td valign="top">'.$displayPts[1].'</td>'.
1.484     albertel 4709: 		&Apache::loncommon::end_data_table_row();
1.68      ng       4710: 
1.196     albertel 4711: 	    $prob++;
1.68      ng       4712: 	}
1.71      ng       4713:         $curRes = $iterator->next();
1.68      ng       4714:     }
1.98      albertel 4715: 
1.484     albertel 4716:     $studentTable.=&Apache::loncommon::end_data_table();
1.526     raeburn  4717:     my $grademsg=($changeflag == 0 ? &mt('No score was changed or updated.') :
                   4718: 		  &mt('The scores were changed for [quant,_1,problem].',
                   4719: 		  $changeflag));
1.76      ng       4720:     $request->print($grademsg.$studentTable);
1.68      ng       4721: 
1.70      ng       4722:     return '';
                   4723: }
                   4724: 
1.72      ng       4725: #-------- end of section for handling grading by page/sequence ---------
                   4726: #
                   4727: #-------------------------------------------------------------------
                   4728: 
1.581     www      4729: #-------------------- Bubblesheet (Scantron) Grading -------------------
1.75      albertel 4730: #
                   4731: #------ start of section for handling grading by page/sequence ---------
                   4732: 
1.423     albertel 4733: =pod
                   4734: 
                   4735: =head1 Bubble sheet grading routines
                   4736: 
1.424     albertel 4737:   For this documentation:
                   4738: 
                   4739:    'scanline' refers to the full line of characters
                   4740:    from the file that we are parsing that represents one entire sheet
                   4741: 
                   4742:    'bubble line' refers to the data
                   4743:    representing the line of bubbles that are on the physical bubble sheet
                   4744: 
                   4745: 
                   4746: The overall process is that a scanned in bubble sheet data is uploaded
                   4747: into a course. When a user wants to grade, they select a
                   4748: sequence/folder of resources, a file of bubble sheet info, and pick
                   4749: one of the predefined configurations for what each scanline looks
                   4750: like.
                   4751: 
                   4752: Next each scanline is checked for any errors of either 'missing
1.435     foxr     4753: bubbles' (it's an error because it may have been mis-scanned
1.424     albertel 4754: because too light bubbling), 'double bubble' (each bubble line should
                   4755: have no more that one letter picked), invalid or duplicated CODE,
1.556     weissno  4756: invalid student/employee ID
1.424     albertel 4757: 
                   4758: If the CODE option is used that determines the randomization of the
1.556     weissno  4759: homework problems, either way the student/employee ID is looked up into a
1.424     albertel 4760: username:domain.
                   4761: 
                   4762: During the validation phase the instructor can choose to skip scanlines. 
                   4763: 
1.435     foxr     4764: After the validation phase, there are now 3 bubble sheet files
1.424     albertel 4765: 
                   4766:   scantron_original_filename (unmodified original file)
                   4767:   scantron_corrected_filename (file where the corrected information has replaced the original information)
                   4768:   scantron_skipped_filename (contains the exact text of scanlines that where skipped)
                   4769: 
                   4770: Also there is a separate hash nohist_scantrondata that contains extra
                   4771: correction information that isn't representable in the bubble sheet
                   4772: file (see &scantron_getfile() for more information)
                   4773: 
                   4774: After all scanlines are either valid, marked as valid or skipped, then
                   4775: foreach line foreach problem in the picked sequence, an ssi request is
                   4776: made that simulates a user submitting their selected letter(s) against
                   4777: the homework problem.
1.423     albertel 4778: 
                   4779: =over 4
                   4780: 
                   4781: 
                   4782: 
                   4783: =item defaultFormData
                   4784: 
                   4785:   Returns html hidden inputs used to hold context/default values.
                   4786: 
                   4787:  Arguments:
                   4788:   $symb - $symb of the current resource 
                   4789: 
                   4790: =cut
1.422     foxr     4791: 
1.81      albertel 4792: sub defaultFormData {
1.324     albertel 4793:     my ($symb)=@_;
1.613     www      4794:     return '<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />';
1.81      albertel 4795: }
                   4796: 
1.447     foxr     4797: 
1.423     albertel 4798: =pod 
                   4799: 
                   4800: =item getSequenceDropDown
                   4801: 
                   4802:    Return html dropdown of possible sequences to grade
                   4803:  
                   4804:  Arguments:
1.582     raeburn  4805:    $symb - $symb of the current resource
                   4806:    $map_error - ref to scalar which will container error if
                   4807:                 $navmap object is unavailable in &getSymbMap().
1.423     albertel 4808: 
                   4809: =cut
1.422     foxr     4810: 
1.75      albertel 4811: sub getSequenceDropDown {
1.582     raeburn  4812:     my ($symb,$map_error)=@_;
1.75      albertel 4813:     my $result='<select name="selectpage">'."\n";
1.582     raeburn  4814:     my ($titles,$symbx) = &getSymbMap($map_error);
                   4815:     if (ref($map_error)) {
                   4816:         return if ($$map_error);
                   4817:     }
1.137     albertel 4818:     my ($curpage)=&Apache::lonnet::decode_symb($symb); 
1.75      albertel 4819:     my $ctr=0;
                   4820:     foreach (@$titles) {
                   4821: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
                   4822: 	$result.='<option value="'.$$symbx{$_}.'" '.
1.401     albertel 4823: 	    ($$symbx{$_} =~ /$curpage$/ ? 'selected="selected"' : '').
1.75      albertel 4824: 	    '>'.$showtitle.'</option>'."\n";
                   4825: 	$ctr++;
                   4826:     }
                   4827:     $result.= '</select>';
                   4828:     return $result;
                   4829: }
                   4830: 
1.495     albertel 4831: my %bubble_lines_per_response;     # no. bubble lines for each response.
1.554     raeburn  4832:                                    # key is zero-based index - 0, 1, 2 ...
1.495     albertel 4833: 
                   4834: my %first_bubble_line;             # First bubble line no. for each bubble.
                   4835: 
1.509     raeburn  4836: my %subdivided_bubble_lines;       # no. bubble lines for optionresponse, 
                   4837:                                    # matchresponse or rankresponse, where 
                   4838:                                    # an individual response can have multiple 
                   4839:                                    # lines
1.503     raeburn  4840: 
                   4841: my %responsetype_per_response;     # responsetype for each response
                   4842: 
1.495     albertel 4843: # Save and restore the bubble lines array to the form env.
                   4844: 
                   4845: 
                   4846: sub save_bubble_lines {
                   4847:     foreach my $line (keys(%bubble_lines_per_response)) {
                   4848: 	$env{"form.scantron.bubblelines.$line"}  = $bubble_lines_per_response{$line};
                   4849: 	$env{"form.scantron.first_bubble_line.$line"} =
                   4850: 	    $first_bubble_line{$line};
1.503     raeburn  4851:         $env{"form.scantron.sub_bubblelines.$line"} = 
                   4852:             $subdivided_bubble_lines{$line};
                   4853:         $env{"form.scantron.responsetype.$line"} =
                   4854:             $responsetype_per_response{$line};
1.495     albertel 4855:     }
                   4856: }
                   4857: 
                   4858: 
                   4859: sub restore_bubble_lines {
                   4860:     my $line = 0;
                   4861:     %bubble_lines_per_response = ();
                   4862:     while ($env{"form.scantron.bubblelines.$line"}) {
                   4863: 	my $value = $env{"form.scantron.bubblelines.$line"};
                   4864: 	$bubble_lines_per_response{$line} = $value;
                   4865: 	$first_bubble_line{$line}  =
                   4866: 	    $env{"form.scantron.first_bubble_line.$line"};
1.503     raeburn  4867:         $subdivided_bubble_lines{$line} =
                   4868:             $env{"form.scantron.sub_bubblelines.$line"};
                   4869:         $responsetype_per_response{$line} =
                   4870:             $env{"form.scantron.responsetype.$line"};
1.495     albertel 4871: 	$line++;
                   4872:     }
                   4873: }
                   4874: 
                   4875: #  Given the parsed scanline, get the response for 
                   4876: #  'answer' number n:
                   4877: 
                   4878: sub get_response_bubbles {
                   4879:     my ($parsed_line, $response)  = @_;
                   4880: 
                   4881:     my $bubble_line = $first_bubble_line{$response-1} +1;
                   4882:     my $bubble_lines= $bubble_lines_per_response{$response-1};
                   4883:     
                   4884:     my $selected = "";
                   4885: 
                   4886:     for (my $bline = 0; $bline < $bubble_lines; $bline++) {
                   4887: 	$selected .= $$parsed_line{"scantron.$bubble_line.answer"}.":";
                   4888: 	$bubble_line++;
                   4889:     }
                   4890:     return $selected;
                   4891: }
1.423     albertel 4892: 
                   4893: =pod 
                   4894: 
                   4895: =item scantron_filenames
                   4896: 
                   4897:    Returns a list of the scantron files in the current course 
                   4898: 
                   4899: =cut
1.422     foxr     4900: 
1.202     albertel 4901: sub scantron_filenames {
1.257     albertel 4902:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   4903:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
1.517     raeburn  4904:     my $getpropath = 1;
1.157     albertel 4905:     my @files=&Apache::lonnet::dirlist('userfiles',$cdom,$cname,
1.517     raeburn  4906:                                        $getpropath);
1.202     albertel 4907:     my @possiblenames;
1.201     albertel 4908:     foreach my $filename (sort(@files)) {
1.157     albertel 4909: 	($filename)=split(/&/,$filename);
                   4910: 	if ($filename!~/^scantron_orig_/) { next ; }
                   4911: 	$filename=~s/^scantron_orig_//;
1.202     albertel 4912: 	push(@possiblenames,$filename);
                   4913:     }
                   4914:     return @possiblenames;
                   4915: }
                   4916: 
1.423     albertel 4917: =pod 
                   4918: 
                   4919: =item scantron_uploads
                   4920: 
                   4921:    Returns  html drop-down list of scantron files in current course.
                   4922: 
                   4923:  Arguments:
                   4924:    $file2grade - filename to set as selected in the dropdown
                   4925: 
                   4926: =cut
1.422     foxr     4927: 
1.202     albertel 4928: sub scantron_uploads {
1.209     ng       4929:     my ($file2grade) = @_;
1.202     albertel 4930:     my $result=	'<select name="scantron_selectfile">';
                   4931:     $result.="<option></option>";
                   4932:     foreach my $filename (sort(&scantron_filenames())) {
1.401     albertel 4933: 	$result.="<option".($filename eq $file2grade ? ' selected="selected"':'').">$filename</option>\n";
1.81      albertel 4934:     }
                   4935:     $result.="</select>";
                   4936:     return $result;
                   4937: }
                   4938: 
1.423     albertel 4939: =pod 
                   4940: 
                   4941: =item scantron_scantab
                   4942: 
                   4943:   Returns html drop down of the scantron formats in the scantronformat.tab
                   4944:   file.
                   4945: 
                   4946: =cut
1.422     foxr     4947: 
1.82      albertel 4948: sub scantron_scantab {
                   4949:     my $result='<select name="scantron_format">'."\n";
1.191     albertel 4950:     $result.='<option></option>'."\n";
1.518     raeburn  4951:     my @lines = &get_scantronformat_file();
                   4952:     if (@lines > 0) {
                   4953:         foreach my $line (@lines) {
                   4954:             next if (($line =~ /^\#/) || ($line eq ''));
                   4955: 	    my ($name,$descrip)=split(/:/,$line);
                   4956: 	    $result.='<option value="'.$name.'">'.$descrip.'</option>'."\n";
                   4957:         }
1.82      albertel 4958:     }
                   4959:     $result.='</select>'."\n";
1.518     raeburn  4960:     return $result;
                   4961: }
                   4962: 
                   4963: =pod
                   4964: 
                   4965: =item get_scantronformat_file
                   4966: 
                   4967:   Returns an array containing lines from the scantron format file for
                   4968:   the domain of the course.
                   4969: 
                   4970:   If a url for a custom.tab file is listed in domain's configuration.db, 
                   4971:   lines are from this file.
                   4972: 
                   4973:   Otherwise, if a default.tab has been published in RES space by the 
                   4974:   domainconfig user, lines are from this file.
                   4975: 
                   4976:   Otherwise, fall back to getting lines from the legacy file on the
1.519     raeburn  4977:   local server:  /home/httpd/lonTabs/default_scantronformat.tab    
1.82      albertel 4978: 
1.518     raeburn  4979: =cut
                   4980: 
                   4981: sub get_scantronformat_file {
                   4982:     my $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
                   4983:     my %domconfig = &Apache::lonnet::get_dom('configuration',['scantron'],$cdom);
                   4984:     my $gottab = 0;
                   4985:     my @lines;
                   4986:     if (ref($domconfig{'scantron'}) eq 'HASH') {
                   4987:         if ($domconfig{'scantron'}{'scantronformat'} ne '') {
                   4988:             my $formatfile = &Apache::lonnet::getfile($Apache::lonnet::perlvar{'lonDocRoot'}.$domconfig{'scantron'}{'scantronformat'});
                   4989:             if ($formatfile ne '-1') {
                   4990:                 @lines = split("\n",$formatfile,-1);
                   4991:                 $gottab = 1;
                   4992:             }
                   4993:         }
                   4994:     }
                   4995:     if (!$gottab) {
                   4996:         my $confname = $cdom.'-domainconfig';
                   4997:         my $default = $Apache::lonnet::perlvar{'lonDocRoot'}.'/res/'.$cdom.'/'.$confname.'/default.tab';
                   4998:         my $formatfile =  &Apache::lonnet::getfile($default);
                   4999:         if ($formatfile ne '-1') {
                   5000:             @lines = split("\n",$formatfile,-1);
                   5001:             $gottab = 1;
                   5002:         }
                   5003:     }
                   5004:     if (!$gottab) {
1.519     raeburn  5005:         my @domains = &Apache::lonnet::current_machine_domains();
                   5006:         if (grep(/^\Q$cdom\E$/,@domains)) {
                   5007:             my $fh=Apache::File->new($Apache::lonnet::perlvar{'lonTabDir'}.'/scantronformat.tab');
                   5008:             @lines = <$fh>;
                   5009:             close($fh);
                   5010:         } else {
                   5011:             my $fh=Apache::File->new($Apache::lonnet::perlvar{'lonTabDir'}.'/default_scantronformat.tab');
                   5012:             @lines = <$fh>;
                   5013:             close($fh);
                   5014:         }
1.518     raeburn  5015:     }
                   5016:     return @lines;
1.82      albertel 5017: }
                   5018: 
1.423     albertel 5019: =pod 
                   5020: 
                   5021: =item scantron_CODElist
                   5022: 
                   5023:   Returns html drop down of the saved CODE lists from current course,
                   5024:   generated from earlier printings.
                   5025: 
                   5026: =cut
1.422     foxr     5027: 
1.186     albertel 5028: sub scantron_CODElist {
1.257     albertel 5029:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   5030:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
1.186     albertel 5031:     my @names=&Apache::lonnet::getkeys('CODEs',$cdom,$cnum);
                   5032:     my $namechoice='<option></option>';
1.225     albertel 5033:     foreach my $name (sort {uc($a) cmp uc($b)} @names) {
1.191     albertel 5034: 	if ($name =~ /^error: 2 /) { next; }
1.278     albertel 5035: 	if ($name =~ /^type\0/) { next; }
1.186     albertel 5036: 	$namechoice.='<option value="'.$name.'">'.$name.'</option>';
                   5037:     }
                   5038:     $namechoice='<select name="scantron_CODElist">'.$namechoice.'</select>';
                   5039:     return $namechoice;
                   5040: }
                   5041: 
1.423     albertel 5042: =pod 
                   5043: 
                   5044: =item scantron_CODEunique
                   5045: 
                   5046:   Returns the html for "Each CODE to be used once" radio.
                   5047: 
                   5048: =cut
1.422     foxr     5049: 
1.186     albertel 5050: sub scantron_CODEunique {
1.532     bisitz   5051:     my $result='<span class="LC_nobreak">
1.272     albertel 5052:                  <label><input type="radio" name="scantron_CODEunique"
1.423     albertel 5053:                         value="yes" checked="checked" />'.&mt('Yes').' </label>
1.381     albertel 5054:                 </span>
1.532     bisitz   5055:                 <span class="LC_nobreak">
1.272     albertel 5056:                  <label><input type="radio" name="scantron_CODEunique"
1.423     albertel 5057:                         value="no" />'.&mt('No').' </label>
1.381     albertel 5058:                 </span>';
1.186     albertel 5059:     return $result;
                   5060: }
1.423     albertel 5061: 
                   5062: =pod 
                   5063: 
                   5064: =item scantron_selectphase
                   5065: 
                   5066:   Generates the initial screen to start the bubble sheet process.
                   5067:   Allows for - starting a grading run.
1.424     albertel 5068:              - downloading existing scan data (original, corrected
1.423     albertel 5069:                                                 or skipped info)
                   5070: 
                   5071:              - uploading new scan data
                   5072: 
                   5073:  Arguments:
                   5074:   $r          - The Apache request object
                   5075:   $file2grade - name of the file that contain the scanned data to score
                   5076: 
                   5077: =cut
1.186     albertel 5078: 
1.75      albertel 5079: sub scantron_selectphase {
1.608     www      5080:     my ($r,$file2grade,$symb) = @_;
1.75      albertel 5081:     if (!$symb) {return '';}
1.582     raeburn  5082:     my $map_error;
                   5083:     my $sequence_selector=&getSequenceDropDown($symb,\$map_error);
                   5084:     if ($map_error) {
                   5085:         $r->print('<br />'.&navmap_errormsg().'<br />');
                   5086:         return;
                   5087:     }
1.324     albertel 5088:     my $default_form_data=&defaultFormData($symb);
1.209     ng       5089:     my $file_selector=&scantron_uploads($file2grade);
1.82      albertel 5090:     my $format_selector=&scantron_scantab();
1.186     albertel 5091:     my $CODE_selector=&scantron_CODElist();
                   5092:     my $CODE_unique=&scantron_CODEunique();
1.75      albertel 5093:     my $result;
1.422     foxr     5094: 
1.513     foxr     5095:     $ssi_error = 0;
                   5096: 
1.606     wenzelju 5097:     if (&Apache::lonnet::allowed('usc',$env{'request.role.domain'}) ||
                   5098:         &Apache::lonnet::allowed('usc',$env{'request.course.id'})) {
                   5099: 
                   5100: 	# Chunk of form to prompt for a scantron file upload.
                   5101: 
                   5102:         $r->print('
                   5103:     <br />
                   5104:     '.&Apache::loncommon::start_data_table('LC_scantron_action').'
                   5105:        '.&Apache::loncommon::start_data_table_header_row().'
                   5106:             <th>
                   5107:               &nbsp;'.&mt('Specify a bubblesheet data file to upload.').'
                   5108:             </th>
                   5109:        '.&Apache::loncommon::end_data_table_header_row().'
                   5110:        '.&Apache::loncommon::start_data_table_row().'
                   5111:             <td>
                   5112: ');
1.608     www      5113:     my $default_form_data=&defaultFormData($symb);
1.606     wenzelju 5114:     my $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
                   5115:     my $cnum= $env{'course.'.$env{'request.course.id'}.'.num'};
                   5116:     $r->print(&Apache::lonhtmlcommon::scripttag('
                   5117:     function checkUpload(formname) {
                   5118: 	if (formname.upfile.value == "") {
                   5119: 	    alert("'.&mt('Please use the browse button to select a file from your local directory.').'");
                   5120: 	    return false;
                   5121: 	}
                   5122: 	formname.submit();
                   5123:     }'));
                   5124:     $r->print('
                   5125:               <form enctype="multipart/form-data" action="/adm/grades" name="rules" method="post">
                   5126:                 '.$default_form_data.'
                   5127:                 <input name="courseid" type="hidden" value="'.$cnum.'" />
                   5128:                 <input name="domainid" type="hidden" value="'.$cdom.'" />
                   5129:                 <input name="command" value="scantronupload_save" type="hidden" />
                   5130:                 '.&mt('File to upload: [_1]','<input type="file" name="upfile" size="50" />').'
                   5131:                 <br />
                   5132:                 <input type="button" onclick="javascript:checkUpload(this.form);" value="'.&mt('Upload Bubblesheet Data').'" />
                   5133:               </form>
                   5134: ');
                   5135: 
                   5136:         $r->print('
                   5137:             </td>
                   5138:        '.&Apache::loncommon::end_data_table_row().'
                   5139:        '.&Apache::loncommon::end_data_table().'
                   5140: ');
                   5141:     }
                   5142: 
1.422     foxr     5143:     # Chunk of form to prompt for a file to grade and how:
                   5144: 
1.489     albertel 5145:     $result.= '
                   5146:     <br />
                   5147:     <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantron_process">
                   5148:     <input type="hidden" name="command" value="scantron_warning" />
                   5149:     '.$default_form_data.'
                   5150:     '.&Apache::loncommon::start_data_table('LC_scantron_action').'
                   5151:        '.&Apache::loncommon::start_data_table_header_row().'
                   5152:             <th colspan="2">
1.492     albertel 5153:               &nbsp;'.&mt('Specify file and which Folder/Sequence to grade').'
1.489     albertel 5154:             </th>
                   5155:        '.&Apache::loncommon::end_data_table_header_row().'
                   5156:        '.&Apache::loncommon::start_data_table_row().'
1.492     albertel 5157:             <td> '.&mt('Sequence to grade:').' </td><td> '.$sequence_selector.' </td>
1.489     albertel 5158:        '.&Apache::loncommon::end_data_table_row().'
                   5159:        '.&Apache::loncommon::start_data_table_row().'
1.572     www      5160:             <td> '.&mt('Filename of bubblesheet data file:').' </td><td> '.$file_selector.' </td>
1.489     albertel 5161:        '.&Apache::loncommon::end_data_table_row().'
                   5162:        '.&Apache::loncommon::start_data_table_row().'
1.572     www      5163:             <td> '.&mt('Format of bubblesheet data file:').' </td><td> '.$format_selector.' </td>
1.489     albertel 5164:        '.&Apache::loncommon::end_data_table_row().'
                   5165:        '.&Apache::loncommon::start_data_table_row().'
1.492     albertel 5166:             <td> '.&mt('Saved CODEs to validate against:').' </td><td> '.$CODE_selector.' </td>
1.489     albertel 5167:        '.&Apache::loncommon::end_data_table_row().'
                   5168:        '.&Apache::loncommon::start_data_table_row().'
1.492     albertel 5169:             <td> '.&mt('Each CODE is only to be used once:').'</td><td> '.$CODE_unique.' </td>
1.489     albertel 5170:        '.&Apache::loncommon::end_data_table_row().'
                   5171:        '.&Apache::loncommon::start_data_table_row().'
1.492     albertel 5172: 	    <td> '.&mt('Options:').' </td>
1.187     albertel 5173:             <td>
1.492     albertel 5174: 	       <label><input type="checkbox" name="scantron_options_redo" value="redo_skipped"/> '.&mt('Do only previously skipped records').'</label> <br />
                   5175:                <label><input type="checkbox" name="scantron_options_ignore" value="ignore_corrections"/> '.&mt('Remove all existing corrections').'</label> <br />
                   5176:                <label><input type="checkbox" name="scantron_options_hidden" value="ignore_hidden"/> '.&mt('Skip hidden resources when grading').'</label>
1.187     albertel 5177: 	    </td>
1.489     albertel 5178:        '.&Apache::loncommon::end_data_table_row().'
                   5179:        '.&Apache::loncommon::start_data_table_row().'
1.174     albertel 5180:             <td colspan="2">
1.572     www      5181:               <input type="submit" value="'.&mt('Grading: Validate Bubblesheet Records').'" />
1.162     albertel 5182:             </td>
1.489     albertel 5183:        '.&Apache::loncommon::end_data_table_row().'
                   5184:     '.&Apache::loncommon::end_data_table().'
                   5185:     </form>
                   5186: ';
1.162     albertel 5187:    
                   5188:     $r->print($result);
                   5189: 
1.422     foxr     5190: 
                   5191: 
                   5192:     # Chunk of the form that prompts to view a scoring office file,
                   5193:     # corrected file, skipped records in a file.
                   5194: 
1.489     albertel 5195:     $r->print('
                   5196:    <br />
                   5197:    <form action="/adm/grades" name="scantron_download">
                   5198:      '.$default_form_data.'
                   5199:      <input type="hidden" name="command" value="scantron_download" />
                   5200:      '.&Apache::loncommon::start_data_table('LC_scantron_action').'
                   5201:        '.&Apache::loncommon::start_data_table_header_row().'
                   5202:               <th>
1.492     albertel 5203:                 &nbsp;'.&mt('Download a scoring office file').'
1.489     albertel 5204:               </th>
                   5205:        '.&Apache::loncommon::end_data_table_header_row().'
                   5206:        '.&Apache::loncommon::start_data_table_row().'
1.492     albertel 5207:               <td> '.&mt('Filename of scoring office file: [_1]',$file_selector).' 
1.489     albertel 5208:                 <br />
1.492     albertel 5209:                 <input type="submit" value="'.&mt('Download: Show List of Associated Files').'" />
1.489     albertel 5210:        '.&Apache::loncommon::end_data_table_row().'
                   5211:      '.&Apache::loncommon::end_data_table().'
                   5212:    </form>
                   5213:    <br />
                   5214: ');
1.162     albertel 5215: 
1.457     banghart 5216:     &Apache::lonpickcode::code_list($r,2);
1.523     raeburn  5217: 
1.528     raeburn  5218:     $r->print('<br /><form method="post" name="checkscantron">'.
1.523     raeburn  5219:              $default_form_data."\n".
                   5220:              &Apache::loncommon::start_data_table('LC_scantron_action')."\n".
                   5221:              &Apache::loncommon::start_data_table_header_row()."\n".
                   5222:              '<th colspan="2">
1.572     www      5223:               &nbsp;'.&mt('Review bubblesheet data and submissions for a previously graded folder/sequence')."\n".
1.523     raeburn  5224:              '</th>'."\n".
                   5225:               &Apache::loncommon::end_data_table_header_row()."\n".
                   5226:               &Apache::loncommon::start_data_table_row()."\n".
                   5227:               '<td> '.&mt('Graded folder/sequence:').' </td>'."\n".
                   5228:               '<td> '.$sequence_selector.' </td>'.
                   5229:               &Apache::loncommon::end_data_table_row()."\n".
                   5230:               &Apache::loncommon::start_data_table_row()."\n".
                   5231:               '<td> '.&mt('Filename of scoring office file:').' </td>'."\n".
                   5232:               '<td> '.$file_selector.' </td>'."\n".
                   5233:               &Apache::loncommon::end_data_table_row()."\n".
                   5234:               &Apache::loncommon::start_data_table_row()."\n".
                   5235:               '<td> '.&mt('Format of data file:').' </td>'."\n".
                   5236:               '<td> '.$format_selector.' </td>'."\n".
                   5237:               &Apache::loncommon::end_data_table_row()."\n".
                   5238:               &Apache::loncommon::start_data_table_row()."\n".
1.557     raeburn  5239:               '<td> '.&mt('Options').' </td>'."\n".
                   5240:               '<td> <label><input type="checkbox" name="scantron_options_hidden" value="ignore_hidden"/> '.&mt('Skip hidden resources').'</label></td>'.
                   5241:               &Apache::loncommon::end_data_table_row()."\n".
                   5242:               &Apache::loncommon::start_data_table_row()."\n".
1.523     raeburn  5243:               '<td colspan="2">'."\n".
                   5244:               '<input type="hidden" name="command" value="checksubmissions" />'."\n".
1.575     www      5245:               '<input type="submit" value="'.&mt('Review Bubblesheet Data and Submission Records').'" />'."\n".
1.523     raeburn  5246:               '</td>'."\n".
                   5247:               &Apache::loncommon::end_data_table_row()."\n".
                   5248:               &Apache::loncommon::end_data_table()."\n".
                   5249:               '</form><br />');
                   5250:     return;
1.75      albertel 5251: }
                   5252: 
1.423     albertel 5253: =pod
                   5254: 
                   5255: =item get_scantron_config
                   5256: 
                   5257:    Parse and return the scantron configuration line selected as a
                   5258:    hash of configuration file fields.
                   5259: 
                   5260:  Arguments:
                   5261:     which - the name of the configuration to parse from the file.
                   5262: 
                   5263: 
                   5264:  Returns:
                   5265:             If the named configuration is not in the file, an empty
                   5266:             hash is returned.
                   5267:     a hash with the fields
                   5268:       name         - internal name for the this configuration setup
                   5269:       description  - text to display to operator that describes this config
                   5270:       CODElocation - if 0 or the string 'none'
                   5271:                           - no CODE exists for this config
                   5272:                      if -1 || the string 'letter'
                   5273:                           - a CODE exists for this config and is
                   5274:                             a string of letters
                   5275:                      Unsupported value (but planned for future support)
                   5276:                           if a positive integer
                   5277:                                - The CODE exists as the first n items from
                   5278:                                  the question section of the form
                   5279:                           if the string 'number'
                   5280:                                - The CODE exists for this config and is
                   5281:                                  a string of numbers
                   5282:       CODEstart   - (only matter if a CODE exists) column in the line where
                   5283:                      the CODE starts
                   5284:       CODElength  - length of the CODE
1.573     bisitz   5285:       IDstart     - column where the student/employee ID starts
1.556     weissno  5286:       IDlength    - length of the student/employee ID info
1.423     albertel 5287:       Qstart      - column where the information from the bubbled
                   5288:                     'questions' start
                   5289:       Qlength     - number of columns comprising a single bubble line from
                   5290:                     the sheet. (usually either 1 or 10)
1.424     albertel 5291:       Qon         - either a single character representing the character used
1.423     albertel 5292:                     to signal a bubble was chosen in the positional setup, or
                   5293:                     the string 'letter' if the letter of the chosen bubble is
                   5294:                     in the final, or 'number' if a number representing the
                   5295:                     chosen bubble is in the file (1->A 0->J)
1.424     albertel 5296:       Qoff        - the character used to represent that a bubble was
                   5297:                     left blank
1.423     albertel 5298:       PaperID     - if the scanning process generates a unique number for each
                   5299:                     sheet scanned the column that this ID number starts in
                   5300:       PaperIDlength - number of columns that comprise the unique ID number
                   5301:                       for the sheet of paper
1.424     albertel 5302:       FirstName   - column that the first name starts in
1.423     albertel 5303:       FirstNameLength - number of columns that the first name spans
                   5304:  
                   5305:       LastName    - column that the last name starts in
                   5306:       LastNameLength - number of columns that the last name spans
                   5307: 
                   5308: =cut
1.422     foxr     5309: 
1.82      albertel 5310: sub get_scantron_config {
                   5311:     my ($which) = @_;
1.518     raeburn  5312:     my @lines = &get_scantronformat_file();
1.82      albertel 5313:     my %config;
1.157     albertel 5314:     #FIXME probably should move to XML it has already gotten a bit much now
1.518     raeburn  5315:     foreach my $line (@lines) {
1.82      albertel 5316: 	my ($name,$descrip)=split(/:/,$line);
                   5317: 	if ($name ne $which ) { next; }
                   5318: 	chomp($line);
                   5319: 	my @config=split(/:/,$line);
                   5320: 	$config{'name'}=$config[0];
                   5321: 	$config{'description'}=$config[1];
                   5322: 	$config{'CODElocation'}=$config[2];
                   5323: 	$config{'CODEstart'}=$config[3];
                   5324: 	$config{'CODElength'}=$config[4];
                   5325: 	$config{'IDstart'}=$config[5];
                   5326: 	$config{'IDlength'}=$config[6];
                   5327: 	$config{'Qstart'}=$config[7];
1.497     foxr     5328:  	$config{'Qlength'}=$config[8];
1.82      albertel 5329: 	$config{'Qoff'}=$config[9];
                   5330: 	$config{'Qon'}=$config[10];
1.157     albertel 5331: 	$config{'PaperID'}=$config[11];
                   5332: 	$config{'PaperIDlength'}=$config[12];
                   5333: 	$config{'FirstName'}=$config[13];
                   5334: 	$config{'FirstNamelength'}=$config[14];
                   5335: 	$config{'LastName'}=$config[15];
                   5336: 	$config{'LastNamelength'}=$config[16];
1.82      albertel 5337: 	last;
                   5338:     }
                   5339:     return %config;
                   5340: }
                   5341: 
1.423     albertel 5342: =pod 
                   5343: 
                   5344: =item username_to_idmap
                   5345: 
1.556     weissno  5346:     creates a hash keyed by student/employee ID with values of the corresponding
1.423     albertel 5347:     student username:domain.
                   5348: 
                   5349:   Arguments:
                   5350: 
                   5351:     $classlist - reference to the class list hash. This is a hash
                   5352:                  keyed by student name:domain  whose elements are references
1.424     albertel 5353:                  to arrays containing various chunks of information
1.423     albertel 5354:                  about the student. (See loncoursedata for more info).
                   5355: 
                   5356:   Returns
                   5357:     %idmap - the constructed hash
                   5358: 
                   5359: =cut
                   5360: 
1.82      albertel 5361: sub username_to_idmap {
                   5362:     my ($classlist)= @_;
                   5363:     my %idmap;
                   5364:     foreach my $student (keys(%$classlist)) {
                   5365: 	$idmap{$classlist->{$student}->[&Apache::loncoursedata::CL_ID]}=
                   5366: 	    $student;
                   5367:     }
                   5368:     return %idmap;
                   5369: }
1.423     albertel 5370: 
                   5371: =pod
                   5372: 
1.424     albertel 5373: =item scantron_fixup_scanline
1.423     albertel 5374: 
                   5375:    Process a requested correction to a scanline.
                   5376: 
                   5377:   Arguments:
                   5378:     $scantron_config   - hash from &get_scantron_config()
                   5379:     $scan_data         - hash of correction information 
                   5380:                           (see &scantron_getfile())
                   5381:     $line              - existing scanline
                   5382:     $whichline         - line number of the passed in scanline
                   5383:     $field             - type of change to process 
                   5384:                          (either 
1.573     bisitz   5385:                           'ID'     -> correct the student/employee ID
1.423     albertel 5386:                           'CODE'   -> correct the CODE
                   5387:                           'answer' -> fixup the submitted answers)
                   5388:     
                   5389:    $args               - hash of additional info,
                   5390:                           - 'ID' 
                   5391:                                'newid' -> studentID to use in replacement
1.424     albertel 5392:                                           of existing one
1.423     albertel 5393:                           - 'CODE' 
                   5394:                                'CODE_ignore_dup' - set to true if duplicates
                   5395:                                                    should be ignored.
                   5396: 	                       'CODE' - is new code or 'use_unfound'
1.424     albertel 5397:                                         if the existing unfound code should
1.423     albertel 5398:                                         be used as is
                   5399:                           - 'answer'
                   5400:                                'response' - new answer or 'none' if blank
                   5401:                                'question' - the bubble line to change
1.503     raeburn  5402:                                'questionnum' - the question identifier,
                   5403:                                                may include subquestion. 
1.423     albertel 5404: 
                   5405:   Returns:
                   5406:     $line - the modified scanline
                   5407: 
                   5408:   Side effects: 
                   5409:     $scan_data - may be updated
                   5410: 
                   5411: =cut
                   5412: 
1.82      albertel 5413: 
1.157     albertel 5414: sub scantron_fixup_scanline {
                   5415:     my ($scantron_config,$scan_data,$line,$whichline,$field,$args)=@_;
                   5416:     if ($field eq 'ID') {
                   5417: 	if (length($args->{'newid'}) > $$scantron_config{'IDlength'}) {
1.186     albertel 5418: 	    return ($line,1,'New value too large');
1.157     albertel 5419: 	}
                   5420: 	if (length($args->{'newid'}) < $$scantron_config{'IDlength'}) {
                   5421: 	    $args->{'newid'}=sprintf('%-'.$$scantron_config{'IDlength'}.'s',
                   5422: 				     $args->{'newid'});
                   5423: 	}
                   5424: 	substr($line,$$scantron_config{'IDstart'}-1,
                   5425: 	       $$scantron_config{'IDlength'})=$args->{'newid'};
                   5426: 	if ($args->{'newid'}=~/^\s*$/) {
                   5427: 	    &scan_data($scan_data,"$whichline.user",
                   5428: 		       $args->{'username'}.':'.$args->{'domain'});
                   5429: 	}
1.186     albertel 5430:     } elsif ($field eq 'CODE') {
1.192     albertel 5431: 	if ($args->{'CODE_ignore_dup'}) {
                   5432: 	    &scan_data($scan_data,"$whichline.CODE_ignore_dup",'1');
                   5433: 	}
                   5434: 	&scan_data($scan_data,"$whichline.useCODE",'1');
                   5435: 	if ($args->{'CODE'} ne 'use_unfound') {
1.191     albertel 5436: 	    if (length($args->{'CODE'}) > $$scantron_config{'CODElength'}) {
                   5437: 		return ($line,1,'New CODE value too large');
                   5438: 	    }
                   5439: 	    if (length($args->{'CODE'}) < $$scantron_config{'CODElength'}) {
                   5440: 		$args->{'CODE'}=sprintf('%-'.$$scantron_config{'CODElength'}.'s',$args->{'CODE'});
                   5441: 	    }
                   5442: 	    substr($line,$$scantron_config{'CODEstart'}-1,
                   5443: 		   $$scantron_config{'CODElength'})=$args->{'CODE'};
1.186     albertel 5444: 	}
1.157     albertel 5445:     } elsif ($field eq 'answer') {
1.497     foxr     5446: 	my $length=$scantron_config->{'Qlength'};
1.157     albertel 5447: 	my $off=$scantron_config->{'Qoff'};
                   5448: 	my $on=$scantron_config->{'Qon'};
1.497     foxr     5449: 	my $answer=${off}x$length;
                   5450: 	if ($args->{'response'} eq 'none') {
                   5451: 	    &scan_data($scan_data,
1.503     raeburn  5452: 		       "$whichline.no_bubble.".$args->{'questionnum'},'1');
1.497     foxr     5453: 	} else {
                   5454: 	    if ($on eq 'letter') {
                   5455: 		my @alphabet=('A'..'Z');
                   5456: 		$answer=$alphabet[$args->{'response'}];
                   5457: 	    } elsif ($on eq 'number') {
                   5458: 		$answer=$args->{'response'}+1;
                   5459: 		if ($answer == 10) { $answer = '0'; }
1.274     albertel 5460: 	    } else {
1.497     foxr     5461: 		substr($answer,$args->{'response'},1)=$on;
1.274     albertel 5462: 	    }
1.497     foxr     5463: 	    &scan_data($scan_data,
1.503     raeburn  5464: 		       "$whichline.no_bubble.".$args->{'questionnum'},undef,'1');
1.157     albertel 5465: 	}
1.497     foxr     5466: 	my $where=$length*($args->{'question'}-1)+$scantron_config->{'Qstart'};
                   5467: 	substr($line,$where-1,$length)=$answer;
1.157     albertel 5468:     }
                   5469:     return $line;
                   5470: }
1.423     albertel 5471: 
                   5472: =pod
                   5473: 
                   5474: =item scan_data
                   5475: 
                   5476:     Edit or look up  an item in the scan_data hash.
                   5477: 
                   5478:   Arguments:
                   5479:     $scan_data  - The hash (see scantron_getfile)
                   5480:     $key        - shorthand of the key to edit (actual key is
1.424     albertel 5481:                   scantronfilename_key).
1.423     albertel 5482:     $data        - New value of the hash entry.
                   5483:     $delete      - If true, the entry is removed from the hash.
                   5484: 
                   5485:   Returns:
                   5486:     The new value of the hash table field (undefined if deleted).
                   5487: 
                   5488: =cut
                   5489: 
                   5490: 
1.157     albertel 5491: sub scan_data {
                   5492:     my ($scan_data,$key,$value,$delete)=@_;
1.257     albertel 5493:     my $filename=$env{'form.scantron_selectfile'};
1.157     albertel 5494:     if (defined($value)) {
                   5495: 	$scan_data->{$filename.'_'.$key} = $value;
                   5496:     }
                   5497:     if ($delete) { delete($scan_data->{$filename.'_'.$key}); }
                   5498:     return $scan_data->{$filename.'_'.$key};
                   5499: }
1.423     albertel 5500: 
1.495     albertel 5501: # ----- These first few routines are general use routines.----
                   5502: 
                   5503: # Return the number of occurences of a pattern in a string.
                   5504: 
                   5505: sub occurence_count {
                   5506:     my ($string, $pattern) = @_;
                   5507: 
                   5508:     my @matches = ($string =~ /$pattern/g);
                   5509: 
                   5510:     return scalar(@matches);
                   5511: }
                   5512: 
                   5513: 
                   5514: # Take a string known to have digits and convert all the
                   5515: # digits into letters in the range J,A..I.
                   5516: 
                   5517: sub digits_to_letters {
                   5518:     my ($input) = @_;
                   5519: 
                   5520:     my @alphabet = ('J', 'A'..'I');
                   5521: 
                   5522:     my @input    = split(//, $input);
                   5523:     my $output ='';
                   5524:     for (my $i = 0; $i < scalar(@input); $i++) {
                   5525: 	if ($input[$i] =~ /\d/) {
                   5526: 	    $output .= $alphabet[$input[$i]];
                   5527: 	} else {
                   5528: 	    $output .= $input[$i];
                   5529: 	}
                   5530:     }
                   5531:     return $output;
                   5532: }
                   5533: 
1.423     albertel 5534: =pod 
                   5535: 
                   5536: =item scantron_parse_scanline
                   5537: 
                   5538:   Decodes a scanline from the selected scantron file
                   5539: 
                   5540:  Arguments:
                   5541:     line             - The text of the scantron file line to process
                   5542:     whichline        - Line number
                   5543:     scantron_config  - Hash describing the format of the scantron lines.
                   5544:     scan_data        - Hash of extra information about the scanline
                   5545:                        (see scantron_getfile for more information)
                   5546:     just_header      - True if should not process question answers but only
                   5547:                        the stuff to the left of the answers.
                   5548:  Returns:
                   5549:    Hash containing the result of parsing the scanline
                   5550: 
                   5551:    Keys are all proceeded by the string 'scantron.'
                   5552: 
                   5553:        CODE    - the CODE in use for this scanline
                   5554:        useCODE - 1 if the CODE is invalid but it usage has been forced
                   5555:                  by the operator
                   5556:        CODE_ignore_dup - 1 if the CODE is a duplicated use when unique
                   5557:                             CODEs were selected, but the usage has been
                   5558:                             forced by the operator
1.556     weissno  5559:        ID  - student/employee ID
1.423     albertel 5560:        PaperID - if used, the ID number printed on the sheet when the 
                   5561:                  paper was scanned
                   5562:        FirstName - first name from the sheet
                   5563:        LastName  - last name from the sheet
                   5564: 
                   5565:      if just_header was not true these key may also exist
                   5566: 
1.447     foxr     5567:        missingerror - a list of bubble ranges that are considered to be answers
                   5568:                       to a single question that don't have any bubbles filled in.
                   5569:                       Of the form questionnumber:firstbubblenumber:count.
                   5570:        doubleerror  - a list of bubble ranges that are considered to be answers
                   5571:                       to a single question that have more than one bubble filled in.
                   5572:                       Of the form questionnumber::firstbubblenumber:count
                   5573:    
                   5574:                 In the above, count is the number of bubble responses in the
                   5575:                 input line needed to represent the possible answers to the question.
                   5576:                 e.g. a radioresponse with 15 choices in an answer sheet with 10 choices
                   5577:                 per line would have count = 2.
                   5578: 
1.423     albertel 5579:        maxquest     - the number of the last bubble line that was parsed
                   5580: 
                   5581:        (<number> starts at 1)
                   5582:        <number>.answer - zero or more letters representing the selected
                   5583:                          letters from the scanline for the bubble line 
                   5584:                          <number>.
                   5585:                          if blank there was either no bubble or there where
                   5586:                          multiple bubbles, (consult the keys missingerror and
                   5587:                          doubleerror if this is an error condition)
                   5588: 
                   5589: =cut
                   5590: 
1.82      albertel 5591: sub scantron_parse_scanline {
1.423     albertel 5592:     my ($line,$whichline,$scantron_config,$scan_data,$just_header)=@_;
1.470     foxr     5593: 
1.82      albertel 5594:     my %record;
1.550     raeburn  5595:     my $lastpos = $env{'form.scantron_maxbubble'}*$$scantron_config{'Qlength'};
                   5596:     my $questions=substr($line,$$scantron_config{'Qstart'}-1,$lastpos);  # Answers
1.422     foxr     5597:     my $data=substr($line,0,$$scantron_config{'Qstart'}-1);     # earlier stuff
1.278     albertel 5598:     if (!($$scantron_config{'CODElocation'} eq 0 ||
                   5599: 	  $$scantron_config{'CODElocation'} eq 'none')) {
                   5600: 	if ($$scantron_config{'CODElocation'} < 0 ||
                   5601: 	    $$scantron_config{'CODElocation'} eq 'letter' ||
                   5602: 	    $$scantron_config{'CODElocation'} eq 'number') {
1.191     albertel 5603: 	    $record{'scantron.CODE'}=substr($data,
                   5604: 					    $$scantron_config{'CODEstart'}-1,
1.83      albertel 5605: 					    $$scantron_config{'CODElength'});
1.191     albertel 5606: 	    if (&scan_data($scan_data,"$whichline.useCODE")) {
                   5607: 		$record{'scantron.useCODE'}=1;
                   5608: 	    }
1.192     albertel 5609: 	    if (&scan_data($scan_data,"$whichline.CODE_ignore_dup")) {
                   5610: 		$record{'scantron.CODE_ignore_dup'}=1;
                   5611: 	    }
1.82      albertel 5612: 	} else {
                   5613: 	    #FIXME interpret first N questions
                   5614: 	}
                   5615:     }
1.83      albertel 5616:     $record{'scantron.ID'}=substr($data,$$scantron_config{'IDstart'}-1,
                   5617: 				  $$scantron_config{'IDlength'});
1.157     albertel 5618:     $record{'scantron.PaperID'}=
                   5619: 	substr($data,$$scantron_config{'PaperID'}-1,
                   5620: 	       $$scantron_config{'PaperIDlength'});
                   5621:     $record{'scantron.FirstName'}=
                   5622: 	substr($data,$$scantron_config{'FirstName'}-1,
                   5623: 	       $$scantron_config{'FirstNamelength'});
                   5624:     $record{'scantron.LastName'}=
                   5625: 	substr($data,$$scantron_config{'LastName'}-1,
                   5626: 	       $$scantron_config{'LastNamelength'});
1.423     albertel 5627:     if ($just_header) { return \%record; }
1.194     albertel 5628: 
1.82      albertel 5629:     my @alphabet=('A'..'Z');
                   5630:     my $questnum=0;
1.447     foxr     5631:     my $ansnum  =1;		# Multiple 'answer lines'/question.
                   5632: 
1.470     foxr     5633:     chomp($questions);		# Get rid of any trailing \n.
                   5634:     $questions =~ s/\r$//;      # Get rid of trailing \r too (MAC or Win uploads).
                   5635:     while (length($questions)) {
1.447     foxr     5636: 	my $answers_needed = $bubble_lines_per_response{$questnum};
1.503     raeburn  5637:         my $answer_length  = ($$scantron_config{'Qlength'} * $answers_needed)
                   5638:                              || 1;
                   5639:         $questnum++;
                   5640:         my $quest_id = $questnum;
                   5641:         my $currentquest = substr($questions,0,$answer_length);
                   5642:         $questions       = substr($questions,$answer_length);
                   5643:         if (length($currentquest) < $answer_length) { next; }
                   5644: 
                   5645:         if ($subdivided_bubble_lines{$questnum-1} =~ /,/) {
                   5646:             my $subquestnum = 1;
                   5647:             my $subquestions = $currentquest;
                   5648:             my @subanswers_needed = 
                   5649:                 split(/,/,$subdivided_bubble_lines{$questnum-1});  
                   5650:             foreach my $subans (@subanswers_needed) {
                   5651:                 my $subans_length =
                   5652:                     ($$scantron_config{'Qlength'} * $subans)  || 1;
                   5653:                 my $currsubquest = substr($subquestions,0,$subans_length);
                   5654:                 $subquestions   = substr($subquestions,$subans_length);
                   5655:                 $quest_id = "$questnum.$subquestnum";
                   5656:                 if (($$scantron_config{'Qon'} eq 'letter') ||
                   5657:                     ($$scantron_config{'Qon'} eq 'number')) {
                   5658:                     $ansnum = &scantron_validator_lettnum($ansnum, 
                   5659:                         $questnum,$quest_id,$subans,$currsubquest,$whichline,
                   5660:                         \@alphabet,\%record,$scantron_config,$scan_data);
                   5661:                 } else {
                   5662:                     $ansnum = &scantron_validator_positional($ansnum,
                   5663:                         $questnum,$quest_id,$subans,$currsubquest,$whichline,                        \@alphabet,\%record,$scantron_config,$scan_data);
                   5664:                 }
                   5665:                 $subquestnum ++;
                   5666:             }
                   5667:         } else {
                   5668:             if (($$scantron_config{'Qon'} eq 'letter') ||
                   5669:                 ($$scantron_config{'Qon'} eq 'number')) {
                   5670:                 $ansnum = &scantron_validator_lettnum($ansnum,$questnum,
                   5671:                     $quest_id,$answers_needed,$currentquest,$whichline,
                   5672:                     \@alphabet,\%record,$scantron_config,$scan_data);
                   5673:             } else {
                   5674:                 $ansnum = &scantron_validator_positional($ansnum,$questnum,
                   5675:                     $quest_id,$answers_needed,$currentquest,$whichline,
                   5676:                     \@alphabet,\%record,$scantron_config,$scan_data);
                   5677:             }
                   5678:         }
                   5679:     }
                   5680:     $record{'scantron.maxquest'}=$questnum;
                   5681:     return \%record;
                   5682: }
1.447     foxr     5683: 
1.503     raeburn  5684: sub scantron_validator_lettnum {
                   5685:     my ($ansnum,$questnum,$quest_id,$answers_needed,$currquest,$whichline,
                   5686:         $alphabet,$record,$scantron_config,$scan_data) = @_;
                   5687: 
                   5688:     # Qon 'letter' implies for each slot in currquest we have:
                   5689:     #    ? or * for doubles, a letter in A-Z for a bubble, and
                   5690:     #    about anything else (esp. a value of Qoff) for missing
                   5691:     #    bubbles.
                   5692:     #
                   5693:     # Qon 'number' implies each slot gives a digit that indexes the
                   5694:     #    bubbles filled, or Qoff, or a non-number for unbubbled lines,
                   5695:     #    and * or ? for double bubbles on a single line.
                   5696:     #
1.447     foxr     5697: 
1.503     raeburn  5698:     my $matchon;
                   5699:     if ($$scantron_config{'Qon'} eq 'letter') {
                   5700:         $matchon = '[A-Z]';
                   5701:     } elsif ($$scantron_config{'Qon'} eq 'number') {
                   5702:         $matchon = '\d';
                   5703:     }
                   5704:     my $occurrences = 0;
                   5705:     if (($responsetype_per_response{$questnum-1} eq 'essayresponse') ||
                   5706:         ($responsetype_per_response{$questnum-1} eq 'formularesponse') ||
1.510     raeburn  5707:         ($responsetype_per_response{$questnum-1} eq 'stringresponse') ||
                   5708:         ($responsetype_per_response{$questnum-1} eq 'imageresponse') ||
                   5709:         ($responsetype_per_response{$questnum-1} eq 'reactionresponse') ||
                   5710:         ($responsetype_per_response{$questnum-1} eq 'organicresponse')) {
1.503     raeburn  5711:         my @singlelines = split('',$currquest);
                   5712:         foreach my $entry (@singlelines) {
                   5713:             $occurrences = &occurence_count($entry,$matchon);
                   5714:             if ($occurrences > 1) {
                   5715:                 last;
                   5716:             }
                   5717:         } 
                   5718:     } else {
                   5719:         $occurrences = &occurence_count($currquest,$matchon); 
                   5720:     }
                   5721:     if (($currquest =~ /\?/ || $currquest =~ /\*/) || ($occurrences > 1)) {
                   5722:         push(@{$record->{'scantron.doubleerror'}},$quest_id);
                   5723:         for (my $ans=0; $ans<$answers_needed; $ans++) {
                   5724:             my $bubble = substr($currquest,$ans,1);
                   5725:             if ($bubble =~ /$matchon/ ) {
                   5726:                 if ($$scantron_config{'Qon'} eq 'number') {
                   5727:                     if ($bubble == 0) {
                   5728:                         $bubble = 10; 
                   5729:                     }
                   5730:                     $record->{"scantron.$ansnum.answer"} = 
                   5731:                         $alphabet->[$bubble-1];
                   5732:                 } else {
                   5733:                     $record->{"scantron.$ansnum.answer"} = $bubble;
                   5734:                 }
                   5735:             } else {
                   5736:                 $record->{"scantron.$ansnum.answer"}='';
                   5737:             }
                   5738:             $ansnum++;
                   5739:         }
                   5740:     } elsif (!defined($currquest)
                   5741:             || (&occurence_count($currquest, $$scantron_config{'Qoff'}) == length($currquest))
                   5742:             || (&occurence_count($currquest,$matchon) == 0)) {
                   5743:         for (my $ans=0; $ans<$answers_needed; $ans++ ) {
                   5744:             $record->{"scantron.$ansnum.answer"}='';
                   5745:             $ansnum++;
                   5746:         }
                   5747:         if (!&scan_data($scan_data,"$whichline.no_bubble.$quest_id")) {
                   5748:             push(@{$record->{'scantron.missingerror'}},$quest_id);
                   5749:         }
                   5750:     } else {
                   5751:         if ($$scantron_config{'Qon'} eq 'number') {
                   5752:             $currquest = &digits_to_letters($currquest);            
                   5753:         }
                   5754:         for (my $ans=0; $ans<$answers_needed; $ans++) {
                   5755:             my $bubble = substr($currquest,$ans,1);
                   5756:             $record->{"scantron.$ansnum.answer"} = $bubble;
                   5757:             $ansnum++;
                   5758:         }
                   5759:     }
                   5760:     return $ansnum;
                   5761: }
1.447     foxr     5762: 
1.503     raeburn  5763: sub scantron_validator_positional {
                   5764:     my ($ansnum,$questnum,$quest_id,$answers_needed,$currquest,
                   5765:         $whichline,$alphabet,$record,$scantron_config,$scan_data) = @_;
1.447     foxr     5766: 
1.503     raeburn  5767:     # Otherwise there's a positional notation;
                   5768:     # each bubble line requires Qlength items, and there are filled in
                   5769:     # bubbles for each case where there 'Qon' characters.
                   5770:     #
1.447     foxr     5771: 
1.503     raeburn  5772:     my @array=split($$scantron_config{'Qon'},$currquest,-1);
1.447     foxr     5773: 
1.503     raeburn  5774:     # If the split only gives us one element.. the full length of the
                   5775:     # answer string, no bubbles are filled in:
1.447     foxr     5776: 
1.507     raeburn  5777:     if ($answers_needed eq '') {
                   5778:         return;
                   5779:     }
                   5780: 
1.503     raeburn  5781:     if (length($array[0]) eq $$scantron_config{'Qlength'}*$answers_needed) {
                   5782:         for (my $ans=0; $ans<$answers_needed; $ans++ ) {
                   5783:             $record->{"scantron.$ansnum.answer"}='';
                   5784:             $ansnum++;
                   5785:         }
                   5786:         if (!&scan_data($scan_data,"$whichline.no_bubble.$quest_id")) {
                   5787:             push(@{$record->{"scantron.missingerror"}},$quest_id);
                   5788:         }
                   5789:     } elsif (scalar(@array) == 2) {
                   5790:         my $location = length($array[0]);
                   5791:         my $line_num = int($location / $$scantron_config{'Qlength'});
                   5792:         my $bubble   = $alphabet->[$location % $$scantron_config{'Qlength'}];
                   5793:         for (my $ans=0; $ans<$answers_needed; $ans++) {
                   5794:             if ($ans eq $line_num) {
                   5795:                 $record->{"scantron.$ansnum.answer"} = $bubble;
                   5796:             } else {
                   5797:                 $record->{"scantron.$ansnum.answer"} = ' ';
                   5798:             }
                   5799:             $ansnum++;
                   5800:          }
                   5801:     } else {
                   5802:         #  If there's more than one instance of a bubble character
                   5803:         #  That's a double bubble; with positional notation we can
                   5804:         #  record all the bubbles filled in as well as the
                   5805:         #  fact this response consists of multiple bubbles.
                   5806:         #
                   5807:         if (($responsetype_per_response{$questnum-1} eq 'essayresponse') ||
                   5808:             ($responsetype_per_response{$questnum-1} eq 'formularesponse') ||
1.510     raeburn  5809:             ($responsetype_per_response{$questnum-1} eq 'stringresponse') ||
                   5810:             ($responsetype_per_response{$questnum-1} eq 'imageresponse') ||
                   5811:             ($responsetype_per_response{$questnum-1} eq 'reactionresponse') ||
                   5812:             ($responsetype_per_response{$questnum-1} eq 'organicresponse')) {
1.503     raeburn  5813:             my $doubleerror = 0;
                   5814:             while (($currquest >= $$scantron_config{'Qlength'}) && 
                   5815:                    (!$doubleerror)) {
                   5816:                my $currline = substr($currquest,0,$$scantron_config{'Qlength'});
                   5817:                $currquest = substr($currquest,$$scantron_config{'Qlength'});
                   5818:                my @currarray = split($$scantron_config{'Qon'},$currline,-1);
                   5819:                if (length(@currarray) > 2) {
                   5820:                    $doubleerror = 1;
                   5821:                } 
                   5822:             }
                   5823:             if ($doubleerror) {
                   5824:                 push(@{$record->{'scantron.doubleerror'}},$quest_id);
                   5825:             }
                   5826:         } else {
                   5827:             push(@{$record->{'scantron.doubleerror'}},$quest_id);
                   5828:         }
                   5829:         my $item = $ansnum;
                   5830:         for (my $ans=0; $ans<$answers_needed; $ans++) {
                   5831:             $record->{"scantron.$item.answer"} = '';
                   5832:             $item ++;
                   5833:         }
1.447     foxr     5834: 
1.503     raeburn  5835:         my @ans=@array;
                   5836:         my $i=0;
                   5837:         my $increment = 0;
                   5838:         while ($#ans) {
                   5839:             $i+=length($ans[0]) + $increment;
                   5840:             my $line   = int($i/$$scantron_config{'Qlength'} + $ansnum);
                   5841:             my $bubble = $i%$$scantron_config{'Qlength'};
                   5842:             $record->{"scantron.$line.answer"}.=$alphabet->[$bubble];
                   5843:             shift(@ans);
                   5844:             $increment = 1;
                   5845:         }
                   5846:         $ansnum += $answers_needed;
1.82      albertel 5847:     }
1.503     raeburn  5848:     return $ansnum;
1.82      albertel 5849: }
                   5850: 
1.423     albertel 5851: =pod
                   5852: 
                   5853: =item scantron_add_delay
                   5854: 
                   5855:    Adds an error message that occurred during the grading phase to a
                   5856:    queue of messages to be shown after grading pass is complete
                   5857: 
                   5858:  Arguments:
1.424     albertel 5859:    $delayqueue  - arrary ref of hash ref of error messages
1.423     albertel 5860:    $scanline    - the scanline that caused the error
                   5861:    $errormesage - the error message
                   5862:    $errorcode   - a numeric code for the error
                   5863: 
                   5864:  Side Effects:
1.424     albertel 5865:    updates the $delayqueue to have a new hash ref of the error
1.423     albertel 5866: 
                   5867: =cut
                   5868: 
1.82      albertel 5869: sub scantron_add_delay {
1.140     albertel 5870:     my ($delayqueue,$scanline,$errormessage,$errorcode)=@_;
                   5871:     push(@$delayqueue,
                   5872: 	 {'line' => $scanline, 'emsg' => $errormessage,
                   5873: 	  'ecode' => $errorcode }
                   5874: 	 );
1.82      albertel 5875: }
                   5876: 
1.423     albertel 5877: =pod
                   5878: 
                   5879: =item scantron_find_student
                   5880: 
1.424     albertel 5881:    Finds the username for the current scanline
                   5882: 
                   5883:   Arguments:
                   5884:    $scantron_record - hash result from scantron_parse_scanline
                   5885:    $scan_data       - hash of correction information 
                   5886:                       (see &scantron_getfile() form more information)
                   5887:    $idmap           - hash from &username_to_idmap()
                   5888:    $line            - number of current scanline
                   5889:  
                   5890:   Returns:
                   5891:    Either 'username:domain' or undef if unknown
                   5892: 
1.423     albertel 5893: =cut
                   5894: 
1.82      albertel 5895: sub scantron_find_student {
1.157     albertel 5896:     my ($scantron_record,$scan_data,$idmap,$line)=@_;
1.83      albertel 5897:     my $scanID=$$scantron_record{'scantron.ID'};
1.157     albertel 5898:     if ($scanID =~ /^\s*$/) {
                   5899:  	return &scan_data($scan_data,"$line.user");
                   5900:     }
1.83      albertel 5901:     foreach my $id (keys(%$idmap)) {
1.157     albertel 5902:  	if (lc($id) eq lc($scanID)) {
                   5903:  	    return $$idmap{$id};
                   5904:  	}
1.83      albertel 5905:     }
                   5906:     return undef;
                   5907: }
                   5908: 
1.423     albertel 5909: =pod
                   5910: 
                   5911: =item scantron_filter
                   5912: 
1.424     albertel 5913:    Filter sub for lonnavmaps, filters out hidden resources if ignore
                   5914:    hidden resources was selected
                   5915: 
1.423     albertel 5916: =cut
                   5917: 
1.83      albertel 5918: sub scantron_filter {
                   5919:     my ($curres)=@_;
1.331     albertel 5920: 
                   5921:     if (ref($curres) && $curres->is_problem()) {
                   5922: 	# if the user has asked to not have either hidden
                   5923: 	# or 'randomout' controlled resources to be graded
                   5924: 	# don't include them
                   5925: 	if ($env{'form.scantron_options_hidden'} eq 'ignore_hidden'
                   5926: 	    && $curres->randomout) {
                   5927: 	    return 0;
                   5928: 	}
1.83      albertel 5929: 	return 1;
                   5930:     }
                   5931:     return 0;
1.82      albertel 5932: }
                   5933: 
1.423     albertel 5934: =pod
                   5935: 
                   5936: =item scantron_process_corrections
                   5937: 
1.424     albertel 5938:    Gets correction information out of submitted form data and corrects
                   5939:    the scanline
                   5940: 
1.423     albertel 5941: =cut
                   5942: 
1.157     albertel 5943: sub scantron_process_corrections {
                   5944:     my ($r) = @_;
1.257     albertel 5945:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.157     albertel 5946:     my ($scanlines,$scan_data)=&scantron_getfile();
                   5947:     my $classlist=&Apache::loncoursedata::get_classlist();
1.257     albertel 5948:     my $which=$env{'form.scantron_line'};
1.200     albertel 5949:     my $line=&scantron_get_line($scanlines,$scan_data,$which);
1.157     albertel 5950:     my ($skip,$err,$errmsg);
1.257     albertel 5951:     if ($env{'form.scantron_skip_record'}) {
1.157     albertel 5952: 	$skip=1;
1.257     albertel 5953:     } elsif ($env{'form.scantron_corrections'} =~ /^(duplicate|incorrect)ID$/) {
                   5954: 	my $newstudent=$env{'form.scantron_username'}.':'.
                   5955: 	    $env{'form.scantron_domain'};
1.157     albertel 5956: 	my $newid=$classlist->{$newstudent}->[&Apache::loncoursedata::CL_ID];
                   5957: 	($line,$err,$errmsg)=
                   5958: 	    &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,$which,
                   5959: 				     'ID',{'newid'=>$newid,
1.257     albertel 5960: 				    'username'=>$env{'form.scantron_username'},
                   5961: 				    'domain'=>$env{'form.scantron_domain'}});
                   5962:     } elsif ($env{'form.scantron_corrections'} =~ /^(duplicate|incorrect)CODE$/) {
                   5963: 	my $resolution=$env{'form.scantron_CODE_resolution'};
1.190     albertel 5964: 	my $newCODE;
1.192     albertel 5965: 	my %args;
1.190     albertel 5966: 	if      ($resolution eq 'use_unfound') {
1.191     albertel 5967: 	    $newCODE='use_unfound';
1.190     albertel 5968: 	} elsif ($resolution eq 'use_found') {
1.257     albertel 5969: 	    $newCODE=$env{'form.scantron_CODE_selectedvalue'};
1.190     albertel 5970: 	} elsif ($resolution eq 'use_typed') {
1.257     albertel 5971: 	    $newCODE=$env{'form.scantron_CODE_newvalue'};
1.194     albertel 5972: 	} elsif ($resolution =~ /^use_closest_(\d+)/) {
1.257     albertel 5973: 	    $newCODE=$env{"form.scantron_CODE_closest_$1"};
1.190     albertel 5974: 	}
1.257     albertel 5975: 	if ($env{'form.scantron_corrections'} eq 'duplicateCODE') {
1.192     albertel 5976: 	    $args{'CODE_ignore_dup'}=1;
                   5977: 	}
                   5978: 	$args{'CODE'}=$newCODE;
1.186     albertel 5979: 	($line,$err,$errmsg)=
                   5980: 	    &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,$which,
1.192     albertel 5981: 				     'CODE',\%args);
1.257     albertel 5982:     } elsif ($env{'form.scantron_corrections'} =~ /^(missing|double)bubble$/) {
                   5983: 	foreach my $question (split(',',$env{'form.scantron_questions'})) {
1.157     albertel 5984: 	    ($line,$err,$errmsg)=
                   5985: 		&scantron_fixup_scanline(\%scantron_config,$scan_data,$line,
                   5986: 					 $which,'answer',
                   5987: 					 { 'question'=>$question,
1.503     raeburn  5988: 		      		   'response'=>$env{"form.scantron_correct_Q_$question"},
                   5989:                                    'questionnum'=>$env{"form.scantron_questionnum_Q_$question"}});
1.157     albertel 5990: 	    if ($err) { last; }
                   5991: 	}
                   5992:     }
                   5993:     if ($err) {
1.398     albertel 5994: 	$r->print("<span class=\"LC_warning\">Unable to accept last correction, an error occurred :$errmsg:</span>");
1.157     albertel 5995:     } else {
1.200     albertel 5996: 	&scantron_put_line($scanlines,$scan_data,$which,$line,$skip);
1.157     albertel 5997: 	&scantron_putfile($scanlines,$scan_data);
                   5998:     }
                   5999: }
                   6000: 
1.423     albertel 6001: =pod
                   6002: 
                   6003: =item reset_skipping_status
                   6004: 
1.424     albertel 6005:    Forgets the current set of remember skipped scanlines (and thus
                   6006:    reverts back to considering all lines in the
                   6007:    scantron_skipped_<filename> file)
                   6008: 
1.423     albertel 6009: =cut
                   6010: 
1.200     albertel 6011: sub reset_skipping_status {
                   6012:     my ($scanlines,$scan_data)=&scantron_getfile();
                   6013:     &scan_data($scan_data,'remember_skipping',undef,1);
                   6014:     &scantron_putfile(undef,$scan_data);
                   6015: }
                   6016: 
1.423     albertel 6017: =pod
                   6018: 
                   6019: =item start_skipping
                   6020: 
1.424     albertel 6021:    Marks a scanline to be skipped. 
                   6022: 
1.423     albertel 6023: =cut
                   6024: 
1.376     albertel 6025: sub start_skipping {
1.200     albertel 6026:     my ($scan_data,$i)=@_;
                   6027:     my %remembered=split(':',&scan_data($scan_data,'remember_skipping'));
1.376     albertel 6028:     if ($env{'form.scantron_options_redo'} =~ /^redo_/) {
                   6029: 	$remembered{$i}=2;
                   6030:     } else {
                   6031: 	$remembered{$i}=1;
                   6032:     }
1.200     albertel 6033:     &scan_data($scan_data,'remember_skipping',join(':',%remembered));
                   6034: }
                   6035: 
1.423     albertel 6036: =pod
                   6037: 
                   6038: =item should_be_skipped
                   6039: 
1.424     albertel 6040:    Checks whether a scanline should be skipped.
                   6041: 
1.423     albertel 6042: =cut
                   6043: 
1.200     albertel 6044: sub should_be_skipped {
1.376     albertel 6045:     my ($scanlines,$scan_data,$i)=@_;
1.257     albertel 6046:     if ($env{'form.scantron_options_redo'} !~ /^redo_/) {
1.200     albertel 6047: 	# not redoing old skips
1.376     albertel 6048: 	if ($scanlines->{'skipped'}[$i]) { return 1; }
1.200     albertel 6049: 	return 0;
                   6050:     }
                   6051:     my %remembered=split(':',&scan_data($scan_data,'remember_skipping'));
1.376     albertel 6052: 
                   6053:     if (exists($remembered{$i}) && $remembered{$i} != 2 ) {
                   6054: 	return 0;
                   6055:     }
1.200     albertel 6056:     return 1;
                   6057: }
                   6058: 
1.423     albertel 6059: =pod
                   6060: 
                   6061: =item remember_current_skipped
                   6062: 
1.424     albertel 6063:    Discovers what scanlines are in the scantron_skipped_<filename>
                   6064:    file and remembers them into scan_data for later use.
                   6065: 
1.423     albertel 6066: =cut
                   6067: 
1.200     albertel 6068: sub remember_current_skipped {
                   6069:     my ($scanlines,$scan_data)=&scantron_getfile();
                   6070:     my %to_remember;
                   6071:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
                   6072: 	if ($scanlines->{'skipped'}[$i]) {
                   6073: 	    $to_remember{$i}=1;
                   6074: 	}
                   6075:     }
1.376     albertel 6076: 
1.200     albertel 6077:     &scan_data($scan_data,'remember_skipping',join(':',%to_remember));
                   6078:     &scantron_putfile(undef,$scan_data);
                   6079: }
                   6080: 
1.423     albertel 6081: =pod
                   6082: 
                   6083: =item check_for_error
                   6084: 
1.424     albertel 6085:     Checks if there was an error when attempting to remove a specific
                   6086:     scantron_.. bubble sheet data file. Prints out an error if
                   6087:     something went wrong.
                   6088: 
1.423     albertel 6089: =cut
                   6090: 
1.200     albertel 6091: sub check_for_error {
                   6092:     my ($r,$result)=@_;
                   6093:     if ($result ne 'ok' && $result ne 'not_found' ) {
1.492     albertel 6094: 	$r->print(&mt("An error occurred ([_1]) when trying to remove the existing corrections.",$result));
1.200     albertel 6095:     }
                   6096: }
1.157     albertel 6097: 
1.423     albertel 6098: =pod
                   6099: 
                   6100: =item scantron_warning_screen
                   6101: 
1.424     albertel 6102:    Interstitial screen to make sure the operator has selected the
                   6103:    correct options before we start the validation phase.
                   6104: 
1.423     albertel 6105: =cut
                   6106: 
1.203     albertel 6107: sub scantron_warning_screen {
                   6108:     my ($button_text)=@_;
1.257     albertel 6109:     my $title=&Apache::lonnet::gettitle($env{'form.selectpage'});
1.284     albertel 6110:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.373     albertel 6111:     my $CODElist;
1.284     albertel 6112:     if ($scantron_config{'CODElocation'} &&
                   6113: 	$scantron_config{'CODEstart'} &&
                   6114: 	$scantron_config{'CODElength'}) {
                   6115: 	$CODElist=$env{'form.scantron_CODElist'};
1.398     albertel 6116: 	if ($env{'form.scantron_CODElist'} eq '') { $CODElist='<span class="LC_warning">None</span>'; }
1.284     albertel 6117: 	$CODElist=
1.492     albertel 6118: 	    '<tr><td><b>'.&mt('List of CODES to validate against:').'</b></td><td><tt>'.
1.373     albertel 6119: 	    $env{'form.scantron_CODElist'}.'</tt></td></tr>';
1.284     albertel 6120:     }
1.492     albertel 6121:     return ('
1.203     albertel 6122: <p>
1.492     albertel 6123: <span class="LC_warning">
                   6124: '.&mt('Please double check the information below before clicking on \'[_1]\'',&mt($button_text)).'</span>
1.203     albertel 6125: </p>
                   6126: <table>
1.492     albertel 6127: <tr><td><b>'.&mt('Sequence to be Graded:').'</b></td><td>'.$title.'</td></tr>
                   6128: <tr><td><b>'.&mt('Data File that will be used:').'</b></td><td><tt>'.$env{'form.scantron_selectfile'}.'</tt></td></tr>
                   6129: '.$CODElist.'
1.203     albertel 6130: </table>
                   6131: <br />
1.492     albertel 6132: <p> '.&mt('If this information is correct, please click on \'[_1]\'.',&mt($button_text)).'</p>
                   6133: <p> '.&mt('If something is incorrect, please click the \'Grading Menu\' button to start over.').'</p>
1.203     albertel 6134: 
                   6135: <br />
1.492     albertel 6136: ');
1.203     albertel 6137: }
                   6138: 
1.423     albertel 6139: =pod
                   6140: 
                   6141: =item scantron_do_warning
                   6142: 
1.424     albertel 6143:    Check if the operator has picked something for all required
                   6144:    fields. Error out if something is missing.
                   6145: 
1.423     albertel 6146: =cut
                   6147: 
1.203     albertel 6148: sub scantron_do_warning {
1.608     www      6149:     my ($r,$symb)=@_;
1.203     albertel 6150:     if (!$symb) {return '';}
1.324     albertel 6151:     my $default_form_data=&defaultFormData($symb);
1.203     albertel 6152:     $r->print(&scantron_form_start().$default_form_data);
1.257     albertel 6153:     if ( $env{'form.selectpage'} eq '' ||
                   6154: 	 $env{'form.scantron_selectfile'} eq '' ||
                   6155: 	 $env{'form.scantron_format'} eq '' ) {
1.492     albertel 6156: 	$r->print("<p>".&mt('You have forgetten to specify some information. Please go Back and try again.')."</p>");
1.257     albertel 6157: 	if ( $env{'form.selectpage'} eq '') {
1.492     albertel 6158: 	    $r->print('<p><span class="LC_error">'.&mt('You have not selected a Sequence to grade').'</span></p>');
1.237     albertel 6159: 	} 
1.257     albertel 6160: 	if ( $env{'form.scantron_selectfile'} eq '') {
1.492     albertel 6161: 	    $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 6162: 	} 
1.257     albertel 6163: 	if ( $env{'form.scantron_format'} eq '') {
1.492     albertel 6164: 	    $r->print('<p><span class="LC_error">'.&mt('You have not selected a the format of the student\'s response data.').'</span></p>');
1.237     albertel 6165: 	} 
                   6166:     } else {
1.265     www      6167: 	my $warning=&scantron_warning_screen('Grading: Validate Records');
1.492     albertel 6168: 	$r->print('
                   6169: '.$warning.'
                   6170: <input type="submit" name="submit" value="'.&mt('Grading: Validate Records').'" />
1.203     albertel 6171: <input type="hidden" name="command" value="scantron_validate" />
1.492     albertel 6172: ');
1.237     albertel 6173:     }
1.614     www      6174:     $r->print("</form><br />");
1.203     albertel 6175:     return '';
                   6176: }
                   6177: 
1.423     albertel 6178: =pod
                   6179: 
                   6180: =item scantron_form_start
                   6181: 
1.424     albertel 6182:     html hidden input for remembering all selected grading options
                   6183: 
1.423     albertel 6184: =cut
                   6185: 
1.203     albertel 6186: sub scantron_form_start {
                   6187:     my ($max_bubble)=@_;
                   6188:     my $result= <<SCANTRONFORM;
                   6189: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantronupload">
1.257     albertel 6190:   <input type="hidden" name="selectpage" value="$env{'form.selectpage'}" />
                   6191:   <input type="hidden" name="scantron_format" value="$env{'form.scantron_format'}" />
                   6192:   <input type="hidden" name="scantron_selectfile" value="$env{'form.scantron_selectfile'}" />
1.218     albertel 6193:   <input type="hidden" name="scantron_maxbubble" value="$max_bubble" />
1.257     albertel 6194:   <input type="hidden" name="scantron_CODElist" value="$env{'form.scantron_CODElist'}" />
                   6195:   <input type="hidden" name="scantron_CODEunique" value="$env{'form.scantron_CODEunique'}" />
                   6196:   <input type="hidden" name="scantron_options_redo" value="$env{'form.scantron_options_redo'}" />
                   6197:   <input type="hidden" name="scantron_options_ignore" value="$env{'form.scantron_options_ignore'}" />
1.331     albertel 6198:   <input type="hidden" name="scantron_options_hidden" value="$env{'form.scantron_options_hidden'}" />
1.203     albertel 6199: SCANTRONFORM
1.447     foxr     6200: 
                   6201:   my $line = 0;
                   6202:     while (defined($env{"form.scantron.bubblelines.$line"})) {
                   6203:        my $chunk =
                   6204: 	   '<input type="hidden" name="scantron.bubblelines.'.$line.'" value="'.$env{"form.scantron.bubblelines.$line"}.'" />'."\n";
1.448     foxr     6205:        $chunk .=
                   6206: 	   '<input type="hidden" name="scantron.first_bubble_line.'.$line.'" value="'.$env{"form.scantron.first_bubble_line.$line"}.'" />'."\n";
1.503     raeburn  6207:        $chunk .= 
                   6208:            '<input type="hidden" name="scantron.sub_bubblelines.'.$line.'" value="'.$env{"form.scantron.sub_bubblelines.$line"}.'" />'."\n";
1.504     raeburn  6209:        $chunk .=
                   6210:            '<input type="hidden" name="scantron.responsetype.'.$line.'" value="'.$env{"form.scantron.responsetype.$line"}.'" />'."\n";
1.447     foxr     6211:        $result .= $chunk;
                   6212:        $line++;
                   6213:    }
1.203     albertel 6214:     return $result;
                   6215: }
                   6216: 
1.423     albertel 6217: =pod
                   6218: 
                   6219: =item scantron_validate_file
                   6220: 
1.424     albertel 6221:     Dispatch routine for doing validation of a bubble sheet data file.
                   6222: 
                   6223:     Also processes any necessary information resets that need to
                   6224:     occur before validation begins (ignore previous corrections,
                   6225:     restarting the skipped records processing)
                   6226: 
1.423     albertel 6227: =cut
                   6228: 
1.157     albertel 6229: sub scantron_validate_file {
1.608     www      6230:     my ($r,$symb) = @_;
1.157     albertel 6231:     if (!$symb) {return '';}
1.324     albertel 6232:     my $default_form_data=&defaultFormData($symb);
1.200     albertel 6233:     
                   6234:     # do the detection of only doing skipped records first befroe we delete
1.424     albertel 6235:     # them when doing the corrections reset
1.257     albertel 6236:     if ($env{'form.scantron_options_redo'} ne 'redo_skipped_ready') {
1.200     albertel 6237: 	&reset_skipping_status();
                   6238:     }
1.257     albertel 6239:     if ($env{'form.scantron_options_redo'} eq 'redo_skipped') {
1.200     albertel 6240: 	&remember_current_skipped();
1.257     albertel 6241: 	$env{'form.scantron_options_redo'}='redo_skipped_ready';
1.200     albertel 6242:     }
                   6243: 
1.257     albertel 6244:     if ($env{'form.scantron_options_ignore'} eq 'ignore_corrections') {
1.200     albertel 6245: 	&check_for_error($r,&scantron_remove_file('corrected'));
                   6246: 	&check_for_error($r,&scantron_remove_file('skipped'));
                   6247: 	&check_for_error($r,&scantron_remove_scan_data());
1.257     albertel 6248: 	$env{'form.scantron_options_ignore'}='done';
1.192     albertel 6249:     }
1.200     albertel 6250: 
1.257     albertel 6251:     if ($env{'form.scantron_corrections'}) {
1.157     albertel 6252: 	&scantron_process_corrections($r);
                   6253:     }
1.503     raeburn  6254:     $r->print('<p>'.&mt('Gathering necessary information.').'</p>');$r->rflush();
1.157     albertel 6255:     #get the student pick code ready
                   6256:     $r->print(&Apache::loncommon::studentbrowser_javascript());
1.582     raeburn  6257:     my $nav_error;
                   6258:     my $max_bubble=&scantron_get_maxbubble(\$nav_error);
                   6259:     if ($nav_error) {
                   6260:         $r->print(&navmap_errormsg());
                   6261:         return '';
                   6262:     }
1.203     albertel 6263:     my $result=&scantron_form_start($max_bubble).$default_form_data;
1.157     albertel 6264:     $r->print($result);
                   6265:     
1.334     albertel 6266:     my @validate_phases=( 'sequence',
                   6267: 			  'ID',
1.157     albertel 6268: 			  'CODE',
                   6269: 			  'doublebubble',
                   6270: 			  'missingbubbles');
1.257     albertel 6271:     if (!$env{'form.validatepass'}) {
                   6272: 	$env{'form.validatepass'} = 0;
1.157     albertel 6273:     }
1.257     albertel 6274:     my $currentphase=$env{'form.validatepass'};
1.157     albertel 6275: 
1.448     foxr     6276: 
1.157     albertel 6277:     my $stop=0;
                   6278:     while (!$stop && $currentphase < scalar(@validate_phases)) {
1.503     raeburn  6279: 	$r->print(&mt('Validating '.$validate_phases[$currentphase]).'<br />');
1.157     albertel 6280: 	$r->rflush();
                   6281: 	my $which="scantron_validate_".$validate_phases[$currentphase];
                   6282: 	{
                   6283: 	    no strict 'refs';
                   6284: 	    ($stop,$currentphase)=&$which($r,$currentphase);
                   6285: 	}
                   6286:     }
                   6287:     if (!$stop) {
1.203     albertel 6288: 	my $warning=&scantron_warning_screen('Start Grading');
1.542     raeburn  6289: 	$r->print(&mt('Validation process complete.').'<br />'.
                   6290:                   $warning.
                   6291:                   &mt('Perform verification for each student after storage of submissions?').
                   6292:                   '&nbsp;<span class="LC_nobreak"><label>'.
                   6293:                   '<input type="radio" name="verifyrecord" value="1" />'.&mt('Yes').'</label>'.
                   6294:                   ('&nbsp;'x3).'<label>'.
                   6295:                   '<input type="radio" name="verifyrecord" value="0" checked="checked" />'.&mt('No').
                   6296:                   '</label></span><br />'.
                   6297:                   &mt('Grading will take longer if you use verification.').'<br />'.
1.572     www      6298:                   &mt("Alternatively, the 'Review bubblesheet data' utility (see grading menu) can be used for all students after grading is complete.").'<br /><br />'.
1.542     raeburn  6299:                   '<input type="submit" name="submit" value="'.&mt('Start Grading').'" />'.
                   6300:                   '<input type="hidden" name="command" value="scantron_process" />'."\n");
1.157     albertel 6301:     } else {
                   6302: 	$r->print('<input type="hidden" name="command" value="scantron_validate" />');
                   6303: 	$r->print("<input type='hidden' name='validatepass' value='".$currentphase."' />");
                   6304:     }
                   6305:     if ($stop) {
1.334     albertel 6306: 	if ($validate_phases[$currentphase] eq 'sequence') {
1.539     riegler  6307: 	    $r->print('<input type="submit" name="submit" value="'.&mt('Ignore').' &rarr; " />');
1.492     albertel 6308: 	    $r->print(' '.&mt('this error').' <br />');
1.334     albertel 6309: 
1.492     albertel 6310: 	    $r->print(" <p>".&mt("Or click the 'Grading Menu' button to start over.")."</p>");
1.334     albertel 6311: 	} else {
1.503     raeburn  6312:             if ($validate_phases[$currentphase] eq 'doublebubble' || $validate_phases[$currentphase] eq 'missingbubbles') {
1.539     riegler  6313: 	        $r->print('<input type="button" name="submitbutton" value="'.&mt('Continue').' &rarr;" onclick="javascript:verify_bubble_radio(this.form)" />');
1.503     raeburn  6314:             } else {
1.539     riegler  6315:                 $r->print('<input type="submit" name="submit" value="'.&mt('Continue').' &rarr;" />');
1.503     raeburn  6316:             }
1.492     albertel 6317: 	    $r->print(' '.&mt('using corrected info').' <br />');
                   6318: 	    $r->print("<input type='submit' value='".&mt("Skip")."' name='scantron_skip_record' />");
                   6319: 	    $r->print(" ".&mt("this scanline saving it for later."));
1.334     albertel 6320: 	}
1.157     albertel 6321:     }
1.614     www      6322:     $r->print(" </form><br />");
1.157     albertel 6323:     return '';
                   6324: }
                   6325: 
1.423     albertel 6326: 
                   6327: =pod
                   6328: 
                   6329: =item scantron_remove_file
                   6330: 
1.424     albertel 6331:    Removes the requested bubble sheet data file, makes sure that
                   6332:    scantron_original_<filename> is never removed
                   6333: 
                   6334: 
1.423     albertel 6335: =cut
                   6336: 
1.200     albertel 6337: sub scantron_remove_file {
1.192     albertel 6338:     my ($which)=@_;
1.257     albertel 6339:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   6340:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.192     albertel 6341:     my $file='scantron_';
1.200     albertel 6342:     if ($which eq 'corrected' || $which eq 'skipped') {
                   6343: 	$file.=$which.'_';
1.192     albertel 6344:     } else {
                   6345: 	return 'refused';
                   6346:     }
1.257     albertel 6347:     $file.=$env{'form.scantron_selectfile'};
1.200     albertel 6348:     return &Apache::lonnet::removeuserfile($cname,$cdom,$file);
                   6349: }
                   6350: 
1.423     albertel 6351: 
                   6352: =pod
                   6353: 
                   6354: =item scantron_remove_scan_data
                   6355: 
1.424     albertel 6356:    Removes all scan_data correction for the requested bubble sheet
                   6357:    data file.  (In the case that both the are doing skipped records we need
                   6358:    to remember the old skipped lines for the time being so that element
                   6359:    persists for a while.)
                   6360: 
1.423     albertel 6361: =cut
                   6362: 
1.200     albertel 6363: sub scantron_remove_scan_data {
1.257     albertel 6364:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   6365:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.192     albertel 6366:     my @keys=&Apache::lonnet::getkeys('nohist_scantrondata',$cdom,$cname);
                   6367:     my @todelete;
1.257     albertel 6368:     my $filename=$env{'form.scantron_selectfile'};
1.192     albertel 6369:     foreach my $key (@keys) {
                   6370: 	if ($key=~/^\Q$filename\E_/) {
1.257     albertel 6371: 	    if ($env{'form.scantron_options_redo'} eq 'redo_skipped_ready' &&
1.200     albertel 6372: 		$key=~/remember_skipping/) {
                   6373: 		next;
                   6374: 	    }
1.192     albertel 6375: 	    push(@todelete,$key);
                   6376: 	}
                   6377:     }
1.200     albertel 6378:     my $result;
1.192     albertel 6379:     if (@todelete) {
1.491     albertel 6380: 	$result = &Apache::lonnet::del('nohist_scantrondata',
                   6381: 				       \@todelete,$cdom,$cname);
                   6382:     } else {
                   6383: 	$result = 'ok';
1.192     albertel 6384:     }
                   6385:     return $result;
                   6386: }
                   6387: 
1.423     albertel 6388: 
                   6389: =pod
                   6390: 
                   6391: =item scantron_getfile
                   6392: 
1.424     albertel 6393:     Fetches the requested bubble sheet data file (all 3 versions), and
                   6394:     the scan_data hash
                   6395:   
                   6396:   Arguments:
                   6397:     None
                   6398: 
                   6399:   Returns:
                   6400:     2 hash references
                   6401: 
                   6402:      - first one has 
                   6403:          orig      -
                   6404:          corrected -
                   6405:          skipped   -  each of which points to an array ref of the specified
                   6406:                       file broken up into individual lines
                   6407:          count     - number of scanlines
                   6408:  
                   6409:      - second is the scan_data hash possible keys are
1.425     albertel 6410:        ($number refers to scanline numbered $number and thus the key affects
                   6411:         only that scanline
                   6412:         $bubline refers to the specific bubble line element and the aspects
                   6413:         refers to that specific bubble line element)
                   6414: 
                   6415:        $number.user - username:domain to use
                   6416:        $number.CODE_ignore_dup 
                   6417:                     - ignore the duplicate CODE error 
                   6418:        $number.useCODE
                   6419:                     - use the CODE in the scanline as is
                   6420:        $number.no_bubble.$bubline
                   6421:                     - it is valid that there is no bubbled in bubble
                   6422:                       at $number $bubline
                   6423:        remember_skipping
                   6424:                     - a frozen hash containing keys of $number and values
                   6425:                       of either 
                   6426:                         1 - we are on a 'do skipped records pass' and plan
                   6427:                             on processing this line
                   6428:                         2 - we are on a 'do skipped records pass' and this
                   6429:                             scanline has been marked to skip yet again
1.424     albertel 6430: 
1.423     albertel 6431: =cut
                   6432: 
1.157     albertel 6433: sub scantron_getfile {
1.200     albertel 6434:     #FIXME really would prefer a scantron directory
1.257     albertel 6435:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   6436:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.157     albertel 6437:     my $lines;
                   6438:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
1.257     albertel 6439: 		       'scantron_orig_'.$env{'form.scantron_selectfile'});
1.157     albertel 6440:     my %scanlines;
                   6441:     $scanlines{'orig'}=[(split("\n",$lines,-1))];
                   6442:     my $temp=$scanlines{'orig'};
                   6443:     $scanlines{'count'}=$#$temp;
                   6444: 
                   6445:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
1.257     albertel 6446: 		       'scantron_corrected_'.$env{'form.scantron_selectfile'});
1.157     albertel 6447:     if ($lines eq '-1') {
                   6448: 	$scanlines{'corrected'}=[];
                   6449:     } else {
                   6450: 	$scanlines{'corrected'}=[(split("\n",$lines,-1))];
                   6451:     }
                   6452:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
1.257     albertel 6453: 		       'scantron_skipped_'.$env{'form.scantron_selectfile'});
1.157     albertel 6454:     if ($lines eq '-1') {
                   6455: 	$scanlines{'skipped'}=[];
                   6456:     } else {
                   6457: 	$scanlines{'skipped'}=[(split("\n",$lines,-1))];
                   6458:     }
1.175     albertel 6459:     my @tmp=&Apache::lonnet::dump('nohist_scantrondata',$cdom,$cname);
1.157     albertel 6460:     if ($tmp[0] =~ /^(error:|no_such_host)/) { @tmp=(); }
                   6461:     my %scan_data = @tmp;
                   6462:     return (\%scanlines,\%scan_data);
                   6463: }
                   6464: 
1.423     albertel 6465: =pod
                   6466: 
                   6467: =item lonnet_putfile
                   6468: 
1.424     albertel 6469:    Wrapper routine to call &Apache::lonnet::finishuserfileupload
                   6470: 
                   6471:  Arguments:
                   6472:    $contents - data to store
                   6473:    $filename - filename to store $contents into
                   6474: 
                   6475:  Returns:
                   6476:    result value from &Apache::lonnet::finishuserfileupload
                   6477: 
1.423     albertel 6478: =cut
                   6479: 
1.157     albertel 6480: sub lonnet_putfile {
                   6481:     my ($contents,$filename)=@_;
1.257     albertel 6482:     my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   6483:     my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   6484:     $env{'form.sillywaytopassafilearound'}=$contents;
1.275     albertel 6485:     &Apache::lonnet::finishuserfileupload($docuname,$docudom,'sillywaytopassafilearound',$filename);
1.157     albertel 6486: 
                   6487: }
                   6488: 
1.423     albertel 6489: =pod
                   6490: 
                   6491: =item scantron_putfile
                   6492: 
1.424     albertel 6493:     Stores the current version of the bubble sheet data files, and the
                   6494:     scan_data hash. (Does not modify the original version only the
                   6495:     corrected and skipped versions.
                   6496: 
                   6497:  Arguments:
                   6498:     $scanlines - hash ref that looks like the first return value from
                   6499:                  &scantron_getfile()
                   6500:     $scan_data - hash ref that looks like the second return value from
                   6501:                  &scantron_getfile()
                   6502: 
1.423     albertel 6503: =cut
                   6504: 
1.157     albertel 6505: sub scantron_putfile {
                   6506:     my ($scanlines,$scan_data) = @_;
1.200     albertel 6507:     #FIXME really would prefer a scantron directory
1.257     albertel 6508:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   6509:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.200     albertel 6510:     if ($scanlines) {
                   6511: 	my $prefix='scantron_';
1.157     albertel 6512: # no need to update orig, shouldn't change
                   6513: #   &lonnet_putfile(join("\n",@{$scanlines->{'orig'}}),$prefix.'orig_'.
1.257     albertel 6514: #		    $env{'form.scantron_selectfile'});
1.200     albertel 6515: 	&lonnet_putfile(join("\n",@{$scanlines->{'corrected'}}),
                   6516: 			$prefix.'corrected_'.
1.257     albertel 6517: 			$env{'form.scantron_selectfile'});
1.200     albertel 6518: 	&lonnet_putfile(join("\n",@{$scanlines->{'skipped'}}),
                   6519: 			$prefix.'skipped_'.
1.257     albertel 6520: 			$env{'form.scantron_selectfile'});
1.200     albertel 6521:     }
1.175     albertel 6522:     &Apache::lonnet::put('nohist_scantrondata',$scan_data,$cdom,$cname);
1.157     albertel 6523: }
                   6524: 
1.423     albertel 6525: =pod
                   6526: 
                   6527: =item scantron_get_line
                   6528: 
1.424     albertel 6529:    Returns the correct version of the scanline
                   6530: 
                   6531:  Arguments:
                   6532:     $scanlines - hash ref that looks like the first return value from
                   6533:                  &scantron_getfile()
                   6534:     $scan_data - hash ref that looks like the second return value from
                   6535:                  &scantron_getfile()
                   6536:     $i         - number of the requested line (starts at 0)
                   6537: 
                   6538:  Returns:
                   6539:    A scanline, (either the original or the corrected one if it
                   6540:    exists), or undef if the requested scanline should be
                   6541:    skipped. (Either because it's an skipped scanline, or it's an
                   6542:    unskipped scanline and we are not doing a 'do skipped scanlines'
                   6543:    pass.
                   6544: 
1.423     albertel 6545: =cut
                   6546: 
1.157     albertel 6547: sub scantron_get_line {
1.200     albertel 6548:     my ($scanlines,$scan_data,$i)=@_;
1.376     albertel 6549:     if (&should_be_skipped($scanlines,$scan_data,$i)) { return undef; }
                   6550:     #if ($scanlines->{'skipped'}[$i]) { return undef; }
1.157     albertel 6551:     if ($scanlines->{'corrected'}[$i]) {return $scanlines->{'corrected'}[$i];}
                   6552:     return $scanlines->{'orig'}[$i]; 
                   6553: }
                   6554: 
1.423     albertel 6555: =pod
                   6556: 
                   6557: =item scantron_todo_count
                   6558: 
1.424     albertel 6559:     Counts the number of scanlines that need processing.
                   6560: 
                   6561:  Arguments:
                   6562:     $scanlines - hash ref that looks like the first return value from
                   6563:                  &scantron_getfile()
                   6564:     $scan_data - hash ref that looks like the second return value from
                   6565:                  &scantron_getfile()
                   6566: 
                   6567:  Returns:
                   6568:     $count - number of scanlines to process
                   6569: 
1.423     albertel 6570: =cut
                   6571: 
1.200     albertel 6572: sub get_todo_count {
                   6573:     my ($scanlines,$scan_data)=@_;
                   6574:     my $count=0;
                   6575:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
                   6576: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
                   6577: 	if ($line=~/^[\s\cz]*$/) { next; }
                   6578: 	$count++;
                   6579:     }
                   6580:     return $count;
                   6581: }
                   6582: 
1.423     albertel 6583: =pod
                   6584: 
                   6585: =item scantron_put_line
                   6586: 
1.424     albertel 6587:     Updates the 'corrected' or 'skipped' versions of the bubble sheet
                   6588:     data file.
                   6589: 
                   6590:  Arguments:
                   6591:     $scanlines - hash ref that looks like the first return value from
                   6592:                  &scantron_getfile()
                   6593:     $scan_data - hash ref that looks like the second return value from
                   6594:                  &scantron_getfile()
                   6595:     $i         - line number to update
                   6596:     $newline   - contents of the updated scanline
                   6597:     $skip      - if true make the line for skipping and update the
                   6598:                  'skipped' file
                   6599: 
1.423     albertel 6600: =cut
                   6601: 
1.157     albertel 6602: sub scantron_put_line {
1.200     albertel 6603:     my ($scanlines,$scan_data,$i,$newline,$skip)=@_;
1.157     albertel 6604:     if ($skip) {
                   6605: 	$scanlines->{'skipped'}[$i]=$newline;
1.376     albertel 6606: 	&start_skipping($scan_data,$i);
1.157     albertel 6607: 	return;
                   6608:     }
                   6609:     $scanlines->{'corrected'}[$i]=$newline;
                   6610: }
                   6611: 
1.423     albertel 6612: =pod
                   6613: 
                   6614: =item scantron_clear_skip
                   6615: 
1.424     albertel 6616:    Remove a line from the 'skipped' file
                   6617: 
                   6618:  Arguments:
                   6619:     $scanlines - hash ref that looks like the first return value from
                   6620:                  &scantron_getfile()
                   6621:     $scan_data - hash ref that looks like the second return value from
                   6622:                  &scantron_getfile()
                   6623:     $i         - line number to update
                   6624: 
1.423     albertel 6625: =cut
                   6626: 
1.376     albertel 6627: sub scantron_clear_skip {
                   6628:     my ($scanlines,$scan_data,$i)=@_;
                   6629:     if (exists($scanlines->{'skipped'}[$i])) {
                   6630: 	undef($scanlines->{'skipped'}[$i]);
                   6631: 	return 1;
                   6632:     }
                   6633:     return 0;
                   6634: }
                   6635: 
1.423     albertel 6636: =pod
                   6637: 
                   6638: =item scantron_filter_not_exam
                   6639: 
1.424     albertel 6640:    Filter routine used by &Apache::lonnavmaps::retrieveResources(), to
                   6641:    filter out resources that are not marked as 'exam' mode
                   6642: 
1.423     albertel 6643: =cut
                   6644: 
1.334     albertel 6645: sub scantron_filter_not_exam {
                   6646:     my ($curres)=@_;
                   6647:     
                   6648:     if (ref($curres) && $curres->is_problem() && !$curres->is_exam()) {
                   6649: 	# if the user has asked to not have either hidden
                   6650: 	# or 'randomout' controlled resources to be graded
                   6651: 	# don't include them
                   6652: 	if ($env{'form.scantron_options_hidden'} eq 'ignore_hidden'
                   6653: 	    && $curres->randomout) {
                   6654: 	    return 0;
                   6655: 	}
                   6656: 	return 1;
                   6657:     }
                   6658:     return 0;
                   6659: }
                   6660: 
1.423     albertel 6661: =pod
                   6662: 
                   6663: =item scantron_validate_sequence
                   6664: 
1.424     albertel 6665:     Validates the selected sequence, checking for resource that are
                   6666:     not set to exam mode.
                   6667: 
1.423     albertel 6668: =cut
                   6669: 
1.334     albertel 6670: sub scantron_validate_sequence {
                   6671:     my ($r,$currentphase) = @_;
                   6672: 
                   6673:     my $navmap=Apache::lonnavmaps::navmap->new();
1.582     raeburn  6674:     unless (ref($navmap)) {
                   6675:         $r->print(&navmap_errormsg());
                   6676:         return (1,$currentphase);
                   6677:     }
1.334     albertel 6678:     my (undef,undef,$sequence)=
                   6679: 	&Apache::lonnet::decode_symb($env{'form.selectpage'});
                   6680: 
                   6681:     my $map=$navmap->getResourceByUrl($sequence);
                   6682: 
                   6683:     $r->print('<input type="hidden" name="validate_sequence_exam"
                   6684:                                     value="ignore" />');
                   6685:     if ($env{'form.validate_sequence_exam'} ne 'ignore') {
                   6686: 	my @resources=
                   6687: 	    $navmap->retrieveResources($map,\&scantron_filter_not_exam,1,0);
                   6688: 	if (@resources) {
1.357     banghart 6689: 	    $r->print("<p>".&mt('Some resources in the sequence currently are not set to exam mode. Grading these resources currently may not work correctly.')."</p>");
1.334     albertel 6690: 	    return (1,$currentphase);
                   6691: 	}
                   6692:     }
                   6693: 
                   6694:     return (0,$currentphase+1);
                   6695: }
                   6696: 
1.423     albertel 6697: 
                   6698: 
1.157     albertel 6699: sub scantron_validate_ID {
                   6700:     my ($r,$currentphase) = @_;
                   6701:     
                   6702:     #get student info
                   6703:     my $classlist=&Apache::loncoursedata::get_classlist();
                   6704:     my %idmap=&username_to_idmap($classlist);
                   6705: 
                   6706:     #get scantron line setup
1.257     albertel 6707:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.157     albertel 6708:     my ($scanlines,$scan_data)=&scantron_getfile();
1.582     raeburn  6709: 
                   6710:     my $nav_error;
                   6711:     &scantron_get_maxbubble(\$nav_error); # parse needs the bubble_lines.. array.
                   6712:     if ($nav_error) {
                   6713:         $r->print(&navmap_errormsg());
                   6714:         return(1,$currentphase);
                   6715:     }
1.157     albertel 6716: 
                   6717:     my %found=('ids'=>{},'usernames'=>{});
                   6718:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
1.200     albertel 6719: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.157     albertel 6720: 	if ($line=~/^[\s\cz]*$/) { next; }
                   6721: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
                   6722: 						 $scan_data);
                   6723: 	my $id=$$scan_record{'scantron.ID'};
                   6724: 	my $found;
                   6725: 	foreach my $checkid (keys(%idmap)) {
                   6726: 	    if (lc($checkid) eq lc($id)) { $found=$checkid;last; }
                   6727: 	}
                   6728: 	if ($found) {
                   6729: 	    my $username=$idmap{$found};
                   6730: 	    if ($found{'ids'}{$found}) {
                   6731: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
                   6732: 					 $line,'duplicateID',$found);
1.194     albertel 6733: 		return(1,$currentphase);
1.157     albertel 6734: 	    } elsif ($found{'usernames'}{$username}) {
                   6735: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
                   6736: 					 $line,'duplicateID',$username);
1.194     albertel 6737: 		return(1,$currentphase);
1.157     albertel 6738: 	    }
1.186     albertel 6739: 	    #FIXME store away line we previously saw the ID on to use above
1.157     albertel 6740: 	    $found{'ids'}{$found}++;
                   6741: 	    $found{'usernames'}{$username}++;
                   6742: 	} else {
                   6743: 	    if ($id =~ /^\s*$/) {
1.158     albertel 6744: 		my $username=&scan_data($scan_data,"$i.user");
1.157     albertel 6745: 		if (defined($username) && $found{'usernames'}{$username}) {
                   6746: 		    &scantron_get_correction($r,$i,$scan_record,
                   6747: 					     \%scantron_config,
                   6748: 					     $line,'duplicateID',$username);
1.194     albertel 6749: 		    return(1,$currentphase);
1.157     albertel 6750: 		} elsif (!defined($username)) {
                   6751: 		    &scantron_get_correction($r,$i,$scan_record,
                   6752: 					     \%scantron_config,
                   6753: 					     $line,'incorrectID');
1.194     albertel 6754: 		    return(1,$currentphase);
1.157     albertel 6755: 		}
                   6756: 		$found{'usernames'}{$username}++;
                   6757: 	    } else {
                   6758: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
                   6759: 					 $line,'incorrectID');
1.194     albertel 6760: 		return(1,$currentphase);
1.157     albertel 6761: 	    }
                   6762: 	}
                   6763:     }
                   6764: 
                   6765:     return (0,$currentphase+1);
                   6766: }
                   6767: 
1.423     albertel 6768: 
1.157     albertel 6769: sub scantron_get_correction {
                   6770:     my ($r,$i,$scan_record,$scan_config,$line,$error,$arg)=@_;
1.454     banghart 6771: #FIXME in the case of a duplicated ID the previous line, probably need
1.157     albertel 6772: #to show both the current line and the previous one and allow skipping
                   6773: #the previous one or the current one
                   6774: 
1.333     albertel 6775:     if ( $$scan_record{'scantron.PaperID'} =~ /\S/) {
1.492     albertel 6776: 	$r->print("<p>".&mt("<b>An error was detected ($error)</b>".
                   6777: 			    " for PaperID <tt>[_1]</tt>",
                   6778: 			    $$scan_record{'scantron.PaperID'})."</p> \n");
1.157     albertel 6779:     } else {
1.492     albertel 6780: 	$r->print("<p>".&mt("<b>An error was detected ($error)</b>".
                   6781: 			    " in scanline [_1] <pre>[_2]</pre>",
                   6782: 			    $i,$line)."</p> \n");
                   6783:     }
                   6784:     my $message="<p>".&mt("The ID on the form is  <tt>[_1]</tt><br />".
                   6785: 			  "The name on the paper is [_2],[_3]",
                   6786: 			  $$scan_record{'scantron.ID'},
                   6787: 			  $$scan_record{'scantron.LastName'},
                   6788: 			  $$scan_record{'scantron.FirstName'})."</p>";
1.242     albertel 6789: 
1.157     albertel 6790:     $r->print('<input type="hidden" name="scantron_corrections" value="'.$error.'" />'."\n");
                   6791:     $r->print('<input type="hidden" name="scantron_line" value="'.$i.'" />'."\n");
1.503     raeburn  6792:                            # Array populated for doublebubble or
                   6793:     my @lines_to_correct;  # missingbubble errors to build javascript
                   6794:                            # to validate radio button checking   
                   6795: 
1.157     albertel 6796:     if ($error =~ /ID$/) {
1.186     albertel 6797: 	if ($error eq 'incorrectID') {
1.492     albertel 6798: 	    $r->print("<p>".&mt("The encoded ID is not in the classlist").
                   6799: 		      "</p>\n");
1.157     albertel 6800: 	} elsif ($error eq 'duplicateID') {
1.492     albertel 6801: 	    $r->print("<p>".&mt("The encoded ID has also been used by a previous paper [_1]",$arg)."</p>\n");
1.157     albertel 6802: 	}
1.242     albertel 6803: 	$r->print($message);
1.492     albertel 6804: 	$r->print("<p>".&mt("How should I handle this?")." <br /> \n");
1.157     albertel 6805: 	$r->print("\n<ul><li> ");
                   6806: 	#FIXME it would be nice if this sent back the user ID and
                   6807: 	#could do partial userID matches
                   6808: 	$r->print(&Apache::loncommon::selectstudent_link('scantronupload',
                   6809: 				       'scantron_username','scantron_domain'));
                   6810: 	$r->print(": <input type='text' name='scantron_username' value='' />");
                   6811: 	$r->print("\n@".
1.257     albertel 6812: 		 &Apache::loncommon::select_dom_form($env{'request.role.domain'},'scantron_domain'));
1.157     albertel 6813: 
                   6814: 	$r->print('</li>');
1.186     albertel 6815:     } elsif ($error =~ /CODE$/) {
                   6816: 	if ($error eq 'incorrectCODE') {
1.492     albertel 6817: 	    $r->print("<p>".&mt("The encoded CODE is not in the list of possible CODEs.")."</p>\n");
1.186     albertel 6818: 	} elsif ($error eq 'duplicateCODE') {
1.492     albertel 6819: 	    $r->print("<p>".&mt("The encoded CODE has also been used by a previous paper [_1], and CODEs are supposed to be unique.",join(', ',@{$arg}))."</p>\n");
1.186     albertel 6820: 	}
1.492     albertel 6821: 	$r->print("<p>".&mt("The CODE on the form is  <tt>'[_1]'</tt>",
                   6822: 			    $$scan_record{'scantron.CODE'})."<br />\n");
1.242     albertel 6823: 	$r->print($message);
1.492     albertel 6824: 	$r->print("<p>".&mt("How should I handle this?")." <br /> \n");
1.187     albertel 6825: 	$r->print("\n<br /> ");
1.194     albertel 6826: 	my $i=0;
1.273     albertel 6827: 	if ($error eq 'incorrectCODE' 
                   6828: 	    && $$scan_record{'scantron.CODE'}=~/\S/ ) {
1.194     albertel 6829: 	    my ($max,$closest)=&scantron_get_closely_matching_CODEs($arg,$$scan_record{'scantron.CODE'});
1.278     albertel 6830: 	    if ($closest > 0) {
                   6831: 		foreach my $testcode (@{$closest}) {
                   6832: 		    my $checked='';
1.569     bisitz   6833: 		    if (!$i) { $checked=' checked="checked"'; }
1.492     albertel 6834: 		    $r->print("
                   6835:    <label>
1.569     bisitz   6836:        <input type='radio' name='scantron_CODE_resolution' value='use_closest_$i'$checked />
1.492     albertel 6837:        ".&mt("Use the similar CODE [_1] instead.",
                   6838: 	    "<b><tt>".$testcode."</tt></b>")."
                   6839:     </label>
                   6840:     <input type='hidden' name='scantron_CODE_closest_$i' value='$testcode' />");
1.278     albertel 6841: 		    $r->print("\n<br />");
                   6842: 		    $i++;
                   6843: 		}
1.194     albertel 6844: 	    }
                   6845: 	}
1.273     albertel 6846: 	if ($$scan_record{'scantron.CODE'}=~/\S/ ) {
1.569     bisitz   6847: 	    my $checked; if (!$i) { $checked=' checked="checked"'; }
1.492     albertel 6848: 	    $r->print("
                   6849:     <label>
1.569     bisitz   6850:         <input type='radio' name='scantron_CODE_resolution' value='use_unfound'$checked />
1.492     albertel 6851:        ".&mt("Use the CODE [_1] that is was on the paper, ignoring the error.",
                   6852: 	     "<b><tt>".$$scan_record{'scantron.CODE'}."</tt></b>")."
                   6853:     </label>");
1.273     albertel 6854: 	    $r->print("\n<br />");
                   6855: 	}
1.194     albertel 6856: 
1.597     wenzelju 6857: 	$r->print(&Apache::lonhtmlcommon::scripttag(<<ENDSCRIPT));
1.188     albertel 6858: function change_radio(field) {
1.190     albertel 6859:     var slct=document.scantronupload.scantron_CODE_resolution;
1.188     albertel 6860:     var i;
                   6861:     for (i=0;i<slct.length;i++) {
                   6862:         if (slct[i].value==field) { slct[i].checked=true; }
                   6863:     }
                   6864: }
                   6865: ENDSCRIPT
1.187     albertel 6866: 	my $href="/adm/pickcode?".
1.359     www      6867: 	   "form=".&escape("scantronupload").
                   6868: 	   "&scantron_format=".&escape($env{'form.scantron_format'}).
                   6869: 	   "&scantron_CODElist=".&escape($env{'form.scantron_CODElist'}).
                   6870: 	   "&curCODE=".&escape($$scan_record{'scantron.CODE'}).
                   6871: 	   "&scantron_selectfile=".&escape($env{'form.scantron_selectfile'});
1.332     albertel 6872: 	if ($env{'form.scantron_CODElist'} =~ /\S/) { 
1.492     albertel 6873: 	    $r->print("
                   6874:     <label>
                   6875:        <input type='radio' name='scantron_CODE_resolution' value='use_found' />
                   6876:        ".&mt("[_1]Select[_2] a CODE from the list of all CODEs and use it.",
                   6877: 	     "<a target='_blank' href='$href'>","</a>")."
                   6878:     </label> 
1.558     bisitz   6879:     ".&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 6880: 	    $r->print("\n<br />");
                   6881: 	}
1.492     albertel 6882: 	$r->print("
                   6883:     <label>
                   6884:        <input type='radio' name='scantron_CODE_resolution' value='use_typed' />
                   6885:        ".&mt("Use [_1] as the CODE.",
                   6886: 	     "</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 6887: 	$r->print("\n<br /><br />");
1.157     albertel 6888:     } elsif ($error eq 'doublebubble') {
1.503     raeburn  6889: 	$r->print("<p>".&mt("There have been multiple bubbles scanned for some question(s)")."</p>\n");
1.497     foxr     6890: 
                   6891: 	# The form field scantron_questions is acutally a list of line numbers.
                   6892: 	# represented by this form so:
                   6893: 
                   6894: 	my $line_list = &questions_to_line_list($arg);
                   6895: 
1.157     albertel 6896: 	$r->print('<input type="hidden" name="scantron_questions" value="'.
1.497     foxr     6897: 		  $line_list.'" />');
1.242     albertel 6898: 	$r->print($message);
1.492     albertel 6899: 	$r->print("<p>".&mt("Please indicate which bubble should be used for grading")."</p>");
1.157     albertel 6900: 	foreach my $question (@{$arg}) {
1.503     raeburn  6901: 	    my @linenums = &prompt_for_corrections($r,$question,$scan_config,
                   6902:                                                    $scan_record, $error);
1.524     raeburn  6903:             push(@lines_to_correct,@linenums);
1.157     albertel 6904: 	}
1.503     raeburn  6905:         $r->print(&verify_bubbles_checked(@lines_to_correct));
1.157     albertel 6906:     } elsif ($error eq 'missingbubble') {
1.492     albertel 6907: 	$r->print("<p>".&mt("There have been <b>no</b> bubbles scanned for some question(s)")."</p>\n");
1.242     albertel 6908: 	$r->print($message);
1.492     albertel 6909: 	$r->print("<p>".&mt("Please indicate which bubble should be used for grading.")."</p>");
1.503     raeburn  6910: 	$r->print(&mt("Some questions have no scanned bubbles.")."\n");
1.497     foxr     6911: 
1.503     raeburn  6912: 	# The form field scantron_questions is actually a list of line numbers not
1.497     foxr     6913: 	# a list of question numbers. Therefore:
                   6914: 	#
                   6915: 	
                   6916: 	my $line_list = &questions_to_line_list($arg);
                   6917: 
1.157     albertel 6918: 	$r->print('<input type="hidden" name="scantron_questions" value="'.
1.497     foxr     6919: 		  $line_list.'" />');
1.157     albertel 6920: 	foreach my $question (@{$arg}) {
1.503     raeburn  6921: 	    my @linenums = &prompt_for_corrections($r,$question,$scan_config,
                   6922:                                                    $scan_record, $error);
1.524     raeburn  6923:             push(@lines_to_correct,@linenums);
1.157     albertel 6924: 	}
1.503     raeburn  6925:         $r->print(&verify_bubbles_checked(@lines_to_correct));
1.157     albertel 6926:     } else {
                   6927: 	$r->print("\n<ul>");
                   6928:     }
                   6929:     $r->print("\n</li></ul>");
1.497     foxr     6930: }
                   6931: 
1.503     raeburn  6932: sub verify_bubbles_checked {
                   6933:     my (@ansnums) = @_;
                   6934:     my $ansnumstr = join('","',@ansnums);
                   6935:     my $warning = &mt("A bubble or 'No bubble' selection has not been made for one or more lines.");
1.597     wenzelju 6936:     my $output = &Apache::lonhtmlcommon::scripttag((<<ENDSCRIPT));
1.503     raeburn  6937: function verify_bubble_radio(form) {
                   6938:     var ansnumArray = new Array ("$ansnumstr");
                   6939:     var need_bubble_count = 0;
                   6940:     for (var i=0; i<ansnumArray.length; i++) {
                   6941:         if (form.elements["scantron_correct_Q_"+ansnumArray[i]].length > 1) {
                   6942:             var bubble_picked = 0; 
                   6943:             for (var j=0; j<form.elements["scantron_correct_Q_"+ansnumArray[i]].length; j++) {
                   6944:                 if (form.elements["scantron_correct_Q_"+ansnumArray[i]][j].checked == true) {
                   6945:                     bubble_picked = 1;
                   6946:                 }
                   6947:             }
                   6948:             if (bubble_picked == 0) {
                   6949:                 need_bubble_count ++;
                   6950:             }
                   6951:         }
                   6952:     }
                   6953:     if (need_bubble_count) {
                   6954:         alert("$warning");
                   6955:         return;
                   6956:     }
                   6957:     form.submit(); 
                   6958: }
                   6959: ENDSCRIPT
                   6960:     return $output;
                   6961: }
                   6962: 
1.497     foxr     6963: =pod
                   6964: 
                   6965: =item  questions_to_line_list
1.157     albertel 6966: 
1.497     foxr     6967: Converts a list of questions into a string of comma separated
                   6968: line numbers in the answer sheet used by the questions.  This is
                   6969: used to fill in the scantron_questions form field.
                   6970: 
                   6971:   Arguments:
                   6972:      questions    - Reference to an array of questions.
                   6973: 
                   6974: =cut
                   6975: 
                   6976: 
                   6977: sub questions_to_line_list {
                   6978:     my ($questions) = @_;
                   6979:     my @lines;
                   6980: 
1.503     raeburn  6981:     foreach my $item (@{$questions}) {
                   6982:         my $question = $item;
                   6983:         my ($first,$count,$last);
                   6984:         if ($item =~ /^(\d+)\.(\d+)$/) {
                   6985:             $question = $1;
                   6986:             my $subquestion = $2;
                   6987:             $first = $first_bubble_line{$question-1} + 1;
                   6988:             my @subans = split(/,/,$subdivided_bubble_lines{$question-1});
                   6989:             my $subcount = 1;
                   6990:             while ($subcount<$subquestion) {
                   6991:                 $first += $subans[$subcount-1];
                   6992:                 $subcount ++;
                   6993:             }
                   6994:             $count = $subans[$subquestion-1];
                   6995:         } else {
                   6996: 	    $first   = $first_bubble_line{$question-1} + 1;
                   6997: 	    $count   = $bubble_lines_per_response{$question-1};
                   6998:         }
1.506     raeburn  6999:         $last = $first+$count-1;
1.503     raeburn  7000:         push(@lines, ($first..$last));
1.497     foxr     7001:     }
                   7002:     return join(',', @lines);
                   7003: }
                   7004: 
                   7005: =pod 
                   7006: 
                   7007: =item prompt_for_corrections
                   7008: 
                   7009: Prompts for a potentially multiline correction to the
                   7010: user's bubbling (factors out common code from scantron_get_correction
                   7011: for multi and missing bubble cases).
                   7012: 
                   7013:  Arguments:
                   7014:    $r           - Apache request object.
                   7015:    $question    - The question number to prompt for.
                   7016:    $scan_config - The scantron file configuration hash.
                   7017:    $scan_record - Reference to the hash that has the the parsed scanlines.
1.503     raeburn  7018:    $error       - Type of error
1.497     foxr     7019: 
                   7020:  Implicit inputs:
                   7021:    %bubble_lines_per_response   - Starting line numbers for each question.
                   7022:                                   Numbered from 0 (but question numbers are from
                   7023:                                   1.
                   7024:    %first_bubble_line           - Starting bubble line for each question.
1.509     raeburn  7025:    %subdivided_bubble_lines     - optionresponse, matchresponse and rankresponse 
                   7026:                                   type problems render as separate sub-questions, 
1.503     raeburn  7027:                                   in exam mode. This hash contains a 
                   7028:                                   comma-separated list of the lines per 
                   7029:                                   sub-question.
1.510     raeburn  7030:    %responsetype_per_response   - essayresponse, formularesponse,
                   7031:                                   stringresponse, imageresponse, reactionresponse,
                   7032:                                   and organicresponse type problem parts can have
1.503     raeburn  7033:                                   multiple lines per response if the weight
                   7034:                                   assigned exceeds 10.  In this case, only
                   7035:                                   one bubble per line is permitted, but more 
                   7036:                                   than one line might contain bubbles, e.g.
                   7037:                                   bubbling of: line 1 - J, line 2 - J, 
                   7038:                                   line 3 - B would assign 22 points.  
1.497     foxr     7039: 
                   7040: =cut
                   7041: 
                   7042: sub prompt_for_corrections {
1.503     raeburn  7043:     my ($r, $question, $scan_config, $scan_record, $error) = @_;
                   7044:     my ($current_line,$lines);
                   7045:     my @linenums;
                   7046:     my $questionnum = $question;
                   7047:     if ($question =~ /^(\d+)\.(\d+)$/) {
                   7048:         $question = $1;
                   7049:         $current_line = $first_bubble_line{$question-1} + 1 ;
                   7050:         my $subquestion = $2;
                   7051:         my @subans = split(/,/,$subdivided_bubble_lines{$question-1});
                   7052:         my $subcount = 1;
                   7053:         while ($subcount<$subquestion) {
                   7054:             $current_line += $subans[$subcount-1];
                   7055:             $subcount ++;
                   7056:         }
                   7057:         $lines = $subans[$subquestion-1];
                   7058:     } else {
                   7059:         $current_line = $first_bubble_line{$question-1} + 1 ;
                   7060:         $lines        = $bubble_lines_per_response{$question-1};
                   7061:     }
1.497     foxr     7062:     if ($lines > 1) {
1.503     raeburn  7063:         $r->print(&mt('The group of bubble lines below responds to a single question.').'<br />');
                   7064:         if (($responsetype_per_response{$question-1} eq 'essayresponse') ||
                   7065:             ($responsetype_per_response{$question-1} eq 'formularesponse') ||
1.510     raeburn  7066:             ($responsetype_per_response{$question-1} eq 'stringresponse') ||
                   7067:             ($responsetype_per_response{$question-1} eq 'imageresponse') ||
                   7068:             ($responsetype_per_response{$question-1} eq 'reactionresponse') ||
                   7069:             ($responsetype_per_response{$question-1} eq 'organicresponse')) {
1.572     www      7070:             $r->print(&mt("Although this particular question type requires handgrading, the instructions for this question in the exam directed students to leave [quant,_1,line] blank on their bubblesheets.",$lines).'<br /><br />'.&mt('A non-zero score can be assigned to the student during bubblesheet grading by selecting a bubble in at least one line.').'<br />'.&mt('The score for this question will be a sum of the numeric values for the selected bubbles from each line, where A=1 point, B=2 points etc.').'<br />'.&mt("To assign a score of zero for this question, mark all lines as 'No bubble'.").'<br /><br />');
1.503     raeburn  7071:         } else {
                   7072:             $r->print(&mt("Select at most one bubble in a single line and select 'No Bubble' in all the other lines. ")."<br />");
                   7073:         }
1.497     foxr     7074:     }
                   7075:     for (my $i =0; $i < $lines; $i++) {
1.503     raeburn  7076:         my $selected = $$scan_record{"scantron.$current_line.answer"};
                   7077: 	&scantron_bubble_selector($r,$scan_config,$current_line, 
                   7078: 	        		  $questionnum,$error,split('', $selected));
1.524     raeburn  7079:         push(@linenums,$current_line);
1.497     foxr     7080: 	$current_line++;
                   7081:     }
                   7082:     if ($lines > 1) {
                   7083: 	$r->print("<hr /><br />");
                   7084:     }
1.503     raeburn  7085:     return @linenums;
1.157     albertel 7086: }
1.423     albertel 7087: 
                   7088: =pod
                   7089: 
                   7090: =item scantron_bubble_selector
                   7091:   
                   7092:    Generates the html radiobuttons to correct a single bubble line
1.424     albertel 7093:    possibly showing the existing the selected bubbles if known
1.423     albertel 7094: 
                   7095:  Arguments:
                   7096:     $r           - Apache request object
                   7097:     $scan_config - hash from &get_scantron_config()
1.497     foxr     7098:     $line        - Number of the line being displayed.
1.503     raeburn  7099:     $questionnum - Question number (may include subquestion)
                   7100:     $error       - Type of error.
1.497     foxr     7101:     @selected    - Array of bubbles picked on this line.
1.423     albertel 7102: 
                   7103: =cut
                   7104: 
1.157     albertel 7105: sub scantron_bubble_selector {
1.503     raeburn  7106:     my ($r,$scan_config,$line,$questionnum,$error,@selected)=@_;
1.157     albertel 7107:     my $max=$$scan_config{'Qlength'};
1.274     albertel 7108: 
                   7109:     my $scmode=$$scan_config{'Qon'};
                   7110:     if ($scmode eq 'number' || $scmode eq 'letter') { $max=10; }	     
                   7111: 
1.157     albertel 7112:     my @alphabet=('A'..'Z');
1.503     raeburn  7113:     $r->print(&Apache::loncommon::start_data_table().
                   7114:               &Apache::loncommon::start_data_table_row());
                   7115:     $r->print('<td rowspan="2" class="LC_leftcol_header">'.$line.'</td>');
1.497     foxr     7116:     for (my $i=0;$i<$max+1;$i++) {
                   7117: 	$r->print("\n".'<td align="center">');
                   7118: 	if ($selected[0] eq $alphabet[$i]) { $r->print('X'); shift(@selected) }
                   7119: 	else { $r->print('&nbsp;'); }
                   7120: 	$r->print('</td>');
                   7121:     }
1.503     raeburn  7122:     $r->print(&Apache::loncommon::end_data_table_row().
                   7123:               &Apache::loncommon::start_data_table_row());
1.497     foxr     7124:     for (my $i=0;$i<$max;$i++) {
                   7125: 	$r->print("\n".
                   7126: 		  '<td><label><input type="radio" name="scantron_correct_Q_'.
                   7127: 		  $line.'" value="'.$i.'" />'.$alphabet[$i]."</label></td>");
                   7128:     }
1.503     raeburn  7129:     my $nobub_checked = ' ';
                   7130:     if ($error eq 'missingbubble') {
                   7131:         $nobub_checked = ' checked = "checked" ';
                   7132:     }
                   7133:     $r->print("\n".'<td><label><input type="radio" name="scantron_correct_Q_'.
                   7134: 	      $line.'" value="none"'.$nobub_checked.'/>'.&mt('No bubble').
                   7135:               '</label>'."\n".'<input type="hidden" name="scantron_questionnum_Q_'.
                   7136:               $line.'" value="'.$questionnum.'" /></td>');
                   7137:     $r->print(&Apache::loncommon::end_data_table_row().
                   7138:               &Apache::loncommon::end_data_table());
1.157     albertel 7139: }
                   7140: 
1.423     albertel 7141: =pod
                   7142: 
                   7143: =item num_matches
                   7144: 
1.424     albertel 7145:    Counts the number of characters that are the same between the two arguments.
                   7146: 
                   7147:  Arguments:
                   7148:    $orig - CODE from the scanline
                   7149:    $code - CODE to match against
                   7150: 
                   7151:  Returns:
                   7152:    $count - integer count of the number of same characters between the
                   7153:             two arguments
                   7154: 
1.423     albertel 7155: =cut
                   7156: 
1.194     albertel 7157: sub num_matches {
                   7158:     my ($orig,$code) = @_;
                   7159:     my @code=split(//,$code);
                   7160:     my @orig=split(//,$orig);
                   7161:     my $same=0;
                   7162:     for (my $i=0;$i<scalar(@code);$i++) {
                   7163: 	if ($code[$i] eq $orig[$i]) { $same++; }
                   7164:     }
                   7165:     return $same;
                   7166: }
                   7167: 
1.423     albertel 7168: =pod
                   7169: 
                   7170: =item scantron_get_closely_matching_CODEs
                   7171: 
1.424     albertel 7172:    Cycles through all CODEs and finds the set that has the greatest
                   7173:    number of same characters as the provided CODE
                   7174: 
                   7175:  Arguments:
                   7176:    $allcodes - hash ref returned by &get_codes()
                   7177:    $CODE     - CODE from the current scanline
                   7178: 
                   7179:  Returns:
                   7180:    2 element list
                   7181:     - first elements is number of how closely matching the best fit is 
                   7182:       (5 means best set has 5 matching characters)
                   7183:     - second element is an arrary ref containing the set of valid CODEs
                   7184:       that best fit the passed in CODE
                   7185: 
1.423     albertel 7186: =cut
                   7187: 
1.194     albertel 7188: sub scantron_get_closely_matching_CODEs {
                   7189:     my ($allcodes,$CODE)=@_;
                   7190:     my @CODEs;
                   7191:     foreach my $testcode (sort(keys(%{$allcodes}))) {
                   7192: 	push(@{$CODEs[&num_matches($CODE,$testcode)]},$testcode);
                   7193:     }
                   7194: 
                   7195:     return ($#CODEs,$CODEs[-1]);
                   7196: }
                   7197: 
1.423     albertel 7198: =pod
                   7199: 
                   7200: =item get_codes
                   7201: 
1.424     albertel 7202:    Builds a hash which has keys of all of the valid CODEs from the selected
                   7203:    set of remembered CODEs.
                   7204: 
                   7205:  Arguments:
                   7206:   $old_name - name of the set of remembered CODEs
                   7207:   $cdom     - domain of the course
                   7208:   $cnum     - internal course name
                   7209: 
                   7210:  Returns:
                   7211:   %allcodes - keys are the valid CODEs, values are all 1
                   7212: 
1.423     albertel 7213: =cut
                   7214: 
1.194     albertel 7215: sub get_codes {
1.280     foxr     7216:     my ($old_name, $cdom, $cnum) = @_;
                   7217:     if (!$old_name) {
                   7218: 	$old_name=$env{'form.scantron_CODElist'};
                   7219:     }
                   7220:     if (!$cdom) {
                   7221: 	$cdom =$env{'course.'.$env{'request.course.id'}.'.domain'};
                   7222:     }
                   7223:     if (!$cnum) {
                   7224: 	$cnum =$env{'course.'.$env{'request.course.id'}.'.num'};
                   7225:     }
1.278     albertel 7226:     my %result=&Apache::lonnet::get('CODEs',[$old_name,"type\0$old_name"],
                   7227: 				    $cdom,$cnum);
                   7228:     my %allcodes;
                   7229:     if ($result{"type\0$old_name"} eq 'number') {
                   7230: 	%allcodes=map {($_,1)} split(',',$result{$old_name});
                   7231:     } else {
                   7232: 	%allcodes=map {(&Apache::lonprintout::num_to_letters($_),1)} split(',',$result{$old_name});
                   7233:     }
1.194     albertel 7234:     return %allcodes;
                   7235: }
                   7236: 
1.423     albertel 7237: =pod
                   7238: 
                   7239: =item scantron_validate_CODE
                   7240: 
1.424     albertel 7241:    Validates all scanlines in the selected file to not have any
                   7242:    invalid or underspecified CODEs and that none of the codes are
                   7243:    duplicated if this was requested.
                   7244: 
1.423     albertel 7245: =cut
                   7246: 
1.157     albertel 7247: sub scantron_validate_CODE {
                   7248:     my ($r,$currentphase) = @_;
1.257     albertel 7249:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.186     albertel 7250:     if ($scantron_config{'CODElocation'} &&
                   7251: 	$scantron_config{'CODEstart'} &&
                   7252: 	$scantron_config{'CODElength'}) {
1.257     albertel 7253: 	if (!defined($env{'form.scantron_CODElist'})) {
1.186     albertel 7254: 	    &FIXME_blow_up()
                   7255: 	}
                   7256:     } else {
                   7257: 	return (0,$currentphase+1);
                   7258:     }
                   7259:     
                   7260:     my %usedCODEs;
                   7261: 
1.194     albertel 7262:     my %allcodes=&get_codes();
1.186     albertel 7263: 
1.582     raeburn  7264:     my $nav_error;
                   7265:     &scantron_get_maxbubble(\$nav_error); # parse needs the lines per response array.
                   7266:     if ($nav_error) {
                   7267:         $r->print(&navmap_errormsg());
                   7268:         return(1,$currentphase);
                   7269:     }
1.447     foxr     7270: 
1.186     albertel 7271:     my ($scanlines,$scan_data)=&scantron_getfile();
                   7272:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
1.200     albertel 7273: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.186     albertel 7274: 	if ($line=~/^[\s\cz]*$/) { next; }
                   7275: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
                   7276: 						 $scan_data);
                   7277: 	my $CODE=$$scan_record{'scantron.CODE'};
                   7278: 	my $error=0;
1.224     albertel 7279: 	if (!&Apache::lonnet::validCODE($CODE)) {
                   7280: 	    &scantron_get_correction($r,$i,$scan_record,
                   7281: 				     \%scantron_config,
                   7282: 				     $line,'incorrectCODE',\%allcodes);
                   7283: 	    return(1,$currentphase);
                   7284: 	}
1.221     albertel 7285: 	if (%allcodes && !exists($allcodes{$CODE}) 
                   7286: 	    && !$$scan_record{'scantron.useCODE'}) {
1.186     albertel 7287: 	    &scantron_get_correction($r,$i,$scan_record,
                   7288: 				     \%scantron_config,
1.194     albertel 7289: 				     $line,'incorrectCODE',\%allcodes);
                   7290: 	    return(1,$currentphase);
1.186     albertel 7291: 	}
1.214     albertel 7292: 	if (exists($usedCODEs{$CODE}) 
1.257     albertel 7293: 	    && $env{'form.scantron_CODEunique'} eq 'yes'
1.192     albertel 7294: 	    && !$$scan_record{'scantron.CODE_ignore_dup'}) {
1.186     albertel 7295: 	    &scantron_get_correction($r,$i,$scan_record,
                   7296: 				     \%scantron_config,
1.194     albertel 7297: 				     $line,'duplicateCODE',$usedCODEs{$CODE});
                   7298: 	    return(1,$currentphase);
1.186     albertel 7299: 	}
1.524     raeburn  7300: 	push(@{$usedCODEs{$CODE}},$$scan_record{'scantron.PaperID'});
1.186     albertel 7301:     }
1.157     albertel 7302:     return (0,$currentphase+1);
                   7303: }
                   7304: 
1.423     albertel 7305: =pod
                   7306: 
                   7307: =item scantron_validate_doublebubble
                   7308: 
1.424     albertel 7309:    Validates all scanlines in the selected file to not have any
                   7310:    bubble lines with multiple bubbles marked.
                   7311: 
1.423     albertel 7312: =cut
                   7313: 
1.157     albertel 7314: sub scantron_validate_doublebubble {
                   7315:     my ($r,$currentphase) = @_;
                   7316:     #get student info
                   7317:     my $classlist=&Apache::loncoursedata::get_classlist();
                   7318:     my %idmap=&username_to_idmap($classlist);
                   7319: 
                   7320:     #get scantron line setup
1.257     albertel 7321:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.157     albertel 7322:     my ($scanlines,$scan_data)=&scantron_getfile();
1.583     raeburn  7323:     my $nav_error;
                   7324:     &scantron_get_maxbubble(\$nav_error); # parse needs the bubble line array.
                   7325:     if ($nav_error) {
                   7326:         $r->print(&navmap_errormsg());
                   7327:         return(1,$currentphase);
                   7328:     }
1.447     foxr     7329: 
1.157     albertel 7330:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
1.200     albertel 7331: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.157     albertel 7332: 	if ($line=~/^[\s\cz]*$/) { next; }
                   7333: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
                   7334: 						 $scan_data);
                   7335: 	if (!defined($$scan_record{'scantron.doubleerror'})) { next; }
                   7336: 	&scantron_get_correction($r,$i,$scan_record,\%scantron_config,$line,
                   7337: 				 'doublebubble',
                   7338: 				 $$scan_record{'scantron.doubleerror'});
                   7339:     	return (1,$currentphase);
                   7340:     }
                   7341:     return (0,$currentphase+1);
                   7342: }
                   7343: 
1.423     albertel 7344: 
1.503     raeburn  7345: sub scantron_get_maxbubble {
1.582     raeburn  7346:     my ($nav_error) = @_;
1.257     albertel 7347:     if (defined($env{'form.scantron_maxbubble'}) &&
                   7348: 	$env{'form.scantron_maxbubble'}) {
1.447     foxr     7349: 	&restore_bubble_lines();
1.257     albertel 7350: 	return $env{'form.scantron_maxbubble'};
1.191     albertel 7351:     }
1.330     albertel 7352: 
1.447     foxr     7353:     my (undef, undef, $sequence) =
1.257     albertel 7354: 	&Apache::lonnet::decode_symb($env{'form.selectpage'});
1.330     albertel 7355: 
1.447     foxr     7356:     my $navmap=Apache::lonnavmaps::navmap->new();
1.582     raeburn  7357:     unless (ref($navmap)) {
                   7358:         if (ref($nav_error)) {
                   7359:             $$nav_error = 1;
                   7360:         }
1.591     raeburn  7361:         return;
1.582     raeburn  7362:     }
1.191     albertel 7363:     my $map=$navmap->getResourceByUrl($sequence);
                   7364:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
1.330     albertel 7365: 
                   7366:     &Apache::lonxml::clear_problem_counter();
                   7367: 
1.557     raeburn  7368:     my $uname       = $env{'user.name'};
                   7369:     my $udom        = $env{'user.domain'};
1.435     foxr     7370:     my $cid         = $env{'request.course.id'};
                   7371:     my $total_lines = 0;
                   7372:     %bubble_lines_per_response = ();
1.447     foxr     7373:     %first_bubble_line         = ();
1.503     raeburn  7374:     %subdivided_bubble_lines   = ();
                   7375:     %responsetype_per_response = ();
1.554     raeburn  7376: 
1.447     foxr     7377:     my $response_number = 0;
                   7378:     my $bubble_line     = 0;
1.191     albertel 7379:     foreach my $resource (@resources) {
1.542     raeburn  7380:         my ($analysis,$parts) = &scantron_partids_tograde($resource,$cid,$uname,$udom);
                   7381:         if ((ref($analysis) eq 'HASH') && (ref($parts) eq 'ARRAY')) {
                   7382: 	    foreach my $part_id (@{$parts}) {
                   7383:                 my $lines;
                   7384: 
                   7385: 	        # TODO - make this a persistent hash not an array.
                   7386: 
                   7387:                 # optionresponse, matchresponse and rankresponse type items 
                   7388:                 # render as separate sub-questions in exam mode.
                   7389:                 if (($analysis->{$part_id.'.type'} eq 'optionresponse') ||
                   7390:                     ($analysis->{$part_id.'.type'} eq 'matchresponse') ||
                   7391:                     ($analysis->{$part_id.'.type'} eq 'rankresponse')) {
                   7392:                     my ($numbub,$numshown);
                   7393:                     if ($analysis->{$part_id.'.type'} eq 'optionresponse') {
                   7394:                         if (ref($analysis->{$part_id.'.options'}) eq 'ARRAY') {
                   7395:                             $numbub = scalar(@{$analysis->{$part_id.'.options'}});
                   7396:                         }
                   7397:                     } elsif ($analysis->{$part_id.'.type'} eq 'matchresponse') {
                   7398:                         if (ref($analysis->{$part_id.'.items'}) eq 'ARRAY') {
                   7399:                             $numbub = scalar(@{$analysis->{$part_id.'.items'}});
                   7400:                         }
                   7401:                     } elsif ($analysis->{$part_id.'.type'} eq 'rankresponse') {
                   7402:                         if (ref($analysis->{$part_id.'.foils'}) eq 'ARRAY') {
                   7403:                             $numbub = scalar(@{$analysis->{$part_id.'.foils'}});
                   7404:                         }
                   7405:                     }
                   7406:                     if (ref($analysis->{$part_id.'.shown'}) eq 'ARRAY') {
                   7407:                         $numshown = scalar(@{$analysis->{$part_id.'.shown'}});
                   7408:                     }
                   7409:                     my $bubbles_per_line = 10;
                   7410:                     my $inner_bubble_lines = int($numbub/$bubbles_per_line);
                   7411:                     if (($numbub % $bubbles_per_line) != 0) {
                   7412:                         $inner_bubble_lines++;
                   7413:                     }
                   7414:                     for (my $i=0; $i<$numshown; $i++) {
                   7415:                         $subdivided_bubble_lines{$response_number} .= 
                   7416:                             $inner_bubble_lines.',';
                   7417:                     }
                   7418:                     $subdivided_bubble_lines{$response_number} =~ s/,$//;
                   7419:                     $lines = $numshown * $inner_bubble_lines;
                   7420:                 } else {
                   7421:                     $lines = $analysis->{"$part_id.bubble_lines"};
                   7422:                 } 
                   7423: 
                   7424:                 $first_bubble_line{$response_number} = $bubble_line;
                   7425: 	        $bubble_lines_per_response{$response_number} = $lines;
                   7426:                 $responsetype_per_response{$response_number} = 
                   7427:                     $analysis->{$part_id.'.type'};
                   7428: 	        $response_number++;
                   7429: 
                   7430: 	        $bubble_line +=  $lines;
                   7431: 	        $total_lines +=  $lines;
                   7432: 	    }
                   7433:         }
                   7434:     }
1.552     raeburn  7435:     &Apache::lonnet::delenv('scantron.');
1.542     raeburn  7436: 
                   7437:     &save_bubble_lines();
                   7438:     $env{'form.scantron_maxbubble'} =
                   7439: 	$total_lines;
                   7440:     return $env{'form.scantron_maxbubble'};
                   7441: }
1.523     raeburn  7442: 
1.157     albertel 7443: sub scantron_validate_missingbubbles {
                   7444:     my ($r,$currentphase) = @_;
                   7445:     #get student info
                   7446:     my $classlist=&Apache::loncoursedata::get_classlist();
                   7447:     my %idmap=&username_to_idmap($classlist);
                   7448: 
                   7449:     #get scantron line setup
1.257     albertel 7450:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.157     albertel 7451:     my ($scanlines,$scan_data)=&scantron_getfile();
1.582     raeburn  7452:     my $nav_error;
                   7453:     my $max_bubble=&scantron_get_maxbubble(\$nav_error);
                   7454:     if ($nav_error) {
                   7455:         return(1,$currentphase);
                   7456:     }
1.157     albertel 7457:     if (!$max_bubble) { $max_bubble=2**31; }
                   7458:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
1.200     albertel 7459: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.157     albertel 7460: 	if ($line=~/^[\s\cz]*$/) { next; }
                   7461: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
                   7462: 						 $scan_data);
                   7463: 	if (!defined($$scan_record{'scantron.missingerror'})) { next; }
                   7464: 	my @to_correct;
1.470     foxr     7465: 	
                   7466: 	# Probably here's where the error is...
                   7467: 
1.157     albertel 7468: 	foreach my $missing (@{$$scan_record{'scantron.missingerror'}}) {
1.505     raeburn  7469:             my $lastbubble;
                   7470:             if ($missing =~ /^(\d+)\.(\d+)$/) {
                   7471:                my $question = $1;
                   7472:                my $subquestion = $2;
                   7473:                if (!defined($first_bubble_line{$question -1})) { next; }
                   7474:                my $first = $first_bubble_line{$question-1};
                   7475:                my @subans = split(/,/,$subdivided_bubble_lines{$question-1});
                   7476:                my $subcount = 1;
                   7477:                while ($subcount<$subquestion) {
                   7478:                    $first += $subans[$subcount-1];
                   7479:                    $subcount ++;
                   7480:                }
                   7481:                my $count = $subans[$subquestion-1];
                   7482:                $lastbubble = $first + $count;
                   7483:             } else {
                   7484:                 if (!defined($first_bubble_line{$missing - 1})) { next; }
                   7485:                 $lastbubble = $first_bubble_line{$missing - 1} + $bubble_lines_per_response{$missing - 1};
                   7486:             }
                   7487:             if ($lastbubble > $max_bubble) { next; }
1.157     albertel 7488: 	    push(@to_correct,$missing);
                   7489: 	}
                   7490: 	if (@to_correct) {
                   7491: 	    &scantron_get_correction($r,$i,$scan_record,\%scantron_config,
                   7492: 				     $line,'missingbubble',\@to_correct);
                   7493: 	    return (1,$currentphase);
                   7494: 	}
                   7495: 
                   7496:     }
                   7497:     return (0,$currentphase+1);
                   7498: }
                   7499: 
1.423     albertel 7500: 
1.82      albertel 7501: sub scantron_process_students {
1.608     www      7502:     my ($r,$symb) = @_;
1.513     foxr     7503: 
1.257     albertel 7504:     my (undef,undef,$sequence)=&Apache::lonnet::decode_symb($env{'form.selectpage'});
1.513     foxr     7505:     if (!$symb) {
                   7506: 	return '';
                   7507:     }
1.324     albertel 7508:     my $default_form_data=&defaultFormData($symb);
1.82      albertel 7509: 
1.257     albertel 7510:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.157     albertel 7511:     my ($scanlines,$scan_data)=&scantron_getfile();
1.82      albertel 7512:     my $classlist=&Apache::loncoursedata::get_classlist();
                   7513:     my %idmap=&username_to_idmap($classlist);
1.132     bowersj2 7514:     my $navmap=Apache::lonnavmaps::navmap->new();
1.582     raeburn  7515:     unless (ref($navmap)) {
                   7516:         $r->print(&navmap_errormsg());
                   7517:         return '';
                   7518:     }  
1.83      albertel 7519:     my $map=$navmap->getResourceByUrl($sequence);
                   7520:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
1.557     raeburn  7521:     my (%grader_partids_by_symb,%grader_randomlists_by_symb);
                   7522:     &graders_resources_pass(\@resources,\%grader_partids_by_symb,
                   7523:                             \%grader_randomlists_by_symb);
1.586     raeburn  7524:     my $resource_error;
1.557     raeburn  7525:     foreach my $resource (@resources) {
1.586     raeburn  7526:         my $ressymb;
                   7527:         if (ref($resource)) {
                   7528:             $ressymb = $resource->symb();
                   7529:         } else {
                   7530:             $resource_error = 1;
                   7531:             last;
                   7532:         }
1.557     raeburn  7533:         my ($analysis,$parts) =
                   7534:             &scantron_partids_tograde($resource,$env{'request.course.id'},
                   7535:                                       $env{'user.name'},$env{'user.domain'},1);
                   7536:         $grader_partids_by_symb{$ressymb} = $parts;
                   7537:         if (ref($analysis) eq 'HASH') {
                   7538:             if (ref($analysis->{'parts_withrandomlist'}) eq 'ARRAY') {
                   7539:                 $grader_randomlists_by_symb{$ressymb} = 
                   7540:                     $analysis->{'parts_withrandomlist'};
                   7541:             }
                   7542:         }
                   7543:     }
1.586     raeburn  7544:     if ($resource_error) {
                   7545:         $r->print(&navmap_errormsg());
                   7546:         return '';
                   7547:     }
1.557     raeburn  7548: 
1.554     raeburn  7549:     my ($uname,$udom);
1.82      albertel 7550:     my $result= <<SCANTRONFORM;
1.81      albertel 7551: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantronupload">
                   7552:   <input type="hidden" name="command" value="scantron_configphase" />
                   7553:   $default_form_data
                   7554: SCANTRONFORM
1.82      albertel 7555:     $r->print($result);
                   7556: 
                   7557:     my @delayqueue;
1.542     raeburn  7558:     my (%completedstudents,%scandata);
1.140     albertel 7559:     
1.520     www      7560:     my $lock=&Apache::lonnet::set_lock(&mt('Grading bubblesheet exam'));
1.200     albertel 7561:     my $count=&get_todo_count($scanlines,$scan_data);
1.575     www      7562:     my %prog_state=&Apache::lonhtmlcommon::Create_PrgWin($r,'Bubblesheet Status',
                   7563:  				    'Bubblesheet Progress',$count,
1.195     albertel 7564: 				    'inline',undef,'scantronupload');
1.140     albertel 7565:     &Apache::lonhtmlcommon::Update_PrgWin($r,\%prog_state,
                   7566: 					  'Processing first student');
1.542     raeburn  7567:     $r->print('<br />');
1.140     albertel 7568:     my $start=&Time::HiRes::time();
1.158     albertel 7569:     my $i=-1;
1.542     raeburn  7570:     my $started;
1.447     foxr     7571: 
1.582     raeburn  7572:     my $nav_error;
                   7573:     &scantron_get_maxbubble(\$nav_error); # Need the bubble lines array to parse.
                   7574:     if ($nav_error) {
                   7575:         $r->print(&navmap_errormsg());
                   7576:         return '';
                   7577:     }
                   7578: 
1.513     foxr     7579:     # If an ssi failed in scantron_get_maxbubble, put an error message out to
                   7580:     # the user and return.
                   7581: 
                   7582:     if ($ssi_error) {
                   7583: 	$r->print("</form>");
                   7584: 	&ssi_print_error($r);
1.520     www      7585:         &Apache::lonnet::remove_lock($lock);
1.513     foxr     7586: 	return '';		# Dunno why the other returns return '' rather than just returning.
                   7587:     }
1.447     foxr     7588: 
1.542     raeburn  7589:     my %lettdig = &letter_to_digits();
                   7590:     my $numletts = scalar(keys(%lettdig));
                   7591: 
1.157     albertel 7592:     while ($i<$scanlines->{'count'}) {
                   7593:  	($uname,$udom)=('','');
                   7594:  	$i++;
1.200     albertel 7595:  	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.157     albertel 7596:  	if ($line=~/^[\s\cz]*$/) { next; }
1.200     albertel 7597: 	if ($started) {
                   7598: 	    &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state,
                   7599: 						     'last student');
                   7600: 	}
                   7601: 	$started=1;
1.157     albertel 7602:  	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
                   7603:  						 $scan_data);
                   7604:  	unless ($uname=&scantron_find_student($scan_record,$scan_data,
                   7605:  					      \%idmap,$i)) {
                   7606:   	    &scantron_add_delay(\@delayqueue,$line,
                   7607:  				'Unable to find a student that matches',1);
                   7608:  	    next;
                   7609:   	}
                   7610:  	if (exists $completedstudents{$uname}) {
                   7611:  	    &scantron_add_delay(\@delayqueue,$line,
                   7612:  				'Student '.$uname.' has multiple sheets',2);
                   7613:  	    next;
                   7614:  	}
                   7615:   	($uname,$udom)=split(/:/,$uname);
1.330     albertel 7616: 
1.586     raeburn  7617:         my (%partids_by_symb,$res_error);
1.554     raeburn  7618:         foreach my $resource (@resources) {
1.586     raeburn  7619:             my $ressymb;
                   7620:             if (ref($resource)) {
                   7621:                 $ressymb = $resource->symb();
                   7622:             } else {
                   7623:                 $res_error = 1;
                   7624:                 last;
                   7625:             }
1.557     raeburn  7626:             if ((exists($grader_randomlists_by_symb{$ressymb})) ||
                   7627:                 (ref($grader_partids_by_symb{$ressymb}) ne 'ARRAY')) {
                   7628:                 my ($analysis,$parts) =
                   7629:                     &scantron_partids_tograde($resource,$env{'request.course.id'},$uname,$udom);
                   7630:                 $partids_by_symb{$ressymb} = $parts;
                   7631:             } else {
                   7632:                 $partids_by_symb{$ressymb} = $grader_partids_by_symb{$ressymb};
                   7633:             }
1.554     raeburn  7634:         }
                   7635: 
1.586     raeburn  7636:         if ($res_error) {
                   7637:             &scantron_add_delay(\@delayqueue,$line,
                   7638:                                 'An error occurred while grading student '.$uname,2);
                   7639:             next;
                   7640:         }
                   7641: 
1.330     albertel 7642: 	&Apache::lonxml::clear_problem_counter();
1.514     raeburn  7643:   	&Apache::lonnet::appenv($scan_record);
1.376     albertel 7644: 
                   7645: 	if (&scantron_clear_skip($scanlines,$scan_data,$i)) {
                   7646: 	    &scantron_putfile($scanlines,$scan_data);
                   7647: 	}
1.161     albertel 7648: 	
1.542     raeburn  7649:         my $scancode;
                   7650:         if ((exists($scan_record->{'scantron.CODE'})) &&
                   7651:             (&Apache::lonnet::validCODE($scan_record->{'scantron.CODE'}))) {
                   7652:             $scancode = $scan_record->{'scantron.CODE'};
                   7653:         } else {
                   7654:             $scancode = '';
                   7655:         }
                   7656: 
                   7657:         if (&grade_student_bubbles($r,$uname,$udom,$scan_record,$scancode,
1.554     raeburn  7658:                                    \@resources,\%partids_by_symb) eq 'ssi_error') {
1.542     raeburn  7659:             $ssi_error = 0; # So end of handler error message does not trigger.
                   7660:             $r->print("</form>");
                   7661:             &ssi_print_error($r);
                   7662:             &Apache::lonnet::remove_lock($lock);
                   7663:             return '';      # Why return ''?  Beats me.
                   7664:         }
1.513     foxr     7665: 
1.140     albertel 7666: 	$completedstudents{$uname}={'line'=>$line};
1.542     raeburn  7667:         if ($env{'form.verifyrecord'}) {
                   7668:             my $lastpos = $env{'form.scantron_maxbubble'}*$scantron_config{'Qlength'};
                   7669:             my $studentdata = substr($line,$scantron_config{'Qstart'}-1,$lastpos);
                   7670:             chomp($studentdata);
                   7671:             $studentdata =~ s/\r$//;
                   7672:             my $studentrecord = '';
                   7673:             my $counter = -1;
                   7674:             foreach my $resource (@resources) {
1.554     raeburn  7675:                 my $ressymb = $resource->symb();
1.542     raeburn  7676:                 ($counter,my $recording) =
                   7677:                     &verify_scantron_grading($resource,$udom,$uname,$env{'request.course.id'},
1.554     raeburn  7678:                                              $counter,$studentdata,$partids_by_symb{$ressymb},
1.542     raeburn  7679:                                              \%scantron_config,\%lettdig,$numletts);
                   7680:                 $studentrecord .= $recording;
                   7681:             }
                   7682:             if ($studentrecord ne $studentdata) {
1.554     raeburn  7683:                 &Apache::lonxml::clear_problem_counter();
                   7684:                 if (&grade_student_bubbles($r,$uname,$udom,$scan_record,$scancode,
                   7685:                                            \@resources,\%partids_by_symb) eq 'ssi_error') {
                   7686:                     $ssi_error = 0; # So end of handler error message does not trigger.
                   7687:                     $r->print("</form>");
                   7688:                     &ssi_print_error($r);
                   7689:                     &Apache::lonnet::remove_lock($lock);
                   7690:                     delete($completedstudents{$uname});
                   7691:                     return '';
                   7692:                 }
1.542     raeburn  7693:                 $counter = -1;
                   7694:                 $studentrecord = '';
                   7695:                 foreach my $resource (@resources) {
1.554     raeburn  7696:                     my $ressymb = $resource->symb();
1.542     raeburn  7697:                     ($counter,my $recording) =
                   7698:                         &verify_scantron_grading($resource,$udom,$uname,$env{'request.course.id'},
1.554     raeburn  7699:                                                  $counter,$studentdata,$partids_by_symb{$ressymb},
1.542     raeburn  7700:                                                  \%scantron_config,\%lettdig,$numletts);
                   7701:                     $studentrecord .= $recording;
                   7702:                 }
                   7703:                 if ($studentrecord ne $studentdata) {
                   7704:                     $r->print('<p><span class="LC_error">');
                   7705:                     if ($scancode eq '') {
                   7706:                         $r->print(&mt('Mismatch grading bubble sheet for user: [_1] with ID: [_2].',
                   7707:                                   $uname.':'.$udom,$scan_record->{'scantron.ID'}));
                   7708:                     } else {
                   7709:                         $r->print(&mt('Mismatch grading bubble sheet for user: [_1] with ID: [_2] and CODE: [_3].',
                   7710:                                   $uname.':'.$udom,$scan_record->{'scantron.ID'},$scancode));
                   7711:                     }
                   7712:                     $r->print('</span><br />'.&Apache::loncommon::start_data_table()."\n".
                   7713:                               &Apache::loncommon::start_data_table_header_row()."\n".
                   7714:                               '<th>'.&mt('Source').'</th><th>'.&mt('Bubbled responses').'</th>'.
                   7715:                               &Apache::loncommon::end_data_table_header_row()."\n".
                   7716:                               &Apache::loncommon::start_data_table_row().
                   7717:                               '<td>'.&mt('Bubble Sheet').'</td>'.
                   7718:                               '<td><span class="LC_nobreak">'.$studentdata.'</span></td>'.
                   7719:                               &Apache::loncommon::end_data_table_row().
                   7720:                               &Apache::loncommon::start_data_table_row().
                   7721:                               '<td>Stored submissions</td>'.
                   7722:                               '<td><span class="LC_nobreak">'.$studentrecord.'</span></td>'."\n".
                   7723:                               &Apache::loncommon::end_data_table_row().
                   7724:                               &Apache::loncommon::end_data_table().'</p>');
                   7725:                 } else {
                   7726:                     $r->print('<br /><span class="LC_warning">'.
                   7727:                              &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 />'.
                   7728:                              &mt("As a consequence, this user's submission history records two tries.").
                   7729:                                  '</span><br />');
                   7730:                 }
                   7731:             }
                   7732:         }
1.543     raeburn  7733:         if (&Apache::loncommon::connection_aborted($r)) { last; }
1.140     albertel 7734:     } continue {
1.330     albertel 7735: 	&Apache::lonxml::clear_problem_counter();
1.552     raeburn  7736: 	&Apache::lonnet::delenv('scantron.');
1.82      albertel 7737:     }
1.140     albertel 7738:     &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
1.520     www      7739:     &Apache::lonnet::remove_lock($lock);
1.172     albertel 7740: #    my $lasttime = &Time::HiRes::time()-$start;
                   7741: #    $r->print("<p>took $lasttime</p>");
1.140     albertel 7742: 
1.200     albertel 7743:     $r->print("</form>");
1.157     albertel 7744:     return '';
1.75      albertel 7745: }
1.157     albertel 7746: 
1.557     raeburn  7747: sub graders_resources_pass {
                   7748:     my ($resources,$grader_partids_by_symb,$grader_randomlists_by_symb) = @_;
                   7749:     if ((ref($resources) eq 'ARRAY') && (ref($grader_partids_by_symb)) && 
                   7750:         (ref($grader_randomlists_by_symb) eq 'HASH')) {
                   7751:         foreach my $resource (@{$resources}) {
                   7752:             my $ressymb = $resource->symb();
                   7753:             my ($analysis,$parts) =
                   7754:                 &scantron_partids_tograde($resource,$env{'request.course.id'},
                   7755:                                           $env{'user.name'},$env{'user.domain'},1);
                   7756:             $grader_partids_by_symb->{$ressymb} = $parts;
                   7757:             if (ref($analysis) eq 'HASH') {
                   7758:                 if (ref($analysis->{'parts_withrandomlist'}) eq 'ARRAY') {
                   7759:                     $grader_randomlists_by_symb->{$ressymb} =
                   7760:                         $analysis->{'parts_withrandomlist'};
                   7761:                 }
                   7762:             }
                   7763:         }
                   7764:     }
                   7765:     return;
                   7766: }
                   7767: 
1.542     raeburn  7768: sub grade_student_bubbles {
1.554     raeburn  7769:     my ($r,$uname,$udom,$scan_record,$scancode,$resources,$parts) = @_;
                   7770:     if (ref($resources) eq 'ARRAY') {
                   7771:         my $count = 0;
                   7772:         foreach my $resource (@{$resources}) {
                   7773:             my $ressymb = $resource->symb();
                   7774:             my %form = ('submitted'      => 'scantron',
                   7775:                         'grade_target'   => 'grade',
                   7776:                         'grade_username' => $uname,
                   7777:                         'grade_domain'   => $udom,
                   7778:                         'grade_courseid' => $env{'request.course.id'},
                   7779:                         'grade_symb'     => $ressymb,
                   7780:                         'CODE'           => $scancode
                   7781:                        );
                   7782:             if (ref($parts) eq 'HASH') {
                   7783:                 if (ref($parts->{$ressymb}) eq 'ARRAY') {
                   7784:                     foreach my $part (@{$parts->{$ressymb}}) {
                   7785:                         $form{'scantron_questnum_start.'.$part} =
                   7786:                             1+$env{'form.scantron.first_bubble_line.'.$count};
                   7787:                         $count++;
                   7788:                     }
                   7789:                 }
                   7790:             }
                   7791:             my $result=&ssi_with_retries($resource->src(),$ssi_retries,%form);
                   7792:             return 'ssi_error' if ($ssi_error);
                   7793:             last if (&Apache::loncommon::connection_aborted($r));
                   7794:         }
1.542     raeburn  7795:     }
                   7796:     return;
                   7797: }
                   7798: 
1.157     albertel 7799: sub scantron_upload_scantron_data {
1.608     www      7800:     my ($r,$symb)=@_;
1.565     raeburn  7801:     my $dom = $env{'request.role.domain'};
                   7802:     my $domdesc = &Apache::lonnet::domain($dom,'description');
                   7803:     $r->print(&Apache::loncommon::coursebrowser_javascript($dom));
1.157     albertel 7804:     my $select_link=&Apache::loncommon::selectcourse_link('rules','courseid',
1.181     albertel 7805: 							  'domainid',
1.565     raeburn  7806: 							  'coursename',$dom);
                   7807:     my $syllabuslink = '<a href="javascript:ToSyllabus();">'.&mt('Syllabus').'</a>'.
                   7808:                        ('&nbsp'x2).&mt('(shows course personnel)'); 
1.608     www      7809:     my $default_form_data=&defaultFormData($symb);
1.579     raeburn  7810:     my $nofile_alert = &mt('Please use the browse button to select a file from your local directory.');
                   7811:     my $nocourseid_alert = &mt("Please use the 'Select Course' link to open a separate window where you can search for a course to which a file can be uploaded.");
1.597     wenzelju 7812:     $r->print(&Apache::lonhtmlcommon::scripttag('
1.157     albertel 7813:     function checkUpload(formname) {
                   7814: 	if (formname.upfile.value == "") {
1.579     raeburn  7815: 	    alert("'.$nofile_alert.'");
1.157     albertel 7816: 	    return false;
                   7817: 	}
1.565     raeburn  7818:         if (formname.courseid.value == "") {
1.579     raeburn  7819:             alert("'.$nocourseid_alert.'");
1.565     raeburn  7820:             return false;
                   7821:         }
1.157     albertel 7822: 	formname.submit();
                   7823:     }
1.565     raeburn  7824: 
                   7825:     function ToSyllabus() {
                   7826:         var cdom = '."'$dom'".';
                   7827:         var cnum = document.rules.courseid.value;
                   7828:         if (cdom == "" || cdom == null) {
                   7829:             return;
                   7830:         }
                   7831:         if (cnum == "" || cnum == null) {
                   7832:            return;
                   7833:         }
                   7834:         syllwin=window.open("/public/"+cdom+"/"+cnum+"/syllabus","LONCAPASyllabus",
                   7835:                             "height=350,width=350,scrollbars=yes,menubar=no");
                   7836:         return;
                   7837:     }
                   7838: 
1.597     wenzelju 7839: '));
                   7840:     $r->print('
1.566     raeburn  7841: <h3>'.&mt('Send scanned bubblesheet data to a course').'</h3>
                   7842: 
1.492     albertel 7843: <form enctype="multipart/form-data" action="/adm/grades" name="rules" method="post">
1.565     raeburn  7844: '.$default_form_data.
                   7845:   &Apache::lonhtmlcommon::start_pick_box().
                   7846:   &Apache::lonhtmlcommon::row_title(&mt('Course ID')).
                   7847:   '<input name="courseid" type="text" size="30" />'.$select_link.
                   7848:   &Apache::lonhtmlcommon::row_closure().
                   7849:   &Apache::lonhtmlcommon::row_title(&mt('Course Name')).
                   7850:   '<input name="coursename" type="text" size="30" />'.$syllabuslink.
                   7851:   &Apache::lonhtmlcommon::row_closure().
                   7852:   &Apache::lonhtmlcommon::row_title(&mt('Domain')).
                   7853:   '<input name="domainid" type="hidden" />'.$domdesc.
                   7854:   &Apache::lonhtmlcommon::row_closure().
                   7855:   &Apache::lonhtmlcommon::row_title(&mt('File to upload')).
                   7856:   '<input type="file" name="upfile" size="50" />'.
                   7857:   &Apache::lonhtmlcommon::row_closure(1).
                   7858:   &Apache::lonhtmlcommon::end_pick_box().'<br />
                   7859: 
1.492     albertel 7860: <input name="command" value="scantronupload_save" type="hidden" />
1.589     bisitz   7861: <input type="button" onclick="javascript:checkUpload(this.form);" value="'.&mt('Upload Bubblesheet Data').'" />
1.157     albertel 7862: </form>
1.492     albertel 7863: ');
1.157     albertel 7864:     return '';
                   7865: }
                   7866: 
1.423     albertel 7867: 
1.157     albertel 7868: sub scantron_upload_scantron_data_save {
1.608     www      7869:     my($r,$symb)=@_;
1.182     albertel 7870:     my $doanotherupload=
                   7871: 	'<br /><form action="/adm/grades" method="post">'."\n".
                   7872: 	'<input type="hidden" name="command" value="scantronupload" />'."\n".
1.492     albertel 7873: 	'<input type="submit" name="submit" value="'.&mt('Do Another Upload').'" />'."\n".
1.182     albertel 7874: 	'</form>'."\n";
1.257     albertel 7875:     if (!&Apache::lonnet::allowed('usc',$env{'form.domainid'}) &&
1.162     albertel 7876: 	!&Apache::lonnet::allowed('usc',
1.257     albertel 7877: 			    $env{'form.domainid'}.'_'.$env{'form.courseid'})) {
1.575     www      7878: 	$r->print(&mt("You are not allowed to upload bubblesheet data to the requested course.")."<br />");
1.614     www      7879: 	unless ($symb) {
1.182     albertel 7880: 	    $r->print($doanotherupload);
                   7881: 	}
1.162     albertel 7882: 	return '';
                   7883:     }
1.257     albertel 7884:     my %coursedata=&Apache::lonnet::coursedescription($env{'form.domainid'}.'_'.$env{'form.courseid'});
1.568     raeburn  7885:     my $uploadedfile;
1.567     raeburn  7886:     $r->print('<h3>'.&mt("Uploading file to [_1]",$coursedata{'description'}).'</h3>');
1.257     albertel 7887:     if (length($env{'form.upfile'}) < 2) {
1.568     raeburn  7888:         $r->print(&mt('[_1]Error:[_2] The file you attempted to upload, [_3] contained no information. Please check that you entered the correct filename.','<span class="LC_error">','</span>','<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>'));
1.183     albertel 7889:     } else {
1.568     raeburn  7890:         my $result = 
                   7891:             &Apache::lonnet::userfileupload('upfile','','scantron','','','',
                   7892:                                             $env{'form.courseid'},$env{'form.domainid'});
                   7893: 	if ($result =~ m{^/uploaded/}) {
1.567     raeburn  7894: 	    $r->print(&mt('[_1]Success:[_2] Successfully uploaded [_3] bytes of data into location: [_4]',
                   7895:                           '<span class="LC_success">','</span>',(length($env{'form.upfile'})-1),
                   7896: 			  '<span class="LC_filename">'.$result.'</span>'));
1.568     raeburn  7897:             ($uploadedfile) = ($result =~ m{/([^/]+)$});
1.567     raeburn  7898:             $r->print(&validate_uploaded_scantron_file($env{'form.domainid'},
1.568     raeburn  7899:                                                        $env{'form.courseid'},$uploadedfile));
1.210     albertel 7900: 	} else {
1.567     raeburn  7901: 	    $r->print(&mt('[_1]Error:[_2] An error ([_3]) occurred when attempting to upload the file, [_4]',
                   7902:                           '<span class="LC_error">','</span>',$result,
1.568     raeburn  7903: 			  '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>'));
1.183     albertel 7904: 	}
                   7905:     }
1.174     albertel 7906:     if ($symb) {
1.612     www      7907: 	$r->print(&scantron_selectphase($r,$uploadedfile,$symb));
1.174     albertel 7908:     } else {
1.182     albertel 7909: 	$r->print($doanotherupload);
1.174     albertel 7910:     }
1.157     albertel 7911:     return '';
                   7912: }
                   7913: 
1.567     raeburn  7914: sub validate_uploaded_scantron_file {
                   7915:     my ($cdom,$cname,$fname) = @_;
                   7916:     my $scanlines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.$fname);
                   7917:     my @lines;
                   7918:     if ($scanlines ne '-1') {
                   7919:         @lines=split("\n",$scanlines,-1);
                   7920:     }
                   7921:     my $output;
                   7922:     if (@lines) {
                   7923:         my (%counts,$max_match_format);
                   7924:         my ($max_match_count,$max_match_pct) = (0,0);
                   7925:         my $classlist = &Apache::loncoursedata::get_classlist($cdom,$cname);
                   7926:         my %idmap = &username_to_idmap($classlist);
                   7927:         foreach my $key (keys(%idmap)) {
                   7928:             my $lckey = lc($key);
                   7929:             $idmap{$lckey} = $idmap{$key};
                   7930:         }
                   7931:         my %unique_formats;
                   7932:         my @formatlines = &get_scantronformat_file();
                   7933:         foreach my $line (@formatlines) {
                   7934:             chomp($line);
                   7935:             my @config = split(/:/,$line);
                   7936:             my $idstart = $config[5];
                   7937:             my $idlength = $config[6];
                   7938:             if (($idstart ne '') && ($idlength > 0)) {
                   7939:                 if (ref($unique_formats{$idstart.':'.$idlength}) eq 'ARRAY') {
                   7940:                     push(@{$unique_formats{$idstart.':'.$idlength}},$config[0].':'.$config[1]); 
                   7941:                 } else {
                   7942:                     $unique_formats{$idstart.':'.$idlength} = [$config[0].':'.$config[1]];
                   7943:                 }
                   7944:             }
                   7945:         }
                   7946:         foreach my $key (keys(%unique_formats)) {
                   7947:             my ($idstart,$idlength) = split(':',$key);
                   7948:             %{$counts{$key}} = (
                   7949:                                'found'   => 0,
                   7950:                                'total'   => 0,
                   7951:                               );
                   7952:             foreach my $line (@lines) {
                   7953:                 next if ($line =~ /^#/);
                   7954:                 next if ($line =~ /^[\s\cz]*$/);
                   7955:                 my $id = substr($line,$idstart-1,$idlength);
                   7956:                 $id = lc($id);
                   7957:                 if (exists($idmap{$id})) {
                   7958:                     $counts{$key}{'found'} ++;
                   7959:                 }
                   7960:                 $counts{$key}{'total'} ++;
                   7961:             }
                   7962:             if ($counts{$key}{'total'}) {
                   7963:                 my $percent_match = (100*$counts{$key}{'found'})/($counts{$key}{'total'});
                   7964:                 if (($max_match_format eq '') || ($percent_match > $max_match_pct)) {
                   7965:                     $max_match_pct = $percent_match;
                   7966:                     $max_match_format = $key;
                   7967:                     $max_match_count = $counts{$key}{'total'};
                   7968:                 }
                   7969:             }
                   7970:         }
                   7971:         if (ref($unique_formats{$max_match_format}) eq 'ARRAY') {
                   7972:             my $format_descs;
                   7973:             my $numwithformat = @{$unique_formats{$max_match_format}};
                   7974:             for (my $i=0; $i<$numwithformat; $i++) {
                   7975:                 my ($name,$desc) = split(':',$unique_formats{$max_match_format}[$i]);
                   7976:                 if ($i<$numwithformat-2) {
                   7977:                     $format_descs .= '"<i>'.$desc.'</i>", ';
                   7978:                 } elsif ($i==$numwithformat-2) {
                   7979:                     $format_descs .= '"<i>'.$desc.'</i>" '.&mt('and').' ';
                   7980:                 } elsif ($i==$numwithformat-1) {
                   7981:                     $format_descs .= '"<i>'.$desc.'</i>"';
                   7982:                 }
                   7983:             }
                   7984:             my $showpct = sprintf("%.0f",$max_match_pct).'%';
                   7985:             $output .= '<br />'.&mt('Comparison of student IDs in the uploaded file with the course roster found matches for [_1] of the [_2] entries in the file (for the format defined for [_3]).','<b>'.$showpct.'</b>','<b>'.$max_match_count.'</b>',$format_descs).
                   7986:                        '<br />'.&mt('A low percentage of matches results from one of the following:').'<ul>'.
                   7987:                        '<li>'.&mt('The file was uploaded to the wrong course').'</li>'.
                   7988:                        '<li>'.&mt('The data are not in the format expected for the domain: [_1]',
                   7989:                                   '<i>'.$cdom.'</i>').'</li>'.
                   7990:                        '<li>'.&mt('Students did not bubble their IDs, or mis-bubbled them').'</li>'.
                   7991:                        '<li>'.&mt('The course roster is not up to date').'</li>'.
                   7992:                        '</ul>';
                   7993:         }
                   7994:     } else {
                   7995:         $output = '<span class="LC_warning">'.&mt('Uploaded file contained no data').'</span>';
                   7996:     }
                   7997:     return $output;
                   7998: }
                   7999: 
1.202     albertel 8000: sub valid_file {
                   8001:     my ($requested_file)=@_;
                   8002:     foreach my $filename (sort(&scantron_filenames())) {
                   8003: 	if ($requested_file eq $filename) { return 1; }
                   8004:     }
                   8005:     return 0;
                   8006: }
                   8007: 
                   8008: sub scantron_download_scantron_data {
1.608     www      8009:     my ($r,$symb)=@_;
                   8010:     my $default_form_data=&defaultFormData($symb);
1.257     albertel 8011:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   8012:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   8013:     my $file=$env{'form.scantron_selectfile'};
1.202     albertel 8014:     if (! &valid_file($file)) {
1.492     albertel 8015: 	$r->print('
1.202     albertel 8016: 	<p>
1.492     albertel 8017: 	    '.&mt('The requested file name was invalid.').'
1.202     albertel 8018:         </p>
1.492     albertel 8019: ');
1.202     albertel 8020: 	return;
                   8021:     }
                   8022:     my $orig='/uploaded/'.$cdom.'/'.$cname.'/scantron_orig_'.$file;
                   8023:     my $corrected='/uploaded/'.$cdom.'/'.$cname.'/scantron_corrected_'.$file;
                   8024:     my $skipped='/uploaded/'.$cdom.'/'.$cname.'/scantron_skipped_'.$file;
                   8025:     &Apache::lonnet::allowuploaded('/adm/grades',$orig);
                   8026:     &Apache::lonnet::allowuploaded('/adm/grades',$corrected);
                   8027:     &Apache::lonnet::allowuploaded('/adm/grades',$skipped);
1.492     albertel 8028:     $r->print('
1.202     albertel 8029:     <p>
1.492     albertel 8030: 	'.&mt('[_1]Original[_2] file as uploaded by the scantron office.',
                   8031: 	      '<a href="'.$orig.'">','</a>').'
1.202     albertel 8032:     </p>
                   8033:     <p>
1.492     albertel 8034: 	'.&mt('[_1]Corrections[_2], a file of corrected records that were used in grading.',
                   8035: 	      '<a href="'.$corrected.'">','</a>').'
1.202     albertel 8036:     </p>
                   8037:     <p>
1.492     albertel 8038: 	'.&mt('[_1]Skipped[_2], a file of records that were skipped.',
                   8039: 	      '<a href="'.$skipped.'">','</a>').'
1.202     albertel 8040:     </p>
1.492     albertel 8041: ');
1.202     albertel 8042:     return '';
                   8043: }
1.157     albertel 8044: 
1.523     raeburn  8045: sub checkscantron_results {
1.608     www      8046:     my ($r,$symb) = @_;
1.523     raeburn  8047:     if (!$symb) {return '';}
                   8048:     my $cid = $env{'request.course.id'};
1.542     raeburn  8049:     my %lettdig = &letter_to_digits();
1.523     raeburn  8050:     my $numletts = scalar(keys(%lettdig));
                   8051:     my $cnum = $env{'course.'.$cid.'.num'};
                   8052:     my $cdom = $env{'course.'.$cid.'.domain'};
                   8053:     my (undef, undef, $sequence) = &Apache::lonnet::decode_symb($env{'form.selectpage'});
                   8054:     my %record;
                   8055:     my %scantron_config =
                   8056:         &Apache::grades::get_scantron_config($env{'form.scantron_format'});
                   8057:     my ($scanlines,$scan_data)=&Apache::grades::scantron_getfile();
                   8058:     my $classlist=&Apache::loncoursedata::get_classlist();
                   8059:     my %idmap=&Apache::grades::username_to_idmap($classlist);
                   8060:     my $navmap=Apache::lonnavmaps::navmap->new();
1.582     raeburn  8061:     unless (ref($navmap)) {
                   8062:         $r->print(&navmap_errormsg());
                   8063:         return '';
                   8064:     }
1.523     raeburn  8065:     my $map=$navmap->getResourceByUrl($sequence);
1.557     raeburn  8066:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
                   8067:     my (%grader_partids_by_symb,%grader_randomlists_by_symb);
                   8068:     &graders_resources_pass(\@resources,\%grader_partids_by_symb,                             \%grader_randomlists_by_symb);
                   8069: 
1.554     raeburn  8070:     my ($uname,$udom);
1.523     raeburn  8071:     my (%scandata,%lastname,%bylast);
                   8072:     $r->print('
                   8073: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="checkscantron">'."\n");
                   8074: 
                   8075:     my @delayqueue;
                   8076:     my %completedstudents;
                   8077: 
                   8078:     my $count=&Apache::grades::get_todo_count($scanlines,$scan_data);
1.581     www      8079:     my %prog_state=&Apache::lonhtmlcommon::Create_PrgWin($r,'Bubblesheet/Submissions Comparison Status',
                   8080:                                     'Progress of Bubblesheet Data/Submission Records Comparison',$count,
1.523     raeburn  8081:                                     'inline',undef,'checkscantron');
1.546     raeburn  8082:     my ($username,$domain,$started);
1.582     raeburn  8083:     my $nav_error;
                   8084:     &scantron_get_maxbubble(\$nav_error); # Need the bubble lines array to parse.
                   8085:     if ($nav_error) {
                   8086:         $r->print(&navmap_errormsg());
                   8087:         return '';
                   8088:     }
1.523     raeburn  8089: 
                   8090:     &Apache::lonhtmlcommon::Update_PrgWin($r,\%prog_state,
                   8091:                                           'Processing first student');
                   8092:     my $start=&Time::HiRes::time();
                   8093:     my $i=-1;
                   8094: 
                   8095:     while ($i<$scanlines->{'count'}) {
                   8096:         ($username,$domain,$uname)=('','','');
                   8097:         $i++;
                   8098:         my $line=&Apache::grades::scantron_get_line($scanlines,$scan_data,$i);
                   8099:         if ($line=~/^[\s\cz]*$/) { next; }
                   8100:         if ($started) {
                   8101:             &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state,
                   8102:                                                      'last student');
                   8103:         }
                   8104:         $started=1;
                   8105:         my $scan_record=
                   8106:             &Apache::grades::scantron_parse_scanline($line,$i,\%scantron_config,
                   8107:                                                      $scan_data);
                   8108:         unless ($uname=&Apache::grades::scantron_find_student($scan_record,$scan_data,
                   8109:                                                               \%idmap,$i)) {
                   8110:             &Apache::grades::scantron_add_delay(\@delayqueue,$line,
                   8111:                                 'Unable to find a student that matches',1);
                   8112:             next;
                   8113:         }
                   8114:         if (exists $completedstudents{$uname}) {
                   8115:             &Apache::grades::scantron_add_delay(\@delayqueue,$line,
                   8116:                                 'Student '.$uname.' has multiple sheets',2);
                   8117:             next;
                   8118:         }
                   8119:         my $pid = $scan_record->{'scantron.ID'};
                   8120:         $lastname{$pid} = $scan_record->{'scantron.LastName'};
                   8121:         push(@{$bylast{$lastname{$pid}}},$pid);
                   8122:         my $lastpos = $env{'form.scantron_maxbubble'}*$scantron_config{'Qlength'};
                   8123:         $scandata{$pid} = substr($line,$scantron_config{'Qstart'}-1,$lastpos);
                   8124:         chomp($scandata{$pid});
                   8125:         $scandata{$pid} =~ s/\r$//;
                   8126:         ($username,$domain)=split(/:/,$uname);
                   8127:         my $counter = -1;
                   8128:         foreach my $resource (@resources) {
1.557     raeburn  8129:             my $parts;
1.554     raeburn  8130:             my $ressymb = $resource->symb();
1.557     raeburn  8131:             if ((exists($grader_randomlists_by_symb{$ressymb})) ||
                   8132:                 (ref($grader_partids_by_symb{$ressymb}) ne 'ARRAY')) {
                   8133:                 (my $analysis,$parts) =
                   8134:                     &scantron_partids_tograde($resource,$env{'request.course.id'},$username,$domain);
                   8135:             } else {
                   8136:                 $parts = $grader_partids_by_symb{$ressymb};
                   8137:             }
1.542     raeburn  8138:             ($counter,my $recording) =
                   8139:                 &verify_scantron_grading($resource,$domain,$username,$cid,$counter,
1.554     raeburn  8140:                                          $scandata{$pid},$parts,
1.542     raeburn  8141:                                          \%scantron_config,\%lettdig,$numletts);
                   8142:             $record{$pid} .= $recording;
1.523     raeburn  8143:         }
                   8144:     }
                   8145:     &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
                   8146:     $r->print('<br />');
                   8147:     my ($okstudents,$badstudents,$numstudents,$passed,$failed);
                   8148:     $passed = 0;
                   8149:     $failed = 0;
                   8150:     $numstudents = 0;
                   8151:     foreach my $last (sort(keys(%bylast))) {
                   8152:         if (ref($bylast{$last}) eq 'ARRAY') {
                   8153:             foreach my $pid (sort(@{$bylast{$last}})) {
                   8154:                 my $showscandata = $scandata{$pid};
                   8155:                 my $showrecord = $record{$pid};
                   8156:                 $showscandata =~ s/\s/&nbsp;/g;
                   8157:                 $showrecord =~ s/\s/&nbsp;/g;
                   8158:                 if ($scandata{$pid} eq $record{$pid}) {
                   8159:                     my $css_class = ($passed % 2)?'LC_odd_row':'LC_even_row';
                   8160:                     $okstudents .= '<tr class="'.$css_class.'">'.
1.581     www      8161: '<td>'.&mt('Bubblesheet').'</td><td>'.$showscandata.'</td><td rowspan="2">'.$last.'</td><td rowspan="2">'.$pid.'</td>'."\n".
1.523     raeburn  8162: '</tr>'."\n".
                   8163: '<tr class="'.$css_class.'">'."\n".
                   8164: '<td>Submissions</td><td>'.$showrecord.'</td></tr>'."\n";
                   8165:                     $passed ++;
                   8166:                 } else {
                   8167:                     my $css_class = ($failed % 2)?'LC_odd_row':'LC_even_row';
1.581     www      8168:                     $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  8169: '</tr>'."\n".
                   8170: '<tr class="'.$css_class.'">'."\n".
                   8171: '<td>Submissions</td><td><span class="LC_nobreak">'.$record{$pid}.'</span></td>'."\n".
                   8172: '</tr>'."\n";
                   8173:                     $failed ++;
                   8174:                 }
                   8175:                 $numstudents ++;
                   8176:             }
                   8177:         }
                   8178:     }
1.572     www      8179:     $r->print('<p>'.&mt('Comparison of bubblesheet data (including corrections) with corresponding submission records (most recent submission) for <b>[quant,_1,student]</b>  ([_2] scantron lines/student).',$numstudents,$env{'form.scantron_maxbubble'}).'</p>');
1.523     raeburn  8180:     $r->print('<p>'.&mt('Exact matches for <b>[quant,_1,student]</b>.',$passed).'<br />'.&mt('Discrepancies detected for <b>[quant,_1,student]</b>.',$failed).'</p>');
                   8181:     if ($passed) {
1.572     www      8182:         $r->print(&mt('Students with exact correspondence between bubblesheet data and submissions are as follows:').'<br /><br />');
1.523     raeburn  8183:         $r->print(&Apache::loncommon::start_data_table()."\n".
                   8184:                  &Apache::loncommon::start_data_table_header_row()."\n".
                   8185:                  '<th>'.&mt('Source').'</th><th>'.&mt('Bubble records').'</th><th>'.&mt('Name').'</th><th>'.&mt('ID').'</th>'.
                   8186:                  &Apache::loncommon::end_data_table_header_row()."\n".
                   8187:                  $okstudents."\n".
                   8188:                  &Apache::loncommon::end_data_table().'<br />');
                   8189:     }
                   8190:     if ($failed) {
1.572     www      8191:         $r->print(&mt('Students with differences between bubblesheet data and submissions are as follows:').'<br /><br />');
1.523     raeburn  8192:         $r->print(&Apache::loncommon::start_data_table()."\n".
                   8193:                  &Apache::loncommon::start_data_table_header_row()."\n".
                   8194:                  '<th>'.&mt('Source').'</th><th>'.&mt('Bubble records').'</th><th>'.&mt('Name').'</th><th>'.&mt('ID').'</th>'.
                   8195:                  &Apache::loncommon::end_data_table_header_row()."\n".
                   8196:                  $badstudents."\n".
                   8197:                  &Apache::loncommon::end_data_table()).'<br />'.
1.572     www      8198:                  &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  8199:     }
1.614     www      8200:     $r->print('</form><br />');
1.523     raeburn  8201:     return;
                   8202: }
                   8203: 
1.542     raeburn  8204: sub verify_scantron_grading {
1.554     raeburn  8205:     my ($resource,$domain,$username,$cid,$counter,$scandata,$partids,
1.542     raeburn  8206:         $scantron_config,$lettdig,$numletts) = @_;
                   8207:     my ($record,%expected,%startpos);
                   8208:     return ($counter,$record) if (!ref($resource));
                   8209:     return ($counter,$record) if (!$resource->is_problem());
                   8210:     my $symb = $resource->symb();
1.554     raeburn  8211:     return ($counter,$record) if (ref($partids) ne 'ARRAY');
                   8212:     foreach my $part_id (@{$partids}) {
1.542     raeburn  8213:         $counter ++;
                   8214:         $expected{$part_id} = 0;
                   8215:         if ($env{"form.scantron.sub_bubblelines.$counter"}) {
                   8216:             my @sub_lines = split(/,/,$env{"form.scantron.sub_bubblelines.$counter"});
                   8217:             foreach my $item (@sub_lines) {
                   8218:                 $expected{$part_id} += $item;
                   8219:             }
                   8220:         } else {
                   8221:             $expected{$part_id} = $env{"form.scantron.bubblelines.$counter"};
                   8222:         }
                   8223:         $startpos{$part_id} = $env{"form.scantron.first_bubble_line.$counter"};
                   8224:     }
                   8225:     if ($symb) {
                   8226:         my %recorded;
                   8227:         my (%returnhash) = &Apache::lonnet::restore($symb,$cid,$domain,$username);
                   8228:         if ($returnhash{'version'}) {
                   8229:             my %lasthash=();
                   8230:             my $version;
                   8231:             for ($version=1;$version<=$returnhash{'version'};$version++) {
                   8232:                 foreach my $key (sort(split(/\:/,$returnhash{$version.':keys'}))) {
                   8233:                     $lasthash{$key}=$returnhash{$version.':'.$key};
                   8234:                 }
                   8235:             }
                   8236:             foreach my $key (keys(%lasthash)) {
                   8237:                 if ($key =~ /\.scantron$/) {
                   8238:                     my $value = &unescape($lasthash{$key});
                   8239:                     my ($part_id) = ($key =~ /^resource\.(.+)\.scantron$/);
                   8240:                     if ($value eq '') {
                   8241:                         for (my $i=0; $i<$expected{$part_id}; $i++) {
                   8242:                             for (my $j=0; $j<$scantron_config->{'length'}; $j++) {
                   8243:                                 $recorded{$part_id} .= $scantron_config->{'Qoff'};
                   8244:                             }
                   8245:                         }
                   8246:                     } else {
                   8247:                         my @tocheck;
                   8248:                         my @items = split(//,$value);
                   8249:                         if (($scantron_config->{'Qon'} eq 'letter') ||
                   8250:                             ($scantron_config->{'Qon'} eq 'number')) {
                   8251:                             if (@items < $expected{$part_id}) {
                   8252:                                 my $fragment = substr($scandata,$startpos{$part_id},$expected{$part_id});
                   8253:                                 my @singles = split(//,$fragment);
                   8254:                                 foreach my $pos (@singles) {
                   8255:                                     if ($pos eq ' ') {
                   8256:                                         push(@tocheck,$pos);
                   8257:                                     } else {
                   8258:                                         my $next = shift(@items);
                   8259:                                         push(@tocheck,$next);
                   8260:                                     }
                   8261:                                 }
                   8262:                             } else {
                   8263:                                 @tocheck = @items;
                   8264:                             }
                   8265:                             foreach my $letter (@tocheck) {
                   8266:                                 if ($scantron_config->{'Qon'} eq 'letter') {
                   8267:                                     if ($letter !~ /^[A-J]$/) {
                   8268:                                         $letter = $scantron_config->{'Qoff'};
                   8269:                                     }
                   8270:                                     $recorded{$part_id} .= $letter;
                   8271:                                 } elsif ($scantron_config->{'Qon'} eq 'number') {
                   8272:                                     my $digit;
                   8273:                                     if ($letter !~ /^[A-J]$/) {
                   8274:                                         $digit = $scantron_config->{'Qoff'};
                   8275:                                     } else {
                   8276:                                         $digit = $lettdig->{$letter};
                   8277:                                     }
                   8278:                                     $recorded{$part_id} .= $digit;
                   8279:                                 }
                   8280:                             }
                   8281:                         } else {
                   8282:                             @tocheck = @items;
                   8283:                             for (my $i=0; $i<$expected{$part_id}; $i++) {
                   8284:                                 my $curr_sub = shift(@tocheck);
                   8285:                                 my $digit;
                   8286:                                 if ($curr_sub =~ /^[A-J]$/) {
                   8287:                                     $digit = $lettdig->{$curr_sub}-1;
                   8288:                                 }
                   8289:                                 if ($curr_sub eq 'J') {
                   8290:                                     $digit += scalar($numletts);
                   8291:                                 }
                   8292:                                 for (my $j=0; $j<$scantron_config->{'Qlength'}; $j++) {
                   8293:                                     if ($j == $digit) {
                   8294:                                         $recorded{$part_id} .= $scantron_config->{'Qon'};
                   8295:                                     } else {
                   8296:                                         $recorded{$part_id} .= $scantron_config->{'Qoff'};
                   8297:                                     }
                   8298:                                 }
                   8299:                             }
                   8300:                         }
                   8301:                     }
                   8302:                 }
                   8303:             }
                   8304:         }
1.554     raeburn  8305:         foreach my $part_id (@{$partids}) {
1.542     raeburn  8306:             if ($recorded{$part_id} eq '') {
                   8307:                 for (my $i=0; $i<$expected{$part_id}; $i++) {
                   8308:                     for (my $j=0; $j<$scantron_config->{'Qlength'}; $j++) {
                   8309:                         $recorded{$part_id} .= $scantron_config->{'Qoff'};
                   8310:                     }
                   8311:                 }
                   8312:             }
                   8313:             $record .= $recorded{$part_id};
                   8314:         }
                   8315:     }
                   8316:     return ($counter,$record);
                   8317: }
                   8318: 
                   8319: sub letter_to_digits { 
                   8320:     my %lettdig = (
                   8321:                     A => 1,
                   8322:                     B => 2,
                   8323:                     C => 3,
                   8324:                     D => 4,
                   8325:                     E => 5,
                   8326:                     F => 6,
                   8327:                     G => 7,
                   8328:                     H => 8,
                   8329:                     I => 9,
                   8330:                     J => 0,
                   8331:                   );
                   8332:     return %lettdig;
                   8333: }
                   8334: 
1.423     albertel 8335: 
1.75      albertel 8336: #-------- end of section for handling grading scantron forms -------
                   8337: #
                   8338: #-------------------------------------------------------------------
                   8339: 
1.72      ng       8340: #-------------------------- Menu interface -------------------------
                   8341: #
1.614     www      8342: #--- Href with symb and command ---
                   8343: 
                   8344: sub href_symb_cmd {
                   8345:     my ($symb,$cmd)=@_;
                   8346:     return '/adm/grades?symb='.&HTML::Entities::encode(&Apache::lonenc::check_encrypt($symb),'<>&"').'&command='.$cmd;
1.72      ng       8347: }
                   8348: 
1.443     banghart 8349: sub grading_menu {
1.608     www      8350:     my ($request,$symb) = @_;
1.443     banghart 8351:     if (!$symb) {return '';}
                   8352: 
                   8353:     my %fields = ('symb'=>&Apache::lonenc::check_encrypt($symb),
1.618     www      8354:                   'command'=>'individual');
1.538     schulted 8355:     
1.598     www      8356:     my $url1a = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   8357: 
                   8358:     $fields{'command'}='ungraded';
                   8359:     my $url1b=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   8360: 
                   8361:     $fields{'command'}='table';
                   8362:     my $url1c=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   8363: 
                   8364:     $fields{'command'}='all_for_one';
                   8365:     my $url1d=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   8366: 
1.621     www      8367:     $fields{'command'}='downloadfilesselect';
                   8368:     my $url1e=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   8369: 
1.443     banghart 8370:     $fields{'command'} = 'csvform';
1.538     schulted 8371:     my $url2 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   8372:     
1.443     banghart 8373:     $fields{'command'} = 'processclicker';
1.538     schulted 8374:     my $url3 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   8375:     
1.443     banghart 8376:     $fields{'command'} = 'scantron_selectphase';
1.538     schulted 8377:     my $url4 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
1.602     www      8378: 
                   8379:     $fields{'command'} = 'initialverifyreceipt';
                   8380:     my $url5 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
1.538     schulted 8381:     
1.598     www      8382:     my @menu = ({	categorytitle=>'Hand Grading',
1.538     schulted 8383:             items =>[
1.598     www      8384:                         {	linktext => 'Select individual students to grade',
                   8385:                     		url => $url1a,
1.538     schulted 8386:                     		permission => 'F',
1.636     wenzelju 8387:                     		icon => 'grade_students.png',
1.598     www      8388:                     		linktitle => 'Grade current resource for a selection of students.'
                   8389:                         }, 
                   8390:                         {       linktext => 'Grade ungraded submissions.',
                   8391:                                 url => $url1b,
                   8392:                                 permission => 'F',
1.636     wenzelju 8393:                                 icon => 'ungrade_sub.png',
1.598     www      8394:                                 linktitle => 'Grade all submissions that have not been graded yet.'
1.538     schulted 8395:                         },
1.598     www      8396: 
                   8397:                         {       linktext => 'Grading table',
                   8398:                                 url => $url1c,
                   8399:                                 permission => 'F',
1.636     wenzelju 8400:                                 icon => 'grading_table.png',
1.598     www      8401:                                 linktitle => 'Grade current resource for all students.'
                   8402:                         },
1.615     www      8403:                         {       linktext => 'Grade page/folder for one student',
1.598     www      8404:                                 url => $url1d,
                   8405:                                 permission => 'F',
1.636     wenzelju 8406:                                 icon => 'grade_PageFolder.png',
1.598     www      8407:                                 linktitle => 'Grade all resources in current page/sequence/folder for one student.'
1.621     www      8408:                         },
                   8409:                         {       linktext => 'Download submissions',
                   8410:                                 url => $url1e,
                   8411:                                 permission => 'F',
1.636     wenzelju 8412:                                 icon => 'download_sub.png',
1.621     www      8413:                                 linktitle => 'Download all students submissions.'
1.598     www      8414:                         }]},
                   8415:                          { categorytitle=>'Automated Grading',
                   8416:                items =>[
                   8417: 
1.538     schulted 8418:                 	    {	linktext => 'Upload Scores',
                   8419:                     		url => $url2,
                   8420:                     		permission => 'F',
                   8421:                     		icon => 'uploadscores.png',
                   8422:                     		linktitle => 'Specify a file containing the class scores for current resource.'
                   8423:                 	    },
                   8424:                 	    {	linktext => 'Process Clicker',
                   8425:                     		url => $url3,
                   8426:                     		permission => 'F',
                   8427:                     		icon => 'addClickerInfoFile.png',
                   8428:                     		linktitle => 'Specify a file containing the clicker information for this resource.'
                   8429:                 	    },
1.587     raeburn  8430:                 	    {	linktext => 'Grade/Manage/Review Bubblesheets',
1.538     schulted 8431:                     		url => $url4,
                   8432:                     		permission => 'F',
1.636     wenzelju 8433:                     		icon => 'bubblesheet.png',
1.538     schulted 8434:                     		linktitle => 'Grade scantron exams, upload/download scantron data files, and review previously graded scantron exams.'
1.602     www      8435:                 	    },
1.616     www      8436:                             {   linktext => 'Verify Receipt Number',
1.602     www      8437:                                 url => $url5,
                   8438:                                 permission => 'F',
1.636     wenzelju 8439:                                 icon => 'receipt_number.png',
1.602     www      8440:                                 linktitle => 'Verify a system-generated receipt number for correct problem solution.'
                   8441:                             }
                   8442: 
1.538     schulted 8443:                     ]
                   8444:             });
                   8445: 
1.443     banghart 8446:     # Create the menu
                   8447:     my $Str;
1.445     banghart 8448:     $Str .= '<form method="post" action="" name="gradingMenu">';
                   8449:     $Str .= '<input type="hidden" name="command" value="" />'.
1.618     www      8450:     	'<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
1.445     banghart 8451: 
1.602     www      8452:     $Str .= &Apache::lonhtmlcommon::generate_menu(@menu);
1.443     banghart 8453:     return $Str;    
                   8454: }
                   8455: 
1.598     www      8456: 
                   8457: sub ungraded {
                   8458:     my ($request)=@_;
                   8459:     &submit_options($request);
                   8460: }
                   8461: 
1.599     www      8462: sub submit_options_sequence {
1.608     www      8463:     my ($request,$symb) = @_;
1.599     www      8464:     if (!$symb) {return '';}
1.600     www      8465:     &commonJSfunctions($request);
                   8466:     my $result;
1.599     www      8467: 
1.600     www      8468:     $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
1.618     www      8469:         '<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
1.632     www      8470:     $result.=&selectfield(0).
1.601     www      8471:             '<input type="hidden" name="command" value="pickStudentPage" />
1.600     www      8472:             <div>
                   8473:               <input type="submit" value="'.&mt('Next').' &rarr;" />
                   8474:             </div>
                   8475:         </div>
                   8476:   </form>';
                   8477:     return $result;
                   8478: }
                   8479: 
                   8480: sub submit_options_table {
1.608     www      8481:     my ($request,$symb) = @_;
1.600     www      8482:     if (!$symb) {return '';}
1.599     www      8483:     &commonJSfunctions($request);
                   8484:     my $result;
                   8485: 
                   8486:     $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
1.618     www      8487:         '<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
1.599     www      8488: 
1.632     www      8489:     $result.=&selectfield(0).
1.601     www      8490:             '<input type="hidden" name="command" value="viewgrades" />
1.599     www      8491:             <div>
                   8492:               <input type="submit" value="'.&mt('Next').' &rarr;" />
                   8493:             </div>
                   8494:         </div>
                   8495:   </form>';
                   8496:     return $result;
                   8497: }
1.443     banghart 8498: 
1.621     www      8499: sub submit_options_download {
                   8500:     my ($request,$symb) = @_;
                   8501:     if (!$symb) {return '';}
                   8502: 
                   8503:     &commonJSfunctions($request);
                   8504: 
                   8505:     my $result='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
                   8506:         '<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
                   8507:     $result.='
                   8508: <h2>
                   8509:   '.&mt('Select Students for Which to Download Submissions').'
                   8510: </h2>'.&selectfield(1).'
                   8511:                 <input type="hidden" name="command" value="downloadfileslink" /> 
                   8512:               <input type="submit" value="'.&mt('Next').' &rarr;" />
                   8513:             </div>
                   8514:           </div>
1.600     www      8515: 
                   8516: 
1.621     www      8517:   </form>';
                   8518:     return $result;
                   8519: }
                   8520: 
1.443     banghart 8521: #--- Displays the submissions first page -------
                   8522: sub submit_options {
1.608     www      8523:     my ($request,$symb) = @_;
1.72      ng       8524:     if (!$symb) {return '';}
                   8525: 
1.118     ng       8526:     &commonJSfunctions($request);
1.473     albertel 8527:     my $result;
1.533     bisitz   8528: 
1.72      ng       8529:     $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
1.618     www      8530: 	'<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
1.632     www      8531:     $result.=&selectfield(1).'
1.601     www      8532:                 <input type="hidden" name="command" value="submission" /> 
                   8533: 	      <input type="submit" value="'.&mt('Next').' &rarr;" />
                   8534:             </div>
                   8535:           </div>
                   8536: 
                   8537: 
                   8538:   </form>';
                   8539:     return $result;
                   8540: }
1.533     bisitz   8541: 
1.601     www      8542: sub selectfield {
                   8543:    my ($full)=@_;
1.635     raeburn  8544:    my %options = 
                   8545:           (&Apache::lonlocal::texthash(
                   8546:              'yes'       => 'with submissions',
                   8547:              'queued'    => 'in grading queue',
                   8548:              'graded'    => 'with ungraded submissions',
                   8549:              'incorrect' => 'with incorrect submissions',
                   8550:              'all'       => 'with any status'),
                   8551:              'select_form_order' => ['yes','queued','graded','incorrect','all']);
1.601     www      8552:    my $result='<div class="LC_columnSection">
1.537     harmsja  8553:   
1.533     bisitz   8554:     <fieldset>
                   8555:       <legend>
                   8556:        '.&mt('Sections').'
                   8557:       </legend>
1.601     www      8558:       '.&Apache::lonstatistics::SectionSelect('section','multiple',5).'
1.533     bisitz   8559:     </fieldset>
1.537     harmsja  8560:   
1.533     bisitz   8561:     <fieldset>
                   8562:       <legend>
                   8563:         '.&mt('Groups').'
                   8564:       </legend>
                   8565:       '.&Apache::lonstatistics::GroupSelect('group','multiple',5).'
                   8566:     </fieldset>
1.537     harmsja  8567:   
1.533     bisitz   8568:     <fieldset>
                   8569:       <legend>
                   8570:         '.&mt('Access Status').'
                   8571:       </legend>
1.601     www      8572:       '.&Apache::lonhtmlcommon::StatusOptions(undef,undef,5,undef,'mult').'
                   8573:     </fieldset>';
                   8574:     if ($full) {
                   8575:        $result.='
1.533     bisitz   8576:     <fieldset>
                   8577:       <legend>
                   8578:         '.&mt('Submission Status').'
1.601     www      8579:       </legend>'.
1.635     raeburn  8580:        &Apache::loncommon::select_form('all','submitonly',\%options).
1.601     www      8581:    '</fieldset>';
                   8582:     }
                   8583:     $result.='</div><br />';
1.44      ng       8584:     return $result;
1.2       albertel 8585: }
                   8586: 
1.285     albertel 8587: sub reset_perm {
                   8588:     undef(%perm);
                   8589: }
                   8590: 
                   8591: sub init_perm {
                   8592:     &reset_perm();
1.300     albertel 8593:     foreach my $test_perm ('vgr','mgr','opa') {
                   8594: 
                   8595: 	my $scope = $env{'request.course.id'};
                   8596: 	if (!($perm{$test_perm}=&Apache::lonnet::allowed($test_perm,$scope))) {
                   8597: 
                   8598: 	    $scope .= '/'.$env{'request.course.sec'};
                   8599: 	    if ( $perm{$test_perm}=
                   8600: 		 &Apache::lonnet::allowed($test_perm,$scope)) {
                   8601: 		$perm{$test_perm.'_section'}=$env{'request.course.sec'};
                   8602: 	    } else {
                   8603: 		delete($perm{$test_perm});
                   8604: 	    }
1.285     albertel 8605: 	}
                   8606:     }
                   8607: }
                   8608: 
1.400     www      8609: sub gather_clicker_ids {
1.408     albertel 8610:     my %clicker_ids;
1.400     www      8611: 
                   8612:     my $classlist = &Apache::loncoursedata::get_classlist();
                   8613: 
                   8614:     # Set up a couple variables.
1.407     albertel 8615:     my $username_idx = &Apache::loncoursedata::CL_SNAME();
                   8616:     my $domain_idx   = &Apache::loncoursedata::CL_SDOM();
1.438     www      8617:     my $status_idx   = &Apache::loncoursedata::CL_STATUS();
1.400     www      8618: 
1.407     albertel 8619:     foreach my $student (keys(%$classlist)) {
1.438     www      8620:         if ($classlist->{$student}->[$status_idx] ne 'Active') { next; }
1.407     albertel 8621:         my $username = $classlist->{$student}->[$username_idx];
                   8622:         my $domain   = $classlist->{$student}->[$domain_idx];
1.400     www      8623:         my $clickers =
1.408     albertel 8624: 	    (&Apache::lonnet::userenvironment($domain,$username,'clickers'))[1];
1.400     www      8625:         foreach my $id (split(/\,/,$clickers)) {
1.414     www      8626:             $id=~s/^[\#0]+//;
1.421     www      8627:             $id=~s/[\-\:]//g;
1.407     albertel 8628:             if (exists($clicker_ids{$id})) {
1.408     albertel 8629: 		$clicker_ids{$id}.=','.$username.':'.$domain;
1.400     www      8630:             } else {
1.408     albertel 8631: 		$clicker_ids{$id}=$username.':'.$domain;
1.400     www      8632:             }
                   8633:         }
                   8634:     }
1.407     albertel 8635:     return %clicker_ids;
1.400     www      8636: }
                   8637: 
1.402     www      8638: sub gather_adv_clicker_ids {
1.408     albertel 8639:     my %clicker_ids;
1.402     www      8640:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
                   8641:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   8642:     my %coursepersonnel=&Apache::lonnet::get_course_adv_roles($cdom.'/'.$cnum);
1.409     albertel 8643:     foreach my $element (sort(keys(%coursepersonnel))) {
1.402     www      8644:         foreach my $person (split(/\,/,$coursepersonnel{$element})) {
                   8645:             my ($puname,$pudom)=split(/\:/,$person);
                   8646:             my $clickers =
1.408     albertel 8647: 		(&Apache::lonnet::userenvironment($pudom,$puname,'clickers'))[1];
1.405     www      8648:             foreach my $id (split(/\,/,$clickers)) {
1.414     www      8649: 		$id=~s/^[\#0]+//;
1.421     www      8650:                 $id=~s/[\-\:]//g;
1.408     albertel 8651: 		if (exists($clicker_ids{$id})) {
                   8652: 		    $clicker_ids{$id}.=','.$puname.':'.$pudom;
                   8653: 		} else {
                   8654: 		    $clicker_ids{$id}=$puname.':'.$pudom;
                   8655: 		}
1.405     www      8656:             }
1.402     www      8657:         }
                   8658:     }
1.407     albertel 8659:     return %clicker_ids;
1.402     www      8660: }
                   8661: 
1.413     www      8662: sub clicker_grading_parameters {
                   8663:     return ('gradingmechanism' => 'scalar',
                   8664:             'upfiletype' => 'scalar',
                   8665:             'specificid' => 'scalar',
                   8666:             'pcorrect' => 'scalar',
                   8667:             'pincorrect' => 'scalar');
                   8668: }
                   8669: 
1.400     www      8670: sub process_clicker {
1.608     www      8671:     my ($r,$symb)=@_;
1.400     www      8672:     if (!$symb) {return '';}
                   8673:     my $result=&checkforfile_js();
1.632     www      8674:     $result.=&Apache::loncommon::start_data_table().
                   8675:              &Apache::loncommon::start_data_table_header_row().
                   8676:              '<th>'.&mt('Specify a file containing clicker information and set grading options.').'</th>'.
                   8677:              &Apache::loncommon::end_data_table_header_row().
                   8678:              &Apache::loncommon::start_data_table_row()."<td>\n";
1.413     www      8679: # Attempt to restore parameters from last session, set defaults if not present
                   8680:     my %Saveable_Parameters=&clicker_grading_parameters();
                   8681:     &Apache::loncommon::restore_course_settings('grades_clicker',
                   8682:                                                  \%Saveable_Parameters);
                   8683:     if (!$env{'form.pcorrect'}) { $env{'form.pcorrect'}=100; }
                   8684:     if (!$env{'form.pincorrect'}) { $env{'form.pincorrect'}=100; }
                   8685:     if (!$env{'form.gradingmechanism'}) { $env{'form.gradingmechanism'}='attendance'; }
                   8686:     if (!$env{'form.upfiletype'}) { $env{'form.upfiletype'}='iclicker'; }
                   8687: 
                   8688:     my %checked;
1.521     www      8689:     foreach my $gradingmechanism ('attendance','personnel','specific','given') {
1.413     www      8690:        if ($env{'form.gradingmechanism'} eq $gradingmechanism) {
1.569     bisitz   8691:           $checked{$gradingmechanism}=' checked="checked"';
1.413     www      8692:        }
                   8693:     }
                   8694: 
1.632     www      8695:     my $upload=&mt("Evaluate File");
1.400     www      8696:     my $type=&mt("Type");
1.402     www      8697:     my $attendance=&mt("Award points just for participation");
                   8698:     my $personnel=&mt("Correctness determined from response by course personnel");
1.414     www      8699:     my $specific=&mt("Correctness determined from response with clicker ID(s)"); 
1.521     www      8700:     my $given=&mt("Correctness determined from given list of answers").' '.
                   8701:               '<font size="-2"><tt>('.&mt("Provide comma-separated list. Use '*' for any answer correct, '-' for skip").')</tt></font>';
1.402     www      8702:     my $pcorrect=&mt("Percentage points for correct solution");
                   8703:     my $pincorrect=&mt("Percentage points for incorrect solution");
1.413     www      8704:     my $selectform=&Apache::loncommon::select_form($env{'form.upfiletype'},'upfiletype',
1.635     raeburn  8705: 						   {'iclicker' => 'i>clicker',
                   8706:                                                     'interwrite' => 'interwrite PRS'});
1.418     albertel 8707:     $symb = &Apache::lonenc::check_encrypt($symb);
1.597     wenzelju 8708:     $result.= &Apache::lonhtmlcommon::scripttag(<<ENDUPFORM);
1.402     www      8709: function sanitycheck() {
                   8710: // Accept only integer percentages
                   8711:    document.forms.gradesupload.pcorrect.value=Math.round(document.forms.gradesupload.pcorrect.value);
                   8712:    document.forms.gradesupload.pincorrect.value=Math.round(document.forms.gradesupload.pincorrect.value);
                   8713: // Find out grading choice
                   8714:    for (i=0; i<document.forms.gradesupload.gradingmechanism.length; i++) {
                   8715:       if (document.forms.gradesupload.gradingmechanism[i].checked) {
                   8716:          gradingchoice=document.forms.gradesupload.gradingmechanism[i].value;
                   8717:       }
                   8718:    }
                   8719: // By default, new choice equals user selection
                   8720:    newgradingchoice=gradingchoice;
                   8721: // Not good to give more points for false answers than correct ones
                   8722:    if (Math.round(document.forms.gradesupload.pcorrect.value)<Math.round(document.forms.gradesupload.pincorrect.value)) {
                   8723:       document.forms.gradesupload.pcorrect.value=document.forms.gradesupload.pincorrect.value;
                   8724:    }
                   8725: // If new choice is attendance only, and old choice was correctness-based, restore defaults
                   8726:    if ((gradingchoice=='attendance') && (document.forms.gradesupload.waschecked.value!='attendance')) {
                   8727:       document.forms.gradesupload.pcorrect.value=100;
                   8728:       document.forms.gradesupload.pincorrect.value=100;
                   8729:    }
                   8730: // If the values are different, cannot be attendance only
                   8731:    if ((Math.round(document.forms.gradesupload.pcorrect.value)!=Math.round(document.forms.gradesupload.pincorrect.value)) &&
                   8732:        (gradingchoice=='attendance')) {
                   8733:        newgradingchoice='personnel';
                   8734:    }
                   8735: // Change grading choice to new one
                   8736:    for (i=0; i<document.forms.gradesupload.gradingmechanism.length; i++) {
                   8737:       if (document.forms.gradesupload.gradingmechanism[i].value==newgradingchoice) {
                   8738:          document.forms.gradesupload.gradingmechanism[i].checked=true;
                   8739:       } else {
                   8740:          document.forms.gradesupload.gradingmechanism[i].checked=false;
                   8741:       }
                   8742:    }
                   8743: // Remember the old state
                   8744:    document.forms.gradesupload.waschecked.value=newgradingchoice;
                   8745: }
1.597     wenzelju 8746: ENDUPFORM
                   8747:     $result.= <<ENDUPFORM;
1.400     www      8748: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
                   8749: <input type="hidden" name="symb" value="$symb" />
                   8750: <input type="hidden" name="command" value="processclickerfile" />
                   8751: <input type="file" name="upfile" size="50" />
                   8752: <br /><label>$type: $selectform</label>
1.632     www      8753: ENDUPFORM
                   8754:     $result.='</td>'.&Apache::loncommon::end_data_table_row().
                   8755:                      &Apache::loncommon::start_data_table_row().'<td>'.(<<ENDGRADINGFORM);
                   8756:       <label><input type="radio" name="gradingmechanism" value="attendance"$checked{'attendance'} onclick="sanitycheck()" />$attendance </label>
1.589     bisitz   8757: <br /><label><input type="radio" name="gradingmechanism" value="personnel"$checked{'personnel'} onclick="sanitycheck()" />$personnel</label>
                   8758: <br /><label><input type="radio" name="gradingmechanism" value="specific"$checked{'specific'} onclick="sanitycheck()" />$specific </label>
1.414     www      8759: <input type="text" name="specificid" value="$env{'form.specificid'}" size="20" />
1.589     bisitz   8760: <br /><label><input type="radio" name="gradingmechanism" value="given"$checked{'given'} onclick="sanitycheck()" />$given </label>
1.521     www      8761: <br />&nbsp;&nbsp;&nbsp;
                   8762: <input type="text" name="givenanswer" size="50" />
1.413     www      8763: <input type="hidden" name="waschecked" value="$env{'form.gradingmechanism'}" />
1.632     www      8764: ENDGRADINGFORM
                   8765:          $result.='</td>'.&Apache::loncommon::end_data_table_row().
                   8766:                      &Apache::loncommon::start_data_table_row().'<td>'.(<<ENDPERCFORM);
                   8767:       <label>$pcorrect: <input type="text" name="pcorrect" size="4" value="$env{'form.pcorrect'}" onchange="sanitycheck()" /></label>
1.589     bisitz   8768: <br /><label>$pincorrect: <input type="text" name="pincorrect" size="4" value="$env{'form.pincorrect'}" onchange="sanitycheck()" /></label>
                   8769: <br /><input type="button" onclick="javascript:checkUpload(this.form);" value="$upload" />
1.597     wenzelju 8770: </form>'
1.632     www      8771: ENDPERCFORM
                   8772:     $result.='</td>'.
                   8773:              &Apache::loncommon::end_data_table_row().
                   8774:              &Apache::loncommon::end_data_table();
1.400     www      8775:     return $result;
                   8776: }
                   8777: 
                   8778: sub process_clicker_file {
1.608     www      8779:     my ($r,$symb)=@_;
1.400     www      8780:     if (!$symb) {return '';}
1.413     www      8781: 
                   8782:     my %Saveable_Parameters=&clicker_grading_parameters();
                   8783:     &Apache::loncommon::store_course_settings('grades_clicker',
                   8784:                                               \%Saveable_Parameters);
1.598     www      8785:     my $result='';
1.404     www      8786:     if (($env{'form.gradingmechanism'} eq 'specific') && ($env{'form.specificid'}!~/\w/)) {
1.408     albertel 8787: 	$result.='<span class="LC_error">'.&mt('You need to specify a clicker ID for the correct answer').'</span>';
1.614     www      8788: 	return $result;
1.404     www      8789:     }
1.522     www      8790:     if (($env{'form.gradingmechanism'} eq 'given') && ($env{'form.givenanswer'}!~/\S/)) {
1.521     www      8791:         $result.='<span class="LC_error">'.&mt('You need to specify the correct answer').'</span>';
1.614     www      8792:         return $result;
1.521     www      8793:     }
1.522     www      8794:     my $foundgiven=0;
1.521     www      8795:     if ($env{'form.gradingmechanism'} eq 'given') {
                   8796:         $env{'form.givenanswer'}=~s/^\s*//gs;
                   8797:         $env{'form.givenanswer'}=~s/\s*$//gs;
                   8798:         $env{'form.givenanswer'}=~s/[^a-zA-Z0-9\.\*\-]+/\,/g;
                   8799:         $env{'form.givenanswer'}=uc($env{'form.givenanswer'});
1.522     www      8800:         my @answers=split(/\,/,$env{'form.givenanswer'});
                   8801:         $foundgiven=$#answers+1;
1.521     www      8802:     }
1.407     albertel 8803:     my %clicker_ids=&gather_clicker_ids();
1.408     albertel 8804:     my %correct_ids;
1.404     www      8805:     if ($env{'form.gradingmechanism'} eq 'personnel') {
1.408     albertel 8806: 	%correct_ids=&gather_adv_clicker_ids();
1.404     www      8807:     }
                   8808:     if ($env{'form.gradingmechanism'} eq 'specific') {
1.414     www      8809: 	foreach my $correct_id (split(/[\s\,]/,$env{'form.specificid'})) {;
                   8810: 	   $correct_id=~tr/a-z/A-Z/;
                   8811: 	   $correct_id=~s/\s//gs;
                   8812: 	   $correct_id=~s/^[\#0]+//;
1.421     www      8813:            $correct_id=~s/[\-\:]//g;
1.414     www      8814:            if ($correct_id) {
                   8815: 	      $correct_ids{$correct_id}='specified';
                   8816:            }
                   8817:         }
1.400     www      8818:     }
1.404     www      8819:     if ($env{'form.gradingmechanism'} eq 'attendance') {
1.408     albertel 8820: 	$result.=&mt('Score based on attendance only');
1.521     www      8821:     } elsif ($env{'form.gradingmechanism'} eq 'given') {
1.522     www      8822:         $result.=&mt('Score based on [_1] ([_2] answers)','<tt>'.$env{'form.givenanswer'}.'</tt>',$foundgiven);
1.404     www      8823:     } else {
1.408     albertel 8824: 	my $number=0;
1.411     www      8825: 	$result.='<p><b>'.&mt('Correctness determined by the following IDs').'</b>';
1.408     albertel 8826: 	foreach my $id (sort(keys(%correct_ids))) {
1.411     www      8827: 	    $result.='<br /><tt>'.$id.'</tt> - ';
1.408     albertel 8828: 	    if ($correct_ids{$id} eq 'specified') {
                   8829: 		$result.=&mt('specified');
                   8830: 	    } else {
                   8831: 		my ($uname,$udom)=split(/\:/,$correct_ids{$id});
                   8832: 		$result.=&Apache::loncommon::plainname($uname,$udom);
                   8833: 	    }
                   8834: 	    $number++;
                   8835: 	}
1.411     www      8836:         $result.="</p>\n";
1.408     albertel 8837: 	if ($number==0) {
                   8838: 	    $result.='<span class="LC_error">'.&mt('No IDs found to determine correct answer').'</span>';
1.614     www      8839: 	    return $result;
1.408     albertel 8840: 	}
1.404     www      8841:     }
1.405     www      8842:     if (length($env{'form.upfile'}) < 2) {
1.407     albertel 8843:         $result.=&mt('[_1] Error: [_2] The file you attempted to upload, [_3] contained no information. Please check that you entered the correct filename.',
                   8844: 		     '<span class="LC_error">',
                   8845: 		     '</span>',
                   8846: 		     '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>');
1.614     www      8847:         return $result;
1.405     www      8848:     }
1.410     www      8849: 
                   8850: # Were able to get all the info needed, now analyze the file
                   8851: 
1.411     www      8852:     $result.=&Apache::loncommon::studentbrowser_javascript();
1.418     albertel 8853:     $symb = &Apache::lonenc::check_encrypt($symb);
1.632     www      8854:     $result.=&Apache::loncommon::start_data_table().
                   8855:              &Apache::loncommon::start_data_table_header_row().
                   8856:              '<th>'.&mt('Evaluate clicker file').'</th>'.
                   8857:              &Apache::loncommon::end_data_table_header_row().
                   8858:              &Apache::loncommon::start_data_table_row().(<<ENDHEADER);
                   8859: <td>
1.410     www      8860: <form method="post" action="/adm/grades" name="clickeranalysis">
                   8861: <input type="hidden" name="symb" value="$symb" />
                   8862: <input type="hidden" name="command" value="assignclickergrades" />
1.411     www      8863: <input type="hidden" name="gradingmechanism" value="$env{'form.gradingmechanism'}" />
                   8864: <input type="hidden" name="pcorrect" value="$env{'form.pcorrect'}" />
                   8865: <input type="hidden" name="pincorrect" value="$env{'form.pincorrect'}" />
1.410     www      8866: ENDHEADER
1.522     www      8867:     if ($env{'form.gradingmechanism'} eq 'given') {
                   8868:        $result.='<input type="hidden" name="correct:given" value="'.$env{'form.givenanswer'}.'" />';
                   8869:     } 
1.408     albertel 8870:     my %responses;
                   8871:     my @questiontitles;
1.405     www      8872:     my $errormsg='';
                   8873:     my $number=0;
                   8874:     if ($env{'form.upfiletype'} eq 'iclicker') {
1.408     albertel 8875: 	($errormsg,$number)=&iclicker_eval(\@questiontitles,\%responses);
1.406     www      8876:     }
1.419     www      8877:     if ($env{'form.upfiletype'} eq 'interwrite') {
                   8878:         ($errormsg,$number)=&interwrite_eval(\@questiontitles,\%responses);
                   8879:     }
1.411     www      8880:     $result.='<br />'.&mt('Found [_1] question(s)',$number).'<br />'.
                   8881:              '<input type="hidden" name="number" value="'.$number.'" />'.
                   8882:              &mt('Awarding [_1] percent for correct and [_2] percent for incorrect responses',
                   8883:                  $env{'form.pcorrect'},$env{'form.pincorrect'}).
                   8884:              '<br />';
1.522     www      8885:     if (($env{'form.gradingmechanism'} eq 'given') && ($number!=$foundgiven)) {
                   8886:        $result.='<span class="LC_error">'.&mt('Number of given answers does not agree with number of questions in file.').'</span>';
1.614     www      8887:        return $result;
1.522     www      8888:     } 
1.414     www      8889: # Remember Question Titles
                   8890: # FIXME: Possibly need delimiter other than ":"
                   8891:     for (my $i=0;$i<$number;$i++) {
                   8892:         $result.='<input type="hidden" name="question:'.$i.'" value="'.
                   8893:                  &HTML::Entities::encode($questiontitles[$i],'"&<>').'" />';
                   8894:     }
1.411     www      8895:     my $correct_count=0;
                   8896:     my $student_count=0;
                   8897:     my $unknown_count=0;
1.414     www      8898: # Match answers with usernames
                   8899: # FIXME: Possibly need delimiter other than ":"
1.409     albertel 8900:     foreach my $id (keys(%responses)) {
1.410     www      8901:        if ($correct_ids{$id}) {
1.414     www      8902:           $result.="\n".'<input type="hidden" name="correct:'.$correct_count.':'.$correct_ids{$id}.'" value="'.$responses{$id}.'" />';
1.411     www      8903:           $correct_count++;
1.410     www      8904:        } elsif ($clicker_ids{$id}) {
1.437     www      8905:           if ($clicker_ids{$id}=~/\,/) {
                   8906: # More than one user with the same clicker!
1.632     www      8907:              $result.="</td>".&Apache::loncommon::end_data_table_row().
                   8908:                            &Apache::loncommon::start_data_table_row()."<td>".
                   8909:                        &mt('Clicker registered more than once').": <tt>".$id."</tt><br />";
1.437     www      8910:              $result.="\n".'<input type="hidden" name="unknown:'.$id.'" value="'.$responses{$id}.'" />'.
                   8911:                            "<select name='multi".$id."'>";
                   8912:              foreach my $reguser (sort(split(/\,/,$clicker_ids{$id}))) {
                   8913:                  $result.="<option value='".$reguser."'>".&Apache::loncommon::plainname(split(/\:/,$reguser)).' ('.$reguser.')</option>';
                   8914:              }
                   8915:              $result.='</select>';
                   8916:              $unknown_count++;
                   8917:           } else {
                   8918: # Good: found one and only one user with the right clicker
                   8919:              $result.="\n".'<input type="hidden" name="student:'.$clicker_ids{$id}.'" value="'.$responses{$id}.'" />';
                   8920:              $student_count++;
                   8921:           }
1.410     www      8922:        } else {
1.632     www      8923:           $result.="</td>".&Apache::loncommon::end_data_table_row().
                   8924:                            &Apache::loncommon::start_data_table_row()."<td>".
                   8925:                     &mt('Unregistered Clicker')." <tt>".$id."</tt><br />";
1.411     www      8926:           $result.="\n".'<input type="hidden" name="unknown:'.$id.'" value="'.$responses{$id}.'" />'.
                   8927:                    "\n".&mt("Username").": <input type='text' name='uname".$id."' />&nbsp;".
                   8928:                    "\n".&mt("Domain").": ".
                   8929:                    &Apache::loncommon::select_dom_form($env{'course.'.$env{'request.course.id'}.'.domain'},'udom'.$id).'&nbsp;'.
                   8930:                    &Apache::loncommon::selectstudent_link('clickeranalysis','uname'.$id,'udom'.$id);
                   8931:           $unknown_count++;
1.410     www      8932:        }
1.405     www      8933:     }
1.412     www      8934:     $result.='<hr />'.
                   8935:              &mt('Found [_1] registered and [_2] unregistered clickers.',$student_count,$unknown_count);
1.521     www      8936:     if (($env{'form.gradingmechanism'} ne 'attendance') && ($env{'form.gradingmechanism'} ne 'given')) {
1.412     www      8937:        if ($correct_count==0) {
                   8938:           $errormsg.="Found no correct answers answers for grading!";
                   8939:        } elsif ($correct_count>1) {
1.414     www      8940:           $result.='<br /><span class="LC_warning">'.&mt("Found [_1] entries for grading!",$correct_count).'</span>';
1.412     www      8941:        }
                   8942:     }
1.428     www      8943:     if ($number<1) {
                   8944:        $errormsg.="Found no questions.";
                   8945:     }
1.412     www      8946:     if ($errormsg) {
                   8947:        $result.='<br /><span class="LC_error">'.&mt($errormsg).'</span>';
                   8948:     } else {
                   8949:        $result.='<br /><input type="submit" name="finalize" value="'.&mt('Finalize Grading').'" />';
                   8950:     }
1.632     www      8951:     $result.='</form></td>'.
                   8952:              &Apache::loncommon::end_data_table_row().
                   8953:              &Apache::loncommon::end_data_table();
1.614     www      8954:     return $result;
1.400     www      8955: }
                   8956: 
1.405     www      8957: sub iclicker_eval {
1.406     www      8958:     my ($questiontitles,$responses)=@_;
1.405     www      8959:     my $number=0;
                   8960:     my $errormsg='';
                   8961:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
1.410     www      8962:         my %components=&Apache::loncommon::record_sep($line);
                   8963:         my @entries=map {$components{$_}} (sort(keys(%components)));
1.408     albertel 8964: 	if ($entries[0] eq 'Question') {
                   8965: 	    for (my $i=3;$i<$#entries;$i+=6) {
                   8966: 		$$questiontitles[$number]=$entries[$i];
                   8967: 		$number++;
                   8968: 	    }
                   8969: 	}
                   8970: 	if ($entries[0]=~/^\#/) {
                   8971: 	    my $id=$entries[0];
                   8972: 	    my @idresponses;
                   8973: 	    $id=~s/^[\#0]+//;
                   8974: 	    for (my $i=0;$i<$number;$i++) {
                   8975: 		my $idx=3+$i*6;
                   8976: 		push(@idresponses,$entries[$idx]);
                   8977: 	    }
                   8978: 	    $$responses{$id}=join(',',@idresponses);
                   8979: 	}
1.405     www      8980:     }
                   8981:     return ($errormsg,$number);
                   8982: }
                   8983: 
1.419     www      8984: sub interwrite_eval {
                   8985:     my ($questiontitles,$responses)=@_;
                   8986:     my $number=0;
                   8987:     my $errormsg='';
1.420     www      8988:     my $skipline=1;
                   8989:     my $questionnumber=0;
                   8990:     my %idresponses=();
1.419     www      8991:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
                   8992:         my %components=&Apache::loncommon::record_sep($line);
                   8993:         my @entries=map {$components{$_}} (sort(keys(%components)));
1.420     www      8994:         if ($entries[1] eq 'Time') { $skipline=0; next; }
                   8995:         if ($entries[1] eq 'Response') { $skipline=1; }
                   8996:         next if $skipline;
                   8997:         if ($entries[0]!=$questionnumber) {
                   8998:            $questionnumber=$entries[0];
                   8999:            $$questiontitles[$number]=&mt('Question [_1]',$questionnumber);
                   9000:            $number++;
1.419     www      9001:         }
1.420     www      9002:         my $id=$entries[4];
                   9003:         $id=~s/^[\#0]+//;
1.421     www      9004:         $id=~s/^v\d*\://i;
                   9005:         $id=~s/[\-\:]//g;
1.420     www      9006:         $idresponses{$id}[$number]=$entries[6];
                   9007:     }
1.524     raeburn  9008:     foreach my $id (keys(%idresponses)) {
1.420     www      9009:        $$responses{$id}=join(',',@{$idresponses{$id}});
                   9010:        $$responses{$id}=~s/^\s*\,//;
1.419     www      9011:     }
                   9012:     return ($errormsg,$number);
                   9013: }
                   9014: 
1.414     www      9015: sub assign_clicker_grades {
1.608     www      9016:     my ($r,$symb)=@_;
1.414     www      9017:     if (!$symb) {return '';}
1.416     www      9018: # See which part we are saving to
1.582     raeburn  9019:     my $res_error;
                   9020:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
                   9021:     if ($res_error) {
                   9022:         return &navmap_errormsg();
                   9023:     }
1.416     www      9024: # FIXME: This should probably look for the first handgradeable part
                   9025:     my $part=$$partlist[0];
                   9026: # Start screen output
1.632     www      9027:     my $result=&Apache::loncommon::start_data_table().
                   9028:              &Apache::loncommon::start_data_table_header_row().
                   9029:              '<th>'.&mt('Assigning grades based on clicker file').'</th>'.
                   9030:              &Apache::loncommon::end_data_table_header_row().
                   9031:              &Apache::loncommon::start_data_table_row().'<td>';
1.414     www      9032: # Get correct result
                   9033: # FIXME: Possibly need delimiter other than ":"
                   9034:     my @correct=();
1.415     www      9035:     my $gradingmechanism=$env{'form.gradingmechanism'};
                   9036:     my $number=$env{'form.number'};
                   9037:     if ($gradingmechanism ne 'attendance') {
1.414     www      9038:        foreach my $key (keys(%env)) {
                   9039:           if ($key=~/^form\.correct\:/) {
                   9040:              my @input=split(/\,/,$env{$key});
                   9041:              for (my $i=0;$i<=$#input;$i++) {
                   9042:                  if (($correct[$i]) && ($input[$i]) &&
                   9043:                      ($correct[$i] ne $input[$i])) {
                   9044:                     $result.='<br /><span class="LC_warning">'.
                   9045:                              &mt('More than one correct result given for question "[_1]": [_2] versus [_3].',
                   9046:                                  $env{'form.question:'.$i},$correct[$i],$input[$i]).'</span>';
                   9047:                  } elsif ($input[$i]) {
                   9048:                     $correct[$i]=$input[$i];
                   9049:                  }
                   9050:              }
                   9051:           }
                   9052:        }
1.415     www      9053:        for (my $i=0;$i<$number;$i++) {
1.414     www      9054:           if (!$correct[$i]) {
                   9055:              $result.='<br /><span class="LC_error">'.
                   9056:                       &mt('No correct result given for question "[_1]"!',
                   9057:                           $env{'form.question:'.$i}).'</span>';
                   9058:           }
                   9059:        }
                   9060:        $result.='<br />'.&mt("Correct answer: [_1]",join(', ',map { ($_?$_:'-') } @correct));
                   9061:     }
                   9062: # Start grading
1.415     www      9063:     my $pcorrect=$env{'form.pcorrect'};
                   9064:     my $pincorrect=$env{'form.pincorrect'};
1.416     www      9065:     my $storecount=0;
1.632     www      9066:     my %users=();
1.415     www      9067:     foreach my $key (keys(%env)) {
1.420     www      9068:        my $user='';
1.415     www      9069:        if ($key=~/^form\.student\:(.*)$/) {
1.420     www      9070:           $user=$1;
                   9071:        }
                   9072:        if ($key=~/^form\.unknown\:(.*)$/) {
                   9073:           my $id=$1;
                   9074:           if (($env{'form.uname'.$id}) && ($env{'form.udom'.$id})) {
                   9075:              $user=$env{'form.uname'.$id}.':'.$env{'form.udom'.$id};
1.437     www      9076:           } elsif ($env{'form.multi'.$id}) {
                   9077:              $user=$env{'form.multi'.$id};
1.420     www      9078:           }
                   9079:        }
1.632     www      9080:        if ($user) {
                   9081:           if ($users{$user}) {
                   9082:              $result.='<br /><span class="LC_warning">'.
                   9083:                       &mt("More than one entry found for <tt>[_1]</tt>!",$user).
                   9084:                       '</span><br />';
                   9085:           }
                   9086:           $users{$user}=1; 
1.415     www      9087:           my @answer=split(/\,/,$env{$key});
                   9088:           my $sum=0;
1.522     www      9089:           my $realnumber=$number;
1.415     www      9090:           for (my $i=0;$i<$number;$i++) {
1.576     www      9091:              if  ($correct[$i] eq '-') {
                   9092:                 $realnumber--;
                   9093:              } elsif ($answer[$i]) {
1.415     www      9094:                 if ($gradingmechanism eq 'attendance') {
                   9095:                    $sum+=$pcorrect;
1.576     www      9096:                 } elsif ($correct[$i] eq '*') {
1.522     www      9097:                    $sum+=$pcorrect;
1.415     www      9098:                 } else {
                   9099:                    if ($answer[$i] eq $correct[$i]) {
                   9100:                       $sum+=$pcorrect;
                   9101:                    } else {
                   9102:                       $sum+=$pincorrect;
                   9103:                    }
                   9104:                 }
                   9105:              }
                   9106:           }
1.522     www      9107:           my $ave=$sum/(100*$realnumber);
1.416     www      9108: # Store
                   9109:           my ($username,$domain)=split(/\:/,$user);
                   9110:           my %grades=();
                   9111:           $grades{"resource.$part.solved"}='correct_by_override';
                   9112:           $grades{"resource.$part.awarded"}=$ave;
                   9113:           $grades{"resource.regrader"}="$env{'user.name'}:$env{'user.domain'}";
                   9114:           my $returncode=&Apache::lonnet::cstore(\%grades,$symb,
                   9115:                                                  $env{'request.course.id'},
                   9116:                                                  $domain,$username);
                   9117:           if ($returncode ne 'ok') {
                   9118:              $result.="<br /><span class=\"LC_error\">Failed to save student $username:$domain. Message when trying to save was ($returncode)</span>";
                   9119:           } else {
                   9120:              $storecount++;
                   9121:           }
1.415     www      9122:        }
                   9123:     }
                   9124: # We are done
1.549     hauer    9125:     $result.='<br />'.&mt('Successfully stored grades for [quant,_1,student].',$storecount).
1.632     www      9126:              '</td>'.
                   9127:              &Apache::loncommon::end_data_table_row().
                   9128:              &Apache::loncommon::end_data_table();
1.614     www      9129:     return $result;
1.414     www      9130: }
                   9131: 
1.582     raeburn  9132: sub navmap_errormsg {
                   9133:     return '<div class="LC_error">'.
                   9134:            &mt('An error occurred retrieving information about resources in the course.').'<br />'.
1.595     raeburn  9135:            &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  9136:            '</div>';
                   9137: }
1.607     droeschl 9138: 
1.609     www      9139: sub startpage {
1.613     www      9140:     my ($r,$symb,$crumbs,$onlyfolderflag,$nodisplayflag) = @_;
1.614     www      9141:     unshift(@$crumbs,{href=>&href_symb_cmd($symb,'gradingmenu'),text=>"Grading"});
1.607     droeschl 9142:     $r->print(&Apache::loncommon::start_page('Grading',undef,
1.610     www      9143:                                           {'bread_crumbs' => $crumbs}));
1.639   ! www      9144:     &Apache::lonquickgrades::startGradeScreen($r,'grading');
1.613     www      9145:     unless ($nodisplayflag) {
                   9146:        $r->print(&Apache::lonhtmlcommon::resource_info_box($symb,$onlyfolderflag));
                   9147:     }
1.607     droeschl 9148: }
1.582     raeburn  9149: 
1.622     www      9150: sub select_problem {
                   9151:     my ($r)=@_;
1.632     www      9152:     $r->print('<h3>'.&mt('Select the problem or one of the problems you want to grade').'</h3><form action="/adm/grades">');
1.622     www      9153:     $r->print(&Apache::lonstathelpers::problem_selector('.',undef,1));
                   9154:     $r->print('<input type="hidden" name="command" value="gradingmenu" />');
                   9155:     $r->print('<input type="submit" value="'.&mt('Next').' &rarr;" /></form>');
                   9156: }
                   9157: 
1.1       albertel 9158: sub handler {
1.41      ng       9159:     my $request=$_[0];
1.434     albertel 9160:     &reset_caches();
1.257     albertel 9161:     if ($env{'browser.mathml'}) {
1.141     www      9162: 	&Apache::loncommon::content_type($request,'text/xml');
1.41      ng       9163:     } else {
1.141     www      9164: 	&Apache::loncommon::content_type($request,'text/html');
1.41      ng       9165:     }
                   9166:     $request->send_http_header;
1.44      ng       9167:     return '' if $request->header_only;
1.41      ng       9168:     &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'});
1.608     www      9169: 
                   9170: # see what command we need to execute
                   9171: 
1.160     albertel 9172:     my @commands=&Apache::loncommon::get_env_multiple('form.command');
                   9173:     my $command=$commands[0];
1.447     foxr     9174: 
1.160     albertel 9175:     if ($#commands > 0) {
                   9176: 	&Apache::lonnet::logthis("grades got multiple commands ".join(':',@commands));
                   9177:     }
1.608     www      9178: 
                   9179: # see what the symb is
                   9180: 
                   9181:     my $symb=$env{'form.symb'};
                   9182:     unless ($symb) {
                   9183:        (my $url=$env{'form.url'}) =~ s-^https*://($ENV{'SERVER_NAME'}|$ENV{'HTTP_HOST'})--;
                   9184:        $symb=&Apache::lonnet::symbread($url);
                   9185:     }
                   9186:     &Apache::lonenc::check_decrypt(\$symb);                             
                   9187: 
1.513     foxr     9188:     $ssi_error = 0;
1.637     www      9189:     if (($symb eq '' || $command eq '') && ($env{'request.course.id'})) {
1.601     www      9190: #
1.637     www      9191: # Not called from a resource, but inside a course
1.601     www      9192: #    
1.622     www      9193:         &startpage($request,undef,[],1,1);
                   9194:         &select_problem($request);
1.41      ng       9195:     } else {
1.285     albertel 9196: 	&init_perm();
1.104     albertel 9197: 	if ($command eq 'submission' && $perm{'vgr'}) {
1.608     www      9198:             &startpage($request,$symb,[{href=>"", text=>"Student Submissions"}]);
1.611     www      9199: 	    ($env{'form.student'} eq '' ? &listStudents($request,$symb) : &submission($request,0,0,$symb));
1.103     albertel 9200: 	} elsif ($command eq 'pickStudentPage' && $perm{'vgr'}) {
1.615     www      9201:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,'all_for_one'),text=>'Grade page/folder for one student'},
                   9202:                                        {href=>'',text=>'Select student'}],1,1);
1.608     www      9203: 	    &pickStudentPage($request,$symb);
1.103     albertel 9204: 	} elsif ($command eq 'displayPage' && $perm{'vgr'}) {
1.615     www      9205:             &startpage($request,$symb,
                   9206:                                       [{href=>&href_symb_cmd($symb,'all_for_one'),text=>'Grade page/folder for one student'},
                   9207:                                        {href=>'',text=>'Select student'},
                   9208:                                        {href=>'',text=>'Grade student'}],1,1);
1.608     www      9209: 	    &displayPage($request,$symb);
1.104     albertel 9210: 	} elsif ($command eq 'gradeByPage' && $perm{'mgr'}) {
1.616     www      9211:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,'all_for_one'),text=>'Grade page/folder for one student'},
                   9212:                                        {href=>'',text=>'Select student'},
                   9213:                                        {href=>'',text=>'Grade student'},
                   9214:                                        {href=>'',text=>'Store grades'}],1,1);
1.608     www      9215: 	    &updateGradeByPage($request,$symb);
1.104     albertel 9216: 	} elsif ($command eq 'processGroup' && $perm{'vgr'}) {
1.619     www      9217:             &startpage($request,$symb,[{href=>'',text=>'...'},
                   9218:                                        {href=>'',text=>'Modify grades'}]);
1.608     www      9219: 	    &processGroup($request,$symb);
1.104     albertel 9220: 	} elsif ($command eq 'gradingmenu' && $perm{'vgr'}) {
1.608     www      9221:             &startpage($request,$symb);
                   9222: 	    $request->print(&grading_menu($request,$symb));
1.598     www      9223: 	} elsif ($command eq 'individual' && $perm{'vgr'}) {
1.617     www      9224:             &startpage($request,$symb,[{href=>'',text=>'Select individual students to grade'}]);
1.608     www      9225: 	    $request->print(&submit_options($request,$symb));
1.598     www      9226:         } elsif ($command eq 'ungraded' && $perm{'vgr'}) {
1.617     www      9227:             &startpage($request,$symb,[{href=>'',text=>'Grade ungraded submissions'}]);
                   9228:             $request->print(&listStudents($request,$symb,'graded'));
1.598     www      9229:         } elsif ($command eq 'table' && $perm{'vgr'}) {
1.614     www      9230:             &startpage($request,$symb,[{href=>"", text=>"Grading table"}]);
1.611     www      9231:             $request->print(&submit_options_table($request,$symb));
1.598     www      9232:         } elsif ($command eq 'all_for_one' && $perm{'vgr'}) {
1.615     www      9233:             &startpage($request,$symb,[{href=>'',text=>'Grade page/folder for one student'}],1,1);
1.608     www      9234:             $request->print(&submit_options_sequence($request,$symb));
1.104     albertel 9235: 	} elsif ($command eq 'viewgrades' && $perm{'vgr'}) {
1.614     www      9236:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,"table"), text=>"Grading table"},{href=>'', text=>"Modify grades"}]);
1.608     www      9237: 	    $request->print(&viewgrades($request,$symb));
1.104     albertel 9238: 	} elsif ($command eq 'handgrade' && $perm{'mgr'}) {
1.620     www      9239:             &startpage($request,$symb,[{href=>'',text=>'...'},
                   9240:                                        {href=>'',text=>'Store grades'}]);
1.608     www      9241: 	    $request->print(&processHandGrade($request,$symb));
1.106     albertel 9242: 	} elsif ($command eq 'editgrades' && $perm{'mgr'}) {
1.614     www      9243:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,"table"), text=>"Grading table"},
                   9244:                                        {href=>&href_symb_cmd($symb,'viewgrades').'&group=all&section=all&Status=Active',
                   9245:                                                                              text=>"Modify grades"},
                   9246:                                        {href=>'', text=>"Store grades"}]);
1.608     www      9247: 	    $request->print(&editgrades($request,$symb));
1.602     www      9248:         } elsif ($command eq 'initialverifyreceipt' && $perm{'vgr'}) {
1.616     www      9249:             &startpage($request,$symb,[{href=>'',text=>'Verify Receipt Number'}]);
1.611     www      9250:             $request->print(&initialverifyreceipt($request,$symb));
1.106     albertel 9251: 	} elsif ($command eq 'verify' && $perm{'vgr'}) {
1.616     www      9252:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,"initialverifyreceipt"),text=>'Verify Receipt Number'},
                   9253:                                        {href=>'',text=>'Verification Result'}]);
1.608     www      9254: 	    $request->print(&verifyreceipt($request,$symb));
1.400     www      9255:         } elsif ($command eq 'processclicker' && $perm{'mgr'}) {
1.615     www      9256:             &startpage($request,$symb,[{href=>'', text=>'Process clicker'}]);
1.608     www      9257:             $request->print(&process_clicker($request,$symb));
1.400     www      9258:         } elsif ($command eq 'processclickerfile' && $perm{'mgr'}) {
1.615     www      9259:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,'processclicker'), text=>'Process clicker'},
                   9260:                                        {href=>'', text=>'Process clicker file'}]);
1.608     www      9261:             $request->print(&process_clicker_file($request,$symb));
1.414     www      9262:         } elsif ($command eq 'assignclickergrades' && $perm{'mgr'}) {
1.615     www      9263:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,'processclicker'), text=>'Process clicker'},
                   9264:                                        {href=>'', text=>'Process clicker file'},
                   9265:                                        {href=>'', text=>'Store grades'}]);
1.608     www      9266:             $request->print(&assign_clicker_grades($request,$symb));
1.106     albertel 9267: 	} elsif ($command eq 'csvform' && $perm{'mgr'}) {
1.627     www      9268:             &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
1.608     www      9269: 	    $request->print(&upcsvScores_form($request,$symb));
1.106     albertel 9270: 	} elsif ($command eq 'csvupload' && $perm{'mgr'}) {
1.627     www      9271:             &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
1.608     www      9272: 	    $request->print(&csvupload($request,$symb));
1.106     albertel 9273: 	} elsif ($command eq 'csvuploadmap' && $perm{'mgr'} ) {
1.627     www      9274:             &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
1.608     www      9275: 	    $request->print(&csvuploadmap($request,$symb));
1.246     albertel 9276: 	} elsif ($command eq 'csvuploadoptions' && $perm{'mgr'}) {
1.257     albertel 9277: 	    if ($env{'form.associate'} ne 'Reverse Association') {
1.627     www      9278:                 &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
1.608     www      9279: 		$request->print(&csvuploadoptions($request,$symb));
1.41      ng       9280: 	    } else {
1.257     albertel 9281: 		if ( $env{'form.upfile_associate'} ne 'reverse' ) {
                   9282: 		    $env{'form.upfile_associate'} = 'reverse';
1.41      ng       9283: 		} else {
1.257     albertel 9284: 		    $env{'form.upfile_associate'} = 'forward';
1.41      ng       9285: 		}
1.627     www      9286:                 &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
1.608     www      9287: 		$request->print(&csvuploadmap($request,$symb));
1.41      ng       9288: 	    }
1.246     albertel 9289: 	} elsif ($command eq 'csvuploadassign' && $perm{'mgr'} ) {
1.627     www      9290:             &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
1.608     www      9291: 	    $request->print(&csvuploadassign($request,$symb));
1.106     albertel 9292: 	} elsif ($command eq 'scantron_selectphase' && $perm{'mgr'}) {
1.616     www      9293:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
1.612     www      9294: 	    $request->print(&scantron_selectphase($request,undef,$symb));
1.203     albertel 9295:  	} elsif ($command eq 'scantron_warning' && $perm{'mgr'}) {
1.616     www      9296:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
1.608     www      9297:  	    $request->print(&scantron_do_warning($request,$symb));
1.142     albertel 9298: 	} elsif ($command eq 'scantron_validate' && $perm{'mgr'}) {
1.616     www      9299:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
1.608     www      9300: 	    $request->print(&scantron_validate_file($request,$symb));
1.106     albertel 9301: 	} elsif ($command eq 'scantron_process' && $perm{'mgr'}) {
1.616     www      9302:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
1.608     www      9303: 	    $request->print(&scantron_process_students($request,$symb));
1.157     albertel 9304:  	} elsif ($command eq 'scantronupload' && 
1.257     albertel 9305:  		 (&Apache::lonnet::allowed('usc',$env{'request.role.domain'})||
                   9306: 		  &Apache::lonnet::allowed('usc',$env{'request.course.id'}))) {
1.616     www      9307:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
1.608     www      9308:  	    $request->print(&scantron_upload_scantron_data($request,$symb)); 
1.157     albertel 9309:  	} elsif ($command eq 'scantronupload_save' &&
1.257     albertel 9310:  		 (&Apache::lonnet::allowed('usc',$env{'request.role.domain'})||
                   9311: 		  &Apache::lonnet::allowed('usc',$env{'request.course.id'}))) {
1.616     www      9312:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
1.608     www      9313:  	    $request->print(&scantron_upload_scantron_data_save($request,$symb));
1.202     albertel 9314:  	} elsif ($command eq 'scantron_download' &&
1.257     albertel 9315: 		 &Apache::lonnet::allowed('usc',$env{'request.course.id'})) {
1.616     www      9316:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
1.608     www      9317:  	    $request->print(&scantron_download_scantron_data($request,$symb));
1.523     raeburn  9318:         } elsif ($command eq 'checksubmissions' && $perm{'vgr'}) {
1.616     www      9319:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
1.621     www      9320:             $request->print(&checkscantron_results($request,$symb));
                   9321:         } elsif ($command eq 'downloadfilesselect' && $perm{'vgr'}) {
                   9322:             &startpage($request,$symb,[{href=>'', text=>'Select which submissions to download'}]);
                   9323:             $request->print(&submit_options_download($request,$symb));
                   9324:          } elsif ($command eq 'downloadfileslink' && $perm{'vgr'}) {
                   9325:             &startpage($request,$symb,
                   9326:    [{href=>&href_symb_cmd($symb,'downloadfilesselect'), text=>'Select which submissions to download'},
                   9327:     {href=>'', text=>'Download submissions'}]);
                   9328:             &submit_download_link($request,$symb);
1.106     albertel 9329: 	} elsif ($command) {
1.620     www      9330:             &startpage($request,$symb,[{href=>'', text=>'Access denied'}]);
1.562     bisitz   9331: 	    $request->print('<p class="LC_error">'.&mt('Access Denied ([_1])',$command).'</p>');
1.26      albertel 9332: 	}
1.2       albertel 9333:     }
1.513     foxr     9334:     if ($ssi_error) {
                   9335: 	&ssi_print_error($request);
                   9336:     }
1.639   ! www      9337:     &Apache::lonquickgrades::endGradeScreen($request);
1.353     albertel 9338:     $request->print(&Apache::loncommon::end_page());
1.434     albertel 9339:     &reset_caches();
1.44      ng       9340:     return '';
                   9341: }
                   9342: 
1.1       albertel 9343: 1;
                   9344: 
1.13      albertel 9345: __END__;
1.531     jms      9346: 
                   9347: 
                   9348: =head1 NAME
                   9349: 
                   9350: Apache::grades
                   9351: 
                   9352: =head1 SYNOPSIS
                   9353: 
                   9354: Handles the viewing of grades.
                   9355: 
                   9356: This is part of the LearningOnline Network with CAPA project
                   9357: described at http://www.lon-capa.org.
                   9358: 
                   9359: =head1 OVERVIEW
                   9360: 
                   9361: Do an ssi with retries:
                   9362: While I'd love to factor out this with the vesrion in lonprintout,
                   9363: 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
                   9364: I'm not quite ready to invent (e.g. an ssi_with_retry object).
                   9365: 
                   9366: At least the logic that drives this has been pulled out into loncommon.
                   9367: 
                   9368: 
                   9369: 
                   9370: ssi_with_retries - Does the server side include of a resource.
                   9371:                      if the ssi call returns an error we'll retry it up to
                   9372:                      the number of times requested by the caller.
                   9373:                      If we still have a proble, no text is appended to the
                   9374:                      output and we set some global variables.
                   9375:                      to indicate to the caller an SSI error occurred.  
                   9376:                      All of this is supposed to deal with the issues described
                   9377:                      in LonCAPA BZ 5631 see:
                   9378:                      http://bugs.lon-capa.org/show_bug.cgi?id=5631
                   9379:                      by informing the user that this happened.
                   9380: 
                   9381: Parameters:
                   9382:   resource   - The resource to include.  This is passed directly, without
                   9383:                interpretation to lonnet::ssi.
                   9384:   form       - The form hash parameters that guide the interpretation of the resource
                   9385:                
                   9386:   retries    - Number of retries allowed before giving up completely.
                   9387: Returns:
                   9388:   On success, returns the rendered resource identified by the resource parameter.
                   9389: Side Effects:
                   9390:   The following global variables can be set:
                   9391:    ssi_error                - If an unrecoverable error occurred this becomes true.
                   9392:                               It is up to the caller to initialize this to false
                   9393:                               if desired.
                   9394:    ssi_error_resource  - If an unrecoverable error occurred, this is the value
                   9395:                               of the resource that could not be rendered by the ssi
                   9396:                               call.
                   9397:    ssi_error_message   - The error string fetched from the ssi response
                   9398:                               in the event of an error.
                   9399: 
                   9400: 
                   9401: =head1 HANDLER SUBROUTINE
                   9402: 
                   9403: ssi_with_retries()
                   9404: 
                   9405: =head1 SUBROUTINES
                   9406: 
                   9407: =over
                   9408: 
                   9409: =item scantron_get_correction() : 
                   9410: 
                   9411:    Builds the interface screen to interact with the operator to fix a
                   9412:    specific error condition in a specific scanline
                   9413: 
                   9414:  Arguments:
                   9415:     $r           - Apache request object
                   9416:     $i           - number of the current scanline
                   9417:     $scan_record - hash ref as returned from &scantron_parse_scanline()
                   9418:     $scan_config - hash ref as returned from &get_scantron_config()
                   9419:     $line        - full contents of the current scanline
                   9420:     $error       - error condition, valid values are
                   9421:                    'incorrectCODE', 'duplicateCODE',
                   9422:                    'doublebubble', 'missingbubble',
                   9423:                    'duplicateID', 'incorrectID'
                   9424:     $arg         - extra information needed
                   9425:        For errors:
                   9426:          - duplicateID   - paper number that this studentID was seen before on
                   9427:          - duplicateCODE - array ref of the paper numbers this CODE was
                   9428:                            seen on before
                   9429:          - incorrectCODE - current incorrect CODE 
                   9430:          - doublebubble  - array ref of the bubble lines that have double
                   9431:                            bubble errors
                   9432:          - missingbubble - array ref of the bubble lines that have missing
                   9433:                            bubble errors
                   9434: 
                   9435: =item  scantron_get_maxbubble() : 
                   9436: 
1.582     raeburn  9437:    Arguments:
                   9438:        $nav_error  - Reference to scalar which is a flag to indicate a
                   9439:                       failure to retrieve a navmap object.
                   9440:        if $nav_error is set to 1 by scantron_get_maxbubble(), the 
                   9441:        calling routine should trap the error condition and display the warning
                   9442:        found in &navmap_errormsg().
                   9443: 
1.531     jms      9444:    Returns the maximum number of bubble lines that are expected to
                   9445:    occur. Does this by walking the selected sequence rendering the
                   9446:    resource and then checking &Apache::lonxml::get_problem_counter()
                   9447:    for what the current value of the problem counter is.
                   9448: 
                   9449:    Caches the results to $env{'form.scantron_maxbubble'},
                   9450:    $env{'form.scantron.bubble_lines.n'}, 
                   9451:    $env{'form.scantron.first_bubble_line.n'} and
                   9452:    $env{"form.scantron.sub_bubblelines.n"}
                   9453:    which are the total number of bubble, lines, the number of bubble
                   9454:    lines for response n and number of the first bubble line for response n,
                   9455:    and a comma separated list of numbers of bubble lines for sub-questions
                   9456:    (for optionresponse, matchresponse, and rankresponse items), for response n.  
                   9457: 
                   9458: 
                   9459: =item  scantron_validate_missingbubbles() : 
                   9460: 
                   9461:    Validates all scanlines in the selected file to not have any
                   9462:     answers that don't have bubbles that have not been verified
                   9463:     to be bubble free.
                   9464: 
                   9465: =item  scantron_process_students() : 
                   9466: 
                   9467:    Routine that does the actual grading of the bubble sheet information.
                   9468: 
                   9469:    The parsed scanline hash is added to %env 
                   9470: 
                   9471:    Then foreach unskipped scanline it does an &Apache::lonnet::ssi()
                   9472:    foreach resource , with the form data of
                   9473: 
                   9474: 	'submitted'     =>'scantron' 
                   9475: 	'grade_target'  =>'grade',
                   9476: 	'grade_username'=> username of student
                   9477: 	'grade_domain'  => domain of student
                   9478: 	'grade_courseid'=> of course
                   9479: 	'grade_symb'    => symb of resource to grade
                   9480: 
                   9481:     This triggers a grading pass. The problem grading code takes care
                   9482:     of converting the bubbled letter information (now in %env) into a
                   9483:     valid submission.
                   9484: 
                   9485: =item  scantron_upload_scantron_data() :
                   9486: 
                   9487:     Creates the screen for adding a new bubble sheet data file to a course.
                   9488: 
                   9489: =item  scantron_upload_scantron_data_save() : 
                   9490: 
                   9491:    Adds a provided bubble information data file to the course if user
                   9492:    has the correct privileges to do so. 
                   9493: 
                   9494: =item  valid_file() :
                   9495: 
                   9496:    Validates that the requested bubble data file exists in the course.
                   9497: 
                   9498: =item  scantron_download_scantron_data() : 
                   9499: 
                   9500:    Shows a list of the three internal files (original, corrected,
                   9501:    skipped) for a specific bubble sheet data file that exists in the
                   9502:    course.
                   9503: 
                   9504: =item  scantron_validate_ID() : 
                   9505: 
                   9506:    Validates all scanlines in the selected file to not have any
1.556     weissno  9507:    invalid or underspecified student/employee IDs
1.531     jms      9508: 
1.582     raeburn  9509: =item navmap_errormsg() :
                   9510: 
                   9511:    Returns HTML mark-up inside a <div></div> with a link to re-initialize the course.
                   9512:    Should be called whenever the request to instantiate a navmap object fails.  
                   9513: 
1.531     jms      9514: =back
                   9515: 
                   9516: =cut

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