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

1.17      albertel    1: # The LearningOnline Network with CAPA
1.13      albertel    2: # The LON-CAPA Grading handler
1.17      albertel    3: #
1.622   ! www         4: # $Id: grades.pm,v 1.621 2010/04/17 16:38:38 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.170     albertel   47: use String::Similarity;
1.359     www        48: use LONCAPA;
                     49: 
1.315     bowersj2   50: use POSIX qw(floor);
1.87      www        51: 
1.435     foxr       52: 
1.513     foxr       53: 
1.435     foxr       54: my %perm=();
1.447     foxr       55: 
1.513     foxr       56: #  These variables are used to recover from ssi errors
                     57: 
                     58: my $ssi_retries = 5;
                     59: my $ssi_error;
                     60: my $ssi_error_resource;
                     61: my $ssi_error_message;
                     62: 
                     63: 
                     64: sub ssi_with_retries {
                     65:     my ($resource, $retries, %form) = @_;
                     66:     my ($content, $response) = &Apache::loncommon::ssi_with_retries($resource, $retries, %form);
                     67:     if ($response->is_error) {
                     68: 	$ssi_error          = 1;
                     69: 	$ssi_error_resource = $resource;
                     70: 	$ssi_error_message  = $response->code . " " . $response->message;
                     71:     }
                     72: 
                     73:     return $content;
                     74: 
                     75: }
                     76: #
                     77: #  Prodcuces an ssi retry failure error message to the user:
                     78: #
                     79: 
                     80: sub ssi_print_error {
                     81:     my ($r) = @_;
1.516     raeburn    82:     my $helpurl = &Apache::loncommon::top_nav_help('Helpdesk');
                     83:     $r->print('
                     84: <br />
                     85: <h2>'.&mt('An unrecoverable network error occurred:').'</h2>
                     86: <p>
                     87: '.&mt('Unable to retrieve a resource from a server:').'<br />
                     88: '.&mt('Resource:').' '.$ssi_error_resource.'<br />
                     89: '.&mt('Error:').' '.$ssi_error_message.'
                     90: </p>
                     91: <p>'.
                     92: &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 />'.
                     93: &mt('If the error persists, please contact the [_1] for assistance.',$helpurl).
                     94: '</p>');
                     95:     return;
1.513     foxr       96: }
                     97: 
1.44      ng         98: #
1.146     albertel   99: # --- Retrieve the parts from the metadata file.---
1.598     www       100: # Returns an array of everything that the resources stores away
                    101: #
                    102: 
1.44      ng        103: sub getpartlist {
1.582     raeburn   104:     my ($symb,$errorref) = @_;
1.439     albertel  105: 
                    106:     my $navmap   = Apache::lonnavmaps::navmap->new();
1.582     raeburn   107:     unless (ref($navmap)) {
                    108:         if (ref($errorref)) { 
                    109:             $$errorref = 'navmap';
                    110:             return;
                    111:         }
                    112:     }
1.439     albertel  113:     my $res      = $navmap->getBySymb($symb);
                    114:     my $partlist = $res->parts();
                    115:     my $url      = $res->src();
                    116:     my @metakeys = split(/,/,&Apache::lonnet::metadata($url,'keys'));
                    117: 
1.146     albertel  118:     my @stores;
1.439     albertel  119:     foreach my $part (@{ $partlist }) {
1.146     albertel  120: 	foreach my $key (@metakeys) {
                    121: 	    if ($key =~ m/^stores_\Q$part\E_/) { push(@stores,$key); }
                    122: 	}
                    123:     }
                    124:     return @stores;
1.2       albertel  125: }
                    126: 
1.129     ng        127: #--- Format fullname, username:domain if different for display
                    128: #--- Use anywhere where the student names are listed
                    129: sub nameUserString {
                    130:     my ($type,$fullname,$uname,$udom) = @_;
                    131:     if ($type eq 'header') {
1.485     albertel  132: 	return '<b>&nbsp;'.&mt('Fullname').'&nbsp;</b><span class="LC_internal_info">('.&mt('Username').')</span>';
1.129     ng        133:     } else {
1.398     albertel  134: 	return '&nbsp;'.$fullname.'<span class="LC_internal_info">&nbsp;('.$uname.
                    135: 	    ($env{'user.domain'} eq $udom ? '' : ' ('.$udom.')').')</span>';
1.129     ng        136:     }
                    137: }
                    138: 
1.44      ng        139: #--- Get the partlist and the response type for a given problem. ---
                    140: #--- Indicate if a response type is coded handgraded or not. ---
1.39      ng        141: sub response_type {
1.582     raeburn   142:     my ($symb,$response_error) = @_;
1.377     albertel  143: 
                    144:     my $navmap = Apache::lonnavmaps::navmap->new();
1.582     raeburn   145:     unless (ref($navmap)) {
                    146:         if (ref($response_error)) {
                    147:             $$response_error = 1;
                    148:         }
                    149:         return;
                    150:     }
1.377     albertel  151:     my $res = $navmap->getBySymb($symb);
1.593     raeburn   152:     unless (ref($res)) {
                    153:         $$response_error = 1;
                    154:         return;
                    155:     }
1.377     albertel  156:     my $partlist = $res->parts();
1.392     albertel  157:     my %vPart = 
                    158: 	map { $_ => 1 } (&Apache::loncommon::get_env_multiple('form.vPart'));
1.377     albertel  159:     my (%response_types,%handgrade);
                    160:     foreach my $part (@{ $partlist }) {
1.392     albertel  161: 	next if (%vPart && !exists($vPart{$part}));
                    162: 
1.377     albertel  163: 	my @types = $res->responseType($part);
                    164: 	my @ids = $res->responseIds($part);
                    165: 	for (my $i=0; $i < scalar(@ids); $i++) {
                    166: 	    $response_types{$part}{$ids[$i]} = $types[$i];
                    167: 	    $handgrade{$part.'_'.$ids[$i]} = 
                    168: 		&Apache::lonnet::EXT('resource.'.$part.'_'.$ids[$i].
                    169: 				     '.handgrade',$symb);
1.41      ng        170: 	}
                    171:     }
1.377     albertel  172:     return ($partlist,\%handgrade,\%response_types);
1.39      ng        173: }
                    174: 
1.375     albertel  175: sub flatten_responseType {
                    176:     my ($responseType) = @_;
                    177:     my @part_response_id =
                    178: 	map { 
                    179: 	    my $part = $_;
                    180: 	    map {
                    181: 		[$part,$_]
                    182: 		} sort(keys(%{ $responseType->{$part} }));
                    183: 	} sort(keys(%$responseType));
                    184:     return @part_response_id;
                    185: }
                    186: 
1.207     albertel  187: sub get_display_part {
1.324     albertel  188:     my ($partID,$symb)=@_;
1.207     albertel  189:     my $display=&Apache::lonnet::EXT('resource.'.$partID.'.display',$symb);
                    190:     if (defined($display) and $display ne '') {
1.577     bisitz    191:         $display.= ' (<span class="LC_internal_info">'
                    192:                   .&mt('Part ID: [_1]',$partID).'</span>)';
1.207     albertel  193:     } else {
                    194: 	$display=$partID;
                    195:     }
                    196:     return $display;
                    197: }
1.269     raeburn   198: 
1.434     albertel  199: sub reset_caches {
                    200:     &reset_analyze_cache();
                    201:     &reset_perm();
                    202: }
                    203: 
                    204: {
                    205:     my %analyze_cache;
1.557     raeburn   206:     my %analyze_cache_formkeys;
1.148     albertel  207: 
1.434     albertel  208:     sub reset_analyze_cache {
                    209: 	undef(%analyze_cache);
1.557     raeburn   210:         undef(%analyze_cache_formkeys);
1.434     albertel  211:     }
                    212: 
                    213:     sub get_analyze {
1.557     raeburn   214: 	my ($symb,$uname,$udom,$no_increment,$add_to_hash)=@_;
1.434     albertel  215: 	my $key = "$symb\0$uname\0$udom";
1.557     raeburn   216: 	if (exists($analyze_cache{$key})) {
                    217:             my $getupdate = 0;
                    218:             if (ref($add_to_hash) eq 'HASH') {
                    219:                 foreach my $item (keys(%{$add_to_hash})) {
                    220:                     if (ref($analyze_cache_formkeys{$key}) eq 'HASH') {
                    221:                         if (!exists($analyze_cache_formkeys{$key}{$item})) {
                    222:                             $getupdate = 1;
                    223:                             last;
                    224:                         }
                    225:                     } else {
                    226:                         $getupdate = 1;
                    227:                     }
                    228:                 }
                    229:             }
                    230:             if (!$getupdate) {
                    231:                 return $analyze_cache{$key};
                    232:             }
                    233:         }
1.434     albertel  234: 
                    235: 	my (undef,undef,$url)=&Apache::lonnet::decode_symb($symb);
                    236: 	$url=&Apache::lonnet::clutter($url);
1.557     raeburn   237:         my %form = ('grade_target'      => 'analyze',
                    238:                     'grade_domain'      => $udom,
                    239:                     'grade_symb'        => $symb,
                    240:                     'grade_courseid'    =>  $env{'request.course.id'},
                    241:                     'grade_username'    => $uname,
                    242:                     'grade_noincrement' => $no_increment);
                    243:         if (ref($add_to_hash)) {
                    244:             %form = (%form,%{$add_to_hash});
                    245:         } 
                    246: 	my $subresult=&ssi_with_retries($url, $ssi_retries,%form);
1.434     albertel  247: 	(undef,$subresult)=split(/_HASH_REF__/,$subresult,2);
                    248: 	my %analyze=&Apache::lonnet::str2hash($subresult);
1.557     raeburn   249:         if (ref($add_to_hash) eq 'HASH') {
                    250:             $analyze_cache_formkeys{$key} = $add_to_hash;
                    251:         } else {
                    252:             $analyze_cache_formkeys{$key} = {};
                    253:         }
1.434     albertel  254: 	return $analyze_cache{$key} = \%analyze;
                    255:     }
                    256: 
                    257:     sub get_order {
1.525     raeburn   258: 	my ($partid,$respid,$symb,$uname,$udom,$no_increment)=@_;
                    259: 	my $analyze = &get_analyze($symb,$uname,$udom,$no_increment);
1.434     albertel  260: 	return $analyze->{"$partid.$respid.shown"};
                    261:     }
                    262: 
                    263:     sub get_radiobutton_correct_foil {
                    264: 	my ($partid,$respid,$symb,$uname,$udom)=@_;
                    265: 	my $analyze = &get_analyze($symb,$uname,$udom);
1.555     raeburn   266:         my $foils = &get_order($partid,$respid,$symb,$uname,$udom);
                    267:         if (ref($foils) eq 'ARRAY') {
                    268: 	    foreach my $foil (@{$foils}) {
                    269: 	        if ($analyze->{"$partid.$respid.foil.value.$foil"} eq 'true') {
                    270: 		    return $foil;
                    271: 	        }
1.434     albertel  272: 	    }
                    273: 	}
                    274:     }
1.554     raeburn   275: 
                    276:     sub scantron_partids_tograde {
1.557     raeburn   277:         my ($resource,$cid,$uname,$udom,$check_for_randomlist) = @_;
1.554     raeburn   278:         my (%analysis,@parts);
                    279:         if (ref($resource)) {
                    280:             my $symb = $resource->symb();
1.557     raeburn   281:             my $add_to_form;
                    282:             if ($check_for_randomlist) {
                    283:                 $add_to_form = { 'check_parts_withrandomlist' => 1,};
                    284:             }
                    285:             my $analyze = &get_analyze($symb,$uname,$udom,undef,$add_to_form);
1.554     raeburn   286:             if (ref($analyze) eq 'HASH') {
                    287:                 %analysis = %{$analyze};
                    288:             }
                    289:             if (ref($analysis{'parts'}) eq 'ARRAY') {
                    290:                 foreach my $part (@{$analysis{'parts'}}) {
                    291:                     my ($id,$respid) = split(/\./,$part);
                    292:                     if (!&Apache::loncommon::check_if_partid_hidden($id,$symb,$udom,$uname)) {
                    293:                         push(@parts,$part);
                    294:                     }
                    295:                 }
                    296:             }
                    297:         }
                    298:         return (\%analysis,\@parts);
                    299:     }
                    300: 
1.148     albertel  301: }
1.434     albertel  302: 
1.118     ng        303: #--- Clean response type for display
1.335     albertel  304: #--- Currently filters option/rank/radiobutton/match/essay/Task
                    305: #        response types only.
1.118     ng        306: sub cleanRecord {
1.336     albertel  307:     my ($answer,$response,$symb,$partid,$respid,$record,$order,$version,
                    308: 	$uname,$udom) = @_;
1.398     albertel  309:     my $grayFont = '<span class="LC_internal_info">';
1.148     albertel  310:     if ($response =~ /^(option|rank)$/) {
                    311: 	my %answer=&Apache::lonnet::str2hash($answer);
                    312: 	my %grading=&Apache::lonnet::str2hash($record->{$version."resource.$partid.$respid.submissiongrading"});
                    313: 	my ($toprow,$bottomrow);
                    314: 	foreach my $foil (@$order) {
                    315: 	    if ($grading{$foil} == 1) {
                    316: 		$toprow.='<td><b>'.$answer{$foil}.'&nbsp;</b></td>';
                    317: 	    } else {
                    318: 		$toprow.='<td><i>'.$answer{$foil}.'&nbsp;</i></td>';
                    319: 	    }
1.398     albertel  320: 	    $bottomrow.='<td>'.$grayFont.$foil.'</span>&nbsp;</td>';
1.148     albertel  321: 	}
                    322: 	return '<blockquote><table border="1">'.
1.466     albertel  323: 	    '<tr valign="top"><td>'.&mt('Answer').'</td>'.$toprow.'</tr>'.
                    324: 	    '<tr valign="top"><td>'.$grayFont.&mt('Option ID').'</span></td>'.
1.148     albertel  325: 	    $grayFont.$bottomrow.'</tr>'.'</table></blockquote>';
                    326:     } elsif ($response eq 'match') {
                    327: 	my %answer=&Apache::lonnet::str2hash($answer);
                    328: 	my %grading=&Apache::lonnet::str2hash($record->{$version."resource.$partid.$respid.submissiongrading"});
                    329: 	my @items=&Apache::lonnet::str2array($record->{$version."resource.$partid.$respid.submissionitems"});
                    330: 	my ($toprow,$middlerow,$bottomrow);
                    331: 	foreach my $foil (@$order) {
                    332: 	    my $item=shift(@items);
                    333: 	    if ($grading{$foil} == 1) {
                    334: 		$toprow.='<td><b>'.$item.'&nbsp;</b></td>';
1.398     albertel  335: 		$middlerow.='<td><b>'.$grayFont.$answer{$foil}.'&nbsp;</span></b></td>';
1.148     albertel  336: 	    } else {
                    337: 		$toprow.='<td><i>'.$item.'&nbsp;</i></td>';
1.398     albertel  338: 		$middlerow.='<td><i>'.$grayFont.$answer{$foil}.'&nbsp;</span></i></td>';
1.148     albertel  339: 	    }
1.398     albertel  340: 	    $bottomrow.='<td>'.$grayFont.$foil.'</span>&nbsp;</td>';
1.118     ng        341: 	}
1.126     ng        342: 	return '<blockquote><table border="1">'.
1.466     albertel  343: 	    '<tr valign="top"><td>'.&mt('Answer').'</td>'.$toprow.'</tr>'.
                    344: 	    '<tr valign="top"><td>'.$grayFont.&mt('Item ID').'</span></td>'.
1.148     albertel  345: 	    $middlerow.'</tr>'.
1.466     albertel  346: 	    '<tr valign="top"><td>'.$grayFont.&mt('Option ID').'</span></td>'.
1.148     albertel  347: 	    $bottomrow.'</tr>'.'</table></blockquote>';
                    348:     } elsif ($response eq 'radiobutton') {
                    349: 	my %answer=&Apache::lonnet::str2hash($answer);
                    350: 	my ($toprow,$bottomrow);
1.434     albertel  351: 	my $correct = 
                    352: 	    &get_radiobutton_correct_foil($partid,$respid,$symb,$uname,$udom);
                    353: 	foreach my $foil (@$order) {
1.148     albertel  354: 	    if (exists($answer{$foil})) {
1.434     albertel  355: 		if ($foil eq $correct) {
1.466     albertel  356: 		    $toprow.='<td><b>'.&mt('true').'</b></td>';
1.148     albertel  357: 		} else {
1.466     albertel  358: 		    $toprow.='<td><i>'.&mt('true').'</i></td>';
1.148     albertel  359: 		}
                    360: 	    } else {
1.466     albertel  361: 		$toprow.='<td>'.&mt('false').'</td>';
1.148     albertel  362: 	    }
1.398     albertel  363: 	    $bottomrow.='<td>'.$grayFont.$foil.'</span>&nbsp;</td>';
1.148     albertel  364: 	}
                    365: 	return '<blockquote><table border="1">'.
1.466     albertel  366: 	    '<tr valign="top"><td>'.&mt('Answer').'</td>'.$toprow.'</tr>'.
                    367: 	    '<tr valign="top"><td>'.$grayFont.&mt('Option ID').'</span></td>'.
1.597     wenzelju  368: 	    $bottomrow.'</tr>'.'</table></blockquote>';
1.148     albertel  369:     } elsif ($response eq 'essay') {
1.257     albertel  370: 	if (! exists ($env{'form.'.$symb})) {
1.122     ng        371: 	    my (%keyhash) = &Apache::lonnet::dump('nohist_handgrade',
1.257     albertel  372: 						  $env{'course.'.$env{'request.course.id'}.'.domain'},
                    373: 						  $env{'course.'.$env{'request.course.id'}.'.num'});
1.122     ng        374: 
1.257     albertel  375: 	    my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
                    376: 	    $env{'form.keywords'} = $keyhash{$symb.'_keywords'} ne '' ? $keyhash{$symb.'_keywords'} : '';
                    377: 	    $env{'form.kwclr'}    = $keyhash{$loginuser.'_kwclr'} ne '' ? $keyhash{$loginuser.'_kwclr'} : 'red';
                    378: 	    $env{'form.kwsize'}   = $keyhash{$loginuser.'_kwsize'} ne '' ? $keyhash{$loginuser.'_kwsize'} : '0';
                    379: 	    $env{'form.kwstyle'}  = $keyhash{$loginuser.'_kwstyle'} ne '' ? $keyhash{$loginuser.'_kwstyle'} : '';
                    380: 	    $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        381: 	}
1.166     albertel  382: 	$answer =~ s-\n-<br />-g;
                    383: 	return '<br /><br /><blockquote><tt>'.&keywords_highlight($answer).'</tt></blockquote>';
1.268     albertel  384:     } elsif ( $response eq 'organic') {
                    385: 	my $result='Smile representation: "<tt>'.$answer.'</tt>"';
                    386: 	my $jme=$record->{$version."resource.$partid.$respid.molecule"};
                    387: 	$result.=&Apache::chemresponse::jme_img($jme,$answer,400);
                    388: 	return $result;
1.335     albertel  389:     } elsif ( $response eq 'Task') {
                    390: 	if ( $answer eq 'SUBMITTED') {
                    391: 	    my $files = $record->{$version."resource.$respid.$partid.bridgetask.portfiles"};
1.336     albertel  392: 	    my $result = &Apache::bridgetask::file_list($files,$uname,$udom);
1.335     albertel  393: 	    return $result;
                    394: 	} elsif ( grep(/^\Q$version\E.*?\.instance$/, keys(%{$record})) ) {
                    395: 	    my @matches = grep(/^\Q$version\E.*?\.instance$/,
                    396: 			       keys(%{$record}));
                    397: 	    return join('<br />',($version,@matches));
                    398: 			       
                    399: 			       
                    400: 	} else {
                    401: 	    my $result =
                    402: 		'<p>'
                    403: 		.&mt('Overall result: [_1]',
                    404: 		     $record->{$version."resource.$respid.$partid.status"})
                    405: 		.'</p>';
                    406: 	    
                    407: 	    $result .= '<ul>';
                    408: 	    my @grade = grep(/^\Q${version}resource.$respid.$partid.\E[^.]*[.]status$/,
                    409: 			     keys(%{$record}));
                    410: 	    foreach my $grade (sort(@grade)) {
                    411: 		my ($dim) = ($grade =~/[.]([^.]+)[.]status$/);
                    412: 		$result.= '<li>'.&mt("Dimension: [_1], status [_2] ",
                    413: 				     $dim, $record->{$grade}).
                    414: 			  '</li>';
                    415: 	    }
                    416: 	    $result.='</ul>';
                    417: 	    return $result;
                    418: 	}
1.440     albertel  419:     } elsif ( $response =~ m/(?:numerical|formula)/) {
                    420: 	$answer = 
                    421: 	    &Apache::loncommon::format_previous_attempt_value('submission',
                    422: 							      $answer);
1.122     ng        423:     }
1.118     ng        424:     return $answer;
                    425: }
                    426: 
                    427: #-- A couple of common js functions
                    428: sub commonJSfunctions {
                    429:     my $request = shift;
1.597     wenzelju  430:     $request->print(&Apache::lonhtmlcommon::scripttag(<<COMMONJSFUNCTIONS));
1.118     ng        431:     function radioSelection(radioButton) {
                    432: 	var selection=null;
                    433: 	if (radioButton.length > 1) {
                    434: 	    for (var i=0; i<radioButton.length; i++) {
                    435: 		if (radioButton[i].checked) {
                    436: 		    return radioButton[i].value;
                    437: 		}
                    438: 	    }
                    439: 	} else {
                    440: 	    if (radioButton.checked) return radioButton.value;
                    441: 	}
                    442: 	return selection;
                    443:     }
                    444: 
                    445:     function pullDownSelection(selectOne) {
                    446: 	var selection="";
                    447: 	if (selectOne.length > 1) {
                    448: 	    for (var i=0; i<selectOne.length; i++) {
                    449: 		if (selectOne[i].selected) {
                    450: 		    return selectOne[i].value;
                    451: 		}
                    452: 	    }
                    453: 	} else {
1.138     albertel  454:             // only one value it must be the selected one
                    455: 	    return selectOne.value;
1.118     ng        456: 	}
                    457:     }
                    458: COMMONJSFUNCTIONS
                    459: }
                    460: 
1.44      ng        461: #--- Dumps the class list with usernames,list of sections,
                    462: #--- section, ids and fullnames for each user.
                    463: sub getclasslist {
1.449     banghart  464:     my ($getsec,$filterlist,$getgroup) = @_;
1.291     albertel  465:     my @getsec;
1.450     banghart  466:     my @getgroup;
1.442     banghart  467:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
1.291     albertel  468:     if (!ref($getsec)) {
                    469: 	if ($getsec ne '' && $getsec ne 'all') {
                    470: 	    @getsec=($getsec);
                    471: 	}
                    472:     } else {
                    473: 	@getsec=@{$getsec};
                    474:     }
                    475:     if (grep(/^all$/,@getsec)) { undef(@getsec); }
1.450     banghart  476:     if (!ref($getgroup)) {
                    477: 	if ($getgroup ne '' && $getgroup ne 'all') {
                    478: 	    @getgroup=($getgroup);
                    479: 	}
                    480:     } else {
                    481: 	@getgroup=@{$getgroup};
                    482:     }
                    483:     if (grep(/^all$/,@getgroup)) { undef(@getgroup); }
1.291     albertel  484: 
1.449     banghart  485:     my ($classlist,$keylist)=&Apache::loncoursedata::get_classlist();
1.49      albertel  486:     # Bail out if we were unable to get the classlist
1.56      matthew   487:     return if (! defined($classlist));
1.449     banghart  488:     &Apache::loncoursedata::get_group_memberships($classlist,$keylist);
1.56      matthew   489:     #
                    490:     my %sections;
                    491:     my %fullnames;
1.205     matthew   492:     foreach my $student (keys(%$classlist)) {
                    493:         my $end      = 
                    494:             $classlist->{$student}->[&Apache::loncoursedata::CL_END()];
                    495:         my $start    = 
                    496:             $classlist->{$student}->[&Apache::loncoursedata::CL_START()];
                    497:         my $id       = 
                    498:             $classlist->{$student}->[&Apache::loncoursedata::CL_ID()];
                    499:         my $section  = 
                    500:             $classlist->{$student}->[&Apache::loncoursedata::CL_SECTION()];
                    501:         my $fullname = 
                    502:             $classlist->{$student}->[&Apache::loncoursedata::CL_FULLNAME()];
                    503:         my $status   = 
                    504:             $classlist->{$student}->[&Apache::loncoursedata::CL_STATUS()];
1.449     banghart  505:         my $group   = 
                    506:             $classlist->{$student}->[&Apache::loncoursedata::CL_GROUP()];
1.76      ng        507: 	# filter students according to status selected
1.442     banghart  508: 	if ($filterlist && (!($stu_status =~ /Any/))) {
                    509: 	    if (!($stu_status =~ $status)) {
1.450     banghart  510: 		delete($classlist->{$student});
1.76      ng        511: 		next;
                    512: 	    }
                    513: 	}
1.450     banghart  514: 	# filter students according to groups selected
1.453     banghart  515: 	my @stu_groups = split(/,/,$group);
1.450     banghart  516: 	if (@getgroup) {
                    517: 	    my $exclude = 1;
1.454     banghart  518: 	    foreach my $grp (@getgroup) {
                    519: 	        foreach my $stu_group (@stu_groups) {
1.453     banghart  520: 	            if ($stu_group eq $grp) {
                    521: 	                $exclude = 0;
                    522:     	            } 
1.450     banghart  523: 	        }
1.453     banghart  524:     	        if (($grp eq 'none') && !$group) {
                    525:         	        $exclude = 0;
                    526:         	}
1.450     banghart  527: 	    }
                    528: 	    if ($exclude) {
                    529: 	        delete($classlist->{$student});
                    530: 	    }
                    531: 	}
1.205     matthew   532: 	$section = ($section ne '' ? $section : 'none');
1.106     albertel  533: 	if (&canview($section)) {
1.291     albertel  534: 	    if (!@getsec || grep(/^\Q$section\E$/,@getsec)) {
1.103     albertel  535: 		$sections{$section}++;
1.450     banghart  536: 		if ($classlist->{$student}) {
                    537: 		    $fullnames{$student}=$fullname;
                    538: 		}
1.103     albertel  539: 	    } else {
1.205     matthew   540: 		delete($classlist->{$student});
1.103     albertel  541: 	    }
                    542: 	} else {
1.205     matthew   543: 	    delete($classlist->{$student});
1.103     albertel  544: 	}
1.44      ng        545:     }
                    546:     my %seen = ();
1.56      matthew   547:     my @sections = sort(keys(%sections));
                    548:     return ($classlist,\@sections,\%fullnames);
1.44      ng        549: }
                    550: 
1.103     albertel  551: sub canmodify {
                    552:     my ($sec)=@_;
                    553:     if ($perm{'mgr'}) {
                    554: 	if (!defined($perm{'mgr_section'})) {
                    555: 	    # can modify whole class
                    556: 	    return 1;
                    557: 	} else {
                    558: 	    if ($sec eq $perm{'mgr_section'}) {
                    559: 		#can modify the requested section
                    560: 		return 1;
                    561: 	    } else {
                    562: 		# can't modify the request section
                    563: 		return 0;
                    564: 	    }
                    565: 	}
                    566:     }
                    567:     #can't modify
                    568:     return 0;
                    569: }
                    570: 
                    571: sub canview {
                    572:     my ($sec)=@_;
                    573:     if ($perm{'vgr'}) {
                    574: 	if (!defined($perm{'vgr_section'})) {
                    575: 	    # can modify whole class
                    576: 	    return 1;
                    577: 	} else {
                    578: 	    if ($sec eq $perm{'vgr_section'}) {
                    579: 		#can modify the requested section
                    580: 		return 1;
                    581: 	    } else {
                    582: 		# can't modify the request section
                    583: 		return 0;
                    584: 	    }
                    585: 	}
                    586:     }
                    587:     #can't modify
                    588:     return 0;
                    589: }
                    590: 
1.44      ng        591: #--- Retrieve the grade status of a student for all the parts
                    592: sub student_gradeStatus {
1.324     albertel  593:     my ($symb,$udom,$uname,$partlist) = @_;
1.257     albertel  594:     my %record     = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
1.44      ng        595:     my %partstatus = ();
                    596:     foreach (@$partlist) {
1.128     ng        597: 	my ($status,undef)   = split(/_/,$record{"resource.$_.solved"},2);
1.44      ng        598: 	$status              = 'nothing' if ($status eq '');
                    599: 	$partstatus{$_}      = $status;
                    600: 	my $subkey           = "resource.$_.submitted_by";
                    601: 	$partstatus{$subkey} = $record{$subkey} if ($record{$subkey} ne '');
                    602:     }
                    603:     return %partstatus;
                    604: }
                    605: 
1.45      ng        606: # hidden form and javascript that calls the form
                    607: # Use by verifyscript and viewgrades
                    608: # Shows a student's view of problem and submission
                    609: sub jscriptNform {
1.324     albertel  610:     my ($symb) = @_;
1.442     banghart  611:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
1.597     wenzelju  612:     my $jscript= &Apache::lonhtmlcommon::scripttag(
1.45      ng        613: 	'    function viewOneStudent(user,domain) {'."\n".
                    614: 	'	document.onestudent.student.value = user;'."\n".
                    615: 	'	document.onestudent.userdom.value = domain;'."\n".
                    616: 	'	document.onestudent.submit();'."\n".
                    617: 	'    }'."\n".
1.597     wenzelju  618: 	"\n");
1.45      ng        619:     $jscript.= '<form action="/adm/grades" method="post" name="onestudent">'."\n".
1.418     albertel  620: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.442     banghart  621: 	'<input type="hidden" name="Status"  value="'.$stu_status.'" />'."\n".
1.45      ng        622: 	'<input type="hidden" name="command" value="submission" />'."\n".
                    623: 	'<input type="hidden" name="student" value="" />'."\n".
                    624: 	'<input type="hidden" name="userdom" value="" />'."\n".
                    625: 	'</form>'."\n";
                    626:     return $jscript;
                    627: }
1.39      ng        628: 
1.447     foxr      629: 
                    630: 
1.315     bowersj2  631: # Given the score (as a number [0-1] and the weight) what is the final
                    632: # point value? This function will round to the nearest tenth, third,
                    633: # or quarter if one of those is within the tolerance of .00001.
1.316     albertel  634: sub compute_points {
1.315     bowersj2  635:     my ($score, $weight) = @_;
                    636:     
                    637:     my $tolerance = .00001;
                    638:     my $points = $score * $weight;
                    639: 
                    640:     # Check for nearness to 1/x.
                    641:     my $check_for_nearness = sub {
                    642:         my ($factor) = @_;
                    643:         my $num = ($points * $factor) + $tolerance;
                    644:         my $floored_num = floor($num);
1.316     albertel  645:         if ($num - $floored_num < 2 * $tolerance * $factor) {
1.315     bowersj2  646:             return $floored_num / $factor;
                    647:         }
                    648:         return $points;
                    649:     };
                    650: 
                    651:     $points = $check_for_nearness->(10);
                    652:     $points = $check_for_nearness->(3);
                    653:     $points = $check_for_nearness->(4);
                    654:     
                    655:     return $points;
                    656: }
                    657: 
1.44      ng        658: #------------------ End of general use routines --------------------
1.87      www       659: 
                    660: #
                    661: # Find most similar essay
                    662: #
                    663: 
                    664: sub most_similar {
1.426     albertel  665:     my ($uname,$udom,$uessay,$old_essays)=@_;
1.87      www       666: 
                    667: # ignore spaces and punctuation
                    668: 
                    669:     $uessay=~s/\W+/ /gs;
                    670: 
1.282     www       671: # ignore empty submissions (occuring when only files are sent)
                    672: 
1.598     www       673:     unless ($uessay=~/\w+/s) { return ''; }
1.282     www       674: 
1.87      www       675: # these will be returned. Do not care if not at least 50 percent similar
1.88      www       676:     my $limit=0.6;
1.87      www       677:     my $sname='';
                    678:     my $sdom='';
                    679:     my $scrsid='';
                    680:     my $sessay='';
                    681: # go through all essays ...
1.426     albertel  682:     foreach my $tkey (keys(%$old_essays)) {
                    683: 	my ($tname,$tdom,$tcrsid)=map {&unescape($_)} (split(/\./,$tkey));
1.87      www       684: # ... except the same student
1.426     albertel  685:         next if (($tname eq $uname) && ($tdom eq $udom));
                    686: 	my $tessay=$old_essays->{$tkey};
                    687: 	$tessay=~s/\W+/ /gs;
1.87      www       688: # String similarity gives up if not even limit
1.426     albertel  689: 	my $tsimilar=&String::Similarity::similarity($uessay,$tessay,$limit);
1.87      www       690: # Found one
1.426     albertel  691: 	if ($tsimilar>$limit) {
                    692: 	    $limit=$tsimilar;
                    693: 	    $sname=$tname;
                    694: 	    $sdom=$tdom;
                    695: 	    $scrsid=$tcrsid;
                    696: 	    $sessay=$old_essays->{$tkey};
                    697: 	}
1.87      www       698:     }
1.88      www       699:     if ($limit>0.6) {
1.87      www       700:        return ($sname,$sdom,$scrsid,$sessay,$limit);
                    701:     } else {
                    702:        return ('','','','',0);
                    703:     }
                    704: }
                    705: 
1.44      ng        706: #-------------------------------------------------------------------
                    707: 
                    708: #------------------------------------ Receipt Verification Routines
1.45      ng        709: #
1.602     www       710: 
                    711: sub initialverifyreceipt {
1.608     www       712:    my ($request,$symb) = @_;
1.602     www       713:    &commonJSfunctions($request);
1.605     www       714:    return '<form name="gradingMenu"><input type="submit" value="'.&mt('Verify Receipt Number.').'" />'.
1.602     www       715:         &Apache::lonnet::recprefix($env{'request.course.id'}).
                    716:         '-<input type="text" name="receipt" size="4" />'.
1.603     www       717:         '<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
                    718:         '<input type="hidden" name="command" value="verify" />'.
                    719:         "</form>\n";
1.602     www       720: }
                    721: 
1.44      ng        722: #--- Check whether a receipt number is valid.---
                    723: sub verifyreceipt {
1.608     www       724:     my ($request,$symb)  = @_;
1.44      ng        725: 
1.257     albertel  726:     my $courseid = $env{'request.course.id'};
1.184     www       727:     my $receipt  = &Apache::lonnet::recprefix($courseid).'-'.
1.257     albertel  728: 	$env{'form.receipt'};
1.44      ng        729:     $receipt     =~ s/[^\-\d]//g;
                    730: 
1.487     albertel  731:     my $title.=
                    732: 	'<h3><span class="LC_info">'.
1.605     www       733: 	&mt('Verifying Receipt Number [_1]',$receipt).
                    734: 	'</span></h3>'."\n";
1.44      ng        735: 
                    736:     my ($string,$contents,$matches) = ('','',0);
1.56      matthew   737:     my (undef,undef,$fullname) = &getclasslist('all','0');
1.177     albertel  738:     
                    739:     my $receiptparts=0;
1.390     albertel  740:     if ($env{"course.$courseid.receiptalg"} eq 'receipt2' ||
                    741: 	$env{"course.$courseid.receiptalg"} eq 'receipt3') { $receiptparts=1; }
1.177     albertel  742:     my $parts=['0'];
1.582     raeburn   743:     if ($receiptparts) {
                    744:         my $res_error; 
                    745:         ($parts)=&response_type($symb,\$res_error);
                    746:         if ($res_error) {
                    747:             return &navmap_errormsg();
                    748:         } 
                    749:     }
1.486     albertel  750:     
                    751:     my $header = 
                    752: 	&Apache::loncommon::start_data_table().
                    753: 	&Apache::loncommon::start_data_table_header_row().
1.487     albertel  754: 	'<th>&nbsp;'.&mt('Fullname').'&nbsp;</th>'."\n".
                    755: 	'<th>&nbsp;'.&mt('Username').'&nbsp;</th>'."\n".
                    756: 	'<th>&nbsp;'.&mt('Domain').'&nbsp;</th>';
1.486     albertel  757:     if ($receiptparts) {
1.487     albertel  758: 	$header.='<th>&nbsp;'.&mt('Problem Part').'&nbsp;</th>';
1.486     albertel  759:     }
                    760:     $header.=
                    761: 	&Apache::loncommon::end_data_table_header_row();
                    762: 
1.294     albertel  763:     foreach (sort 
                    764: 	     {
                    765: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                    766: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                    767: 		 }
                    768: 		 return $a cmp $b;
                    769: 	     } (keys(%$fullname))) {
1.44      ng        770: 	my ($uname,$udom)=split(/\:/);
1.177     albertel  771: 	foreach my $part (@$parts) {
                    772: 	    if ($receipt eq &Apache::lonnet::ireceipt($uname,$udom,$courseid,$symb,$part)) {
1.486     albertel  773: 		$contents.=
                    774: 		    &Apache::loncommon::start_data_table_row().
                    775: 		    '<td>&nbsp;'."\n".
1.177     albertel  776: 		    '<a href="javascript:viewOneStudent(\''.$uname.'\',\''.$udom.
1.417     albertel  777: 		    '\');" target="_self">'.$$fullname{$_}.'</a>&nbsp;</td>'."\n".
1.177     albertel  778: 		    '<td>&nbsp;'.$uname.'&nbsp;</td>'.
                    779: 		    '<td>&nbsp;'.$udom.'&nbsp;</td>';
                    780: 		if ($receiptparts) {
                    781: 		    $contents.='<td>&nbsp;'.$part.'&nbsp;</td>';
                    782: 		}
1.486     albertel  783: 		$contents.= 
                    784: 		    &Apache::loncommon::end_data_table_row()."\n";
1.177     albertel  785: 		
                    786: 		$matches++;
                    787: 	    }
1.44      ng        788: 	}
                    789:     }
                    790:     if ($matches == 0) {
1.584     bisitz    791:         $string = $title
                    792:                  .'<p class="LC_warning">'
                    793:                  .&mt('No match found for the above receipt number.')
                    794:                  .'</p>';
1.44      ng        795:     } else {
1.324     albertel  796: 	$string = &jscriptNform($symb).$title.
1.487     albertel  797: 	    '<p>'.
1.584     bisitz    798: 	    &mt('The above receipt number matches the following [quant,_1,student].',$matches).
1.487     albertel  799: 	    '</p>'.
1.486     albertel  800: 	    $header.
                    801: 	    $contents.
                    802: 	    &Apache::loncommon::end_data_table()."\n";
1.44      ng        803:     }
1.614     www       804:     return $string;
1.44      ng        805: }
                    806: 
                    807: #--- This is called by a number of programs.
                    808: #--- Called from the Grading Menu - View/Grade an individual student
                    809: #--- Also called directly when one clicks on the subm button 
                    810: #    on the problem page.
1.30      ng        811: sub listStudents {
1.617     www       812:     my ($request,$symb,$submitonly) = @_;
1.49      albertel  813: 
1.257     albertel  814:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
                    815:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
                    816:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
1.449     banghart  817:     my $getgroup  = $env{'form.group'} eq '' ? 'all' : $env{'form.group'};
1.617     www       818:     unless ($submitonly) {
                    819:        $submitonly= $env{'form.submitonly'} eq '' ? 'all' : $env{'form.submitonly'};
                    820:     }
1.49      albertel  821: 
1.548     bisitz    822:     my $result='<h3><span class="LC_info">&nbsp;'
1.618     www       823: 	.&mt("View/Grade/Regrade Submissions for a Student or a Group of Students")
1.485     albertel  824: 	.'</span></h3>';
1.118     ng        825: 
1.598     www       826:     my ($partlist,$handgrade,$responseType) = &response_type($symb
                    827: #,$res_error
                    828:     );
1.49      albertel  829: 
1.559     raeburn   830:     my %lt = &Apache::lonlocal::texthash (
                    831: 		'multiple' => 'Please select a student or group of students before clicking on the Next button.',
                    832: 		'single'   => 'Please select the student before clicking on the Next button.',
                    833: 	     );
1.597     wenzelju  834:     $request->print(&Apache::lonhtmlcommon::scripttag(<<LISTJAVASCRIPT));
1.110     ng        835:     function checkSelect(checkBox) {
                    836: 	var ctr=0;
                    837: 	var sense="";
                    838: 	if (checkBox.length > 1) {
                    839: 	    for (var i=0; i<checkBox.length; i++) {
                    840: 		if (checkBox[i].checked) {
                    841: 		    ctr++;
                    842: 		}
                    843: 	    }
1.485     albertel  844: 	    sense = '$lt{'multiple'}';
1.110     ng        845: 	} else {
                    846: 	    if (checkBox.checked) {
                    847: 		ctr = 1;
                    848: 	    }
1.485     albertel  849: 	    sense = '$lt{'single'}';
1.110     ng        850: 	}
                    851: 	if (ctr == 0) {
1.485     albertel  852: 	    alert(sense);
1.110     ng        853: 	    return false;
                    854: 	}
                    855: 	document.gradesub.submit();
                    856:     }
                    857: 
                    858:     function reLoadList(formname) {
1.112     ng        859: 	if (formname.saveStatusOld.value == pullDownSelection(formname.Status)) {return;}
1.110     ng        860: 	formname.command.value = 'submission';
                    861: 	formname.submit();
                    862:     }
1.45      ng        863: LISTJAVASCRIPT
                    864: 
1.118     ng        865:     &commonJSfunctions($request);
1.41      ng        866:     $request->print($result);
1.39      ng        867: 
1.401     albertel  868:     my $checkhdgrade = ($env{'form.handgrade'} eq 'yes' && scalar(@$partlist) > 1 ) ? 'checked="checked"' : '';
                    869:     my $checklastsub = $checkhdgrade eq '' ? 'checked="checked"' : '';
1.154     albertel  870:     my $gradeTable='<form action="/adm/grades" method="post" name="gradesub">'.
1.598     www       871: 	"\n";
1.485     albertel  872: 	
1.561     bisitz    873:     $gradeTable .= &Apache::lonhtmlcommon::start_pick_box();
                    874:     $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('View Problem Text'))
                    875:                   .'<label><input type="radio" name="vProb" value="no" checked="checked" /> '.&mt('no').' </label>'."\n"
                    876:                   .'<label><input type="radio" name="vProb" value="yes" /> '.&mt('one student').' </label>'."\n"
                    877:                   .'<label><input type="radio" name="vProb" value="all" /> '.&mt('all students').' </label><br />'."\n"
                    878:                   .&Apache::lonhtmlcommon::row_closure();
                    879:     $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('View Answer'))
                    880:                   .'<label><input type="radio" name="vAns" value="no"  /> '.&mt('no').' </label>'."\n"
                    881:                   .'<label><input type="radio" name="vAns" value="yes" /> '.&mt('one student').' </label>'."\n"
                    882:                   .'<label><input type="radio" name="vAns" value="all" checked="checked" /> '.&mt('all students').' </label><br />'."\n"
                    883:                   .&Apache::lonhtmlcommon::row_closure();
1.485     albertel  884: 
                    885:     my $submission_options;
1.257     albertel  886:     if ($env{'form.handgrade'} eq 'yes' && scalar(@$partlist) > 1) {
1.485     albertel  887: 	$submission_options.=
                    888: 	    '<label><input type="radio" name="lastSub" value="hdgrade" '.$checkhdgrade.' /> '.&mt('essay part only').' </label>'."\n";
1.49      albertel  889:     }
1.442     banghart  890:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
                    891:     my $saveStatus = $stu_status eq '' ? 'Active' : $stu_status;
1.257     albertel  892:     $env{'form.Status'} = $saveStatus;
1.485     albertel  893:     $submission_options.=
1.592     bisitz    894:         '<span class="LC_nobreak">'.
                    895:         '<label><input type="radio" name="lastSub" value="lastonly" '.$checklastsub.' /> '.
                    896:         &mt('last submission only').' </label></span>'."\n".
                    897:         '<span class="LC_nobreak">'.
                    898:         '<label><input type="radio" name="lastSub" value="last" /> '.
                    899:         &mt('last submission &amp; parts info').' </label></span>'."\n".
                    900:         '<span class="LC_nobreak">'.
                    901:         '<label><input type="radio" name="lastSub" value="datesub" /> '.
                    902:         &mt('by dates and submissions').'</label></span>'."\n".
                    903:         '<span class="LC_nobreak">'.
                    904:         '<label><input type="radio" name="lastSub" value="all" /> '.
                    905:         &mt('all details').'</label></span>';
1.561     bisitz    906:     $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('Submissions'))
                    907:                   .$submission_options
                    908:                   .&Apache::lonhtmlcommon::row_closure();
                    909: 
                    910:     $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('Grading Increments'))
                    911:                   .'<select name="increment">'
                    912:                   .'<option value="1">'.&mt('Whole Points').'</option>'
                    913:                   .'<option value=".5">'.&mt('Half Points').'</option>'
                    914:                   .'<option value=".25">'.&mt('Quarter Points').'</option>'
                    915:                   .'<option value=".1">'.&mt('Tenths of a Point').'</option>'
                    916:                   .'</select>'
                    917:                   .&Apache::lonhtmlcommon::row_closure();
1.485     albertel  918: 
                    919:     $gradeTable .= 
1.432     banghart  920:         &build_section_inputs().
1.45      ng        921: 	'<input type="hidden" name="submitonly"  value="'.$submitonly.'" />'."\n".
1.257     albertel  922: 	'<input type="hidden" name="handgrade"   value="'.$env{'form.handgrade'}.'" /><br />'."\n".
1.418     albertel  923: 	'<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.110     ng        924: 	'<input type="hidden" name="saveStatusOld" value="'.$saveStatus.'" />'."\n";
                    925: 
1.618     www       926:     if (exists($env{'form.Status'})) {
1.561     bisitz    927: 	$gradeTable .= '<input type="hidden" name="Status" value="'.$stu_status.'" />'."\n";
1.124     ng        928:     } else {
1.561     bisitz    929:         $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('Student Status'))
                    930:                       .&Apache::lonhtmlcommon::StatusOptions(
                    931:                            $saveStatus,undef,1,'javascript:reLoadList(this.form);')
                    932:                       .&Apache::lonhtmlcommon::row_closure();
1.124     ng        933:     }
1.112     ng        934: 
1.561     bisitz    935:     $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('Check For Plagiarism'))
                    936:                   .'<input type="checkbox" name="checkPlag" checked="checked" />'
                    937:                   .&Apache::lonhtmlcommon::row_closure(1)
                    938:                   .&Apache::lonhtmlcommon::end_pick_box();
                    939: 
                    940:     $gradeTable .= '<p>'
1.618     www       941:                   .&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    942:                   .'<input type="hidden" name="command" value="processGroup" />'
                    943:                   .'</p>';
1.249     albertel  944: 
                    945: # checkall buttons
                    946:     $gradeTable.=&check_script('gradesub', 'stuinfo');
1.110     ng        947:     $gradeTable.='<input type="button" '."\n".
1.589     bisitz    948:         'onclick="javascript:checkSelect(this.form.stuinfo);" '."\n".
                    949:         'value="'.&mt('Next').' &rarr;" /> <br />'."\n";
1.249     albertel  950:     $gradeTable.=&check_buttons();
1.450     banghart  951:     my ($classlist, undef, $fullname) = &getclasslist($getsec,'1',$getgroup);
1.474     albertel  952:     $gradeTable.= &Apache::loncommon::start_data_table().
                    953: 	&Apache::loncommon::start_data_table_header_row();
1.110     ng        954:     my $loop = 0;
                    955:     while ($loop < 2) {
1.485     albertel  956: 	$gradeTable.='<th>'.&mt('No.').'</th><th>'.&mt('Select').'</th>'.
                    957: 	    '<th>'.&nameUserString('header').'&nbsp;'.&mt('Section/Group').'</th>';
1.618     www       958: 	if (($submitonly ne 'queued') && ($submitonly ne 'all')) {
1.485     albertel  959: 	    foreach my $part (sort(@$partlist)) {
                    960: 		my $display_part=
                    961: 		    &get_display_part((split(/_/,$part))[0],$symb);
                    962: 		$gradeTable.=
                    963: 		    '<th>'.&mt('Part: [_1] Status',$display_part).'</th>';
1.110     ng        964: 	    }
1.301     albertel  965: 	} elsif ($submitonly eq 'queued') {
1.474     albertel  966: 	    $gradeTable.='<th>'.&mt('Queue Status').'&nbsp;</th>';
1.110     ng        967: 	}
                    968: 	$loop++;
1.126     ng        969: #	$gradeTable.='<td></td>' if ($loop%2 ==1);
1.41      ng        970:     }
1.474     albertel  971:     $gradeTable.=&Apache::loncommon::end_data_table_header_row()."\n";
1.41      ng        972: 
1.45      ng        973:     my $ctr = 0;
1.294     albertel  974:     foreach my $student (sort 
                    975: 			 {
                    976: 			     if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                    977: 				 return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                    978: 			     }
                    979: 			     return $a cmp $b;
                    980: 			 }
                    981: 			 (keys(%$fullname))) {
1.41      ng        982: 	my ($uname,$udom) = split(/:/,$student);
1.301     albertel  983: 
1.110     ng        984: 	my %status = ();
1.301     albertel  985: 
                    986: 	if ($submitonly eq 'queued') {
                    987: 	    my %queue_status = 
                    988: 		&Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
                    989: 							$udom,$uname);
                    990: 	    next if (!defined($queue_status{'gradingqueue'}));
                    991: 	    $status{'gradingqueue'} = $queue_status{'gradingqueue'};
                    992: 	}
                    993: 
1.618     www       994: 	if (($submitonly ne 'queued') && ($submitonly ne 'all')) {
1.324     albertel  995: 	    (%status) =&student_gradeStatus($symb,$udom,$uname,$partlist);
1.145     albertel  996: 	    my $submitted = 0;
1.164     albertel  997: 	    my $graded = 0;
1.248     albertel  998: 	    my $incorrect = 0;
1.110     ng        999: 	    foreach (keys(%status)) {
1.145     albertel 1000: 		$submitted = 1 if ($status{$_} ne 'nothing');
1.248     albertel 1001: 		$graded = 1 if ($status{$_} =~ /^ungraded/);
                   1002: 		$incorrect = 1 if ($status{$_} =~ /^incorrect/);
                   1003: 		
1.110     ng       1004: 		my ($foo,$partid,$foo1) = split(/\./,$_);
                   1005: 		if ($status{'resource.'.$partid.'.submitted_by'} ne '') {
1.145     albertel 1006: 		    $submitted = 0;
1.150     albertel 1007: 		    my ($part)=split(/\./,$partid);
1.110     ng       1008: 		    $gradeTable.='<input type="hidden" name="'.
1.150     albertel 1009: 			$student.':'.$part.':submitted_by" value="'.
1.110     ng       1010: 			$status{'resource.'.$partid.'.submitted_by'}.'" />';
                   1011: 		}
1.41      ng       1012: 	    }
1.248     albertel 1013: 	    
1.156     albertel 1014: 	    next if (!$submitted && ($submitonly eq 'yes' ||
                   1015: 				     $submitonly eq 'incorrect' ||
                   1016: 				     $submitonly eq 'graded'));
1.248     albertel 1017: 	    next if (!$graded && ($submitonly eq 'graded'));
                   1018: 	    next if (!$incorrect && $submitonly eq 'incorrect');
1.41      ng       1019: 	}
1.34      ng       1020: 
1.45      ng       1021: 	$ctr++;
1.249     albertel 1022: 	my $section = $classlist->{$student}->[&Apache::loncoursedata::CL_SECTION()];
1.452     banghart 1023:         my $group = $classlist->{$student}->[&Apache::loncoursedata::CL_GROUP()];
1.104     albertel 1024: 	if ( $perm{'vgr'} eq 'F' ) {
1.474     albertel 1025: 	    if ($ctr%2 ==1) {
                   1026: 		$gradeTable.= &Apache::loncommon::start_data_table_row();
                   1027: 	    }
1.126     ng       1028: 	    $gradeTable.='<td align="right">'.$ctr.'&nbsp;</td>'.
1.563     bisitz   1029:                '<td align="center"><label><input type="checkbox" name="stuinfo" value="'.
1.249     albertel 1030:                $student.':'.$$fullname{$student}.':::SECTION'.$section.
                   1031: 	       ')&nbsp;" />&nbsp;&nbsp;</label></td>'."\n".'<td>'.
                   1032: 	       &nameUserString(undef,$$fullname{$student},$uname,$udom).
1.474     albertel 1033: 	       '&nbsp;'.$section.($group ne '' ?'/'.$group:'').'</td>'."\n";
1.110     ng       1034: 
1.618     www      1035: 	    if ($submitonly ne 'all') {
1.524     raeburn  1036: 		foreach (sort(keys(%status))) {
1.485     albertel 1037: 		    next if ($_ =~ /^resource.*?submitted_by$/);
                   1038: 		    $gradeTable.='<td align="center">&nbsp;'.&mt($status{$_}).'&nbsp;</td>'."\n";
1.110     ng       1039: 		}
1.41      ng       1040: 	    }
1.126     ng       1041: #	    $gradeTable.='<td></td>' if ($ctr%2 ==1);
1.474     albertel 1042: 	    if ($ctr%2 ==0) {
                   1043: 		$gradeTable.=&Apache::loncommon::end_data_table_row()."\n";
                   1044: 	    }
1.41      ng       1045: 	}
                   1046:     }
1.110     ng       1047:     if ($ctr%2 ==1) {
1.126     ng       1048: 	$gradeTable.='<td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td>';
1.618     www      1049: 	    if (($submitonly ne 'queued') && ($submitonly ne 'all')) {
1.110     ng       1050: 		foreach (@$partlist) {
                   1051: 		    $gradeTable.='<td>&nbsp;</td>';
                   1052: 		}
1.301     albertel 1053: 	    } elsif ($submitonly eq 'queued') {
                   1054: 		$gradeTable.='<td>&nbsp;</td>';
1.110     ng       1055: 	    }
1.474     albertel 1056: 	$gradeTable.=&Apache::loncommon::end_data_table_row();
1.110     ng       1057:     }
                   1058: 
1.474     albertel 1059:     $gradeTable.=&Apache::loncommon::end_data_table()."\n".
1.589     bisitz   1060:         '<input type="button" '.
                   1061:         'onclick="javascript:checkSelect(this.form.stuinfo);" '.
                   1062:         'value="'.&mt('Next').' &rarr;" /></form>'."\n";
1.45      ng       1063:     if ($ctr == 0) {
1.96      albertel 1064: 	my $num_students=(scalar(keys(%$fullname)));
                   1065: 	if ($num_students eq 0) {
1.485     albertel 1066: 	    $gradeTable='<br />&nbsp;<span class="LC_warning">'.&mt('There are no students currently enrolled.').'</span>';
1.96      albertel 1067: 	} else {
1.171     albertel 1068: 	    my $submissions='submissions';
                   1069: 	    if ($submitonly eq 'incorrect') { $submissions = 'incorrect submissions'; }
                   1070: 	    if ($submitonly eq 'graded'   ) { $submissions = 'ungraded submissions'; }
1.301     albertel 1071: 	    if ($submitonly eq 'queued'   ) { $submissions = 'queued submissions'; }
1.398     albertel 1072: 	    $gradeTable='<br />&nbsp;<span class="LC_warning">'.
1.485     albertel 1073: 		&mt('No '.$submissions.' found for this resource for any students. ([_1] students checked for '.$submissions.')',
                   1074: 		    $num_students).
                   1075: 		'</span><br />';
1.96      albertel 1076: 	}
1.46      ng       1077:     } elsif ($ctr == 1) {
1.474     albertel 1078: 	$gradeTable =~ s/type="checkbox"/type="checkbox" checked="checked"/;
1.45      ng       1079:     }
                   1080:     $request->print($gradeTable);
1.44      ng       1081:     return '';
1.10      ng       1082: }
                   1083: 
1.44      ng       1084: #---- Called from the listStudents routine
1.249     albertel 1085: 
                   1086: sub check_script {
                   1087:     my ($form, $type)=@_;
1.597     wenzelju 1088:     my $chkallscript= &Apache::lonhtmlcommon::scripttag('
1.249     albertel 1089:     function checkall() {
                   1090:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
                   1091:             ele = document.forms.'.$form.'.elements[i];
                   1092:             if (ele.name == "'.$type.'") {
                   1093:             document.forms.'.$form.'.elements[i].checked=true;
                   1094:                                        }
                   1095:         }
                   1096:     }
                   1097: 
                   1098:     function checksec() {
                   1099:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
                   1100:             ele = document.forms.'.$form.'.elements[i];
                   1101:            string = document.forms.'.$form.'.chksec.value;
                   1102:            if
                   1103:           (ele.value.indexOf(":::SECTION"+string)>0) {
                   1104:               document.forms.'.$form.'.elements[i].checked=true;
                   1105:             }
                   1106:         }
                   1107:     }
                   1108: 
                   1109: 
                   1110:     function uncheckall() {
                   1111:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
                   1112:             ele = document.forms.'.$form.'.elements[i];
                   1113:             if (ele.name == "'.$type.'") {
                   1114:             document.forms.'.$form.'.elements[i].checked=false;
                   1115:                                        }
                   1116:         }
                   1117:     }
                   1118: 
1.597     wenzelju 1119: '."\n");
1.249     albertel 1120:     return $chkallscript;
                   1121: }
                   1122: 
                   1123: sub check_buttons {
1.485     albertel 1124:     my $buttons.='<input type="button" onclick="checkall()" value="'.&mt('Check All').'" />';
                   1125:     $buttons.='<input type="button" onclick="uncheckall()" value="'.&mt('Uncheck All').'" />&nbsp;';
                   1126:     $buttons.='<input type="button" onclick="checksec()" value="'.&mt('Check Section/Group').'" />';
1.249     albertel 1127:     $buttons.='<input type="text" size="5" name="chksec" />&nbsp;';
                   1128:     return $buttons;
                   1129: }
                   1130: 
1.44      ng       1131: #     Displays the submissions for one student or a group of students
1.34      ng       1132: sub processGroup {
1.619     www      1133:     my ($request,$symb)  = @_;
1.41      ng       1134:     my $ctr        = 0;
1.155     albertel 1135:     my @stuchecked = &Apache::loncommon::get_env_multiple('form.stuinfo');
1.41      ng       1136:     my $total      = scalar(@stuchecked)-1;
1.45      ng       1137: 
1.396     banghart 1138:     foreach my $student (@stuchecked) {
                   1139: 	my ($uname,$udom,$fullname) = split(/:/,$student);
1.257     albertel 1140: 	$env{'form.student'}        = $uname;
                   1141: 	$env{'form.userdom'}        = $udom;
                   1142: 	$env{'form.fullname'}       = $fullname;
1.619     www      1143: 	&submission($request,$ctr,$total,$symb);
1.41      ng       1144: 	$ctr++;
                   1145:     }
                   1146:     return '';
1.35      ng       1147: }
1.34      ng       1148: 
1.44      ng       1149: #------------------------------------------------------------------------------------
                   1150: #
                   1151: #-------------------------- Next few routines handles grading by student, essentially
                   1152: #                           handles essay response type problem/part
                   1153: #
                   1154: #--- Javascript to handle the submission page functionality ---
                   1155: sub sub_page_js {
                   1156:     my $request = shift;
1.539     riegler  1157: 	    my $alertmsg = &mt('A number equal or greater than 0 is expected. Entered value = ');
1.597     wenzelju 1158:     $request->print(&Apache::lonhtmlcommon::scripttag(<<SUBJAVASCRIPT));
1.71      ng       1159:     function updateRadio(formname,id,weight) {
1.125     ng       1160: 	var gradeBox = formname["GD_BOX"+id];
                   1161: 	var radioButton = formname["RADVAL"+id];
                   1162: 	var oldpts = formname["oldpts"+id].value;
1.72      ng       1163: 	var pts = checkSolved(formname,id) == 'update' ? gradeBox.value : oldpts;
1.71      ng       1164: 	gradeBox.value = pts;
                   1165: 	var resetbox = false;
                   1166: 	if (isNaN(pts) || pts < 0) {
1.539     riegler  1167: 	    alert("$alertmsg"+pts);
1.71      ng       1168: 	    for (var i=0; i<radioButton.length; i++) {
                   1169: 		if (radioButton[i].checked) {
                   1170: 		    gradeBox.value = i;
                   1171: 		    resetbox = true;
                   1172: 		}
                   1173: 	    }
                   1174: 	    if (!resetbox) {
                   1175: 		formtextbox.value = "";
                   1176: 	    }
                   1177: 	    return;
1.44      ng       1178: 	}
1.71      ng       1179: 
                   1180: 	if (pts > weight) {
                   1181: 	    var resp = confirm("You entered a value ("+pts+
                   1182: 			       ") greater than the weight for the part. Accept?");
                   1183: 	    if (resp == false) {
1.125     ng       1184: 		gradeBox.value = oldpts;
1.71      ng       1185: 		return;
                   1186: 	    }
1.44      ng       1187: 	}
1.13      albertel 1188: 
1.71      ng       1189: 	for (var i=0; i<radioButton.length; i++) {
                   1190: 	    radioButton[i].checked=false;
                   1191: 	    if (pts == i && pts != "") {
                   1192: 		radioButton[i].checked=true;
                   1193: 	    }
                   1194: 	}
                   1195: 	updateSelect(formname,id);
1.125     ng       1196: 	formname["stores"+id].value = "0";
1.41      ng       1197:     }
1.5       albertel 1198: 
1.72      ng       1199:     function writeBox(formname,id,pts) {
1.125     ng       1200: 	var gradeBox = formname["GD_BOX"+id];
1.71      ng       1201: 	if (checkSolved(formname,id) == 'update') {
                   1202: 	    gradeBox.value = pts;
                   1203: 	} else {
1.125     ng       1204: 	    var oldpts = formname["oldpts"+id].value;
1.72      ng       1205: 	    gradeBox.value = oldpts;
1.125     ng       1206: 	    var radioButton = formname["RADVAL"+id];
1.71      ng       1207: 	    for (var i=0; i<radioButton.length; i++) {
                   1208: 		radioButton[i].checked=false;
1.72      ng       1209: 		if (i == oldpts) {
1.71      ng       1210: 		    radioButton[i].checked=true;
                   1211: 		}
                   1212: 	    }
1.41      ng       1213: 	}
1.125     ng       1214: 	formname["stores"+id].value = "0";
1.71      ng       1215: 	updateSelect(formname,id);
                   1216: 	return;
1.41      ng       1217:     }
1.44      ng       1218: 
1.71      ng       1219:     function clearRadBox(formname,id) {
                   1220: 	if (checkSolved(formname,id) == 'noupdate') {
                   1221: 	    updateSelect(formname,id);
                   1222: 	    return;
                   1223: 	}
1.125     ng       1224: 	gradeSelect = formname["GD_SEL"+id];
1.71      ng       1225: 	for (var i=0; i<gradeSelect.length; i++) {
                   1226: 	    if (gradeSelect[i].selected) {
                   1227: 		var selectx=i;
                   1228: 	    }
                   1229: 	}
1.125     ng       1230: 	var stores = formname["stores"+id];
1.71      ng       1231: 	if (selectx == stores.value) { return };
1.125     ng       1232: 	var gradeBox = formname["GD_BOX"+id];
1.71      ng       1233: 	gradeBox.value = "";
1.125     ng       1234: 	var radioButton = formname["RADVAL"+id];
1.71      ng       1235: 	for (var i=0; i<radioButton.length; i++) {
                   1236: 	    radioButton[i].checked=false;
                   1237: 	}
                   1238: 	stores.value = selectx;
                   1239:     }
1.5       albertel 1240: 
1.71      ng       1241:     function checkSolved(formname,id) {
1.125     ng       1242: 	if (formname["solved"+id].value == "correct_by_student" && formname.overRideScore.value == 'no') {
1.118     ng       1243: 	    var reply = confirm("This problem has been graded correct by the computer. Do you want to change the score?");
                   1244: 	    if (!reply) {return "noupdate";}
1.120     ng       1245: 	    formname.overRideScore.value = 'yes';
1.41      ng       1246: 	}
1.71      ng       1247: 	return "update";
1.13      albertel 1248:     }
1.71      ng       1249: 
                   1250:     function updateSelect(formname,id) {
1.125     ng       1251: 	formname["GD_SEL"+id][0].selected = true;
1.71      ng       1252: 	return;
1.41      ng       1253:     }
1.33      ng       1254: 
1.121     ng       1255: //=========== Check that a point is assigned for all the parts  ============
1.71      ng       1256:     function checksubmit(formname,val,total,parttot) {
1.121     ng       1257: 	formname.gradeOpt.value = val;
1.71      ng       1258: 	if (val == "Save & Next") {
                   1259: 	    for (i=0;i<=total;i++) {
                   1260: 		for (j=0;j<parttot;j++) {
1.125     ng       1261: 		    var partid = formname["partid"+i+"_"+j].value;
1.127     ng       1262: 		    if (formname["GD_SEL"+i+"_"+partid][0].selected) {
1.125     ng       1263: 			var points = formname["GD_BOX"+i+"_"+partid].value;
1.71      ng       1264: 			if (points == "") {
1.125     ng       1265: 			    var name = formname["name"+i].value;
1.129     ng       1266: 			    var studentID = (name != '' ? name : formname["unamedom"+i].value);
                   1267: 			    var resp = confirm("You did not assign a score for "+studentID+
                   1268: 					       ", part "+partid+". Continue?");
1.71      ng       1269: 			    if (resp == false) {
1.125     ng       1270: 				formname["GD_BOX"+i+"_"+partid].focus();
1.71      ng       1271: 				return false;
                   1272: 			    }
                   1273: 			}
                   1274: 		    }
                   1275: 		    
                   1276: 		}
                   1277: 	    }
                   1278: 	    
                   1279: 	}
1.121     ng       1280: 	if (val == "Grade Student") {
                   1281: 	    if (formname.Status.value == "") {
                   1282: 		formname.Status.value = "Active";
                   1283: 	    }
                   1284: 	    formname.studentNo.value = total;
                   1285: 	}
1.120     ng       1286: 	formname.submit();
                   1287:     }
                   1288: 
1.71      ng       1289: //======= Check that a score is assigned for all the problems (page/sequence grading only) =========
                   1290:     function checkSubmitPage(formname,total) {
                   1291: 	noscore = new Array(100);
                   1292: 	var ptr = 0;
                   1293: 	for (i=1;i<total;i++) {
1.125     ng       1294: 	    var partid = formname["q_"+i].value;
1.127     ng       1295: 	    if (formname["GD_SEL"+i+"_"+partid][0].selected) {
1.125     ng       1296: 		var points = formname["GD_BOX"+i+"_"+partid].value;
                   1297: 		var status = formname["solved"+i+"_"+partid].value;
1.71      ng       1298: 		if (points == "" && status != "correct_by_student") {
                   1299: 		    noscore[ptr] = i;
                   1300: 		    ptr++;
                   1301: 		}
                   1302: 	    }
                   1303: 	}
                   1304: 	if (ptr != 0) {
                   1305: 	    var sense = ptr == 1 ? ": " : "s: ";
                   1306: 	    var prolist = "";
                   1307: 	    if (ptr == 1) {
                   1308: 		prolist = noscore[0];
                   1309: 	    } else {
                   1310: 		var i = 0;
                   1311: 		while (i < ptr-1) {
                   1312: 		    prolist += noscore[i]+", ";
                   1313: 		    i++;
                   1314: 		}
                   1315: 		prolist += "and "+noscore[i];
                   1316: 	    }
                   1317: 	    var resp = confirm("You did not assign any score for the following problem"+sense+prolist+". Continue?");
                   1318: 	    if (resp == false) {
                   1319: 		return false;
                   1320: 	    }
                   1321: 	}
1.45      ng       1322: 
1.71      ng       1323: 	formname.submit();
                   1324:     }
                   1325: SUBJAVASCRIPT
                   1326: }
1.45      ng       1327: 
1.71      ng       1328: #--- javascript for essay type problem --
                   1329: sub sub_page_kw_js {
                   1330:     my $request = shift;
1.80      ng       1331:     my $iconpath = $request->dir_config('lonIconsURL');
1.118     ng       1332:     &commonJSfunctions($request);
1.350     albertel 1333: 
1.597     wenzelju 1334:     my $inner_js_msg_central= &Apache::lonhtmlcommon::scripttag(<<INNERJS);
1.350     albertel 1335:     function checkInput() {
                   1336:       opener.document.SCORE.msgsub.value = opener.checkEntities(document.msgcenter.msgsub.value);
                   1337:       var nmsg   = opener.document.SCORE.savemsgN.value;
                   1338:       var usrctr = document.msgcenter.usrctr.value;
                   1339:       var newval = opener.document.SCORE["newmsg"+usrctr];
                   1340:       newval.value = opener.checkEntities(document.msgcenter.newmsg.value);
                   1341: 
                   1342:       var msgchk = "";
                   1343:       if (document.msgcenter.subchk.checked) {
                   1344:          msgchk = "msgsub,";
                   1345:       }
                   1346:       var includemsg = 0;
                   1347:       for (var i=1; i<=nmsg; i++) {
                   1348:           var opnmsg = opener.document.SCORE["savemsg"+i];
                   1349:           var frmmsg = document.msgcenter["msg"+i];
                   1350:           opnmsg.value = opener.checkEntities(frmmsg.value);
                   1351:           var showflg = opener.document.SCORE["shownOnce"+i];
                   1352:           showflg.value = "1";
                   1353:           var chkbox = document.msgcenter["msgn"+i];
                   1354:           if (chkbox.checked) {
                   1355:              msgchk += "savemsg"+i+",";
                   1356:              includemsg = 1;
                   1357:           }
                   1358:       }
                   1359:       if (document.msgcenter.newmsgchk.checked) {
                   1360:          msgchk += "newmsg"+usrctr;
                   1361:          includemsg = 1;
                   1362:       }
                   1363:       imgformname = opener.document.SCORE["mailicon"+usrctr];
                   1364:       imgformname.src = "$iconpath/"+((includemsg) ? "mailto.gif" : "mailbkgrd.gif");
                   1365:       var includemsg = opener.document.SCORE["includemsg"+usrctr];
                   1366:       includemsg.value = msgchk;
                   1367: 
                   1368:       self.close()
                   1369: 
                   1370:     }
                   1371: INNERJS
                   1372: 
1.597     wenzelju 1373:     my $inner_js_highlight_central= &Apache::lonhtmlcommon::scripttag(<<INNERJS);
1.351     albertel 1374:     function updateChoice(flag) {
                   1375:       opener.document.SCORE.kwclr.value = opener.radioSelection(document.hlCenter.kwdclr);
                   1376:       opener.document.SCORE.kwsize.value = opener.radioSelection(document.hlCenter.kwdsize);
                   1377:       opener.document.SCORE.kwstyle.value = opener.radioSelection(document.hlCenter.kwdstyle);
                   1378:       opener.document.SCORE.refresh.value = "on";
                   1379:       if (opener.document.SCORE.keywords.value!=""){
                   1380:          opener.document.SCORE.submit();
                   1381:       }
                   1382:       self.close()
                   1383:     }
                   1384: INNERJS
                   1385: 
                   1386:     my $start_page_msg_central = 
                   1387:         &Apache::loncommon::start_page('Message Central',$inner_js_msg_central,
                   1388: 				       {'js_ready'  => 1,
                   1389: 					'only_body' => 1,
                   1390: 					'bgcolor'   =>'#FFFFFF',});
                   1391:     my $end_page_msg_central = 
                   1392: 	&Apache::loncommon::end_page({'js_ready' => 1});
                   1393: 
                   1394: 
                   1395:     my $start_page_highlight_central = 
                   1396:         &Apache::loncommon::start_page('Highlight Central',
                   1397: 				       $inner_js_highlight_central,
1.350     albertel 1398: 				       {'js_ready'  => 1,
                   1399: 					'only_body' => 1,
                   1400: 					'bgcolor'   =>'#FFFFFF',});
1.351     albertel 1401:     my $end_page_highlight_central = 
1.350     albertel 1402: 	&Apache::loncommon::end_page({'js_ready' => 1});
                   1403: 
1.219     www      1404:     my $docopen=&Apache::lonhtmlcommon::javascript_docopen();
1.236     albertel 1405:     $docopen=~s/^document\.//;
1.539     riegler  1406:     my $alertmsg = &mt('Please select a word or group of words from document and then click this link.');
1.597     wenzelju 1407:     $request->print(&Apache::lonhtmlcommon::scripttag(<<SUBJAVASCRIPT));
1.45      ng       1408: 
1.44      ng       1409: //===================== Show list of keywords ====================
1.122     ng       1410:   function keywords(formname) {
                   1411:     var nret = prompt("Keywords list, separated by a space. Add/delete to list if desired.",formname.keywords.value);
1.44      ng       1412:     if (nret==null) return;
1.122     ng       1413:     formname.keywords.value = nret;
1.44      ng       1414: 
1.122     ng       1415:     if (formname.keywords.value != "") {
1.128     ng       1416: 	formname.refresh.value = "on";
1.122     ng       1417: 	formname.submit();
1.44      ng       1418:     }
                   1419:     return;
                   1420:   }
                   1421: 
                   1422: //===================== Script to view submitted by ==================
                   1423:   function viewSubmitter(submitter) {
                   1424:     document.SCORE.refresh.value = "on";
                   1425:     document.SCORE.NCT.value = "1";
                   1426:     document.SCORE.unamedom0.value = submitter;
                   1427:     document.SCORE.submit();
                   1428:     return;
                   1429:   }
                   1430: 
                   1431: //===================== Script to add keyword(s) ==================
                   1432:   function getSel() {
                   1433:     if (document.getSelection) txt = document.getSelection();
                   1434:     else if (document.selection) txt = document.selection.createRange().text;
                   1435:     else return;
                   1436:     var cleantxt = txt.replace(new RegExp('([\\f\\n\\r\\t\\v ])+', 'g')," ");
                   1437:     if (cleantxt=="") {
1.539     riegler  1438: 	alert("$alertmsg");
1.44      ng       1439: 	return;
                   1440:     }
                   1441:     var nret = prompt("Add selection to keyword list? Edit if desired.",cleantxt);
                   1442:     if (nret==null) return;
1.127     ng       1443:     document.SCORE.keywords.value = document.SCORE.keywords.value+" "+nret;
1.44      ng       1444:     if (document.SCORE.keywords.value != "") {
1.127     ng       1445: 	document.SCORE.refresh.value = "on";
1.44      ng       1446: 	document.SCORE.submit();
                   1447:     }
                   1448:     return;
                   1449:   }
                   1450: 
                   1451: //====================== Script for composing message ==============
1.80      ng       1452:    // preload images
                   1453:    img1 = new Image();
                   1454:    img1.src = "$iconpath/mailbkgrd.gif";
                   1455:    img2 = new Image();
                   1456:    img2.src = "$iconpath/mailto.gif";
                   1457: 
1.44      ng       1458:   function msgCenter(msgform,usrctr,fullname) {
                   1459:     var Nmsg  = msgform.savemsgN.value;
                   1460:     savedMsgHeader(Nmsg,usrctr,fullname);
                   1461:     var subject = msgform.msgsub.value;
1.127     ng       1462:     var msgchk = document.SCORE["includemsg"+usrctr].value;
1.44      ng       1463:     re = /msgsub/;
                   1464:     var shwsel = "";
                   1465:     if (re.test(msgchk)) { shwsel = "checked" }
1.123     ng       1466:     subject = (document.SCORE.shownSub.value == 0 ? checkEntities(subject) : subject);
                   1467:     displaySubject(checkEntities(subject),shwsel);
1.44      ng       1468:     for (var i=1; i<=Nmsg; i++) {
1.123     ng       1469: 	var testmsg = "savemsg"+i+",";
                   1470: 	re = new RegExp(testmsg,"g");
1.44      ng       1471: 	shwsel = "";
                   1472: 	if (re.test(msgchk)) { shwsel = "checked" }
1.125     ng       1473: 	var message = document.SCORE["savemsg"+i].value;
1.126     ng       1474: 	message = (document.SCORE["shownOnce"+i].value == 0 ? checkEntities(message) : message);
1.123     ng       1475: 	displaySavedMsg(i,message,shwsel); //I do not get it. w/o checkEntities on saved messages,
                   1476: 	                                   //any &lt; is already converted to <, etc. However, only once!!
1.44      ng       1477:     }
1.125     ng       1478:     newmsg = document.SCORE["newmsg"+usrctr].value;
1.44      ng       1479:     shwsel = "";
                   1480:     re = /newmsg/;
                   1481:     if (re.test(msgchk)) { shwsel = "checked" }
                   1482:     newMsg(newmsg,shwsel);
                   1483:     msgTail(); 
                   1484:     return;
                   1485:   }
                   1486: 
1.123     ng       1487:   function checkEntities(strx) {
                   1488:     if (strx.length == 0) return strx;
                   1489:     var orgStr = ["&", "<", ">", '"']; 
                   1490:     var newStr = ["&amp;", "&lt;", "&gt;", "&quot;"];
                   1491:     var counter = 0;
                   1492:     while (counter < 4) {
                   1493: 	strx = strReplace(strx,orgStr[counter],newStr[counter]);
                   1494: 	counter++;
                   1495:     }
                   1496:     return strx;
                   1497:   }
                   1498: 
                   1499:   function strReplace(strx, orgStr, newStr) {
                   1500:     return strx.split(orgStr).join(newStr);
                   1501:   }
                   1502: 
1.44      ng       1503:   function savedMsgHeader(Nmsg,usrctr,fullname) {
1.76      ng       1504:     var height = 70*Nmsg+250;
1.44      ng       1505:     var scrollbar = "no";
                   1506:     if (height > 600) {
                   1507: 	height = 600;
                   1508: 	scrollbar = "yes";
                   1509:     }
1.118     ng       1510:     var xpos = (screen.width-600)/2;
                   1511:     xpos = (xpos < 0) ? '0' : xpos;
                   1512:     var ypos = (screen.height-height)/2-30;
                   1513:     ypos = (ypos < 0) ? '0' : ypos;
                   1514: 
1.206     albertel 1515:     pWin = window.open('', 'MessageCenter', 'resizable=yes,toolbar=no,location=no,scrollbars='+scrollbar+',screenx='+xpos+',screeny='+ypos+',width=600,height='+height);
1.76      ng       1516:     pWin.focus();
                   1517:     pDoc = pWin.document;
1.219     www      1518:     pDoc.$docopen;
1.351     albertel 1519:     pDoc.write('$start_page_msg_central');
1.76      ng       1520: 
                   1521:     pDoc.write("<form action=\\"inactive\\" name=\\"msgcenter\\">");
                   1522:     pDoc.write("<input value=\\""+usrctr+"\\" name=\\"usrctr\\" type=\\"hidden\\">");
1.465     albertel 1523:     pDoc.write("<h3><span class=\\"LC_info\\">&nbsp;Compose Message for \"+fullname+\"<\\/span><\\/h3><br /><br />");
1.76      ng       1524: 
1.564     bisitz   1525:     pDoc.write('<table border="0" width="100%"><tr><td bgcolor="#777777">');
                   1526:     pDoc.write('<table border="0" width="100%"><tr bgcolor="#DDFFFF">');
1.465     albertel 1527:     pDoc.write("<td><b>Type<\\/b><\\/td><td><b>Include<\\/b><\\/td><td><b>Message<\\/td><\\/tr>");
1.44      ng       1528: }
                   1529:     function displaySubject(msg,shwsel) {
1.76      ng       1530:     pDoc = pWin.document;
                   1531:     pDoc.write("<tr bgcolor=\\"#ffffdd\\">");
1.465     albertel 1532:     pDoc.write("<td>Subject<\\/td>");
                   1533:     pDoc.write("<td align=\\"center\\"><input name=\\"subchk\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
                   1534:     pDoc.write("<td><input name=\\"msgsub\\" type=\\"text\\" value=\\""+msg+"\\"size=\\"60\\" maxlength=\\"80\\"><\\/td><\\/tr>");
1.44      ng       1535: }
                   1536: 
1.72      ng       1537:   function displaySavedMsg(ctr,msg,shwsel) {
1.76      ng       1538:     pDoc = pWin.document;
                   1539:     pDoc.write("<tr bgcolor=\\"#ffffdd\\">");
1.465     albertel 1540:     pDoc.write("<td align=\\"center\\">"+ctr+"<\\/td>");
                   1541:     pDoc.write("<td align=\\"center\\"><input name=\\"msgn"+ctr+"\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
                   1542:     pDoc.write("<td><textarea name=\\"msg"+ctr+"\\" cols=\\"60\\" rows=\\"3\\">"+msg+"<\\/textarea><\\/td><\\/tr>");
1.44      ng       1543: }
                   1544: 
                   1545:   function newMsg(newmsg,shwsel) {
1.76      ng       1546:     pDoc = pWin.document;
                   1547:     pDoc.write("<tr bgcolor=\\"#ffffdd\\">");
1.465     albertel 1548:     pDoc.write("<td align=\\"center\\">New<\\/td>");
                   1549:     pDoc.write("<td align=\\"center\\"><input name=\\"newmsgchk\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
                   1550:     pDoc.write("<td><textarea name=\\"newmsg\\" cols=\\"60\\" rows=\\"3\\" onchange=\\"javascript:this.form.newmsgchk.checked=true\\" >"+newmsg+"<\\/textarea><\\/td><\\/tr>");
1.44      ng       1551: }
                   1552: 
                   1553:   function msgTail() {
1.76      ng       1554:     pDoc = pWin.document;
1.465     albertel 1555:     pDoc.write("<\\/table>");
                   1556:     pDoc.write("<\\/td><\\/tr><\\/table>&nbsp;");
1.589     bisitz   1557:     pDoc.write("<input type=\\"button\\" value=\\"Save\\" onclick=\\"javascript:checkInput()\\">&nbsp;&nbsp;");
                   1558:     pDoc.write("<input type=\\"button\\" value=\\"Cancel\\" onclick=\\"self.close()\\"><br /><br />");
1.465     albertel 1559:     pDoc.write("<\\/form>");
1.351     albertel 1560:     pDoc.write('$end_page_msg_central');
1.128     ng       1561:     pDoc.close();
1.44      ng       1562: }
                   1563: 
                   1564: //====================== Script for keyword highlight options ==============
                   1565:   function kwhighlight() {
                   1566:     var kwclr    = document.SCORE.kwclr.value;
                   1567:     var kwsize   = document.SCORE.kwsize.value;
                   1568:     var kwstyle  = document.SCORE.kwstyle.value;
                   1569:     var redsel = "";
                   1570:     var grnsel = "";
                   1571:     var blusel = "";
                   1572:     if (kwclr=="red")   {var redsel="checked"};
                   1573:     if (kwclr=="green") {var grnsel="checked"};
                   1574:     if (kwclr=="blue")  {var blusel="checked"};
                   1575:     var sznsel = "";
                   1576:     var sz1sel = "";
                   1577:     var sz2sel = "";
                   1578:     if (kwsize=="0")  {var sznsel="checked"};
                   1579:     if (kwsize=="+1") {var sz1sel="checked"};
                   1580:     if (kwsize=="+2") {var sz2sel="checked"};
                   1581:     var synsel = "";
                   1582:     var syisel = "";
                   1583:     var sybsel = "";
                   1584:     if (kwstyle=="")    {var synsel="checked"};
                   1585:     if (kwstyle=="<i>") {var syisel="checked"};
                   1586:     if (kwstyle=="<b>") {var sybsel="checked"};
                   1587:     highlightCentral();
                   1588:     highlightbody('red','red',redsel,'0','normal',sznsel,'','normal',synsel);
                   1589:     highlightbody('green','green',grnsel,'+1','+1',sz1sel,'<i>','italic',syisel);
                   1590:     highlightbody('blue','blue',blusel,'+2','+2',sz2sel,'<b>','bold',sybsel);
                   1591:     highlightend();
                   1592:     return;
                   1593:   }
                   1594: 
                   1595:   function highlightCentral() {
1.76      ng       1596: //    if (window.hwdWin) window.hwdWin.close();
1.118     ng       1597:     var xpos = (screen.width-400)/2;
                   1598:     xpos = (xpos < 0) ? '0' : xpos;
                   1599:     var ypos = (screen.height-330)/2-30;
                   1600:     ypos = (ypos < 0) ? '0' : ypos;
                   1601: 
1.206     albertel 1602:     hwdWin = window.open('', 'KeywordHighlightCentral', 'resizeable=yes,toolbar=no,location=no,scrollbars=no,width=400,height=300,screenx='+xpos+',screeny='+ypos);
1.76      ng       1603:     hwdWin.focus();
                   1604:     var hDoc = hwdWin.document;
1.219     www      1605:     hDoc.$docopen;
1.351     albertel 1606:     hDoc.write('$start_page_highlight_central');
1.76      ng       1607:     hDoc.write("<form action=\\"inactive\\" name=\\"hlCenter\\">");
1.465     albertel 1608:     hDoc.write("<h3><span class=\\"LC_info\\">&nbsp;Keyword Highlight Options<\\/span><\\/h3><br /><br />");
1.76      ng       1609: 
1.564     bisitz   1610:     hDoc.write('<table border="0" width="100%"><tr><td bgcolor="#777777">');
                   1611:     hDoc.write('<table border="0" width="100%"><tr bgcolor="#DDFFFF">');
1.465     albertel 1612:     hDoc.write("<td><b>Text Color<\\/b><\\/td><td><b>Font Size<\\/b><\\/td><td><b>Font Style<\\/td><\\/tr>");
1.44      ng       1613:   }
                   1614: 
                   1615:   function highlightbody(clrval,clrtxt,clrsel,szval,sztxt,szsel,syval,sytxt,sysel) { 
1.76      ng       1616:     var hDoc = hwdWin.document;
                   1617:     hDoc.write("<tr bgcolor=\\"#ffffdd\\">");
                   1618:     hDoc.write("<td align=\\"left\\">");
1.465     albertel 1619:     hDoc.write("<input name=\\"kwdclr\\" type=\\"radio\\" value=\\""+clrval+"\\" "+clrsel+">&nbsp;"+clrtxt+"<\\/td>");
1.76      ng       1620:     hDoc.write("<td align=\\"left\\">");
1.465     albertel 1621:     hDoc.write("<input name=\\"kwdsize\\" type=\\"radio\\" value=\\""+szval+"\\" "+szsel+">&nbsp;"+sztxt+"<\\/td>");
1.76      ng       1622:     hDoc.write("<td align=\\"left\\">");
1.465     albertel 1623:     hDoc.write("<input name=\\"kwdstyle\\" type=\\"radio\\" value=\\""+syval+"\\" "+sysel+">&nbsp;"+sytxt+"<\\/td>");
                   1624:     hDoc.write("<\\/tr>");
1.44      ng       1625:   }
                   1626: 
                   1627:   function highlightend() { 
1.76      ng       1628:     var hDoc = hwdWin.document;
1.465     albertel 1629:     hDoc.write("<\\/table>");
                   1630:     hDoc.write("<\\/td><\\/tr><\\/table>&nbsp;");
1.589     bisitz   1631:     hDoc.write("<input type=\\"button\\" value=\\"Save\\" onclick=\\"javascript:updateChoice(1)\\">&nbsp;&nbsp;");
                   1632:     hDoc.write("<input type=\\"button\\" value=\\"Cancel\\" onclick=\\"self.close()\\"><br /><br />");
1.465     albertel 1633:     hDoc.write("<\\/form>");
1.351     albertel 1634:     hDoc.write('$end_page_highlight_central');
1.128     ng       1635:     hDoc.close();
1.44      ng       1636:   }
                   1637: 
                   1638: SUBJAVASCRIPT
                   1639: }
                   1640: 
1.349     albertel 1641: sub get_increment {
1.348     bowersj2 1642:     my $increment = $env{'form.increment'};
                   1643:     if ($increment != 1 && $increment != .5 && $increment != .25 &&
                   1644:         $increment != .1) {
                   1645:         $increment = 1;
                   1646:     }
                   1647:     return $increment;
                   1648: }
                   1649: 
1.585     bisitz   1650: sub gradeBox_start {
                   1651:     return (
                   1652:         &Apache::loncommon::start_data_table()
                   1653:        .&Apache::loncommon::start_data_table_header_row()
                   1654:        .'<th>'.&mt('Part').'</th>'
                   1655:        .'<th>'.&mt('Points').'</th>'
                   1656:        .'<th>&nbsp;</th>'
                   1657:        .'<th>'.&mt('Assign Grade').'</th>'
                   1658:        .'<th>'.&mt('Weight').'</th>'
                   1659:        .'<th>'.&mt('Grade Status').'</th>'
                   1660:        .&Apache::loncommon::end_data_table_header_row()
                   1661:     );
                   1662: }
                   1663: 
                   1664: sub gradeBox_end {
                   1665:     return (
                   1666:         &Apache::loncommon::end_data_table()
                   1667:     );
                   1668: }
1.71      ng       1669: #--- displays the grading box, used in essay type problem and grading by page/sequence
                   1670: sub gradeBox {
1.322     albertel 1671:     my ($request,$symb,$uname,$udom,$counter,$partid,$record) = @_;
1.381     albertel 1672:     my $checkIcon = '<img alt="'.&mt('Check Mark').
1.485     albertel 1673: 	'" src="'.&Apache::loncommon::lonhttpdurl($request->dir_config('lonIconsURL').'/check.gif').'" height="16" border="0" />';
1.71      ng       1674:     my $wgt    = &Apache::lonnet::EXT('resource.'.$partid.'.weight',$symb,$udom,$uname);
1.466     albertel 1675:     my $wgtmsg = ($wgt > 0) ? &mt('(problem weight)') 
                   1676:                            : '<span class="LC_info">'.&mt('problem weight assigned by computer').'</span>';
1.71      ng       1677:     $wgt       = ($wgt > 0 ? $wgt : '1');
                   1678:     my $score  = ($$record{'resource.'.$partid.'.awarded'} eq '' ?
1.320     albertel 1679: 		  '' : &compute_points($$record{'resource.'.$partid.'.awarded'},$wgt));
1.71      ng       1680:     my $result='<input type="hidden" name="WGT'.$counter.'_'.$partid.'" value="'.$wgt.'" />'."\n";
1.466     albertel 1681:     my $display_part= &get_display_part($partid,$symb);
1.270     albertel 1682:     my %last_resets = &get_last_resets($symb,$env{'request.course.id'},
                   1683: 				       [$partid]);
                   1684:     my $aggtries = $$record{'resource.'.$partid.'.tries'};
1.269     raeburn  1685:     if ($last_resets{$partid}) {
                   1686:         $aggtries = &get_num_tries($record,$last_resets{$partid},$partid);
                   1687:     }
1.585     bisitz   1688:     $result.=&Apache::loncommon::start_data_table_row();
1.71      ng       1689:     my $ctr = 0;
1.348     bowersj2 1690:     my $thisweight = 0;
1.349     albertel 1691:     my $increment = &get_increment();
1.485     albertel 1692: 
                   1693:     my $radio.='<table border="0"><tr>'."\n";  # display radio buttons in a nice table 10 across
1.348     bowersj2 1694:     while ($thisweight<=$wgt) {
1.532     bisitz   1695: 	$radio.= '<td><span class="LC_nobreak"><label><input type="radio" name="RADVAL'.$counter.'_'.$partid.'" '.
1.589     bisitz   1696:         'onclick="javascript:writeBox(this.form,\''.$counter.'_'.$partid.'\','.
1.348     bowersj2 1697: 	    $thisweight.')" value="'.$thisweight.'" '.
1.401     albertel 1698: 	    ($score eq $thisweight ? 'checked="checked"':'').' /> '.$thisweight."</label></span></td>\n";
1.485     albertel 1699: 	$radio.=(($ctr+1)%10 == 0 ? '</tr><tr>' : '');
1.348     bowersj2 1700:         $thisweight += $increment;
1.71      ng       1701: 	$ctr++;
                   1702:     }
1.485     albertel 1703:     $radio.='</tr></table>';
                   1704: 
                   1705:     my $line.='<input type="text" name="GD_BOX'.$counter.'_'.$partid.'"'.
1.71      ng       1706: 	($score ne ''? ' value = "'.$score.'"':'').' size="4" '.
1.589     bisitz   1707: 	'onchange="javascript:updateRadio(this.form,\''.$counter.'_'.$partid.'\','.
1.71      ng       1708: 	$wgt.')" /></td>'."\n";
1.485     albertel 1709:     $line.='<td>/'.$wgt.' '.$wgtmsg.
1.71      ng       1710: 	($$record{'resource.'.$partid.'.solved'} eq 'correct_by_student' ? '&nbsp;'.$checkIcon : '').
1.585     bisitz   1711: 	' </td>'."\n";
                   1712:     $line.='<td><select name="GD_SEL'.$counter.'_'.$partid.'" '.
1.589     bisitz   1713: 	'onchange="javascript:clearRadBox(this.form,\''.$counter.'_'.$partid.'\')" >'."\n";
1.71      ng       1714:     if ($$record{'resource.'.$partid.'.solved'} eq 'excused') {
1.485     albertel 1715: 	$line.='<option></option>'.
                   1716: 	    '<option value="excused" selected="selected">'.&mt('excused').'</option>';
1.71      ng       1717:     } else {
1.485     albertel 1718: 	$line.='<option selected="selected"></option>'.
                   1719: 	    '<option value="excused" >'.&mt('excused').'</option>';
1.71      ng       1720:     }
1.485     albertel 1721:     $line.='<option value="reset status">'.&mt('reset status').'</option></select>'."\n";
                   1722: 
                   1723: 
                   1724:     $result .= 
1.585     bisitz   1725: 	    '<td>'.$display_part.'</td><td>'.$radio.'</td><td>'.&mt('or').'</td><td>'.$line.'</td>';
                   1726:     $result.=&Apache::loncommon::end_data_table_row();
1.71      ng       1727:     $result.='<input type="hidden" name="stores'.$counter.'_'.$partid.'" value="" />'."\n".
                   1728: 	'<input type="hidden" name="oldpts'.$counter.'_'.$partid.'" value="'.$score.'" />'."\n".
                   1729: 	'<input type="hidden" name="solved'.$counter.'_'.$partid.'" value="'.
1.269     raeburn  1730: 	$$record{'resource.'.$partid.'.solved'}.'" />'."\n".
                   1731:         '<input type="hidden" name="totaltries'.$counter.'_'.$partid.'" value="'.
                   1732:         $$record{'resource.'.$partid.'.tries'}.'" />'."\n".
                   1733:         '<input type="hidden" name="aggtries'.$counter.'_'.$partid.'" value="'.
                   1734:         $aggtries.'" />'."\n";
1.582     raeburn  1735:     my $res_error;
                   1736:     $result.=&handback_box($symb,$uname,$udom,$counter,$partid,$record,\$res_error);
                   1737:     if ($res_error) {
                   1738:         return &navmap_errormsg();
                   1739:     }
1.318     banghart 1740:     return $result;
                   1741: }
1.322     albertel 1742: 
                   1743: sub handback_box {
1.582     raeburn  1744:     my ($symb,$uname,$udom,$counter,$partid,$record,$res_error) = @_;
                   1745:     my ($partlist,$handgrade,$responseType) = &response_type($symb,$res_error);
1.323     banghart 1746:     my (@respids);
1.375     albertel 1747:      my @part_response_id = &flatten_responseType($responseType);
                   1748:     foreach my $part_response_id (@part_response_id) {
                   1749:     	my ($part,$resp) = @{ $part_response_id };
1.323     banghart 1750:         if ($part eq $partid) {
1.375     albertel 1751:             push(@respids,$resp);
1.323     banghart 1752:         }
                   1753:     }
1.318     banghart 1754:     my $result;
1.323     banghart 1755:     foreach my $respid (@respids) {
1.322     albertel 1756: 	my $prefix = $counter.'_'.$partid.'_'.$respid.'_';
                   1757: 	my $files=&get_submitted_files($udom,$uname,$partid,$respid,$record);
                   1758: 	next if (!@$files);
                   1759: 	my $file_counter = 1;
1.313     banghart 1760: 	foreach my $file (@$files) {
1.368     banghart 1761: 	    if ($file =~ /\/portfolio\//) {
                   1762:     	        my ($file_path, $file_disp) = ($file =~ m|(.+/)(.+)$|);
                   1763:     	        my ($name,$version,$ext) = &file_name_version_ext($file_disp);
                   1764:     	        $file_disp = "$name.$ext";
                   1765:     	        $file = $file_path.$file_disp;
                   1766:     	        $result.=&mt('Return commented version of [_1] to student.',
                   1767:     			 '<span class="LC_filename">'.$file_disp.'</span>');
                   1768:     	        $result.='<input type="file"   name="'.$prefix.'returndoc'.$file_counter.'" />'."\n";
                   1769:     	        $result.='<input type="hidden" name="'.$prefix.'origdoc'.$file_counter.'" value="'.$file.'" /><br />';
1.485     albertel 1770:     	        $result.='('.&mt('File will be uploaded when you click on Save &amp; Next below.').')<br />';
1.368     banghart 1771:     	        $file_counter++;
                   1772: 	    }
1.322     albertel 1773: 	}
1.313     banghart 1774:     }
1.318     banghart 1775:     return $result;    
1.71      ng       1776: }
1.44      ng       1777: 
1.58      albertel 1778: sub show_problem {
1.382     albertel 1779:     my ($request,$symb,$uname,$udom,$removeform,$viewon,$mode,$form) = @_;
1.144     albertel 1780:     my $rendered;
1.382     albertel 1781:     my %form = ((ref($form) eq 'HASH')? %{$form} : ());
1.329     albertel 1782:     &Apache::lonxml::remember_problem_counter();
1.144     albertel 1783:     if ($mode eq 'both' or $mode eq 'text') {
                   1784: 	$rendered=&Apache::loncommon::get_student_view($symb,$uname,$udom,
1.382     albertel 1785: 						       $env{'request.course.id'},
                   1786: 						       undef,\%form);
1.144     albertel 1787:     }
1.58      albertel 1788:     if ($removeform) {
                   1789: 	$rendered=~s|<form(.*?)>||g;
                   1790: 	$rendered=~s|</form>||g;
1.374     albertel 1791: 	$rendered=~s|(<input[^>]*name\s*=\s*"?)(\w+)("?)|$1would_have_been_$2$3|g;
1.58      albertel 1792:     }
1.144     albertel 1793:     my $companswer;
                   1794:     if ($mode eq 'both' or $mode eq 'answer') {
1.329     albertel 1795: 	&Apache::lonxml::restore_problem_counter();
1.382     albertel 1796: 	$companswer=
                   1797: 	    &Apache::loncommon::get_student_answers($symb,$uname,$udom,
                   1798: 						    $env{'request.course.id'},
                   1799: 						    %form);
1.144     albertel 1800:     }
1.58      albertel 1801:     if ($removeform) {
                   1802: 	$companswer=~s|<form(.*?)>||g;
                   1803: 	$companswer=~s|</form>||g;
1.144     albertel 1804: 	$companswer=~s|name="submit"|name="would_have_been_submit"|g;
1.58      albertel 1805:     }
1.468     albertel 1806:     $rendered=
1.588     bisitz   1807:         '<div class="LC_Box">'
                   1808:        .'<h3 class="LC_hcell">'.&mt('View of the problem').'</h3>'
                   1809:        .$rendered
                   1810:        .'</div>';
1.468     albertel 1811:     $companswer=
1.588     bisitz   1812:         '<div class="LC_Box">'
                   1813:        .'<h3 class="LC_hcell">'.&mt('Correct answer').'</h3>'
                   1814:        .$companswer
                   1815:        .'</div>';
1.468     albertel 1816:     my $result;
1.144     albertel 1817:     if ($mode eq 'both') {
1.588     bisitz   1818:         $result=$rendered.$companswer;
1.144     albertel 1819:     } elsif ($mode eq 'text') {
1.588     bisitz   1820:         $result=$rendered;
1.144     albertel 1821:     } elsif ($mode eq 'answer') {
1.588     bisitz   1822:         $result=$companswer;
1.144     albertel 1823:     }
1.71      ng       1824:     return $result;
1.58      albertel 1825: }
1.397     albertel 1826: 
1.396     banghart 1827: sub files_exist {
                   1828:     my ($r, $symb) = @_;
                   1829:     my @students = &Apache::loncommon::get_env_multiple('form.stuinfo');
1.397     albertel 1830: 
1.396     banghart 1831:     foreach my $student (@students) {
                   1832:         my ($uname,$udom,$fullname) = split(/:/,$student);
1.397     albertel 1833:         my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},
                   1834: 					      $udom,$uname);
1.396     banghart 1835:         my ($string,$timestamp)= &get_last_submission(\%record);
1.397     albertel 1836:         foreach my $submission (@$string) {
                   1837:             my ($partid,$respid) =
                   1838: 		($submission =~ /^resource\.([^\.]*)\.([^\.]*)\.submission/);
                   1839:             my $files=&get_submitted_files($udom,$uname,$partid,$respid,
                   1840: 					   \%record);
                   1841:             return 1 if (@$files);
1.396     banghart 1842:         }
                   1843:     }
1.397     albertel 1844:     return 0;
1.396     banghart 1845: }
1.397     albertel 1846: 
1.394     banghart 1847: sub download_all_link {
                   1848:     my ($r,$symb) = @_;
1.621     www      1849:     unless (&files_exist($r, $symb)) {
                   1850:        $r->print(&mt('There are currently no submitted documents.'));
                   1851:        return;
                   1852:     }
                   1853: 
1.395     albertel 1854:     my $all_students = 
                   1855: 	join("\n", &Apache::loncommon::get_env_multiple('form.stuinfo'));
                   1856: 
                   1857:     my $parts =
                   1858: 	join("\n",&Apache::loncommon::get_env_multiple('form.vPart'));
                   1859: 
1.394     banghart 1860:     my $identifier = &Apache::loncommon::get_cgi_id();
1.514     raeburn  1861:     &Apache::lonnet::appenv({'cgi.'.$identifier.'.students' => $all_students,
                   1862:                              'cgi.'.$identifier.'.symb' => $symb,
                   1863:                              'cgi.'.$identifier.'.parts' => $parts,});
1.395     albertel 1864:     $r->print('<a href="/cgi-bin/multidownload.pl?'.$identifier.'">'.
                   1865: 	      &mt('Download All Submitted Documents').'</a>');
1.621     www      1866:     return;
                   1867: }
                   1868: 
                   1869: sub submit_download_link {
                   1870:     my ($request,$symb) = @_;
                   1871:     if (!$symb) { return ''; }
                   1872: #FIXME: Figure out which type of problem this is and provide appropriate download
                   1873:     &download_all_link($request,$symb);
1.394     banghart 1874: }
1.395     albertel 1875: 
1.432     banghart 1876: sub build_section_inputs {
                   1877:     my $section_inputs;
                   1878:     if ($env{'form.section'} eq '') {
                   1879:         $section_inputs .= '<input type="hidden" name="section" value="all" />'."\n";
                   1880:     } else {
                   1881:         my @sections = &Apache::loncommon::get_env_multiple('form.section');
1.434     albertel 1882:         foreach my $section (@sections) {
1.432     banghart 1883:             $section_inputs .= '<input type="hidden" name="section" value="'.$section.'" />'."\n";
                   1884:         }
                   1885:     }
                   1886:     return $section_inputs;
                   1887: }
                   1888: 
1.44      ng       1889: # --------------------------- show submissions of a student, option to grade 
                   1890: sub submission {
1.608     www      1891:     my ($request,$counter,$total,$symb) = @_;
1.257     albertel 1892:     my ($uname,$udom)     = ($env{'form.student'},$env{'form.userdom'});
                   1893:     $udom = ($udom eq '' ? $env{'user.domain'} : $udom); #has form.userdom changed for a student?
                   1894:     my $usec = &Apache::lonnet::getsection($udom,$uname,$env{'request.course.id'});
                   1895:     $env{'form.fullname'} = &Apache::loncommon::plainname($uname,$udom,'lastname') if $env{'form.fullname'} eq '';
1.608     www      1896: 
1.605     www      1897:     my $probtitle=&Apache::lonnet::gettitle($symb); 
1.324     albertel 1898:     if ($symb eq '') { $request->print("Unable to handle ambiguous references:."); return ''; }
1.104     albertel 1899: 
                   1900:     if (!&canview($usec)) {
1.398     albertel 1901: 	$request->print('<span class="LC_warning">Unable to view requested student.('.
                   1902: 			$uname.':'.$udom.' in section '.$usec.' in course id '.
                   1903: 			$env{'request.course.id'}.')</span>');
1.104     albertel 1904: 	return;
                   1905:     }
                   1906: 
1.257     albertel 1907:     if (!$env{'form.lastSub'}) { $env{'form.lastSub'} = 'datesub'; }
                   1908:     if (!$env{'form.vProb'}) { $env{'form.vProb'} = 'yes'; }
                   1909:     if (!$env{'form.vAns'}) { $env{'form.vAns'} = 'yes'; }
                   1910:     my $last = ($env{'form.lastSub'} eq 'last' ? 'last' : '');
1.381     albertel 1911:     my $checkIcon = '<img alt="'.&mt('Check Mark').
                   1912: 	'" src="'.$request->dir_config('lonIconsURL').
1.122     ng       1913: 	'/check.gif" height="16" border="0" />';
1.41      ng       1914: 
1.426     albertel 1915:     my %old_essays;
1.41      ng       1916:     # header info
                   1917:     if ($counter == 0) {
                   1918: 	&sub_page_js($request);
1.621     www      1919: 	&sub_page_kw_js($request);
1.605     www      1920: 	$request->print('<h3>&nbsp;<span class="LC_info">'.&mt('Submission Record').'</span></h3>');
1.118     ng       1921: 
1.44      ng       1922: 	# option to display problem, only once else it cause problems 
                   1923:         # with the form later since the problem has a form.
1.257     albertel 1924: 	if ($env{'form.vProb'} eq 'yes' or $env{'form.vAns'} eq 'yes') {
1.144     albertel 1925: 	    my $mode;
1.257     albertel 1926: 	    if ($env{'form.vProb'} eq 'yes' && $env{'form.vAns'} eq 'yes') {
1.144     albertel 1927: 		$mode='both';
1.257     albertel 1928: 	    } elsif ($env{'form.vProb'} eq 'yes') {
1.144     albertel 1929: 		$mode='text';
1.257     albertel 1930: 	    } elsif ($env{'form.vAns'} eq 'yes') {
1.144     albertel 1931: 		$mode='answer';
                   1932: 	    }
1.329     albertel 1933: 	    &Apache::lonxml::clear_problem_counter();
1.144     albertel 1934: 	    $request->print(&show_problem($request,$symb,$uname,$udom,0,1,$mode));
1.41      ng       1935: 	}
1.441     www      1936: 
1.44      ng       1937: 	# kwclr is the only variable that is guaranteed to be non blank 
                   1938:         # if this subroutine has been called once.
1.41      ng       1939: 	my %keyhash = ();
1.257     albertel 1940: 	if ($env{'form.kwclr'} eq '' && $env{'form.handgrade'} eq 'yes') {
1.41      ng       1941: 	    %keyhash = &Apache::lonnet::dump('nohist_handgrade',
1.257     albertel 1942: 					     $env{'course.'.$env{'request.course.id'}.'.domain'},
                   1943: 					     $env{'course.'.$env{'request.course.id'}.'.num'});
1.41      ng       1944: 
1.257     albertel 1945: 	    my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
                   1946: 	    $env{'form.keywords'} = $keyhash{$symb.'_keywords'} ne '' ? $keyhash{$symb.'_keywords'} : '';
                   1947: 	    $env{'form.kwclr'}    = $keyhash{$loginuser.'_kwclr'} ne '' ? $keyhash{$loginuser.'_kwclr'} : 'red';
                   1948: 	    $env{'form.kwsize'}   = $keyhash{$loginuser.'_kwsize'} ne '' ? $keyhash{$loginuser.'_kwsize'} : '0';
                   1949: 	    $env{'form.kwstyle'}  = $keyhash{$loginuser.'_kwstyle'} ne '' ? $keyhash{$loginuser.'_kwstyle'} : '';
                   1950: 	    $env{'form.msgsub'}   = $keyhash{$symb.'_subject'} ne '' ? 
1.605     www      1951: 		$keyhash{$symb.'_subject'} : $probtitle;
1.257     albertel 1952: 	    $env{'form.savemsgN'} = $keyhash{$symb.'_savemsgN'} ne '' ? $keyhash{$symb.'_savemsgN'} : '0';
1.41      ng       1953: 	}
1.257     albertel 1954: 	my $overRideScore = $env{'form.overRideScore'} eq '' ? 'no' : $env{'form.overRideScore'};
1.442     banghart 1955: 	my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
1.303     banghart 1956: 	$request->print('<form action="/adm/grades" method="post" name="SCORE" enctype="multipart/form-data">'."\n".
1.41      ng       1957: 			'<input type="hidden" name="command"    value="handgrade" />'."\n".
1.442     banghart 1958: 			'<input type="hidden" name="Status"     value="'.$stu_status.'" />'."\n".
1.120     ng       1959: 			'<input type="hidden" name="overRideScore" value="'.$overRideScore.'" />'."\n".
1.41      ng       1960: 			'<input type="hidden" name="refresh"    value="off" />'."\n".
1.120     ng       1961: 			'<input type="hidden" name="studentNo"  value="" />'."\n".
                   1962: 			'<input type="hidden" name="gradeOpt"   value="" />'."\n".
1.418     albertel 1963: 			'<input type="hidden" name="symb"       value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.257     albertel 1964: 			'<input type="hidden" name="vProb"      value="'.$env{'form.vProb'}.'" />'."\n".
                   1965: 			'<input type="hidden" name="vAns"       value="'.$env{'form.vAns'}.'" />'."\n".
                   1966: 			'<input type="hidden" name="lastSub"    value="'.$env{'form.lastSub'}.'" />'."\n".
1.432     banghart 1967: 			&build_section_inputs().
1.326     albertel 1968: 			'<input type="hidden" name="submitonly" value="'.$env{'form.submitonly'}.'" />'."\n".
                   1969: 			'<input type="hidden" name="handgrade"  value="'.$env{'form.handgrade'}.'" />'."\n".
1.41      ng       1970: 			'<input type="hidden" name="NCT"'.
1.257     albertel 1971: 			' value="'.($env{'form.NTSTU'} ne '' ? $env{'form.NTSTU'} : $total+1).'" />'."\n");
                   1972: 	if ($env{'form.handgrade'} eq 'yes') {
                   1973: 	    $request->print('<input type="hidden" name="keywords" value="'.$env{'form.keywords'}.'" />'."\n".
                   1974: 			    '<input type="hidden" name="kwclr"    value="'.$env{'form.kwclr'}.'" />'."\n".
                   1975: 			    '<input type="hidden" name="kwsize"   value="'.$env{'form.kwsize'}.'" />'."\n".
                   1976: 			    '<input type="hidden" name="kwstyle"  value="'.$env{'form.kwstyle'}.'" />'."\n".
                   1977: 			    '<input type="hidden" name="msgsub"   value="'.$env{'form.msgsub'}.'" />'."\n".
1.123     ng       1978: 			    '<input type="hidden" name="shownSub" value="0" />'."\n".
1.257     albertel 1979: 			    '<input type="hidden" name="savemsgN" value="'.$env{'form.savemsgN'}.'" />'."\n");
1.154     albertel 1980: 	    foreach my $partid (&Apache::loncommon::get_env_multiple('form.vPart')) {
                   1981: 		$request->print('<input type="hidden" name="vPart" value="'.$partid.'" />'."\n");
                   1982: 	    }
1.123     ng       1983: 	}
1.41      ng       1984: 	
                   1985: 	my ($cts,$prnmsg) = (1,'');
1.257     albertel 1986: 	while ($cts <= $env{'form.savemsgN'}) {
1.41      ng       1987: 	    $prnmsg.='<input type="hidden" name="savemsg'.$cts.'" value="'.
1.123     ng       1988: 		(!exists($keyhash{$symb.'_savemsg'.$cts}) ? 
1.257     albertel 1989: 		 &Apache::lonfeedback::clear_out_html($env{'form.savemsg'.$cts}) :
1.80      ng       1990: 		 &Apache::lonfeedback::clear_out_html($keyhash{$symb.'_savemsg'.$cts})).
1.123     ng       1991: 		'" />'."\n".
                   1992: 		'<input type="hidden" name="shownOnce'.$cts.'" value="0" />'."\n";
1.41      ng       1993: 	    $cts++;
                   1994: 	}
                   1995: 	$request->print($prnmsg);
1.32      ng       1996: 
1.618     www      1997: 	if ($env{'form.handgrade'} eq 'yes') {
1.88      www      1998: #
                   1999: # Print out the keyword options line
                   2000: #
1.41      ng       2001: 	    $request->print(<<KEYWORDS);
1.38      ng       2002: &nbsp;<b>Keyword Options:</b>&nbsp;
1.417     albertel 2003: <a href="javascript:keywords(document.SCORE);" target="_self">List</a>&nbsp; &nbsp;
1.589     bisitz   2004: <a href="#" onmousedown="javascript:getSel(); return false"
1.38      ng       2005:  CLASS="page">Paste Selection to List</a>&nbsp; &nbsp;
1.417     albertel 2006: <a href="javascript:kwhighlight();" target="_self">Highlight Attribute</a><br /><br />
1.38      ng       2007: KEYWORDS
1.88      www      2008: #
                   2009: # Load the other essays for similarity check
                   2010: #
1.324     albertel 2011:             my (undef,undef,$essayurl) = &Apache::lonnet::decode_symb($symb);
1.384     albertel 2012: 	    my ($adom,$aname,$apath)=($essayurl=~/^($LONCAPA::domain_re)\/($LONCAPA::username_re)\/(.*)$/);
1.359     www      2013: 	    $apath=&escape($apath);
1.88      www      2014: 	    $apath=~s/\W/\_/gs;
1.426     albertel 2015: 	    %old_essays=&Apache::lonnet::dump('nohist_essay_'.$apath,$adom,$aname);
1.41      ng       2016:         }
                   2017:     }
1.44      ng       2018: 
1.441     www      2019: # This is where output for one specific student would start
1.592     bisitz   2020:     my $add_class = ($counter%2) ? ' LC_grade_show_user_odd_row' : '';
                   2021:     $request->print(
                   2022:         "\n\n"
                   2023:        .'<div class="LC_grade_show_user'.$add_class.'">'
                   2024:        .'<h2>'.&nameUserString(undef,$env{'form.fullname'},$uname,$udom).'</h2>'
                   2025:        ."\n"
                   2026:     );
1.441     www      2027: 
1.592     bisitz   2028:     # Show additional functions if allowed
                   2029:     if ($perm{'vgr'}) {
                   2030:         $request->print(
                   2031:             &Apache::loncommon::track_student_link(
                   2032:                 &mt('View recent activity'),
                   2033:                 $uname,$udom,'check')
                   2034:            .' '
                   2035:         );
                   2036:     }
                   2037:     if ($perm{'opa'}) {
                   2038:         $request->print(
                   2039:             &Apache::loncommon::pprmlink(
                   2040:                 &mt('Set/Change parameters'),
                   2041:                 $uname,$udom,$symb,'check'));
                   2042:     }
                   2043: 
                   2044:     # Show Problem
1.257     albertel 2045:     if ($env{'form.vProb'} eq 'all' or $env{'form.vAns'} eq 'all') {
1.144     albertel 2046: 	my $mode;
1.257     albertel 2047: 	if ($env{'form.vProb'} eq 'all' && $env{'form.vAns'} eq 'all') {
1.144     albertel 2048: 	    $mode='both';
1.257     albertel 2049: 	} elsif ($env{'form.vProb'} eq 'all' ) {
1.144     albertel 2050: 	    $mode='text';
1.257     albertel 2051: 	} elsif ($env{'form.vAns'} eq 'all') {
1.144     albertel 2052: 	    $mode='answer';
                   2053: 	}
1.329     albertel 2054: 	&Apache::lonxml::clear_problem_counter();
1.475     albertel 2055: 	$request->print(&show_problem($request,$symb,$uname,$udom,1,1,$mode,{'request.prefix' => 'ctr'.$counter}));
1.58      albertel 2056:     }
1.144     albertel 2057: 
1.257     albertel 2058:     my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
1.582     raeburn  2059:     my $res_error;
                   2060:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
                   2061:     if ($res_error) {
                   2062:         $request->print(&navmap_errormsg());
                   2063:         return;
                   2064:     }
1.41      ng       2065: 
1.44      ng       2066:     # Display student info
1.41      ng       2067:     $request->print(($counter == 0 ? '' : '<br />'));
1.590     bisitz   2068: 
                   2069:     my $result='<div class="LC_Box">'
                   2070:               .'<h3 class="LC_hcell">'.&mt('Submissions').'</h3>';
1.45      ng       2071:     $result.='<input type="hidden" name="name'.$counter.
1.588     bisitz   2072:              '" value="'.$env{'form.fullname'}.'" />'."\n";
1.469     albertel 2073:     if ($env{'form.handgrade'} eq 'no') {
1.588     bisitz   2074:         $result.='<p class="LC_info">'
                   2075:                 .&mt('Part(s) graded correct by the computer is marked with a [_1] symbol.',$checkIcon)
                   2076:                 ."</p>\n";
1.469     albertel 2077:     }
                   2078: 
1.118     ng       2079:     # If any part of the problem is an essay-response (handgraded), then check for collaborators
1.464     albertel 2080:     my $fullname;
                   2081:     my $col_fullnames = [];
1.257     albertel 2082:     if ($env{'form.handgrade'} eq 'yes') {
1.464     albertel 2083: 	(my $sub_result,$fullname,$col_fullnames)=
                   2084: 	    &check_collaborators($symb,$uname,$udom,\%record,$handgrade,
                   2085: 				 $counter);
                   2086: 	$result.=$sub_result;
1.41      ng       2087:     }
1.44      ng       2088:     $request->print($result."\n");
1.588     bisitz   2089: 
1.44      ng       2090:     # print student answer/submission
1.588     bisitz   2091:     # Options are (1) Handgraded submission only
1.44      ng       2092:     #             (2) Last submission, includes submission that is not handgraded 
                   2093:     #                  (for multi-response type part)
                   2094:     #             (3) Last submission plus the parts info
                   2095:     #             (4) The whole record for this student
1.257     albertel 2096:     if ($env{'form.lastSub'} =~ /^(lastonly|hdgrade)$/) {
1.151     albertel 2097: 	my ($string,$timestamp)= &get_last_submission(\%record);
1.468     albertel 2098: 	
                   2099: 	my $lastsubonly;
                   2100: 
1.588     bisitz   2101:         if ($$timestamp eq '') {
                   2102:             $lastsubonly.='<div class="LC_grade_submissions_body">'.$$string[0].'</div>'; 
                   2103:         } else {
1.592     bisitz   2104:             $lastsubonly =
                   2105:                 '<div class="LC_grade_submissions_body">'
                   2106:                .'<b>'.&mt('Date Submitted:').'</b> '.$$timestamp."\n";
1.468     albertel 2107: 
1.151     albertel 2108: 	    my %seenparts;
1.375     albertel 2109: 	    my @part_response_id = &flatten_responseType($responseType);
                   2110: 	    foreach my $part (@part_response_id) {
1.393     albertel 2111: 		next if ($env{'form.lastSub'} eq 'hdgrade' 
                   2112: 			 && $$handgrade{$$part[0].'_'.$$part[1]} ne 'yes');
                   2113: 
1.375     albertel 2114: 		my ($partid,$respid) = @{ $part };
1.324     albertel 2115: 		my $display_part=&get_display_part($partid,$symb);
1.257     albertel 2116: 		if ($env{"form.$uname:$udom:$partid:submitted_by"}) {
1.151     albertel 2117: 		    if (exists($seenparts{$partid})) { next; }
                   2118: 		    $seenparts{$partid}=1;
1.207     albertel 2119: 		    my $submitby='<b>Part:</b> '.$display_part.
                   2120: 			' <b>Collaborative submission by:</b> '.
1.151     albertel 2121: 			'<a href="javascript:viewSubmitter(\''.
1.257     albertel 2122: 			$env{"form.$uname:$udom:$partid:submitted_by"}.
1.417     albertel 2123: 			'\');" target="_self">'.
1.257     albertel 2124: 			$$fullname{$env{"form.$uname:$udom:$partid:submitted_by"}}.'</a><br />';
1.151     albertel 2125: 		    $request->print($submitby);
                   2126: 		    next;
                   2127: 		}
                   2128: 		my $responsetype = $responseType->{$partid}->{$respid};
                   2129: 		if (!exists($record{"resource.$partid.$respid.submission"})) {
1.577     bisitz   2130:                     $lastsubonly.="\n".'<div class="LC_grade_submission_part">'.
                   2131:                         '<b>'.&mt('Part: [_1]',$display_part).'</b>'.
                   2132:                         ' <span class="LC_internal_info">'.
1.597     wenzelju 2133:                         '('.&mt('Part ID: [_1]',$respid).')'.
1.577     bisitz   2134:                         '</span>&nbsp; &nbsp;'.
1.539     riegler  2135: 			'<span class="LC_warning">'.&mt('Nothing submitted - no attempts.').'</span><br /><br /></div>';
1.151     albertel 2136: 		    next;
                   2137: 		}
1.468     albertel 2138: 		foreach my $submission (@$string) {
                   2139: 		    my ($partid,$respid) = ($submission =~ /^resource\.([^\.]*)\.([^\.]*)\.submission/);
1.375     albertel 2140: 		    if (join('_',@{$part}) ne ($partid.'_'.$respid)) { next; }
1.596     raeburn  2141: 		    my ($ressub,$hide,$subval) = split(/:/,$submission,3);
1.151     albertel 2142: 		    # Similarity check
                   2143: 		    my $similar='';
1.257     albertel 2144: 		    if($env{'form.checkPlag'}){
1.151     albertel 2145: 			my ($oname,$odom,$ocrsid,$oessay,$osim)=
1.426     albertel 2146: 			    &most_similar($uname,$udom,$subval,\%old_essays);
1.151     albertel 2147: 			if ($osim) {
                   2148: 			    $osim=int($osim*100.0);
1.426     albertel 2149: 			    my %old_course_desc = 
                   2150: 				&Apache::lonnet::coursedescription($ocrsid,
                   2151: 								   {'one_time' => 1});
                   2152: 
1.596     raeburn  2153:                             if ($hide) {
                   2154:                                 $similar='<hr /><span class="LC_warning">'.&mt("Essay was found to be similar to another essay submitted for this assignment.").'<br />'.
                   2155:                                          &mt('As the current submission is for an anonymous survey, no other details are available.').'</span><hr />';
                   2156:                             } else {
                   2157: 			        $similar="<hr /><h3><span class=\"LC_warning\">".
                   2158: 				    &mt('Essay is [_1]% similar to an essay by [_2] in course [_3] (course id [_4]:[_5])',
                   2159: 				        $osim,
                   2160: 				        &Apache::loncommon::plainname($oname,$odom).' ('.$oname.':'.$odom.')',
                   2161: 				        $old_course_desc{'description'},
                   2162: 				        $old_course_desc{'num'},
                   2163: 				        $old_course_desc{'domain'}).
                   2164: 				    '</span></h3><blockquote><i>'.
                   2165: 				    &keywords_highlight($oessay).
                   2166: 				    '</i></blockquote><hr />';
                   2167:                             }
1.151     albertel 2168: 			}
1.150     albertel 2169: 		    }
1.151     albertel 2170: 		    my $order=&get_order($partid,$respid,$symb,$uname,$udom);
1.257     albertel 2171: 		    if ($env{'form.lastSub'} eq 'lastonly' || 
                   2172: 			($env{'form.lastSub'} eq 'hdgrade' && 
1.377     albertel 2173: 			 $$handgrade{$$part[0].'_'.$$part[1]} eq 'yes')) {
1.324     albertel 2174: 			my $display_part=&get_display_part($partid,$symb);
1.577     bisitz   2175:                         $lastsubonly.='<div class="LC_grade_submission_part">'.
                   2176:                             '<b>'.&mt('Part: [_1]',$display_part).'</b>'.
                   2177:                             ' <span class="LC_internal_info">'.
                   2178:                             '('.&mt('Part ID: [_1]',$respid).')'.
1.597     wenzelju 2179:                             '</span>&nbsp; &nbsp;';
1.313     banghart 2180: 			my $files=&get_submitted_files($udom,$uname,$partid,$respid,\%record);
                   2181: 			if (@$files) {
1.596     raeburn  2182:                             if ($hide) {
                   2183:                                 $lastsubonly.='<br />'.&mt('[quant,_1,file] uploaded to this anonymous survey',scalar(@{$files}));
                   2184:                             } else {
                   2185:                                 $lastsubonly.='<br /><span class="LC_warning">'.&mt('Like all files provided by users, this file may contain viruses').'</span><br />';
                   2186:                                 foreach my $file (@$files) {
                   2187:                                     &Apache::lonnet::allowuploaded('/adm/grades',$file);
                   2188:                                     $lastsubonly.='<br /><a href="'.$file.'?rawmode=1" target="lonGRDs"><img src="'.&Apache::loncommon::icon($file).'" border="0" /> '.$file.'</a>';
                   2189:                                 }
                   2190:                             }
1.236     albertel 2191: 			    $lastsubonly.='<br />';
1.41      ng       2192: 			}
1.596     raeburn  2193:                         if ($hide) {
                   2194:                             $lastsubonly.='<b>'.&mt('Anonymous Survey').'</b>'; 
                   2195:                         } else {
                   2196: 			    $lastsubonly.='<b>'.&mt('Submitted Answer:').' </b>'.
                   2197: 			        &cleanRecord($subval,$responsetype,$symb,$partid,
                   2198: 					     $respid,\%record,$order,undef,$uname,$udom);
                   2199:                         }
1.151     albertel 2200: 			if ($similar) {$lastsubonly.="<br /><br />$similar\n";}
1.468     albertel 2201: 			$lastsubonly.='</div>';
1.41      ng       2202: 		    }
                   2203: 		}
                   2204: 	    }
1.588     bisitz   2205: 	    $lastsubonly.='</div>'."\n"; # End: LC_grade_submissions_body
1.151     albertel 2206: 	}
                   2207: 	$request->print($lastsubonly);
1.468     albertel 2208:    } elsif ($env{'form.lastSub'} eq 'datesub') {
1.618     www      2209:         my ($parts,$handgrade,$responseType) = &response_type($symb);
1.148     albertel 2210: 	$request->print(&displaySubByDates($symb,\%record,$parts,$responseType,$checkIcon,$uname,$udom));
1.257     albertel 2211:     } elsif ($env{'form.lastSub'} =~ /^(last|all)$/) {
1.41      ng       2212: 	$request->print(&Apache::loncommon::get_previous_attempt($symb,$uname,$udom,
1.257     albertel 2213: 								 $env{'request.course.id'},
1.44      ng       2214: 								 $last,'.submission',
                   2215: 								 'Apache::grades::keywords_highlight'));
1.41      ng       2216:     }
1.120     ng       2217: 
1.121     ng       2218:     $request->print('<input type="hidden" name="unamedom'.$counter.'" value="'.$uname.':'
                   2219: 	.$udom.'" />'."\n");
1.44      ng       2220:     # return if view submission with no grading option
1.619     www      2221: # FIXME: the logic seems off here. Why show the grade button if you cannot grade?
1.618     www      2222:     if (!&canmodify($usec)) {
1.120     ng       2223: 	my $toGrade.='<input type="button" value="Grade Student" '.
1.589     bisitz   2224: 	    'onclick="javascript:checksubmit(this.form,\'Grade Student\',\''
1.417     albertel 2225: 	    .$counter.'\');" target="_self" /> &nbsp;'."\n" if (&canmodify($usec));
1.468     albertel 2226: 	$toGrade.='</div>'."\n";
1.180     albertel 2227: 	$request->print($toGrade);
1.41      ng       2228: 	return;
1.180     albertel 2229:     } else {
1.468     albertel 2230: 	$request->print('</div>'."\n");
1.41      ng       2231:     }
1.33      ng       2232: 
1.121     ng       2233:     # essay grading message center
1.257     albertel 2234:     if ($env{'form.handgrade'} eq 'yes') {
1.468     albertel 2235: 	my $result='<div class="LC_grade_message_center">';
                   2236:     
                   2237: 	$result.='<div class="LC_grade_message_center_header">'.
                   2238: 	    &mt('Send Message').'</div><div class="LC_grade_message_center_body">';
1.257     albertel 2239: 	my ($lastname,$givenn) = split(/,/,$env{'form.fullname'});
1.118     ng       2240: 	my $msgfor = $givenn.' '.$lastname;
1.464     albertel 2241: 	if (scalar(@$col_fullnames) > 0) {
                   2242: 	    my $lastone = pop(@$col_fullnames);
                   2243: 	    $msgfor .= ', '.(join ', ',@$col_fullnames).' and '.$lastone.'.';
1.118     ng       2244: 	}
                   2245: 	$msgfor =~ s/\'/\\'/g; #' stupid emacs - no! javascript
1.468     albertel 2246: 	$result.='<input type="hidden" name="includemsg'.$counter.'" value="" />'."\n".
1.121     ng       2247: 	    '<input type="hidden" name="newmsg'.$counter.'" value="" />'."\n";
                   2248: 	$result.='&nbsp;<a href="javascript:msgCenter(document.SCORE,'.$counter.
1.417     albertel 2249: 	    ',\''.$msgfor.'\');" target="_self">'.
1.464     albertel 2250: 	    &mt('Compose message to student').(scalar(@$col_fullnames) >= 1 ? 's' : '').'</a><label> ('.
1.350     albertel 2251: 	    &mt('incl. grades').' <input type="checkbox" name="withgrades'.$counter.'" /></label>)'.
1.118     ng       2252: 	    '<img src="'.$request->dir_config('lonIconsURL').
                   2253: 	    '/mailbkgrd.gif" width="14" height="10" name="mailicon'.$counter.'" />'."\n".
1.298     www      2254: 	    '<br />&nbsp;('.
1.468     albertel 2255: 	    &mt('Message will be sent when you click on Save &amp; Next below.').")\n";
                   2256: 	$result.='</div></div>';
1.121     ng       2257: 	$request->print($result);
1.118     ng       2258:     }
1.41      ng       2259: 
                   2260:     my %seen = ();
                   2261:     my @partlist;
1.129     ng       2262:     my @gradePartRespid;
1.375     albertel 2263:     my @part_response_id = &flatten_responseType($responseType);
1.585     bisitz   2264:     $request->print(
1.588     bisitz   2265:         '<div class="LC_Box">'
                   2266:        .'<h3 class="LC_hcell">'.&mt('Assign Grades').'</h3>'
1.585     bisitz   2267:     );
1.592     bisitz   2268:     $request->print(&gradeBox_start());
1.375     albertel 2269:     foreach my $part_response_id (@part_response_id) {
                   2270:     	my ($partid,$respid) = @{ $part_response_id };
                   2271: 	my $part_resp = join('_',@{ $part_response_id });
1.322     albertel 2272: 	next if ($seen{$partid} > 0);
1.41      ng       2273: 	$seen{$partid}++;
1.393     albertel 2274: 	next if ($$handgrade{$part_resp} ne 'yes' 
                   2275: 		 && $env{'form.lastSub'} eq 'hdgrade');
1.524     raeburn  2276: 	push(@partlist,$partid);
                   2277: 	push(@gradePartRespid,$partid.'.'.$respid);
1.322     albertel 2278: 	$request->print(&gradeBox($request,$symb,$uname,$udom,$counter,$partid,\%record));
1.41      ng       2279:     }
1.585     bisitz   2280:     $request->print(&gradeBox_end()); # </div>
                   2281:     $request->print('</div>');
1.468     albertel 2282: 
                   2283:     $request->print('<div class="LC_grade_info_links">');
                   2284:     $request->print('</div>');
                   2285: 
1.45      ng       2286:     $result='<input type="hidden" name="partlist'.$counter.
                   2287: 	'" value="'.(join ":",@partlist).'" />'."\n";
1.129     ng       2288:     $result.='<input type="hidden" name="gradePartRespid'.
                   2289: 	'" value="'.(join ":",@gradePartRespid).'" />'."\n" if ($counter == 0);
1.45      ng       2290:     my $ctr = 0;
                   2291:     while ($ctr < scalar(@partlist)) {
                   2292: 	$result.='<input type="hidden" name="partid'.$counter.'_'.$ctr.'" value="'.
                   2293: 	    $partlist[$ctr].'" />'."\n";
                   2294: 	$ctr++;
                   2295:     }
1.468     albertel 2296:     $request->print($result.''."\n");
1.41      ng       2297: 
1.441     www      2298: # Done with printing info for one student
                   2299: 
1.468     albertel 2300:     $request->print('</div>');#LC_grade_show_user
1.441     www      2301: 
                   2302: 
1.41      ng       2303:     # print end of form
                   2304:     if ($counter == $total) {
1.592     bisitz   2305:         my $endform='<br /><hr /><table border="0"><tr><td>'."\n";
1.485     albertel 2306: 	$endform.='<input type="button" value="'.&mt('Save &amp; Next').'" '.
1.589     bisitz   2307: 	    'onclick="javascript:checksubmit(this.form,\'Save & Next\','.
1.417     albertel 2308: 	    $total.','.scalar(@partlist).');" target="_self" /> &nbsp;'."\n";
1.119     ng       2309: 	my $ntstu ='<select name="NTSTU">'.
                   2310: 	    '<option>1</option><option>2</option>'.
                   2311: 	    '<option>3</option><option>5</option>'.
                   2312: 	    '<option>7</option><option>10</option></select>'."\n";
1.257     albertel 2313: 	my $nsel = ($env{'form.NTSTU'} ne '' ? $env{'form.NTSTU'} : '1');
1.401     albertel 2314: 	$ntstu =~ s/<option>$nsel</<option selected="selected">$nsel</;
1.578     raeburn  2315:         $endform.=&mt('[_1]student(s)',$ntstu);
1.485     albertel 2316: 	$endform.='&nbsp;&nbsp;<input type="button" value="'.&mt('Previous').'" '.
1.589     bisitz   2317: 	    'onclick="javascript:checksubmit(this.form,\'Previous\');" target="_self" /> &nbsp;'."\n".
1.485     albertel 2318: 	    '<input type="button" value="'.&mt('Next').'" '.
1.589     bisitz   2319: 	    'onclick="javascript:checksubmit(this.form,\'Next\');" target="_self" /> &nbsp;';
1.592     bisitz   2320:         $endform.='<span class="LC_warning">'.
                   2321:                   &mt('(Next and Previous (student) do not save the scores.)').
                   2322:                   '</span>'."\n" ;
1.349     albertel 2323:         $endform.="<input type='hidden' value='".&get_increment().
1.348     bowersj2 2324:             "' name='increment' />";
1.485     albertel 2325: 	$endform.='</td></tr></table></form>';
1.41      ng       2326: 	$request->print($endform);
                   2327:     }
                   2328:     return '';
1.38      ng       2329: }
                   2330: 
1.464     albertel 2331: sub check_collaborators {
                   2332:     my ($symb,$uname,$udom,$record,$handgrade,$counter) = @_;
                   2333:     my ($result,@col_fullnames);
                   2334:     my ($classlist,undef,$fullname) = &getclasslist('all','0');
                   2335:     foreach my $part (keys(%$handgrade)) {
                   2336: 	my $ncol = &Apache::lonnet::EXT('resource.'.$part.
                   2337: 					'.maxcollaborators',
                   2338: 					$symb,$udom,$uname);
                   2339: 	next if ($ncol <= 0);
                   2340: 	$part =~ s/\_/\./g;
                   2341: 	next if ($record->{'resource.'.$part.'.collaborators'} eq '');
                   2342: 	my (@good_collaborators, @bad_collaborators);
                   2343: 	foreach my $possible_collaborator
                   2344: 	    (split(/,?\s+/,$record->{'resource.'.$part.'.collaborators'})) { 
                   2345: 	    $possible_collaborator =~ s/[\$\^\(\)]//g;
                   2346: 	    next if ($possible_collaborator eq '');
                   2347: 	    my ($co_name,$co_dom) = split(/\@|:/,$possible_collaborator);
                   2348: 	    $co_dom = $udom if (! defined($co_dom) || $co_dom =~ /^domain$/i);
                   2349: 	    next if ($co_name eq $uname && $co_dom eq $udom);
                   2350: 	    # Doing this grep allows 'fuzzy' specification
                   2351: 	    my @matches = grep(/^\Q$co_name\E:\Q$co_dom\E$/i, 
                   2352: 			       keys(%$classlist));
                   2353: 	    if (! scalar(@matches)) {
                   2354: 		push(@bad_collaborators, $possible_collaborator);
                   2355: 	    } else {
                   2356: 		push(@good_collaborators, @matches);
                   2357: 	    }
                   2358: 	}
                   2359: 	if (scalar(@good_collaborators) != 0) {
1.466     albertel 2360: 	    $result.='<br />'.&mt('Collaborators: ');
1.464     albertel 2361: 	    foreach my $name (@good_collaborators) {
                   2362: 		my ($lastname,$givenn) = split(/,/,$$fullname{$name});
                   2363: 		push(@col_fullnames, $givenn.' '.$lastname);
                   2364: 		$result.=$fullname->{$name}.'&nbsp; &nbsp; &nbsp;';
                   2365: 	    }
                   2366: 	    $result.='<br />'."\n";
1.466     albertel 2367: 	    my ($part)=split(/\./,$part);
1.464     albertel 2368: 	    $result.='<input type="hidden" name="collaborator'.$counter.
                   2369: 		'" value="'.$part.':'.(join ':',@good_collaborators).'" />'.
                   2370: 		"\n";
                   2371: 	}
                   2372: 	if (scalar(@bad_collaborators) > 0) {
1.466     albertel 2373: 	    $result.='<div class="LC_warning">';
1.464     albertel 2374: 	    $result.=&mt('This student has submitted [quant,_1,invalid collaborator]: [_2]',scalar(@bad_collaborators),join(', ',@bad_collaborators));
                   2375: 	    $result .= '</div>';
                   2376: 	}         
                   2377: 	if (scalar(@bad_collaborators > $ncol)) {
1.466     albertel 2378: 	    $result .= '<div class="LC_warning">';
1.464     albertel 2379: 	    $result .= &mt('This student has submitted too many '.
                   2380: 		'collaborators.  Maximum is [_1].',$ncol);
                   2381: 	    $result .= '</div>';
                   2382: 	}
                   2383:     }
                   2384:     return ($result,$fullname,\@col_fullnames);
                   2385: }
                   2386: 
1.44      ng       2387: #--- Retrieve the last submission for all the parts
1.38      ng       2388: sub get_last_submission {
1.119     ng       2389:     my ($returnhash)=@_;
1.596     raeburn  2390:     my (@string,$timestamp,%lasthidden);
1.119     ng       2391:     if ($$returnhash{'version'}) {
1.46      ng       2392: 	my %lasthash=();
                   2393: 	my ($version);
1.119     ng       2394: 	for ($version=1;$version<=$$returnhash{'version'};$version++) {
1.397     albertel 2395: 	    foreach my $key (sort(split(/\:/,
                   2396: 					$$returnhash{$version.':keys'}))) {
                   2397: 		$lasthash{$key}=$$returnhash{$version.':'.$key};
                   2398: 		$timestamp = 
1.545     raeburn  2399: 		    &Apache::lonlocal::locallocaltime($$returnhash{$version.':timestamp'});
1.46      ng       2400: 	    }
                   2401: 	}
1.596     raeburn  2402:         my %typeparts;
                   2403:         my $showsurv = 
                   2404:             &Apache::lonnet::allowed('vas',$env{'request.course.id'});
                   2405:         foreach my $key (sort(keys(%lasthash))) {
                   2406:             if ($key =~ /\.type$/) {
                   2407:                 if (($lasthash{$key} eq 'anonsurvey') || 
                   2408:                     ($lasthash{$key} eq 'anonsurveycred')) {
                   2409:                     my ($ign,@parts) = split(/\./,$key);
                   2410:                     pop(@parts);
                   2411:                     unless ($showsurv) {
                   2412:                         my $id = join(',',@parts);
                   2413:                         $typeparts{$ign.'.'.$id} = $lasthash{$key};
                   2414:                     }
                   2415:                     delete($lasthash{$key});
                   2416:                 }
                   2417:             }
                   2418:         }
                   2419:         my @hidden = keys(%typeparts);
1.397     albertel 2420: 	foreach my $key (keys(%lasthash)) {
                   2421: 	    next if ($key !~ /\.submission$/);
1.596     raeburn  2422:             my $hide;
                   2423:             if (@hidden) {
                   2424:                 foreach my $id (@hidden) {
                   2425:                     if ($key =~ /^\Q$id\E/) {
                   2426:                         $hide = 1;
                   2427:                         last;
                   2428:                     }
                   2429:                 }
                   2430:             }
1.397     albertel 2431: 	    my ($partid,$foo) = split(/submission$/,$key);
                   2432: 	    my $draft  = $lasthash{$partid.'awarddetail'} eq 'DRAFT' ?
1.398     albertel 2433: 		'<span class="LC_warning">Draft Copy</span> ' : '';
1.596     raeburn  2434: 	    push(@string, join(':', $key, $hide, $draft.$lasthash{$key}));
1.41      ng       2435: 	}
                   2436:     }
1.397     albertel 2437:     if (!@string) {
                   2438: 	$string[0] =
1.539     riegler  2439: 	    '<span class="LC_warning">'.&mt('Nothing submitted - no attempts.').'</span>';
1.397     albertel 2440:     }
                   2441:     return (\@string,\$timestamp);
1.38      ng       2442: }
1.35      ng       2443: 
1.44      ng       2444: #--- High light keywords, with style choosen by user.
1.38      ng       2445: sub keywords_highlight {
1.44      ng       2446:     my $string    = shift;
1.257     albertel 2447:     my $size      = $env{'form.kwsize'} eq '0' ? '' : 'size='.$env{'form.kwsize'};
                   2448:     my $styleon   = $env{'form.kwstyle'} eq ''  ? '' : $env{'form.kwstyle'};
1.41      ng       2449:     (my $styleoff = $styleon) =~ s/\</\<\//;
1.257     albertel 2450:     my @keylist   = split(/[,\s+]/,$env{'form.keywords'});
1.398     albertel 2451:     foreach my $keyword (@keylist) {
                   2452: 	$string =~ s/\b\Q$keyword\E(\b|\.)/<font color\=$env{'form.kwclr'} $size\>$styleon$keyword$styleoff<\/font>/gi;
1.41      ng       2453:     }
                   2454:     return $string;
1.38      ng       2455: }
1.36      ng       2456: 
1.44      ng       2457: #--- Called from submission routine
1.38      ng       2458: sub processHandGrade {
1.608     www      2459:     my ($request,$symb) = @_;
1.324     albertel 2460:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
1.257     albertel 2461:     my $button = $env{'form.gradeOpt'};
                   2462:     my $ngrade = $env{'form.NCT'};
                   2463:     my $ntstu  = $env{'form.NTSTU'};
1.301     albertel 2464:     my $cdom   = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   2465:     my $cnum   = $env{'course.'.$env{'request.course.id'}.'.num'};
                   2466: 
1.44      ng       2467:     if ($button eq 'Save & Next') {
                   2468: 	my $ctr = 0;
                   2469: 	while ($ctr < $ngrade) {
1.257     albertel 2470: 	    my ($uname,$udom) = split(/:/,$env{'form.unamedom'.$ctr});
1.324     albertel 2471: 	    my ($errorflag,$pts,$wgt) = &saveHandGrade($request,$symb,$uname,$udom,$ctr);
1.71      ng       2472: 	    if ($errorflag eq 'no_score') {
                   2473: 		$ctr++;
                   2474: 		next;
                   2475: 	    }
1.104     albertel 2476: 	    if ($errorflag eq 'not_allowed') {
1.398     albertel 2477: 		$request->print("<span class=\"LC_warning\">Not allowed to modify grades for $uname:$udom</span>");
1.104     albertel 2478: 		$ctr++;
                   2479: 		next;
                   2480: 	    }
1.257     albertel 2481: 	    my $includemsg = $env{'form.includemsg'.$ctr};
1.44      ng       2482: 	    my ($subject,$message,$msgstatus) = ('','','');
1.418     albertel 2483: 	    my $restitle = &Apache::lonnet::gettitle($symb);
                   2484:             my ($feedurl,$showsymb) =
                   2485: 		&get_feedurl_and_symb($symb,$uname,$udom);
                   2486: 	    my $messagetail;
1.62      albertel 2487: 	    if ($includemsg =~ /savemsg|newmsg\Q$ctr\E/) {
1.298     www      2488: 		$subject = $env{'form.msgsub'} if ($includemsg =~ /msgsub/);
1.295     www      2489: 		unless ($subject=~/\w/) { $subject=&mt('Grading Feedback'); }
1.386     raeburn  2490: 		$subject.=' ['.$restitle.']';
1.44      ng       2491: 		my (@msgnum) = split(/,/,$includemsg);
                   2492: 		foreach (@msgnum) {
1.257     albertel 2493: 		    $message.=$env{'form.'.$_} if ($_ =~ /savemsg|newmsg/ && $_ ne '');
1.44      ng       2494: 		}
1.80      ng       2495: 		$message =&Apache::lonfeedback::clear_out_html($message);
1.298     www      2496: 		if ($env{'form.withgrades'.$ctr}) {
                   2497: 		    $message.="\n\nPoint".($pts > 1 ? 's':'').' awarded = '.$pts.' out of '.$wgt;
1.386     raeburn  2498: 		    $messagetail = " for <a href=\"".
1.605     www      2499: 		                   $feedurl."?symb=$showsymb\">$restitle</a>";
1.386     raeburn  2500: 		}
                   2501: 		$msgstatus = 
                   2502:                     &Apache::lonmsg::user_normal_msg($uname,$udom,$subject,
                   2503: 						     $message.$messagetail,
1.418     albertel 2504:                                                      undef,$feedurl,undef,
1.386     raeburn  2505:                                                      undef,undef,$showsymb,
                   2506:                                                      $restitle);
1.574     bisitz   2507: 		$request->print('<br />'.&mt('Sending message to [_1]',$uname.':'.$udom).': '.
1.296     www      2508: 				$msgstatus);
1.44      ng       2509: 	    }
1.257     albertel 2510: 	    if ($env{'form.collaborator'.$ctr}) {
1.155     albertel 2511: 		my @collabstrs=&Apache::loncommon::get_env_multiple("form.collaborator$ctr");
1.150     albertel 2512: 		foreach my $collabstr (@collabstrs) {
                   2513: 		    my ($part,@collaborators) = split(/:/,$collabstr);
1.310     banghart 2514: 		    foreach my $collaborator (@collaborators) {
1.150     albertel 2515: 			my ($errorflag,$pts,$wgt) = 
1.324     albertel 2516: 			    &saveHandGrade($request,$symb,$collaborator,$udom,$ctr,
1.257     albertel 2517: 					   $env{'form.unamedom'.$ctr},$part);
1.150     albertel 2518: 			if ($errorflag eq 'not_allowed') {
1.362     albertel 2519: 			    $request->print("<span class=\"LC_error\">".&mt('Not allowed to modify grades for [_1]',"$collaborator:$udom")."</span>");
1.150     albertel 2520: 			    next;
1.418     albertel 2521: 			} elsif ($message ne '') {
                   2522: 			    my ($baseurl,$showsymb) = 
                   2523: 				&get_feedurl_and_symb($symb,$collaborator,
                   2524: 						      $udom);
                   2525: 			    if ($env{'form.withgrades'.$ctr}) {
                   2526: 				$messagetail = " for <a href=\"".
1.605     www      2527:                                     $baseurl."?symb=$showsymb\">$restitle</a>";
1.150     albertel 2528: 			    }
1.418     albertel 2529: 			    $msgstatus = 
                   2530: 				&Apache::lonmsg::user_normal_msg($collaborator,$udom,$subject,$message.$messagetail,undef,$baseurl,undef,undef,undef,$showsymb,$restitle);
1.104     albertel 2531: 			}
1.44      ng       2532: 		    }
                   2533: 		}
                   2534: 	    }
                   2535: 	    $ctr++;
                   2536: 	}
                   2537:     }
                   2538: 
1.257     albertel 2539:     if ($env{'form.handgrade'} eq 'yes') {
1.119     ng       2540: 	# Keywords sorted in alphabatical order
1.257     albertel 2541: 	my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
1.119     ng       2542: 	my %keyhash = ();
1.257     albertel 2543: 	$env{'form.keywords'}           =~ s/,\s{0,}|\s+/ /g;
                   2544: 	$env{'form.keywords'}           =~ s/^\s+|\s+$//;
                   2545: 	my (@keywords) = sort(split(/\s+/,$env{'form.keywords'}));
                   2546: 	$env{'form.keywords'} = join(' ',@keywords);
                   2547: 	$keyhash{$symb.'_keywords'}     = $env{'form.keywords'};
                   2548: 	$keyhash{$symb.'_subject'}      = $env{'form.msgsub'};
                   2549: 	$keyhash{$loginuser.'_kwclr'}   = $env{'form.kwclr'};
                   2550: 	$keyhash{$loginuser.'_kwsize'}  = $env{'form.kwsize'};
                   2551: 	$keyhash{$loginuser.'_kwstyle'} = $env{'form.kwstyle'};
1.119     ng       2552: 
                   2553: 	# message center - Order of message gets changed. Blank line is eliminated.
1.257     albertel 2554: 	# New messages are saved in env for the next student.
1.119     ng       2555: 	# All messages are saved in nohist_handgrade.db
                   2556: 	my ($ctr,$idx) = (1,1);
1.257     albertel 2557: 	while ($ctr <= $env{'form.savemsgN'}) {
                   2558: 	    if ($env{'form.savemsg'.$ctr} ne '') {
                   2559: 		$keyhash{$symb.'_savemsg'.$idx} = $env{'form.savemsg'.$ctr};
1.119     ng       2560: 		$idx++;
                   2561: 	    }
                   2562: 	    $ctr++;
1.41      ng       2563: 	}
1.119     ng       2564: 	$ctr = 0;
                   2565: 	while ($ctr < $ngrade) {
1.257     albertel 2566: 	    if ($env{'form.newmsg'.$ctr} ne '') {
                   2567: 		$keyhash{$symb.'_savemsg'.$idx} = $env{'form.newmsg'.$ctr};
                   2568: 		$env{'form.savemsg'.$idx} = $env{'form.newmsg'.$ctr};
1.119     ng       2569: 		$idx++;
                   2570: 	    }
                   2571: 	    $ctr++;
1.41      ng       2572: 	}
1.257     albertel 2573: 	$env{'form.savemsgN'} = --$idx;
                   2574: 	$keyhash{$symb.'_savemsgN'} = $env{'form.savemsgN'};
1.119     ng       2575: 	my $putresult = &Apache::lonnet::put
1.301     albertel 2576: 	    ('nohist_handgrade',\%keyhash,$cdom,$cnum);
1.41      ng       2577:     }
1.44      ng       2578:     # Called by Save & Refresh from Highlight Attribute Window
1.257     albertel 2579:     my (undef,undef,$fullname) = &getclasslist($env{'form.section'},'1');
                   2580:     if ($env{'form.refresh'} eq 'on') {
1.86      ng       2581: 	my ($ctr,$total) = (0,0);
                   2582: 	while ($ctr < $ngrade) {
1.257     albertel 2583: 	    $total++ if  $env{'form.unamedom'.$ctr} ne '';
1.86      ng       2584: 	    $ctr++;
                   2585: 	}
1.257     albertel 2586: 	$env{'form.NTSTU'}=$ngrade;
1.86      ng       2587: 	$ctr = 0;
                   2588: 	while ($ctr < $total) {
1.257     albertel 2589: 	    my $processUser = $env{'form.unamedom'.$ctr};
                   2590: 	    ($env{'form.student'},$env{'form.userdom'}) = split(/:/,$processUser);
                   2591: 	    $env{'form.fullname'} = $$fullname{$processUser};
1.86      ng       2592: 	    &submission($request,$ctr,$total-1);
1.41      ng       2593: 	    $ctr++;
                   2594: 	}
                   2595: 	return '';
                   2596:     }
1.36      ng       2597: 
1.121     ng       2598: # Go directly to grade student - from submission or link from chart page
1.120     ng       2599:     if ($button eq 'Grade Student') {
1.598     www      2600: #	(undef,undef,$env{'form.handgrade'},undef,undef) = &showResourceInfo($symb);
1.257     albertel 2601: 	my $processUser = $env{'form.unamedom'.$env{'form.studentNo'}};
                   2602: 	($env{'form.student'},$env{'form.userdom'}) = split(/:/,$processUser);
                   2603: 	$env{'form.fullname'} = $$fullname{$processUser};
1.120     ng       2604: 	&submission($request,0,0);
                   2605: 	return '';
                   2606:     }
                   2607: 
1.44      ng       2608:     # Get the next/previous one or group of students
1.257     albertel 2609:     my $firststu = $env{'form.unamedom0'};
                   2610:     my $laststu = $env{'form.unamedom'.($ngrade-1)};
1.119     ng       2611:     my $ctr = 2;
1.41      ng       2612:     while ($laststu eq '') {
1.257     albertel 2613: 	$laststu  = $env{'form.unamedom'.($ngrade-$ctr)};
1.41      ng       2614: 	$ctr++;
                   2615: 	$laststu = $firststu if ($ctr > $ngrade);
                   2616:     }
1.44      ng       2617: 
1.41      ng       2618:     my (@parsedlist,@nextlist);
                   2619:     my ($nextflg) = 0;
1.524     raeburn  2620:     foreach my $item (sort 
1.294     albertel 2621: 	     {
                   2622: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                   2623: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                   2624: 		 }
                   2625: 		 return $a cmp $b;
                   2626: 	     } (keys(%$fullname))) {
1.605     www      2627: # FIXME: this is fishy, looks like the button label
1.41      ng       2628: 	if ($nextflg == 1 && $button =~ /Next$/) {
1.524     raeburn  2629: 	    push(@parsedlist,$item);
1.41      ng       2630: 	}
1.524     raeburn  2631: 	$nextflg = 1 if ($item eq $laststu);
1.41      ng       2632: 	if ($button eq 'Previous') {
1.524     raeburn  2633: 	    last if ($item eq $firststu);
                   2634: 	    push(@parsedlist,$item);
1.41      ng       2635: 	}
                   2636:     }
                   2637:     $ctr = 0;
1.605     www      2638: # FIXME: this is fishy, looks like the button label
1.41      ng       2639:     @parsedlist = reverse @parsedlist if ($button eq 'Previous');
1.582     raeburn  2640:     my $res_error;
                   2641:     my ($partlist) = &response_type($symb,\$res_error);
                   2642:     if ($res_error) {
                   2643:         $request->print(&navmap_errormsg());
                   2644:         return;
                   2645:     }
1.41      ng       2646:     foreach my $student (@parsedlist) {
1.257     albertel 2647: 	my $submitonly=$env{'form.submitonly'};
1.41      ng       2648: 	my ($uname,$udom) = split(/:/,$student);
1.301     albertel 2649: 	
                   2650: 	if ($submitonly eq 'queued') {
                   2651: 	    my %queue_status = 
                   2652: 		&Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
                   2653: 							$udom,$uname);
                   2654: 	    next if (!defined($queue_status{'gradingqueue'}));
                   2655: 	}
                   2656: 
1.156     albertel 2657: 	if ($submitonly =~ /^(yes|graded|incorrect)$/) {
1.257     albertel 2658: #	    my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
1.324     albertel 2659: 	    my %status=&student_gradeStatus($symb,$udom,$uname,$partlist);
1.145     albertel 2660: 	    my $submitted = 0;
1.248     albertel 2661: 	    my $ungraded = 0;
                   2662: 	    my $incorrect = 0;
1.524     raeburn  2663: 	    foreach my $item (keys(%status)) {
                   2664: 		$submitted = 1 if ($status{$item} ne 'nothing');
                   2665: 		$ungraded = 1 if ($status{$item} =~ /^ungraded/);
                   2666: 		$incorrect = 1 if ($status{$item} =~ /^incorrect/);
                   2667: 		my ($foo,$partid,$foo1) = split(/\./,$item);
1.145     albertel 2668: 		if ($status{'resource.'.$partid.'.submitted_by'} ne '') {
                   2669: 		    $submitted = 0;
                   2670: 		}
1.41      ng       2671: 	    }
1.156     albertel 2672: 	    next if (!$submitted && ($submitonly eq 'yes' ||
                   2673: 				     $submitonly eq 'incorrect' ||
                   2674: 				     $submitonly eq 'graded'));
1.248     albertel 2675: 	    next if (!$ungraded && ($submitonly eq 'graded'));
                   2676: 	    next if (!$incorrect && $submitonly eq 'incorrect');
1.41      ng       2677: 	}
1.524     raeburn  2678: 	push(@nextlist,$student) if ($ctr < $ntstu);
1.129     ng       2679: 	last if ($ctr == $ntstu);
1.41      ng       2680: 	$ctr++;
                   2681:     }
1.36      ng       2682: 
1.41      ng       2683:     $ctr = 0;
                   2684:     my $total = scalar(@nextlist)-1;
1.39      ng       2685: 
1.524     raeburn  2686:     foreach (sort(@nextlist)) {
1.41      ng       2687: 	my ($uname,$udom,$submitter) = split(/:/);
1.257     albertel 2688: 	$env{'form.student'}  = $uname;
                   2689: 	$env{'form.userdom'}  = $udom;
                   2690: 	$env{'form.fullname'} = $$fullname{$_};
1.41      ng       2691: 	&submission($request,$ctr,$total);
                   2692: 	$ctr++;
                   2693:     }
                   2694:     if ($total < 0) {
1.485     albertel 2695: 	my $the_end = '<h3><span class="LC_info">'.&mt('LON-CAPA User Message').'</span></h3><br />'."\n";
                   2696: 	$the_end.=&mt('<b>Message: </b> No more students for this section or class.').'<br /><br />'."\n";
                   2697: 	$the_end.=&mt('Click on the button below to return to the grading menu.').'<br /><br />'."\n";
1.41      ng       2698: 	$request->print($the_end);
                   2699:     }
                   2700:     return '';
1.38      ng       2701: }
1.36      ng       2702: 
1.44      ng       2703: #---- Save the score and award for each student, if changed
1.38      ng       2704: sub saveHandGrade {
1.324     albertel 2705:     my ($request,$symb,$stuname,$domain,$newflg,$submitter,$part) = @_;
1.342     banghart 2706:     my @version_parts;
1.104     albertel 2707:     my $usec = &Apache::lonnet::getsection($domain,$stuname,
1.257     albertel 2708: 					   $env{'request.course.id'});
1.104     albertel 2709:     if (!&canmodify($usec)) { return('not_allowed'); }
1.337     banghart 2710:     my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$domain,$stuname);
1.251     banghart 2711:     my @parts_graded;
1.77      ng       2712:     my %newrecord  = ();
                   2713:     my ($pts,$wgt) = ('','');
1.269     raeburn  2714:     my %aggregate = ();
                   2715:     my $aggregateflag = 0;
1.301     albertel 2716:     my @parts = split(/:/,$env{'form.partlist'.$newflg});
                   2717:     foreach my $new_part (@parts) {
1.337     banghart 2718: 	#collaborator ($submi may vary for different parts
1.259     banghart 2719: 	if ($submitter && $new_part ne $part) { next; }
                   2720: 	my $dropMenu = $env{'form.GD_SEL'.$newflg.'_'.$new_part};
1.125     ng       2721: 	if ($dropMenu eq 'excused') {
1.259     banghart 2722: 	    if ($record{'resource.'.$new_part.'.solved'} ne 'excused') {
                   2723: 		$newrecord{'resource.'.$new_part.'.solved'} = 'excused';
                   2724: 		if (exists($record{'resource.'.$new_part.'.awarded'})) {
                   2725: 		    $newrecord{'resource.'.$new_part.'.awarded'} = '';
1.58      albertel 2726: 		}
1.364     banghart 2727: 	        $newrecord{'resource.'.$new_part.'.regrader'}="$env{'user.name'}:$env{'user.domain'}";
1.58      albertel 2728: 	    }
1.125     ng       2729: 	} elsif ($dropMenu eq 'reset status'
1.259     banghart 2730: 		 && exists($record{'resource.'.$new_part.'.solved'})) { #don't bother if no old records -> no attempts
1.524     raeburn  2731: 	    foreach my $key (keys(%record)) {
1.259     banghart 2732: 		if ($key=~/^resource\.\Q$new_part\E\./) { $newrecord{$key} = ''; }
1.197     albertel 2733: 	    }
1.259     banghart 2734: 	    $newrecord{'resource.'.$new_part.'.regrader'}=
1.257     albertel 2735: 		"$env{'user.name'}:$env{'user.domain'}";
1.270     albertel 2736:             my $totaltries = $record{'resource.'.$part.'.tries'};
                   2737: 
                   2738:             my %last_resets = &get_last_resets($symb,$env{'request.course.id'},
                   2739: 					       [$new_part]);
                   2740:             my $aggtries =$totaltries;
1.269     raeburn  2741:             if ($last_resets{$new_part}) {
1.270     albertel 2742:                 $aggtries = &get_num_tries(\%record,$last_resets{$new_part},
                   2743: 					   $new_part);
1.269     raeburn  2744:             }
1.270     albertel 2745: 
                   2746:             my $solvedstatus = $record{'resource.'.$new_part.'.solved'};
1.269     raeburn  2747:             if ($aggtries > 0) {
1.327     albertel 2748:                 &decrement_aggs($symb,$new_part,\%aggregate,$aggtries,$totaltries,$solvedstatus);
1.269     raeburn  2749:                 $aggregateflag = 1;
                   2750:             }
1.125     ng       2751: 	} elsif ($dropMenu eq '') {
1.259     banghart 2752: 	    $pts = ($env{'form.GD_BOX'.$newflg.'_'.$new_part} ne '' ? 
                   2753: 		    $env{'form.GD_BOX'.$newflg.'_'.$new_part} : 
                   2754: 		    $env{'form.RADVAL'.$newflg.'_'.$new_part});
                   2755: 	    if ($pts eq '' && $env{'form.GD_SEL'.$newflg.'_'.$new_part} eq '') {
1.153     albertel 2756: 		next;
                   2757: 	    }
1.259     banghart 2758: 	    $wgt = $env{'form.WGT'.$newflg.'_'.$new_part} eq '' ? 1 : 
                   2759: 		$env{'form.WGT'.$newflg.'_'.$new_part};
1.41      ng       2760: 	    my $partial= $pts/$wgt;
1.259     banghart 2761: 	    if ($partial eq $record{'resource.'.$new_part.'.awarded'}) {
1.153     albertel 2762: 		#do not update score for part if not changed.
1.346     banghart 2763:                 &handback_files($request,$symb,$stuname,$domain,$newflg,$new_part,\%newrecord);
1.153     albertel 2764: 		next;
1.251     banghart 2765: 	    } else {
1.524     raeburn  2766: 	        push(@parts_graded,$new_part);
1.153     albertel 2767: 	    }
1.259     banghart 2768: 	    if ($record{'resource.'.$new_part.'.awarded'} ne $partial) {
                   2769: 		$newrecord{'resource.'.$new_part.'.awarded'}  = $partial;
1.153     albertel 2770: 	    }
1.259     banghart 2771: 	    my $reckey = 'resource.'.$new_part.'.solved';
1.41      ng       2772: 	    if ($partial == 0) {
1.153     albertel 2773: 		if ($record{$reckey} ne 'incorrect_by_override') {
                   2774: 		    $newrecord{$reckey} = 'incorrect_by_override';
                   2775: 		}
1.41      ng       2776: 	    } else {
1.153     albertel 2777: 		if ($record{$reckey} ne 'correct_by_override') {
                   2778: 		    $newrecord{$reckey} = 'correct_by_override';
                   2779: 		}
                   2780: 	    }	    
                   2781: 	    if ($submitter && 
1.259     banghart 2782: 		($record{'resource.'.$new_part.'.submitted_by'} ne $submitter)) {
                   2783: 		$newrecord{'resource.'.$new_part.'.submitted_by'} = $submitter;
1.41      ng       2784: 	    }
1.259     banghart 2785: 	    $newrecord{'resource.'.$new_part.'.regrader'}=
1.257     albertel 2786: 		"$env{'user.name'}:$env{'user.domain'}";
1.41      ng       2787: 	}
1.259     banghart 2788: 	# unless problem has been graded, set flag to version the submitted files
1.305     banghart 2789: 	unless ($record{'resource.'.$new_part.'.solved'} =~ /^correct_/  || 
                   2790: 	        $record{'resource.'.$new_part.'.solved'} eq 'incorrect_by_override' ||
                   2791: 	        $dropMenu eq 'reset status')
                   2792: 	   {
1.524     raeburn  2793: 	    push(@version_parts,$new_part);
1.259     banghart 2794: 	}
1.41      ng       2795:     }
1.301     albertel 2796:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   2797:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   2798: 
1.344     albertel 2799:     if (%newrecord) {
                   2800:         if (@version_parts) {
1.364     banghart 2801:             my @changed_keys = &version_portfiles(\%record, \@parts_graded, 
                   2802:                                 $env{'request.course.id'}, $symb, $domain, $stuname, \@version_parts);
1.344     albertel 2803: 	    @newrecord{@changed_keys} = @record{@changed_keys};
1.367     albertel 2804: 	    foreach my $new_part (@version_parts) {
                   2805: 		&handback_files($request,$symb,$stuname,$domain,$newflg,
                   2806: 				$new_part,\%newrecord);
                   2807: 	    }
1.259     banghart 2808:         }
1.44      ng       2809: 	&Apache::lonnet::cstore(\%newrecord,$symb,
1.257     albertel 2810: 				$env{'request.course.id'},$domain,$stuname);
1.380     albertel 2811: 	&check_and_remove_from_queue(\@parts,\%record,\%newrecord,$symb,
                   2812: 				     $cdom,$cnum,$domain,$stuname);
1.41      ng       2813:     }
1.269     raeburn  2814:     if ($aggregateflag) {
                   2815:         &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
1.301     albertel 2816: 			      $cdom,$cnum);
1.269     raeburn  2817:     }
1.301     albertel 2818:     return ('',$pts,$wgt);
1.36      ng       2819: }
1.322     albertel 2820: 
1.380     albertel 2821: sub check_and_remove_from_queue {
                   2822:     my ($parts,$record,$newrecord,$symb,$cdom,$cnum,$domain,$stuname) = @_;
                   2823:     my @ungraded_parts;
                   2824:     foreach my $part (@{$parts}) {
                   2825: 	if (    $record->{   'resource.'.$part.'.awarded'} eq ''
                   2826: 	     && $record->{   'resource.'.$part.'.solved' } ne 'excused'
                   2827: 	     && $newrecord->{'resource.'.$part.'.awarded'} eq ''
                   2828: 	     && $newrecord->{'resource.'.$part.'.solved' } ne 'excused'
                   2829: 		) {
                   2830: 	    push(@ungraded_parts, $part);
                   2831: 	}
                   2832:     }
                   2833:     if ( !@ungraded_parts ) {
                   2834: 	&Apache::bridgetask::remove_from_queue('gradingqueue',$symb,$cdom,
                   2835: 					       $cnum,$domain,$stuname);
                   2836:     }
                   2837: }
                   2838: 
1.337     banghart 2839: sub handback_files {
                   2840:     my ($request,$symb,$stuname,$domain,$newflg,$new_part,$newrecord) = @_;
1.517     raeburn  2841:     my $portfolio_root = '/userfiles/portfolio';
1.582     raeburn  2842:     my $res_error;
                   2843:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
                   2844:     if ($res_error) {
                   2845:         $request->print('<br />'.&navmap_errormsg().'<br />');
                   2846:         return;
                   2847:     }
1.375     albertel 2848:     my @part_response_id = &flatten_responseType($responseType);
                   2849:     foreach my $part_response_id (@part_response_id) {
                   2850:     	my ($part_id,$resp_id) = @{ $part_response_id };
                   2851: 	my $part_resp = join('_',@{ $part_response_id });
1.337     banghart 2852:             if (($env{'form.'.$newflg.'_'.$part_resp.'_returndoc1'}) && ($new_part == $part_id)) {
                   2853:                 # if multiple files are uploaded names will be 'returndoc2','returndoc3'
                   2854:                 my $file_counter = 1;
1.367     albertel 2855: 		my $file_msg;
1.337     banghart 2856:                 while ($env{'form.'.$newflg.'_'.$part_resp.'_returndoc'.$file_counter}) {
                   2857:                     my $fname=$env{'form.'.$newflg.'_'.$part_resp.'_returndoc'.$file_counter.'.filename'};
1.338     banghart 2858:                     my ($directory,$answer_file) = 
                   2859:                         ($env{'form.'.$newflg.'_'.$part_resp.'_origdoc'.$file_counter} =~ /^(.*?)([^\/]*)$/);
                   2860:                     my ($answer_name,$answer_ver,$answer_ext) =
                   2861: 		        &file_name_version_ext($answer_file);
1.355     banghart 2862: 		    my ($portfolio_path) = ($directory =~ /^.+$stuname\/portfolio(.*)/);
1.517     raeburn  2863:                     my $getpropath = 1;
                   2864: 		    my @dir_list = &Apache::lonnet::dirlist($portfolio_root.$portfolio_path,$domain,$stuname,$getpropath);
1.338     banghart 2865: 		    my $version = &get_next_version($answer_name, $answer_ext, \@dir_list);
1.355     banghart 2866:                     # fix file name
                   2867:                     my ($save_file_name) = (($directory.$answer_name.".$version.".$answer_ext) =~ /^.+\/${stuname}\/(.*)/);
                   2868:                     my $result=&Apache::lonnet::finishuserfileupload($stuname,$domain,
                   2869:             	                                $newflg.'_'.$part_resp.'_returndoc'.$file_counter,
                   2870:             	                                $save_file_name);
1.337     banghart 2871:                     if ($result !~ m|^/uploaded/|) {
1.536     raeburn  2872:                         $request->print('<br /><span class="LC_error">'.
                   2873:                             &mt('An error occurred ([_1]) while trying to upload [_2].',
                   2874:                                 $result,$newflg.'_'.$part_resp.'_returndoc'.$file_counter).
                   2875:                                         '</span>');
1.356     banghart 2876:                     } else {
1.360     banghart 2877:                         # mark the file as read only
                   2878:                         my @files = ($save_file_name);
1.372     albertel 2879:                         my @what = ($symb,$env{'request.course.id'},'handback');
1.360     banghart 2880:                         &Apache::lonnet::mark_as_readonly($domain,$stuname,\@files,\@what);
1.367     albertel 2881: 			if (exists($$newrecord{"resource.$new_part.$resp_id.handback"})) {
                   2882: 			    $$newrecord{"resource.$new_part.$resp_id.handback"}.=',';
                   2883: 			}
                   2884:                         $$newrecord{"resource.$new_part.$resp_id.handback"} .= $save_file_name;
                   2885: 			$file_msg.= "\n".'<br /><span class="LC_filename"><a href="/uploaded/'."$domain/$stuname/".$save_file_name.'">'.$save_file_name."</a></span><br />";
                   2886: 
1.337     banghart 2887:                     }
                   2888:                     $request->print("<br />".$fname." will be the uploaded file name");
1.354     albertel 2889:                     $request->print(" ".$env{'form.'.$newflg.'_'.$part_resp.'_origdoc'.$file_counter});
1.337     banghart 2890:                     $file_counter++;
                   2891:                 }
1.367     albertel 2892: 		my $subject = "File Handed Back by Instructor ";
                   2893: 		my $message = "A file has been returned that was originally submitted in reponse to: <br />";
                   2894: 		$message .= "<strong>".&Apache::lonnet::gettitle($symb)."</strong><br />";
                   2895: 		$message .= ' The returned file(s) are named: '. $file_msg;
                   2896: 		$message .= " and can be found in your portfolio space.";
1.418     albertel 2897: 		my ($feedurl,$showsymb) = 
                   2898: 		    &get_feedurl_and_symb($symb,$domain,$stuname);
1.386     raeburn  2899:                 my $restitle = &Apache::lonnet::gettitle($symb);
                   2900: 		my $msgstatus = 
                   2901:                    &Apache::lonmsg::user_normal_msg($stuname,$domain,$subject.
                   2902: 			 ' (File Returned) ['.$restitle.']',$message,undef,
1.418     albertel 2903:                          $feedurl,undef,undef,undef,$showsymb,$restitle);
1.337     banghart 2904:             }
                   2905:         }
1.338     banghart 2906:     return;
1.337     banghart 2907: }
                   2908: 
1.418     albertel 2909: sub get_feedurl_and_symb {
                   2910:     my ($symb,$uname,$udom) = @_;
                   2911:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
                   2912:     $url = &Apache::lonnet::clutter($url);
                   2913:     my $encrypturl=&Apache::lonnet::EXT('resource.0.encrypturl',
                   2914: 					$symb,$udom,$uname);
                   2915:     if ($encrypturl =~ /^yes$/i) {
                   2916: 	&Apache::lonenc::encrypted(\$url,1);
                   2917: 	&Apache::lonenc::encrypted(\$symb,1);
                   2918:     }
                   2919:     return ($url,$symb);
                   2920: }
                   2921: 
1.313     banghart 2922: sub get_submitted_files {
                   2923:     my ($udom,$uname,$partid,$respid,$record) = @_;
                   2924:     my @files;
                   2925:     if ($$record{"resource.$partid.$respid.portfiles"}) {
                   2926:         my $file_url = '/uploaded/'.$udom.'/'.$uname.'/portfolio';
                   2927:         foreach my $file (split(',',$$record{"resource.$partid.$respid.portfiles"})) {
                   2928:     	    push(@files,$file_url.$file);
                   2929:         }
                   2930:     }
                   2931:     if ($$record{"resource.$partid.$respid.uploadedurl"}) {
                   2932:         push(@files,$$record{"resource.$partid.$respid.uploadedurl"});
                   2933:     }
                   2934:     return (\@files);
                   2935: }
1.322     albertel 2936: 
1.269     raeburn  2937: # ----------- Provides number of tries since last reset.
                   2938: sub get_num_tries {
                   2939:     my ($record,$last_reset,$part) = @_;
                   2940:     my $timestamp = '';
                   2941:     my $num_tries = 0;
                   2942:     if ($$record{'version'}) {
                   2943:         for (my $version=$$record{'version'};$version>=1;$version--) {
                   2944:             if (exists($$record{$version.':resource.'.$part.'.solved'})) {
                   2945:                 $timestamp = $$record{$version.':timestamp'};
                   2946:                 if ($timestamp > $last_reset) {
                   2947:                     $num_tries ++;
                   2948:                 } else {
                   2949:                     last;
                   2950:                 }
                   2951:             }
                   2952:         }
                   2953:     }
                   2954:     return $num_tries;
                   2955: }
                   2956: 
                   2957: # ----------- Determine decrements required in aggregate totals 
                   2958: sub decrement_aggs {
                   2959:     my ($symb,$part,$aggregate,$aggtries,$totaltries,$solvedstatus) = @_;
                   2960:     my %decrement = (
                   2961:                         attempts => 0,
                   2962:                         users => 0,
                   2963:                         correct => 0
                   2964:                     );
                   2965:     $decrement{'attempts'} = $aggtries;
                   2966:     if ($solvedstatus =~ /^correct/) {
                   2967:         $decrement{'correct'} = 1;
                   2968:     }
                   2969:     if ($aggtries == $totaltries) {
                   2970:         $decrement{'users'} = 1;
                   2971:     }
1.524     raeburn  2972:     foreach my $type (keys(%decrement)) {
1.269     raeburn  2973:         $$aggregate{$symb."\0".$part."\0".$type} = -$decrement{$type};
                   2974:     }
                   2975:     return;
                   2976: }
                   2977: 
                   2978: # ----------- Determine timestamps for last reset of aggregate totals for parts  
                   2979: sub get_last_resets {
1.270     albertel 2980:     my ($symb,$courseid,$partids) =@_;
                   2981:     my %last_resets;
1.269     raeburn  2982:     my $cdom = $env{'course.'.$courseid.'.domain'};
                   2983:     my $cname = $env{'course.'.$courseid.'.num'};
1.271     albertel 2984:     my @keys;
                   2985:     foreach my $part (@{$partids}) {
                   2986: 	push(@keys,"$symb\0$part\0resettime");
                   2987:     }
                   2988:     my %results=&Apache::lonnet::get('nohist_resourcetracker',\@keys,
                   2989: 				     $cdom,$cname);
                   2990:     foreach my $part (@{$partids}) {
                   2991: 	$last_resets{$part}=$results{"$symb\0$part\0resettime"};
1.269     raeburn  2992:     }
1.270     albertel 2993:     return %last_resets;
1.269     raeburn  2994: }
                   2995: 
1.251     banghart 2996: # ----------- Handles creating versions for portfolio files as answers
                   2997: sub version_portfiles {
1.343     banghart 2998:     my ($record, $parts_graded, $courseid, $symb, $domain, $stu_name, $v_flag) = @_;
1.263     banghart 2999:     my $version_parts = join('|',@$v_flag);
1.343     banghart 3000:     my @returned_keys;
1.255     banghart 3001:     my $parts = join('|', @$parts_graded);
1.517     raeburn  3002:     my $portfolio_root = '/userfiles/portfolio';
1.277     albertel 3003:     foreach my $key (keys(%$record)) {
1.259     banghart 3004:         my $new_portfiles;
1.263     banghart 3005:         if ($key =~ /^resource\.($version_parts)\./ && $key =~ /\.portfiles$/ ) {
1.342     banghart 3006:             my @versioned_portfiles;
1.367     albertel 3007:             my @portfiles = split(/\s*,\s*/,$$record{$key});
1.252     banghart 3008:             foreach my $file (@portfiles) {
1.306     banghart 3009:                 &Apache::lonnet::unmark_as_readonly($domain,$stu_name,[$symb,$env{'request.course.id'}],$file);
1.304     albertel 3010:                 my ($directory,$answer_file) =($file =~ /^(.*?)([^\/]*)$/);
                   3011: 		my ($answer_name,$answer_ver,$answer_ext) =
                   3012: 		    &file_name_version_ext($answer_file);
1.517     raeburn  3013:                 my $getpropath = 1;    
                   3014:                 my @dir_list = &Apache::lonnet::dirlist($portfolio_root.$directory,$domain,$stu_name,$getpropath);
1.342     banghart 3015:                 my $version = &get_next_version($answer_name, $answer_ext, \@dir_list);
1.306     banghart 3016:                 my $new_answer = &version_selected_portfile($domain, $stu_name, $directory, $answer_file, $version);
                   3017:                 if ($new_answer ne 'problem getting file') {
1.342     banghart 3018:                     push(@versioned_portfiles, $directory.$new_answer);
1.306     banghart 3019:                     &Apache::lonnet::mark_as_readonly($domain,$stu_name,
1.367     albertel 3020:                         [$directory.$new_answer],
1.306     banghart 3021:                         [$symb,$env{'request.course.id'},'graded']);
1.259     banghart 3022:                 }
1.252     banghart 3023:             }
1.343     banghart 3024:             $$record{$key} = join(',',@versioned_portfiles);
                   3025:             push(@returned_keys,$key);
1.251     banghart 3026:         }
                   3027:     } 
1.343     banghart 3028:     return (@returned_keys);   
1.305     banghart 3029: }
                   3030: 
1.307     banghart 3031: sub get_next_version {
1.341     banghart 3032:     my ($answer_name, $answer_ext, $dir_list) = @_;
1.307     banghart 3033:     my $version;
                   3034:     foreach my $row (@$dir_list) {
                   3035:         my ($file) = split(/\&/,$row,2);
                   3036:         my ($file_name,$file_version,$file_ext) =
                   3037: 	    &file_name_version_ext($file);
                   3038:         if (($file_name eq $answer_name) && 
                   3039: 	    ($file_ext eq $answer_ext)) {
                   3040:                 # gets here if filename and extension match, regardless of version
                   3041:                 if ($file_version ne '') {
                   3042:                 # a versioned file is found  so save it for later
                   3043:                 if ($file_version > $version) {
                   3044: 		    $version = $file_version;
                   3045: 	        }
                   3046:             }
                   3047:         }
                   3048:     } 
                   3049:     $version ++;
                   3050:     return($version);
                   3051: }
                   3052: 
1.305     banghart 3053: sub version_selected_portfile {
1.306     banghart 3054:     my ($domain,$stu_name,$directory,$file_name,$version) = @_;
                   3055:     my ($answer_name,$answer_ver,$answer_ext) =
                   3056:         &file_name_version_ext($file_name);
                   3057:     my $new_answer;
                   3058:     $env{'form.copy'} = &Apache::lonnet::getfile("/uploaded/$domain/$stu_name/portfolio$directory$file_name");
                   3059:     if($env{'form.copy'} eq '-1') {
                   3060:         $new_answer = 'problem getting file';
                   3061:     } else {
                   3062:         $new_answer = $answer_name.'.'.$version.'.'.$answer_ext;
                   3063:         my $copy_result = &Apache::lonnet::finishuserfileupload(
                   3064:                             $stu_name,$domain,'copy',
                   3065: 		        '/portfolio'.$directory.$new_answer);
                   3066:     }    
                   3067:     return ($new_answer);
1.251     banghart 3068: }
                   3069: 
1.304     albertel 3070: sub file_name_version_ext {
                   3071:     my ($file)=@_;
                   3072:     my @file_parts = split(/\./, $file);
                   3073:     my ($name,$version,$ext);
                   3074:     if (@file_parts > 1) {
                   3075: 	$ext=pop(@file_parts);
                   3076: 	if (@file_parts > 1 && $file_parts[-1] =~ /^\d+$/) {
                   3077: 	    $version=pop(@file_parts);
                   3078: 	}
                   3079: 	$name=join('.',@file_parts);
                   3080:     } else {
                   3081: 	$name=join('.',@file_parts);
                   3082:     }
                   3083:     return($name,$version,$ext);
                   3084: }
                   3085: 
1.44      ng       3086: #--------------------------------------------------------------------------------------
                   3087: #
                   3088: #-------------------------- Next few routines handles grading by section or whole class
                   3089: #
                   3090: #--- Javascript to handle grading by section or whole class
1.42      ng       3091: sub viewgrades_js {
                   3092:     my ($request) = shift;
                   3093: 
1.539     riegler  3094:     my $alertmsg = &mt('A number equal or greater than 0 is expected. Entered value = ');
1.597     wenzelju 3095:     $request->print(&Apache::lonhtmlcommon::scripttag(<<VIEWJAVASCRIPT));
1.45      ng       3096:    function writePoint(partid,weight,point) {
1.125     ng       3097: 	var radioButton = document.classgrade["RADVAL_"+partid];
                   3098: 	var textbox = document.classgrade["TEXTVAL_"+partid];
1.42      ng       3099: 	if (point == "textval") {
1.125     ng       3100: 	    point = document.classgrade["TEXTVAL_"+partid].value;
1.109     matthew  3101: 	    if (isNaN(point) || parseFloat(point) < 0) {
1.539     riegler  3102: 		alert("$alertmsg"+parseFloat(point));
1.42      ng       3103: 		var resetbox = false;
                   3104: 		for (var i=0; i<radioButton.length; i++) {
                   3105: 		    if (radioButton[i].checked) {
                   3106: 			textbox.value = i;
                   3107: 			resetbox = true;
                   3108: 		    }
                   3109: 		}
                   3110: 		if (!resetbox) {
                   3111: 		    textbox.value = "";
                   3112: 		}
                   3113: 		return;
                   3114: 	    }
1.109     matthew  3115: 	    if (parseFloat(point) > parseFloat(weight)) {
                   3116: 		var resp = confirm("You entered a value ("+parseFloat(point)+
1.44      ng       3117: 				   ") greater than the weight for the part. Accept?");
                   3118: 		if (resp == false) {
                   3119: 		    textbox.value = "";
                   3120: 		    return;
                   3121: 		}
                   3122: 	    }
1.42      ng       3123: 	    for (var i=0; i<radioButton.length; i++) {
                   3124: 		radioButton[i].checked=false;
1.109     matthew  3125: 		if (parseFloat(point) == i) {
1.42      ng       3126: 		    radioButton[i].checked=true;
                   3127: 		}
                   3128: 	    }
1.41      ng       3129: 
1.42      ng       3130: 	} else {
1.125     ng       3131: 	    textbox.value = parseFloat(point);
1.42      ng       3132: 	}
1.41      ng       3133: 	for (i=0;i<document.classgrade.total.value;i++) {
1.125     ng       3134: 	    var user = document.classgrade["ctr"+i].value;
1.289     albertel 3135: 	    user = user.replace(new RegExp(':', 'g'),"_");
1.125     ng       3136: 	    var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
                   3137: 	    var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
                   3138: 	    var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
1.42      ng       3139: 	    if (saveval != "correct") {
                   3140: 		scorename.value = point;
1.43      ng       3141: 		if (selname[0].selected != true) {
                   3142: 		    selname[0].selected = true;
                   3143: 		}
1.42      ng       3144: 	    }
                   3145: 	}
1.125     ng       3146: 	document.classgrade["SELVAL_"+partid][0].selected = true;
1.42      ng       3147:     }
                   3148: 
                   3149:     function writeRadText(partid,weight) {
1.125     ng       3150: 	var selval   = document.classgrade["SELVAL_"+partid];
                   3151: 	var radioButton = document.classgrade["RADVAL_"+partid];
1.265     www      3152:         var override = document.classgrade["FORCE_"+partid].checked;
1.125     ng       3153: 	var textbox = document.classgrade["TEXTVAL_"+partid];
                   3154: 	if (selval[1].selected || selval[2].selected) {
1.42      ng       3155: 	    for (var i=0; i<radioButton.length; i++) {
                   3156: 		radioButton[i].checked=false;
                   3157: 
                   3158: 	    }
                   3159: 	    textbox.value = "";
                   3160: 
                   3161: 	    for (i=0;i<document.classgrade.total.value;i++) {
1.125     ng       3162: 		var user = document.classgrade["ctr"+i].value;
1.289     albertel 3163: 		user = user.replace(new RegExp(':', 'g'),"_");
1.125     ng       3164: 		var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
                   3165: 		var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
                   3166: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
1.265     www      3167: 		if ((saveval != "correct") || override) {
1.42      ng       3168: 		    scorename.value = "";
1.125     ng       3169: 		    if (selval[1].selected) {
                   3170: 			selname[1].selected = true;
                   3171: 		    } else {
                   3172: 			selname[2].selected = true;
                   3173: 			if (Number(document.classgrade["GD_"+user+"_"+partid+"_tries"].value)) 
                   3174: 			{document.classgrade["GD_"+user+"_"+partid+"_tries"].value = '0';}
                   3175: 		    }
1.42      ng       3176: 		}
                   3177: 	    }
1.43      ng       3178: 	} else {
                   3179: 	    for (i=0;i<document.classgrade.total.value;i++) {
1.125     ng       3180: 		var user = document.classgrade["ctr"+i].value;
1.289     albertel 3181: 		user = user.replace(new RegExp(':', 'g'),"_");
1.125     ng       3182: 		var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
                   3183: 		var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
                   3184: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
1.265     www      3185: 		if ((saveval != "correct") || override) {
1.125     ng       3186: 		    scorename.value = document.classgrade["GD_"+user+"_"+partid+"_awarded_s"].value;
1.43      ng       3187: 		    selname[0].selected = true;
                   3188: 		}
                   3189: 	    }
                   3190: 	}	    
1.42      ng       3191:     }
                   3192: 
                   3193:     function changeSelect(partid,user) {
1.125     ng       3194: 	var selval = document.classgrade["GD_"+user+'_'+partid+"_solved"];
                   3195: 	var textbox = document.classgrade["GD_"+user+'_'+partid+"_awarded"];
1.44      ng       3196: 	var point  = textbox.value;
1.125     ng       3197: 	var weight = document.classgrade["weight_"+partid].value;
1.44      ng       3198: 
1.109     matthew  3199: 	if (isNaN(point) || parseFloat(point) < 0) {
1.539     riegler  3200: 	    alert("$alertmsg"+parseFloat(point));
1.44      ng       3201: 	    textbox.value = "";
                   3202: 	    return;
                   3203: 	}
1.109     matthew  3204: 	if (parseFloat(point) > parseFloat(weight)) {
                   3205: 	    var resp = confirm("You entered a value ("+parseFloat(point)+
1.44      ng       3206: 			       ") greater than the weight of the part. Accept?");
                   3207: 	    if (resp == false) {
                   3208: 		textbox.value = "";
                   3209: 		return;
                   3210: 	    }
                   3211: 	}
1.42      ng       3212: 	selval[0].selected = true;
                   3213:     }
                   3214: 
                   3215:     function changeOneScore(partid,user) {
1.125     ng       3216: 	var selval = document.classgrade["GD_"+user+'_'+partid+"_solved"];
                   3217: 	if (selval[1].selected || selval[2].selected) {
                   3218: 	    document.classgrade["GD_"+user+'_'+partid+"_awarded"].value = "";
                   3219: 	    if (selval[2].selected) {
                   3220: 		document.classgrade["GD_"+user+'_'+partid+"_tries"].value = "0";
                   3221: 	    }
1.269     raeburn  3222:         }
1.42      ng       3223:     }
                   3224: 
                   3225:     function resetEntry(numpart) {
                   3226: 	for (ctpart=0;ctpart<numpart;ctpart++) {
1.125     ng       3227: 	    var partid = document.classgrade["partid_"+ctpart].value;
                   3228: 	    var radioButton = document.classgrade["RADVAL_"+partid];
                   3229: 	    var textbox = document.classgrade["TEXTVAL_"+partid];
                   3230: 	    var selval  = document.classgrade["SELVAL_"+partid];
1.42      ng       3231: 	    for (var i=0; i<radioButton.length; i++) {
                   3232: 		radioButton[i].checked=false;
                   3233: 
                   3234: 	    }
                   3235: 	    textbox.value = "";
                   3236: 	    selval[0].selected = true;
                   3237: 
                   3238: 	    for (i=0;i<document.classgrade.total.value;i++) {
1.125     ng       3239: 		var user = document.classgrade["ctr"+i].value;
1.289     albertel 3240: 		user = user.replace(new RegExp(':', 'g'),"_");
1.125     ng       3241: 		var resetscore = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
                   3242: 		resetscore.value = document.classgrade["GD_"+user+"_"+partid+"_awarded_s"].value;
                   3243: 		var resettries = document.classgrade["GD_"+user+"_"+partid+"_tries"];
                   3244: 		resettries.value = document.classgrade["GD_"+user+"_"+partid+"_tries_s"].value;
                   3245: 		var saveselval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
                   3246: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
1.42      ng       3247: 		if (saveselval == "excused") {
1.43      ng       3248: 		    if (selname[1].selected == false) { selname[1].selected = true;}
1.42      ng       3249: 		} else {
1.43      ng       3250: 		    if (selname[0].selected == false) {selname[0].selected = true};
1.42      ng       3251: 		}
                   3252: 	    }
1.41      ng       3253: 	}
1.42      ng       3254:     }
                   3255: 
1.41      ng       3256: VIEWJAVASCRIPT
1.42      ng       3257: }
                   3258: 
1.44      ng       3259: #--- show scores for a section or whole class w/ option to change/update a score
1.42      ng       3260: sub viewgrades {
1.608     www      3261:     my ($request,$symb) = @_;
1.42      ng       3262:     &viewgrades_js($request);
1.41      ng       3263: 
1.168     albertel 3264:     #need to make sure we have the correct data for later EXT calls, 
                   3265:     #thus invalidate the cache
                   3266:     &Apache::lonnet::devalidatecourseresdata(
1.257     albertel 3267:                  $env{'course.'.$env{'request.course.id'}.'.num'},
                   3268:                  $env{'course.'.$env{'request.course.id'}.'.domain'});
1.168     albertel 3269:     &Apache::lonnet::clear_EXT_cache_status();
                   3270: 
1.398     albertel 3271:     my $result='<h3><span class="LC_info">'.&mt('Manual Grading').'</span></h3>';
1.41      ng       3272: 
                   3273:     #view individual student submission form - called using Javascript viewOneStudent
1.324     albertel 3274:     $result.=&jscriptNform($symb);
1.41      ng       3275: 
1.44      ng       3276:     #beginning of class grading form
1.442     banghart 3277:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
1.41      ng       3278:     $result.= '<form action="/adm/grades" method="post" name="classgrade">'."\n".
1.418     albertel 3279: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.38      ng       3280: 	'<input type="hidden" name="command" value="editgrades" />'."\n".
1.432     banghart 3281: 	&build_section_inputs().
1.442     banghart 3282: 	'<input type="hidden" name="Status" value="'.$env{'stu_status'}.'" />'."\n".
1.72      ng       3283: 
1.560     raeburn  3284:     my ($common_header,$specific_header);
1.257     albertel 3285:     if ($env{'form.section'} eq 'all') {
1.560     raeburn  3286: 	$common_header = &mt('Assign Common Grade to Class');
                   3287:         $specific_header = &mt('Assign Grade to Specific Students in Class');
1.257     albertel 3288:     } elsif ($env{'form.section'} eq 'none') {
1.560     raeburn  3289:         $common_header = &mt('Assign Common Grade to Students in no Section');
                   3290: 	$specific_header = &mt('Assign Grade to Specific Students in no Section');
1.52      albertel 3291:     } else {
1.560     raeburn  3292:         my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
                   3293:         $common_header = &mt('Assign Common Grade to Students in Section(s) [_1]',$section_display);
                   3294: 	$specific_header = &mt('Assign Grade to Specific Students in Section(s) [_1]',$section_display);
1.52      albertel 3295:     }
1.560     raeburn  3296:     $result.= '<h3>'.$common_header.'</h3>'.&Apache::loncommon::start_data_table();
1.44      ng       3297:     #radio buttons/text box for assigning points for a section or class.
                   3298:     #handles different parts of a problem
1.582     raeburn  3299:     my $res_error;
                   3300:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
                   3301:     if ($res_error) {
                   3302:         return &navmap_errormsg();
                   3303:     }
1.42      ng       3304:     my %weight = ();
                   3305:     my $ctsparts = 0;
1.45      ng       3306:     my %seen = ();
1.375     albertel 3307:     my @part_response_id = &flatten_responseType($responseType);
                   3308:     foreach my $part_response_id (@part_response_id) {
                   3309:     	my ($partid,$respid) = @{ $part_response_id };
                   3310: 	my $part_resp = join('_',@{ $part_response_id });
1.45      ng       3311: 	next if $seen{$partid};
                   3312: 	$seen{$partid}++;
1.375     albertel 3313: 	my $handgrade=$$handgrade{$part_resp};
1.42      ng       3314: 	my $wgt = &Apache::lonnet::EXT('resource.'.$partid.'.weight',$symb);
                   3315: 	$weight{$partid} = $wgt eq '' ? '1' : $wgt;
                   3316: 
1.324     albertel 3317: 	my $display_part=&get_display_part($partid,$symb);
1.485     albertel 3318: 	my $radio.='<table border="0"><tr>';  
1.41      ng       3319: 	my $ctr = 0;
1.42      ng       3320: 	while ($ctr<=$weight{$partid}) { # display radio buttons in a nice table 10 across
1.485     albertel 3321: 	    $radio.= '<td><label><input type="radio" name="RADVAL_'.$partid.'" '.
1.54      albertel 3322: 		'onclick="javascript:writePoint(\''.$partid.'\','.$weight{$partid}.
1.288     albertel 3323: 		','.$ctr.')" />'.$ctr."</label></td>\n";
1.41      ng       3324: 	    $result.=(($ctr+1)%10 == 0 ? '</tr><tr>' : '');
                   3325: 	    $ctr++;
                   3326: 	}
1.485     albertel 3327: 	$radio.='</tr></table>';
                   3328: 	my $line = '<input type="text" name="TEXTVAL_'.
1.589     bisitz   3329: 	    $partid.'" size="4" '.'onchange="javascript:writePoint(\''.
1.54      albertel 3330: 		$partid.'\','.$weight{$partid}.',\'textval\')" /> /'.
1.539     riegler  3331: 	    $weight{$partid}.' '.&mt('(problem weight)').'</td>'."\n";
                   3332: 	$line.= '<td><b>'.&mt('Grade Status').':</b><select name="SELVAL_'.$partid.'"'.
1.589     bisitz   3333: 	    'onchange="javascript:writeRadText(\''.$partid.'\','.
1.59      albertel 3334: 		$weight{$partid}.')"> '.
1.401     albertel 3335: 	    '<option selected="selected"> </option>'.
1.485     albertel 3336: 	    '<option value="excused">'.&mt('excused').'</option>'.
                   3337: 	    '<option value="reset status">'.&mt('reset status').'</option>'.
                   3338: 	    '</select></td>'.
                   3339:             '<td><label><input type="checkbox" name="FORCE_'.$partid.'" />'.&mt('Override "Correct"').'</label>';
                   3340: 	$line.='<input type="hidden" name="partid_'.
                   3341: 	    $ctsparts.'" value="'.$partid.'" />'."\n";
                   3342: 	$line.='<input type="hidden" name="weight_'.
                   3343: 	    $partid.'" value="'.$weight{$partid}.'" />'."\n";
                   3344: 
                   3345: 	$result.=
                   3346: 	    &Apache::loncommon::start_data_table_row()."\n".
1.577     bisitz   3347: 	    '<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 3348: 	    &Apache::loncommon::end_data_table_row()."\n";
1.42      ng       3349: 	$ctsparts++;
1.41      ng       3350:     }
1.474     albertel 3351:     $result.=&Apache::loncommon::end_data_table()."\n".
1.52      albertel 3352: 	'<input type="hidden" name="totalparts" value="'.$ctsparts.'" />';
1.485     albertel 3353:     $result.='<input type="button" value="'.&mt('Revert to Default').'" '.
1.589     bisitz   3354: 	'onclick="javascript:resetEntry('.$ctsparts.');" />';
1.41      ng       3355: 
1.44      ng       3356:     #table listing all the students in a section/class
                   3357:     #header of table
1.560     raeburn  3358:     $result.= '<h3>'.$specific_header.'</h3>'.
                   3359:               &Apache::loncommon::start_data_table().
                   3360: 	      &Apache::loncommon::start_data_table_header_row().
                   3361: 	      '<th>'.&mt('No.').'</th>'.
                   3362: 	      '<th>'.&nameUserString('header')."</th>\n";
1.582     raeburn  3363:     my $partserror;
                   3364:     my (@parts) = sort(&getpartlist($symb,\$partserror));
                   3365:     if ($partserror) {
                   3366:         return &navmap_errormsg();
                   3367:     }
1.324     albertel 3368:     my (undef,undef,$url)=&Apache::lonnet::decode_symb($symb);
1.269     raeburn  3369:     my @partids = ();
1.41      ng       3370:     foreach my $part (@parts) {
                   3371: 	my $display=&Apache::lonnet::metadata($url,$part.'.display');
1.539     riegler  3372:         my $narrowtext = &mt('Tries');
                   3373: 	$display =~ s|^Number of Attempts|$narrowtext <br />|; # makes the column narrower
1.41      ng       3374: 	if  (!$display) { $display = &Apache::lonnet::metadata($url,$part.'.name'); }
1.207     albertel 3375: 	my ($partid) = &split_part_type($part);
1.524     raeburn  3376:         push(@partids,$partid);
1.324     albertel 3377: 	my $display_part=&get_display_part($partid,$symb);
1.41      ng       3378: 	if ($display =~ /^Partial Credit Factor/) {
1.485     albertel 3379: 	    $result.='<th>'.
                   3380: 		&mt('Score Part: [_1]<br /> (weight = [_2])',
                   3381: 		    $display_part,$weight{$partid}).'</th>'."\n";
1.41      ng       3382: 	    next;
1.485     albertel 3383: 	    
1.207     albertel 3384: 	} else {
1.485     albertel 3385: 	    if ($display =~ /Problem Status/) {
                   3386: 		my $grade_status_mt = &mt('Grade Status');
                   3387: 		$display =~ s{Problem Status}{$grade_status_mt<br />};
                   3388: 	    }
                   3389: 	    my $part_mt = &mt('Part:');
                   3390: 	    $display =~s{\[Part: \Q$partid\E\]}{$part_mt $display_part};
1.41      ng       3391: 	}
1.485     albertel 3392: 
1.474     albertel 3393: 	$result.='<th>'.$display.'</th>'."\n";
1.41      ng       3394:     }
1.474     albertel 3395:     $result.=&Apache::loncommon::end_data_table_header_row();
1.44      ng       3396: 
1.270     albertel 3397:     my %last_resets = 
                   3398: 	&get_last_resets($symb,$env{'request.course.id'},\@partids);
1.269     raeburn  3399: 
1.41      ng       3400:     #get info for each student
1.44      ng       3401:     #list all the students - with points and grade status
1.257     albertel 3402:     my (undef,undef,$fullname) = &getclasslist($env{'form.section'},'1');
1.41      ng       3403:     my $ctr = 0;
1.294     albertel 3404:     foreach (sort 
                   3405: 	     {
                   3406: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                   3407: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                   3408: 		 }
                   3409: 		 return $a cmp $b;
                   3410: 	     } (keys(%$fullname))) {
1.126     ng       3411: 	$ctr++;
1.324     albertel 3412: 	$result.=&viewstudentgrade($symb,$env{'request.course.id'},
1.269     raeburn  3413: 				   $_,$$fullname{$_},\@parts,\%weight,$ctr,\%last_resets);
1.41      ng       3414:     }
1.474     albertel 3415:     $result.=&Apache::loncommon::end_data_table();
1.41      ng       3416:     $result.='<input type="hidden" name="total" value="'.$ctr.'" />'."\n";
1.485     albertel 3417:     $result.='<input type="button" value="'.&mt('Save').'" '.
1.589     bisitz   3418: 	'onclick="javascript:submit();" target="_self" /></form>'."\n";
1.96      albertel 3419:     if (scalar(%$fullname) eq 0) {
                   3420: 	my $colspan=3+scalar(@parts);
1.433     banghart 3421: 	my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
1.442     banghart 3422:         my $stu_status = join(' or ',&Apache::loncommon::get_env_multiple('form.Status'));
1.433     banghart 3423: 	$result='<span class="LC_warning">'.
1.485     albertel 3424: 	    &mt('There are no students in section(s) [_1] with enrollment status [_2] to modify or grade.',
1.442     banghart 3425: 	        $section_display, $stu_status).
1.433     banghart 3426: 	    '</span>';
1.96      albertel 3427:     }
1.41      ng       3428:     return $result;
                   3429: }
                   3430: 
1.44      ng       3431: #--- call by previous routine to display each student
1.41      ng       3432: sub viewstudentgrade {
1.324     albertel 3433:     my ($symb,$courseid,$student,$fullname,$parts,$weight,$ctr,$last_resets) = @_;
1.44      ng       3434:     my ($uname,$udom) = split(/:/,$student);
                   3435:     my %record=&Apache::lonnet::restore($symb,$courseid,$udom,$uname);
1.269     raeburn  3436:     my %aggregates = (); 
1.474     albertel 3437:     my $result=&Apache::loncommon::start_data_table_row().'<td align="right">'.
1.233     albertel 3438: 	'<input type="hidden" name="ctr'.($ctr-1).'" value="'.$student.'" />'.
                   3439: 	"\n".$ctr.'&nbsp;</td><td>&nbsp;'.
1.44      ng       3440: 	'<a href="javascript:viewOneStudent(\''.$uname.'\',\''.$udom.
1.417     albertel 3441: 	'\');" target="_self">'.$fullname.'</a> '.
1.398     albertel 3442: 	'<span class="LC_internal_info">('.$uname.($env{'user.domain'} eq $udom ? '' : ':'.$udom).')</span></td>'."\n";
1.281     albertel 3443:     $student=~s/:/_/; # colon doen't work in javascript for names
1.63      albertel 3444:     foreach my $apart (@$parts) {
                   3445: 	my ($part,$type) = &split_part_type($apart);
1.41      ng       3446: 	my $score=$record{"resource.$part.$type"};
1.276     albertel 3447:         $result.='<td align="center">';
1.269     raeburn  3448:         my ($aggtries,$totaltries);
                   3449:         unless (exists($aggregates{$part})) {
1.270     albertel 3450: 	    $totaltries = $record{'resource.'.$part.'.tries'};
                   3451: 
                   3452: 	    $aggtries = $totaltries;
1.269     raeburn  3453:             if ($$last_resets{$part}) {  
1.270     albertel 3454:                 $aggtries = &get_num_tries(\%record,$$last_resets{$part},
                   3455: 					   $part);
                   3456:             }
1.269     raeburn  3457:             $result.='<input type="hidden" name="'.
                   3458:                 'GD_'.$student.'_'.$part.'_aggtries" value="'.$aggtries.'" />'."\n";
                   3459:             $result.='<input type="hidden" name="'.
                   3460:                 'GD_'.$student.'_'.$part.'_totaltries" value="'.$totaltries.'" />'."\n";
                   3461:             $aggregates{$part} = 1;
                   3462:         }
1.41      ng       3463: 	if ($type eq 'awarded') {
1.320     albertel 3464: 	    my $pts = $score eq '' ? '' : &compute_points($score,$$weight{$part});
1.42      ng       3465: 	    $result.='<input type="hidden" name="'.
1.89      albertel 3466: 		'GD_'.$student.'_'.$part.'_awarded_s" value="'.$pts.'" />'."\n";
1.233     albertel 3467: 	    $result.='<input type="text" name="'.
1.89      albertel 3468: 		'GD_'.$student.'_'.$part.'_awarded" '.
1.589     bisitz   3469:                 'onchange="javascript:changeSelect(\''.$part.'\',\''.$student.
1.44      ng       3470: 		'\')" value="'.$pts.'" size="4" /></td>'."\n";
1.41      ng       3471: 	} elsif ($type eq 'solved') {
                   3472: 	    my ($status,$foo)=split(/_/,$score,2);
                   3473: 	    $status = 'nothing' if ($status eq '');
1.89      albertel 3474: 	    $result.='<input type="hidden" name="'.'GD_'.$student.'_'.
1.54      albertel 3475: 		$part.'_solved_s" value="'.$status.'" />'."\n";
1.233     albertel 3476: 	    $result.='&nbsp;<select name="'.
1.89      albertel 3477: 		'GD_'.$student.'_'.$part.'_solved" '.
1.589     bisitz   3478:                 'onchange="javascript:changeOneScore(\''.$part.'\',\''.$student.'\')" >'."\n";
1.485     albertel 3479: 	    $result.= (($status eq 'excused') ? '<option> </option><option selected="selected" value="excused">'.&mt('excused').'</option>' 
                   3480: 		: '<option selected="selected"> </option><option value="excused">'.&mt('excused').'</option>')."\n";
                   3481: 	    $result.='<option value="reset status">'.&mt('reset status').'</option>';
1.126     ng       3482: 	    $result.="</select>&nbsp;</td>\n";
1.122     ng       3483: 	} else {
                   3484: 	    $result.='<input type="hidden" name="'.
                   3485: 		'GD_'.$student.'_'.$part.'_'.$type.'_s" value="'.$score.'" />'.
                   3486: 		    "\n";
1.233     albertel 3487: 	    $result.='<input type="text" name="'.
1.122     ng       3488: 		'GD_'.$student.'_'.$part.'_'.$type.'" '.
                   3489: 		'value="'.$score.'" size="4" /></td>'."\n";
1.41      ng       3490: 	}
                   3491:     }
1.474     albertel 3492:     $result.=&Apache::loncommon::end_data_table_row();
1.41      ng       3493:     return $result;
1.38      ng       3494: }
                   3495: 
1.44      ng       3496: #--- change scores for all the students in a section/class
                   3497: #    record does not get update if unchanged
1.38      ng       3498: sub editgrades {
1.608     www      3499:     my ($request,$symb) = @_;
1.41      ng       3500: 
1.433     banghart 3501:     my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
1.477     albertel 3502:     my $title='<h2>'.&mt('Current Grade Status').'</h2>';
1.433     banghart 3503:     $title.='<h4>'.&mt('<b>Section: </b>[_1]',$section_display).'</h4>'."\n";
1.126     ng       3504: 
1.477     albertel 3505:     my $result= &Apache::loncommon::start_data_table().
                   3506: 	&Apache::loncommon::start_data_table_header_row().
                   3507: 	'<th rowspan="2" valign="middle">'.&mt('No.').'</th>'.
                   3508: 	'<th rowspan="2" valign="middle">'.&nameUserString('header')."</th>\n";
1.43      ng       3509:     my %scoreptr = (
                   3510: 		    'correct'  =>'correct_by_override',
                   3511: 		    'incorrect'=>'incorrect_by_override',
                   3512: 		    'excused'  =>'excused',
                   3513: 		    'ungraded' =>'ungraded_attempted',
1.596     raeburn  3514:                     'credited' =>'credit_attempted',
1.43      ng       3515: 		    'nothing'  => '',
                   3516: 		    );
1.257     albertel 3517:     my ($classlist,undef,$fullname) = &getclasslist($env{'form.section'},'0');
1.34      ng       3518: 
1.44      ng       3519:     my (@partid);
                   3520:     my %weight = ();
1.54      albertel 3521:     my %columns = ();
1.44      ng       3522:     my ($i,$ctr,$count,$rec_update) = (0,0,0,0);
1.54      albertel 3523: 
1.582     raeburn  3524:     my $partserror;
                   3525:     my (@parts) = sort(&getpartlist($symb,\$partserror));
                   3526:     if ($partserror) {
                   3527:         return &navmap_errormsg();
                   3528:     }
1.54      albertel 3529:     my $header;
1.257     albertel 3530:     while ($ctr < $env{'form.totalparts'}) {
                   3531: 	my $partid = $env{'form.partid_'.$ctr};
1.524     raeburn  3532: 	push(@partid,$partid);
1.257     albertel 3533: 	$weight{$partid} = $env{'form.weight_'.$partid};
1.44      ng       3534: 	$ctr++;
1.54      albertel 3535:     }
1.324     albertel 3536:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
1.54      albertel 3537:     foreach my $partid (@partid) {
1.478     albertel 3538: 	$header .= '<th align="center">'.&mt('Old Score').'</th>'.
                   3539: 	    '<th align="center">'.&mt('New Score').'</th>';
1.54      albertel 3540: 	$columns{$partid}=2;
                   3541: 	foreach my $stores (@parts) {
                   3542: 	    my ($part,$type) = &split_part_type($stores);
                   3543: 	    if ($part !~ m/^\Q$partid\E/) { next;}
                   3544: 	    if ($type eq 'awarded' || $type eq 'solved') { next; }
                   3545: 	    my $display=&Apache::lonnet::metadata($url,$stores.'.display');
1.551     raeburn  3546: 	    $display =~ s/\[Part: \Q$part\E\]//;
1.539     riegler  3547:             my $narrowtext = &mt('Tries');
                   3548: 	    $display =~ s/Number of Attempts/$narrowtext/;
                   3549: 	    $header .= '<th align="center">'.&mt('Old').' '.$display.'</th>'.
                   3550: 		'<th align="center">'.&mt('New').' '.$display.'</th>';
1.54      albertel 3551: 	    $columns{$partid}+=2;
                   3552: 	}
                   3553:     }
                   3554:     foreach my $partid (@partid) {
1.324     albertel 3555: 	my $display_part=&get_display_part($partid,$symb);
1.478     albertel 3556: 	$result .= '<th colspan="'.$columns{$partid}.'" align="center">'.
                   3557: 	    &mt('Part: [_1] (Weight = [_2])',$display_part,$weight{$partid}).
                   3558: 	    '</th>';
1.54      albertel 3559: 
1.44      ng       3560:     }
1.477     albertel 3561:     $result .= &Apache::loncommon::end_data_table_header_row().
                   3562: 	&Apache::loncommon::start_data_table_header_row().
                   3563: 	$header.
                   3564: 	&Apache::loncommon::end_data_table_header_row();
                   3565:     my @noupdate;
1.126     ng       3566:     my ($updateCtr,$noupdateCtr) = (1,1);
1.257     albertel 3567:     for ($i=0; $i<$env{'form.total'}; $i++) {
1.93      albertel 3568: 	my $line;
1.257     albertel 3569: 	my $user = $env{'form.ctr'.$i};
1.281     albertel 3570: 	my ($uname,$udom)=split(/:/,$user);
1.44      ng       3571: 	my %newrecord;
                   3572: 	my $updateflag = 0;
1.281     albertel 3573: 	$line .= '<td>'.&nameUserString(undef,$$fullname{$user},$uname,$udom).'</td>';
1.108     albertel 3574: 	my $usec=$classlist->{"$uname:$udom"}[5];
1.105     albertel 3575: 	if (!&canmodify($usec)) {
1.126     ng       3576: 	    my $numcols=scalar(@partid)*4+2;
1.477     albertel 3577: 	    push(@noupdate,
1.478     albertel 3578: 		 $line."<td colspan=\"$numcols\"><span class=\"LC_warning\">".
                   3579: 		 &mt('Not allowed to modify student')."</span></td></tr>");
1.105     albertel 3580: 	    next;
                   3581: 	}
1.269     raeburn  3582:         my %aggregate = ();
                   3583:         my $aggregateflag = 0;
1.281     albertel 3584: 	$user=~s/:/_/; # colon doen't work in javascript for names
1.44      ng       3585: 	foreach (@partid) {
1.257     albertel 3586: 	    my $old_aw    = $env{'form.GD_'.$user.'_'.$_.'_awarded_s'};
1.54      albertel 3587: 	    my $old_part_pcr = $old_aw/($weight{$_} ne '0' ? $weight{$_}:1);
                   3588: 	    my $old_part  = $old_aw eq '' ? '' : $old_part_pcr;
1.257     albertel 3589: 	    my $old_score = $scoreptr{$env{'form.GD_'.$user.'_'.$_.'_solved_s'}};
                   3590: 	    my $awarded   = $env{'form.GD_'.$user.'_'.$_.'_awarded'};
1.54      albertel 3591: 	    my $pcr       = $awarded/($weight{$_} ne '0' ? $weight{$_} : 1);
                   3592: 	    my $partial   = $awarded eq '' ? '' : $pcr;
1.44      ng       3593: 	    my $score;
                   3594: 	    if ($partial eq '') {
1.257     albertel 3595: 		$score = $scoreptr{$env{'form.GD_'.$user.'_'.$_.'_solved_s'}};
1.44      ng       3596: 	    } elsif ($partial > 0) {
                   3597: 		$score = 'correct_by_override';
                   3598: 	    } elsif ($partial == 0) {
                   3599: 		$score = 'incorrect_by_override';
                   3600: 	    }
1.257     albertel 3601: 	    my $dropMenu = $env{'form.GD_'.$user.'_'.$_.'_solved'};
1.125     ng       3602: 	    $score = 'excused' if (($dropMenu eq 'excused') && ($score ne 'excused'));
                   3603: 
1.292     albertel 3604: 	    $newrecord{'resource.'.$_.'.regrader'}=
                   3605: 		"$env{'user.name'}:$env{'user.domain'}";
1.125     ng       3606: 	    if ($dropMenu eq 'reset status' &&
                   3607: 		$old_score ne '') { # ignore if no previous attempts => nothing to reset
1.299     albertel 3608: 		$newrecord{'resource.'.$_.'.tries'} = '';
1.125     ng       3609: 		$newrecord{'resource.'.$_.'.solved'} = '';
                   3610: 		$newrecord{'resource.'.$_.'.award'} = '';
1.299     albertel 3611: 		$newrecord{'resource.'.$_.'.awarded'} = '';
1.125     ng       3612: 		$updateflag = 1;
1.269     raeburn  3613:                 if ($env{'form.GD_'.$user.'_'.$_.'_aggtries'} > 0) {
                   3614:                     my $aggtries = $env{'form.GD_'.$user.'_'.$_.'_aggtries'};
                   3615:                     my $totaltries = $env{'form.GD_'.$user.'_'.$_.'_totaltries'};
                   3616:                     my $solvedstatus = $env{'form.GD_'.$user.'_'.$_.'_solved_s'};
                   3617:                     &decrement_aggs($symb,$_,\%aggregate,$aggtries,$totaltries,$solvedstatus);
                   3618:                     $aggregateflag = 1;
                   3619:                 }
1.139     albertel 3620: 	    } elsif (!($old_part eq $partial && $old_score eq $score)) {
                   3621: 		$updateflag = 1;
                   3622: 		$newrecord{'resource.'.$_.'.awarded'}  = $partial if $partial ne '';
                   3623: 		$newrecord{'resource.'.$_.'.solved'}   = $score;
                   3624: 		$rec_update++;
1.125     ng       3625: 	    }
                   3626: 
1.93      albertel 3627: 	    $line .= '<td align="center">'.$old_aw.'&nbsp;</td>'.
1.44      ng       3628: 		'<td align="center">'.$awarded.
                   3629: 		($score eq 'excused' ? $score : '').'&nbsp;</td>';
1.5       albertel 3630: 
1.54      albertel 3631: 
                   3632: 	    my $partid=$_;
                   3633: 	    foreach my $stores (@parts) {
                   3634: 		my ($part,$type) = &split_part_type($stores);
                   3635: 		if ($part !~ m/^\Q$partid\E/) { next;}
                   3636: 		if ($type eq 'awarded' || $type eq 'solved') { next; }
1.257     albertel 3637: 		my $old_aw    = $env{'form.GD_'.$user.'_'.$part.'_'.$type.'_s'};
                   3638: 		my $awarded   = $env{'form.GD_'.$user.'_'.$part.'_'.$type};
1.54      albertel 3639: 		if ($awarded ne '' && $awarded ne $old_aw) {
                   3640: 		    $newrecord{'resource.'.$part.'.'.$type}= $awarded;
1.257     albertel 3641: 		    $newrecord{'resource.'.$part.'.regrader'}="$env{'user.name'}:$env{'user.domain'}";
1.54      albertel 3642: 		    $updateflag=1;
                   3643: 		}
1.93      albertel 3644: 		$line .= '<td align="center">'.$old_aw.'&nbsp;</td>'.
1.54      albertel 3645: 		    '<td align="center">'.$awarded.'&nbsp;</td>';
                   3646: 	    }
1.44      ng       3647: 	}
1.477     albertel 3648: 	$line.="\n";
1.301     albertel 3649: 
                   3650: 	my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   3651: 	my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   3652: 
1.44      ng       3653: 	if ($updateflag) {
                   3654: 	    $count++;
1.257     albertel 3655: 	    &Apache::lonnet::cstore(\%newrecord,$symb,$env{'request.course.id'},
1.89      albertel 3656: 				    $udom,$uname);
1.301     albertel 3657: 
                   3658: 	    if (&Apache::bridgetask::in_queue('gradingqueue',$symb,$cdom,
                   3659: 					      $cnum,$udom,$uname)) {
                   3660: 		# need to figure out if should be in queue.
                   3661: 		my %record =  
                   3662: 		    &Apache::lonnet::restore($symb,$env{'request.course.id'},
                   3663: 					     $udom,$uname);
                   3664: 		my $all_graded = 1;
                   3665: 		my $none_graded = 1;
                   3666: 		foreach my $part (@parts) {
                   3667: 		    if ( $record{'resource.'.$part.'.awarded'} eq '' ) {
                   3668: 			$all_graded = 0;
                   3669: 		    } else {
                   3670: 			$none_graded = 0;
                   3671: 		    }
                   3672: 		}
                   3673: 
                   3674: 		if ($all_graded || $none_graded) {
                   3675: 		    &Apache::bridgetask::remove_from_queue('gradingqueue',
                   3676: 							   $symb,$cdom,$cnum,
                   3677: 							   $udom,$uname);
                   3678: 		}
                   3679: 	    }
                   3680: 
1.477     albertel 3681: 	    $result.=&Apache::loncommon::start_data_table_row().
                   3682: 		'<td align="right">&nbsp;'.$updateCtr.'&nbsp;</td>'.$line.
                   3683: 		&Apache::loncommon::end_data_table_row();
1.126     ng       3684: 	    $updateCtr++;
1.93      albertel 3685: 	} else {
1.477     albertel 3686: 	    push(@noupdate,
                   3687: 		 '<td align="right">&nbsp;'.$noupdateCtr.'&nbsp;</td>'.$line);
1.126     ng       3688: 	    $noupdateCtr++;
1.44      ng       3689: 	}
1.269     raeburn  3690:         if ($aggregateflag) {
                   3691:             &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
1.301     albertel 3692: 				  $cdom,$cnum);
1.269     raeburn  3693:         }
1.93      albertel 3694:     }
1.477     albertel 3695:     if (@noupdate) {
1.126     ng       3696: #	my $numcols=(scalar(@partid)*(scalar(@parts)-1)*2)+3;
                   3697: 	my $numcols=scalar(@partid)*4+2;
1.477     albertel 3698: 	$result .= &Apache::loncommon::start_data_table_row('LC_empty_row').
1.478     albertel 3699: 	    '<td align="center" colspan="'.$numcols.'">'.
                   3700: 	    &mt('No Changes Occurred For the Students Below').
                   3701: 	    '</td>'.
1.477     albertel 3702: 	    &Apache::loncommon::end_data_table_row();
                   3703: 	foreach my $line (@noupdate) {
                   3704: 	    $result.=
                   3705: 		&Apache::loncommon::start_data_table_row().
                   3706: 		$line.
                   3707: 		&Apache::loncommon::end_data_table_row();
                   3708: 	}
1.44      ng       3709:     }
1.614     www      3710:     $result .= &Apache::loncommon::end_data_table();
1.478     albertel 3711:     my $msg = '<p><b>'.
                   3712: 	&mt('Number of records updated = [_1] for [quant,_2,student].',
                   3713: 	    $rec_update,$count).'</b><br />'.
                   3714: 	'<b>'.&mt('Total number of students = [_1]',$env{'form.total'}).
                   3715: 	'</b></p>';
1.44      ng       3716:     return $title.$msg.$result;
1.5       albertel 3717: }
1.54      albertel 3718: 
                   3719: sub split_part_type {
                   3720:     my ($partstr) = @_;
                   3721:     my ($temp,@allparts)=split(/_/,$partstr);
                   3722:     my $type=pop(@allparts);
1.439     albertel 3723:     my $part=join('_',@allparts);
1.54      albertel 3724:     return ($part,$type);
                   3725: }
                   3726: 
1.44      ng       3727: #------------- end of section for handling grading by section/class ---------
                   3728: #
                   3729: #----------------------------------------------------------------------------
                   3730: 
1.5       albertel 3731: 
1.44      ng       3732: #----------------------------------------------------------------------------
                   3733: #
                   3734: #-------------------------- Next few routines handles grading by csv upload
                   3735: #
                   3736: #--- Javascript to handle csv upload
1.27      albertel 3737: sub csvupload_javascript_reverse_associate {
1.573     bisitz   3738:     my $error1=&mt('You need to specify the username or the student/employee ID');
1.246     albertel 3739:     my $error2=&mt('You need to specify at least one grading field');
1.27      albertel 3740:   return(<<ENDPICK);
                   3741:   function verify(vf) {
                   3742:     var foundsomething=0;
                   3743:     var founduname=0;
1.243     albertel 3744:     var foundID=0;
1.27      albertel 3745:     for (i=0;i<=vf.nfields.value;i++) {
                   3746:       tw=eval('vf.f'+i+'.selectedIndex');
1.243     albertel 3747:       if (i==0 && tw!=0) { foundID=1; }
                   3748:       if (i==1 && tw!=0) { founduname=1; }
                   3749:       if (i!=0 && i!=1 && i!=2 && tw!=0) { foundsomething=1; }
1.27      albertel 3750:     }
1.246     albertel 3751:     if (founduname==0 && foundID==0) {
                   3752: 	alert('$error1');
                   3753: 	return;
1.27      albertel 3754:     }
                   3755:     if (foundsomething==0) {
1.246     albertel 3756: 	alert('$error2');
                   3757: 	return;
1.27      albertel 3758:     }
                   3759:     vf.submit();
                   3760:   }
                   3761:   function flip(vf,tf) {
                   3762:     var nw=eval('vf.f'+tf+'.selectedIndex');
                   3763:     var i;
                   3764:     for (i=0;i<=vf.nfields.value;i++) {
                   3765:       //can not pick the same destination field for both name and domain
                   3766:       if (((i ==0)||(i ==1)) && 
                   3767:           ((tf==0)||(tf==1)) && 
                   3768:           (i!=tf) &&
                   3769:           (eval('vf.f'+i+'.selectedIndex')==nw)) {
                   3770:         eval('vf.f'+i+'.selectedIndex=0;')
                   3771:       }
                   3772:     }
                   3773:   }
                   3774: ENDPICK
                   3775: }
                   3776: 
                   3777: sub csvupload_javascript_forward_associate {
1.573     bisitz   3778:     my $error1=&mt('You need to specify the username or the student/employee ID');
1.246     albertel 3779:     my $error2=&mt('You need to specify at least one grading field');
1.27      albertel 3780:   return(<<ENDPICK);
                   3781:   function verify(vf) {
                   3782:     var foundsomething=0;
                   3783:     var founduname=0;
1.243     albertel 3784:     var foundID=0;
1.27      albertel 3785:     for (i=0;i<=vf.nfields.value;i++) {
                   3786:       tw=eval('vf.f'+i+'.selectedIndex');
1.243     albertel 3787:       if (tw==1) { foundID=1; }
                   3788:       if (tw==2) { founduname=1; }
                   3789:       if (tw>3) { foundsomething=1; }
1.27      albertel 3790:     }
1.246     albertel 3791:     if (founduname==0 && foundID==0) {
                   3792: 	alert('$error1');
                   3793: 	return;
1.27      albertel 3794:     }
                   3795:     if (foundsomething==0) {
1.246     albertel 3796: 	alert('$error2');
                   3797: 	return;
1.27      albertel 3798:     }
                   3799:     vf.submit();
                   3800:   }
                   3801:   function flip(vf,tf) {
                   3802:     var nw=eval('vf.f'+tf+'.selectedIndex');
                   3803:     var i;
                   3804:     //can not pick the same destination field twice
                   3805:     for (i=0;i<=vf.nfields.value;i++) {
                   3806:       if ((i!=tf) && (eval('vf.f'+i+'.selectedIndex')==nw)) {
                   3807:         eval('vf.f'+i+'.selectedIndex=0;')
                   3808:       }
                   3809:     }
                   3810:   }
                   3811: ENDPICK
                   3812: }
                   3813: 
1.26      albertel 3814: sub csvuploadmap_header {
1.324     albertel 3815:     my ($request,$symb,$datatoken,$distotal)= @_;
1.41      ng       3816:     my $javascript;
1.257     albertel 3817:     if ($env{'form.upfile_associate'} eq 'reverse') {
1.41      ng       3818: 	$javascript=&csvupload_javascript_reverse_associate();
                   3819:     } else {
                   3820: 	$javascript=&csvupload_javascript_forward_associate();
                   3821:     }
1.45      ng       3822: 
1.598     www      3823:     my $result='';
1.257     albertel 3824:     my $checked=(($env{'form.noFirstLine'})?' checked="checked"':'');
1.245     albertel 3825:     my $ignore=&mt('Ignore First Line');
1.418     albertel 3826:     $symb = &Apache::lonenc::check_encrypt($symb);
1.41      ng       3827:     $request->print(<<ENDPICK);
1.26      albertel 3828: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
1.398     albertel 3829: <h3><span class="LC_info">Uploading Class Grades</span></h3>
1.45      ng       3830: $result
1.326     albertel 3831: <hr />
1.26      albertel 3832: <h3>Identify fields</h3>
                   3833: Total number of records found in file: $distotal <hr />
                   3834: Enter as many fields as you can. The system will inform you and bring you back
                   3835: to this page if the data selected is insufficient to run your class.<hr />
1.589     bisitz   3836: <input type="button" value="Reverse Association" onclick="javascript:this.form.associate.value='Reverse Association';submit(this.form);" />
1.245     albertel 3837: <label><input type="checkbox" name="noFirstLine" $checked />$ignore</label>
1.26      albertel 3838: <input type="hidden" name="associate"  value="" />
                   3839: <input type="hidden" name="phase"      value="three" />
                   3840: <input type="hidden" name="datatoken"  value="$datatoken" />
1.257     albertel 3841: <input type="hidden" name="fileupload" value="$env{'form.fileupload'}" />
                   3842: <input type="hidden" name="upfiletype" value="$env{'form.upfiletype'}" />
1.26      albertel 3843: <input type="hidden" name="upfile_associate" 
1.257     albertel 3844:                                        value="$env{'form.upfile_associate'}" />
1.26      albertel 3845: <input type="hidden" name="symb"       value="$symb" />
1.246     albertel 3846: <input type="hidden" name="command"    value="csvuploadoptions" />
1.26      albertel 3847: <hr />
                   3848: ENDPICK
1.597     wenzelju 3849:     $request->print(&Apache::lonhtmlcommon::scripttag($javascript));
1.118     ng       3850:     return '';
1.26      albertel 3851: 
                   3852: }
                   3853: 
                   3854: sub csvupload_fields {
1.582     raeburn  3855:     my ($symb,$errorref) = @_;
                   3856:     my (@parts) = &getpartlist($symb,$errorref);
                   3857:     if (ref($errorref)) {
                   3858:         if ($$errorref) {
                   3859:             return;
                   3860:         }
                   3861:     }
                   3862: 
1.556     weissno  3863:     my @fields=(['ID','Student/Employee ID'],
1.243     albertel 3864: 		['username','Student Username'],
                   3865: 		['domain','Student Domain']);
1.324     albertel 3866:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
1.41      ng       3867:     foreach my $part (sort(@parts)) {
                   3868: 	my @datum;
                   3869: 	my $display=&Apache::lonnet::metadata($url,$part.'.display');
                   3870: 	my $name=$part;
                   3871: 	if  (!$display) { $display = $name; }
                   3872: 	@datum=($name,$display);
1.244     albertel 3873: 	if ($name=~/^stores_(.*)_awarded/) {
                   3874: 	    push(@fields,['stores_'.$1.'_points',"Points [Part: $1]"]);
                   3875: 	}
1.41      ng       3876: 	push(@fields,\@datum);
                   3877:     }
                   3878:     return (@fields);
1.26      albertel 3879: }
                   3880: 
                   3881: sub csvuploadmap_footer {
1.41      ng       3882:     my ($request,$i,$keyfields) =@_;
                   3883:     $request->print(<<ENDPICK);
1.26      albertel 3884: </table>
                   3885: <input type="hidden" name="nfields" value="$i" />
                   3886: <input type="hidden" name="keyfields" value="$keyfields" />
1.589     bisitz   3887: <input type="button" onclick="javascript:verify(this.form)" value="Assign Grades" /><br />
1.26      albertel 3888: </form>
                   3889: ENDPICK
                   3890: }
                   3891: 
1.283     albertel 3892: sub checkforfile_js {
1.539     riegler  3893:     my $alertmsg = &mt('Please use the browse button to select a file from your local directory.');
1.597     wenzelju 3894:     my $result = &Apache::lonhtmlcommon::scripttag(<<CSVFORMJS);
1.86      ng       3895:     function checkUpload(formname) {
                   3896: 	if (formname.upfile.value == "") {
1.539     riegler  3897: 	    alert("$alertmsg");
1.86      ng       3898: 	    return false;
                   3899: 	}
                   3900: 	formname.submit();
                   3901:     }
                   3902: CSVFORMJS
1.283     albertel 3903:     return $result;
                   3904: }
                   3905: 
                   3906: sub upcsvScores_form {
1.608     www      3907:     my ($request,$symb) = @_;
1.283     albertel 3908:     if (!$symb) {return '';}
                   3909:     my $result=&checkforfile_js();
1.326     albertel 3910:     $result.='<br /><table width="100%" border="0"><tr><td bgcolor="#777777">'."\n";
                   3911:     $result.='<table width="100%" border="0"><tr bgcolor="#e6ffff"><td>'."\n";
1.538     schulted 3912:     $result.='&nbsp;<b>'.&mt('Specify a file containing the class scores for current resource.').
                   3913: 	'</b></td></tr>'."\n";
1.86      ng       3914:     $result.='<tr bgcolor=#ffffe6><td>'."\n";
1.370     www      3915:     my $upload=&mt("Upload Scores");
1.86      ng       3916:     my $upfile_select=&Apache::loncommon::upfile_select_html();
1.245     albertel 3917:     my $ignore=&mt('Ignore First Line');
1.418     albertel 3918:     $symb = &Apache::lonenc::check_encrypt($symb);
1.86      ng       3919:     $result.=<<ENDUPFORM;
1.106     albertel 3920: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
1.86      ng       3921: <input type="hidden" name="symb" value="$symb" />
                   3922: <input type="hidden" name="command" value="csvuploadmap" />
                   3923: $upfile_select
1.589     bisitz   3924: <br /><input type="button" onclick="javascript:checkUpload(this.form);" value="$upload" />
1.283     albertel 3925: <label><input type="checkbox" name="noFirstLine" />$ignore</label>
1.86      ng       3926: </form>
                   3927: ENDUPFORM
1.370     www      3928:     $result.=&Apache::loncommon::help_open_topic("Course_Convert_To_CSV",
                   3929:                            &mt("How do I create a CSV file from a spreadsheet"))
                   3930:     .'</td></tr></table>'."\n";
1.86      ng       3931:     $result.='</td></tr></table><br /><br />'."\n";
                   3932:     return $result;
                   3933: }
                   3934: 
                   3935: 
1.26      albertel 3936: sub csvuploadmap {
1.608     www      3937:     my ($request,$symb)= @_;
1.41      ng       3938:     if (!$symb) {return '';}
1.72      ng       3939: 
1.41      ng       3940:     my $datatoken;
1.257     albertel 3941:     if (!$env{'form.datatoken'}) {
1.41      ng       3942: 	$datatoken=&Apache::loncommon::upfile_store($request);
1.26      albertel 3943:     } else {
1.257     albertel 3944: 	$datatoken=$env{'form.datatoken'};
1.41      ng       3945: 	&Apache::loncommon::load_tmp_file($request);
1.26      albertel 3946:     }
1.41      ng       3947:     my @records=&Apache::loncommon::upfile_record_sep();
1.257     albertel 3948:     if ($env{'form.noFirstLine'}) { shift(@records); }
1.324     albertel 3949:     &csvuploadmap_header($request,$symb,$datatoken,$#records+1);
1.41      ng       3950:     my ($i,$keyfields);
                   3951:     if (@records) {
1.582     raeburn  3952:         my $fieldserror;
                   3953: 	my @fields=&csvupload_fields($symb,\$fieldserror);
                   3954:         if ($fieldserror) {
                   3955:             $request->print(&navmap_errormsg());
                   3956:             return;
                   3957:         }
1.257     albertel 3958: 	if ($env{'form.upfile_associate'} eq 'reverse') {	
1.41      ng       3959: 	    &Apache::loncommon::csv_print_samples($request,\@records);
                   3960: 	    $i=&Apache::loncommon::csv_print_select_table($request,\@records,
                   3961: 							  \@fields);
                   3962: 	    foreach (@fields) { $keyfields.=$_->[0].','; }
                   3963: 	    chop($keyfields);
                   3964: 	} else {
                   3965: 	    unshift(@fields,['none','']);
                   3966: 	    $i=&Apache::loncommon::csv_samples_select_table($request,\@records,
                   3967: 							    \@fields);
1.311     banghart 3968:             foreach my $rec (@records) {
                   3969:                 my %temp = &Apache::loncommon::record_sep($rec);
                   3970:                 if (%temp) {
                   3971:                     $keyfields=join(',',sort(keys(%temp)));
                   3972:                     last;
                   3973:                 }
                   3974:             }
1.41      ng       3975: 	}
                   3976:     }
                   3977:     &csvuploadmap_footer($request,$i,$keyfields);
1.72      ng       3978: 
1.41      ng       3979:     return '';
1.27      albertel 3980: }
                   3981: 
1.246     albertel 3982: sub csvuploadoptions {
1.608     www      3983:     my ($request,$symb)= @_;
1.257     albertel 3984:     my $checked=(($env{'form.noFirstLine'})?'1':'0');
1.246     albertel 3985:     my $ignore=&mt('Ignore First Line');
                   3986:     $request->print(<<ENDPICK);
                   3987: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
1.398     albertel 3988: <h3><span class="LC_info">Uploading Class Grade Options</span></h3>
1.246     albertel 3989: <input type="hidden" name="command"    value="csvuploadassign" />
1.302     albertel 3990: <!--
1.246     albertel 3991: <p>
                   3992: <label>
                   3993:    <input type="checkbox" name="show_full_results" />
                   3994:    Show a table of all changes
                   3995: </label>
                   3996: </p>
1.302     albertel 3997: -->
1.246     albertel 3998: <p>
                   3999: <label>
                   4000:    <input type="checkbox" name="overwite_scores" checked="checked" />
                   4001:    Overwrite any existing score
                   4002: </label>
                   4003: </p>
                   4004: ENDPICK
                   4005:     my %fields=&get_fields();
                   4006:     if (!defined($fields{'domain'})) {
1.257     albertel 4007: 	my $domform = &Apache::loncommon::select_dom_form($env{'request.role.domain'},'default_domain');
1.246     albertel 4008: 	$request->print("\n<p> Users are in domain: ".$domform."</p>\n");
                   4009:     }
1.257     albertel 4010:     foreach my $key (sort(keys(%env))) {
1.246     albertel 4011: 	if ($key !~ /^form\.(.*)$/) { next; }
                   4012: 	my $cleankey=$1;
                   4013: 	if ($cleankey eq 'command') { next; }
                   4014: 	$request->print('<input type="hidden" name="'.$cleankey.
1.257     albertel 4015: 			'"  value="'.$env{$key}.'" />'."\n");
1.246     albertel 4016:     }
                   4017:     # FIXME do a check for any duplicated user ids...
                   4018:     # FIXME do a check for any invalid user ids?...
1.290     albertel 4019:     $request->print('<input type="submit" value="Assign Grades" /><br />
                   4020: <hr /></form>'."\n");
1.246     albertel 4021:     return '';
                   4022: }
                   4023: 
                   4024: sub get_fields {
                   4025:     my %fields;
1.257     albertel 4026:     my @keyfields = split(/\,/,$env{'form.keyfields'});
                   4027:     for (my $i=0; $i<=$env{'form.nfields'}; $i++) {
                   4028: 	if ($env{'form.upfile_associate'} eq 'reverse') {
                   4029: 	    if ($env{'form.f'.$i} ne 'none') {
                   4030: 		$fields{$keyfields[$i]}=$env{'form.f'.$i};
1.41      ng       4031: 	    }
                   4032: 	} else {
1.257     albertel 4033: 	    if ($env{'form.f'.$i} ne 'none') {
                   4034: 		$fields{$env{'form.f'.$i}}=$keyfields[$i];
1.41      ng       4035: 	    }
                   4036: 	}
1.27      albertel 4037:     }
1.246     albertel 4038:     return %fields;
                   4039: }
                   4040: 
                   4041: sub csvuploadassign {
1.608     www      4042:     my ($request,$symb)= @_;
1.246     albertel 4043:     if (!$symb) {return '';}
1.345     bowersj2 4044:     my $error_msg = '';
1.246     albertel 4045:     &Apache::loncommon::load_tmp_file($request);
                   4046:     my @gradedata = &Apache::loncommon::upfile_record_sep();
1.257     albertel 4047:     if ($env{'form.noFirstLine'}) { shift(@gradedata); }
1.246     albertel 4048:     my %fields=&get_fields();
1.41      ng       4049:     $request->print('<h3>Assigning Grades</h3>');
1.257     albertel 4050:     my $courseid=$env{'request.course.id'};
1.97      albertel 4051:     my ($classlist) = &getclasslist('all',0);
1.106     albertel 4052:     my @notallowed;
1.41      ng       4053:     my @skipped;
                   4054:     my $countdone=0;
                   4055:     foreach my $grade (@gradedata) {
                   4056: 	my %entries=&Apache::loncommon::record_sep($grade);
1.246     albertel 4057: 	my $domain;
                   4058: 	if ($entries{$fields{'domain'}}) {
                   4059: 	    $domain=$entries{$fields{'domain'}};
                   4060: 	} else {
1.257     albertel 4061: 	    $domain=$env{'form.default_domain'};
1.246     albertel 4062: 	}
1.243     albertel 4063: 	$domain=~s/\s//g;
1.41      ng       4064: 	my $username=$entries{$fields{'username'}};
1.160     albertel 4065: 	$username=~s/\s//g;
1.243     albertel 4066: 	if (!$username) {
                   4067: 	    my $id=$entries{$fields{'ID'}};
1.247     albertel 4068: 	    $id=~s/\s//g;
1.243     albertel 4069: 	    my %ids=&Apache::lonnet::idget($domain,$id);
                   4070: 	    $username=$ids{$id};
                   4071: 	}
1.41      ng       4072: 	if (!exists($$classlist{"$username:$domain"})) {
1.247     albertel 4073: 	    my $id=$entries{$fields{'ID'}};
                   4074: 	    $id=~s/\s//g;
                   4075: 	    if ($id) {
                   4076: 		push(@skipped,"$id:$domain");
                   4077: 	    } else {
                   4078: 		push(@skipped,"$username:$domain");
                   4079: 	    }
1.41      ng       4080: 	    next;
                   4081: 	}
1.108     albertel 4082: 	my $usec=$classlist->{"$username:$domain"}[5];
1.106     albertel 4083: 	if (!&canmodify($usec)) {
                   4084: 	    push(@notallowed,"$username:$domain");
                   4085: 	    next;
                   4086: 	}
1.244     albertel 4087: 	my %points;
1.41      ng       4088: 	my %grades;
                   4089: 	foreach my $dest (keys(%fields)) {
1.244     albertel 4090: 	    if ($dest eq 'ID' || $dest eq 'username' ||
                   4091: 		$dest eq 'domain') { next; }
                   4092: 	    if ($entries{$fields{$dest}} =~ /^\s*$/) { next; }
                   4093: 	    if ($dest=~/stores_(.*)_points/) {
                   4094: 		my $part=$1;
                   4095: 		my $wgt =&Apache::lonnet::EXT('resource.'.$part.'.weight',
                   4096: 					      $symb,$domain,$username);
1.345     bowersj2 4097:                 if ($wgt) {
                   4098:                     $entries{$fields{$dest}}=~s/\s//g;
                   4099:                     my $pcr=$entries{$fields{$dest}} / $wgt;
1.463     albertel 4100:                     my $award=($pcr == 0) ? 'incorrect_by_override'
                   4101:                                           : 'correct_by_override';
1.345     bowersj2 4102:                     $grades{"resource.$part.awarded"}=$pcr;
                   4103:                     $grades{"resource.$part.solved"}=$award;
                   4104:                     $points{$part}=1;
                   4105:                 } else {
                   4106:                     $error_msg = "<br />" .
                   4107:                         &mt("Some point values were assigned"
                   4108:                             ." for problems with a weight "
                   4109:                             ."of zero. These values were "
                   4110:                             ."ignored.");
                   4111:                 }
1.244     albertel 4112: 	    } else {
                   4113: 		if ($dest=~/stores_(.*)_awarded/) { if ($points{$1}) {next;} }
                   4114: 		if ($dest=~/stores_(.*)_solved/)  { if ($points{$1}) {next;} }
                   4115: 		my $store_key=$dest;
                   4116: 		$store_key=~s/^stores/resource/;
                   4117: 		$store_key=~s/_/\./g;
                   4118: 		$grades{$store_key}=$entries{$fields{$dest}};
                   4119: 	    }
1.41      ng       4120: 	}
1.508     www      4121: 	if (! %grades) { 
                   4122:            push(@skipped,&mt("[_1]: no data to save","$username:$domain")); 
                   4123:         } else {
                   4124: 	   $grades{"resource.regrader"}="$env{'user.name'}:$env{'user.domain'}";
                   4125: 	   my $result=&Apache::lonnet::cstore(\%grades,$symb,
1.302     albertel 4126: 					   $env{'request.course.id'},
                   4127: 					   $domain,$username);
1.508     www      4128: 	   if ($result eq 'ok') {
                   4129: 	      $request->print('.');
                   4130: 	   } else {
                   4131: 	      $request->print("<p><span class=\"LC_error\">".
                   4132:                               &mt("Failed to save data for student [_1]. Message when trying to save was: [_2]",
                   4133:                                   "$username:$domain",$result)."</span></p>");
                   4134: 	   }
                   4135: 	   $request->rflush();
                   4136: 	   $countdone++;
                   4137:         }
1.41      ng       4138:     }
1.570     www      4139:     $request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt("Saved scores for [quant,_1,student]",$countdone),$countdone==0));
1.41      ng       4140:     if (@skipped) {
1.571     www      4141: 	$request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt('No scores stored for the following username(s):'),1).'<br />');
                   4142:         $request->print(join(', ',@skipped));
1.106     albertel 4143:     }
                   4144:     if (@notallowed) {
1.571     www      4145: 	$request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt('Modification of scores not allowed for the following username(s):'),1).'<br />');
                   4146: 	$request->print(join(', ',@notallowed));
1.41      ng       4147:     }
1.106     albertel 4148:     $request->print("<br />\n");
1.345     bowersj2 4149:     return $error_msg;
1.26      albertel 4150: }
1.44      ng       4151: #------------- end of section for handling csv file upload ---------
                   4152: #
                   4153: #-------------------------------------------------------------------
                   4154: #
1.122     ng       4155: #-------------- Next few routines handle grading by page/sequence
1.72      ng       4156: #
                   4157: #--- Select a page/sequence and a student to grade
1.68      ng       4158: sub pickStudentPage {
1.608     www      4159:     my ($request,$symb) = @_;
1.68      ng       4160: 
1.539     riegler  4161:     my $alertmsg = &mt('Please select the student you wish to grade.');
1.597     wenzelju 4162:     $request->print(&Apache::lonhtmlcommon::scripttag(<<LISTJAVASCRIPT));
1.68      ng       4163: 
                   4164: function checkPickOne(formname) {
1.76      ng       4165:     if (radioSelection(formname.student) == null) {
1.539     riegler  4166: 	alert("$alertmsg");
1.68      ng       4167: 	return;
                   4168:     }
1.125     ng       4169:     ptr = pullDownSelection(formname.selectpage);
                   4170:     formname.page.value = formname["page"+ptr].value;
                   4171:     formname.title.value = formname["title"+ptr].value;
1.68      ng       4172:     formname.submit();
                   4173: }
                   4174: 
                   4175: LISTJAVASCRIPT
1.118     ng       4176:     &commonJSfunctions($request);
1.608     www      4177: 
1.257     albertel 4178:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
                   4179:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
                   4180:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
1.68      ng       4181: 
1.398     albertel 4182:     my $result='<h3><span class="LC_info">&nbsp;'.
1.485     albertel 4183: 	&mt('Manual Grading by Page or Sequence').'</span></h3>';
1.68      ng       4184: 
1.80      ng       4185:     $result.='<form action="/adm/grades" method="post" name="displayPage">'."\n";
1.582     raeburn  4186:     my $map_error;
                   4187:     my ($titles,$symbx) = &getSymbMap($map_error);
                   4188:     if ($map_error) {
                   4189:         $request->print(&navmap_errormsg());
                   4190:         return; 
                   4191:     }
1.137     albertel 4192:     my ($curpage) =&Apache::lonnet::decode_symb($symb); 
                   4193: #    my ($curpage,$mapId) =&Apache::lonnet::decode_symb($symb); 
                   4194: #    my $type=($curpage =~ /\.(page|sequence)/);
1.485     albertel 4195:     my $select = '<select name="selectpage">'."\n";
1.70      ng       4196:     my $ctr=0;
1.68      ng       4197:     foreach (@$titles) {
                   4198: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
1.485     albertel 4199: 	$select.='<option value="'.$ctr.'" '.
1.401     albertel 4200: 	    ($$symbx{$_} =~ /$curpage$/ ? 'selected="selected"' : '').
1.71      ng       4201: 	    '>'.$showtitle.'</option>'."\n";
1.70      ng       4202: 	$ctr++;
1.68      ng       4203:     }
1.485     albertel 4204:     $select.= '</select>';
1.539     riegler  4205:     $result.='&nbsp;<b>'.&mt('Problems from').':</b> '.$select."<br />\n";
1.485     albertel 4206: 
1.70      ng       4207:     $ctr=0;
                   4208:     foreach (@$titles) {
                   4209: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
                   4210: 	$result.='<input type="hidden" name="page'.$ctr.'" value="'.$$symbx{$_}.'" />'."\n";
                   4211: 	$result.='<input type="hidden" name="title'.$ctr.'" value="'.$showtitle.'" />'."\n";
                   4212: 	$ctr++;
                   4213:     }
1.72      ng       4214:     $result.='<input type="hidden" name="page" />'."\n".
                   4215: 	'<input type="hidden" name="title" />'."\n";
1.68      ng       4216: 
1.485     albertel 4217:     my $options =
                   4218: 	'<label><input type="radio" name="vProb" value="no" checked="checked" /> '.&mt('no').' </label>'."\n".
                   4219: 	'<label><input type="radio" name="vProb" value="yes" /> '.&mt('yes').' </label>'."<br />\n";
1.539     riegler  4220:     $result.='&nbsp;<b>'.&mt('View Problem Text').': </b>'.$options;
1.485     albertel 4221: 
                   4222:     $options =
                   4223: 	'<label><input type="radio" name="lastSub" value="none" /> '.&mt('none').' </label>'."\n".
                   4224: 	'<label><input type="radio" name="lastSub" value="datesub" checked="checked" /> '.&mt('by dates and submissions').'</label>'."\n".
                   4225: 	'<label><input type="radio" name="lastSub" value="all" /> '.&mt('all details').' </label>'."\n";
1.539     riegler  4226:     $result.='&nbsp;<b>'.&mt('Submissions').': </b>'.$options;
1.432     banghart 4227:     
                   4228:     $result.=&build_section_inputs();
1.442     banghart 4229:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
                   4230:     $result.='<input type="hidden" name="Status"  value="'.$stu_status.'" />'."\n".
1.72      ng       4231: 	'<input type="hidden" name="command" value="displayPage" />'."\n".
1.613     www      4232: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."<br />\n";
1.72      ng       4233: 
1.539     riegler  4234:     $result.='&nbsp;<b>'.&mt('Use CODE').': </b> <input type="text" name="CODE" value="" /> <br />'."\n";
1.382     albertel 4235: 
1.80      ng       4236:     $result.='&nbsp;<input type="button" '.
1.589     bisitz   4237:              'onclick="javascript:checkPickOne(this.form);" value="'.&mt('Next').' &rarr;" /><br />'."\n";
1.72      ng       4238: 
1.68      ng       4239:     $request->print($result);
                   4240: 
1.485     albertel 4241:     my $studentTable.='&nbsp;<b>'.&mt('Select a student you wish to grade and then click on the Next button.').'</b><br />'.
1.484     albertel 4242: 	&Apache::loncommon::start_data_table().
                   4243: 	&Apache::loncommon::start_data_table_header_row().
1.485     albertel 4244: 	'<th align="right">&nbsp;'.&mt('No.').'</th>'.
1.484     albertel 4245: 	'<th>'.&nameUserString('header').'</th>'.
1.485     albertel 4246: 	'<th align="right">&nbsp;'.&mt('No.').'</th>'.
1.484     albertel 4247: 	'<th>'.&nameUserString('header').'</th>'.
                   4248: 	&Apache::loncommon::end_data_table_header_row();
1.68      ng       4249:  
1.76      ng       4250:     my (undef,undef,$fullname) = &getclasslist($getsec,'1');
1.68      ng       4251:     my $ptr = 1;
1.294     albertel 4252:     foreach my $student (sort 
                   4253: 			 {
                   4254: 			     if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                   4255: 				 return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                   4256: 			     }
                   4257: 			     return $a cmp $b;
                   4258: 			 } (keys(%$fullname))) {
1.68      ng       4259: 	my ($uname,$udom) = split(/:/,$student);
1.484     albertel 4260: 	$studentTable.=($ptr%2==1 ? &Apache::loncommon::start_data_table_row()
                   4261:                                   : '</td>');
1.126     ng       4262: 	$studentTable.='<td align="right">'.$ptr.'&nbsp;</td>';
1.288     albertel 4263: 	$studentTable.='<td>&nbsp;<label><input type="radio" name="student" value="'.$student.'" /> '
                   4264: 	    .&nameUserString(undef,$$fullname{$student},$uname,$udom)."</label>\n";
1.484     albertel 4265: 	$studentTable.=
                   4266: 	    ($ptr%2 == 0 ? '</td>'.&Apache::loncommon::end_data_table_row() 
                   4267:                          : '');
1.68      ng       4268: 	$ptr++;
                   4269:     }
1.484     albertel 4270:     if ($ptr%2 == 0) {
                   4271: 	$studentTable.='</td><td>&nbsp;</td><td>&nbsp;</td>'.
                   4272: 	    &Apache::loncommon::end_data_table_row();
                   4273:     }
                   4274:     $studentTable.=&Apache::loncommon::end_data_table()."\n";
1.126     ng       4275:     $studentTable.='<input type="button" '.
1.589     bisitz   4276:                    'onclick="javascript:checkPickOne(this.form);" value="'.&mt('Next').' &rarr;" /></form>'."\n";
1.68      ng       4277: 
                   4278:     $request->print($studentTable);
                   4279: 
                   4280:     return '';
                   4281: }
                   4282: 
                   4283: sub getSymbMap {
1.582     raeburn  4284:     my ($map_error) = @_;
1.132     bowersj2 4285:     my $navmap = Apache::lonnavmaps::navmap->new();
1.582     raeburn  4286:     unless (ref($navmap)) {
                   4287:         if (ref($map_error)) {
                   4288:             $$map_error = 'navmap';
                   4289:         }
                   4290:         return;
                   4291:     }
1.68      ng       4292:     my %symbx = ();
                   4293:     my @titles = ();
1.117     bowersj2 4294:     my $minder = 0;
                   4295: 
                   4296:     # Gather every sequence that has problems.
1.240     albertel 4297:     my @sequences = $navmap->retrieveResources(undef, sub { shift->is_map(); },
                   4298: 					       1,0,1);
1.117     bowersj2 4299:     for my $sequence ($navmap->getById('0.0'), @sequences) {
1.241     albertel 4300: 	if ($navmap->hasResource($sequence, sub { shift->is_problem(); }, 0) ) {
1.381     albertel 4301: 	    my $title = $minder.'.'.
                   4302: 		&HTML::Entities::encode($sequence->compTitle(),'"\'&');
                   4303: 	    push(@titles, $title); # minder in case two titles are identical
                   4304: 	    $symbx{$title} = &HTML::Entities::encode($sequence->symb(),'"\'&');
1.117     bowersj2 4305: 	    $minder++;
1.241     albertel 4306: 	}
1.68      ng       4307:     }
                   4308:     return \@titles,\%symbx;
                   4309: }
                   4310: 
1.72      ng       4311: #
                   4312: #--- Displays a page/sequence w/wo problems, w/wo submissions
1.68      ng       4313: sub displayPage {
1.608     www      4314:     my ($request,$symb) = @_;
1.257     albertel 4315:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
                   4316:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
                   4317:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
                   4318:     my $pageTitle = $env{'form.page'};
1.103     albertel 4319:     my ($classlist,undef,$fullname) = &getclasslist($getsec,'1');
1.257     albertel 4320:     my ($uname,$udom) = split(/:/,$env{'form.student'});
                   4321:     my $usec=$classlist->{$env{'form.student'}}[5];
1.168     albertel 4322: 
                   4323:     #need to make sure we have the correct data for later EXT calls, 
                   4324:     #thus invalidate the cache
                   4325:     &Apache::lonnet::devalidatecourseresdata(
1.257     albertel 4326:                  $env{'course.'.$env{'request.course.id'}.'.num'},
                   4327:                  $env{'course.'.$env{'request.course.id'}.'.domain'});
1.168     albertel 4328:     &Apache::lonnet::clear_EXT_cache_status();
                   4329: 
1.103     albertel 4330:     if (!&canview($usec)) {
1.485     albertel 4331: 	$request->print('<span class="LC_warning">'.&mt('Unable to view requested student. ([_1])',$env{'form.student'}).'</span>');
1.103     albertel 4332: 	return;
                   4333:     }
1.398     albertel 4334:     my $result='<h3><span class="LC_info">&nbsp;'.$env{'form.title'}.'</span></h3>';
1.485     albertel 4335:     $result.='<h3>&nbsp;'.&mt('Student: [_1]',&nameUserString(undef,$$fullname{$env{'form.student'}},$uname,$udom)).
1.129     ng       4336: 	'</h3>'."\n";
1.500     albertel 4337:     $env{'form.CODE'} = uc($env{'form.CODE'});
1.501     foxr     4338:     if (&Apache::lonnet::validCODE(uc($env{'form.CODE'}))) {
1.485     albertel 4339: 	$result.='<h3>&nbsp;'.&mt('CODE: [_1]',$env{'form.CODE'}).'</h3>'."\n";
1.382     albertel 4340:     } else {
                   4341: 	delete($env{'form.CODE'});
                   4342:     }
1.71      ng       4343:     &sub_page_js($request);
                   4344:     $request->print($result);
                   4345: 
1.132     bowersj2 4346:     my $navmap = Apache::lonnavmaps::navmap->new();
1.582     raeburn  4347:     unless (ref($navmap)) {
                   4348:         $request->print(&navmap_errormsg());
                   4349:         return;
                   4350:     }
1.257     albertel 4351:     my ($mapUrl, $id, $resUrl)=&Apache::lonnet::decode_symb($env{'form.page'});
1.68      ng       4352:     my $map = $navmap->getResourceByUrl($resUrl); # add to navmaps
1.288     albertel 4353:     if (!$map) {
1.485     albertel 4354: 	$request->print('<span class="LC_warning">'.&mt('Unable to view requested sequence. ([_1])',$resUrl).'</span>');
1.288     albertel 4355: 	return; 
                   4356:     }
1.68      ng       4357:     my $iterator = $navmap->getIterator($map->map_start(),
                   4358: 					$map->map_finish());
                   4359: 
1.71      ng       4360:     my $studentTable='<form action="/adm/grades" method="post" name="gradePage">'."\n".
1.72      ng       4361: 	'<input type="hidden" name="command" value="gradeByPage" />'."\n".
1.257     albertel 4362: 	'<input type="hidden" name="fullname" value="'.$$fullname{$env{'form.student'}}.'" />'."\n".
                   4363: 	'<input type="hidden" name="student" value="'.$env{'form.student'}.'" />'."\n".
1.72      ng       4364: 	'<input type="hidden" name="page"    value="'.$pageTitle.'" />'."\n".
1.257     albertel 4365: 	'<input type="hidden" name="title"   value="'.$env{'form.title'}.'" />'."\n".
1.418     albertel 4366: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.613     www      4367: 	'<input type="hidden" name="overRideScore" value="no" />'."\n";
1.71      ng       4368: 
1.382     albertel 4369:     if (defined($env{'form.CODE'})) {
                   4370: 	$studentTable.=
                   4371: 	    '<input type="hidden" name="CODE" value="'.$env{'form.CODE'}.'" />'."\n";
                   4372:     }
1.381     albertel 4373:     my $checkIcon = '<img alt="'.&mt('Check Mark').
1.485     albertel 4374: 	'" src="'.&Apache::loncommon::lonhttpdurl($request->dir_config('lonIconsURL').'/check.gif').'" height="16" border="0" />';
1.71      ng       4375: 
1.594     bisitz   4376:     $studentTable.='&nbsp;<span class="LC_info">'.
                   4377:         &mt('Problems graded correct by the computer are marked with a [_1] symbol.',$checkIcon).
                   4378:         '</span>'."\n".
1.484     albertel 4379: 	&Apache::loncommon::start_data_table().
                   4380: 	&Apache::loncommon::start_data_table_header_row().
                   4381: 	'<th align="center">&nbsp;Prob.&nbsp;</th>'.
1.485     albertel 4382: 	'<th>&nbsp;'.($env{'form.vProb'} eq 'no' ? &mt('Title') : &mt('Problem Text')).'/'.&mt('Grade').'</th>'.
1.484     albertel 4383: 	&Apache::loncommon::end_data_table_header_row();
1.71      ng       4384: 
1.329     albertel 4385:     &Apache::lonxml::clear_problem_counter();
1.196     albertel 4386:     my ($depth,$question,$prob) = (1,1,1);
1.68      ng       4387:     $iterator->next(); # skip the first BEGIN_MAP
                   4388:     my $curRes = $iterator->next(); # for "current resource"
1.101     albertel 4389:     while ($depth > 0) {
1.68      ng       4390:         if($curRes == $iterator->BEGIN_MAP) { $depth++; }
1.100     bowersj2 4391:         if($curRes == $iterator->END_MAP) { $depth--; }
1.68      ng       4392: 
1.385     albertel 4393:         if (ref($curRes) && $curRes->is_problem()) {
1.91      albertel 4394: 	    my $parts = $curRes->parts();
1.68      ng       4395:             my $title = $curRes->compTitle();
1.71      ng       4396: 	    my $symbx = $curRes->symb();
1.484     albertel 4397: 	    $studentTable.=
                   4398: 		&Apache::loncommon::start_data_table_row().
                   4399: 		'<td align="center" valign="top" >'.$prob.
1.485     albertel 4400: 		(scalar(@{$parts}) == 1 ? '' 
                   4401: 		                        : '<br />('.&mt('[_1]&nbsp;parts)',
                   4402: 							scalar(@{$parts}))
                   4403: 		 ).
                   4404: 		 '</td>';
1.71      ng       4405: 	    $studentTable.='<td valign="top">';
1.382     albertel 4406: 	    my %form = ('CODE' => $env{'form.CODE'},);
1.257     albertel 4407: 	    if ($env{'form.vProb'} eq 'yes' ) {
1.144     albertel 4408: 		$studentTable.=&show_problem($request,$symbx,$uname,$udom,1,
1.383     albertel 4409: 					     undef,'both',\%form);
1.71      ng       4410: 	    } else {
1.382     albertel 4411: 		my $companswer = &Apache::loncommon::get_student_answers($symbx,$uname,$udom,$env{'request.course.id'},%form);
1.80      ng       4412: 		$companswer =~ s|<form(.*?)>||g;
                   4413: 		$companswer =~ s|</form>||g;
1.71      ng       4414: #		while ($companswer =~ /(<a href\=\"javascript:newWindow.*?Script Vars<\/a>)/s) { #<a href="javascript:newWindow</a>
1.116     ng       4415: #		    $companswer =~ s/$1/ /ms;
1.326     albertel 4416: #		    $request->print('match='.$1."<br />\n");
1.71      ng       4417: #		}
1.116     ng       4418: #		$companswer =~ s|<table border=\"1\">|<table border=\"0\">|g;
1.539     riegler  4419: 		$studentTable.='&nbsp;<b>'.$title.'</b>&nbsp;<br />&nbsp;<b>'.&mt('Correct answer').':</b><br />'.$companswer;
1.71      ng       4420: 	    }
                   4421: 
1.257     albertel 4422: 	    my %record = &Apache::lonnet::restore($symbx,$env{'request.course.id'},$udom,$uname);
1.125     ng       4423: 
1.257     albertel 4424: 	    if ($env{'form.lastSub'} eq 'datesub') {
1.71      ng       4425: 		if ($record{'version'} eq '') {
1.485     albertel 4426: 		    $studentTable.='<br />&nbsp;<span class="LC_warning">'.&mt('No recorded submission for this problem.').'</span><br />';
1.71      ng       4427: 		} else {
1.116     ng       4428: 		    my %responseType = ();
                   4429: 		    foreach my $partid (@{$parts}) {
1.147     albertel 4430: 			my @responseIds =$curRes->responseIds($partid);
                   4431: 			my @responseType =$curRes->responseType($partid);
                   4432: 			my %responseIds;
                   4433: 			for (my $i=0;$i<=$#responseIds;$i++) {
                   4434: 			    $responseIds{$responseIds[$i]}=$responseType[$i];
                   4435: 			}
                   4436: 			$responseType{$partid} = \%responseIds;
1.116     ng       4437: 		    }
1.148     albertel 4438: 		    $studentTable.= &displaySubByDates($symbx,\%record,$parts,\%responseType,$checkIcon,$uname,$udom);
1.147     albertel 4439: 
1.71      ng       4440: 		}
1.257     albertel 4441: 	    } elsif ($env{'form.lastSub'} eq 'all') {
                   4442: 		my $last = ($env{'form.lastSub'} eq 'last' ? 'last' : '');
1.71      ng       4443: 		$studentTable.=&Apache::loncommon::get_previous_attempt($symbx,$uname,$udom,
1.257     albertel 4444: 									$env{'request.course.id'},
1.71      ng       4445: 									'','.submission');
                   4446:  
                   4447: 	    }
1.103     albertel 4448: 	    if (&canmodify($usec)) {
1.585     bisitz   4449:             $studentTable.=&gradeBox_start();
1.103     albertel 4450: 		foreach my $partid (@{$parts}) {
                   4451: 		    $studentTable.=&gradeBox($request,$symbx,$uname,$udom,$question,$partid,\%record);
                   4452: 		    $studentTable.='<input type="hidden" name="q_'.$question.'" value="'.$partid.'" />'."\n";
                   4453: 		    $question++;
                   4454: 		}
1.585     bisitz   4455:             $studentTable.=&gradeBox_end();
1.196     albertel 4456: 		$prob++;
1.71      ng       4457: 	    }
                   4458: 	    $studentTable.='</td></tr>';
1.68      ng       4459: 
1.103     albertel 4460: 	}
1.68      ng       4461:         $curRes = $iterator->next();
                   4462:     }
                   4463: 
1.589     bisitz   4464:     $studentTable.=
                   4465:         '</table>'."\n".
                   4466:         '<input type="button" value="'.&mt('Save').'" '.
                   4467:         'onclick="javascript:checkSubmitPage(this.form,'.$question.');" />'.
                   4468:         '</form>'."\n";
1.71      ng       4469:     $request->print($studentTable);
                   4470: 
                   4471:     return '';
1.119     ng       4472: }
                   4473: 
                   4474: sub displaySubByDates {
1.148     albertel 4475:     my ($symb,$record,$parts,$responseType,$checkIcon,$uname,$udom) = @_;
1.224     albertel 4476:     my $isCODE=0;
1.335     albertel 4477:     my $isTask = ($symb =~/\.task$/);
1.224     albertel 4478:     if (exists($record->{'resource.CODE'})) { $isCODE=1; }
1.467     albertel 4479:     my $studentTable=&Apache::loncommon::start_data_table().
                   4480: 	&Apache::loncommon::start_data_table_header_row().
                   4481: 	'<th>'.&mt('Date/Time').'</th>'.
                   4482: 	($isCODE?'<th>'.&mt('CODE').'</th>':'').
                   4483: 	'<th>'.&mt('Submission').'</th>'.
                   4484: 	'<th>'.&mt('Status').'</th>'.
                   4485: 	&Apache::loncommon::end_data_table_header_row();
1.119     ng       4486:     my ($version);
                   4487:     my %mark;
1.148     albertel 4488:     my %orders;
1.119     ng       4489:     $mark{'correct_by_student'} = $checkIcon;
1.147     albertel 4490:     if (!exists($$record{'1:timestamp'})) {
1.539     riegler  4491: 	return '<br />&nbsp;<span class="LC_warning">'.&mt('Nothing submitted - no attempts.').'</span><br />';
1.147     albertel 4492:     }
1.335     albertel 4493: 
                   4494:     my $interaction;
1.525     raeburn  4495:     my $no_increment = 1;
1.119     ng       4496:     for ($version=1;$version<=$$record{'version'};$version++) {
1.467     albertel 4497: 	my $timestamp = 
                   4498: 	    &Apache::lonlocal::locallocaltime($$record{$version.':timestamp'});
1.335     albertel 4499: 	if (exists($$record{$version.':resource.0.version'})) {
                   4500: 	    $interaction = $$record{$version.':resource.0.version'};
                   4501: 	}
                   4502: 
                   4503: 	my $where = ($isTask ? "$version:resource.$interaction"
                   4504: 		             : "$version:resource");
1.467     albertel 4505: 	$studentTable.=&Apache::loncommon::start_data_table_row().
                   4506: 	    '<td>'.$timestamp.'</td>';
1.224     albertel 4507: 	if ($isCODE) {
                   4508: 	    $studentTable.='<td>'.$record->{$version.':resource.CODE'}.'</td>';
                   4509: 	}
1.119     ng       4510: 	my @versionKeys = split(/\:/,$$record{$version.':keys'});
                   4511: 	my @displaySub = ();
                   4512: 	foreach my $partid (@{$parts}) {
1.596     raeburn  4513:             my $hidden;
                   4514:             if (($$record{$version.':resource.'.$partid.'.type'} eq 'anonsurvey') ||
                   4515:                 ($$record{$version.':resource.'.$partid.'.type'} eq 'anonsurveycred')) {
                   4516:                 $hidden = 1;
                   4517:             }
1.335     albertel 4518: 	    my @matchKey = ($isTask ? sort(grep /^resource\.\d+\.\Q$partid\E\.award$/,@versionKeys)
                   4519: 			            : sort(grep /^resource\.\Q$partid\E\..*?\.submission$/,@versionKeys));
                   4520: 	    
1.122     ng       4521: #	    next if ($$record{"$version:resource.$partid.solved"} eq '');
1.324     albertel 4522: 	    my $display_part=&get_display_part($partid,$symb);
1.147     albertel 4523: 	    foreach my $matchKey (@matchKey) {
1.198     albertel 4524: 		if (exists($$record{$version.':'.$matchKey}) &&
                   4525: 		    $$record{$version.':'.$matchKey} ne '') {
1.596     raeburn  4526:                     
1.335     albertel 4527: 		    my ($responseId)= ($isTask ? ($matchKey=~ /^resource\.(.*?)\.\Q$partid\E\.award$/)
                   4528: 				               : ($matchKey=~ /^resource\.\Q$partid\E\.(.*?)\.submission$/));
1.577     bisitz   4529:                     $displaySub[0].='<span class="LC_nobreak"';
                   4530:                     $displaySub[0].='<b>'.&mt('Part: [_1]',$display_part).'</b>'
                   4531:                                    .' <span class="LC_internal_info">'
                   4532:                                    .'('.&mt('Part ID: [_1]',$responseId).')'
                   4533:                                    .'</span>'
                   4534:                                    .' <b>';
1.596     raeburn  4535:                     if ($hidden) {
                   4536:                         $displaySub[0].= &mt('Anonymous Survey').'</b>';
                   4537:                     } else {
                   4538: 		        if ($$record{"$where.$partid.tries"} eq '') {
                   4539: 			    $displaySub[0].=&mt('Trial not counted');
                   4540: 		        } else {
                   4541: 			    $displaySub[0].=&mt('Trial: [_1]',
1.467     albertel 4542: 					    $$record{"$where.$partid.tries"});
1.596     raeburn  4543: 		        }
                   4544: 		        my $responseType=($isTask ? 'Task'
1.335     albertel 4545:                                               : $responseType->{$partid}->{$responseId});
1.596     raeburn  4546: 		        if (!exists($orders{$partid})) { $orders{$partid}={}; }
                   4547: 		        if (!exists($orders{$partid}->{$responseId})) {
                   4548: 			    $orders{$partid}->{$responseId}=
                   4549: 			        &get_order($partid,$responseId,$symb,$uname,$udom,
                   4550:                                            $no_increment);
                   4551: 		        }
                   4552: 		        $displaySub[0].='</b></span>'; # /nobreak
                   4553: 		        $displaySub[0].='&nbsp; '.
                   4554: 			    &cleanRecord($$record{$version.':'.$matchKey},$responseType,$symb,$partid,$responseId,$record,$orders{$partid}->{$responseId},"$version:",$uname,$udom).'<br />';
                   4555:                     }
1.147     albertel 4556: 		}
                   4557: 	    }
1.335     albertel 4558: 	    if (exists($$record{"$where.$partid.checkedin"})) {
1.485     albertel 4559: 		$displaySub[1].=&mt('Checked in by [_1] into slot [_2]',
                   4560: 				    $$record{"$where.$partid.checkedin"},
                   4561: 				    $$record{"$where.$partid.checkedin.slot"}).
                   4562: 					'<br />';
1.335     albertel 4563: 	    }
                   4564: 	    if (exists $$record{"$where.$partid.award"}) {
1.485     albertel 4565: 		$displaySub[1].='<b>'.&mt('Part:').'</b>&nbsp;'.$display_part.' &nbsp;'.
1.335     albertel 4566: 		    lc($$record{"$where.$partid.award"}).' '.
                   4567: 		    $mark{$$record{"$where.$partid.solved"}}.
1.147     albertel 4568: 		    '<br />';
                   4569: 	    }
1.335     albertel 4570: 	    if (exists $$record{"$where.$partid.regrader"}) {
                   4571: 		$displaySub[2].=$$record{"$where.$partid.regrader"}.
                   4572: 		    ' (<b>'.&mt('Part').':</b> '.$display_part.')';
                   4573: 	    } elsif ($$record{"$version:resource.$partid.regrader"} =~ /\S/) {
                   4574: 		$displaySub[2].=
                   4575: 		    $$record{"$version:resource.$partid.regrader"}.
1.207     albertel 4576: 		    ' (<b>'.&mt('Part').':</b> '.$display_part.')';
1.147     albertel 4577: 	    }
                   4578: 	}
                   4579: 	# needed because old essay regrader has not parts info
                   4580: 	if (exists $$record{"$version:resource.regrader"}) {
                   4581: 	    $displaySub[2].=$$record{"$version:resource.regrader"};
                   4582: 	}
                   4583: 	$studentTable.='<td>'.$displaySub[0].'&nbsp;</td><td>'.$displaySub[1];
                   4584: 	if ($displaySub[2]) {
1.467     albertel 4585: 	    $studentTable.=&mt('Manually graded by [_1]',$displaySub[2]);
1.147     albertel 4586: 	}
1.467     albertel 4587: 	$studentTable.='&nbsp;</td>'.
                   4588: 	    &Apache::loncommon::end_data_table_row();
1.119     ng       4589:     }
1.467     albertel 4590:     $studentTable.=&Apache::loncommon::end_data_table();
1.119     ng       4591:     return $studentTable;
1.71      ng       4592: }
                   4593: 
                   4594: sub updateGradeByPage {
1.608     www      4595:     my ($request,$symb) = @_;
1.71      ng       4596: 
1.257     albertel 4597:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
                   4598:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
                   4599:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
                   4600:     my $pageTitle = $env{'form.page'};
1.103     albertel 4601:     my ($classlist,undef,$fullname) = &getclasslist($getsec,'1');
1.257     albertel 4602:     my ($uname,$udom) = split(/:/,$env{'form.student'});
                   4603:     my $usec=$classlist->{$env{'form.student'}}[5];
1.103     albertel 4604:     if (!&canmodify($usec)) {
1.526     raeburn  4605: 	$request->print('<span class="LC_warning">'.&mt('Unable to modify requested student ([_1])',$env{'form.student'}).'</span>');
1.103     albertel 4606: 	return;
                   4607:     }
1.398     albertel 4608:     my $result='<h3><span class="LC_info">&nbsp;'.$env{'form.title'}.'</span></h3>';
1.526     raeburn  4609:     $result.='<h3>&nbsp;'.&mt('Student: ').&nameUserString(undef,$env{'form.fullname'},$uname,$udom).
1.129     ng       4610: 	'</h3>'."\n";
1.70      ng       4611: 
1.68      ng       4612:     $request->print($result);
                   4613: 
1.582     raeburn  4614: 
1.132     bowersj2 4615:     my $navmap = Apache::lonnavmaps::navmap->new();
1.582     raeburn  4616:     unless (ref($navmap)) {
                   4617:         $request->print(&navmap_errormsg());
                   4618:         return;
                   4619:     }
1.257     albertel 4620:     my ($mapUrl, $id, $resUrl) = &Apache::lonnet::decode_symb( $env{'form.page'});
1.71      ng       4621:     my $map = $navmap->getResourceByUrl($resUrl); # add to navmaps
1.288     albertel 4622:     if (!$map) {
1.527     raeburn  4623: 	$request->print('<span class="LC_warning">'.&mt('Unable to grade requested sequence ([_1]).',$resUrl).'</span>');
1.288     albertel 4624: 	return; 
                   4625:     }
1.71      ng       4626:     my $iterator = $navmap->getIterator($map->map_start(),
                   4627: 					$map->map_finish());
1.70      ng       4628: 
1.484     albertel 4629:     my $studentTable=
                   4630: 	&Apache::loncommon::start_data_table().
                   4631: 	&Apache::loncommon::start_data_table_header_row().
1.485     albertel 4632: 	'<th align="center">&nbsp;'.&mt('Prob.').'&nbsp;</th>'.
                   4633: 	'<th>&nbsp;'.&mt('Title').'&nbsp;</th>'.
                   4634: 	'<th>&nbsp;'.&mt('Previous Score').'&nbsp;</th>'.
                   4635: 	'<th>&nbsp;'.&mt('New Score').'&nbsp;</th>'.
1.484     albertel 4636: 	&Apache::loncommon::end_data_table_header_row();
1.71      ng       4637: 
                   4638:     $iterator->next(); # skip the first BEGIN_MAP
                   4639:     my $curRes = $iterator->next(); # for "current resource"
1.196     albertel 4640:     my ($depth,$question,$prob,$changeflag)= (1,1,1,0);
1.101     albertel 4641:     while ($depth > 0) {
1.71      ng       4642:         if($curRes == $iterator->BEGIN_MAP) { $depth++; }
1.100     bowersj2 4643:         if($curRes == $iterator->END_MAP) { $depth--; }
1.71      ng       4644: 
1.385     albertel 4645:         if (ref($curRes) && $curRes->is_problem()) {
1.91      albertel 4646: 	    my $parts = $curRes->parts();
1.71      ng       4647:             my $title = $curRes->compTitle();
                   4648: 	    my $symbx = $curRes->symb();
1.484     albertel 4649: 	    $studentTable.=
                   4650: 		&Apache::loncommon::start_data_table_row().
                   4651: 		'<td align="center" valign="top" >'.$prob.
1.485     albertel 4652: 		(scalar(@{$parts}) == 1 ? '' 
1.526     raeburn  4653:                                         : '<br />('.&mt('[quant,_1,&nbsp;part]',scalar(@{$parts}))
                   4654: 		.')').'</td>';
1.71      ng       4655: 	    $studentTable.='<td valign="top">&nbsp;<b>'.$title.'</b>&nbsp;</td>';
                   4656: 
                   4657: 	    my %newrecord=();
                   4658: 	    my @displayPts=();
1.269     raeburn  4659:             my %aggregate = ();
                   4660:             my $aggregateflag = 0;
1.71      ng       4661: 	    foreach my $partid (@{$parts}) {
1.257     albertel 4662: 		my $newpts = $env{'form.GD_BOX'.$question.'_'.$partid};
                   4663: 		my $oldpts = $env{'form.oldpts'.$question.'_'.$partid};
1.71      ng       4664: 
1.257     albertel 4665: 		my $wgt = $env{'form.WGT'.$question.'_'.$partid} != 0 ? 
                   4666: 		    $env{'form.WGT'.$question.'_'.$partid} : 1;
1.71      ng       4667: 		my $partial = $newpts/$wgt;
                   4668: 		my $score;
                   4669: 		if ($partial > 0) {
                   4670: 		    $score = 'correct_by_override';
1.125     ng       4671: 		} elsif ($newpts ne '') { #empty is taken as 0
1.71      ng       4672: 		    $score = 'incorrect_by_override';
                   4673: 		}
1.257     albertel 4674: 		my $dropMenu = $env{'form.GD_SEL'.$question.'_'.$partid};
1.125     ng       4675: 		if ($dropMenu eq 'excused') {
1.71      ng       4676: 		    $partial = '';
                   4677: 		    $score = 'excused';
1.125     ng       4678: 		} elsif ($dropMenu eq 'reset status'
1.257     albertel 4679: 			 && $env{'form.solved'.$question.'_'.$partid} ne '') { #update only if previous record exists
1.125     ng       4680: 		    $newrecord{'resource.'.$partid.'.tries'} = 0;
                   4681: 		    $newrecord{'resource.'.$partid.'.solved'} = '';
                   4682: 		    $newrecord{'resource.'.$partid.'.award'} = '';
                   4683: 		    $newrecord{'resource.'.$partid.'.awarded'} = 0;
1.257     albertel 4684: 		    $newrecord{'resource.'.$partid.'.regrader'} = "$env{'user.name'}:$env{'user.domain'}";
1.125     ng       4685: 		    $changeflag++;
                   4686: 		    $newpts = '';
1.269     raeburn  4687:                     
                   4688:                     my $aggtries =  $env{'form.aggtries'.$question.'_'.$partid};
                   4689:                     my $totaltries = $env{'form.totaltries'.$question.'_'.$partid};
                   4690:                     my $solvedstatus = $env{'form.solved'.$question.'_'.$partid};
                   4691:                     if ($aggtries > 0) {
                   4692:                         &decrement_aggs($symbx,$partid,\%aggregate,$aggtries,$totaltries,$solvedstatus);
                   4693:                         $aggregateflag = 1;
                   4694:                     }
1.71      ng       4695: 		}
1.324     albertel 4696: 		my $display_part=&get_display_part($partid,$curRes->symb());
1.257     albertel 4697: 		my $oldstatus = $env{'form.solved'.$question.'_'.$partid};
1.526     raeburn  4698: 		$displayPts[0].='&nbsp;<b>'.&mt('Part').':</b> '.$display_part.' = '.
1.71      ng       4699: 		    (($oldstatus eq 'excused') ? 'excused' : $oldpts).
1.326     albertel 4700: 		    '&nbsp;<br />';
1.526     raeburn  4701: 		$displayPts[1].='&nbsp;<b>'.&mt('Part').':</b> '.$display_part.' = '.
1.125     ng       4702: 		     (($score eq 'excused') ? 'excused' : $newpts).
1.326     albertel 4703: 		    '&nbsp;<br />';
1.71      ng       4704: 		$question++;
1.380     albertel 4705: 		next if ($dropMenu eq 'reset status' || ($newpts eq $oldpts && $score ne 'excused'));
1.125     ng       4706: 
1.71      ng       4707: 		$newrecord{'resource.'.$partid.'.awarded'}  = $partial if $partial ne '';
1.125     ng       4708: 		$newrecord{'resource.'.$partid.'.solved'}   = $score if $score ne '';
1.257     albertel 4709: 		$newrecord{'resource.'.$partid.'.regrader'} = "$env{'user.name'}:$env{'user.domain'}"
1.125     ng       4710: 		    if (scalar(keys(%newrecord)) > 0);
1.71      ng       4711: 
                   4712: 		$changeflag++;
                   4713: 	    }
                   4714: 	    if (scalar(keys(%newrecord)) > 0) {
1.382     albertel 4715: 		my %record = 
                   4716: 		    &Apache::lonnet::restore($symbx,$env{'request.course.id'},
                   4717: 					     $udom,$uname);
                   4718: 
                   4719: 		if (&Apache::lonnet::validCODE($env{'form.CODE'})) {
                   4720: 		    $newrecord{'resource.CODE'} = $env{'form.CODE'};
                   4721: 		} elsif (&Apache::lonnet::validCODE($record{'resource.CODE'})) {
                   4722: 		    $newrecord{'resource.CODE'} = '';
                   4723: 		}
1.257     albertel 4724: 		&Apache::lonnet::cstore(\%newrecord,$symbx,$env{'request.course.id'},
1.71      ng       4725: 					$udom,$uname);
1.382     albertel 4726: 		%record = &Apache::lonnet::restore($symbx,
                   4727: 						   $env{'request.course.id'},
                   4728: 						   $udom,$uname);
1.380     albertel 4729: 		&check_and_remove_from_queue($parts,\%record,undef,$symbx,
                   4730: 					     $cdom,$cnum,$udom,$uname);
1.71      ng       4731: 	    }
1.380     albertel 4732: 	    
1.269     raeburn  4733:             if ($aggregateflag) {
                   4734:                 &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
                   4735:                       $env{'course.'.$env{'request.course.id'}.'.domain'},
                   4736:                       $env{'course.'.$env{'request.course.id'}.'.num'});
                   4737:             }
1.125     ng       4738: 
1.71      ng       4739: 	    $studentTable.='<td valign="top">'.$displayPts[0].'</td>'.
                   4740: 		'<td valign="top">'.$displayPts[1].'</td>'.
1.484     albertel 4741: 		&Apache::loncommon::end_data_table_row();
1.68      ng       4742: 
1.196     albertel 4743: 	    $prob++;
1.68      ng       4744: 	}
1.71      ng       4745:         $curRes = $iterator->next();
1.68      ng       4746:     }
1.98      albertel 4747: 
1.484     albertel 4748:     $studentTable.=&Apache::loncommon::end_data_table();
1.526     raeburn  4749:     my $grademsg=($changeflag == 0 ? &mt('No score was changed or updated.') :
                   4750: 		  &mt('The scores were changed for [quant,_1,problem].',
                   4751: 		  $changeflag));
1.76      ng       4752:     $request->print($grademsg.$studentTable);
1.68      ng       4753: 
1.70      ng       4754:     return '';
                   4755: }
                   4756: 
1.72      ng       4757: #-------- end of section for handling grading by page/sequence ---------
                   4758: #
                   4759: #-------------------------------------------------------------------
                   4760: 
1.581     www      4761: #-------------------- Bubblesheet (Scantron) Grading -------------------
1.75      albertel 4762: #
                   4763: #------ start of section for handling grading by page/sequence ---------
                   4764: 
1.423     albertel 4765: =pod
                   4766: 
                   4767: =head1 Bubble sheet grading routines
                   4768: 
1.424     albertel 4769:   For this documentation:
                   4770: 
                   4771:    'scanline' refers to the full line of characters
                   4772:    from the file that we are parsing that represents one entire sheet
                   4773: 
                   4774:    'bubble line' refers to the data
                   4775:    representing the line of bubbles that are on the physical bubble sheet
                   4776: 
                   4777: 
                   4778: The overall process is that a scanned in bubble sheet data is uploaded
                   4779: into a course. When a user wants to grade, they select a
                   4780: sequence/folder of resources, a file of bubble sheet info, and pick
                   4781: one of the predefined configurations for what each scanline looks
                   4782: like.
                   4783: 
                   4784: Next each scanline is checked for any errors of either 'missing
1.435     foxr     4785: bubbles' (it's an error because it may have been mis-scanned
1.424     albertel 4786: because too light bubbling), 'double bubble' (each bubble line should
                   4787: have no more that one letter picked), invalid or duplicated CODE,
1.556     weissno  4788: invalid student/employee ID
1.424     albertel 4789: 
                   4790: If the CODE option is used that determines the randomization of the
1.556     weissno  4791: homework problems, either way the student/employee ID is looked up into a
1.424     albertel 4792: username:domain.
                   4793: 
                   4794: During the validation phase the instructor can choose to skip scanlines. 
                   4795: 
1.435     foxr     4796: After the validation phase, there are now 3 bubble sheet files
1.424     albertel 4797: 
                   4798:   scantron_original_filename (unmodified original file)
                   4799:   scantron_corrected_filename (file where the corrected information has replaced the original information)
                   4800:   scantron_skipped_filename (contains the exact text of scanlines that where skipped)
                   4801: 
                   4802: Also there is a separate hash nohist_scantrondata that contains extra
                   4803: correction information that isn't representable in the bubble sheet
                   4804: file (see &scantron_getfile() for more information)
                   4805: 
                   4806: After all scanlines are either valid, marked as valid or skipped, then
                   4807: foreach line foreach problem in the picked sequence, an ssi request is
                   4808: made that simulates a user submitting their selected letter(s) against
                   4809: the homework problem.
1.423     albertel 4810: 
                   4811: =over 4
                   4812: 
                   4813: 
                   4814: 
                   4815: =item defaultFormData
                   4816: 
                   4817:   Returns html hidden inputs used to hold context/default values.
                   4818: 
                   4819:  Arguments:
                   4820:   $symb - $symb of the current resource 
                   4821: 
                   4822: =cut
1.422     foxr     4823: 
1.81      albertel 4824: sub defaultFormData {
1.324     albertel 4825:     my ($symb)=@_;
1.613     www      4826:     return '<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />';
1.81      albertel 4827: }
                   4828: 
1.447     foxr     4829: 
1.423     albertel 4830: =pod 
                   4831: 
                   4832: =item getSequenceDropDown
                   4833: 
                   4834:    Return html dropdown of possible sequences to grade
                   4835:  
                   4836:  Arguments:
1.582     raeburn  4837:    $symb - $symb of the current resource
                   4838:    $map_error - ref to scalar which will container error if
                   4839:                 $navmap object is unavailable in &getSymbMap().
1.423     albertel 4840: 
                   4841: =cut
1.422     foxr     4842: 
1.75      albertel 4843: sub getSequenceDropDown {
1.582     raeburn  4844:     my ($symb,$map_error)=@_;
1.75      albertel 4845:     my $result='<select name="selectpage">'."\n";
1.582     raeburn  4846:     my ($titles,$symbx) = &getSymbMap($map_error);
                   4847:     if (ref($map_error)) {
                   4848:         return if ($$map_error);
                   4849:     }
1.137     albertel 4850:     my ($curpage)=&Apache::lonnet::decode_symb($symb); 
1.75      albertel 4851:     my $ctr=0;
                   4852:     foreach (@$titles) {
                   4853: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
                   4854: 	$result.='<option value="'.$$symbx{$_}.'" '.
1.401     albertel 4855: 	    ($$symbx{$_} =~ /$curpage$/ ? 'selected="selected"' : '').
1.75      albertel 4856: 	    '>'.$showtitle.'</option>'."\n";
                   4857: 	$ctr++;
                   4858:     }
                   4859:     $result.= '</select>';
                   4860:     return $result;
                   4861: }
                   4862: 
1.495     albertel 4863: my %bubble_lines_per_response;     # no. bubble lines for each response.
1.554     raeburn  4864:                                    # key is zero-based index - 0, 1, 2 ...
1.495     albertel 4865: 
                   4866: my %first_bubble_line;             # First bubble line no. for each bubble.
                   4867: 
1.509     raeburn  4868: my %subdivided_bubble_lines;       # no. bubble lines for optionresponse, 
                   4869:                                    # matchresponse or rankresponse, where 
                   4870:                                    # an individual response can have multiple 
                   4871:                                    # lines
1.503     raeburn  4872: 
                   4873: my %responsetype_per_response;     # responsetype for each response
                   4874: 
1.495     albertel 4875: # Save and restore the bubble lines array to the form env.
                   4876: 
                   4877: 
                   4878: sub save_bubble_lines {
                   4879:     foreach my $line (keys(%bubble_lines_per_response)) {
                   4880: 	$env{"form.scantron.bubblelines.$line"}  = $bubble_lines_per_response{$line};
                   4881: 	$env{"form.scantron.first_bubble_line.$line"} =
                   4882: 	    $first_bubble_line{$line};
1.503     raeburn  4883:         $env{"form.scantron.sub_bubblelines.$line"} = 
                   4884:             $subdivided_bubble_lines{$line};
                   4885:         $env{"form.scantron.responsetype.$line"} =
                   4886:             $responsetype_per_response{$line};
1.495     albertel 4887:     }
                   4888: }
                   4889: 
                   4890: 
                   4891: sub restore_bubble_lines {
                   4892:     my $line = 0;
                   4893:     %bubble_lines_per_response = ();
                   4894:     while ($env{"form.scantron.bubblelines.$line"}) {
                   4895: 	my $value = $env{"form.scantron.bubblelines.$line"};
                   4896: 	$bubble_lines_per_response{$line} = $value;
                   4897: 	$first_bubble_line{$line}  =
                   4898: 	    $env{"form.scantron.first_bubble_line.$line"};
1.503     raeburn  4899:         $subdivided_bubble_lines{$line} =
                   4900:             $env{"form.scantron.sub_bubblelines.$line"};
                   4901:         $responsetype_per_response{$line} =
                   4902:             $env{"form.scantron.responsetype.$line"};
1.495     albertel 4903: 	$line++;
                   4904:     }
                   4905: }
                   4906: 
                   4907: #  Given the parsed scanline, get the response for 
                   4908: #  'answer' number n:
                   4909: 
                   4910: sub get_response_bubbles {
                   4911:     my ($parsed_line, $response)  = @_;
                   4912: 
                   4913:     my $bubble_line = $first_bubble_line{$response-1} +1;
                   4914:     my $bubble_lines= $bubble_lines_per_response{$response-1};
                   4915:     
                   4916:     my $selected = "";
                   4917: 
                   4918:     for (my $bline = 0; $bline < $bubble_lines; $bline++) {
                   4919: 	$selected .= $$parsed_line{"scantron.$bubble_line.answer"}.":";
                   4920: 	$bubble_line++;
                   4921:     }
                   4922:     return $selected;
                   4923: }
1.423     albertel 4924: 
                   4925: =pod 
                   4926: 
                   4927: =item scantron_filenames
                   4928: 
                   4929:    Returns a list of the scantron files in the current course 
                   4930: 
                   4931: =cut
1.422     foxr     4932: 
1.202     albertel 4933: sub scantron_filenames {
1.257     albertel 4934:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   4935:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
1.517     raeburn  4936:     my $getpropath = 1;
1.157     albertel 4937:     my @files=&Apache::lonnet::dirlist('userfiles',$cdom,$cname,
1.517     raeburn  4938:                                        $getpropath);
1.202     albertel 4939:     my @possiblenames;
1.201     albertel 4940:     foreach my $filename (sort(@files)) {
1.157     albertel 4941: 	($filename)=split(/&/,$filename);
                   4942: 	if ($filename!~/^scantron_orig_/) { next ; }
                   4943: 	$filename=~s/^scantron_orig_//;
1.202     albertel 4944: 	push(@possiblenames,$filename);
                   4945:     }
                   4946:     return @possiblenames;
                   4947: }
                   4948: 
1.423     albertel 4949: =pod 
                   4950: 
                   4951: =item scantron_uploads
                   4952: 
                   4953:    Returns  html drop-down list of scantron files in current course.
                   4954: 
                   4955:  Arguments:
                   4956:    $file2grade - filename to set as selected in the dropdown
                   4957: 
                   4958: =cut
1.422     foxr     4959: 
1.202     albertel 4960: sub scantron_uploads {
1.209     ng       4961:     my ($file2grade) = @_;
1.202     albertel 4962:     my $result=	'<select name="scantron_selectfile">';
                   4963:     $result.="<option></option>";
                   4964:     foreach my $filename (sort(&scantron_filenames())) {
1.401     albertel 4965: 	$result.="<option".($filename eq $file2grade ? ' selected="selected"':'').">$filename</option>\n";
1.81      albertel 4966:     }
                   4967:     $result.="</select>";
                   4968:     return $result;
                   4969: }
                   4970: 
1.423     albertel 4971: =pod 
                   4972: 
                   4973: =item scantron_scantab
                   4974: 
                   4975:   Returns html drop down of the scantron formats in the scantronformat.tab
                   4976:   file.
                   4977: 
                   4978: =cut
1.422     foxr     4979: 
1.82      albertel 4980: sub scantron_scantab {
                   4981:     my $result='<select name="scantron_format">'."\n";
1.191     albertel 4982:     $result.='<option></option>'."\n";
1.518     raeburn  4983:     my @lines = &get_scantronformat_file();
                   4984:     if (@lines > 0) {
                   4985:         foreach my $line (@lines) {
                   4986:             next if (($line =~ /^\#/) || ($line eq ''));
                   4987: 	    my ($name,$descrip)=split(/:/,$line);
                   4988: 	    $result.='<option value="'.$name.'">'.$descrip.'</option>'."\n";
                   4989:         }
1.82      albertel 4990:     }
                   4991:     $result.='</select>'."\n";
1.518     raeburn  4992:     return $result;
                   4993: }
                   4994: 
                   4995: =pod
                   4996: 
                   4997: =item get_scantronformat_file
                   4998: 
                   4999:   Returns an array containing lines from the scantron format file for
                   5000:   the domain of the course.
                   5001: 
                   5002:   If a url for a custom.tab file is listed in domain's configuration.db, 
                   5003:   lines are from this file.
                   5004: 
                   5005:   Otherwise, if a default.tab has been published in RES space by the 
                   5006:   domainconfig user, lines are from this file.
                   5007: 
                   5008:   Otherwise, fall back to getting lines from the legacy file on the
1.519     raeburn  5009:   local server:  /home/httpd/lonTabs/default_scantronformat.tab    
1.82      albertel 5010: 
1.518     raeburn  5011: =cut
                   5012: 
                   5013: sub get_scantronformat_file {
                   5014:     my $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
                   5015:     my %domconfig = &Apache::lonnet::get_dom('configuration',['scantron'],$cdom);
                   5016:     my $gottab = 0;
                   5017:     my @lines;
                   5018:     if (ref($domconfig{'scantron'}) eq 'HASH') {
                   5019:         if ($domconfig{'scantron'}{'scantronformat'} ne '') {
                   5020:             my $formatfile = &Apache::lonnet::getfile($Apache::lonnet::perlvar{'lonDocRoot'}.$domconfig{'scantron'}{'scantronformat'});
                   5021:             if ($formatfile ne '-1') {
                   5022:                 @lines = split("\n",$formatfile,-1);
                   5023:                 $gottab = 1;
                   5024:             }
                   5025:         }
                   5026:     }
                   5027:     if (!$gottab) {
                   5028:         my $confname = $cdom.'-domainconfig';
                   5029:         my $default = $Apache::lonnet::perlvar{'lonDocRoot'}.'/res/'.$cdom.'/'.$confname.'/default.tab';
                   5030:         my $formatfile =  &Apache::lonnet::getfile($default);
                   5031:         if ($formatfile ne '-1') {
                   5032:             @lines = split("\n",$formatfile,-1);
                   5033:             $gottab = 1;
                   5034:         }
                   5035:     }
                   5036:     if (!$gottab) {
1.519     raeburn  5037:         my @domains = &Apache::lonnet::current_machine_domains();
                   5038:         if (grep(/^\Q$cdom\E$/,@domains)) {
                   5039:             my $fh=Apache::File->new($Apache::lonnet::perlvar{'lonTabDir'}.'/scantronformat.tab');
                   5040:             @lines = <$fh>;
                   5041:             close($fh);
                   5042:         } else {
                   5043:             my $fh=Apache::File->new($Apache::lonnet::perlvar{'lonTabDir'}.'/default_scantronformat.tab');
                   5044:             @lines = <$fh>;
                   5045:             close($fh);
                   5046:         }
1.518     raeburn  5047:     }
                   5048:     return @lines;
1.82      albertel 5049: }
                   5050: 
1.423     albertel 5051: =pod 
                   5052: 
                   5053: =item scantron_CODElist
                   5054: 
                   5055:   Returns html drop down of the saved CODE lists from current course,
                   5056:   generated from earlier printings.
                   5057: 
                   5058: =cut
1.422     foxr     5059: 
1.186     albertel 5060: sub scantron_CODElist {
1.257     albertel 5061:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   5062:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
1.186     albertel 5063:     my @names=&Apache::lonnet::getkeys('CODEs',$cdom,$cnum);
                   5064:     my $namechoice='<option></option>';
1.225     albertel 5065:     foreach my $name (sort {uc($a) cmp uc($b)} @names) {
1.191     albertel 5066: 	if ($name =~ /^error: 2 /) { next; }
1.278     albertel 5067: 	if ($name =~ /^type\0/) { next; }
1.186     albertel 5068: 	$namechoice.='<option value="'.$name.'">'.$name.'</option>';
                   5069:     }
                   5070:     $namechoice='<select name="scantron_CODElist">'.$namechoice.'</select>';
                   5071:     return $namechoice;
                   5072: }
                   5073: 
1.423     albertel 5074: =pod 
                   5075: 
                   5076: =item scantron_CODEunique
                   5077: 
                   5078:   Returns the html for "Each CODE to be used once" radio.
                   5079: 
                   5080: =cut
1.422     foxr     5081: 
1.186     albertel 5082: sub scantron_CODEunique {
1.532     bisitz   5083:     my $result='<span class="LC_nobreak">
1.272     albertel 5084:                  <label><input type="radio" name="scantron_CODEunique"
1.423     albertel 5085:                         value="yes" checked="checked" />'.&mt('Yes').' </label>
1.381     albertel 5086:                 </span>
1.532     bisitz   5087:                 <span class="LC_nobreak">
1.272     albertel 5088:                  <label><input type="radio" name="scantron_CODEunique"
1.423     albertel 5089:                         value="no" />'.&mt('No').' </label>
1.381     albertel 5090:                 </span>';
1.186     albertel 5091:     return $result;
                   5092: }
1.423     albertel 5093: 
                   5094: =pod 
                   5095: 
                   5096: =item scantron_selectphase
                   5097: 
                   5098:   Generates the initial screen to start the bubble sheet process.
                   5099:   Allows for - starting a grading run.
1.424     albertel 5100:              - downloading existing scan data (original, corrected
1.423     albertel 5101:                                                 or skipped info)
                   5102: 
                   5103:              - uploading new scan data
                   5104: 
                   5105:  Arguments:
                   5106:   $r          - The Apache request object
                   5107:   $file2grade - name of the file that contain the scanned data to score
                   5108: 
                   5109: =cut
1.186     albertel 5110: 
1.75      albertel 5111: sub scantron_selectphase {
1.608     www      5112:     my ($r,$file2grade,$symb) = @_;
1.75      albertel 5113:     if (!$symb) {return '';}
1.582     raeburn  5114:     my $map_error;
                   5115:     my $sequence_selector=&getSequenceDropDown($symb,\$map_error);
                   5116:     if ($map_error) {
                   5117:         $r->print('<br />'.&navmap_errormsg().'<br />');
                   5118:         return;
                   5119:     }
1.324     albertel 5120:     my $default_form_data=&defaultFormData($symb);
1.209     ng       5121:     my $file_selector=&scantron_uploads($file2grade);
1.82      albertel 5122:     my $format_selector=&scantron_scantab();
1.186     albertel 5123:     my $CODE_selector=&scantron_CODElist();
                   5124:     my $CODE_unique=&scantron_CODEunique();
1.75      albertel 5125:     my $result;
1.422     foxr     5126: 
1.513     foxr     5127:     $ssi_error = 0;
                   5128: 
1.606     wenzelju 5129:     if (&Apache::lonnet::allowed('usc',$env{'request.role.domain'}) ||
                   5130:         &Apache::lonnet::allowed('usc',$env{'request.course.id'})) {
                   5131: 
                   5132: 	# Chunk of form to prompt for a scantron file upload.
                   5133: 
                   5134:         $r->print('
                   5135:     <br />
                   5136:     '.&Apache::loncommon::start_data_table('LC_scantron_action').'
                   5137:        '.&Apache::loncommon::start_data_table_header_row().'
                   5138:             <th>
                   5139:               &nbsp;'.&mt('Specify a bubblesheet data file to upload.').'
                   5140:             </th>
                   5141:        '.&Apache::loncommon::end_data_table_header_row().'
                   5142:        '.&Apache::loncommon::start_data_table_row().'
                   5143:             <td>
                   5144: ');
1.608     www      5145:     my $default_form_data=&defaultFormData($symb);
1.606     wenzelju 5146:     my $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
                   5147:     my $cnum= $env{'course.'.$env{'request.course.id'}.'.num'};
                   5148:     $r->print(&Apache::lonhtmlcommon::scripttag('
                   5149:     function checkUpload(formname) {
                   5150: 	if (formname.upfile.value == "") {
                   5151: 	    alert("'.&mt('Please use the browse button to select a file from your local directory.').'");
                   5152: 	    return false;
                   5153: 	}
                   5154: 	formname.submit();
                   5155:     }'));
                   5156:     $r->print('
                   5157:               <form enctype="multipart/form-data" action="/adm/grades" name="rules" method="post">
                   5158:                 '.$default_form_data.'
                   5159:                 <input name="courseid" type="hidden" value="'.$cnum.'" />
                   5160:                 <input name="domainid" type="hidden" value="'.$cdom.'" />
                   5161:                 <input name="command" value="scantronupload_save" type="hidden" />
                   5162:                 '.&mt('File to upload: [_1]','<input type="file" name="upfile" size="50" />').'
                   5163:                 <br />
                   5164:                 <input type="button" onclick="javascript:checkUpload(this.form);" value="'.&mt('Upload Bubblesheet Data').'" />
                   5165:               </form>
                   5166: ');
                   5167: 
                   5168:         $r->print('
                   5169:             </td>
                   5170:        '.&Apache::loncommon::end_data_table_row().'
                   5171:        '.&Apache::loncommon::end_data_table().'
                   5172: ');
                   5173:     }
                   5174: 
1.422     foxr     5175:     # Chunk of form to prompt for a file to grade and how:
                   5176: 
1.489     albertel 5177:     $result.= '
                   5178:     <br />
                   5179:     <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantron_process">
                   5180:     <input type="hidden" name="command" value="scantron_warning" />
                   5181:     '.$default_form_data.'
                   5182:     '.&Apache::loncommon::start_data_table('LC_scantron_action').'
                   5183:        '.&Apache::loncommon::start_data_table_header_row().'
                   5184:             <th colspan="2">
1.492     albertel 5185:               &nbsp;'.&mt('Specify file and which Folder/Sequence to grade').'
1.489     albertel 5186:             </th>
                   5187:        '.&Apache::loncommon::end_data_table_header_row().'
                   5188:        '.&Apache::loncommon::start_data_table_row().'
1.492     albertel 5189:             <td> '.&mt('Sequence to grade:').' </td><td> '.$sequence_selector.' </td>
1.489     albertel 5190:        '.&Apache::loncommon::end_data_table_row().'
                   5191:        '.&Apache::loncommon::start_data_table_row().'
1.572     www      5192:             <td> '.&mt('Filename of bubblesheet data file:').' </td><td> '.$file_selector.' </td>
1.489     albertel 5193:        '.&Apache::loncommon::end_data_table_row().'
                   5194:        '.&Apache::loncommon::start_data_table_row().'
1.572     www      5195:             <td> '.&mt('Format of bubblesheet data file:').' </td><td> '.$format_selector.' </td>
1.489     albertel 5196:        '.&Apache::loncommon::end_data_table_row().'
                   5197:        '.&Apache::loncommon::start_data_table_row().'
1.492     albertel 5198:             <td> '.&mt('Saved CODEs to validate against:').' </td><td> '.$CODE_selector.' </td>
1.489     albertel 5199:        '.&Apache::loncommon::end_data_table_row().'
                   5200:        '.&Apache::loncommon::start_data_table_row().'
1.492     albertel 5201:             <td> '.&mt('Each CODE is only to be used once:').'</td><td> '.$CODE_unique.' </td>
1.489     albertel 5202:        '.&Apache::loncommon::end_data_table_row().'
                   5203:        '.&Apache::loncommon::start_data_table_row().'
1.492     albertel 5204: 	    <td> '.&mt('Options:').' </td>
1.187     albertel 5205:             <td>
1.492     albertel 5206: 	       <label><input type="checkbox" name="scantron_options_redo" value="redo_skipped"/> '.&mt('Do only previously skipped records').'</label> <br />
                   5207:                <label><input type="checkbox" name="scantron_options_ignore" value="ignore_corrections"/> '.&mt('Remove all existing corrections').'</label> <br />
                   5208:                <label><input type="checkbox" name="scantron_options_hidden" value="ignore_hidden"/> '.&mt('Skip hidden resources when grading').'</label>
1.187     albertel 5209: 	    </td>
1.489     albertel 5210:        '.&Apache::loncommon::end_data_table_row().'
                   5211:        '.&Apache::loncommon::start_data_table_row().'
1.174     albertel 5212:             <td colspan="2">
1.572     www      5213:               <input type="submit" value="'.&mt('Grading: Validate Bubblesheet Records').'" />
1.162     albertel 5214:             </td>
1.489     albertel 5215:        '.&Apache::loncommon::end_data_table_row().'
                   5216:     '.&Apache::loncommon::end_data_table().'
                   5217:     </form>
                   5218: ';
1.162     albertel 5219:    
                   5220:     $r->print($result);
                   5221: 
1.422     foxr     5222: 
                   5223: 
                   5224:     # Chunk of the form that prompts to view a scoring office file,
                   5225:     # corrected file, skipped records in a file.
                   5226: 
1.489     albertel 5227:     $r->print('
                   5228:    <br />
                   5229:    <form action="/adm/grades" name="scantron_download">
                   5230:      '.$default_form_data.'
                   5231:      <input type="hidden" name="command" value="scantron_download" />
                   5232:      '.&Apache::loncommon::start_data_table('LC_scantron_action').'
                   5233:        '.&Apache::loncommon::start_data_table_header_row().'
                   5234:               <th>
1.492     albertel 5235:                 &nbsp;'.&mt('Download a scoring office file').'
1.489     albertel 5236:               </th>
                   5237:        '.&Apache::loncommon::end_data_table_header_row().'
                   5238:        '.&Apache::loncommon::start_data_table_row().'
1.492     albertel 5239:               <td> '.&mt('Filename of scoring office file: [_1]',$file_selector).' 
1.489     albertel 5240:                 <br />
1.492     albertel 5241:                 <input type="submit" value="'.&mt('Download: Show List of Associated Files').'" />
1.489     albertel 5242:        '.&Apache::loncommon::end_data_table_row().'
                   5243:      '.&Apache::loncommon::end_data_table().'
                   5244:    </form>
                   5245:    <br />
                   5246: ');
1.162     albertel 5247: 
1.457     banghart 5248:     &Apache::lonpickcode::code_list($r,2);
1.523     raeburn  5249: 
1.528     raeburn  5250:     $r->print('<br /><form method="post" name="checkscantron">'.
1.523     raeburn  5251:              $default_form_data."\n".
                   5252:              &Apache::loncommon::start_data_table('LC_scantron_action')."\n".
                   5253:              &Apache::loncommon::start_data_table_header_row()."\n".
                   5254:              '<th colspan="2">
1.572     www      5255:               &nbsp;'.&mt('Review bubblesheet data and submissions for a previously graded folder/sequence')."\n".
1.523     raeburn  5256:              '</th>'."\n".
                   5257:               &Apache::loncommon::end_data_table_header_row()."\n".
                   5258:               &Apache::loncommon::start_data_table_row()."\n".
                   5259:               '<td> '.&mt('Graded folder/sequence:').' </td>'."\n".
                   5260:               '<td> '.$sequence_selector.' </td>'.
                   5261:               &Apache::loncommon::end_data_table_row()."\n".
                   5262:               &Apache::loncommon::start_data_table_row()."\n".
                   5263:               '<td> '.&mt('Filename of scoring office file:').' </td>'."\n".
                   5264:               '<td> '.$file_selector.' </td>'."\n".
                   5265:               &Apache::loncommon::end_data_table_row()."\n".
                   5266:               &Apache::loncommon::start_data_table_row()."\n".
                   5267:               '<td> '.&mt('Format of data file:').' </td>'."\n".
                   5268:               '<td> '.$format_selector.' </td>'."\n".
                   5269:               &Apache::loncommon::end_data_table_row()."\n".
                   5270:               &Apache::loncommon::start_data_table_row()."\n".
1.557     raeburn  5271:               '<td> '.&mt('Options').' </td>'."\n".
                   5272:               '<td> <label><input type="checkbox" name="scantron_options_hidden" value="ignore_hidden"/> '.&mt('Skip hidden resources').'</label></td>'.
                   5273:               &Apache::loncommon::end_data_table_row()."\n".
                   5274:               &Apache::loncommon::start_data_table_row()."\n".
1.523     raeburn  5275:               '<td colspan="2">'."\n".
                   5276:               '<input type="hidden" name="command" value="checksubmissions" />'."\n".
1.575     www      5277:               '<input type="submit" value="'.&mt('Review Bubblesheet Data and Submission Records').'" />'."\n".
1.523     raeburn  5278:               '</td>'."\n".
                   5279:               &Apache::loncommon::end_data_table_row()."\n".
                   5280:               &Apache::loncommon::end_data_table()."\n".
                   5281:               '</form><br />');
                   5282:     return;
1.75      albertel 5283: }
                   5284: 
1.423     albertel 5285: =pod
                   5286: 
                   5287: =item get_scantron_config
                   5288: 
                   5289:    Parse and return the scantron configuration line selected as a
                   5290:    hash of configuration file fields.
                   5291: 
                   5292:  Arguments:
                   5293:     which - the name of the configuration to parse from the file.
                   5294: 
                   5295: 
                   5296:  Returns:
                   5297:             If the named configuration is not in the file, an empty
                   5298:             hash is returned.
                   5299:     a hash with the fields
                   5300:       name         - internal name for the this configuration setup
                   5301:       description  - text to display to operator that describes this config
                   5302:       CODElocation - if 0 or the string 'none'
                   5303:                           - no CODE exists for this config
                   5304:                      if -1 || the string 'letter'
                   5305:                           - a CODE exists for this config and is
                   5306:                             a string of letters
                   5307:                      Unsupported value (but planned for future support)
                   5308:                           if a positive integer
                   5309:                                - The CODE exists as the first n items from
                   5310:                                  the question section of the form
                   5311:                           if the string 'number'
                   5312:                                - The CODE exists for this config and is
                   5313:                                  a string of numbers
                   5314:       CODEstart   - (only matter if a CODE exists) column in the line where
                   5315:                      the CODE starts
                   5316:       CODElength  - length of the CODE
1.573     bisitz   5317:       IDstart     - column where the student/employee ID starts
1.556     weissno  5318:       IDlength    - length of the student/employee ID info
1.423     albertel 5319:       Qstart      - column where the information from the bubbled
                   5320:                     'questions' start
                   5321:       Qlength     - number of columns comprising a single bubble line from
                   5322:                     the sheet. (usually either 1 or 10)
1.424     albertel 5323:       Qon         - either a single character representing the character used
1.423     albertel 5324:                     to signal a bubble was chosen in the positional setup, or
                   5325:                     the string 'letter' if the letter of the chosen bubble is
                   5326:                     in the final, or 'number' if a number representing the
                   5327:                     chosen bubble is in the file (1->A 0->J)
1.424     albertel 5328:       Qoff        - the character used to represent that a bubble was
                   5329:                     left blank
1.423     albertel 5330:       PaperID     - if the scanning process generates a unique number for each
                   5331:                     sheet scanned the column that this ID number starts in
                   5332:       PaperIDlength - number of columns that comprise the unique ID number
                   5333:                       for the sheet of paper
1.424     albertel 5334:       FirstName   - column that the first name starts in
1.423     albertel 5335:       FirstNameLength - number of columns that the first name spans
                   5336:  
                   5337:       LastName    - column that the last name starts in
                   5338:       LastNameLength - number of columns that the last name spans
                   5339: 
                   5340: =cut
1.422     foxr     5341: 
1.82      albertel 5342: sub get_scantron_config {
                   5343:     my ($which) = @_;
1.518     raeburn  5344:     my @lines = &get_scantronformat_file();
1.82      albertel 5345:     my %config;
1.157     albertel 5346:     #FIXME probably should move to XML it has already gotten a bit much now
1.518     raeburn  5347:     foreach my $line (@lines) {
1.82      albertel 5348: 	my ($name,$descrip)=split(/:/,$line);
                   5349: 	if ($name ne $which ) { next; }
                   5350: 	chomp($line);
                   5351: 	my @config=split(/:/,$line);
                   5352: 	$config{'name'}=$config[0];
                   5353: 	$config{'description'}=$config[1];
                   5354: 	$config{'CODElocation'}=$config[2];
                   5355: 	$config{'CODEstart'}=$config[3];
                   5356: 	$config{'CODElength'}=$config[4];
                   5357: 	$config{'IDstart'}=$config[5];
                   5358: 	$config{'IDlength'}=$config[6];
                   5359: 	$config{'Qstart'}=$config[7];
1.497     foxr     5360:  	$config{'Qlength'}=$config[8];
1.82      albertel 5361: 	$config{'Qoff'}=$config[9];
                   5362: 	$config{'Qon'}=$config[10];
1.157     albertel 5363: 	$config{'PaperID'}=$config[11];
                   5364: 	$config{'PaperIDlength'}=$config[12];
                   5365: 	$config{'FirstName'}=$config[13];
                   5366: 	$config{'FirstNamelength'}=$config[14];
                   5367: 	$config{'LastName'}=$config[15];
                   5368: 	$config{'LastNamelength'}=$config[16];
1.82      albertel 5369: 	last;
                   5370:     }
                   5371:     return %config;
                   5372: }
                   5373: 
1.423     albertel 5374: =pod 
                   5375: 
                   5376: =item username_to_idmap
                   5377: 
1.556     weissno  5378:     creates a hash keyed by student/employee ID with values of the corresponding
1.423     albertel 5379:     student username:domain.
                   5380: 
                   5381:   Arguments:
                   5382: 
                   5383:     $classlist - reference to the class list hash. This is a hash
                   5384:                  keyed by student name:domain  whose elements are references
1.424     albertel 5385:                  to arrays containing various chunks of information
1.423     albertel 5386:                  about the student. (See loncoursedata for more info).
                   5387: 
                   5388:   Returns
                   5389:     %idmap - the constructed hash
                   5390: 
                   5391: =cut
                   5392: 
1.82      albertel 5393: sub username_to_idmap {
                   5394:     my ($classlist)= @_;
                   5395:     my %idmap;
                   5396:     foreach my $student (keys(%$classlist)) {
                   5397: 	$idmap{$classlist->{$student}->[&Apache::loncoursedata::CL_ID]}=
                   5398: 	    $student;
                   5399:     }
                   5400:     return %idmap;
                   5401: }
1.423     albertel 5402: 
                   5403: =pod
                   5404: 
1.424     albertel 5405: =item scantron_fixup_scanline
1.423     albertel 5406: 
                   5407:    Process a requested correction to a scanline.
                   5408: 
                   5409:   Arguments:
                   5410:     $scantron_config   - hash from &get_scantron_config()
                   5411:     $scan_data         - hash of correction information 
                   5412:                           (see &scantron_getfile())
                   5413:     $line              - existing scanline
                   5414:     $whichline         - line number of the passed in scanline
                   5415:     $field             - type of change to process 
                   5416:                          (either 
1.573     bisitz   5417:                           'ID'     -> correct the student/employee ID
1.423     albertel 5418:                           'CODE'   -> correct the CODE
                   5419:                           'answer' -> fixup the submitted answers)
                   5420:     
                   5421:    $args               - hash of additional info,
                   5422:                           - 'ID' 
                   5423:                                'newid' -> studentID to use in replacement
1.424     albertel 5424:                                           of existing one
1.423     albertel 5425:                           - 'CODE' 
                   5426:                                'CODE_ignore_dup' - set to true if duplicates
                   5427:                                                    should be ignored.
                   5428: 	                       'CODE' - is new code or 'use_unfound'
1.424     albertel 5429:                                         if the existing unfound code should
1.423     albertel 5430:                                         be used as is
                   5431:                           - 'answer'
                   5432:                                'response' - new answer or 'none' if blank
                   5433:                                'question' - the bubble line to change
1.503     raeburn  5434:                                'questionnum' - the question identifier,
                   5435:                                                may include subquestion. 
1.423     albertel 5436: 
                   5437:   Returns:
                   5438:     $line - the modified scanline
                   5439: 
                   5440:   Side effects: 
                   5441:     $scan_data - may be updated
                   5442: 
                   5443: =cut
                   5444: 
1.82      albertel 5445: 
1.157     albertel 5446: sub scantron_fixup_scanline {
                   5447:     my ($scantron_config,$scan_data,$line,$whichline,$field,$args)=@_;
                   5448:     if ($field eq 'ID') {
                   5449: 	if (length($args->{'newid'}) > $$scantron_config{'IDlength'}) {
1.186     albertel 5450: 	    return ($line,1,'New value too large');
1.157     albertel 5451: 	}
                   5452: 	if (length($args->{'newid'}) < $$scantron_config{'IDlength'}) {
                   5453: 	    $args->{'newid'}=sprintf('%-'.$$scantron_config{'IDlength'}.'s',
                   5454: 				     $args->{'newid'});
                   5455: 	}
                   5456: 	substr($line,$$scantron_config{'IDstart'}-1,
                   5457: 	       $$scantron_config{'IDlength'})=$args->{'newid'};
                   5458: 	if ($args->{'newid'}=~/^\s*$/) {
                   5459: 	    &scan_data($scan_data,"$whichline.user",
                   5460: 		       $args->{'username'}.':'.$args->{'domain'});
                   5461: 	}
1.186     albertel 5462:     } elsif ($field eq 'CODE') {
1.192     albertel 5463: 	if ($args->{'CODE_ignore_dup'}) {
                   5464: 	    &scan_data($scan_data,"$whichline.CODE_ignore_dup",'1');
                   5465: 	}
                   5466: 	&scan_data($scan_data,"$whichline.useCODE",'1');
                   5467: 	if ($args->{'CODE'} ne 'use_unfound') {
1.191     albertel 5468: 	    if (length($args->{'CODE'}) > $$scantron_config{'CODElength'}) {
                   5469: 		return ($line,1,'New CODE value too large');
                   5470: 	    }
                   5471: 	    if (length($args->{'CODE'}) < $$scantron_config{'CODElength'}) {
                   5472: 		$args->{'CODE'}=sprintf('%-'.$$scantron_config{'CODElength'}.'s',$args->{'CODE'});
                   5473: 	    }
                   5474: 	    substr($line,$$scantron_config{'CODEstart'}-1,
                   5475: 		   $$scantron_config{'CODElength'})=$args->{'CODE'};
1.186     albertel 5476: 	}
1.157     albertel 5477:     } elsif ($field eq 'answer') {
1.497     foxr     5478: 	my $length=$scantron_config->{'Qlength'};
1.157     albertel 5479: 	my $off=$scantron_config->{'Qoff'};
                   5480: 	my $on=$scantron_config->{'Qon'};
1.497     foxr     5481: 	my $answer=${off}x$length;
                   5482: 	if ($args->{'response'} eq 'none') {
                   5483: 	    &scan_data($scan_data,
1.503     raeburn  5484: 		       "$whichline.no_bubble.".$args->{'questionnum'},'1');
1.497     foxr     5485: 	} else {
                   5486: 	    if ($on eq 'letter') {
                   5487: 		my @alphabet=('A'..'Z');
                   5488: 		$answer=$alphabet[$args->{'response'}];
                   5489: 	    } elsif ($on eq 'number') {
                   5490: 		$answer=$args->{'response'}+1;
                   5491: 		if ($answer == 10) { $answer = '0'; }
1.274     albertel 5492: 	    } else {
1.497     foxr     5493: 		substr($answer,$args->{'response'},1)=$on;
1.274     albertel 5494: 	    }
1.497     foxr     5495: 	    &scan_data($scan_data,
1.503     raeburn  5496: 		       "$whichline.no_bubble.".$args->{'questionnum'},undef,'1');
1.157     albertel 5497: 	}
1.497     foxr     5498: 	my $where=$length*($args->{'question'}-1)+$scantron_config->{'Qstart'};
                   5499: 	substr($line,$where-1,$length)=$answer;
1.157     albertel 5500:     }
                   5501:     return $line;
                   5502: }
1.423     albertel 5503: 
                   5504: =pod
                   5505: 
                   5506: =item scan_data
                   5507: 
                   5508:     Edit or look up  an item in the scan_data hash.
                   5509: 
                   5510:   Arguments:
                   5511:     $scan_data  - The hash (see scantron_getfile)
                   5512:     $key        - shorthand of the key to edit (actual key is
1.424     albertel 5513:                   scantronfilename_key).
1.423     albertel 5514:     $data        - New value of the hash entry.
                   5515:     $delete      - If true, the entry is removed from the hash.
                   5516: 
                   5517:   Returns:
                   5518:     The new value of the hash table field (undefined if deleted).
                   5519: 
                   5520: =cut
                   5521: 
                   5522: 
1.157     albertel 5523: sub scan_data {
                   5524:     my ($scan_data,$key,$value,$delete)=@_;
1.257     albertel 5525:     my $filename=$env{'form.scantron_selectfile'};
1.157     albertel 5526:     if (defined($value)) {
                   5527: 	$scan_data->{$filename.'_'.$key} = $value;
                   5528:     }
                   5529:     if ($delete) { delete($scan_data->{$filename.'_'.$key}); }
                   5530:     return $scan_data->{$filename.'_'.$key};
                   5531: }
1.423     albertel 5532: 
1.495     albertel 5533: # ----- These first few routines are general use routines.----
                   5534: 
                   5535: # Return the number of occurences of a pattern in a string.
                   5536: 
                   5537: sub occurence_count {
                   5538:     my ($string, $pattern) = @_;
                   5539: 
                   5540:     my @matches = ($string =~ /$pattern/g);
                   5541: 
                   5542:     return scalar(@matches);
                   5543: }
                   5544: 
                   5545: 
                   5546: # Take a string known to have digits and convert all the
                   5547: # digits into letters in the range J,A..I.
                   5548: 
                   5549: sub digits_to_letters {
                   5550:     my ($input) = @_;
                   5551: 
                   5552:     my @alphabet = ('J', 'A'..'I');
                   5553: 
                   5554:     my @input    = split(//, $input);
                   5555:     my $output ='';
                   5556:     for (my $i = 0; $i < scalar(@input); $i++) {
                   5557: 	if ($input[$i] =~ /\d/) {
                   5558: 	    $output .= $alphabet[$input[$i]];
                   5559: 	} else {
                   5560: 	    $output .= $input[$i];
                   5561: 	}
                   5562:     }
                   5563:     return $output;
                   5564: }
                   5565: 
1.423     albertel 5566: =pod 
                   5567: 
                   5568: =item scantron_parse_scanline
                   5569: 
                   5570:   Decodes a scanline from the selected scantron file
                   5571: 
                   5572:  Arguments:
                   5573:     line             - The text of the scantron file line to process
                   5574:     whichline        - Line number
                   5575:     scantron_config  - Hash describing the format of the scantron lines.
                   5576:     scan_data        - Hash of extra information about the scanline
                   5577:                        (see scantron_getfile for more information)
                   5578:     just_header      - True if should not process question answers but only
                   5579:                        the stuff to the left of the answers.
                   5580:  Returns:
                   5581:    Hash containing the result of parsing the scanline
                   5582: 
                   5583:    Keys are all proceeded by the string 'scantron.'
                   5584: 
                   5585:        CODE    - the CODE in use for this scanline
                   5586:        useCODE - 1 if the CODE is invalid but it usage has been forced
                   5587:                  by the operator
                   5588:        CODE_ignore_dup - 1 if the CODE is a duplicated use when unique
                   5589:                             CODEs were selected, but the usage has been
                   5590:                             forced by the operator
1.556     weissno  5591:        ID  - student/employee ID
1.423     albertel 5592:        PaperID - if used, the ID number printed on the sheet when the 
                   5593:                  paper was scanned
                   5594:        FirstName - first name from the sheet
                   5595:        LastName  - last name from the sheet
                   5596: 
                   5597:      if just_header was not true these key may also exist
                   5598: 
1.447     foxr     5599:        missingerror - a list of bubble ranges that are considered to be answers
                   5600:                       to a single question that don't have any bubbles filled in.
                   5601:                       Of the form questionnumber:firstbubblenumber:count.
                   5602:        doubleerror  - a list of bubble ranges that are considered to be answers
                   5603:                       to a single question that have more than one bubble filled in.
                   5604:                       Of the form questionnumber::firstbubblenumber:count
                   5605:    
                   5606:                 In the above, count is the number of bubble responses in the
                   5607:                 input line needed to represent the possible answers to the question.
                   5608:                 e.g. a radioresponse with 15 choices in an answer sheet with 10 choices
                   5609:                 per line would have count = 2.
                   5610: 
1.423     albertel 5611:        maxquest     - the number of the last bubble line that was parsed
                   5612: 
                   5613:        (<number> starts at 1)
                   5614:        <number>.answer - zero or more letters representing the selected
                   5615:                          letters from the scanline for the bubble line 
                   5616:                          <number>.
                   5617:                          if blank there was either no bubble or there where
                   5618:                          multiple bubbles, (consult the keys missingerror and
                   5619:                          doubleerror if this is an error condition)
                   5620: 
                   5621: =cut
                   5622: 
1.82      albertel 5623: sub scantron_parse_scanline {
1.423     albertel 5624:     my ($line,$whichline,$scantron_config,$scan_data,$just_header)=@_;
1.470     foxr     5625: 
1.82      albertel 5626:     my %record;
1.550     raeburn  5627:     my $lastpos = $env{'form.scantron_maxbubble'}*$$scantron_config{'Qlength'};
                   5628:     my $questions=substr($line,$$scantron_config{'Qstart'}-1,$lastpos);  # Answers
1.422     foxr     5629:     my $data=substr($line,0,$$scantron_config{'Qstart'}-1);     # earlier stuff
1.278     albertel 5630:     if (!($$scantron_config{'CODElocation'} eq 0 ||
                   5631: 	  $$scantron_config{'CODElocation'} eq 'none')) {
                   5632: 	if ($$scantron_config{'CODElocation'} < 0 ||
                   5633: 	    $$scantron_config{'CODElocation'} eq 'letter' ||
                   5634: 	    $$scantron_config{'CODElocation'} eq 'number') {
1.191     albertel 5635: 	    $record{'scantron.CODE'}=substr($data,
                   5636: 					    $$scantron_config{'CODEstart'}-1,
1.83      albertel 5637: 					    $$scantron_config{'CODElength'});
1.191     albertel 5638: 	    if (&scan_data($scan_data,"$whichline.useCODE")) {
                   5639: 		$record{'scantron.useCODE'}=1;
                   5640: 	    }
1.192     albertel 5641: 	    if (&scan_data($scan_data,"$whichline.CODE_ignore_dup")) {
                   5642: 		$record{'scantron.CODE_ignore_dup'}=1;
                   5643: 	    }
1.82      albertel 5644: 	} else {
                   5645: 	    #FIXME interpret first N questions
                   5646: 	}
                   5647:     }
1.83      albertel 5648:     $record{'scantron.ID'}=substr($data,$$scantron_config{'IDstart'}-1,
                   5649: 				  $$scantron_config{'IDlength'});
1.157     albertel 5650:     $record{'scantron.PaperID'}=
                   5651: 	substr($data,$$scantron_config{'PaperID'}-1,
                   5652: 	       $$scantron_config{'PaperIDlength'});
                   5653:     $record{'scantron.FirstName'}=
                   5654: 	substr($data,$$scantron_config{'FirstName'}-1,
                   5655: 	       $$scantron_config{'FirstNamelength'});
                   5656:     $record{'scantron.LastName'}=
                   5657: 	substr($data,$$scantron_config{'LastName'}-1,
                   5658: 	       $$scantron_config{'LastNamelength'});
1.423     albertel 5659:     if ($just_header) { return \%record; }
1.194     albertel 5660: 
1.82      albertel 5661:     my @alphabet=('A'..'Z');
                   5662:     my $questnum=0;
1.447     foxr     5663:     my $ansnum  =1;		# Multiple 'answer lines'/question.
                   5664: 
1.470     foxr     5665:     chomp($questions);		# Get rid of any trailing \n.
                   5666:     $questions =~ s/\r$//;      # Get rid of trailing \r too (MAC or Win uploads).
                   5667:     while (length($questions)) {
1.447     foxr     5668: 	my $answers_needed = $bubble_lines_per_response{$questnum};
1.503     raeburn  5669:         my $answer_length  = ($$scantron_config{'Qlength'} * $answers_needed)
                   5670:                              || 1;
                   5671:         $questnum++;
                   5672:         my $quest_id = $questnum;
                   5673:         my $currentquest = substr($questions,0,$answer_length);
                   5674:         $questions       = substr($questions,$answer_length);
                   5675:         if (length($currentquest) < $answer_length) { next; }
                   5676: 
                   5677:         if ($subdivided_bubble_lines{$questnum-1} =~ /,/) {
                   5678:             my $subquestnum = 1;
                   5679:             my $subquestions = $currentquest;
                   5680:             my @subanswers_needed = 
                   5681:                 split(/,/,$subdivided_bubble_lines{$questnum-1});  
                   5682:             foreach my $subans (@subanswers_needed) {
                   5683:                 my $subans_length =
                   5684:                     ($$scantron_config{'Qlength'} * $subans)  || 1;
                   5685:                 my $currsubquest = substr($subquestions,0,$subans_length);
                   5686:                 $subquestions   = substr($subquestions,$subans_length);
                   5687:                 $quest_id = "$questnum.$subquestnum";
                   5688:                 if (($$scantron_config{'Qon'} eq 'letter') ||
                   5689:                     ($$scantron_config{'Qon'} eq 'number')) {
                   5690:                     $ansnum = &scantron_validator_lettnum($ansnum, 
                   5691:                         $questnum,$quest_id,$subans,$currsubquest,$whichline,
                   5692:                         \@alphabet,\%record,$scantron_config,$scan_data);
                   5693:                 } else {
                   5694:                     $ansnum = &scantron_validator_positional($ansnum,
                   5695:                         $questnum,$quest_id,$subans,$currsubquest,$whichline,                        \@alphabet,\%record,$scantron_config,$scan_data);
                   5696:                 }
                   5697:                 $subquestnum ++;
                   5698:             }
                   5699:         } else {
                   5700:             if (($$scantron_config{'Qon'} eq 'letter') ||
                   5701:                 ($$scantron_config{'Qon'} eq 'number')) {
                   5702:                 $ansnum = &scantron_validator_lettnum($ansnum,$questnum,
                   5703:                     $quest_id,$answers_needed,$currentquest,$whichline,
                   5704:                     \@alphabet,\%record,$scantron_config,$scan_data);
                   5705:             } else {
                   5706:                 $ansnum = &scantron_validator_positional($ansnum,$questnum,
                   5707:                     $quest_id,$answers_needed,$currentquest,$whichline,
                   5708:                     \@alphabet,\%record,$scantron_config,$scan_data);
                   5709:             }
                   5710:         }
                   5711:     }
                   5712:     $record{'scantron.maxquest'}=$questnum;
                   5713:     return \%record;
                   5714: }
1.447     foxr     5715: 
1.503     raeburn  5716: sub scantron_validator_lettnum {
                   5717:     my ($ansnum,$questnum,$quest_id,$answers_needed,$currquest,$whichline,
                   5718:         $alphabet,$record,$scantron_config,$scan_data) = @_;
                   5719: 
                   5720:     # Qon 'letter' implies for each slot in currquest we have:
                   5721:     #    ? or * for doubles, a letter in A-Z for a bubble, and
                   5722:     #    about anything else (esp. a value of Qoff) for missing
                   5723:     #    bubbles.
                   5724:     #
                   5725:     # Qon 'number' implies each slot gives a digit that indexes the
                   5726:     #    bubbles filled, or Qoff, or a non-number for unbubbled lines,
                   5727:     #    and * or ? for double bubbles on a single line.
                   5728:     #
1.447     foxr     5729: 
1.503     raeburn  5730:     my $matchon;
                   5731:     if ($$scantron_config{'Qon'} eq 'letter') {
                   5732:         $matchon = '[A-Z]';
                   5733:     } elsif ($$scantron_config{'Qon'} eq 'number') {
                   5734:         $matchon = '\d';
                   5735:     }
                   5736:     my $occurrences = 0;
                   5737:     if (($responsetype_per_response{$questnum-1} eq 'essayresponse') ||
                   5738:         ($responsetype_per_response{$questnum-1} eq 'formularesponse') ||
1.510     raeburn  5739:         ($responsetype_per_response{$questnum-1} eq 'stringresponse') ||
                   5740:         ($responsetype_per_response{$questnum-1} eq 'imageresponse') ||
                   5741:         ($responsetype_per_response{$questnum-1} eq 'reactionresponse') ||
                   5742:         ($responsetype_per_response{$questnum-1} eq 'organicresponse')) {
1.503     raeburn  5743:         my @singlelines = split('',$currquest);
                   5744:         foreach my $entry (@singlelines) {
                   5745:             $occurrences = &occurence_count($entry,$matchon);
                   5746:             if ($occurrences > 1) {
                   5747:                 last;
                   5748:             }
                   5749:         } 
                   5750:     } else {
                   5751:         $occurrences = &occurence_count($currquest,$matchon); 
                   5752:     }
                   5753:     if (($currquest =~ /\?/ || $currquest =~ /\*/) || ($occurrences > 1)) {
                   5754:         push(@{$record->{'scantron.doubleerror'}},$quest_id);
                   5755:         for (my $ans=0; $ans<$answers_needed; $ans++) {
                   5756:             my $bubble = substr($currquest,$ans,1);
                   5757:             if ($bubble =~ /$matchon/ ) {
                   5758:                 if ($$scantron_config{'Qon'} eq 'number') {
                   5759:                     if ($bubble == 0) {
                   5760:                         $bubble = 10; 
                   5761:                     }
                   5762:                     $record->{"scantron.$ansnum.answer"} = 
                   5763:                         $alphabet->[$bubble-1];
                   5764:                 } else {
                   5765:                     $record->{"scantron.$ansnum.answer"} = $bubble;
                   5766:                 }
                   5767:             } else {
                   5768:                 $record->{"scantron.$ansnum.answer"}='';
                   5769:             }
                   5770:             $ansnum++;
                   5771:         }
                   5772:     } elsif (!defined($currquest)
                   5773:             || (&occurence_count($currquest, $$scantron_config{'Qoff'}) == length($currquest))
                   5774:             || (&occurence_count($currquest,$matchon) == 0)) {
                   5775:         for (my $ans=0; $ans<$answers_needed; $ans++ ) {
                   5776:             $record->{"scantron.$ansnum.answer"}='';
                   5777:             $ansnum++;
                   5778:         }
                   5779:         if (!&scan_data($scan_data,"$whichline.no_bubble.$quest_id")) {
                   5780:             push(@{$record->{'scantron.missingerror'}},$quest_id);
                   5781:         }
                   5782:     } else {
                   5783:         if ($$scantron_config{'Qon'} eq 'number') {
                   5784:             $currquest = &digits_to_letters($currquest);            
                   5785:         }
                   5786:         for (my $ans=0; $ans<$answers_needed; $ans++) {
                   5787:             my $bubble = substr($currquest,$ans,1);
                   5788:             $record->{"scantron.$ansnum.answer"} = $bubble;
                   5789:             $ansnum++;
                   5790:         }
                   5791:     }
                   5792:     return $ansnum;
                   5793: }
1.447     foxr     5794: 
1.503     raeburn  5795: sub scantron_validator_positional {
                   5796:     my ($ansnum,$questnum,$quest_id,$answers_needed,$currquest,
                   5797:         $whichline,$alphabet,$record,$scantron_config,$scan_data) = @_;
1.447     foxr     5798: 
1.503     raeburn  5799:     # Otherwise there's a positional notation;
                   5800:     # each bubble line requires Qlength items, and there are filled in
                   5801:     # bubbles for each case where there 'Qon' characters.
                   5802:     #
1.447     foxr     5803: 
1.503     raeburn  5804:     my @array=split($$scantron_config{'Qon'},$currquest,-1);
1.447     foxr     5805: 
1.503     raeburn  5806:     # If the split only gives us one element.. the full length of the
                   5807:     # answer string, no bubbles are filled in:
1.447     foxr     5808: 
1.507     raeburn  5809:     if ($answers_needed eq '') {
                   5810:         return;
                   5811:     }
                   5812: 
1.503     raeburn  5813:     if (length($array[0]) eq $$scantron_config{'Qlength'}*$answers_needed) {
                   5814:         for (my $ans=0; $ans<$answers_needed; $ans++ ) {
                   5815:             $record->{"scantron.$ansnum.answer"}='';
                   5816:             $ansnum++;
                   5817:         }
                   5818:         if (!&scan_data($scan_data,"$whichline.no_bubble.$quest_id")) {
                   5819:             push(@{$record->{"scantron.missingerror"}},$quest_id);
                   5820:         }
                   5821:     } elsif (scalar(@array) == 2) {
                   5822:         my $location = length($array[0]);
                   5823:         my $line_num = int($location / $$scantron_config{'Qlength'});
                   5824:         my $bubble   = $alphabet->[$location % $$scantron_config{'Qlength'}];
                   5825:         for (my $ans=0; $ans<$answers_needed; $ans++) {
                   5826:             if ($ans eq $line_num) {
                   5827:                 $record->{"scantron.$ansnum.answer"} = $bubble;
                   5828:             } else {
                   5829:                 $record->{"scantron.$ansnum.answer"} = ' ';
                   5830:             }
                   5831:             $ansnum++;
                   5832:          }
                   5833:     } else {
                   5834:         #  If there's more than one instance of a bubble character
                   5835:         #  That's a double bubble; with positional notation we can
                   5836:         #  record all the bubbles filled in as well as the
                   5837:         #  fact this response consists of multiple bubbles.
                   5838:         #
                   5839:         if (($responsetype_per_response{$questnum-1} eq 'essayresponse') ||
                   5840:             ($responsetype_per_response{$questnum-1} eq 'formularesponse') ||
1.510     raeburn  5841:             ($responsetype_per_response{$questnum-1} eq 'stringresponse') ||
                   5842:             ($responsetype_per_response{$questnum-1} eq 'imageresponse') ||
                   5843:             ($responsetype_per_response{$questnum-1} eq 'reactionresponse') ||
                   5844:             ($responsetype_per_response{$questnum-1} eq 'organicresponse')) {
1.503     raeburn  5845:             my $doubleerror = 0;
                   5846:             while (($currquest >= $$scantron_config{'Qlength'}) && 
                   5847:                    (!$doubleerror)) {
                   5848:                my $currline = substr($currquest,0,$$scantron_config{'Qlength'});
                   5849:                $currquest = substr($currquest,$$scantron_config{'Qlength'});
                   5850:                my @currarray = split($$scantron_config{'Qon'},$currline,-1);
                   5851:                if (length(@currarray) > 2) {
                   5852:                    $doubleerror = 1;
                   5853:                } 
                   5854:             }
                   5855:             if ($doubleerror) {
                   5856:                 push(@{$record->{'scantron.doubleerror'}},$quest_id);
                   5857:             }
                   5858:         } else {
                   5859:             push(@{$record->{'scantron.doubleerror'}},$quest_id);
                   5860:         }
                   5861:         my $item = $ansnum;
                   5862:         for (my $ans=0; $ans<$answers_needed; $ans++) {
                   5863:             $record->{"scantron.$item.answer"} = '';
                   5864:             $item ++;
                   5865:         }
1.447     foxr     5866: 
1.503     raeburn  5867:         my @ans=@array;
                   5868:         my $i=0;
                   5869:         my $increment = 0;
                   5870:         while ($#ans) {
                   5871:             $i+=length($ans[0]) + $increment;
                   5872:             my $line   = int($i/$$scantron_config{'Qlength'} + $ansnum);
                   5873:             my $bubble = $i%$$scantron_config{'Qlength'};
                   5874:             $record->{"scantron.$line.answer"}.=$alphabet->[$bubble];
                   5875:             shift(@ans);
                   5876:             $increment = 1;
                   5877:         }
                   5878:         $ansnum += $answers_needed;
1.82      albertel 5879:     }
1.503     raeburn  5880:     return $ansnum;
1.82      albertel 5881: }
                   5882: 
1.423     albertel 5883: =pod
                   5884: 
                   5885: =item scantron_add_delay
                   5886: 
                   5887:    Adds an error message that occurred during the grading phase to a
                   5888:    queue of messages to be shown after grading pass is complete
                   5889: 
                   5890:  Arguments:
1.424     albertel 5891:    $delayqueue  - arrary ref of hash ref of error messages
1.423     albertel 5892:    $scanline    - the scanline that caused the error
                   5893:    $errormesage - the error message
                   5894:    $errorcode   - a numeric code for the error
                   5895: 
                   5896:  Side Effects:
1.424     albertel 5897:    updates the $delayqueue to have a new hash ref of the error
1.423     albertel 5898: 
                   5899: =cut
                   5900: 
1.82      albertel 5901: sub scantron_add_delay {
1.140     albertel 5902:     my ($delayqueue,$scanline,$errormessage,$errorcode)=@_;
                   5903:     push(@$delayqueue,
                   5904: 	 {'line' => $scanline, 'emsg' => $errormessage,
                   5905: 	  'ecode' => $errorcode }
                   5906: 	 );
1.82      albertel 5907: }
                   5908: 
1.423     albertel 5909: =pod
                   5910: 
                   5911: =item scantron_find_student
                   5912: 
1.424     albertel 5913:    Finds the username for the current scanline
                   5914: 
                   5915:   Arguments:
                   5916:    $scantron_record - hash result from scantron_parse_scanline
                   5917:    $scan_data       - hash of correction information 
                   5918:                       (see &scantron_getfile() form more information)
                   5919:    $idmap           - hash from &username_to_idmap()
                   5920:    $line            - number of current scanline
                   5921:  
                   5922:   Returns:
                   5923:    Either 'username:domain' or undef if unknown
                   5924: 
1.423     albertel 5925: =cut
                   5926: 
1.82      albertel 5927: sub scantron_find_student {
1.157     albertel 5928:     my ($scantron_record,$scan_data,$idmap,$line)=@_;
1.83      albertel 5929:     my $scanID=$$scantron_record{'scantron.ID'};
1.157     albertel 5930:     if ($scanID =~ /^\s*$/) {
                   5931:  	return &scan_data($scan_data,"$line.user");
                   5932:     }
1.83      albertel 5933:     foreach my $id (keys(%$idmap)) {
1.157     albertel 5934:  	if (lc($id) eq lc($scanID)) {
                   5935:  	    return $$idmap{$id};
                   5936:  	}
1.83      albertel 5937:     }
                   5938:     return undef;
                   5939: }
                   5940: 
1.423     albertel 5941: =pod
                   5942: 
                   5943: =item scantron_filter
                   5944: 
1.424     albertel 5945:    Filter sub for lonnavmaps, filters out hidden resources if ignore
                   5946:    hidden resources was selected
                   5947: 
1.423     albertel 5948: =cut
                   5949: 
1.83      albertel 5950: sub scantron_filter {
                   5951:     my ($curres)=@_;
1.331     albertel 5952: 
                   5953:     if (ref($curres) && $curres->is_problem()) {
                   5954: 	# if the user has asked to not have either hidden
                   5955: 	# or 'randomout' controlled resources to be graded
                   5956: 	# don't include them
                   5957: 	if ($env{'form.scantron_options_hidden'} eq 'ignore_hidden'
                   5958: 	    && $curres->randomout) {
                   5959: 	    return 0;
                   5960: 	}
1.83      albertel 5961: 	return 1;
                   5962:     }
                   5963:     return 0;
1.82      albertel 5964: }
                   5965: 
1.423     albertel 5966: =pod
                   5967: 
                   5968: =item scantron_process_corrections
                   5969: 
1.424     albertel 5970:    Gets correction information out of submitted form data and corrects
                   5971:    the scanline
                   5972: 
1.423     albertel 5973: =cut
                   5974: 
1.157     albertel 5975: sub scantron_process_corrections {
                   5976:     my ($r) = @_;
1.257     albertel 5977:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.157     albertel 5978:     my ($scanlines,$scan_data)=&scantron_getfile();
                   5979:     my $classlist=&Apache::loncoursedata::get_classlist();
1.257     albertel 5980:     my $which=$env{'form.scantron_line'};
1.200     albertel 5981:     my $line=&scantron_get_line($scanlines,$scan_data,$which);
1.157     albertel 5982:     my ($skip,$err,$errmsg);
1.257     albertel 5983:     if ($env{'form.scantron_skip_record'}) {
1.157     albertel 5984: 	$skip=1;
1.257     albertel 5985:     } elsif ($env{'form.scantron_corrections'} =~ /^(duplicate|incorrect)ID$/) {
                   5986: 	my $newstudent=$env{'form.scantron_username'}.':'.
                   5987: 	    $env{'form.scantron_domain'};
1.157     albertel 5988: 	my $newid=$classlist->{$newstudent}->[&Apache::loncoursedata::CL_ID];
                   5989: 	($line,$err,$errmsg)=
                   5990: 	    &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,$which,
                   5991: 				     'ID',{'newid'=>$newid,
1.257     albertel 5992: 				    'username'=>$env{'form.scantron_username'},
                   5993: 				    'domain'=>$env{'form.scantron_domain'}});
                   5994:     } elsif ($env{'form.scantron_corrections'} =~ /^(duplicate|incorrect)CODE$/) {
                   5995: 	my $resolution=$env{'form.scantron_CODE_resolution'};
1.190     albertel 5996: 	my $newCODE;
1.192     albertel 5997: 	my %args;
1.190     albertel 5998: 	if      ($resolution eq 'use_unfound') {
1.191     albertel 5999: 	    $newCODE='use_unfound';
1.190     albertel 6000: 	} elsif ($resolution eq 'use_found') {
1.257     albertel 6001: 	    $newCODE=$env{'form.scantron_CODE_selectedvalue'};
1.190     albertel 6002: 	} elsif ($resolution eq 'use_typed') {
1.257     albertel 6003: 	    $newCODE=$env{'form.scantron_CODE_newvalue'};
1.194     albertel 6004: 	} elsif ($resolution =~ /^use_closest_(\d+)/) {
1.257     albertel 6005: 	    $newCODE=$env{"form.scantron_CODE_closest_$1"};
1.190     albertel 6006: 	}
1.257     albertel 6007: 	if ($env{'form.scantron_corrections'} eq 'duplicateCODE') {
1.192     albertel 6008: 	    $args{'CODE_ignore_dup'}=1;
                   6009: 	}
                   6010: 	$args{'CODE'}=$newCODE;
1.186     albertel 6011: 	($line,$err,$errmsg)=
                   6012: 	    &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,$which,
1.192     albertel 6013: 				     'CODE',\%args);
1.257     albertel 6014:     } elsif ($env{'form.scantron_corrections'} =~ /^(missing|double)bubble$/) {
                   6015: 	foreach my $question (split(',',$env{'form.scantron_questions'})) {
1.157     albertel 6016: 	    ($line,$err,$errmsg)=
                   6017: 		&scantron_fixup_scanline(\%scantron_config,$scan_data,$line,
                   6018: 					 $which,'answer',
                   6019: 					 { 'question'=>$question,
1.503     raeburn  6020: 		      		   'response'=>$env{"form.scantron_correct_Q_$question"},
                   6021:                                    'questionnum'=>$env{"form.scantron_questionnum_Q_$question"}});
1.157     albertel 6022: 	    if ($err) { last; }
                   6023: 	}
                   6024:     }
                   6025:     if ($err) {
1.398     albertel 6026: 	$r->print("<span class=\"LC_warning\">Unable to accept last correction, an error occurred :$errmsg:</span>");
1.157     albertel 6027:     } else {
1.200     albertel 6028: 	&scantron_put_line($scanlines,$scan_data,$which,$line,$skip);
1.157     albertel 6029: 	&scantron_putfile($scanlines,$scan_data);
                   6030:     }
                   6031: }
                   6032: 
1.423     albertel 6033: =pod
                   6034: 
                   6035: =item reset_skipping_status
                   6036: 
1.424     albertel 6037:    Forgets the current set of remember skipped scanlines (and thus
                   6038:    reverts back to considering all lines in the
                   6039:    scantron_skipped_<filename> file)
                   6040: 
1.423     albertel 6041: =cut
                   6042: 
1.200     albertel 6043: sub reset_skipping_status {
                   6044:     my ($scanlines,$scan_data)=&scantron_getfile();
                   6045:     &scan_data($scan_data,'remember_skipping',undef,1);
                   6046:     &scantron_putfile(undef,$scan_data);
                   6047: }
                   6048: 
1.423     albertel 6049: =pod
                   6050: 
                   6051: =item start_skipping
                   6052: 
1.424     albertel 6053:    Marks a scanline to be skipped. 
                   6054: 
1.423     albertel 6055: =cut
                   6056: 
1.376     albertel 6057: sub start_skipping {
1.200     albertel 6058:     my ($scan_data,$i)=@_;
                   6059:     my %remembered=split(':',&scan_data($scan_data,'remember_skipping'));
1.376     albertel 6060:     if ($env{'form.scantron_options_redo'} =~ /^redo_/) {
                   6061: 	$remembered{$i}=2;
                   6062:     } else {
                   6063: 	$remembered{$i}=1;
                   6064:     }
1.200     albertel 6065:     &scan_data($scan_data,'remember_skipping',join(':',%remembered));
                   6066: }
                   6067: 
1.423     albertel 6068: =pod
                   6069: 
                   6070: =item should_be_skipped
                   6071: 
1.424     albertel 6072:    Checks whether a scanline should be skipped.
                   6073: 
1.423     albertel 6074: =cut
                   6075: 
1.200     albertel 6076: sub should_be_skipped {
1.376     albertel 6077:     my ($scanlines,$scan_data,$i)=@_;
1.257     albertel 6078:     if ($env{'form.scantron_options_redo'} !~ /^redo_/) {
1.200     albertel 6079: 	# not redoing old skips
1.376     albertel 6080: 	if ($scanlines->{'skipped'}[$i]) { return 1; }
1.200     albertel 6081: 	return 0;
                   6082:     }
                   6083:     my %remembered=split(':',&scan_data($scan_data,'remember_skipping'));
1.376     albertel 6084: 
                   6085:     if (exists($remembered{$i}) && $remembered{$i} != 2 ) {
                   6086: 	return 0;
                   6087:     }
1.200     albertel 6088:     return 1;
                   6089: }
                   6090: 
1.423     albertel 6091: =pod
                   6092: 
                   6093: =item remember_current_skipped
                   6094: 
1.424     albertel 6095:    Discovers what scanlines are in the scantron_skipped_<filename>
                   6096:    file and remembers them into scan_data for later use.
                   6097: 
1.423     albertel 6098: =cut
                   6099: 
1.200     albertel 6100: sub remember_current_skipped {
                   6101:     my ($scanlines,$scan_data)=&scantron_getfile();
                   6102:     my %to_remember;
                   6103:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
                   6104: 	if ($scanlines->{'skipped'}[$i]) {
                   6105: 	    $to_remember{$i}=1;
                   6106: 	}
                   6107:     }
1.376     albertel 6108: 
1.200     albertel 6109:     &scan_data($scan_data,'remember_skipping',join(':',%to_remember));
                   6110:     &scantron_putfile(undef,$scan_data);
                   6111: }
                   6112: 
1.423     albertel 6113: =pod
                   6114: 
                   6115: =item check_for_error
                   6116: 
1.424     albertel 6117:     Checks if there was an error when attempting to remove a specific
                   6118:     scantron_.. bubble sheet data file. Prints out an error if
                   6119:     something went wrong.
                   6120: 
1.423     albertel 6121: =cut
                   6122: 
1.200     albertel 6123: sub check_for_error {
                   6124:     my ($r,$result)=@_;
                   6125:     if ($result ne 'ok' && $result ne 'not_found' ) {
1.492     albertel 6126: 	$r->print(&mt("An error occurred ([_1]) when trying to remove the existing corrections.",$result));
1.200     albertel 6127:     }
                   6128: }
1.157     albertel 6129: 
1.423     albertel 6130: =pod
                   6131: 
                   6132: =item scantron_warning_screen
                   6133: 
1.424     albertel 6134:    Interstitial screen to make sure the operator has selected the
                   6135:    correct options before we start the validation phase.
                   6136: 
1.423     albertel 6137: =cut
                   6138: 
1.203     albertel 6139: sub scantron_warning_screen {
                   6140:     my ($button_text)=@_;
1.257     albertel 6141:     my $title=&Apache::lonnet::gettitle($env{'form.selectpage'});
1.284     albertel 6142:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.373     albertel 6143:     my $CODElist;
1.284     albertel 6144:     if ($scantron_config{'CODElocation'} &&
                   6145: 	$scantron_config{'CODEstart'} &&
                   6146: 	$scantron_config{'CODElength'}) {
                   6147: 	$CODElist=$env{'form.scantron_CODElist'};
1.398     albertel 6148: 	if ($env{'form.scantron_CODElist'} eq '') { $CODElist='<span class="LC_warning">None</span>'; }
1.284     albertel 6149: 	$CODElist=
1.492     albertel 6150: 	    '<tr><td><b>'.&mt('List of CODES to validate against:').'</b></td><td><tt>'.
1.373     albertel 6151: 	    $env{'form.scantron_CODElist'}.'</tt></td></tr>';
1.284     albertel 6152:     }
1.492     albertel 6153:     return ('
1.203     albertel 6154: <p>
1.492     albertel 6155: <span class="LC_warning">
                   6156: '.&mt('Please double check the information below before clicking on \'[_1]\'',&mt($button_text)).'</span>
1.203     albertel 6157: </p>
                   6158: <table>
1.492     albertel 6159: <tr><td><b>'.&mt('Sequence to be Graded:').'</b></td><td>'.$title.'</td></tr>
                   6160: <tr><td><b>'.&mt('Data File that will be used:').'</b></td><td><tt>'.$env{'form.scantron_selectfile'}.'</tt></td></tr>
                   6161: '.$CODElist.'
1.203     albertel 6162: </table>
                   6163: <br />
1.492     albertel 6164: <p> '.&mt('If this information is correct, please click on \'[_1]\'.',&mt($button_text)).'</p>
                   6165: <p> '.&mt('If something is incorrect, please click the \'Grading Menu\' button to start over.').'</p>
1.203     albertel 6166: 
                   6167: <br />
1.492     albertel 6168: ');
1.203     albertel 6169: }
                   6170: 
1.423     albertel 6171: =pod
                   6172: 
                   6173: =item scantron_do_warning
                   6174: 
1.424     albertel 6175:    Check if the operator has picked something for all required
                   6176:    fields. Error out if something is missing.
                   6177: 
1.423     albertel 6178: =cut
                   6179: 
1.203     albertel 6180: sub scantron_do_warning {
1.608     www      6181:     my ($r,$symb)=@_;
1.203     albertel 6182:     if (!$symb) {return '';}
1.324     albertel 6183:     my $default_form_data=&defaultFormData($symb);
1.203     albertel 6184:     $r->print(&scantron_form_start().$default_form_data);
1.257     albertel 6185:     if ( $env{'form.selectpage'} eq '' ||
                   6186: 	 $env{'form.scantron_selectfile'} eq '' ||
                   6187: 	 $env{'form.scantron_format'} eq '' ) {
1.492     albertel 6188: 	$r->print("<p>".&mt('You have forgetten to specify some information. Please go Back and try again.')."</p>");
1.257     albertel 6189: 	if ( $env{'form.selectpage'} eq '') {
1.492     albertel 6190: 	    $r->print('<p><span class="LC_error">'.&mt('You have not selected a Sequence to grade').'</span></p>');
1.237     albertel 6191: 	} 
1.257     albertel 6192: 	if ( $env{'form.scantron_selectfile'} eq '') {
1.492     albertel 6193: 	    $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 6194: 	} 
1.257     albertel 6195: 	if ( $env{'form.scantron_format'} eq '') {
1.492     albertel 6196: 	    $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 6197: 	} 
                   6198:     } else {
1.265     www      6199: 	my $warning=&scantron_warning_screen('Grading: Validate Records');
1.492     albertel 6200: 	$r->print('
                   6201: '.$warning.'
                   6202: <input type="submit" name="submit" value="'.&mt('Grading: Validate Records').'" />
1.203     albertel 6203: <input type="hidden" name="command" value="scantron_validate" />
1.492     albertel 6204: ');
1.237     albertel 6205:     }
1.614     www      6206:     $r->print("</form><br />");
1.203     albertel 6207:     return '';
                   6208: }
                   6209: 
1.423     albertel 6210: =pod
                   6211: 
                   6212: =item scantron_form_start
                   6213: 
1.424     albertel 6214:     html hidden input for remembering all selected grading options
                   6215: 
1.423     albertel 6216: =cut
                   6217: 
1.203     albertel 6218: sub scantron_form_start {
                   6219:     my ($max_bubble)=@_;
                   6220:     my $result= <<SCANTRONFORM;
                   6221: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantronupload">
1.257     albertel 6222:   <input type="hidden" name="selectpage" value="$env{'form.selectpage'}" />
                   6223:   <input type="hidden" name="scantron_format" value="$env{'form.scantron_format'}" />
                   6224:   <input type="hidden" name="scantron_selectfile" value="$env{'form.scantron_selectfile'}" />
1.218     albertel 6225:   <input type="hidden" name="scantron_maxbubble" value="$max_bubble" />
1.257     albertel 6226:   <input type="hidden" name="scantron_CODElist" value="$env{'form.scantron_CODElist'}" />
                   6227:   <input type="hidden" name="scantron_CODEunique" value="$env{'form.scantron_CODEunique'}" />
                   6228:   <input type="hidden" name="scantron_options_redo" value="$env{'form.scantron_options_redo'}" />
                   6229:   <input type="hidden" name="scantron_options_ignore" value="$env{'form.scantron_options_ignore'}" />
1.331     albertel 6230:   <input type="hidden" name="scantron_options_hidden" value="$env{'form.scantron_options_hidden'}" />
1.203     albertel 6231: SCANTRONFORM
1.447     foxr     6232: 
                   6233:   my $line = 0;
                   6234:     while (defined($env{"form.scantron.bubblelines.$line"})) {
                   6235:        my $chunk =
                   6236: 	   '<input type="hidden" name="scantron.bubblelines.'.$line.'" value="'.$env{"form.scantron.bubblelines.$line"}.'" />'."\n";
1.448     foxr     6237:        $chunk .=
                   6238: 	   '<input type="hidden" name="scantron.first_bubble_line.'.$line.'" value="'.$env{"form.scantron.first_bubble_line.$line"}.'" />'."\n";
1.503     raeburn  6239:        $chunk .= 
                   6240:            '<input type="hidden" name="scantron.sub_bubblelines.'.$line.'" value="'.$env{"form.scantron.sub_bubblelines.$line"}.'" />'."\n";
1.504     raeburn  6241:        $chunk .=
                   6242:            '<input type="hidden" name="scantron.responsetype.'.$line.'" value="'.$env{"form.scantron.responsetype.$line"}.'" />'."\n";
1.447     foxr     6243:        $result .= $chunk;
                   6244:        $line++;
                   6245:    }
1.203     albertel 6246:     return $result;
                   6247: }
                   6248: 
1.423     albertel 6249: =pod
                   6250: 
                   6251: =item scantron_validate_file
                   6252: 
1.424     albertel 6253:     Dispatch routine for doing validation of a bubble sheet data file.
                   6254: 
                   6255:     Also processes any necessary information resets that need to
                   6256:     occur before validation begins (ignore previous corrections,
                   6257:     restarting the skipped records processing)
                   6258: 
1.423     albertel 6259: =cut
                   6260: 
1.157     albertel 6261: sub scantron_validate_file {
1.608     www      6262:     my ($r,$symb) = @_;
1.157     albertel 6263:     if (!$symb) {return '';}
1.324     albertel 6264:     my $default_form_data=&defaultFormData($symb);
1.200     albertel 6265:     
                   6266:     # do the detection of only doing skipped records first befroe we delete
1.424     albertel 6267:     # them when doing the corrections reset
1.257     albertel 6268:     if ($env{'form.scantron_options_redo'} ne 'redo_skipped_ready') {
1.200     albertel 6269: 	&reset_skipping_status();
                   6270:     }
1.257     albertel 6271:     if ($env{'form.scantron_options_redo'} eq 'redo_skipped') {
1.200     albertel 6272: 	&remember_current_skipped();
1.257     albertel 6273: 	$env{'form.scantron_options_redo'}='redo_skipped_ready';
1.200     albertel 6274:     }
                   6275: 
1.257     albertel 6276:     if ($env{'form.scantron_options_ignore'} eq 'ignore_corrections') {
1.200     albertel 6277: 	&check_for_error($r,&scantron_remove_file('corrected'));
                   6278: 	&check_for_error($r,&scantron_remove_file('skipped'));
                   6279: 	&check_for_error($r,&scantron_remove_scan_data());
1.257     albertel 6280: 	$env{'form.scantron_options_ignore'}='done';
1.192     albertel 6281:     }
1.200     albertel 6282: 
1.257     albertel 6283:     if ($env{'form.scantron_corrections'}) {
1.157     albertel 6284: 	&scantron_process_corrections($r);
                   6285:     }
1.503     raeburn  6286:     $r->print('<p>'.&mt('Gathering necessary information.').'</p>');$r->rflush();
1.157     albertel 6287:     #get the student pick code ready
                   6288:     $r->print(&Apache::loncommon::studentbrowser_javascript());
1.582     raeburn  6289:     my $nav_error;
                   6290:     my $max_bubble=&scantron_get_maxbubble(\$nav_error);
                   6291:     if ($nav_error) {
                   6292:         $r->print(&navmap_errormsg());
                   6293:         return '';
                   6294:     }
1.203     albertel 6295:     my $result=&scantron_form_start($max_bubble).$default_form_data;
1.157     albertel 6296:     $r->print($result);
                   6297:     
1.334     albertel 6298:     my @validate_phases=( 'sequence',
                   6299: 			  'ID',
1.157     albertel 6300: 			  'CODE',
                   6301: 			  'doublebubble',
                   6302: 			  'missingbubbles');
1.257     albertel 6303:     if (!$env{'form.validatepass'}) {
                   6304: 	$env{'form.validatepass'} = 0;
1.157     albertel 6305:     }
1.257     albertel 6306:     my $currentphase=$env{'form.validatepass'};
1.157     albertel 6307: 
1.448     foxr     6308: 
1.157     albertel 6309:     my $stop=0;
                   6310:     while (!$stop && $currentphase < scalar(@validate_phases)) {
1.503     raeburn  6311: 	$r->print(&mt('Validating '.$validate_phases[$currentphase]).'<br />');
1.157     albertel 6312: 	$r->rflush();
                   6313: 	my $which="scantron_validate_".$validate_phases[$currentphase];
                   6314: 	{
                   6315: 	    no strict 'refs';
                   6316: 	    ($stop,$currentphase)=&$which($r,$currentphase);
                   6317: 	}
                   6318:     }
                   6319:     if (!$stop) {
1.203     albertel 6320: 	my $warning=&scantron_warning_screen('Start Grading');
1.542     raeburn  6321: 	$r->print(&mt('Validation process complete.').'<br />'.
                   6322:                   $warning.
                   6323:                   &mt('Perform verification for each student after storage of submissions?').
                   6324:                   '&nbsp;<span class="LC_nobreak"><label>'.
                   6325:                   '<input type="radio" name="verifyrecord" value="1" />'.&mt('Yes').'</label>'.
                   6326:                   ('&nbsp;'x3).'<label>'.
                   6327:                   '<input type="radio" name="verifyrecord" value="0" checked="checked" />'.&mt('No').
                   6328:                   '</label></span><br />'.
                   6329:                   &mt('Grading will take longer if you use verification.').'<br />'.
1.572     www      6330:                   &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  6331:                   '<input type="submit" name="submit" value="'.&mt('Start Grading').'" />'.
                   6332:                   '<input type="hidden" name="command" value="scantron_process" />'."\n");
1.157     albertel 6333:     } else {
                   6334: 	$r->print('<input type="hidden" name="command" value="scantron_validate" />');
                   6335: 	$r->print("<input type='hidden' name='validatepass' value='".$currentphase."' />");
                   6336:     }
                   6337:     if ($stop) {
1.334     albertel 6338: 	if ($validate_phases[$currentphase] eq 'sequence') {
1.539     riegler  6339: 	    $r->print('<input type="submit" name="submit" value="'.&mt('Ignore').' &rarr; " />');
1.492     albertel 6340: 	    $r->print(' '.&mt('this error').' <br />');
1.334     albertel 6341: 
1.492     albertel 6342: 	    $r->print(" <p>".&mt("Or click the 'Grading Menu' button to start over.")."</p>");
1.334     albertel 6343: 	} else {
1.503     raeburn  6344:             if ($validate_phases[$currentphase] eq 'doublebubble' || $validate_phases[$currentphase] eq 'missingbubbles') {
1.539     riegler  6345: 	        $r->print('<input type="button" name="submitbutton" value="'.&mt('Continue').' &rarr;" onclick="javascript:verify_bubble_radio(this.form)" />');
1.503     raeburn  6346:             } else {
1.539     riegler  6347:                 $r->print('<input type="submit" name="submit" value="'.&mt('Continue').' &rarr;" />');
1.503     raeburn  6348:             }
1.492     albertel 6349: 	    $r->print(' '.&mt('using corrected info').' <br />');
                   6350: 	    $r->print("<input type='submit' value='".&mt("Skip")."' name='scantron_skip_record' />");
                   6351: 	    $r->print(" ".&mt("this scanline saving it for later."));
1.334     albertel 6352: 	}
1.157     albertel 6353:     }
1.614     www      6354:     $r->print(" </form><br />");
1.157     albertel 6355:     return '';
                   6356: }
                   6357: 
1.423     albertel 6358: 
                   6359: =pod
                   6360: 
                   6361: =item scantron_remove_file
                   6362: 
1.424     albertel 6363:    Removes the requested bubble sheet data file, makes sure that
                   6364:    scantron_original_<filename> is never removed
                   6365: 
                   6366: 
1.423     albertel 6367: =cut
                   6368: 
1.200     albertel 6369: sub scantron_remove_file {
1.192     albertel 6370:     my ($which)=@_;
1.257     albertel 6371:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   6372:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.192     albertel 6373:     my $file='scantron_';
1.200     albertel 6374:     if ($which eq 'corrected' || $which eq 'skipped') {
                   6375: 	$file.=$which.'_';
1.192     albertel 6376:     } else {
                   6377: 	return 'refused';
                   6378:     }
1.257     albertel 6379:     $file.=$env{'form.scantron_selectfile'};
1.200     albertel 6380:     return &Apache::lonnet::removeuserfile($cname,$cdom,$file);
                   6381: }
                   6382: 
1.423     albertel 6383: 
                   6384: =pod
                   6385: 
                   6386: =item scantron_remove_scan_data
                   6387: 
1.424     albertel 6388:    Removes all scan_data correction for the requested bubble sheet
                   6389:    data file.  (In the case that both the are doing skipped records we need
                   6390:    to remember the old skipped lines for the time being so that element
                   6391:    persists for a while.)
                   6392: 
1.423     albertel 6393: =cut
                   6394: 
1.200     albertel 6395: sub scantron_remove_scan_data {
1.257     albertel 6396:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   6397:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.192     albertel 6398:     my @keys=&Apache::lonnet::getkeys('nohist_scantrondata',$cdom,$cname);
                   6399:     my @todelete;
1.257     albertel 6400:     my $filename=$env{'form.scantron_selectfile'};
1.192     albertel 6401:     foreach my $key (@keys) {
                   6402: 	if ($key=~/^\Q$filename\E_/) {
1.257     albertel 6403: 	    if ($env{'form.scantron_options_redo'} eq 'redo_skipped_ready' &&
1.200     albertel 6404: 		$key=~/remember_skipping/) {
                   6405: 		next;
                   6406: 	    }
1.192     albertel 6407: 	    push(@todelete,$key);
                   6408: 	}
                   6409:     }
1.200     albertel 6410:     my $result;
1.192     albertel 6411:     if (@todelete) {
1.491     albertel 6412: 	$result = &Apache::lonnet::del('nohist_scantrondata',
                   6413: 				       \@todelete,$cdom,$cname);
                   6414:     } else {
                   6415: 	$result = 'ok';
1.192     albertel 6416:     }
                   6417:     return $result;
                   6418: }
                   6419: 
1.423     albertel 6420: 
                   6421: =pod
                   6422: 
                   6423: =item scantron_getfile
                   6424: 
1.424     albertel 6425:     Fetches the requested bubble sheet data file (all 3 versions), and
                   6426:     the scan_data hash
                   6427:   
                   6428:   Arguments:
                   6429:     None
                   6430: 
                   6431:   Returns:
                   6432:     2 hash references
                   6433: 
                   6434:      - first one has 
                   6435:          orig      -
                   6436:          corrected -
                   6437:          skipped   -  each of which points to an array ref of the specified
                   6438:                       file broken up into individual lines
                   6439:          count     - number of scanlines
                   6440:  
                   6441:      - second is the scan_data hash possible keys are
1.425     albertel 6442:        ($number refers to scanline numbered $number and thus the key affects
                   6443:         only that scanline
                   6444:         $bubline refers to the specific bubble line element and the aspects
                   6445:         refers to that specific bubble line element)
                   6446: 
                   6447:        $number.user - username:domain to use
                   6448:        $number.CODE_ignore_dup 
                   6449:                     - ignore the duplicate CODE error 
                   6450:        $number.useCODE
                   6451:                     - use the CODE in the scanline as is
                   6452:        $number.no_bubble.$bubline
                   6453:                     - it is valid that there is no bubbled in bubble
                   6454:                       at $number $bubline
                   6455:        remember_skipping
                   6456:                     - a frozen hash containing keys of $number and values
                   6457:                       of either 
                   6458:                         1 - we are on a 'do skipped records pass' and plan
                   6459:                             on processing this line
                   6460:                         2 - we are on a 'do skipped records pass' and this
                   6461:                             scanline has been marked to skip yet again
1.424     albertel 6462: 
1.423     albertel 6463: =cut
                   6464: 
1.157     albertel 6465: sub scantron_getfile {
1.200     albertel 6466:     #FIXME really would prefer a scantron directory
1.257     albertel 6467:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   6468:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.157     albertel 6469:     my $lines;
                   6470:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
1.257     albertel 6471: 		       'scantron_orig_'.$env{'form.scantron_selectfile'});
1.157     albertel 6472:     my %scanlines;
                   6473:     $scanlines{'orig'}=[(split("\n",$lines,-1))];
                   6474:     my $temp=$scanlines{'orig'};
                   6475:     $scanlines{'count'}=$#$temp;
                   6476: 
                   6477:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
1.257     albertel 6478: 		       'scantron_corrected_'.$env{'form.scantron_selectfile'});
1.157     albertel 6479:     if ($lines eq '-1') {
                   6480: 	$scanlines{'corrected'}=[];
                   6481:     } else {
                   6482: 	$scanlines{'corrected'}=[(split("\n",$lines,-1))];
                   6483:     }
                   6484:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
1.257     albertel 6485: 		       'scantron_skipped_'.$env{'form.scantron_selectfile'});
1.157     albertel 6486:     if ($lines eq '-1') {
                   6487: 	$scanlines{'skipped'}=[];
                   6488:     } else {
                   6489: 	$scanlines{'skipped'}=[(split("\n",$lines,-1))];
                   6490:     }
1.175     albertel 6491:     my @tmp=&Apache::lonnet::dump('nohist_scantrondata',$cdom,$cname);
1.157     albertel 6492:     if ($tmp[0] =~ /^(error:|no_such_host)/) { @tmp=(); }
                   6493:     my %scan_data = @tmp;
                   6494:     return (\%scanlines,\%scan_data);
                   6495: }
                   6496: 
1.423     albertel 6497: =pod
                   6498: 
                   6499: =item lonnet_putfile
                   6500: 
1.424     albertel 6501:    Wrapper routine to call &Apache::lonnet::finishuserfileupload
                   6502: 
                   6503:  Arguments:
                   6504:    $contents - data to store
                   6505:    $filename - filename to store $contents into
                   6506: 
                   6507:  Returns:
                   6508:    result value from &Apache::lonnet::finishuserfileupload
                   6509: 
1.423     albertel 6510: =cut
                   6511: 
1.157     albertel 6512: sub lonnet_putfile {
                   6513:     my ($contents,$filename)=@_;
1.257     albertel 6514:     my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   6515:     my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   6516:     $env{'form.sillywaytopassafilearound'}=$contents;
1.275     albertel 6517:     &Apache::lonnet::finishuserfileupload($docuname,$docudom,'sillywaytopassafilearound',$filename);
1.157     albertel 6518: 
                   6519: }
                   6520: 
1.423     albertel 6521: =pod
                   6522: 
                   6523: =item scantron_putfile
                   6524: 
1.424     albertel 6525:     Stores the current version of the bubble sheet data files, and the
                   6526:     scan_data hash. (Does not modify the original version only the
                   6527:     corrected and skipped versions.
                   6528: 
                   6529:  Arguments:
                   6530:     $scanlines - hash ref that looks like the first return value from
                   6531:                  &scantron_getfile()
                   6532:     $scan_data - hash ref that looks like the second return value from
                   6533:                  &scantron_getfile()
                   6534: 
1.423     albertel 6535: =cut
                   6536: 
1.157     albertel 6537: sub scantron_putfile {
                   6538:     my ($scanlines,$scan_data) = @_;
1.200     albertel 6539:     #FIXME really would prefer a scantron directory
1.257     albertel 6540:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   6541:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.200     albertel 6542:     if ($scanlines) {
                   6543: 	my $prefix='scantron_';
1.157     albertel 6544: # no need to update orig, shouldn't change
                   6545: #   &lonnet_putfile(join("\n",@{$scanlines->{'orig'}}),$prefix.'orig_'.
1.257     albertel 6546: #		    $env{'form.scantron_selectfile'});
1.200     albertel 6547: 	&lonnet_putfile(join("\n",@{$scanlines->{'corrected'}}),
                   6548: 			$prefix.'corrected_'.
1.257     albertel 6549: 			$env{'form.scantron_selectfile'});
1.200     albertel 6550: 	&lonnet_putfile(join("\n",@{$scanlines->{'skipped'}}),
                   6551: 			$prefix.'skipped_'.
1.257     albertel 6552: 			$env{'form.scantron_selectfile'});
1.200     albertel 6553:     }
1.175     albertel 6554:     &Apache::lonnet::put('nohist_scantrondata',$scan_data,$cdom,$cname);
1.157     albertel 6555: }
                   6556: 
1.423     albertel 6557: =pod
                   6558: 
                   6559: =item scantron_get_line
                   6560: 
1.424     albertel 6561:    Returns the correct version of the scanline
                   6562: 
                   6563:  Arguments:
                   6564:     $scanlines - hash ref that looks like the first return value from
                   6565:                  &scantron_getfile()
                   6566:     $scan_data - hash ref that looks like the second return value from
                   6567:                  &scantron_getfile()
                   6568:     $i         - number of the requested line (starts at 0)
                   6569: 
                   6570:  Returns:
                   6571:    A scanline, (either the original or the corrected one if it
                   6572:    exists), or undef if the requested scanline should be
                   6573:    skipped. (Either because it's an skipped scanline, or it's an
                   6574:    unskipped scanline and we are not doing a 'do skipped scanlines'
                   6575:    pass.
                   6576: 
1.423     albertel 6577: =cut
                   6578: 
1.157     albertel 6579: sub scantron_get_line {
1.200     albertel 6580:     my ($scanlines,$scan_data,$i)=@_;
1.376     albertel 6581:     if (&should_be_skipped($scanlines,$scan_data,$i)) { return undef; }
                   6582:     #if ($scanlines->{'skipped'}[$i]) { return undef; }
1.157     albertel 6583:     if ($scanlines->{'corrected'}[$i]) {return $scanlines->{'corrected'}[$i];}
                   6584:     return $scanlines->{'orig'}[$i]; 
                   6585: }
                   6586: 
1.423     albertel 6587: =pod
                   6588: 
                   6589: =item scantron_todo_count
                   6590: 
1.424     albertel 6591:     Counts the number of scanlines that need processing.
                   6592: 
                   6593:  Arguments:
                   6594:     $scanlines - hash ref that looks like the first return value from
                   6595:                  &scantron_getfile()
                   6596:     $scan_data - hash ref that looks like the second return value from
                   6597:                  &scantron_getfile()
                   6598: 
                   6599:  Returns:
                   6600:     $count - number of scanlines to process
                   6601: 
1.423     albertel 6602: =cut
                   6603: 
1.200     albertel 6604: sub get_todo_count {
                   6605:     my ($scanlines,$scan_data)=@_;
                   6606:     my $count=0;
                   6607:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
                   6608: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
                   6609: 	if ($line=~/^[\s\cz]*$/) { next; }
                   6610: 	$count++;
                   6611:     }
                   6612:     return $count;
                   6613: }
                   6614: 
1.423     albertel 6615: =pod
                   6616: 
                   6617: =item scantron_put_line
                   6618: 
1.424     albertel 6619:     Updates the 'corrected' or 'skipped' versions of the bubble sheet
                   6620:     data file.
                   6621: 
                   6622:  Arguments:
                   6623:     $scanlines - hash ref that looks like the first return value from
                   6624:                  &scantron_getfile()
                   6625:     $scan_data - hash ref that looks like the second return value from
                   6626:                  &scantron_getfile()
                   6627:     $i         - line number to update
                   6628:     $newline   - contents of the updated scanline
                   6629:     $skip      - if true make the line for skipping and update the
                   6630:                  'skipped' file
                   6631: 
1.423     albertel 6632: =cut
                   6633: 
1.157     albertel 6634: sub scantron_put_line {
1.200     albertel 6635:     my ($scanlines,$scan_data,$i,$newline,$skip)=@_;
1.157     albertel 6636:     if ($skip) {
                   6637: 	$scanlines->{'skipped'}[$i]=$newline;
1.376     albertel 6638: 	&start_skipping($scan_data,$i);
1.157     albertel 6639: 	return;
                   6640:     }
                   6641:     $scanlines->{'corrected'}[$i]=$newline;
                   6642: }
                   6643: 
1.423     albertel 6644: =pod
                   6645: 
                   6646: =item scantron_clear_skip
                   6647: 
1.424     albertel 6648:    Remove a line from the 'skipped' file
                   6649: 
                   6650:  Arguments:
                   6651:     $scanlines - hash ref that looks like the first return value from
                   6652:                  &scantron_getfile()
                   6653:     $scan_data - hash ref that looks like the second return value from
                   6654:                  &scantron_getfile()
                   6655:     $i         - line number to update
                   6656: 
1.423     albertel 6657: =cut
                   6658: 
1.376     albertel 6659: sub scantron_clear_skip {
                   6660:     my ($scanlines,$scan_data,$i)=@_;
                   6661:     if (exists($scanlines->{'skipped'}[$i])) {
                   6662: 	undef($scanlines->{'skipped'}[$i]);
                   6663: 	return 1;
                   6664:     }
                   6665:     return 0;
                   6666: }
                   6667: 
1.423     albertel 6668: =pod
                   6669: 
                   6670: =item scantron_filter_not_exam
                   6671: 
1.424     albertel 6672:    Filter routine used by &Apache::lonnavmaps::retrieveResources(), to
                   6673:    filter out resources that are not marked as 'exam' mode
                   6674: 
1.423     albertel 6675: =cut
                   6676: 
1.334     albertel 6677: sub scantron_filter_not_exam {
                   6678:     my ($curres)=@_;
                   6679:     
                   6680:     if (ref($curres) && $curres->is_problem() && !$curres->is_exam()) {
                   6681: 	# if the user has asked to not have either hidden
                   6682: 	# or 'randomout' controlled resources to be graded
                   6683: 	# don't include them
                   6684: 	if ($env{'form.scantron_options_hidden'} eq 'ignore_hidden'
                   6685: 	    && $curres->randomout) {
                   6686: 	    return 0;
                   6687: 	}
                   6688: 	return 1;
                   6689:     }
                   6690:     return 0;
                   6691: }
                   6692: 
1.423     albertel 6693: =pod
                   6694: 
                   6695: =item scantron_validate_sequence
                   6696: 
1.424     albertel 6697:     Validates the selected sequence, checking for resource that are
                   6698:     not set to exam mode.
                   6699: 
1.423     albertel 6700: =cut
                   6701: 
1.334     albertel 6702: sub scantron_validate_sequence {
                   6703:     my ($r,$currentphase) = @_;
                   6704: 
                   6705:     my $navmap=Apache::lonnavmaps::navmap->new();
1.582     raeburn  6706:     unless (ref($navmap)) {
                   6707:         $r->print(&navmap_errormsg());
                   6708:         return (1,$currentphase);
                   6709:     }
1.334     albertel 6710:     my (undef,undef,$sequence)=
                   6711: 	&Apache::lonnet::decode_symb($env{'form.selectpage'});
                   6712: 
                   6713:     my $map=$navmap->getResourceByUrl($sequence);
                   6714: 
                   6715:     $r->print('<input type="hidden" name="validate_sequence_exam"
                   6716:                                     value="ignore" />');
                   6717:     if ($env{'form.validate_sequence_exam'} ne 'ignore') {
                   6718: 	my @resources=
                   6719: 	    $navmap->retrieveResources($map,\&scantron_filter_not_exam,1,0);
                   6720: 	if (@resources) {
1.357     banghart 6721: 	    $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 6722: 	    return (1,$currentphase);
                   6723: 	}
                   6724:     }
                   6725: 
                   6726:     return (0,$currentphase+1);
                   6727: }
                   6728: 
1.423     albertel 6729: 
                   6730: 
1.157     albertel 6731: sub scantron_validate_ID {
                   6732:     my ($r,$currentphase) = @_;
                   6733:     
                   6734:     #get student info
                   6735:     my $classlist=&Apache::loncoursedata::get_classlist();
                   6736:     my %idmap=&username_to_idmap($classlist);
                   6737: 
                   6738:     #get scantron line setup
1.257     albertel 6739:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.157     albertel 6740:     my ($scanlines,$scan_data)=&scantron_getfile();
1.582     raeburn  6741: 
                   6742:     my $nav_error;
                   6743:     &scantron_get_maxbubble(\$nav_error); # parse needs the bubble_lines.. array.
                   6744:     if ($nav_error) {
                   6745:         $r->print(&navmap_errormsg());
                   6746:         return(1,$currentphase);
                   6747:     }
1.157     albertel 6748: 
                   6749:     my %found=('ids'=>{},'usernames'=>{});
                   6750:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
1.200     albertel 6751: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.157     albertel 6752: 	if ($line=~/^[\s\cz]*$/) { next; }
                   6753: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
                   6754: 						 $scan_data);
                   6755: 	my $id=$$scan_record{'scantron.ID'};
                   6756: 	my $found;
                   6757: 	foreach my $checkid (keys(%idmap)) {
                   6758: 	    if (lc($checkid) eq lc($id)) { $found=$checkid;last; }
                   6759: 	}
                   6760: 	if ($found) {
                   6761: 	    my $username=$idmap{$found};
                   6762: 	    if ($found{'ids'}{$found}) {
                   6763: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
                   6764: 					 $line,'duplicateID',$found);
1.194     albertel 6765: 		return(1,$currentphase);
1.157     albertel 6766: 	    } elsif ($found{'usernames'}{$username}) {
                   6767: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
                   6768: 					 $line,'duplicateID',$username);
1.194     albertel 6769: 		return(1,$currentphase);
1.157     albertel 6770: 	    }
1.186     albertel 6771: 	    #FIXME store away line we previously saw the ID on to use above
1.157     albertel 6772: 	    $found{'ids'}{$found}++;
                   6773: 	    $found{'usernames'}{$username}++;
                   6774: 	} else {
                   6775: 	    if ($id =~ /^\s*$/) {
1.158     albertel 6776: 		my $username=&scan_data($scan_data,"$i.user");
1.157     albertel 6777: 		if (defined($username) && $found{'usernames'}{$username}) {
                   6778: 		    &scantron_get_correction($r,$i,$scan_record,
                   6779: 					     \%scantron_config,
                   6780: 					     $line,'duplicateID',$username);
1.194     albertel 6781: 		    return(1,$currentphase);
1.157     albertel 6782: 		} elsif (!defined($username)) {
                   6783: 		    &scantron_get_correction($r,$i,$scan_record,
                   6784: 					     \%scantron_config,
                   6785: 					     $line,'incorrectID');
1.194     albertel 6786: 		    return(1,$currentphase);
1.157     albertel 6787: 		}
                   6788: 		$found{'usernames'}{$username}++;
                   6789: 	    } else {
                   6790: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
                   6791: 					 $line,'incorrectID');
1.194     albertel 6792: 		return(1,$currentphase);
1.157     albertel 6793: 	    }
                   6794: 	}
                   6795:     }
                   6796: 
                   6797:     return (0,$currentphase+1);
                   6798: }
                   6799: 
1.423     albertel 6800: 
1.157     albertel 6801: sub scantron_get_correction {
                   6802:     my ($r,$i,$scan_record,$scan_config,$line,$error,$arg)=@_;
1.454     banghart 6803: #FIXME in the case of a duplicated ID the previous line, probably need
1.157     albertel 6804: #to show both the current line and the previous one and allow skipping
                   6805: #the previous one or the current one
                   6806: 
1.333     albertel 6807:     if ( $$scan_record{'scantron.PaperID'} =~ /\S/) {
1.492     albertel 6808: 	$r->print("<p>".&mt("<b>An error was detected ($error)</b>".
                   6809: 			    " for PaperID <tt>[_1]</tt>",
                   6810: 			    $$scan_record{'scantron.PaperID'})."</p> \n");
1.157     albertel 6811:     } else {
1.492     albertel 6812: 	$r->print("<p>".&mt("<b>An error was detected ($error)</b>".
                   6813: 			    " in scanline [_1] <pre>[_2]</pre>",
                   6814: 			    $i,$line)."</p> \n");
                   6815:     }
                   6816:     my $message="<p>".&mt("The ID on the form is  <tt>[_1]</tt><br />".
                   6817: 			  "The name on the paper is [_2],[_3]",
                   6818: 			  $$scan_record{'scantron.ID'},
                   6819: 			  $$scan_record{'scantron.LastName'},
                   6820: 			  $$scan_record{'scantron.FirstName'})."</p>";
1.242     albertel 6821: 
1.157     albertel 6822:     $r->print('<input type="hidden" name="scantron_corrections" value="'.$error.'" />'."\n");
                   6823:     $r->print('<input type="hidden" name="scantron_line" value="'.$i.'" />'."\n");
1.503     raeburn  6824:                            # Array populated for doublebubble or
                   6825:     my @lines_to_correct;  # missingbubble errors to build javascript
                   6826:                            # to validate radio button checking   
                   6827: 
1.157     albertel 6828:     if ($error =~ /ID$/) {
1.186     albertel 6829: 	if ($error eq 'incorrectID') {
1.492     albertel 6830: 	    $r->print("<p>".&mt("The encoded ID is not in the classlist").
                   6831: 		      "</p>\n");
1.157     albertel 6832: 	} elsif ($error eq 'duplicateID') {
1.492     albertel 6833: 	    $r->print("<p>".&mt("The encoded ID has also been used by a previous paper [_1]",$arg)."</p>\n");
1.157     albertel 6834: 	}
1.242     albertel 6835: 	$r->print($message);
1.492     albertel 6836: 	$r->print("<p>".&mt("How should I handle this?")." <br /> \n");
1.157     albertel 6837: 	$r->print("\n<ul><li> ");
                   6838: 	#FIXME it would be nice if this sent back the user ID and
                   6839: 	#could do partial userID matches
                   6840: 	$r->print(&Apache::loncommon::selectstudent_link('scantronupload',
                   6841: 				       'scantron_username','scantron_domain'));
                   6842: 	$r->print(": <input type='text' name='scantron_username' value='' />");
                   6843: 	$r->print("\n@".
1.257     albertel 6844: 		 &Apache::loncommon::select_dom_form($env{'request.role.domain'},'scantron_domain'));
1.157     albertel 6845: 
                   6846: 	$r->print('</li>');
1.186     albertel 6847:     } elsif ($error =~ /CODE$/) {
                   6848: 	if ($error eq 'incorrectCODE') {
1.492     albertel 6849: 	    $r->print("<p>".&mt("The encoded CODE is not in the list of possible CODEs.")."</p>\n");
1.186     albertel 6850: 	} elsif ($error eq 'duplicateCODE') {
1.492     albertel 6851: 	    $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 6852: 	}
1.492     albertel 6853: 	$r->print("<p>".&mt("The CODE on the form is  <tt>'[_1]'</tt>",
                   6854: 			    $$scan_record{'scantron.CODE'})."<br />\n");
1.242     albertel 6855: 	$r->print($message);
1.492     albertel 6856: 	$r->print("<p>".&mt("How should I handle this?")." <br /> \n");
1.187     albertel 6857: 	$r->print("\n<br /> ");
1.194     albertel 6858: 	my $i=0;
1.273     albertel 6859: 	if ($error eq 'incorrectCODE' 
                   6860: 	    && $$scan_record{'scantron.CODE'}=~/\S/ ) {
1.194     albertel 6861: 	    my ($max,$closest)=&scantron_get_closely_matching_CODEs($arg,$$scan_record{'scantron.CODE'});
1.278     albertel 6862: 	    if ($closest > 0) {
                   6863: 		foreach my $testcode (@{$closest}) {
                   6864: 		    my $checked='';
1.569     bisitz   6865: 		    if (!$i) { $checked=' checked="checked"'; }
1.492     albertel 6866: 		    $r->print("
                   6867:    <label>
1.569     bisitz   6868:        <input type='radio' name='scantron_CODE_resolution' value='use_closest_$i'$checked />
1.492     albertel 6869:        ".&mt("Use the similar CODE [_1] instead.",
                   6870: 	    "<b><tt>".$testcode."</tt></b>")."
                   6871:     </label>
                   6872:     <input type='hidden' name='scantron_CODE_closest_$i' value='$testcode' />");
1.278     albertel 6873: 		    $r->print("\n<br />");
                   6874: 		    $i++;
                   6875: 		}
1.194     albertel 6876: 	    }
                   6877: 	}
1.273     albertel 6878: 	if ($$scan_record{'scantron.CODE'}=~/\S/ ) {
1.569     bisitz   6879: 	    my $checked; if (!$i) { $checked=' checked="checked"'; }
1.492     albertel 6880: 	    $r->print("
                   6881:     <label>
1.569     bisitz   6882:         <input type='radio' name='scantron_CODE_resolution' value='use_unfound'$checked />
1.492     albertel 6883:        ".&mt("Use the CODE [_1] that is was on the paper, ignoring the error.",
                   6884: 	     "<b><tt>".$$scan_record{'scantron.CODE'}."</tt></b>")."
                   6885:     </label>");
1.273     albertel 6886: 	    $r->print("\n<br />");
                   6887: 	}
1.194     albertel 6888: 
1.597     wenzelju 6889: 	$r->print(&Apache::lonhtmlcommon::scripttag(<<ENDSCRIPT));
1.188     albertel 6890: function change_radio(field) {
1.190     albertel 6891:     var slct=document.scantronupload.scantron_CODE_resolution;
1.188     albertel 6892:     var i;
                   6893:     for (i=0;i<slct.length;i++) {
                   6894:         if (slct[i].value==field) { slct[i].checked=true; }
                   6895:     }
                   6896: }
                   6897: ENDSCRIPT
1.187     albertel 6898: 	my $href="/adm/pickcode?".
1.359     www      6899: 	   "form=".&escape("scantronupload").
                   6900: 	   "&scantron_format=".&escape($env{'form.scantron_format'}).
                   6901: 	   "&scantron_CODElist=".&escape($env{'form.scantron_CODElist'}).
                   6902: 	   "&curCODE=".&escape($$scan_record{'scantron.CODE'}).
                   6903: 	   "&scantron_selectfile=".&escape($env{'form.scantron_selectfile'});
1.332     albertel 6904: 	if ($env{'form.scantron_CODElist'} =~ /\S/) { 
1.492     albertel 6905: 	    $r->print("
                   6906:     <label>
                   6907:        <input type='radio' name='scantron_CODE_resolution' value='use_found' />
                   6908:        ".&mt("[_1]Select[_2] a CODE from the list of all CODEs and use it.",
                   6909: 	     "<a target='_blank' href='$href'>","</a>")."
                   6910:     </label> 
1.558     bisitz   6911:     ".&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 6912: 	    $r->print("\n<br />");
                   6913: 	}
1.492     albertel 6914: 	$r->print("
                   6915:     <label>
                   6916:        <input type='radio' name='scantron_CODE_resolution' value='use_typed' />
                   6917:        ".&mt("Use [_1] as the CODE.",
                   6918: 	     "</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 6919: 	$r->print("\n<br /><br />");
1.157     albertel 6920:     } elsif ($error eq 'doublebubble') {
1.503     raeburn  6921: 	$r->print("<p>".&mt("There have been multiple bubbles scanned for some question(s)")."</p>\n");
1.497     foxr     6922: 
                   6923: 	# The form field scantron_questions is acutally a list of line numbers.
                   6924: 	# represented by this form so:
                   6925: 
                   6926: 	my $line_list = &questions_to_line_list($arg);
                   6927: 
1.157     albertel 6928: 	$r->print('<input type="hidden" name="scantron_questions" value="'.
1.497     foxr     6929: 		  $line_list.'" />');
1.242     albertel 6930: 	$r->print($message);
1.492     albertel 6931: 	$r->print("<p>".&mt("Please indicate which bubble should be used for grading")."</p>");
1.157     albertel 6932: 	foreach my $question (@{$arg}) {
1.503     raeburn  6933: 	    my @linenums = &prompt_for_corrections($r,$question,$scan_config,
                   6934:                                                    $scan_record, $error);
1.524     raeburn  6935:             push(@lines_to_correct,@linenums);
1.157     albertel 6936: 	}
1.503     raeburn  6937:         $r->print(&verify_bubbles_checked(@lines_to_correct));
1.157     albertel 6938:     } elsif ($error eq 'missingbubble') {
1.492     albertel 6939: 	$r->print("<p>".&mt("There have been <b>no</b> bubbles scanned for some question(s)")."</p>\n");
1.242     albertel 6940: 	$r->print($message);
1.492     albertel 6941: 	$r->print("<p>".&mt("Please indicate which bubble should be used for grading.")."</p>");
1.503     raeburn  6942: 	$r->print(&mt("Some questions have no scanned bubbles.")."\n");
1.497     foxr     6943: 
1.503     raeburn  6944: 	# The form field scantron_questions is actually a list of line numbers not
1.497     foxr     6945: 	# a list of question numbers. Therefore:
                   6946: 	#
                   6947: 	
                   6948: 	my $line_list = &questions_to_line_list($arg);
                   6949: 
1.157     albertel 6950: 	$r->print('<input type="hidden" name="scantron_questions" value="'.
1.497     foxr     6951: 		  $line_list.'" />');
1.157     albertel 6952: 	foreach my $question (@{$arg}) {
1.503     raeburn  6953: 	    my @linenums = &prompt_for_corrections($r,$question,$scan_config,
                   6954:                                                    $scan_record, $error);
1.524     raeburn  6955:             push(@lines_to_correct,@linenums);
1.157     albertel 6956: 	}
1.503     raeburn  6957:         $r->print(&verify_bubbles_checked(@lines_to_correct));
1.157     albertel 6958:     } else {
                   6959: 	$r->print("\n<ul>");
                   6960:     }
                   6961:     $r->print("\n</li></ul>");
1.497     foxr     6962: }
                   6963: 
1.503     raeburn  6964: sub verify_bubbles_checked {
                   6965:     my (@ansnums) = @_;
                   6966:     my $ansnumstr = join('","',@ansnums);
                   6967:     my $warning = &mt("A bubble or 'No bubble' selection has not been made for one or more lines.");
1.597     wenzelju 6968:     my $output = &Apache::lonhtmlcommon::scripttag((<<ENDSCRIPT));
1.503     raeburn  6969: function verify_bubble_radio(form) {
                   6970:     var ansnumArray = new Array ("$ansnumstr");
                   6971:     var need_bubble_count = 0;
                   6972:     for (var i=0; i<ansnumArray.length; i++) {
                   6973:         if (form.elements["scantron_correct_Q_"+ansnumArray[i]].length > 1) {
                   6974:             var bubble_picked = 0; 
                   6975:             for (var j=0; j<form.elements["scantron_correct_Q_"+ansnumArray[i]].length; j++) {
                   6976:                 if (form.elements["scantron_correct_Q_"+ansnumArray[i]][j].checked == true) {
                   6977:                     bubble_picked = 1;
                   6978:                 }
                   6979:             }
                   6980:             if (bubble_picked == 0) {
                   6981:                 need_bubble_count ++;
                   6982:             }
                   6983:         }
                   6984:     }
                   6985:     if (need_bubble_count) {
                   6986:         alert("$warning");
                   6987:         return;
                   6988:     }
                   6989:     form.submit(); 
                   6990: }
                   6991: ENDSCRIPT
                   6992:     return $output;
                   6993: }
                   6994: 
1.497     foxr     6995: =pod
                   6996: 
                   6997: =item  questions_to_line_list
1.157     albertel 6998: 
1.497     foxr     6999: Converts a list of questions into a string of comma separated
                   7000: line numbers in the answer sheet used by the questions.  This is
                   7001: used to fill in the scantron_questions form field.
                   7002: 
                   7003:   Arguments:
                   7004:      questions    - Reference to an array of questions.
                   7005: 
                   7006: =cut
                   7007: 
                   7008: 
                   7009: sub questions_to_line_list {
                   7010:     my ($questions) = @_;
                   7011:     my @lines;
                   7012: 
1.503     raeburn  7013:     foreach my $item (@{$questions}) {
                   7014:         my $question = $item;
                   7015:         my ($first,$count,$last);
                   7016:         if ($item =~ /^(\d+)\.(\d+)$/) {
                   7017:             $question = $1;
                   7018:             my $subquestion = $2;
                   7019:             $first = $first_bubble_line{$question-1} + 1;
                   7020:             my @subans = split(/,/,$subdivided_bubble_lines{$question-1});
                   7021:             my $subcount = 1;
                   7022:             while ($subcount<$subquestion) {
                   7023:                 $first += $subans[$subcount-1];
                   7024:                 $subcount ++;
                   7025:             }
                   7026:             $count = $subans[$subquestion-1];
                   7027:         } else {
                   7028: 	    $first   = $first_bubble_line{$question-1} + 1;
                   7029: 	    $count   = $bubble_lines_per_response{$question-1};
                   7030:         }
1.506     raeburn  7031:         $last = $first+$count-1;
1.503     raeburn  7032:         push(@lines, ($first..$last));
1.497     foxr     7033:     }
                   7034:     return join(',', @lines);
                   7035: }
                   7036: 
                   7037: =pod 
                   7038: 
                   7039: =item prompt_for_corrections
                   7040: 
                   7041: Prompts for a potentially multiline correction to the
                   7042: user's bubbling (factors out common code from scantron_get_correction
                   7043: for multi and missing bubble cases).
                   7044: 
                   7045:  Arguments:
                   7046:    $r           - Apache request object.
                   7047:    $question    - The question number to prompt for.
                   7048:    $scan_config - The scantron file configuration hash.
                   7049:    $scan_record - Reference to the hash that has the the parsed scanlines.
1.503     raeburn  7050:    $error       - Type of error
1.497     foxr     7051: 
                   7052:  Implicit inputs:
                   7053:    %bubble_lines_per_response   - Starting line numbers for each question.
                   7054:                                   Numbered from 0 (but question numbers are from
                   7055:                                   1.
                   7056:    %first_bubble_line           - Starting bubble line for each question.
1.509     raeburn  7057:    %subdivided_bubble_lines     - optionresponse, matchresponse and rankresponse 
                   7058:                                   type problems render as separate sub-questions, 
1.503     raeburn  7059:                                   in exam mode. This hash contains a 
                   7060:                                   comma-separated list of the lines per 
                   7061:                                   sub-question.
1.510     raeburn  7062:    %responsetype_per_response   - essayresponse, formularesponse,
                   7063:                                   stringresponse, imageresponse, reactionresponse,
                   7064:                                   and organicresponse type problem parts can have
1.503     raeburn  7065:                                   multiple lines per response if the weight
                   7066:                                   assigned exceeds 10.  In this case, only
                   7067:                                   one bubble per line is permitted, but more 
                   7068:                                   than one line might contain bubbles, e.g.
                   7069:                                   bubbling of: line 1 - J, line 2 - J, 
                   7070:                                   line 3 - B would assign 22 points.  
1.497     foxr     7071: 
                   7072: =cut
                   7073: 
                   7074: sub prompt_for_corrections {
1.503     raeburn  7075:     my ($r, $question, $scan_config, $scan_record, $error) = @_;
                   7076:     my ($current_line,$lines);
                   7077:     my @linenums;
                   7078:     my $questionnum = $question;
                   7079:     if ($question =~ /^(\d+)\.(\d+)$/) {
                   7080:         $question = $1;
                   7081:         $current_line = $first_bubble_line{$question-1} + 1 ;
                   7082:         my $subquestion = $2;
                   7083:         my @subans = split(/,/,$subdivided_bubble_lines{$question-1});
                   7084:         my $subcount = 1;
                   7085:         while ($subcount<$subquestion) {
                   7086:             $current_line += $subans[$subcount-1];
                   7087:             $subcount ++;
                   7088:         }
                   7089:         $lines = $subans[$subquestion-1];
                   7090:     } else {
                   7091:         $current_line = $first_bubble_line{$question-1} + 1 ;
                   7092:         $lines        = $bubble_lines_per_response{$question-1};
                   7093:     }
1.497     foxr     7094:     if ($lines > 1) {
1.503     raeburn  7095:         $r->print(&mt('The group of bubble lines below responds to a single question.').'<br />');
                   7096:         if (($responsetype_per_response{$question-1} eq 'essayresponse') ||
                   7097:             ($responsetype_per_response{$question-1} eq 'formularesponse') ||
1.510     raeburn  7098:             ($responsetype_per_response{$question-1} eq 'stringresponse') ||
                   7099:             ($responsetype_per_response{$question-1} eq 'imageresponse') ||
                   7100:             ($responsetype_per_response{$question-1} eq 'reactionresponse') ||
                   7101:             ($responsetype_per_response{$question-1} eq 'organicresponse')) {
1.572     www      7102:             $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  7103:         } else {
                   7104:             $r->print(&mt("Select at most one bubble in a single line and select 'No Bubble' in all the other lines. ")."<br />");
                   7105:         }
1.497     foxr     7106:     }
                   7107:     for (my $i =0; $i < $lines; $i++) {
1.503     raeburn  7108:         my $selected = $$scan_record{"scantron.$current_line.answer"};
                   7109: 	&scantron_bubble_selector($r,$scan_config,$current_line, 
                   7110: 	        		  $questionnum,$error,split('', $selected));
1.524     raeburn  7111:         push(@linenums,$current_line);
1.497     foxr     7112: 	$current_line++;
                   7113:     }
                   7114:     if ($lines > 1) {
                   7115: 	$r->print("<hr /><br />");
                   7116:     }
1.503     raeburn  7117:     return @linenums;
1.157     albertel 7118: }
1.423     albertel 7119: 
                   7120: =pod
                   7121: 
                   7122: =item scantron_bubble_selector
                   7123:   
                   7124:    Generates the html radiobuttons to correct a single bubble line
1.424     albertel 7125:    possibly showing the existing the selected bubbles if known
1.423     albertel 7126: 
                   7127:  Arguments:
                   7128:     $r           - Apache request object
                   7129:     $scan_config - hash from &get_scantron_config()
1.497     foxr     7130:     $line        - Number of the line being displayed.
1.503     raeburn  7131:     $questionnum - Question number (may include subquestion)
                   7132:     $error       - Type of error.
1.497     foxr     7133:     @selected    - Array of bubbles picked on this line.
1.423     albertel 7134: 
                   7135: =cut
                   7136: 
1.157     albertel 7137: sub scantron_bubble_selector {
1.503     raeburn  7138:     my ($r,$scan_config,$line,$questionnum,$error,@selected)=@_;
1.157     albertel 7139:     my $max=$$scan_config{'Qlength'};
1.274     albertel 7140: 
                   7141:     my $scmode=$$scan_config{'Qon'};
                   7142:     if ($scmode eq 'number' || $scmode eq 'letter') { $max=10; }	     
                   7143: 
1.157     albertel 7144:     my @alphabet=('A'..'Z');
1.503     raeburn  7145:     $r->print(&Apache::loncommon::start_data_table().
                   7146:               &Apache::loncommon::start_data_table_row());
                   7147:     $r->print('<td rowspan="2" class="LC_leftcol_header">'.$line.'</td>');
1.497     foxr     7148:     for (my $i=0;$i<$max+1;$i++) {
                   7149: 	$r->print("\n".'<td align="center">');
                   7150: 	if ($selected[0] eq $alphabet[$i]) { $r->print('X'); shift(@selected) }
                   7151: 	else { $r->print('&nbsp;'); }
                   7152: 	$r->print('</td>');
                   7153:     }
1.503     raeburn  7154:     $r->print(&Apache::loncommon::end_data_table_row().
                   7155:               &Apache::loncommon::start_data_table_row());
1.497     foxr     7156:     for (my $i=0;$i<$max;$i++) {
                   7157: 	$r->print("\n".
                   7158: 		  '<td><label><input type="radio" name="scantron_correct_Q_'.
                   7159: 		  $line.'" value="'.$i.'" />'.$alphabet[$i]."</label></td>");
                   7160:     }
1.503     raeburn  7161:     my $nobub_checked = ' ';
                   7162:     if ($error eq 'missingbubble') {
                   7163:         $nobub_checked = ' checked = "checked" ';
                   7164:     }
                   7165:     $r->print("\n".'<td><label><input type="radio" name="scantron_correct_Q_'.
                   7166: 	      $line.'" value="none"'.$nobub_checked.'/>'.&mt('No bubble').
                   7167:               '</label>'."\n".'<input type="hidden" name="scantron_questionnum_Q_'.
                   7168:               $line.'" value="'.$questionnum.'" /></td>');
                   7169:     $r->print(&Apache::loncommon::end_data_table_row().
                   7170:               &Apache::loncommon::end_data_table());
1.157     albertel 7171: }
                   7172: 
1.423     albertel 7173: =pod
                   7174: 
                   7175: =item num_matches
                   7176: 
1.424     albertel 7177:    Counts the number of characters that are the same between the two arguments.
                   7178: 
                   7179:  Arguments:
                   7180:    $orig - CODE from the scanline
                   7181:    $code - CODE to match against
                   7182: 
                   7183:  Returns:
                   7184:    $count - integer count of the number of same characters between the
                   7185:             two arguments
                   7186: 
1.423     albertel 7187: =cut
                   7188: 
1.194     albertel 7189: sub num_matches {
                   7190:     my ($orig,$code) = @_;
                   7191:     my @code=split(//,$code);
                   7192:     my @orig=split(//,$orig);
                   7193:     my $same=0;
                   7194:     for (my $i=0;$i<scalar(@code);$i++) {
                   7195: 	if ($code[$i] eq $orig[$i]) { $same++; }
                   7196:     }
                   7197:     return $same;
                   7198: }
                   7199: 
1.423     albertel 7200: =pod
                   7201: 
                   7202: =item scantron_get_closely_matching_CODEs
                   7203: 
1.424     albertel 7204:    Cycles through all CODEs and finds the set that has the greatest
                   7205:    number of same characters as the provided CODE
                   7206: 
                   7207:  Arguments:
                   7208:    $allcodes - hash ref returned by &get_codes()
                   7209:    $CODE     - CODE from the current scanline
                   7210: 
                   7211:  Returns:
                   7212:    2 element list
                   7213:     - first elements is number of how closely matching the best fit is 
                   7214:       (5 means best set has 5 matching characters)
                   7215:     - second element is an arrary ref containing the set of valid CODEs
                   7216:       that best fit the passed in CODE
                   7217: 
1.423     albertel 7218: =cut
                   7219: 
1.194     albertel 7220: sub scantron_get_closely_matching_CODEs {
                   7221:     my ($allcodes,$CODE)=@_;
                   7222:     my @CODEs;
                   7223:     foreach my $testcode (sort(keys(%{$allcodes}))) {
                   7224: 	push(@{$CODEs[&num_matches($CODE,$testcode)]},$testcode);
                   7225:     }
                   7226: 
                   7227:     return ($#CODEs,$CODEs[-1]);
                   7228: }
                   7229: 
1.423     albertel 7230: =pod
                   7231: 
                   7232: =item get_codes
                   7233: 
1.424     albertel 7234:    Builds a hash which has keys of all of the valid CODEs from the selected
                   7235:    set of remembered CODEs.
                   7236: 
                   7237:  Arguments:
                   7238:   $old_name - name of the set of remembered CODEs
                   7239:   $cdom     - domain of the course
                   7240:   $cnum     - internal course name
                   7241: 
                   7242:  Returns:
                   7243:   %allcodes - keys are the valid CODEs, values are all 1
                   7244: 
1.423     albertel 7245: =cut
                   7246: 
1.194     albertel 7247: sub get_codes {
1.280     foxr     7248:     my ($old_name, $cdom, $cnum) = @_;
                   7249:     if (!$old_name) {
                   7250: 	$old_name=$env{'form.scantron_CODElist'};
                   7251:     }
                   7252:     if (!$cdom) {
                   7253: 	$cdom =$env{'course.'.$env{'request.course.id'}.'.domain'};
                   7254:     }
                   7255:     if (!$cnum) {
                   7256: 	$cnum =$env{'course.'.$env{'request.course.id'}.'.num'};
                   7257:     }
1.278     albertel 7258:     my %result=&Apache::lonnet::get('CODEs',[$old_name,"type\0$old_name"],
                   7259: 				    $cdom,$cnum);
                   7260:     my %allcodes;
                   7261:     if ($result{"type\0$old_name"} eq 'number') {
                   7262: 	%allcodes=map {($_,1)} split(',',$result{$old_name});
                   7263:     } else {
                   7264: 	%allcodes=map {(&Apache::lonprintout::num_to_letters($_),1)} split(',',$result{$old_name});
                   7265:     }
1.194     albertel 7266:     return %allcodes;
                   7267: }
                   7268: 
1.423     albertel 7269: =pod
                   7270: 
                   7271: =item scantron_validate_CODE
                   7272: 
1.424     albertel 7273:    Validates all scanlines in the selected file to not have any
                   7274:    invalid or underspecified CODEs and that none of the codes are
                   7275:    duplicated if this was requested.
                   7276: 
1.423     albertel 7277: =cut
                   7278: 
1.157     albertel 7279: sub scantron_validate_CODE {
                   7280:     my ($r,$currentphase) = @_;
1.257     albertel 7281:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.186     albertel 7282:     if ($scantron_config{'CODElocation'} &&
                   7283: 	$scantron_config{'CODEstart'} &&
                   7284: 	$scantron_config{'CODElength'}) {
1.257     albertel 7285: 	if (!defined($env{'form.scantron_CODElist'})) {
1.186     albertel 7286: 	    &FIXME_blow_up()
                   7287: 	}
                   7288:     } else {
                   7289: 	return (0,$currentphase+1);
                   7290:     }
                   7291:     
                   7292:     my %usedCODEs;
                   7293: 
1.194     albertel 7294:     my %allcodes=&get_codes();
1.186     albertel 7295: 
1.582     raeburn  7296:     my $nav_error;
                   7297:     &scantron_get_maxbubble(\$nav_error); # parse needs the lines per response array.
                   7298:     if ($nav_error) {
                   7299:         $r->print(&navmap_errormsg());
                   7300:         return(1,$currentphase);
                   7301:     }
1.447     foxr     7302: 
1.186     albertel 7303:     my ($scanlines,$scan_data)=&scantron_getfile();
                   7304:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
1.200     albertel 7305: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.186     albertel 7306: 	if ($line=~/^[\s\cz]*$/) { next; }
                   7307: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
                   7308: 						 $scan_data);
                   7309: 	my $CODE=$$scan_record{'scantron.CODE'};
                   7310: 	my $error=0;
1.224     albertel 7311: 	if (!&Apache::lonnet::validCODE($CODE)) {
                   7312: 	    &scantron_get_correction($r,$i,$scan_record,
                   7313: 				     \%scantron_config,
                   7314: 				     $line,'incorrectCODE',\%allcodes);
                   7315: 	    return(1,$currentphase);
                   7316: 	}
1.221     albertel 7317: 	if (%allcodes && !exists($allcodes{$CODE}) 
                   7318: 	    && !$$scan_record{'scantron.useCODE'}) {
1.186     albertel 7319: 	    &scantron_get_correction($r,$i,$scan_record,
                   7320: 				     \%scantron_config,
1.194     albertel 7321: 				     $line,'incorrectCODE',\%allcodes);
                   7322: 	    return(1,$currentphase);
1.186     albertel 7323: 	}
1.214     albertel 7324: 	if (exists($usedCODEs{$CODE}) 
1.257     albertel 7325: 	    && $env{'form.scantron_CODEunique'} eq 'yes'
1.192     albertel 7326: 	    && !$$scan_record{'scantron.CODE_ignore_dup'}) {
1.186     albertel 7327: 	    &scantron_get_correction($r,$i,$scan_record,
                   7328: 				     \%scantron_config,
1.194     albertel 7329: 				     $line,'duplicateCODE',$usedCODEs{$CODE});
                   7330: 	    return(1,$currentphase);
1.186     albertel 7331: 	}
1.524     raeburn  7332: 	push(@{$usedCODEs{$CODE}},$$scan_record{'scantron.PaperID'});
1.186     albertel 7333:     }
1.157     albertel 7334:     return (0,$currentphase+1);
                   7335: }
                   7336: 
1.423     albertel 7337: =pod
                   7338: 
                   7339: =item scantron_validate_doublebubble
                   7340: 
1.424     albertel 7341:    Validates all scanlines in the selected file to not have any
                   7342:    bubble lines with multiple bubbles marked.
                   7343: 
1.423     albertel 7344: =cut
                   7345: 
1.157     albertel 7346: sub scantron_validate_doublebubble {
                   7347:     my ($r,$currentphase) = @_;
                   7348:     #get student info
                   7349:     my $classlist=&Apache::loncoursedata::get_classlist();
                   7350:     my %idmap=&username_to_idmap($classlist);
                   7351: 
                   7352:     #get scantron line setup
1.257     albertel 7353:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.157     albertel 7354:     my ($scanlines,$scan_data)=&scantron_getfile();
1.583     raeburn  7355:     my $nav_error;
                   7356:     &scantron_get_maxbubble(\$nav_error); # parse needs the bubble line array.
                   7357:     if ($nav_error) {
                   7358:         $r->print(&navmap_errormsg());
                   7359:         return(1,$currentphase);
                   7360:     }
1.447     foxr     7361: 
1.157     albertel 7362:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
1.200     albertel 7363: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.157     albertel 7364: 	if ($line=~/^[\s\cz]*$/) { next; }
                   7365: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
                   7366: 						 $scan_data);
                   7367: 	if (!defined($$scan_record{'scantron.doubleerror'})) { next; }
                   7368: 	&scantron_get_correction($r,$i,$scan_record,\%scantron_config,$line,
                   7369: 				 'doublebubble',
                   7370: 				 $$scan_record{'scantron.doubleerror'});
                   7371:     	return (1,$currentphase);
                   7372:     }
                   7373:     return (0,$currentphase+1);
                   7374: }
                   7375: 
1.423     albertel 7376: 
1.503     raeburn  7377: sub scantron_get_maxbubble {
1.582     raeburn  7378:     my ($nav_error) = @_;
1.257     albertel 7379:     if (defined($env{'form.scantron_maxbubble'}) &&
                   7380: 	$env{'form.scantron_maxbubble'}) {
1.447     foxr     7381: 	&restore_bubble_lines();
1.257     albertel 7382: 	return $env{'form.scantron_maxbubble'};
1.191     albertel 7383:     }
1.330     albertel 7384: 
1.447     foxr     7385:     my (undef, undef, $sequence) =
1.257     albertel 7386: 	&Apache::lonnet::decode_symb($env{'form.selectpage'});
1.330     albertel 7387: 
1.447     foxr     7388:     my $navmap=Apache::lonnavmaps::navmap->new();
1.582     raeburn  7389:     unless (ref($navmap)) {
                   7390:         if (ref($nav_error)) {
                   7391:             $$nav_error = 1;
                   7392:         }
1.591     raeburn  7393:         return;
1.582     raeburn  7394:     }
1.191     albertel 7395:     my $map=$navmap->getResourceByUrl($sequence);
                   7396:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
1.330     albertel 7397: 
                   7398:     &Apache::lonxml::clear_problem_counter();
                   7399: 
1.557     raeburn  7400:     my $uname       = $env{'user.name'};
                   7401:     my $udom        = $env{'user.domain'};
1.435     foxr     7402:     my $cid         = $env{'request.course.id'};
                   7403:     my $total_lines = 0;
                   7404:     %bubble_lines_per_response = ();
1.447     foxr     7405:     %first_bubble_line         = ();
1.503     raeburn  7406:     %subdivided_bubble_lines   = ();
                   7407:     %responsetype_per_response = ();
1.554     raeburn  7408: 
1.447     foxr     7409:     my $response_number = 0;
                   7410:     my $bubble_line     = 0;
1.191     albertel 7411:     foreach my $resource (@resources) {
1.542     raeburn  7412:         my ($analysis,$parts) = &scantron_partids_tograde($resource,$cid,$uname,$udom);
                   7413:         if ((ref($analysis) eq 'HASH') && (ref($parts) eq 'ARRAY')) {
                   7414: 	    foreach my $part_id (@{$parts}) {
                   7415:                 my $lines;
                   7416: 
                   7417: 	        # TODO - make this a persistent hash not an array.
                   7418: 
                   7419:                 # optionresponse, matchresponse and rankresponse type items 
                   7420:                 # render as separate sub-questions in exam mode.
                   7421:                 if (($analysis->{$part_id.'.type'} eq 'optionresponse') ||
                   7422:                     ($analysis->{$part_id.'.type'} eq 'matchresponse') ||
                   7423:                     ($analysis->{$part_id.'.type'} eq 'rankresponse')) {
                   7424:                     my ($numbub,$numshown);
                   7425:                     if ($analysis->{$part_id.'.type'} eq 'optionresponse') {
                   7426:                         if (ref($analysis->{$part_id.'.options'}) eq 'ARRAY') {
                   7427:                             $numbub = scalar(@{$analysis->{$part_id.'.options'}});
                   7428:                         }
                   7429:                     } elsif ($analysis->{$part_id.'.type'} eq 'matchresponse') {
                   7430:                         if (ref($analysis->{$part_id.'.items'}) eq 'ARRAY') {
                   7431:                             $numbub = scalar(@{$analysis->{$part_id.'.items'}});
                   7432:                         }
                   7433:                     } elsif ($analysis->{$part_id.'.type'} eq 'rankresponse') {
                   7434:                         if (ref($analysis->{$part_id.'.foils'}) eq 'ARRAY') {
                   7435:                             $numbub = scalar(@{$analysis->{$part_id.'.foils'}});
                   7436:                         }
                   7437:                     }
                   7438:                     if (ref($analysis->{$part_id.'.shown'}) eq 'ARRAY') {
                   7439:                         $numshown = scalar(@{$analysis->{$part_id.'.shown'}});
                   7440:                     }
                   7441:                     my $bubbles_per_line = 10;
                   7442:                     my $inner_bubble_lines = int($numbub/$bubbles_per_line);
                   7443:                     if (($numbub % $bubbles_per_line) != 0) {
                   7444:                         $inner_bubble_lines++;
                   7445:                     }
                   7446:                     for (my $i=0; $i<$numshown; $i++) {
                   7447:                         $subdivided_bubble_lines{$response_number} .= 
                   7448:                             $inner_bubble_lines.',';
                   7449:                     }
                   7450:                     $subdivided_bubble_lines{$response_number} =~ s/,$//;
                   7451:                     $lines = $numshown * $inner_bubble_lines;
                   7452:                 } else {
                   7453:                     $lines = $analysis->{"$part_id.bubble_lines"};
                   7454:                 } 
                   7455: 
                   7456:                 $first_bubble_line{$response_number} = $bubble_line;
                   7457: 	        $bubble_lines_per_response{$response_number} = $lines;
                   7458:                 $responsetype_per_response{$response_number} = 
                   7459:                     $analysis->{$part_id.'.type'};
                   7460: 	        $response_number++;
                   7461: 
                   7462: 	        $bubble_line +=  $lines;
                   7463: 	        $total_lines +=  $lines;
                   7464: 	    }
                   7465:         }
                   7466:     }
1.552     raeburn  7467:     &Apache::lonnet::delenv('scantron.');
1.542     raeburn  7468: 
                   7469:     &save_bubble_lines();
                   7470:     $env{'form.scantron_maxbubble'} =
                   7471: 	$total_lines;
                   7472:     return $env{'form.scantron_maxbubble'};
                   7473: }
1.523     raeburn  7474: 
1.157     albertel 7475: sub scantron_validate_missingbubbles {
                   7476:     my ($r,$currentphase) = @_;
                   7477:     #get student info
                   7478:     my $classlist=&Apache::loncoursedata::get_classlist();
                   7479:     my %idmap=&username_to_idmap($classlist);
                   7480: 
                   7481:     #get scantron line setup
1.257     albertel 7482:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.157     albertel 7483:     my ($scanlines,$scan_data)=&scantron_getfile();
1.582     raeburn  7484:     my $nav_error;
                   7485:     my $max_bubble=&scantron_get_maxbubble(\$nav_error);
                   7486:     if ($nav_error) {
                   7487:         return(1,$currentphase);
                   7488:     }
1.157     albertel 7489:     if (!$max_bubble) { $max_bubble=2**31; }
                   7490:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
1.200     albertel 7491: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.157     albertel 7492: 	if ($line=~/^[\s\cz]*$/) { next; }
                   7493: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
                   7494: 						 $scan_data);
                   7495: 	if (!defined($$scan_record{'scantron.missingerror'})) { next; }
                   7496: 	my @to_correct;
1.470     foxr     7497: 	
                   7498: 	# Probably here's where the error is...
                   7499: 
1.157     albertel 7500: 	foreach my $missing (@{$$scan_record{'scantron.missingerror'}}) {
1.505     raeburn  7501:             my $lastbubble;
                   7502:             if ($missing =~ /^(\d+)\.(\d+)$/) {
                   7503:                my $question = $1;
                   7504:                my $subquestion = $2;
                   7505:                if (!defined($first_bubble_line{$question -1})) { next; }
                   7506:                my $first = $first_bubble_line{$question-1};
                   7507:                my @subans = split(/,/,$subdivided_bubble_lines{$question-1});
                   7508:                my $subcount = 1;
                   7509:                while ($subcount<$subquestion) {
                   7510:                    $first += $subans[$subcount-1];
                   7511:                    $subcount ++;
                   7512:                }
                   7513:                my $count = $subans[$subquestion-1];
                   7514:                $lastbubble = $first + $count;
                   7515:             } else {
                   7516:                 if (!defined($first_bubble_line{$missing - 1})) { next; }
                   7517:                 $lastbubble = $first_bubble_line{$missing - 1} + $bubble_lines_per_response{$missing - 1};
                   7518:             }
                   7519:             if ($lastbubble > $max_bubble) { next; }
1.157     albertel 7520: 	    push(@to_correct,$missing);
                   7521: 	}
                   7522: 	if (@to_correct) {
                   7523: 	    &scantron_get_correction($r,$i,$scan_record,\%scantron_config,
                   7524: 				     $line,'missingbubble',\@to_correct);
                   7525: 	    return (1,$currentphase);
                   7526: 	}
                   7527: 
                   7528:     }
                   7529:     return (0,$currentphase+1);
                   7530: }
                   7531: 
1.423     albertel 7532: 
1.82      albertel 7533: sub scantron_process_students {
1.608     www      7534:     my ($r,$symb) = @_;
1.513     foxr     7535: 
1.257     albertel 7536:     my (undef,undef,$sequence)=&Apache::lonnet::decode_symb($env{'form.selectpage'});
1.513     foxr     7537:     if (!$symb) {
                   7538: 	return '';
                   7539:     }
1.324     albertel 7540:     my $default_form_data=&defaultFormData($symb);
1.82      albertel 7541: 
1.257     albertel 7542:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.157     albertel 7543:     my ($scanlines,$scan_data)=&scantron_getfile();
1.82      albertel 7544:     my $classlist=&Apache::loncoursedata::get_classlist();
                   7545:     my %idmap=&username_to_idmap($classlist);
1.132     bowersj2 7546:     my $navmap=Apache::lonnavmaps::navmap->new();
1.582     raeburn  7547:     unless (ref($navmap)) {
                   7548:         $r->print(&navmap_errormsg());
                   7549:         return '';
                   7550:     }  
1.83      albertel 7551:     my $map=$navmap->getResourceByUrl($sequence);
                   7552:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
1.557     raeburn  7553:     my (%grader_partids_by_symb,%grader_randomlists_by_symb);
                   7554:     &graders_resources_pass(\@resources,\%grader_partids_by_symb,
                   7555:                             \%grader_randomlists_by_symb);
1.586     raeburn  7556:     my $resource_error;
1.557     raeburn  7557:     foreach my $resource (@resources) {
1.586     raeburn  7558:         my $ressymb;
                   7559:         if (ref($resource)) {
                   7560:             $ressymb = $resource->symb();
                   7561:         } else {
                   7562:             $resource_error = 1;
                   7563:             last;
                   7564:         }
1.557     raeburn  7565:         my ($analysis,$parts) =
                   7566:             &scantron_partids_tograde($resource,$env{'request.course.id'},
                   7567:                                       $env{'user.name'},$env{'user.domain'},1);
                   7568:         $grader_partids_by_symb{$ressymb} = $parts;
                   7569:         if (ref($analysis) eq 'HASH') {
                   7570:             if (ref($analysis->{'parts_withrandomlist'}) eq 'ARRAY') {
                   7571:                 $grader_randomlists_by_symb{$ressymb} = 
                   7572:                     $analysis->{'parts_withrandomlist'};
                   7573:             }
                   7574:         }
                   7575:     }
1.586     raeburn  7576:     if ($resource_error) {
                   7577:         $r->print(&navmap_errormsg());
                   7578:         return '';
                   7579:     }
1.557     raeburn  7580: 
1.554     raeburn  7581:     my ($uname,$udom);
1.82      albertel 7582:     my $result= <<SCANTRONFORM;
1.81      albertel 7583: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantronupload">
                   7584:   <input type="hidden" name="command" value="scantron_configphase" />
                   7585:   $default_form_data
                   7586: SCANTRONFORM
1.82      albertel 7587:     $r->print($result);
                   7588: 
                   7589:     my @delayqueue;
1.542     raeburn  7590:     my (%completedstudents,%scandata);
1.140     albertel 7591:     
1.520     www      7592:     my $lock=&Apache::lonnet::set_lock(&mt('Grading bubblesheet exam'));
1.200     albertel 7593:     my $count=&get_todo_count($scanlines,$scan_data);
1.575     www      7594:     my %prog_state=&Apache::lonhtmlcommon::Create_PrgWin($r,'Bubblesheet Status',
                   7595:  				    'Bubblesheet Progress',$count,
1.195     albertel 7596: 				    'inline',undef,'scantronupload');
1.140     albertel 7597:     &Apache::lonhtmlcommon::Update_PrgWin($r,\%prog_state,
                   7598: 					  'Processing first student');
1.542     raeburn  7599:     $r->print('<br />');
1.140     albertel 7600:     my $start=&Time::HiRes::time();
1.158     albertel 7601:     my $i=-1;
1.542     raeburn  7602:     my $started;
1.447     foxr     7603: 
1.582     raeburn  7604:     my $nav_error;
                   7605:     &scantron_get_maxbubble(\$nav_error); # Need the bubble lines array to parse.
                   7606:     if ($nav_error) {
                   7607:         $r->print(&navmap_errormsg());
                   7608:         return '';
                   7609:     }
                   7610: 
1.513     foxr     7611:     # If an ssi failed in scantron_get_maxbubble, put an error message out to
                   7612:     # the user and return.
                   7613: 
                   7614:     if ($ssi_error) {
                   7615: 	$r->print("</form>");
                   7616: 	&ssi_print_error($r);
1.520     www      7617:         &Apache::lonnet::remove_lock($lock);
1.513     foxr     7618: 	return '';		# Dunno why the other returns return '' rather than just returning.
                   7619:     }
1.447     foxr     7620: 
1.542     raeburn  7621:     my %lettdig = &letter_to_digits();
                   7622:     my $numletts = scalar(keys(%lettdig));
                   7623: 
1.157     albertel 7624:     while ($i<$scanlines->{'count'}) {
                   7625:  	($uname,$udom)=('','');
                   7626:  	$i++;
1.200     albertel 7627:  	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.157     albertel 7628:  	if ($line=~/^[\s\cz]*$/) { next; }
1.200     albertel 7629: 	if ($started) {
                   7630: 	    &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state,
                   7631: 						     'last student');
                   7632: 	}
                   7633: 	$started=1;
1.157     albertel 7634:  	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
                   7635:  						 $scan_data);
                   7636:  	unless ($uname=&scantron_find_student($scan_record,$scan_data,
                   7637:  					      \%idmap,$i)) {
                   7638:   	    &scantron_add_delay(\@delayqueue,$line,
                   7639:  				'Unable to find a student that matches',1);
                   7640:  	    next;
                   7641:   	}
                   7642:  	if (exists $completedstudents{$uname}) {
                   7643:  	    &scantron_add_delay(\@delayqueue,$line,
                   7644:  				'Student '.$uname.' has multiple sheets',2);
                   7645:  	    next;
                   7646:  	}
                   7647:   	($uname,$udom)=split(/:/,$uname);
1.330     albertel 7648: 
1.586     raeburn  7649:         my (%partids_by_symb,$res_error);
1.554     raeburn  7650:         foreach my $resource (@resources) {
1.586     raeburn  7651:             my $ressymb;
                   7652:             if (ref($resource)) {
                   7653:                 $ressymb = $resource->symb();
                   7654:             } else {
                   7655:                 $res_error = 1;
                   7656:                 last;
                   7657:             }
1.557     raeburn  7658:             if ((exists($grader_randomlists_by_symb{$ressymb})) ||
                   7659:                 (ref($grader_partids_by_symb{$ressymb}) ne 'ARRAY')) {
                   7660:                 my ($analysis,$parts) =
                   7661:                     &scantron_partids_tograde($resource,$env{'request.course.id'},$uname,$udom);
                   7662:                 $partids_by_symb{$ressymb} = $parts;
                   7663:             } else {
                   7664:                 $partids_by_symb{$ressymb} = $grader_partids_by_symb{$ressymb};
                   7665:             }
1.554     raeburn  7666:         }
                   7667: 
1.586     raeburn  7668:         if ($res_error) {
                   7669:             &scantron_add_delay(\@delayqueue,$line,
                   7670:                                 'An error occurred while grading student '.$uname,2);
                   7671:             next;
                   7672:         }
                   7673: 
1.330     albertel 7674: 	&Apache::lonxml::clear_problem_counter();
1.514     raeburn  7675:   	&Apache::lonnet::appenv($scan_record);
1.376     albertel 7676: 
                   7677: 	if (&scantron_clear_skip($scanlines,$scan_data,$i)) {
                   7678: 	    &scantron_putfile($scanlines,$scan_data);
                   7679: 	}
1.161     albertel 7680: 	
1.542     raeburn  7681:         my $scancode;
                   7682:         if ((exists($scan_record->{'scantron.CODE'})) &&
                   7683:             (&Apache::lonnet::validCODE($scan_record->{'scantron.CODE'}))) {
                   7684:             $scancode = $scan_record->{'scantron.CODE'};
                   7685:         } else {
                   7686:             $scancode = '';
                   7687:         }
                   7688: 
                   7689:         if (&grade_student_bubbles($r,$uname,$udom,$scan_record,$scancode,
1.554     raeburn  7690:                                    \@resources,\%partids_by_symb) eq 'ssi_error') {
1.542     raeburn  7691:             $ssi_error = 0; # So end of handler error message does not trigger.
                   7692:             $r->print("</form>");
                   7693:             &ssi_print_error($r);
                   7694:             &Apache::lonnet::remove_lock($lock);
                   7695:             return '';      # Why return ''?  Beats me.
                   7696:         }
1.513     foxr     7697: 
1.140     albertel 7698: 	$completedstudents{$uname}={'line'=>$line};
1.542     raeburn  7699:         if ($env{'form.verifyrecord'}) {
                   7700:             my $lastpos = $env{'form.scantron_maxbubble'}*$scantron_config{'Qlength'};
                   7701:             my $studentdata = substr($line,$scantron_config{'Qstart'}-1,$lastpos);
                   7702:             chomp($studentdata);
                   7703:             $studentdata =~ s/\r$//;
                   7704:             my $studentrecord = '';
                   7705:             my $counter = -1;
                   7706:             foreach my $resource (@resources) {
1.554     raeburn  7707:                 my $ressymb = $resource->symb();
1.542     raeburn  7708:                 ($counter,my $recording) =
                   7709:                     &verify_scantron_grading($resource,$udom,$uname,$env{'request.course.id'},
1.554     raeburn  7710:                                              $counter,$studentdata,$partids_by_symb{$ressymb},
1.542     raeburn  7711:                                              \%scantron_config,\%lettdig,$numletts);
                   7712:                 $studentrecord .= $recording;
                   7713:             }
                   7714:             if ($studentrecord ne $studentdata) {
1.554     raeburn  7715:                 &Apache::lonxml::clear_problem_counter();
                   7716:                 if (&grade_student_bubbles($r,$uname,$udom,$scan_record,$scancode,
                   7717:                                            \@resources,\%partids_by_symb) eq 'ssi_error') {
                   7718:                     $ssi_error = 0; # So end of handler error message does not trigger.
                   7719:                     $r->print("</form>");
                   7720:                     &ssi_print_error($r);
                   7721:                     &Apache::lonnet::remove_lock($lock);
                   7722:                     delete($completedstudents{$uname});
                   7723:                     return '';
                   7724:                 }
1.542     raeburn  7725:                 $counter = -1;
                   7726:                 $studentrecord = '';
                   7727:                 foreach my $resource (@resources) {
1.554     raeburn  7728:                     my $ressymb = $resource->symb();
1.542     raeburn  7729:                     ($counter,my $recording) =
                   7730:                         &verify_scantron_grading($resource,$udom,$uname,$env{'request.course.id'},
1.554     raeburn  7731:                                                  $counter,$studentdata,$partids_by_symb{$ressymb},
1.542     raeburn  7732:                                                  \%scantron_config,\%lettdig,$numletts);
                   7733:                     $studentrecord .= $recording;
                   7734:                 }
                   7735:                 if ($studentrecord ne $studentdata) {
                   7736:                     $r->print('<p><span class="LC_error">');
                   7737:                     if ($scancode eq '') {
                   7738:                         $r->print(&mt('Mismatch grading bubble sheet for user: [_1] with ID: [_2].',
                   7739:                                   $uname.':'.$udom,$scan_record->{'scantron.ID'}));
                   7740:                     } else {
                   7741:                         $r->print(&mt('Mismatch grading bubble sheet for user: [_1] with ID: [_2] and CODE: [_3].',
                   7742:                                   $uname.':'.$udom,$scan_record->{'scantron.ID'},$scancode));
                   7743:                     }
                   7744:                     $r->print('</span><br />'.&Apache::loncommon::start_data_table()."\n".
                   7745:                               &Apache::loncommon::start_data_table_header_row()."\n".
                   7746:                               '<th>'.&mt('Source').'</th><th>'.&mt('Bubbled responses').'</th>'.
                   7747:                               &Apache::loncommon::end_data_table_header_row()."\n".
                   7748:                               &Apache::loncommon::start_data_table_row().
                   7749:                               '<td>'.&mt('Bubble Sheet').'</td>'.
                   7750:                               '<td><span class="LC_nobreak">'.$studentdata.'</span></td>'.
                   7751:                               &Apache::loncommon::end_data_table_row().
                   7752:                               &Apache::loncommon::start_data_table_row().
                   7753:                               '<td>Stored submissions</td>'.
                   7754:                               '<td><span class="LC_nobreak">'.$studentrecord.'</span></td>'."\n".
                   7755:                               &Apache::loncommon::end_data_table_row().
                   7756:                               &Apache::loncommon::end_data_table().'</p>');
                   7757:                 } else {
                   7758:                     $r->print('<br /><span class="LC_warning">'.
                   7759:                              &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 />'.
                   7760:                              &mt("As a consequence, this user's submission history records two tries.").
                   7761:                                  '</span><br />');
                   7762:                 }
                   7763:             }
                   7764:         }
1.543     raeburn  7765:         if (&Apache::loncommon::connection_aborted($r)) { last; }
1.140     albertel 7766:     } continue {
1.330     albertel 7767: 	&Apache::lonxml::clear_problem_counter();
1.552     raeburn  7768: 	&Apache::lonnet::delenv('scantron.');
1.82      albertel 7769:     }
1.140     albertel 7770:     &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
1.520     www      7771:     &Apache::lonnet::remove_lock($lock);
1.172     albertel 7772: #    my $lasttime = &Time::HiRes::time()-$start;
                   7773: #    $r->print("<p>took $lasttime</p>");
1.140     albertel 7774: 
1.200     albertel 7775:     $r->print("</form>");
1.157     albertel 7776:     return '';
1.75      albertel 7777: }
1.157     albertel 7778: 
1.557     raeburn  7779: sub graders_resources_pass {
                   7780:     my ($resources,$grader_partids_by_symb,$grader_randomlists_by_symb) = @_;
                   7781:     if ((ref($resources) eq 'ARRAY') && (ref($grader_partids_by_symb)) && 
                   7782:         (ref($grader_randomlists_by_symb) eq 'HASH')) {
                   7783:         foreach my $resource (@{$resources}) {
                   7784:             my $ressymb = $resource->symb();
                   7785:             my ($analysis,$parts) =
                   7786:                 &scantron_partids_tograde($resource,$env{'request.course.id'},
                   7787:                                           $env{'user.name'},$env{'user.domain'},1);
                   7788:             $grader_partids_by_symb->{$ressymb} = $parts;
                   7789:             if (ref($analysis) eq 'HASH') {
                   7790:                 if (ref($analysis->{'parts_withrandomlist'}) eq 'ARRAY') {
                   7791:                     $grader_randomlists_by_symb->{$ressymb} =
                   7792:                         $analysis->{'parts_withrandomlist'};
                   7793:                 }
                   7794:             }
                   7795:         }
                   7796:     }
                   7797:     return;
                   7798: }
                   7799: 
1.542     raeburn  7800: sub grade_student_bubbles {
1.554     raeburn  7801:     my ($r,$uname,$udom,$scan_record,$scancode,$resources,$parts) = @_;
                   7802:     if (ref($resources) eq 'ARRAY') {
                   7803:         my $count = 0;
                   7804:         foreach my $resource (@{$resources}) {
                   7805:             my $ressymb = $resource->symb();
                   7806:             my %form = ('submitted'      => 'scantron',
                   7807:                         'grade_target'   => 'grade',
                   7808:                         'grade_username' => $uname,
                   7809:                         'grade_domain'   => $udom,
                   7810:                         'grade_courseid' => $env{'request.course.id'},
                   7811:                         'grade_symb'     => $ressymb,
                   7812:                         'CODE'           => $scancode
                   7813:                        );
                   7814:             if (ref($parts) eq 'HASH') {
                   7815:                 if (ref($parts->{$ressymb}) eq 'ARRAY') {
                   7816:                     foreach my $part (@{$parts->{$ressymb}}) {
                   7817:                         $form{'scantron_questnum_start.'.$part} =
                   7818:                             1+$env{'form.scantron.first_bubble_line.'.$count};
                   7819:                         $count++;
                   7820:                     }
                   7821:                 }
                   7822:             }
                   7823:             my $result=&ssi_with_retries($resource->src(),$ssi_retries,%form);
                   7824:             return 'ssi_error' if ($ssi_error);
                   7825:             last if (&Apache::loncommon::connection_aborted($r));
                   7826:         }
1.542     raeburn  7827:     }
                   7828:     return;
                   7829: }
                   7830: 
1.157     albertel 7831: sub scantron_upload_scantron_data {
1.608     www      7832:     my ($r,$symb)=@_;
1.565     raeburn  7833:     my $dom = $env{'request.role.domain'};
                   7834:     my $domdesc = &Apache::lonnet::domain($dom,'description');
                   7835:     $r->print(&Apache::loncommon::coursebrowser_javascript($dom));
1.157     albertel 7836:     my $select_link=&Apache::loncommon::selectcourse_link('rules','courseid',
1.181     albertel 7837: 							  'domainid',
1.565     raeburn  7838: 							  'coursename',$dom);
                   7839:     my $syllabuslink = '<a href="javascript:ToSyllabus();">'.&mt('Syllabus').'</a>'.
                   7840:                        ('&nbsp'x2).&mt('(shows course personnel)'); 
1.608     www      7841:     my $default_form_data=&defaultFormData($symb);
1.579     raeburn  7842:     my $nofile_alert = &mt('Please use the browse button to select a file from your local directory.');
                   7843:     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 7844:     $r->print(&Apache::lonhtmlcommon::scripttag('
1.157     albertel 7845:     function checkUpload(formname) {
                   7846: 	if (formname.upfile.value == "") {
1.579     raeburn  7847: 	    alert("'.$nofile_alert.'");
1.157     albertel 7848: 	    return false;
                   7849: 	}
1.565     raeburn  7850:         if (formname.courseid.value == "") {
1.579     raeburn  7851:             alert("'.$nocourseid_alert.'");
1.565     raeburn  7852:             return false;
                   7853:         }
1.157     albertel 7854: 	formname.submit();
                   7855:     }
1.565     raeburn  7856: 
                   7857:     function ToSyllabus() {
                   7858:         var cdom = '."'$dom'".';
                   7859:         var cnum = document.rules.courseid.value;
                   7860:         if (cdom == "" || cdom == null) {
                   7861:             return;
                   7862:         }
                   7863:         if (cnum == "" || cnum == null) {
                   7864:            return;
                   7865:         }
                   7866:         syllwin=window.open("/public/"+cdom+"/"+cnum+"/syllabus","LONCAPASyllabus",
                   7867:                             "height=350,width=350,scrollbars=yes,menubar=no");
                   7868:         return;
                   7869:     }
                   7870: 
1.597     wenzelju 7871: '));
                   7872:     $r->print('
1.566     raeburn  7873: <h3>'.&mt('Send scanned bubblesheet data to a course').'</h3>
                   7874: 
1.492     albertel 7875: <form enctype="multipart/form-data" action="/adm/grades" name="rules" method="post">
1.565     raeburn  7876: '.$default_form_data.
                   7877:   &Apache::lonhtmlcommon::start_pick_box().
                   7878:   &Apache::lonhtmlcommon::row_title(&mt('Course ID')).
                   7879:   '<input name="courseid" type="text" size="30" />'.$select_link.
                   7880:   &Apache::lonhtmlcommon::row_closure().
                   7881:   &Apache::lonhtmlcommon::row_title(&mt('Course Name')).
                   7882:   '<input name="coursename" type="text" size="30" />'.$syllabuslink.
                   7883:   &Apache::lonhtmlcommon::row_closure().
                   7884:   &Apache::lonhtmlcommon::row_title(&mt('Domain')).
                   7885:   '<input name="domainid" type="hidden" />'.$domdesc.
                   7886:   &Apache::lonhtmlcommon::row_closure().
                   7887:   &Apache::lonhtmlcommon::row_title(&mt('File to upload')).
                   7888:   '<input type="file" name="upfile" size="50" />'.
                   7889:   &Apache::lonhtmlcommon::row_closure(1).
                   7890:   &Apache::lonhtmlcommon::end_pick_box().'<br />
                   7891: 
1.492     albertel 7892: <input name="command" value="scantronupload_save" type="hidden" />
1.589     bisitz   7893: <input type="button" onclick="javascript:checkUpload(this.form);" value="'.&mt('Upload Bubblesheet Data').'" />
1.157     albertel 7894: </form>
1.492     albertel 7895: ');
1.157     albertel 7896:     return '';
                   7897: }
                   7898: 
1.423     albertel 7899: 
1.157     albertel 7900: sub scantron_upload_scantron_data_save {
1.608     www      7901:     my($r,$symb)=@_;
1.182     albertel 7902:     my $doanotherupload=
                   7903: 	'<br /><form action="/adm/grades" method="post">'."\n".
                   7904: 	'<input type="hidden" name="command" value="scantronupload" />'."\n".
1.492     albertel 7905: 	'<input type="submit" name="submit" value="'.&mt('Do Another Upload').'" />'."\n".
1.182     albertel 7906: 	'</form>'."\n";
1.257     albertel 7907:     if (!&Apache::lonnet::allowed('usc',$env{'form.domainid'}) &&
1.162     albertel 7908: 	!&Apache::lonnet::allowed('usc',
1.257     albertel 7909: 			    $env{'form.domainid'}.'_'.$env{'form.courseid'})) {
1.575     www      7910: 	$r->print(&mt("You are not allowed to upload bubblesheet data to the requested course.")."<br />");
1.614     www      7911: 	unless ($symb) {
1.182     albertel 7912: 	    $r->print($doanotherupload);
                   7913: 	}
1.162     albertel 7914: 	return '';
                   7915:     }
1.257     albertel 7916:     my %coursedata=&Apache::lonnet::coursedescription($env{'form.domainid'}.'_'.$env{'form.courseid'});
1.568     raeburn  7917:     my $uploadedfile;
1.567     raeburn  7918:     $r->print('<h3>'.&mt("Uploading file to [_1]",$coursedata{'description'}).'</h3>');
1.257     albertel 7919:     if (length($env{'form.upfile'}) < 2) {
1.568     raeburn  7920:         $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 7921:     } else {
1.568     raeburn  7922:         my $result = 
                   7923:             &Apache::lonnet::userfileupload('upfile','','scantron','','','',
                   7924:                                             $env{'form.courseid'},$env{'form.domainid'});
                   7925: 	if ($result =~ m{^/uploaded/}) {
1.567     raeburn  7926: 	    $r->print(&mt('[_1]Success:[_2] Successfully uploaded [_3] bytes of data into location: [_4]',
                   7927:                           '<span class="LC_success">','</span>',(length($env{'form.upfile'})-1),
                   7928: 			  '<span class="LC_filename">'.$result.'</span>'));
1.568     raeburn  7929:             ($uploadedfile) = ($result =~ m{/([^/]+)$});
1.567     raeburn  7930:             $r->print(&validate_uploaded_scantron_file($env{'form.domainid'},
1.568     raeburn  7931:                                                        $env{'form.courseid'},$uploadedfile));
1.210     albertel 7932: 	} else {
1.567     raeburn  7933: 	    $r->print(&mt('[_1]Error:[_2] An error ([_3]) occurred when attempting to upload the file, [_4]',
                   7934:                           '<span class="LC_error">','</span>',$result,
1.568     raeburn  7935: 			  '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>'));
1.183     albertel 7936: 	}
                   7937:     }
1.174     albertel 7938:     if ($symb) {
1.612     www      7939: 	$r->print(&scantron_selectphase($r,$uploadedfile,$symb));
1.174     albertel 7940:     } else {
1.182     albertel 7941: 	$r->print($doanotherupload);
1.174     albertel 7942:     }
1.157     albertel 7943:     return '';
                   7944: }
                   7945: 
1.567     raeburn  7946: sub validate_uploaded_scantron_file {
                   7947:     my ($cdom,$cname,$fname) = @_;
                   7948:     my $scanlines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.$fname);
                   7949:     my @lines;
                   7950:     if ($scanlines ne '-1') {
                   7951:         @lines=split("\n",$scanlines,-1);
                   7952:     }
                   7953:     my $output;
                   7954:     if (@lines) {
                   7955:         my (%counts,$max_match_format);
                   7956:         my ($max_match_count,$max_match_pct) = (0,0);
                   7957:         my $classlist = &Apache::loncoursedata::get_classlist($cdom,$cname);
                   7958:         my %idmap = &username_to_idmap($classlist);
                   7959:         foreach my $key (keys(%idmap)) {
                   7960:             my $lckey = lc($key);
                   7961:             $idmap{$lckey} = $idmap{$key};
                   7962:         }
                   7963:         my %unique_formats;
                   7964:         my @formatlines = &get_scantronformat_file();
                   7965:         foreach my $line (@formatlines) {
                   7966:             chomp($line);
                   7967:             my @config = split(/:/,$line);
                   7968:             my $idstart = $config[5];
                   7969:             my $idlength = $config[6];
                   7970:             if (($idstart ne '') && ($idlength > 0)) {
                   7971:                 if (ref($unique_formats{$idstart.':'.$idlength}) eq 'ARRAY') {
                   7972:                     push(@{$unique_formats{$idstart.':'.$idlength}},$config[0].':'.$config[1]); 
                   7973:                 } else {
                   7974:                     $unique_formats{$idstart.':'.$idlength} = [$config[0].':'.$config[1]];
                   7975:                 }
                   7976:             }
                   7977:         }
                   7978:         foreach my $key (keys(%unique_formats)) {
                   7979:             my ($idstart,$idlength) = split(':',$key);
                   7980:             %{$counts{$key}} = (
                   7981:                                'found'   => 0,
                   7982:                                'total'   => 0,
                   7983:                               );
                   7984:             foreach my $line (@lines) {
                   7985:                 next if ($line =~ /^#/);
                   7986:                 next if ($line =~ /^[\s\cz]*$/);
                   7987:                 my $id = substr($line,$idstart-1,$idlength);
                   7988:                 $id = lc($id);
                   7989:                 if (exists($idmap{$id})) {
                   7990:                     $counts{$key}{'found'} ++;
                   7991:                 }
                   7992:                 $counts{$key}{'total'} ++;
                   7993:             }
                   7994:             if ($counts{$key}{'total'}) {
                   7995:                 my $percent_match = (100*$counts{$key}{'found'})/($counts{$key}{'total'});
                   7996:                 if (($max_match_format eq '') || ($percent_match > $max_match_pct)) {
                   7997:                     $max_match_pct = $percent_match;
                   7998:                     $max_match_format = $key;
                   7999:                     $max_match_count = $counts{$key}{'total'};
                   8000:                 }
                   8001:             }
                   8002:         }
                   8003:         if (ref($unique_formats{$max_match_format}) eq 'ARRAY') {
                   8004:             my $format_descs;
                   8005:             my $numwithformat = @{$unique_formats{$max_match_format}};
                   8006:             for (my $i=0; $i<$numwithformat; $i++) {
                   8007:                 my ($name,$desc) = split(':',$unique_formats{$max_match_format}[$i]);
                   8008:                 if ($i<$numwithformat-2) {
                   8009:                     $format_descs .= '"<i>'.$desc.'</i>", ';
                   8010:                 } elsif ($i==$numwithformat-2) {
                   8011:                     $format_descs .= '"<i>'.$desc.'</i>" '.&mt('and').' ';
                   8012:                 } elsif ($i==$numwithformat-1) {
                   8013:                     $format_descs .= '"<i>'.$desc.'</i>"';
                   8014:                 }
                   8015:             }
                   8016:             my $showpct = sprintf("%.0f",$max_match_pct).'%';
                   8017:             $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).
                   8018:                        '<br />'.&mt('A low percentage of matches results from one of the following:').'<ul>'.
                   8019:                        '<li>'.&mt('The file was uploaded to the wrong course').'</li>'.
                   8020:                        '<li>'.&mt('The data are not in the format expected for the domain: [_1]',
                   8021:                                   '<i>'.$cdom.'</i>').'</li>'.
                   8022:                        '<li>'.&mt('Students did not bubble their IDs, or mis-bubbled them').'</li>'.
                   8023:                        '<li>'.&mt('The course roster is not up to date').'</li>'.
                   8024:                        '</ul>';
                   8025:         }
                   8026:     } else {
                   8027:         $output = '<span class="LC_warning">'.&mt('Uploaded file contained no data').'</span>';
                   8028:     }
                   8029:     return $output;
                   8030: }
                   8031: 
1.202     albertel 8032: sub valid_file {
                   8033:     my ($requested_file)=@_;
                   8034:     foreach my $filename (sort(&scantron_filenames())) {
                   8035: 	if ($requested_file eq $filename) { return 1; }
                   8036:     }
                   8037:     return 0;
                   8038: }
                   8039: 
                   8040: sub scantron_download_scantron_data {
1.608     www      8041:     my ($r,$symb)=@_;
                   8042:     my $default_form_data=&defaultFormData($symb);
1.257     albertel 8043:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   8044:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   8045:     my $file=$env{'form.scantron_selectfile'};
1.202     albertel 8046:     if (! &valid_file($file)) {
1.492     albertel 8047: 	$r->print('
1.202     albertel 8048: 	<p>
1.492     albertel 8049: 	    '.&mt('The requested file name was invalid.').'
1.202     albertel 8050:         </p>
1.492     albertel 8051: ');
1.202     albertel 8052: 	return;
                   8053:     }
                   8054:     my $orig='/uploaded/'.$cdom.'/'.$cname.'/scantron_orig_'.$file;
                   8055:     my $corrected='/uploaded/'.$cdom.'/'.$cname.'/scantron_corrected_'.$file;
                   8056:     my $skipped='/uploaded/'.$cdom.'/'.$cname.'/scantron_skipped_'.$file;
                   8057:     &Apache::lonnet::allowuploaded('/adm/grades',$orig);
                   8058:     &Apache::lonnet::allowuploaded('/adm/grades',$corrected);
                   8059:     &Apache::lonnet::allowuploaded('/adm/grades',$skipped);
1.492     albertel 8060:     $r->print('
1.202     albertel 8061:     <p>
1.492     albertel 8062: 	'.&mt('[_1]Original[_2] file as uploaded by the scantron office.',
                   8063: 	      '<a href="'.$orig.'">','</a>').'
1.202     albertel 8064:     </p>
                   8065:     <p>
1.492     albertel 8066: 	'.&mt('[_1]Corrections[_2], a file of corrected records that were used in grading.',
                   8067: 	      '<a href="'.$corrected.'">','</a>').'
1.202     albertel 8068:     </p>
                   8069:     <p>
1.492     albertel 8070: 	'.&mt('[_1]Skipped[_2], a file of records that were skipped.',
                   8071: 	      '<a href="'.$skipped.'">','</a>').'
1.202     albertel 8072:     </p>
1.492     albertel 8073: ');
1.202     albertel 8074:     return '';
                   8075: }
1.157     albertel 8076: 
1.523     raeburn  8077: sub checkscantron_results {
1.608     www      8078:     my ($r,$symb) = @_;
1.523     raeburn  8079:     if (!$symb) {return '';}
                   8080:     my $cid = $env{'request.course.id'};
1.542     raeburn  8081:     my %lettdig = &letter_to_digits();
1.523     raeburn  8082:     my $numletts = scalar(keys(%lettdig));
                   8083:     my $cnum = $env{'course.'.$cid.'.num'};
                   8084:     my $cdom = $env{'course.'.$cid.'.domain'};
                   8085:     my (undef, undef, $sequence) = &Apache::lonnet::decode_symb($env{'form.selectpage'});
                   8086:     my %record;
                   8087:     my %scantron_config =
                   8088:         &Apache::grades::get_scantron_config($env{'form.scantron_format'});
                   8089:     my ($scanlines,$scan_data)=&Apache::grades::scantron_getfile();
                   8090:     my $classlist=&Apache::loncoursedata::get_classlist();
                   8091:     my %idmap=&Apache::grades::username_to_idmap($classlist);
                   8092:     my $navmap=Apache::lonnavmaps::navmap->new();
1.582     raeburn  8093:     unless (ref($navmap)) {
                   8094:         $r->print(&navmap_errormsg());
                   8095:         return '';
                   8096:     }
1.523     raeburn  8097:     my $map=$navmap->getResourceByUrl($sequence);
1.557     raeburn  8098:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
                   8099:     my (%grader_partids_by_symb,%grader_randomlists_by_symb);
                   8100:     &graders_resources_pass(\@resources,\%grader_partids_by_symb,                             \%grader_randomlists_by_symb);
                   8101: 
1.554     raeburn  8102:     my ($uname,$udom);
1.523     raeburn  8103:     my (%scandata,%lastname,%bylast);
                   8104:     $r->print('
                   8105: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="checkscantron">'."\n");
                   8106: 
                   8107:     my @delayqueue;
                   8108:     my %completedstudents;
                   8109: 
                   8110:     my $count=&Apache::grades::get_todo_count($scanlines,$scan_data);
1.581     www      8111:     my %prog_state=&Apache::lonhtmlcommon::Create_PrgWin($r,'Bubblesheet/Submissions Comparison Status',
                   8112:                                     'Progress of Bubblesheet Data/Submission Records Comparison',$count,
1.523     raeburn  8113:                                     'inline',undef,'checkscantron');
1.546     raeburn  8114:     my ($username,$domain,$started);
1.582     raeburn  8115:     my $nav_error;
                   8116:     &scantron_get_maxbubble(\$nav_error); # Need the bubble lines array to parse.
                   8117:     if ($nav_error) {
                   8118:         $r->print(&navmap_errormsg());
                   8119:         return '';
                   8120:     }
1.523     raeburn  8121: 
                   8122:     &Apache::lonhtmlcommon::Update_PrgWin($r,\%prog_state,
                   8123:                                           'Processing first student');
                   8124:     my $start=&Time::HiRes::time();
                   8125:     my $i=-1;
                   8126: 
                   8127:     while ($i<$scanlines->{'count'}) {
                   8128:         ($username,$domain,$uname)=('','','');
                   8129:         $i++;
                   8130:         my $line=&Apache::grades::scantron_get_line($scanlines,$scan_data,$i);
                   8131:         if ($line=~/^[\s\cz]*$/) { next; }
                   8132:         if ($started) {
                   8133:             &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state,
                   8134:                                                      'last student');
                   8135:         }
                   8136:         $started=1;
                   8137:         my $scan_record=
                   8138:             &Apache::grades::scantron_parse_scanline($line,$i,\%scantron_config,
                   8139:                                                      $scan_data);
                   8140:         unless ($uname=&Apache::grades::scantron_find_student($scan_record,$scan_data,
                   8141:                                                               \%idmap,$i)) {
                   8142:             &Apache::grades::scantron_add_delay(\@delayqueue,$line,
                   8143:                                 'Unable to find a student that matches',1);
                   8144:             next;
                   8145:         }
                   8146:         if (exists $completedstudents{$uname}) {
                   8147:             &Apache::grades::scantron_add_delay(\@delayqueue,$line,
                   8148:                                 'Student '.$uname.' has multiple sheets',2);
                   8149:             next;
                   8150:         }
                   8151:         my $pid = $scan_record->{'scantron.ID'};
                   8152:         $lastname{$pid} = $scan_record->{'scantron.LastName'};
                   8153:         push(@{$bylast{$lastname{$pid}}},$pid);
                   8154:         my $lastpos = $env{'form.scantron_maxbubble'}*$scantron_config{'Qlength'};
                   8155:         $scandata{$pid} = substr($line,$scantron_config{'Qstart'}-1,$lastpos);
                   8156:         chomp($scandata{$pid});
                   8157:         $scandata{$pid} =~ s/\r$//;
                   8158:         ($username,$domain)=split(/:/,$uname);
                   8159:         my $counter = -1;
                   8160:         foreach my $resource (@resources) {
1.557     raeburn  8161:             my $parts;
1.554     raeburn  8162:             my $ressymb = $resource->symb();
1.557     raeburn  8163:             if ((exists($grader_randomlists_by_symb{$ressymb})) ||
                   8164:                 (ref($grader_partids_by_symb{$ressymb}) ne 'ARRAY')) {
                   8165:                 (my $analysis,$parts) =
                   8166:                     &scantron_partids_tograde($resource,$env{'request.course.id'},$username,$domain);
                   8167:             } else {
                   8168:                 $parts = $grader_partids_by_symb{$ressymb};
                   8169:             }
1.542     raeburn  8170:             ($counter,my $recording) =
                   8171:                 &verify_scantron_grading($resource,$domain,$username,$cid,$counter,
1.554     raeburn  8172:                                          $scandata{$pid},$parts,
1.542     raeburn  8173:                                          \%scantron_config,\%lettdig,$numletts);
                   8174:             $record{$pid} .= $recording;
1.523     raeburn  8175:         }
                   8176:     }
                   8177:     &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
                   8178:     $r->print('<br />');
                   8179:     my ($okstudents,$badstudents,$numstudents,$passed,$failed);
                   8180:     $passed = 0;
                   8181:     $failed = 0;
                   8182:     $numstudents = 0;
                   8183:     foreach my $last (sort(keys(%bylast))) {
                   8184:         if (ref($bylast{$last}) eq 'ARRAY') {
                   8185:             foreach my $pid (sort(@{$bylast{$last}})) {
                   8186:                 my $showscandata = $scandata{$pid};
                   8187:                 my $showrecord = $record{$pid};
                   8188:                 $showscandata =~ s/\s/&nbsp;/g;
                   8189:                 $showrecord =~ s/\s/&nbsp;/g;
                   8190:                 if ($scandata{$pid} eq $record{$pid}) {
                   8191:                     my $css_class = ($passed % 2)?'LC_odd_row':'LC_even_row';
                   8192:                     $okstudents .= '<tr class="'.$css_class.'">'.
1.581     www      8193: '<td>'.&mt('Bubblesheet').'</td><td>'.$showscandata.'</td><td rowspan="2">'.$last.'</td><td rowspan="2">'.$pid.'</td>'."\n".
1.523     raeburn  8194: '</tr>'."\n".
                   8195: '<tr class="'.$css_class.'">'."\n".
                   8196: '<td>Submissions</td><td>'.$showrecord.'</td></tr>'."\n";
                   8197:                     $passed ++;
                   8198:                 } else {
                   8199:                     my $css_class = ($failed % 2)?'LC_odd_row':'LC_even_row';
1.581     www      8200:                     $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  8201: '</tr>'."\n".
                   8202: '<tr class="'.$css_class.'">'."\n".
                   8203: '<td>Submissions</td><td><span class="LC_nobreak">'.$record{$pid}.'</span></td>'."\n".
                   8204: '</tr>'."\n";
                   8205:                     $failed ++;
                   8206:                 }
                   8207:                 $numstudents ++;
                   8208:             }
                   8209:         }
                   8210:     }
1.572     www      8211:     $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  8212:     $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>');
                   8213:     if ($passed) {
1.572     www      8214:         $r->print(&mt('Students with exact correspondence between bubblesheet data and submissions are as follows:').'<br /><br />');
1.523     raeburn  8215:         $r->print(&Apache::loncommon::start_data_table()."\n".
                   8216:                  &Apache::loncommon::start_data_table_header_row()."\n".
                   8217:                  '<th>'.&mt('Source').'</th><th>'.&mt('Bubble records').'</th><th>'.&mt('Name').'</th><th>'.&mt('ID').'</th>'.
                   8218:                  &Apache::loncommon::end_data_table_header_row()."\n".
                   8219:                  $okstudents."\n".
                   8220:                  &Apache::loncommon::end_data_table().'<br />');
                   8221:     }
                   8222:     if ($failed) {
1.572     www      8223:         $r->print(&mt('Students with differences between bubblesheet data and submissions are as follows:').'<br /><br />');
1.523     raeburn  8224:         $r->print(&Apache::loncommon::start_data_table()."\n".
                   8225:                  &Apache::loncommon::start_data_table_header_row()."\n".
                   8226:                  '<th>'.&mt('Source').'</th><th>'.&mt('Bubble records').'</th><th>'.&mt('Name').'</th><th>'.&mt('ID').'</th>'.
                   8227:                  &Apache::loncommon::end_data_table_header_row()."\n".
                   8228:                  $badstudents."\n".
                   8229:                  &Apache::loncommon::end_data_table()).'<br />'.
1.572     www      8230:                  &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  8231:     }
1.614     www      8232:     $r->print('</form><br />');
1.523     raeburn  8233:     return;
                   8234: }
                   8235: 
1.542     raeburn  8236: sub verify_scantron_grading {
1.554     raeburn  8237:     my ($resource,$domain,$username,$cid,$counter,$scandata,$partids,
1.542     raeburn  8238:         $scantron_config,$lettdig,$numletts) = @_;
                   8239:     my ($record,%expected,%startpos);
                   8240:     return ($counter,$record) if (!ref($resource));
                   8241:     return ($counter,$record) if (!$resource->is_problem());
                   8242:     my $symb = $resource->symb();
1.554     raeburn  8243:     return ($counter,$record) if (ref($partids) ne 'ARRAY');
                   8244:     foreach my $part_id (@{$partids}) {
1.542     raeburn  8245:         $counter ++;
                   8246:         $expected{$part_id} = 0;
                   8247:         if ($env{"form.scantron.sub_bubblelines.$counter"}) {
                   8248:             my @sub_lines = split(/,/,$env{"form.scantron.sub_bubblelines.$counter"});
                   8249:             foreach my $item (@sub_lines) {
                   8250:                 $expected{$part_id} += $item;
                   8251:             }
                   8252:         } else {
                   8253:             $expected{$part_id} = $env{"form.scantron.bubblelines.$counter"};
                   8254:         }
                   8255:         $startpos{$part_id} = $env{"form.scantron.first_bubble_line.$counter"};
                   8256:     }
                   8257:     if ($symb) {
                   8258:         my %recorded;
                   8259:         my (%returnhash) = &Apache::lonnet::restore($symb,$cid,$domain,$username);
                   8260:         if ($returnhash{'version'}) {
                   8261:             my %lasthash=();
                   8262:             my $version;
                   8263:             for ($version=1;$version<=$returnhash{'version'};$version++) {
                   8264:                 foreach my $key (sort(split(/\:/,$returnhash{$version.':keys'}))) {
                   8265:                     $lasthash{$key}=$returnhash{$version.':'.$key};
                   8266:                 }
                   8267:             }
                   8268:             foreach my $key (keys(%lasthash)) {
                   8269:                 if ($key =~ /\.scantron$/) {
                   8270:                     my $value = &unescape($lasthash{$key});
                   8271:                     my ($part_id) = ($key =~ /^resource\.(.+)\.scantron$/);
                   8272:                     if ($value eq '') {
                   8273:                         for (my $i=0; $i<$expected{$part_id}; $i++) {
                   8274:                             for (my $j=0; $j<$scantron_config->{'length'}; $j++) {
                   8275:                                 $recorded{$part_id} .= $scantron_config->{'Qoff'};
                   8276:                             }
                   8277:                         }
                   8278:                     } else {
                   8279:                         my @tocheck;
                   8280:                         my @items = split(//,$value);
                   8281:                         if (($scantron_config->{'Qon'} eq 'letter') ||
                   8282:                             ($scantron_config->{'Qon'} eq 'number')) {
                   8283:                             if (@items < $expected{$part_id}) {
                   8284:                                 my $fragment = substr($scandata,$startpos{$part_id},$expected{$part_id});
                   8285:                                 my @singles = split(//,$fragment);
                   8286:                                 foreach my $pos (@singles) {
                   8287:                                     if ($pos eq ' ') {
                   8288:                                         push(@tocheck,$pos);
                   8289:                                     } else {
                   8290:                                         my $next = shift(@items);
                   8291:                                         push(@tocheck,$next);
                   8292:                                     }
                   8293:                                 }
                   8294:                             } else {
                   8295:                                 @tocheck = @items;
                   8296:                             }
                   8297:                             foreach my $letter (@tocheck) {
                   8298:                                 if ($scantron_config->{'Qon'} eq 'letter') {
                   8299:                                     if ($letter !~ /^[A-J]$/) {
                   8300:                                         $letter = $scantron_config->{'Qoff'};
                   8301:                                     }
                   8302:                                     $recorded{$part_id} .= $letter;
                   8303:                                 } elsif ($scantron_config->{'Qon'} eq 'number') {
                   8304:                                     my $digit;
                   8305:                                     if ($letter !~ /^[A-J]$/) {
                   8306:                                         $digit = $scantron_config->{'Qoff'};
                   8307:                                     } else {
                   8308:                                         $digit = $lettdig->{$letter};
                   8309:                                     }
                   8310:                                     $recorded{$part_id} .= $digit;
                   8311:                                 }
                   8312:                             }
                   8313:                         } else {
                   8314:                             @tocheck = @items;
                   8315:                             for (my $i=0; $i<$expected{$part_id}; $i++) {
                   8316:                                 my $curr_sub = shift(@tocheck);
                   8317:                                 my $digit;
                   8318:                                 if ($curr_sub =~ /^[A-J]$/) {
                   8319:                                     $digit = $lettdig->{$curr_sub}-1;
                   8320:                                 }
                   8321:                                 if ($curr_sub eq 'J') {
                   8322:                                     $digit += scalar($numletts);
                   8323:                                 }
                   8324:                                 for (my $j=0; $j<$scantron_config->{'Qlength'}; $j++) {
                   8325:                                     if ($j == $digit) {
                   8326:                                         $recorded{$part_id} .= $scantron_config->{'Qon'};
                   8327:                                     } else {
                   8328:                                         $recorded{$part_id} .= $scantron_config->{'Qoff'};
                   8329:                                     }
                   8330:                                 }
                   8331:                             }
                   8332:                         }
                   8333:                     }
                   8334:                 }
                   8335:             }
                   8336:         }
1.554     raeburn  8337:         foreach my $part_id (@{$partids}) {
1.542     raeburn  8338:             if ($recorded{$part_id} eq '') {
                   8339:                 for (my $i=0; $i<$expected{$part_id}; $i++) {
                   8340:                     for (my $j=0; $j<$scantron_config->{'Qlength'}; $j++) {
                   8341:                         $recorded{$part_id} .= $scantron_config->{'Qoff'};
                   8342:                     }
                   8343:                 }
                   8344:             }
                   8345:             $record .= $recorded{$part_id};
                   8346:         }
                   8347:     }
                   8348:     return ($counter,$record);
                   8349: }
                   8350: 
                   8351: sub letter_to_digits { 
                   8352:     my %lettdig = (
                   8353:                     A => 1,
                   8354:                     B => 2,
                   8355:                     C => 3,
                   8356:                     D => 4,
                   8357:                     E => 5,
                   8358:                     F => 6,
                   8359:                     G => 7,
                   8360:                     H => 8,
                   8361:                     I => 9,
                   8362:                     J => 0,
                   8363:                   );
                   8364:     return %lettdig;
                   8365: }
                   8366: 
1.423     albertel 8367: 
1.75      albertel 8368: #-------- end of section for handling grading scantron forms -------
                   8369: #
                   8370: #-------------------------------------------------------------------
                   8371: 
1.72      ng       8372: #-------------------------- Menu interface -------------------------
                   8373: #
1.614     www      8374: #--- Href with symb and command ---
                   8375: 
                   8376: sub href_symb_cmd {
                   8377:     my ($symb,$cmd)=@_;
                   8378:     return '/adm/grades?symb='.&HTML::Entities::encode(&Apache::lonenc::check_encrypt($symb),'<>&"').'&command='.$cmd;
1.72      ng       8379: }
                   8380: 
1.443     banghart 8381: sub grading_menu {
1.608     www      8382:     my ($request,$symb) = @_;
1.443     banghart 8383:     if (!$symb) {return '';}
                   8384: 
                   8385:     my %fields = ('symb'=>&Apache::lonenc::check_encrypt($symb),
1.618     www      8386:                   'command'=>'individual');
1.538     schulted 8387:     
1.598     www      8388:     my $url1a = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   8389: 
                   8390:     $fields{'command'}='ungraded';
                   8391:     my $url1b=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   8392: 
                   8393:     $fields{'command'}='table';
                   8394:     my $url1c=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   8395: 
                   8396:     $fields{'command'}='all_for_one';
                   8397:     my $url1d=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   8398: 
1.621     www      8399:     $fields{'command'}='downloadfilesselect';
                   8400:     my $url1e=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   8401: 
1.443     banghart 8402:     $fields{'command'} = 'csvform';
1.538     schulted 8403:     my $url2 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   8404:     
1.443     banghart 8405:     $fields{'command'} = 'processclicker';
1.538     schulted 8406:     my $url3 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   8407:     
1.443     banghart 8408:     $fields{'command'} = 'scantron_selectphase';
1.538     schulted 8409:     my $url4 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
1.602     www      8410: 
                   8411:     $fields{'command'} = 'initialverifyreceipt';
                   8412:     my $url5 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
1.538     schulted 8413:     
1.598     www      8414:     my @menu = ({	categorytitle=>'Hand Grading',
1.538     schulted 8415:             items =>[
1.598     www      8416:                         {	linktext => 'Select individual students to grade',
                   8417:                     		url => $url1a,
1.538     schulted 8418:                     		permission => 'F',
                   8419:                     		icon => 'edit-find-replace.png',
1.598     www      8420:                     		linktitle => 'Grade current resource for a selection of students.'
                   8421:                         }, 
                   8422:                         {       linktext => 'Grade ungraded submissions.',
                   8423:                                 url => $url1b,
                   8424:                                 permission => 'F',
                   8425:                                 icon => 'edit-find-replace.png',
                   8426:                                 linktitle => 'Grade all submissions that have not been graded yet.'
1.538     schulted 8427:                         },
1.598     www      8428: 
                   8429:                         {       linktext => 'Grading table',
                   8430:                                 url => $url1c,
                   8431:                                 permission => 'F',
                   8432:                                 icon => 'edit-find-replace.png',
                   8433:                                 linktitle => 'Grade current resource for all students.'
                   8434:                         },
1.615     www      8435:                         {       linktext => 'Grade page/folder for one student',
1.598     www      8436:                                 url => $url1d,
                   8437:                                 permission => 'F',
                   8438:                                 icon => 'edit-find-replace.png',
                   8439:                                 linktitle => 'Grade all resources in current page/sequence/folder for one student.'
1.621     www      8440:                         },
                   8441:                         {       linktext => 'Download submissions',
                   8442:                                 url => $url1e,
                   8443:                                 permission => 'F',
                   8444:                                 icon => 'edit-find-replace.png',
                   8445:                                 linktitle => 'Download all students submissions.'
1.598     www      8446:                         }]},
                   8447:                          { categorytitle=>'Automated Grading',
                   8448:                items =>[
                   8449: 
1.538     schulted 8450:                 	    {	linktext => 'Upload Scores',
                   8451:                     		url => $url2,
                   8452:                     		permission => 'F',
                   8453:                     		icon => 'uploadscores.png',
                   8454:                     		linktitle => 'Specify a file containing the class scores for current resource.'
                   8455:                 	    },
                   8456:                 	    {	linktext => 'Process Clicker',
                   8457:                     		url => $url3,
                   8458:                     		permission => 'F',
                   8459:                     		icon => 'addClickerInfoFile.png',
                   8460:                     		linktitle => 'Specify a file containing the clicker information for this resource.'
                   8461:                 	    },
1.587     raeburn  8462:                 	    {	linktext => 'Grade/Manage/Review Bubblesheets',
1.538     schulted 8463:                     		url => $url4,
                   8464:                     		permission => 'F',
                   8465:                     		icon => 'stat.png',
                   8466:                     		linktitle => 'Grade scantron exams, upload/download scantron data files, and review previously graded scantron exams.'
1.602     www      8467:                 	    },
1.616     www      8468:                             {   linktext => 'Verify Receipt Number',
1.602     www      8469:                                 url => $url5,
                   8470:                                 permission => 'F',
                   8471:                                 icon => 'edit-find-replace.png',
                   8472:                                 linktitle => 'Verify a system-generated receipt number for correct problem solution.'
                   8473:                             }
                   8474: 
1.538     schulted 8475:                     ]
                   8476:             });
                   8477: 
1.443     banghart 8478:     # Create the menu
                   8479:     my $Str;
1.445     banghart 8480:     $Str .= '<form method="post" action="" name="gradingMenu">';
                   8481:     $Str .= '<input type="hidden" name="command" value="" />'.
1.618     www      8482:     	'<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
1.445     banghart 8483: 
1.602     www      8484:     $Str .= &Apache::lonhtmlcommon::generate_menu(@menu);
1.443     banghart 8485:     return $Str;    
                   8486: }
                   8487: 
1.598     www      8488: 
                   8489: sub ungraded {
                   8490:     my ($request)=@_;
                   8491:     &submit_options($request);
                   8492: }
                   8493: 
1.599     www      8494: sub submit_options_sequence {
1.608     www      8495:     my ($request,$symb) = @_;
1.599     www      8496:     if (!$symb) {return '';}
1.600     www      8497:     &commonJSfunctions($request);
                   8498:     my $result;
1.599     www      8499: 
1.600     www      8500:     $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
1.618     www      8501:         '<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
1.600     www      8502:     $result.='
                   8503: <h2>
1.615     www      8504:   '.&mt('Grade page/folder for one student').'
1.601     www      8505: </h2>'.
                   8506:             &selectfield(0).
                   8507:             '<input type="hidden" name="command" value="pickStudentPage" />
1.600     www      8508:             <div>
                   8509:               <input type="submit" value="'.&mt('Next').' &rarr;" />
                   8510:             </div>
                   8511:         </div>
                   8512:   </form>';
                   8513:     return $result;
                   8514: }
                   8515: 
                   8516: sub submit_options_table {
1.608     www      8517:     my ($request,$symb) = @_;
1.600     www      8518:     if (!$symb) {return '';}
1.599     www      8519:     &commonJSfunctions($request);
                   8520:     my $result;
                   8521: 
                   8522:     $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
1.618     www      8523:         '<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
1.599     www      8524: 
                   8525:     $result.='
                   8526: <h2>
1.600     www      8527:   '.&mt('Grading table').'
1.601     www      8528: </h2>'.
                   8529:             &selectfield(0).
                   8530:             '<input type="hidden" name="command" value="viewgrades" />
1.599     www      8531:             <div>
                   8532:               <input type="submit" value="'.&mt('Next').' &rarr;" />
                   8533:             </div>
                   8534:         </div>
                   8535:   </form>';
                   8536:     return $result;
                   8537: }
1.443     banghart 8538: 
1.621     www      8539: sub submit_options_download {
                   8540:     my ($request,$symb) = @_;
                   8541:     if (!$symb) {return '';}
                   8542: 
                   8543:     &commonJSfunctions($request);
                   8544: 
                   8545:     my $result='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
                   8546:         '<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
                   8547:     $result.='
                   8548: <h2>
                   8549:   '.&mt('Select Students for Which to Download Submissions').'
                   8550: </h2>'.&selectfield(1).'
                   8551:                 <input type="hidden" name="command" value="downloadfileslink" /> 
                   8552:               <input type="submit" value="'.&mt('Next').' &rarr;" />
                   8553:             </div>
                   8554:           </div>
1.600     www      8555: 
                   8556: 
1.621     www      8557:   </form>';
                   8558:     return $result;
                   8559: }
                   8560: 
1.443     banghart 8561: #--- Displays the submissions first page -------
                   8562: sub submit_options {
1.608     www      8563:     my ($request,$symb) = @_;
1.72      ng       8564:     if (!$symb) {return '';}
                   8565: 
1.118     ng       8566:     &commonJSfunctions($request);
1.473     albertel 8567:     my $result;
1.533     bisitz   8568: 
1.72      ng       8569:     $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
1.618     www      8570: 	'<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
1.472     albertel 8571:     $result.='
1.533     bisitz   8572: <h2>
1.600     www      8573:   '.&mt('Select individual students to grade').'
1.601     www      8574: </h2>'.&selectfield(1).'
                   8575:                 <input type="hidden" name="command" value="submission" /> 
                   8576: 	      <input type="submit" value="'.&mt('Next').' &rarr;" />
                   8577:             </div>
                   8578:           </div>
                   8579: 
                   8580: 
                   8581:   </form>';
                   8582:     return $result;
                   8583: }
1.533     bisitz   8584: 
1.601     www      8585: sub selectfield {
                   8586:    my ($full)=@_;
                   8587:    my $result='<div class="LC_columnSection">
1.537     harmsja  8588:   
1.533     bisitz   8589:     <fieldset>
                   8590:       <legend>
                   8591:        '.&mt('Sections').'
                   8592:       </legend>
1.601     www      8593:       '.&Apache::lonstatistics::SectionSelect('section','multiple',5).'
1.533     bisitz   8594:     </fieldset>
1.537     harmsja  8595:   
1.533     bisitz   8596:     <fieldset>
                   8597:       <legend>
                   8598:         '.&mt('Groups').'
                   8599:       </legend>
                   8600:       '.&Apache::lonstatistics::GroupSelect('group','multiple',5).'
                   8601:     </fieldset>
1.537     harmsja  8602:   
1.533     bisitz   8603:     <fieldset>
                   8604:       <legend>
                   8605:         '.&mt('Access Status').'
                   8606:       </legend>
1.601     www      8607:       '.&Apache::lonhtmlcommon::StatusOptions(undef,undef,5,undef,'mult').'
                   8608:     </fieldset>';
                   8609:     if ($full) {
                   8610:        $result.='
1.533     bisitz   8611:     <fieldset>
                   8612:       <legend>
                   8613:         '.&mt('Submission Status').'
1.601     www      8614:       </legend>'.
                   8615:        &Apache::loncommon::select_form('all','submitonly',
                   8616:           (&Apache::lonlocal::texthash(
                   8617:              'yes'       => 'with submissions',
                   8618:              'queued'    => 'in grading queue',
                   8619:              'graded'    => 'with ungraded submissions',
                   8620:              'incorrect' => 'with incorrect submissions',
                   8621:              'all'       => 'with any status'),
                   8622:              'select_form_order' => ['yes','queued','graded','incorrect','all'])).
                   8623:    '</fieldset>';
                   8624:     }
                   8625:     $result.='</div><br />';
1.44      ng       8626:     return $result;
1.2       albertel 8627: }
                   8628: 
1.285     albertel 8629: sub reset_perm {
                   8630:     undef(%perm);
                   8631: }
                   8632: 
                   8633: sub init_perm {
                   8634:     &reset_perm();
1.300     albertel 8635:     foreach my $test_perm ('vgr','mgr','opa') {
                   8636: 
                   8637: 	my $scope = $env{'request.course.id'};
                   8638: 	if (!($perm{$test_perm}=&Apache::lonnet::allowed($test_perm,$scope))) {
                   8639: 
                   8640: 	    $scope .= '/'.$env{'request.course.sec'};
                   8641: 	    if ( $perm{$test_perm}=
                   8642: 		 &Apache::lonnet::allowed($test_perm,$scope)) {
                   8643: 		$perm{$test_perm.'_section'}=$env{'request.course.sec'};
                   8644: 	    } else {
                   8645: 		delete($perm{$test_perm});
                   8646: 	    }
1.285     albertel 8647: 	}
                   8648:     }
                   8649: }
                   8650: 
1.400     www      8651: sub gather_clicker_ids {
1.408     albertel 8652:     my %clicker_ids;
1.400     www      8653: 
                   8654:     my $classlist = &Apache::loncoursedata::get_classlist();
                   8655: 
                   8656:     # Set up a couple variables.
1.407     albertel 8657:     my $username_idx = &Apache::loncoursedata::CL_SNAME();
                   8658:     my $domain_idx   = &Apache::loncoursedata::CL_SDOM();
1.438     www      8659:     my $status_idx   = &Apache::loncoursedata::CL_STATUS();
1.400     www      8660: 
1.407     albertel 8661:     foreach my $student (keys(%$classlist)) {
1.438     www      8662:         if ($classlist->{$student}->[$status_idx] ne 'Active') { next; }
1.407     albertel 8663:         my $username = $classlist->{$student}->[$username_idx];
                   8664:         my $domain   = $classlist->{$student}->[$domain_idx];
1.400     www      8665:         my $clickers =
1.408     albertel 8666: 	    (&Apache::lonnet::userenvironment($domain,$username,'clickers'))[1];
1.400     www      8667:         foreach my $id (split(/\,/,$clickers)) {
1.414     www      8668:             $id=~s/^[\#0]+//;
1.421     www      8669:             $id=~s/[\-\:]//g;
1.407     albertel 8670:             if (exists($clicker_ids{$id})) {
1.408     albertel 8671: 		$clicker_ids{$id}.=','.$username.':'.$domain;
1.400     www      8672:             } else {
1.408     albertel 8673: 		$clicker_ids{$id}=$username.':'.$domain;
1.400     www      8674:             }
                   8675:         }
                   8676:     }
1.407     albertel 8677:     return %clicker_ids;
1.400     www      8678: }
                   8679: 
1.402     www      8680: sub gather_adv_clicker_ids {
1.408     albertel 8681:     my %clicker_ids;
1.402     www      8682:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
                   8683:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   8684:     my %coursepersonnel=&Apache::lonnet::get_course_adv_roles($cdom.'/'.$cnum);
1.409     albertel 8685:     foreach my $element (sort(keys(%coursepersonnel))) {
1.402     www      8686:         foreach my $person (split(/\,/,$coursepersonnel{$element})) {
                   8687:             my ($puname,$pudom)=split(/\:/,$person);
                   8688:             my $clickers =
1.408     albertel 8689: 		(&Apache::lonnet::userenvironment($pudom,$puname,'clickers'))[1];
1.405     www      8690:             foreach my $id (split(/\,/,$clickers)) {
1.414     www      8691: 		$id=~s/^[\#0]+//;
1.421     www      8692:                 $id=~s/[\-\:]//g;
1.408     albertel 8693: 		if (exists($clicker_ids{$id})) {
                   8694: 		    $clicker_ids{$id}.=','.$puname.':'.$pudom;
                   8695: 		} else {
                   8696: 		    $clicker_ids{$id}=$puname.':'.$pudom;
                   8697: 		}
1.405     www      8698:             }
1.402     www      8699:         }
                   8700:     }
1.407     albertel 8701:     return %clicker_ids;
1.402     www      8702: }
                   8703: 
1.413     www      8704: sub clicker_grading_parameters {
                   8705:     return ('gradingmechanism' => 'scalar',
                   8706:             'upfiletype' => 'scalar',
                   8707:             'specificid' => 'scalar',
                   8708:             'pcorrect' => 'scalar',
                   8709:             'pincorrect' => 'scalar');
                   8710: }
                   8711: 
1.400     www      8712: sub process_clicker {
1.608     www      8713:     my ($r,$symb)=@_;
1.400     www      8714:     if (!$symb) {return '';}
                   8715:     my $result=&checkforfile_js();
                   8716:     $result.='<br /><table width="100%" border="0"><tr><td bgcolor="#777777">'."\n";
                   8717:     $result.='<table width="100%" border="0"><tr bgcolor="#e6ffff"><td>'."\n";
1.538     schulted 8718:     $result.='&nbsp;<b>'.&mt('Specify a file containing the clicker information for this resource.').
                   8719:         '</b></td></tr>'."\n";
1.601     www      8720:     $result.='<tr bgcolor="#ffffe6"><td>'."\n";
1.413     www      8721: # Attempt to restore parameters from last session, set defaults if not present
                   8722:     my %Saveable_Parameters=&clicker_grading_parameters();
                   8723:     &Apache::loncommon::restore_course_settings('grades_clicker',
                   8724:                                                  \%Saveable_Parameters);
                   8725:     if (!$env{'form.pcorrect'}) { $env{'form.pcorrect'}=100; }
                   8726:     if (!$env{'form.pincorrect'}) { $env{'form.pincorrect'}=100; }
                   8727:     if (!$env{'form.gradingmechanism'}) { $env{'form.gradingmechanism'}='attendance'; }
                   8728:     if (!$env{'form.upfiletype'}) { $env{'form.upfiletype'}='iclicker'; }
                   8729: 
                   8730:     my %checked;
1.521     www      8731:     foreach my $gradingmechanism ('attendance','personnel','specific','given') {
1.413     www      8732:        if ($env{'form.gradingmechanism'} eq $gradingmechanism) {
1.569     bisitz   8733:           $checked{$gradingmechanism}=' checked="checked"';
1.413     www      8734:        }
                   8735:     }
                   8736: 
1.400     www      8737:     my $upload=&mt("Upload File");
                   8738:     my $type=&mt("Type");
1.402     www      8739:     my $attendance=&mt("Award points just for participation");
                   8740:     my $personnel=&mt("Correctness determined from response by course personnel");
1.414     www      8741:     my $specific=&mt("Correctness determined from response with clicker ID(s)"); 
1.521     www      8742:     my $given=&mt("Correctness determined from given list of answers").' '.
                   8743:               '<font size="-2"><tt>('.&mt("Provide comma-separated list. Use '*' for any answer correct, '-' for skip").')</tt></font>';
1.402     www      8744:     my $pcorrect=&mt("Percentage points for correct solution");
                   8745:     my $pincorrect=&mt("Percentage points for incorrect solution");
1.413     www      8746:     my $selectform=&Apache::loncommon::select_form($env{'form.upfiletype'},'upfiletype',
1.419     www      8747: 						   ('iclicker' => 'i>clicker',
                   8748:                                                     'interwrite' => 'interwrite PRS'));
1.418     albertel 8749:     $symb = &Apache::lonenc::check_encrypt($symb);
1.597     wenzelju 8750:     $result.= &Apache::lonhtmlcommon::scripttag(<<ENDUPFORM);
1.402     www      8751: function sanitycheck() {
                   8752: // Accept only integer percentages
                   8753:    document.forms.gradesupload.pcorrect.value=Math.round(document.forms.gradesupload.pcorrect.value);
                   8754:    document.forms.gradesupload.pincorrect.value=Math.round(document.forms.gradesupload.pincorrect.value);
                   8755: // Find out grading choice
                   8756:    for (i=0; i<document.forms.gradesupload.gradingmechanism.length; i++) {
                   8757:       if (document.forms.gradesupload.gradingmechanism[i].checked) {
                   8758:          gradingchoice=document.forms.gradesupload.gradingmechanism[i].value;
                   8759:       }
                   8760:    }
                   8761: // By default, new choice equals user selection
                   8762:    newgradingchoice=gradingchoice;
                   8763: // Not good to give more points for false answers than correct ones
                   8764:    if (Math.round(document.forms.gradesupload.pcorrect.value)<Math.round(document.forms.gradesupload.pincorrect.value)) {
                   8765:       document.forms.gradesupload.pcorrect.value=document.forms.gradesupload.pincorrect.value;
                   8766:    }
                   8767: // If new choice is attendance only, and old choice was correctness-based, restore defaults
                   8768:    if ((gradingchoice=='attendance') && (document.forms.gradesupload.waschecked.value!='attendance')) {
                   8769:       document.forms.gradesupload.pcorrect.value=100;
                   8770:       document.forms.gradesupload.pincorrect.value=100;
                   8771:    }
                   8772: // If the values are different, cannot be attendance only
                   8773:    if ((Math.round(document.forms.gradesupload.pcorrect.value)!=Math.round(document.forms.gradesupload.pincorrect.value)) &&
                   8774:        (gradingchoice=='attendance')) {
                   8775:        newgradingchoice='personnel';
                   8776:    }
                   8777: // Change grading choice to new one
                   8778:    for (i=0; i<document.forms.gradesupload.gradingmechanism.length; i++) {
                   8779:       if (document.forms.gradesupload.gradingmechanism[i].value==newgradingchoice) {
                   8780:          document.forms.gradesupload.gradingmechanism[i].checked=true;
                   8781:       } else {
                   8782:          document.forms.gradesupload.gradingmechanism[i].checked=false;
                   8783:       }
                   8784:    }
                   8785: // Remember the old state
                   8786:    document.forms.gradesupload.waschecked.value=newgradingchoice;
                   8787: }
1.597     wenzelju 8788: ENDUPFORM
                   8789:     $result.= <<ENDUPFORM;
1.400     www      8790: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
                   8791: <input type="hidden" name="symb" value="$symb" />
                   8792: <input type="hidden" name="command" value="processclickerfile" />
                   8793: <input type="file" name="upfile" size="50" />
                   8794: <br /><label>$type: $selectform</label>
1.589     bisitz   8795: <br /><label><input type="radio" name="gradingmechanism" value="attendance"$checked{'attendance'} onclick="sanitycheck()" />$attendance </label>
                   8796: <br /><label><input type="radio" name="gradingmechanism" value="personnel"$checked{'personnel'} onclick="sanitycheck()" />$personnel</label>
                   8797: <br /><label><input type="radio" name="gradingmechanism" value="specific"$checked{'specific'} onclick="sanitycheck()" />$specific </label>
1.414     www      8798: <input type="text" name="specificid" value="$env{'form.specificid'}" size="20" />
1.589     bisitz   8799: <br /><label><input type="radio" name="gradingmechanism" value="given"$checked{'given'} onclick="sanitycheck()" />$given </label>
1.521     www      8800: <br />&nbsp;&nbsp;&nbsp;
                   8801: <input type="text" name="givenanswer" size="50" />
1.413     www      8802: <input type="hidden" name="waschecked" value="$env{'form.gradingmechanism'}" />
1.589     bisitz   8803: <br /><label>$pcorrect: <input type="text" name="pcorrect" size="4" value="$env{'form.pcorrect'}" onchange="sanitycheck()" /></label>
                   8804: <br /><label>$pincorrect: <input type="text" name="pincorrect" size="4" value="$env{'form.pincorrect'}" onchange="sanitycheck()" /></label>
                   8805: <br /><input type="button" onclick="javascript:checkUpload(this.form);" value="$upload" />
1.597     wenzelju 8806: </form>'
1.400     www      8807: ENDUPFORM
                   8808:     $result.='</td></tr></table>'."\n".
                   8809:              '</td></tr></table><br /><br />'."\n";
                   8810:     return $result;
                   8811: }
                   8812: 
                   8813: sub process_clicker_file {
1.608     www      8814:     my ($r,$symb)=@_;
1.400     www      8815:     if (!$symb) {return '';}
1.413     www      8816: 
                   8817:     my %Saveable_Parameters=&clicker_grading_parameters();
                   8818:     &Apache::loncommon::store_course_settings('grades_clicker',
                   8819:                                               \%Saveable_Parameters);
1.598     www      8820:     my $result='';
1.404     www      8821:     if (($env{'form.gradingmechanism'} eq 'specific') && ($env{'form.specificid'}!~/\w/)) {
1.408     albertel 8822: 	$result.='<span class="LC_error">'.&mt('You need to specify a clicker ID for the correct answer').'</span>';
1.614     www      8823: 	return $result;
1.404     www      8824:     }
1.522     www      8825:     if (($env{'form.gradingmechanism'} eq 'given') && ($env{'form.givenanswer'}!~/\S/)) {
1.521     www      8826:         $result.='<span class="LC_error">'.&mt('You need to specify the correct answer').'</span>';
1.614     www      8827:         return $result;
1.521     www      8828:     }
1.522     www      8829:     my $foundgiven=0;
1.521     www      8830:     if ($env{'form.gradingmechanism'} eq 'given') {
                   8831:         $env{'form.givenanswer'}=~s/^\s*//gs;
                   8832:         $env{'form.givenanswer'}=~s/\s*$//gs;
                   8833:         $env{'form.givenanswer'}=~s/[^a-zA-Z0-9\.\*\-]+/\,/g;
                   8834:         $env{'form.givenanswer'}=uc($env{'form.givenanswer'});
1.522     www      8835:         my @answers=split(/\,/,$env{'form.givenanswer'});
                   8836:         $foundgiven=$#answers+1;
1.521     www      8837:     }
1.407     albertel 8838:     my %clicker_ids=&gather_clicker_ids();
1.408     albertel 8839:     my %correct_ids;
1.404     www      8840:     if ($env{'form.gradingmechanism'} eq 'personnel') {
1.408     albertel 8841: 	%correct_ids=&gather_adv_clicker_ids();
1.404     www      8842:     }
                   8843:     if ($env{'form.gradingmechanism'} eq 'specific') {
1.414     www      8844: 	foreach my $correct_id (split(/[\s\,]/,$env{'form.specificid'})) {;
                   8845: 	   $correct_id=~tr/a-z/A-Z/;
                   8846: 	   $correct_id=~s/\s//gs;
                   8847: 	   $correct_id=~s/^[\#0]+//;
1.421     www      8848:            $correct_id=~s/[\-\:]//g;
1.414     www      8849:            if ($correct_id) {
                   8850: 	      $correct_ids{$correct_id}='specified';
                   8851:            }
                   8852:         }
1.400     www      8853:     }
1.404     www      8854:     if ($env{'form.gradingmechanism'} eq 'attendance') {
1.408     albertel 8855: 	$result.=&mt('Score based on attendance only');
1.521     www      8856:     } elsif ($env{'form.gradingmechanism'} eq 'given') {
1.522     www      8857:         $result.=&mt('Score based on [_1] ([_2] answers)','<tt>'.$env{'form.givenanswer'}.'</tt>',$foundgiven);
1.404     www      8858:     } else {
1.408     albertel 8859: 	my $number=0;
1.411     www      8860: 	$result.='<p><b>'.&mt('Correctness determined by the following IDs').'</b>';
1.408     albertel 8861: 	foreach my $id (sort(keys(%correct_ids))) {
1.411     www      8862: 	    $result.='<br /><tt>'.$id.'</tt> - ';
1.408     albertel 8863: 	    if ($correct_ids{$id} eq 'specified') {
                   8864: 		$result.=&mt('specified');
                   8865: 	    } else {
                   8866: 		my ($uname,$udom)=split(/\:/,$correct_ids{$id});
                   8867: 		$result.=&Apache::loncommon::plainname($uname,$udom);
                   8868: 	    }
                   8869: 	    $number++;
                   8870: 	}
1.411     www      8871:         $result.="</p>\n";
1.408     albertel 8872: 	if ($number==0) {
                   8873: 	    $result.='<span class="LC_error">'.&mt('No IDs found to determine correct answer').'</span>';
1.614     www      8874: 	    return $result;
1.408     albertel 8875: 	}
1.404     www      8876:     }
1.405     www      8877:     if (length($env{'form.upfile'}) < 2) {
1.407     albertel 8878:         $result.=&mt('[_1] Error: [_2] The file you attempted to upload, [_3] contained no information. Please check that you entered the correct filename.',
                   8879: 		     '<span class="LC_error">',
                   8880: 		     '</span>',
                   8881: 		     '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>');
1.614     www      8882:         return $result;
1.405     www      8883:     }
1.410     www      8884: 
                   8885: # Were able to get all the info needed, now analyze the file
                   8886: 
1.411     www      8887:     $result.=&Apache::loncommon::studentbrowser_javascript();
1.418     albertel 8888:     $symb = &Apache::lonenc::check_encrypt($symb);
1.410     www      8889:     my $heading=&mt('Scanning clicker file');
                   8890:     $result.=(<<ENDHEADER);
                   8891: <br /><table width="100%" border="0"><tr><td bgcolor="#777777">
                   8892: <table width="100%" border="0"><tr bgcolor="#e6ffff"><td>
                   8893: <b>$heading</b></td></tr><tr bgcolor=#ffffe6><td>
                   8894: <form method="post" action="/adm/grades" name="clickeranalysis">
                   8895: <input type="hidden" name="symb" value="$symb" />
                   8896: <input type="hidden" name="command" value="assignclickergrades" />
1.411     www      8897: <input type="hidden" name="gradingmechanism" value="$env{'form.gradingmechanism'}" />
                   8898: <input type="hidden" name="pcorrect" value="$env{'form.pcorrect'}" />
                   8899: <input type="hidden" name="pincorrect" value="$env{'form.pincorrect'}" />
1.410     www      8900: ENDHEADER
1.522     www      8901:     if ($env{'form.gradingmechanism'} eq 'given') {
                   8902:        $result.='<input type="hidden" name="correct:given" value="'.$env{'form.givenanswer'}.'" />';
                   8903:     } 
1.408     albertel 8904:     my %responses;
                   8905:     my @questiontitles;
1.405     www      8906:     my $errormsg='';
                   8907:     my $number=0;
                   8908:     if ($env{'form.upfiletype'} eq 'iclicker') {
1.408     albertel 8909: 	($errormsg,$number)=&iclicker_eval(\@questiontitles,\%responses);
1.406     www      8910:     }
1.419     www      8911:     if ($env{'form.upfiletype'} eq 'interwrite') {
                   8912:         ($errormsg,$number)=&interwrite_eval(\@questiontitles,\%responses);
                   8913:     }
1.411     www      8914:     $result.='<br />'.&mt('Found [_1] question(s)',$number).'<br />'.
                   8915:              '<input type="hidden" name="number" value="'.$number.'" />'.
                   8916:              &mt('Awarding [_1] percent for correct and [_2] percent for incorrect responses',
                   8917:                  $env{'form.pcorrect'},$env{'form.pincorrect'}).
                   8918:              '<br />';
1.522     www      8919:     if (($env{'form.gradingmechanism'} eq 'given') && ($number!=$foundgiven)) {
                   8920:        $result.='<span class="LC_error">'.&mt('Number of given answers does not agree with number of questions in file.').'</span>';
1.614     www      8921:        return $result;
1.522     www      8922:     } 
1.414     www      8923: # Remember Question Titles
                   8924: # FIXME: Possibly need delimiter other than ":"
                   8925:     for (my $i=0;$i<$number;$i++) {
                   8926:         $result.='<input type="hidden" name="question:'.$i.'" value="'.
                   8927:                  &HTML::Entities::encode($questiontitles[$i],'"&<>').'" />';
                   8928:     }
1.411     www      8929:     my $correct_count=0;
                   8930:     my $student_count=0;
                   8931:     my $unknown_count=0;
1.414     www      8932: # Match answers with usernames
                   8933: # FIXME: Possibly need delimiter other than ":"
1.409     albertel 8934:     foreach my $id (keys(%responses)) {
1.410     www      8935:        if ($correct_ids{$id}) {
1.414     www      8936:           $result.="\n".'<input type="hidden" name="correct:'.$correct_count.':'.$correct_ids{$id}.'" value="'.$responses{$id}.'" />';
1.411     www      8937:           $correct_count++;
1.410     www      8938:        } elsif ($clicker_ids{$id}) {
1.437     www      8939:           if ($clicker_ids{$id}=~/\,/) {
                   8940: # More than one user with the same clicker!
                   8941:              $result.="\n<hr />".&mt('Clicker registered more than once').": <tt>".$id."</tt><br />";
                   8942:              $result.="\n".'<input type="hidden" name="unknown:'.$id.'" value="'.$responses{$id}.'" />'.
                   8943:                            "<select name='multi".$id."'>";
                   8944:              foreach my $reguser (sort(split(/\,/,$clicker_ids{$id}))) {
                   8945:                  $result.="<option value='".$reguser."'>".&Apache::loncommon::plainname(split(/\:/,$reguser)).' ('.$reguser.')</option>';
                   8946:              }
                   8947:              $result.='</select>';
                   8948:              $unknown_count++;
                   8949:           } else {
                   8950: # Good: found one and only one user with the right clicker
                   8951:              $result.="\n".'<input type="hidden" name="student:'.$clicker_ids{$id}.'" value="'.$responses{$id}.'" />';
                   8952:              $student_count++;
                   8953:           }
1.410     www      8954:        } else {
1.411     www      8955:           $result.="\n<hr />".&mt('Unregistered Clicker')." <tt>".$id."</tt><br />";
                   8956:           $result.="\n".'<input type="hidden" name="unknown:'.$id.'" value="'.$responses{$id}.'" />'.
                   8957:                    "\n".&mt("Username").": <input type='text' name='uname".$id."' />&nbsp;".
                   8958:                    "\n".&mt("Domain").": ".
                   8959:                    &Apache::loncommon::select_dom_form($env{'course.'.$env{'request.course.id'}.'.domain'},'udom'.$id).'&nbsp;'.
                   8960:                    &Apache::loncommon::selectstudent_link('clickeranalysis','uname'.$id,'udom'.$id);
                   8961:           $unknown_count++;
1.410     www      8962:        }
1.405     www      8963:     }
1.412     www      8964:     $result.='<hr />'.
                   8965:              &mt('Found [_1] registered and [_2] unregistered clickers.',$student_count,$unknown_count);
1.521     www      8966:     if (($env{'form.gradingmechanism'} ne 'attendance') && ($env{'form.gradingmechanism'} ne 'given')) {
1.412     www      8967:        if ($correct_count==0) {
                   8968:           $errormsg.="Found no correct answers answers for grading!";
                   8969:        } elsif ($correct_count>1) {
1.414     www      8970:           $result.='<br /><span class="LC_warning">'.&mt("Found [_1] entries for grading!",$correct_count).'</span>';
1.412     www      8971:        }
                   8972:     }
1.428     www      8973:     if ($number<1) {
                   8974:        $errormsg.="Found no questions.";
                   8975:     }
1.412     www      8976:     if ($errormsg) {
                   8977:        $result.='<br /><span class="LC_error">'.&mt($errormsg).'</span>';
                   8978:     } else {
                   8979:        $result.='<br /><input type="submit" name="finalize" value="'.&mt('Finalize Grading').'" />';
                   8980:     }
                   8981:     $result.='</form></td></tr></table>'."\n".
1.410     www      8982:              '</td></tr></table><br /><br />'."\n";
1.614     www      8983:     return $result;
1.400     www      8984: }
                   8985: 
1.405     www      8986: sub iclicker_eval {
1.406     www      8987:     my ($questiontitles,$responses)=@_;
1.405     www      8988:     my $number=0;
                   8989:     my $errormsg='';
                   8990:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
1.410     www      8991:         my %components=&Apache::loncommon::record_sep($line);
                   8992:         my @entries=map {$components{$_}} (sort(keys(%components)));
1.408     albertel 8993: 	if ($entries[0] eq 'Question') {
                   8994: 	    for (my $i=3;$i<$#entries;$i+=6) {
                   8995: 		$$questiontitles[$number]=$entries[$i];
                   8996: 		$number++;
                   8997: 	    }
                   8998: 	}
                   8999: 	if ($entries[0]=~/^\#/) {
                   9000: 	    my $id=$entries[0];
                   9001: 	    my @idresponses;
                   9002: 	    $id=~s/^[\#0]+//;
                   9003: 	    for (my $i=0;$i<$number;$i++) {
                   9004: 		my $idx=3+$i*6;
                   9005: 		push(@idresponses,$entries[$idx]);
                   9006: 	    }
                   9007: 	    $$responses{$id}=join(',',@idresponses);
                   9008: 	}
1.405     www      9009:     }
                   9010:     return ($errormsg,$number);
                   9011: }
                   9012: 
1.419     www      9013: sub interwrite_eval {
                   9014:     my ($questiontitles,$responses)=@_;
                   9015:     my $number=0;
                   9016:     my $errormsg='';
1.420     www      9017:     my $skipline=1;
                   9018:     my $questionnumber=0;
                   9019:     my %idresponses=();
1.419     www      9020:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
                   9021:         my %components=&Apache::loncommon::record_sep($line);
                   9022:         my @entries=map {$components{$_}} (sort(keys(%components)));
1.420     www      9023:         if ($entries[1] eq 'Time') { $skipline=0; next; }
                   9024:         if ($entries[1] eq 'Response') { $skipline=1; }
                   9025:         next if $skipline;
                   9026:         if ($entries[0]!=$questionnumber) {
                   9027:            $questionnumber=$entries[0];
                   9028:            $$questiontitles[$number]=&mt('Question [_1]',$questionnumber);
                   9029:            $number++;
1.419     www      9030:         }
1.420     www      9031:         my $id=$entries[4];
                   9032:         $id=~s/^[\#0]+//;
1.421     www      9033:         $id=~s/^v\d*\://i;
                   9034:         $id=~s/[\-\:]//g;
1.420     www      9035:         $idresponses{$id}[$number]=$entries[6];
                   9036:     }
1.524     raeburn  9037:     foreach my $id (keys(%idresponses)) {
1.420     www      9038:        $$responses{$id}=join(',',@{$idresponses{$id}});
                   9039:        $$responses{$id}=~s/^\s*\,//;
1.419     www      9040:     }
                   9041:     return ($errormsg,$number);
                   9042: }
                   9043: 
1.414     www      9044: sub assign_clicker_grades {
1.608     www      9045:     my ($r,$symb)=@_;
1.414     www      9046:     if (!$symb) {return '';}
1.416     www      9047: # See which part we are saving to
1.582     raeburn  9048:     my $res_error;
                   9049:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
                   9050:     if ($res_error) {
                   9051:         return &navmap_errormsg();
                   9052:     }
1.416     www      9053: # FIXME: This should probably look for the first handgradeable part
                   9054:     my $part=$$partlist[0];
                   9055: # Start screen output
1.598     www      9056:     my $result='';
1.416     www      9057: 
1.414     www      9058:     my $heading=&mt('Assigning grades based on clicker file');
                   9059:     $result.=(<<ENDHEADER);
                   9060: <br /><table width="100%" border="0"><tr><td bgcolor="#777777">
                   9061: <table width="100%" border="0"><tr bgcolor="#e6ffff"><td>
                   9062: <b>$heading</b></td></tr><tr bgcolor=#ffffe6><td>
                   9063: ENDHEADER
                   9064: # Get correct result
                   9065: # FIXME: Possibly need delimiter other than ":"
                   9066:     my @correct=();
1.415     www      9067:     my $gradingmechanism=$env{'form.gradingmechanism'};
                   9068:     my $number=$env{'form.number'};
                   9069:     if ($gradingmechanism ne 'attendance') {
1.414     www      9070:        foreach my $key (keys(%env)) {
                   9071:           if ($key=~/^form\.correct\:/) {
                   9072:              my @input=split(/\,/,$env{$key});
                   9073:              for (my $i=0;$i<=$#input;$i++) {
                   9074:                  if (($correct[$i]) && ($input[$i]) &&
                   9075:                      ($correct[$i] ne $input[$i])) {
                   9076:                     $result.='<br /><span class="LC_warning">'.
                   9077:                              &mt('More than one correct result given for question "[_1]": [_2] versus [_3].',
                   9078:                                  $env{'form.question:'.$i},$correct[$i],$input[$i]).'</span>';
                   9079:                  } elsif ($input[$i]) {
                   9080:                     $correct[$i]=$input[$i];
                   9081:                  }
                   9082:              }
                   9083:           }
                   9084:        }
1.415     www      9085:        for (my $i=0;$i<$number;$i++) {
1.414     www      9086:           if (!$correct[$i]) {
                   9087:              $result.='<br /><span class="LC_error">'.
                   9088:                       &mt('No correct result given for question "[_1]"!',
                   9089:                           $env{'form.question:'.$i}).'</span>';
                   9090:           }
                   9091:        }
                   9092:        $result.='<br />'.&mt("Correct answer: [_1]",join(', ',map { ($_?$_:'-') } @correct));
                   9093:     }
                   9094: # Start grading
1.415     www      9095:     my $pcorrect=$env{'form.pcorrect'};
                   9096:     my $pincorrect=$env{'form.pincorrect'};
1.416     www      9097:     my $storecount=0;
1.415     www      9098:     foreach my $key (keys(%env)) {
1.420     www      9099:        my $user='';
1.415     www      9100:        if ($key=~/^form\.student\:(.*)$/) {
1.420     www      9101:           $user=$1;
                   9102:        }
                   9103:        if ($key=~/^form\.unknown\:(.*)$/) {
                   9104:           my $id=$1;
                   9105:           if (($env{'form.uname'.$id}) && ($env{'form.udom'.$id})) {
                   9106:              $user=$env{'form.uname'.$id}.':'.$env{'form.udom'.$id};
1.437     www      9107:           } elsif ($env{'form.multi'.$id}) {
                   9108:              $user=$env{'form.multi'.$id};
1.420     www      9109:           }
                   9110:        }
                   9111:        if ($user) { 
1.415     www      9112:           my @answer=split(/\,/,$env{$key});
                   9113:           my $sum=0;
1.522     www      9114:           my $realnumber=$number;
1.415     www      9115:           for (my $i=0;$i<$number;$i++) {
1.576     www      9116:              if  ($correct[$i] eq '-') {
                   9117:                 $realnumber--;
                   9118:              } elsif ($answer[$i]) {
1.415     www      9119:                 if ($gradingmechanism eq 'attendance') {
                   9120:                    $sum+=$pcorrect;
1.576     www      9121:                 } elsif ($correct[$i] eq '*') {
1.522     www      9122:                    $sum+=$pcorrect;
1.415     www      9123:                 } else {
                   9124:                    if ($answer[$i] eq $correct[$i]) {
                   9125:                       $sum+=$pcorrect;
                   9126:                    } else {
                   9127:                       $sum+=$pincorrect;
                   9128:                    }
                   9129:                 }
                   9130:              }
                   9131:           }
1.522     www      9132:           my $ave=$sum/(100*$realnumber);
1.416     www      9133: # Store
                   9134:           my ($username,$domain)=split(/\:/,$user);
                   9135:           my %grades=();
                   9136:           $grades{"resource.$part.solved"}='correct_by_override';
                   9137:           $grades{"resource.$part.awarded"}=$ave;
                   9138:           $grades{"resource.regrader"}="$env{'user.name'}:$env{'user.domain'}";
                   9139:           my $returncode=&Apache::lonnet::cstore(\%grades,$symb,
                   9140:                                                  $env{'request.course.id'},
                   9141:                                                  $domain,$username);
                   9142:           if ($returncode ne 'ok') {
                   9143:              $result.="<br /><span class=\"LC_error\">Failed to save student $username:$domain. Message when trying to save was ($returncode)</span>";
                   9144:           } else {
                   9145:              $storecount++;
                   9146:           }
1.415     www      9147:        }
                   9148:     }
                   9149: # We are done
1.549     hauer    9150:     $result.='<br />'.&mt('Successfully stored grades for [quant,_1,student].',$storecount).
1.416     www      9151:              '</td></tr></table>'."\n".
1.414     www      9152:              '</td></tr></table><br /><br />'."\n";
1.614     www      9153:     return $result;
1.414     www      9154: }
                   9155: 
1.582     raeburn  9156: sub navmap_errormsg {
                   9157:     return '<div class="LC_error">'.
                   9158:            &mt('An error occurred retrieving information about resources in the course.').'<br />'.
1.595     raeburn  9159:            &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  9160:            '</div>';
                   9161: }
1.607     droeschl 9162: 
1.609     www      9163: sub startpage {
1.613     www      9164:     my ($r,$symb,$crumbs,$onlyfolderflag,$nodisplayflag) = @_;
1.614     www      9165:     unshift(@$crumbs,{href=>&href_symb_cmd($symb,'gradingmenu'),text=>"Grading"});
1.607     droeschl 9166:     $r->print(&Apache::loncommon::start_page('Grading',undef,
1.610     www      9167:                                           {'bread_crumbs' => $crumbs}));
1.613     www      9168:     unless ($nodisplayflag) {
                   9169:        $r->print(&Apache::lonhtmlcommon::resource_info_box($symb,$onlyfolderflag));
                   9170:     }
1.607     droeschl 9171: }
1.582     raeburn  9172: 
1.622   ! www      9173: sub select_problem {
        !          9174:     my ($r)=@_;
        !          9175:     $r->print('<h2>'.&mt('Select the problem you want to grade').'</h2><form action="/adm/grades">');
        !          9176:     $r->print(&Apache::lonstathelpers::problem_selector('.',undef,1));
        !          9177:     $r->print('<input type="hidden" name="command" value="gradingmenu" />');
        !          9178:     $r->print('<input type="submit" value="'.&mt('Next').' &rarr;" /></form>');
        !          9179: }
        !          9180: 
1.1       albertel 9181: sub handler {
1.41      ng       9182:     my $request=$_[0];
1.434     albertel 9183:     &reset_caches();
1.257     albertel 9184:     if ($env{'browser.mathml'}) {
1.141     www      9185: 	&Apache::loncommon::content_type($request,'text/xml');
1.41      ng       9186:     } else {
1.141     www      9187: 	&Apache::loncommon::content_type($request,'text/html');
1.41      ng       9188:     }
                   9189:     $request->send_http_header;
1.44      ng       9190:     return '' if $request->header_only;
1.41      ng       9191:     &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'});
1.608     www      9192: 
                   9193: # see what command we need to execute
                   9194: 
1.160     albertel 9195:     my @commands=&Apache::loncommon::get_env_multiple('form.command');
                   9196:     my $command=$commands[0];
1.447     foxr     9197: 
1.160     albertel 9198:     if ($#commands > 0) {
                   9199: 	&Apache::lonnet::logthis("grades got multiple commands ".join(':',@commands));
                   9200:     }
1.608     www      9201: 
                   9202: # see what the symb is
                   9203: 
                   9204:     my $symb=$env{'form.symb'};
                   9205:     unless ($symb) {
                   9206:        (my $url=$env{'form.url'}) =~ s-^https*://($ENV{'SERVER_NAME'}|$ENV{'HTTP_HOST'})--;
                   9207:        $symb=&Apache::lonnet::symbread($url);
                   9208:     }
                   9209:     &Apache::lonenc::check_decrypt(\$symb);                             
                   9210: 
1.513     foxr     9211:     $ssi_error = 0;
1.622   ! www      9212:     if ($symb eq '' || $command eq '') {
1.601     www      9213: #
                   9214: # Not called from a resource
                   9215: #    
1.622   ! www      9216:         &startpage($request,undef,[],1,1);
        !          9217:         &select_problem($request);
1.41      ng       9218:     } else {
1.285     albertel 9219: 	&init_perm();
1.104     albertel 9220: 	if ($command eq 'submission' && $perm{'vgr'}) {
1.608     www      9221:             &startpage($request,$symb,[{href=>"", text=>"Student Submissions"}]);
1.611     www      9222: 	    ($env{'form.student'} eq '' ? &listStudents($request,$symb) : &submission($request,0,0,$symb));
1.103     albertel 9223: 	} elsif ($command eq 'pickStudentPage' && $perm{'vgr'}) {
1.615     www      9224:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,'all_for_one'),text=>'Grade page/folder for one student'},
                   9225:                                        {href=>'',text=>'Select student'}],1,1);
1.608     www      9226: 	    &pickStudentPage($request,$symb);
1.103     albertel 9227: 	} elsif ($command eq 'displayPage' && $perm{'vgr'}) {
1.615     www      9228:             &startpage($request,$symb,
                   9229:                                       [{href=>&href_symb_cmd($symb,'all_for_one'),text=>'Grade page/folder for one student'},
                   9230:                                        {href=>'',text=>'Select student'},
                   9231:                                        {href=>'',text=>'Grade student'}],1,1);
1.608     www      9232: 	    &displayPage($request,$symb);
1.104     albertel 9233: 	} elsif ($command eq 'gradeByPage' && $perm{'mgr'}) {
1.616     www      9234:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,'all_for_one'),text=>'Grade page/folder for one student'},
                   9235:                                        {href=>'',text=>'Select student'},
                   9236:                                        {href=>'',text=>'Grade student'},
                   9237:                                        {href=>'',text=>'Store grades'}],1,1);
1.608     www      9238: 	    &updateGradeByPage($request,$symb);
1.104     albertel 9239: 	} elsif ($command eq 'processGroup' && $perm{'vgr'}) {
1.619     www      9240:             &startpage($request,$symb,[{href=>'',text=>'...'},
                   9241:                                        {href=>'',text=>'Modify grades'}]);
1.608     www      9242: 	    &processGroup($request,$symb);
1.104     albertel 9243: 	} elsif ($command eq 'gradingmenu' && $perm{'vgr'}) {
1.608     www      9244:             &startpage($request,$symb);
                   9245: 	    $request->print(&grading_menu($request,$symb));
1.598     www      9246: 	} elsif ($command eq 'individual' && $perm{'vgr'}) {
1.617     www      9247:             &startpage($request,$symb,[{href=>'',text=>'Select individual students to grade'}]);
1.608     www      9248: 	    $request->print(&submit_options($request,$symb));
1.598     www      9249:         } elsif ($command eq 'ungraded' && $perm{'vgr'}) {
1.617     www      9250:             &startpage($request,$symb,[{href=>'',text=>'Grade ungraded submissions'}]);
                   9251:             $request->print(&listStudents($request,$symb,'graded'));
1.598     www      9252:         } elsif ($command eq 'table' && $perm{'vgr'}) {
1.614     www      9253:             &startpage($request,$symb,[{href=>"", text=>"Grading table"}]);
1.611     www      9254:             $request->print(&submit_options_table($request,$symb));
1.598     www      9255:         } elsif ($command eq 'all_for_one' && $perm{'vgr'}) {
1.615     www      9256:             &startpage($request,$symb,[{href=>'',text=>'Grade page/folder for one student'}],1,1);
1.608     www      9257:             $request->print(&submit_options_sequence($request,$symb));
1.104     albertel 9258: 	} elsif ($command eq 'viewgrades' && $perm{'vgr'}) {
1.614     www      9259:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,"table"), text=>"Grading table"},{href=>'', text=>"Modify grades"}]);
1.608     www      9260: 	    $request->print(&viewgrades($request,$symb));
1.104     albertel 9261: 	} elsif ($command eq 'handgrade' && $perm{'mgr'}) {
1.620     www      9262:             &startpage($request,$symb,[{href=>'',text=>'...'},
                   9263:                                        {href=>'',text=>'Store grades'}]);
1.608     www      9264: 	    $request->print(&processHandGrade($request,$symb));
1.106     albertel 9265: 	} elsif ($command eq 'editgrades' && $perm{'mgr'}) {
1.614     www      9266:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,"table"), text=>"Grading table"},
                   9267:                                        {href=>&href_symb_cmd($symb,'viewgrades').'&group=all&section=all&Status=Active',
                   9268:                                                                              text=>"Modify grades"},
                   9269:                                        {href=>'', text=>"Store grades"}]);
1.608     www      9270: 	    $request->print(&editgrades($request,$symb));
1.602     www      9271:         } elsif ($command eq 'initialverifyreceipt' && $perm{'vgr'}) {
1.616     www      9272:             &startpage($request,$symb,[{href=>'',text=>'Verify Receipt Number'}]);
1.611     www      9273:             $request->print(&initialverifyreceipt($request,$symb));
1.106     albertel 9274: 	} elsif ($command eq 'verify' && $perm{'vgr'}) {
1.616     www      9275:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,"initialverifyreceipt"),text=>'Verify Receipt Number'},
                   9276:                                        {href=>'',text=>'Verification Result'}]);
1.608     www      9277: 	    $request->print(&verifyreceipt($request,$symb));
1.400     www      9278:         } elsif ($command eq 'processclicker' && $perm{'mgr'}) {
1.615     www      9279:             &startpage($request,$symb,[{href=>'', text=>'Process clicker'}]);
1.608     www      9280:             $request->print(&process_clicker($request,$symb));
1.400     www      9281:         } elsif ($command eq 'processclickerfile' && $perm{'mgr'}) {
1.615     www      9282:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,'processclicker'), text=>'Process clicker'},
                   9283:                                        {href=>'', text=>'Process clicker file'}]);
1.608     www      9284:             $request->print(&process_clicker_file($request,$symb));
1.414     www      9285:         } elsif ($command eq 'assignclickergrades' && $perm{'mgr'}) {
1.615     www      9286:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,'processclicker'), text=>'Process clicker'},
                   9287:                                        {href=>'', text=>'Process clicker file'},
                   9288:                                        {href=>'', text=>'Store grades'}]);
1.608     www      9289:             $request->print(&assign_clicker_grades($request,$symb));
1.106     albertel 9290: 	} elsif ($command eq 'csvform' && $perm{'mgr'}) {
1.616     www      9291:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
1.608     www      9292: 	    $request->print(&upcsvScores_form($request,$symb));
1.106     albertel 9293: 	} elsif ($command eq 'csvupload' && $perm{'mgr'}) {
1.616     www      9294:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
1.608     www      9295: 	    $request->print(&csvupload($request,$symb));
1.106     albertel 9296: 	} elsif ($command eq 'csvuploadmap' && $perm{'mgr'} ) {
1.616     www      9297:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
1.608     www      9298: 	    $request->print(&csvuploadmap($request,$symb));
1.246     albertel 9299: 	} elsif ($command eq 'csvuploadoptions' && $perm{'mgr'}) {
1.257     albertel 9300: 	    if ($env{'form.associate'} ne 'Reverse Association') {
1.616     www      9301:                 &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
1.608     www      9302: 		$request->print(&csvuploadoptions($request,$symb));
1.41      ng       9303: 	    } else {
1.257     albertel 9304: 		if ( $env{'form.upfile_associate'} ne 'reverse' ) {
                   9305: 		    $env{'form.upfile_associate'} = 'reverse';
1.41      ng       9306: 		} else {
1.257     albertel 9307: 		    $env{'form.upfile_associate'} = 'forward';
1.41      ng       9308: 		}
1.616     www      9309:                 &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
1.608     www      9310: 		$request->print(&csvuploadmap($request,$symb));
1.41      ng       9311: 	    }
1.246     albertel 9312: 	} elsif ($command eq 'csvuploadassign' && $perm{'mgr'} ) {
1.616     www      9313:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
1.608     www      9314: 	    $request->print(&csvuploadassign($request,$symb));
1.106     albertel 9315: 	} elsif ($command eq 'scantron_selectphase' && $perm{'mgr'}) {
1.616     www      9316:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
1.612     www      9317: 	    $request->print(&scantron_selectphase($request,undef,$symb));
1.203     albertel 9318:  	} elsif ($command eq 'scantron_warning' && $perm{'mgr'}) {
1.616     www      9319:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
1.608     www      9320:  	    $request->print(&scantron_do_warning($request,$symb));
1.142     albertel 9321: 	} elsif ($command eq 'scantron_validate' && $perm{'mgr'}) {
1.616     www      9322:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
1.608     www      9323: 	    $request->print(&scantron_validate_file($request,$symb));
1.106     albertel 9324: 	} elsif ($command eq 'scantron_process' && $perm{'mgr'}) {
1.616     www      9325:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
1.608     www      9326: 	    $request->print(&scantron_process_students($request,$symb));
1.157     albertel 9327:  	} elsif ($command eq 'scantronupload' && 
1.257     albertel 9328:  		 (&Apache::lonnet::allowed('usc',$env{'request.role.domain'})||
                   9329: 		  &Apache::lonnet::allowed('usc',$env{'request.course.id'}))) {
1.616     www      9330:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
1.608     www      9331:  	    $request->print(&scantron_upload_scantron_data($request,$symb)); 
1.157     albertel 9332:  	} elsif ($command eq 'scantronupload_save' &&
1.257     albertel 9333:  		 (&Apache::lonnet::allowed('usc',$env{'request.role.domain'})||
                   9334: 		  &Apache::lonnet::allowed('usc',$env{'request.course.id'}))) {
1.616     www      9335:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
1.608     www      9336:  	    $request->print(&scantron_upload_scantron_data_save($request,$symb));
1.202     albertel 9337:  	} elsif ($command eq 'scantron_download' &&
1.257     albertel 9338: 		 &Apache::lonnet::allowed('usc',$env{'request.course.id'})) {
1.616     www      9339:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
1.608     www      9340:  	    $request->print(&scantron_download_scantron_data($request,$symb));
1.523     raeburn  9341:         } elsif ($command eq 'checksubmissions' && $perm{'vgr'}) {
1.616     www      9342:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
1.621     www      9343:             $request->print(&checkscantron_results($request,$symb));
                   9344:         } elsif ($command eq 'downloadfilesselect' && $perm{'vgr'}) {
                   9345:             &startpage($request,$symb,[{href=>'', text=>'Select which submissions to download'}]);
                   9346:             $request->print(&submit_options_download($request,$symb));
                   9347:          } elsif ($command eq 'downloadfileslink' && $perm{'vgr'}) {
                   9348:             &startpage($request,$symb,
                   9349:    [{href=>&href_symb_cmd($symb,'downloadfilesselect'), text=>'Select which submissions to download'},
                   9350:     {href=>'', text=>'Download submissions'}]);
                   9351:             &submit_download_link($request,$symb);
1.106     albertel 9352: 	} elsif ($command) {
1.620     www      9353:             &startpage($request,$symb,[{href=>'', text=>'Access denied'}]);
1.562     bisitz   9354: 	    $request->print('<p class="LC_error">'.&mt('Access Denied ([_1])',$command).'</p>');
1.26      albertel 9355: 	}
1.2       albertel 9356:     }
1.513     foxr     9357:     if ($ssi_error) {
                   9358: 	&ssi_print_error($request);
                   9359:     }
1.353     albertel 9360:     $request->print(&Apache::loncommon::end_page());
1.434     albertel 9361:     &reset_caches();
1.44      ng       9362:     return '';
                   9363: }
                   9364: 
1.1       albertel 9365: 1;
                   9366: 
1.13      albertel 9367: __END__;
1.531     jms      9368: 
                   9369: 
                   9370: =head1 NAME
                   9371: 
                   9372: Apache::grades
                   9373: 
                   9374: =head1 SYNOPSIS
                   9375: 
                   9376: Handles the viewing of grades.
                   9377: 
                   9378: This is part of the LearningOnline Network with CAPA project
                   9379: described at http://www.lon-capa.org.
                   9380: 
                   9381: =head1 OVERVIEW
                   9382: 
                   9383: Do an ssi with retries:
                   9384: While I'd love to factor out this with the vesrion in lonprintout,
                   9385: 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
                   9386: I'm not quite ready to invent (e.g. an ssi_with_retry object).
                   9387: 
                   9388: At least the logic that drives this has been pulled out into loncommon.
                   9389: 
                   9390: 
                   9391: 
                   9392: ssi_with_retries - Does the server side include of a resource.
                   9393:                      if the ssi call returns an error we'll retry it up to
                   9394:                      the number of times requested by the caller.
                   9395:                      If we still have a proble, no text is appended to the
                   9396:                      output and we set some global variables.
                   9397:                      to indicate to the caller an SSI error occurred.  
                   9398:                      All of this is supposed to deal with the issues described
                   9399:                      in LonCAPA BZ 5631 see:
                   9400:                      http://bugs.lon-capa.org/show_bug.cgi?id=5631
                   9401:                      by informing the user that this happened.
                   9402: 
                   9403: Parameters:
                   9404:   resource   - The resource to include.  This is passed directly, without
                   9405:                interpretation to lonnet::ssi.
                   9406:   form       - The form hash parameters that guide the interpretation of the resource
                   9407:                
                   9408:   retries    - Number of retries allowed before giving up completely.
                   9409: Returns:
                   9410:   On success, returns the rendered resource identified by the resource parameter.
                   9411: Side Effects:
                   9412:   The following global variables can be set:
                   9413:    ssi_error                - If an unrecoverable error occurred this becomes true.
                   9414:                               It is up to the caller to initialize this to false
                   9415:                               if desired.
                   9416:    ssi_error_resource  - If an unrecoverable error occurred, this is the value
                   9417:                               of the resource that could not be rendered by the ssi
                   9418:                               call.
                   9419:    ssi_error_message   - The error string fetched from the ssi response
                   9420:                               in the event of an error.
                   9421: 
                   9422: 
                   9423: =head1 HANDLER SUBROUTINE
                   9424: 
                   9425: ssi_with_retries()
                   9426: 
                   9427: =head1 SUBROUTINES
                   9428: 
                   9429: =over
                   9430: 
                   9431: =item scantron_get_correction() : 
                   9432: 
                   9433:    Builds the interface screen to interact with the operator to fix a
                   9434:    specific error condition in a specific scanline
                   9435: 
                   9436:  Arguments:
                   9437:     $r           - Apache request object
                   9438:     $i           - number of the current scanline
                   9439:     $scan_record - hash ref as returned from &scantron_parse_scanline()
                   9440:     $scan_config - hash ref as returned from &get_scantron_config()
                   9441:     $line        - full contents of the current scanline
                   9442:     $error       - error condition, valid values are
                   9443:                    'incorrectCODE', 'duplicateCODE',
                   9444:                    'doublebubble', 'missingbubble',
                   9445:                    'duplicateID', 'incorrectID'
                   9446:     $arg         - extra information needed
                   9447:        For errors:
                   9448:          - duplicateID   - paper number that this studentID was seen before on
                   9449:          - duplicateCODE - array ref of the paper numbers this CODE was
                   9450:                            seen on before
                   9451:          - incorrectCODE - current incorrect CODE 
                   9452:          - doublebubble  - array ref of the bubble lines that have double
                   9453:                            bubble errors
                   9454:          - missingbubble - array ref of the bubble lines that have missing
                   9455:                            bubble errors
                   9456: 
                   9457: =item  scantron_get_maxbubble() : 
                   9458: 
1.582     raeburn  9459:    Arguments:
                   9460:        $nav_error  - Reference to scalar which is a flag to indicate a
                   9461:                       failure to retrieve a navmap object.
                   9462:        if $nav_error is set to 1 by scantron_get_maxbubble(), the 
                   9463:        calling routine should trap the error condition and display the warning
                   9464:        found in &navmap_errormsg().
                   9465: 
1.531     jms      9466:    Returns the maximum number of bubble lines that are expected to
                   9467:    occur. Does this by walking the selected sequence rendering the
                   9468:    resource and then checking &Apache::lonxml::get_problem_counter()
                   9469:    for what the current value of the problem counter is.
                   9470: 
                   9471:    Caches the results to $env{'form.scantron_maxbubble'},
                   9472:    $env{'form.scantron.bubble_lines.n'}, 
                   9473:    $env{'form.scantron.first_bubble_line.n'} and
                   9474:    $env{"form.scantron.sub_bubblelines.n"}
                   9475:    which are the total number of bubble, lines, the number of bubble
                   9476:    lines for response n and number of the first bubble line for response n,
                   9477:    and a comma separated list of numbers of bubble lines for sub-questions
                   9478:    (for optionresponse, matchresponse, and rankresponse items), for response n.  
                   9479: 
                   9480: 
                   9481: =item  scantron_validate_missingbubbles() : 
                   9482: 
                   9483:    Validates all scanlines in the selected file to not have any
                   9484:     answers that don't have bubbles that have not been verified
                   9485:     to be bubble free.
                   9486: 
                   9487: =item  scantron_process_students() : 
                   9488: 
                   9489:    Routine that does the actual grading of the bubble sheet information.
                   9490: 
                   9491:    The parsed scanline hash is added to %env 
                   9492: 
                   9493:    Then foreach unskipped scanline it does an &Apache::lonnet::ssi()
                   9494:    foreach resource , with the form data of
                   9495: 
                   9496: 	'submitted'     =>'scantron' 
                   9497: 	'grade_target'  =>'grade',
                   9498: 	'grade_username'=> username of student
                   9499: 	'grade_domain'  => domain of student
                   9500: 	'grade_courseid'=> of course
                   9501: 	'grade_symb'    => symb of resource to grade
                   9502: 
                   9503:     This triggers a grading pass. The problem grading code takes care
                   9504:     of converting the bubbled letter information (now in %env) into a
                   9505:     valid submission.
                   9506: 
                   9507: =item  scantron_upload_scantron_data() :
                   9508: 
                   9509:     Creates the screen for adding a new bubble sheet data file to a course.
                   9510: 
                   9511: =item  scantron_upload_scantron_data_save() : 
                   9512: 
                   9513:    Adds a provided bubble information data file to the course if user
                   9514:    has the correct privileges to do so. 
                   9515: 
                   9516: =item  valid_file() :
                   9517: 
                   9518:    Validates that the requested bubble data file exists in the course.
                   9519: 
                   9520: =item  scantron_download_scantron_data() : 
                   9521: 
                   9522:    Shows a list of the three internal files (original, corrected,
                   9523:    skipped) for a specific bubble sheet data file that exists in the
                   9524:    course.
                   9525: 
                   9526: =item  scantron_validate_ID() : 
                   9527: 
                   9528:    Validates all scanlines in the selected file to not have any
1.556     weissno  9529:    invalid or underspecified student/employee IDs
1.531     jms      9530: 
1.582     raeburn  9531: =item navmap_errormsg() :
                   9532: 
                   9533:    Returns HTML mark-up inside a <div></div> with a link to re-initialize the course.
                   9534:    Should be called whenever the request to instantiate a navmap object fails.  
                   9535: 
1.531     jms      9536: =back
                   9537: 
                   9538: =cut

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