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

1.17      albertel    1: # The LearningOnline Network with CAPA
1.13      albertel    2: # The LON-CAPA Grading handler
1.17      albertel    3: #
1.625   ! www         4: # $Id: grades.pm,v 1.624 2010/04/18 19:29:10 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.623     www       141: #--- Sets response_error pointer to "1" if navmaps object broken ---
1.39      ng        142: sub response_type {
1.582     raeburn   143:     my ($symb,$response_error) = @_;
1.377     albertel  144: 
                    145:     my $navmap = Apache::lonnavmaps::navmap->new();
1.582     raeburn   146:     unless (ref($navmap)) {
                    147:         if (ref($response_error)) {
                    148:             $$response_error = 1;
                    149:         }
                    150:         return;
                    151:     }
1.377     albertel  152:     my $res = $navmap->getBySymb($symb);
1.593     raeburn   153:     unless (ref($res)) {
                    154:         $$response_error = 1;
                    155:         return;
                    156:     }
1.377     albertel  157:     my $partlist = $res->parts();
1.392     albertel  158:     my %vPart = 
                    159: 	map { $_ => 1 } (&Apache::loncommon::get_env_multiple('form.vPart'));
1.377     albertel  160:     my (%response_types,%handgrade);
                    161:     foreach my $part (@{ $partlist }) {
1.392     albertel  162: 	next if (%vPart && !exists($vPart{$part}));
                    163: 
1.377     albertel  164: 	my @types = $res->responseType($part);
                    165: 	my @ids = $res->responseIds($part);
                    166: 	for (my $i=0; $i < scalar(@ids); $i++) {
                    167: 	    $response_types{$part}{$ids[$i]} = $types[$i];
                    168: 	    $handgrade{$part.'_'.$ids[$i]} = 
                    169: 		&Apache::lonnet::EXT('resource.'.$part.'_'.$ids[$i].
                    170: 				     '.handgrade',$symb);
1.41      ng        171: 	}
                    172:     }
1.377     albertel  173:     return ($partlist,\%handgrade,\%response_types);
1.39      ng        174: }
                    175: 
1.375     albertel  176: sub flatten_responseType {
                    177:     my ($responseType) = @_;
                    178:     my @part_response_id =
                    179: 	map { 
                    180: 	    my $part = $_;
                    181: 	    map {
                    182: 		[$part,$_]
                    183: 		} sort(keys(%{ $responseType->{$part} }));
                    184: 	} sort(keys(%$responseType));
                    185:     return @part_response_id;
                    186: }
                    187: 
1.207     albertel  188: sub get_display_part {
1.324     albertel  189:     my ($partID,$symb)=@_;
1.207     albertel  190:     my $display=&Apache::lonnet::EXT('resource.'.$partID.'.display',$symb);
                    191:     if (defined($display) and $display ne '') {
1.577     bisitz    192:         $display.= ' (<span class="LC_internal_info">'
                    193:                   .&mt('Part ID: [_1]',$partID).'</span>)';
1.207     albertel  194:     } else {
                    195: 	$display=$partID;
                    196:     }
                    197:     return $display;
                    198: }
1.269     raeburn   199: 
1.434     albertel  200: sub reset_caches {
                    201:     &reset_analyze_cache();
                    202:     &reset_perm();
                    203: }
                    204: 
                    205: {
                    206:     my %analyze_cache;
1.557     raeburn   207:     my %analyze_cache_formkeys;
1.148     albertel  208: 
1.434     albertel  209:     sub reset_analyze_cache {
                    210: 	undef(%analyze_cache);
1.557     raeburn   211:         undef(%analyze_cache_formkeys);
1.434     albertel  212:     }
                    213: 
                    214:     sub get_analyze {
1.557     raeburn   215: 	my ($symb,$uname,$udom,$no_increment,$add_to_hash)=@_;
1.434     albertel  216: 	my $key = "$symb\0$uname\0$udom";
1.557     raeburn   217: 	if (exists($analyze_cache{$key})) {
                    218:             my $getupdate = 0;
                    219:             if (ref($add_to_hash) eq 'HASH') {
                    220:                 foreach my $item (keys(%{$add_to_hash})) {
                    221:                     if (ref($analyze_cache_formkeys{$key}) eq 'HASH') {
                    222:                         if (!exists($analyze_cache_formkeys{$key}{$item})) {
                    223:                             $getupdate = 1;
                    224:                             last;
                    225:                         }
                    226:                     } else {
                    227:                         $getupdate = 1;
                    228:                     }
                    229:                 }
                    230:             }
                    231:             if (!$getupdate) {
                    232:                 return $analyze_cache{$key};
                    233:             }
                    234:         }
1.434     albertel  235: 
                    236: 	my (undef,undef,$url)=&Apache::lonnet::decode_symb($symb);
                    237: 	$url=&Apache::lonnet::clutter($url);
1.557     raeburn   238:         my %form = ('grade_target'      => 'analyze',
                    239:                     'grade_domain'      => $udom,
                    240:                     'grade_symb'        => $symb,
                    241:                     'grade_courseid'    =>  $env{'request.course.id'},
                    242:                     'grade_username'    => $uname,
                    243:                     'grade_noincrement' => $no_increment);
                    244:         if (ref($add_to_hash)) {
                    245:             %form = (%form,%{$add_to_hash});
                    246:         } 
                    247: 	my $subresult=&ssi_with_retries($url, $ssi_retries,%form);
1.434     albertel  248: 	(undef,$subresult)=split(/_HASH_REF__/,$subresult,2);
                    249: 	my %analyze=&Apache::lonnet::str2hash($subresult);
1.557     raeburn   250:         if (ref($add_to_hash) eq 'HASH') {
                    251:             $analyze_cache_formkeys{$key} = $add_to_hash;
                    252:         } else {
                    253:             $analyze_cache_formkeys{$key} = {};
                    254:         }
1.434     albertel  255: 	return $analyze_cache{$key} = \%analyze;
                    256:     }
                    257: 
                    258:     sub get_order {
1.525     raeburn   259: 	my ($partid,$respid,$symb,$uname,$udom,$no_increment)=@_;
                    260: 	my $analyze = &get_analyze($symb,$uname,$udom,$no_increment);
1.434     albertel  261: 	return $analyze->{"$partid.$respid.shown"};
                    262:     }
                    263: 
                    264:     sub get_radiobutton_correct_foil {
                    265: 	my ($partid,$respid,$symb,$uname,$udom)=@_;
                    266: 	my $analyze = &get_analyze($symb,$uname,$udom);
1.555     raeburn   267:         my $foils = &get_order($partid,$respid,$symb,$uname,$udom);
                    268:         if (ref($foils) eq 'ARRAY') {
                    269: 	    foreach my $foil (@{$foils}) {
                    270: 	        if ($analyze->{"$partid.$respid.foil.value.$foil"} eq 'true') {
                    271: 		    return $foil;
                    272: 	        }
1.434     albertel  273: 	    }
                    274: 	}
                    275:     }
1.554     raeburn   276: 
                    277:     sub scantron_partids_tograde {
1.557     raeburn   278:         my ($resource,$cid,$uname,$udom,$check_for_randomlist) = @_;
1.554     raeburn   279:         my (%analysis,@parts);
                    280:         if (ref($resource)) {
                    281:             my $symb = $resource->symb();
1.557     raeburn   282:             my $add_to_form;
                    283:             if ($check_for_randomlist) {
                    284:                 $add_to_form = { 'check_parts_withrandomlist' => 1,};
                    285:             }
                    286:             my $analyze = &get_analyze($symb,$uname,$udom,undef,$add_to_form);
1.554     raeburn   287:             if (ref($analyze) eq 'HASH') {
                    288:                 %analysis = %{$analyze};
                    289:             }
                    290:             if (ref($analysis{'parts'}) eq 'ARRAY') {
                    291:                 foreach my $part (@{$analysis{'parts'}}) {
                    292:                     my ($id,$respid) = split(/\./,$part);
                    293:                     if (!&Apache::loncommon::check_if_partid_hidden($id,$symb,$udom,$uname)) {
                    294:                         push(@parts,$part);
                    295:                     }
                    296:                 }
                    297:             }
                    298:         }
                    299:         return (\%analysis,\@parts);
                    300:     }
                    301: 
1.148     albertel  302: }
1.434     albertel  303: 
1.118     ng        304: #--- Clean response type for display
1.335     albertel  305: #--- Currently filters option/rank/radiobutton/match/essay/Task
                    306: #        response types only.
1.118     ng        307: sub cleanRecord {
1.336     albertel  308:     my ($answer,$response,$symb,$partid,$respid,$record,$order,$version,
                    309: 	$uname,$udom) = @_;
1.398     albertel  310:     my $grayFont = '<span class="LC_internal_info">';
1.148     albertel  311:     if ($response =~ /^(option|rank)$/) {
                    312: 	my %answer=&Apache::lonnet::str2hash($answer);
                    313: 	my %grading=&Apache::lonnet::str2hash($record->{$version."resource.$partid.$respid.submissiongrading"});
                    314: 	my ($toprow,$bottomrow);
                    315: 	foreach my $foil (@$order) {
                    316: 	    if ($grading{$foil} == 1) {
                    317: 		$toprow.='<td><b>'.$answer{$foil}.'&nbsp;</b></td>';
                    318: 	    } else {
                    319: 		$toprow.='<td><i>'.$answer{$foil}.'&nbsp;</i></td>';
                    320: 	    }
1.398     albertel  321: 	    $bottomrow.='<td>'.$grayFont.$foil.'</span>&nbsp;</td>';
1.148     albertel  322: 	}
                    323: 	return '<blockquote><table border="1">'.
1.466     albertel  324: 	    '<tr valign="top"><td>'.&mt('Answer').'</td>'.$toprow.'</tr>'.
                    325: 	    '<tr valign="top"><td>'.$grayFont.&mt('Option ID').'</span></td>'.
1.148     albertel  326: 	    $grayFont.$bottomrow.'</tr>'.'</table></blockquote>';
                    327:     } elsif ($response eq 'match') {
                    328: 	my %answer=&Apache::lonnet::str2hash($answer);
                    329: 	my %grading=&Apache::lonnet::str2hash($record->{$version."resource.$partid.$respid.submissiongrading"});
                    330: 	my @items=&Apache::lonnet::str2array($record->{$version."resource.$partid.$respid.submissionitems"});
                    331: 	my ($toprow,$middlerow,$bottomrow);
                    332: 	foreach my $foil (@$order) {
                    333: 	    my $item=shift(@items);
                    334: 	    if ($grading{$foil} == 1) {
                    335: 		$toprow.='<td><b>'.$item.'&nbsp;</b></td>';
1.398     albertel  336: 		$middlerow.='<td><b>'.$grayFont.$answer{$foil}.'&nbsp;</span></b></td>';
1.148     albertel  337: 	    } else {
                    338: 		$toprow.='<td><i>'.$item.'&nbsp;</i></td>';
1.398     albertel  339: 		$middlerow.='<td><i>'.$grayFont.$answer{$foil}.'&nbsp;</span></i></td>';
1.148     albertel  340: 	    }
1.398     albertel  341: 	    $bottomrow.='<td>'.$grayFont.$foil.'</span>&nbsp;</td>';
1.118     ng        342: 	}
1.126     ng        343: 	return '<blockquote><table border="1">'.
1.466     albertel  344: 	    '<tr valign="top"><td>'.&mt('Answer').'</td>'.$toprow.'</tr>'.
                    345: 	    '<tr valign="top"><td>'.$grayFont.&mt('Item ID').'</span></td>'.
1.148     albertel  346: 	    $middlerow.'</tr>'.
1.466     albertel  347: 	    '<tr valign="top"><td>'.$grayFont.&mt('Option ID').'</span></td>'.
1.148     albertel  348: 	    $bottomrow.'</tr>'.'</table></blockquote>';
                    349:     } elsif ($response eq 'radiobutton') {
                    350: 	my %answer=&Apache::lonnet::str2hash($answer);
                    351: 	my ($toprow,$bottomrow);
1.434     albertel  352: 	my $correct = 
                    353: 	    &get_radiobutton_correct_foil($partid,$respid,$symb,$uname,$udom);
                    354: 	foreach my $foil (@$order) {
1.148     albertel  355: 	    if (exists($answer{$foil})) {
1.434     albertel  356: 		if ($foil eq $correct) {
1.466     albertel  357: 		    $toprow.='<td><b>'.&mt('true').'</b></td>';
1.148     albertel  358: 		} else {
1.466     albertel  359: 		    $toprow.='<td><i>'.&mt('true').'</i></td>';
1.148     albertel  360: 		}
                    361: 	    } else {
1.466     albertel  362: 		$toprow.='<td>'.&mt('false').'</td>';
1.148     albertel  363: 	    }
1.398     albertel  364: 	    $bottomrow.='<td>'.$grayFont.$foil.'</span>&nbsp;</td>';
1.148     albertel  365: 	}
                    366: 	return '<blockquote><table border="1">'.
1.466     albertel  367: 	    '<tr valign="top"><td>'.&mt('Answer').'</td>'.$toprow.'</tr>'.
                    368: 	    '<tr valign="top"><td>'.$grayFont.&mt('Option ID').'</span></td>'.
1.597     wenzelju  369: 	    $bottomrow.'</tr>'.'</table></blockquote>';
1.148     albertel  370:     } elsif ($response eq 'essay') {
1.257     albertel  371: 	if (! exists ($env{'form.'.$symb})) {
1.122     ng        372: 	    my (%keyhash) = &Apache::lonnet::dump('nohist_handgrade',
1.257     albertel  373: 						  $env{'course.'.$env{'request.course.id'}.'.domain'},
                    374: 						  $env{'course.'.$env{'request.course.id'}.'.num'});
1.122     ng        375: 
1.257     albertel  376: 	    my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
                    377: 	    $env{'form.keywords'} = $keyhash{$symb.'_keywords'} ne '' ? $keyhash{$symb.'_keywords'} : '';
                    378: 	    $env{'form.kwclr'}    = $keyhash{$loginuser.'_kwclr'} ne '' ? $keyhash{$loginuser.'_kwclr'} : 'red';
                    379: 	    $env{'form.kwsize'}   = $keyhash{$loginuser.'_kwsize'} ne '' ? $keyhash{$loginuser.'_kwsize'} : '0';
                    380: 	    $env{'form.kwstyle'}  = $keyhash{$loginuser.'_kwstyle'} ne '' ? $keyhash{$loginuser.'_kwstyle'} : '';
                    381: 	    $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        382: 	}
1.166     albertel  383: 	$answer =~ s-\n-<br />-g;
                    384: 	return '<br /><br /><blockquote><tt>'.&keywords_highlight($answer).'</tt></blockquote>';
1.268     albertel  385:     } elsif ( $response eq 'organic') {
                    386: 	my $result='Smile representation: "<tt>'.$answer.'</tt>"';
                    387: 	my $jme=$record->{$version."resource.$partid.$respid.molecule"};
                    388: 	$result.=&Apache::chemresponse::jme_img($jme,$answer,400);
                    389: 	return $result;
1.335     albertel  390:     } elsif ( $response eq 'Task') {
                    391: 	if ( $answer eq 'SUBMITTED') {
                    392: 	    my $files = $record->{$version."resource.$respid.$partid.bridgetask.portfiles"};
1.336     albertel  393: 	    my $result = &Apache::bridgetask::file_list($files,$uname,$udom);
1.335     albertel  394: 	    return $result;
                    395: 	} elsif ( grep(/^\Q$version\E.*?\.instance$/, keys(%{$record})) ) {
                    396: 	    my @matches = grep(/^\Q$version\E.*?\.instance$/,
                    397: 			       keys(%{$record}));
                    398: 	    return join('<br />',($version,@matches));
                    399: 			       
                    400: 			       
                    401: 	} else {
                    402: 	    my $result =
                    403: 		'<p>'
                    404: 		.&mt('Overall result: [_1]',
                    405: 		     $record->{$version."resource.$respid.$partid.status"})
                    406: 		.'</p>';
                    407: 	    
                    408: 	    $result .= '<ul>';
                    409: 	    my @grade = grep(/^\Q${version}resource.$respid.$partid.\E[^.]*[.]status$/,
                    410: 			     keys(%{$record}));
                    411: 	    foreach my $grade (sort(@grade)) {
                    412: 		my ($dim) = ($grade =~/[.]([^.]+)[.]status$/);
                    413: 		$result.= '<li>'.&mt("Dimension: [_1], status [_2] ",
                    414: 				     $dim, $record->{$grade}).
                    415: 			  '</li>';
                    416: 	    }
                    417: 	    $result.='</ul>';
                    418: 	    return $result;
                    419: 	}
1.440     albertel  420:     } elsif ( $response =~ m/(?:numerical|formula)/) {
                    421: 	$answer = 
                    422: 	    &Apache::loncommon::format_previous_attempt_value('submission',
                    423: 							      $answer);
1.122     ng        424:     }
1.118     ng        425:     return $answer;
                    426: }
                    427: 
                    428: #-- A couple of common js functions
                    429: sub commonJSfunctions {
                    430:     my $request = shift;
1.597     wenzelju  431:     $request->print(&Apache::lonhtmlcommon::scripttag(<<COMMONJSFUNCTIONS));
1.118     ng        432:     function radioSelection(radioButton) {
                    433: 	var selection=null;
                    434: 	if (radioButton.length > 1) {
                    435: 	    for (var i=0; i<radioButton.length; i++) {
                    436: 		if (radioButton[i].checked) {
                    437: 		    return radioButton[i].value;
                    438: 		}
                    439: 	    }
                    440: 	} else {
                    441: 	    if (radioButton.checked) return radioButton.value;
                    442: 	}
                    443: 	return selection;
                    444:     }
                    445: 
                    446:     function pullDownSelection(selectOne) {
                    447: 	var selection="";
                    448: 	if (selectOne.length > 1) {
                    449: 	    for (var i=0; i<selectOne.length; i++) {
                    450: 		if (selectOne[i].selected) {
                    451: 		    return selectOne[i].value;
                    452: 		}
                    453: 	    }
                    454: 	} else {
1.138     albertel  455:             // only one value it must be the selected one
                    456: 	    return selectOne.value;
1.118     ng        457: 	}
                    458:     }
                    459: COMMONJSFUNCTIONS
                    460: }
                    461: 
1.44      ng        462: #--- Dumps the class list with usernames,list of sections,
                    463: #--- section, ids and fullnames for each user.
                    464: sub getclasslist {
1.449     banghart  465:     my ($getsec,$filterlist,$getgroup) = @_;
1.291     albertel  466:     my @getsec;
1.450     banghart  467:     my @getgroup;
1.442     banghart  468:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
1.291     albertel  469:     if (!ref($getsec)) {
                    470: 	if ($getsec ne '' && $getsec ne 'all') {
                    471: 	    @getsec=($getsec);
                    472: 	}
                    473:     } else {
                    474: 	@getsec=@{$getsec};
                    475:     }
                    476:     if (grep(/^all$/,@getsec)) { undef(@getsec); }
1.450     banghart  477:     if (!ref($getgroup)) {
                    478: 	if ($getgroup ne '' && $getgroup ne 'all') {
                    479: 	    @getgroup=($getgroup);
                    480: 	}
                    481:     } else {
                    482: 	@getgroup=@{$getgroup};
                    483:     }
                    484:     if (grep(/^all$/,@getgroup)) { undef(@getgroup); }
1.291     albertel  485: 
1.449     banghart  486:     my ($classlist,$keylist)=&Apache::loncoursedata::get_classlist();
1.49      albertel  487:     # Bail out if we were unable to get the classlist
1.56      matthew   488:     return if (! defined($classlist));
1.449     banghart  489:     &Apache::loncoursedata::get_group_memberships($classlist,$keylist);
1.56      matthew   490:     #
                    491:     my %sections;
                    492:     my %fullnames;
1.205     matthew   493:     foreach my $student (keys(%$classlist)) {
                    494:         my $end      = 
                    495:             $classlist->{$student}->[&Apache::loncoursedata::CL_END()];
                    496:         my $start    = 
                    497:             $classlist->{$student}->[&Apache::loncoursedata::CL_START()];
                    498:         my $id       = 
                    499:             $classlist->{$student}->[&Apache::loncoursedata::CL_ID()];
                    500:         my $section  = 
                    501:             $classlist->{$student}->[&Apache::loncoursedata::CL_SECTION()];
                    502:         my $fullname = 
                    503:             $classlist->{$student}->[&Apache::loncoursedata::CL_FULLNAME()];
                    504:         my $status   = 
                    505:             $classlist->{$student}->[&Apache::loncoursedata::CL_STATUS()];
1.449     banghart  506:         my $group   = 
                    507:             $classlist->{$student}->[&Apache::loncoursedata::CL_GROUP()];
1.76      ng        508: 	# filter students according to status selected
1.442     banghart  509: 	if ($filterlist && (!($stu_status =~ /Any/))) {
                    510: 	    if (!($stu_status =~ $status)) {
1.450     banghart  511: 		delete($classlist->{$student});
1.76      ng        512: 		next;
                    513: 	    }
                    514: 	}
1.450     banghart  515: 	# filter students according to groups selected
1.453     banghart  516: 	my @stu_groups = split(/,/,$group);
1.450     banghart  517: 	if (@getgroup) {
                    518: 	    my $exclude = 1;
1.454     banghart  519: 	    foreach my $grp (@getgroup) {
                    520: 	        foreach my $stu_group (@stu_groups) {
1.453     banghart  521: 	            if ($stu_group eq $grp) {
                    522: 	                $exclude = 0;
                    523:     	            } 
1.450     banghart  524: 	        }
1.453     banghart  525:     	        if (($grp eq 'none') && !$group) {
                    526:         	        $exclude = 0;
                    527:         	}
1.450     banghart  528: 	    }
                    529: 	    if ($exclude) {
                    530: 	        delete($classlist->{$student});
                    531: 	    }
                    532: 	}
1.205     matthew   533: 	$section = ($section ne '' ? $section : 'none');
1.106     albertel  534: 	if (&canview($section)) {
1.291     albertel  535: 	    if (!@getsec || grep(/^\Q$section\E$/,@getsec)) {
1.103     albertel  536: 		$sections{$section}++;
1.450     banghart  537: 		if ($classlist->{$student}) {
                    538: 		    $fullnames{$student}=$fullname;
                    539: 		}
1.103     albertel  540: 	    } else {
1.205     matthew   541: 		delete($classlist->{$student});
1.103     albertel  542: 	    }
                    543: 	} else {
1.205     matthew   544: 	    delete($classlist->{$student});
1.103     albertel  545: 	}
1.44      ng        546:     }
                    547:     my %seen = ();
1.56      matthew   548:     my @sections = sort(keys(%sections));
                    549:     return ($classlist,\@sections,\%fullnames);
1.44      ng        550: }
                    551: 
1.103     albertel  552: sub canmodify {
                    553:     my ($sec)=@_;
                    554:     if ($perm{'mgr'}) {
                    555: 	if (!defined($perm{'mgr_section'})) {
                    556: 	    # can modify whole class
                    557: 	    return 1;
                    558: 	} else {
                    559: 	    if ($sec eq $perm{'mgr_section'}) {
                    560: 		#can modify the requested section
                    561: 		return 1;
                    562: 	    } else {
                    563: 		# can't modify the request section
                    564: 		return 0;
                    565: 	    }
                    566: 	}
                    567:     }
                    568:     #can't modify
                    569:     return 0;
                    570: }
                    571: 
                    572: sub canview {
                    573:     my ($sec)=@_;
                    574:     if ($perm{'vgr'}) {
                    575: 	if (!defined($perm{'vgr_section'})) {
                    576: 	    # can modify whole class
                    577: 	    return 1;
                    578: 	} else {
                    579: 	    if ($sec eq $perm{'vgr_section'}) {
                    580: 		#can modify the requested section
                    581: 		return 1;
                    582: 	    } else {
                    583: 		# can't modify the request section
                    584: 		return 0;
                    585: 	    }
                    586: 	}
                    587:     }
                    588:     #can't modify
                    589:     return 0;
                    590: }
                    591: 
1.44      ng        592: #--- Retrieve the grade status of a student for all the parts
                    593: sub student_gradeStatus {
1.324     albertel  594:     my ($symb,$udom,$uname,$partlist) = @_;
1.257     albertel  595:     my %record     = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
1.44      ng        596:     my %partstatus = ();
                    597:     foreach (@$partlist) {
1.128     ng        598: 	my ($status,undef)   = split(/_/,$record{"resource.$_.solved"},2);
1.44      ng        599: 	$status              = 'nothing' if ($status eq '');
                    600: 	$partstatus{$_}      = $status;
                    601: 	my $subkey           = "resource.$_.submitted_by";
                    602: 	$partstatus{$subkey} = $record{$subkey} if ($record{$subkey} ne '');
                    603:     }
                    604:     return %partstatus;
                    605: }
                    606: 
1.45      ng        607: # hidden form and javascript that calls the form
                    608: # Use by verifyscript and viewgrades
                    609: # Shows a student's view of problem and submission
                    610: sub jscriptNform {
1.324     albertel  611:     my ($symb) = @_;
1.442     banghart  612:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
1.597     wenzelju  613:     my $jscript= &Apache::lonhtmlcommon::scripttag(
1.45      ng        614: 	'    function viewOneStudent(user,domain) {'."\n".
                    615: 	'	document.onestudent.student.value = user;'."\n".
                    616: 	'	document.onestudent.userdom.value = domain;'."\n".
                    617: 	'	document.onestudent.submit();'."\n".
                    618: 	'    }'."\n".
1.597     wenzelju  619: 	"\n");
1.45      ng        620:     $jscript.= '<form action="/adm/grades" method="post" name="onestudent">'."\n".
1.418     albertel  621: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.442     banghart  622: 	'<input type="hidden" name="Status"  value="'.$stu_status.'" />'."\n".
1.45      ng        623: 	'<input type="hidden" name="command" value="submission" />'."\n".
                    624: 	'<input type="hidden" name="student" value="" />'."\n".
                    625: 	'<input type="hidden" name="userdom" value="" />'."\n".
                    626: 	'</form>'."\n";
                    627:     return $jscript;
                    628: }
1.39      ng        629: 
1.447     foxr      630: 
                    631: 
1.315     bowersj2  632: # Given the score (as a number [0-1] and the weight) what is the final
                    633: # point value? This function will round to the nearest tenth, third,
                    634: # or quarter if one of those is within the tolerance of .00001.
1.316     albertel  635: sub compute_points {
1.315     bowersj2  636:     my ($score, $weight) = @_;
                    637:     
                    638:     my $tolerance = .00001;
                    639:     my $points = $score * $weight;
                    640: 
                    641:     # Check for nearness to 1/x.
                    642:     my $check_for_nearness = sub {
                    643:         my ($factor) = @_;
                    644:         my $num = ($points * $factor) + $tolerance;
                    645:         my $floored_num = floor($num);
1.316     albertel  646:         if ($num - $floored_num < 2 * $tolerance * $factor) {
1.315     bowersj2  647:             return $floored_num / $factor;
                    648:         }
                    649:         return $points;
                    650:     };
                    651: 
                    652:     $points = $check_for_nearness->(10);
                    653:     $points = $check_for_nearness->(3);
                    654:     $points = $check_for_nearness->(4);
                    655:     
                    656:     return $points;
                    657: }
                    658: 
1.44      ng        659: #------------------ End of general use routines --------------------
1.87      www       660: 
                    661: #
                    662: # Find most similar essay
                    663: #
                    664: 
                    665: sub most_similar {
1.426     albertel  666:     my ($uname,$udom,$uessay,$old_essays)=@_;
1.87      www       667: 
                    668: # ignore spaces and punctuation
                    669: 
                    670:     $uessay=~s/\W+/ /gs;
                    671: 
1.282     www       672: # ignore empty submissions (occuring when only files are sent)
                    673: 
1.598     www       674:     unless ($uessay=~/\w+/s) { return ''; }
1.282     www       675: 
1.87      www       676: # these will be returned. Do not care if not at least 50 percent similar
1.88      www       677:     my $limit=0.6;
1.87      www       678:     my $sname='';
                    679:     my $sdom='';
                    680:     my $scrsid='';
                    681:     my $sessay='';
                    682: # go through all essays ...
1.426     albertel  683:     foreach my $tkey (keys(%$old_essays)) {
                    684: 	my ($tname,$tdom,$tcrsid)=map {&unescape($_)} (split(/\./,$tkey));
1.87      www       685: # ... except the same student
1.426     albertel  686:         next if (($tname eq $uname) && ($tdom eq $udom));
                    687: 	my $tessay=$old_essays->{$tkey};
                    688: 	$tessay=~s/\W+/ /gs;
1.87      www       689: # String similarity gives up if not even limit
1.426     albertel  690: 	my $tsimilar=&String::Similarity::similarity($uessay,$tessay,$limit);
1.87      www       691: # Found one
1.426     albertel  692: 	if ($tsimilar>$limit) {
                    693: 	    $limit=$tsimilar;
                    694: 	    $sname=$tname;
                    695: 	    $sdom=$tdom;
                    696: 	    $scrsid=$tcrsid;
                    697: 	    $sessay=$old_essays->{$tkey};
                    698: 	}
1.87      www       699:     }
1.88      www       700:     if ($limit>0.6) {
1.87      www       701:        return ($sname,$sdom,$scrsid,$sessay,$limit);
                    702:     } else {
                    703:        return ('','','','',0);
                    704:     }
                    705: }
                    706: 
1.44      ng        707: #-------------------------------------------------------------------
                    708: 
                    709: #------------------------------------ Receipt Verification Routines
1.45      ng        710: #
1.602     www       711: 
                    712: sub initialverifyreceipt {
1.608     www       713:    my ($request,$symb) = @_;
1.602     www       714:    &commonJSfunctions($request);
1.605     www       715:    return '<form name="gradingMenu"><input type="submit" value="'.&mt('Verify Receipt Number.').'" />'.
1.602     www       716:         &Apache::lonnet::recprefix($env{'request.course.id'}).
                    717:         '-<input type="text" name="receipt" size="4" />'.
1.603     www       718:         '<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
                    719:         '<input type="hidden" name="command" value="verify" />'.
                    720:         "</form>\n";
1.602     www       721: }
                    722: 
1.44      ng        723: #--- Check whether a receipt number is valid.---
                    724: sub verifyreceipt {
1.608     www       725:     my ($request,$symb)  = @_;
1.44      ng        726: 
1.257     albertel  727:     my $courseid = $env{'request.course.id'};
1.184     www       728:     my $receipt  = &Apache::lonnet::recprefix($courseid).'-'.
1.257     albertel  729: 	$env{'form.receipt'};
1.44      ng        730:     $receipt     =~ s/[^\-\d]//g;
                    731: 
1.487     albertel  732:     my $title.=
                    733: 	'<h3><span class="LC_info">'.
1.605     www       734: 	&mt('Verifying Receipt Number [_1]',$receipt).
                    735: 	'</span></h3>'."\n";
1.44      ng        736: 
                    737:     my ($string,$contents,$matches) = ('','',0);
1.56      matthew   738:     my (undef,undef,$fullname) = &getclasslist('all','0');
1.177     albertel  739:     
                    740:     my $receiptparts=0;
1.390     albertel  741:     if ($env{"course.$courseid.receiptalg"} eq 'receipt2' ||
                    742: 	$env{"course.$courseid.receiptalg"} eq 'receipt3') { $receiptparts=1; }
1.177     albertel  743:     my $parts=['0'];
1.582     raeburn   744:     if ($receiptparts) {
                    745:         my $res_error; 
                    746:         ($parts)=&response_type($symb,\$res_error);
                    747:         if ($res_error) {
                    748:             return &navmap_errormsg();
                    749:         } 
                    750:     }
1.486     albertel  751:     
                    752:     my $header = 
                    753: 	&Apache::loncommon::start_data_table().
                    754: 	&Apache::loncommon::start_data_table_header_row().
1.487     albertel  755: 	'<th>&nbsp;'.&mt('Fullname').'&nbsp;</th>'."\n".
                    756: 	'<th>&nbsp;'.&mt('Username').'&nbsp;</th>'."\n".
                    757: 	'<th>&nbsp;'.&mt('Domain').'&nbsp;</th>';
1.486     albertel  758:     if ($receiptparts) {
1.487     albertel  759: 	$header.='<th>&nbsp;'.&mt('Problem Part').'&nbsp;</th>';
1.486     albertel  760:     }
                    761:     $header.=
                    762: 	&Apache::loncommon::end_data_table_header_row();
                    763: 
1.294     albertel  764:     foreach (sort 
                    765: 	     {
                    766: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                    767: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                    768: 		 }
                    769: 		 return $a cmp $b;
                    770: 	     } (keys(%$fullname))) {
1.44      ng        771: 	my ($uname,$udom)=split(/\:/);
1.177     albertel  772: 	foreach my $part (@$parts) {
                    773: 	    if ($receipt eq &Apache::lonnet::ireceipt($uname,$udom,$courseid,$symb,$part)) {
1.486     albertel  774: 		$contents.=
                    775: 		    &Apache::loncommon::start_data_table_row().
                    776: 		    '<td>&nbsp;'."\n".
1.177     albertel  777: 		    '<a href="javascript:viewOneStudent(\''.$uname.'\',\''.$udom.
1.417     albertel  778: 		    '\');" target="_self">'.$$fullname{$_}.'</a>&nbsp;</td>'."\n".
1.177     albertel  779: 		    '<td>&nbsp;'.$uname.'&nbsp;</td>'.
                    780: 		    '<td>&nbsp;'.$udom.'&nbsp;</td>';
                    781: 		if ($receiptparts) {
                    782: 		    $contents.='<td>&nbsp;'.$part.'&nbsp;</td>';
                    783: 		}
1.486     albertel  784: 		$contents.= 
                    785: 		    &Apache::loncommon::end_data_table_row()."\n";
1.177     albertel  786: 		
                    787: 		$matches++;
                    788: 	    }
1.44      ng        789: 	}
                    790:     }
                    791:     if ($matches == 0) {
1.584     bisitz    792:         $string = $title
                    793:                  .'<p class="LC_warning">'
                    794:                  .&mt('No match found for the above receipt number.')
                    795:                  .'</p>';
1.44      ng        796:     } else {
1.324     albertel  797: 	$string = &jscriptNform($symb).$title.
1.487     albertel  798: 	    '<p>'.
1.584     bisitz    799: 	    &mt('The above receipt number matches the following [quant,_1,student].',$matches).
1.487     albertel  800: 	    '</p>'.
1.486     albertel  801: 	    $header.
                    802: 	    $contents.
                    803: 	    &Apache::loncommon::end_data_table()."\n";
1.44      ng        804:     }
1.614     www       805:     return $string;
1.44      ng        806: }
                    807: 
                    808: #--- This is called by a number of programs.
                    809: #--- Called from the Grading Menu - View/Grade an individual student
                    810: #--- Also called directly when one clicks on the subm button 
                    811: #    on the problem page.
1.30      ng        812: sub listStudents {
1.617     www       813:     my ($request,$symb,$submitonly) = @_;
1.49      albertel  814: 
1.257     albertel  815:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
                    816:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
                    817:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
1.449     banghart  818:     my $getgroup  = $env{'form.group'} eq '' ? 'all' : $env{'form.group'};
1.617     www       819:     unless ($submitonly) {
                    820:        $submitonly= $env{'form.submitonly'} eq '' ? 'all' : $env{'form.submitonly'};
                    821:     }
1.49      albertel  822: 
1.548     bisitz    823:     my $result='<h3><span class="LC_info">&nbsp;'
1.618     www       824: 	.&mt("View/Grade/Regrade Submissions for a Student or a Group of Students")
1.485     albertel  825: 	.'</span></h3>';
1.623     www       826:     my $res_error;
                    827:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
1.49      albertel  828: 
1.559     raeburn   829:     my %lt = &Apache::lonlocal::texthash (
                    830: 		'multiple' => 'Please select a student or group of students before clicking on the Next button.',
                    831: 		'single'   => 'Please select the student before clicking on the Next button.',
                    832: 	     );
1.597     wenzelju  833:     $request->print(&Apache::lonhtmlcommon::scripttag(<<LISTJAVASCRIPT));
1.110     ng        834:     function checkSelect(checkBox) {
                    835: 	var ctr=0;
                    836: 	var sense="";
                    837: 	if (checkBox.length > 1) {
                    838: 	    for (var i=0; i<checkBox.length; i++) {
                    839: 		if (checkBox[i].checked) {
                    840: 		    ctr++;
                    841: 		}
                    842: 	    }
1.485     albertel  843: 	    sense = '$lt{'multiple'}';
1.110     ng        844: 	} else {
                    845: 	    if (checkBox.checked) {
                    846: 		ctr = 1;
                    847: 	    }
1.485     albertel  848: 	    sense = '$lt{'single'}';
1.110     ng        849: 	}
                    850: 	if (ctr == 0) {
1.485     albertel  851: 	    alert(sense);
1.110     ng        852: 	    return false;
                    853: 	}
                    854: 	document.gradesub.submit();
                    855:     }
                    856: 
                    857:     function reLoadList(formname) {
1.112     ng        858: 	if (formname.saveStatusOld.value == pullDownSelection(formname.Status)) {return;}
1.110     ng        859: 	formname.command.value = 'submission';
                    860: 	formname.submit();
                    861:     }
1.45      ng        862: LISTJAVASCRIPT
                    863: 
1.118     ng        864:     &commonJSfunctions($request);
1.41      ng        865:     $request->print($result);
1.39      ng        866: 
1.154     albertel  867:     my $gradeTable='<form action="/adm/grades" method="post" name="gradesub">'.
1.598     www       868: 	"\n";
1.485     albertel  869: 	
1.561     bisitz    870:     $gradeTable .= &Apache::lonhtmlcommon::start_pick_box();
                    871:     $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('View Problem Text'))
                    872:                   .'<label><input type="radio" name="vProb" value="no" checked="checked" /> '.&mt('no').' </label>'."\n"
                    873:                   .'<label><input type="radio" name="vProb" value="yes" /> '.&mt('one student').' </label>'."\n"
                    874:                   .'<label><input type="radio" name="vProb" value="all" /> '.&mt('all students').' </label><br />'."\n"
                    875:                   .&Apache::lonhtmlcommon::row_closure();
                    876:     $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('View Answer'))
                    877:                   .'<label><input type="radio" name="vAns" value="no"  /> '.&mt('no').' </label>'."\n"
                    878:                   .'<label><input type="radio" name="vAns" value="yes" /> '.&mt('one student').' </label>'."\n"
                    879:                   .'<label><input type="radio" name="vAns" value="all" checked="checked" /> '.&mt('all students').' </label><br />'."\n"
                    880:                   .&Apache::lonhtmlcommon::row_closure();
1.485     albertel  881: 
                    882:     my $submission_options;
1.442     banghart  883:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
                    884:     my $saveStatus = $stu_status eq '' ? 'Active' : $stu_status;
1.257     albertel  885:     $env{'form.Status'} = $saveStatus;
1.485     albertel  886:     $submission_options.=
1.592     bisitz    887:         '<span class="LC_nobreak">'.
1.624     www       888:         '<label><input type="radio" name="lastSub" value="lastonly" /> '.
1.592     bisitz    889:         &mt('last submission only').' </label></span>'."\n".
                    890:         '<span class="LC_nobreak">'.
                    891:         '<label><input type="radio" name="lastSub" value="last" /> '.
                    892:         &mt('last submission &amp; parts info').' </label></span>'."\n".
                    893:         '<span class="LC_nobreak">'.
                    894:         '<label><input type="radio" name="lastSub" value="datesub" /> '.
                    895:         &mt('by dates and submissions').'</label></span>'."\n".
                    896:         '<span class="LC_nobreak">'.
                    897:         '<label><input type="radio" name="lastSub" value="all" /> '.
                    898:         &mt('all details').'</label></span>';
1.561     bisitz    899:     $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('Submissions'))
                    900:                   .$submission_options
                    901:                   .&Apache::lonhtmlcommon::row_closure();
                    902: 
                    903:     $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('Grading Increments'))
                    904:                   .'<select name="increment">'
                    905:                   .'<option value="1">'.&mt('Whole Points').'</option>'
                    906:                   .'<option value=".5">'.&mt('Half Points').'</option>'
                    907:                   .'<option value=".25">'.&mt('Quarter Points').'</option>'
                    908:                   .'<option value=".1">'.&mt('Tenths of a Point').'</option>'
                    909:                   .'</select>'
                    910:                   .&Apache::lonhtmlcommon::row_closure();
1.485     albertel  911: 
                    912:     $gradeTable .= 
1.432     banghart  913:         &build_section_inputs().
1.45      ng        914: 	'<input type="hidden" name="submitonly"  value="'.$submitonly.'" />'."\n".
1.418     albertel  915: 	'<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.110     ng        916: 	'<input type="hidden" name="saveStatusOld" value="'.$saveStatus.'" />'."\n";
                    917: 
1.618     www       918:     if (exists($env{'form.Status'})) {
1.561     bisitz    919: 	$gradeTable .= '<input type="hidden" name="Status" value="'.$stu_status.'" />'."\n";
1.124     ng        920:     } else {
1.561     bisitz    921:         $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('Student Status'))
                    922:                       .&Apache::lonhtmlcommon::StatusOptions(
                    923:                            $saveStatus,undef,1,'javascript:reLoadList(this.form);')
                    924:                       .&Apache::lonhtmlcommon::row_closure();
1.124     ng        925:     }
1.112     ng        926: 
1.561     bisitz    927:     $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('Check For Plagiarism'))
                    928:                   .'<input type="checkbox" name="checkPlag" checked="checked" />'
                    929:                   .&Apache::lonhtmlcommon::row_closure(1)
                    930:                   .&Apache::lonhtmlcommon::end_pick_box();
                    931: 
                    932:     $gradeTable .= '<p>'
1.618     www       933:                   .&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    934:                   .'<input type="hidden" name="command" value="processGroup" />'
                    935:                   .'</p>';
1.249     albertel  936: 
                    937: # checkall buttons
                    938:     $gradeTable.=&check_script('gradesub', 'stuinfo');
1.110     ng        939:     $gradeTable.='<input type="button" '."\n".
1.589     bisitz    940:         'onclick="javascript:checkSelect(this.form.stuinfo);" '."\n".
                    941:         'value="'.&mt('Next').' &rarr;" /> <br />'."\n";
1.249     albertel  942:     $gradeTable.=&check_buttons();
1.450     banghart  943:     my ($classlist, undef, $fullname) = &getclasslist($getsec,'1',$getgroup);
1.474     albertel  944:     $gradeTable.= &Apache::loncommon::start_data_table().
                    945: 	&Apache::loncommon::start_data_table_header_row();
1.110     ng        946:     my $loop = 0;
                    947:     while ($loop < 2) {
1.485     albertel  948: 	$gradeTable.='<th>'.&mt('No.').'</th><th>'.&mt('Select').'</th>'.
                    949: 	    '<th>'.&nameUserString('header').'&nbsp;'.&mt('Section/Group').'</th>';
1.618     www       950: 	if (($submitonly ne 'queued') && ($submitonly ne 'all')) {
1.485     albertel  951: 	    foreach my $part (sort(@$partlist)) {
                    952: 		my $display_part=
                    953: 		    &get_display_part((split(/_/,$part))[0],$symb);
                    954: 		$gradeTable.=
                    955: 		    '<th>'.&mt('Part: [_1] Status',$display_part).'</th>';
1.110     ng        956: 	    }
1.301     albertel  957: 	} elsif ($submitonly eq 'queued') {
1.474     albertel  958: 	    $gradeTable.='<th>'.&mt('Queue Status').'&nbsp;</th>';
1.110     ng        959: 	}
                    960: 	$loop++;
1.126     ng        961: #	$gradeTable.='<td></td>' if ($loop%2 ==1);
1.41      ng        962:     }
1.474     albertel  963:     $gradeTable.=&Apache::loncommon::end_data_table_header_row()."\n";
1.41      ng        964: 
1.45      ng        965:     my $ctr = 0;
1.294     albertel  966:     foreach my $student (sort 
                    967: 			 {
                    968: 			     if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                    969: 				 return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                    970: 			     }
                    971: 			     return $a cmp $b;
                    972: 			 }
                    973: 			 (keys(%$fullname))) {
1.41      ng        974: 	my ($uname,$udom) = split(/:/,$student);
1.301     albertel  975: 
1.110     ng        976: 	my %status = ();
1.301     albertel  977: 
                    978: 	if ($submitonly eq 'queued') {
                    979: 	    my %queue_status = 
                    980: 		&Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
                    981: 							$udom,$uname);
                    982: 	    next if (!defined($queue_status{'gradingqueue'}));
                    983: 	    $status{'gradingqueue'} = $queue_status{'gradingqueue'};
                    984: 	}
                    985: 
1.618     www       986: 	if (($submitonly ne 'queued') && ($submitonly ne 'all')) {
1.324     albertel  987: 	    (%status) =&student_gradeStatus($symb,$udom,$uname,$partlist);
1.145     albertel  988: 	    my $submitted = 0;
1.164     albertel  989: 	    my $graded = 0;
1.248     albertel  990: 	    my $incorrect = 0;
1.110     ng        991: 	    foreach (keys(%status)) {
1.145     albertel  992: 		$submitted = 1 if ($status{$_} ne 'nothing');
1.248     albertel  993: 		$graded = 1 if ($status{$_} =~ /^ungraded/);
                    994: 		$incorrect = 1 if ($status{$_} =~ /^incorrect/);
                    995: 		
1.110     ng        996: 		my ($foo,$partid,$foo1) = split(/\./,$_);
                    997: 		if ($status{'resource.'.$partid.'.submitted_by'} ne '') {
1.145     albertel  998: 		    $submitted = 0;
1.150     albertel  999: 		    my ($part)=split(/\./,$partid);
1.110     ng       1000: 		    $gradeTable.='<input type="hidden" name="'.
1.150     albertel 1001: 			$student.':'.$part.':submitted_by" value="'.
1.110     ng       1002: 			$status{'resource.'.$partid.'.submitted_by'}.'" />';
                   1003: 		}
1.41      ng       1004: 	    }
1.248     albertel 1005: 	    
1.156     albertel 1006: 	    next if (!$submitted && ($submitonly eq 'yes' ||
                   1007: 				     $submitonly eq 'incorrect' ||
                   1008: 				     $submitonly eq 'graded'));
1.248     albertel 1009: 	    next if (!$graded && ($submitonly eq 'graded'));
                   1010: 	    next if (!$incorrect && $submitonly eq 'incorrect');
1.41      ng       1011: 	}
1.34      ng       1012: 
1.45      ng       1013: 	$ctr++;
1.249     albertel 1014: 	my $section = $classlist->{$student}->[&Apache::loncoursedata::CL_SECTION()];
1.452     banghart 1015:         my $group = $classlist->{$student}->[&Apache::loncoursedata::CL_GROUP()];
1.104     albertel 1016: 	if ( $perm{'vgr'} eq 'F' ) {
1.474     albertel 1017: 	    if ($ctr%2 ==1) {
                   1018: 		$gradeTable.= &Apache::loncommon::start_data_table_row();
                   1019: 	    }
1.126     ng       1020: 	    $gradeTable.='<td align="right">'.$ctr.'&nbsp;</td>'.
1.563     bisitz   1021:                '<td align="center"><label><input type="checkbox" name="stuinfo" value="'.
1.249     albertel 1022:                $student.':'.$$fullname{$student}.':::SECTION'.$section.
                   1023: 	       ')&nbsp;" />&nbsp;&nbsp;</label></td>'."\n".'<td>'.
                   1024: 	       &nameUserString(undef,$$fullname{$student},$uname,$udom).
1.474     albertel 1025: 	       '&nbsp;'.$section.($group ne '' ?'/'.$group:'').'</td>'."\n";
1.110     ng       1026: 
1.618     www      1027: 	    if ($submitonly ne 'all') {
1.524     raeburn  1028: 		foreach (sort(keys(%status))) {
1.485     albertel 1029: 		    next if ($_ =~ /^resource.*?submitted_by$/);
                   1030: 		    $gradeTable.='<td align="center">&nbsp;'.&mt($status{$_}).'&nbsp;</td>'."\n";
1.110     ng       1031: 		}
1.41      ng       1032: 	    }
1.126     ng       1033: #	    $gradeTable.='<td></td>' if ($ctr%2 ==1);
1.474     albertel 1034: 	    if ($ctr%2 ==0) {
                   1035: 		$gradeTable.=&Apache::loncommon::end_data_table_row()."\n";
                   1036: 	    }
1.41      ng       1037: 	}
                   1038:     }
1.110     ng       1039:     if ($ctr%2 ==1) {
1.126     ng       1040: 	$gradeTable.='<td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td>';
1.618     www      1041: 	    if (($submitonly ne 'queued') && ($submitonly ne 'all')) {
1.110     ng       1042: 		foreach (@$partlist) {
                   1043: 		    $gradeTable.='<td>&nbsp;</td>';
                   1044: 		}
1.301     albertel 1045: 	    } elsif ($submitonly eq 'queued') {
                   1046: 		$gradeTable.='<td>&nbsp;</td>';
1.110     ng       1047: 	    }
1.474     albertel 1048: 	$gradeTable.=&Apache::loncommon::end_data_table_row();
1.110     ng       1049:     }
                   1050: 
1.474     albertel 1051:     $gradeTable.=&Apache::loncommon::end_data_table()."\n".
1.589     bisitz   1052:         '<input type="button" '.
                   1053:         'onclick="javascript:checkSelect(this.form.stuinfo);" '.
                   1054:         'value="'.&mt('Next').' &rarr;" /></form>'."\n";
1.45      ng       1055:     if ($ctr == 0) {
1.96      albertel 1056: 	my $num_students=(scalar(keys(%$fullname)));
                   1057: 	if ($num_students eq 0) {
1.485     albertel 1058: 	    $gradeTable='<br />&nbsp;<span class="LC_warning">'.&mt('There are no students currently enrolled.').'</span>';
1.96      albertel 1059: 	} else {
1.171     albertel 1060: 	    my $submissions='submissions';
                   1061: 	    if ($submitonly eq 'incorrect') { $submissions = 'incorrect submissions'; }
                   1062: 	    if ($submitonly eq 'graded'   ) { $submissions = 'ungraded submissions'; }
1.301     albertel 1063: 	    if ($submitonly eq 'queued'   ) { $submissions = 'queued submissions'; }
1.398     albertel 1064: 	    $gradeTable='<br />&nbsp;<span class="LC_warning">'.
1.485     albertel 1065: 		&mt('No '.$submissions.' found for this resource for any students. ([_1] students checked for '.$submissions.')',
                   1066: 		    $num_students).
                   1067: 		'</span><br />';
1.96      albertel 1068: 	}
1.46      ng       1069:     } elsif ($ctr == 1) {
1.474     albertel 1070: 	$gradeTable =~ s/type="checkbox"/type="checkbox" checked="checked"/;
1.45      ng       1071:     }
                   1072:     $request->print($gradeTable);
1.44      ng       1073:     return '';
1.10      ng       1074: }
                   1075: 
1.44      ng       1076: #---- Called from the listStudents routine
1.249     albertel 1077: 
                   1078: sub check_script {
                   1079:     my ($form, $type)=@_;
1.597     wenzelju 1080:     my $chkallscript= &Apache::lonhtmlcommon::scripttag('
1.249     albertel 1081:     function checkall() {
                   1082:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
                   1083:             ele = document.forms.'.$form.'.elements[i];
                   1084:             if (ele.name == "'.$type.'") {
                   1085:             document.forms.'.$form.'.elements[i].checked=true;
                   1086:                                        }
                   1087:         }
                   1088:     }
                   1089: 
                   1090:     function checksec() {
                   1091:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
                   1092:             ele = document.forms.'.$form.'.elements[i];
                   1093:            string = document.forms.'.$form.'.chksec.value;
                   1094:            if
                   1095:           (ele.value.indexOf(":::SECTION"+string)>0) {
                   1096:               document.forms.'.$form.'.elements[i].checked=true;
                   1097:             }
                   1098:         }
                   1099:     }
                   1100: 
                   1101: 
                   1102:     function uncheckall() {
                   1103:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
                   1104:             ele = document.forms.'.$form.'.elements[i];
                   1105:             if (ele.name == "'.$type.'") {
                   1106:             document.forms.'.$form.'.elements[i].checked=false;
                   1107:                                        }
                   1108:         }
                   1109:     }
                   1110: 
1.597     wenzelju 1111: '."\n");
1.249     albertel 1112:     return $chkallscript;
                   1113: }
                   1114: 
                   1115: sub check_buttons {
1.485     albertel 1116:     my $buttons.='<input type="button" onclick="checkall()" value="'.&mt('Check All').'" />';
                   1117:     $buttons.='<input type="button" onclick="uncheckall()" value="'.&mt('Uncheck All').'" />&nbsp;';
                   1118:     $buttons.='<input type="button" onclick="checksec()" value="'.&mt('Check Section/Group').'" />';
1.249     albertel 1119:     $buttons.='<input type="text" size="5" name="chksec" />&nbsp;';
                   1120:     return $buttons;
                   1121: }
                   1122: 
1.44      ng       1123: #     Displays the submissions for one student or a group of students
1.34      ng       1124: sub processGroup {
1.619     www      1125:     my ($request,$symb)  = @_;
1.41      ng       1126:     my $ctr        = 0;
1.155     albertel 1127:     my @stuchecked = &Apache::loncommon::get_env_multiple('form.stuinfo');
1.41      ng       1128:     my $total      = scalar(@stuchecked)-1;
1.45      ng       1129: 
1.396     banghart 1130:     foreach my $student (@stuchecked) {
                   1131: 	my ($uname,$udom,$fullname) = split(/:/,$student);
1.257     albertel 1132: 	$env{'form.student'}        = $uname;
                   1133: 	$env{'form.userdom'}        = $udom;
                   1134: 	$env{'form.fullname'}       = $fullname;
1.619     www      1135: 	&submission($request,$ctr,$total,$symb);
1.41      ng       1136: 	$ctr++;
                   1137:     }
                   1138:     return '';
1.35      ng       1139: }
1.34      ng       1140: 
1.44      ng       1141: #------------------------------------------------------------------------------------
                   1142: #
                   1143: #-------------------------- Next few routines handles grading by student, essentially
                   1144: #                           handles essay response type problem/part
                   1145: #
                   1146: #--- Javascript to handle the submission page functionality ---
                   1147: sub sub_page_js {
                   1148:     my $request = shift;
1.539     riegler  1149: 	    my $alertmsg = &mt('A number equal or greater than 0 is expected. Entered value = ');
1.597     wenzelju 1150:     $request->print(&Apache::lonhtmlcommon::scripttag(<<SUBJAVASCRIPT));
1.71      ng       1151:     function updateRadio(formname,id,weight) {
1.125     ng       1152: 	var gradeBox = formname["GD_BOX"+id];
                   1153: 	var radioButton = formname["RADVAL"+id];
                   1154: 	var oldpts = formname["oldpts"+id].value;
1.72      ng       1155: 	var pts = checkSolved(formname,id) == 'update' ? gradeBox.value : oldpts;
1.71      ng       1156: 	gradeBox.value = pts;
                   1157: 	var resetbox = false;
                   1158: 	if (isNaN(pts) || pts < 0) {
1.539     riegler  1159: 	    alert("$alertmsg"+pts);
1.71      ng       1160: 	    for (var i=0; i<radioButton.length; i++) {
                   1161: 		if (radioButton[i].checked) {
                   1162: 		    gradeBox.value = i;
                   1163: 		    resetbox = true;
                   1164: 		}
                   1165: 	    }
                   1166: 	    if (!resetbox) {
                   1167: 		formtextbox.value = "";
                   1168: 	    }
                   1169: 	    return;
1.44      ng       1170: 	}
1.71      ng       1171: 
                   1172: 	if (pts > weight) {
                   1173: 	    var resp = confirm("You entered a value ("+pts+
                   1174: 			       ") greater than the weight for the part. Accept?");
                   1175: 	    if (resp == false) {
1.125     ng       1176: 		gradeBox.value = oldpts;
1.71      ng       1177: 		return;
                   1178: 	    }
1.44      ng       1179: 	}
1.13      albertel 1180: 
1.71      ng       1181: 	for (var i=0; i<radioButton.length; i++) {
                   1182: 	    radioButton[i].checked=false;
                   1183: 	    if (pts == i && pts != "") {
                   1184: 		radioButton[i].checked=true;
                   1185: 	    }
                   1186: 	}
                   1187: 	updateSelect(formname,id);
1.125     ng       1188: 	formname["stores"+id].value = "0";
1.41      ng       1189:     }
1.5       albertel 1190: 
1.72      ng       1191:     function writeBox(formname,id,pts) {
1.125     ng       1192: 	var gradeBox = formname["GD_BOX"+id];
1.71      ng       1193: 	if (checkSolved(formname,id) == 'update') {
                   1194: 	    gradeBox.value = pts;
                   1195: 	} else {
1.125     ng       1196: 	    var oldpts = formname["oldpts"+id].value;
1.72      ng       1197: 	    gradeBox.value = oldpts;
1.125     ng       1198: 	    var radioButton = formname["RADVAL"+id];
1.71      ng       1199: 	    for (var i=0; i<radioButton.length; i++) {
                   1200: 		radioButton[i].checked=false;
1.72      ng       1201: 		if (i == oldpts) {
1.71      ng       1202: 		    radioButton[i].checked=true;
                   1203: 		}
                   1204: 	    }
1.41      ng       1205: 	}
1.125     ng       1206: 	formname["stores"+id].value = "0";
1.71      ng       1207: 	updateSelect(formname,id);
                   1208: 	return;
1.41      ng       1209:     }
1.44      ng       1210: 
1.71      ng       1211:     function clearRadBox(formname,id) {
                   1212: 	if (checkSolved(formname,id) == 'noupdate') {
                   1213: 	    updateSelect(formname,id);
                   1214: 	    return;
                   1215: 	}
1.125     ng       1216: 	gradeSelect = formname["GD_SEL"+id];
1.71      ng       1217: 	for (var i=0; i<gradeSelect.length; i++) {
                   1218: 	    if (gradeSelect[i].selected) {
                   1219: 		var selectx=i;
                   1220: 	    }
                   1221: 	}
1.125     ng       1222: 	var stores = formname["stores"+id];
1.71      ng       1223: 	if (selectx == stores.value) { return };
1.125     ng       1224: 	var gradeBox = formname["GD_BOX"+id];
1.71      ng       1225: 	gradeBox.value = "";
1.125     ng       1226: 	var radioButton = formname["RADVAL"+id];
1.71      ng       1227: 	for (var i=0; i<radioButton.length; i++) {
                   1228: 	    radioButton[i].checked=false;
                   1229: 	}
                   1230: 	stores.value = selectx;
                   1231:     }
1.5       albertel 1232: 
1.71      ng       1233:     function checkSolved(formname,id) {
1.125     ng       1234: 	if (formname["solved"+id].value == "correct_by_student" && formname.overRideScore.value == 'no') {
1.118     ng       1235: 	    var reply = confirm("This problem has been graded correct by the computer. Do you want to change the score?");
                   1236: 	    if (!reply) {return "noupdate";}
1.120     ng       1237: 	    formname.overRideScore.value = 'yes';
1.41      ng       1238: 	}
1.71      ng       1239: 	return "update";
1.13      albertel 1240:     }
1.71      ng       1241: 
                   1242:     function updateSelect(formname,id) {
1.125     ng       1243: 	formname["GD_SEL"+id][0].selected = true;
1.71      ng       1244: 	return;
1.41      ng       1245:     }
1.33      ng       1246: 
1.121     ng       1247: //=========== Check that a point is assigned for all the parts  ============
1.71      ng       1248:     function checksubmit(formname,val,total,parttot) {
1.121     ng       1249: 	formname.gradeOpt.value = val;
1.71      ng       1250: 	if (val == "Save & Next") {
                   1251: 	    for (i=0;i<=total;i++) {
                   1252: 		for (j=0;j<parttot;j++) {
1.125     ng       1253: 		    var partid = formname["partid"+i+"_"+j].value;
1.127     ng       1254: 		    if (formname["GD_SEL"+i+"_"+partid][0].selected) {
1.125     ng       1255: 			var points = formname["GD_BOX"+i+"_"+partid].value;
1.71      ng       1256: 			if (points == "") {
1.125     ng       1257: 			    var name = formname["name"+i].value;
1.129     ng       1258: 			    var studentID = (name != '' ? name : formname["unamedom"+i].value);
                   1259: 			    var resp = confirm("You did not assign a score for "+studentID+
                   1260: 					       ", part "+partid+". Continue?");
1.71      ng       1261: 			    if (resp == false) {
1.125     ng       1262: 				formname["GD_BOX"+i+"_"+partid].focus();
1.71      ng       1263: 				return false;
                   1264: 			    }
                   1265: 			}
                   1266: 		    }
                   1267: 		    
                   1268: 		}
                   1269: 	    }
                   1270: 	    
                   1271: 	}
1.121     ng       1272: 	if (val == "Grade Student") {
                   1273: 	    if (formname.Status.value == "") {
                   1274: 		formname.Status.value = "Active";
                   1275: 	    }
                   1276: 	    formname.studentNo.value = total;
                   1277: 	}
1.120     ng       1278: 	formname.submit();
                   1279:     }
                   1280: 
1.71      ng       1281: //======= Check that a score is assigned for all the problems (page/sequence grading only) =========
                   1282:     function checkSubmitPage(formname,total) {
                   1283: 	noscore = new Array(100);
                   1284: 	var ptr = 0;
                   1285: 	for (i=1;i<total;i++) {
1.125     ng       1286: 	    var partid = formname["q_"+i].value;
1.127     ng       1287: 	    if (formname["GD_SEL"+i+"_"+partid][0].selected) {
1.125     ng       1288: 		var points = formname["GD_BOX"+i+"_"+partid].value;
                   1289: 		var status = formname["solved"+i+"_"+partid].value;
1.71      ng       1290: 		if (points == "" && status != "correct_by_student") {
                   1291: 		    noscore[ptr] = i;
                   1292: 		    ptr++;
                   1293: 		}
                   1294: 	    }
                   1295: 	}
                   1296: 	if (ptr != 0) {
                   1297: 	    var sense = ptr == 1 ? ": " : "s: ";
                   1298: 	    var prolist = "";
                   1299: 	    if (ptr == 1) {
                   1300: 		prolist = noscore[0];
                   1301: 	    } else {
                   1302: 		var i = 0;
                   1303: 		while (i < ptr-1) {
                   1304: 		    prolist += noscore[i]+", ";
                   1305: 		    i++;
                   1306: 		}
                   1307: 		prolist += "and "+noscore[i];
                   1308: 	    }
                   1309: 	    var resp = confirm("You did not assign any score for the following problem"+sense+prolist+". Continue?");
                   1310: 	    if (resp == false) {
                   1311: 		return false;
                   1312: 	    }
                   1313: 	}
1.45      ng       1314: 
1.71      ng       1315: 	formname.submit();
                   1316:     }
                   1317: SUBJAVASCRIPT
                   1318: }
1.45      ng       1319: 
1.71      ng       1320: #--- javascript for essay type problem --
                   1321: sub sub_page_kw_js {
                   1322:     my $request = shift;
1.80      ng       1323:     my $iconpath = $request->dir_config('lonIconsURL');
1.118     ng       1324:     &commonJSfunctions($request);
1.350     albertel 1325: 
1.597     wenzelju 1326:     my $inner_js_msg_central= &Apache::lonhtmlcommon::scripttag(<<INNERJS);
1.350     albertel 1327:     function checkInput() {
                   1328:       opener.document.SCORE.msgsub.value = opener.checkEntities(document.msgcenter.msgsub.value);
                   1329:       var nmsg   = opener.document.SCORE.savemsgN.value;
                   1330:       var usrctr = document.msgcenter.usrctr.value;
                   1331:       var newval = opener.document.SCORE["newmsg"+usrctr];
                   1332:       newval.value = opener.checkEntities(document.msgcenter.newmsg.value);
                   1333: 
                   1334:       var msgchk = "";
                   1335:       if (document.msgcenter.subchk.checked) {
                   1336:          msgchk = "msgsub,";
                   1337:       }
                   1338:       var includemsg = 0;
                   1339:       for (var i=1; i<=nmsg; i++) {
                   1340:           var opnmsg = opener.document.SCORE["savemsg"+i];
                   1341:           var frmmsg = document.msgcenter["msg"+i];
                   1342:           opnmsg.value = opener.checkEntities(frmmsg.value);
                   1343:           var showflg = opener.document.SCORE["shownOnce"+i];
                   1344:           showflg.value = "1";
                   1345:           var chkbox = document.msgcenter["msgn"+i];
                   1346:           if (chkbox.checked) {
                   1347:              msgchk += "savemsg"+i+",";
                   1348:              includemsg = 1;
                   1349:           }
                   1350:       }
                   1351:       if (document.msgcenter.newmsgchk.checked) {
                   1352:          msgchk += "newmsg"+usrctr;
                   1353:          includemsg = 1;
                   1354:       }
                   1355:       imgformname = opener.document.SCORE["mailicon"+usrctr];
                   1356:       imgformname.src = "$iconpath/"+((includemsg) ? "mailto.gif" : "mailbkgrd.gif");
                   1357:       var includemsg = opener.document.SCORE["includemsg"+usrctr];
                   1358:       includemsg.value = msgchk;
                   1359: 
                   1360:       self.close()
                   1361: 
                   1362:     }
                   1363: INNERJS
                   1364: 
1.597     wenzelju 1365:     my $inner_js_highlight_central= &Apache::lonhtmlcommon::scripttag(<<INNERJS);
1.351     albertel 1366:     function updateChoice(flag) {
                   1367:       opener.document.SCORE.kwclr.value = opener.radioSelection(document.hlCenter.kwdclr);
                   1368:       opener.document.SCORE.kwsize.value = opener.radioSelection(document.hlCenter.kwdsize);
                   1369:       opener.document.SCORE.kwstyle.value = opener.radioSelection(document.hlCenter.kwdstyle);
                   1370:       opener.document.SCORE.refresh.value = "on";
                   1371:       if (opener.document.SCORE.keywords.value!=""){
                   1372:          opener.document.SCORE.submit();
                   1373:       }
                   1374:       self.close()
                   1375:     }
                   1376: INNERJS
                   1377: 
                   1378:     my $start_page_msg_central = 
                   1379:         &Apache::loncommon::start_page('Message Central',$inner_js_msg_central,
                   1380: 				       {'js_ready'  => 1,
                   1381: 					'only_body' => 1,
                   1382: 					'bgcolor'   =>'#FFFFFF',});
                   1383:     my $end_page_msg_central = 
                   1384: 	&Apache::loncommon::end_page({'js_ready' => 1});
                   1385: 
                   1386: 
                   1387:     my $start_page_highlight_central = 
                   1388:         &Apache::loncommon::start_page('Highlight Central',
                   1389: 				       $inner_js_highlight_central,
1.350     albertel 1390: 				       {'js_ready'  => 1,
                   1391: 					'only_body' => 1,
                   1392: 					'bgcolor'   =>'#FFFFFF',});
1.351     albertel 1393:     my $end_page_highlight_central = 
1.350     albertel 1394: 	&Apache::loncommon::end_page({'js_ready' => 1});
                   1395: 
1.219     www      1396:     my $docopen=&Apache::lonhtmlcommon::javascript_docopen();
1.236     albertel 1397:     $docopen=~s/^document\.//;
1.539     riegler  1398:     my $alertmsg = &mt('Please select a word or group of words from document and then click this link.');
1.597     wenzelju 1399:     $request->print(&Apache::lonhtmlcommon::scripttag(<<SUBJAVASCRIPT));
1.45      ng       1400: 
1.44      ng       1401: //===================== Show list of keywords ====================
1.122     ng       1402:   function keywords(formname) {
                   1403:     var nret = prompt("Keywords list, separated by a space. Add/delete to list if desired.",formname.keywords.value);
1.44      ng       1404:     if (nret==null) return;
1.122     ng       1405:     formname.keywords.value = nret;
1.44      ng       1406: 
1.122     ng       1407:     if (formname.keywords.value != "") {
1.128     ng       1408: 	formname.refresh.value = "on";
1.122     ng       1409: 	formname.submit();
1.44      ng       1410:     }
                   1411:     return;
                   1412:   }
                   1413: 
                   1414: //===================== Script to view submitted by ==================
                   1415:   function viewSubmitter(submitter) {
                   1416:     document.SCORE.refresh.value = "on";
                   1417:     document.SCORE.NCT.value = "1";
                   1418:     document.SCORE.unamedom0.value = submitter;
                   1419:     document.SCORE.submit();
                   1420:     return;
                   1421:   }
                   1422: 
                   1423: //===================== Script to add keyword(s) ==================
                   1424:   function getSel() {
                   1425:     if (document.getSelection) txt = document.getSelection();
                   1426:     else if (document.selection) txt = document.selection.createRange().text;
                   1427:     else return;
                   1428:     var cleantxt = txt.replace(new RegExp('([\\f\\n\\r\\t\\v ])+', 'g')," ");
                   1429:     if (cleantxt=="") {
1.539     riegler  1430: 	alert("$alertmsg");
1.44      ng       1431: 	return;
                   1432:     }
                   1433:     var nret = prompt("Add selection to keyword list? Edit if desired.",cleantxt);
                   1434:     if (nret==null) return;
1.127     ng       1435:     document.SCORE.keywords.value = document.SCORE.keywords.value+" "+nret;
1.44      ng       1436:     if (document.SCORE.keywords.value != "") {
1.127     ng       1437: 	document.SCORE.refresh.value = "on";
1.44      ng       1438: 	document.SCORE.submit();
                   1439:     }
                   1440:     return;
                   1441:   }
                   1442: 
                   1443: //====================== Script for composing message ==============
1.80      ng       1444:    // preload images
                   1445:    img1 = new Image();
                   1446:    img1.src = "$iconpath/mailbkgrd.gif";
                   1447:    img2 = new Image();
                   1448:    img2.src = "$iconpath/mailto.gif";
                   1449: 
1.44      ng       1450:   function msgCenter(msgform,usrctr,fullname) {
                   1451:     var Nmsg  = msgform.savemsgN.value;
                   1452:     savedMsgHeader(Nmsg,usrctr,fullname);
                   1453:     var subject = msgform.msgsub.value;
1.127     ng       1454:     var msgchk = document.SCORE["includemsg"+usrctr].value;
1.44      ng       1455:     re = /msgsub/;
                   1456:     var shwsel = "";
                   1457:     if (re.test(msgchk)) { shwsel = "checked" }
1.123     ng       1458:     subject = (document.SCORE.shownSub.value == 0 ? checkEntities(subject) : subject);
                   1459:     displaySubject(checkEntities(subject),shwsel);
1.44      ng       1460:     for (var i=1; i<=Nmsg; i++) {
1.123     ng       1461: 	var testmsg = "savemsg"+i+",";
                   1462: 	re = new RegExp(testmsg,"g");
1.44      ng       1463: 	shwsel = "";
                   1464: 	if (re.test(msgchk)) { shwsel = "checked" }
1.125     ng       1465: 	var message = document.SCORE["savemsg"+i].value;
1.126     ng       1466: 	message = (document.SCORE["shownOnce"+i].value == 0 ? checkEntities(message) : message);
1.123     ng       1467: 	displaySavedMsg(i,message,shwsel); //I do not get it. w/o checkEntities on saved messages,
                   1468: 	                                   //any &lt; is already converted to <, etc. However, only once!!
1.44      ng       1469:     }
1.125     ng       1470:     newmsg = document.SCORE["newmsg"+usrctr].value;
1.44      ng       1471:     shwsel = "";
                   1472:     re = /newmsg/;
                   1473:     if (re.test(msgchk)) { shwsel = "checked" }
                   1474:     newMsg(newmsg,shwsel);
                   1475:     msgTail(); 
                   1476:     return;
                   1477:   }
                   1478: 
1.123     ng       1479:   function checkEntities(strx) {
                   1480:     if (strx.length == 0) return strx;
                   1481:     var orgStr = ["&", "<", ">", '"']; 
                   1482:     var newStr = ["&amp;", "&lt;", "&gt;", "&quot;"];
                   1483:     var counter = 0;
                   1484:     while (counter < 4) {
                   1485: 	strx = strReplace(strx,orgStr[counter],newStr[counter]);
                   1486: 	counter++;
                   1487:     }
                   1488:     return strx;
                   1489:   }
                   1490: 
                   1491:   function strReplace(strx, orgStr, newStr) {
                   1492:     return strx.split(orgStr).join(newStr);
                   1493:   }
                   1494: 
1.44      ng       1495:   function savedMsgHeader(Nmsg,usrctr,fullname) {
1.76      ng       1496:     var height = 70*Nmsg+250;
1.44      ng       1497:     var scrollbar = "no";
                   1498:     if (height > 600) {
                   1499: 	height = 600;
                   1500: 	scrollbar = "yes";
                   1501:     }
1.118     ng       1502:     var xpos = (screen.width-600)/2;
                   1503:     xpos = (xpos < 0) ? '0' : xpos;
                   1504:     var ypos = (screen.height-height)/2-30;
                   1505:     ypos = (ypos < 0) ? '0' : ypos;
                   1506: 
1.206     albertel 1507:     pWin = window.open('', 'MessageCenter', 'resizable=yes,toolbar=no,location=no,scrollbars='+scrollbar+',screenx='+xpos+',screeny='+ypos+',width=600,height='+height);
1.76      ng       1508:     pWin.focus();
                   1509:     pDoc = pWin.document;
1.219     www      1510:     pDoc.$docopen;
1.351     albertel 1511:     pDoc.write('$start_page_msg_central');
1.76      ng       1512: 
                   1513:     pDoc.write("<form action=\\"inactive\\" name=\\"msgcenter\\">");
                   1514:     pDoc.write("<input value=\\""+usrctr+"\\" name=\\"usrctr\\" type=\\"hidden\\">");
1.465     albertel 1515:     pDoc.write("<h3><span class=\\"LC_info\\">&nbsp;Compose Message for \"+fullname+\"<\\/span><\\/h3><br /><br />");
1.76      ng       1516: 
1.564     bisitz   1517:     pDoc.write('<table border="0" width="100%"><tr><td bgcolor="#777777">');
                   1518:     pDoc.write('<table border="0" width="100%"><tr bgcolor="#DDFFFF">');
1.465     albertel 1519:     pDoc.write("<td><b>Type<\\/b><\\/td><td><b>Include<\\/b><\\/td><td><b>Message<\\/td><\\/tr>");
1.44      ng       1520: }
                   1521:     function displaySubject(msg,shwsel) {
1.76      ng       1522:     pDoc = pWin.document;
                   1523:     pDoc.write("<tr bgcolor=\\"#ffffdd\\">");
1.465     albertel 1524:     pDoc.write("<td>Subject<\\/td>");
                   1525:     pDoc.write("<td align=\\"center\\"><input name=\\"subchk\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
                   1526:     pDoc.write("<td><input name=\\"msgsub\\" type=\\"text\\" value=\\""+msg+"\\"size=\\"60\\" maxlength=\\"80\\"><\\/td><\\/tr>");
1.44      ng       1527: }
                   1528: 
1.72      ng       1529:   function displaySavedMsg(ctr,msg,shwsel) {
1.76      ng       1530:     pDoc = pWin.document;
                   1531:     pDoc.write("<tr bgcolor=\\"#ffffdd\\">");
1.465     albertel 1532:     pDoc.write("<td align=\\"center\\">"+ctr+"<\\/td>");
                   1533:     pDoc.write("<td align=\\"center\\"><input name=\\"msgn"+ctr+"\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
                   1534:     pDoc.write("<td><textarea name=\\"msg"+ctr+"\\" cols=\\"60\\" rows=\\"3\\">"+msg+"<\\/textarea><\\/td><\\/tr>");
1.44      ng       1535: }
                   1536: 
                   1537:   function newMsg(newmsg,shwsel) {
1.76      ng       1538:     pDoc = pWin.document;
                   1539:     pDoc.write("<tr bgcolor=\\"#ffffdd\\">");
1.465     albertel 1540:     pDoc.write("<td align=\\"center\\">New<\\/td>");
                   1541:     pDoc.write("<td align=\\"center\\"><input name=\\"newmsgchk\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
                   1542:     pDoc.write("<td><textarea name=\\"newmsg\\" cols=\\"60\\" rows=\\"3\\" onchange=\\"javascript:this.form.newmsgchk.checked=true\\" >"+newmsg+"<\\/textarea><\\/td><\\/tr>");
1.44      ng       1543: }
                   1544: 
                   1545:   function msgTail() {
1.76      ng       1546:     pDoc = pWin.document;
1.465     albertel 1547:     pDoc.write("<\\/table>");
                   1548:     pDoc.write("<\\/td><\\/tr><\\/table>&nbsp;");
1.589     bisitz   1549:     pDoc.write("<input type=\\"button\\" value=\\"Save\\" onclick=\\"javascript:checkInput()\\">&nbsp;&nbsp;");
                   1550:     pDoc.write("<input type=\\"button\\" value=\\"Cancel\\" onclick=\\"self.close()\\"><br /><br />");
1.465     albertel 1551:     pDoc.write("<\\/form>");
1.351     albertel 1552:     pDoc.write('$end_page_msg_central');
1.128     ng       1553:     pDoc.close();
1.44      ng       1554: }
                   1555: 
                   1556: //====================== Script for keyword highlight options ==============
                   1557:   function kwhighlight() {
                   1558:     var kwclr    = document.SCORE.kwclr.value;
                   1559:     var kwsize   = document.SCORE.kwsize.value;
                   1560:     var kwstyle  = document.SCORE.kwstyle.value;
                   1561:     var redsel = "";
                   1562:     var grnsel = "";
                   1563:     var blusel = "";
                   1564:     if (kwclr=="red")   {var redsel="checked"};
                   1565:     if (kwclr=="green") {var grnsel="checked"};
                   1566:     if (kwclr=="blue")  {var blusel="checked"};
                   1567:     var sznsel = "";
                   1568:     var sz1sel = "";
                   1569:     var sz2sel = "";
                   1570:     if (kwsize=="0")  {var sznsel="checked"};
                   1571:     if (kwsize=="+1") {var sz1sel="checked"};
                   1572:     if (kwsize=="+2") {var sz2sel="checked"};
                   1573:     var synsel = "";
                   1574:     var syisel = "";
                   1575:     var sybsel = "";
                   1576:     if (kwstyle=="")    {var synsel="checked"};
                   1577:     if (kwstyle=="<i>") {var syisel="checked"};
                   1578:     if (kwstyle=="<b>") {var sybsel="checked"};
                   1579:     highlightCentral();
                   1580:     highlightbody('red','red',redsel,'0','normal',sznsel,'','normal',synsel);
                   1581:     highlightbody('green','green',grnsel,'+1','+1',sz1sel,'<i>','italic',syisel);
                   1582:     highlightbody('blue','blue',blusel,'+2','+2',sz2sel,'<b>','bold',sybsel);
                   1583:     highlightend();
                   1584:     return;
                   1585:   }
                   1586: 
                   1587:   function highlightCentral() {
1.76      ng       1588: //    if (window.hwdWin) window.hwdWin.close();
1.118     ng       1589:     var xpos = (screen.width-400)/2;
                   1590:     xpos = (xpos < 0) ? '0' : xpos;
                   1591:     var ypos = (screen.height-330)/2-30;
                   1592:     ypos = (ypos < 0) ? '0' : ypos;
                   1593: 
1.206     albertel 1594:     hwdWin = window.open('', 'KeywordHighlightCentral', 'resizeable=yes,toolbar=no,location=no,scrollbars=no,width=400,height=300,screenx='+xpos+',screeny='+ypos);
1.76      ng       1595:     hwdWin.focus();
                   1596:     var hDoc = hwdWin.document;
1.219     www      1597:     hDoc.$docopen;
1.351     albertel 1598:     hDoc.write('$start_page_highlight_central');
1.76      ng       1599:     hDoc.write("<form action=\\"inactive\\" name=\\"hlCenter\\">");
1.465     albertel 1600:     hDoc.write("<h3><span class=\\"LC_info\\">&nbsp;Keyword Highlight Options<\\/span><\\/h3><br /><br />");
1.76      ng       1601: 
1.564     bisitz   1602:     hDoc.write('<table border="0" width="100%"><tr><td bgcolor="#777777">');
                   1603:     hDoc.write('<table border="0" width="100%"><tr bgcolor="#DDFFFF">');
1.465     albertel 1604:     hDoc.write("<td><b>Text Color<\\/b><\\/td><td><b>Font Size<\\/b><\\/td><td><b>Font Style<\\/td><\\/tr>");
1.44      ng       1605:   }
                   1606: 
                   1607:   function highlightbody(clrval,clrtxt,clrsel,szval,sztxt,szsel,syval,sytxt,sysel) { 
1.76      ng       1608:     var hDoc = hwdWin.document;
                   1609:     hDoc.write("<tr bgcolor=\\"#ffffdd\\">");
                   1610:     hDoc.write("<td align=\\"left\\">");
1.465     albertel 1611:     hDoc.write("<input name=\\"kwdclr\\" type=\\"radio\\" value=\\""+clrval+"\\" "+clrsel+">&nbsp;"+clrtxt+"<\\/td>");
1.76      ng       1612:     hDoc.write("<td align=\\"left\\">");
1.465     albertel 1613:     hDoc.write("<input name=\\"kwdsize\\" type=\\"radio\\" value=\\""+szval+"\\" "+szsel+">&nbsp;"+sztxt+"<\\/td>");
1.76      ng       1614:     hDoc.write("<td align=\\"left\\">");
1.465     albertel 1615:     hDoc.write("<input name=\\"kwdstyle\\" type=\\"radio\\" value=\\""+syval+"\\" "+sysel+">&nbsp;"+sytxt+"<\\/td>");
                   1616:     hDoc.write("<\\/tr>");
1.44      ng       1617:   }
                   1618: 
                   1619:   function highlightend() { 
1.76      ng       1620:     var hDoc = hwdWin.document;
1.465     albertel 1621:     hDoc.write("<\\/table>");
                   1622:     hDoc.write("<\\/td><\\/tr><\\/table>&nbsp;");
1.589     bisitz   1623:     hDoc.write("<input type=\\"button\\" value=\\"Save\\" onclick=\\"javascript:updateChoice(1)\\">&nbsp;&nbsp;");
                   1624:     hDoc.write("<input type=\\"button\\" value=\\"Cancel\\" onclick=\\"self.close()\\"><br /><br />");
1.465     albertel 1625:     hDoc.write("<\\/form>");
1.351     albertel 1626:     hDoc.write('$end_page_highlight_central');
1.128     ng       1627:     hDoc.close();
1.44      ng       1628:   }
                   1629: 
                   1630: SUBJAVASCRIPT
                   1631: }
                   1632: 
1.349     albertel 1633: sub get_increment {
1.348     bowersj2 1634:     my $increment = $env{'form.increment'};
                   1635:     if ($increment != 1 && $increment != .5 && $increment != .25 &&
                   1636:         $increment != .1) {
                   1637:         $increment = 1;
                   1638:     }
                   1639:     return $increment;
                   1640: }
                   1641: 
1.585     bisitz   1642: sub gradeBox_start {
                   1643:     return (
                   1644:         &Apache::loncommon::start_data_table()
                   1645:        .&Apache::loncommon::start_data_table_header_row()
                   1646:        .'<th>'.&mt('Part').'</th>'
                   1647:        .'<th>'.&mt('Points').'</th>'
                   1648:        .'<th>&nbsp;</th>'
                   1649:        .'<th>'.&mt('Assign Grade').'</th>'
                   1650:        .'<th>'.&mt('Weight').'</th>'
                   1651:        .'<th>'.&mt('Grade Status').'</th>'
                   1652:        .&Apache::loncommon::end_data_table_header_row()
                   1653:     );
                   1654: }
                   1655: 
                   1656: sub gradeBox_end {
                   1657:     return (
                   1658:         &Apache::loncommon::end_data_table()
                   1659:     );
                   1660: }
1.71      ng       1661: #--- displays the grading box, used in essay type problem and grading by page/sequence
                   1662: sub gradeBox {
1.322     albertel 1663:     my ($request,$symb,$uname,$udom,$counter,$partid,$record) = @_;
1.381     albertel 1664:     my $checkIcon = '<img alt="'.&mt('Check Mark').
1.485     albertel 1665: 	'" src="'.&Apache::loncommon::lonhttpdurl($request->dir_config('lonIconsURL').'/check.gif').'" height="16" border="0" />';
1.71      ng       1666:     my $wgt    = &Apache::lonnet::EXT('resource.'.$partid.'.weight',$symb,$udom,$uname);
1.466     albertel 1667:     my $wgtmsg = ($wgt > 0) ? &mt('(problem weight)') 
                   1668:                            : '<span class="LC_info">'.&mt('problem weight assigned by computer').'</span>';
1.71      ng       1669:     $wgt       = ($wgt > 0 ? $wgt : '1');
                   1670:     my $score  = ($$record{'resource.'.$partid.'.awarded'} eq '' ?
1.320     albertel 1671: 		  '' : &compute_points($$record{'resource.'.$partid.'.awarded'},$wgt));
1.71      ng       1672:     my $result='<input type="hidden" name="WGT'.$counter.'_'.$partid.'" value="'.$wgt.'" />'."\n";
1.466     albertel 1673:     my $display_part= &get_display_part($partid,$symb);
1.270     albertel 1674:     my %last_resets = &get_last_resets($symb,$env{'request.course.id'},
                   1675: 				       [$partid]);
                   1676:     my $aggtries = $$record{'resource.'.$partid.'.tries'};
1.269     raeburn  1677:     if ($last_resets{$partid}) {
                   1678:         $aggtries = &get_num_tries($record,$last_resets{$partid},$partid);
                   1679:     }
1.585     bisitz   1680:     $result.=&Apache::loncommon::start_data_table_row();
1.71      ng       1681:     my $ctr = 0;
1.348     bowersj2 1682:     my $thisweight = 0;
1.349     albertel 1683:     my $increment = &get_increment();
1.485     albertel 1684: 
                   1685:     my $radio.='<table border="0"><tr>'."\n";  # display radio buttons in a nice table 10 across
1.348     bowersj2 1686:     while ($thisweight<=$wgt) {
1.532     bisitz   1687: 	$radio.= '<td><span class="LC_nobreak"><label><input type="radio" name="RADVAL'.$counter.'_'.$partid.'" '.
1.589     bisitz   1688:         'onclick="javascript:writeBox(this.form,\''.$counter.'_'.$partid.'\','.
1.348     bowersj2 1689: 	    $thisweight.')" value="'.$thisweight.'" '.
1.401     albertel 1690: 	    ($score eq $thisweight ? 'checked="checked"':'').' /> '.$thisweight."</label></span></td>\n";
1.485     albertel 1691: 	$radio.=(($ctr+1)%10 == 0 ? '</tr><tr>' : '');
1.348     bowersj2 1692:         $thisweight += $increment;
1.71      ng       1693: 	$ctr++;
                   1694:     }
1.485     albertel 1695:     $radio.='</tr></table>';
                   1696: 
                   1697:     my $line.='<input type="text" name="GD_BOX'.$counter.'_'.$partid.'"'.
1.71      ng       1698: 	($score ne ''? ' value = "'.$score.'"':'').' size="4" '.
1.589     bisitz   1699: 	'onchange="javascript:updateRadio(this.form,\''.$counter.'_'.$partid.'\','.
1.71      ng       1700: 	$wgt.')" /></td>'."\n";
1.485     albertel 1701:     $line.='<td>/'.$wgt.' '.$wgtmsg.
1.71      ng       1702: 	($$record{'resource.'.$partid.'.solved'} eq 'correct_by_student' ? '&nbsp;'.$checkIcon : '').
1.585     bisitz   1703: 	' </td>'."\n";
                   1704:     $line.='<td><select name="GD_SEL'.$counter.'_'.$partid.'" '.
1.589     bisitz   1705: 	'onchange="javascript:clearRadBox(this.form,\''.$counter.'_'.$partid.'\')" >'."\n";
1.71      ng       1706:     if ($$record{'resource.'.$partid.'.solved'} eq 'excused') {
1.485     albertel 1707: 	$line.='<option></option>'.
                   1708: 	    '<option value="excused" selected="selected">'.&mt('excused').'</option>';
1.71      ng       1709:     } else {
1.485     albertel 1710: 	$line.='<option selected="selected"></option>'.
                   1711: 	    '<option value="excused" >'.&mt('excused').'</option>';
1.71      ng       1712:     }
1.485     albertel 1713:     $line.='<option value="reset status">'.&mt('reset status').'</option></select>'."\n";
                   1714: 
                   1715: 
                   1716:     $result .= 
1.585     bisitz   1717: 	    '<td>'.$display_part.'</td><td>'.$radio.'</td><td>'.&mt('or').'</td><td>'.$line.'</td>';
                   1718:     $result.=&Apache::loncommon::end_data_table_row();
1.71      ng       1719:     $result.='<input type="hidden" name="stores'.$counter.'_'.$partid.'" value="" />'."\n".
                   1720: 	'<input type="hidden" name="oldpts'.$counter.'_'.$partid.'" value="'.$score.'" />'."\n".
                   1721: 	'<input type="hidden" name="solved'.$counter.'_'.$partid.'" value="'.
1.269     raeburn  1722: 	$$record{'resource.'.$partid.'.solved'}.'" />'."\n".
                   1723:         '<input type="hidden" name="totaltries'.$counter.'_'.$partid.'" value="'.
                   1724:         $$record{'resource.'.$partid.'.tries'}.'" />'."\n".
                   1725:         '<input type="hidden" name="aggtries'.$counter.'_'.$partid.'" value="'.
                   1726:         $aggtries.'" />'."\n";
1.582     raeburn  1727:     my $res_error;
                   1728:     $result.=&handback_box($symb,$uname,$udom,$counter,$partid,$record,\$res_error);
                   1729:     if ($res_error) {
                   1730:         return &navmap_errormsg();
                   1731:     }
1.318     banghart 1732:     return $result;
                   1733: }
1.322     albertel 1734: 
                   1735: sub handback_box {
1.623     www      1736:     my ($symb,$uname,$udom,$counter,$partid,$record,$res_error_pointer) = @_;
                   1737:     my ($partlist,$handgrade,$responseType) = &response_type($symb,$res_error_pointer);
1.323     banghart 1738:     my (@respids);
1.375     albertel 1739:      my @part_response_id = &flatten_responseType($responseType);
                   1740:     foreach my $part_response_id (@part_response_id) {
                   1741:     	my ($part,$resp) = @{ $part_response_id };
1.323     banghart 1742:         if ($part eq $partid) {
1.375     albertel 1743:             push(@respids,$resp);
1.323     banghart 1744:         }
                   1745:     }
1.318     banghart 1746:     my $result;
1.323     banghart 1747:     foreach my $respid (@respids) {
1.322     albertel 1748: 	my $prefix = $counter.'_'.$partid.'_'.$respid.'_';
                   1749: 	my $files=&get_submitted_files($udom,$uname,$partid,$respid,$record);
                   1750: 	next if (!@$files);
                   1751: 	my $file_counter = 1;
1.313     banghart 1752: 	foreach my $file (@$files) {
1.368     banghart 1753: 	    if ($file =~ /\/portfolio\//) {
                   1754:     	        my ($file_path, $file_disp) = ($file =~ m|(.+/)(.+)$|);
                   1755:     	        my ($name,$version,$ext) = &file_name_version_ext($file_disp);
                   1756:     	        $file_disp = "$name.$ext";
                   1757:     	        $file = $file_path.$file_disp;
                   1758:     	        $result.=&mt('Return commented version of [_1] to student.',
                   1759:     			 '<span class="LC_filename">'.$file_disp.'</span>');
                   1760:     	        $result.='<input type="file"   name="'.$prefix.'returndoc'.$file_counter.'" />'."\n";
                   1761:     	        $result.='<input type="hidden" name="'.$prefix.'origdoc'.$file_counter.'" value="'.$file.'" /><br />';
1.485     albertel 1762:     	        $result.='('.&mt('File will be uploaded when you click on Save &amp; Next below.').')<br />';
1.368     banghart 1763:     	        $file_counter++;
                   1764: 	    }
1.322     albertel 1765: 	}
1.313     banghart 1766:     }
1.318     banghart 1767:     return $result;    
1.71      ng       1768: }
1.44      ng       1769: 
1.58      albertel 1770: sub show_problem {
1.382     albertel 1771:     my ($request,$symb,$uname,$udom,$removeform,$viewon,$mode,$form) = @_;
1.144     albertel 1772:     my $rendered;
1.382     albertel 1773:     my %form = ((ref($form) eq 'HASH')? %{$form} : ());
1.329     albertel 1774:     &Apache::lonxml::remember_problem_counter();
1.144     albertel 1775:     if ($mode eq 'both' or $mode eq 'text') {
                   1776: 	$rendered=&Apache::loncommon::get_student_view($symb,$uname,$udom,
1.382     albertel 1777: 						       $env{'request.course.id'},
                   1778: 						       undef,\%form);
1.144     albertel 1779:     }
1.58      albertel 1780:     if ($removeform) {
                   1781: 	$rendered=~s|<form(.*?)>||g;
                   1782: 	$rendered=~s|</form>||g;
1.374     albertel 1783: 	$rendered=~s|(<input[^>]*name\s*=\s*"?)(\w+)("?)|$1would_have_been_$2$3|g;
1.58      albertel 1784:     }
1.144     albertel 1785:     my $companswer;
                   1786:     if ($mode eq 'both' or $mode eq 'answer') {
1.329     albertel 1787: 	&Apache::lonxml::restore_problem_counter();
1.382     albertel 1788: 	$companswer=
                   1789: 	    &Apache::loncommon::get_student_answers($symb,$uname,$udom,
                   1790: 						    $env{'request.course.id'},
                   1791: 						    %form);
1.144     albertel 1792:     }
1.58      albertel 1793:     if ($removeform) {
                   1794: 	$companswer=~s|<form(.*?)>||g;
                   1795: 	$companswer=~s|</form>||g;
1.144     albertel 1796: 	$companswer=~s|name="submit"|name="would_have_been_submit"|g;
1.58      albertel 1797:     }
1.468     albertel 1798:     $rendered=
1.588     bisitz   1799:         '<div class="LC_Box">'
                   1800:        .'<h3 class="LC_hcell">'.&mt('View of the problem').'</h3>'
                   1801:        .$rendered
                   1802:        .'</div>';
1.468     albertel 1803:     $companswer=
1.588     bisitz   1804:         '<div class="LC_Box">'
                   1805:        .'<h3 class="LC_hcell">'.&mt('Correct answer').'</h3>'
                   1806:        .$companswer
                   1807:        .'</div>';
1.468     albertel 1808:     my $result;
1.144     albertel 1809:     if ($mode eq 'both') {
1.588     bisitz   1810:         $result=$rendered.$companswer;
1.144     albertel 1811:     } elsif ($mode eq 'text') {
1.588     bisitz   1812:         $result=$rendered;
1.144     albertel 1813:     } elsif ($mode eq 'answer') {
1.588     bisitz   1814:         $result=$companswer;
1.144     albertel 1815:     }
1.71      ng       1816:     return $result;
1.58      albertel 1817: }
1.397     albertel 1818: 
1.396     banghart 1819: sub files_exist {
                   1820:     my ($r, $symb) = @_;
                   1821:     my @students = &Apache::loncommon::get_env_multiple('form.stuinfo');
1.397     albertel 1822: 
1.396     banghart 1823:     foreach my $student (@students) {
                   1824:         my ($uname,$udom,$fullname) = split(/:/,$student);
1.397     albertel 1825:         my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},
                   1826: 					      $udom,$uname);
1.396     banghart 1827:         my ($string,$timestamp)= &get_last_submission(\%record);
1.397     albertel 1828:         foreach my $submission (@$string) {
                   1829:             my ($partid,$respid) =
                   1830: 		($submission =~ /^resource\.([^\.]*)\.([^\.]*)\.submission/);
                   1831:             my $files=&get_submitted_files($udom,$uname,$partid,$respid,
                   1832: 					   \%record);
                   1833:             return 1 if (@$files);
1.396     banghart 1834:         }
                   1835:     }
1.397     albertel 1836:     return 0;
1.396     banghart 1837: }
1.397     albertel 1838: 
1.394     banghart 1839: sub download_all_link {
                   1840:     my ($r,$symb) = @_;
1.621     www      1841:     unless (&files_exist($r, $symb)) {
                   1842:        $r->print(&mt('There are currently no submitted documents.'));
                   1843:        return;
                   1844:     }
                   1845: 
1.395     albertel 1846:     my $all_students = 
                   1847: 	join("\n", &Apache::loncommon::get_env_multiple('form.stuinfo'));
                   1848: 
                   1849:     my $parts =
                   1850: 	join("\n",&Apache::loncommon::get_env_multiple('form.vPart'));
                   1851: 
1.394     banghart 1852:     my $identifier = &Apache::loncommon::get_cgi_id();
1.514     raeburn  1853:     &Apache::lonnet::appenv({'cgi.'.$identifier.'.students' => $all_students,
                   1854:                              'cgi.'.$identifier.'.symb' => $symb,
                   1855:                              'cgi.'.$identifier.'.parts' => $parts,});
1.395     albertel 1856:     $r->print('<a href="/cgi-bin/multidownload.pl?'.$identifier.'">'.
                   1857: 	      &mt('Download All Submitted Documents').'</a>');
1.621     www      1858:     return;
                   1859: }
                   1860: 
                   1861: sub submit_download_link {
                   1862:     my ($request,$symb) = @_;
                   1863:     if (!$symb) { return ''; }
                   1864: #FIXME: Figure out which type of problem this is and provide appropriate download
                   1865:     &download_all_link($request,$symb);
1.394     banghart 1866: }
1.395     albertel 1867: 
1.432     banghart 1868: sub build_section_inputs {
                   1869:     my $section_inputs;
                   1870:     if ($env{'form.section'} eq '') {
                   1871:         $section_inputs .= '<input type="hidden" name="section" value="all" />'."\n";
                   1872:     } else {
                   1873:         my @sections = &Apache::loncommon::get_env_multiple('form.section');
1.434     albertel 1874:         foreach my $section (@sections) {
1.432     banghart 1875:             $section_inputs .= '<input type="hidden" name="section" value="'.$section.'" />'."\n";
                   1876:         }
                   1877:     }
                   1878:     return $section_inputs;
                   1879: }
                   1880: 
1.44      ng       1881: # --------------------------- show submissions of a student, option to grade 
                   1882: sub submission {
1.608     www      1883:     my ($request,$counter,$total,$symb) = @_;
1.257     albertel 1884:     my ($uname,$udom)     = ($env{'form.student'},$env{'form.userdom'});
                   1885:     $udom = ($udom eq '' ? $env{'user.domain'} : $udom); #has form.userdom changed for a student?
                   1886:     my $usec = &Apache::lonnet::getsection($udom,$uname,$env{'request.course.id'});
                   1887:     $env{'form.fullname'} = &Apache::loncommon::plainname($uname,$udom,'lastname') if $env{'form.fullname'} eq '';
1.608     www      1888: 
1.605     www      1889:     my $probtitle=&Apache::lonnet::gettitle($symb); 
1.324     albertel 1890:     if ($symb eq '') { $request->print("Unable to handle ambiguous references:."); return ''; }
1.104     albertel 1891: 
                   1892:     if (!&canview($usec)) {
1.398     albertel 1893: 	$request->print('<span class="LC_warning">Unable to view requested student.('.
                   1894: 			$uname.':'.$udom.' in section '.$usec.' in course id '.
                   1895: 			$env{'request.course.id'}.')</span>');
1.104     albertel 1896: 	return;
                   1897:     }
                   1898: 
1.257     albertel 1899:     if (!$env{'form.lastSub'}) { $env{'form.lastSub'} = 'datesub'; }
                   1900:     if (!$env{'form.vProb'}) { $env{'form.vProb'} = 'yes'; }
                   1901:     if (!$env{'form.vAns'}) { $env{'form.vAns'} = 'yes'; }
                   1902:     my $last = ($env{'form.lastSub'} eq 'last' ? 'last' : '');
1.381     albertel 1903:     my $checkIcon = '<img alt="'.&mt('Check Mark').
                   1904: 	'" src="'.$request->dir_config('lonIconsURL').
1.122     ng       1905: 	'/check.gif" height="16" border="0" />';
1.41      ng       1906: 
1.426     albertel 1907:     my %old_essays;
1.41      ng       1908:     # header info
                   1909:     if ($counter == 0) {
                   1910: 	&sub_page_js($request);
1.621     www      1911: 	&sub_page_kw_js($request);
1.605     www      1912: 	$request->print('<h3>&nbsp;<span class="LC_info">'.&mt('Submission Record').'</span></h3>');
1.118     ng       1913: 
1.44      ng       1914: 	# option to display problem, only once else it cause problems 
                   1915:         # with the form later since the problem has a form.
1.257     albertel 1916: 	if ($env{'form.vProb'} eq 'yes' or $env{'form.vAns'} eq 'yes') {
1.144     albertel 1917: 	    my $mode;
1.257     albertel 1918: 	    if ($env{'form.vProb'} eq 'yes' && $env{'form.vAns'} eq 'yes') {
1.144     albertel 1919: 		$mode='both';
1.257     albertel 1920: 	    } elsif ($env{'form.vProb'} eq 'yes') {
1.144     albertel 1921: 		$mode='text';
1.257     albertel 1922: 	    } elsif ($env{'form.vAns'} eq 'yes') {
1.144     albertel 1923: 		$mode='answer';
                   1924: 	    }
1.329     albertel 1925: 	    &Apache::lonxml::clear_problem_counter();
1.144     albertel 1926: 	    $request->print(&show_problem($request,$symb,$uname,$udom,0,1,$mode));
1.41      ng       1927: 	}
1.441     www      1928: 
1.44      ng       1929: 	# kwclr is the only variable that is guaranteed to be non blank 
                   1930:         # if this subroutine has been called once.
1.41      ng       1931: 	my %keyhash = ();
1.624     www      1932: #	if ($env{'form.kwclr'} eq '' && $env{'form.handgrade'} eq 'yes') {
                   1933:         if (1) {
1.41      ng       1934: 	    %keyhash = &Apache::lonnet::dump('nohist_handgrade',
1.257     albertel 1935: 					     $env{'course.'.$env{'request.course.id'}.'.domain'},
                   1936: 					     $env{'course.'.$env{'request.course.id'}.'.num'});
1.41      ng       1937: 
1.257     albertel 1938: 	    my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
                   1939: 	    $env{'form.keywords'} = $keyhash{$symb.'_keywords'} ne '' ? $keyhash{$symb.'_keywords'} : '';
                   1940: 	    $env{'form.kwclr'}    = $keyhash{$loginuser.'_kwclr'} ne '' ? $keyhash{$loginuser.'_kwclr'} : 'red';
                   1941: 	    $env{'form.kwsize'}   = $keyhash{$loginuser.'_kwsize'} ne '' ? $keyhash{$loginuser.'_kwsize'} : '0';
                   1942: 	    $env{'form.kwstyle'}  = $keyhash{$loginuser.'_kwstyle'} ne '' ? $keyhash{$loginuser.'_kwstyle'} : '';
                   1943: 	    $env{'form.msgsub'}   = $keyhash{$symb.'_subject'} ne '' ? 
1.605     www      1944: 		$keyhash{$symb.'_subject'} : $probtitle;
1.257     albertel 1945: 	    $env{'form.savemsgN'} = $keyhash{$symb.'_savemsgN'} ne '' ? $keyhash{$symb.'_savemsgN'} : '0';
1.41      ng       1946: 	}
1.257     albertel 1947: 	my $overRideScore = $env{'form.overRideScore'} eq '' ? 'no' : $env{'form.overRideScore'};
1.442     banghart 1948: 	my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
1.303     banghart 1949: 	$request->print('<form action="/adm/grades" method="post" name="SCORE" enctype="multipart/form-data">'."\n".
1.41      ng       1950: 			'<input type="hidden" name="command"    value="handgrade" />'."\n".
1.442     banghart 1951: 			'<input type="hidden" name="Status"     value="'.$stu_status.'" />'."\n".
1.120     ng       1952: 			'<input type="hidden" name="overRideScore" value="'.$overRideScore.'" />'."\n".
1.41      ng       1953: 			'<input type="hidden" name="refresh"    value="off" />'."\n".
1.120     ng       1954: 			'<input type="hidden" name="studentNo"  value="" />'."\n".
                   1955: 			'<input type="hidden" name="gradeOpt"   value="" />'."\n".
1.418     albertel 1956: 			'<input type="hidden" name="symb"       value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.257     albertel 1957: 			'<input type="hidden" name="vProb"      value="'.$env{'form.vProb'}.'" />'."\n".
                   1958: 			'<input type="hidden" name="vAns"       value="'.$env{'form.vAns'}.'" />'."\n".
                   1959: 			'<input type="hidden" name="lastSub"    value="'.$env{'form.lastSub'}.'" />'."\n".
1.432     banghart 1960: 			&build_section_inputs().
1.326     albertel 1961: 			'<input type="hidden" name="submitonly" value="'.$env{'form.submitonly'}.'" />'."\n".
1.41      ng       1962: 			'<input type="hidden" name="NCT"'.
1.257     albertel 1963: 			' value="'.($env{'form.NTSTU'} ne '' ? $env{'form.NTSTU'} : $total+1).'" />'."\n");
1.624     www      1964: #	if ($env{'form.handgrade'} eq 'yes') {
                   1965:         if (1) {
1.257     albertel 1966: 	    $request->print('<input type="hidden" name="keywords" value="'.$env{'form.keywords'}.'" />'."\n".
                   1967: 			    '<input type="hidden" name="kwclr"    value="'.$env{'form.kwclr'}.'" />'."\n".
                   1968: 			    '<input type="hidden" name="kwsize"   value="'.$env{'form.kwsize'}.'" />'."\n".
                   1969: 			    '<input type="hidden" name="kwstyle"  value="'.$env{'form.kwstyle'}.'" />'."\n".
                   1970: 			    '<input type="hidden" name="msgsub"   value="'.$env{'form.msgsub'}.'" />'."\n".
1.123     ng       1971: 			    '<input type="hidden" name="shownSub" value="0" />'."\n".
1.257     albertel 1972: 			    '<input type="hidden" name="savemsgN" value="'.$env{'form.savemsgN'}.'" />'."\n");
1.154     albertel 1973: 	    foreach my $partid (&Apache::loncommon::get_env_multiple('form.vPart')) {
                   1974: 		$request->print('<input type="hidden" name="vPart" value="'.$partid.'" />'."\n");
                   1975: 	    }
1.123     ng       1976: 	}
1.41      ng       1977: 	
                   1978: 	my ($cts,$prnmsg) = (1,'');
1.257     albertel 1979: 	while ($cts <= $env{'form.savemsgN'}) {
1.41      ng       1980: 	    $prnmsg.='<input type="hidden" name="savemsg'.$cts.'" value="'.
1.123     ng       1981: 		(!exists($keyhash{$symb.'_savemsg'.$cts}) ? 
1.257     albertel 1982: 		 &Apache::lonfeedback::clear_out_html($env{'form.savemsg'.$cts}) :
1.80      ng       1983: 		 &Apache::lonfeedback::clear_out_html($keyhash{$symb.'_savemsg'.$cts})).
1.123     ng       1984: 		'" />'."\n".
                   1985: 		'<input type="hidden" name="shownOnce'.$cts.'" value="0" />'."\n";
1.41      ng       1986: 	    $cts++;
                   1987: 	}
                   1988: 	$request->print($prnmsg);
1.32      ng       1989: 
1.624     www      1990: #	if ($env{'form.handgrade'} eq 'yes') {
                   1991:         if (1) {
1.88      www      1992: #
                   1993: # Print out the keyword options line
                   1994: #
1.41      ng       1995: 	    $request->print(<<KEYWORDS);
1.38      ng       1996: &nbsp;<b>Keyword Options:</b>&nbsp;
1.417     albertel 1997: <a href="javascript:keywords(document.SCORE);" target="_self">List</a>&nbsp; &nbsp;
1.589     bisitz   1998: <a href="#" onmousedown="javascript:getSel(); return false"
1.38      ng       1999:  CLASS="page">Paste Selection to List</a>&nbsp; &nbsp;
1.417     albertel 2000: <a href="javascript:kwhighlight();" target="_self">Highlight Attribute</a><br /><br />
1.38      ng       2001: KEYWORDS
1.88      www      2002: #
                   2003: # Load the other essays for similarity check
                   2004: #
1.324     albertel 2005:             my (undef,undef,$essayurl) = &Apache::lonnet::decode_symb($symb);
1.384     albertel 2006: 	    my ($adom,$aname,$apath)=($essayurl=~/^($LONCAPA::domain_re)\/($LONCAPA::username_re)\/(.*)$/);
1.359     www      2007: 	    $apath=&escape($apath);
1.88      www      2008: 	    $apath=~s/\W/\_/gs;
1.426     albertel 2009: 	    %old_essays=&Apache::lonnet::dump('nohist_essay_'.$apath,$adom,$aname);
1.41      ng       2010:         }
                   2011:     }
1.44      ng       2012: 
1.441     www      2013: # This is where output for one specific student would start
1.592     bisitz   2014:     my $add_class = ($counter%2) ? ' LC_grade_show_user_odd_row' : '';
                   2015:     $request->print(
                   2016:         "\n\n"
                   2017:        .'<div class="LC_grade_show_user'.$add_class.'">'
                   2018:        .'<h2>'.&nameUserString(undef,$env{'form.fullname'},$uname,$udom).'</h2>'
                   2019:        ."\n"
                   2020:     );
1.441     www      2021: 
1.592     bisitz   2022:     # Show additional functions if allowed
                   2023:     if ($perm{'vgr'}) {
                   2024:         $request->print(
                   2025:             &Apache::loncommon::track_student_link(
                   2026:                 &mt('View recent activity'),
                   2027:                 $uname,$udom,'check')
                   2028:            .' '
                   2029:         );
                   2030:     }
                   2031:     if ($perm{'opa'}) {
                   2032:         $request->print(
                   2033:             &Apache::loncommon::pprmlink(
                   2034:                 &mt('Set/Change parameters'),
                   2035:                 $uname,$udom,$symb,'check'));
                   2036:     }
                   2037: 
                   2038:     # Show Problem
1.257     albertel 2039:     if ($env{'form.vProb'} eq 'all' or $env{'form.vAns'} eq 'all') {
1.144     albertel 2040: 	my $mode;
1.257     albertel 2041: 	if ($env{'form.vProb'} eq 'all' && $env{'form.vAns'} eq 'all') {
1.144     albertel 2042: 	    $mode='both';
1.257     albertel 2043: 	} elsif ($env{'form.vProb'} eq 'all' ) {
1.144     albertel 2044: 	    $mode='text';
1.257     albertel 2045: 	} elsif ($env{'form.vAns'} eq 'all') {
1.144     albertel 2046: 	    $mode='answer';
                   2047: 	}
1.329     albertel 2048: 	&Apache::lonxml::clear_problem_counter();
1.475     albertel 2049: 	$request->print(&show_problem($request,$symb,$uname,$udom,1,1,$mode,{'request.prefix' => 'ctr'.$counter}));
1.58      albertel 2050:     }
1.144     albertel 2051: 
1.257     albertel 2052:     my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
1.582     raeburn  2053:     my $res_error;
                   2054:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
                   2055:     if ($res_error) {
                   2056:         $request->print(&navmap_errormsg());
                   2057:         return;
                   2058:     }
1.41      ng       2059: 
1.44      ng       2060:     # Display student info
1.41      ng       2061:     $request->print(($counter == 0 ? '' : '<br />'));
1.590     bisitz   2062: 
                   2063:     my $result='<div class="LC_Box">'
                   2064:               .'<h3 class="LC_hcell">'.&mt('Submissions').'</h3>';
1.45      ng       2065:     $result.='<input type="hidden" name="name'.$counter.
1.588     bisitz   2066:              '" value="'.$env{'form.fullname'}.'" />'."\n";
1.624     www      2067: #    if ($env{'form.handgrade'} eq 'no') {
                   2068:     if (1) {
1.588     bisitz   2069:         $result.='<p class="LC_info">'
                   2070:                 .&mt('Part(s) graded correct by the computer is marked with a [_1] symbol.',$checkIcon)
                   2071:                 ."</p>\n";
1.469     albertel 2072:     }
                   2073: 
1.118     ng       2074:     # If any part of the problem is an essay-response (handgraded), then check for collaborators
1.464     albertel 2075:     my $fullname;
                   2076:     my $col_fullnames = [];
1.624     www      2077: #    if ($env{'form.handgrade'} eq 'yes') {
                   2078:     if (1) {
1.464     albertel 2079: 	(my $sub_result,$fullname,$col_fullnames)=
                   2080: 	    &check_collaborators($symb,$uname,$udom,\%record,$handgrade,
                   2081: 				 $counter);
                   2082: 	$result.=$sub_result;
1.41      ng       2083:     }
1.44      ng       2084:     $request->print($result."\n");
1.588     bisitz   2085: 
1.44      ng       2086:     # print student answer/submission
1.588     bisitz   2087:     # Options are (1) Handgraded submission only
1.44      ng       2088:     #             (2) Last submission, includes submission that is not handgraded 
                   2089:     #                  (for multi-response type part)
                   2090:     #             (3) Last submission plus the parts info
                   2091:     #             (4) The whole record for this student
1.257     albertel 2092:     if ($env{'form.lastSub'} =~ /^(lastonly|hdgrade)$/) {
1.151     albertel 2093: 	my ($string,$timestamp)= &get_last_submission(\%record);
1.468     albertel 2094: 	
                   2095: 	my $lastsubonly;
                   2096: 
1.588     bisitz   2097:         if ($$timestamp eq '') {
                   2098:             $lastsubonly.='<div class="LC_grade_submissions_body">'.$$string[0].'</div>'; 
                   2099:         } else {
1.592     bisitz   2100:             $lastsubonly =
                   2101:                 '<div class="LC_grade_submissions_body">'
                   2102:                .'<b>'.&mt('Date Submitted:').'</b> '.$$timestamp."\n";
1.468     albertel 2103: 
1.151     albertel 2104: 	    my %seenparts;
1.375     albertel 2105: 	    my @part_response_id = &flatten_responseType($responseType);
                   2106: 	    foreach my $part (@part_response_id) {
1.393     albertel 2107: 		next if ($env{'form.lastSub'} eq 'hdgrade' 
                   2108: 			 && $$handgrade{$$part[0].'_'.$$part[1]} ne 'yes');
                   2109: 
1.375     albertel 2110: 		my ($partid,$respid) = @{ $part };
1.324     albertel 2111: 		my $display_part=&get_display_part($partid,$symb);
1.257     albertel 2112: 		if ($env{"form.$uname:$udom:$partid:submitted_by"}) {
1.151     albertel 2113: 		    if (exists($seenparts{$partid})) { next; }
                   2114: 		    $seenparts{$partid}=1;
1.207     albertel 2115: 		    my $submitby='<b>Part:</b> '.$display_part.
                   2116: 			' <b>Collaborative submission by:</b> '.
1.151     albertel 2117: 			'<a href="javascript:viewSubmitter(\''.
1.257     albertel 2118: 			$env{"form.$uname:$udom:$partid:submitted_by"}.
1.417     albertel 2119: 			'\');" target="_self">'.
1.257     albertel 2120: 			$$fullname{$env{"form.$uname:$udom:$partid:submitted_by"}}.'</a><br />';
1.151     albertel 2121: 		    $request->print($submitby);
                   2122: 		    next;
                   2123: 		}
                   2124: 		my $responsetype = $responseType->{$partid}->{$respid};
                   2125: 		if (!exists($record{"resource.$partid.$respid.submission"})) {
1.577     bisitz   2126:                     $lastsubonly.="\n".'<div class="LC_grade_submission_part">'.
                   2127:                         '<b>'.&mt('Part: [_1]',$display_part).'</b>'.
                   2128:                         ' <span class="LC_internal_info">'.
1.623     www      2129:                         '('.&mt('Response ID: [_1]',$respid).')'.
1.577     bisitz   2130:                         '</span>&nbsp; &nbsp;'.
1.539     riegler  2131: 			'<span class="LC_warning">'.&mt('Nothing submitted - no attempts.').'</span><br /><br /></div>';
1.151     albertel 2132: 		    next;
                   2133: 		}
1.468     albertel 2134: 		foreach my $submission (@$string) {
                   2135: 		    my ($partid,$respid) = ($submission =~ /^resource\.([^\.]*)\.([^\.]*)\.submission/);
1.375     albertel 2136: 		    if (join('_',@{$part}) ne ($partid.'_'.$respid)) { next; }
1.596     raeburn  2137: 		    my ($ressub,$hide,$subval) = split(/:/,$submission,3);
1.151     albertel 2138: 		    # Similarity check
                   2139: 		    my $similar='';
1.257     albertel 2140: 		    if($env{'form.checkPlag'}){
1.151     albertel 2141: 			my ($oname,$odom,$ocrsid,$oessay,$osim)=
1.426     albertel 2142: 			    &most_similar($uname,$udom,$subval,\%old_essays);
1.151     albertel 2143: 			if ($osim) {
                   2144: 			    $osim=int($osim*100.0);
1.426     albertel 2145: 			    my %old_course_desc = 
                   2146: 				&Apache::lonnet::coursedescription($ocrsid,
                   2147: 								   {'one_time' => 1});
                   2148: 
1.596     raeburn  2149:                             if ($hide) {
                   2150:                                 $similar='<hr /><span class="LC_warning">'.&mt("Essay was found to be similar to another essay submitted for this assignment.").'<br />'.
                   2151:                                          &mt('As the current submission is for an anonymous survey, no other details are available.').'</span><hr />';
                   2152:                             } else {
                   2153: 			        $similar="<hr /><h3><span class=\"LC_warning\">".
                   2154: 				    &mt('Essay is [_1]% similar to an essay by [_2] in course [_3] (course id [_4]:[_5])',
                   2155: 				        $osim,
                   2156: 				        &Apache::loncommon::plainname($oname,$odom).' ('.$oname.':'.$odom.')',
                   2157: 				        $old_course_desc{'description'},
                   2158: 				        $old_course_desc{'num'},
                   2159: 				        $old_course_desc{'domain'}).
                   2160: 				    '</span></h3><blockquote><i>'.
                   2161: 				    &keywords_highlight($oessay).
                   2162: 				    '</i></blockquote><hr />';
                   2163:                             }
1.151     albertel 2164: 			}
1.150     albertel 2165: 		    }
1.151     albertel 2166: 		    my $order=&get_order($partid,$respid,$symb,$uname,$udom);
1.257     albertel 2167: 		    if ($env{'form.lastSub'} eq 'lastonly' || 
                   2168: 			($env{'form.lastSub'} eq 'hdgrade' && 
1.377     albertel 2169: 			 $$handgrade{$$part[0].'_'.$$part[1]} eq 'yes')) {
1.324     albertel 2170: 			my $display_part=&get_display_part($partid,$symb);
1.577     bisitz   2171:                         $lastsubonly.='<div class="LC_grade_submission_part">'.
                   2172:                             '<b>'.&mt('Part: [_1]',$display_part).'</b>'.
                   2173:                             ' <span class="LC_internal_info">'.
1.623     www      2174:                             '('.&mt('Response ID: [_1]',$respid).')'.
1.597     wenzelju 2175:                             '</span>&nbsp; &nbsp;';
1.313     banghart 2176: 			my $files=&get_submitted_files($udom,$uname,$partid,$respid,\%record);
                   2177: 			if (@$files) {
1.596     raeburn  2178:                             if ($hide) {
                   2179:                                 $lastsubonly.='<br />'.&mt('[quant,_1,file] uploaded to this anonymous survey',scalar(@{$files}));
                   2180:                             } else {
                   2181:                                 $lastsubonly.='<br /><span class="LC_warning">'.&mt('Like all files provided by users, this file may contain viruses').'</span><br />';
                   2182:                                 foreach my $file (@$files) {
                   2183:                                     &Apache::lonnet::allowuploaded('/adm/grades',$file);
                   2184:                                     $lastsubonly.='<br /><a href="'.$file.'?rawmode=1" target="lonGRDs"><img src="'.&Apache::loncommon::icon($file).'" border="0" /> '.$file.'</a>';
                   2185:                                 }
                   2186:                             }
1.236     albertel 2187: 			    $lastsubonly.='<br />';
1.41      ng       2188: 			}
1.596     raeburn  2189:                         if ($hide) {
                   2190:                             $lastsubonly.='<b>'.&mt('Anonymous Survey').'</b>'; 
                   2191:                         } else {
                   2192: 			    $lastsubonly.='<b>'.&mt('Submitted Answer:').' </b>'.
                   2193: 			        &cleanRecord($subval,$responsetype,$symb,$partid,
                   2194: 					     $respid,\%record,$order,undef,$uname,$udom);
                   2195:                         }
1.151     albertel 2196: 			if ($similar) {$lastsubonly.="<br /><br />$similar\n";}
1.468     albertel 2197: 			$lastsubonly.='</div>';
1.41      ng       2198: 		    }
                   2199: 		}
                   2200: 	    }
1.588     bisitz   2201: 	    $lastsubonly.='</div>'."\n"; # End: LC_grade_submissions_body
1.151     albertel 2202: 	}
                   2203: 	$request->print($lastsubonly);
1.468     albertel 2204:    } elsif ($env{'form.lastSub'} eq 'datesub') {
1.623     www      2205:         my ($parts,$handgrade,$responseType) = &response_type($symb,\$res_error);
1.148     albertel 2206: 	$request->print(&displaySubByDates($symb,\%record,$parts,$responseType,$checkIcon,$uname,$udom));
1.257     albertel 2207:     } elsif ($env{'form.lastSub'} =~ /^(last|all)$/) {
1.41      ng       2208: 	$request->print(&Apache::loncommon::get_previous_attempt($symb,$uname,$udom,
1.257     albertel 2209: 								 $env{'request.course.id'},
1.44      ng       2210: 								 $last,'.submission',
                   2211: 								 'Apache::grades::keywords_highlight'));
1.41      ng       2212:     }
1.121     ng       2213:     $request->print('<input type="hidden" name="unamedom'.$counter.'" value="'.$uname.':'
                   2214: 	.$udom.'" />'."\n");
1.44      ng       2215:     # return if view submission with no grading option
1.619     www      2216: # FIXME: the logic seems off here. Why show the grade button if you cannot grade?
1.618     www      2217:     if (!&canmodify($usec)) {
1.120     ng       2218: 	my $toGrade.='<input type="button" value="Grade Student" '.
1.589     bisitz   2219: 	    'onclick="javascript:checksubmit(this.form,\'Grade Student\',\''
1.417     albertel 2220: 	    .$counter.'\');" target="_self" /> &nbsp;'."\n" if (&canmodify($usec));
1.468     albertel 2221: 	$toGrade.='</div>'."\n";
1.180     albertel 2222: 	$request->print($toGrade);
1.41      ng       2223: 	return;
1.180     albertel 2224:     } else {
1.468     albertel 2225: 	$request->print('</div>'."\n");
1.41      ng       2226:     }
1.33      ng       2227: 
1.121     ng       2228:     # essay grading message center
1.624     www      2229: #    if ($env{'form.handgrade'} eq 'yes') {
                   2230:     if (1) {
1.468     albertel 2231: 	my $result='<div class="LC_grade_message_center">';
                   2232:     
                   2233: 	$result.='<div class="LC_grade_message_center_header">'.
                   2234: 	    &mt('Send Message').'</div><div class="LC_grade_message_center_body">';
1.257     albertel 2235: 	my ($lastname,$givenn) = split(/,/,$env{'form.fullname'});
1.118     ng       2236: 	my $msgfor = $givenn.' '.$lastname;
1.464     albertel 2237: 	if (scalar(@$col_fullnames) > 0) {
                   2238: 	    my $lastone = pop(@$col_fullnames);
                   2239: 	    $msgfor .= ', '.(join ', ',@$col_fullnames).' and '.$lastone.'.';
1.118     ng       2240: 	}
                   2241: 	$msgfor =~ s/\'/\\'/g; #' stupid emacs - no! javascript
1.468     albertel 2242: 	$result.='<input type="hidden" name="includemsg'.$counter.'" value="" />'."\n".
1.121     ng       2243: 	    '<input type="hidden" name="newmsg'.$counter.'" value="" />'."\n";
                   2244: 	$result.='&nbsp;<a href="javascript:msgCenter(document.SCORE,'.$counter.
1.417     albertel 2245: 	    ',\''.$msgfor.'\');" target="_self">'.
1.464     albertel 2246: 	    &mt('Compose message to student').(scalar(@$col_fullnames) >= 1 ? 's' : '').'</a><label> ('.
1.350     albertel 2247: 	    &mt('incl. grades').' <input type="checkbox" name="withgrades'.$counter.'" /></label>)'.
1.118     ng       2248: 	    '<img src="'.$request->dir_config('lonIconsURL').
                   2249: 	    '/mailbkgrd.gif" width="14" height="10" name="mailicon'.$counter.'" />'."\n".
1.298     www      2250: 	    '<br />&nbsp;('.
1.468     albertel 2251: 	    &mt('Message will be sent when you click on Save &amp; Next below.').")\n";
                   2252: 	$result.='</div></div>';
1.121     ng       2253: 	$request->print($result);
1.118     ng       2254:     }
1.41      ng       2255: 
                   2256:     my %seen = ();
                   2257:     my @partlist;
1.129     ng       2258:     my @gradePartRespid;
1.375     albertel 2259:     my @part_response_id = &flatten_responseType($responseType);
1.585     bisitz   2260:     $request->print(
1.588     bisitz   2261:         '<div class="LC_Box">'
                   2262:        .'<h3 class="LC_hcell">'.&mt('Assign Grades').'</h3>'
1.585     bisitz   2263:     );
1.592     bisitz   2264:     $request->print(&gradeBox_start());
1.375     albertel 2265:     foreach my $part_response_id (@part_response_id) {
                   2266:     	my ($partid,$respid) = @{ $part_response_id };
                   2267: 	my $part_resp = join('_',@{ $part_response_id });
1.322     albertel 2268: 	next if ($seen{$partid} > 0);
1.41      ng       2269: 	$seen{$partid}++;
1.393     albertel 2270: 	next if ($$handgrade{$part_resp} ne 'yes' 
                   2271: 		 && $env{'form.lastSub'} eq 'hdgrade');
1.524     raeburn  2272: 	push(@partlist,$partid);
                   2273: 	push(@gradePartRespid,$partid.'.'.$respid);
1.322     albertel 2274: 	$request->print(&gradeBox($request,$symb,$uname,$udom,$counter,$partid,\%record));
1.41      ng       2275:     }
1.585     bisitz   2276:     $request->print(&gradeBox_end()); # </div>
                   2277:     $request->print('</div>');
1.468     albertel 2278: 
                   2279:     $request->print('<div class="LC_grade_info_links">');
                   2280:     $request->print('</div>');
                   2281: 
1.45      ng       2282:     $result='<input type="hidden" name="partlist'.$counter.
                   2283: 	'" value="'.(join ":",@partlist).'" />'."\n";
1.129     ng       2284:     $result.='<input type="hidden" name="gradePartRespid'.
                   2285: 	'" value="'.(join ":",@gradePartRespid).'" />'."\n" if ($counter == 0);
1.45      ng       2286:     my $ctr = 0;
                   2287:     while ($ctr < scalar(@partlist)) {
                   2288: 	$result.='<input type="hidden" name="partid'.$counter.'_'.$ctr.'" value="'.
                   2289: 	    $partlist[$ctr].'" />'."\n";
                   2290: 	$ctr++;
                   2291:     }
1.468     albertel 2292:     $request->print($result.''."\n");
1.41      ng       2293: 
1.441     www      2294: # Done with printing info for one student
                   2295: 
1.468     albertel 2296:     $request->print('</div>');#LC_grade_show_user
1.441     www      2297: 
                   2298: 
1.41      ng       2299:     # print end of form
                   2300:     if ($counter == $total) {
1.592     bisitz   2301:         my $endform='<br /><hr /><table border="0"><tr><td>'."\n";
1.485     albertel 2302: 	$endform.='<input type="button" value="'.&mt('Save &amp; Next').'" '.
1.589     bisitz   2303: 	    'onclick="javascript:checksubmit(this.form,\'Save & Next\','.
1.417     albertel 2304: 	    $total.','.scalar(@partlist).');" target="_self" /> &nbsp;'."\n";
1.119     ng       2305: 	my $ntstu ='<select name="NTSTU">'.
                   2306: 	    '<option>1</option><option>2</option>'.
                   2307: 	    '<option>3</option><option>5</option>'.
                   2308: 	    '<option>7</option><option>10</option></select>'."\n";
1.257     albertel 2309: 	my $nsel = ($env{'form.NTSTU'} ne '' ? $env{'form.NTSTU'} : '1');
1.401     albertel 2310: 	$ntstu =~ s/<option>$nsel</<option selected="selected">$nsel</;
1.578     raeburn  2311:         $endform.=&mt('[_1]student(s)',$ntstu);
1.485     albertel 2312: 	$endform.='&nbsp;&nbsp;<input type="button" value="'.&mt('Previous').'" '.
1.589     bisitz   2313: 	    'onclick="javascript:checksubmit(this.form,\'Previous\');" target="_self" /> &nbsp;'."\n".
1.485     albertel 2314: 	    '<input type="button" value="'.&mt('Next').'" '.
1.589     bisitz   2315: 	    'onclick="javascript:checksubmit(this.form,\'Next\');" target="_self" /> &nbsp;';
1.592     bisitz   2316:         $endform.='<span class="LC_warning">'.
                   2317:                   &mt('(Next and Previous (student) do not save the scores.)').
                   2318:                   '</span>'."\n" ;
1.349     albertel 2319:         $endform.="<input type='hidden' value='".&get_increment().
1.348     bowersj2 2320:             "' name='increment' />";
1.485     albertel 2321: 	$endform.='</td></tr></table></form>';
1.41      ng       2322: 	$request->print($endform);
                   2323:     }
                   2324:     return '';
1.38      ng       2325: }
                   2326: 
1.464     albertel 2327: sub check_collaborators {
                   2328:     my ($symb,$uname,$udom,$record,$handgrade,$counter) = @_;
                   2329:     my ($result,@col_fullnames);
                   2330:     my ($classlist,undef,$fullname) = &getclasslist('all','0');
                   2331:     foreach my $part (keys(%$handgrade)) {
                   2332: 	my $ncol = &Apache::lonnet::EXT('resource.'.$part.
                   2333: 					'.maxcollaborators',
                   2334: 					$symb,$udom,$uname);
                   2335: 	next if ($ncol <= 0);
                   2336: 	$part =~ s/\_/\./g;
                   2337: 	next if ($record->{'resource.'.$part.'.collaborators'} eq '');
                   2338: 	my (@good_collaborators, @bad_collaborators);
                   2339: 	foreach my $possible_collaborator
                   2340: 	    (split(/,?\s+/,$record->{'resource.'.$part.'.collaborators'})) { 
                   2341: 	    $possible_collaborator =~ s/[\$\^\(\)]//g;
                   2342: 	    next if ($possible_collaborator eq '');
                   2343: 	    my ($co_name,$co_dom) = split(/\@|:/,$possible_collaborator);
                   2344: 	    $co_dom = $udom if (! defined($co_dom) || $co_dom =~ /^domain$/i);
                   2345: 	    next if ($co_name eq $uname && $co_dom eq $udom);
                   2346: 	    # Doing this grep allows 'fuzzy' specification
                   2347: 	    my @matches = grep(/^\Q$co_name\E:\Q$co_dom\E$/i, 
                   2348: 			       keys(%$classlist));
                   2349: 	    if (! scalar(@matches)) {
                   2350: 		push(@bad_collaborators, $possible_collaborator);
                   2351: 	    } else {
                   2352: 		push(@good_collaborators, @matches);
                   2353: 	    }
                   2354: 	}
                   2355: 	if (scalar(@good_collaborators) != 0) {
1.466     albertel 2356: 	    $result.='<br />'.&mt('Collaborators: ');
1.464     albertel 2357: 	    foreach my $name (@good_collaborators) {
                   2358: 		my ($lastname,$givenn) = split(/,/,$$fullname{$name});
                   2359: 		push(@col_fullnames, $givenn.' '.$lastname);
                   2360: 		$result.=$fullname->{$name}.'&nbsp; &nbsp; &nbsp;';
                   2361: 	    }
                   2362: 	    $result.='<br />'."\n";
1.466     albertel 2363: 	    my ($part)=split(/\./,$part);
1.464     albertel 2364: 	    $result.='<input type="hidden" name="collaborator'.$counter.
                   2365: 		'" value="'.$part.':'.(join ':',@good_collaborators).'" />'.
                   2366: 		"\n";
                   2367: 	}
                   2368: 	if (scalar(@bad_collaborators) > 0) {
1.466     albertel 2369: 	    $result.='<div class="LC_warning">';
1.464     albertel 2370: 	    $result.=&mt('This student has submitted [quant,_1,invalid collaborator]: [_2]',scalar(@bad_collaborators),join(', ',@bad_collaborators));
                   2371: 	    $result .= '</div>';
                   2372: 	}         
                   2373: 	if (scalar(@bad_collaborators > $ncol)) {
1.466     albertel 2374: 	    $result .= '<div class="LC_warning">';
1.464     albertel 2375: 	    $result .= &mt('This student has submitted too many '.
                   2376: 		'collaborators.  Maximum is [_1].',$ncol);
                   2377: 	    $result .= '</div>';
                   2378: 	}
                   2379:     }
                   2380:     return ($result,$fullname,\@col_fullnames);
                   2381: }
                   2382: 
1.44      ng       2383: #--- Retrieve the last submission for all the parts
1.38      ng       2384: sub get_last_submission {
1.119     ng       2385:     my ($returnhash)=@_;
1.596     raeburn  2386:     my (@string,$timestamp,%lasthidden);
1.119     ng       2387:     if ($$returnhash{'version'}) {
1.46      ng       2388: 	my %lasthash=();
                   2389: 	my ($version);
1.119     ng       2390: 	for ($version=1;$version<=$$returnhash{'version'};$version++) {
1.397     albertel 2391: 	    foreach my $key (sort(split(/\:/,
                   2392: 					$$returnhash{$version.':keys'}))) {
                   2393: 		$lasthash{$key}=$$returnhash{$version.':'.$key};
                   2394: 		$timestamp = 
1.545     raeburn  2395: 		    &Apache::lonlocal::locallocaltime($$returnhash{$version.':timestamp'});
1.46      ng       2396: 	    }
                   2397: 	}
1.596     raeburn  2398:         my %typeparts;
                   2399:         my $showsurv = 
                   2400:             &Apache::lonnet::allowed('vas',$env{'request.course.id'});
                   2401:         foreach my $key (sort(keys(%lasthash))) {
                   2402:             if ($key =~ /\.type$/) {
                   2403:                 if (($lasthash{$key} eq 'anonsurvey') || 
                   2404:                     ($lasthash{$key} eq 'anonsurveycred')) {
                   2405:                     my ($ign,@parts) = split(/\./,$key);
                   2406:                     pop(@parts);
                   2407:                     unless ($showsurv) {
                   2408:                         my $id = join(',',@parts);
                   2409:                         $typeparts{$ign.'.'.$id} = $lasthash{$key};
                   2410:                     }
                   2411:                     delete($lasthash{$key});
                   2412:                 }
                   2413:             }
                   2414:         }
                   2415:         my @hidden = keys(%typeparts);
1.397     albertel 2416: 	foreach my $key (keys(%lasthash)) {
                   2417: 	    next if ($key !~ /\.submission$/);
1.596     raeburn  2418:             my $hide;
                   2419:             if (@hidden) {
                   2420:                 foreach my $id (@hidden) {
                   2421:                     if ($key =~ /^\Q$id\E/) {
                   2422:                         $hide = 1;
                   2423:                         last;
                   2424:                     }
                   2425:                 }
                   2426:             }
1.397     albertel 2427: 	    my ($partid,$foo) = split(/submission$/,$key);
                   2428: 	    my $draft  = $lasthash{$partid.'awarddetail'} eq 'DRAFT' ?
1.398     albertel 2429: 		'<span class="LC_warning">Draft Copy</span> ' : '';
1.596     raeburn  2430: 	    push(@string, join(':', $key, $hide, $draft.$lasthash{$key}));
1.41      ng       2431: 	}
                   2432:     }
1.397     albertel 2433:     if (!@string) {
                   2434: 	$string[0] =
1.539     riegler  2435: 	    '<span class="LC_warning">'.&mt('Nothing submitted - no attempts.').'</span>';
1.397     albertel 2436:     }
                   2437:     return (\@string,\$timestamp);
1.38      ng       2438: }
1.35      ng       2439: 
1.44      ng       2440: #--- High light keywords, with style choosen by user.
1.38      ng       2441: sub keywords_highlight {
1.44      ng       2442:     my $string    = shift;
1.257     albertel 2443:     my $size      = $env{'form.kwsize'} eq '0' ? '' : 'size='.$env{'form.kwsize'};
                   2444:     my $styleon   = $env{'form.kwstyle'} eq ''  ? '' : $env{'form.kwstyle'};
1.41      ng       2445:     (my $styleoff = $styleon) =~ s/\</\<\//;
1.257     albertel 2446:     my @keylist   = split(/[,\s+]/,$env{'form.keywords'});
1.398     albertel 2447:     foreach my $keyword (@keylist) {
                   2448: 	$string =~ s/\b\Q$keyword\E(\b|\.)/<font color\=$env{'form.kwclr'} $size\>$styleon$keyword$styleoff<\/font>/gi;
1.41      ng       2449:     }
                   2450:     return $string;
1.38      ng       2451: }
1.36      ng       2452: 
1.44      ng       2453: #--- Called from submission routine
1.38      ng       2454: sub processHandGrade {
1.608     www      2455:     my ($request,$symb) = @_;
1.324     albertel 2456:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
1.257     albertel 2457:     my $button = $env{'form.gradeOpt'};
                   2458:     my $ngrade = $env{'form.NCT'};
                   2459:     my $ntstu  = $env{'form.NTSTU'};
1.301     albertel 2460:     my $cdom   = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   2461:     my $cnum   = $env{'course.'.$env{'request.course.id'}.'.num'};
                   2462: 
1.44      ng       2463:     if ($button eq 'Save & Next') {
                   2464: 	my $ctr = 0;
                   2465: 	while ($ctr < $ngrade) {
1.257     albertel 2466: 	    my ($uname,$udom) = split(/:/,$env{'form.unamedom'.$ctr});
1.324     albertel 2467: 	    my ($errorflag,$pts,$wgt) = &saveHandGrade($request,$symb,$uname,$udom,$ctr);
1.71      ng       2468: 	    if ($errorflag eq 'no_score') {
                   2469: 		$ctr++;
                   2470: 		next;
                   2471: 	    }
1.104     albertel 2472: 	    if ($errorflag eq 'not_allowed') {
1.398     albertel 2473: 		$request->print("<span class=\"LC_warning\">Not allowed to modify grades for $uname:$udom</span>");
1.104     albertel 2474: 		$ctr++;
                   2475: 		next;
                   2476: 	    }
1.257     albertel 2477: 	    my $includemsg = $env{'form.includemsg'.$ctr};
1.44      ng       2478: 	    my ($subject,$message,$msgstatus) = ('','','');
1.418     albertel 2479: 	    my $restitle = &Apache::lonnet::gettitle($symb);
                   2480:             my ($feedurl,$showsymb) =
                   2481: 		&get_feedurl_and_symb($symb,$uname,$udom);
                   2482: 	    my $messagetail;
1.62      albertel 2483: 	    if ($includemsg =~ /savemsg|newmsg\Q$ctr\E/) {
1.298     www      2484: 		$subject = $env{'form.msgsub'} if ($includemsg =~ /msgsub/);
1.295     www      2485: 		unless ($subject=~/\w/) { $subject=&mt('Grading Feedback'); }
1.386     raeburn  2486: 		$subject.=' ['.$restitle.']';
1.44      ng       2487: 		my (@msgnum) = split(/,/,$includemsg);
                   2488: 		foreach (@msgnum) {
1.257     albertel 2489: 		    $message.=$env{'form.'.$_} if ($_ =~ /savemsg|newmsg/ && $_ ne '');
1.44      ng       2490: 		}
1.80      ng       2491: 		$message =&Apache::lonfeedback::clear_out_html($message);
1.298     www      2492: 		if ($env{'form.withgrades'.$ctr}) {
                   2493: 		    $message.="\n\nPoint".($pts > 1 ? 's':'').' awarded = '.$pts.' out of '.$wgt;
1.386     raeburn  2494: 		    $messagetail = " for <a href=\"".
1.605     www      2495: 		                   $feedurl."?symb=$showsymb\">$restitle</a>";
1.386     raeburn  2496: 		}
                   2497: 		$msgstatus = 
                   2498:                     &Apache::lonmsg::user_normal_msg($uname,$udom,$subject,
                   2499: 						     $message.$messagetail,
1.418     albertel 2500:                                                      undef,$feedurl,undef,
1.386     raeburn  2501:                                                      undef,undef,$showsymb,
                   2502:                                                      $restitle);
1.574     bisitz   2503: 		$request->print('<br />'.&mt('Sending message to [_1]',$uname.':'.$udom).': '.
1.296     www      2504: 				$msgstatus);
1.44      ng       2505: 	    }
1.257     albertel 2506: 	    if ($env{'form.collaborator'.$ctr}) {
1.155     albertel 2507: 		my @collabstrs=&Apache::loncommon::get_env_multiple("form.collaborator$ctr");
1.150     albertel 2508: 		foreach my $collabstr (@collabstrs) {
                   2509: 		    my ($part,@collaborators) = split(/:/,$collabstr);
1.310     banghart 2510: 		    foreach my $collaborator (@collaborators) {
1.150     albertel 2511: 			my ($errorflag,$pts,$wgt) = 
1.324     albertel 2512: 			    &saveHandGrade($request,$symb,$collaborator,$udom,$ctr,
1.257     albertel 2513: 					   $env{'form.unamedom'.$ctr},$part);
1.150     albertel 2514: 			if ($errorflag eq 'not_allowed') {
1.362     albertel 2515: 			    $request->print("<span class=\"LC_error\">".&mt('Not allowed to modify grades for [_1]',"$collaborator:$udom")."</span>");
1.150     albertel 2516: 			    next;
1.418     albertel 2517: 			} elsif ($message ne '') {
                   2518: 			    my ($baseurl,$showsymb) = 
                   2519: 				&get_feedurl_and_symb($symb,$collaborator,
                   2520: 						      $udom);
                   2521: 			    if ($env{'form.withgrades'.$ctr}) {
                   2522: 				$messagetail = " for <a href=\"".
1.605     www      2523:                                     $baseurl."?symb=$showsymb\">$restitle</a>";
1.150     albertel 2524: 			    }
1.418     albertel 2525: 			    $msgstatus = 
                   2526: 				&Apache::lonmsg::user_normal_msg($collaborator,$udom,$subject,$message.$messagetail,undef,$baseurl,undef,undef,undef,$showsymb,$restitle);
1.104     albertel 2527: 			}
1.44      ng       2528: 		    }
                   2529: 		}
                   2530: 	    }
                   2531: 	    $ctr++;
                   2532: 	}
                   2533:     }
                   2534: 
1.624     www      2535: #    if ($env{'form.handgrade'} eq 'yes') {
                   2536:     if (1) {
1.119     ng       2537: 	# Keywords sorted in alphabatical order
1.257     albertel 2538: 	my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
1.119     ng       2539: 	my %keyhash = ();
1.257     albertel 2540: 	$env{'form.keywords'}           =~ s/,\s{0,}|\s+/ /g;
                   2541: 	$env{'form.keywords'}           =~ s/^\s+|\s+$//;
                   2542: 	my (@keywords) = sort(split(/\s+/,$env{'form.keywords'}));
                   2543: 	$env{'form.keywords'} = join(' ',@keywords);
                   2544: 	$keyhash{$symb.'_keywords'}     = $env{'form.keywords'};
                   2545: 	$keyhash{$symb.'_subject'}      = $env{'form.msgsub'};
                   2546: 	$keyhash{$loginuser.'_kwclr'}   = $env{'form.kwclr'};
                   2547: 	$keyhash{$loginuser.'_kwsize'}  = $env{'form.kwsize'};
                   2548: 	$keyhash{$loginuser.'_kwstyle'} = $env{'form.kwstyle'};
1.119     ng       2549: 
                   2550: 	# message center - Order of message gets changed. Blank line is eliminated.
1.257     albertel 2551: 	# New messages are saved in env for the next student.
1.119     ng       2552: 	# All messages are saved in nohist_handgrade.db
                   2553: 	my ($ctr,$idx) = (1,1);
1.257     albertel 2554: 	while ($ctr <= $env{'form.savemsgN'}) {
                   2555: 	    if ($env{'form.savemsg'.$ctr} ne '') {
                   2556: 		$keyhash{$symb.'_savemsg'.$idx} = $env{'form.savemsg'.$ctr};
1.119     ng       2557: 		$idx++;
                   2558: 	    }
                   2559: 	    $ctr++;
1.41      ng       2560: 	}
1.119     ng       2561: 	$ctr = 0;
                   2562: 	while ($ctr < $ngrade) {
1.257     albertel 2563: 	    if ($env{'form.newmsg'.$ctr} ne '') {
                   2564: 		$keyhash{$symb.'_savemsg'.$idx} = $env{'form.newmsg'.$ctr};
                   2565: 		$env{'form.savemsg'.$idx} = $env{'form.newmsg'.$ctr};
1.119     ng       2566: 		$idx++;
                   2567: 	    }
                   2568: 	    $ctr++;
1.41      ng       2569: 	}
1.257     albertel 2570: 	$env{'form.savemsgN'} = --$idx;
                   2571: 	$keyhash{$symb.'_savemsgN'} = $env{'form.savemsgN'};
1.119     ng       2572: 	my $putresult = &Apache::lonnet::put
1.301     albertel 2573: 	    ('nohist_handgrade',\%keyhash,$cdom,$cnum);
1.41      ng       2574:     }
1.44      ng       2575:     # Called by Save & Refresh from Highlight Attribute Window
1.257     albertel 2576:     my (undef,undef,$fullname) = &getclasslist($env{'form.section'},'1');
                   2577:     if ($env{'form.refresh'} eq 'on') {
1.86      ng       2578: 	my ($ctr,$total) = (0,0);
                   2579: 	while ($ctr < $ngrade) {
1.257     albertel 2580: 	    $total++ if  $env{'form.unamedom'.$ctr} ne '';
1.86      ng       2581: 	    $ctr++;
                   2582: 	}
1.257     albertel 2583: 	$env{'form.NTSTU'}=$ngrade;
1.86      ng       2584: 	$ctr = 0;
                   2585: 	while ($ctr < $total) {
1.257     albertel 2586: 	    my $processUser = $env{'form.unamedom'.$ctr};
                   2587: 	    ($env{'form.student'},$env{'form.userdom'}) = split(/:/,$processUser);
                   2588: 	    $env{'form.fullname'} = $$fullname{$processUser};
1.625   ! www      2589: 	    &submission($request,$ctr,$total-1,$symb);
1.41      ng       2590: 	    $ctr++;
                   2591: 	}
                   2592: 	return '';
                   2593:     }
1.36      ng       2594: 
1.121     ng       2595: # Go directly to grade student - from submission or link from chart page
1.625   ! www      2596: # FIXME: looks like reading off the button label!
1.120     ng       2597:     if ($button eq 'Grade Student') {
1.257     albertel 2598: 	my $processUser = $env{'form.unamedom'.$env{'form.studentNo'}};
                   2599: 	($env{'form.student'},$env{'form.userdom'}) = split(/:/,$processUser);
                   2600: 	$env{'form.fullname'} = $$fullname{$processUser};
1.625   ! www      2601: 	&submission($request,0,0,$symb);
1.120     ng       2602: 	return '';
                   2603:     }
                   2604: 
1.44      ng       2605:     # Get the next/previous one or group of students
1.257     albertel 2606:     my $firststu = $env{'form.unamedom0'};
                   2607:     my $laststu = $env{'form.unamedom'.($ngrade-1)};
1.119     ng       2608:     my $ctr = 2;
1.41      ng       2609:     while ($laststu eq '') {
1.257     albertel 2610: 	$laststu  = $env{'form.unamedom'.($ngrade-$ctr)};
1.41      ng       2611: 	$ctr++;
                   2612: 	$laststu = $firststu if ($ctr > $ngrade);
                   2613:     }
1.44      ng       2614: 
1.41      ng       2615:     my (@parsedlist,@nextlist);
                   2616:     my ($nextflg) = 0;
1.524     raeburn  2617:     foreach my $item (sort 
1.294     albertel 2618: 	     {
                   2619: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                   2620: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                   2621: 		 }
                   2622: 		 return $a cmp $b;
                   2623: 	     } (keys(%$fullname))) {
1.605     www      2624: # FIXME: this is fishy, looks like the button label
1.41      ng       2625: 	if ($nextflg == 1 && $button =~ /Next$/) {
1.524     raeburn  2626: 	    push(@parsedlist,$item);
1.41      ng       2627: 	}
1.524     raeburn  2628: 	$nextflg = 1 if ($item eq $laststu);
1.41      ng       2629: 	if ($button eq 'Previous') {
1.524     raeburn  2630: 	    last if ($item eq $firststu);
                   2631: 	    push(@parsedlist,$item);
1.41      ng       2632: 	}
                   2633:     }
                   2634:     $ctr = 0;
1.605     www      2635: # FIXME: this is fishy, looks like the button label
1.41      ng       2636:     @parsedlist = reverse @parsedlist if ($button eq 'Previous');
1.582     raeburn  2637:     my $res_error;
                   2638:     my ($partlist) = &response_type($symb,\$res_error);
                   2639:     if ($res_error) {
                   2640:         $request->print(&navmap_errormsg());
                   2641:         return;
                   2642:     }
1.41      ng       2643:     foreach my $student (@parsedlist) {
1.257     albertel 2644: 	my $submitonly=$env{'form.submitonly'};
1.41      ng       2645: 	my ($uname,$udom) = split(/:/,$student);
1.301     albertel 2646: 	
                   2647: 	if ($submitonly eq 'queued') {
                   2648: 	    my %queue_status = 
                   2649: 		&Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
                   2650: 							$udom,$uname);
                   2651: 	    next if (!defined($queue_status{'gradingqueue'}));
                   2652: 	}
                   2653: 
1.156     albertel 2654: 	if ($submitonly =~ /^(yes|graded|incorrect)$/) {
1.257     albertel 2655: #	    my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
1.324     albertel 2656: 	    my %status=&student_gradeStatus($symb,$udom,$uname,$partlist);
1.145     albertel 2657: 	    my $submitted = 0;
1.248     albertel 2658: 	    my $ungraded = 0;
                   2659: 	    my $incorrect = 0;
1.524     raeburn  2660: 	    foreach my $item (keys(%status)) {
                   2661: 		$submitted = 1 if ($status{$item} ne 'nothing');
                   2662: 		$ungraded = 1 if ($status{$item} =~ /^ungraded/);
                   2663: 		$incorrect = 1 if ($status{$item} =~ /^incorrect/);
                   2664: 		my ($foo,$partid,$foo1) = split(/\./,$item);
1.145     albertel 2665: 		if ($status{'resource.'.$partid.'.submitted_by'} ne '') {
                   2666: 		    $submitted = 0;
                   2667: 		}
1.41      ng       2668: 	    }
1.156     albertel 2669: 	    next if (!$submitted && ($submitonly eq 'yes' ||
                   2670: 				     $submitonly eq 'incorrect' ||
                   2671: 				     $submitonly eq 'graded'));
1.248     albertel 2672: 	    next if (!$ungraded && ($submitonly eq 'graded'));
                   2673: 	    next if (!$incorrect && $submitonly eq 'incorrect');
1.41      ng       2674: 	}
1.524     raeburn  2675: 	push(@nextlist,$student) if ($ctr < $ntstu);
1.129     ng       2676: 	last if ($ctr == $ntstu);
1.41      ng       2677: 	$ctr++;
                   2678:     }
1.36      ng       2679: 
1.41      ng       2680:     $ctr = 0;
                   2681:     my $total = scalar(@nextlist)-1;
1.39      ng       2682: 
1.524     raeburn  2683:     foreach (sort(@nextlist)) {
1.41      ng       2684: 	my ($uname,$udom,$submitter) = split(/:/);
1.257     albertel 2685: 	$env{'form.student'}  = $uname;
                   2686: 	$env{'form.userdom'}  = $udom;
                   2687: 	$env{'form.fullname'} = $$fullname{$_};
1.625   ! www      2688: 	&submission($request,$ctr,$total,$symb);
1.41      ng       2689: 	$ctr++;
                   2690:     }
                   2691:     if ($total < 0) {
1.485     albertel 2692: 	my $the_end = '<h3><span class="LC_info">'.&mt('LON-CAPA User Message').'</span></h3><br />'."\n";
                   2693: 	$the_end.=&mt('<b>Message: </b> No more students for this section or class.').'<br /><br />'."\n";
                   2694: 	$the_end.=&mt('Click on the button below to return to the grading menu.').'<br /><br />'."\n";
1.41      ng       2695: 	$request->print($the_end);
                   2696:     }
                   2697:     return '';
1.38      ng       2698: }
1.36      ng       2699: 
1.44      ng       2700: #---- Save the score and award for each student, if changed
1.38      ng       2701: sub saveHandGrade {
1.324     albertel 2702:     my ($request,$symb,$stuname,$domain,$newflg,$submitter,$part) = @_;
1.342     banghart 2703:     my @version_parts;
1.104     albertel 2704:     my $usec = &Apache::lonnet::getsection($domain,$stuname,
1.257     albertel 2705: 					   $env{'request.course.id'});
1.104     albertel 2706:     if (!&canmodify($usec)) { return('not_allowed'); }
1.337     banghart 2707:     my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$domain,$stuname);
1.251     banghart 2708:     my @parts_graded;
1.77      ng       2709:     my %newrecord  = ();
                   2710:     my ($pts,$wgt) = ('','');
1.269     raeburn  2711:     my %aggregate = ();
                   2712:     my $aggregateflag = 0;
1.301     albertel 2713:     my @parts = split(/:/,$env{'form.partlist'.$newflg});
                   2714:     foreach my $new_part (@parts) {
1.337     banghart 2715: 	#collaborator ($submi may vary for different parts
1.259     banghart 2716: 	if ($submitter && $new_part ne $part) { next; }
                   2717: 	my $dropMenu = $env{'form.GD_SEL'.$newflg.'_'.$new_part};
1.125     ng       2718: 	if ($dropMenu eq 'excused') {
1.259     banghart 2719: 	    if ($record{'resource.'.$new_part.'.solved'} ne 'excused') {
                   2720: 		$newrecord{'resource.'.$new_part.'.solved'} = 'excused';
                   2721: 		if (exists($record{'resource.'.$new_part.'.awarded'})) {
                   2722: 		    $newrecord{'resource.'.$new_part.'.awarded'} = '';
1.58      albertel 2723: 		}
1.364     banghart 2724: 	        $newrecord{'resource.'.$new_part.'.regrader'}="$env{'user.name'}:$env{'user.domain'}";
1.58      albertel 2725: 	    }
1.125     ng       2726: 	} elsif ($dropMenu eq 'reset status'
1.259     banghart 2727: 		 && exists($record{'resource.'.$new_part.'.solved'})) { #don't bother if no old records -> no attempts
1.524     raeburn  2728: 	    foreach my $key (keys(%record)) {
1.259     banghart 2729: 		if ($key=~/^resource\.\Q$new_part\E\./) { $newrecord{$key} = ''; }
1.197     albertel 2730: 	    }
1.259     banghart 2731: 	    $newrecord{'resource.'.$new_part.'.regrader'}=
1.257     albertel 2732: 		"$env{'user.name'}:$env{'user.domain'}";
1.270     albertel 2733:             my $totaltries = $record{'resource.'.$part.'.tries'};
                   2734: 
                   2735:             my %last_resets = &get_last_resets($symb,$env{'request.course.id'},
                   2736: 					       [$new_part]);
                   2737:             my $aggtries =$totaltries;
1.269     raeburn  2738:             if ($last_resets{$new_part}) {
1.270     albertel 2739:                 $aggtries = &get_num_tries(\%record,$last_resets{$new_part},
                   2740: 					   $new_part);
1.269     raeburn  2741:             }
1.270     albertel 2742: 
                   2743:             my $solvedstatus = $record{'resource.'.$new_part.'.solved'};
1.269     raeburn  2744:             if ($aggtries > 0) {
1.327     albertel 2745:                 &decrement_aggs($symb,$new_part,\%aggregate,$aggtries,$totaltries,$solvedstatus);
1.269     raeburn  2746:                 $aggregateflag = 1;
                   2747:             }
1.125     ng       2748: 	} elsif ($dropMenu eq '') {
1.259     banghart 2749: 	    $pts = ($env{'form.GD_BOX'.$newflg.'_'.$new_part} ne '' ? 
                   2750: 		    $env{'form.GD_BOX'.$newflg.'_'.$new_part} : 
                   2751: 		    $env{'form.RADVAL'.$newflg.'_'.$new_part});
                   2752: 	    if ($pts eq '' && $env{'form.GD_SEL'.$newflg.'_'.$new_part} eq '') {
1.153     albertel 2753: 		next;
                   2754: 	    }
1.259     banghart 2755: 	    $wgt = $env{'form.WGT'.$newflg.'_'.$new_part} eq '' ? 1 : 
                   2756: 		$env{'form.WGT'.$newflg.'_'.$new_part};
1.41      ng       2757: 	    my $partial= $pts/$wgt;
1.259     banghart 2758: 	    if ($partial eq $record{'resource.'.$new_part.'.awarded'}) {
1.153     albertel 2759: 		#do not update score for part if not changed.
1.346     banghart 2760:                 &handback_files($request,$symb,$stuname,$domain,$newflg,$new_part,\%newrecord);
1.153     albertel 2761: 		next;
1.251     banghart 2762: 	    } else {
1.524     raeburn  2763: 	        push(@parts_graded,$new_part);
1.153     albertel 2764: 	    }
1.259     banghart 2765: 	    if ($record{'resource.'.$new_part.'.awarded'} ne $partial) {
                   2766: 		$newrecord{'resource.'.$new_part.'.awarded'}  = $partial;
1.153     albertel 2767: 	    }
1.259     banghart 2768: 	    my $reckey = 'resource.'.$new_part.'.solved';
1.41      ng       2769: 	    if ($partial == 0) {
1.153     albertel 2770: 		if ($record{$reckey} ne 'incorrect_by_override') {
                   2771: 		    $newrecord{$reckey} = 'incorrect_by_override';
                   2772: 		}
1.41      ng       2773: 	    } else {
1.153     albertel 2774: 		if ($record{$reckey} ne 'correct_by_override') {
                   2775: 		    $newrecord{$reckey} = 'correct_by_override';
                   2776: 		}
                   2777: 	    }	    
                   2778: 	    if ($submitter && 
1.259     banghart 2779: 		($record{'resource.'.$new_part.'.submitted_by'} ne $submitter)) {
                   2780: 		$newrecord{'resource.'.$new_part.'.submitted_by'} = $submitter;
1.41      ng       2781: 	    }
1.259     banghart 2782: 	    $newrecord{'resource.'.$new_part.'.regrader'}=
1.257     albertel 2783: 		"$env{'user.name'}:$env{'user.domain'}";
1.41      ng       2784: 	}
1.259     banghart 2785: 	# unless problem has been graded, set flag to version the submitted files
1.305     banghart 2786: 	unless ($record{'resource.'.$new_part.'.solved'} =~ /^correct_/  || 
                   2787: 	        $record{'resource.'.$new_part.'.solved'} eq 'incorrect_by_override' ||
                   2788: 	        $dropMenu eq 'reset status')
                   2789: 	   {
1.524     raeburn  2790: 	    push(@version_parts,$new_part);
1.259     banghart 2791: 	}
1.41      ng       2792:     }
1.301     albertel 2793:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   2794:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   2795: 
1.344     albertel 2796:     if (%newrecord) {
                   2797:         if (@version_parts) {
1.364     banghart 2798:             my @changed_keys = &version_portfiles(\%record, \@parts_graded, 
                   2799:                                 $env{'request.course.id'}, $symb, $domain, $stuname, \@version_parts);
1.344     albertel 2800: 	    @newrecord{@changed_keys} = @record{@changed_keys};
1.367     albertel 2801: 	    foreach my $new_part (@version_parts) {
                   2802: 		&handback_files($request,$symb,$stuname,$domain,$newflg,
                   2803: 				$new_part,\%newrecord);
                   2804: 	    }
1.259     banghart 2805:         }
1.44      ng       2806: 	&Apache::lonnet::cstore(\%newrecord,$symb,
1.257     albertel 2807: 				$env{'request.course.id'},$domain,$stuname);
1.380     albertel 2808: 	&check_and_remove_from_queue(\@parts,\%record,\%newrecord,$symb,
                   2809: 				     $cdom,$cnum,$domain,$stuname);
1.41      ng       2810:     }
1.269     raeburn  2811:     if ($aggregateflag) {
                   2812:         &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
1.301     albertel 2813: 			      $cdom,$cnum);
1.269     raeburn  2814:     }
1.301     albertel 2815:     return ('',$pts,$wgt);
1.36      ng       2816: }
1.322     albertel 2817: 
1.380     albertel 2818: sub check_and_remove_from_queue {
                   2819:     my ($parts,$record,$newrecord,$symb,$cdom,$cnum,$domain,$stuname) = @_;
                   2820:     my @ungraded_parts;
                   2821:     foreach my $part (@{$parts}) {
                   2822: 	if (    $record->{   'resource.'.$part.'.awarded'} eq ''
                   2823: 	     && $record->{   'resource.'.$part.'.solved' } ne 'excused'
                   2824: 	     && $newrecord->{'resource.'.$part.'.awarded'} eq ''
                   2825: 	     && $newrecord->{'resource.'.$part.'.solved' } ne 'excused'
                   2826: 		) {
                   2827: 	    push(@ungraded_parts, $part);
                   2828: 	}
                   2829:     }
                   2830:     if ( !@ungraded_parts ) {
                   2831: 	&Apache::bridgetask::remove_from_queue('gradingqueue',$symb,$cdom,
                   2832: 					       $cnum,$domain,$stuname);
                   2833:     }
                   2834: }
                   2835: 
1.337     banghart 2836: sub handback_files {
                   2837:     my ($request,$symb,$stuname,$domain,$newflg,$new_part,$newrecord) = @_;
1.517     raeburn  2838:     my $portfolio_root = '/userfiles/portfolio';
1.582     raeburn  2839:     my $res_error;
                   2840:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
                   2841:     if ($res_error) {
                   2842:         $request->print('<br />'.&navmap_errormsg().'<br />');
                   2843:         return;
                   2844:     }
1.375     albertel 2845:     my @part_response_id = &flatten_responseType($responseType);
                   2846:     foreach my $part_response_id (@part_response_id) {
                   2847:     	my ($part_id,$resp_id) = @{ $part_response_id };
                   2848: 	my $part_resp = join('_',@{ $part_response_id });
1.337     banghart 2849:             if (($env{'form.'.$newflg.'_'.$part_resp.'_returndoc1'}) && ($new_part == $part_id)) {
                   2850:                 # if multiple files are uploaded names will be 'returndoc2','returndoc3'
                   2851:                 my $file_counter = 1;
1.367     albertel 2852: 		my $file_msg;
1.337     banghart 2853:                 while ($env{'form.'.$newflg.'_'.$part_resp.'_returndoc'.$file_counter}) {
                   2854:                     my $fname=$env{'form.'.$newflg.'_'.$part_resp.'_returndoc'.$file_counter.'.filename'};
1.338     banghart 2855:                     my ($directory,$answer_file) = 
                   2856:                         ($env{'form.'.$newflg.'_'.$part_resp.'_origdoc'.$file_counter} =~ /^(.*?)([^\/]*)$/);
                   2857:                     my ($answer_name,$answer_ver,$answer_ext) =
                   2858: 		        &file_name_version_ext($answer_file);
1.355     banghart 2859: 		    my ($portfolio_path) = ($directory =~ /^.+$stuname\/portfolio(.*)/);
1.517     raeburn  2860:                     my $getpropath = 1;
                   2861: 		    my @dir_list = &Apache::lonnet::dirlist($portfolio_root.$portfolio_path,$domain,$stuname,$getpropath);
1.338     banghart 2862: 		    my $version = &get_next_version($answer_name, $answer_ext, \@dir_list);
1.355     banghart 2863:                     # fix file name
                   2864:                     my ($save_file_name) = (($directory.$answer_name.".$version.".$answer_ext) =~ /^.+\/${stuname}\/(.*)/);
                   2865:                     my $result=&Apache::lonnet::finishuserfileupload($stuname,$domain,
                   2866:             	                                $newflg.'_'.$part_resp.'_returndoc'.$file_counter,
                   2867:             	                                $save_file_name);
1.337     banghart 2868:                     if ($result !~ m|^/uploaded/|) {
1.536     raeburn  2869:                         $request->print('<br /><span class="LC_error">'.
                   2870:                             &mt('An error occurred ([_1]) while trying to upload [_2].',
                   2871:                                 $result,$newflg.'_'.$part_resp.'_returndoc'.$file_counter).
                   2872:                                         '</span>');
1.356     banghart 2873:                     } else {
1.360     banghart 2874:                         # mark the file as read only
                   2875:                         my @files = ($save_file_name);
1.372     albertel 2876:                         my @what = ($symb,$env{'request.course.id'},'handback');
1.360     banghart 2877:                         &Apache::lonnet::mark_as_readonly($domain,$stuname,\@files,\@what);
1.367     albertel 2878: 			if (exists($$newrecord{"resource.$new_part.$resp_id.handback"})) {
                   2879: 			    $$newrecord{"resource.$new_part.$resp_id.handback"}.=',';
                   2880: 			}
                   2881:                         $$newrecord{"resource.$new_part.$resp_id.handback"} .= $save_file_name;
                   2882: 			$file_msg.= "\n".'<br /><span class="LC_filename"><a href="/uploaded/'."$domain/$stuname/".$save_file_name.'">'.$save_file_name."</a></span><br />";
                   2883: 
1.337     banghart 2884:                     }
                   2885:                     $request->print("<br />".$fname." will be the uploaded file name");
1.354     albertel 2886:                     $request->print(" ".$env{'form.'.$newflg.'_'.$part_resp.'_origdoc'.$file_counter});
1.337     banghart 2887:                     $file_counter++;
                   2888:                 }
1.367     albertel 2889: 		my $subject = "File Handed Back by Instructor ";
                   2890: 		my $message = "A file has been returned that was originally submitted in reponse to: <br />";
                   2891: 		$message .= "<strong>".&Apache::lonnet::gettitle($symb)."</strong><br />";
                   2892: 		$message .= ' The returned file(s) are named: '. $file_msg;
                   2893: 		$message .= " and can be found in your portfolio space.";
1.418     albertel 2894: 		my ($feedurl,$showsymb) = 
                   2895: 		    &get_feedurl_and_symb($symb,$domain,$stuname);
1.386     raeburn  2896:                 my $restitle = &Apache::lonnet::gettitle($symb);
                   2897: 		my $msgstatus = 
                   2898:                    &Apache::lonmsg::user_normal_msg($stuname,$domain,$subject.
                   2899: 			 ' (File Returned) ['.$restitle.']',$message,undef,
1.418     albertel 2900:                          $feedurl,undef,undef,undef,$showsymb,$restitle);
1.337     banghart 2901:             }
                   2902:         }
1.338     banghart 2903:     return;
1.337     banghart 2904: }
                   2905: 
1.418     albertel 2906: sub get_feedurl_and_symb {
                   2907:     my ($symb,$uname,$udom) = @_;
                   2908:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
                   2909:     $url = &Apache::lonnet::clutter($url);
                   2910:     my $encrypturl=&Apache::lonnet::EXT('resource.0.encrypturl',
                   2911: 					$symb,$udom,$uname);
                   2912:     if ($encrypturl =~ /^yes$/i) {
                   2913: 	&Apache::lonenc::encrypted(\$url,1);
                   2914: 	&Apache::lonenc::encrypted(\$symb,1);
                   2915:     }
                   2916:     return ($url,$symb);
                   2917: }
                   2918: 
1.313     banghart 2919: sub get_submitted_files {
                   2920:     my ($udom,$uname,$partid,$respid,$record) = @_;
                   2921:     my @files;
                   2922:     if ($$record{"resource.$partid.$respid.portfiles"}) {
                   2923:         my $file_url = '/uploaded/'.$udom.'/'.$uname.'/portfolio';
                   2924:         foreach my $file (split(',',$$record{"resource.$partid.$respid.portfiles"})) {
                   2925:     	    push(@files,$file_url.$file);
                   2926:         }
                   2927:     }
                   2928:     if ($$record{"resource.$partid.$respid.uploadedurl"}) {
                   2929:         push(@files,$$record{"resource.$partid.$respid.uploadedurl"});
                   2930:     }
                   2931:     return (\@files);
                   2932: }
1.322     albertel 2933: 
1.269     raeburn  2934: # ----------- Provides number of tries since last reset.
                   2935: sub get_num_tries {
                   2936:     my ($record,$last_reset,$part) = @_;
                   2937:     my $timestamp = '';
                   2938:     my $num_tries = 0;
                   2939:     if ($$record{'version'}) {
                   2940:         for (my $version=$$record{'version'};$version>=1;$version--) {
                   2941:             if (exists($$record{$version.':resource.'.$part.'.solved'})) {
                   2942:                 $timestamp = $$record{$version.':timestamp'};
                   2943:                 if ($timestamp > $last_reset) {
                   2944:                     $num_tries ++;
                   2945:                 } else {
                   2946:                     last;
                   2947:                 }
                   2948:             }
                   2949:         }
                   2950:     }
                   2951:     return $num_tries;
                   2952: }
                   2953: 
                   2954: # ----------- Determine decrements required in aggregate totals 
                   2955: sub decrement_aggs {
                   2956:     my ($symb,$part,$aggregate,$aggtries,$totaltries,$solvedstatus) = @_;
                   2957:     my %decrement = (
                   2958:                         attempts => 0,
                   2959:                         users => 0,
                   2960:                         correct => 0
                   2961:                     );
                   2962:     $decrement{'attempts'} = $aggtries;
                   2963:     if ($solvedstatus =~ /^correct/) {
                   2964:         $decrement{'correct'} = 1;
                   2965:     }
                   2966:     if ($aggtries == $totaltries) {
                   2967:         $decrement{'users'} = 1;
                   2968:     }
1.524     raeburn  2969:     foreach my $type (keys(%decrement)) {
1.269     raeburn  2970:         $$aggregate{$symb."\0".$part."\0".$type} = -$decrement{$type};
                   2971:     }
                   2972:     return;
                   2973: }
                   2974: 
                   2975: # ----------- Determine timestamps for last reset of aggregate totals for parts  
                   2976: sub get_last_resets {
1.270     albertel 2977:     my ($symb,$courseid,$partids) =@_;
                   2978:     my %last_resets;
1.269     raeburn  2979:     my $cdom = $env{'course.'.$courseid.'.domain'};
                   2980:     my $cname = $env{'course.'.$courseid.'.num'};
1.271     albertel 2981:     my @keys;
                   2982:     foreach my $part (@{$partids}) {
                   2983: 	push(@keys,"$symb\0$part\0resettime");
                   2984:     }
                   2985:     my %results=&Apache::lonnet::get('nohist_resourcetracker',\@keys,
                   2986: 				     $cdom,$cname);
                   2987:     foreach my $part (@{$partids}) {
                   2988: 	$last_resets{$part}=$results{"$symb\0$part\0resettime"};
1.269     raeburn  2989:     }
1.270     albertel 2990:     return %last_resets;
1.269     raeburn  2991: }
                   2992: 
1.251     banghart 2993: # ----------- Handles creating versions for portfolio files as answers
                   2994: sub version_portfiles {
1.343     banghart 2995:     my ($record, $parts_graded, $courseid, $symb, $domain, $stu_name, $v_flag) = @_;
1.263     banghart 2996:     my $version_parts = join('|',@$v_flag);
1.343     banghart 2997:     my @returned_keys;
1.255     banghart 2998:     my $parts = join('|', @$parts_graded);
1.517     raeburn  2999:     my $portfolio_root = '/userfiles/portfolio';
1.277     albertel 3000:     foreach my $key (keys(%$record)) {
1.259     banghart 3001:         my $new_portfiles;
1.263     banghart 3002:         if ($key =~ /^resource\.($version_parts)\./ && $key =~ /\.portfiles$/ ) {
1.342     banghart 3003:             my @versioned_portfiles;
1.367     albertel 3004:             my @portfiles = split(/\s*,\s*/,$$record{$key});
1.252     banghart 3005:             foreach my $file (@portfiles) {
1.306     banghart 3006:                 &Apache::lonnet::unmark_as_readonly($domain,$stu_name,[$symb,$env{'request.course.id'}],$file);
1.304     albertel 3007:                 my ($directory,$answer_file) =($file =~ /^(.*?)([^\/]*)$/);
                   3008: 		my ($answer_name,$answer_ver,$answer_ext) =
                   3009: 		    &file_name_version_ext($answer_file);
1.517     raeburn  3010:                 my $getpropath = 1;    
                   3011:                 my @dir_list = &Apache::lonnet::dirlist($portfolio_root.$directory,$domain,$stu_name,$getpropath);
1.342     banghart 3012:                 my $version = &get_next_version($answer_name, $answer_ext, \@dir_list);
1.306     banghart 3013:                 my $new_answer = &version_selected_portfile($domain, $stu_name, $directory, $answer_file, $version);
                   3014:                 if ($new_answer ne 'problem getting file') {
1.342     banghart 3015:                     push(@versioned_portfiles, $directory.$new_answer);
1.306     banghart 3016:                     &Apache::lonnet::mark_as_readonly($domain,$stu_name,
1.367     albertel 3017:                         [$directory.$new_answer],
1.306     banghart 3018:                         [$symb,$env{'request.course.id'},'graded']);
1.259     banghart 3019:                 }
1.252     banghart 3020:             }
1.343     banghart 3021:             $$record{$key} = join(',',@versioned_portfiles);
                   3022:             push(@returned_keys,$key);
1.251     banghart 3023:         }
                   3024:     } 
1.343     banghart 3025:     return (@returned_keys);   
1.305     banghart 3026: }
                   3027: 
1.307     banghart 3028: sub get_next_version {
1.341     banghart 3029:     my ($answer_name, $answer_ext, $dir_list) = @_;
1.307     banghart 3030:     my $version;
                   3031:     foreach my $row (@$dir_list) {
                   3032:         my ($file) = split(/\&/,$row,2);
                   3033:         my ($file_name,$file_version,$file_ext) =
                   3034: 	    &file_name_version_ext($file);
                   3035:         if (($file_name eq $answer_name) && 
                   3036: 	    ($file_ext eq $answer_ext)) {
                   3037:                 # gets here if filename and extension match, regardless of version
                   3038:                 if ($file_version ne '') {
                   3039:                 # a versioned file is found  so save it for later
                   3040:                 if ($file_version > $version) {
                   3041: 		    $version = $file_version;
                   3042: 	        }
                   3043:             }
                   3044:         }
                   3045:     } 
                   3046:     $version ++;
                   3047:     return($version);
                   3048: }
                   3049: 
1.305     banghart 3050: sub version_selected_portfile {
1.306     banghart 3051:     my ($domain,$stu_name,$directory,$file_name,$version) = @_;
                   3052:     my ($answer_name,$answer_ver,$answer_ext) =
                   3053:         &file_name_version_ext($file_name);
                   3054:     my $new_answer;
                   3055:     $env{'form.copy'} = &Apache::lonnet::getfile("/uploaded/$domain/$stu_name/portfolio$directory$file_name");
                   3056:     if($env{'form.copy'} eq '-1') {
                   3057:         $new_answer = 'problem getting file';
                   3058:     } else {
                   3059:         $new_answer = $answer_name.'.'.$version.'.'.$answer_ext;
                   3060:         my $copy_result = &Apache::lonnet::finishuserfileupload(
                   3061:                             $stu_name,$domain,'copy',
                   3062: 		        '/portfolio'.$directory.$new_answer);
                   3063:     }    
                   3064:     return ($new_answer);
1.251     banghart 3065: }
                   3066: 
1.304     albertel 3067: sub file_name_version_ext {
                   3068:     my ($file)=@_;
                   3069:     my @file_parts = split(/\./, $file);
                   3070:     my ($name,$version,$ext);
                   3071:     if (@file_parts > 1) {
                   3072: 	$ext=pop(@file_parts);
                   3073: 	if (@file_parts > 1 && $file_parts[-1] =~ /^\d+$/) {
                   3074: 	    $version=pop(@file_parts);
                   3075: 	}
                   3076: 	$name=join('.',@file_parts);
                   3077:     } else {
                   3078: 	$name=join('.',@file_parts);
                   3079:     }
                   3080:     return($name,$version,$ext);
                   3081: }
                   3082: 
1.44      ng       3083: #--------------------------------------------------------------------------------------
                   3084: #
                   3085: #-------------------------- Next few routines handles grading by section or whole class
                   3086: #
                   3087: #--- Javascript to handle grading by section or whole class
1.42      ng       3088: sub viewgrades_js {
                   3089:     my ($request) = shift;
                   3090: 
1.539     riegler  3091:     my $alertmsg = &mt('A number equal or greater than 0 is expected. Entered value = ');
1.597     wenzelju 3092:     $request->print(&Apache::lonhtmlcommon::scripttag(<<VIEWJAVASCRIPT));
1.45      ng       3093:    function writePoint(partid,weight,point) {
1.125     ng       3094: 	var radioButton = document.classgrade["RADVAL_"+partid];
                   3095: 	var textbox = document.classgrade["TEXTVAL_"+partid];
1.42      ng       3096: 	if (point == "textval") {
1.125     ng       3097: 	    point = document.classgrade["TEXTVAL_"+partid].value;
1.109     matthew  3098: 	    if (isNaN(point) || parseFloat(point) < 0) {
1.539     riegler  3099: 		alert("$alertmsg"+parseFloat(point));
1.42      ng       3100: 		var resetbox = false;
                   3101: 		for (var i=0; i<radioButton.length; i++) {
                   3102: 		    if (radioButton[i].checked) {
                   3103: 			textbox.value = i;
                   3104: 			resetbox = true;
                   3105: 		    }
                   3106: 		}
                   3107: 		if (!resetbox) {
                   3108: 		    textbox.value = "";
                   3109: 		}
                   3110: 		return;
                   3111: 	    }
1.109     matthew  3112: 	    if (parseFloat(point) > parseFloat(weight)) {
                   3113: 		var resp = confirm("You entered a value ("+parseFloat(point)+
1.44      ng       3114: 				   ") greater than the weight for the part. Accept?");
                   3115: 		if (resp == false) {
                   3116: 		    textbox.value = "";
                   3117: 		    return;
                   3118: 		}
                   3119: 	    }
1.42      ng       3120: 	    for (var i=0; i<radioButton.length; i++) {
                   3121: 		radioButton[i].checked=false;
1.109     matthew  3122: 		if (parseFloat(point) == i) {
1.42      ng       3123: 		    radioButton[i].checked=true;
                   3124: 		}
                   3125: 	    }
1.41      ng       3126: 
1.42      ng       3127: 	} else {
1.125     ng       3128: 	    textbox.value = parseFloat(point);
1.42      ng       3129: 	}
1.41      ng       3130: 	for (i=0;i<document.classgrade.total.value;i++) {
1.125     ng       3131: 	    var user = document.classgrade["ctr"+i].value;
1.289     albertel 3132: 	    user = user.replace(new RegExp(':', 'g'),"_");
1.125     ng       3133: 	    var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
                   3134: 	    var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
                   3135: 	    var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
1.42      ng       3136: 	    if (saveval != "correct") {
                   3137: 		scorename.value = point;
1.43      ng       3138: 		if (selname[0].selected != true) {
                   3139: 		    selname[0].selected = true;
                   3140: 		}
1.42      ng       3141: 	    }
                   3142: 	}
1.125     ng       3143: 	document.classgrade["SELVAL_"+partid][0].selected = true;
1.42      ng       3144:     }
                   3145: 
                   3146:     function writeRadText(partid,weight) {
1.125     ng       3147: 	var selval   = document.classgrade["SELVAL_"+partid];
                   3148: 	var radioButton = document.classgrade["RADVAL_"+partid];
1.265     www      3149:         var override = document.classgrade["FORCE_"+partid].checked;
1.125     ng       3150: 	var textbox = document.classgrade["TEXTVAL_"+partid];
                   3151: 	if (selval[1].selected || selval[2].selected) {
1.42      ng       3152: 	    for (var i=0; i<radioButton.length; i++) {
                   3153: 		radioButton[i].checked=false;
                   3154: 
                   3155: 	    }
                   3156: 	    textbox.value = "";
                   3157: 
                   3158: 	    for (i=0;i<document.classgrade.total.value;i++) {
1.125     ng       3159: 		var user = document.classgrade["ctr"+i].value;
1.289     albertel 3160: 		user = user.replace(new RegExp(':', 'g'),"_");
1.125     ng       3161: 		var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
                   3162: 		var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
                   3163: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
1.265     www      3164: 		if ((saveval != "correct") || override) {
1.42      ng       3165: 		    scorename.value = "";
1.125     ng       3166: 		    if (selval[1].selected) {
                   3167: 			selname[1].selected = true;
                   3168: 		    } else {
                   3169: 			selname[2].selected = true;
                   3170: 			if (Number(document.classgrade["GD_"+user+"_"+partid+"_tries"].value)) 
                   3171: 			{document.classgrade["GD_"+user+"_"+partid+"_tries"].value = '0';}
                   3172: 		    }
1.42      ng       3173: 		}
                   3174: 	    }
1.43      ng       3175: 	} else {
                   3176: 	    for (i=0;i<document.classgrade.total.value;i++) {
1.125     ng       3177: 		var user = document.classgrade["ctr"+i].value;
1.289     albertel 3178: 		user = user.replace(new RegExp(':', 'g'),"_");
1.125     ng       3179: 		var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
                   3180: 		var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
                   3181: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
1.265     www      3182: 		if ((saveval != "correct") || override) {
1.125     ng       3183: 		    scorename.value = document.classgrade["GD_"+user+"_"+partid+"_awarded_s"].value;
1.43      ng       3184: 		    selname[0].selected = true;
                   3185: 		}
                   3186: 	    }
                   3187: 	}	    
1.42      ng       3188:     }
                   3189: 
                   3190:     function changeSelect(partid,user) {
1.125     ng       3191: 	var selval = document.classgrade["GD_"+user+'_'+partid+"_solved"];
                   3192: 	var textbox = document.classgrade["GD_"+user+'_'+partid+"_awarded"];
1.44      ng       3193: 	var point  = textbox.value;
1.125     ng       3194: 	var weight = document.classgrade["weight_"+partid].value;
1.44      ng       3195: 
1.109     matthew  3196: 	if (isNaN(point) || parseFloat(point) < 0) {
1.539     riegler  3197: 	    alert("$alertmsg"+parseFloat(point));
1.44      ng       3198: 	    textbox.value = "";
                   3199: 	    return;
                   3200: 	}
1.109     matthew  3201: 	if (parseFloat(point) > parseFloat(weight)) {
                   3202: 	    var resp = confirm("You entered a value ("+parseFloat(point)+
1.44      ng       3203: 			       ") greater than the weight of the part. Accept?");
                   3204: 	    if (resp == false) {
                   3205: 		textbox.value = "";
                   3206: 		return;
                   3207: 	    }
                   3208: 	}
1.42      ng       3209: 	selval[0].selected = true;
                   3210:     }
                   3211: 
                   3212:     function changeOneScore(partid,user) {
1.125     ng       3213: 	var selval = document.classgrade["GD_"+user+'_'+partid+"_solved"];
                   3214: 	if (selval[1].selected || selval[2].selected) {
                   3215: 	    document.classgrade["GD_"+user+'_'+partid+"_awarded"].value = "";
                   3216: 	    if (selval[2].selected) {
                   3217: 		document.classgrade["GD_"+user+'_'+partid+"_tries"].value = "0";
                   3218: 	    }
1.269     raeburn  3219:         }
1.42      ng       3220:     }
                   3221: 
                   3222:     function resetEntry(numpart) {
                   3223: 	for (ctpart=0;ctpart<numpart;ctpart++) {
1.125     ng       3224: 	    var partid = document.classgrade["partid_"+ctpart].value;
                   3225: 	    var radioButton = document.classgrade["RADVAL_"+partid];
                   3226: 	    var textbox = document.classgrade["TEXTVAL_"+partid];
                   3227: 	    var selval  = document.classgrade["SELVAL_"+partid];
1.42      ng       3228: 	    for (var i=0; i<radioButton.length; i++) {
                   3229: 		radioButton[i].checked=false;
                   3230: 
                   3231: 	    }
                   3232: 	    textbox.value = "";
                   3233: 	    selval[0].selected = true;
                   3234: 
                   3235: 	    for (i=0;i<document.classgrade.total.value;i++) {
1.125     ng       3236: 		var user = document.classgrade["ctr"+i].value;
1.289     albertel 3237: 		user = user.replace(new RegExp(':', 'g'),"_");
1.125     ng       3238: 		var resetscore = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
                   3239: 		resetscore.value = document.classgrade["GD_"+user+"_"+partid+"_awarded_s"].value;
                   3240: 		var resettries = document.classgrade["GD_"+user+"_"+partid+"_tries"];
                   3241: 		resettries.value = document.classgrade["GD_"+user+"_"+partid+"_tries_s"].value;
                   3242: 		var saveselval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
                   3243: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
1.42      ng       3244: 		if (saveselval == "excused") {
1.43      ng       3245: 		    if (selname[1].selected == false) { selname[1].selected = true;}
1.42      ng       3246: 		} else {
1.43      ng       3247: 		    if (selname[0].selected == false) {selname[0].selected = true};
1.42      ng       3248: 		}
                   3249: 	    }
1.41      ng       3250: 	}
1.42      ng       3251:     }
                   3252: 
1.41      ng       3253: VIEWJAVASCRIPT
1.42      ng       3254: }
                   3255: 
1.44      ng       3256: #--- show scores for a section or whole class w/ option to change/update a score
1.42      ng       3257: sub viewgrades {
1.608     www      3258:     my ($request,$symb) = @_;
1.42      ng       3259:     &viewgrades_js($request);
1.41      ng       3260: 
1.168     albertel 3261:     #need to make sure we have the correct data for later EXT calls, 
                   3262:     #thus invalidate the cache
                   3263:     &Apache::lonnet::devalidatecourseresdata(
1.257     albertel 3264:                  $env{'course.'.$env{'request.course.id'}.'.num'},
                   3265:                  $env{'course.'.$env{'request.course.id'}.'.domain'});
1.168     albertel 3266:     &Apache::lonnet::clear_EXT_cache_status();
                   3267: 
1.398     albertel 3268:     my $result='<h3><span class="LC_info">'.&mt('Manual Grading').'</span></h3>';
1.41      ng       3269: 
                   3270:     #view individual student submission form - called using Javascript viewOneStudent
1.324     albertel 3271:     $result.=&jscriptNform($symb);
1.41      ng       3272: 
1.44      ng       3273:     #beginning of class grading form
1.442     banghart 3274:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
1.41      ng       3275:     $result.= '<form action="/adm/grades" method="post" name="classgrade">'."\n".
1.418     albertel 3276: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.38      ng       3277: 	'<input type="hidden" name="command" value="editgrades" />'."\n".
1.432     banghart 3278: 	&build_section_inputs().
1.442     banghart 3279: 	'<input type="hidden" name="Status" value="'.$env{'stu_status'}.'" />'."\n".
1.72      ng       3280: 
1.560     raeburn  3281:     my ($common_header,$specific_header);
1.257     albertel 3282:     if ($env{'form.section'} eq 'all') {
1.560     raeburn  3283: 	$common_header = &mt('Assign Common Grade to Class');
                   3284:         $specific_header = &mt('Assign Grade to Specific Students in Class');
1.257     albertel 3285:     } elsif ($env{'form.section'} eq 'none') {
1.560     raeburn  3286:         $common_header = &mt('Assign Common Grade to Students in no Section');
                   3287: 	$specific_header = &mt('Assign Grade to Specific Students in no Section');
1.52      albertel 3288:     } else {
1.560     raeburn  3289:         my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
                   3290:         $common_header = &mt('Assign Common Grade to Students in Section(s) [_1]',$section_display);
                   3291: 	$specific_header = &mt('Assign Grade to Specific Students in Section(s) [_1]',$section_display);
1.52      albertel 3292:     }
1.560     raeburn  3293:     $result.= '<h3>'.$common_header.'</h3>'.&Apache::loncommon::start_data_table();
1.44      ng       3294:     #radio buttons/text box for assigning points for a section or class.
                   3295:     #handles different parts of a problem
1.582     raeburn  3296:     my $res_error;
                   3297:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
                   3298:     if ($res_error) {
                   3299:         return &navmap_errormsg();
                   3300:     }
1.42      ng       3301:     my %weight = ();
                   3302:     my $ctsparts = 0;
1.45      ng       3303:     my %seen = ();
1.375     albertel 3304:     my @part_response_id = &flatten_responseType($responseType);
                   3305:     foreach my $part_response_id (@part_response_id) {
                   3306:     	my ($partid,$respid) = @{ $part_response_id };
                   3307: 	my $part_resp = join('_',@{ $part_response_id });
1.45      ng       3308: 	next if $seen{$partid};
                   3309: 	$seen{$partid}++;
1.375     albertel 3310: 	my $handgrade=$$handgrade{$part_resp};
1.42      ng       3311: 	my $wgt = &Apache::lonnet::EXT('resource.'.$partid.'.weight',$symb);
                   3312: 	$weight{$partid} = $wgt eq '' ? '1' : $wgt;
                   3313: 
1.324     albertel 3314: 	my $display_part=&get_display_part($partid,$symb);
1.485     albertel 3315: 	my $radio.='<table border="0"><tr>';  
1.41      ng       3316: 	my $ctr = 0;
1.42      ng       3317: 	while ($ctr<=$weight{$partid}) { # display radio buttons in a nice table 10 across
1.485     albertel 3318: 	    $radio.= '<td><label><input type="radio" name="RADVAL_'.$partid.'" '.
1.54      albertel 3319: 		'onclick="javascript:writePoint(\''.$partid.'\','.$weight{$partid}.
1.288     albertel 3320: 		','.$ctr.')" />'.$ctr."</label></td>\n";
1.41      ng       3321: 	    $result.=(($ctr+1)%10 == 0 ? '</tr><tr>' : '');
                   3322: 	    $ctr++;
                   3323: 	}
1.485     albertel 3324: 	$radio.='</tr></table>';
                   3325: 	my $line = '<input type="text" name="TEXTVAL_'.
1.589     bisitz   3326: 	    $partid.'" size="4" '.'onchange="javascript:writePoint(\''.
1.54      albertel 3327: 		$partid.'\','.$weight{$partid}.',\'textval\')" /> /'.
1.539     riegler  3328: 	    $weight{$partid}.' '.&mt('(problem weight)').'</td>'."\n";
                   3329: 	$line.= '<td><b>'.&mt('Grade Status').':</b><select name="SELVAL_'.$partid.'"'.
1.589     bisitz   3330: 	    'onchange="javascript:writeRadText(\''.$partid.'\','.
1.59      albertel 3331: 		$weight{$partid}.')"> '.
1.401     albertel 3332: 	    '<option selected="selected"> </option>'.
1.485     albertel 3333: 	    '<option value="excused">'.&mt('excused').'</option>'.
                   3334: 	    '<option value="reset status">'.&mt('reset status').'</option>'.
                   3335: 	    '</select></td>'.
                   3336:             '<td><label><input type="checkbox" name="FORCE_'.$partid.'" />'.&mt('Override "Correct"').'</label>';
                   3337: 	$line.='<input type="hidden" name="partid_'.
                   3338: 	    $ctsparts.'" value="'.$partid.'" />'."\n";
                   3339: 	$line.='<input type="hidden" name="weight_'.
                   3340: 	    $partid.'" value="'.$weight{$partid}.'" />'."\n";
                   3341: 
                   3342: 	$result.=
                   3343: 	    &Apache::loncommon::start_data_table_row()."\n".
1.577     bisitz   3344: 	    '<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 3345: 	    &Apache::loncommon::end_data_table_row()."\n";
1.42      ng       3346: 	$ctsparts++;
1.41      ng       3347:     }
1.474     albertel 3348:     $result.=&Apache::loncommon::end_data_table()."\n".
1.52      albertel 3349: 	'<input type="hidden" name="totalparts" value="'.$ctsparts.'" />';
1.485     albertel 3350:     $result.='<input type="button" value="'.&mt('Revert to Default').'" '.
1.589     bisitz   3351: 	'onclick="javascript:resetEntry('.$ctsparts.');" />';
1.41      ng       3352: 
1.44      ng       3353:     #table listing all the students in a section/class
                   3354:     #header of table
1.560     raeburn  3355:     $result.= '<h3>'.$specific_header.'</h3>'.
                   3356:               &Apache::loncommon::start_data_table().
                   3357: 	      &Apache::loncommon::start_data_table_header_row().
                   3358: 	      '<th>'.&mt('No.').'</th>'.
                   3359: 	      '<th>'.&nameUserString('header')."</th>\n";
1.582     raeburn  3360:     my $partserror;
                   3361:     my (@parts) = sort(&getpartlist($symb,\$partserror));
                   3362:     if ($partserror) {
                   3363:         return &navmap_errormsg();
                   3364:     }
1.324     albertel 3365:     my (undef,undef,$url)=&Apache::lonnet::decode_symb($symb);
1.269     raeburn  3366:     my @partids = ();
1.41      ng       3367:     foreach my $part (@parts) {
                   3368: 	my $display=&Apache::lonnet::metadata($url,$part.'.display');
1.539     riegler  3369:         my $narrowtext = &mt('Tries');
                   3370: 	$display =~ s|^Number of Attempts|$narrowtext <br />|; # makes the column narrower
1.41      ng       3371: 	if  (!$display) { $display = &Apache::lonnet::metadata($url,$part.'.name'); }
1.207     albertel 3372: 	my ($partid) = &split_part_type($part);
1.524     raeburn  3373:         push(@partids,$partid);
1.324     albertel 3374: 	my $display_part=&get_display_part($partid,$symb);
1.41      ng       3375: 	if ($display =~ /^Partial Credit Factor/) {
1.485     albertel 3376: 	    $result.='<th>'.
                   3377: 		&mt('Score Part: [_1]<br /> (weight = [_2])',
                   3378: 		    $display_part,$weight{$partid}).'</th>'."\n";
1.41      ng       3379: 	    next;
1.485     albertel 3380: 	    
1.207     albertel 3381: 	} else {
1.485     albertel 3382: 	    if ($display =~ /Problem Status/) {
                   3383: 		my $grade_status_mt = &mt('Grade Status');
                   3384: 		$display =~ s{Problem Status}{$grade_status_mt<br />};
                   3385: 	    }
                   3386: 	    my $part_mt = &mt('Part:');
                   3387: 	    $display =~s{\[Part: \Q$partid\E\]}{$part_mt $display_part};
1.41      ng       3388: 	}
1.485     albertel 3389: 
1.474     albertel 3390: 	$result.='<th>'.$display.'</th>'."\n";
1.41      ng       3391:     }
1.474     albertel 3392:     $result.=&Apache::loncommon::end_data_table_header_row();
1.44      ng       3393: 
1.270     albertel 3394:     my %last_resets = 
                   3395: 	&get_last_resets($symb,$env{'request.course.id'},\@partids);
1.269     raeburn  3396: 
1.41      ng       3397:     #get info for each student
1.44      ng       3398:     #list all the students - with points and grade status
1.257     albertel 3399:     my (undef,undef,$fullname) = &getclasslist($env{'form.section'},'1');
1.41      ng       3400:     my $ctr = 0;
1.294     albertel 3401:     foreach (sort 
                   3402: 	     {
                   3403: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                   3404: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                   3405: 		 }
                   3406: 		 return $a cmp $b;
                   3407: 	     } (keys(%$fullname))) {
1.126     ng       3408: 	$ctr++;
1.324     albertel 3409: 	$result.=&viewstudentgrade($symb,$env{'request.course.id'},
1.269     raeburn  3410: 				   $_,$$fullname{$_},\@parts,\%weight,$ctr,\%last_resets);
1.41      ng       3411:     }
1.474     albertel 3412:     $result.=&Apache::loncommon::end_data_table();
1.41      ng       3413:     $result.='<input type="hidden" name="total" value="'.$ctr.'" />'."\n";
1.485     albertel 3414:     $result.='<input type="button" value="'.&mt('Save').'" '.
1.589     bisitz   3415: 	'onclick="javascript:submit();" target="_self" /></form>'."\n";
1.96      albertel 3416:     if (scalar(%$fullname) eq 0) {
                   3417: 	my $colspan=3+scalar(@parts);
1.433     banghart 3418: 	my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
1.442     banghart 3419:         my $stu_status = join(' or ',&Apache::loncommon::get_env_multiple('form.Status'));
1.433     banghart 3420: 	$result='<span class="LC_warning">'.
1.485     albertel 3421: 	    &mt('There are no students in section(s) [_1] with enrollment status [_2] to modify or grade.',
1.442     banghart 3422: 	        $section_display, $stu_status).
1.433     banghart 3423: 	    '</span>';
1.96      albertel 3424:     }
1.41      ng       3425:     return $result;
                   3426: }
                   3427: 
1.44      ng       3428: #--- call by previous routine to display each student
1.41      ng       3429: sub viewstudentgrade {
1.324     albertel 3430:     my ($symb,$courseid,$student,$fullname,$parts,$weight,$ctr,$last_resets) = @_;
1.44      ng       3431:     my ($uname,$udom) = split(/:/,$student);
                   3432:     my %record=&Apache::lonnet::restore($symb,$courseid,$udom,$uname);
1.269     raeburn  3433:     my %aggregates = (); 
1.474     albertel 3434:     my $result=&Apache::loncommon::start_data_table_row().'<td align="right">'.
1.233     albertel 3435: 	'<input type="hidden" name="ctr'.($ctr-1).'" value="'.$student.'" />'.
                   3436: 	"\n".$ctr.'&nbsp;</td><td>&nbsp;'.
1.44      ng       3437: 	'<a href="javascript:viewOneStudent(\''.$uname.'\',\''.$udom.
1.417     albertel 3438: 	'\');" target="_self">'.$fullname.'</a> '.
1.398     albertel 3439: 	'<span class="LC_internal_info">('.$uname.($env{'user.domain'} eq $udom ? '' : ':'.$udom).')</span></td>'."\n";
1.281     albertel 3440:     $student=~s/:/_/; # colon doen't work in javascript for names
1.63      albertel 3441:     foreach my $apart (@$parts) {
                   3442: 	my ($part,$type) = &split_part_type($apart);
1.41      ng       3443: 	my $score=$record{"resource.$part.$type"};
1.276     albertel 3444:         $result.='<td align="center">';
1.269     raeburn  3445:         my ($aggtries,$totaltries);
                   3446:         unless (exists($aggregates{$part})) {
1.270     albertel 3447: 	    $totaltries = $record{'resource.'.$part.'.tries'};
                   3448: 
                   3449: 	    $aggtries = $totaltries;
1.269     raeburn  3450:             if ($$last_resets{$part}) {  
1.270     albertel 3451:                 $aggtries = &get_num_tries(\%record,$$last_resets{$part},
                   3452: 					   $part);
                   3453:             }
1.269     raeburn  3454:             $result.='<input type="hidden" name="'.
                   3455:                 'GD_'.$student.'_'.$part.'_aggtries" value="'.$aggtries.'" />'."\n";
                   3456:             $result.='<input type="hidden" name="'.
                   3457:                 'GD_'.$student.'_'.$part.'_totaltries" value="'.$totaltries.'" />'."\n";
                   3458:             $aggregates{$part} = 1;
                   3459:         }
1.41      ng       3460: 	if ($type eq 'awarded') {
1.320     albertel 3461: 	    my $pts = $score eq '' ? '' : &compute_points($score,$$weight{$part});
1.42      ng       3462: 	    $result.='<input type="hidden" name="'.
1.89      albertel 3463: 		'GD_'.$student.'_'.$part.'_awarded_s" value="'.$pts.'" />'."\n";
1.233     albertel 3464: 	    $result.='<input type="text" name="'.
1.89      albertel 3465: 		'GD_'.$student.'_'.$part.'_awarded" '.
1.589     bisitz   3466:                 'onchange="javascript:changeSelect(\''.$part.'\',\''.$student.
1.44      ng       3467: 		'\')" value="'.$pts.'" size="4" /></td>'."\n";
1.41      ng       3468: 	} elsif ($type eq 'solved') {
                   3469: 	    my ($status,$foo)=split(/_/,$score,2);
                   3470: 	    $status = 'nothing' if ($status eq '');
1.89      albertel 3471: 	    $result.='<input type="hidden" name="'.'GD_'.$student.'_'.
1.54      albertel 3472: 		$part.'_solved_s" value="'.$status.'" />'."\n";
1.233     albertel 3473: 	    $result.='&nbsp;<select name="'.
1.89      albertel 3474: 		'GD_'.$student.'_'.$part.'_solved" '.
1.589     bisitz   3475:                 'onchange="javascript:changeOneScore(\''.$part.'\',\''.$student.'\')" >'."\n";
1.485     albertel 3476: 	    $result.= (($status eq 'excused') ? '<option> </option><option selected="selected" value="excused">'.&mt('excused').'</option>' 
                   3477: 		: '<option selected="selected"> </option><option value="excused">'.&mt('excused').'</option>')."\n";
                   3478: 	    $result.='<option value="reset status">'.&mt('reset status').'</option>';
1.126     ng       3479: 	    $result.="</select>&nbsp;</td>\n";
1.122     ng       3480: 	} else {
                   3481: 	    $result.='<input type="hidden" name="'.
                   3482: 		'GD_'.$student.'_'.$part.'_'.$type.'_s" value="'.$score.'" />'.
                   3483: 		    "\n";
1.233     albertel 3484: 	    $result.='<input type="text" name="'.
1.122     ng       3485: 		'GD_'.$student.'_'.$part.'_'.$type.'" '.
                   3486: 		'value="'.$score.'" size="4" /></td>'."\n";
1.41      ng       3487: 	}
                   3488:     }
1.474     albertel 3489:     $result.=&Apache::loncommon::end_data_table_row();
1.41      ng       3490:     return $result;
1.38      ng       3491: }
                   3492: 
1.44      ng       3493: #--- change scores for all the students in a section/class
                   3494: #    record does not get update if unchanged
1.38      ng       3495: sub editgrades {
1.608     www      3496:     my ($request,$symb) = @_;
1.41      ng       3497: 
1.433     banghart 3498:     my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
1.477     albertel 3499:     my $title='<h2>'.&mt('Current Grade Status').'</h2>';
1.433     banghart 3500:     $title.='<h4>'.&mt('<b>Section: </b>[_1]',$section_display).'</h4>'."\n";
1.126     ng       3501: 
1.477     albertel 3502:     my $result= &Apache::loncommon::start_data_table().
                   3503: 	&Apache::loncommon::start_data_table_header_row().
                   3504: 	'<th rowspan="2" valign="middle">'.&mt('No.').'</th>'.
                   3505: 	'<th rowspan="2" valign="middle">'.&nameUserString('header')."</th>\n";
1.43      ng       3506:     my %scoreptr = (
                   3507: 		    'correct'  =>'correct_by_override',
                   3508: 		    'incorrect'=>'incorrect_by_override',
                   3509: 		    'excused'  =>'excused',
                   3510: 		    'ungraded' =>'ungraded_attempted',
1.596     raeburn  3511:                     'credited' =>'credit_attempted',
1.43      ng       3512: 		    'nothing'  => '',
                   3513: 		    );
1.257     albertel 3514:     my ($classlist,undef,$fullname) = &getclasslist($env{'form.section'},'0');
1.34      ng       3515: 
1.44      ng       3516:     my (@partid);
                   3517:     my %weight = ();
1.54      albertel 3518:     my %columns = ();
1.44      ng       3519:     my ($i,$ctr,$count,$rec_update) = (0,0,0,0);
1.54      albertel 3520: 
1.582     raeburn  3521:     my $partserror;
                   3522:     my (@parts) = sort(&getpartlist($symb,\$partserror));
                   3523:     if ($partserror) {
                   3524:         return &navmap_errormsg();
                   3525:     }
1.54      albertel 3526:     my $header;
1.257     albertel 3527:     while ($ctr < $env{'form.totalparts'}) {
                   3528: 	my $partid = $env{'form.partid_'.$ctr};
1.524     raeburn  3529: 	push(@partid,$partid);
1.257     albertel 3530: 	$weight{$partid} = $env{'form.weight_'.$partid};
1.44      ng       3531: 	$ctr++;
1.54      albertel 3532:     }
1.324     albertel 3533:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
1.54      albertel 3534:     foreach my $partid (@partid) {
1.478     albertel 3535: 	$header .= '<th align="center">'.&mt('Old Score').'</th>'.
                   3536: 	    '<th align="center">'.&mt('New Score').'</th>';
1.54      albertel 3537: 	$columns{$partid}=2;
                   3538: 	foreach my $stores (@parts) {
                   3539: 	    my ($part,$type) = &split_part_type($stores);
                   3540: 	    if ($part !~ m/^\Q$partid\E/) { next;}
                   3541: 	    if ($type eq 'awarded' || $type eq 'solved') { next; }
                   3542: 	    my $display=&Apache::lonnet::metadata($url,$stores.'.display');
1.551     raeburn  3543: 	    $display =~ s/\[Part: \Q$part\E\]//;
1.539     riegler  3544:             my $narrowtext = &mt('Tries');
                   3545: 	    $display =~ s/Number of Attempts/$narrowtext/;
                   3546: 	    $header .= '<th align="center">'.&mt('Old').' '.$display.'</th>'.
                   3547: 		'<th align="center">'.&mt('New').' '.$display.'</th>';
1.54      albertel 3548: 	    $columns{$partid}+=2;
                   3549: 	}
                   3550:     }
                   3551:     foreach my $partid (@partid) {
1.324     albertel 3552: 	my $display_part=&get_display_part($partid,$symb);
1.478     albertel 3553: 	$result .= '<th colspan="'.$columns{$partid}.'" align="center">'.
                   3554: 	    &mt('Part: [_1] (Weight = [_2])',$display_part,$weight{$partid}).
                   3555: 	    '</th>';
1.54      albertel 3556: 
1.44      ng       3557:     }
1.477     albertel 3558:     $result .= &Apache::loncommon::end_data_table_header_row().
                   3559: 	&Apache::loncommon::start_data_table_header_row().
                   3560: 	$header.
                   3561: 	&Apache::loncommon::end_data_table_header_row();
                   3562:     my @noupdate;
1.126     ng       3563:     my ($updateCtr,$noupdateCtr) = (1,1);
1.257     albertel 3564:     for ($i=0; $i<$env{'form.total'}; $i++) {
1.93      albertel 3565: 	my $line;
1.257     albertel 3566: 	my $user = $env{'form.ctr'.$i};
1.281     albertel 3567: 	my ($uname,$udom)=split(/:/,$user);
1.44      ng       3568: 	my %newrecord;
                   3569: 	my $updateflag = 0;
1.281     albertel 3570: 	$line .= '<td>'.&nameUserString(undef,$$fullname{$user},$uname,$udom).'</td>';
1.108     albertel 3571: 	my $usec=$classlist->{"$uname:$udom"}[5];
1.105     albertel 3572: 	if (!&canmodify($usec)) {
1.126     ng       3573: 	    my $numcols=scalar(@partid)*4+2;
1.477     albertel 3574: 	    push(@noupdate,
1.478     albertel 3575: 		 $line."<td colspan=\"$numcols\"><span class=\"LC_warning\">".
                   3576: 		 &mt('Not allowed to modify student')."</span></td></tr>");
1.105     albertel 3577: 	    next;
                   3578: 	}
1.269     raeburn  3579:         my %aggregate = ();
                   3580:         my $aggregateflag = 0;
1.281     albertel 3581: 	$user=~s/:/_/; # colon doen't work in javascript for names
1.44      ng       3582: 	foreach (@partid) {
1.257     albertel 3583: 	    my $old_aw    = $env{'form.GD_'.$user.'_'.$_.'_awarded_s'};
1.54      albertel 3584: 	    my $old_part_pcr = $old_aw/($weight{$_} ne '0' ? $weight{$_}:1);
                   3585: 	    my $old_part  = $old_aw eq '' ? '' : $old_part_pcr;
1.257     albertel 3586: 	    my $old_score = $scoreptr{$env{'form.GD_'.$user.'_'.$_.'_solved_s'}};
                   3587: 	    my $awarded   = $env{'form.GD_'.$user.'_'.$_.'_awarded'};
1.54      albertel 3588: 	    my $pcr       = $awarded/($weight{$_} ne '0' ? $weight{$_} : 1);
                   3589: 	    my $partial   = $awarded eq '' ? '' : $pcr;
1.44      ng       3590: 	    my $score;
                   3591: 	    if ($partial eq '') {
1.257     albertel 3592: 		$score = $scoreptr{$env{'form.GD_'.$user.'_'.$_.'_solved_s'}};
1.44      ng       3593: 	    } elsif ($partial > 0) {
                   3594: 		$score = 'correct_by_override';
                   3595: 	    } elsif ($partial == 0) {
                   3596: 		$score = 'incorrect_by_override';
                   3597: 	    }
1.257     albertel 3598: 	    my $dropMenu = $env{'form.GD_'.$user.'_'.$_.'_solved'};
1.125     ng       3599: 	    $score = 'excused' if (($dropMenu eq 'excused') && ($score ne 'excused'));
                   3600: 
1.292     albertel 3601: 	    $newrecord{'resource.'.$_.'.regrader'}=
                   3602: 		"$env{'user.name'}:$env{'user.domain'}";
1.125     ng       3603: 	    if ($dropMenu eq 'reset status' &&
                   3604: 		$old_score ne '') { # ignore if no previous attempts => nothing to reset
1.299     albertel 3605: 		$newrecord{'resource.'.$_.'.tries'} = '';
1.125     ng       3606: 		$newrecord{'resource.'.$_.'.solved'} = '';
                   3607: 		$newrecord{'resource.'.$_.'.award'} = '';
1.299     albertel 3608: 		$newrecord{'resource.'.$_.'.awarded'} = '';
1.125     ng       3609: 		$updateflag = 1;
1.269     raeburn  3610:                 if ($env{'form.GD_'.$user.'_'.$_.'_aggtries'} > 0) {
                   3611:                     my $aggtries = $env{'form.GD_'.$user.'_'.$_.'_aggtries'};
                   3612:                     my $totaltries = $env{'form.GD_'.$user.'_'.$_.'_totaltries'};
                   3613:                     my $solvedstatus = $env{'form.GD_'.$user.'_'.$_.'_solved_s'};
                   3614:                     &decrement_aggs($symb,$_,\%aggregate,$aggtries,$totaltries,$solvedstatus);
                   3615:                     $aggregateflag = 1;
                   3616:                 }
1.139     albertel 3617: 	    } elsif (!($old_part eq $partial && $old_score eq $score)) {
                   3618: 		$updateflag = 1;
                   3619: 		$newrecord{'resource.'.$_.'.awarded'}  = $partial if $partial ne '';
                   3620: 		$newrecord{'resource.'.$_.'.solved'}   = $score;
                   3621: 		$rec_update++;
1.125     ng       3622: 	    }
                   3623: 
1.93      albertel 3624: 	    $line .= '<td align="center">'.$old_aw.'&nbsp;</td>'.
1.44      ng       3625: 		'<td align="center">'.$awarded.
                   3626: 		($score eq 'excused' ? $score : '').'&nbsp;</td>';
1.5       albertel 3627: 
1.54      albertel 3628: 
                   3629: 	    my $partid=$_;
                   3630: 	    foreach my $stores (@parts) {
                   3631: 		my ($part,$type) = &split_part_type($stores);
                   3632: 		if ($part !~ m/^\Q$partid\E/) { next;}
                   3633: 		if ($type eq 'awarded' || $type eq 'solved') { next; }
1.257     albertel 3634: 		my $old_aw    = $env{'form.GD_'.$user.'_'.$part.'_'.$type.'_s'};
                   3635: 		my $awarded   = $env{'form.GD_'.$user.'_'.$part.'_'.$type};
1.54      albertel 3636: 		if ($awarded ne '' && $awarded ne $old_aw) {
                   3637: 		    $newrecord{'resource.'.$part.'.'.$type}= $awarded;
1.257     albertel 3638: 		    $newrecord{'resource.'.$part.'.regrader'}="$env{'user.name'}:$env{'user.domain'}";
1.54      albertel 3639: 		    $updateflag=1;
                   3640: 		}
1.93      albertel 3641: 		$line .= '<td align="center">'.$old_aw.'&nbsp;</td>'.
1.54      albertel 3642: 		    '<td align="center">'.$awarded.'&nbsp;</td>';
                   3643: 	    }
1.44      ng       3644: 	}
1.477     albertel 3645: 	$line.="\n";
1.301     albertel 3646: 
                   3647: 	my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   3648: 	my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   3649: 
1.44      ng       3650: 	if ($updateflag) {
                   3651: 	    $count++;
1.257     albertel 3652: 	    &Apache::lonnet::cstore(\%newrecord,$symb,$env{'request.course.id'},
1.89      albertel 3653: 				    $udom,$uname);
1.301     albertel 3654: 
                   3655: 	    if (&Apache::bridgetask::in_queue('gradingqueue',$symb,$cdom,
                   3656: 					      $cnum,$udom,$uname)) {
                   3657: 		# need to figure out if should be in queue.
                   3658: 		my %record =  
                   3659: 		    &Apache::lonnet::restore($symb,$env{'request.course.id'},
                   3660: 					     $udom,$uname);
                   3661: 		my $all_graded = 1;
                   3662: 		my $none_graded = 1;
                   3663: 		foreach my $part (@parts) {
                   3664: 		    if ( $record{'resource.'.$part.'.awarded'} eq '' ) {
                   3665: 			$all_graded = 0;
                   3666: 		    } else {
                   3667: 			$none_graded = 0;
                   3668: 		    }
                   3669: 		}
                   3670: 
                   3671: 		if ($all_graded || $none_graded) {
                   3672: 		    &Apache::bridgetask::remove_from_queue('gradingqueue',
                   3673: 							   $symb,$cdom,$cnum,
                   3674: 							   $udom,$uname);
                   3675: 		}
                   3676: 	    }
                   3677: 
1.477     albertel 3678: 	    $result.=&Apache::loncommon::start_data_table_row().
                   3679: 		'<td align="right">&nbsp;'.$updateCtr.'&nbsp;</td>'.$line.
                   3680: 		&Apache::loncommon::end_data_table_row();
1.126     ng       3681: 	    $updateCtr++;
1.93      albertel 3682: 	} else {
1.477     albertel 3683: 	    push(@noupdate,
                   3684: 		 '<td align="right">&nbsp;'.$noupdateCtr.'&nbsp;</td>'.$line);
1.126     ng       3685: 	    $noupdateCtr++;
1.44      ng       3686: 	}
1.269     raeburn  3687:         if ($aggregateflag) {
                   3688:             &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
1.301     albertel 3689: 				  $cdom,$cnum);
1.269     raeburn  3690:         }
1.93      albertel 3691:     }
1.477     albertel 3692:     if (@noupdate) {
1.126     ng       3693: #	my $numcols=(scalar(@partid)*(scalar(@parts)-1)*2)+3;
                   3694: 	my $numcols=scalar(@partid)*4+2;
1.477     albertel 3695: 	$result .= &Apache::loncommon::start_data_table_row('LC_empty_row').
1.478     albertel 3696: 	    '<td align="center" colspan="'.$numcols.'">'.
                   3697: 	    &mt('No Changes Occurred For the Students Below').
                   3698: 	    '</td>'.
1.477     albertel 3699: 	    &Apache::loncommon::end_data_table_row();
                   3700: 	foreach my $line (@noupdate) {
                   3701: 	    $result.=
                   3702: 		&Apache::loncommon::start_data_table_row().
                   3703: 		$line.
                   3704: 		&Apache::loncommon::end_data_table_row();
                   3705: 	}
1.44      ng       3706:     }
1.614     www      3707:     $result .= &Apache::loncommon::end_data_table();
1.478     albertel 3708:     my $msg = '<p><b>'.
                   3709: 	&mt('Number of records updated = [_1] for [quant,_2,student].',
                   3710: 	    $rec_update,$count).'</b><br />'.
                   3711: 	'<b>'.&mt('Total number of students = [_1]',$env{'form.total'}).
                   3712: 	'</b></p>';
1.44      ng       3713:     return $title.$msg.$result;
1.5       albertel 3714: }
1.54      albertel 3715: 
                   3716: sub split_part_type {
                   3717:     my ($partstr) = @_;
                   3718:     my ($temp,@allparts)=split(/_/,$partstr);
                   3719:     my $type=pop(@allparts);
1.439     albertel 3720:     my $part=join('_',@allparts);
1.54      albertel 3721:     return ($part,$type);
                   3722: }
                   3723: 
1.44      ng       3724: #------------- end of section for handling grading by section/class ---------
                   3725: #
                   3726: #----------------------------------------------------------------------------
                   3727: 
1.5       albertel 3728: 
1.44      ng       3729: #----------------------------------------------------------------------------
                   3730: #
                   3731: #-------------------------- Next few routines handles grading by csv upload
                   3732: #
                   3733: #--- Javascript to handle csv upload
1.27      albertel 3734: sub csvupload_javascript_reverse_associate {
1.573     bisitz   3735:     my $error1=&mt('You need to specify the username or the student/employee ID');
1.246     albertel 3736:     my $error2=&mt('You need to specify at least one grading field');
1.27      albertel 3737:   return(<<ENDPICK);
                   3738:   function verify(vf) {
                   3739:     var foundsomething=0;
                   3740:     var founduname=0;
1.243     albertel 3741:     var foundID=0;
1.27      albertel 3742:     for (i=0;i<=vf.nfields.value;i++) {
                   3743:       tw=eval('vf.f'+i+'.selectedIndex');
1.243     albertel 3744:       if (i==0 && tw!=0) { foundID=1; }
                   3745:       if (i==1 && tw!=0) { founduname=1; }
                   3746:       if (i!=0 && i!=1 && i!=2 && tw!=0) { foundsomething=1; }
1.27      albertel 3747:     }
1.246     albertel 3748:     if (founduname==0 && foundID==0) {
                   3749: 	alert('$error1');
                   3750: 	return;
1.27      albertel 3751:     }
                   3752:     if (foundsomething==0) {
1.246     albertel 3753: 	alert('$error2');
                   3754: 	return;
1.27      albertel 3755:     }
                   3756:     vf.submit();
                   3757:   }
                   3758:   function flip(vf,tf) {
                   3759:     var nw=eval('vf.f'+tf+'.selectedIndex');
                   3760:     var i;
                   3761:     for (i=0;i<=vf.nfields.value;i++) {
                   3762:       //can not pick the same destination field for both name and domain
                   3763:       if (((i ==0)||(i ==1)) && 
                   3764:           ((tf==0)||(tf==1)) && 
                   3765:           (i!=tf) &&
                   3766:           (eval('vf.f'+i+'.selectedIndex')==nw)) {
                   3767:         eval('vf.f'+i+'.selectedIndex=0;')
                   3768:       }
                   3769:     }
                   3770:   }
                   3771: ENDPICK
                   3772: }
                   3773: 
                   3774: sub csvupload_javascript_forward_associate {
1.573     bisitz   3775:     my $error1=&mt('You need to specify the username or the student/employee ID');
1.246     albertel 3776:     my $error2=&mt('You need to specify at least one grading field');
1.27      albertel 3777:   return(<<ENDPICK);
                   3778:   function verify(vf) {
                   3779:     var foundsomething=0;
                   3780:     var founduname=0;
1.243     albertel 3781:     var foundID=0;
1.27      albertel 3782:     for (i=0;i<=vf.nfields.value;i++) {
                   3783:       tw=eval('vf.f'+i+'.selectedIndex');
1.243     albertel 3784:       if (tw==1) { foundID=1; }
                   3785:       if (tw==2) { founduname=1; }
                   3786:       if (tw>3) { foundsomething=1; }
1.27      albertel 3787:     }
1.246     albertel 3788:     if (founduname==0 && foundID==0) {
                   3789: 	alert('$error1');
                   3790: 	return;
1.27      albertel 3791:     }
                   3792:     if (foundsomething==0) {
1.246     albertel 3793: 	alert('$error2');
                   3794: 	return;
1.27      albertel 3795:     }
                   3796:     vf.submit();
                   3797:   }
                   3798:   function flip(vf,tf) {
                   3799:     var nw=eval('vf.f'+tf+'.selectedIndex');
                   3800:     var i;
                   3801:     //can not pick the same destination field twice
                   3802:     for (i=0;i<=vf.nfields.value;i++) {
                   3803:       if ((i!=tf) && (eval('vf.f'+i+'.selectedIndex')==nw)) {
                   3804:         eval('vf.f'+i+'.selectedIndex=0;')
                   3805:       }
                   3806:     }
                   3807:   }
                   3808: ENDPICK
                   3809: }
                   3810: 
1.26      albertel 3811: sub csvuploadmap_header {
1.324     albertel 3812:     my ($request,$symb,$datatoken,$distotal)= @_;
1.41      ng       3813:     my $javascript;
1.257     albertel 3814:     if ($env{'form.upfile_associate'} eq 'reverse') {
1.41      ng       3815: 	$javascript=&csvupload_javascript_reverse_associate();
                   3816:     } else {
                   3817: 	$javascript=&csvupload_javascript_forward_associate();
                   3818:     }
1.45      ng       3819: 
1.598     www      3820:     my $result='';
1.257     albertel 3821:     my $checked=(($env{'form.noFirstLine'})?' checked="checked"':'');
1.245     albertel 3822:     my $ignore=&mt('Ignore First Line');
1.418     albertel 3823:     $symb = &Apache::lonenc::check_encrypt($symb);
1.41      ng       3824:     $request->print(<<ENDPICK);
1.26      albertel 3825: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
1.398     albertel 3826: <h3><span class="LC_info">Uploading Class Grades</span></h3>
1.45      ng       3827: $result
1.326     albertel 3828: <hr />
1.26      albertel 3829: <h3>Identify fields</h3>
                   3830: Total number of records found in file: $distotal <hr />
                   3831: Enter as many fields as you can. The system will inform you and bring you back
                   3832: to this page if the data selected is insufficient to run your class.<hr />
1.589     bisitz   3833: <input type="button" value="Reverse Association" onclick="javascript:this.form.associate.value='Reverse Association';submit(this.form);" />
1.245     albertel 3834: <label><input type="checkbox" name="noFirstLine" $checked />$ignore</label>
1.26      albertel 3835: <input type="hidden" name="associate"  value="" />
                   3836: <input type="hidden" name="phase"      value="three" />
                   3837: <input type="hidden" name="datatoken"  value="$datatoken" />
1.257     albertel 3838: <input type="hidden" name="fileupload" value="$env{'form.fileupload'}" />
                   3839: <input type="hidden" name="upfiletype" value="$env{'form.upfiletype'}" />
1.26      albertel 3840: <input type="hidden" name="upfile_associate" 
1.257     albertel 3841:                                        value="$env{'form.upfile_associate'}" />
1.26      albertel 3842: <input type="hidden" name="symb"       value="$symb" />
1.246     albertel 3843: <input type="hidden" name="command"    value="csvuploadoptions" />
1.26      albertel 3844: <hr />
                   3845: ENDPICK
1.597     wenzelju 3846:     $request->print(&Apache::lonhtmlcommon::scripttag($javascript));
1.118     ng       3847:     return '';
1.26      albertel 3848: 
                   3849: }
                   3850: 
                   3851: sub csvupload_fields {
1.582     raeburn  3852:     my ($symb,$errorref) = @_;
                   3853:     my (@parts) = &getpartlist($symb,$errorref);
                   3854:     if (ref($errorref)) {
                   3855:         if ($$errorref) {
                   3856:             return;
                   3857:         }
                   3858:     }
                   3859: 
1.556     weissno  3860:     my @fields=(['ID','Student/Employee ID'],
1.243     albertel 3861: 		['username','Student Username'],
                   3862: 		['domain','Student Domain']);
1.324     albertel 3863:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
1.41      ng       3864:     foreach my $part (sort(@parts)) {
                   3865: 	my @datum;
                   3866: 	my $display=&Apache::lonnet::metadata($url,$part.'.display');
                   3867: 	my $name=$part;
                   3868: 	if  (!$display) { $display = $name; }
                   3869: 	@datum=($name,$display);
1.244     albertel 3870: 	if ($name=~/^stores_(.*)_awarded/) {
                   3871: 	    push(@fields,['stores_'.$1.'_points',"Points [Part: $1]"]);
                   3872: 	}
1.41      ng       3873: 	push(@fields,\@datum);
                   3874:     }
                   3875:     return (@fields);
1.26      albertel 3876: }
                   3877: 
                   3878: sub csvuploadmap_footer {
1.41      ng       3879:     my ($request,$i,$keyfields) =@_;
                   3880:     $request->print(<<ENDPICK);
1.26      albertel 3881: </table>
                   3882: <input type="hidden" name="nfields" value="$i" />
                   3883: <input type="hidden" name="keyfields" value="$keyfields" />
1.589     bisitz   3884: <input type="button" onclick="javascript:verify(this.form)" value="Assign Grades" /><br />
1.26      albertel 3885: </form>
                   3886: ENDPICK
                   3887: }
                   3888: 
1.283     albertel 3889: sub checkforfile_js {
1.539     riegler  3890:     my $alertmsg = &mt('Please use the browse button to select a file from your local directory.');
1.597     wenzelju 3891:     my $result = &Apache::lonhtmlcommon::scripttag(<<CSVFORMJS);
1.86      ng       3892:     function checkUpload(formname) {
                   3893: 	if (formname.upfile.value == "") {
1.539     riegler  3894: 	    alert("$alertmsg");
1.86      ng       3895: 	    return false;
                   3896: 	}
                   3897: 	formname.submit();
                   3898:     }
                   3899: CSVFORMJS
1.283     albertel 3900:     return $result;
                   3901: }
                   3902: 
                   3903: sub upcsvScores_form {
1.608     www      3904:     my ($request,$symb) = @_;
1.283     albertel 3905:     if (!$symb) {return '';}
                   3906:     my $result=&checkforfile_js();
1.326     albertel 3907:     $result.='<br /><table width="100%" border="0"><tr><td bgcolor="#777777">'."\n";
                   3908:     $result.='<table width="100%" border="0"><tr bgcolor="#e6ffff"><td>'."\n";
1.538     schulted 3909:     $result.='&nbsp;<b>'.&mt('Specify a file containing the class scores for current resource.').
                   3910: 	'</b></td></tr>'."\n";
1.86      ng       3911:     $result.='<tr bgcolor=#ffffe6><td>'."\n";
1.370     www      3912:     my $upload=&mt("Upload Scores");
1.86      ng       3913:     my $upfile_select=&Apache::loncommon::upfile_select_html();
1.245     albertel 3914:     my $ignore=&mt('Ignore First Line');
1.418     albertel 3915:     $symb = &Apache::lonenc::check_encrypt($symb);
1.86      ng       3916:     $result.=<<ENDUPFORM;
1.106     albertel 3917: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
1.86      ng       3918: <input type="hidden" name="symb" value="$symb" />
                   3919: <input type="hidden" name="command" value="csvuploadmap" />
                   3920: $upfile_select
1.589     bisitz   3921: <br /><input type="button" onclick="javascript:checkUpload(this.form);" value="$upload" />
1.283     albertel 3922: <label><input type="checkbox" name="noFirstLine" />$ignore</label>
1.86      ng       3923: </form>
                   3924: ENDUPFORM
1.370     www      3925:     $result.=&Apache::loncommon::help_open_topic("Course_Convert_To_CSV",
                   3926:                            &mt("How do I create a CSV file from a spreadsheet"))
                   3927:     .'</td></tr></table>'."\n";
1.86      ng       3928:     $result.='</td></tr></table><br /><br />'."\n";
                   3929:     return $result;
                   3930: }
                   3931: 
                   3932: 
1.26      albertel 3933: sub csvuploadmap {
1.608     www      3934:     my ($request,$symb)= @_;
1.41      ng       3935:     if (!$symb) {return '';}
1.72      ng       3936: 
1.41      ng       3937:     my $datatoken;
1.257     albertel 3938:     if (!$env{'form.datatoken'}) {
1.41      ng       3939: 	$datatoken=&Apache::loncommon::upfile_store($request);
1.26      albertel 3940:     } else {
1.257     albertel 3941: 	$datatoken=$env{'form.datatoken'};
1.41      ng       3942: 	&Apache::loncommon::load_tmp_file($request);
1.26      albertel 3943:     }
1.41      ng       3944:     my @records=&Apache::loncommon::upfile_record_sep();
1.257     albertel 3945:     if ($env{'form.noFirstLine'}) { shift(@records); }
1.324     albertel 3946:     &csvuploadmap_header($request,$symb,$datatoken,$#records+1);
1.41      ng       3947:     my ($i,$keyfields);
                   3948:     if (@records) {
1.582     raeburn  3949:         my $fieldserror;
                   3950: 	my @fields=&csvupload_fields($symb,\$fieldserror);
                   3951:         if ($fieldserror) {
                   3952:             $request->print(&navmap_errormsg());
                   3953:             return;
                   3954:         }
1.257     albertel 3955: 	if ($env{'form.upfile_associate'} eq 'reverse') {	
1.41      ng       3956: 	    &Apache::loncommon::csv_print_samples($request,\@records);
                   3957: 	    $i=&Apache::loncommon::csv_print_select_table($request,\@records,
                   3958: 							  \@fields);
                   3959: 	    foreach (@fields) { $keyfields.=$_->[0].','; }
                   3960: 	    chop($keyfields);
                   3961: 	} else {
                   3962: 	    unshift(@fields,['none','']);
                   3963: 	    $i=&Apache::loncommon::csv_samples_select_table($request,\@records,
                   3964: 							    \@fields);
1.311     banghart 3965:             foreach my $rec (@records) {
                   3966:                 my %temp = &Apache::loncommon::record_sep($rec);
                   3967:                 if (%temp) {
                   3968:                     $keyfields=join(',',sort(keys(%temp)));
                   3969:                     last;
                   3970:                 }
                   3971:             }
1.41      ng       3972: 	}
                   3973:     }
                   3974:     &csvuploadmap_footer($request,$i,$keyfields);
1.72      ng       3975: 
1.41      ng       3976:     return '';
1.27      albertel 3977: }
                   3978: 
1.246     albertel 3979: sub csvuploadoptions {
1.608     www      3980:     my ($request,$symb)= @_;
1.257     albertel 3981:     my $checked=(($env{'form.noFirstLine'})?'1':'0');
1.246     albertel 3982:     my $ignore=&mt('Ignore First Line');
                   3983:     $request->print(<<ENDPICK);
                   3984: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
1.398     albertel 3985: <h3><span class="LC_info">Uploading Class Grade Options</span></h3>
1.246     albertel 3986: <input type="hidden" name="command"    value="csvuploadassign" />
1.302     albertel 3987: <!--
1.246     albertel 3988: <p>
                   3989: <label>
                   3990:    <input type="checkbox" name="show_full_results" />
                   3991:    Show a table of all changes
                   3992: </label>
                   3993: </p>
1.302     albertel 3994: -->
1.246     albertel 3995: <p>
                   3996: <label>
                   3997:    <input type="checkbox" name="overwite_scores" checked="checked" />
                   3998:    Overwrite any existing score
                   3999: </label>
                   4000: </p>
                   4001: ENDPICK
                   4002:     my %fields=&get_fields();
                   4003:     if (!defined($fields{'domain'})) {
1.257     albertel 4004: 	my $domform = &Apache::loncommon::select_dom_form($env{'request.role.domain'},'default_domain');
1.246     albertel 4005: 	$request->print("\n<p> Users are in domain: ".$domform."</p>\n");
                   4006:     }
1.257     albertel 4007:     foreach my $key (sort(keys(%env))) {
1.246     albertel 4008: 	if ($key !~ /^form\.(.*)$/) { next; }
                   4009: 	my $cleankey=$1;
                   4010: 	if ($cleankey eq 'command') { next; }
                   4011: 	$request->print('<input type="hidden" name="'.$cleankey.
1.257     albertel 4012: 			'"  value="'.$env{$key}.'" />'."\n");
1.246     albertel 4013:     }
                   4014:     # FIXME do a check for any duplicated user ids...
                   4015:     # FIXME do a check for any invalid user ids?...
1.290     albertel 4016:     $request->print('<input type="submit" value="Assign Grades" /><br />
                   4017: <hr /></form>'."\n");
1.246     albertel 4018:     return '';
                   4019: }
                   4020: 
                   4021: sub get_fields {
                   4022:     my %fields;
1.257     albertel 4023:     my @keyfields = split(/\,/,$env{'form.keyfields'});
                   4024:     for (my $i=0; $i<=$env{'form.nfields'}; $i++) {
                   4025: 	if ($env{'form.upfile_associate'} eq 'reverse') {
                   4026: 	    if ($env{'form.f'.$i} ne 'none') {
                   4027: 		$fields{$keyfields[$i]}=$env{'form.f'.$i};
1.41      ng       4028: 	    }
                   4029: 	} else {
1.257     albertel 4030: 	    if ($env{'form.f'.$i} ne 'none') {
                   4031: 		$fields{$env{'form.f'.$i}}=$keyfields[$i];
1.41      ng       4032: 	    }
                   4033: 	}
1.27      albertel 4034:     }
1.246     albertel 4035:     return %fields;
                   4036: }
                   4037: 
                   4038: sub csvuploadassign {
1.608     www      4039:     my ($request,$symb)= @_;
1.246     albertel 4040:     if (!$symb) {return '';}
1.345     bowersj2 4041:     my $error_msg = '';
1.246     albertel 4042:     &Apache::loncommon::load_tmp_file($request);
                   4043:     my @gradedata = &Apache::loncommon::upfile_record_sep();
1.257     albertel 4044:     if ($env{'form.noFirstLine'}) { shift(@gradedata); }
1.246     albertel 4045:     my %fields=&get_fields();
1.41      ng       4046:     $request->print('<h3>Assigning Grades</h3>');
1.257     albertel 4047:     my $courseid=$env{'request.course.id'};
1.97      albertel 4048:     my ($classlist) = &getclasslist('all',0);
1.106     albertel 4049:     my @notallowed;
1.41      ng       4050:     my @skipped;
                   4051:     my $countdone=0;
                   4052:     foreach my $grade (@gradedata) {
                   4053: 	my %entries=&Apache::loncommon::record_sep($grade);
1.246     albertel 4054: 	my $domain;
                   4055: 	if ($entries{$fields{'domain'}}) {
                   4056: 	    $domain=$entries{$fields{'domain'}};
                   4057: 	} else {
1.257     albertel 4058: 	    $domain=$env{'form.default_domain'};
1.246     albertel 4059: 	}
1.243     albertel 4060: 	$domain=~s/\s//g;
1.41      ng       4061: 	my $username=$entries{$fields{'username'}};
1.160     albertel 4062: 	$username=~s/\s//g;
1.243     albertel 4063: 	if (!$username) {
                   4064: 	    my $id=$entries{$fields{'ID'}};
1.247     albertel 4065: 	    $id=~s/\s//g;
1.243     albertel 4066: 	    my %ids=&Apache::lonnet::idget($domain,$id);
                   4067: 	    $username=$ids{$id};
                   4068: 	}
1.41      ng       4069: 	if (!exists($$classlist{"$username:$domain"})) {
1.247     albertel 4070: 	    my $id=$entries{$fields{'ID'}};
                   4071: 	    $id=~s/\s//g;
                   4072: 	    if ($id) {
                   4073: 		push(@skipped,"$id:$domain");
                   4074: 	    } else {
                   4075: 		push(@skipped,"$username:$domain");
                   4076: 	    }
1.41      ng       4077: 	    next;
                   4078: 	}
1.108     albertel 4079: 	my $usec=$classlist->{"$username:$domain"}[5];
1.106     albertel 4080: 	if (!&canmodify($usec)) {
                   4081: 	    push(@notallowed,"$username:$domain");
                   4082: 	    next;
                   4083: 	}
1.244     albertel 4084: 	my %points;
1.41      ng       4085: 	my %grades;
                   4086: 	foreach my $dest (keys(%fields)) {
1.244     albertel 4087: 	    if ($dest eq 'ID' || $dest eq 'username' ||
                   4088: 		$dest eq 'domain') { next; }
                   4089: 	    if ($entries{$fields{$dest}} =~ /^\s*$/) { next; }
                   4090: 	    if ($dest=~/stores_(.*)_points/) {
                   4091: 		my $part=$1;
                   4092: 		my $wgt =&Apache::lonnet::EXT('resource.'.$part.'.weight',
                   4093: 					      $symb,$domain,$username);
1.345     bowersj2 4094:                 if ($wgt) {
                   4095:                     $entries{$fields{$dest}}=~s/\s//g;
                   4096:                     my $pcr=$entries{$fields{$dest}} / $wgt;
1.463     albertel 4097:                     my $award=($pcr == 0) ? 'incorrect_by_override'
                   4098:                                           : 'correct_by_override';
1.345     bowersj2 4099:                     $grades{"resource.$part.awarded"}=$pcr;
                   4100:                     $grades{"resource.$part.solved"}=$award;
                   4101:                     $points{$part}=1;
                   4102:                 } else {
                   4103:                     $error_msg = "<br />" .
                   4104:                         &mt("Some point values were assigned"
                   4105:                             ." for problems with a weight "
                   4106:                             ."of zero. These values were "
                   4107:                             ."ignored.");
                   4108:                 }
1.244     albertel 4109: 	    } else {
                   4110: 		if ($dest=~/stores_(.*)_awarded/) { if ($points{$1}) {next;} }
                   4111: 		if ($dest=~/stores_(.*)_solved/)  { if ($points{$1}) {next;} }
                   4112: 		my $store_key=$dest;
                   4113: 		$store_key=~s/^stores/resource/;
                   4114: 		$store_key=~s/_/\./g;
                   4115: 		$grades{$store_key}=$entries{$fields{$dest}};
                   4116: 	    }
1.41      ng       4117: 	}
1.508     www      4118: 	if (! %grades) { 
                   4119:            push(@skipped,&mt("[_1]: no data to save","$username:$domain")); 
                   4120:         } else {
                   4121: 	   $grades{"resource.regrader"}="$env{'user.name'}:$env{'user.domain'}";
                   4122: 	   my $result=&Apache::lonnet::cstore(\%grades,$symb,
1.302     albertel 4123: 					   $env{'request.course.id'},
                   4124: 					   $domain,$username);
1.508     www      4125: 	   if ($result eq 'ok') {
                   4126: 	      $request->print('.');
                   4127: 	   } else {
                   4128: 	      $request->print("<p><span class=\"LC_error\">".
                   4129:                               &mt("Failed to save data for student [_1]. Message when trying to save was: [_2]",
                   4130:                                   "$username:$domain",$result)."</span></p>");
                   4131: 	   }
                   4132: 	   $request->rflush();
                   4133: 	   $countdone++;
                   4134:         }
1.41      ng       4135:     }
1.570     www      4136:     $request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt("Saved scores for [quant,_1,student]",$countdone),$countdone==0));
1.41      ng       4137:     if (@skipped) {
1.571     www      4138: 	$request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt('No scores stored for the following username(s):'),1).'<br />');
                   4139:         $request->print(join(', ',@skipped));
1.106     albertel 4140:     }
                   4141:     if (@notallowed) {
1.571     www      4142: 	$request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt('Modification of scores not allowed for the following username(s):'),1).'<br />');
                   4143: 	$request->print(join(', ',@notallowed));
1.41      ng       4144:     }
1.106     albertel 4145:     $request->print("<br />\n");
1.345     bowersj2 4146:     return $error_msg;
1.26      albertel 4147: }
1.44      ng       4148: #------------- end of section for handling csv file upload ---------
                   4149: #
                   4150: #-------------------------------------------------------------------
                   4151: #
1.122     ng       4152: #-------------- Next few routines handle grading by page/sequence
1.72      ng       4153: #
                   4154: #--- Select a page/sequence and a student to grade
1.68      ng       4155: sub pickStudentPage {
1.608     www      4156:     my ($request,$symb) = @_;
1.68      ng       4157: 
1.539     riegler  4158:     my $alertmsg = &mt('Please select the student you wish to grade.');
1.597     wenzelju 4159:     $request->print(&Apache::lonhtmlcommon::scripttag(<<LISTJAVASCRIPT));
1.68      ng       4160: 
                   4161: function checkPickOne(formname) {
1.76      ng       4162:     if (radioSelection(formname.student) == null) {
1.539     riegler  4163: 	alert("$alertmsg");
1.68      ng       4164: 	return;
                   4165:     }
1.125     ng       4166:     ptr = pullDownSelection(formname.selectpage);
                   4167:     formname.page.value = formname["page"+ptr].value;
                   4168:     formname.title.value = formname["title"+ptr].value;
1.68      ng       4169:     formname.submit();
                   4170: }
                   4171: 
                   4172: LISTJAVASCRIPT
1.118     ng       4173:     &commonJSfunctions($request);
1.608     www      4174: 
1.257     albertel 4175:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
                   4176:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
                   4177:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
1.68      ng       4178: 
1.398     albertel 4179:     my $result='<h3><span class="LC_info">&nbsp;'.
1.485     albertel 4180: 	&mt('Manual Grading by Page or Sequence').'</span></h3>';
1.68      ng       4181: 
1.80      ng       4182:     $result.='<form action="/adm/grades" method="post" name="displayPage">'."\n";
1.582     raeburn  4183:     my $map_error;
                   4184:     my ($titles,$symbx) = &getSymbMap($map_error);
                   4185:     if ($map_error) {
                   4186:         $request->print(&navmap_errormsg());
                   4187:         return; 
                   4188:     }
1.137     albertel 4189:     my ($curpage) =&Apache::lonnet::decode_symb($symb); 
                   4190: #    my ($curpage,$mapId) =&Apache::lonnet::decode_symb($symb); 
                   4191: #    my $type=($curpage =~ /\.(page|sequence)/);
1.485     albertel 4192:     my $select = '<select name="selectpage">'."\n";
1.70      ng       4193:     my $ctr=0;
1.68      ng       4194:     foreach (@$titles) {
                   4195: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
1.485     albertel 4196: 	$select.='<option value="'.$ctr.'" '.
1.401     albertel 4197: 	    ($$symbx{$_} =~ /$curpage$/ ? 'selected="selected"' : '').
1.71      ng       4198: 	    '>'.$showtitle.'</option>'."\n";
1.70      ng       4199: 	$ctr++;
1.68      ng       4200:     }
1.485     albertel 4201:     $select.= '</select>';
1.539     riegler  4202:     $result.='&nbsp;<b>'.&mt('Problems from').':</b> '.$select."<br />\n";
1.485     albertel 4203: 
1.70      ng       4204:     $ctr=0;
                   4205:     foreach (@$titles) {
                   4206: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
                   4207: 	$result.='<input type="hidden" name="page'.$ctr.'" value="'.$$symbx{$_}.'" />'."\n";
                   4208: 	$result.='<input type="hidden" name="title'.$ctr.'" value="'.$showtitle.'" />'."\n";
                   4209: 	$ctr++;
                   4210:     }
1.72      ng       4211:     $result.='<input type="hidden" name="page" />'."\n".
                   4212: 	'<input type="hidden" name="title" />'."\n";
1.68      ng       4213: 
1.485     albertel 4214:     my $options =
                   4215: 	'<label><input type="radio" name="vProb" value="no" checked="checked" /> '.&mt('no').' </label>'."\n".
                   4216: 	'<label><input type="radio" name="vProb" value="yes" /> '.&mt('yes').' </label>'."<br />\n";
1.539     riegler  4217:     $result.='&nbsp;<b>'.&mt('View Problem Text').': </b>'.$options;
1.485     albertel 4218: 
                   4219:     $options =
                   4220: 	'<label><input type="radio" name="lastSub" value="none" /> '.&mt('none').' </label>'."\n".
                   4221: 	'<label><input type="radio" name="lastSub" value="datesub" checked="checked" /> '.&mt('by dates and submissions').'</label>'."\n".
                   4222: 	'<label><input type="radio" name="lastSub" value="all" /> '.&mt('all details').' </label>'."\n";
1.539     riegler  4223:     $result.='&nbsp;<b>'.&mt('Submissions').': </b>'.$options;
1.432     banghart 4224:     
                   4225:     $result.=&build_section_inputs();
1.442     banghart 4226:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
                   4227:     $result.='<input type="hidden" name="Status"  value="'.$stu_status.'" />'."\n".
1.72      ng       4228: 	'<input type="hidden" name="command" value="displayPage" />'."\n".
1.613     www      4229: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."<br />\n";
1.72      ng       4230: 
1.539     riegler  4231:     $result.='&nbsp;<b>'.&mt('Use CODE').': </b> <input type="text" name="CODE" value="" /> <br />'."\n";
1.382     albertel 4232: 
1.80      ng       4233:     $result.='&nbsp;<input type="button" '.
1.589     bisitz   4234:              'onclick="javascript:checkPickOne(this.form);" value="'.&mt('Next').' &rarr;" /><br />'."\n";
1.72      ng       4235: 
1.68      ng       4236:     $request->print($result);
                   4237: 
1.485     albertel 4238:     my $studentTable.='&nbsp;<b>'.&mt('Select a student you wish to grade and then click on the Next button.').'</b><br />'.
1.484     albertel 4239: 	&Apache::loncommon::start_data_table().
                   4240: 	&Apache::loncommon::start_data_table_header_row().
1.485     albertel 4241: 	'<th align="right">&nbsp;'.&mt('No.').'</th>'.
1.484     albertel 4242: 	'<th>'.&nameUserString('header').'</th>'.
1.485     albertel 4243: 	'<th align="right">&nbsp;'.&mt('No.').'</th>'.
1.484     albertel 4244: 	'<th>'.&nameUserString('header').'</th>'.
                   4245: 	&Apache::loncommon::end_data_table_header_row();
1.68      ng       4246:  
1.76      ng       4247:     my (undef,undef,$fullname) = &getclasslist($getsec,'1');
1.68      ng       4248:     my $ptr = 1;
1.294     albertel 4249:     foreach my $student (sort 
                   4250: 			 {
                   4251: 			     if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                   4252: 				 return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                   4253: 			     }
                   4254: 			     return $a cmp $b;
                   4255: 			 } (keys(%$fullname))) {
1.68      ng       4256: 	my ($uname,$udom) = split(/:/,$student);
1.484     albertel 4257: 	$studentTable.=($ptr%2==1 ? &Apache::loncommon::start_data_table_row()
                   4258:                                   : '</td>');
1.126     ng       4259: 	$studentTable.='<td align="right">'.$ptr.'&nbsp;</td>';
1.288     albertel 4260: 	$studentTable.='<td>&nbsp;<label><input type="radio" name="student" value="'.$student.'" /> '
                   4261: 	    .&nameUserString(undef,$$fullname{$student},$uname,$udom)."</label>\n";
1.484     albertel 4262: 	$studentTable.=
                   4263: 	    ($ptr%2 == 0 ? '</td>'.&Apache::loncommon::end_data_table_row() 
                   4264:                          : '');
1.68      ng       4265: 	$ptr++;
                   4266:     }
1.484     albertel 4267:     if ($ptr%2 == 0) {
                   4268: 	$studentTable.='</td><td>&nbsp;</td><td>&nbsp;</td>'.
                   4269: 	    &Apache::loncommon::end_data_table_row();
                   4270:     }
                   4271:     $studentTable.=&Apache::loncommon::end_data_table()."\n";
1.126     ng       4272:     $studentTable.='<input type="button" '.
1.589     bisitz   4273:                    'onclick="javascript:checkPickOne(this.form);" value="'.&mt('Next').' &rarr;" /></form>'."\n";
1.68      ng       4274: 
                   4275:     $request->print($studentTable);
                   4276: 
                   4277:     return '';
                   4278: }
                   4279: 
                   4280: sub getSymbMap {
1.582     raeburn  4281:     my ($map_error) = @_;
1.132     bowersj2 4282:     my $navmap = Apache::lonnavmaps::navmap->new();
1.582     raeburn  4283:     unless (ref($navmap)) {
                   4284:         if (ref($map_error)) {
                   4285:             $$map_error = 'navmap';
                   4286:         }
                   4287:         return;
                   4288:     }
1.68      ng       4289:     my %symbx = ();
                   4290:     my @titles = ();
1.117     bowersj2 4291:     my $minder = 0;
                   4292: 
                   4293:     # Gather every sequence that has problems.
1.240     albertel 4294:     my @sequences = $navmap->retrieveResources(undef, sub { shift->is_map(); },
                   4295: 					       1,0,1);
1.117     bowersj2 4296:     for my $sequence ($navmap->getById('0.0'), @sequences) {
1.241     albertel 4297: 	if ($navmap->hasResource($sequence, sub { shift->is_problem(); }, 0) ) {
1.381     albertel 4298: 	    my $title = $minder.'.'.
                   4299: 		&HTML::Entities::encode($sequence->compTitle(),'"\'&');
                   4300: 	    push(@titles, $title); # minder in case two titles are identical
                   4301: 	    $symbx{$title} = &HTML::Entities::encode($sequence->symb(),'"\'&');
1.117     bowersj2 4302: 	    $minder++;
1.241     albertel 4303: 	}
1.68      ng       4304:     }
                   4305:     return \@titles,\%symbx;
                   4306: }
                   4307: 
1.72      ng       4308: #
                   4309: #--- Displays a page/sequence w/wo problems, w/wo submissions
1.68      ng       4310: sub displayPage {
1.608     www      4311:     my ($request,$symb) = @_;
1.257     albertel 4312:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
                   4313:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
                   4314:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
                   4315:     my $pageTitle = $env{'form.page'};
1.103     albertel 4316:     my ($classlist,undef,$fullname) = &getclasslist($getsec,'1');
1.257     albertel 4317:     my ($uname,$udom) = split(/:/,$env{'form.student'});
                   4318:     my $usec=$classlist->{$env{'form.student'}}[5];
1.168     albertel 4319: 
                   4320:     #need to make sure we have the correct data for later EXT calls, 
                   4321:     #thus invalidate the cache
                   4322:     &Apache::lonnet::devalidatecourseresdata(
1.257     albertel 4323:                  $env{'course.'.$env{'request.course.id'}.'.num'},
                   4324:                  $env{'course.'.$env{'request.course.id'}.'.domain'});
1.168     albertel 4325:     &Apache::lonnet::clear_EXT_cache_status();
                   4326: 
1.103     albertel 4327:     if (!&canview($usec)) {
1.485     albertel 4328: 	$request->print('<span class="LC_warning">'.&mt('Unable to view requested student. ([_1])',$env{'form.student'}).'</span>');
1.103     albertel 4329: 	return;
                   4330:     }
1.398     albertel 4331:     my $result='<h3><span class="LC_info">&nbsp;'.$env{'form.title'}.'</span></h3>';
1.485     albertel 4332:     $result.='<h3>&nbsp;'.&mt('Student: [_1]',&nameUserString(undef,$$fullname{$env{'form.student'}},$uname,$udom)).
1.129     ng       4333: 	'</h3>'."\n";
1.500     albertel 4334:     $env{'form.CODE'} = uc($env{'form.CODE'});
1.501     foxr     4335:     if (&Apache::lonnet::validCODE(uc($env{'form.CODE'}))) {
1.485     albertel 4336: 	$result.='<h3>&nbsp;'.&mt('CODE: [_1]',$env{'form.CODE'}).'</h3>'."\n";
1.382     albertel 4337:     } else {
                   4338: 	delete($env{'form.CODE'});
                   4339:     }
1.71      ng       4340:     &sub_page_js($request);
                   4341:     $request->print($result);
                   4342: 
1.132     bowersj2 4343:     my $navmap = Apache::lonnavmaps::navmap->new();
1.582     raeburn  4344:     unless (ref($navmap)) {
                   4345:         $request->print(&navmap_errormsg());
                   4346:         return;
                   4347:     }
1.257     albertel 4348:     my ($mapUrl, $id, $resUrl)=&Apache::lonnet::decode_symb($env{'form.page'});
1.68      ng       4349:     my $map = $navmap->getResourceByUrl($resUrl); # add to navmaps
1.288     albertel 4350:     if (!$map) {
1.485     albertel 4351: 	$request->print('<span class="LC_warning">'.&mt('Unable to view requested sequence. ([_1])',$resUrl).'</span>');
1.288     albertel 4352: 	return; 
                   4353:     }
1.68      ng       4354:     my $iterator = $navmap->getIterator($map->map_start(),
                   4355: 					$map->map_finish());
                   4356: 
1.71      ng       4357:     my $studentTable='<form action="/adm/grades" method="post" name="gradePage">'."\n".
1.72      ng       4358: 	'<input type="hidden" name="command" value="gradeByPage" />'."\n".
1.257     albertel 4359: 	'<input type="hidden" name="fullname" value="'.$$fullname{$env{'form.student'}}.'" />'."\n".
                   4360: 	'<input type="hidden" name="student" value="'.$env{'form.student'}.'" />'."\n".
1.72      ng       4361: 	'<input type="hidden" name="page"    value="'.$pageTitle.'" />'."\n".
1.257     albertel 4362: 	'<input type="hidden" name="title"   value="'.$env{'form.title'}.'" />'."\n".
1.418     albertel 4363: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.613     www      4364: 	'<input type="hidden" name="overRideScore" value="no" />'."\n";
1.71      ng       4365: 
1.382     albertel 4366:     if (defined($env{'form.CODE'})) {
                   4367: 	$studentTable.=
                   4368: 	    '<input type="hidden" name="CODE" value="'.$env{'form.CODE'}.'" />'."\n";
                   4369:     }
1.381     albertel 4370:     my $checkIcon = '<img alt="'.&mt('Check Mark').
1.485     albertel 4371: 	'" src="'.&Apache::loncommon::lonhttpdurl($request->dir_config('lonIconsURL').'/check.gif').'" height="16" border="0" />';
1.71      ng       4372: 
1.594     bisitz   4373:     $studentTable.='&nbsp;<span class="LC_info">'.
                   4374:         &mt('Problems graded correct by the computer are marked with a [_1] symbol.',$checkIcon).
                   4375:         '</span>'."\n".
1.484     albertel 4376: 	&Apache::loncommon::start_data_table().
                   4377: 	&Apache::loncommon::start_data_table_header_row().
                   4378: 	'<th align="center">&nbsp;Prob.&nbsp;</th>'.
1.485     albertel 4379: 	'<th>&nbsp;'.($env{'form.vProb'} eq 'no' ? &mt('Title') : &mt('Problem Text')).'/'.&mt('Grade').'</th>'.
1.484     albertel 4380: 	&Apache::loncommon::end_data_table_header_row();
1.71      ng       4381: 
1.329     albertel 4382:     &Apache::lonxml::clear_problem_counter();
1.196     albertel 4383:     my ($depth,$question,$prob) = (1,1,1);
1.68      ng       4384:     $iterator->next(); # skip the first BEGIN_MAP
                   4385:     my $curRes = $iterator->next(); # for "current resource"
1.101     albertel 4386:     while ($depth > 0) {
1.68      ng       4387:         if($curRes == $iterator->BEGIN_MAP) { $depth++; }
1.100     bowersj2 4388:         if($curRes == $iterator->END_MAP) { $depth--; }
1.68      ng       4389: 
1.385     albertel 4390:         if (ref($curRes) && $curRes->is_problem()) {
1.91      albertel 4391: 	    my $parts = $curRes->parts();
1.68      ng       4392:             my $title = $curRes->compTitle();
1.71      ng       4393: 	    my $symbx = $curRes->symb();
1.484     albertel 4394: 	    $studentTable.=
                   4395: 		&Apache::loncommon::start_data_table_row().
                   4396: 		'<td align="center" valign="top" >'.$prob.
1.485     albertel 4397: 		(scalar(@{$parts}) == 1 ? '' 
                   4398: 		                        : '<br />('.&mt('[_1]&nbsp;parts)',
                   4399: 							scalar(@{$parts}))
                   4400: 		 ).
                   4401: 		 '</td>';
1.71      ng       4402: 	    $studentTable.='<td valign="top">';
1.382     albertel 4403: 	    my %form = ('CODE' => $env{'form.CODE'},);
1.257     albertel 4404: 	    if ($env{'form.vProb'} eq 'yes' ) {
1.144     albertel 4405: 		$studentTable.=&show_problem($request,$symbx,$uname,$udom,1,
1.383     albertel 4406: 					     undef,'both',\%form);
1.71      ng       4407: 	    } else {
1.382     albertel 4408: 		my $companswer = &Apache::loncommon::get_student_answers($symbx,$uname,$udom,$env{'request.course.id'},%form);
1.80      ng       4409: 		$companswer =~ s|<form(.*?)>||g;
                   4410: 		$companswer =~ s|</form>||g;
1.71      ng       4411: #		while ($companswer =~ /(<a href\=\"javascript:newWindow.*?Script Vars<\/a>)/s) { #<a href="javascript:newWindow</a>
1.116     ng       4412: #		    $companswer =~ s/$1/ /ms;
1.326     albertel 4413: #		    $request->print('match='.$1."<br />\n");
1.71      ng       4414: #		}
1.116     ng       4415: #		$companswer =~ s|<table border=\"1\">|<table border=\"0\">|g;
1.539     riegler  4416: 		$studentTable.='&nbsp;<b>'.$title.'</b>&nbsp;<br />&nbsp;<b>'.&mt('Correct answer').':</b><br />'.$companswer;
1.71      ng       4417: 	    }
                   4418: 
1.257     albertel 4419: 	    my %record = &Apache::lonnet::restore($symbx,$env{'request.course.id'},$udom,$uname);
1.125     ng       4420: 
1.257     albertel 4421: 	    if ($env{'form.lastSub'} eq 'datesub') {
1.71      ng       4422: 		if ($record{'version'} eq '') {
1.485     albertel 4423: 		    $studentTable.='<br />&nbsp;<span class="LC_warning">'.&mt('No recorded submission for this problem.').'</span><br />';
1.71      ng       4424: 		} else {
1.116     ng       4425: 		    my %responseType = ();
                   4426: 		    foreach my $partid (@{$parts}) {
1.147     albertel 4427: 			my @responseIds =$curRes->responseIds($partid);
                   4428: 			my @responseType =$curRes->responseType($partid);
                   4429: 			my %responseIds;
                   4430: 			for (my $i=0;$i<=$#responseIds;$i++) {
                   4431: 			    $responseIds{$responseIds[$i]}=$responseType[$i];
                   4432: 			}
                   4433: 			$responseType{$partid} = \%responseIds;
1.116     ng       4434: 		    }
1.148     albertel 4435: 		    $studentTable.= &displaySubByDates($symbx,\%record,$parts,\%responseType,$checkIcon,$uname,$udom);
1.147     albertel 4436: 
1.71      ng       4437: 		}
1.257     albertel 4438: 	    } elsif ($env{'form.lastSub'} eq 'all') {
                   4439: 		my $last = ($env{'form.lastSub'} eq 'last' ? 'last' : '');
1.71      ng       4440: 		$studentTable.=&Apache::loncommon::get_previous_attempt($symbx,$uname,$udom,
1.257     albertel 4441: 									$env{'request.course.id'},
1.71      ng       4442: 									'','.submission');
                   4443:  
                   4444: 	    }
1.103     albertel 4445: 	    if (&canmodify($usec)) {
1.585     bisitz   4446:             $studentTable.=&gradeBox_start();
1.103     albertel 4447: 		foreach my $partid (@{$parts}) {
                   4448: 		    $studentTable.=&gradeBox($request,$symbx,$uname,$udom,$question,$partid,\%record);
                   4449: 		    $studentTable.='<input type="hidden" name="q_'.$question.'" value="'.$partid.'" />'."\n";
                   4450: 		    $question++;
                   4451: 		}
1.585     bisitz   4452:             $studentTable.=&gradeBox_end();
1.196     albertel 4453: 		$prob++;
1.71      ng       4454: 	    }
                   4455: 	    $studentTable.='</td></tr>';
1.68      ng       4456: 
1.103     albertel 4457: 	}
1.68      ng       4458:         $curRes = $iterator->next();
                   4459:     }
                   4460: 
1.589     bisitz   4461:     $studentTable.=
                   4462:         '</table>'."\n".
                   4463:         '<input type="button" value="'.&mt('Save').'" '.
                   4464:         'onclick="javascript:checkSubmitPage(this.form,'.$question.');" />'.
                   4465:         '</form>'."\n";
1.71      ng       4466:     $request->print($studentTable);
                   4467: 
                   4468:     return '';
1.119     ng       4469: }
                   4470: 
                   4471: sub displaySubByDates {
1.148     albertel 4472:     my ($symb,$record,$parts,$responseType,$checkIcon,$uname,$udom) = @_;
1.224     albertel 4473:     my $isCODE=0;
1.335     albertel 4474:     my $isTask = ($symb =~/\.task$/);
1.224     albertel 4475:     if (exists($record->{'resource.CODE'})) { $isCODE=1; }
1.467     albertel 4476:     my $studentTable=&Apache::loncommon::start_data_table().
                   4477: 	&Apache::loncommon::start_data_table_header_row().
                   4478: 	'<th>'.&mt('Date/Time').'</th>'.
                   4479: 	($isCODE?'<th>'.&mt('CODE').'</th>':'').
                   4480: 	'<th>'.&mt('Submission').'</th>'.
                   4481: 	'<th>'.&mt('Status').'</th>'.
                   4482: 	&Apache::loncommon::end_data_table_header_row();
1.119     ng       4483:     my ($version);
                   4484:     my %mark;
1.148     albertel 4485:     my %orders;
1.119     ng       4486:     $mark{'correct_by_student'} = $checkIcon;
1.147     albertel 4487:     if (!exists($$record{'1:timestamp'})) {
1.539     riegler  4488: 	return '<br />&nbsp;<span class="LC_warning">'.&mt('Nothing submitted - no attempts.').'</span><br />';
1.147     albertel 4489:     }
1.335     albertel 4490: 
                   4491:     my $interaction;
1.525     raeburn  4492:     my $no_increment = 1;
1.119     ng       4493:     for ($version=1;$version<=$$record{'version'};$version++) {
1.467     albertel 4494: 	my $timestamp = 
                   4495: 	    &Apache::lonlocal::locallocaltime($$record{$version.':timestamp'});
1.335     albertel 4496: 	if (exists($$record{$version.':resource.0.version'})) {
                   4497: 	    $interaction = $$record{$version.':resource.0.version'};
                   4498: 	}
                   4499: 
                   4500: 	my $where = ($isTask ? "$version:resource.$interaction"
                   4501: 		             : "$version:resource");
1.467     albertel 4502: 	$studentTable.=&Apache::loncommon::start_data_table_row().
                   4503: 	    '<td>'.$timestamp.'</td>';
1.224     albertel 4504: 	if ($isCODE) {
                   4505: 	    $studentTable.='<td>'.$record->{$version.':resource.CODE'}.'</td>';
                   4506: 	}
1.119     ng       4507: 	my @versionKeys = split(/\:/,$$record{$version.':keys'});
                   4508: 	my @displaySub = ();
                   4509: 	foreach my $partid (@{$parts}) {
1.596     raeburn  4510:             my $hidden;
                   4511:             if (($$record{$version.':resource.'.$partid.'.type'} eq 'anonsurvey') ||
                   4512:                 ($$record{$version.':resource.'.$partid.'.type'} eq 'anonsurveycred')) {
                   4513:                 $hidden = 1;
                   4514:             }
1.335     albertel 4515: 	    my @matchKey = ($isTask ? sort(grep /^resource\.\d+\.\Q$partid\E\.award$/,@versionKeys)
                   4516: 			            : sort(grep /^resource\.\Q$partid\E\..*?\.submission$/,@versionKeys));
                   4517: 	    
1.122     ng       4518: #	    next if ($$record{"$version:resource.$partid.solved"} eq '');
1.324     albertel 4519: 	    my $display_part=&get_display_part($partid,$symb);
1.147     albertel 4520: 	    foreach my $matchKey (@matchKey) {
1.198     albertel 4521: 		if (exists($$record{$version.':'.$matchKey}) &&
                   4522: 		    $$record{$version.':'.$matchKey} ne '') {
1.596     raeburn  4523:                     
1.335     albertel 4524: 		    my ($responseId)= ($isTask ? ($matchKey=~ /^resource\.(.*?)\.\Q$partid\E\.award$/)
                   4525: 				               : ($matchKey=~ /^resource\.\Q$partid\E\.(.*?)\.submission$/));
1.577     bisitz   4526:                     $displaySub[0].='<span class="LC_nobreak"';
                   4527:                     $displaySub[0].='<b>'.&mt('Part: [_1]',$display_part).'</b>'
                   4528:                                    .' <span class="LC_internal_info">'
1.625   ! www      4529:                                    .'('.&mt('Response ID: [_1]',$responseId).')'
1.577     bisitz   4530:                                    .'</span>'
                   4531:                                    .' <b>';
1.596     raeburn  4532:                     if ($hidden) {
                   4533:                         $displaySub[0].= &mt('Anonymous Survey').'</b>';
                   4534:                     } else {
                   4535: 		        if ($$record{"$where.$partid.tries"} eq '') {
                   4536: 			    $displaySub[0].=&mt('Trial not counted');
                   4537: 		        } else {
                   4538: 			    $displaySub[0].=&mt('Trial: [_1]',
1.467     albertel 4539: 					    $$record{"$where.$partid.tries"});
1.596     raeburn  4540: 		        }
                   4541: 		        my $responseType=($isTask ? 'Task'
1.335     albertel 4542:                                               : $responseType->{$partid}->{$responseId});
1.596     raeburn  4543: 		        if (!exists($orders{$partid})) { $orders{$partid}={}; }
                   4544: 		        if (!exists($orders{$partid}->{$responseId})) {
                   4545: 			    $orders{$partid}->{$responseId}=
                   4546: 			        &get_order($partid,$responseId,$symb,$uname,$udom,
                   4547:                                            $no_increment);
                   4548: 		        }
                   4549: 		        $displaySub[0].='</b></span>'; # /nobreak
                   4550: 		        $displaySub[0].='&nbsp; '.
                   4551: 			    &cleanRecord($$record{$version.':'.$matchKey},$responseType,$symb,$partid,$responseId,$record,$orders{$partid}->{$responseId},"$version:",$uname,$udom).'<br />';
                   4552:                     }
1.147     albertel 4553: 		}
                   4554: 	    }
1.335     albertel 4555: 	    if (exists($$record{"$where.$partid.checkedin"})) {
1.485     albertel 4556: 		$displaySub[1].=&mt('Checked in by [_1] into slot [_2]',
                   4557: 				    $$record{"$where.$partid.checkedin"},
                   4558: 				    $$record{"$where.$partid.checkedin.slot"}).
                   4559: 					'<br />';
1.335     albertel 4560: 	    }
                   4561: 	    if (exists $$record{"$where.$partid.award"}) {
1.485     albertel 4562: 		$displaySub[1].='<b>'.&mt('Part:').'</b>&nbsp;'.$display_part.' &nbsp;'.
1.335     albertel 4563: 		    lc($$record{"$where.$partid.award"}).' '.
                   4564: 		    $mark{$$record{"$where.$partid.solved"}}.
1.147     albertel 4565: 		    '<br />';
                   4566: 	    }
1.335     albertel 4567: 	    if (exists $$record{"$where.$partid.regrader"}) {
                   4568: 		$displaySub[2].=$$record{"$where.$partid.regrader"}.
                   4569: 		    ' (<b>'.&mt('Part').':</b> '.$display_part.')';
                   4570: 	    } elsif ($$record{"$version:resource.$partid.regrader"} =~ /\S/) {
                   4571: 		$displaySub[2].=
                   4572: 		    $$record{"$version:resource.$partid.regrader"}.
1.207     albertel 4573: 		    ' (<b>'.&mt('Part').':</b> '.$display_part.')';
1.147     albertel 4574: 	    }
                   4575: 	}
                   4576: 	# needed because old essay regrader has not parts info
                   4577: 	if (exists $$record{"$version:resource.regrader"}) {
                   4578: 	    $displaySub[2].=$$record{"$version:resource.regrader"};
                   4579: 	}
                   4580: 	$studentTable.='<td>'.$displaySub[0].'&nbsp;</td><td>'.$displaySub[1];
                   4581: 	if ($displaySub[2]) {
1.467     albertel 4582: 	    $studentTable.=&mt('Manually graded by [_1]',$displaySub[2]);
1.147     albertel 4583: 	}
1.467     albertel 4584: 	$studentTable.='&nbsp;</td>'.
                   4585: 	    &Apache::loncommon::end_data_table_row();
1.119     ng       4586:     }
1.467     albertel 4587:     $studentTable.=&Apache::loncommon::end_data_table();
1.119     ng       4588:     return $studentTable;
1.71      ng       4589: }
                   4590: 
                   4591: sub updateGradeByPage {
1.608     www      4592:     my ($request,$symb) = @_;
1.71      ng       4593: 
1.257     albertel 4594:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
                   4595:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
                   4596:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
                   4597:     my $pageTitle = $env{'form.page'};
1.103     albertel 4598:     my ($classlist,undef,$fullname) = &getclasslist($getsec,'1');
1.257     albertel 4599:     my ($uname,$udom) = split(/:/,$env{'form.student'});
                   4600:     my $usec=$classlist->{$env{'form.student'}}[5];
1.103     albertel 4601:     if (!&canmodify($usec)) {
1.526     raeburn  4602: 	$request->print('<span class="LC_warning">'.&mt('Unable to modify requested student ([_1])',$env{'form.student'}).'</span>');
1.103     albertel 4603: 	return;
                   4604:     }
1.398     albertel 4605:     my $result='<h3><span class="LC_info">&nbsp;'.$env{'form.title'}.'</span></h3>';
1.526     raeburn  4606:     $result.='<h3>&nbsp;'.&mt('Student: ').&nameUserString(undef,$env{'form.fullname'},$uname,$udom).
1.129     ng       4607: 	'</h3>'."\n";
1.70      ng       4608: 
1.68      ng       4609:     $request->print($result);
                   4610: 
1.582     raeburn  4611: 
1.132     bowersj2 4612:     my $navmap = Apache::lonnavmaps::navmap->new();
1.582     raeburn  4613:     unless (ref($navmap)) {
                   4614:         $request->print(&navmap_errormsg());
                   4615:         return;
                   4616:     }
1.257     albertel 4617:     my ($mapUrl, $id, $resUrl) = &Apache::lonnet::decode_symb( $env{'form.page'});
1.71      ng       4618:     my $map = $navmap->getResourceByUrl($resUrl); # add to navmaps
1.288     albertel 4619:     if (!$map) {
1.527     raeburn  4620: 	$request->print('<span class="LC_warning">'.&mt('Unable to grade requested sequence ([_1]).',$resUrl).'</span>');
1.288     albertel 4621: 	return; 
                   4622:     }
1.71      ng       4623:     my $iterator = $navmap->getIterator($map->map_start(),
                   4624: 					$map->map_finish());
1.70      ng       4625: 
1.484     albertel 4626:     my $studentTable=
                   4627: 	&Apache::loncommon::start_data_table().
                   4628: 	&Apache::loncommon::start_data_table_header_row().
1.485     albertel 4629: 	'<th align="center">&nbsp;'.&mt('Prob.').'&nbsp;</th>'.
                   4630: 	'<th>&nbsp;'.&mt('Title').'&nbsp;</th>'.
                   4631: 	'<th>&nbsp;'.&mt('Previous Score').'&nbsp;</th>'.
                   4632: 	'<th>&nbsp;'.&mt('New Score').'&nbsp;</th>'.
1.484     albertel 4633: 	&Apache::loncommon::end_data_table_header_row();
1.71      ng       4634: 
                   4635:     $iterator->next(); # skip the first BEGIN_MAP
                   4636:     my $curRes = $iterator->next(); # for "current resource"
1.196     albertel 4637:     my ($depth,$question,$prob,$changeflag)= (1,1,1,0);
1.101     albertel 4638:     while ($depth > 0) {
1.71      ng       4639:         if($curRes == $iterator->BEGIN_MAP) { $depth++; }
1.100     bowersj2 4640:         if($curRes == $iterator->END_MAP) { $depth--; }
1.71      ng       4641: 
1.385     albertel 4642:         if (ref($curRes) && $curRes->is_problem()) {
1.91      albertel 4643: 	    my $parts = $curRes->parts();
1.71      ng       4644:             my $title = $curRes->compTitle();
                   4645: 	    my $symbx = $curRes->symb();
1.484     albertel 4646: 	    $studentTable.=
                   4647: 		&Apache::loncommon::start_data_table_row().
                   4648: 		'<td align="center" valign="top" >'.$prob.
1.485     albertel 4649: 		(scalar(@{$parts}) == 1 ? '' 
1.526     raeburn  4650:                                         : '<br />('.&mt('[quant,_1,&nbsp;part]',scalar(@{$parts}))
                   4651: 		.')').'</td>';
1.71      ng       4652: 	    $studentTable.='<td valign="top">&nbsp;<b>'.$title.'</b>&nbsp;</td>';
                   4653: 
                   4654: 	    my %newrecord=();
                   4655: 	    my @displayPts=();
1.269     raeburn  4656:             my %aggregate = ();
                   4657:             my $aggregateflag = 0;
1.71      ng       4658: 	    foreach my $partid (@{$parts}) {
1.257     albertel 4659: 		my $newpts = $env{'form.GD_BOX'.$question.'_'.$partid};
                   4660: 		my $oldpts = $env{'form.oldpts'.$question.'_'.$partid};
1.71      ng       4661: 
1.257     albertel 4662: 		my $wgt = $env{'form.WGT'.$question.'_'.$partid} != 0 ? 
                   4663: 		    $env{'form.WGT'.$question.'_'.$partid} : 1;
1.71      ng       4664: 		my $partial = $newpts/$wgt;
                   4665: 		my $score;
                   4666: 		if ($partial > 0) {
                   4667: 		    $score = 'correct_by_override';
1.125     ng       4668: 		} elsif ($newpts ne '') { #empty is taken as 0
1.71      ng       4669: 		    $score = 'incorrect_by_override';
                   4670: 		}
1.257     albertel 4671: 		my $dropMenu = $env{'form.GD_SEL'.$question.'_'.$partid};
1.125     ng       4672: 		if ($dropMenu eq 'excused') {
1.71      ng       4673: 		    $partial = '';
                   4674: 		    $score = 'excused';
1.125     ng       4675: 		} elsif ($dropMenu eq 'reset status'
1.257     albertel 4676: 			 && $env{'form.solved'.$question.'_'.$partid} ne '') { #update only if previous record exists
1.125     ng       4677: 		    $newrecord{'resource.'.$partid.'.tries'} = 0;
                   4678: 		    $newrecord{'resource.'.$partid.'.solved'} = '';
                   4679: 		    $newrecord{'resource.'.$partid.'.award'} = '';
                   4680: 		    $newrecord{'resource.'.$partid.'.awarded'} = 0;
1.257     albertel 4681: 		    $newrecord{'resource.'.$partid.'.regrader'} = "$env{'user.name'}:$env{'user.domain'}";
1.125     ng       4682: 		    $changeflag++;
                   4683: 		    $newpts = '';
1.269     raeburn  4684:                     
                   4685:                     my $aggtries =  $env{'form.aggtries'.$question.'_'.$partid};
                   4686:                     my $totaltries = $env{'form.totaltries'.$question.'_'.$partid};
                   4687:                     my $solvedstatus = $env{'form.solved'.$question.'_'.$partid};
                   4688:                     if ($aggtries > 0) {
                   4689:                         &decrement_aggs($symbx,$partid,\%aggregate,$aggtries,$totaltries,$solvedstatus);
                   4690:                         $aggregateflag = 1;
                   4691:                     }
1.71      ng       4692: 		}
1.324     albertel 4693: 		my $display_part=&get_display_part($partid,$curRes->symb());
1.257     albertel 4694: 		my $oldstatus = $env{'form.solved'.$question.'_'.$partid};
1.526     raeburn  4695: 		$displayPts[0].='&nbsp;<b>'.&mt('Part').':</b> '.$display_part.' = '.
1.71      ng       4696: 		    (($oldstatus eq 'excused') ? 'excused' : $oldpts).
1.326     albertel 4697: 		    '&nbsp;<br />';
1.526     raeburn  4698: 		$displayPts[1].='&nbsp;<b>'.&mt('Part').':</b> '.$display_part.' = '.
1.125     ng       4699: 		     (($score eq 'excused') ? 'excused' : $newpts).
1.326     albertel 4700: 		    '&nbsp;<br />';
1.71      ng       4701: 		$question++;
1.380     albertel 4702: 		next if ($dropMenu eq 'reset status' || ($newpts eq $oldpts && $score ne 'excused'));
1.125     ng       4703: 
1.71      ng       4704: 		$newrecord{'resource.'.$partid.'.awarded'}  = $partial if $partial ne '';
1.125     ng       4705: 		$newrecord{'resource.'.$partid.'.solved'}   = $score if $score ne '';
1.257     albertel 4706: 		$newrecord{'resource.'.$partid.'.regrader'} = "$env{'user.name'}:$env{'user.domain'}"
1.125     ng       4707: 		    if (scalar(keys(%newrecord)) > 0);
1.71      ng       4708: 
                   4709: 		$changeflag++;
                   4710: 	    }
                   4711: 	    if (scalar(keys(%newrecord)) > 0) {
1.382     albertel 4712: 		my %record = 
                   4713: 		    &Apache::lonnet::restore($symbx,$env{'request.course.id'},
                   4714: 					     $udom,$uname);
                   4715: 
                   4716: 		if (&Apache::lonnet::validCODE($env{'form.CODE'})) {
                   4717: 		    $newrecord{'resource.CODE'} = $env{'form.CODE'};
                   4718: 		} elsif (&Apache::lonnet::validCODE($record{'resource.CODE'})) {
                   4719: 		    $newrecord{'resource.CODE'} = '';
                   4720: 		}
1.257     albertel 4721: 		&Apache::lonnet::cstore(\%newrecord,$symbx,$env{'request.course.id'},
1.71      ng       4722: 					$udom,$uname);
1.382     albertel 4723: 		%record = &Apache::lonnet::restore($symbx,
                   4724: 						   $env{'request.course.id'},
                   4725: 						   $udom,$uname);
1.380     albertel 4726: 		&check_and_remove_from_queue($parts,\%record,undef,$symbx,
                   4727: 					     $cdom,$cnum,$udom,$uname);
1.71      ng       4728: 	    }
1.380     albertel 4729: 	    
1.269     raeburn  4730:             if ($aggregateflag) {
                   4731:                 &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
                   4732:                       $env{'course.'.$env{'request.course.id'}.'.domain'},
                   4733:                       $env{'course.'.$env{'request.course.id'}.'.num'});
                   4734:             }
1.125     ng       4735: 
1.71      ng       4736: 	    $studentTable.='<td valign="top">'.$displayPts[0].'</td>'.
                   4737: 		'<td valign="top">'.$displayPts[1].'</td>'.
1.484     albertel 4738: 		&Apache::loncommon::end_data_table_row();
1.68      ng       4739: 
1.196     albertel 4740: 	    $prob++;
1.68      ng       4741: 	}
1.71      ng       4742:         $curRes = $iterator->next();
1.68      ng       4743:     }
1.98      albertel 4744: 
1.484     albertel 4745:     $studentTable.=&Apache::loncommon::end_data_table();
1.526     raeburn  4746:     my $grademsg=($changeflag == 0 ? &mt('No score was changed or updated.') :
                   4747: 		  &mt('The scores were changed for [quant,_1,problem].',
                   4748: 		  $changeflag));
1.76      ng       4749:     $request->print($grademsg.$studentTable);
1.68      ng       4750: 
1.70      ng       4751:     return '';
                   4752: }
                   4753: 
1.72      ng       4754: #-------- end of section for handling grading by page/sequence ---------
                   4755: #
                   4756: #-------------------------------------------------------------------
                   4757: 
1.581     www      4758: #-------------------- Bubblesheet (Scantron) Grading -------------------
1.75      albertel 4759: #
                   4760: #------ start of section for handling grading by page/sequence ---------
                   4761: 
1.423     albertel 4762: =pod
                   4763: 
                   4764: =head1 Bubble sheet grading routines
                   4765: 
1.424     albertel 4766:   For this documentation:
                   4767: 
                   4768:    'scanline' refers to the full line of characters
                   4769:    from the file that we are parsing that represents one entire sheet
                   4770: 
                   4771:    'bubble line' refers to the data
                   4772:    representing the line of bubbles that are on the physical bubble sheet
                   4773: 
                   4774: 
                   4775: The overall process is that a scanned in bubble sheet data is uploaded
                   4776: into a course. When a user wants to grade, they select a
                   4777: sequence/folder of resources, a file of bubble sheet info, and pick
                   4778: one of the predefined configurations for what each scanline looks
                   4779: like.
                   4780: 
                   4781: Next each scanline is checked for any errors of either 'missing
1.435     foxr     4782: bubbles' (it's an error because it may have been mis-scanned
1.424     albertel 4783: because too light bubbling), 'double bubble' (each bubble line should
                   4784: have no more that one letter picked), invalid or duplicated CODE,
1.556     weissno  4785: invalid student/employee ID
1.424     albertel 4786: 
                   4787: If the CODE option is used that determines the randomization of the
1.556     weissno  4788: homework problems, either way the student/employee ID is looked up into a
1.424     albertel 4789: username:domain.
                   4790: 
                   4791: During the validation phase the instructor can choose to skip scanlines. 
                   4792: 
1.435     foxr     4793: After the validation phase, there are now 3 bubble sheet files
1.424     albertel 4794: 
                   4795:   scantron_original_filename (unmodified original file)
                   4796:   scantron_corrected_filename (file where the corrected information has replaced the original information)
                   4797:   scantron_skipped_filename (contains the exact text of scanlines that where skipped)
                   4798: 
                   4799: Also there is a separate hash nohist_scantrondata that contains extra
                   4800: correction information that isn't representable in the bubble sheet
                   4801: file (see &scantron_getfile() for more information)
                   4802: 
                   4803: After all scanlines are either valid, marked as valid or skipped, then
                   4804: foreach line foreach problem in the picked sequence, an ssi request is
                   4805: made that simulates a user submitting their selected letter(s) against
                   4806: the homework problem.
1.423     albertel 4807: 
                   4808: =over 4
                   4809: 
                   4810: 
                   4811: 
                   4812: =item defaultFormData
                   4813: 
                   4814:   Returns html hidden inputs used to hold context/default values.
                   4815: 
                   4816:  Arguments:
                   4817:   $symb - $symb of the current resource 
                   4818: 
                   4819: =cut
1.422     foxr     4820: 
1.81      albertel 4821: sub defaultFormData {
1.324     albertel 4822:     my ($symb)=@_;
1.613     www      4823:     return '<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />';
1.81      albertel 4824: }
                   4825: 
1.447     foxr     4826: 
1.423     albertel 4827: =pod 
                   4828: 
                   4829: =item getSequenceDropDown
                   4830: 
                   4831:    Return html dropdown of possible sequences to grade
                   4832:  
                   4833:  Arguments:
1.582     raeburn  4834:    $symb - $symb of the current resource
                   4835:    $map_error - ref to scalar which will container error if
                   4836:                 $navmap object is unavailable in &getSymbMap().
1.423     albertel 4837: 
                   4838: =cut
1.422     foxr     4839: 
1.75      albertel 4840: sub getSequenceDropDown {
1.582     raeburn  4841:     my ($symb,$map_error)=@_;
1.75      albertel 4842:     my $result='<select name="selectpage">'."\n";
1.582     raeburn  4843:     my ($titles,$symbx) = &getSymbMap($map_error);
                   4844:     if (ref($map_error)) {
                   4845:         return if ($$map_error);
                   4846:     }
1.137     albertel 4847:     my ($curpage)=&Apache::lonnet::decode_symb($symb); 
1.75      albertel 4848:     my $ctr=0;
                   4849:     foreach (@$titles) {
                   4850: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
                   4851: 	$result.='<option value="'.$$symbx{$_}.'" '.
1.401     albertel 4852: 	    ($$symbx{$_} =~ /$curpage$/ ? 'selected="selected"' : '').
1.75      albertel 4853: 	    '>'.$showtitle.'</option>'."\n";
                   4854: 	$ctr++;
                   4855:     }
                   4856:     $result.= '</select>';
                   4857:     return $result;
                   4858: }
                   4859: 
1.495     albertel 4860: my %bubble_lines_per_response;     # no. bubble lines for each response.
1.554     raeburn  4861:                                    # key is zero-based index - 0, 1, 2 ...
1.495     albertel 4862: 
                   4863: my %first_bubble_line;             # First bubble line no. for each bubble.
                   4864: 
1.509     raeburn  4865: my %subdivided_bubble_lines;       # no. bubble lines for optionresponse, 
                   4866:                                    # matchresponse or rankresponse, where 
                   4867:                                    # an individual response can have multiple 
                   4868:                                    # lines
1.503     raeburn  4869: 
                   4870: my %responsetype_per_response;     # responsetype for each response
                   4871: 
1.495     albertel 4872: # Save and restore the bubble lines array to the form env.
                   4873: 
                   4874: 
                   4875: sub save_bubble_lines {
                   4876:     foreach my $line (keys(%bubble_lines_per_response)) {
                   4877: 	$env{"form.scantron.bubblelines.$line"}  = $bubble_lines_per_response{$line};
                   4878: 	$env{"form.scantron.first_bubble_line.$line"} =
                   4879: 	    $first_bubble_line{$line};
1.503     raeburn  4880:         $env{"form.scantron.sub_bubblelines.$line"} = 
                   4881:             $subdivided_bubble_lines{$line};
                   4882:         $env{"form.scantron.responsetype.$line"} =
                   4883:             $responsetype_per_response{$line};
1.495     albertel 4884:     }
                   4885: }
                   4886: 
                   4887: 
                   4888: sub restore_bubble_lines {
                   4889:     my $line = 0;
                   4890:     %bubble_lines_per_response = ();
                   4891:     while ($env{"form.scantron.bubblelines.$line"}) {
                   4892: 	my $value = $env{"form.scantron.bubblelines.$line"};
                   4893: 	$bubble_lines_per_response{$line} = $value;
                   4894: 	$first_bubble_line{$line}  =
                   4895: 	    $env{"form.scantron.first_bubble_line.$line"};
1.503     raeburn  4896:         $subdivided_bubble_lines{$line} =
                   4897:             $env{"form.scantron.sub_bubblelines.$line"};
                   4898:         $responsetype_per_response{$line} =
                   4899:             $env{"form.scantron.responsetype.$line"};
1.495     albertel 4900: 	$line++;
                   4901:     }
                   4902: }
                   4903: 
                   4904: #  Given the parsed scanline, get the response for 
                   4905: #  'answer' number n:
                   4906: 
                   4907: sub get_response_bubbles {
                   4908:     my ($parsed_line, $response)  = @_;
                   4909: 
                   4910:     my $bubble_line = $first_bubble_line{$response-1} +1;
                   4911:     my $bubble_lines= $bubble_lines_per_response{$response-1};
                   4912:     
                   4913:     my $selected = "";
                   4914: 
                   4915:     for (my $bline = 0; $bline < $bubble_lines; $bline++) {
                   4916: 	$selected .= $$parsed_line{"scantron.$bubble_line.answer"}.":";
                   4917: 	$bubble_line++;
                   4918:     }
                   4919:     return $selected;
                   4920: }
1.423     albertel 4921: 
                   4922: =pod 
                   4923: 
                   4924: =item scantron_filenames
                   4925: 
                   4926:    Returns a list of the scantron files in the current course 
                   4927: 
                   4928: =cut
1.422     foxr     4929: 
1.202     albertel 4930: sub scantron_filenames {
1.257     albertel 4931:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   4932:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
1.517     raeburn  4933:     my $getpropath = 1;
1.157     albertel 4934:     my @files=&Apache::lonnet::dirlist('userfiles',$cdom,$cname,
1.517     raeburn  4935:                                        $getpropath);
1.202     albertel 4936:     my @possiblenames;
1.201     albertel 4937:     foreach my $filename (sort(@files)) {
1.157     albertel 4938: 	($filename)=split(/&/,$filename);
                   4939: 	if ($filename!~/^scantron_orig_/) { next ; }
                   4940: 	$filename=~s/^scantron_orig_//;
1.202     albertel 4941: 	push(@possiblenames,$filename);
                   4942:     }
                   4943:     return @possiblenames;
                   4944: }
                   4945: 
1.423     albertel 4946: =pod 
                   4947: 
                   4948: =item scantron_uploads
                   4949: 
                   4950:    Returns  html drop-down list of scantron files in current course.
                   4951: 
                   4952:  Arguments:
                   4953:    $file2grade - filename to set as selected in the dropdown
                   4954: 
                   4955: =cut
1.422     foxr     4956: 
1.202     albertel 4957: sub scantron_uploads {
1.209     ng       4958:     my ($file2grade) = @_;
1.202     albertel 4959:     my $result=	'<select name="scantron_selectfile">';
                   4960:     $result.="<option></option>";
                   4961:     foreach my $filename (sort(&scantron_filenames())) {
1.401     albertel 4962: 	$result.="<option".($filename eq $file2grade ? ' selected="selected"':'').">$filename</option>\n";
1.81      albertel 4963:     }
                   4964:     $result.="</select>";
                   4965:     return $result;
                   4966: }
                   4967: 
1.423     albertel 4968: =pod 
                   4969: 
                   4970: =item scantron_scantab
                   4971: 
                   4972:   Returns html drop down of the scantron formats in the scantronformat.tab
                   4973:   file.
                   4974: 
                   4975: =cut
1.422     foxr     4976: 
1.82      albertel 4977: sub scantron_scantab {
                   4978:     my $result='<select name="scantron_format">'."\n";
1.191     albertel 4979:     $result.='<option></option>'."\n";
1.518     raeburn  4980:     my @lines = &get_scantronformat_file();
                   4981:     if (@lines > 0) {
                   4982:         foreach my $line (@lines) {
                   4983:             next if (($line =~ /^\#/) || ($line eq ''));
                   4984: 	    my ($name,$descrip)=split(/:/,$line);
                   4985: 	    $result.='<option value="'.$name.'">'.$descrip.'</option>'."\n";
                   4986:         }
1.82      albertel 4987:     }
                   4988:     $result.='</select>'."\n";
1.518     raeburn  4989:     return $result;
                   4990: }
                   4991: 
                   4992: =pod
                   4993: 
                   4994: =item get_scantronformat_file
                   4995: 
                   4996:   Returns an array containing lines from the scantron format file for
                   4997:   the domain of the course.
                   4998: 
                   4999:   If a url for a custom.tab file is listed in domain's configuration.db, 
                   5000:   lines are from this file.
                   5001: 
                   5002:   Otherwise, if a default.tab has been published in RES space by the 
                   5003:   domainconfig user, lines are from this file.
                   5004: 
                   5005:   Otherwise, fall back to getting lines from the legacy file on the
1.519     raeburn  5006:   local server:  /home/httpd/lonTabs/default_scantronformat.tab    
1.82      albertel 5007: 
1.518     raeburn  5008: =cut
                   5009: 
                   5010: sub get_scantronformat_file {
                   5011:     my $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
                   5012:     my %domconfig = &Apache::lonnet::get_dom('configuration',['scantron'],$cdom);
                   5013:     my $gottab = 0;
                   5014:     my @lines;
                   5015:     if (ref($domconfig{'scantron'}) eq 'HASH') {
                   5016:         if ($domconfig{'scantron'}{'scantronformat'} ne '') {
                   5017:             my $formatfile = &Apache::lonnet::getfile($Apache::lonnet::perlvar{'lonDocRoot'}.$domconfig{'scantron'}{'scantronformat'});
                   5018:             if ($formatfile ne '-1') {
                   5019:                 @lines = split("\n",$formatfile,-1);
                   5020:                 $gottab = 1;
                   5021:             }
                   5022:         }
                   5023:     }
                   5024:     if (!$gottab) {
                   5025:         my $confname = $cdom.'-domainconfig';
                   5026:         my $default = $Apache::lonnet::perlvar{'lonDocRoot'}.'/res/'.$cdom.'/'.$confname.'/default.tab';
                   5027:         my $formatfile =  &Apache::lonnet::getfile($default);
                   5028:         if ($formatfile ne '-1') {
                   5029:             @lines = split("\n",$formatfile,-1);
                   5030:             $gottab = 1;
                   5031:         }
                   5032:     }
                   5033:     if (!$gottab) {
1.519     raeburn  5034:         my @domains = &Apache::lonnet::current_machine_domains();
                   5035:         if (grep(/^\Q$cdom\E$/,@domains)) {
                   5036:             my $fh=Apache::File->new($Apache::lonnet::perlvar{'lonTabDir'}.'/scantronformat.tab');
                   5037:             @lines = <$fh>;
                   5038:             close($fh);
                   5039:         } else {
                   5040:             my $fh=Apache::File->new($Apache::lonnet::perlvar{'lonTabDir'}.'/default_scantronformat.tab');
                   5041:             @lines = <$fh>;
                   5042:             close($fh);
                   5043:         }
1.518     raeburn  5044:     }
                   5045:     return @lines;
1.82      albertel 5046: }
                   5047: 
1.423     albertel 5048: =pod 
                   5049: 
                   5050: =item scantron_CODElist
                   5051: 
                   5052:   Returns html drop down of the saved CODE lists from current course,
                   5053:   generated from earlier printings.
                   5054: 
                   5055: =cut
1.422     foxr     5056: 
1.186     albertel 5057: sub scantron_CODElist {
1.257     albertel 5058:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   5059:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
1.186     albertel 5060:     my @names=&Apache::lonnet::getkeys('CODEs',$cdom,$cnum);
                   5061:     my $namechoice='<option></option>';
1.225     albertel 5062:     foreach my $name (sort {uc($a) cmp uc($b)} @names) {
1.191     albertel 5063: 	if ($name =~ /^error: 2 /) { next; }
1.278     albertel 5064: 	if ($name =~ /^type\0/) { next; }
1.186     albertel 5065: 	$namechoice.='<option value="'.$name.'">'.$name.'</option>';
                   5066:     }
                   5067:     $namechoice='<select name="scantron_CODElist">'.$namechoice.'</select>';
                   5068:     return $namechoice;
                   5069: }
                   5070: 
1.423     albertel 5071: =pod 
                   5072: 
                   5073: =item scantron_CODEunique
                   5074: 
                   5075:   Returns the html for "Each CODE to be used once" radio.
                   5076: 
                   5077: =cut
1.422     foxr     5078: 
1.186     albertel 5079: sub scantron_CODEunique {
1.532     bisitz   5080:     my $result='<span class="LC_nobreak">
1.272     albertel 5081:                  <label><input type="radio" name="scantron_CODEunique"
1.423     albertel 5082:                         value="yes" checked="checked" />'.&mt('Yes').' </label>
1.381     albertel 5083:                 </span>
1.532     bisitz   5084:                 <span class="LC_nobreak">
1.272     albertel 5085:                  <label><input type="radio" name="scantron_CODEunique"
1.423     albertel 5086:                         value="no" />'.&mt('No').' </label>
1.381     albertel 5087:                 </span>';
1.186     albertel 5088:     return $result;
                   5089: }
1.423     albertel 5090: 
                   5091: =pod 
                   5092: 
                   5093: =item scantron_selectphase
                   5094: 
                   5095:   Generates the initial screen to start the bubble sheet process.
                   5096:   Allows for - starting a grading run.
1.424     albertel 5097:              - downloading existing scan data (original, corrected
1.423     albertel 5098:                                                 or skipped info)
                   5099: 
                   5100:              - uploading new scan data
                   5101: 
                   5102:  Arguments:
                   5103:   $r          - The Apache request object
                   5104:   $file2grade - name of the file that contain the scanned data to score
                   5105: 
                   5106: =cut
1.186     albertel 5107: 
1.75      albertel 5108: sub scantron_selectphase {
1.608     www      5109:     my ($r,$file2grade,$symb) = @_;
1.75      albertel 5110:     if (!$symb) {return '';}
1.582     raeburn  5111:     my $map_error;
                   5112:     my $sequence_selector=&getSequenceDropDown($symb,\$map_error);
                   5113:     if ($map_error) {
                   5114:         $r->print('<br />'.&navmap_errormsg().'<br />');
                   5115:         return;
                   5116:     }
1.324     albertel 5117:     my $default_form_data=&defaultFormData($symb);
1.209     ng       5118:     my $file_selector=&scantron_uploads($file2grade);
1.82      albertel 5119:     my $format_selector=&scantron_scantab();
1.186     albertel 5120:     my $CODE_selector=&scantron_CODElist();
                   5121:     my $CODE_unique=&scantron_CODEunique();
1.75      albertel 5122:     my $result;
1.422     foxr     5123: 
1.513     foxr     5124:     $ssi_error = 0;
                   5125: 
1.606     wenzelju 5126:     if (&Apache::lonnet::allowed('usc',$env{'request.role.domain'}) ||
                   5127:         &Apache::lonnet::allowed('usc',$env{'request.course.id'})) {
                   5128: 
                   5129: 	# Chunk of form to prompt for a scantron file upload.
                   5130: 
                   5131:         $r->print('
                   5132:     <br />
                   5133:     '.&Apache::loncommon::start_data_table('LC_scantron_action').'
                   5134:        '.&Apache::loncommon::start_data_table_header_row().'
                   5135:             <th>
                   5136:               &nbsp;'.&mt('Specify a bubblesheet data file to upload.').'
                   5137:             </th>
                   5138:        '.&Apache::loncommon::end_data_table_header_row().'
                   5139:        '.&Apache::loncommon::start_data_table_row().'
                   5140:             <td>
                   5141: ');
1.608     www      5142:     my $default_form_data=&defaultFormData($symb);
1.606     wenzelju 5143:     my $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
                   5144:     my $cnum= $env{'course.'.$env{'request.course.id'}.'.num'};
                   5145:     $r->print(&Apache::lonhtmlcommon::scripttag('
                   5146:     function checkUpload(formname) {
                   5147: 	if (formname.upfile.value == "") {
                   5148: 	    alert("'.&mt('Please use the browse button to select a file from your local directory.').'");
                   5149: 	    return false;
                   5150: 	}
                   5151: 	formname.submit();
                   5152:     }'));
                   5153:     $r->print('
                   5154:               <form enctype="multipart/form-data" action="/adm/grades" name="rules" method="post">
                   5155:                 '.$default_form_data.'
                   5156:                 <input name="courseid" type="hidden" value="'.$cnum.'" />
                   5157:                 <input name="domainid" type="hidden" value="'.$cdom.'" />
                   5158:                 <input name="command" value="scantronupload_save" type="hidden" />
                   5159:                 '.&mt('File to upload: [_1]','<input type="file" name="upfile" size="50" />').'
                   5160:                 <br />
                   5161:                 <input type="button" onclick="javascript:checkUpload(this.form);" value="'.&mt('Upload Bubblesheet Data').'" />
                   5162:               </form>
                   5163: ');
                   5164: 
                   5165:         $r->print('
                   5166:             </td>
                   5167:        '.&Apache::loncommon::end_data_table_row().'
                   5168:        '.&Apache::loncommon::end_data_table().'
                   5169: ');
                   5170:     }
                   5171: 
1.422     foxr     5172:     # Chunk of form to prompt for a file to grade and how:
                   5173: 
1.489     albertel 5174:     $result.= '
                   5175:     <br />
                   5176:     <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantron_process">
                   5177:     <input type="hidden" name="command" value="scantron_warning" />
                   5178:     '.$default_form_data.'
                   5179:     '.&Apache::loncommon::start_data_table('LC_scantron_action').'
                   5180:        '.&Apache::loncommon::start_data_table_header_row().'
                   5181:             <th colspan="2">
1.492     albertel 5182:               &nbsp;'.&mt('Specify file and which Folder/Sequence to grade').'
1.489     albertel 5183:             </th>
                   5184:        '.&Apache::loncommon::end_data_table_header_row().'
                   5185:        '.&Apache::loncommon::start_data_table_row().'
1.492     albertel 5186:             <td> '.&mt('Sequence to grade:').' </td><td> '.$sequence_selector.' </td>
1.489     albertel 5187:        '.&Apache::loncommon::end_data_table_row().'
                   5188:        '.&Apache::loncommon::start_data_table_row().'
1.572     www      5189:             <td> '.&mt('Filename of bubblesheet data file:').' </td><td> '.$file_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('Format of bubblesheet data file:').' </td><td> '.$format_selector.' </td>
1.489     albertel 5193:        '.&Apache::loncommon::end_data_table_row().'
                   5194:        '.&Apache::loncommon::start_data_table_row().'
1.492     albertel 5195:             <td> '.&mt('Saved CODEs to validate against:').' </td><td> '.$CODE_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('Each CODE is only to be used once:').'</td><td> '.$CODE_unique.' </td>
1.489     albertel 5199:        '.&Apache::loncommon::end_data_table_row().'
                   5200:        '.&Apache::loncommon::start_data_table_row().'
1.492     albertel 5201: 	    <td> '.&mt('Options:').' </td>
1.187     albertel 5202:             <td>
1.492     albertel 5203: 	       <label><input type="checkbox" name="scantron_options_redo" value="redo_skipped"/> '.&mt('Do only previously skipped records').'</label> <br />
                   5204:                <label><input type="checkbox" name="scantron_options_ignore" value="ignore_corrections"/> '.&mt('Remove all existing corrections').'</label> <br />
                   5205:                <label><input type="checkbox" name="scantron_options_hidden" value="ignore_hidden"/> '.&mt('Skip hidden resources when grading').'</label>
1.187     albertel 5206: 	    </td>
1.489     albertel 5207:        '.&Apache::loncommon::end_data_table_row().'
                   5208:        '.&Apache::loncommon::start_data_table_row().'
1.174     albertel 5209:             <td colspan="2">
1.572     www      5210:               <input type="submit" value="'.&mt('Grading: Validate Bubblesheet Records').'" />
1.162     albertel 5211:             </td>
1.489     albertel 5212:        '.&Apache::loncommon::end_data_table_row().'
                   5213:     '.&Apache::loncommon::end_data_table().'
                   5214:     </form>
                   5215: ';
1.162     albertel 5216:    
                   5217:     $r->print($result);
                   5218: 
1.422     foxr     5219: 
                   5220: 
                   5221:     # Chunk of the form that prompts to view a scoring office file,
                   5222:     # corrected file, skipped records in a file.
                   5223: 
1.489     albertel 5224:     $r->print('
                   5225:    <br />
                   5226:    <form action="/adm/grades" name="scantron_download">
                   5227:      '.$default_form_data.'
                   5228:      <input type="hidden" name="command" value="scantron_download" />
                   5229:      '.&Apache::loncommon::start_data_table('LC_scantron_action').'
                   5230:        '.&Apache::loncommon::start_data_table_header_row().'
                   5231:               <th>
1.492     albertel 5232:                 &nbsp;'.&mt('Download a scoring office file').'
1.489     albertel 5233:               </th>
                   5234:        '.&Apache::loncommon::end_data_table_header_row().'
                   5235:        '.&Apache::loncommon::start_data_table_row().'
1.492     albertel 5236:               <td> '.&mt('Filename of scoring office file: [_1]',$file_selector).' 
1.489     albertel 5237:                 <br />
1.492     albertel 5238:                 <input type="submit" value="'.&mt('Download: Show List of Associated Files').'" />
1.489     albertel 5239:        '.&Apache::loncommon::end_data_table_row().'
                   5240:      '.&Apache::loncommon::end_data_table().'
                   5241:    </form>
                   5242:    <br />
                   5243: ');
1.162     albertel 5244: 
1.457     banghart 5245:     &Apache::lonpickcode::code_list($r,2);
1.523     raeburn  5246: 
1.528     raeburn  5247:     $r->print('<br /><form method="post" name="checkscantron">'.
1.523     raeburn  5248:              $default_form_data."\n".
                   5249:              &Apache::loncommon::start_data_table('LC_scantron_action')."\n".
                   5250:              &Apache::loncommon::start_data_table_header_row()."\n".
                   5251:              '<th colspan="2">
1.572     www      5252:               &nbsp;'.&mt('Review bubblesheet data and submissions for a previously graded folder/sequence')."\n".
1.523     raeburn  5253:              '</th>'."\n".
                   5254:               &Apache::loncommon::end_data_table_header_row()."\n".
                   5255:               &Apache::loncommon::start_data_table_row()."\n".
                   5256:               '<td> '.&mt('Graded folder/sequence:').' </td>'."\n".
                   5257:               '<td> '.$sequence_selector.' </td>'.
                   5258:               &Apache::loncommon::end_data_table_row()."\n".
                   5259:               &Apache::loncommon::start_data_table_row()."\n".
                   5260:               '<td> '.&mt('Filename of scoring office file:').' </td>'."\n".
                   5261:               '<td> '.$file_selector.' </td>'."\n".
                   5262:               &Apache::loncommon::end_data_table_row()."\n".
                   5263:               &Apache::loncommon::start_data_table_row()."\n".
                   5264:               '<td> '.&mt('Format of data file:').' </td>'."\n".
                   5265:               '<td> '.$format_selector.' </td>'."\n".
                   5266:               &Apache::loncommon::end_data_table_row()."\n".
                   5267:               &Apache::loncommon::start_data_table_row()."\n".
1.557     raeburn  5268:               '<td> '.&mt('Options').' </td>'."\n".
                   5269:               '<td> <label><input type="checkbox" name="scantron_options_hidden" value="ignore_hidden"/> '.&mt('Skip hidden resources').'</label></td>'.
                   5270:               &Apache::loncommon::end_data_table_row()."\n".
                   5271:               &Apache::loncommon::start_data_table_row()."\n".
1.523     raeburn  5272:               '<td colspan="2">'."\n".
                   5273:               '<input type="hidden" name="command" value="checksubmissions" />'."\n".
1.575     www      5274:               '<input type="submit" value="'.&mt('Review Bubblesheet Data and Submission Records').'" />'."\n".
1.523     raeburn  5275:               '</td>'."\n".
                   5276:               &Apache::loncommon::end_data_table_row()."\n".
                   5277:               &Apache::loncommon::end_data_table()."\n".
                   5278:               '</form><br />');
                   5279:     return;
1.75      albertel 5280: }
                   5281: 
1.423     albertel 5282: =pod
                   5283: 
                   5284: =item get_scantron_config
                   5285: 
                   5286:    Parse and return the scantron configuration line selected as a
                   5287:    hash of configuration file fields.
                   5288: 
                   5289:  Arguments:
                   5290:     which - the name of the configuration to parse from the file.
                   5291: 
                   5292: 
                   5293:  Returns:
                   5294:             If the named configuration is not in the file, an empty
                   5295:             hash is returned.
                   5296:     a hash with the fields
                   5297:       name         - internal name for the this configuration setup
                   5298:       description  - text to display to operator that describes this config
                   5299:       CODElocation - if 0 or the string 'none'
                   5300:                           - no CODE exists for this config
                   5301:                      if -1 || the string 'letter'
                   5302:                           - a CODE exists for this config and is
                   5303:                             a string of letters
                   5304:                      Unsupported value (but planned for future support)
                   5305:                           if a positive integer
                   5306:                                - The CODE exists as the first n items from
                   5307:                                  the question section of the form
                   5308:                           if the string 'number'
                   5309:                                - The CODE exists for this config and is
                   5310:                                  a string of numbers
                   5311:       CODEstart   - (only matter if a CODE exists) column in the line where
                   5312:                      the CODE starts
                   5313:       CODElength  - length of the CODE
1.573     bisitz   5314:       IDstart     - column where the student/employee ID starts
1.556     weissno  5315:       IDlength    - length of the student/employee ID info
1.423     albertel 5316:       Qstart      - column where the information from the bubbled
                   5317:                     'questions' start
                   5318:       Qlength     - number of columns comprising a single bubble line from
                   5319:                     the sheet. (usually either 1 or 10)
1.424     albertel 5320:       Qon         - either a single character representing the character used
1.423     albertel 5321:                     to signal a bubble was chosen in the positional setup, or
                   5322:                     the string 'letter' if the letter of the chosen bubble is
                   5323:                     in the final, or 'number' if a number representing the
                   5324:                     chosen bubble is in the file (1->A 0->J)
1.424     albertel 5325:       Qoff        - the character used to represent that a bubble was
                   5326:                     left blank
1.423     albertel 5327:       PaperID     - if the scanning process generates a unique number for each
                   5328:                     sheet scanned the column that this ID number starts in
                   5329:       PaperIDlength - number of columns that comprise the unique ID number
                   5330:                       for the sheet of paper
1.424     albertel 5331:       FirstName   - column that the first name starts in
1.423     albertel 5332:       FirstNameLength - number of columns that the first name spans
                   5333:  
                   5334:       LastName    - column that the last name starts in
                   5335:       LastNameLength - number of columns that the last name spans
                   5336: 
                   5337: =cut
1.422     foxr     5338: 
1.82      albertel 5339: sub get_scantron_config {
                   5340:     my ($which) = @_;
1.518     raeburn  5341:     my @lines = &get_scantronformat_file();
1.82      albertel 5342:     my %config;
1.157     albertel 5343:     #FIXME probably should move to XML it has already gotten a bit much now
1.518     raeburn  5344:     foreach my $line (@lines) {
1.82      albertel 5345: 	my ($name,$descrip)=split(/:/,$line);
                   5346: 	if ($name ne $which ) { next; }
                   5347: 	chomp($line);
                   5348: 	my @config=split(/:/,$line);
                   5349: 	$config{'name'}=$config[0];
                   5350: 	$config{'description'}=$config[1];
                   5351: 	$config{'CODElocation'}=$config[2];
                   5352: 	$config{'CODEstart'}=$config[3];
                   5353: 	$config{'CODElength'}=$config[4];
                   5354: 	$config{'IDstart'}=$config[5];
                   5355: 	$config{'IDlength'}=$config[6];
                   5356: 	$config{'Qstart'}=$config[7];
1.497     foxr     5357:  	$config{'Qlength'}=$config[8];
1.82      albertel 5358: 	$config{'Qoff'}=$config[9];
                   5359: 	$config{'Qon'}=$config[10];
1.157     albertel 5360: 	$config{'PaperID'}=$config[11];
                   5361: 	$config{'PaperIDlength'}=$config[12];
                   5362: 	$config{'FirstName'}=$config[13];
                   5363: 	$config{'FirstNamelength'}=$config[14];
                   5364: 	$config{'LastName'}=$config[15];
                   5365: 	$config{'LastNamelength'}=$config[16];
1.82      albertel 5366: 	last;
                   5367:     }
                   5368:     return %config;
                   5369: }
                   5370: 
1.423     albertel 5371: =pod 
                   5372: 
                   5373: =item username_to_idmap
                   5374: 
1.556     weissno  5375:     creates a hash keyed by student/employee ID with values of the corresponding
1.423     albertel 5376:     student username:domain.
                   5377: 
                   5378:   Arguments:
                   5379: 
                   5380:     $classlist - reference to the class list hash. This is a hash
                   5381:                  keyed by student name:domain  whose elements are references
1.424     albertel 5382:                  to arrays containing various chunks of information
1.423     albertel 5383:                  about the student. (See loncoursedata for more info).
                   5384: 
                   5385:   Returns
                   5386:     %idmap - the constructed hash
                   5387: 
                   5388: =cut
                   5389: 
1.82      albertel 5390: sub username_to_idmap {
                   5391:     my ($classlist)= @_;
                   5392:     my %idmap;
                   5393:     foreach my $student (keys(%$classlist)) {
                   5394: 	$idmap{$classlist->{$student}->[&Apache::loncoursedata::CL_ID]}=
                   5395: 	    $student;
                   5396:     }
                   5397:     return %idmap;
                   5398: }
1.423     albertel 5399: 
                   5400: =pod
                   5401: 
1.424     albertel 5402: =item scantron_fixup_scanline
1.423     albertel 5403: 
                   5404:    Process a requested correction to a scanline.
                   5405: 
                   5406:   Arguments:
                   5407:     $scantron_config   - hash from &get_scantron_config()
                   5408:     $scan_data         - hash of correction information 
                   5409:                           (see &scantron_getfile())
                   5410:     $line              - existing scanline
                   5411:     $whichline         - line number of the passed in scanline
                   5412:     $field             - type of change to process 
                   5413:                          (either 
1.573     bisitz   5414:                           'ID'     -> correct the student/employee ID
1.423     albertel 5415:                           'CODE'   -> correct the CODE
                   5416:                           'answer' -> fixup the submitted answers)
                   5417:     
                   5418:    $args               - hash of additional info,
                   5419:                           - 'ID' 
                   5420:                                'newid' -> studentID to use in replacement
1.424     albertel 5421:                                           of existing one
1.423     albertel 5422:                           - 'CODE' 
                   5423:                                'CODE_ignore_dup' - set to true if duplicates
                   5424:                                                    should be ignored.
                   5425: 	                       'CODE' - is new code or 'use_unfound'
1.424     albertel 5426:                                         if the existing unfound code should
1.423     albertel 5427:                                         be used as is
                   5428:                           - 'answer'
                   5429:                                'response' - new answer or 'none' if blank
                   5430:                                'question' - the bubble line to change
1.503     raeburn  5431:                                'questionnum' - the question identifier,
                   5432:                                                may include subquestion. 
1.423     albertel 5433: 
                   5434:   Returns:
                   5435:     $line - the modified scanline
                   5436: 
                   5437:   Side effects: 
                   5438:     $scan_data - may be updated
                   5439: 
                   5440: =cut
                   5441: 
1.82      albertel 5442: 
1.157     albertel 5443: sub scantron_fixup_scanline {
                   5444:     my ($scantron_config,$scan_data,$line,$whichline,$field,$args)=@_;
                   5445:     if ($field eq 'ID') {
                   5446: 	if (length($args->{'newid'}) > $$scantron_config{'IDlength'}) {
1.186     albertel 5447: 	    return ($line,1,'New value too large');
1.157     albertel 5448: 	}
                   5449: 	if (length($args->{'newid'}) < $$scantron_config{'IDlength'}) {
                   5450: 	    $args->{'newid'}=sprintf('%-'.$$scantron_config{'IDlength'}.'s',
                   5451: 				     $args->{'newid'});
                   5452: 	}
                   5453: 	substr($line,$$scantron_config{'IDstart'}-1,
                   5454: 	       $$scantron_config{'IDlength'})=$args->{'newid'};
                   5455: 	if ($args->{'newid'}=~/^\s*$/) {
                   5456: 	    &scan_data($scan_data,"$whichline.user",
                   5457: 		       $args->{'username'}.':'.$args->{'domain'});
                   5458: 	}
1.186     albertel 5459:     } elsif ($field eq 'CODE') {
1.192     albertel 5460: 	if ($args->{'CODE_ignore_dup'}) {
                   5461: 	    &scan_data($scan_data,"$whichline.CODE_ignore_dup",'1');
                   5462: 	}
                   5463: 	&scan_data($scan_data,"$whichline.useCODE",'1');
                   5464: 	if ($args->{'CODE'} ne 'use_unfound') {
1.191     albertel 5465: 	    if (length($args->{'CODE'}) > $$scantron_config{'CODElength'}) {
                   5466: 		return ($line,1,'New CODE value too large');
                   5467: 	    }
                   5468: 	    if (length($args->{'CODE'}) < $$scantron_config{'CODElength'}) {
                   5469: 		$args->{'CODE'}=sprintf('%-'.$$scantron_config{'CODElength'}.'s',$args->{'CODE'});
                   5470: 	    }
                   5471: 	    substr($line,$$scantron_config{'CODEstart'}-1,
                   5472: 		   $$scantron_config{'CODElength'})=$args->{'CODE'};
1.186     albertel 5473: 	}
1.157     albertel 5474:     } elsif ($field eq 'answer') {
1.497     foxr     5475: 	my $length=$scantron_config->{'Qlength'};
1.157     albertel 5476: 	my $off=$scantron_config->{'Qoff'};
                   5477: 	my $on=$scantron_config->{'Qon'};
1.497     foxr     5478: 	my $answer=${off}x$length;
                   5479: 	if ($args->{'response'} eq 'none') {
                   5480: 	    &scan_data($scan_data,
1.503     raeburn  5481: 		       "$whichline.no_bubble.".$args->{'questionnum'},'1');
1.497     foxr     5482: 	} else {
                   5483: 	    if ($on eq 'letter') {
                   5484: 		my @alphabet=('A'..'Z');
                   5485: 		$answer=$alphabet[$args->{'response'}];
                   5486: 	    } elsif ($on eq 'number') {
                   5487: 		$answer=$args->{'response'}+1;
                   5488: 		if ($answer == 10) { $answer = '0'; }
1.274     albertel 5489: 	    } else {
1.497     foxr     5490: 		substr($answer,$args->{'response'},1)=$on;
1.274     albertel 5491: 	    }
1.497     foxr     5492: 	    &scan_data($scan_data,
1.503     raeburn  5493: 		       "$whichline.no_bubble.".$args->{'questionnum'},undef,'1');
1.157     albertel 5494: 	}
1.497     foxr     5495: 	my $where=$length*($args->{'question'}-1)+$scantron_config->{'Qstart'};
                   5496: 	substr($line,$where-1,$length)=$answer;
1.157     albertel 5497:     }
                   5498:     return $line;
                   5499: }
1.423     albertel 5500: 
                   5501: =pod
                   5502: 
                   5503: =item scan_data
                   5504: 
                   5505:     Edit or look up  an item in the scan_data hash.
                   5506: 
                   5507:   Arguments:
                   5508:     $scan_data  - The hash (see scantron_getfile)
                   5509:     $key        - shorthand of the key to edit (actual key is
1.424     albertel 5510:                   scantronfilename_key).
1.423     albertel 5511:     $data        - New value of the hash entry.
                   5512:     $delete      - If true, the entry is removed from the hash.
                   5513: 
                   5514:   Returns:
                   5515:     The new value of the hash table field (undefined if deleted).
                   5516: 
                   5517: =cut
                   5518: 
                   5519: 
1.157     albertel 5520: sub scan_data {
                   5521:     my ($scan_data,$key,$value,$delete)=@_;
1.257     albertel 5522:     my $filename=$env{'form.scantron_selectfile'};
1.157     albertel 5523:     if (defined($value)) {
                   5524: 	$scan_data->{$filename.'_'.$key} = $value;
                   5525:     }
                   5526:     if ($delete) { delete($scan_data->{$filename.'_'.$key}); }
                   5527:     return $scan_data->{$filename.'_'.$key};
                   5528: }
1.423     albertel 5529: 
1.495     albertel 5530: # ----- These first few routines are general use routines.----
                   5531: 
                   5532: # Return the number of occurences of a pattern in a string.
                   5533: 
                   5534: sub occurence_count {
                   5535:     my ($string, $pattern) = @_;
                   5536: 
                   5537:     my @matches = ($string =~ /$pattern/g);
                   5538: 
                   5539:     return scalar(@matches);
                   5540: }
                   5541: 
                   5542: 
                   5543: # Take a string known to have digits and convert all the
                   5544: # digits into letters in the range J,A..I.
                   5545: 
                   5546: sub digits_to_letters {
                   5547:     my ($input) = @_;
                   5548: 
                   5549:     my @alphabet = ('J', 'A'..'I');
                   5550: 
                   5551:     my @input    = split(//, $input);
                   5552:     my $output ='';
                   5553:     for (my $i = 0; $i < scalar(@input); $i++) {
                   5554: 	if ($input[$i] =~ /\d/) {
                   5555: 	    $output .= $alphabet[$input[$i]];
                   5556: 	} else {
                   5557: 	    $output .= $input[$i];
                   5558: 	}
                   5559:     }
                   5560:     return $output;
                   5561: }
                   5562: 
1.423     albertel 5563: =pod 
                   5564: 
                   5565: =item scantron_parse_scanline
                   5566: 
                   5567:   Decodes a scanline from the selected scantron file
                   5568: 
                   5569:  Arguments:
                   5570:     line             - The text of the scantron file line to process
                   5571:     whichline        - Line number
                   5572:     scantron_config  - Hash describing the format of the scantron lines.
                   5573:     scan_data        - Hash of extra information about the scanline
                   5574:                        (see scantron_getfile for more information)
                   5575:     just_header      - True if should not process question answers but only
                   5576:                        the stuff to the left of the answers.
                   5577:  Returns:
                   5578:    Hash containing the result of parsing the scanline
                   5579: 
                   5580:    Keys are all proceeded by the string 'scantron.'
                   5581: 
                   5582:        CODE    - the CODE in use for this scanline
                   5583:        useCODE - 1 if the CODE is invalid but it usage has been forced
                   5584:                  by the operator
                   5585:        CODE_ignore_dup - 1 if the CODE is a duplicated use when unique
                   5586:                             CODEs were selected, but the usage has been
                   5587:                             forced by the operator
1.556     weissno  5588:        ID  - student/employee ID
1.423     albertel 5589:        PaperID - if used, the ID number printed on the sheet when the 
                   5590:                  paper was scanned
                   5591:        FirstName - first name from the sheet
                   5592:        LastName  - last name from the sheet
                   5593: 
                   5594:      if just_header was not true these key may also exist
                   5595: 
1.447     foxr     5596:        missingerror - a list of bubble ranges that are considered to be answers
                   5597:                       to a single question that don't have any bubbles filled in.
                   5598:                       Of the form questionnumber:firstbubblenumber:count.
                   5599:        doubleerror  - a list of bubble ranges that are considered to be answers
                   5600:                       to a single question that have more than one bubble filled in.
                   5601:                       Of the form questionnumber::firstbubblenumber:count
                   5602:    
                   5603:                 In the above, count is the number of bubble responses in the
                   5604:                 input line needed to represent the possible answers to the question.
                   5605:                 e.g. a radioresponse with 15 choices in an answer sheet with 10 choices
                   5606:                 per line would have count = 2.
                   5607: 
1.423     albertel 5608:        maxquest     - the number of the last bubble line that was parsed
                   5609: 
                   5610:        (<number> starts at 1)
                   5611:        <number>.answer - zero or more letters representing the selected
                   5612:                          letters from the scanline for the bubble line 
                   5613:                          <number>.
                   5614:                          if blank there was either no bubble or there where
                   5615:                          multiple bubbles, (consult the keys missingerror and
                   5616:                          doubleerror if this is an error condition)
                   5617: 
                   5618: =cut
                   5619: 
1.82      albertel 5620: sub scantron_parse_scanline {
1.423     albertel 5621:     my ($line,$whichline,$scantron_config,$scan_data,$just_header)=@_;
1.470     foxr     5622: 
1.82      albertel 5623:     my %record;
1.550     raeburn  5624:     my $lastpos = $env{'form.scantron_maxbubble'}*$$scantron_config{'Qlength'};
                   5625:     my $questions=substr($line,$$scantron_config{'Qstart'}-1,$lastpos);  # Answers
1.422     foxr     5626:     my $data=substr($line,0,$$scantron_config{'Qstart'}-1);     # earlier stuff
1.278     albertel 5627:     if (!($$scantron_config{'CODElocation'} eq 0 ||
                   5628: 	  $$scantron_config{'CODElocation'} eq 'none')) {
                   5629: 	if ($$scantron_config{'CODElocation'} < 0 ||
                   5630: 	    $$scantron_config{'CODElocation'} eq 'letter' ||
                   5631: 	    $$scantron_config{'CODElocation'} eq 'number') {
1.191     albertel 5632: 	    $record{'scantron.CODE'}=substr($data,
                   5633: 					    $$scantron_config{'CODEstart'}-1,
1.83      albertel 5634: 					    $$scantron_config{'CODElength'});
1.191     albertel 5635: 	    if (&scan_data($scan_data,"$whichline.useCODE")) {
                   5636: 		$record{'scantron.useCODE'}=1;
                   5637: 	    }
1.192     albertel 5638: 	    if (&scan_data($scan_data,"$whichline.CODE_ignore_dup")) {
                   5639: 		$record{'scantron.CODE_ignore_dup'}=1;
                   5640: 	    }
1.82      albertel 5641: 	} else {
                   5642: 	    #FIXME interpret first N questions
                   5643: 	}
                   5644:     }
1.83      albertel 5645:     $record{'scantron.ID'}=substr($data,$$scantron_config{'IDstart'}-1,
                   5646: 				  $$scantron_config{'IDlength'});
1.157     albertel 5647:     $record{'scantron.PaperID'}=
                   5648: 	substr($data,$$scantron_config{'PaperID'}-1,
                   5649: 	       $$scantron_config{'PaperIDlength'});
                   5650:     $record{'scantron.FirstName'}=
                   5651: 	substr($data,$$scantron_config{'FirstName'}-1,
                   5652: 	       $$scantron_config{'FirstNamelength'});
                   5653:     $record{'scantron.LastName'}=
                   5654: 	substr($data,$$scantron_config{'LastName'}-1,
                   5655: 	       $$scantron_config{'LastNamelength'});
1.423     albertel 5656:     if ($just_header) { return \%record; }
1.194     albertel 5657: 
1.82      albertel 5658:     my @alphabet=('A'..'Z');
                   5659:     my $questnum=0;
1.447     foxr     5660:     my $ansnum  =1;		# Multiple 'answer lines'/question.
                   5661: 
1.470     foxr     5662:     chomp($questions);		# Get rid of any trailing \n.
                   5663:     $questions =~ s/\r$//;      # Get rid of trailing \r too (MAC or Win uploads).
                   5664:     while (length($questions)) {
1.447     foxr     5665: 	my $answers_needed = $bubble_lines_per_response{$questnum};
1.503     raeburn  5666:         my $answer_length  = ($$scantron_config{'Qlength'} * $answers_needed)
                   5667:                              || 1;
                   5668:         $questnum++;
                   5669:         my $quest_id = $questnum;
                   5670:         my $currentquest = substr($questions,0,$answer_length);
                   5671:         $questions       = substr($questions,$answer_length);
                   5672:         if (length($currentquest) < $answer_length) { next; }
                   5673: 
                   5674:         if ($subdivided_bubble_lines{$questnum-1} =~ /,/) {
                   5675:             my $subquestnum = 1;
                   5676:             my $subquestions = $currentquest;
                   5677:             my @subanswers_needed = 
                   5678:                 split(/,/,$subdivided_bubble_lines{$questnum-1});  
                   5679:             foreach my $subans (@subanswers_needed) {
                   5680:                 my $subans_length =
                   5681:                     ($$scantron_config{'Qlength'} * $subans)  || 1;
                   5682:                 my $currsubquest = substr($subquestions,0,$subans_length);
                   5683:                 $subquestions   = substr($subquestions,$subans_length);
                   5684:                 $quest_id = "$questnum.$subquestnum";
                   5685:                 if (($$scantron_config{'Qon'} eq 'letter') ||
                   5686:                     ($$scantron_config{'Qon'} eq 'number')) {
                   5687:                     $ansnum = &scantron_validator_lettnum($ansnum, 
                   5688:                         $questnum,$quest_id,$subans,$currsubquest,$whichline,
                   5689:                         \@alphabet,\%record,$scantron_config,$scan_data);
                   5690:                 } else {
                   5691:                     $ansnum = &scantron_validator_positional($ansnum,
                   5692:                         $questnum,$quest_id,$subans,$currsubquest,$whichline,                        \@alphabet,\%record,$scantron_config,$scan_data);
                   5693:                 }
                   5694:                 $subquestnum ++;
                   5695:             }
                   5696:         } else {
                   5697:             if (($$scantron_config{'Qon'} eq 'letter') ||
                   5698:                 ($$scantron_config{'Qon'} eq 'number')) {
                   5699:                 $ansnum = &scantron_validator_lettnum($ansnum,$questnum,
                   5700:                     $quest_id,$answers_needed,$currentquest,$whichline,
                   5701:                     \@alphabet,\%record,$scantron_config,$scan_data);
                   5702:             } else {
                   5703:                 $ansnum = &scantron_validator_positional($ansnum,$questnum,
                   5704:                     $quest_id,$answers_needed,$currentquest,$whichline,
                   5705:                     \@alphabet,\%record,$scantron_config,$scan_data);
                   5706:             }
                   5707:         }
                   5708:     }
                   5709:     $record{'scantron.maxquest'}=$questnum;
                   5710:     return \%record;
                   5711: }
1.447     foxr     5712: 
1.503     raeburn  5713: sub scantron_validator_lettnum {
                   5714:     my ($ansnum,$questnum,$quest_id,$answers_needed,$currquest,$whichline,
                   5715:         $alphabet,$record,$scantron_config,$scan_data) = @_;
                   5716: 
                   5717:     # Qon 'letter' implies for each slot in currquest we have:
                   5718:     #    ? or * for doubles, a letter in A-Z for a bubble, and
                   5719:     #    about anything else (esp. a value of Qoff) for missing
                   5720:     #    bubbles.
                   5721:     #
                   5722:     # Qon 'number' implies each slot gives a digit that indexes the
                   5723:     #    bubbles filled, or Qoff, or a non-number for unbubbled lines,
                   5724:     #    and * or ? for double bubbles on a single line.
                   5725:     #
1.447     foxr     5726: 
1.503     raeburn  5727:     my $matchon;
                   5728:     if ($$scantron_config{'Qon'} eq 'letter') {
                   5729:         $matchon = '[A-Z]';
                   5730:     } elsif ($$scantron_config{'Qon'} eq 'number') {
                   5731:         $matchon = '\d';
                   5732:     }
                   5733:     my $occurrences = 0;
                   5734:     if (($responsetype_per_response{$questnum-1} eq 'essayresponse') ||
                   5735:         ($responsetype_per_response{$questnum-1} eq 'formularesponse') ||
1.510     raeburn  5736:         ($responsetype_per_response{$questnum-1} eq 'stringresponse') ||
                   5737:         ($responsetype_per_response{$questnum-1} eq 'imageresponse') ||
                   5738:         ($responsetype_per_response{$questnum-1} eq 'reactionresponse') ||
                   5739:         ($responsetype_per_response{$questnum-1} eq 'organicresponse')) {
1.503     raeburn  5740:         my @singlelines = split('',$currquest);
                   5741:         foreach my $entry (@singlelines) {
                   5742:             $occurrences = &occurence_count($entry,$matchon);
                   5743:             if ($occurrences > 1) {
                   5744:                 last;
                   5745:             }
                   5746:         } 
                   5747:     } else {
                   5748:         $occurrences = &occurence_count($currquest,$matchon); 
                   5749:     }
                   5750:     if (($currquest =~ /\?/ || $currquest =~ /\*/) || ($occurrences > 1)) {
                   5751:         push(@{$record->{'scantron.doubleerror'}},$quest_id);
                   5752:         for (my $ans=0; $ans<$answers_needed; $ans++) {
                   5753:             my $bubble = substr($currquest,$ans,1);
                   5754:             if ($bubble =~ /$matchon/ ) {
                   5755:                 if ($$scantron_config{'Qon'} eq 'number') {
                   5756:                     if ($bubble == 0) {
                   5757:                         $bubble = 10; 
                   5758:                     }
                   5759:                     $record->{"scantron.$ansnum.answer"} = 
                   5760:                         $alphabet->[$bubble-1];
                   5761:                 } else {
                   5762:                     $record->{"scantron.$ansnum.answer"} = $bubble;
                   5763:                 }
                   5764:             } else {
                   5765:                 $record->{"scantron.$ansnum.answer"}='';
                   5766:             }
                   5767:             $ansnum++;
                   5768:         }
                   5769:     } elsif (!defined($currquest)
                   5770:             || (&occurence_count($currquest, $$scantron_config{'Qoff'}) == length($currquest))
                   5771:             || (&occurence_count($currquest,$matchon) == 0)) {
                   5772:         for (my $ans=0; $ans<$answers_needed; $ans++ ) {
                   5773:             $record->{"scantron.$ansnum.answer"}='';
                   5774:             $ansnum++;
                   5775:         }
                   5776:         if (!&scan_data($scan_data,"$whichline.no_bubble.$quest_id")) {
                   5777:             push(@{$record->{'scantron.missingerror'}},$quest_id);
                   5778:         }
                   5779:     } else {
                   5780:         if ($$scantron_config{'Qon'} eq 'number') {
                   5781:             $currquest = &digits_to_letters($currquest);            
                   5782:         }
                   5783:         for (my $ans=0; $ans<$answers_needed; $ans++) {
                   5784:             my $bubble = substr($currquest,$ans,1);
                   5785:             $record->{"scantron.$ansnum.answer"} = $bubble;
                   5786:             $ansnum++;
                   5787:         }
                   5788:     }
                   5789:     return $ansnum;
                   5790: }
1.447     foxr     5791: 
1.503     raeburn  5792: sub scantron_validator_positional {
                   5793:     my ($ansnum,$questnum,$quest_id,$answers_needed,$currquest,
                   5794:         $whichline,$alphabet,$record,$scantron_config,$scan_data) = @_;
1.447     foxr     5795: 
1.503     raeburn  5796:     # Otherwise there's a positional notation;
                   5797:     # each bubble line requires Qlength items, and there are filled in
                   5798:     # bubbles for each case where there 'Qon' characters.
                   5799:     #
1.447     foxr     5800: 
1.503     raeburn  5801:     my @array=split($$scantron_config{'Qon'},$currquest,-1);
1.447     foxr     5802: 
1.503     raeburn  5803:     # If the split only gives us one element.. the full length of the
                   5804:     # answer string, no bubbles are filled in:
1.447     foxr     5805: 
1.507     raeburn  5806:     if ($answers_needed eq '') {
                   5807:         return;
                   5808:     }
                   5809: 
1.503     raeburn  5810:     if (length($array[0]) eq $$scantron_config{'Qlength'}*$answers_needed) {
                   5811:         for (my $ans=0; $ans<$answers_needed; $ans++ ) {
                   5812:             $record->{"scantron.$ansnum.answer"}='';
                   5813:             $ansnum++;
                   5814:         }
                   5815:         if (!&scan_data($scan_data,"$whichline.no_bubble.$quest_id")) {
                   5816:             push(@{$record->{"scantron.missingerror"}},$quest_id);
                   5817:         }
                   5818:     } elsif (scalar(@array) == 2) {
                   5819:         my $location = length($array[0]);
                   5820:         my $line_num = int($location / $$scantron_config{'Qlength'});
                   5821:         my $bubble   = $alphabet->[$location % $$scantron_config{'Qlength'}];
                   5822:         for (my $ans=0; $ans<$answers_needed; $ans++) {
                   5823:             if ($ans eq $line_num) {
                   5824:                 $record->{"scantron.$ansnum.answer"} = $bubble;
                   5825:             } else {
                   5826:                 $record->{"scantron.$ansnum.answer"} = ' ';
                   5827:             }
                   5828:             $ansnum++;
                   5829:          }
                   5830:     } else {
                   5831:         #  If there's more than one instance of a bubble character
                   5832:         #  That's a double bubble; with positional notation we can
                   5833:         #  record all the bubbles filled in as well as the
                   5834:         #  fact this response consists of multiple bubbles.
                   5835:         #
                   5836:         if (($responsetype_per_response{$questnum-1} eq 'essayresponse') ||
                   5837:             ($responsetype_per_response{$questnum-1} eq 'formularesponse') ||
1.510     raeburn  5838:             ($responsetype_per_response{$questnum-1} eq 'stringresponse') ||
                   5839:             ($responsetype_per_response{$questnum-1} eq 'imageresponse') ||
                   5840:             ($responsetype_per_response{$questnum-1} eq 'reactionresponse') ||
                   5841:             ($responsetype_per_response{$questnum-1} eq 'organicresponse')) {
1.503     raeburn  5842:             my $doubleerror = 0;
                   5843:             while (($currquest >= $$scantron_config{'Qlength'}) && 
                   5844:                    (!$doubleerror)) {
                   5845:                my $currline = substr($currquest,0,$$scantron_config{'Qlength'});
                   5846:                $currquest = substr($currquest,$$scantron_config{'Qlength'});
                   5847:                my @currarray = split($$scantron_config{'Qon'},$currline,-1);
                   5848:                if (length(@currarray) > 2) {
                   5849:                    $doubleerror = 1;
                   5850:                } 
                   5851:             }
                   5852:             if ($doubleerror) {
                   5853:                 push(@{$record->{'scantron.doubleerror'}},$quest_id);
                   5854:             }
                   5855:         } else {
                   5856:             push(@{$record->{'scantron.doubleerror'}},$quest_id);
                   5857:         }
                   5858:         my $item = $ansnum;
                   5859:         for (my $ans=0; $ans<$answers_needed; $ans++) {
                   5860:             $record->{"scantron.$item.answer"} = '';
                   5861:             $item ++;
                   5862:         }
1.447     foxr     5863: 
1.503     raeburn  5864:         my @ans=@array;
                   5865:         my $i=0;
                   5866:         my $increment = 0;
                   5867:         while ($#ans) {
                   5868:             $i+=length($ans[0]) + $increment;
                   5869:             my $line   = int($i/$$scantron_config{'Qlength'} + $ansnum);
                   5870:             my $bubble = $i%$$scantron_config{'Qlength'};
                   5871:             $record->{"scantron.$line.answer"}.=$alphabet->[$bubble];
                   5872:             shift(@ans);
                   5873:             $increment = 1;
                   5874:         }
                   5875:         $ansnum += $answers_needed;
1.82      albertel 5876:     }
1.503     raeburn  5877:     return $ansnum;
1.82      albertel 5878: }
                   5879: 
1.423     albertel 5880: =pod
                   5881: 
                   5882: =item scantron_add_delay
                   5883: 
                   5884:    Adds an error message that occurred during the grading phase to a
                   5885:    queue of messages to be shown after grading pass is complete
                   5886: 
                   5887:  Arguments:
1.424     albertel 5888:    $delayqueue  - arrary ref of hash ref of error messages
1.423     albertel 5889:    $scanline    - the scanline that caused the error
                   5890:    $errormesage - the error message
                   5891:    $errorcode   - a numeric code for the error
                   5892: 
                   5893:  Side Effects:
1.424     albertel 5894:    updates the $delayqueue to have a new hash ref of the error
1.423     albertel 5895: 
                   5896: =cut
                   5897: 
1.82      albertel 5898: sub scantron_add_delay {
1.140     albertel 5899:     my ($delayqueue,$scanline,$errormessage,$errorcode)=@_;
                   5900:     push(@$delayqueue,
                   5901: 	 {'line' => $scanline, 'emsg' => $errormessage,
                   5902: 	  'ecode' => $errorcode }
                   5903: 	 );
1.82      albertel 5904: }
                   5905: 
1.423     albertel 5906: =pod
                   5907: 
                   5908: =item scantron_find_student
                   5909: 
1.424     albertel 5910:    Finds the username for the current scanline
                   5911: 
                   5912:   Arguments:
                   5913:    $scantron_record - hash result from scantron_parse_scanline
                   5914:    $scan_data       - hash of correction information 
                   5915:                       (see &scantron_getfile() form more information)
                   5916:    $idmap           - hash from &username_to_idmap()
                   5917:    $line            - number of current scanline
                   5918:  
                   5919:   Returns:
                   5920:    Either 'username:domain' or undef if unknown
                   5921: 
1.423     albertel 5922: =cut
                   5923: 
1.82      albertel 5924: sub scantron_find_student {
1.157     albertel 5925:     my ($scantron_record,$scan_data,$idmap,$line)=@_;
1.83      albertel 5926:     my $scanID=$$scantron_record{'scantron.ID'};
1.157     albertel 5927:     if ($scanID =~ /^\s*$/) {
                   5928:  	return &scan_data($scan_data,"$line.user");
                   5929:     }
1.83      albertel 5930:     foreach my $id (keys(%$idmap)) {
1.157     albertel 5931:  	if (lc($id) eq lc($scanID)) {
                   5932:  	    return $$idmap{$id};
                   5933:  	}
1.83      albertel 5934:     }
                   5935:     return undef;
                   5936: }
                   5937: 
1.423     albertel 5938: =pod
                   5939: 
                   5940: =item scantron_filter
                   5941: 
1.424     albertel 5942:    Filter sub for lonnavmaps, filters out hidden resources if ignore
                   5943:    hidden resources was selected
                   5944: 
1.423     albertel 5945: =cut
                   5946: 
1.83      albertel 5947: sub scantron_filter {
                   5948:     my ($curres)=@_;
1.331     albertel 5949: 
                   5950:     if (ref($curres) && $curres->is_problem()) {
                   5951: 	# if the user has asked to not have either hidden
                   5952: 	# or 'randomout' controlled resources to be graded
                   5953: 	# don't include them
                   5954: 	if ($env{'form.scantron_options_hidden'} eq 'ignore_hidden'
                   5955: 	    && $curres->randomout) {
                   5956: 	    return 0;
                   5957: 	}
1.83      albertel 5958: 	return 1;
                   5959:     }
                   5960:     return 0;
1.82      albertel 5961: }
                   5962: 
1.423     albertel 5963: =pod
                   5964: 
                   5965: =item scantron_process_corrections
                   5966: 
1.424     albertel 5967:    Gets correction information out of submitted form data and corrects
                   5968:    the scanline
                   5969: 
1.423     albertel 5970: =cut
                   5971: 
1.157     albertel 5972: sub scantron_process_corrections {
                   5973:     my ($r) = @_;
1.257     albertel 5974:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.157     albertel 5975:     my ($scanlines,$scan_data)=&scantron_getfile();
                   5976:     my $classlist=&Apache::loncoursedata::get_classlist();
1.257     albertel 5977:     my $which=$env{'form.scantron_line'};
1.200     albertel 5978:     my $line=&scantron_get_line($scanlines,$scan_data,$which);
1.157     albertel 5979:     my ($skip,$err,$errmsg);
1.257     albertel 5980:     if ($env{'form.scantron_skip_record'}) {
1.157     albertel 5981: 	$skip=1;
1.257     albertel 5982:     } elsif ($env{'form.scantron_corrections'} =~ /^(duplicate|incorrect)ID$/) {
                   5983: 	my $newstudent=$env{'form.scantron_username'}.':'.
                   5984: 	    $env{'form.scantron_domain'};
1.157     albertel 5985: 	my $newid=$classlist->{$newstudent}->[&Apache::loncoursedata::CL_ID];
                   5986: 	($line,$err,$errmsg)=
                   5987: 	    &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,$which,
                   5988: 				     'ID',{'newid'=>$newid,
1.257     albertel 5989: 				    'username'=>$env{'form.scantron_username'},
                   5990: 				    'domain'=>$env{'form.scantron_domain'}});
                   5991:     } elsif ($env{'form.scantron_corrections'} =~ /^(duplicate|incorrect)CODE$/) {
                   5992: 	my $resolution=$env{'form.scantron_CODE_resolution'};
1.190     albertel 5993: 	my $newCODE;
1.192     albertel 5994: 	my %args;
1.190     albertel 5995: 	if      ($resolution eq 'use_unfound') {
1.191     albertel 5996: 	    $newCODE='use_unfound';
1.190     albertel 5997: 	} elsif ($resolution eq 'use_found') {
1.257     albertel 5998: 	    $newCODE=$env{'form.scantron_CODE_selectedvalue'};
1.190     albertel 5999: 	} elsif ($resolution eq 'use_typed') {
1.257     albertel 6000: 	    $newCODE=$env{'form.scantron_CODE_newvalue'};
1.194     albertel 6001: 	} elsif ($resolution =~ /^use_closest_(\d+)/) {
1.257     albertel 6002: 	    $newCODE=$env{"form.scantron_CODE_closest_$1"};
1.190     albertel 6003: 	}
1.257     albertel 6004: 	if ($env{'form.scantron_corrections'} eq 'duplicateCODE') {
1.192     albertel 6005: 	    $args{'CODE_ignore_dup'}=1;
                   6006: 	}
                   6007: 	$args{'CODE'}=$newCODE;
1.186     albertel 6008: 	($line,$err,$errmsg)=
                   6009: 	    &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,$which,
1.192     albertel 6010: 				     'CODE',\%args);
1.257     albertel 6011:     } elsif ($env{'form.scantron_corrections'} =~ /^(missing|double)bubble$/) {
                   6012: 	foreach my $question (split(',',$env{'form.scantron_questions'})) {
1.157     albertel 6013: 	    ($line,$err,$errmsg)=
                   6014: 		&scantron_fixup_scanline(\%scantron_config,$scan_data,$line,
                   6015: 					 $which,'answer',
                   6016: 					 { 'question'=>$question,
1.503     raeburn  6017: 		      		   'response'=>$env{"form.scantron_correct_Q_$question"},
                   6018:                                    'questionnum'=>$env{"form.scantron_questionnum_Q_$question"}});
1.157     albertel 6019: 	    if ($err) { last; }
                   6020: 	}
                   6021:     }
                   6022:     if ($err) {
1.398     albertel 6023: 	$r->print("<span class=\"LC_warning\">Unable to accept last correction, an error occurred :$errmsg:</span>");
1.157     albertel 6024:     } else {
1.200     albertel 6025: 	&scantron_put_line($scanlines,$scan_data,$which,$line,$skip);
1.157     albertel 6026: 	&scantron_putfile($scanlines,$scan_data);
                   6027:     }
                   6028: }
                   6029: 
1.423     albertel 6030: =pod
                   6031: 
                   6032: =item reset_skipping_status
                   6033: 
1.424     albertel 6034:    Forgets the current set of remember skipped scanlines (and thus
                   6035:    reverts back to considering all lines in the
                   6036:    scantron_skipped_<filename> file)
                   6037: 
1.423     albertel 6038: =cut
                   6039: 
1.200     albertel 6040: sub reset_skipping_status {
                   6041:     my ($scanlines,$scan_data)=&scantron_getfile();
                   6042:     &scan_data($scan_data,'remember_skipping',undef,1);
                   6043:     &scantron_putfile(undef,$scan_data);
                   6044: }
                   6045: 
1.423     albertel 6046: =pod
                   6047: 
                   6048: =item start_skipping
                   6049: 
1.424     albertel 6050:    Marks a scanline to be skipped. 
                   6051: 
1.423     albertel 6052: =cut
                   6053: 
1.376     albertel 6054: sub start_skipping {
1.200     albertel 6055:     my ($scan_data,$i)=@_;
                   6056:     my %remembered=split(':',&scan_data($scan_data,'remember_skipping'));
1.376     albertel 6057:     if ($env{'form.scantron_options_redo'} =~ /^redo_/) {
                   6058: 	$remembered{$i}=2;
                   6059:     } else {
                   6060: 	$remembered{$i}=1;
                   6061:     }
1.200     albertel 6062:     &scan_data($scan_data,'remember_skipping',join(':',%remembered));
                   6063: }
                   6064: 
1.423     albertel 6065: =pod
                   6066: 
                   6067: =item should_be_skipped
                   6068: 
1.424     albertel 6069:    Checks whether a scanline should be skipped.
                   6070: 
1.423     albertel 6071: =cut
                   6072: 
1.200     albertel 6073: sub should_be_skipped {
1.376     albertel 6074:     my ($scanlines,$scan_data,$i)=@_;
1.257     albertel 6075:     if ($env{'form.scantron_options_redo'} !~ /^redo_/) {
1.200     albertel 6076: 	# not redoing old skips
1.376     albertel 6077: 	if ($scanlines->{'skipped'}[$i]) { return 1; }
1.200     albertel 6078: 	return 0;
                   6079:     }
                   6080:     my %remembered=split(':',&scan_data($scan_data,'remember_skipping'));
1.376     albertel 6081: 
                   6082:     if (exists($remembered{$i}) && $remembered{$i} != 2 ) {
                   6083: 	return 0;
                   6084:     }
1.200     albertel 6085:     return 1;
                   6086: }
                   6087: 
1.423     albertel 6088: =pod
                   6089: 
                   6090: =item remember_current_skipped
                   6091: 
1.424     albertel 6092:    Discovers what scanlines are in the scantron_skipped_<filename>
                   6093:    file and remembers them into scan_data for later use.
                   6094: 
1.423     albertel 6095: =cut
                   6096: 
1.200     albertel 6097: sub remember_current_skipped {
                   6098:     my ($scanlines,$scan_data)=&scantron_getfile();
                   6099:     my %to_remember;
                   6100:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
                   6101: 	if ($scanlines->{'skipped'}[$i]) {
                   6102: 	    $to_remember{$i}=1;
                   6103: 	}
                   6104:     }
1.376     albertel 6105: 
1.200     albertel 6106:     &scan_data($scan_data,'remember_skipping',join(':',%to_remember));
                   6107:     &scantron_putfile(undef,$scan_data);
                   6108: }
                   6109: 
1.423     albertel 6110: =pod
                   6111: 
                   6112: =item check_for_error
                   6113: 
1.424     albertel 6114:     Checks if there was an error when attempting to remove a specific
                   6115:     scantron_.. bubble sheet data file. Prints out an error if
                   6116:     something went wrong.
                   6117: 
1.423     albertel 6118: =cut
                   6119: 
1.200     albertel 6120: sub check_for_error {
                   6121:     my ($r,$result)=@_;
                   6122:     if ($result ne 'ok' && $result ne 'not_found' ) {
1.492     albertel 6123: 	$r->print(&mt("An error occurred ([_1]) when trying to remove the existing corrections.",$result));
1.200     albertel 6124:     }
                   6125: }
1.157     albertel 6126: 
1.423     albertel 6127: =pod
                   6128: 
                   6129: =item scantron_warning_screen
                   6130: 
1.424     albertel 6131:    Interstitial screen to make sure the operator has selected the
                   6132:    correct options before we start the validation phase.
                   6133: 
1.423     albertel 6134: =cut
                   6135: 
1.203     albertel 6136: sub scantron_warning_screen {
                   6137:     my ($button_text)=@_;
1.257     albertel 6138:     my $title=&Apache::lonnet::gettitle($env{'form.selectpage'});
1.284     albertel 6139:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.373     albertel 6140:     my $CODElist;
1.284     albertel 6141:     if ($scantron_config{'CODElocation'} &&
                   6142: 	$scantron_config{'CODEstart'} &&
                   6143: 	$scantron_config{'CODElength'}) {
                   6144: 	$CODElist=$env{'form.scantron_CODElist'};
1.398     albertel 6145: 	if ($env{'form.scantron_CODElist'} eq '') { $CODElist='<span class="LC_warning">None</span>'; }
1.284     albertel 6146: 	$CODElist=
1.492     albertel 6147: 	    '<tr><td><b>'.&mt('List of CODES to validate against:').'</b></td><td><tt>'.
1.373     albertel 6148: 	    $env{'form.scantron_CODElist'}.'</tt></td></tr>';
1.284     albertel 6149:     }
1.492     albertel 6150:     return ('
1.203     albertel 6151: <p>
1.492     albertel 6152: <span class="LC_warning">
                   6153: '.&mt('Please double check the information below before clicking on \'[_1]\'',&mt($button_text)).'</span>
1.203     albertel 6154: </p>
                   6155: <table>
1.492     albertel 6156: <tr><td><b>'.&mt('Sequence to be Graded:').'</b></td><td>'.$title.'</td></tr>
                   6157: <tr><td><b>'.&mt('Data File that will be used:').'</b></td><td><tt>'.$env{'form.scantron_selectfile'}.'</tt></td></tr>
                   6158: '.$CODElist.'
1.203     albertel 6159: </table>
                   6160: <br />
1.492     albertel 6161: <p> '.&mt('If this information is correct, please click on \'[_1]\'.',&mt($button_text)).'</p>
                   6162: <p> '.&mt('If something is incorrect, please click the \'Grading Menu\' button to start over.').'</p>
1.203     albertel 6163: 
                   6164: <br />
1.492     albertel 6165: ');
1.203     albertel 6166: }
                   6167: 
1.423     albertel 6168: =pod
                   6169: 
                   6170: =item scantron_do_warning
                   6171: 
1.424     albertel 6172:    Check if the operator has picked something for all required
                   6173:    fields. Error out if something is missing.
                   6174: 
1.423     albertel 6175: =cut
                   6176: 
1.203     albertel 6177: sub scantron_do_warning {
1.608     www      6178:     my ($r,$symb)=@_;
1.203     albertel 6179:     if (!$symb) {return '';}
1.324     albertel 6180:     my $default_form_data=&defaultFormData($symb);
1.203     albertel 6181:     $r->print(&scantron_form_start().$default_form_data);
1.257     albertel 6182:     if ( $env{'form.selectpage'} eq '' ||
                   6183: 	 $env{'form.scantron_selectfile'} eq '' ||
                   6184: 	 $env{'form.scantron_format'} eq '' ) {
1.492     albertel 6185: 	$r->print("<p>".&mt('You have forgetten to specify some information. Please go Back and try again.')."</p>");
1.257     albertel 6186: 	if ( $env{'form.selectpage'} eq '') {
1.492     albertel 6187: 	    $r->print('<p><span class="LC_error">'.&mt('You have not selected a Sequence to grade').'</span></p>');
1.237     albertel 6188: 	} 
1.257     albertel 6189: 	if ( $env{'form.scantron_selectfile'} eq '') {
1.492     albertel 6190: 	    $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 6191: 	} 
1.257     albertel 6192: 	if ( $env{'form.scantron_format'} eq '') {
1.492     albertel 6193: 	    $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 6194: 	} 
                   6195:     } else {
1.265     www      6196: 	my $warning=&scantron_warning_screen('Grading: Validate Records');
1.492     albertel 6197: 	$r->print('
                   6198: '.$warning.'
                   6199: <input type="submit" name="submit" value="'.&mt('Grading: Validate Records').'" />
1.203     albertel 6200: <input type="hidden" name="command" value="scantron_validate" />
1.492     albertel 6201: ');
1.237     albertel 6202:     }
1.614     www      6203:     $r->print("</form><br />");
1.203     albertel 6204:     return '';
                   6205: }
                   6206: 
1.423     albertel 6207: =pod
                   6208: 
                   6209: =item scantron_form_start
                   6210: 
1.424     albertel 6211:     html hidden input for remembering all selected grading options
                   6212: 
1.423     albertel 6213: =cut
                   6214: 
1.203     albertel 6215: sub scantron_form_start {
                   6216:     my ($max_bubble)=@_;
                   6217:     my $result= <<SCANTRONFORM;
                   6218: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantronupload">
1.257     albertel 6219:   <input type="hidden" name="selectpage" value="$env{'form.selectpage'}" />
                   6220:   <input type="hidden" name="scantron_format" value="$env{'form.scantron_format'}" />
                   6221:   <input type="hidden" name="scantron_selectfile" value="$env{'form.scantron_selectfile'}" />
1.218     albertel 6222:   <input type="hidden" name="scantron_maxbubble" value="$max_bubble" />
1.257     albertel 6223:   <input type="hidden" name="scantron_CODElist" value="$env{'form.scantron_CODElist'}" />
                   6224:   <input type="hidden" name="scantron_CODEunique" value="$env{'form.scantron_CODEunique'}" />
                   6225:   <input type="hidden" name="scantron_options_redo" value="$env{'form.scantron_options_redo'}" />
                   6226:   <input type="hidden" name="scantron_options_ignore" value="$env{'form.scantron_options_ignore'}" />
1.331     albertel 6227:   <input type="hidden" name="scantron_options_hidden" value="$env{'form.scantron_options_hidden'}" />
1.203     albertel 6228: SCANTRONFORM
1.447     foxr     6229: 
                   6230:   my $line = 0;
                   6231:     while (defined($env{"form.scantron.bubblelines.$line"})) {
                   6232:        my $chunk =
                   6233: 	   '<input type="hidden" name="scantron.bubblelines.'.$line.'" value="'.$env{"form.scantron.bubblelines.$line"}.'" />'."\n";
1.448     foxr     6234:        $chunk .=
                   6235: 	   '<input type="hidden" name="scantron.first_bubble_line.'.$line.'" value="'.$env{"form.scantron.first_bubble_line.$line"}.'" />'."\n";
1.503     raeburn  6236:        $chunk .= 
                   6237:            '<input type="hidden" name="scantron.sub_bubblelines.'.$line.'" value="'.$env{"form.scantron.sub_bubblelines.$line"}.'" />'."\n";
1.504     raeburn  6238:        $chunk .=
                   6239:            '<input type="hidden" name="scantron.responsetype.'.$line.'" value="'.$env{"form.scantron.responsetype.$line"}.'" />'."\n";
1.447     foxr     6240:        $result .= $chunk;
                   6241:        $line++;
                   6242:    }
1.203     albertel 6243:     return $result;
                   6244: }
                   6245: 
1.423     albertel 6246: =pod
                   6247: 
                   6248: =item scantron_validate_file
                   6249: 
1.424     albertel 6250:     Dispatch routine for doing validation of a bubble sheet data file.
                   6251: 
                   6252:     Also processes any necessary information resets that need to
                   6253:     occur before validation begins (ignore previous corrections,
                   6254:     restarting the skipped records processing)
                   6255: 
1.423     albertel 6256: =cut
                   6257: 
1.157     albertel 6258: sub scantron_validate_file {
1.608     www      6259:     my ($r,$symb) = @_;
1.157     albertel 6260:     if (!$symb) {return '';}
1.324     albertel 6261:     my $default_form_data=&defaultFormData($symb);
1.200     albertel 6262:     
                   6263:     # do the detection of only doing skipped records first befroe we delete
1.424     albertel 6264:     # them when doing the corrections reset
1.257     albertel 6265:     if ($env{'form.scantron_options_redo'} ne 'redo_skipped_ready') {
1.200     albertel 6266: 	&reset_skipping_status();
                   6267:     }
1.257     albertel 6268:     if ($env{'form.scantron_options_redo'} eq 'redo_skipped') {
1.200     albertel 6269: 	&remember_current_skipped();
1.257     albertel 6270: 	$env{'form.scantron_options_redo'}='redo_skipped_ready';
1.200     albertel 6271:     }
                   6272: 
1.257     albertel 6273:     if ($env{'form.scantron_options_ignore'} eq 'ignore_corrections') {
1.200     albertel 6274: 	&check_for_error($r,&scantron_remove_file('corrected'));
                   6275: 	&check_for_error($r,&scantron_remove_file('skipped'));
                   6276: 	&check_for_error($r,&scantron_remove_scan_data());
1.257     albertel 6277: 	$env{'form.scantron_options_ignore'}='done';
1.192     albertel 6278:     }
1.200     albertel 6279: 
1.257     albertel 6280:     if ($env{'form.scantron_corrections'}) {
1.157     albertel 6281: 	&scantron_process_corrections($r);
                   6282:     }
1.503     raeburn  6283:     $r->print('<p>'.&mt('Gathering necessary information.').'</p>');$r->rflush();
1.157     albertel 6284:     #get the student pick code ready
                   6285:     $r->print(&Apache::loncommon::studentbrowser_javascript());
1.582     raeburn  6286:     my $nav_error;
                   6287:     my $max_bubble=&scantron_get_maxbubble(\$nav_error);
                   6288:     if ($nav_error) {
                   6289:         $r->print(&navmap_errormsg());
                   6290:         return '';
                   6291:     }
1.203     albertel 6292:     my $result=&scantron_form_start($max_bubble).$default_form_data;
1.157     albertel 6293:     $r->print($result);
                   6294:     
1.334     albertel 6295:     my @validate_phases=( 'sequence',
                   6296: 			  'ID',
1.157     albertel 6297: 			  'CODE',
                   6298: 			  'doublebubble',
                   6299: 			  'missingbubbles');
1.257     albertel 6300:     if (!$env{'form.validatepass'}) {
                   6301: 	$env{'form.validatepass'} = 0;
1.157     albertel 6302:     }
1.257     albertel 6303:     my $currentphase=$env{'form.validatepass'};
1.157     albertel 6304: 
1.448     foxr     6305: 
1.157     albertel 6306:     my $stop=0;
                   6307:     while (!$stop && $currentphase < scalar(@validate_phases)) {
1.503     raeburn  6308: 	$r->print(&mt('Validating '.$validate_phases[$currentphase]).'<br />');
1.157     albertel 6309: 	$r->rflush();
                   6310: 	my $which="scantron_validate_".$validate_phases[$currentphase];
                   6311: 	{
                   6312: 	    no strict 'refs';
                   6313: 	    ($stop,$currentphase)=&$which($r,$currentphase);
                   6314: 	}
                   6315:     }
                   6316:     if (!$stop) {
1.203     albertel 6317: 	my $warning=&scantron_warning_screen('Start Grading');
1.542     raeburn  6318: 	$r->print(&mt('Validation process complete.').'<br />'.
                   6319:                   $warning.
                   6320:                   &mt('Perform verification for each student after storage of submissions?').
                   6321:                   '&nbsp;<span class="LC_nobreak"><label>'.
                   6322:                   '<input type="radio" name="verifyrecord" value="1" />'.&mt('Yes').'</label>'.
                   6323:                   ('&nbsp;'x3).'<label>'.
                   6324:                   '<input type="radio" name="verifyrecord" value="0" checked="checked" />'.&mt('No').
                   6325:                   '</label></span><br />'.
                   6326:                   &mt('Grading will take longer if you use verification.').'<br />'.
1.572     www      6327:                   &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  6328:                   '<input type="submit" name="submit" value="'.&mt('Start Grading').'" />'.
                   6329:                   '<input type="hidden" name="command" value="scantron_process" />'."\n");
1.157     albertel 6330:     } else {
                   6331: 	$r->print('<input type="hidden" name="command" value="scantron_validate" />');
                   6332: 	$r->print("<input type='hidden' name='validatepass' value='".$currentphase."' />");
                   6333:     }
                   6334:     if ($stop) {
1.334     albertel 6335: 	if ($validate_phases[$currentphase] eq 'sequence') {
1.539     riegler  6336: 	    $r->print('<input type="submit" name="submit" value="'.&mt('Ignore').' &rarr; " />');
1.492     albertel 6337: 	    $r->print(' '.&mt('this error').' <br />');
1.334     albertel 6338: 
1.492     albertel 6339: 	    $r->print(" <p>".&mt("Or click the 'Grading Menu' button to start over.")."</p>");
1.334     albertel 6340: 	} else {
1.503     raeburn  6341:             if ($validate_phases[$currentphase] eq 'doublebubble' || $validate_phases[$currentphase] eq 'missingbubbles') {
1.539     riegler  6342: 	        $r->print('<input type="button" name="submitbutton" value="'.&mt('Continue').' &rarr;" onclick="javascript:verify_bubble_radio(this.form)" />');
1.503     raeburn  6343:             } else {
1.539     riegler  6344:                 $r->print('<input type="submit" name="submit" value="'.&mt('Continue').' &rarr;" />');
1.503     raeburn  6345:             }
1.492     albertel 6346: 	    $r->print(' '.&mt('using corrected info').' <br />');
                   6347: 	    $r->print("<input type='submit' value='".&mt("Skip")."' name='scantron_skip_record' />");
                   6348: 	    $r->print(" ".&mt("this scanline saving it for later."));
1.334     albertel 6349: 	}
1.157     albertel 6350:     }
1.614     www      6351:     $r->print(" </form><br />");
1.157     albertel 6352:     return '';
                   6353: }
                   6354: 
1.423     albertel 6355: 
                   6356: =pod
                   6357: 
                   6358: =item scantron_remove_file
                   6359: 
1.424     albertel 6360:    Removes the requested bubble sheet data file, makes sure that
                   6361:    scantron_original_<filename> is never removed
                   6362: 
                   6363: 
1.423     albertel 6364: =cut
                   6365: 
1.200     albertel 6366: sub scantron_remove_file {
1.192     albertel 6367:     my ($which)=@_;
1.257     albertel 6368:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   6369:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.192     albertel 6370:     my $file='scantron_';
1.200     albertel 6371:     if ($which eq 'corrected' || $which eq 'skipped') {
                   6372: 	$file.=$which.'_';
1.192     albertel 6373:     } else {
                   6374: 	return 'refused';
                   6375:     }
1.257     albertel 6376:     $file.=$env{'form.scantron_selectfile'};
1.200     albertel 6377:     return &Apache::lonnet::removeuserfile($cname,$cdom,$file);
                   6378: }
                   6379: 
1.423     albertel 6380: 
                   6381: =pod
                   6382: 
                   6383: =item scantron_remove_scan_data
                   6384: 
1.424     albertel 6385:    Removes all scan_data correction for the requested bubble sheet
                   6386:    data file.  (In the case that both the are doing skipped records we need
                   6387:    to remember the old skipped lines for the time being so that element
                   6388:    persists for a while.)
                   6389: 
1.423     albertel 6390: =cut
                   6391: 
1.200     albertel 6392: sub scantron_remove_scan_data {
1.257     albertel 6393:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   6394:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.192     albertel 6395:     my @keys=&Apache::lonnet::getkeys('nohist_scantrondata',$cdom,$cname);
                   6396:     my @todelete;
1.257     albertel 6397:     my $filename=$env{'form.scantron_selectfile'};
1.192     albertel 6398:     foreach my $key (@keys) {
                   6399: 	if ($key=~/^\Q$filename\E_/) {
1.257     albertel 6400: 	    if ($env{'form.scantron_options_redo'} eq 'redo_skipped_ready' &&
1.200     albertel 6401: 		$key=~/remember_skipping/) {
                   6402: 		next;
                   6403: 	    }
1.192     albertel 6404: 	    push(@todelete,$key);
                   6405: 	}
                   6406:     }
1.200     albertel 6407:     my $result;
1.192     albertel 6408:     if (@todelete) {
1.491     albertel 6409: 	$result = &Apache::lonnet::del('nohist_scantrondata',
                   6410: 				       \@todelete,$cdom,$cname);
                   6411:     } else {
                   6412: 	$result = 'ok';
1.192     albertel 6413:     }
                   6414:     return $result;
                   6415: }
                   6416: 
1.423     albertel 6417: 
                   6418: =pod
                   6419: 
                   6420: =item scantron_getfile
                   6421: 
1.424     albertel 6422:     Fetches the requested bubble sheet data file (all 3 versions), and
                   6423:     the scan_data hash
                   6424:   
                   6425:   Arguments:
                   6426:     None
                   6427: 
                   6428:   Returns:
                   6429:     2 hash references
                   6430: 
                   6431:      - first one has 
                   6432:          orig      -
                   6433:          corrected -
                   6434:          skipped   -  each of which points to an array ref of the specified
                   6435:                       file broken up into individual lines
                   6436:          count     - number of scanlines
                   6437:  
                   6438:      - second is the scan_data hash possible keys are
1.425     albertel 6439:        ($number refers to scanline numbered $number and thus the key affects
                   6440:         only that scanline
                   6441:         $bubline refers to the specific bubble line element and the aspects
                   6442:         refers to that specific bubble line element)
                   6443: 
                   6444:        $number.user - username:domain to use
                   6445:        $number.CODE_ignore_dup 
                   6446:                     - ignore the duplicate CODE error 
                   6447:        $number.useCODE
                   6448:                     - use the CODE in the scanline as is
                   6449:        $number.no_bubble.$bubline
                   6450:                     - it is valid that there is no bubbled in bubble
                   6451:                       at $number $bubline
                   6452:        remember_skipping
                   6453:                     - a frozen hash containing keys of $number and values
                   6454:                       of either 
                   6455:                         1 - we are on a 'do skipped records pass' and plan
                   6456:                             on processing this line
                   6457:                         2 - we are on a 'do skipped records pass' and this
                   6458:                             scanline has been marked to skip yet again
1.424     albertel 6459: 
1.423     albertel 6460: =cut
                   6461: 
1.157     albertel 6462: sub scantron_getfile {
1.200     albertel 6463:     #FIXME really would prefer a scantron directory
1.257     albertel 6464:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   6465:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.157     albertel 6466:     my $lines;
                   6467:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
1.257     albertel 6468: 		       'scantron_orig_'.$env{'form.scantron_selectfile'});
1.157     albertel 6469:     my %scanlines;
                   6470:     $scanlines{'orig'}=[(split("\n",$lines,-1))];
                   6471:     my $temp=$scanlines{'orig'};
                   6472:     $scanlines{'count'}=$#$temp;
                   6473: 
                   6474:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
1.257     albertel 6475: 		       'scantron_corrected_'.$env{'form.scantron_selectfile'});
1.157     albertel 6476:     if ($lines eq '-1') {
                   6477: 	$scanlines{'corrected'}=[];
                   6478:     } else {
                   6479: 	$scanlines{'corrected'}=[(split("\n",$lines,-1))];
                   6480:     }
                   6481:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
1.257     albertel 6482: 		       'scantron_skipped_'.$env{'form.scantron_selectfile'});
1.157     albertel 6483:     if ($lines eq '-1') {
                   6484: 	$scanlines{'skipped'}=[];
                   6485:     } else {
                   6486: 	$scanlines{'skipped'}=[(split("\n",$lines,-1))];
                   6487:     }
1.175     albertel 6488:     my @tmp=&Apache::lonnet::dump('nohist_scantrondata',$cdom,$cname);
1.157     albertel 6489:     if ($tmp[0] =~ /^(error:|no_such_host)/) { @tmp=(); }
                   6490:     my %scan_data = @tmp;
                   6491:     return (\%scanlines,\%scan_data);
                   6492: }
                   6493: 
1.423     albertel 6494: =pod
                   6495: 
                   6496: =item lonnet_putfile
                   6497: 
1.424     albertel 6498:    Wrapper routine to call &Apache::lonnet::finishuserfileupload
                   6499: 
                   6500:  Arguments:
                   6501:    $contents - data to store
                   6502:    $filename - filename to store $contents into
                   6503: 
                   6504:  Returns:
                   6505:    result value from &Apache::lonnet::finishuserfileupload
                   6506: 
1.423     albertel 6507: =cut
                   6508: 
1.157     albertel 6509: sub lonnet_putfile {
                   6510:     my ($contents,$filename)=@_;
1.257     albertel 6511:     my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   6512:     my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   6513:     $env{'form.sillywaytopassafilearound'}=$contents;
1.275     albertel 6514:     &Apache::lonnet::finishuserfileupload($docuname,$docudom,'sillywaytopassafilearound',$filename);
1.157     albertel 6515: 
                   6516: }
                   6517: 
1.423     albertel 6518: =pod
                   6519: 
                   6520: =item scantron_putfile
                   6521: 
1.424     albertel 6522:     Stores the current version of the bubble sheet data files, and the
                   6523:     scan_data hash. (Does not modify the original version only the
                   6524:     corrected and skipped versions.
                   6525: 
                   6526:  Arguments:
                   6527:     $scanlines - hash ref that looks like the first return value from
                   6528:                  &scantron_getfile()
                   6529:     $scan_data - hash ref that looks like the second return value from
                   6530:                  &scantron_getfile()
                   6531: 
1.423     albertel 6532: =cut
                   6533: 
1.157     albertel 6534: sub scantron_putfile {
                   6535:     my ($scanlines,$scan_data) = @_;
1.200     albertel 6536:     #FIXME really would prefer a scantron directory
1.257     albertel 6537:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   6538:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.200     albertel 6539:     if ($scanlines) {
                   6540: 	my $prefix='scantron_';
1.157     albertel 6541: # no need to update orig, shouldn't change
                   6542: #   &lonnet_putfile(join("\n",@{$scanlines->{'orig'}}),$prefix.'orig_'.
1.257     albertel 6543: #		    $env{'form.scantron_selectfile'});
1.200     albertel 6544: 	&lonnet_putfile(join("\n",@{$scanlines->{'corrected'}}),
                   6545: 			$prefix.'corrected_'.
1.257     albertel 6546: 			$env{'form.scantron_selectfile'});
1.200     albertel 6547: 	&lonnet_putfile(join("\n",@{$scanlines->{'skipped'}}),
                   6548: 			$prefix.'skipped_'.
1.257     albertel 6549: 			$env{'form.scantron_selectfile'});
1.200     albertel 6550:     }
1.175     albertel 6551:     &Apache::lonnet::put('nohist_scantrondata',$scan_data,$cdom,$cname);
1.157     albertel 6552: }
                   6553: 
1.423     albertel 6554: =pod
                   6555: 
                   6556: =item scantron_get_line
                   6557: 
1.424     albertel 6558:    Returns the correct version of the scanline
                   6559: 
                   6560:  Arguments:
                   6561:     $scanlines - hash ref that looks like the first return value from
                   6562:                  &scantron_getfile()
                   6563:     $scan_data - hash ref that looks like the second return value from
                   6564:                  &scantron_getfile()
                   6565:     $i         - number of the requested line (starts at 0)
                   6566: 
                   6567:  Returns:
                   6568:    A scanline, (either the original or the corrected one if it
                   6569:    exists), or undef if the requested scanline should be
                   6570:    skipped. (Either because it's an skipped scanline, or it's an
                   6571:    unskipped scanline and we are not doing a 'do skipped scanlines'
                   6572:    pass.
                   6573: 
1.423     albertel 6574: =cut
                   6575: 
1.157     albertel 6576: sub scantron_get_line {
1.200     albertel 6577:     my ($scanlines,$scan_data,$i)=@_;
1.376     albertel 6578:     if (&should_be_skipped($scanlines,$scan_data,$i)) { return undef; }
                   6579:     #if ($scanlines->{'skipped'}[$i]) { return undef; }
1.157     albertel 6580:     if ($scanlines->{'corrected'}[$i]) {return $scanlines->{'corrected'}[$i];}
                   6581:     return $scanlines->{'orig'}[$i]; 
                   6582: }
                   6583: 
1.423     albertel 6584: =pod
                   6585: 
                   6586: =item scantron_todo_count
                   6587: 
1.424     albertel 6588:     Counts the number of scanlines that need processing.
                   6589: 
                   6590:  Arguments:
                   6591:     $scanlines - hash ref that looks like the first return value from
                   6592:                  &scantron_getfile()
                   6593:     $scan_data - hash ref that looks like the second return value from
                   6594:                  &scantron_getfile()
                   6595: 
                   6596:  Returns:
                   6597:     $count - number of scanlines to process
                   6598: 
1.423     albertel 6599: =cut
                   6600: 
1.200     albertel 6601: sub get_todo_count {
                   6602:     my ($scanlines,$scan_data)=@_;
                   6603:     my $count=0;
                   6604:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
                   6605: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
                   6606: 	if ($line=~/^[\s\cz]*$/) { next; }
                   6607: 	$count++;
                   6608:     }
                   6609:     return $count;
                   6610: }
                   6611: 
1.423     albertel 6612: =pod
                   6613: 
                   6614: =item scantron_put_line
                   6615: 
1.424     albertel 6616:     Updates the 'corrected' or 'skipped' versions of the bubble sheet
                   6617:     data file.
                   6618: 
                   6619:  Arguments:
                   6620:     $scanlines - hash ref that looks like the first return value from
                   6621:                  &scantron_getfile()
                   6622:     $scan_data - hash ref that looks like the second return value from
                   6623:                  &scantron_getfile()
                   6624:     $i         - line number to update
                   6625:     $newline   - contents of the updated scanline
                   6626:     $skip      - if true make the line for skipping and update the
                   6627:                  'skipped' file
                   6628: 
1.423     albertel 6629: =cut
                   6630: 
1.157     albertel 6631: sub scantron_put_line {
1.200     albertel 6632:     my ($scanlines,$scan_data,$i,$newline,$skip)=@_;
1.157     albertel 6633:     if ($skip) {
                   6634: 	$scanlines->{'skipped'}[$i]=$newline;
1.376     albertel 6635: 	&start_skipping($scan_data,$i);
1.157     albertel 6636: 	return;
                   6637:     }
                   6638:     $scanlines->{'corrected'}[$i]=$newline;
                   6639: }
                   6640: 
1.423     albertel 6641: =pod
                   6642: 
                   6643: =item scantron_clear_skip
                   6644: 
1.424     albertel 6645:    Remove a line from the 'skipped' file
                   6646: 
                   6647:  Arguments:
                   6648:     $scanlines - hash ref that looks like the first return value from
                   6649:                  &scantron_getfile()
                   6650:     $scan_data - hash ref that looks like the second return value from
                   6651:                  &scantron_getfile()
                   6652:     $i         - line number to update
                   6653: 
1.423     albertel 6654: =cut
                   6655: 
1.376     albertel 6656: sub scantron_clear_skip {
                   6657:     my ($scanlines,$scan_data,$i)=@_;
                   6658:     if (exists($scanlines->{'skipped'}[$i])) {
                   6659: 	undef($scanlines->{'skipped'}[$i]);
                   6660: 	return 1;
                   6661:     }
                   6662:     return 0;
                   6663: }
                   6664: 
1.423     albertel 6665: =pod
                   6666: 
                   6667: =item scantron_filter_not_exam
                   6668: 
1.424     albertel 6669:    Filter routine used by &Apache::lonnavmaps::retrieveResources(), to
                   6670:    filter out resources that are not marked as 'exam' mode
                   6671: 
1.423     albertel 6672: =cut
                   6673: 
1.334     albertel 6674: sub scantron_filter_not_exam {
                   6675:     my ($curres)=@_;
                   6676:     
                   6677:     if (ref($curres) && $curres->is_problem() && !$curres->is_exam()) {
                   6678: 	# if the user has asked to not have either hidden
                   6679: 	# or 'randomout' controlled resources to be graded
                   6680: 	# don't include them
                   6681: 	if ($env{'form.scantron_options_hidden'} eq 'ignore_hidden'
                   6682: 	    && $curres->randomout) {
                   6683: 	    return 0;
                   6684: 	}
                   6685: 	return 1;
                   6686:     }
                   6687:     return 0;
                   6688: }
                   6689: 
1.423     albertel 6690: =pod
                   6691: 
                   6692: =item scantron_validate_sequence
                   6693: 
1.424     albertel 6694:     Validates the selected sequence, checking for resource that are
                   6695:     not set to exam mode.
                   6696: 
1.423     albertel 6697: =cut
                   6698: 
1.334     albertel 6699: sub scantron_validate_sequence {
                   6700:     my ($r,$currentphase) = @_;
                   6701: 
                   6702:     my $navmap=Apache::lonnavmaps::navmap->new();
1.582     raeburn  6703:     unless (ref($navmap)) {
                   6704:         $r->print(&navmap_errormsg());
                   6705:         return (1,$currentphase);
                   6706:     }
1.334     albertel 6707:     my (undef,undef,$sequence)=
                   6708: 	&Apache::lonnet::decode_symb($env{'form.selectpage'});
                   6709: 
                   6710:     my $map=$navmap->getResourceByUrl($sequence);
                   6711: 
                   6712:     $r->print('<input type="hidden" name="validate_sequence_exam"
                   6713:                                     value="ignore" />');
                   6714:     if ($env{'form.validate_sequence_exam'} ne 'ignore') {
                   6715: 	my @resources=
                   6716: 	    $navmap->retrieveResources($map,\&scantron_filter_not_exam,1,0);
                   6717: 	if (@resources) {
1.357     banghart 6718: 	    $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 6719: 	    return (1,$currentphase);
                   6720: 	}
                   6721:     }
                   6722: 
                   6723:     return (0,$currentphase+1);
                   6724: }
                   6725: 
1.423     albertel 6726: 
                   6727: 
1.157     albertel 6728: sub scantron_validate_ID {
                   6729:     my ($r,$currentphase) = @_;
                   6730:     
                   6731:     #get student info
                   6732:     my $classlist=&Apache::loncoursedata::get_classlist();
                   6733:     my %idmap=&username_to_idmap($classlist);
                   6734: 
                   6735:     #get scantron line setup
1.257     albertel 6736:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.157     albertel 6737:     my ($scanlines,$scan_data)=&scantron_getfile();
1.582     raeburn  6738: 
                   6739:     my $nav_error;
                   6740:     &scantron_get_maxbubble(\$nav_error); # parse needs the bubble_lines.. array.
                   6741:     if ($nav_error) {
                   6742:         $r->print(&navmap_errormsg());
                   6743:         return(1,$currentphase);
                   6744:     }
1.157     albertel 6745: 
                   6746:     my %found=('ids'=>{},'usernames'=>{});
                   6747:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
1.200     albertel 6748: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.157     albertel 6749: 	if ($line=~/^[\s\cz]*$/) { next; }
                   6750: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
                   6751: 						 $scan_data);
                   6752: 	my $id=$$scan_record{'scantron.ID'};
                   6753: 	my $found;
                   6754: 	foreach my $checkid (keys(%idmap)) {
                   6755: 	    if (lc($checkid) eq lc($id)) { $found=$checkid;last; }
                   6756: 	}
                   6757: 	if ($found) {
                   6758: 	    my $username=$idmap{$found};
                   6759: 	    if ($found{'ids'}{$found}) {
                   6760: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
                   6761: 					 $line,'duplicateID',$found);
1.194     albertel 6762: 		return(1,$currentphase);
1.157     albertel 6763: 	    } elsif ($found{'usernames'}{$username}) {
                   6764: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
                   6765: 					 $line,'duplicateID',$username);
1.194     albertel 6766: 		return(1,$currentphase);
1.157     albertel 6767: 	    }
1.186     albertel 6768: 	    #FIXME store away line we previously saw the ID on to use above
1.157     albertel 6769: 	    $found{'ids'}{$found}++;
                   6770: 	    $found{'usernames'}{$username}++;
                   6771: 	} else {
                   6772: 	    if ($id =~ /^\s*$/) {
1.158     albertel 6773: 		my $username=&scan_data($scan_data,"$i.user");
1.157     albertel 6774: 		if (defined($username) && $found{'usernames'}{$username}) {
                   6775: 		    &scantron_get_correction($r,$i,$scan_record,
                   6776: 					     \%scantron_config,
                   6777: 					     $line,'duplicateID',$username);
1.194     albertel 6778: 		    return(1,$currentphase);
1.157     albertel 6779: 		} elsif (!defined($username)) {
                   6780: 		    &scantron_get_correction($r,$i,$scan_record,
                   6781: 					     \%scantron_config,
                   6782: 					     $line,'incorrectID');
1.194     albertel 6783: 		    return(1,$currentphase);
1.157     albertel 6784: 		}
                   6785: 		$found{'usernames'}{$username}++;
                   6786: 	    } else {
                   6787: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
                   6788: 					 $line,'incorrectID');
1.194     albertel 6789: 		return(1,$currentphase);
1.157     albertel 6790: 	    }
                   6791: 	}
                   6792:     }
                   6793: 
                   6794:     return (0,$currentphase+1);
                   6795: }
                   6796: 
1.423     albertel 6797: 
1.157     albertel 6798: sub scantron_get_correction {
                   6799:     my ($r,$i,$scan_record,$scan_config,$line,$error,$arg)=@_;
1.454     banghart 6800: #FIXME in the case of a duplicated ID the previous line, probably need
1.157     albertel 6801: #to show both the current line and the previous one and allow skipping
                   6802: #the previous one or the current one
                   6803: 
1.333     albertel 6804:     if ( $$scan_record{'scantron.PaperID'} =~ /\S/) {
1.492     albertel 6805: 	$r->print("<p>".&mt("<b>An error was detected ($error)</b>".
                   6806: 			    " for PaperID <tt>[_1]</tt>",
                   6807: 			    $$scan_record{'scantron.PaperID'})."</p> \n");
1.157     albertel 6808:     } else {
1.492     albertel 6809: 	$r->print("<p>".&mt("<b>An error was detected ($error)</b>".
                   6810: 			    " in scanline [_1] <pre>[_2]</pre>",
                   6811: 			    $i,$line)."</p> \n");
                   6812:     }
                   6813:     my $message="<p>".&mt("The ID on the form is  <tt>[_1]</tt><br />".
                   6814: 			  "The name on the paper is [_2],[_3]",
                   6815: 			  $$scan_record{'scantron.ID'},
                   6816: 			  $$scan_record{'scantron.LastName'},
                   6817: 			  $$scan_record{'scantron.FirstName'})."</p>";
1.242     albertel 6818: 
1.157     albertel 6819:     $r->print('<input type="hidden" name="scantron_corrections" value="'.$error.'" />'."\n");
                   6820:     $r->print('<input type="hidden" name="scantron_line" value="'.$i.'" />'."\n");
1.503     raeburn  6821:                            # Array populated for doublebubble or
                   6822:     my @lines_to_correct;  # missingbubble errors to build javascript
                   6823:                            # to validate radio button checking   
                   6824: 
1.157     albertel 6825:     if ($error =~ /ID$/) {
1.186     albertel 6826: 	if ($error eq 'incorrectID') {
1.492     albertel 6827: 	    $r->print("<p>".&mt("The encoded ID is not in the classlist").
                   6828: 		      "</p>\n");
1.157     albertel 6829: 	} elsif ($error eq 'duplicateID') {
1.492     albertel 6830: 	    $r->print("<p>".&mt("The encoded ID has also been used by a previous paper [_1]",$arg)."</p>\n");
1.157     albertel 6831: 	}
1.242     albertel 6832: 	$r->print($message);
1.492     albertel 6833: 	$r->print("<p>".&mt("How should I handle this?")." <br /> \n");
1.157     albertel 6834: 	$r->print("\n<ul><li> ");
                   6835: 	#FIXME it would be nice if this sent back the user ID and
                   6836: 	#could do partial userID matches
                   6837: 	$r->print(&Apache::loncommon::selectstudent_link('scantronupload',
                   6838: 				       'scantron_username','scantron_domain'));
                   6839: 	$r->print(": <input type='text' name='scantron_username' value='' />");
                   6840: 	$r->print("\n@".
1.257     albertel 6841: 		 &Apache::loncommon::select_dom_form($env{'request.role.domain'},'scantron_domain'));
1.157     albertel 6842: 
                   6843: 	$r->print('</li>');
1.186     albertel 6844:     } elsif ($error =~ /CODE$/) {
                   6845: 	if ($error eq 'incorrectCODE') {
1.492     albertel 6846: 	    $r->print("<p>".&mt("The encoded CODE is not in the list of possible CODEs.")."</p>\n");
1.186     albertel 6847: 	} elsif ($error eq 'duplicateCODE') {
1.492     albertel 6848: 	    $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 6849: 	}
1.492     albertel 6850: 	$r->print("<p>".&mt("The CODE on the form is  <tt>'[_1]'</tt>",
                   6851: 			    $$scan_record{'scantron.CODE'})."<br />\n");
1.242     albertel 6852: 	$r->print($message);
1.492     albertel 6853: 	$r->print("<p>".&mt("How should I handle this?")." <br /> \n");
1.187     albertel 6854: 	$r->print("\n<br /> ");
1.194     albertel 6855: 	my $i=0;
1.273     albertel 6856: 	if ($error eq 'incorrectCODE' 
                   6857: 	    && $$scan_record{'scantron.CODE'}=~/\S/ ) {
1.194     albertel 6858: 	    my ($max,$closest)=&scantron_get_closely_matching_CODEs($arg,$$scan_record{'scantron.CODE'});
1.278     albertel 6859: 	    if ($closest > 0) {
                   6860: 		foreach my $testcode (@{$closest}) {
                   6861: 		    my $checked='';
1.569     bisitz   6862: 		    if (!$i) { $checked=' checked="checked"'; }
1.492     albertel 6863: 		    $r->print("
                   6864:    <label>
1.569     bisitz   6865:        <input type='radio' name='scantron_CODE_resolution' value='use_closest_$i'$checked />
1.492     albertel 6866:        ".&mt("Use the similar CODE [_1] instead.",
                   6867: 	    "<b><tt>".$testcode."</tt></b>")."
                   6868:     </label>
                   6869:     <input type='hidden' name='scantron_CODE_closest_$i' value='$testcode' />");
1.278     albertel 6870: 		    $r->print("\n<br />");
                   6871: 		    $i++;
                   6872: 		}
1.194     albertel 6873: 	    }
                   6874: 	}
1.273     albertel 6875: 	if ($$scan_record{'scantron.CODE'}=~/\S/ ) {
1.569     bisitz   6876: 	    my $checked; if (!$i) { $checked=' checked="checked"'; }
1.492     albertel 6877: 	    $r->print("
                   6878:     <label>
1.569     bisitz   6879:         <input type='radio' name='scantron_CODE_resolution' value='use_unfound'$checked />
1.492     albertel 6880:        ".&mt("Use the CODE [_1] that is was on the paper, ignoring the error.",
                   6881: 	     "<b><tt>".$$scan_record{'scantron.CODE'}."</tt></b>")."
                   6882:     </label>");
1.273     albertel 6883: 	    $r->print("\n<br />");
                   6884: 	}
1.194     albertel 6885: 
1.597     wenzelju 6886: 	$r->print(&Apache::lonhtmlcommon::scripttag(<<ENDSCRIPT));
1.188     albertel 6887: function change_radio(field) {
1.190     albertel 6888:     var slct=document.scantronupload.scantron_CODE_resolution;
1.188     albertel 6889:     var i;
                   6890:     for (i=0;i<slct.length;i++) {
                   6891:         if (slct[i].value==field) { slct[i].checked=true; }
                   6892:     }
                   6893: }
                   6894: ENDSCRIPT
1.187     albertel 6895: 	my $href="/adm/pickcode?".
1.359     www      6896: 	   "form=".&escape("scantronupload").
                   6897: 	   "&scantron_format=".&escape($env{'form.scantron_format'}).
                   6898: 	   "&scantron_CODElist=".&escape($env{'form.scantron_CODElist'}).
                   6899: 	   "&curCODE=".&escape($$scan_record{'scantron.CODE'}).
                   6900: 	   "&scantron_selectfile=".&escape($env{'form.scantron_selectfile'});
1.332     albertel 6901: 	if ($env{'form.scantron_CODElist'} =~ /\S/) { 
1.492     albertel 6902: 	    $r->print("
                   6903:     <label>
                   6904:        <input type='radio' name='scantron_CODE_resolution' value='use_found' />
                   6905:        ".&mt("[_1]Select[_2] a CODE from the list of all CODEs and use it.",
                   6906: 	     "<a target='_blank' href='$href'>","</a>")."
                   6907:     </label> 
1.558     bisitz   6908:     ".&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 6909: 	    $r->print("\n<br />");
                   6910: 	}
1.492     albertel 6911: 	$r->print("
                   6912:     <label>
                   6913:        <input type='radio' name='scantron_CODE_resolution' value='use_typed' />
                   6914:        ".&mt("Use [_1] as the CODE.",
                   6915: 	     "</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 6916: 	$r->print("\n<br /><br />");
1.157     albertel 6917:     } elsif ($error eq 'doublebubble') {
1.503     raeburn  6918: 	$r->print("<p>".&mt("There have been multiple bubbles scanned for some question(s)")."</p>\n");
1.497     foxr     6919: 
                   6920: 	# The form field scantron_questions is acutally a list of line numbers.
                   6921: 	# represented by this form so:
                   6922: 
                   6923: 	my $line_list = &questions_to_line_list($arg);
                   6924: 
1.157     albertel 6925: 	$r->print('<input type="hidden" name="scantron_questions" value="'.
1.497     foxr     6926: 		  $line_list.'" />');
1.242     albertel 6927: 	$r->print($message);
1.492     albertel 6928: 	$r->print("<p>".&mt("Please indicate which bubble should be used for grading")."</p>");
1.157     albertel 6929: 	foreach my $question (@{$arg}) {
1.503     raeburn  6930: 	    my @linenums = &prompt_for_corrections($r,$question,$scan_config,
                   6931:                                                    $scan_record, $error);
1.524     raeburn  6932:             push(@lines_to_correct,@linenums);
1.157     albertel 6933: 	}
1.503     raeburn  6934:         $r->print(&verify_bubbles_checked(@lines_to_correct));
1.157     albertel 6935:     } elsif ($error eq 'missingbubble') {
1.492     albertel 6936: 	$r->print("<p>".&mt("There have been <b>no</b> bubbles scanned for some question(s)")."</p>\n");
1.242     albertel 6937: 	$r->print($message);
1.492     albertel 6938: 	$r->print("<p>".&mt("Please indicate which bubble should be used for grading.")."</p>");
1.503     raeburn  6939: 	$r->print(&mt("Some questions have no scanned bubbles.")."\n");
1.497     foxr     6940: 
1.503     raeburn  6941: 	# The form field scantron_questions is actually a list of line numbers not
1.497     foxr     6942: 	# a list of question numbers. Therefore:
                   6943: 	#
                   6944: 	
                   6945: 	my $line_list = &questions_to_line_list($arg);
                   6946: 
1.157     albertel 6947: 	$r->print('<input type="hidden" name="scantron_questions" value="'.
1.497     foxr     6948: 		  $line_list.'" />');
1.157     albertel 6949: 	foreach my $question (@{$arg}) {
1.503     raeburn  6950: 	    my @linenums = &prompt_for_corrections($r,$question,$scan_config,
                   6951:                                                    $scan_record, $error);
1.524     raeburn  6952:             push(@lines_to_correct,@linenums);
1.157     albertel 6953: 	}
1.503     raeburn  6954:         $r->print(&verify_bubbles_checked(@lines_to_correct));
1.157     albertel 6955:     } else {
                   6956: 	$r->print("\n<ul>");
                   6957:     }
                   6958:     $r->print("\n</li></ul>");
1.497     foxr     6959: }
                   6960: 
1.503     raeburn  6961: sub verify_bubbles_checked {
                   6962:     my (@ansnums) = @_;
                   6963:     my $ansnumstr = join('","',@ansnums);
                   6964:     my $warning = &mt("A bubble or 'No bubble' selection has not been made for one or more lines.");
1.597     wenzelju 6965:     my $output = &Apache::lonhtmlcommon::scripttag((<<ENDSCRIPT));
1.503     raeburn  6966: function verify_bubble_radio(form) {
                   6967:     var ansnumArray = new Array ("$ansnumstr");
                   6968:     var need_bubble_count = 0;
                   6969:     for (var i=0; i<ansnumArray.length; i++) {
                   6970:         if (form.elements["scantron_correct_Q_"+ansnumArray[i]].length > 1) {
                   6971:             var bubble_picked = 0; 
                   6972:             for (var j=0; j<form.elements["scantron_correct_Q_"+ansnumArray[i]].length; j++) {
                   6973:                 if (form.elements["scantron_correct_Q_"+ansnumArray[i]][j].checked == true) {
                   6974:                     bubble_picked = 1;
                   6975:                 }
                   6976:             }
                   6977:             if (bubble_picked == 0) {
                   6978:                 need_bubble_count ++;
                   6979:             }
                   6980:         }
                   6981:     }
                   6982:     if (need_bubble_count) {
                   6983:         alert("$warning");
                   6984:         return;
                   6985:     }
                   6986:     form.submit(); 
                   6987: }
                   6988: ENDSCRIPT
                   6989:     return $output;
                   6990: }
                   6991: 
1.497     foxr     6992: =pod
                   6993: 
                   6994: =item  questions_to_line_list
1.157     albertel 6995: 
1.497     foxr     6996: Converts a list of questions into a string of comma separated
                   6997: line numbers in the answer sheet used by the questions.  This is
                   6998: used to fill in the scantron_questions form field.
                   6999: 
                   7000:   Arguments:
                   7001:      questions    - Reference to an array of questions.
                   7002: 
                   7003: =cut
                   7004: 
                   7005: 
                   7006: sub questions_to_line_list {
                   7007:     my ($questions) = @_;
                   7008:     my @lines;
                   7009: 
1.503     raeburn  7010:     foreach my $item (@{$questions}) {
                   7011:         my $question = $item;
                   7012:         my ($first,$count,$last);
                   7013:         if ($item =~ /^(\d+)\.(\d+)$/) {
                   7014:             $question = $1;
                   7015:             my $subquestion = $2;
                   7016:             $first = $first_bubble_line{$question-1} + 1;
                   7017:             my @subans = split(/,/,$subdivided_bubble_lines{$question-1});
                   7018:             my $subcount = 1;
                   7019:             while ($subcount<$subquestion) {
                   7020:                 $first += $subans[$subcount-1];
                   7021:                 $subcount ++;
                   7022:             }
                   7023:             $count = $subans[$subquestion-1];
                   7024:         } else {
                   7025: 	    $first   = $first_bubble_line{$question-1} + 1;
                   7026: 	    $count   = $bubble_lines_per_response{$question-1};
                   7027:         }
1.506     raeburn  7028:         $last = $first+$count-1;
1.503     raeburn  7029:         push(@lines, ($first..$last));
1.497     foxr     7030:     }
                   7031:     return join(',', @lines);
                   7032: }
                   7033: 
                   7034: =pod 
                   7035: 
                   7036: =item prompt_for_corrections
                   7037: 
                   7038: Prompts for a potentially multiline correction to the
                   7039: user's bubbling (factors out common code from scantron_get_correction
                   7040: for multi and missing bubble cases).
                   7041: 
                   7042:  Arguments:
                   7043:    $r           - Apache request object.
                   7044:    $question    - The question number to prompt for.
                   7045:    $scan_config - The scantron file configuration hash.
                   7046:    $scan_record - Reference to the hash that has the the parsed scanlines.
1.503     raeburn  7047:    $error       - Type of error
1.497     foxr     7048: 
                   7049:  Implicit inputs:
                   7050:    %bubble_lines_per_response   - Starting line numbers for each question.
                   7051:                                   Numbered from 0 (but question numbers are from
                   7052:                                   1.
                   7053:    %first_bubble_line           - Starting bubble line for each question.
1.509     raeburn  7054:    %subdivided_bubble_lines     - optionresponse, matchresponse and rankresponse 
                   7055:                                   type problems render as separate sub-questions, 
1.503     raeburn  7056:                                   in exam mode. This hash contains a 
                   7057:                                   comma-separated list of the lines per 
                   7058:                                   sub-question.
1.510     raeburn  7059:    %responsetype_per_response   - essayresponse, formularesponse,
                   7060:                                   stringresponse, imageresponse, reactionresponse,
                   7061:                                   and organicresponse type problem parts can have
1.503     raeburn  7062:                                   multiple lines per response if the weight
                   7063:                                   assigned exceeds 10.  In this case, only
                   7064:                                   one bubble per line is permitted, but more 
                   7065:                                   than one line might contain bubbles, e.g.
                   7066:                                   bubbling of: line 1 - J, line 2 - J, 
                   7067:                                   line 3 - B would assign 22 points.  
1.497     foxr     7068: 
                   7069: =cut
                   7070: 
                   7071: sub prompt_for_corrections {
1.503     raeburn  7072:     my ($r, $question, $scan_config, $scan_record, $error) = @_;
                   7073:     my ($current_line,$lines);
                   7074:     my @linenums;
                   7075:     my $questionnum = $question;
                   7076:     if ($question =~ /^(\d+)\.(\d+)$/) {
                   7077:         $question = $1;
                   7078:         $current_line = $first_bubble_line{$question-1} + 1 ;
                   7079:         my $subquestion = $2;
                   7080:         my @subans = split(/,/,$subdivided_bubble_lines{$question-1});
                   7081:         my $subcount = 1;
                   7082:         while ($subcount<$subquestion) {
                   7083:             $current_line += $subans[$subcount-1];
                   7084:             $subcount ++;
                   7085:         }
                   7086:         $lines = $subans[$subquestion-1];
                   7087:     } else {
                   7088:         $current_line = $first_bubble_line{$question-1} + 1 ;
                   7089:         $lines        = $bubble_lines_per_response{$question-1};
                   7090:     }
1.497     foxr     7091:     if ($lines > 1) {
1.503     raeburn  7092:         $r->print(&mt('The group of bubble lines below responds to a single question.').'<br />');
                   7093:         if (($responsetype_per_response{$question-1} eq 'essayresponse') ||
                   7094:             ($responsetype_per_response{$question-1} eq 'formularesponse') ||
1.510     raeburn  7095:             ($responsetype_per_response{$question-1} eq 'stringresponse') ||
                   7096:             ($responsetype_per_response{$question-1} eq 'imageresponse') ||
                   7097:             ($responsetype_per_response{$question-1} eq 'reactionresponse') ||
                   7098:             ($responsetype_per_response{$question-1} eq 'organicresponse')) {
1.572     www      7099:             $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  7100:         } else {
                   7101:             $r->print(&mt("Select at most one bubble in a single line and select 'No Bubble' in all the other lines. ")."<br />");
                   7102:         }
1.497     foxr     7103:     }
                   7104:     for (my $i =0; $i < $lines; $i++) {
1.503     raeburn  7105:         my $selected = $$scan_record{"scantron.$current_line.answer"};
                   7106: 	&scantron_bubble_selector($r,$scan_config,$current_line, 
                   7107: 	        		  $questionnum,$error,split('', $selected));
1.524     raeburn  7108:         push(@linenums,$current_line);
1.497     foxr     7109: 	$current_line++;
                   7110:     }
                   7111:     if ($lines > 1) {
                   7112: 	$r->print("<hr /><br />");
                   7113:     }
1.503     raeburn  7114:     return @linenums;
1.157     albertel 7115: }
1.423     albertel 7116: 
                   7117: =pod
                   7118: 
                   7119: =item scantron_bubble_selector
                   7120:   
                   7121:    Generates the html radiobuttons to correct a single bubble line
1.424     albertel 7122:    possibly showing the existing the selected bubbles if known
1.423     albertel 7123: 
                   7124:  Arguments:
                   7125:     $r           - Apache request object
                   7126:     $scan_config - hash from &get_scantron_config()
1.497     foxr     7127:     $line        - Number of the line being displayed.
1.503     raeburn  7128:     $questionnum - Question number (may include subquestion)
                   7129:     $error       - Type of error.
1.497     foxr     7130:     @selected    - Array of bubbles picked on this line.
1.423     albertel 7131: 
                   7132: =cut
                   7133: 
1.157     albertel 7134: sub scantron_bubble_selector {
1.503     raeburn  7135:     my ($r,$scan_config,$line,$questionnum,$error,@selected)=@_;
1.157     albertel 7136:     my $max=$$scan_config{'Qlength'};
1.274     albertel 7137: 
                   7138:     my $scmode=$$scan_config{'Qon'};
                   7139:     if ($scmode eq 'number' || $scmode eq 'letter') { $max=10; }	     
                   7140: 
1.157     albertel 7141:     my @alphabet=('A'..'Z');
1.503     raeburn  7142:     $r->print(&Apache::loncommon::start_data_table().
                   7143:               &Apache::loncommon::start_data_table_row());
                   7144:     $r->print('<td rowspan="2" class="LC_leftcol_header">'.$line.'</td>');
1.497     foxr     7145:     for (my $i=0;$i<$max+1;$i++) {
                   7146: 	$r->print("\n".'<td align="center">');
                   7147: 	if ($selected[0] eq $alphabet[$i]) { $r->print('X'); shift(@selected) }
                   7148: 	else { $r->print('&nbsp;'); }
                   7149: 	$r->print('</td>');
                   7150:     }
1.503     raeburn  7151:     $r->print(&Apache::loncommon::end_data_table_row().
                   7152:               &Apache::loncommon::start_data_table_row());
1.497     foxr     7153:     for (my $i=0;$i<$max;$i++) {
                   7154: 	$r->print("\n".
                   7155: 		  '<td><label><input type="radio" name="scantron_correct_Q_'.
                   7156: 		  $line.'" value="'.$i.'" />'.$alphabet[$i]."</label></td>");
                   7157:     }
1.503     raeburn  7158:     my $nobub_checked = ' ';
                   7159:     if ($error eq 'missingbubble') {
                   7160:         $nobub_checked = ' checked = "checked" ';
                   7161:     }
                   7162:     $r->print("\n".'<td><label><input type="radio" name="scantron_correct_Q_'.
                   7163: 	      $line.'" value="none"'.$nobub_checked.'/>'.&mt('No bubble').
                   7164:               '</label>'."\n".'<input type="hidden" name="scantron_questionnum_Q_'.
                   7165:               $line.'" value="'.$questionnum.'" /></td>');
                   7166:     $r->print(&Apache::loncommon::end_data_table_row().
                   7167:               &Apache::loncommon::end_data_table());
1.157     albertel 7168: }
                   7169: 
1.423     albertel 7170: =pod
                   7171: 
                   7172: =item num_matches
                   7173: 
1.424     albertel 7174:    Counts the number of characters that are the same between the two arguments.
                   7175: 
                   7176:  Arguments:
                   7177:    $orig - CODE from the scanline
                   7178:    $code - CODE to match against
                   7179: 
                   7180:  Returns:
                   7181:    $count - integer count of the number of same characters between the
                   7182:             two arguments
                   7183: 
1.423     albertel 7184: =cut
                   7185: 
1.194     albertel 7186: sub num_matches {
                   7187:     my ($orig,$code) = @_;
                   7188:     my @code=split(//,$code);
                   7189:     my @orig=split(//,$orig);
                   7190:     my $same=0;
                   7191:     for (my $i=0;$i<scalar(@code);$i++) {
                   7192: 	if ($code[$i] eq $orig[$i]) { $same++; }
                   7193:     }
                   7194:     return $same;
                   7195: }
                   7196: 
1.423     albertel 7197: =pod
                   7198: 
                   7199: =item scantron_get_closely_matching_CODEs
                   7200: 
1.424     albertel 7201:    Cycles through all CODEs and finds the set that has the greatest
                   7202:    number of same characters as the provided CODE
                   7203: 
                   7204:  Arguments:
                   7205:    $allcodes - hash ref returned by &get_codes()
                   7206:    $CODE     - CODE from the current scanline
                   7207: 
                   7208:  Returns:
                   7209:    2 element list
                   7210:     - first elements is number of how closely matching the best fit is 
                   7211:       (5 means best set has 5 matching characters)
                   7212:     - second element is an arrary ref containing the set of valid CODEs
                   7213:       that best fit the passed in CODE
                   7214: 
1.423     albertel 7215: =cut
                   7216: 
1.194     albertel 7217: sub scantron_get_closely_matching_CODEs {
                   7218:     my ($allcodes,$CODE)=@_;
                   7219:     my @CODEs;
                   7220:     foreach my $testcode (sort(keys(%{$allcodes}))) {
                   7221: 	push(@{$CODEs[&num_matches($CODE,$testcode)]},$testcode);
                   7222:     }
                   7223: 
                   7224:     return ($#CODEs,$CODEs[-1]);
                   7225: }
                   7226: 
1.423     albertel 7227: =pod
                   7228: 
                   7229: =item get_codes
                   7230: 
1.424     albertel 7231:    Builds a hash which has keys of all of the valid CODEs from the selected
                   7232:    set of remembered CODEs.
                   7233: 
                   7234:  Arguments:
                   7235:   $old_name - name of the set of remembered CODEs
                   7236:   $cdom     - domain of the course
                   7237:   $cnum     - internal course name
                   7238: 
                   7239:  Returns:
                   7240:   %allcodes - keys are the valid CODEs, values are all 1
                   7241: 
1.423     albertel 7242: =cut
                   7243: 
1.194     albertel 7244: sub get_codes {
1.280     foxr     7245:     my ($old_name, $cdom, $cnum) = @_;
                   7246:     if (!$old_name) {
                   7247: 	$old_name=$env{'form.scantron_CODElist'};
                   7248:     }
                   7249:     if (!$cdom) {
                   7250: 	$cdom =$env{'course.'.$env{'request.course.id'}.'.domain'};
                   7251:     }
                   7252:     if (!$cnum) {
                   7253: 	$cnum =$env{'course.'.$env{'request.course.id'}.'.num'};
                   7254:     }
1.278     albertel 7255:     my %result=&Apache::lonnet::get('CODEs',[$old_name,"type\0$old_name"],
                   7256: 				    $cdom,$cnum);
                   7257:     my %allcodes;
                   7258:     if ($result{"type\0$old_name"} eq 'number') {
                   7259: 	%allcodes=map {($_,1)} split(',',$result{$old_name});
                   7260:     } else {
                   7261: 	%allcodes=map {(&Apache::lonprintout::num_to_letters($_),1)} split(',',$result{$old_name});
                   7262:     }
1.194     albertel 7263:     return %allcodes;
                   7264: }
                   7265: 
1.423     albertel 7266: =pod
                   7267: 
                   7268: =item scantron_validate_CODE
                   7269: 
1.424     albertel 7270:    Validates all scanlines in the selected file to not have any
                   7271:    invalid or underspecified CODEs and that none of the codes are
                   7272:    duplicated if this was requested.
                   7273: 
1.423     albertel 7274: =cut
                   7275: 
1.157     albertel 7276: sub scantron_validate_CODE {
                   7277:     my ($r,$currentphase) = @_;
1.257     albertel 7278:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.186     albertel 7279:     if ($scantron_config{'CODElocation'} &&
                   7280: 	$scantron_config{'CODEstart'} &&
                   7281: 	$scantron_config{'CODElength'}) {
1.257     albertel 7282: 	if (!defined($env{'form.scantron_CODElist'})) {
1.186     albertel 7283: 	    &FIXME_blow_up()
                   7284: 	}
                   7285:     } else {
                   7286: 	return (0,$currentphase+1);
                   7287:     }
                   7288:     
                   7289:     my %usedCODEs;
                   7290: 
1.194     albertel 7291:     my %allcodes=&get_codes();
1.186     albertel 7292: 
1.582     raeburn  7293:     my $nav_error;
                   7294:     &scantron_get_maxbubble(\$nav_error); # parse needs the lines per response array.
                   7295:     if ($nav_error) {
                   7296:         $r->print(&navmap_errormsg());
                   7297:         return(1,$currentphase);
                   7298:     }
1.447     foxr     7299: 
1.186     albertel 7300:     my ($scanlines,$scan_data)=&scantron_getfile();
                   7301:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
1.200     albertel 7302: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.186     albertel 7303: 	if ($line=~/^[\s\cz]*$/) { next; }
                   7304: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
                   7305: 						 $scan_data);
                   7306: 	my $CODE=$$scan_record{'scantron.CODE'};
                   7307: 	my $error=0;
1.224     albertel 7308: 	if (!&Apache::lonnet::validCODE($CODE)) {
                   7309: 	    &scantron_get_correction($r,$i,$scan_record,
                   7310: 				     \%scantron_config,
                   7311: 				     $line,'incorrectCODE',\%allcodes);
                   7312: 	    return(1,$currentphase);
                   7313: 	}
1.221     albertel 7314: 	if (%allcodes && !exists($allcodes{$CODE}) 
                   7315: 	    && !$$scan_record{'scantron.useCODE'}) {
1.186     albertel 7316: 	    &scantron_get_correction($r,$i,$scan_record,
                   7317: 				     \%scantron_config,
1.194     albertel 7318: 				     $line,'incorrectCODE',\%allcodes);
                   7319: 	    return(1,$currentphase);
1.186     albertel 7320: 	}
1.214     albertel 7321: 	if (exists($usedCODEs{$CODE}) 
1.257     albertel 7322: 	    && $env{'form.scantron_CODEunique'} eq 'yes'
1.192     albertel 7323: 	    && !$$scan_record{'scantron.CODE_ignore_dup'}) {
1.186     albertel 7324: 	    &scantron_get_correction($r,$i,$scan_record,
                   7325: 				     \%scantron_config,
1.194     albertel 7326: 				     $line,'duplicateCODE',$usedCODEs{$CODE});
                   7327: 	    return(1,$currentphase);
1.186     albertel 7328: 	}
1.524     raeburn  7329: 	push(@{$usedCODEs{$CODE}},$$scan_record{'scantron.PaperID'});
1.186     albertel 7330:     }
1.157     albertel 7331:     return (0,$currentphase+1);
                   7332: }
                   7333: 
1.423     albertel 7334: =pod
                   7335: 
                   7336: =item scantron_validate_doublebubble
                   7337: 
1.424     albertel 7338:    Validates all scanlines in the selected file to not have any
                   7339:    bubble lines with multiple bubbles marked.
                   7340: 
1.423     albertel 7341: =cut
                   7342: 
1.157     albertel 7343: sub scantron_validate_doublebubble {
                   7344:     my ($r,$currentphase) = @_;
                   7345:     #get student info
                   7346:     my $classlist=&Apache::loncoursedata::get_classlist();
                   7347:     my %idmap=&username_to_idmap($classlist);
                   7348: 
                   7349:     #get scantron line setup
1.257     albertel 7350:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.157     albertel 7351:     my ($scanlines,$scan_data)=&scantron_getfile();
1.583     raeburn  7352:     my $nav_error;
                   7353:     &scantron_get_maxbubble(\$nav_error); # parse needs the bubble line array.
                   7354:     if ($nav_error) {
                   7355:         $r->print(&navmap_errormsg());
                   7356:         return(1,$currentphase);
                   7357:     }
1.447     foxr     7358: 
1.157     albertel 7359:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
1.200     albertel 7360: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.157     albertel 7361: 	if ($line=~/^[\s\cz]*$/) { next; }
                   7362: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
                   7363: 						 $scan_data);
                   7364: 	if (!defined($$scan_record{'scantron.doubleerror'})) { next; }
                   7365: 	&scantron_get_correction($r,$i,$scan_record,\%scantron_config,$line,
                   7366: 				 'doublebubble',
                   7367: 				 $$scan_record{'scantron.doubleerror'});
                   7368:     	return (1,$currentphase);
                   7369:     }
                   7370:     return (0,$currentphase+1);
                   7371: }
                   7372: 
1.423     albertel 7373: 
1.503     raeburn  7374: sub scantron_get_maxbubble {
1.582     raeburn  7375:     my ($nav_error) = @_;
1.257     albertel 7376:     if (defined($env{'form.scantron_maxbubble'}) &&
                   7377: 	$env{'form.scantron_maxbubble'}) {
1.447     foxr     7378: 	&restore_bubble_lines();
1.257     albertel 7379: 	return $env{'form.scantron_maxbubble'};
1.191     albertel 7380:     }
1.330     albertel 7381: 
1.447     foxr     7382:     my (undef, undef, $sequence) =
1.257     albertel 7383: 	&Apache::lonnet::decode_symb($env{'form.selectpage'});
1.330     albertel 7384: 
1.447     foxr     7385:     my $navmap=Apache::lonnavmaps::navmap->new();
1.582     raeburn  7386:     unless (ref($navmap)) {
                   7387:         if (ref($nav_error)) {
                   7388:             $$nav_error = 1;
                   7389:         }
1.591     raeburn  7390:         return;
1.582     raeburn  7391:     }
1.191     albertel 7392:     my $map=$navmap->getResourceByUrl($sequence);
                   7393:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
1.330     albertel 7394: 
                   7395:     &Apache::lonxml::clear_problem_counter();
                   7396: 
1.557     raeburn  7397:     my $uname       = $env{'user.name'};
                   7398:     my $udom        = $env{'user.domain'};
1.435     foxr     7399:     my $cid         = $env{'request.course.id'};
                   7400:     my $total_lines = 0;
                   7401:     %bubble_lines_per_response = ();
1.447     foxr     7402:     %first_bubble_line         = ();
1.503     raeburn  7403:     %subdivided_bubble_lines   = ();
                   7404:     %responsetype_per_response = ();
1.554     raeburn  7405: 
1.447     foxr     7406:     my $response_number = 0;
                   7407:     my $bubble_line     = 0;
1.191     albertel 7408:     foreach my $resource (@resources) {
1.542     raeburn  7409:         my ($analysis,$parts) = &scantron_partids_tograde($resource,$cid,$uname,$udom);
                   7410:         if ((ref($analysis) eq 'HASH') && (ref($parts) eq 'ARRAY')) {
                   7411: 	    foreach my $part_id (@{$parts}) {
                   7412:                 my $lines;
                   7413: 
                   7414: 	        # TODO - make this a persistent hash not an array.
                   7415: 
                   7416:                 # optionresponse, matchresponse and rankresponse type items 
                   7417:                 # render as separate sub-questions in exam mode.
                   7418:                 if (($analysis->{$part_id.'.type'} eq 'optionresponse') ||
                   7419:                     ($analysis->{$part_id.'.type'} eq 'matchresponse') ||
                   7420:                     ($analysis->{$part_id.'.type'} eq 'rankresponse')) {
                   7421:                     my ($numbub,$numshown);
                   7422:                     if ($analysis->{$part_id.'.type'} eq 'optionresponse') {
                   7423:                         if (ref($analysis->{$part_id.'.options'}) eq 'ARRAY') {
                   7424:                             $numbub = scalar(@{$analysis->{$part_id.'.options'}});
                   7425:                         }
                   7426:                     } elsif ($analysis->{$part_id.'.type'} eq 'matchresponse') {
                   7427:                         if (ref($analysis->{$part_id.'.items'}) eq 'ARRAY') {
                   7428:                             $numbub = scalar(@{$analysis->{$part_id.'.items'}});
                   7429:                         }
                   7430:                     } elsif ($analysis->{$part_id.'.type'} eq 'rankresponse') {
                   7431:                         if (ref($analysis->{$part_id.'.foils'}) eq 'ARRAY') {
                   7432:                             $numbub = scalar(@{$analysis->{$part_id.'.foils'}});
                   7433:                         }
                   7434:                     }
                   7435:                     if (ref($analysis->{$part_id.'.shown'}) eq 'ARRAY') {
                   7436:                         $numshown = scalar(@{$analysis->{$part_id.'.shown'}});
                   7437:                     }
                   7438:                     my $bubbles_per_line = 10;
                   7439:                     my $inner_bubble_lines = int($numbub/$bubbles_per_line);
                   7440:                     if (($numbub % $bubbles_per_line) != 0) {
                   7441:                         $inner_bubble_lines++;
                   7442:                     }
                   7443:                     for (my $i=0; $i<$numshown; $i++) {
                   7444:                         $subdivided_bubble_lines{$response_number} .= 
                   7445:                             $inner_bubble_lines.',';
                   7446:                     }
                   7447:                     $subdivided_bubble_lines{$response_number} =~ s/,$//;
                   7448:                     $lines = $numshown * $inner_bubble_lines;
                   7449:                 } else {
                   7450:                     $lines = $analysis->{"$part_id.bubble_lines"};
                   7451:                 } 
                   7452: 
                   7453:                 $first_bubble_line{$response_number} = $bubble_line;
                   7454: 	        $bubble_lines_per_response{$response_number} = $lines;
                   7455:                 $responsetype_per_response{$response_number} = 
                   7456:                     $analysis->{$part_id.'.type'};
                   7457: 	        $response_number++;
                   7458: 
                   7459: 	        $bubble_line +=  $lines;
                   7460: 	        $total_lines +=  $lines;
                   7461: 	    }
                   7462:         }
                   7463:     }
1.552     raeburn  7464:     &Apache::lonnet::delenv('scantron.');
1.542     raeburn  7465: 
                   7466:     &save_bubble_lines();
                   7467:     $env{'form.scantron_maxbubble'} =
                   7468: 	$total_lines;
                   7469:     return $env{'form.scantron_maxbubble'};
                   7470: }
1.523     raeburn  7471: 
1.157     albertel 7472: sub scantron_validate_missingbubbles {
                   7473:     my ($r,$currentphase) = @_;
                   7474:     #get student info
                   7475:     my $classlist=&Apache::loncoursedata::get_classlist();
                   7476:     my %idmap=&username_to_idmap($classlist);
                   7477: 
                   7478:     #get scantron line setup
1.257     albertel 7479:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.157     albertel 7480:     my ($scanlines,$scan_data)=&scantron_getfile();
1.582     raeburn  7481:     my $nav_error;
                   7482:     my $max_bubble=&scantron_get_maxbubble(\$nav_error);
                   7483:     if ($nav_error) {
                   7484:         return(1,$currentphase);
                   7485:     }
1.157     albertel 7486:     if (!$max_bubble) { $max_bubble=2**31; }
                   7487:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
1.200     albertel 7488: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.157     albertel 7489: 	if ($line=~/^[\s\cz]*$/) { next; }
                   7490: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
                   7491: 						 $scan_data);
                   7492: 	if (!defined($$scan_record{'scantron.missingerror'})) { next; }
                   7493: 	my @to_correct;
1.470     foxr     7494: 	
                   7495: 	# Probably here's where the error is...
                   7496: 
1.157     albertel 7497: 	foreach my $missing (@{$$scan_record{'scantron.missingerror'}}) {
1.505     raeburn  7498:             my $lastbubble;
                   7499:             if ($missing =~ /^(\d+)\.(\d+)$/) {
                   7500:                my $question = $1;
                   7501:                my $subquestion = $2;
                   7502:                if (!defined($first_bubble_line{$question -1})) { next; }
                   7503:                my $first = $first_bubble_line{$question-1};
                   7504:                my @subans = split(/,/,$subdivided_bubble_lines{$question-1});
                   7505:                my $subcount = 1;
                   7506:                while ($subcount<$subquestion) {
                   7507:                    $first += $subans[$subcount-1];
                   7508:                    $subcount ++;
                   7509:                }
                   7510:                my $count = $subans[$subquestion-1];
                   7511:                $lastbubble = $first + $count;
                   7512:             } else {
                   7513:                 if (!defined($first_bubble_line{$missing - 1})) { next; }
                   7514:                 $lastbubble = $first_bubble_line{$missing - 1} + $bubble_lines_per_response{$missing - 1};
                   7515:             }
                   7516:             if ($lastbubble > $max_bubble) { next; }
1.157     albertel 7517: 	    push(@to_correct,$missing);
                   7518: 	}
                   7519: 	if (@to_correct) {
                   7520: 	    &scantron_get_correction($r,$i,$scan_record,\%scantron_config,
                   7521: 				     $line,'missingbubble',\@to_correct);
                   7522: 	    return (1,$currentphase);
                   7523: 	}
                   7524: 
                   7525:     }
                   7526:     return (0,$currentphase+1);
                   7527: }
                   7528: 
1.423     albertel 7529: 
1.82      albertel 7530: sub scantron_process_students {
1.608     www      7531:     my ($r,$symb) = @_;
1.513     foxr     7532: 
1.257     albertel 7533:     my (undef,undef,$sequence)=&Apache::lonnet::decode_symb($env{'form.selectpage'});
1.513     foxr     7534:     if (!$symb) {
                   7535: 	return '';
                   7536:     }
1.324     albertel 7537:     my $default_form_data=&defaultFormData($symb);
1.82      albertel 7538: 
1.257     albertel 7539:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.157     albertel 7540:     my ($scanlines,$scan_data)=&scantron_getfile();
1.82      albertel 7541:     my $classlist=&Apache::loncoursedata::get_classlist();
                   7542:     my %idmap=&username_to_idmap($classlist);
1.132     bowersj2 7543:     my $navmap=Apache::lonnavmaps::navmap->new();
1.582     raeburn  7544:     unless (ref($navmap)) {
                   7545:         $r->print(&navmap_errormsg());
                   7546:         return '';
                   7547:     }  
1.83      albertel 7548:     my $map=$navmap->getResourceByUrl($sequence);
                   7549:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
1.557     raeburn  7550:     my (%grader_partids_by_symb,%grader_randomlists_by_symb);
                   7551:     &graders_resources_pass(\@resources,\%grader_partids_by_symb,
                   7552:                             \%grader_randomlists_by_symb);
1.586     raeburn  7553:     my $resource_error;
1.557     raeburn  7554:     foreach my $resource (@resources) {
1.586     raeburn  7555:         my $ressymb;
                   7556:         if (ref($resource)) {
                   7557:             $ressymb = $resource->symb();
                   7558:         } else {
                   7559:             $resource_error = 1;
                   7560:             last;
                   7561:         }
1.557     raeburn  7562:         my ($analysis,$parts) =
                   7563:             &scantron_partids_tograde($resource,$env{'request.course.id'},
                   7564:                                       $env{'user.name'},$env{'user.domain'},1);
                   7565:         $grader_partids_by_symb{$ressymb} = $parts;
                   7566:         if (ref($analysis) eq 'HASH') {
                   7567:             if (ref($analysis->{'parts_withrandomlist'}) eq 'ARRAY') {
                   7568:                 $grader_randomlists_by_symb{$ressymb} = 
                   7569:                     $analysis->{'parts_withrandomlist'};
                   7570:             }
                   7571:         }
                   7572:     }
1.586     raeburn  7573:     if ($resource_error) {
                   7574:         $r->print(&navmap_errormsg());
                   7575:         return '';
                   7576:     }
1.557     raeburn  7577: 
1.554     raeburn  7578:     my ($uname,$udom);
1.82      albertel 7579:     my $result= <<SCANTRONFORM;
1.81      albertel 7580: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantronupload">
                   7581:   <input type="hidden" name="command" value="scantron_configphase" />
                   7582:   $default_form_data
                   7583: SCANTRONFORM
1.82      albertel 7584:     $r->print($result);
                   7585: 
                   7586:     my @delayqueue;
1.542     raeburn  7587:     my (%completedstudents,%scandata);
1.140     albertel 7588:     
1.520     www      7589:     my $lock=&Apache::lonnet::set_lock(&mt('Grading bubblesheet exam'));
1.200     albertel 7590:     my $count=&get_todo_count($scanlines,$scan_data);
1.575     www      7591:     my %prog_state=&Apache::lonhtmlcommon::Create_PrgWin($r,'Bubblesheet Status',
                   7592:  				    'Bubblesheet Progress',$count,
1.195     albertel 7593: 				    'inline',undef,'scantronupload');
1.140     albertel 7594:     &Apache::lonhtmlcommon::Update_PrgWin($r,\%prog_state,
                   7595: 					  'Processing first student');
1.542     raeburn  7596:     $r->print('<br />');
1.140     albertel 7597:     my $start=&Time::HiRes::time();
1.158     albertel 7598:     my $i=-1;
1.542     raeburn  7599:     my $started;
1.447     foxr     7600: 
1.582     raeburn  7601:     my $nav_error;
                   7602:     &scantron_get_maxbubble(\$nav_error); # Need the bubble lines array to parse.
                   7603:     if ($nav_error) {
                   7604:         $r->print(&navmap_errormsg());
                   7605:         return '';
                   7606:     }
                   7607: 
1.513     foxr     7608:     # If an ssi failed in scantron_get_maxbubble, put an error message out to
                   7609:     # the user and return.
                   7610: 
                   7611:     if ($ssi_error) {
                   7612: 	$r->print("</form>");
                   7613: 	&ssi_print_error($r);
1.520     www      7614:         &Apache::lonnet::remove_lock($lock);
1.513     foxr     7615: 	return '';		# Dunno why the other returns return '' rather than just returning.
                   7616:     }
1.447     foxr     7617: 
1.542     raeburn  7618:     my %lettdig = &letter_to_digits();
                   7619:     my $numletts = scalar(keys(%lettdig));
                   7620: 
1.157     albertel 7621:     while ($i<$scanlines->{'count'}) {
                   7622:  	($uname,$udom)=('','');
                   7623:  	$i++;
1.200     albertel 7624:  	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.157     albertel 7625:  	if ($line=~/^[\s\cz]*$/) { next; }
1.200     albertel 7626: 	if ($started) {
                   7627: 	    &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state,
                   7628: 						     'last student');
                   7629: 	}
                   7630: 	$started=1;
1.157     albertel 7631:  	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
                   7632:  						 $scan_data);
                   7633:  	unless ($uname=&scantron_find_student($scan_record,$scan_data,
                   7634:  					      \%idmap,$i)) {
                   7635:   	    &scantron_add_delay(\@delayqueue,$line,
                   7636:  				'Unable to find a student that matches',1);
                   7637:  	    next;
                   7638:   	}
                   7639:  	if (exists $completedstudents{$uname}) {
                   7640:  	    &scantron_add_delay(\@delayqueue,$line,
                   7641:  				'Student '.$uname.' has multiple sheets',2);
                   7642:  	    next;
                   7643:  	}
                   7644:   	($uname,$udom)=split(/:/,$uname);
1.330     albertel 7645: 
1.586     raeburn  7646:         my (%partids_by_symb,$res_error);
1.554     raeburn  7647:         foreach my $resource (@resources) {
1.586     raeburn  7648:             my $ressymb;
                   7649:             if (ref($resource)) {
                   7650:                 $ressymb = $resource->symb();
                   7651:             } else {
                   7652:                 $res_error = 1;
                   7653:                 last;
                   7654:             }
1.557     raeburn  7655:             if ((exists($grader_randomlists_by_symb{$ressymb})) ||
                   7656:                 (ref($grader_partids_by_symb{$ressymb}) ne 'ARRAY')) {
                   7657:                 my ($analysis,$parts) =
                   7658:                     &scantron_partids_tograde($resource,$env{'request.course.id'},$uname,$udom);
                   7659:                 $partids_by_symb{$ressymb} = $parts;
                   7660:             } else {
                   7661:                 $partids_by_symb{$ressymb} = $grader_partids_by_symb{$ressymb};
                   7662:             }
1.554     raeburn  7663:         }
                   7664: 
1.586     raeburn  7665:         if ($res_error) {
                   7666:             &scantron_add_delay(\@delayqueue,$line,
                   7667:                                 'An error occurred while grading student '.$uname,2);
                   7668:             next;
                   7669:         }
                   7670: 
1.330     albertel 7671: 	&Apache::lonxml::clear_problem_counter();
1.514     raeburn  7672:   	&Apache::lonnet::appenv($scan_record);
1.376     albertel 7673: 
                   7674: 	if (&scantron_clear_skip($scanlines,$scan_data,$i)) {
                   7675: 	    &scantron_putfile($scanlines,$scan_data);
                   7676: 	}
1.161     albertel 7677: 	
1.542     raeburn  7678:         my $scancode;
                   7679:         if ((exists($scan_record->{'scantron.CODE'})) &&
                   7680:             (&Apache::lonnet::validCODE($scan_record->{'scantron.CODE'}))) {
                   7681:             $scancode = $scan_record->{'scantron.CODE'};
                   7682:         } else {
                   7683:             $scancode = '';
                   7684:         }
                   7685: 
                   7686:         if (&grade_student_bubbles($r,$uname,$udom,$scan_record,$scancode,
1.554     raeburn  7687:                                    \@resources,\%partids_by_symb) eq 'ssi_error') {
1.542     raeburn  7688:             $ssi_error = 0; # So end of handler error message does not trigger.
                   7689:             $r->print("</form>");
                   7690:             &ssi_print_error($r);
                   7691:             &Apache::lonnet::remove_lock($lock);
                   7692:             return '';      # Why return ''?  Beats me.
                   7693:         }
1.513     foxr     7694: 
1.140     albertel 7695: 	$completedstudents{$uname}={'line'=>$line};
1.542     raeburn  7696:         if ($env{'form.verifyrecord'}) {
                   7697:             my $lastpos = $env{'form.scantron_maxbubble'}*$scantron_config{'Qlength'};
                   7698:             my $studentdata = substr($line,$scantron_config{'Qstart'}-1,$lastpos);
                   7699:             chomp($studentdata);
                   7700:             $studentdata =~ s/\r$//;
                   7701:             my $studentrecord = '';
                   7702:             my $counter = -1;
                   7703:             foreach my $resource (@resources) {
1.554     raeburn  7704:                 my $ressymb = $resource->symb();
1.542     raeburn  7705:                 ($counter,my $recording) =
                   7706:                     &verify_scantron_grading($resource,$udom,$uname,$env{'request.course.id'},
1.554     raeburn  7707:                                              $counter,$studentdata,$partids_by_symb{$ressymb},
1.542     raeburn  7708:                                              \%scantron_config,\%lettdig,$numletts);
                   7709:                 $studentrecord .= $recording;
                   7710:             }
                   7711:             if ($studentrecord ne $studentdata) {
1.554     raeburn  7712:                 &Apache::lonxml::clear_problem_counter();
                   7713:                 if (&grade_student_bubbles($r,$uname,$udom,$scan_record,$scancode,
                   7714:                                            \@resources,\%partids_by_symb) eq 'ssi_error') {
                   7715:                     $ssi_error = 0; # So end of handler error message does not trigger.
                   7716:                     $r->print("</form>");
                   7717:                     &ssi_print_error($r);
                   7718:                     &Apache::lonnet::remove_lock($lock);
                   7719:                     delete($completedstudents{$uname});
                   7720:                     return '';
                   7721:                 }
1.542     raeburn  7722:                 $counter = -1;
                   7723:                 $studentrecord = '';
                   7724:                 foreach my $resource (@resources) {
1.554     raeburn  7725:                     my $ressymb = $resource->symb();
1.542     raeburn  7726:                     ($counter,my $recording) =
                   7727:                         &verify_scantron_grading($resource,$udom,$uname,$env{'request.course.id'},
1.554     raeburn  7728:                                                  $counter,$studentdata,$partids_by_symb{$ressymb},
1.542     raeburn  7729:                                                  \%scantron_config,\%lettdig,$numletts);
                   7730:                     $studentrecord .= $recording;
                   7731:                 }
                   7732:                 if ($studentrecord ne $studentdata) {
                   7733:                     $r->print('<p><span class="LC_error">');
                   7734:                     if ($scancode eq '') {
                   7735:                         $r->print(&mt('Mismatch grading bubble sheet for user: [_1] with ID: [_2].',
                   7736:                                   $uname.':'.$udom,$scan_record->{'scantron.ID'}));
                   7737:                     } else {
                   7738:                         $r->print(&mt('Mismatch grading bubble sheet for user: [_1] with ID: [_2] and CODE: [_3].',
                   7739:                                   $uname.':'.$udom,$scan_record->{'scantron.ID'},$scancode));
                   7740:                     }
                   7741:                     $r->print('</span><br />'.&Apache::loncommon::start_data_table()."\n".
                   7742:                               &Apache::loncommon::start_data_table_header_row()."\n".
                   7743:                               '<th>'.&mt('Source').'</th><th>'.&mt('Bubbled responses').'</th>'.
                   7744:                               &Apache::loncommon::end_data_table_header_row()."\n".
                   7745:                               &Apache::loncommon::start_data_table_row().
                   7746:                               '<td>'.&mt('Bubble Sheet').'</td>'.
                   7747:                               '<td><span class="LC_nobreak">'.$studentdata.'</span></td>'.
                   7748:                               &Apache::loncommon::end_data_table_row().
                   7749:                               &Apache::loncommon::start_data_table_row().
                   7750:                               '<td>Stored submissions</td>'.
                   7751:                               '<td><span class="LC_nobreak">'.$studentrecord.'</span></td>'."\n".
                   7752:                               &Apache::loncommon::end_data_table_row().
                   7753:                               &Apache::loncommon::end_data_table().'</p>');
                   7754:                 } else {
                   7755:                     $r->print('<br /><span class="LC_warning">'.
                   7756:                              &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 />'.
                   7757:                              &mt("As a consequence, this user's submission history records two tries.").
                   7758:                                  '</span><br />');
                   7759:                 }
                   7760:             }
                   7761:         }
1.543     raeburn  7762:         if (&Apache::loncommon::connection_aborted($r)) { last; }
1.140     albertel 7763:     } continue {
1.330     albertel 7764: 	&Apache::lonxml::clear_problem_counter();
1.552     raeburn  7765: 	&Apache::lonnet::delenv('scantron.');
1.82      albertel 7766:     }
1.140     albertel 7767:     &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
1.520     www      7768:     &Apache::lonnet::remove_lock($lock);
1.172     albertel 7769: #    my $lasttime = &Time::HiRes::time()-$start;
                   7770: #    $r->print("<p>took $lasttime</p>");
1.140     albertel 7771: 
1.200     albertel 7772:     $r->print("</form>");
1.157     albertel 7773:     return '';
1.75      albertel 7774: }
1.157     albertel 7775: 
1.557     raeburn  7776: sub graders_resources_pass {
                   7777:     my ($resources,$grader_partids_by_symb,$grader_randomlists_by_symb) = @_;
                   7778:     if ((ref($resources) eq 'ARRAY') && (ref($grader_partids_by_symb)) && 
                   7779:         (ref($grader_randomlists_by_symb) eq 'HASH')) {
                   7780:         foreach my $resource (@{$resources}) {
                   7781:             my $ressymb = $resource->symb();
                   7782:             my ($analysis,$parts) =
                   7783:                 &scantron_partids_tograde($resource,$env{'request.course.id'},
                   7784:                                           $env{'user.name'},$env{'user.domain'},1);
                   7785:             $grader_partids_by_symb->{$ressymb} = $parts;
                   7786:             if (ref($analysis) eq 'HASH') {
                   7787:                 if (ref($analysis->{'parts_withrandomlist'}) eq 'ARRAY') {
                   7788:                     $grader_randomlists_by_symb->{$ressymb} =
                   7789:                         $analysis->{'parts_withrandomlist'};
                   7790:                 }
                   7791:             }
                   7792:         }
                   7793:     }
                   7794:     return;
                   7795: }
                   7796: 
1.542     raeburn  7797: sub grade_student_bubbles {
1.554     raeburn  7798:     my ($r,$uname,$udom,$scan_record,$scancode,$resources,$parts) = @_;
                   7799:     if (ref($resources) eq 'ARRAY') {
                   7800:         my $count = 0;
                   7801:         foreach my $resource (@{$resources}) {
                   7802:             my $ressymb = $resource->symb();
                   7803:             my %form = ('submitted'      => 'scantron',
                   7804:                         'grade_target'   => 'grade',
                   7805:                         'grade_username' => $uname,
                   7806:                         'grade_domain'   => $udom,
                   7807:                         'grade_courseid' => $env{'request.course.id'},
                   7808:                         'grade_symb'     => $ressymb,
                   7809:                         'CODE'           => $scancode
                   7810:                        );
                   7811:             if (ref($parts) eq 'HASH') {
                   7812:                 if (ref($parts->{$ressymb}) eq 'ARRAY') {
                   7813:                     foreach my $part (@{$parts->{$ressymb}}) {
                   7814:                         $form{'scantron_questnum_start.'.$part} =
                   7815:                             1+$env{'form.scantron.first_bubble_line.'.$count};
                   7816:                         $count++;
                   7817:                     }
                   7818:                 }
                   7819:             }
                   7820:             my $result=&ssi_with_retries($resource->src(),$ssi_retries,%form);
                   7821:             return 'ssi_error' if ($ssi_error);
                   7822:             last if (&Apache::loncommon::connection_aborted($r));
                   7823:         }
1.542     raeburn  7824:     }
                   7825:     return;
                   7826: }
                   7827: 
1.157     albertel 7828: sub scantron_upload_scantron_data {
1.608     www      7829:     my ($r,$symb)=@_;
1.565     raeburn  7830:     my $dom = $env{'request.role.domain'};
                   7831:     my $domdesc = &Apache::lonnet::domain($dom,'description');
                   7832:     $r->print(&Apache::loncommon::coursebrowser_javascript($dom));
1.157     albertel 7833:     my $select_link=&Apache::loncommon::selectcourse_link('rules','courseid',
1.181     albertel 7834: 							  'domainid',
1.565     raeburn  7835: 							  'coursename',$dom);
                   7836:     my $syllabuslink = '<a href="javascript:ToSyllabus();">'.&mt('Syllabus').'</a>'.
                   7837:                        ('&nbsp'x2).&mt('(shows course personnel)'); 
1.608     www      7838:     my $default_form_data=&defaultFormData($symb);
1.579     raeburn  7839:     my $nofile_alert = &mt('Please use the browse button to select a file from your local directory.');
                   7840:     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 7841:     $r->print(&Apache::lonhtmlcommon::scripttag('
1.157     albertel 7842:     function checkUpload(formname) {
                   7843: 	if (formname.upfile.value == "") {
1.579     raeburn  7844: 	    alert("'.$nofile_alert.'");
1.157     albertel 7845: 	    return false;
                   7846: 	}
1.565     raeburn  7847:         if (formname.courseid.value == "") {
1.579     raeburn  7848:             alert("'.$nocourseid_alert.'");
1.565     raeburn  7849:             return false;
                   7850:         }
1.157     albertel 7851: 	formname.submit();
                   7852:     }
1.565     raeburn  7853: 
                   7854:     function ToSyllabus() {
                   7855:         var cdom = '."'$dom'".';
                   7856:         var cnum = document.rules.courseid.value;
                   7857:         if (cdom == "" || cdom == null) {
                   7858:             return;
                   7859:         }
                   7860:         if (cnum == "" || cnum == null) {
                   7861:            return;
                   7862:         }
                   7863:         syllwin=window.open("/public/"+cdom+"/"+cnum+"/syllabus","LONCAPASyllabus",
                   7864:                             "height=350,width=350,scrollbars=yes,menubar=no");
                   7865:         return;
                   7866:     }
                   7867: 
1.597     wenzelju 7868: '));
                   7869:     $r->print('
1.566     raeburn  7870: <h3>'.&mt('Send scanned bubblesheet data to a course').'</h3>
                   7871: 
1.492     albertel 7872: <form enctype="multipart/form-data" action="/adm/grades" name="rules" method="post">
1.565     raeburn  7873: '.$default_form_data.
                   7874:   &Apache::lonhtmlcommon::start_pick_box().
                   7875:   &Apache::lonhtmlcommon::row_title(&mt('Course ID')).
                   7876:   '<input name="courseid" type="text" size="30" />'.$select_link.
                   7877:   &Apache::lonhtmlcommon::row_closure().
                   7878:   &Apache::lonhtmlcommon::row_title(&mt('Course Name')).
                   7879:   '<input name="coursename" type="text" size="30" />'.$syllabuslink.
                   7880:   &Apache::lonhtmlcommon::row_closure().
                   7881:   &Apache::lonhtmlcommon::row_title(&mt('Domain')).
                   7882:   '<input name="domainid" type="hidden" />'.$domdesc.
                   7883:   &Apache::lonhtmlcommon::row_closure().
                   7884:   &Apache::lonhtmlcommon::row_title(&mt('File to upload')).
                   7885:   '<input type="file" name="upfile" size="50" />'.
                   7886:   &Apache::lonhtmlcommon::row_closure(1).
                   7887:   &Apache::lonhtmlcommon::end_pick_box().'<br />
                   7888: 
1.492     albertel 7889: <input name="command" value="scantronupload_save" type="hidden" />
1.589     bisitz   7890: <input type="button" onclick="javascript:checkUpload(this.form);" value="'.&mt('Upload Bubblesheet Data').'" />
1.157     albertel 7891: </form>
1.492     albertel 7892: ');
1.157     albertel 7893:     return '';
                   7894: }
                   7895: 
1.423     albertel 7896: 
1.157     albertel 7897: sub scantron_upload_scantron_data_save {
1.608     www      7898:     my($r,$symb)=@_;
1.182     albertel 7899:     my $doanotherupload=
                   7900: 	'<br /><form action="/adm/grades" method="post">'."\n".
                   7901: 	'<input type="hidden" name="command" value="scantronupload" />'."\n".
1.492     albertel 7902: 	'<input type="submit" name="submit" value="'.&mt('Do Another Upload').'" />'."\n".
1.182     albertel 7903: 	'</form>'."\n";
1.257     albertel 7904:     if (!&Apache::lonnet::allowed('usc',$env{'form.domainid'}) &&
1.162     albertel 7905: 	!&Apache::lonnet::allowed('usc',
1.257     albertel 7906: 			    $env{'form.domainid'}.'_'.$env{'form.courseid'})) {
1.575     www      7907: 	$r->print(&mt("You are not allowed to upload bubblesheet data to the requested course.")."<br />");
1.614     www      7908: 	unless ($symb) {
1.182     albertel 7909: 	    $r->print($doanotherupload);
                   7910: 	}
1.162     albertel 7911: 	return '';
                   7912:     }
1.257     albertel 7913:     my %coursedata=&Apache::lonnet::coursedescription($env{'form.domainid'}.'_'.$env{'form.courseid'});
1.568     raeburn  7914:     my $uploadedfile;
1.567     raeburn  7915:     $r->print('<h3>'.&mt("Uploading file to [_1]",$coursedata{'description'}).'</h3>');
1.257     albertel 7916:     if (length($env{'form.upfile'}) < 2) {
1.568     raeburn  7917:         $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 7918:     } else {
1.568     raeburn  7919:         my $result = 
                   7920:             &Apache::lonnet::userfileupload('upfile','','scantron','','','',
                   7921:                                             $env{'form.courseid'},$env{'form.domainid'});
                   7922: 	if ($result =~ m{^/uploaded/}) {
1.567     raeburn  7923: 	    $r->print(&mt('[_1]Success:[_2] Successfully uploaded [_3] bytes of data into location: [_4]',
                   7924:                           '<span class="LC_success">','</span>',(length($env{'form.upfile'})-1),
                   7925: 			  '<span class="LC_filename">'.$result.'</span>'));
1.568     raeburn  7926:             ($uploadedfile) = ($result =~ m{/([^/]+)$});
1.567     raeburn  7927:             $r->print(&validate_uploaded_scantron_file($env{'form.domainid'},
1.568     raeburn  7928:                                                        $env{'form.courseid'},$uploadedfile));
1.210     albertel 7929: 	} else {
1.567     raeburn  7930: 	    $r->print(&mt('[_1]Error:[_2] An error ([_3]) occurred when attempting to upload the file, [_4]',
                   7931:                           '<span class="LC_error">','</span>',$result,
1.568     raeburn  7932: 			  '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>'));
1.183     albertel 7933: 	}
                   7934:     }
1.174     albertel 7935:     if ($symb) {
1.612     www      7936: 	$r->print(&scantron_selectphase($r,$uploadedfile,$symb));
1.174     albertel 7937:     } else {
1.182     albertel 7938: 	$r->print($doanotherupload);
1.174     albertel 7939:     }
1.157     albertel 7940:     return '';
                   7941: }
                   7942: 
1.567     raeburn  7943: sub validate_uploaded_scantron_file {
                   7944:     my ($cdom,$cname,$fname) = @_;
                   7945:     my $scanlines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.$fname);
                   7946:     my @lines;
                   7947:     if ($scanlines ne '-1') {
                   7948:         @lines=split("\n",$scanlines,-1);
                   7949:     }
                   7950:     my $output;
                   7951:     if (@lines) {
                   7952:         my (%counts,$max_match_format);
                   7953:         my ($max_match_count,$max_match_pct) = (0,0);
                   7954:         my $classlist = &Apache::loncoursedata::get_classlist($cdom,$cname);
                   7955:         my %idmap = &username_to_idmap($classlist);
                   7956:         foreach my $key (keys(%idmap)) {
                   7957:             my $lckey = lc($key);
                   7958:             $idmap{$lckey} = $idmap{$key};
                   7959:         }
                   7960:         my %unique_formats;
                   7961:         my @formatlines = &get_scantronformat_file();
                   7962:         foreach my $line (@formatlines) {
                   7963:             chomp($line);
                   7964:             my @config = split(/:/,$line);
                   7965:             my $idstart = $config[5];
                   7966:             my $idlength = $config[6];
                   7967:             if (($idstart ne '') && ($idlength > 0)) {
                   7968:                 if (ref($unique_formats{$idstart.':'.$idlength}) eq 'ARRAY') {
                   7969:                     push(@{$unique_formats{$idstart.':'.$idlength}},$config[0].':'.$config[1]); 
                   7970:                 } else {
                   7971:                     $unique_formats{$idstart.':'.$idlength} = [$config[0].':'.$config[1]];
                   7972:                 }
                   7973:             }
                   7974:         }
                   7975:         foreach my $key (keys(%unique_formats)) {
                   7976:             my ($idstart,$idlength) = split(':',$key);
                   7977:             %{$counts{$key}} = (
                   7978:                                'found'   => 0,
                   7979:                                'total'   => 0,
                   7980:                               );
                   7981:             foreach my $line (@lines) {
                   7982:                 next if ($line =~ /^#/);
                   7983:                 next if ($line =~ /^[\s\cz]*$/);
                   7984:                 my $id = substr($line,$idstart-1,$idlength);
                   7985:                 $id = lc($id);
                   7986:                 if (exists($idmap{$id})) {
                   7987:                     $counts{$key}{'found'} ++;
                   7988:                 }
                   7989:                 $counts{$key}{'total'} ++;
                   7990:             }
                   7991:             if ($counts{$key}{'total'}) {
                   7992:                 my $percent_match = (100*$counts{$key}{'found'})/($counts{$key}{'total'});
                   7993:                 if (($max_match_format eq '') || ($percent_match > $max_match_pct)) {
                   7994:                     $max_match_pct = $percent_match;
                   7995:                     $max_match_format = $key;
                   7996:                     $max_match_count = $counts{$key}{'total'};
                   7997:                 }
                   7998:             }
                   7999:         }
                   8000:         if (ref($unique_formats{$max_match_format}) eq 'ARRAY') {
                   8001:             my $format_descs;
                   8002:             my $numwithformat = @{$unique_formats{$max_match_format}};
                   8003:             for (my $i=0; $i<$numwithformat; $i++) {
                   8004:                 my ($name,$desc) = split(':',$unique_formats{$max_match_format}[$i]);
                   8005:                 if ($i<$numwithformat-2) {
                   8006:                     $format_descs .= '"<i>'.$desc.'</i>", ';
                   8007:                 } elsif ($i==$numwithformat-2) {
                   8008:                     $format_descs .= '"<i>'.$desc.'</i>" '.&mt('and').' ';
                   8009:                 } elsif ($i==$numwithformat-1) {
                   8010:                     $format_descs .= '"<i>'.$desc.'</i>"';
                   8011:                 }
                   8012:             }
                   8013:             my $showpct = sprintf("%.0f",$max_match_pct).'%';
                   8014:             $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).
                   8015:                        '<br />'.&mt('A low percentage of matches results from one of the following:').'<ul>'.
                   8016:                        '<li>'.&mt('The file was uploaded to the wrong course').'</li>'.
                   8017:                        '<li>'.&mt('The data are not in the format expected for the domain: [_1]',
                   8018:                                   '<i>'.$cdom.'</i>').'</li>'.
                   8019:                        '<li>'.&mt('Students did not bubble their IDs, or mis-bubbled them').'</li>'.
                   8020:                        '<li>'.&mt('The course roster is not up to date').'</li>'.
                   8021:                        '</ul>';
                   8022:         }
                   8023:     } else {
                   8024:         $output = '<span class="LC_warning">'.&mt('Uploaded file contained no data').'</span>';
                   8025:     }
                   8026:     return $output;
                   8027: }
                   8028: 
1.202     albertel 8029: sub valid_file {
                   8030:     my ($requested_file)=@_;
                   8031:     foreach my $filename (sort(&scantron_filenames())) {
                   8032: 	if ($requested_file eq $filename) { return 1; }
                   8033:     }
                   8034:     return 0;
                   8035: }
                   8036: 
                   8037: sub scantron_download_scantron_data {
1.608     www      8038:     my ($r,$symb)=@_;
                   8039:     my $default_form_data=&defaultFormData($symb);
1.257     albertel 8040:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   8041:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   8042:     my $file=$env{'form.scantron_selectfile'};
1.202     albertel 8043:     if (! &valid_file($file)) {
1.492     albertel 8044: 	$r->print('
1.202     albertel 8045: 	<p>
1.492     albertel 8046: 	    '.&mt('The requested file name was invalid.').'
1.202     albertel 8047:         </p>
1.492     albertel 8048: ');
1.202     albertel 8049: 	return;
                   8050:     }
                   8051:     my $orig='/uploaded/'.$cdom.'/'.$cname.'/scantron_orig_'.$file;
                   8052:     my $corrected='/uploaded/'.$cdom.'/'.$cname.'/scantron_corrected_'.$file;
                   8053:     my $skipped='/uploaded/'.$cdom.'/'.$cname.'/scantron_skipped_'.$file;
                   8054:     &Apache::lonnet::allowuploaded('/adm/grades',$orig);
                   8055:     &Apache::lonnet::allowuploaded('/adm/grades',$corrected);
                   8056:     &Apache::lonnet::allowuploaded('/adm/grades',$skipped);
1.492     albertel 8057:     $r->print('
1.202     albertel 8058:     <p>
1.492     albertel 8059: 	'.&mt('[_1]Original[_2] file as uploaded by the scantron office.',
                   8060: 	      '<a href="'.$orig.'">','</a>').'
1.202     albertel 8061:     </p>
                   8062:     <p>
1.492     albertel 8063: 	'.&mt('[_1]Corrections[_2], a file of corrected records that were used in grading.',
                   8064: 	      '<a href="'.$corrected.'">','</a>').'
1.202     albertel 8065:     </p>
                   8066:     <p>
1.492     albertel 8067: 	'.&mt('[_1]Skipped[_2], a file of records that were skipped.',
                   8068: 	      '<a href="'.$skipped.'">','</a>').'
1.202     albertel 8069:     </p>
1.492     albertel 8070: ');
1.202     albertel 8071:     return '';
                   8072: }
1.157     albertel 8073: 
1.523     raeburn  8074: sub checkscantron_results {
1.608     www      8075:     my ($r,$symb) = @_;
1.523     raeburn  8076:     if (!$symb) {return '';}
                   8077:     my $cid = $env{'request.course.id'};
1.542     raeburn  8078:     my %lettdig = &letter_to_digits();
1.523     raeburn  8079:     my $numletts = scalar(keys(%lettdig));
                   8080:     my $cnum = $env{'course.'.$cid.'.num'};
                   8081:     my $cdom = $env{'course.'.$cid.'.domain'};
                   8082:     my (undef, undef, $sequence) = &Apache::lonnet::decode_symb($env{'form.selectpage'});
                   8083:     my %record;
                   8084:     my %scantron_config =
                   8085:         &Apache::grades::get_scantron_config($env{'form.scantron_format'});
                   8086:     my ($scanlines,$scan_data)=&Apache::grades::scantron_getfile();
                   8087:     my $classlist=&Apache::loncoursedata::get_classlist();
                   8088:     my %idmap=&Apache::grades::username_to_idmap($classlist);
                   8089:     my $navmap=Apache::lonnavmaps::navmap->new();
1.582     raeburn  8090:     unless (ref($navmap)) {
                   8091:         $r->print(&navmap_errormsg());
                   8092:         return '';
                   8093:     }
1.523     raeburn  8094:     my $map=$navmap->getResourceByUrl($sequence);
1.557     raeburn  8095:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
                   8096:     my (%grader_partids_by_symb,%grader_randomlists_by_symb);
                   8097:     &graders_resources_pass(\@resources,\%grader_partids_by_symb,                             \%grader_randomlists_by_symb);
                   8098: 
1.554     raeburn  8099:     my ($uname,$udom);
1.523     raeburn  8100:     my (%scandata,%lastname,%bylast);
                   8101:     $r->print('
                   8102: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="checkscantron">'."\n");
                   8103: 
                   8104:     my @delayqueue;
                   8105:     my %completedstudents;
                   8106: 
                   8107:     my $count=&Apache::grades::get_todo_count($scanlines,$scan_data);
1.581     www      8108:     my %prog_state=&Apache::lonhtmlcommon::Create_PrgWin($r,'Bubblesheet/Submissions Comparison Status',
                   8109:                                     'Progress of Bubblesheet Data/Submission Records Comparison',$count,
1.523     raeburn  8110:                                     'inline',undef,'checkscantron');
1.546     raeburn  8111:     my ($username,$domain,$started);
1.582     raeburn  8112:     my $nav_error;
                   8113:     &scantron_get_maxbubble(\$nav_error); # Need the bubble lines array to parse.
                   8114:     if ($nav_error) {
                   8115:         $r->print(&navmap_errormsg());
                   8116:         return '';
                   8117:     }
1.523     raeburn  8118: 
                   8119:     &Apache::lonhtmlcommon::Update_PrgWin($r,\%prog_state,
                   8120:                                           'Processing first student');
                   8121:     my $start=&Time::HiRes::time();
                   8122:     my $i=-1;
                   8123: 
                   8124:     while ($i<$scanlines->{'count'}) {
                   8125:         ($username,$domain,$uname)=('','','');
                   8126:         $i++;
                   8127:         my $line=&Apache::grades::scantron_get_line($scanlines,$scan_data,$i);
                   8128:         if ($line=~/^[\s\cz]*$/) { next; }
                   8129:         if ($started) {
                   8130:             &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state,
                   8131:                                                      'last student');
                   8132:         }
                   8133:         $started=1;
                   8134:         my $scan_record=
                   8135:             &Apache::grades::scantron_parse_scanline($line,$i,\%scantron_config,
                   8136:                                                      $scan_data);
                   8137:         unless ($uname=&Apache::grades::scantron_find_student($scan_record,$scan_data,
                   8138:                                                               \%idmap,$i)) {
                   8139:             &Apache::grades::scantron_add_delay(\@delayqueue,$line,
                   8140:                                 'Unable to find a student that matches',1);
                   8141:             next;
                   8142:         }
                   8143:         if (exists $completedstudents{$uname}) {
                   8144:             &Apache::grades::scantron_add_delay(\@delayqueue,$line,
                   8145:                                 'Student '.$uname.' has multiple sheets',2);
                   8146:             next;
                   8147:         }
                   8148:         my $pid = $scan_record->{'scantron.ID'};
                   8149:         $lastname{$pid} = $scan_record->{'scantron.LastName'};
                   8150:         push(@{$bylast{$lastname{$pid}}},$pid);
                   8151:         my $lastpos = $env{'form.scantron_maxbubble'}*$scantron_config{'Qlength'};
                   8152:         $scandata{$pid} = substr($line,$scantron_config{'Qstart'}-1,$lastpos);
                   8153:         chomp($scandata{$pid});
                   8154:         $scandata{$pid} =~ s/\r$//;
                   8155:         ($username,$domain)=split(/:/,$uname);
                   8156:         my $counter = -1;
                   8157:         foreach my $resource (@resources) {
1.557     raeburn  8158:             my $parts;
1.554     raeburn  8159:             my $ressymb = $resource->symb();
1.557     raeburn  8160:             if ((exists($grader_randomlists_by_symb{$ressymb})) ||
                   8161:                 (ref($grader_partids_by_symb{$ressymb}) ne 'ARRAY')) {
                   8162:                 (my $analysis,$parts) =
                   8163:                     &scantron_partids_tograde($resource,$env{'request.course.id'},$username,$domain);
                   8164:             } else {
                   8165:                 $parts = $grader_partids_by_symb{$ressymb};
                   8166:             }
1.542     raeburn  8167:             ($counter,my $recording) =
                   8168:                 &verify_scantron_grading($resource,$domain,$username,$cid,$counter,
1.554     raeburn  8169:                                          $scandata{$pid},$parts,
1.542     raeburn  8170:                                          \%scantron_config,\%lettdig,$numletts);
                   8171:             $record{$pid} .= $recording;
1.523     raeburn  8172:         }
                   8173:     }
                   8174:     &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
                   8175:     $r->print('<br />');
                   8176:     my ($okstudents,$badstudents,$numstudents,$passed,$failed);
                   8177:     $passed = 0;
                   8178:     $failed = 0;
                   8179:     $numstudents = 0;
                   8180:     foreach my $last (sort(keys(%bylast))) {
                   8181:         if (ref($bylast{$last}) eq 'ARRAY') {
                   8182:             foreach my $pid (sort(@{$bylast{$last}})) {
                   8183:                 my $showscandata = $scandata{$pid};
                   8184:                 my $showrecord = $record{$pid};
                   8185:                 $showscandata =~ s/\s/&nbsp;/g;
                   8186:                 $showrecord =~ s/\s/&nbsp;/g;
                   8187:                 if ($scandata{$pid} eq $record{$pid}) {
                   8188:                     my $css_class = ($passed % 2)?'LC_odd_row':'LC_even_row';
                   8189:                     $okstudents .= '<tr class="'.$css_class.'">'.
1.581     www      8190: '<td>'.&mt('Bubblesheet').'</td><td>'.$showscandata.'</td><td rowspan="2">'.$last.'</td><td rowspan="2">'.$pid.'</td>'."\n".
1.523     raeburn  8191: '</tr>'."\n".
                   8192: '<tr class="'.$css_class.'">'."\n".
                   8193: '<td>Submissions</td><td>'.$showrecord.'</td></tr>'."\n";
                   8194:                     $passed ++;
                   8195:                 } else {
                   8196:                     my $css_class = ($failed % 2)?'LC_odd_row':'LC_even_row';
1.581     www      8197:                     $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  8198: '</tr>'."\n".
                   8199: '<tr class="'.$css_class.'">'."\n".
                   8200: '<td>Submissions</td><td><span class="LC_nobreak">'.$record{$pid}.'</span></td>'."\n".
                   8201: '</tr>'."\n";
                   8202:                     $failed ++;
                   8203:                 }
                   8204:                 $numstudents ++;
                   8205:             }
                   8206:         }
                   8207:     }
1.572     www      8208:     $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  8209:     $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>');
                   8210:     if ($passed) {
1.572     www      8211:         $r->print(&mt('Students with exact correspondence between bubblesheet data and submissions are as follows:').'<br /><br />');
1.523     raeburn  8212:         $r->print(&Apache::loncommon::start_data_table()."\n".
                   8213:                  &Apache::loncommon::start_data_table_header_row()."\n".
                   8214:                  '<th>'.&mt('Source').'</th><th>'.&mt('Bubble records').'</th><th>'.&mt('Name').'</th><th>'.&mt('ID').'</th>'.
                   8215:                  &Apache::loncommon::end_data_table_header_row()."\n".
                   8216:                  $okstudents."\n".
                   8217:                  &Apache::loncommon::end_data_table().'<br />');
                   8218:     }
                   8219:     if ($failed) {
1.572     www      8220:         $r->print(&mt('Students with differences between bubblesheet data and submissions are as follows:').'<br /><br />');
1.523     raeburn  8221:         $r->print(&Apache::loncommon::start_data_table()."\n".
                   8222:                  &Apache::loncommon::start_data_table_header_row()."\n".
                   8223:                  '<th>'.&mt('Source').'</th><th>'.&mt('Bubble records').'</th><th>'.&mt('Name').'</th><th>'.&mt('ID').'</th>'.
                   8224:                  &Apache::loncommon::end_data_table_header_row()."\n".
                   8225:                  $badstudents."\n".
                   8226:                  &Apache::loncommon::end_data_table()).'<br />'.
1.572     www      8227:                  &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  8228:     }
1.614     www      8229:     $r->print('</form><br />');
1.523     raeburn  8230:     return;
                   8231: }
                   8232: 
1.542     raeburn  8233: sub verify_scantron_grading {
1.554     raeburn  8234:     my ($resource,$domain,$username,$cid,$counter,$scandata,$partids,
1.542     raeburn  8235:         $scantron_config,$lettdig,$numletts) = @_;
                   8236:     my ($record,%expected,%startpos);
                   8237:     return ($counter,$record) if (!ref($resource));
                   8238:     return ($counter,$record) if (!$resource->is_problem());
                   8239:     my $symb = $resource->symb();
1.554     raeburn  8240:     return ($counter,$record) if (ref($partids) ne 'ARRAY');
                   8241:     foreach my $part_id (@{$partids}) {
1.542     raeburn  8242:         $counter ++;
                   8243:         $expected{$part_id} = 0;
                   8244:         if ($env{"form.scantron.sub_bubblelines.$counter"}) {
                   8245:             my @sub_lines = split(/,/,$env{"form.scantron.sub_bubblelines.$counter"});
                   8246:             foreach my $item (@sub_lines) {
                   8247:                 $expected{$part_id} += $item;
                   8248:             }
                   8249:         } else {
                   8250:             $expected{$part_id} = $env{"form.scantron.bubblelines.$counter"};
                   8251:         }
                   8252:         $startpos{$part_id} = $env{"form.scantron.first_bubble_line.$counter"};
                   8253:     }
                   8254:     if ($symb) {
                   8255:         my %recorded;
                   8256:         my (%returnhash) = &Apache::lonnet::restore($symb,$cid,$domain,$username);
                   8257:         if ($returnhash{'version'}) {
                   8258:             my %lasthash=();
                   8259:             my $version;
                   8260:             for ($version=1;$version<=$returnhash{'version'};$version++) {
                   8261:                 foreach my $key (sort(split(/\:/,$returnhash{$version.':keys'}))) {
                   8262:                     $lasthash{$key}=$returnhash{$version.':'.$key};
                   8263:                 }
                   8264:             }
                   8265:             foreach my $key (keys(%lasthash)) {
                   8266:                 if ($key =~ /\.scantron$/) {
                   8267:                     my $value = &unescape($lasthash{$key});
                   8268:                     my ($part_id) = ($key =~ /^resource\.(.+)\.scantron$/);
                   8269:                     if ($value eq '') {
                   8270:                         for (my $i=0; $i<$expected{$part_id}; $i++) {
                   8271:                             for (my $j=0; $j<$scantron_config->{'length'}; $j++) {
                   8272:                                 $recorded{$part_id} .= $scantron_config->{'Qoff'};
                   8273:                             }
                   8274:                         }
                   8275:                     } else {
                   8276:                         my @tocheck;
                   8277:                         my @items = split(//,$value);
                   8278:                         if (($scantron_config->{'Qon'} eq 'letter') ||
                   8279:                             ($scantron_config->{'Qon'} eq 'number')) {
                   8280:                             if (@items < $expected{$part_id}) {
                   8281:                                 my $fragment = substr($scandata,$startpos{$part_id},$expected{$part_id});
                   8282:                                 my @singles = split(//,$fragment);
                   8283:                                 foreach my $pos (@singles) {
                   8284:                                     if ($pos eq ' ') {
                   8285:                                         push(@tocheck,$pos);
                   8286:                                     } else {
                   8287:                                         my $next = shift(@items);
                   8288:                                         push(@tocheck,$next);
                   8289:                                     }
                   8290:                                 }
                   8291:                             } else {
                   8292:                                 @tocheck = @items;
                   8293:                             }
                   8294:                             foreach my $letter (@tocheck) {
                   8295:                                 if ($scantron_config->{'Qon'} eq 'letter') {
                   8296:                                     if ($letter !~ /^[A-J]$/) {
                   8297:                                         $letter = $scantron_config->{'Qoff'};
                   8298:                                     }
                   8299:                                     $recorded{$part_id} .= $letter;
                   8300:                                 } elsif ($scantron_config->{'Qon'} eq 'number') {
                   8301:                                     my $digit;
                   8302:                                     if ($letter !~ /^[A-J]$/) {
                   8303:                                         $digit = $scantron_config->{'Qoff'};
                   8304:                                     } else {
                   8305:                                         $digit = $lettdig->{$letter};
                   8306:                                     }
                   8307:                                     $recorded{$part_id} .= $digit;
                   8308:                                 }
                   8309:                             }
                   8310:                         } else {
                   8311:                             @tocheck = @items;
                   8312:                             for (my $i=0; $i<$expected{$part_id}; $i++) {
                   8313:                                 my $curr_sub = shift(@tocheck);
                   8314:                                 my $digit;
                   8315:                                 if ($curr_sub =~ /^[A-J]$/) {
                   8316:                                     $digit = $lettdig->{$curr_sub}-1;
                   8317:                                 }
                   8318:                                 if ($curr_sub eq 'J') {
                   8319:                                     $digit += scalar($numletts);
                   8320:                                 }
                   8321:                                 for (my $j=0; $j<$scantron_config->{'Qlength'}; $j++) {
                   8322:                                     if ($j == $digit) {
                   8323:                                         $recorded{$part_id} .= $scantron_config->{'Qon'};
                   8324:                                     } else {
                   8325:                                         $recorded{$part_id} .= $scantron_config->{'Qoff'};
                   8326:                                     }
                   8327:                                 }
                   8328:                             }
                   8329:                         }
                   8330:                     }
                   8331:                 }
                   8332:             }
                   8333:         }
1.554     raeburn  8334:         foreach my $part_id (@{$partids}) {
1.542     raeburn  8335:             if ($recorded{$part_id} eq '') {
                   8336:                 for (my $i=0; $i<$expected{$part_id}; $i++) {
                   8337:                     for (my $j=0; $j<$scantron_config->{'Qlength'}; $j++) {
                   8338:                         $recorded{$part_id} .= $scantron_config->{'Qoff'};
                   8339:                     }
                   8340:                 }
                   8341:             }
                   8342:             $record .= $recorded{$part_id};
                   8343:         }
                   8344:     }
                   8345:     return ($counter,$record);
                   8346: }
                   8347: 
                   8348: sub letter_to_digits { 
                   8349:     my %lettdig = (
                   8350:                     A => 1,
                   8351:                     B => 2,
                   8352:                     C => 3,
                   8353:                     D => 4,
                   8354:                     E => 5,
                   8355:                     F => 6,
                   8356:                     G => 7,
                   8357:                     H => 8,
                   8358:                     I => 9,
                   8359:                     J => 0,
                   8360:                   );
                   8361:     return %lettdig;
                   8362: }
                   8363: 
1.423     albertel 8364: 
1.75      albertel 8365: #-------- end of section for handling grading scantron forms -------
                   8366: #
                   8367: #-------------------------------------------------------------------
                   8368: 
1.72      ng       8369: #-------------------------- Menu interface -------------------------
                   8370: #
1.614     www      8371: #--- Href with symb and command ---
                   8372: 
                   8373: sub href_symb_cmd {
                   8374:     my ($symb,$cmd)=@_;
                   8375:     return '/adm/grades?symb='.&HTML::Entities::encode(&Apache::lonenc::check_encrypt($symb),'<>&"').'&command='.$cmd;
1.72      ng       8376: }
                   8377: 
1.443     banghart 8378: sub grading_menu {
1.608     www      8379:     my ($request,$symb) = @_;
1.443     banghart 8380:     if (!$symb) {return '';}
                   8381: 
                   8382:     my %fields = ('symb'=>&Apache::lonenc::check_encrypt($symb),
1.618     www      8383:                   'command'=>'individual');
1.538     schulted 8384:     
1.598     www      8385:     my $url1a = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   8386: 
                   8387:     $fields{'command'}='ungraded';
                   8388:     my $url1b=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   8389: 
                   8390:     $fields{'command'}='table';
                   8391:     my $url1c=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   8392: 
                   8393:     $fields{'command'}='all_for_one';
                   8394:     my $url1d=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   8395: 
1.621     www      8396:     $fields{'command'}='downloadfilesselect';
                   8397:     my $url1e=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   8398: 
1.443     banghart 8399:     $fields{'command'} = 'csvform';
1.538     schulted 8400:     my $url2 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   8401:     
1.443     banghart 8402:     $fields{'command'} = 'processclicker';
1.538     schulted 8403:     my $url3 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   8404:     
1.443     banghart 8405:     $fields{'command'} = 'scantron_selectphase';
1.538     schulted 8406:     my $url4 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
1.602     www      8407: 
                   8408:     $fields{'command'} = 'initialverifyreceipt';
                   8409:     my $url5 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
1.538     schulted 8410:     
1.598     www      8411:     my @menu = ({	categorytitle=>'Hand Grading',
1.538     schulted 8412:             items =>[
1.598     www      8413:                         {	linktext => 'Select individual students to grade',
                   8414:                     		url => $url1a,
1.538     schulted 8415:                     		permission => 'F',
                   8416:                     		icon => 'edit-find-replace.png',
1.598     www      8417:                     		linktitle => 'Grade current resource for a selection of students.'
                   8418:                         }, 
                   8419:                         {       linktext => 'Grade ungraded submissions.',
                   8420:                                 url => $url1b,
                   8421:                                 permission => 'F',
                   8422:                                 icon => 'edit-find-replace.png',
                   8423:                                 linktitle => 'Grade all submissions that have not been graded yet.'
1.538     schulted 8424:                         },
1.598     www      8425: 
                   8426:                         {       linktext => 'Grading table',
                   8427:                                 url => $url1c,
                   8428:                                 permission => 'F',
                   8429:                                 icon => 'edit-find-replace.png',
                   8430:                                 linktitle => 'Grade current resource for all students.'
                   8431:                         },
1.615     www      8432:                         {       linktext => 'Grade page/folder for one student',
1.598     www      8433:                                 url => $url1d,
                   8434:                                 permission => 'F',
                   8435:                                 icon => 'edit-find-replace.png',
                   8436:                                 linktitle => 'Grade all resources in current page/sequence/folder for one student.'
1.621     www      8437:                         },
                   8438:                         {       linktext => 'Download submissions',
                   8439:                                 url => $url1e,
                   8440:                                 permission => 'F',
                   8441:                                 icon => 'edit-find-replace.png',
                   8442:                                 linktitle => 'Download all students submissions.'
1.598     www      8443:                         }]},
                   8444:                          { categorytitle=>'Automated Grading',
                   8445:                items =>[
                   8446: 
1.538     schulted 8447:                 	    {	linktext => 'Upload Scores',
                   8448:                     		url => $url2,
                   8449:                     		permission => 'F',
                   8450:                     		icon => 'uploadscores.png',
                   8451:                     		linktitle => 'Specify a file containing the class scores for current resource.'
                   8452:                 	    },
                   8453:                 	    {	linktext => 'Process Clicker',
                   8454:                     		url => $url3,
                   8455:                     		permission => 'F',
                   8456:                     		icon => 'addClickerInfoFile.png',
                   8457:                     		linktitle => 'Specify a file containing the clicker information for this resource.'
                   8458:                 	    },
1.587     raeburn  8459:                 	    {	linktext => 'Grade/Manage/Review Bubblesheets',
1.538     schulted 8460:                     		url => $url4,
                   8461:                     		permission => 'F',
                   8462:                     		icon => 'stat.png',
                   8463:                     		linktitle => 'Grade scantron exams, upload/download scantron data files, and review previously graded scantron exams.'
1.602     www      8464:                 	    },
1.616     www      8465:                             {   linktext => 'Verify Receipt Number',
1.602     www      8466:                                 url => $url5,
                   8467:                                 permission => 'F',
                   8468:                                 icon => 'edit-find-replace.png',
                   8469:                                 linktitle => 'Verify a system-generated receipt number for correct problem solution.'
                   8470:                             }
                   8471: 
1.538     schulted 8472:                     ]
                   8473:             });
                   8474: 
1.443     banghart 8475:     # Create the menu
                   8476:     my $Str;
1.445     banghart 8477:     $Str .= '<form method="post" action="" name="gradingMenu">';
                   8478:     $Str .= '<input type="hidden" name="command" value="" />'.
1.618     www      8479:     	'<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
1.445     banghart 8480: 
1.602     www      8481:     $Str .= &Apache::lonhtmlcommon::generate_menu(@menu);
1.443     banghart 8482:     return $Str;    
                   8483: }
                   8484: 
1.598     www      8485: 
                   8486: sub ungraded {
                   8487:     my ($request)=@_;
                   8488:     &submit_options($request);
                   8489: }
                   8490: 
1.599     www      8491: sub submit_options_sequence {
1.608     www      8492:     my ($request,$symb) = @_;
1.599     www      8493:     if (!$symb) {return '';}
1.600     www      8494:     &commonJSfunctions($request);
                   8495:     my $result;
1.599     www      8496: 
1.600     www      8497:     $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
1.618     www      8498:         '<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
1.600     www      8499:     $result.='
                   8500: <h2>
1.615     www      8501:   '.&mt('Grade page/folder for one student').'
1.601     www      8502: </h2>'.
                   8503:             &selectfield(0).
                   8504:             '<input type="hidden" name="command" value="pickStudentPage" />
1.600     www      8505:             <div>
                   8506:               <input type="submit" value="'.&mt('Next').' &rarr;" />
                   8507:             </div>
                   8508:         </div>
                   8509:   </form>';
                   8510:     return $result;
                   8511: }
                   8512: 
                   8513: sub submit_options_table {
1.608     www      8514:     my ($request,$symb) = @_;
1.600     www      8515:     if (!$symb) {return '';}
1.599     www      8516:     &commonJSfunctions($request);
                   8517:     my $result;
                   8518: 
                   8519:     $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
1.618     www      8520:         '<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
1.599     www      8521: 
                   8522:     $result.='
                   8523: <h2>
1.600     www      8524:   '.&mt('Grading table').'
1.601     www      8525: </h2>'.
                   8526:             &selectfield(0).
                   8527:             '<input type="hidden" name="command" value="viewgrades" />
1.599     www      8528:             <div>
                   8529:               <input type="submit" value="'.&mt('Next').' &rarr;" />
                   8530:             </div>
                   8531:         </div>
                   8532:   </form>';
                   8533:     return $result;
                   8534: }
1.443     banghart 8535: 
1.621     www      8536: sub submit_options_download {
                   8537:     my ($request,$symb) = @_;
                   8538:     if (!$symb) {return '';}
                   8539: 
                   8540:     &commonJSfunctions($request);
                   8541: 
                   8542:     my $result='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
                   8543:         '<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
                   8544:     $result.='
                   8545: <h2>
                   8546:   '.&mt('Select Students for Which to Download Submissions').'
                   8547: </h2>'.&selectfield(1).'
                   8548:                 <input type="hidden" name="command" value="downloadfileslink" /> 
                   8549:               <input type="submit" value="'.&mt('Next').' &rarr;" />
                   8550:             </div>
                   8551:           </div>
1.600     www      8552: 
                   8553: 
1.621     www      8554:   </form>';
                   8555:     return $result;
                   8556: }
                   8557: 
1.443     banghart 8558: #--- Displays the submissions first page -------
                   8559: sub submit_options {
1.608     www      8560:     my ($request,$symb) = @_;
1.72      ng       8561:     if (!$symb) {return '';}
                   8562: 
1.118     ng       8563:     &commonJSfunctions($request);
1.473     albertel 8564:     my $result;
1.533     bisitz   8565: 
1.72      ng       8566:     $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
1.618     www      8567: 	'<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
1.472     albertel 8568:     $result.='
1.533     bisitz   8569: <h2>
1.600     www      8570:   '.&mt('Select individual students to grade').'
1.601     www      8571: </h2>'.&selectfield(1).'
                   8572:                 <input type="hidden" name="command" value="submission" /> 
                   8573: 	      <input type="submit" value="'.&mt('Next').' &rarr;" />
                   8574:             </div>
                   8575:           </div>
                   8576: 
                   8577: 
                   8578:   </form>';
                   8579:     return $result;
                   8580: }
1.533     bisitz   8581: 
1.601     www      8582: sub selectfield {
                   8583:    my ($full)=@_;
                   8584:    my $result='<div class="LC_columnSection">
1.537     harmsja  8585:   
1.533     bisitz   8586:     <fieldset>
                   8587:       <legend>
                   8588:        '.&mt('Sections').'
                   8589:       </legend>
1.601     www      8590:       '.&Apache::lonstatistics::SectionSelect('section','multiple',5).'
1.533     bisitz   8591:     </fieldset>
1.537     harmsja  8592:   
1.533     bisitz   8593:     <fieldset>
                   8594:       <legend>
                   8595:         '.&mt('Groups').'
                   8596:       </legend>
                   8597:       '.&Apache::lonstatistics::GroupSelect('group','multiple',5).'
                   8598:     </fieldset>
1.537     harmsja  8599:   
1.533     bisitz   8600:     <fieldset>
                   8601:       <legend>
                   8602:         '.&mt('Access Status').'
                   8603:       </legend>
1.601     www      8604:       '.&Apache::lonhtmlcommon::StatusOptions(undef,undef,5,undef,'mult').'
                   8605:     </fieldset>';
                   8606:     if ($full) {
                   8607:        $result.='
1.533     bisitz   8608:     <fieldset>
                   8609:       <legend>
                   8610:         '.&mt('Submission Status').'
1.601     www      8611:       </legend>'.
                   8612:        &Apache::loncommon::select_form('all','submitonly',
                   8613:           (&Apache::lonlocal::texthash(
                   8614:              'yes'       => 'with submissions',
                   8615:              'queued'    => 'in grading queue',
                   8616:              'graded'    => 'with ungraded submissions',
                   8617:              'incorrect' => 'with incorrect submissions',
                   8618:              'all'       => 'with any status'),
                   8619:              'select_form_order' => ['yes','queued','graded','incorrect','all'])).
                   8620:    '</fieldset>';
                   8621:     }
                   8622:     $result.='</div><br />';
1.44      ng       8623:     return $result;
1.2       albertel 8624: }
                   8625: 
1.285     albertel 8626: sub reset_perm {
                   8627:     undef(%perm);
                   8628: }
                   8629: 
                   8630: sub init_perm {
                   8631:     &reset_perm();
1.300     albertel 8632:     foreach my $test_perm ('vgr','mgr','opa') {
                   8633: 
                   8634: 	my $scope = $env{'request.course.id'};
                   8635: 	if (!($perm{$test_perm}=&Apache::lonnet::allowed($test_perm,$scope))) {
                   8636: 
                   8637: 	    $scope .= '/'.$env{'request.course.sec'};
                   8638: 	    if ( $perm{$test_perm}=
                   8639: 		 &Apache::lonnet::allowed($test_perm,$scope)) {
                   8640: 		$perm{$test_perm.'_section'}=$env{'request.course.sec'};
                   8641: 	    } else {
                   8642: 		delete($perm{$test_perm});
                   8643: 	    }
1.285     albertel 8644: 	}
                   8645:     }
                   8646: }
                   8647: 
1.400     www      8648: sub gather_clicker_ids {
1.408     albertel 8649:     my %clicker_ids;
1.400     www      8650: 
                   8651:     my $classlist = &Apache::loncoursedata::get_classlist();
                   8652: 
                   8653:     # Set up a couple variables.
1.407     albertel 8654:     my $username_idx = &Apache::loncoursedata::CL_SNAME();
                   8655:     my $domain_idx   = &Apache::loncoursedata::CL_SDOM();
1.438     www      8656:     my $status_idx   = &Apache::loncoursedata::CL_STATUS();
1.400     www      8657: 
1.407     albertel 8658:     foreach my $student (keys(%$classlist)) {
1.438     www      8659:         if ($classlist->{$student}->[$status_idx] ne 'Active') { next; }
1.407     albertel 8660:         my $username = $classlist->{$student}->[$username_idx];
                   8661:         my $domain   = $classlist->{$student}->[$domain_idx];
1.400     www      8662:         my $clickers =
1.408     albertel 8663: 	    (&Apache::lonnet::userenvironment($domain,$username,'clickers'))[1];
1.400     www      8664:         foreach my $id (split(/\,/,$clickers)) {
1.414     www      8665:             $id=~s/^[\#0]+//;
1.421     www      8666:             $id=~s/[\-\:]//g;
1.407     albertel 8667:             if (exists($clicker_ids{$id})) {
1.408     albertel 8668: 		$clicker_ids{$id}.=','.$username.':'.$domain;
1.400     www      8669:             } else {
1.408     albertel 8670: 		$clicker_ids{$id}=$username.':'.$domain;
1.400     www      8671:             }
                   8672:         }
                   8673:     }
1.407     albertel 8674:     return %clicker_ids;
1.400     www      8675: }
                   8676: 
1.402     www      8677: sub gather_adv_clicker_ids {
1.408     albertel 8678:     my %clicker_ids;
1.402     www      8679:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
                   8680:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   8681:     my %coursepersonnel=&Apache::lonnet::get_course_adv_roles($cdom.'/'.$cnum);
1.409     albertel 8682:     foreach my $element (sort(keys(%coursepersonnel))) {
1.402     www      8683:         foreach my $person (split(/\,/,$coursepersonnel{$element})) {
                   8684:             my ($puname,$pudom)=split(/\:/,$person);
                   8685:             my $clickers =
1.408     albertel 8686: 		(&Apache::lonnet::userenvironment($pudom,$puname,'clickers'))[1];
1.405     www      8687:             foreach my $id (split(/\,/,$clickers)) {
1.414     www      8688: 		$id=~s/^[\#0]+//;
1.421     www      8689:                 $id=~s/[\-\:]//g;
1.408     albertel 8690: 		if (exists($clicker_ids{$id})) {
                   8691: 		    $clicker_ids{$id}.=','.$puname.':'.$pudom;
                   8692: 		} else {
                   8693: 		    $clicker_ids{$id}=$puname.':'.$pudom;
                   8694: 		}
1.405     www      8695:             }
1.402     www      8696:         }
                   8697:     }
1.407     albertel 8698:     return %clicker_ids;
1.402     www      8699: }
                   8700: 
1.413     www      8701: sub clicker_grading_parameters {
                   8702:     return ('gradingmechanism' => 'scalar',
                   8703:             'upfiletype' => 'scalar',
                   8704:             'specificid' => 'scalar',
                   8705:             'pcorrect' => 'scalar',
                   8706:             'pincorrect' => 'scalar');
                   8707: }
                   8708: 
1.400     www      8709: sub process_clicker {
1.608     www      8710:     my ($r,$symb)=@_;
1.400     www      8711:     if (!$symb) {return '';}
                   8712:     my $result=&checkforfile_js();
                   8713:     $result.='<br /><table width="100%" border="0"><tr><td bgcolor="#777777">'."\n";
                   8714:     $result.='<table width="100%" border="0"><tr bgcolor="#e6ffff"><td>'."\n";
1.538     schulted 8715:     $result.='&nbsp;<b>'.&mt('Specify a file containing the clicker information for this resource.').
                   8716:         '</b></td></tr>'."\n";
1.601     www      8717:     $result.='<tr bgcolor="#ffffe6"><td>'."\n";
1.413     www      8718: # Attempt to restore parameters from last session, set defaults if not present
                   8719:     my %Saveable_Parameters=&clicker_grading_parameters();
                   8720:     &Apache::loncommon::restore_course_settings('grades_clicker',
                   8721:                                                  \%Saveable_Parameters);
                   8722:     if (!$env{'form.pcorrect'}) { $env{'form.pcorrect'}=100; }
                   8723:     if (!$env{'form.pincorrect'}) { $env{'form.pincorrect'}=100; }
                   8724:     if (!$env{'form.gradingmechanism'}) { $env{'form.gradingmechanism'}='attendance'; }
                   8725:     if (!$env{'form.upfiletype'}) { $env{'form.upfiletype'}='iclicker'; }
                   8726: 
                   8727:     my %checked;
1.521     www      8728:     foreach my $gradingmechanism ('attendance','personnel','specific','given') {
1.413     www      8729:        if ($env{'form.gradingmechanism'} eq $gradingmechanism) {
1.569     bisitz   8730:           $checked{$gradingmechanism}=' checked="checked"';
1.413     www      8731:        }
                   8732:     }
                   8733: 
1.400     www      8734:     my $upload=&mt("Upload File");
                   8735:     my $type=&mt("Type");
1.402     www      8736:     my $attendance=&mt("Award points just for participation");
                   8737:     my $personnel=&mt("Correctness determined from response by course personnel");
1.414     www      8738:     my $specific=&mt("Correctness determined from response with clicker ID(s)"); 
1.521     www      8739:     my $given=&mt("Correctness determined from given list of answers").' '.
                   8740:               '<font size="-2"><tt>('.&mt("Provide comma-separated list. Use '*' for any answer correct, '-' for skip").')</tt></font>';
1.402     www      8741:     my $pcorrect=&mt("Percentage points for correct solution");
                   8742:     my $pincorrect=&mt("Percentage points for incorrect solution");
1.413     www      8743:     my $selectform=&Apache::loncommon::select_form($env{'form.upfiletype'},'upfiletype',
1.419     www      8744: 						   ('iclicker' => 'i>clicker',
                   8745:                                                     'interwrite' => 'interwrite PRS'));
1.418     albertel 8746:     $symb = &Apache::lonenc::check_encrypt($symb);
1.597     wenzelju 8747:     $result.= &Apache::lonhtmlcommon::scripttag(<<ENDUPFORM);
1.402     www      8748: function sanitycheck() {
                   8749: // Accept only integer percentages
                   8750:    document.forms.gradesupload.pcorrect.value=Math.round(document.forms.gradesupload.pcorrect.value);
                   8751:    document.forms.gradesupload.pincorrect.value=Math.round(document.forms.gradesupload.pincorrect.value);
                   8752: // Find out grading choice
                   8753:    for (i=0; i<document.forms.gradesupload.gradingmechanism.length; i++) {
                   8754:       if (document.forms.gradesupload.gradingmechanism[i].checked) {
                   8755:          gradingchoice=document.forms.gradesupload.gradingmechanism[i].value;
                   8756:       }
                   8757:    }
                   8758: // By default, new choice equals user selection
                   8759:    newgradingchoice=gradingchoice;
                   8760: // Not good to give more points for false answers than correct ones
                   8761:    if (Math.round(document.forms.gradesupload.pcorrect.value)<Math.round(document.forms.gradesupload.pincorrect.value)) {
                   8762:       document.forms.gradesupload.pcorrect.value=document.forms.gradesupload.pincorrect.value;
                   8763:    }
                   8764: // If new choice is attendance only, and old choice was correctness-based, restore defaults
                   8765:    if ((gradingchoice=='attendance') && (document.forms.gradesupload.waschecked.value!='attendance')) {
                   8766:       document.forms.gradesupload.pcorrect.value=100;
                   8767:       document.forms.gradesupload.pincorrect.value=100;
                   8768:    }
                   8769: // If the values are different, cannot be attendance only
                   8770:    if ((Math.round(document.forms.gradesupload.pcorrect.value)!=Math.round(document.forms.gradesupload.pincorrect.value)) &&
                   8771:        (gradingchoice=='attendance')) {
                   8772:        newgradingchoice='personnel';
                   8773:    }
                   8774: // Change grading choice to new one
                   8775:    for (i=0; i<document.forms.gradesupload.gradingmechanism.length; i++) {
                   8776:       if (document.forms.gradesupload.gradingmechanism[i].value==newgradingchoice) {
                   8777:          document.forms.gradesupload.gradingmechanism[i].checked=true;
                   8778:       } else {
                   8779:          document.forms.gradesupload.gradingmechanism[i].checked=false;
                   8780:       }
                   8781:    }
                   8782: // Remember the old state
                   8783:    document.forms.gradesupload.waschecked.value=newgradingchoice;
                   8784: }
1.597     wenzelju 8785: ENDUPFORM
                   8786:     $result.= <<ENDUPFORM;
1.400     www      8787: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
                   8788: <input type="hidden" name="symb" value="$symb" />
                   8789: <input type="hidden" name="command" value="processclickerfile" />
                   8790: <input type="file" name="upfile" size="50" />
                   8791: <br /><label>$type: $selectform</label>
1.589     bisitz   8792: <br /><label><input type="radio" name="gradingmechanism" value="attendance"$checked{'attendance'} onclick="sanitycheck()" />$attendance </label>
                   8793: <br /><label><input type="radio" name="gradingmechanism" value="personnel"$checked{'personnel'} onclick="sanitycheck()" />$personnel</label>
                   8794: <br /><label><input type="radio" name="gradingmechanism" value="specific"$checked{'specific'} onclick="sanitycheck()" />$specific </label>
1.414     www      8795: <input type="text" name="specificid" value="$env{'form.specificid'}" size="20" />
1.589     bisitz   8796: <br /><label><input type="radio" name="gradingmechanism" value="given"$checked{'given'} onclick="sanitycheck()" />$given </label>
1.521     www      8797: <br />&nbsp;&nbsp;&nbsp;
                   8798: <input type="text" name="givenanswer" size="50" />
1.413     www      8799: <input type="hidden" name="waschecked" value="$env{'form.gradingmechanism'}" />
1.589     bisitz   8800: <br /><label>$pcorrect: <input type="text" name="pcorrect" size="4" value="$env{'form.pcorrect'}" onchange="sanitycheck()" /></label>
                   8801: <br /><label>$pincorrect: <input type="text" name="pincorrect" size="4" value="$env{'form.pincorrect'}" onchange="sanitycheck()" /></label>
                   8802: <br /><input type="button" onclick="javascript:checkUpload(this.form);" value="$upload" />
1.597     wenzelju 8803: </form>'
1.400     www      8804: ENDUPFORM
                   8805:     $result.='</td></tr></table>'."\n".
                   8806:              '</td></tr></table><br /><br />'."\n";
                   8807:     return $result;
                   8808: }
                   8809: 
                   8810: sub process_clicker_file {
1.608     www      8811:     my ($r,$symb)=@_;
1.400     www      8812:     if (!$symb) {return '';}
1.413     www      8813: 
                   8814:     my %Saveable_Parameters=&clicker_grading_parameters();
                   8815:     &Apache::loncommon::store_course_settings('grades_clicker',
                   8816:                                               \%Saveable_Parameters);
1.598     www      8817:     my $result='';
1.404     www      8818:     if (($env{'form.gradingmechanism'} eq 'specific') && ($env{'form.specificid'}!~/\w/)) {
1.408     albertel 8819: 	$result.='<span class="LC_error">'.&mt('You need to specify a clicker ID for the correct answer').'</span>';
1.614     www      8820: 	return $result;
1.404     www      8821:     }
1.522     www      8822:     if (($env{'form.gradingmechanism'} eq 'given') && ($env{'form.givenanswer'}!~/\S/)) {
1.521     www      8823:         $result.='<span class="LC_error">'.&mt('You need to specify the correct answer').'</span>';
1.614     www      8824:         return $result;
1.521     www      8825:     }
1.522     www      8826:     my $foundgiven=0;
1.521     www      8827:     if ($env{'form.gradingmechanism'} eq 'given') {
                   8828:         $env{'form.givenanswer'}=~s/^\s*//gs;
                   8829:         $env{'form.givenanswer'}=~s/\s*$//gs;
                   8830:         $env{'form.givenanswer'}=~s/[^a-zA-Z0-9\.\*\-]+/\,/g;
                   8831:         $env{'form.givenanswer'}=uc($env{'form.givenanswer'});
1.522     www      8832:         my @answers=split(/\,/,$env{'form.givenanswer'});
                   8833:         $foundgiven=$#answers+1;
1.521     www      8834:     }
1.407     albertel 8835:     my %clicker_ids=&gather_clicker_ids();
1.408     albertel 8836:     my %correct_ids;
1.404     www      8837:     if ($env{'form.gradingmechanism'} eq 'personnel') {
1.408     albertel 8838: 	%correct_ids=&gather_adv_clicker_ids();
1.404     www      8839:     }
                   8840:     if ($env{'form.gradingmechanism'} eq 'specific') {
1.414     www      8841: 	foreach my $correct_id (split(/[\s\,]/,$env{'form.specificid'})) {;
                   8842: 	   $correct_id=~tr/a-z/A-Z/;
                   8843: 	   $correct_id=~s/\s//gs;
                   8844: 	   $correct_id=~s/^[\#0]+//;
1.421     www      8845:            $correct_id=~s/[\-\:]//g;
1.414     www      8846:            if ($correct_id) {
                   8847: 	      $correct_ids{$correct_id}='specified';
                   8848:            }
                   8849:         }
1.400     www      8850:     }
1.404     www      8851:     if ($env{'form.gradingmechanism'} eq 'attendance') {
1.408     albertel 8852: 	$result.=&mt('Score based on attendance only');
1.521     www      8853:     } elsif ($env{'form.gradingmechanism'} eq 'given') {
1.522     www      8854:         $result.=&mt('Score based on [_1] ([_2] answers)','<tt>'.$env{'form.givenanswer'}.'</tt>',$foundgiven);
1.404     www      8855:     } else {
1.408     albertel 8856: 	my $number=0;
1.411     www      8857: 	$result.='<p><b>'.&mt('Correctness determined by the following IDs').'</b>';
1.408     albertel 8858: 	foreach my $id (sort(keys(%correct_ids))) {
1.411     www      8859: 	    $result.='<br /><tt>'.$id.'</tt> - ';
1.408     albertel 8860: 	    if ($correct_ids{$id} eq 'specified') {
                   8861: 		$result.=&mt('specified');
                   8862: 	    } else {
                   8863: 		my ($uname,$udom)=split(/\:/,$correct_ids{$id});
                   8864: 		$result.=&Apache::loncommon::plainname($uname,$udom);
                   8865: 	    }
                   8866: 	    $number++;
                   8867: 	}
1.411     www      8868:         $result.="</p>\n";
1.408     albertel 8869: 	if ($number==0) {
                   8870: 	    $result.='<span class="LC_error">'.&mt('No IDs found to determine correct answer').'</span>';
1.614     www      8871: 	    return $result;
1.408     albertel 8872: 	}
1.404     www      8873:     }
1.405     www      8874:     if (length($env{'form.upfile'}) < 2) {
1.407     albertel 8875:         $result.=&mt('[_1] Error: [_2] The file you attempted to upload, [_3] contained no information. Please check that you entered the correct filename.',
                   8876: 		     '<span class="LC_error">',
                   8877: 		     '</span>',
                   8878: 		     '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>');
1.614     www      8879:         return $result;
1.405     www      8880:     }
1.410     www      8881: 
                   8882: # Were able to get all the info needed, now analyze the file
                   8883: 
1.411     www      8884:     $result.=&Apache::loncommon::studentbrowser_javascript();
1.418     albertel 8885:     $symb = &Apache::lonenc::check_encrypt($symb);
1.410     www      8886:     my $heading=&mt('Scanning clicker file');
                   8887:     $result.=(<<ENDHEADER);
                   8888: <br /><table width="100%" border="0"><tr><td bgcolor="#777777">
                   8889: <table width="100%" border="0"><tr bgcolor="#e6ffff"><td>
                   8890: <b>$heading</b></td></tr><tr bgcolor=#ffffe6><td>
                   8891: <form method="post" action="/adm/grades" name="clickeranalysis">
                   8892: <input type="hidden" name="symb" value="$symb" />
                   8893: <input type="hidden" name="command" value="assignclickergrades" />
1.411     www      8894: <input type="hidden" name="gradingmechanism" value="$env{'form.gradingmechanism'}" />
                   8895: <input type="hidden" name="pcorrect" value="$env{'form.pcorrect'}" />
                   8896: <input type="hidden" name="pincorrect" value="$env{'form.pincorrect'}" />
1.410     www      8897: ENDHEADER
1.522     www      8898:     if ($env{'form.gradingmechanism'} eq 'given') {
                   8899:        $result.='<input type="hidden" name="correct:given" value="'.$env{'form.givenanswer'}.'" />';
                   8900:     } 
1.408     albertel 8901:     my %responses;
                   8902:     my @questiontitles;
1.405     www      8903:     my $errormsg='';
                   8904:     my $number=0;
                   8905:     if ($env{'form.upfiletype'} eq 'iclicker') {
1.408     albertel 8906: 	($errormsg,$number)=&iclicker_eval(\@questiontitles,\%responses);
1.406     www      8907:     }
1.419     www      8908:     if ($env{'form.upfiletype'} eq 'interwrite') {
                   8909:         ($errormsg,$number)=&interwrite_eval(\@questiontitles,\%responses);
                   8910:     }
1.411     www      8911:     $result.='<br />'.&mt('Found [_1] question(s)',$number).'<br />'.
                   8912:              '<input type="hidden" name="number" value="'.$number.'" />'.
                   8913:              &mt('Awarding [_1] percent for correct and [_2] percent for incorrect responses',
                   8914:                  $env{'form.pcorrect'},$env{'form.pincorrect'}).
                   8915:              '<br />';
1.522     www      8916:     if (($env{'form.gradingmechanism'} eq 'given') && ($number!=$foundgiven)) {
                   8917:        $result.='<span class="LC_error">'.&mt('Number of given answers does not agree with number of questions in file.').'</span>';
1.614     www      8918:        return $result;
1.522     www      8919:     } 
1.414     www      8920: # Remember Question Titles
                   8921: # FIXME: Possibly need delimiter other than ":"
                   8922:     for (my $i=0;$i<$number;$i++) {
                   8923:         $result.='<input type="hidden" name="question:'.$i.'" value="'.
                   8924:                  &HTML::Entities::encode($questiontitles[$i],'"&<>').'" />';
                   8925:     }
1.411     www      8926:     my $correct_count=0;
                   8927:     my $student_count=0;
                   8928:     my $unknown_count=0;
1.414     www      8929: # Match answers with usernames
                   8930: # FIXME: Possibly need delimiter other than ":"
1.409     albertel 8931:     foreach my $id (keys(%responses)) {
1.410     www      8932:        if ($correct_ids{$id}) {
1.414     www      8933:           $result.="\n".'<input type="hidden" name="correct:'.$correct_count.':'.$correct_ids{$id}.'" value="'.$responses{$id}.'" />';
1.411     www      8934:           $correct_count++;
1.410     www      8935:        } elsif ($clicker_ids{$id}) {
1.437     www      8936:           if ($clicker_ids{$id}=~/\,/) {
                   8937: # More than one user with the same clicker!
                   8938:              $result.="\n<hr />".&mt('Clicker registered more than once').": <tt>".$id."</tt><br />";
                   8939:              $result.="\n".'<input type="hidden" name="unknown:'.$id.'" value="'.$responses{$id}.'" />'.
                   8940:                            "<select name='multi".$id."'>";
                   8941:              foreach my $reguser (sort(split(/\,/,$clicker_ids{$id}))) {
                   8942:                  $result.="<option value='".$reguser."'>".&Apache::loncommon::plainname(split(/\:/,$reguser)).' ('.$reguser.')</option>';
                   8943:              }
                   8944:              $result.='</select>';
                   8945:              $unknown_count++;
                   8946:           } else {
                   8947: # Good: found one and only one user with the right clicker
                   8948:              $result.="\n".'<input type="hidden" name="student:'.$clicker_ids{$id}.'" value="'.$responses{$id}.'" />';
                   8949:              $student_count++;
                   8950:           }
1.410     www      8951:        } else {
1.411     www      8952:           $result.="\n<hr />".&mt('Unregistered Clicker')." <tt>".$id."</tt><br />";
                   8953:           $result.="\n".'<input type="hidden" name="unknown:'.$id.'" value="'.$responses{$id}.'" />'.
                   8954:                    "\n".&mt("Username").": <input type='text' name='uname".$id."' />&nbsp;".
                   8955:                    "\n".&mt("Domain").": ".
                   8956:                    &Apache::loncommon::select_dom_form($env{'course.'.$env{'request.course.id'}.'.domain'},'udom'.$id).'&nbsp;'.
                   8957:                    &Apache::loncommon::selectstudent_link('clickeranalysis','uname'.$id,'udom'.$id);
                   8958:           $unknown_count++;
1.410     www      8959:        }
1.405     www      8960:     }
1.412     www      8961:     $result.='<hr />'.
                   8962:              &mt('Found [_1] registered and [_2] unregistered clickers.',$student_count,$unknown_count);
1.521     www      8963:     if (($env{'form.gradingmechanism'} ne 'attendance') && ($env{'form.gradingmechanism'} ne 'given')) {
1.412     www      8964:        if ($correct_count==0) {
                   8965:           $errormsg.="Found no correct answers answers for grading!";
                   8966:        } elsif ($correct_count>1) {
1.414     www      8967:           $result.='<br /><span class="LC_warning">'.&mt("Found [_1] entries for grading!",$correct_count).'</span>';
1.412     www      8968:        }
                   8969:     }
1.428     www      8970:     if ($number<1) {
                   8971:        $errormsg.="Found no questions.";
                   8972:     }
1.412     www      8973:     if ($errormsg) {
                   8974:        $result.='<br /><span class="LC_error">'.&mt($errormsg).'</span>';
                   8975:     } else {
                   8976:        $result.='<br /><input type="submit" name="finalize" value="'.&mt('Finalize Grading').'" />';
                   8977:     }
                   8978:     $result.='</form></td></tr></table>'."\n".
1.410     www      8979:              '</td></tr></table><br /><br />'."\n";
1.614     www      8980:     return $result;
1.400     www      8981: }
                   8982: 
1.405     www      8983: sub iclicker_eval {
1.406     www      8984:     my ($questiontitles,$responses)=@_;
1.405     www      8985:     my $number=0;
                   8986:     my $errormsg='';
                   8987:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
1.410     www      8988:         my %components=&Apache::loncommon::record_sep($line);
                   8989:         my @entries=map {$components{$_}} (sort(keys(%components)));
1.408     albertel 8990: 	if ($entries[0] eq 'Question') {
                   8991: 	    for (my $i=3;$i<$#entries;$i+=6) {
                   8992: 		$$questiontitles[$number]=$entries[$i];
                   8993: 		$number++;
                   8994: 	    }
                   8995: 	}
                   8996: 	if ($entries[0]=~/^\#/) {
                   8997: 	    my $id=$entries[0];
                   8998: 	    my @idresponses;
                   8999: 	    $id=~s/^[\#0]+//;
                   9000: 	    for (my $i=0;$i<$number;$i++) {
                   9001: 		my $idx=3+$i*6;
                   9002: 		push(@idresponses,$entries[$idx]);
                   9003: 	    }
                   9004: 	    $$responses{$id}=join(',',@idresponses);
                   9005: 	}
1.405     www      9006:     }
                   9007:     return ($errormsg,$number);
                   9008: }
                   9009: 
1.419     www      9010: sub interwrite_eval {
                   9011:     my ($questiontitles,$responses)=@_;
                   9012:     my $number=0;
                   9013:     my $errormsg='';
1.420     www      9014:     my $skipline=1;
                   9015:     my $questionnumber=0;
                   9016:     my %idresponses=();
1.419     www      9017:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
                   9018:         my %components=&Apache::loncommon::record_sep($line);
                   9019:         my @entries=map {$components{$_}} (sort(keys(%components)));
1.420     www      9020:         if ($entries[1] eq 'Time') { $skipline=0; next; }
                   9021:         if ($entries[1] eq 'Response') { $skipline=1; }
                   9022:         next if $skipline;
                   9023:         if ($entries[0]!=$questionnumber) {
                   9024:            $questionnumber=$entries[0];
                   9025:            $$questiontitles[$number]=&mt('Question [_1]',$questionnumber);
                   9026:            $number++;
1.419     www      9027:         }
1.420     www      9028:         my $id=$entries[4];
                   9029:         $id=~s/^[\#0]+//;
1.421     www      9030:         $id=~s/^v\d*\://i;
                   9031:         $id=~s/[\-\:]//g;
1.420     www      9032:         $idresponses{$id}[$number]=$entries[6];
                   9033:     }
1.524     raeburn  9034:     foreach my $id (keys(%idresponses)) {
1.420     www      9035:        $$responses{$id}=join(',',@{$idresponses{$id}});
                   9036:        $$responses{$id}=~s/^\s*\,//;
1.419     www      9037:     }
                   9038:     return ($errormsg,$number);
                   9039: }
                   9040: 
1.414     www      9041: sub assign_clicker_grades {
1.608     www      9042:     my ($r,$symb)=@_;
1.414     www      9043:     if (!$symb) {return '';}
1.416     www      9044: # See which part we are saving to
1.582     raeburn  9045:     my $res_error;
                   9046:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
                   9047:     if ($res_error) {
                   9048:         return &navmap_errormsg();
                   9049:     }
1.416     www      9050: # FIXME: This should probably look for the first handgradeable part
                   9051:     my $part=$$partlist[0];
                   9052: # Start screen output
1.598     www      9053:     my $result='';
1.416     www      9054: 
1.414     www      9055:     my $heading=&mt('Assigning grades based on clicker file');
                   9056:     $result.=(<<ENDHEADER);
                   9057: <br /><table width="100%" border="0"><tr><td bgcolor="#777777">
                   9058: <table width="100%" border="0"><tr bgcolor="#e6ffff"><td>
                   9059: <b>$heading</b></td></tr><tr bgcolor=#ffffe6><td>
                   9060: ENDHEADER
                   9061: # Get correct result
                   9062: # FIXME: Possibly need delimiter other than ":"
                   9063:     my @correct=();
1.415     www      9064:     my $gradingmechanism=$env{'form.gradingmechanism'};
                   9065:     my $number=$env{'form.number'};
                   9066:     if ($gradingmechanism ne 'attendance') {
1.414     www      9067:        foreach my $key (keys(%env)) {
                   9068:           if ($key=~/^form\.correct\:/) {
                   9069:              my @input=split(/\,/,$env{$key});
                   9070:              for (my $i=0;$i<=$#input;$i++) {
                   9071:                  if (($correct[$i]) && ($input[$i]) &&
                   9072:                      ($correct[$i] ne $input[$i])) {
                   9073:                     $result.='<br /><span class="LC_warning">'.
                   9074:                              &mt('More than one correct result given for question "[_1]": [_2] versus [_3].',
                   9075:                                  $env{'form.question:'.$i},$correct[$i],$input[$i]).'</span>';
                   9076:                  } elsif ($input[$i]) {
                   9077:                     $correct[$i]=$input[$i];
                   9078:                  }
                   9079:              }
                   9080:           }
                   9081:        }
1.415     www      9082:        for (my $i=0;$i<$number;$i++) {
1.414     www      9083:           if (!$correct[$i]) {
                   9084:              $result.='<br /><span class="LC_error">'.
                   9085:                       &mt('No correct result given for question "[_1]"!',
                   9086:                           $env{'form.question:'.$i}).'</span>';
                   9087:           }
                   9088:        }
                   9089:        $result.='<br />'.&mt("Correct answer: [_1]",join(', ',map { ($_?$_:'-') } @correct));
                   9090:     }
                   9091: # Start grading
1.415     www      9092:     my $pcorrect=$env{'form.pcorrect'};
                   9093:     my $pincorrect=$env{'form.pincorrect'};
1.416     www      9094:     my $storecount=0;
1.415     www      9095:     foreach my $key (keys(%env)) {
1.420     www      9096:        my $user='';
1.415     www      9097:        if ($key=~/^form\.student\:(.*)$/) {
1.420     www      9098:           $user=$1;
                   9099:        }
                   9100:        if ($key=~/^form\.unknown\:(.*)$/) {
                   9101:           my $id=$1;
                   9102:           if (($env{'form.uname'.$id}) && ($env{'form.udom'.$id})) {
                   9103:              $user=$env{'form.uname'.$id}.':'.$env{'form.udom'.$id};
1.437     www      9104:           } elsif ($env{'form.multi'.$id}) {
                   9105:              $user=$env{'form.multi'.$id};
1.420     www      9106:           }
                   9107:        }
                   9108:        if ($user) { 
1.415     www      9109:           my @answer=split(/\,/,$env{$key});
                   9110:           my $sum=0;
1.522     www      9111:           my $realnumber=$number;
1.415     www      9112:           for (my $i=0;$i<$number;$i++) {
1.576     www      9113:              if  ($correct[$i] eq '-') {
                   9114:                 $realnumber--;
                   9115:              } elsif ($answer[$i]) {
1.415     www      9116:                 if ($gradingmechanism eq 'attendance') {
                   9117:                    $sum+=$pcorrect;
1.576     www      9118:                 } elsif ($correct[$i] eq '*') {
1.522     www      9119:                    $sum+=$pcorrect;
1.415     www      9120:                 } else {
                   9121:                    if ($answer[$i] eq $correct[$i]) {
                   9122:                       $sum+=$pcorrect;
                   9123:                    } else {
                   9124:                       $sum+=$pincorrect;
                   9125:                    }
                   9126:                 }
                   9127:              }
                   9128:           }
1.522     www      9129:           my $ave=$sum/(100*$realnumber);
1.416     www      9130: # Store
                   9131:           my ($username,$domain)=split(/\:/,$user);
                   9132:           my %grades=();
                   9133:           $grades{"resource.$part.solved"}='correct_by_override';
                   9134:           $grades{"resource.$part.awarded"}=$ave;
                   9135:           $grades{"resource.regrader"}="$env{'user.name'}:$env{'user.domain'}";
                   9136:           my $returncode=&Apache::lonnet::cstore(\%grades,$symb,
                   9137:                                                  $env{'request.course.id'},
                   9138:                                                  $domain,$username);
                   9139:           if ($returncode ne 'ok') {
                   9140:              $result.="<br /><span class=\"LC_error\">Failed to save student $username:$domain. Message when trying to save was ($returncode)</span>";
                   9141:           } else {
                   9142:              $storecount++;
                   9143:           }
1.415     www      9144:        }
                   9145:     }
                   9146: # We are done
1.549     hauer    9147:     $result.='<br />'.&mt('Successfully stored grades for [quant,_1,student].',$storecount).
1.416     www      9148:              '</td></tr></table>'."\n".
1.414     www      9149:              '</td></tr></table><br /><br />'."\n";
1.614     www      9150:     return $result;
1.414     www      9151: }
                   9152: 
1.582     raeburn  9153: sub navmap_errormsg {
                   9154:     return '<div class="LC_error">'.
                   9155:            &mt('An error occurred retrieving information about resources in the course.').'<br />'.
1.595     raeburn  9156:            &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  9157:            '</div>';
                   9158: }
1.607     droeschl 9159: 
1.609     www      9160: sub startpage {
1.613     www      9161:     my ($r,$symb,$crumbs,$onlyfolderflag,$nodisplayflag) = @_;
1.614     www      9162:     unshift(@$crumbs,{href=>&href_symb_cmd($symb,'gradingmenu'),text=>"Grading"});
1.607     droeschl 9163:     $r->print(&Apache::loncommon::start_page('Grading',undef,
1.610     www      9164:                                           {'bread_crumbs' => $crumbs}));
1.613     www      9165:     unless ($nodisplayflag) {
                   9166:        $r->print(&Apache::lonhtmlcommon::resource_info_box($symb,$onlyfolderflag));
                   9167:     }
1.607     droeschl 9168: }
1.582     raeburn  9169: 
1.622     www      9170: sub select_problem {
                   9171:     my ($r)=@_;
1.623     www      9172:     $r->print('<h2>'.&mt('Select the problem or one of the problems you want to grade').'</h2><form action="/adm/grades">');
1.622     www      9173:     $r->print(&Apache::lonstathelpers::problem_selector('.',undef,1));
                   9174:     $r->print('<input type="hidden" name="command" value="gradingmenu" />');
                   9175:     $r->print('<input type="submit" value="'.&mt('Next').' &rarr;" /></form>');
                   9176: }
                   9177: 
1.1       albertel 9178: sub handler {
1.41      ng       9179:     my $request=$_[0];
1.434     albertel 9180:     &reset_caches();
1.257     albertel 9181:     if ($env{'browser.mathml'}) {
1.141     www      9182: 	&Apache::loncommon::content_type($request,'text/xml');
1.41      ng       9183:     } else {
1.141     www      9184: 	&Apache::loncommon::content_type($request,'text/html');
1.41      ng       9185:     }
                   9186:     $request->send_http_header;
1.44      ng       9187:     return '' if $request->header_only;
1.41      ng       9188:     &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'});
1.608     www      9189: 
                   9190: # see what command we need to execute
                   9191: 
1.160     albertel 9192:     my @commands=&Apache::loncommon::get_env_multiple('form.command');
                   9193:     my $command=$commands[0];
1.447     foxr     9194: 
1.160     albertel 9195:     if ($#commands > 0) {
                   9196: 	&Apache::lonnet::logthis("grades got multiple commands ".join(':',@commands));
                   9197:     }
1.608     www      9198: 
                   9199: # see what the symb is
                   9200: 
                   9201:     my $symb=$env{'form.symb'};
                   9202:     unless ($symb) {
                   9203:        (my $url=$env{'form.url'}) =~ s-^https*://($ENV{'SERVER_NAME'}|$ENV{'HTTP_HOST'})--;
                   9204:        $symb=&Apache::lonnet::symbread($url);
                   9205:     }
                   9206:     &Apache::lonenc::check_decrypt(\$symb);                             
                   9207: 
1.513     foxr     9208:     $ssi_error = 0;
1.622     www      9209:     if ($symb eq '' || $command eq '') {
1.601     www      9210: #
                   9211: # Not called from a resource
                   9212: #    
1.622     www      9213:         &startpage($request,undef,[],1,1);
                   9214:         &select_problem($request);
1.41      ng       9215:     } else {
1.285     albertel 9216: 	&init_perm();
1.104     albertel 9217: 	if ($command eq 'submission' && $perm{'vgr'}) {
1.608     www      9218:             &startpage($request,$symb,[{href=>"", text=>"Student Submissions"}]);
1.611     www      9219: 	    ($env{'form.student'} eq '' ? &listStudents($request,$symb) : &submission($request,0,0,$symb));
1.103     albertel 9220: 	} elsif ($command eq 'pickStudentPage' && $perm{'vgr'}) {
1.615     www      9221:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,'all_for_one'),text=>'Grade page/folder for one student'},
                   9222:                                        {href=>'',text=>'Select student'}],1,1);
1.608     www      9223: 	    &pickStudentPage($request,$symb);
1.103     albertel 9224: 	} elsif ($command eq 'displayPage' && $perm{'vgr'}) {
1.615     www      9225:             &startpage($request,$symb,
                   9226:                                       [{href=>&href_symb_cmd($symb,'all_for_one'),text=>'Grade page/folder for one student'},
                   9227:                                        {href=>'',text=>'Select student'},
                   9228:                                        {href=>'',text=>'Grade student'}],1,1);
1.608     www      9229: 	    &displayPage($request,$symb);
1.104     albertel 9230: 	} elsif ($command eq 'gradeByPage' && $perm{'mgr'}) {
1.616     www      9231:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,'all_for_one'),text=>'Grade page/folder for one student'},
                   9232:                                        {href=>'',text=>'Select student'},
                   9233:                                        {href=>'',text=>'Grade student'},
                   9234:                                        {href=>'',text=>'Store grades'}],1,1);
1.608     www      9235: 	    &updateGradeByPage($request,$symb);
1.104     albertel 9236: 	} elsif ($command eq 'processGroup' && $perm{'vgr'}) {
1.619     www      9237:             &startpage($request,$symb,[{href=>'',text=>'...'},
                   9238:                                        {href=>'',text=>'Modify grades'}]);
1.608     www      9239: 	    &processGroup($request,$symb);
1.104     albertel 9240: 	} elsif ($command eq 'gradingmenu' && $perm{'vgr'}) {
1.608     www      9241:             &startpage($request,$symb);
                   9242: 	    $request->print(&grading_menu($request,$symb));
1.598     www      9243: 	} elsif ($command eq 'individual' && $perm{'vgr'}) {
1.617     www      9244:             &startpage($request,$symb,[{href=>'',text=>'Select individual students to grade'}]);
1.608     www      9245: 	    $request->print(&submit_options($request,$symb));
1.598     www      9246:         } elsif ($command eq 'ungraded' && $perm{'vgr'}) {
1.617     www      9247:             &startpage($request,$symb,[{href=>'',text=>'Grade ungraded submissions'}]);
                   9248:             $request->print(&listStudents($request,$symb,'graded'));
1.598     www      9249:         } elsif ($command eq 'table' && $perm{'vgr'}) {
1.614     www      9250:             &startpage($request,$symb,[{href=>"", text=>"Grading table"}]);
1.611     www      9251:             $request->print(&submit_options_table($request,$symb));
1.598     www      9252:         } elsif ($command eq 'all_for_one' && $perm{'vgr'}) {
1.615     www      9253:             &startpage($request,$symb,[{href=>'',text=>'Grade page/folder for one student'}],1,1);
1.608     www      9254:             $request->print(&submit_options_sequence($request,$symb));
1.104     albertel 9255: 	} elsif ($command eq 'viewgrades' && $perm{'vgr'}) {
1.614     www      9256:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,"table"), text=>"Grading table"},{href=>'', text=>"Modify grades"}]);
1.608     www      9257: 	    $request->print(&viewgrades($request,$symb));
1.104     albertel 9258: 	} elsif ($command eq 'handgrade' && $perm{'mgr'}) {
1.620     www      9259:             &startpage($request,$symb,[{href=>'',text=>'...'},
                   9260:                                        {href=>'',text=>'Store grades'}]);
1.608     www      9261: 	    $request->print(&processHandGrade($request,$symb));
1.106     albertel 9262: 	} elsif ($command eq 'editgrades' && $perm{'mgr'}) {
1.614     www      9263:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,"table"), text=>"Grading table"},
                   9264:                                        {href=>&href_symb_cmd($symb,'viewgrades').'&group=all&section=all&Status=Active',
                   9265:                                                                              text=>"Modify grades"},
                   9266:                                        {href=>'', text=>"Store grades"}]);
1.608     www      9267: 	    $request->print(&editgrades($request,$symb));
1.602     www      9268:         } elsif ($command eq 'initialverifyreceipt' && $perm{'vgr'}) {
1.616     www      9269:             &startpage($request,$symb,[{href=>'',text=>'Verify Receipt Number'}]);
1.611     www      9270:             $request->print(&initialverifyreceipt($request,$symb));
1.106     albertel 9271: 	} elsif ($command eq 'verify' && $perm{'vgr'}) {
1.616     www      9272:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,"initialverifyreceipt"),text=>'Verify Receipt Number'},
                   9273:                                        {href=>'',text=>'Verification Result'}]);
1.608     www      9274: 	    $request->print(&verifyreceipt($request,$symb));
1.400     www      9275:         } elsif ($command eq 'processclicker' && $perm{'mgr'}) {
1.615     www      9276:             &startpage($request,$symb,[{href=>'', text=>'Process clicker'}]);
1.608     www      9277:             $request->print(&process_clicker($request,$symb));
1.400     www      9278:         } elsif ($command eq 'processclickerfile' && $perm{'mgr'}) {
1.615     www      9279:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,'processclicker'), text=>'Process clicker'},
                   9280:                                        {href=>'', text=>'Process clicker file'}]);
1.608     www      9281:             $request->print(&process_clicker_file($request,$symb));
1.414     www      9282:         } elsif ($command eq 'assignclickergrades' && $perm{'mgr'}) {
1.615     www      9283:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,'processclicker'), text=>'Process clicker'},
                   9284:                                        {href=>'', text=>'Process clicker file'},
                   9285:                                        {href=>'', text=>'Store grades'}]);
1.608     www      9286:             $request->print(&assign_clicker_grades($request,$symb));
1.106     albertel 9287: 	} elsif ($command eq 'csvform' && $perm{'mgr'}) {
1.616     www      9288:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
1.608     www      9289: 	    $request->print(&upcsvScores_form($request,$symb));
1.106     albertel 9290: 	} elsif ($command eq 'csvupload' && $perm{'mgr'}) {
1.616     www      9291:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
1.608     www      9292: 	    $request->print(&csvupload($request,$symb));
1.106     albertel 9293: 	} elsif ($command eq 'csvuploadmap' && $perm{'mgr'} ) {
1.616     www      9294:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
1.608     www      9295: 	    $request->print(&csvuploadmap($request,$symb));
1.246     albertel 9296: 	} elsif ($command eq 'csvuploadoptions' && $perm{'mgr'}) {
1.257     albertel 9297: 	    if ($env{'form.associate'} ne 'Reverse Association') {
1.616     www      9298:                 &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
1.608     www      9299: 		$request->print(&csvuploadoptions($request,$symb));
1.41      ng       9300: 	    } else {
1.257     albertel 9301: 		if ( $env{'form.upfile_associate'} ne 'reverse' ) {
                   9302: 		    $env{'form.upfile_associate'} = 'reverse';
1.41      ng       9303: 		} else {
1.257     albertel 9304: 		    $env{'form.upfile_associate'} = 'forward';
1.41      ng       9305: 		}
1.616     www      9306:                 &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
1.608     www      9307: 		$request->print(&csvuploadmap($request,$symb));
1.41      ng       9308: 	    }
1.246     albertel 9309: 	} elsif ($command eq 'csvuploadassign' && $perm{'mgr'} ) {
1.616     www      9310:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
1.608     www      9311: 	    $request->print(&csvuploadassign($request,$symb));
1.106     albertel 9312: 	} elsif ($command eq 'scantron_selectphase' && $perm{'mgr'}) {
1.616     www      9313:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
1.612     www      9314: 	    $request->print(&scantron_selectphase($request,undef,$symb));
1.203     albertel 9315:  	} elsif ($command eq 'scantron_warning' && $perm{'mgr'}) {
1.616     www      9316:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
1.608     www      9317:  	    $request->print(&scantron_do_warning($request,$symb));
1.142     albertel 9318: 	} elsif ($command eq 'scantron_validate' && $perm{'mgr'}) {
1.616     www      9319:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
1.608     www      9320: 	    $request->print(&scantron_validate_file($request,$symb));
1.106     albertel 9321: 	} elsif ($command eq 'scantron_process' && $perm{'mgr'}) {
1.616     www      9322:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
1.608     www      9323: 	    $request->print(&scantron_process_students($request,$symb));
1.157     albertel 9324:  	} elsif ($command eq 'scantronupload' && 
1.257     albertel 9325:  		 (&Apache::lonnet::allowed('usc',$env{'request.role.domain'})||
                   9326: 		  &Apache::lonnet::allowed('usc',$env{'request.course.id'}))) {
1.616     www      9327:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
1.608     www      9328:  	    $request->print(&scantron_upload_scantron_data($request,$symb)); 
1.157     albertel 9329:  	} elsif ($command eq 'scantronupload_save' &&
1.257     albertel 9330:  		 (&Apache::lonnet::allowed('usc',$env{'request.role.domain'})||
                   9331: 		  &Apache::lonnet::allowed('usc',$env{'request.course.id'}))) {
1.616     www      9332:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
1.608     www      9333:  	    $request->print(&scantron_upload_scantron_data_save($request,$symb));
1.202     albertel 9334:  	} elsif ($command eq 'scantron_download' &&
1.257     albertel 9335: 		 &Apache::lonnet::allowed('usc',$env{'request.course.id'})) {
1.616     www      9336:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
1.608     www      9337:  	    $request->print(&scantron_download_scantron_data($request,$symb));
1.523     raeburn  9338:         } elsif ($command eq 'checksubmissions' && $perm{'vgr'}) {
1.616     www      9339:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
1.621     www      9340:             $request->print(&checkscantron_results($request,$symb));
                   9341:         } elsif ($command eq 'downloadfilesselect' && $perm{'vgr'}) {
                   9342:             &startpage($request,$symb,[{href=>'', text=>'Select which submissions to download'}]);
                   9343:             $request->print(&submit_options_download($request,$symb));
                   9344:          } elsif ($command eq 'downloadfileslink' && $perm{'vgr'}) {
                   9345:             &startpage($request,$symb,
                   9346:    [{href=>&href_symb_cmd($symb,'downloadfilesselect'), text=>'Select which submissions to download'},
                   9347:     {href=>'', text=>'Download submissions'}]);
                   9348:             &submit_download_link($request,$symb);
1.106     albertel 9349: 	} elsif ($command) {
1.620     www      9350:             &startpage($request,$symb,[{href=>'', text=>'Access denied'}]);
1.562     bisitz   9351: 	    $request->print('<p class="LC_error">'.&mt('Access Denied ([_1])',$command).'</p>');
1.26      albertel 9352: 	}
1.2       albertel 9353:     }
1.513     foxr     9354:     if ($ssi_error) {
                   9355: 	&ssi_print_error($request);
                   9356:     }
1.353     albertel 9357:     $request->print(&Apache::loncommon::end_page());
1.434     albertel 9358:     &reset_caches();
1.44      ng       9359:     return '';
                   9360: }
                   9361: 
1.1       albertel 9362: 1;
                   9363: 
1.13      albertel 9364: __END__;
1.531     jms      9365: 
                   9366: 
                   9367: =head1 NAME
                   9368: 
                   9369: Apache::grades
                   9370: 
                   9371: =head1 SYNOPSIS
                   9372: 
                   9373: Handles the viewing of grades.
                   9374: 
                   9375: This is part of the LearningOnline Network with CAPA project
                   9376: described at http://www.lon-capa.org.
                   9377: 
                   9378: =head1 OVERVIEW
                   9379: 
                   9380: Do an ssi with retries:
                   9381: While I'd love to factor out this with the vesrion in lonprintout,
                   9382: 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
                   9383: I'm not quite ready to invent (e.g. an ssi_with_retry object).
                   9384: 
                   9385: At least the logic that drives this has been pulled out into loncommon.
                   9386: 
                   9387: 
                   9388: 
                   9389: ssi_with_retries - Does the server side include of a resource.
                   9390:                      if the ssi call returns an error we'll retry it up to
                   9391:                      the number of times requested by the caller.
                   9392:                      If we still have a proble, no text is appended to the
                   9393:                      output and we set some global variables.
                   9394:                      to indicate to the caller an SSI error occurred.  
                   9395:                      All of this is supposed to deal with the issues described
                   9396:                      in LonCAPA BZ 5631 see:
                   9397:                      http://bugs.lon-capa.org/show_bug.cgi?id=5631
                   9398:                      by informing the user that this happened.
                   9399: 
                   9400: Parameters:
                   9401:   resource   - The resource to include.  This is passed directly, without
                   9402:                interpretation to lonnet::ssi.
                   9403:   form       - The form hash parameters that guide the interpretation of the resource
                   9404:                
                   9405:   retries    - Number of retries allowed before giving up completely.
                   9406: Returns:
                   9407:   On success, returns the rendered resource identified by the resource parameter.
                   9408: Side Effects:
                   9409:   The following global variables can be set:
                   9410:    ssi_error                - If an unrecoverable error occurred this becomes true.
                   9411:                               It is up to the caller to initialize this to false
                   9412:                               if desired.
                   9413:    ssi_error_resource  - If an unrecoverable error occurred, this is the value
                   9414:                               of the resource that could not be rendered by the ssi
                   9415:                               call.
                   9416:    ssi_error_message   - The error string fetched from the ssi response
                   9417:                               in the event of an error.
                   9418: 
                   9419: 
                   9420: =head1 HANDLER SUBROUTINE
                   9421: 
                   9422: ssi_with_retries()
                   9423: 
                   9424: =head1 SUBROUTINES
                   9425: 
                   9426: =over
                   9427: 
                   9428: =item scantron_get_correction() : 
                   9429: 
                   9430:    Builds the interface screen to interact with the operator to fix a
                   9431:    specific error condition in a specific scanline
                   9432: 
                   9433:  Arguments:
                   9434:     $r           - Apache request object
                   9435:     $i           - number of the current scanline
                   9436:     $scan_record - hash ref as returned from &scantron_parse_scanline()
                   9437:     $scan_config - hash ref as returned from &get_scantron_config()
                   9438:     $line        - full contents of the current scanline
                   9439:     $error       - error condition, valid values are
                   9440:                    'incorrectCODE', 'duplicateCODE',
                   9441:                    'doublebubble', 'missingbubble',
                   9442:                    'duplicateID', 'incorrectID'
                   9443:     $arg         - extra information needed
                   9444:        For errors:
                   9445:          - duplicateID   - paper number that this studentID was seen before on
                   9446:          - duplicateCODE - array ref of the paper numbers this CODE was
                   9447:                            seen on before
                   9448:          - incorrectCODE - current incorrect CODE 
                   9449:          - doublebubble  - array ref of the bubble lines that have double
                   9450:                            bubble errors
                   9451:          - missingbubble - array ref of the bubble lines that have missing
                   9452:                            bubble errors
                   9453: 
                   9454: =item  scantron_get_maxbubble() : 
                   9455: 
1.582     raeburn  9456:    Arguments:
                   9457:        $nav_error  - Reference to scalar which is a flag to indicate a
                   9458:                       failure to retrieve a navmap object.
                   9459:        if $nav_error is set to 1 by scantron_get_maxbubble(), the 
                   9460:        calling routine should trap the error condition and display the warning
                   9461:        found in &navmap_errormsg().
                   9462: 
1.531     jms      9463:    Returns the maximum number of bubble lines that are expected to
                   9464:    occur. Does this by walking the selected sequence rendering the
                   9465:    resource and then checking &Apache::lonxml::get_problem_counter()
                   9466:    for what the current value of the problem counter is.
                   9467: 
                   9468:    Caches the results to $env{'form.scantron_maxbubble'},
                   9469:    $env{'form.scantron.bubble_lines.n'}, 
                   9470:    $env{'form.scantron.first_bubble_line.n'} and
                   9471:    $env{"form.scantron.sub_bubblelines.n"}
                   9472:    which are the total number of bubble, lines, the number of bubble
                   9473:    lines for response n and number of the first bubble line for response n,
                   9474:    and a comma separated list of numbers of bubble lines for sub-questions
                   9475:    (for optionresponse, matchresponse, and rankresponse items), for response n.  
                   9476: 
                   9477: 
                   9478: =item  scantron_validate_missingbubbles() : 
                   9479: 
                   9480:    Validates all scanlines in the selected file to not have any
                   9481:     answers that don't have bubbles that have not been verified
                   9482:     to be bubble free.
                   9483: 
                   9484: =item  scantron_process_students() : 
                   9485: 
                   9486:    Routine that does the actual grading of the bubble sheet information.
                   9487: 
                   9488:    The parsed scanline hash is added to %env 
                   9489: 
                   9490:    Then foreach unskipped scanline it does an &Apache::lonnet::ssi()
                   9491:    foreach resource , with the form data of
                   9492: 
                   9493: 	'submitted'     =>'scantron' 
                   9494: 	'grade_target'  =>'grade',
                   9495: 	'grade_username'=> username of student
                   9496: 	'grade_domain'  => domain of student
                   9497: 	'grade_courseid'=> of course
                   9498: 	'grade_symb'    => symb of resource to grade
                   9499: 
                   9500:     This triggers a grading pass. The problem grading code takes care
                   9501:     of converting the bubbled letter information (now in %env) into a
                   9502:     valid submission.
                   9503: 
                   9504: =item  scantron_upload_scantron_data() :
                   9505: 
                   9506:     Creates the screen for adding a new bubble sheet data file to a course.
                   9507: 
                   9508: =item  scantron_upload_scantron_data_save() : 
                   9509: 
                   9510:    Adds a provided bubble information data file to the course if user
                   9511:    has the correct privileges to do so. 
                   9512: 
                   9513: =item  valid_file() :
                   9514: 
                   9515:    Validates that the requested bubble data file exists in the course.
                   9516: 
                   9517: =item  scantron_download_scantron_data() : 
                   9518: 
                   9519:    Shows a list of the three internal files (original, corrected,
                   9520:    skipped) for a specific bubble sheet data file that exists in the
                   9521:    course.
                   9522: 
                   9523: =item  scantron_validate_ID() : 
                   9524: 
                   9525:    Validates all scanlines in the selected file to not have any
1.556     weissno  9526:    invalid or underspecified student/employee IDs
1.531     jms      9527: 
1.582     raeburn  9528: =item navmap_errormsg() :
                   9529: 
                   9530:    Returns HTML mark-up inside a <div></div> with a link to re-initialize the course.
                   9531:    Should be called whenever the request to instantiate a navmap object fails.  
                   9532: 
1.531     jms      9533: =back
                   9534: 
                   9535: =cut

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