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

1.17      albertel    1: # The LearningOnline Network with CAPA
1.13      albertel    2: # The LON-CAPA Grading handler
1.17      albertel    3: #
1.637   ! www         4: # $Id: grades.pm,v 1.636 2010/08/30 09:47:32 wenzelju 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.632     www       823:     my $result='';
1.623     www       824:     my $res_error;
                    825:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
1.49      albertel  826: 
1.559     raeburn   827:     my %lt = &Apache::lonlocal::texthash (
                    828: 		'multiple' => 'Please select a student or group of students before clicking on the Next button.',
                    829: 		'single'   => 'Please select the student before clicking on the Next button.',
                    830: 	     );
1.597     wenzelju  831:     $request->print(&Apache::lonhtmlcommon::scripttag(<<LISTJAVASCRIPT));
1.110     ng        832:     function checkSelect(checkBox) {
                    833: 	var ctr=0;
                    834: 	var sense="";
                    835: 	if (checkBox.length > 1) {
                    836: 	    for (var i=0; i<checkBox.length; i++) {
                    837: 		if (checkBox[i].checked) {
                    838: 		    ctr++;
                    839: 		}
                    840: 	    }
1.485     albertel  841: 	    sense = '$lt{'multiple'}';
1.110     ng        842: 	} else {
                    843: 	    if (checkBox.checked) {
                    844: 		ctr = 1;
                    845: 	    }
1.485     albertel  846: 	    sense = '$lt{'single'}';
1.110     ng        847: 	}
                    848: 	if (ctr == 0) {
1.485     albertel  849: 	    alert(sense);
1.110     ng        850: 	    return false;
                    851: 	}
                    852: 	document.gradesub.submit();
                    853:     }
                    854: 
                    855:     function reLoadList(formname) {
1.112     ng        856: 	if (formname.saveStatusOld.value == pullDownSelection(formname.Status)) {return;}
1.110     ng        857: 	formname.command.value = 'submission';
                    858: 	formname.submit();
                    859:     }
1.45      ng        860: LISTJAVASCRIPT
                    861: 
1.118     ng        862:     &commonJSfunctions($request);
1.41      ng        863:     $request->print($result);
1.39      ng        864: 
1.154     albertel  865:     my $gradeTable='<form action="/adm/grades" method="post" name="gradesub">'.
1.598     www       866: 	"\n";
1.485     albertel  867: 	
1.561     bisitz    868:     $gradeTable .= &Apache::lonhtmlcommon::start_pick_box();
                    869:     $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('View Problem Text'))
                    870:                   .'<label><input type="radio" name="vProb" value="no" checked="checked" /> '.&mt('no').' </label>'."\n"
                    871:                   .'<label><input type="radio" name="vProb" value="yes" /> '.&mt('one student').' </label>'."\n"
                    872:                   .'<label><input type="radio" name="vProb" value="all" /> '.&mt('all students').' </label><br />'."\n"
                    873:                   .&Apache::lonhtmlcommon::row_closure();
                    874:     $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('View Answer'))
                    875:                   .'<label><input type="radio" name="vAns" value="no"  /> '.&mt('no').' </label>'."\n"
                    876:                   .'<label><input type="radio" name="vAns" value="yes" /> '.&mt('one student').' </label>'."\n"
                    877:                   .'<label><input type="radio" name="vAns" value="all" checked="checked" /> '.&mt('all students').' </label><br />'."\n"
                    878:                   .&Apache::lonhtmlcommon::row_closure();
1.485     albertel  879: 
                    880:     my $submission_options;
1.442     banghart  881:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
                    882:     my $saveStatus = $stu_status eq '' ? 'Active' : $stu_status;
1.257     albertel  883:     $env{'form.Status'} = $saveStatus;
1.485     albertel  884:     $submission_options.=
1.592     bisitz    885:         '<span class="LC_nobreak">'.
1.624     www       886:         '<label><input type="radio" name="lastSub" value="lastonly" /> '.
1.592     bisitz    887:         &mt('last submission only').' </label></span>'."\n".
                    888:         '<span class="LC_nobreak">'.
                    889:         '<label><input type="radio" name="lastSub" value="last" /> '.
                    890:         &mt('last submission &amp; parts info').' </label></span>'."\n".
                    891:         '<span class="LC_nobreak">'.
1.628     www       892:         '<label><input type="radio" name="lastSub" value="datesub" checked="checked" /> '.
1.592     bisitz    893:         &mt('by dates and submissions').'</label></span>'."\n".
                    894:         '<span class="LC_nobreak">'.
                    895:         '<label><input type="radio" name="lastSub" value="all" /> '.
                    896:         &mt('all details').'</label></span>';
1.561     bisitz    897:     $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('Submissions'))
                    898:                   .$submission_options
                    899:                   .&Apache::lonhtmlcommon::row_closure();
                    900: 
                    901:     $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('Grading Increments'))
                    902:                   .'<select name="increment">'
                    903:                   .'<option value="1">'.&mt('Whole Points').'</option>'
                    904:                   .'<option value=".5">'.&mt('Half Points').'</option>'
                    905:                   .'<option value=".25">'.&mt('Quarter Points').'</option>'
                    906:                   .'<option value=".1">'.&mt('Tenths of a Point').'</option>'
                    907:                   .'</select>'
                    908:                   .&Apache::lonhtmlcommon::row_closure();
1.485     albertel  909: 
                    910:     $gradeTable .= 
1.432     banghart  911:         &build_section_inputs().
1.45      ng        912: 	'<input type="hidden" name="submitonly"  value="'.$submitonly.'" />'."\n".
1.418     albertel  913: 	'<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.110     ng        914: 	'<input type="hidden" name="saveStatusOld" value="'.$saveStatus.'" />'."\n";
                    915: 
1.618     www       916:     if (exists($env{'form.Status'})) {
1.561     bisitz    917: 	$gradeTable .= '<input type="hidden" name="Status" value="'.$stu_status.'" />'."\n";
1.124     ng        918:     } else {
1.561     bisitz    919:         $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('Student Status'))
                    920:                       .&Apache::lonhtmlcommon::StatusOptions(
                    921:                            $saveStatus,undef,1,'javascript:reLoadList(this.form);')
                    922:                       .&Apache::lonhtmlcommon::row_closure();
1.124     ng        923:     }
1.112     ng        924: 
1.561     bisitz    925:     $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('Check For Plagiarism'))
                    926:                   .'<input type="checkbox" name="checkPlag" checked="checked" />'
                    927:                   .&Apache::lonhtmlcommon::row_closure(1)
                    928:                   .&Apache::lonhtmlcommon::end_pick_box();
                    929: 
                    930:     $gradeTable .= '<p>'
1.618     www       931:                   .&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    932:                   .'<input type="hidden" name="command" value="processGroup" />'
                    933:                   .'</p>';
1.249     albertel  934: 
                    935: # checkall buttons
                    936:     $gradeTable.=&check_script('gradesub', 'stuinfo');
1.110     ng        937:     $gradeTable.='<input type="button" '."\n".
1.589     bisitz    938:         'onclick="javascript:checkSelect(this.form.stuinfo);" '."\n".
                    939:         'value="'.&mt('Next').' &rarr;" /> <br />'."\n";
1.249     albertel  940:     $gradeTable.=&check_buttons();
1.450     banghart  941:     my ($classlist, undef, $fullname) = &getclasslist($getsec,'1',$getgroup);
1.474     albertel  942:     $gradeTable.= &Apache::loncommon::start_data_table().
                    943: 	&Apache::loncommon::start_data_table_header_row();
1.110     ng        944:     my $loop = 0;
                    945:     while ($loop < 2) {
1.485     albertel  946: 	$gradeTable.='<th>'.&mt('No.').'</th><th>'.&mt('Select').'</th>'.
                    947: 	    '<th>'.&nameUserString('header').'&nbsp;'.&mt('Section/Group').'</th>';
1.618     www       948: 	if (($submitonly ne 'queued') && ($submitonly ne 'all')) {
1.485     albertel  949: 	    foreach my $part (sort(@$partlist)) {
                    950: 		my $display_part=
                    951: 		    &get_display_part((split(/_/,$part))[0],$symb);
                    952: 		$gradeTable.=
                    953: 		    '<th>'.&mt('Part: [_1] Status',$display_part).'</th>';
1.110     ng        954: 	    }
1.301     albertel  955: 	} elsif ($submitonly eq 'queued') {
1.474     albertel  956: 	    $gradeTable.='<th>'.&mt('Queue Status').'&nbsp;</th>';
1.110     ng        957: 	}
                    958: 	$loop++;
1.126     ng        959: #	$gradeTable.='<td></td>' if ($loop%2 ==1);
1.41      ng        960:     }
1.474     albertel  961:     $gradeTable.=&Apache::loncommon::end_data_table_header_row()."\n";
1.41      ng        962: 
1.45      ng        963:     my $ctr = 0;
1.294     albertel  964:     foreach my $student (sort 
                    965: 			 {
                    966: 			     if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                    967: 				 return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                    968: 			     }
                    969: 			     return $a cmp $b;
                    970: 			 }
                    971: 			 (keys(%$fullname))) {
1.41      ng        972: 	my ($uname,$udom) = split(/:/,$student);
1.301     albertel  973: 
1.110     ng        974: 	my %status = ();
1.301     albertel  975: 
                    976: 	if ($submitonly eq 'queued') {
                    977: 	    my %queue_status = 
                    978: 		&Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
                    979: 							$udom,$uname);
                    980: 	    next if (!defined($queue_status{'gradingqueue'}));
                    981: 	    $status{'gradingqueue'} = $queue_status{'gradingqueue'};
                    982: 	}
                    983: 
1.618     www       984: 	if (($submitonly ne 'queued') && ($submitonly ne 'all')) {
1.324     albertel  985: 	    (%status) =&student_gradeStatus($symb,$udom,$uname,$partlist);
1.145     albertel  986: 	    my $submitted = 0;
1.164     albertel  987: 	    my $graded = 0;
1.248     albertel  988: 	    my $incorrect = 0;
1.110     ng        989: 	    foreach (keys(%status)) {
1.145     albertel  990: 		$submitted = 1 if ($status{$_} ne 'nothing');
1.248     albertel  991: 		$graded = 1 if ($status{$_} =~ /^ungraded/);
                    992: 		$incorrect = 1 if ($status{$_} =~ /^incorrect/);
                    993: 		
1.110     ng        994: 		my ($foo,$partid,$foo1) = split(/\./,$_);
                    995: 		if ($status{'resource.'.$partid.'.submitted_by'} ne '') {
1.145     albertel  996: 		    $submitted = 0;
1.150     albertel  997: 		    my ($part)=split(/\./,$partid);
1.110     ng        998: 		    $gradeTable.='<input type="hidden" name="'.
1.150     albertel  999: 			$student.':'.$part.':submitted_by" value="'.
1.110     ng       1000: 			$status{'resource.'.$partid.'.submitted_by'}.'" />';
                   1001: 		}
1.41      ng       1002: 	    }
1.248     albertel 1003: 	    
1.156     albertel 1004: 	    next if (!$submitted && ($submitonly eq 'yes' ||
                   1005: 				     $submitonly eq 'incorrect' ||
                   1006: 				     $submitonly eq 'graded'));
1.248     albertel 1007: 	    next if (!$graded && ($submitonly eq 'graded'));
                   1008: 	    next if (!$incorrect && $submitonly eq 'incorrect');
1.41      ng       1009: 	}
1.34      ng       1010: 
1.45      ng       1011: 	$ctr++;
1.249     albertel 1012: 	my $section = $classlist->{$student}->[&Apache::loncoursedata::CL_SECTION()];
1.452     banghart 1013:         my $group = $classlist->{$student}->[&Apache::loncoursedata::CL_GROUP()];
1.104     albertel 1014: 	if ( $perm{'vgr'} eq 'F' ) {
1.474     albertel 1015: 	    if ($ctr%2 ==1) {
                   1016: 		$gradeTable.= &Apache::loncommon::start_data_table_row();
                   1017: 	    }
1.126     ng       1018: 	    $gradeTable.='<td align="right">'.$ctr.'&nbsp;</td>'.
1.563     bisitz   1019:                '<td align="center"><label><input type="checkbox" name="stuinfo" value="'.
1.249     albertel 1020:                $student.':'.$$fullname{$student}.':::SECTION'.$section.
                   1021: 	       ')&nbsp;" />&nbsp;&nbsp;</label></td>'."\n".'<td>'.
                   1022: 	       &nameUserString(undef,$$fullname{$student},$uname,$udom).
1.474     albertel 1023: 	       '&nbsp;'.$section.($group ne '' ?'/'.$group:'').'</td>'."\n";
1.110     ng       1024: 
1.618     www      1025: 	    if ($submitonly ne 'all') {
1.524     raeburn  1026: 		foreach (sort(keys(%status))) {
1.485     albertel 1027: 		    next if ($_ =~ /^resource.*?submitted_by$/);
                   1028: 		    $gradeTable.='<td align="center">&nbsp;'.&mt($status{$_}).'&nbsp;</td>'."\n";
1.110     ng       1029: 		}
1.41      ng       1030: 	    }
1.126     ng       1031: #	    $gradeTable.='<td></td>' if ($ctr%2 ==1);
1.474     albertel 1032: 	    if ($ctr%2 ==0) {
                   1033: 		$gradeTable.=&Apache::loncommon::end_data_table_row()."\n";
                   1034: 	    }
1.41      ng       1035: 	}
                   1036:     }
1.110     ng       1037:     if ($ctr%2 ==1) {
1.126     ng       1038: 	$gradeTable.='<td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td>';
1.618     www      1039: 	    if (($submitonly ne 'queued') && ($submitonly ne 'all')) {
1.110     ng       1040: 		foreach (@$partlist) {
                   1041: 		    $gradeTable.='<td>&nbsp;</td>';
                   1042: 		}
1.301     albertel 1043: 	    } elsif ($submitonly eq 'queued') {
                   1044: 		$gradeTable.='<td>&nbsp;</td>';
1.110     ng       1045: 	    }
1.474     albertel 1046: 	$gradeTable.=&Apache::loncommon::end_data_table_row();
1.110     ng       1047:     }
                   1048: 
1.474     albertel 1049:     $gradeTable.=&Apache::loncommon::end_data_table()."\n".
1.589     bisitz   1050:         '<input type="button" '.
                   1051:         'onclick="javascript:checkSelect(this.form.stuinfo);" '.
                   1052:         'value="'.&mt('Next').' &rarr;" /></form>'."\n";
1.45      ng       1053:     if ($ctr == 0) {
1.96      albertel 1054: 	my $num_students=(scalar(keys(%$fullname)));
                   1055: 	if ($num_students eq 0) {
1.485     albertel 1056: 	    $gradeTable='<br />&nbsp;<span class="LC_warning">'.&mt('There are no students currently enrolled.').'</span>';
1.96      albertel 1057: 	} else {
1.171     albertel 1058: 	    my $submissions='submissions';
                   1059: 	    if ($submitonly eq 'incorrect') { $submissions = 'incorrect submissions'; }
                   1060: 	    if ($submitonly eq 'graded'   ) { $submissions = 'ungraded submissions'; }
1.301     albertel 1061: 	    if ($submitonly eq 'queued'   ) { $submissions = 'queued submissions'; }
1.398     albertel 1062: 	    $gradeTable='<br />&nbsp;<span class="LC_warning">'.
1.485     albertel 1063: 		&mt('No '.$submissions.' found for this resource for any students. ([_1] students checked for '.$submissions.')',
                   1064: 		    $num_students).
                   1065: 		'</span><br />';
1.96      albertel 1066: 	}
1.46      ng       1067:     } elsif ($ctr == 1) {
1.474     albertel 1068: 	$gradeTable =~ s/type="checkbox"/type="checkbox" checked="checked"/;
1.45      ng       1069:     }
                   1070:     $request->print($gradeTable);
1.44      ng       1071:     return '';
1.10      ng       1072: }
                   1073: 
1.44      ng       1074: #---- Called from the listStudents routine
1.249     albertel 1075: 
                   1076: sub check_script {
                   1077:     my ($form, $type)=@_;
1.597     wenzelju 1078:     my $chkallscript= &Apache::lonhtmlcommon::scripttag('
1.249     albertel 1079:     function checkall() {
                   1080:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
                   1081:             ele = document.forms.'.$form.'.elements[i];
                   1082:             if (ele.name == "'.$type.'") {
                   1083:             document.forms.'.$form.'.elements[i].checked=true;
                   1084:                                        }
                   1085:         }
                   1086:     }
                   1087: 
                   1088:     function checksec() {
                   1089:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
                   1090:             ele = document.forms.'.$form.'.elements[i];
                   1091:            string = document.forms.'.$form.'.chksec.value;
                   1092:            if
                   1093:           (ele.value.indexOf(":::SECTION"+string)>0) {
                   1094:               document.forms.'.$form.'.elements[i].checked=true;
                   1095:             }
                   1096:         }
                   1097:     }
                   1098: 
                   1099: 
                   1100:     function uncheckall() {
                   1101:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
                   1102:             ele = document.forms.'.$form.'.elements[i];
                   1103:             if (ele.name == "'.$type.'") {
                   1104:             document.forms.'.$form.'.elements[i].checked=false;
                   1105:                                        }
                   1106:         }
                   1107:     }
                   1108: 
1.597     wenzelju 1109: '."\n");
1.249     albertel 1110:     return $chkallscript;
                   1111: }
                   1112: 
                   1113: sub check_buttons {
1.485     albertel 1114:     my $buttons.='<input type="button" onclick="checkall()" value="'.&mt('Check All').'" />';
                   1115:     $buttons.='<input type="button" onclick="uncheckall()" value="'.&mt('Uncheck All').'" />&nbsp;';
                   1116:     $buttons.='<input type="button" onclick="checksec()" value="'.&mt('Check Section/Group').'" />';
1.249     albertel 1117:     $buttons.='<input type="text" size="5" name="chksec" />&nbsp;';
                   1118:     return $buttons;
                   1119: }
                   1120: 
1.44      ng       1121: #     Displays the submissions for one student or a group of students
1.34      ng       1122: sub processGroup {
1.619     www      1123:     my ($request,$symb)  = @_;
1.41      ng       1124:     my $ctr        = 0;
1.155     albertel 1125:     my @stuchecked = &Apache::loncommon::get_env_multiple('form.stuinfo');
1.41      ng       1126:     my $total      = scalar(@stuchecked)-1;
1.45      ng       1127: 
1.396     banghart 1128:     foreach my $student (@stuchecked) {
                   1129: 	my ($uname,$udom,$fullname) = split(/:/,$student);
1.257     albertel 1130: 	$env{'form.student'}        = $uname;
                   1131: 	$env{'form.userdom'}        = $udom;
                   1132: 	$env{'form.fullname'}       = $fullname;
1.619     www      1133: 	&submission($request,$ctr,$total,$symb);
1.41      ng       1134: 	$ctr++;
                   1135:     }
                   1136:     return '';
1.35      ng       1137: }
1.34      ng       1138: 
1.44      ng       1139: #------------------------------------------------------------------------------------
                   1140: #
                   1141: #-------------------------- Next few routines handles grading by student, essentially
                   1142: #                           handles essay response type problem/part
                   1143: #
                   1144: #--- Javascript to handle the submission page functionality ---
                   1145: sub sub_page_js {
                   1146:     my $request = shift;
1.539     riegler  1147: 	    my $alertmsg = &mt('A number equal or greater than 0 is expected. Entered value = ');
1.597     wenzelju 1148:     $request->print(&Apache::lonhtmlcommon::scripttag(<<SUBJAVASCRIPT));
1.71      ng       1149:     function updateRadio(formname,id,weight) {
1.125     ng       1150: 	var gradeBox = formname["GD_BOX"+id];
                   1151: 	var radioButton = formname["RADVAL"+id];
                   1152: 	var oldpts = formname["oldpts"+id].value;
1.72      ng       1153: 	var pts = checkSolved(formname,id) == 'update' ? gradeBox.value : oldpts;
1.71      ng       1154: 	gradeBox.value = pts;
                   1155: 	var resetbox = false;
                   1156: 	if (isNaN(pts) || pts < 0) {
1.539     riegler  1157: 	    alert("$alertmsg"+pts);
1.71      ng       1158: 	    for (var i=0; i<radioButton.length; i++) {
                   1159: 		if (radioButton[i].checked) {
                   1160: 		    gradeBox.value = i;
                   1161: 		    resetbox = true;
                   1162: 		}
                   1163: 	    }
                   1164: 	    if (!resetbox) {
                   1165: 		formtextbox.value = "";
                   1166: 	    }
                   1167: 	    return;
1.44      ng       1168: 	}
1.71      ng       1169: 
                   1170: 	if (pts > weight) {
                   1171: 	    var resp = confirm("You entered a value ("+pts+
                   1172: 			       ") greater than the weight for the part. Accept?");
                   1173: 	    if (resp == false) {
1.125     ng       1174: 		gradeBox.value = oldpts;
1.71      ng       1175: 		return;
                   1176: 	    }
1.44      ng       1177: 	}
1.13      albertel 1178: 
1.71      ng       1179: 	for (var i=0; i<radioButton.length; i++) {
                   1180: 	    radioButton[i].checked=false;
                   1181: 	    if (pts == i && pts != "") {
                   1182: 		radioButton[i].checked=true;
                   1183: 	    }
                   1184: 	}
                   1185: 	updateSelect(formname,id);
1.125     ng       1186: 	formname["stores"+id].value = "0";
1.41      ng       1187:     }
1.5       albertel 1188: 
1.72      ng       1189:     function writeBox(formname,id,pts) {
1.125     ng       1190: 	var gradeBox = formname["GD_BOX"+id];
1.71      ng       1191: 	if (checkSolved(formname,id) == 'update') {
                   1192: 	    gradeBox.value = pts;
                   1193: 	} else {
1.125     ng       1194: 	    var oldpts = formname["oldpts"+id].value;
1.72      ng       1195: 	    gradeBox.value = oldpts;
1.125     ng       1196: 	    var radioButton = formname["RADVAL"+id];
1.71      ng       1197: 	    for (var i=0; i<radioButton.length; i++) {
                   1198: 		radioButton[i].checked=false;
1.72      ng       1199: 		if (i == oldpts) {
1.71      ng       1200: 		    radioButton[i].checked=true;
                   1201: 		}
                   1202: 	    }
1.41      ng       1203: 	}
1.125     ng       1204: 	formname["stores"+id].value = "0";
1.71      ng       1205: 	updateSelect(formname,id);
                   1206: 	return;
1.41      ng       1207:     }
1.44      ng       1208: 
1.71      ng       1209:     function clearRadBox(formname,id) {
                   1210: 	if (checkSolved(formname,id) == 'noupdate') {
                   1211: 	    updateSelect(formname,id);
                   1212: 	    return;
                   1213: 	}
1.125     ng       1214: 	gradeSelect = formname["GD_SEL"+id];
1.71      ng       1215: 	for (var i=0; i<gradeSelect.length; i++) {
                   1216: 	    if (gradeSelect[i].selected) {
                   1217: 		var selectx=i;
                   1218: 	    }
                   1219: 	}
1.125     ng       1220: 	var stores = formname["stores"+id];
1.71      ng       1221: 	if (selectx == stores.value) { return };
1.125     ng       1222: 	var gradeBox = formname["GD_BOX"+id];
1.71      ng       1223: 	gradeBox.value = "";
1.125     ng       1224: 	var radioButton = formname["RADVAL"+id];
1.71      ng       1225: 	for (var i=0; i<radioButton.length; i++) {
                   1226: 	    radioButton[i].checked=false;
                   1227: 	}
                   1228: 	stores.value = selectx;
                   1229:     }
1.5       albertel 1230: 
1.71      ng       1231:     function checkSolved(formname,id) {
1.125     ng       1232: 	if (formname["solved"+id].value == "correct_by_student" && formname.overRideScore.value == 'no') {
1.118     ng       1233: 	    var reply = confirm("This problem has been graded correct by the computer. Do you want to change the score?");
                   1234: 	    if (!reply) {return "noupdate";}
1.120     ng       1235: 	    formname.overRideScore.value = 'yes';
1.41      ng       1236: 	}
1.71      ng       1237: 	return "update";
1.13      albertel 1238:     }
1.71      ng       1239: 
                   1240:     function updateSelect(formname,id) {
1.125     ng       1241: 	formname["GD_SEL"+id][0].selected = true;
1.71      ng       1242: 	return;
1.41      ng       1243:     }
1.33      ng       1244: 
1.121     ng       1245: //=========== Check that a point is assigned for all the parts  ============
1.71      ng       1246:     function checksubmit(formname,val,total,parttot) {
1.121     ng       1247: 	formname.gradeOpt.value = val;
1.71      ng       1248: 	if (val == "Save & Next") {
                   1249: 	    for (i=0;i<=total;i++) {
                   1250: 		for (j=0;j<parttot;j++) {
1.125     ng       1251: 		    var partid = formname["partid"+i+"_"+j].value;
1.127     ng       1252: 		    if (formname["GD_SEL"+i+"_"+partid][0].selected) {
1.125     ng       1253: 			var points = formname["GD_BOX"+i+"_"+partid].value;
1.71      ng       1254: 			if (points == "") {
1.125     ng       1255: 			    var name = formname["name"+i].value;
1.129     ng       1256: 			    var studentID = (name != '' ? name : formname["unamedom"+i].value);
                   1257: 			    var resp = confirm("You did not assign a score for "+studentID+
                   1258: 					       ", part "+partid+". Continue?");
1.71      ng       1259: 			    if (resp == false) {
1.125     ng       1260: 				formname["GD_BOX"+i+"_"+partid].focus();
1.71      ng       1261: 				return false;
                   1262: 			    }
                   1263: 			}
                   1264: 		    }
                   1265: 		    
                   1266: 		}
                   1267: 	    }
                   1268: 	    
                   1269: 	}
1.120     ng       1270: 	formname.submit();
                   1271:     }
                   1272: 
1.71      ng       1273: //======= Check that a score is assigned for all the problems (page/sequence grading only) =========
                   1274:     function checkSubmitPage(formname,total) {
                   1275: 	noscore = new Array(100);
                   1276: 	var ptr = 0;
                   1277: 	for (i=1;i<total;i++) {
1.125     ng       1278: 	    var partid = formname["q_"+i].value;
1.127     ng       1279: 	    if (formname["GD_SEL"+i+"_"+partid][0].selected) {
1.125     ng       1280: 		var points = formname["GD_BOX"+i+"_"+partid].value;
                   1281: 		var status = formname["solved"+i+"_"+partid].value;
1.71      ng       1282: 		if (points == "" && status != "correct_by_student") {
                   1283: 		    noscore[ptr] = i;
                   1284: 		    ptr++;
                   1285: 		}
                   1286: 	    }
                   1287: 	}
                   1288: 	if (ptr != 0) {
                   1289: 	    var sense = ptr == 1 ? ": " : "s: ";
                   1290: 	    var prolist = "";
                   1291: 	    if (ptr == 1) {
                   1292: 		prolist = noscore[0];
                   1293: 	    } else {
                   1294: 		var i = 0;
                   1295: 		while (i < ptr-1) {
                   1296: 		    prolist += noscore[i]+", ";
                   1297: 		    i++;
                   1298: 		}
                   1299: 		prolist += "and "+noscore[i];
                   1300: 	    }
                   1301: 	    var resp = confirm("You did not assign any score for the following problem"+sense+prolist+". Continue?");
                   1302: 	    if (resp == false) {
                   1303: 		return false;
                   1304: 	    }
                   1305: 	}
1.45      ng       1306: 
1.71      ng       1307: 	formname.submit();
                   1308:     }
                   1309: SUBJAVASCRIPT
                   1310: }
1.45      ng       1311: 
1.71      ng       1312: #--- javascript for essay type problem --
                   1313: sub sub_page_kw_js {
                   1314:     my $request = shift;
1.80      ng       1315:     my $iconpath = $request->dir_config('lonIconsURL');
1.118     ng       1316:     &commonJSfunctions($request);
1.350     albertel 1317: 
1.629     www      1318:     my $inner_js_msg_central= (<<INNERJS);
                   1319: <script type="text/javascript">
1.350     albertel 1320:     function checkInput() {
                   1321:       opener.document.SCORE.msgsub.value = opener.checkEntities(document.msgcenter.msgsub.value);
                   1322:       var nmsg   = opener.document.SCORE.savemsgN.value;
                   1323:       var usrctr = document.msgcenter.usrctr.value;
                   1324:       var newval = opener.document.SCORE["newmsg"+usrctr];
                   1325:       newval.value = opener.checkEntities(document.msgcenter.newmsg.value);
                   1326: 
                   1327:       var msgchk = "";
                   1328:       if (document.msgcenter.subchk.checked) {
                   1329:          msgchk = "msgsub,";
                   1330:       }
                   1331:       var includemsg = 0;
                   1332:       for (var i=1; i<=nmsg; i++) {
                   1333:           var opnmsg = opener.document.SCORE["savemsg"+i];
                   1334:           var frmmsg = document.msgcenter["msg"+i];
                   1335:           opnmsg.value = opener.checkEntities(frmmsg.value);
                   1336:           var showflg = opener.document.SCORE["shownOnce"+i];
                   1337:           showflg.value = "1";
                   1338:           var chkbox = document.msgcenter["msgn"+i];
                   1339:           if (chkbox.checked) {
                   1340:              msgchk += "savemsg"+i+",";
                   1341:              includemsg = 1;
                   1342:           }
                   1343:       }
                   1344:       if (document.msgcenter.newmsgchk.checked) {
                   1345:          msgchk += "newmsg"+usrctr;
                   1346:          includemsg = 1;
                   1347:       }
                   1348:       imgformname = opener.document.SCORE["mailicon"+usrctr];
                   1349:       imgformname.src = "$iconpath/"+((includemsg) ? "mailto.gif" : "mailbkgrd.gif");
                   1350:       var includemsg = opener.document.SCORE["includemsg"+usrctr];
                   1351:       includemsg.value = msgchk;
                   1352: 
                   1353:       self.close()
                   1354: 
                   1355:     }
1.629     www      1356: </script>
1.350     albertel 1357: INNERJS
                   1358: 
1.629     www      1359:     my $inner_js_highlight_central= (<<INNERJS);
                   1360: <script type="text/javascript">
1.351     albertel 1361:     function updateChoice(flag) {
                   1362:       opener.document.SCORE.kwclr.value = opener.radioSelection(document.hlCenter.kwdclr);
                   1363:       opener.document.SCORE.kwsize.value = opener.radioSelection(document.hlCenter.kwdsize);
                   1364:       opener.document.SCORE.kwstyle.value = opener.radioSelection(document.hlCenter.kwdstyle);
                   1365:       opener.document.SCORE.refresh.value = "on";
                   1366:       if (opener.document.SCORE.keywords.value!=""){
                   1367:          opener.document.SCORE.submit();
                   1368:       }
                   1369:       self.close()
                   1370:     }
1.629     www      1371: </script>
1.351     albertel 1372: INNERJS
                   1373: 
                   1374:     my $start_page_msg_central = 
                   1375:         &Apache::loncommon::start_page('Message Central',$inner_js_msg_central,
                   1376: 				       {'js_ready'  => 1,
                   1377: 					'only_body' => 1,
                   1378: 					'bgcolor'   =>'#FFFFFF',});
                   1379:     my $end_page_msg_central = 
                   1380: 	&Apache::loncommon::end_page({'js_ready' => 1});
                   1381: 
                   1382: 
                   1383:     my $start_page_highlight_central = 
                   1384:         &Apache::loncommon::start_page('Highlight Central',
                   1385: 				       $inner_js_highlight_central,
1.350     albertel 1386: 				       {'js_ready'  => 1,
                   1387: 					'only_body' => 1,
                   1388: 					'bgcolor'   =>'#FFFFFF',});
1.351     albertel 1389:     my $end_page_highlight_central = 
1.350     albertel 1390: 	&Apache::loncommon::end_page({'js_ready' => 1});
                   1391: 
1.219     www      1392:     my $docopen=&Apache::lonhtmlcommon::javascript_docopen();
1.236     albertel 1393:     $docopen=~s/^document\.//;
1.539     riegler  1394:     my $alertmsg = &mt('Please select a word or group of words from document and then click this link.');
1.597     wenzelju 1395:     $request->print(&Apache::lonhtmlcommon::scripttag(<<SUBJAVASCRIPT));
1.45      ng       1396: 
1.44      ng       1397: //===================== Show list of keywords ====================
1.122     ng       1398:   function keywords(formname) {
                   1399:     var nret = prompt("Keywords list, separated by a space. Add/delete to list if desired.",formname.keywords.value);
1.44      ng       1400:     if (nret==null) return;
1.122     ng       1401:     formname.keywords.value = nret;
1.44      ng       1402: 
1.122     ng       1403:     if (formname.keywords.value != "") {
1.128     ng       1404: 	formname.refresh.value = "on";
1.122     ng       1405: 	formname.submit();
1.44      ng       1406:     }
                   1407:     return;
                   1408:   }
                   1409: 
                   1410: //===================== Script to view submitted by ==================
                   1411:   function viewSubmitter(submitter) {
                   1412:     document.SCORE.refresh.value = "on";
                   1413:     document.SCORE.NCT.value = "1";
                   1414:     document.SCORE.unamedom0.value = submitter;
                   1415:     document.SCORE.submit();
                   1416:     return;
                   1417:   }
                   1418: 
                   1419: //===================== Script to add keyword(s) ==================
                   1420:   function getSel() {
                   1421:     if (document.getSelection) txt = document.getSelection();
                   1422:     else if (document.selection) txt = document.selection.createRange().text;
                   1423:     else return;
                   1424:     var cleantxt = txt.replace(new RegExp('([\\f\\n\\r\\t\\v ])+', 'g')," ");
                   1425:     if (cleantxt=="") {
1.539     riegler  1426: 	alert("$alertmsg");
1.44      ng       1427: 	return;
                   1428:     }
                   1429:     var nret = prompt("Add selection to keyword list? Edit if desired.",cleantxt);
                   1430:     if (nret==null) return;
1.127     ng       1431:     document.SCORE.keywords.value = document.SCORE.keywords.value+" "+nret;
1.44      ng       1432:     if (document.SCORE.keywords.value != "") {
1.127     ng       1433: 	document.SCORE.refresh.value = "on";
1.44      ng       1434: 	document.SCORE.submit();
                   1435:     }
                   1436:     return;
                   1437:   }
                   1438: 
                   1439: //====================== Script for composing message ==============
1.80      ng       1440:    // preload images
                   1441:    img1 = new Image();
                   1442:    img1.src = "$iconpath/mailbkgrd.gif";
                   1443:    img2 = new Image();
                   1444:    img2.src = "$iconpath/mailto.gif";
                   1445: 
1.44      ng       1446:   function msgCenter(msgform,usrctr,fullname) {
                   1447:     var Nmsg  = msgform.savemsgN.value;
                   1448:     savedMsgHeader(Nmsg,usrctr,fullname);
                   1449:     var subject = msgform.msgsub.value;
1.127     ng       1450:     var msgchk = document.SCORE["includemsg"+usrctr].value;
1.44      ng       1451:     re = /msgsub/;
                   1452:     var shwsel = "";
                   1453:     if (re.test(msgchk)) { shwsel = "checked" }
1.123     ng       1454:     subject = (document.SCORE.shownSub.value == 0 ? checkEntities(subject) : subject);
                   1455:     displaySubject(checkEntities(subject),shwsel);
1.44      ng       1456:     for (var i=1; i<=Nmsg; i++) {
1.123     ng       1457: 	var testmsg = "savemsg"+i+",";
                   1458: 	re = new RegExp(testmsg,"g");
1.44      ng       1459: 	shwsel = "";
                   1460: 	if (re.test(msgchk)) { shwsel = "checked" }
1.125     ng       1461: 	var message = document.SCORE["savemsg"+i].value;
1.126     ng       1462: 	message = (document.SCORE["shownOnce"+i].value == 0 ? checkEntities(message) : message);
1.123     ng       1463: 	displaySavedMsg(i,message,shwsel); //I do not get it. w/o checkEntities on saved messages,
                   1464: 	                                   //any &lt; is already converted to <, etc. However, only once!!
1.44      ng       1465:     }
1.125     ng       1466:     newmsg = document.SCORE["newmsg"+usrctr].value;
1.44      ng       1467:     shwsel = "";
                   1468:     re = /newmsg/;
                   1469:     if (re.test(msgchk)) { shwsel = "checked" }
                   1470:     newMsg(newmsg,shwsel);
                   1471:     msgTail(); 
                   1472:     return;
                   1473:   }
                   1474: 
1.123     ng       1475:   function checkEntities(strx) {
                   1476:     if (strx.length == 0) return strx;
                   1477:     var orgStr = ["&", "<", ">", '"']; 
                   1478:     var newStr = ["&amp;", "&lt;", "&gt;", "&quot;"];
                   1479:     var counter = 0;
                   1480:     while (counter < 4) {
                   1481: 	strx = strReplace(strx,orgStr[counter],newStr[counter]);
                   1482: 	counter++;
                   1483:     }
                   1484:     return strx;
                   1485:   }
                   1486: 
                   1487:   function strReplace(strx, orgStr, newStr) {
                   1488:     return strx.split(orgStr).join(newStr);
                   1489:   }
                   1490: 
1.44      ng       1491:   function savedMsgHeader(Nmsg,usrctr,fullname) {
1.76      ng       1492:     var height = 70*Nmsg+250;
1.44      ng       1493:     var scrollbar = "no";
                   1494:     if (height > 600) {
                   1495: 	height = 600;
                   1496: 	scrollbar = "yes";
                   1497:     }
1.118     ng       1498:     var xpos = (screen.width-600)/2;
                   1499:     xpos = (xpos < 0) ? '0' : xpos;
                   1500:     var ypos = (screen.height-height)/2-30;
                   1501:     ypos = (ypos < 0) ? '0' : ypos;
                   1502: 
1.206     albertel 1503:     pWin = window.open('', 'MessageCenter', 'resizable=yes,toolbar=no,location=no,scrollbars='+scrollbar+',screenx='+xpos+',screeny='+ypos+',width=600,height='+height);
1.76      ng       1504:     pWin.focus();
                   1505:     pDoc = pWin.document;
1.219     www      1506:     pDoc.$docopen;
1.351     albertel 1507:     pDoc.write('$start_page_msg_central');
1.76      ng       1508: 
                   1509:     pDoc.write("<form action=\\"inactive\\" name=\\"msgcenter\\">");
                   1510:     pDoc.write("<input value=\\""+usrctr+"\\" name=\\"usrctr\\" type=\\"hidden\\">");
1.465     albertel 1511:     pDoc.write("<h3><span class=\\"LC_info\\">&nbsp;Compose Message for \"+fullname+\"<\\/span><\\/h3><br /><br />");
1.76      ng       1512: 
1.564     bisitz   1513:     pDoc.write('<table border="0" width="100%"><tr><td bgcolor="#777777">');
                   1514:     pDoc.write('<table border="0" width="100%"><tr bgcolor="#DDFFFF">');
1.465     albertel 1515:     pDoc.write("<td><b>Type<\\/b><\\/td><td><b>Include<\\/b><\\/td><td><b>Message<\\/td><\\/tr>");
1.44      ng       1516: }
                   1517:     function displaySubject(msg,shwsel) {
1.76      ng       1518:     pDoc = pWin.document;
                   1519:     pDoc.write("<tr bgcolor=\\"#ffffdd\\">");
1.465     albertel 1520:     pDoc.write("<td>Subject<\\/td>");
                   1521:     pDoc.write("<td align=\\"center\\"><input name=\\"subchk\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
                   1522:     pDoc.write("<td><input name=\\"msgsub\\" type=\\"text\\" value=\\""+msg+"\\"size=\\"60\\" maxlength=\\"80\\"><\\/td><\\/tr>");
1.44      ng       1523: }
                   1524: 
1.72      ng       1525:   function displaySavedMsg(ctr,msg,shwsel) {
1.76      ng       1526:     pDoc = pWin.document;
                   1527:     pDoc.write("<tr bgcolor=\\"#ffffdd\\">");
1.465     albertel 1528:     pDoc.write("<td align=\\"center\\">"+ctr+"<\\/td>");
                   1529:     pDoc.write("<td align=\\"center\\"><input name=\\"msgn"+ctr+"\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
                   1530:     pDoc.write("<td><textarea name=\\"msg"+ctr+"\\" cols=\\"60\\" rows=\\"3\\">"+msg+"<\\/textarea><\\/td><\\/tr>");
1.44      ng       1531: }
                   1532: 
                   1533:   function newMsg(newmsg,shwsel) {
1.76      ng       1534:     pDoc = pWin.document;
                   1535:     pDoc.write("<tr bgcolor=\\"#ffffdd\\">");
1.465     albertel 1536:     pDoc.write("<td align=\\"center\\">New<\\/td>");
                   1537:     pDoc.write("<td align=\\"center\\"><input name=\\"newmsgchk\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
                   1538:     pDoc.write("<td><textarea name=\\"newmsg\\" cols=\\"60\\" rows=\\"3\\" onchange=\\"javascript:this.form.newmsgchk.checked=true\\" >"+newmsg+"<\\/textarea><\\/td><\\/tr>");
1.44      ng       1539: }
                   1540: 
                   1541:   function msgTail() {
1.76      ng       1542:     pDoc = pWin.document;
1.465     albertel 1543:     pDoc.write("<\\/table>");
                   1544:     pDoc.write("<\\/td><\\/tr><\\/table>&nbsp;");
1.589     bisitz   1545:     pDoc.write("<input type=\\"button\\" value=\\"Save\\" onclick=\\"javascript:checkInput()\\">&nbsp;&nbsp;");
                   1546:     pDoc.write("<input type=\\"button\\" value=\\"Cancel\\" onclick=\\"self.close()\\"><br /><br />");
1.465     albertel 1547:     pDoc.write("<\\/form>");
1.351     albertel 1548:     pDoc.write('$end_page_msg_central');
1.128     ng       1549:     pDoc.close();
1.44      ng       1550: }
                   1551: 
                   1552: //====================== Script for keyword highlight options ==============
                   1553:   function kwhighlight() {
                   1554:     var kwclr    = document.SCORE.kwclr.value;
                   1555:     var kwsize   = document.SCORE.kwsize.value;
                   1556:     var kwstyle  = document.SCORE.kwstyle.value;
                   1557:     var redsel = "";
                   1558:     var grnsel = "";
                   1559:     var blusel = "";
                   1560:     if (kwclr=="red")   {var redsel="checked"};
                   1561:     if (kwclr=="green") {var grnsel="checked"};
                   1562:     if (kwclr=="blue")  {var blusel="checked"};
                   1563:     var sznsel = "";
                   1564:     var sz1sel = "";
                   1565:     var sz2sel = "";
                   1566:     if (kwsize=="0")  {var sznsel="checked"};
                   1567:     if (kwsize=="+1") {var sz1sel="checked"};
                   1568:     if (kwsize=="+2") {var sz2sel="checked"};
                   1569:     var synsel = "";
                   1570:     var syisel = "";
                   1571:     var sybsel = "";
                   1572:     if (kwstyle=="")    {var synsel="checked"};
                   1573:     if (kwstyle=="<i>") {var syisel="checked"};
                   1574:     if (kwstyle=="<b>") {var sybsel="checked"};
                   1575:     highlightCentral();
                   1576:     highlightbody('red','red',redsel,'0','normal',sznsel,'','normal',synsel);
                   1577:     highlightbody('green','green',grnsel,'+1','+1',sz1sel,'<i>','italic',syisel);
                   1578:     highlightbody('blue','blue',blusel,'+2','+2',sz2sel,'<b>','bold',sybsel);
                   1579:     highlightend();
                   1580:     return;
                   1581:   }
                   1582: 
                   1583:   function highlightCentral() {
1.76      ng       1584: //    if (window.hwdWin) window.hwdWin.close();
1.118     ng       1585:     var xpos = (screen.width-400)/2;
                   1586:     xpos = (xpos < 0) ? '0' : xpos;
                   1587:     var ypos = (screen.height-330)/2-30;
                   1588:     ypos = (ypos < 0) ? '0' : ypos;
                   1589: 
1.206     albertel 1590:     hwdWin = window.open('', 'KeywordHighlightCentral', 'resizeable=yes,toolbar=no,location=no,scrollbars=no,width=400,height=300,screenx='+xpos+',screeny='+ypos);
1.76      ng       1591:     hwdWin.focus();
                   1592:     var hDoc = hwdWin.document;
1.219     www      1593:     hDoc.$docopen;
1.351     albertel 1594:     hDoc.write('$start_page_highlight_central');
1.76      ng       1595:     hDoc.write("<form action=\\"inactive\\" name=\\"hlCenter\\">");
1.465     albertel 1596:     hDoc.write("<h3><span class=\\"LC_info\\">&nbsp;Keyword Highlight Options<\\/span><\\/h3><br /><br />");
1.76      ng       1597: 
1.564     bisitz   1598:     hDoc.write('<table border="0" width="100%"><tr><td bgcolor="#777777">');
                   1599:     hDoc.write('<table border="0" width="100%"><tr bgcolor="#DDFFFF">');
1.465     albertel 1600:     hDoc.write("<td><b>Text Color<\\/b><\\/td><td><b>Font Size<\\/b><\\/td><td><b>Font Style<\\/td><\\/tr>");
1.44      ng       1601:   }
                   1602: 
                   1603:   function highlightbody(clrval,clrtxt,clrsel,szval,sztxt,szsel,syval,sytxt,sysel) { 
1.76      ng       1604:     var hDoc = hwdWin.document;
                   1605:     hDoc.write("<tr bgcolor=\\"#ffffdd\\">");
                   1606:     hDoc.write("<td align=\\"left\\">");
1.465     albertel 1607:     hDoc.write("<input name=\\"kwdclr\\" type=\\"radio\\" value=\\""+clrval+"\\" "+clrsel+">&nbsp;"+clrtxt+"<\\/td>");
1.76      ng       1608:     hDoc.write("<td align=\\"left\\">");
1.465     albertel 1609:     hDoc.write("<input name=\\"kwdsize\\" type=\\"radio\\" value=\\""+szval+"\\" "+szsel+">&nbsp;"+sztxt+"<\\/td>");
1.76      ng       1610:     hDoc.write("<td align=\\"left\\">");
1.465     albertel 1611:     hDoc.write("<input name=\\"kwdstyle\\" type=\\"radio\\" value=\\""+syval+"\\" "+sysel+">&nbsp;"+sytxt+"<\\/td>");
                   1612:     hDoc.write("<\\/tr>");
1.44      ng       1613:   }
                   1614: 
                   1615:   function highlightend() { 
1.76      ng       1616:     var hDoc = hwdWin.document;
1.465     albertel 1617:     hDoc.write("<\\/table>");
                   1618:     hDoc.write("<\\/td><\\/tr><\\/table>&nbsp;");
1.589     bisitz   1619:     hDoc.write("<input type=\\"button\\" value=\\"Save\\" onclick=\\"javascript:updateChoice(1)\\">&nbsp;&nbsp;");
                   1620:     hDoc.write("<input type=\\"button\\" value=\\"Cancel\\" onclick=\\"self.close()\\"><br /><br />");
1.465     albertel 1621:     hDoc.write("<\\/form>");
1.351     albertel 1622:     hDoc.write('$end_page_highlight_central');
1.128     ng       1623:     hDoc.close();
1.44      ng       1624:   }
                   1625: 
                   1626: SUBJAVASCRIPT
                   1627: }
                   1628: 
1.349     albertel 1629: sub get_increment {
1.348     bowersj2 1630:     my $increment = $env{'form.increment'};
                   1631:     if ($increment != 1 && $increment != .5 && $increment != .25 &&
                   1632:         $increment != .1) {
                   1633:         $increment = 1;
                   1634:     }
                   1635:     return $increment;
                   1636: }
                   1637: 
1.585     bisitz   1638: sub gradeBox_start {
                   1639:     return (
                   1640:         &Apache::loncommon::start_data_table()
                   1641:        .&Apache::loncommon::start_data_table_header_row()
                   1642:        .'<th>'.&mt('Part').'</th>'
                   1643:        .'<th>'.&mt('Points').'</th>'
                   1644:        .'<th>&nbsp;</th>'
                   1645:        .'<th>'.&mt('Assign Grade').'</th>'
                   1646:        .'<th>'.&mt('Weight').'</th>'
                   1647:        .'<th>'.&mt('Grade Status').'</th>'
                   1648:        .&Apache::loncommon::end_data_table_header_row()
                   1649:     );
                   1650: }
                   1651: 
                   1652: sub gradeBox_end {
                   1653:     return (
                   1654:         &Apache::loncommon::end_data_table()
                   1655:     );
                   1656: }
1.71      ng       1657: #--- displays the grading box, used in essay type problem and grading by page/sequence
                   1658: sub gradeBox {
1.322     albertel 1659:     my ($request,$symb,$uname,$udom,$counter,$partid,$record) = @_;
1.381     albertel 1660:     my $checkIcon = '<img alt="'.&mt('Check Mark').
1.485     albertel 1661: 	'" src="'.&Apache::loncommon::lonhttpdurl($request->dir_config('lonIconsURL').'/check.gif').'" height="16" border="0" />';
1.71      ng       1662:     my $wgt    = &Apache::lonnet::EXT('resource.'.$partid.'.weight',$symb,$udom,$uname);
1.466     albertel 1663:     my $wgtmsg = ($wgt > 0) ? &mt('(problem weight)') 
                   1664:                            : '<span class="LC_info">'.&mt('problem weight assigned by computer').'</span>';
1.71      ng       1665:     $wgt       = ($wgt > 0 ? $wgt : '1');
                   1666:     my $score  = ($$record{'resource.'.$partid.'.awarded'} eq '' ?
1.320     albertel 1667: 		  '' : &compute_points($$record{'resource.'.$partid.'.awarded'},$wgt));
1.71      ng       1668:     my $result='<input type="hidden" name="WGT'.$counter.'_'.$partid.'" value="'.$wgt.'" />'."\n";
1.466     albertel 1669:     my $display_part= &get_display_part($partid,$symb);
1.270     albertel 1670:     my %last_resets = &get_last_resets($symb,$env{'request.course.id'},
                   1671: 				       [$partid]);
                   1672:     my $aggtries = $$record{'resource.'.$partid.'.tries'};
1.269     raeburn  1673:     if ($last_resets{$partid}) {
                   1674:         $aggtries = &get_num_tries($record,$last_resets{$partid},$partid);
                   1675:     }
1.585     bisitz   1676:     $result.=&Apache::loncommon::start_data_table_row();
1.71      ng       1677:     my $ctr = 0;
1.348     bowersj2 1678:     my $thisweight = 0;
1.349     albertel 1679:     my $increment = &get_increment();
1.485     albertel 1680: 
                   1681:     my $radio.='<table border="0"><tr>'."\n";  # display radio buttons in a nice table 10 across
1.348     bowersj2 1682:     while ($thisweight<=$wgt) {
1.532     bisitz   1683: 	$radio.= '<td><span class="LC_nobreak"><label><input type="radio" name="RADVAL'.$counter.'_'.$partid.'" '.
1.589     bisitz   1684:         'onclick="javascript:writeBox(this.form,\''.$counter.'_'.$partid.'\','.
1.348     bowersj2 1685: 	    $thisweight.')" value="'.$thisweight.'" '.
1.401     albertel 1686: 	    ($score eq $thisweight ? 'checked="checked"':'').' /> '.$thisweight."</label></span></td>\n";
1.485     albertel 1687: 	$radio.=(($ctr+1)%10 == 0 ? '</tr><tr>' : '');
1.348     bowersj2 1688:         $thisweight += $increment;
1.71      ng       1689: 	$ctr++;
                   1690:     }
1.485     albertel 1691:     $radio.='</tr></table>';
                   1692: 
                   1693:     my $line.='<input type="text" name="GD_BOX'.$counter.'_'.$partid.'"'.
1.71      ng       1694: 	($score ne ''? ' value = "'.$score.'"':'').' size="4" '.
1.589     bisitz   1695: 	'onchange="javascript:updateRadio(this.form,\''.$counter.'_'.$partid.'\','.
1.71      ng       1696: 	$wgt.')" /></td>'."\n";
1.485     albertel 1697:     $line.='<td>/'.$wgt.' '.$wgtmsg.
1.71      ng       1698: 	($$record{'resource.'.$partid.'.solved'} eq 'correct_by_student' ? '&nbsp;'.$checkIcon : '').
1.585     bisitz   1699: 	' </td>'."\n";
                   1700:     $line.='<td><select name="GD_SEL'.$counter.'_'.$partid.'" '.
1.589     bisitz   1701: 	'onchange="javascript:clearRadBox(this.form,\''.$counter.'_'.$partid.'\')" >'."\n";
1.71      ng       1702:     if ($$record{'resource.'.$partid.'.solved'} eq 'excused') {
1.485     albertel 1703: 	$line.='<option></option>'.
                   1704: 	    '<option value="excused" selected="selected">'.&mt('excused').'</option>';
1.71      ng       1705:     } else {
1.485     albertel 1706: 	$line.='<option selected="selected"></option>'.
                   1707: 	    '<option value="excused" >'.&mt('excused').'</option>';
1.71      ng       1708:     }
1.485     albertel 1709:     $line.='<option value="reset status">'.&mt('reset status').'</option></select>'."\n";
                   1710: 
                   1711: 
                   1712:     $result .= 
1.585     bisitz   1713: 	    '<td>'.$display_part.'</td><td>'.$radio.'</td><td>'.&mt('or').'</td><td>'.$line.'</td>';
                   1714:     $result.=&Apache::loncommon::end_data_table_row();
1.71      ng       1715:     $result.='<input type="hidden" name="stores'.$counter.'_'.$partid.'" value="" />'."\n".
                   1716: 	'<input type="hidden" name="oldpts'.$counter.'_'.$partid.'" value="'.$score.'" />'."\n".
                   1717: 	'<input type="hidden" name="solved'.$counter.'_'.$partid.'" value="'.
1.269     raeburn  1718: 	$$record{'resource.'.$partid.'.solved'}.'" />'."\n".
                   1719:         '<input type="hidden" name="totaltries'.$counter.'_'.$partid.'" value="'.
                   1720:         $$record{'resource.'.$partid.'.tries'}.'" />'."\n".
                   1721:         '<input type="hidden" name="aggtries'.$counter.'_'.$partid.'" value="'.
                   1722:         $aggtries.'" />'."\n";
1.582     raeburn  1723:     my $res_error;
                   1724:     $result.=&handback_box($symb,$uname,$udom,$counter,$partid,$record,\$res_error);
                   1725:     if ($res_error) {
                   1726:         return &navmap_errormsg();
                   1727:     }
1.318     banghart 1728:     return $result;
                   1729: }
1.322     albertel 1730: 
                   1731: sub handback_box {
1.623     www      1732:     my ($symb,$uname,$udom,$counter,$partid,$record,$res_error_pointer) = @_;
                   1733:     my ($partlist,$handgrade,$responseType) = &response_type($symb,$res_error_pointer);
1.323     banghart 1734:     my (@respids);
1.375     albertel 1735:      my @part_response_id = &flatten_responseType($responseType);
                   1736:     foreach my $part_response_id (@part_response_id) {
                   1737:     	my ($part,$resp) = @{ $part_response_id };
1.323     banghart 1738:         if ($part eq $partid) {
1.375     albertel 1739:             push(@respids,$resp);
1.323     banghart 1740:         }
                   1741:     }
1.318     banghart 1742:     my $result;
1.323     banghart 1743:     foreach my $respid (@respids) {
1.322     albertel 1744: 	my $prefix = $counter.'_'.$partid.'_'.$respid.'_';
                   1745: 	my $files=&get_submitted_files($udom,$uname,$partid,$respid,$record);
                   1746: 	next if (!@$files);
                   1747: 	my $file_counter = 1;
1.313     banghart 1748: 	foreach my $file (@$files) {
1.368     banghart 1749: 	    if ($file =~ /\/portfolio\//) {
                   1750:     	        my ($file_path, $file_disp) = ($file =~ m|(.+/)(.+)$|);
                   1751:     	        my ($name,$version,$ext) = &file_name_version_ext($file_disp);
                   1752:     	        $file_disp = "$name.$ext";
                   1753:     	        $file = $file_path.$file_disp;
                   1754:     	        $result.=&mt('Return commented version of [_1] to student.',
                   1755:     			 '<span class="LC_filename">'.$file_disp.'</span>');
                   1756:     	        $result.='<input type="file"   name="'.$prefix.'returndoc'.$file_counter.'" />'."\n";
                   1757:     	        $result.='<input type="hidden" name="'.$prefix.'origdoc'.$file_counter.'" value="'.$file.'" /><br />';
1.485     albertel 1758:     	        $result.='('.&mt('File will be uploaded when you click on Save &amp; Next below.').')<br />';
1.368     banghart 1759:     	        $file_counter++;
                   1760: 	    }
1.322     albertel 1761: 	}
1.313     banghart 1762:     }
1.318     banghart 1763:     return $result;    
1.71      ng       1764: }
1.44      ng       1765: 
1.58      albertel 1766: sub show_problem {
1.382     albertel 1767:     my ($request,$symb,$uname,$udom,$removeform,$viewon,$mode,$form) = @_;
1.144     albertel 1768:     my $rendered;
1.382     albertel 1769:     my %form = ((ref($form) eq 'HASH')? %{$form} : ());
1.329     albertel 1770:     &Apache::lonxml::remember_problem_counter();
1.144     albertel 1771:     if ($mode eq 'both' or $mode eq 'text') {
                   1772: 	$rendered=&Apache::loncommon::get_student_view($symb,$uname,$udom,
1.382     albertel 1773: 						       $env{'request.course.id'},
                   1774: 						       undef,\%form);
1.144     albertel 1775:     }
1.58      albertel 1776:     if ($removeform) {
                   1777: 	$rendered=~s|<form(.*?)>||g;
                   1778: 	$rendered=~s|</form>||g;
1.374     albertel 1779: 	$rendered=~s|(<input[^>]*name\s*=\s*"?)(\w+)("?)|$1would_have_been_$2$3|g;
1.58      albertel 1780:     }
1.144     albertel 1781:     my $companswer;
                   1782:     if ($mode eq 'both' or $mode eq 'answer') {
1.329     albertel 1783: 	&Apache::lonxml::restore_problem_counter();
1.382     albertel 1784: 	$companswer=
                   1785: 	    &Apache::loncommon::get_student_answers($symb,$uname,$udom,
                   1786: 						    $env{'request.course.id'},
                   1787: 						    %form);
1.144     albertel 1788:     }
1.58      albertel 1789:     if ($removeform) {
                   1790: 	$companswer=~s|<form(.*?)>||g;
                   1791: 	$companswer=~s|</form>||g;
1.144     albertel 1792: 	$companswer=~s|name="submit"|name="would_have_been_submit"|g;
1.58      albertel 1793:     }
1.468     albertel 1794:     $rendered=
1.588     bisitz   1795:         '<div class="LC_Box">'
                   1796:        .'<h3 class="LC_hcell">'.&mt('View of the problem').'</h3>'
                   1797:        .$rendered
                   1798:        .'</div>';
1.468     albertel 1799:     $companswer=
1.588     bisitz   1800:         '<div class="LC_Box">'
                   1801:        .'<h3 class="LC_hcell">'.&mt('Correct answer').'</h3>'
                   1802:        .$companswer
                   1803:        .'</div>';
1.468     albertel 1804:     my $result;
1.144     albertel 1805:     if ($mode eq 'both') {
1.588     bisitz   1806:         $result=$rendered.$companswer;
1.144     albertel 1807:     } elsif ($mode eq 'text') {
1.588     bisitz   1808:         $result=$rendered;
1.144     albertel 1809:     } elsif ($mode eq 'answer') {
1.588     bisitz   1810:         $result=$companswer;
1.144     albertel 1811:     }
1.71      ng       1812:     return $result;
1.58      albertel 1813: }
1.397     albertel 1814: 
1.396     banghart 1815: sub files_exist {
                   1816:     my ($r, $symb) = @_;
                   1817:     my @students = &Apache::loncommon::get_env_multiple('form.stuinfo');
1.397     albertel 1818: 
1.396     banghart 1819:     foreach my $student (@students) {
                   1820:         my ($uname,$udom,$fullname) = split(/:/,$student);
1.397     albertel 1821:         my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},
                   1822: 					      $udom,$uname);
1.396     banghart 1823:         my ($string,$timestamp)= &get_last_submission(\%record);
1.397     albertel 1824:         foreach my $submission (@$string) {
                   1825:             my ($partid,$respid) =
                   1826: 		($submission =~ /^resource\.([^\.]*)\.([^\.]*)\.submission/);
                   1827:             my $files=&get_submitted_files($udom,$uname,$partid,$respid,
                   1828: 					   \%record);
                   1829:             return 1 if (@$files);
1.396     banghart 1830:         }
                   1831:     }
1.397     albertel 1832:     return 0;
1.396     banghart 1833: }
1.397     albertel 1834: 
1.394     banghart 1835: sub download_all_link {
                   1836:     my ($r,$symb) = @_;
1.621     www      1837:     unless (&files_exist($r, $symb)) {
                   1838:        $r->print(&mt('There are currently no submitted documents.'));
                   1839:        return;
                   1840:     }
                   1841: 
1.395     albertel 1842:     my $all_students = 
                   1843: 	join("\n", &Apache::loncommon::get_env_multiple('form.stuinfo'));
                   1844: 
                   1845:     my $parts =
                   1846: 	join("\n",&Apache::loncommon::get_env_multiple('form.vPart'));
                   1847: 
1.394     banghart 1848:     my $identifier = &Apache::loncommon::get_cgi_id();
1.514     raeburn  1849:     &Apache::lonnet::appenv({'cgi.'.$identifier.'.students' => $all_students,
                   1850:                              'cgi.'.$identifier.'.symb' => $symb,
                   1851:                              'cgi.'.$identifier.'.parts' => $parts,});
1.395     albertel 1852:     $r->print('<a href="/cgi-bin/multidownload.pl?'.$identifier.'">'.
                   1853: 	      &mt('Download All Submitted Documents').'</a>');
1.621     www      1854:     return;
                   1855: }
                   1856: 
                   1857: sub submit_download_link {
                   1858:     my ($request,$symb) = @_;
                   1859:     if (!$symb) { return ''; }
                   1860: #FIXME: Figure out which type of problem this is and provide appropriate download
                   1861:     &download_all_link($request,$symb);
1.394     banghart 1862: }
1.395     albertel 1863: 
1.432     banghart 1864: sub build_section_inputs {
                   1865:     my $section_inputs;
                   1866:     if ($env{'form.section'} eq '') {
                   1867:         $section_inputs .= '<input type="hidden" name="section" value="all" />'."\n";
                   1868:     } else {
                   1869:         my @sections = &Apache::loncommon::get_env_multiple('form.section');
1.434     albertel 1870:         foreach my $section (@sections) {
1.432     banghart 1871:             $section_inputs .= '<input type="hidden" name="section" value="'.$section.'" />'."\n";
                   1872:         }
                   1873:     }
                   1874:     return $section_inputs;
                   1875: }
                   1876: 
1.44      ng       1877: # --------------------------- show submissions of a student, option to grade 
                   1878: sub submission {
1.608     www      1879:     my ($request,$counter,$total,$symb) = @_;
1.257     albertel 1880:     my ($uname,$udom)     = ($env{'form.student'},$env{'form.userdom'});
                   1881:     $udom = ($udom eq '' ? $env{'user.domain'} : $udom); #has form.userdom changed for a student?
                   1882:     my $usec = &Apache::lonnet::getsection($udom,$uname,$env{'request.course.id'});
                   1883:     $env{'form.fullname'} = &Apache::loncommon::plainname($uname,$udom,'lastname') if $env{'form.fullname'} eq '';
1.608     www      1884: 
1.605     www      1885:     my $probtitle=&Apache::lonnet::gettitle($symb); 
1.324     albertel 1886:     if ($symb eq '') { $request->print("Unable to handle ambiguous references:."); return ''; }
1.104     albertel 1887: 
                   1888:     if (!&canview($usec)) {
1.398     albertel 1889: 	$request->print('<span class="LC_warning">Unable to view requested student.('.
                   1890: 			$uname.':'.$udom.' in section '.$usec.' in course id '.
                   1891: 			$env{'request.course.id'}.')</span>');
1.104     albertel 1892: 	return;
                   1893:     }
                   1894: 
1.257     albertel 1895:     if (!$env{'form.lastSub'}) { $env{'form.lastSub'} = 'datesub'; }
                   1896:     if (!$env{'form.vProb'}) { $env{'form.vProb'} = 'yes'; }
                   1897:     if (!$env{'form.vAns'}) { $env{'form.vAns'} = 'yes'; }
                   1898:     my $last = ($env{'form.lastSub'} eq 'last' ? 'last' : '');
1.381     albertel 1899:     my $checkIcon = '<img alt="'.&mt('Check Mark').
                   1900: 	'" src="'.$request->dir_config('lonIconsURL').
1.122     ng       1901: 	'/check.gif" height="16" border="0" />';
1.41      ng       1902: 
1.426     albertel 1903:     my %old_essays;
1.41      ng       1904:     # header info
                   1905:     if ($counter == 0) {
                   1906: 	&sub_page_js($request);
1.621     www      1907: 	&sub_page_kw_js($request);
1.118     ng       1908: 
1.44      ng       1909: 	# option to display problem, only once else it cause problems 
                   1910:         # with the form later since the problem has a form.
1.257     albertel 1911: 	if ($env{'form.vProb'} eq 'yes' or $env{'form.vAns'} eq 'yes') {
1.144     albertel 1912: 	    my $mode;
1.257     albertel 1913: 	    if ($env{'form.vProb'} eq 'yes' && $env{'form.vAns'} eq 'yes') {
1.144     albertel 1914: 		$mode='both';
1.257     albertel 1915: 	    } elsif ($env{'form.vProb'} eq 'yes') {
1.144     albertel 1916: 		$mode='text';
1.257     albertel 1917: 	    } elsif ($env{'form.vAns'} eq 'yes') {
1.144     albertel 1918: 		$mode='answer';
                   1919: 	    }
1.329     albertel 1920: 	    &Apache::lonxml::clear_problem_counter();
1.144     albertel 1921: 	    $request->print(&show_problem($request,$symb,$uname,$udom,0,1,$mode));
1.41      ng       1922: 	}
1.441     www      1923: 
1.44      ng       1924: 	# kwclr is the only variable that is guaranteed to be non blank 
                   1925:         # if this subroutine has been called once.
1.41      ng       1926: 	my %keyhash = ();
1.624     www      1927: #	if ($env{'form.kwclr'} eq '' && $env{'form.handgrade'} eq 'yes') {
                   1928:         if (1) {
1.41      ng       1929: 	    %keyhash = &Apache::lonnet::dump('nohist_handgrade',
1.257     albertel 1930: 					     $env{'course.'.$env{'request.course.id'}.'.domain'},
                   1931: 					     $env{'course.'.$env{'request.course.id'}.'.num'});
1.41      ng       1932: 
1.257     albertel 1933: 	    my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
                   1934: 	    $env{'form.keywords'} = $keyhash{$symb.'_keywords'} ne '' ? $keyhash{$symb.'_keywords'} : '';
                   1935: 	    $env{'form.kwclr'}    = $keyhash{$loginuser.'_kwclr'} ne '' ? $keyhash{$loginuser.'_kwclr'} : 'red';
                   1936: 	    $env{'form.kwsize'}   = $keyhash{$loginuser.'_kwsize'} ne '' ? $keyhash{$loginuser.'_kwsize'} : '0';
                   1937: 	    $env{'form.kwstyle'}  = $keyhash{$loginuser.'_kwstyle'} ne '' ? $keyhash{$loginuser.'_kwstyle'} : '';
                   1938: 	    $env{'form.msgsub'}   = $keyhash{$symb.'_subject'} ne '' ? 
1.605     www      1939: 		$keyhash{$symb.'_subject'} : $probtitle;
1.257     albertel 1940: 	    $env{'form.savemsgN'} = $keyhash{$symb.'_savemsgN'} ne '' ? $keyhash{$symb.'_savemsgN'} : '0';
1.41      ng       1941: 	}
1.257     albertel 1942: 	my $overRideScore = $env{'form.overRideScore'} eq '' ? 'no' : $env{'form.overRideScore'};
1.442     banghart 1943: 	my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
1.303     banghart 1944: 	$request->print('<form action="/adm/grades" method="post" name="SCORE" enctype="multipart/form-data">'."\n".
1.41      ng       1945: 			'<input type="hidden" name="command"    value="handgrade" />'."\n".
1.442     banghart 1946: 			'<input type="hidden" name="Status"     value="'.$stu_status.'" />'."\n".
1.120     ng       1947: 			'<input type="hidden" name="overRideScore" value="'.$overRideScore.'" />'."\n".
1.41      ng       1948: 			'<input type="hidden" name="refresh"    value="off" />'."\n".
1.120     ng       1949: 			'<input type="hidden" name="studentNo"  value="" />'."\n".
                   1950: 			'<input type="hidden" name="gradeOpt"   value="" />'."\n".
1.418     albertel 1951: 			'<input type="hidden" name="symb"       value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.257     albertel 1952: 			'<input type="hidden" name="vProb"      value="'.$env{'form.vProb'}.'" />'."\n".
                   1953: 			'<input type="hidden" name="vAns"       value="'.$env{'form.vAns'}.'" />'."\n".
                   1954: 			'<input type="hidden" name="lastSub"    value="'.$env{'form.lastSub'}.'" />'."\n".
1.432     banghart 1955: 			&build_section_inputs().
1.326     albertel 1956: 			'<input type="hidden" name="submitonly" value="'.$env{'form.submitonly'}.'" />'."\n".
1.41      ng       1957: 			'<input type="hidden" name="NCT"'.
1.257     albertel 1958: 			' value="'.($env{'form.NTSTU'} ne '' ? $env{'form.NTSTU'} : $total+1).'" />'."\n");
1.624     www      1959: #	if ($env{'form.handgrade'} eq 'yes') {
                   1960:         if (1) {
1.257     albertel 1961: 	    $request->print('<input type="hidden" name="keywords" value="'.$env{'form.keywords'}.'" />'."\n".
                   1962: 			    '<input type="hidden" name="kwclr"    value="'.$env{'form.kwclr'}.'" />'."\n".
                   1963: 			    '<input type="hidden" name="kwsize"   value="'.$env{'form.kwsize'}.'" />'."\n".
                   1964: 			    '<input type="hidden" name="kwstyle"  value="'.$env{'form.kwstyle'}.'" />'."\n".
                   1965: 			    '<input type="hidden" name="msgsub"   value="'.$env{'form.msgsub'}.'" />'."\n".
1.123     ng       1966: 			    '<input type="hidden" name="shownSub" value="0" />'."\n".
1.257     albertel 1967: 			    '<input type="hidden" name="savemsgN" value="'.$env{'form.savemsgN'}.'" />'."\n");
1.154     albertel 1968: 	    foreach my $partid (&Apache::loncommon::get_env_multiple('form.vPart')) {
                   1969: 		$request->print('<input type="hidden" name="vPart" value="'.$partid.'" />'."\n");
                   1970: 	    }
1.123     ng       1971: 	}
1.41      ng       1972: 	
                   1973: 	my ($cts,$prnmsg) = (1,'');
1.257     albertel 1974: 	while ($cts <= $env{'form.savemsgN'}) {
1.41      ng       1975: 	    $prnmsg.='<input type="hidden" name="savemsg'.$cts.'" value="'.
1.123     ng       1976: 		(!exists($keyhash{$symb.'_savemsg'.$cts}) ? 
1.257     albertel 1977: 		 &Apache::lonfeedback::clear_out_html($env{'form.savemsg'.$cts}) :
1.80      ng       1978: 		 &Apache::lonfeedback::clear_out_html($keyhash{$symb.'_savemsg'.$cts})).
1.123     ng       1979: 		'" />'."\n".
                   1980: 		'<input type="hidden" name="shownOnce'.$cts.'" value="0" />'."\n";
1.41      ng       1981: 	    $cts++;
                   1982: 	}
                   1983: 	$request->print($prnmsg);
1.32      ng       1984: 
1.624     www      1985: #	if ($env{'form.handgrade'} eq 'yes') {
                   1986:         if (1) {
1.88      www      1987: #
                   1988: # Print out the keyword options line
                   1989: #
1.41      ng       1990: 	    $request->print(<<KEYWORDS);
1.38      ng       1991: &nbsp;<b>Keyword Options:</b>&nbsp;
1.417     albertel 1992: <a href="javascript:keywords(document.SCORE);" target="_self">List</a>&nbsp; &nbsp;
1.589     bisitz   1993: <a href="#" onmousedown="javascript:getSel(); return false"
1.38      ng       1994:  CLASS="page">Paste Selection to List</a>&nbsp; &nbsp;
1.417     albertel 1995: <a href="javascript:kwhighlight();" target="_self">Highlight Attribute</a><br /><br />
1.38      ng       1996: KEYWORDS
1.88      www      1997: #
                   1998: # Load the other essays for similarity check
                   1999: #
1.324     albertel 2000:             my (undef,undef,$essayurl) = &Apache::lonnet::decode_symb($symb);
1.384     albertel 2001: 	    my ($adom,$aname,$apath)=($essayurl=~/^($LONCAPA::domain_re)\/($LONCAPA::username_re)\/(.*)$/);
1.359     www      2002: 	    $apath=&escape($apath);
1.88      www      2003: 	    $apath=~s/\W/\_/gs;
1.426     albertel 2004: 	    %old_essays=&Apache::lonnet::dump('nohist_essay_'.$apath,$adom,$aname);
1.41      ng       2005:         }
                   2006:     }
1.44      ng       2007: 
1.441     www      2008: # This is where output for one specific student would start
1.592     bisitz   2009:     my $add_class = ($counter%2) ? ' LC_grade_show_user_odd_row' : '';
                   2010:     $request->print(
                   2011:         "\n\n"
                   2012:        .'<div class="LC_grade_show_user'.$add_class.'">'
                   2013:        .'<h2>'.&nameUserString(undef,$env{'form.fullname'},$uname,$udom).'</h2>'
                   2014:        ."\n"
                   2015:     );
1.441     www      2016: 
1.592     bisitz   2017:     # Show additional functions if allowed
                   2018:     if ($perm{'vgr'}) {
                   2019:         $request->print(
                   2020:             &Apache::loncommon::track_student_link(
                   2021:                 &mt('View recent activity'),
                   2022:                 $uname,$udom,'check')
                   2023:            .' '
                   2024:         );
                   2025:     }
                   2026:     if ($perm{'opa'}) {
                   2027:         $request->print(
                   2028:             &Apache::loncommon::pprmlink(
                   2029:                 &mt('Set/Change parameters'),
                   2030:                 $uname,$udom,$symb,'check'));
                   2031:     }
                   2032: 
                   2033:     # Show Problem
1.257     albertel 2034:     if ($env{'form.vProb'} eq 'all' or $env{'form.vAns'} eq 'all') {
1.144     albertel 2035: 	my $mode;
1.257     albertel 2036: 	if ($env{'form.vProb'} eq 'all' && $env{'form.vAns'} eq 'all') {
1.144     albertel 2037: 	    $mode='both';
1.257     albertel 2038: 	} elsif ($env{'form.vProb'} eq 'all' ) {
1.144     albertel 2039: 	    $mode='text';
1.257     albertel 2040: 	} elsif ($env{'form.vAns'} eq 'all') {
1.144     albertel 2041: 	    $mode='answer';
                   2042: 	}
1.329     albertel 2043: 	&Apache::lonxml::clear_problem_counter();
1.475     albertel 2044: 	$request->print(&show_problem($request,$symb,$uname,$udom,1,1,$mode,{'request.prefix' => 'ctr'.$counter}));
1.58      albertel 2045:     }
1.144     albertel 2046: 
1.257     albertel 2047:     my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
1.582     raeburn  2048:     my $res_error;
                   2049:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
                   2050:     if ($res_error) {
                   2051:         $request->print(&navmap_errormsg());
                   2052:         return;
                   2053:     }
1.41      ng       2054: 
1.44      ng       2055:     # Display student info
1.41      ng       2056:     $request->print(($counter == 0 ? '' : '<br />'));
1.590     bisitz   2057: 
                   2058:     my $result='<div class="LC_Box">'
                   2059:               .'<h3 class="LC_hcell">'.&mt('Submissions').'</h3>';
1.45      ng       2060:     $result.='<input type="hidden" name="name'.$counter.
1.588     bisitz   2061:              '" value="'.$env{'form.fullname'}.'" />'."\n";
1.624     www      2062: #    if ($env{'form.handgrade'} eq 'no') {
                   2063:     if (1) {
1.588     bisitz   2064:         $result.='<p class="LC_info">'
                   2065:                 .&mt('Part(s) graded correct by the computer is marked with a [_1] symbol.',$checkIcon)
                   2066:                 ."</p>\n";
1.469     albertel 2067:     }
                   2068: 
1.118     ng       2069:     # If any part of the problem is an essay-response (handgraded), then check for collaborators
1.464     albertel 2070:     my $fullname;
                   2071:     my $col_fullnames = [];
1.624     www      2072: #    if ($env{'form.handgrade'} eq 'yes') {
                   2073:     if (1) {
1.464     albertel 2074: 	(my $sub_result,$fullname,$col_fullnames)=
                   2075: 	    &check_collaborators($symb,$uname,$udom,\%record,$handgrade,
                   2076: 				 $counter);
                   2077: 	$result.=$sub_result;
1.41      ng       2078:     }
1.44      ng       2079:     $request->print($result."\n");
1.588     bisitz   2080: 
1.44      ng       2081:     # print student answer/submission
1.588     bisitz   2082:     # Options are (1) Handgraded submission only
1.44      ng       2083:     #             (2) Last submission, includes submission that is not handgraded 
                   2084:     #                  (for multi-response type part)
                   2085:     #             (3) Last submission plus the parts info
                   2086:     #             (4) The whole record for this student
1.257     albertel 2087:     if ($env{'form.lastSub'} =~ /^(lastonly|hdgrade)$/) {
1.151     albertel 2088: 	my ($string,$timestamp)= &get_last_submission(\%record);
1.468     albertel 2089: 	
                   2090: 	my $lastsubonly;
                   2091: 
1.588     bisitz   2092:         if ($$timestamp eq '') {
                   2093:             $lastsubonly.='<div class="LC_grade_submissions_body">'.$$string[0].'</div>'; 
                   2094:         } else {
1.592     bisitz   2095:             $lastsubonly =
                   2096:                 '<div class="LC_grade_submissions_body">'
                   2097:                .'<b>'.&mt('Date Submitted:').'</b> '.$$timestamp."\n";
1.468     albertel 2098: 
1.151     albertel 2099: 	    my %seenparts;
1.375     albertel 2100: 	    my @part_response_id = &flatten_responseType($responseType);
                   2101: 	    foreach my $part (@part_response_id) {
1.393     albertel 2102: 		next if ($env{'form.lastSub'} eq 'hdgrade' 
                   2103: 			 && $$handgrade{$$part[0].'_'.$$part[1]} ne 'yes');
                   2104: 
1.375     albertel 2105: 		my ($partid,$respid) = @{ $part };
1.324     albertel 2106: 		my $display_part=&get_display_part($partid,$symb);
1.257     albertel 2107: 		if ($env{"form.$uname:$udom:$partid:submitted_by"}) {
1.151     albertel 2108: 		    if (exists($seenparts{$partid})) { next; }
                   2109: 		    $seenparts{$partid}=1;
1.207     albertel 2110: 		    my $submitby='<b>Part:</b> '.$display_part.
                   2111: 			' <b>Collaborative submission by:</b> '.
1.151     albertel 2112: 			'<a href="javascript:viewSubmitter(\''.
1.257     albertel 2113: 			$env{"form.$uname:$udom:$partid:submitted_by"}.
1.417     albertel 2114: 			'\');" target="_self">'.
1.257     albertel 2115: 			$$fullname{$env{"form.$uname:$udom:$partid:submitted_by"}}.'</a><br />';
1.151     albertel 2116: 		    $request->print($submitby);
                   2117: 		    next;
                   2118: 		}
                   2119: 		my $responsetype = $responseType->{$partid}->{$respid};
                   2120: 		if (!exists($record{"resource.$partid.$respid.submission"})) {
1.577     bisitz   2121:                     $lastsubonly.="\n".'<div class="LC_grade_submission_part">'.
                   2122:                         '<b>'.&mt('Part: [_1]',$display_part).'</b>'.
                   2123:                         ' <span class="LC_internal_info">'.
1.623     www      2124:                         '('.&mt('Response ID: [_1]',$respid).')'.
1.577     bisitz   2125:                         '</span>&nbsp; &nbsp;'.
1.539     riegler  2126: 			'<span class="LC_warning">'.&mt('Nothing submitted - no attempts.').'</span><br /><br /></div>';
1.151     albertel 2127: 		    next;
                   2128: 		}
1.468     albertel 2129: 		foreach my $submission (@$string) {
                   2130: 		    my ($partid,$respid) = ($submission =~ /^resource\.([^\.]*)\.([^\.]*)\.submission/);
1.375     albertel 2131: 		    if (join('_',@{$part}) ne ($partid.'_'.$respid)) { next; }
1.596     raeburn  2132: 		    my ($ressub,$hide,$subval) = split(/:/,$submission,3);
1.151     albertel 2133: 		    # Similarity check
                   2134: 		    my $similar='';
1.257     albertel 2135: 		    if($env{'form.checkPlag'}){
1.151     albertel 2136: 			my ($oname,$odom,$ocrsid,$oessay,$osim)=
1.426     albertel 2137: 			    &most_similar($uname,$udom,$subval,\%old_essays);
1.151     albertel 2138: 			if ($osim) {
                   2139: 			    $osim=int($osim*100.0);
1.426     albertel 2140: 			    my %old_course_desc = 
                   2141: 				&Apache::lonnet::coursedescription($ocrsid,
                   2142: 								   {'one_time' => 1});
                   2143: 
1.596     raeburn  2144:                             if ($hide) {
                   2145:                                 $similar='<hr /><span class="LC_warning">'.&mt("Essay was found to be similar to another essay submitted for this assignment.").'<br />'.
                   2146:                                          &mt('As the current submission is for an anonymous survey, no other details are available.').'</span><hr />';
                   2147:                             } else {
                   2148: 			        $similar="<hr /><h3><span class=\"LC_warning\">".
                   2149: 				    &mt('Essay is [_1]% similar to an essay by [_2] in course [_3] (course id [_4]:[_5])',
                   2150: 				        $osim,
                   2151: 				        &Apache::loncommon::plainname($oname,$odom).' ('.$oname.':'.$odom.')',
                   2152: 				        $old_course_desc{'description'},
                   2153: 				        $old_course_desc{'num'},
                   2154: 				        $old_course_desc{'domain'}).
                   2155: 				    '</span></h3><blockquote><i>'.
                   2156: 				    &keywords_highlight($oessay).
                   2157: 				    '</i></blockquote><hr />';
                   2158:                             }
1.151     albertel 2159: 			}
1.150     albertel 2160: 		    }
1.151     albertel 2161: 		    my $order=&get_order($partid,$respid,$symb,$uname,$udom);
1.257     albertel 2162: 		    if ($env{'form.lastSub'} eq 'lastonly' || 
                   2163: 			($env{'form.lastSub'} eq 'hdgrade' && 
1.377     albertel 2164: 			 $$handgrade{$$part[0].'_'.$$part[1]} eq 'yes')) {
1.324     albertel 2165: 			my $display_part=&get_display_part($partid,$symb);
1.577     bisitz   2166:                         $lastsubonly.='<div class="LC_grade_submission_part">'.
                   2167:                             '<b>'.&mt('Part: [_1]',$display_part).'</b>'.
                   2168:                             ' <span class="LC_internal_info">'.
1.623     www      2169:                             '('.&mt('Response ID: [_1]',$respid).')'.
1.597     wenzelju 2170:                             '</span>&nbsp; &nbsp;';
1.313     banghart 2171: 			my $files=&get_submitted_files($udom,$uname,$partid,$respid,\%record);
                   2172: 			if (@$files) {
1.596     raeburn  2173:                             if ($hide) {
                   2174:                                 $lastsubonly.='<br />'.&mt('[quant,_1,file] uploaded to this anonymous survey',scalar(@{$files}));
                   2175:                             } else {
                   2176:                                 $lastsubonly.='<br /><span class="LC_warning">'.&mt('Like all files provided by users, this file may contain viruses').'</span><br />';
                   2177:                                 foreach my $file (@$files) {
                   2178:                                     &Apache::lonnet::allowuploaded('/adm/grades',$file);
                   2179:                                     $lastsubonly.='<br /><a href="'.$file.'?rawmode=1" target="lonGRDs"><img src="'.&Apache::loncommon::icon($file).'" border="0" /> '.$file.'</a>';
                   2180:                                 }
                   2181:                             }
1.236     albertel 2182: 			    $lastsubonly.='<br />';
1.41      ng       2183: 			}
1.596     raeburn  2184:                         if ($hide) {
                   2185:                             $lastsubonly.='<b>'.&mt('Anonymous Survey').'</b>'; 
                   2186:                         } else {
                   2187: 			    $lastsubonly.='<b>'.&mt('Submitted Answer:').' </b>'.
                   2188: 			        &cleanRecord($subval,$responsetype,$symb,$partid,
                   2189: 					     $respid,\%record,$order,undef,$uname,$udom);
                   2190:                         }
1.151     albertel 2191: 			if ($similar) {$lastsubonly.="<br /><br />$similar\n";}
1.468     albertel 2192: 			$lastsubonly.='</div>';
1.41      ng       2193: 		    }
                   2194: 		}
                   2195: 	    }
1.588     bisitz   2196: 	    $lastsubonly.='</div>'."\n"; # End: LC_grade_submissions_body
1.151     albertel 2197: 	}
                   2198: 	$request->print($lastsubonly);
1.468     albertel 2199:    } elsif ($env{'form.lastSub'} eq 'datesub') {
1.623     www      2200:         my ($parts,$handgrade,$responseType) = &response_type($symb,\$res_error);
1.148     albertel 2201: 	$request->print(&displaySubByDates($symb,\%record,$parts,$responseType,$checkIcon,$uname,$udom));
1.257     albertel 2202:     } elsif ($env{'form.lastSub'} =~ /^(last|all)$/) {
1.41      ng       2203: 	$request->print(&Apache::loncommon::get_previous_attempt($symb,$uname,$udom,
1.257     albertel 2204: 								 $env{'request.course.id'},
1.44      ng       2205: 								 $last,'.submission',
                   2206: 								 'Apache::grades::keywords_highlight'));
1.41      ng       2207:     }
1.121     ng       2208:     $request->print('<input type="hidden" name="unamedom'.$counter.'" value="'.$uname.':'
                   2209: 	.$udom.'" />'."\n");
1.44      ng       2210:     # return if view submission with no grading option
1.618     www      2211:     if (!&canmodify($usec)) {
1.633     www      2212: 	$request->print('<p><span class="LC_warning">'.&mt('No grading privileges').'</span></p></div>');
1.41      ng       2213: 	return;
1.180     albertel 2214:     } else {
1.468     albertel 2215: 	$request->print('</div>'."\n");
1.41      ng       2216:     }
1.33      ng       2217: 
1.121     ng       2218:     # essay grading message center
1.624     www      2219: #    if ($env{'form.handgrade'} eq 'yes') {
                   2220:     if (1) {
1.468     albertel 2221: 	my $result='<div class="LC_grade_message_center">';
                   2222:     
                   2223: 	$result.='<div class="LC_grade_message_center_header">'.
                   2224: 	    &mt('Send Message').'</div><div class="LC_grade_message_center_body">';
1.257     albertel 2225: 	my ($lastname,$givenn) = split(/,/,$env{'form.fullname'});
1.118     ng       2226: 	my $msgfor = $givenn.' '.$lastname;
1.464     albertel 2227: 	if (scalar(@$col_fullnames) > 0) {
                   2228: 	    my $lastone = pop(@$col_fullnames);
                   2229: 	    $msgfor .= ', '.(join ', ',@$col_fullnames).' and '.$lastone.'.';
1.118     ng       2230: 	}
                   2231: 	$msgfor =~ s/\'/\\'/g; #' stupid emacs - no! javascript
1.468     albertel 2232: 	$result.='<input type="hidden" name="includemsg'.$counter.'" value="" />'."\n".
1.121     ng       2233: 	    '<input type="hidden" name="newmsg'.$counter.'" value="" />'."\n";
                   2234: 	$result.='&nbsp;<a href="javascript:msgCenter(document.SCORE,'.$counter.
1.417     albertel 2235: 	    ',\''.$msgfor.'\');" target="_self">'.
1.464     albertel 2236: 	    &mt('Compose message to student').(scalar(@$col_fullnames) >= 1 ? 's' : '').'</a><label> ('.
1.350     albertel 2237: 	    &mt('incl. grades').' <input type="checkbox" name="withgrades'.$counter.'" /></label>)'.
1.118     ng       2238: 	    '<img src="'.$request->dir_config('lonIconsURL').
                   2239: 	    '/mailbkgrd.gif" width="14" height="10" name="mailicon'.$counter.'" />'."\n".
1.298     www      2240: 	    '<br />&nbsp;('.
1.468     albertel 2241: 	    &mt('Message will be sent when you click on Save &amp; Next below.').")\n";
                   2242: 	$result.='</div></div>';
1.121     ng       2243: 	$request->print($result);
1.118     ng       2244:     }
1.41      ng       2245: 
                   2246:     my %seen = ();
                   2247:     my @partlist;
1.129     ng       2248:     my @gradePartRespid;
1.375     albertel 2249:     my @part_response_id = &flatten_responseType($responseType);
1.585     bisitz   2250:     $request->print(
1.588     bisitz   2251:         '<div class="LC_Box">'
                   2252:        .'<h3 class="LC_hcell">'.&mt('Assign Grades').'</h3>'
1.585     bisitz   2253:     );
1.592     bisitz   2254:     $request->print(&gradeBox_start());
1.375     albertel 2255:     foreach my $part_response_id (@part_response_id) {
                   2256:     	my ($partid,$respid) = @{ $part_response_id };
                   2257: 	my $part_resp = join('_',@{ $part_response_id });
1.322     albertel 2258: 	next if ($seen{$partid} > 0);
1.41      ng       2259: 	$seen{$partid}++;
1.393     albertel 2260: 	next if ($$handgrade{$part_resp} ne 'yes' 
                   2261: 		 && $env{'form.lastSub'} eq 'hdgrade');
1.524     raeburn  2262: 	push(@partlist,$partid);
                   2263: 	push(@gradePartRespid,$partid.'.'.$respid);
1.322     albertel 2264: 	$request->print(&gradeBox($request,$symb,$uname,$udom,$counter,$partid,\%record));
1.41      ng       2265:     }
1.585     bisitz   2266:     $request->print(&gradeBox_end()); # </div>
                   2267:     $request->print('</div>');
1.468     albertel 2268: 
                   2269:     $request->print('<div class="LC_grade_info_links">');
                   2270:     $request->print('</div>');
                   2271: 
1.45      ng       2272:     $result='<input type="hidden" name="partlist'.$counter.
                   2273: 	'" value="'.(join ":",@partlist).'" />'."\n";
1.129     ng       2274:     $result.='<input type="hidden" name="gradePartRespid'.
                   2275: 	'" value="'.(join ":",@gradePartRespid).'" />'."\n" if ($counter == 0);
1.45      ng       2276:     my $ctr = 0;
                   2277:     while ($ctr < scalar(@partlist)) {
                   2278: 	$result.='<input type="hidden" name="partid'.$counter.'_'.$ctr.'" value="'.
                   2279: 	    $partlist[$ctr].'" />'."\n";
                   2280: 	$ctr++;
                   2281:     }
1.468     albertel 2282:     $request->print($result.''."\n");
1.41      ng       2283: 
1.441     www      2284: # Done with printing info for one student
                   2285: 
1.468     albertel 2286:     $request->print('</div>');#LC_grade_show_user
1.441     www      2287: 
                   2288: 
1.41      ng       2289:     # print end of form
                   2290:     if ($counter == $total) {
1.592     bisitz   2291:         my $endform='<br /><hr /><table border="0"><tr><td>'."\n";
1.485     albertel 2292: 	$endform.='<input type="button" value="'.&mt('Save &amp; Next').'" '.
1.589     bisitz   2293: 	    'onclick="javascript:checksubmit(this.form,\'Save & Next\','.
1.417     albertel 2294: 	    $total.','.scalar(@partlist).');" target="_self" /> &nbsp;'."\n";
1.119     ng       2295: 	my $ntstu ='<select name="NTSTU">'.
                   2296: 	    '<option>1</option><option>2</option>'.
                   2297: 	    '<option>3</option><option>5</option>'.
                   2298: 	    '<option>7</option><option>10</option></select>'."\n";
1.257     albertel 2299: 	my $nsel = ($env{'form.NTSTU'} ne '' ? $env{'form.NTSTU'} : '1');
1.401     albertel 2300: 	$ntstu =~ s/<option>$nsel</<option selected="selected">$nsel</;
1.578     raeburn  2301:         $endform.=&mt('[_1]student(s)',$ntstu);
1.485     albertel 2302: 	$endform.='&nbsp;&nbsp;<input type="button" value="'.&mt('Previous').'" '.
1.589     bisitz   2303: 	    'onclick="javascript:checksubmit(this.form,\'Previous\');" target="_self" /> &nbsp;'."\n".
1.485     albertel 2304: 	    '<input type="button" value="'.&mt('Next').'" '.
1.589     bisitz   2305: 	    'onclick="javascript:checksubmit(this.form,\'Next\');" target="_self" /> &nbsp;';
1.592     bisitz   2306:         $endform.='<span class="LC_warning">'.
                   2307:                   &mt('(Next and Previous (student) do not save the scores.)').
                   2308:                   '</span>'."\n" ;
1.349     albertel 2309:         $endform.="<input type='hidden' value='".&get_increment().
1.348     bowersj2 2310:             "' name='increment' />";
1.485     albertel 2311: 	$endform.='</td></tr></table></form>';
1.41      ng       2312: 	$request->print($endform);
                   2313:     }
                   2314:     return '';
1.38      ng       2315: }
                   2316: 
1.464     albertel 2317: sub check_collaborators {
                   2318:     my ($symb,$uname,$udom,$record,$handgrade,$counter) = @_;
                   2319:     my ($result,@col_fullnames);
                   2320:     my ($classlist,undef,$fullname) = &getclasslist('all','0');
                   2321:     foreach my $part (keys(%$handgrade)) {
                   2322: 	my $ncol = &Apache::lonnet::EXT('resource.'.$part.
                   2323: 					'.maxcollaborators',
                   2324: 					$symb,$udom,$uname);
                   2325: 	next if ($ncol <= 0);
                   2326: 	$part =~ s/\_/\./g;
                   2327: 	next if ($record->{'resource.'.$part.'.collaborators'} eq '');
                   2328: 	my (@good_collaborators, @bad_collaborators);
                   2329: 	foreach my $possible_collaborator
1.630     www      2330: 	    (split(/[,;\s]+/,$record->{'resource.'.$part.'.collaborators'})) { 
1.464     albertel 2331: 	    $possible_collaborator =~ s/[\$\^\(\)]//g;
                   2332: 	    next if ($possible_collaborator eq '');
1.631     www      2333: 	    my ($co_name,$co_dom) = split(/:/,$possible_collaborator);
1.464     albertel 2334: 	    $co_dom = $udom if (! defined($co_dom) || $co_dom =~ /^domain$/i);
                   2335: 	    next if ($co_name eq $uname && $co_dom eq $udom);
                   2336: 	    # Doing this grep allows 'fuzzy' specification
                   2337: 	    my @matches = grep(/^\Q$co_name\E:\Q$co_dom\E$/i, 
                   2338: 			       keys(%$classlist));
                   2339: 	    if (! scalar(@matches)) {
                   2340: 		push(@bad_collaborators, $possible_collaborator);
                   2341: 	    } else {
                   2342: 		push(@good_collaborators, @matches);
                   2343: 	    }
                   2344: 	}
                   2345: 	if (scalar(@good_collaborators) != 0) {
1.630     www      2346: 	    $result.='<br />'.&mt('Collaborators:').'<ol>';
1.464     albertel 2347: 	    foreach my $name (@good_collaborators) {
                   2348: 		my ($lastname,$givenn) = split(/,/,$$fullname{$name});
                   2349: 		push(@col_fullnames, $givenn.' '.$lastname);
1.630     www      2350: 		$result.='<li>'.$fullname->{$name}.'</li>';
1.464     albertel 2351: 	    }
1.630     www      2352: 	    $result.='</ol><br />'."\n";
1.466     albertel 2353: 	    my ($part)=split(/\./,$part);
1.464     albertel 2354: 	    $result.='<input type="hidden" name="collaborator'.$counter.
                   2355: 		'" value="'.$part.':'.(join ':',@good_collaborators).'" />'.
                   2356: 		"\n";
                   2357: 	}
                   2358: 	if (scalar(@bad_collaborators) > 0) {
1.466     albertel 2359: 	    $result.='<div class="LC_warning">';
1.464     albertel 2360: 	    $result.=&mt('This student has submitted [quant,_1,invalid collaborator]: [_2]',scalar(@bad_collaborators),join(', ',@bad_collaborators));
                   2361: 	    $result .= '</div>';
                   2362: 	}         
                   2363: 	if (scalar(@bad_collaborators > $ncol)) {
1.466     albertel 2364: 	    $result .= '<div class="LC_warning">';
1.464     albertel 2365: 	    $result .= &mt('This student has submitted too many '.
                   2366: 		'collaborators.  Maximum is [_1].',$ncol);
                   2367: 	    $result .= '</div>';
                   2368: 	}
                   2369:     }
                   2370:     return ($result,$fullname,\@col_fullnames);
                   2371: }
                   2372: 
1.44      ng       2373: #--- Retrieve the last submission for all the parts
1.38      ng       2374: sub get_last_submission {
1.119     ng       2375:     my ($returnhash)=@_;
1.596     raeburn  2376:     my (@string,$timestamp,%lasthidden);
1.119     ng       2377:     if ($$returnhash{'version'}) {
1.46      ng       2378: 	my %lasthash=();
                   2379: 	my ($version);
1.119     ng       2380: 	for ($version=1;$version<=$$returnhash{'version'};$version++) {
1.397     albertel 2381: 	    foreach my $key (sort(split(/\:/,
                   2382: 					$$returnhash{$version.':keys'}))) {
                   2383: 		$lasthash{$key}=$$returnhash{$version.':'.$key};
                   2384: 		$timestamp = 
1.545     raeburn  2385: 		    &Apache::lonlocal::locallocaltime($$returnhash{$version.':timestamp'});
1.46      ng       2386: 	    }
                   2387: 	}
1.596     raeburn  2388:         my %typeparts;
                   2389:         my $showsurv = 
                   2390:             &Apache::lonnet::allowed('vas',$env{'request.course.id'});
                   2391:         foreach my $key (sort(keys(%lasthash))) {
                   2392:             if ($key =~ /\.type$/) {
                   2393:                 if (($lasthash{$key} eq 'anonsurvey') || 
                   2394:                     ($lasthash{$key} eq 'anonsurveycred')) {
                   2395:                     my ($ign,@parts) = split(/\./,$key);
                   2396:                     pop(@parts);
                   2397:                     unless ($showsurv) {
                   2398:                         my $id = join(',',@parts);
                   2399:                         $typeparts{$ign.'.'.$id} = $lasthash{$key};
                   2400:                     }
                   2401:                     delete($lasthash{$key});
                   2402:                 }
                   2403:             }
                   2404:         }
                   2405:         my @hidden = keys(%typeparts);
1.397     albertel 2406: 	foreach my $key (keys(%lasthash)) {
                   2407: 	    next if ($key !~ /\.submission$/);
1.596     raeburn  2408:             my $hide;
                   2409:             if (@hidden) {
                   2410:                 foreach my $id (@hidden) {
                   2411:                     if ($key =~ /^\Q$id\E/) {
                   2412:                         $hide = 1;
                   2413:                         last;
                   2414:                     }
                   2415:                 }
                   2416:             }
1.397     albertel 2417: 	    my ($partid,$foo) = split(/submission$/,$key);
                   2418: 	    my $draft  = $lasthash{$partid.'awarddetail'} eq 'DRAFT' ?
1.398     albertel 2419: 		'<span class="LC_warning">Draft Copy</span> ' : '';
1.596     raeburn  2420: 	    push(@string, join(':', $key, $hide, $draft.$lasthash{$key}));
1.41      ng       2421: 	}
                   2422:     }
1.397     albertel 2423:     if (!@string) {
                   2424: 	$string[0] =
1.539     riegler  2425: 	    '<span class="LC_warning">'.&mt('Nothing submitted - no attempts.').'</span>';
1.397     albertel 2426:     }
                   2427:     return (\@string,\$timestamp);
1.38      ng       2428: }
1.35      ng       2429: 
1.44      ng       2430: #--- High light keywords, with style choosen by user.
1.38      ng       2431: sub keywords_highlight {
1.44      ng       2432:     my $string    = shift;
1.257     albertel 2433:     my $size      = $env{'form.kwsize'} eq '0' ? '' : 'size='.$env{'form.kwsize'};
                   2434:     my $styleon   = $env{'form.kwstyle'} eq ''  ? '' : $env{'form.kwstyle'};
1.41      ng       2435:     (my $styleoff = $styleon) =~ s/\</\<\//;
1.257     albertel 2436:     my @keylist   = split(/[,\s+]/,$env{'form.keywords'});
1.398     albertel 2437:     foreach my $keyword (@keylist) {
                   2438: 	$string =~ s/\b\Q$keyword\E(\b|\.)/<font color\=$env{'form.kwclr'} $size\>$styleon$keyword$styleoff<\/font>/gi;
1.41      ng       2439:     }
                   2440:     return $string;
1.38      ng       2441: }
1.36      ng       2442: 
1.44      ng       2443: #--- Called from submission routine
1.38      ng       2444: sub processHandGrade {
1.608     www      2445:     my ($request,$symb) = @_;
1.324     albertel 2446:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
1.257     albertel 2447:     my $button = $env{'form.gradeOpt'};
                   2448:     my $ngrade = $env{'form.NCT'};
                   2449:     my $ntstu  = $env{'form.NTSTU'};
1.301     albertel 2450:     my $cdom   = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   2451:     my $cnum   = $env{'course.'.$env{'request.course.id'}.'.num'};
                   2452: 
1.44      ng       2453:     if ($button eq 'Save & Next') {
                   2454: 	my $ctr = 0;
                   2455: 	while ($ctr < $ngrade) {
1.257     albertel 2456: 	    my ($uname,$udom) = split(/:/,$env{'form.unamedom'.$ctr});
1.324     albertel 2457: 	    my ($errorflag,$pts,$wgt) = &saveHandGrade($request,$symb,$uname,$udom,$ctr);
1.71      ng       2458: 	    if ($errorflag eq 'no_score') {
                   2459: 		$ctr++;
                   2460: 		next;
                   2461: 	    }
1.104     albertel 2462: 	    if ($errorflag eq 'not_allowed') {
1.398     albertel 2463: 		$request->print("<span class=\"LC_warning\">Not allowed to modify grades for $uname:$udom</span>");
1.104     albertel 2464: 		$ctr++;
                   2465: 		next;
                   2466: 	    }
1.257     albertel 2467: 	    my $includemsg = $env{'form.includemsg'.$ctr};
1.44      ng       2468: 	    my ($subject,$message,$msgstatus) = ('','','');
1.418     albertel 2469: 	    my $restitle = &Apache::lonnet::gettitle($symb);
                   2470:             my ($feedurl,$showsymb) =
                   2471: 		&get_feedurl_and_symb($symb,$uname,$udom);
                   2472: 	    my $messagetail;
1.62      albertel 2473: 	    if ($includemsg =~ /savemsg|newmsg\Q$ctr\E/) {
1.298     www      2474: 		$subject = $env{'form.msgsub'} if ($includemsg =~ /msgsub/);
1.295     www      2475: 		unless ($subject=~/\w/) { $subject=&mt('Grading Feedback'); }
1.386     raeburn  2476: 		$subject.=' ['.$restitle.']';
1.44      ng       2477: 		my (@msgnum) = split(/,/,$includemsg);
                   2478: 		foreach (@msgnum) {
1.257     albertel 2479: 		    $message.=$env{'form.'.$_} if ($_ =~ /savemsg|newmsg/ && $_ ne '');
1.44      ng       2480: 		}
1.80      ng       2481: 		$message =&Apache::lonfeedback::clear_out_html($message);
1.298     www      2482: 		if ($env{'form.withgrades'.$ctr}) {
                   2483: 		    $message.="\n\nPoint".($pts > 1 ? 's':'').' awarded = '.$pts.' out of '.$wgt;
1.386     raeburn  2484: 		    $messagetail = " for <a href=\"".
1.605     www      2485: 		                   $feedurl."?symb=$showsymb\">$restitle</a>";
1.386     raeburn  2486: 		}
                   2487: 		$msgstatus = 
                   2488:                     &Apache::lonmsg::user_normal_msg($uname,$udom,$subject,
                   2489: 						     $message.$messagetail,
1.418     albertel 2490:                                                      undef,$feedurl,undef,
1.386     raeburn  2491:                                                      undef,undef,$showsymb,
                   2492:                                                      $restitle);
1.574     bisitz   2493: 		$request->print('<br />'.&mt('Sending message to [_1]',$uname.':'.$udom).': '.
1.296     www      2494: 				$msgstatus);
1.44      ng       2495: 	    }
1.257     albertel 2496: 	    if ($env{'form.collaborator'.$ctr}) {
1.155     albertel 2497: 		my @collabstrs=&Apache::loncommon::get_env_multiple("form.collaborator$ctr");
1.150     albertel 2498: 		foreach my $collabstr (@collabstrs) {
                   2499: 		    my ($part,@collaborators) = split(/:/,$collabstr);
1.310     banghart 2500: 		    foreach my $collaborator (@collaborators) {
1.150     albertel 2501: 			my ($errorflag,$pts,$wgt) = 
1.324     albertel 2502: 			    &saveHandGrade($request,$symb,$collaborator,$udom,$ctr,
1.257     albertel 2503: 					   $env{'form.unamedom'.$ctr},$part);
1.150     albertel 2504: 			if ($errorflag eq 'not_allowed') {
1.362     albertel 2505: 			    $request->print("<span class=\"LC_error\">".&mt('Not allowed to modify grades for [_1]',"$collaborator:$udom")."</span>");
1.150     albertel 2506: 			    next;
1.418     albertel 2507: 			} elsif ($message ne '') {
                   2508: 			    my ($baseurl,$showsymb) = 
                   2509: 				&get_feedurl_and_symb($symb,$collaborator,
                   2510: 						      $udom);
                   2511: 			    if ($env{'form.withgrades'.$ctr}) {
                   2512: 				$messagetail = " for <a href=\"".
1.605     www      2513:                                     $baseurl."?symb=$showsymb\">$restitle</a>";
1.150     albertel 2514: 			    }
1.418     albertel 2515: 			    $msgstatus = 
                   2516: 				&Apache::lonmsg::user_normal_msg($collaborator,$udom,$subject,$message.$messagetail,undef,$baseurl,undef,undef,undef,$showsymb,$restitle);
1.104     albertel 2517: 			}
1.44      ng       2518: 		    }
                   2519: 		}
                   2520: 	    }
                   2521: 	    $ctr++;
                   2522: 	}
                   2523:     }
                   2524: 
1.624     www      2525: #    if ($env{'form.handgrade'} eq 'yes') {
                   2526:     if (1) {
1.119     ng       2527: 	# Keywords sorted in alphabatical order
1.257     albertel 2528: 	my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
1.119     ng       2529: 	my %keyhash = ();
1.257     albertel 2530: 	$env{'form.keywords'}           =~ s/,\s{0,}|\s+/ /g;
                   2531: 	$env{'form.keywords'}           =~ s/^\s+|\s+$//;
                   2532: 	my (@keywords) = sort(split(/\s+/,$env{'form.keywords'}));
                   2533: 	$env{'form.keywords'} = join(' ',@keywords);
                   2534: 	$keyhash{$symb.'_keywords'}     = $env{'form.keywords'};
                   2535: 	$keyhash{$symb.'_subject'}      = $env{'form.msgsub'};
                   2536: 	$keyhash{$loginuser.'_kwclr'}   = $env{'form.kwclr'};
                   2537: 	$keyhash{$loginuser.'_kwsize'}  = $env{'form.kwsize'};
                   2538: 	$keyhash{$loginuser.'_kwstyle'} = $env{'form.kwstyle'};
1.119     ng       2539: 
                   2540: 	# message center - Order of message gets changed. Blank line is eliminated.
1.257     albertel 2541: 	# New messages are saved in env for the next student.
1.119     ng       2542: 	# All messages are saved in nohist_handgrade.db
                   2543: 	my ($ctr,$idx) = (1,1);
1.257     albertel 2544: 	while ($ctr <= $env{'form.savemsgN'}) {
                   2545: 	    if ($env{'form.savemsg'.$ctr} ne '') {
                   2546: 		$keyhash{$symb.'_savemsg'.$idx} = $env{'form.savemsg'.$ctr};
1.119     ng       2547: 		$idx++;
                   2548: 	    }
                   2549: 	    $ctr++;
1.41      ng       2550: 	}
1.119     ng       2551: 	$ctr = 0;
                   2552: 	while ($ctr < $ngrade) {
1.257     albertel 2553: 	    if ($env{'form.newmsg'.$ctr} ne '') {
                   2554: 		$keyhash{$symb.'_savemsg'.$idx} = $env{'form.newmsg'.$ctr};
                   2555: 		$env{'form.savemsg'.$idx} = $env{'form.newmsg'.$ctr};
1.119     ng       2556: 		$idx++;
                   2557: 	    }
                   2558: 	    $ctr++;
1.41      ng       2559: 	}
1.257     albertel 2560: 	$env{'form.savemsgN'} = --$idx;
                   2561: 	$keyhash{$symb.'_savemsgN'} = $env{'form.savemsgN'};
1.119     ng       2562: 	my $putresult = &Apache::lonnet::put
1.301     albertel 2563: 	    ('nohist_handgrade',\%keyhash,$cdom,$cnum);
1.41      ng       2564:     }
1.44      ng       2565:     # Called by Save & Refresh from Highlight Attribute Window
1.257     albertel 2566:     my (undef,undef,$fullname) = &getclasslist($env{'form.section'},'1');
                   2567:     if ($env{'form.refresh'} eq 'on') {
1.86      ng       2568: 	my ($ctr,$total) = (0,0);
                   2569: 	while ($ctr < $ngrade) {
1.257     albertel 2570: 	    $total++ if  $env{'form.unamedom'.$ctr} ne '';
1.86      ng       2571: 	    $ctr++;
                   2572: 	}
1.257     albertel 2573: 	$env{'form.NTSTU'}=$ngrade;
1.86      ng       2574: 	$ctr = 0;
                   2575: 	while ($ctr < $total) {
1.257     albertel 2576: 	    my $processUser = $env{'form.unamedom'.$ctr};
                   2577: 	    ($env{'form.student'},$env{'form.userdom'}) = split(/:/,$processUser);
                   2578: 	    $env{'form.fullname'} = $$fullname{$processUser};
1.625     www      2579: 	    &submission($request,$ctr,$total-1,$symb);
1.41      ng       2580: 	    $ctr++;
                   2581: 	}
                   2582: 	return '';
                   2583:     }
1.36      ng       2584: 
1.44      ng       2585:     # Get the next/previous one or group of students
1.257     albertel 2586:     my $firststu = $env{'form.unamedom0'};
                   2587:     my $laststu = $env{'form.unamedom'.($ngrade-1)};
1.119     ng       2588:     my $ctr = 2;
1.41      ng       2589:     while ($laststu eq '') {
1.257     albertel 2590: 	$laststu  = $env{'form.unamedom'.($ngrade-$ctr)};
1.41      ng       2591: 	$ctr++;
                   2592: 	$laststu = $firststu if ($ctr > $ngrade);
                   2593:     }
1.44      ng       2594: 
1.41      ng       2595:     my (@parsedlist,@nextlist);
                   2596:     my ($nextflg) = 0;
1.524     raeburn  2597:     foreach my $item (sort 
1.294     albertel 2598: 	     {
                   2599: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                   2600: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                   2601: 		 }
                   2602: 		 return $a cmp $b;
                   2603: 	     } (keys(%$fullname))) {
1.605     www      2604: # FIXME: this is fishy, looks like the button label
1.41      ng       2605: 	if ($nextflg == 1 && $button =~ /Next$/) {
1.524     raeburn  2606: 	    push(@parsedlist,$item);
1.41      ng       2607: 	}
1.524     raeburn  2608: 	$nextflg = 1 if ($item eq $laststu);
1.41      ng       2609: 	if ($button eq 'Previous') {
1.524     raeburn  2610: 	    last if ($item eq $firststu);
                   2611: 	    push(@parsedlist,$item);
1.41      ng       2612: 	}
                   2613:     }
                   2614:     $ctr = 0;
1.605     www      2615: # FIXME: this is fishy, looks like the button label
1.41      ng       2616:     @parsedlist = reverse @parsedlist if ($button eq 'Previous');
1.582     raeburn  2617:     my $res_error;
                   2618:     my ($partlist) = &response_type($symb,\$res_error);
                   2619:     if ($res_error) {
                   2620:         $request->print(&navmap_errormsg());
                   2621:         return;
                   2622:     }
1.41      ng       2623:     foreach my $student (@parsedlist) {
1.257     albertel 2624: 	my $submitonly=$env{'form.submitonly'};
1.41      ng       2625: 	my ($uname,$udom) = split(/:/,$student);
1.301     albertel 2626: 	
                   2627: 	if ($submitonly eq 'queued') {
                   2628: 	    my %queue_status = 
                   2629: 		&Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
                   2630: 							$udom,$uname);
                   2631: 	    next if (!defined($queue_status{'gradingqueue'}));
                   2632: 	}
                   2633: 
1.156     albertel 2634: 	if ($submitonly =~ /^(yes|graded|incorrect)$/) {
1.257     albertel 2635: #	    my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
1.324     albertel 2636: 	    my %status=&student_gradeStatus($symb,$udom,$uname,$partlist);
1.145     albertel 2637: 	    my $submitted = 0;
1.248     albertel 2638: 	    my $ungraded = 0;
                   2639: 	    my $incorrect = 0;
1.524     raeburn  2640: 	    foreach my $item (keys(%status)) {
                   2641: 		$submitted = 1 if ($status{$item} ne 'nothing');
                   2642: 		$ungraded = 1 if ($status{$item} =~ /^ungraded/);
                   2643: 		$incorrect = 1 if ($status{$item} =~ /^incorrect/);
                   2644: 		my ($foo,$partid,$foo1) = split(/\./,$item);
1.145     albertel 2645: 		if ($status{'resource.'.$partid.'.submitted_by'} ne '') {
                   2646: 		    $submitted = 0;
                   2647: 		}
1.41      ng       2648: 	    }
1.156     albertel 2649: 	    next if (!$submitted && ($submitonly eq 'yes' ||
                   2650: 				     $submitonly eq 'incorrect' ||
                   2651: 				     $submitonly eq 'graded'));
1.248     albertel 2652: 	    next if (!$ungraded && ($submitonly eq 'graded'));
                   2653: 	    next if (!$incorrect && $submitonly eq 'incorrect');
1.41      ng       2654: 	}
1.524     raeburn  2655: 	push(@nextlist,$student) if ($ctr < $ntstu);
1.129     ng       2656: 	last if ($ctr == $ntstu);
1.41      ng       2657: 	$ctr++;
                   2658:     }
1.36      ng       2659: 
1.41      ng       2660:     $ctr = 0;
                   2661:     my $total = scalar(@nextlist)-1;
1.39      ng       2662: 
1.524     raeburn  2663:     foreach (sort(@nextlist)) {
1.41      ng       2664: 	my ($uname,$udom,$submitter) = split(/:/);
1.257     albertel 2665: 	$env{'form.student'}  = $uname;
                   2666: 	$env{'form.userdom'}  = $udom;
                   2667: 	$env{'form.fullname'} = $$fullname{$_};
1.625     www      2668: 	&submission($request,$ctr,$total,$symb);
1.41      ng       2669: 	$ctr++;
                   2670:     }
                   2671:     if ($total < 0) {
1.632     www      2672: 	my $the_end.=&mt('<b>Message: </b> No more students for this section or class.').'<br /><br />'."\n";
1.41      ng       2673: 	$request->print($the_end);
                   2674:     }
                   2675:     return '';
1.38      ng       2676: }
1.36      ng       2677: 
1.44      ng       2678: #---- Save the score and award for each student, if changed
1.38      ng       2679: sub saveHandGrade {
1.324     albertel 2680:     my ($request,$symb,$stuname,$domain,$newflg,$submitter,$part) = @_;
1.342     banghart 2681:     my @version_parts;
1.104     albertel 2682:     my $usec = &Apache::lonnet::getsection($domain,$stuname,
1.257     albertel 2683: 					   $env{'request.course.id'});
1.104     albertel 2684:     if (!&canmodify($usec)) { return('not_allowed'); }
1.337     banghart 2685:     my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$domain,$stuname);
1.251     banghart 2686:     my @parts_graded;
1.77      ng       2687:     my %newrecord  = ();
                   2688:     my ($pts,$wgt) = ('','');
1.269     raeburn  2689:     my %aggregate = ();
                   2690:     my $aggregateflag = 0;
1.301     albertel 2691:     my @parts = split(/:/,$env{'form.partlist'.$newflg});
                   2692:     foreach my $new_part (@parts) {
1.337     banghart 2693: 	#collaborator ($submi may vary for different parts
1.259     banghart 2694: 	if ($submitter && $new_part ne $part) { next; }
                   2695: 	my $dropMenu = $env{'form.GD_SEL'.$newflg.'_'.$new_part};
1.125     ng       2696: 	if ($dropMenu eq 'excused') {
1.259     banghart 2697: 	    if ($record{'resource.'.$new_part.'.solved'} ne 'excused') {
                   2698: 		$newrecord{'resource.'.$new_part.'.solved'} = 'excused';
                   2699: 		if (exists($record{'resource.'.$new_part.'.awarded'})) {
                   2700: 		    $newrecord{'resource.'.$new_part.'.awarded'} = '';
1.58      albertel 2701: 		}
1.364     banghart 2702: 	        $newrecord{'resource.'.$new_part.'.regrader'}="$env{'user.name'}:$env{'user.domain'}";
1.58      albertel 2703: 	    }
1.125     ng       2704: 	} elsif ($dropMenu eq 'reset status'
1.259     banghart 2705: 		 && exists($record{'resource.'.$new_part.'.solved'})) { #don't bother if no old records -> no attempts
1.524     raeburn  2706: 	    foreach my $key (keys(%record)) {
1.259     banghart 2707: 		if ($key=~/^resource\.\Q$new_part\E\./) { $newrecord{$key} = ''; }
1.197     albertel 2708: 	    }
1.259     banghart 2709: 	    $newrecord{'resource.'.$new_part.'.regrader'}=
1.257     albertel 2710: 		"$env{'user.name'}:$env{'user.domain'}";
1.270     albertel 2711:             my $totaltries = $record{'resource.'.$part.'.tries'};
                   2712: 
                   2713:             my %last_resets = &get_last_resets($symb,$env{'request.course.id'},
                   2714: 					       [$new_part]);
                   2715:             my $aggtries =$totaltries;
1.269     raeburn  2716:             if ($last_resets{$new_part}) {
1.270     albertel 2717:                 $aggtries = &get_num_tries(\%record,$last_resets{$new_part},
                   2718: 					   $new_part);
1.269     raeburn  2719:             }
1.270     albertel 2720: 
                   2721:             my $solvedstatus = $record{'resource.'.$new_part.'.solved'};
1.269     raeburn  2722:             if ($aggtries > 0) {
1.327     albertel 2723:                 &decrement_aggs($symb,$new_part,\%aggregate,$aggtries,$totaltries,$solvedstatus);
1.269     raeburn  2724:                 $aggregateflag = 1;
                   2725:             }
1.125     ng       2726: 	} elsif ($dropMenu eq '') {
1.259     banghart 2727: 	    $pts = ($env{'form.GD_BOX'.$newflg.'_'.$new_part} ne '' ? 
                   2728: 		    $env{'form.GD_BOX'.$newflg.'_'.$new_part} : 
                   2729: 		    $env{'form.RADVAL'.$newflg.'_'.$new_part});
                   2730: 	    if ($pts eq '' && $env{'form.GD_SEL'.$newflg.'_'.$new_part} eq '') {
1.153     albertel 2731: 		next;
                   2732: 	    }
1.259     banghart 2733: 	    $wgt = $env{'form.WGT'.$newflg.'_'.$new_part} eq '' ? 1 : 
                   2734: 		$env{'form.WGT'.$newflg.'_'.$new_part};
1.41      ng       2735: 	    my $partial= $pts/$wgt;
1.259     banghart 2736: 	    if ($partial eq $record{'resource.'.$new_part.'.awarded'}) {
1.153     albertel 2737: 		#do not update score for part if not changed.
1.346     banghart 2738:                 &handback_files($request,$symb,$stuname,$domain,$newflg,$new_part,\%newrecord);
1.153     albertel 2739: 		next;
1.251     banghart 2740: 	    } else {
1.524     raeburn  2741: 	        push(@parts_graded,$new_part);
1.153     albertel 2742: 	    }
1.259     banghart 2743: 	    if ($record{'resource.'.$new_part.'.awarded'} ne $partial) {
                   2744: 		$newrecord{'resource.'.$new_part.'.awarded'}  = $partial;
1.153     albertel 2745: 	    }
1.259     banghart 2746: 	    my $reckey = 'resource.'.$new_part.'.solved';
1.41      ng       2747: 	    if ($partial == 0) {
1.153     albertel 2748: 		if ($record{$reckey} ne 'incorrect_by_override') {
                   2749: 		    $newrecord{$reckey} = 'incorrect_by_override';
                   2750: 		}
1.41      ng       2751: 	    } else {
1.153     albertel 2752: 		if ($record{$reckey} ne 'correct_by_override') {
                   2753: 		    $newrecord{$reckey} = 'correct_by_override';
                   2754: 		}
                   2755: 	    }	    
                   2756: 	    if ($submitter && 
1.259     banghart 2757: 		($record{'resource.'.$new_part.'.submitted_by'} ne $submitter)) {
                   2758: 		$newrecord{'resource.'.$new_part.'.submitted_by'} = $submitter;
1.41      ng       2759: 	    }
1.259     banghart 2760: 	    $newrecord{'resource.'.$new_part.'.regrader'}=
1.257     albertel 2761: 		"$env{'user.name'}:$env{'user.domain'}";
1.41      ng       2762: 	}
1.259     banghart 2763: 	# unless problem has been graded, set flag to version the submitted files
1.305     banghart 2764: 	unless ($record{'resource.'.$new_part.'.solved'} =~ /^correct_/  || 
                   2765: 	        $record{'resource.'.$new_part.'.solved'} eq 'incorrect_by_override' ||
                   2766: 	        $dropMenu eq 'reset status')
                   2767: 	   {
1.524     raeburn  2768: 	    push(@version_parts,$new_part);
1.259     banghart 2769: 	}
1.41      ng       2770:     }
1.301     albertel 2771:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   2772:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   2773: 
1.344     albertel 2774:     if (%newrecord) {
                   2775:         if (@version_parts) {
1.364     banghart 2776:             my @changed_keys = &version_portfiles(\%record, \@parts_graded, 
                   2777:                                 $env{'request.course.id'}, $symb, $domain, $stuname, \@version_parts);
1.344     albertel 2778: 	    @newrecord{@changed_keys} = @record{@changed_keys};
1.367     albertel 2779: 	    foreach my $new_part (@version_parts) {
                   2780: 		&handback_files($request,$symb,$stuname,$domain,$newflg,
                   2781: 				$new_part,\%newrecord);
                   2782: 	    }
1.259     banghart 2783:         }
1.44      ng       2784: 	&Apache::lonnet::cstore(\%newrecord,$symb,
1.257     albertel 2785: 				$env{'request.course.id'},$domain,$stuname);
1.380     albertel 2786: 	&check_and_remove_from_queue(\@parts,\%record,\%newrecord,$symb,
                   2787: 				     $cdom,$cnum,$domain,$stuname);
1.41      ng       2788:     }
1.269     raeburn  2789:     if ($aggregateflag) {
                   2790:         &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
1.301     albertel 2791: 			      $cdom,$cnum);
1.269     raeburn  2792:     }
1.301     albertel 2793:     return ('',$pts,$wgt);
1.36      ng       2794: }
1.322     albertel 2795: 
1.380     albertel 2796: sub check_and_remove_from_queue {
                   2797:     my ($parts,$record,$newrecord,$symb,$cdom,$cnum,$domain,$stuname) = @_;
                   2798:     my @ungraded_parts;
                   2799:     foreach my $part (@{$parts}) {
                   2800: 	if (    $record->{   'resource.'.$part.'.awarded'} eq ''
                   2801: 	     && $record->{   'resource.'.$part.'.solved' } ne 'excused'
                   2802: 	     && $newrecord->{'resource.'.$part.'.awarded'} eq ''
                   2803: 	     && $newrecord->{'resource.'.$part.'.solved' } ne 'excused'
                   2804: 		) {
                   2805: 	    push(@ungraded_parts, $part);
                   2806: 	}
                   2807:     }
                   2808:     if ( !@ungraded_parts ) {
                   2809: 	&Apache::bridgetask::remove_from_queue('gradingqueue',$symb,$cdom,
                   2810: 					       $cnum,$domain,$stuname);
                   2811:     }
                   2812: }
                   2813: 
1.337     banghart 2814: sub handback_files {
                   2815:     my ($request,$symb,$stuname,$domain,$newflg,$new_part,$newrecord) = @_;
1.517     raeburn  2816:     my $portfolio_root = '/userfiles/portfolio';
1.582     raeburn  2817:     my $res_error;
                   2818:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
                   2819:     if ($res_error) {
                   2820:         $request->print('<br />'.&navmap_errormsg().'<br />');
                   2821:         return;
                   2822:     }
1.375     albertel 2823:     my @part_response_id = &flatten_responseType($responseType);
                   2824:     foreach my $part_response_id (@part_response_id) {
                   2825:     	my ($part_id,$resp_id) = @{ $part_response_id };
                   2826: 	my $part_resp = join('_',@{ $part_response_id });
1.337     banghart 2827:             if (($env{'form.'.$newflg.'_'.$part_resp.'_returndoc1'}) && ($new_part == $part_id)) {
                   2828:                 # if multiple files are uploaded names will be 'returndoc2','returndoc3'
                   2829:                 my $file_counter = 1;
1.367     albertel 2830: 		my $file_msg;
1.337     banghart 2831:                 while ($env{'form.'.$newflg.'_'.$part_resp.'_returndoc'.$file_counter}) {
                   2832:                     my $fname=$env{'form.'.$newflg.'_'.$part_resp.'_returndoc'.$file_counter.'.filename'};
1.338     banghart 2833:                     my ($directory,$answer_file) = 
                   2834:                         ($env{'form.'.$newflg.'_'.$part_resp.'_origdoc'.$file_counter} =~ /^(.*?)([^\/]*)$/);
                   2835:                     my ($answer_name,$answer_ver,$answer_ext) =
                   2836: 		        &file_name_version_ext($answer_file);
1.355     banghart 2837: 		    my ($portfolio_path) = ($directory =~ /^.+$stuname\/portfolio(.*)/);
1.517     raeburn  2838:                     my $getpropath = 1;
                   2839: 		    my @dir_list = &Apache::lonnet::dirlist($portfolio_root.$portfolio_path,$domain,$stuname,$getpropath);
1.338     banghart 2840: 		    my $version = &get_next_version($answer_name, $answer_ext, \@dir_list);
1.355     banghart 2841:                     # fix file name
                   2842:                     my ($save_file_name) = (($directory.$answer_name.".$version.".$answer_ext) =~ /^.+\/${stuname}\/(.*)/);
                   2843:                     my $result=&Apache::lonnet::finishuserfileupload($stuname,$domain,
                   2844:             	                                $newflg.'_'.$part_resp.'_returndoc'.$file_counter,
                   2845:             	                                $save_file_name);
1.337     banghart 2846:                     if ($result !~ m|^/uploaded/|) {
1.536     raeburn  2847:                         $request->print('<br /><span class="LC_error">'.
                   2848:                             &mt('An error occurred ([_1]) while trying to upload [_2].',
                   2849:                                 $result,$newflg.'_'.$part_resp.'_returndoc'.$file_counter).
                   2850:                                         '</span>');
1.356     banghart 2851:                     } else {
1.360     banghart 2852:                         # mark the file as read only
                   2853:                         my @files = ($save_file_name);
1.372     albertel 2854:                         my @what = ($symb,$env{'request.course.id'},'handback');
1.360     banghart 2855:                         &Apache::lonnet::mark_as_readonly($domain,$stuname,\@files,\@what);
1.367     albertel 2856: 			if (exists($$newrecord{"resource.$new_part.$resp_id.handback"})) {
                   2857: 			    $$newrecord{"resource.$new_part.$resp_id.handback"}.=',';
                   2858: 			}
                   2859:                         $$newrecord{"resource.$new_part.$resp_id.handback"} .= $save_file_name;
                   2860: 			$file_msg.= "\n".'<br /><span class="LC_filename"><a href="/uploaded/'."$domain/$stuname/".$save_file_name.'">'.$save_file_name."</a></span><br />";
                   2861: 
1.337     banghart 2862:                     }
                   2863:                     $request->print("<br />".$fname." will be the uploaded file name");
1.354     albertel 2864:                     $request->print(" ".$env{'form.'.$newflg.'_'.$part_resp.'_origdoc'.$file_counter});
1.337     banghart 2865:                     $file_counter++;
                   2866:                 }
1.367     albertel 2867: 		my $subject = "File Handed Back by Instructor ";
                   2868: 		my $message = "A file has been returned that was originally submitted in reponse to: <br />";
                   2869: 		$message .= "<strong>".&Apache::lonnet::gettitle($symb)."</strong><br />";
                   2870: 		$message .= ' The returned file(s) are named: '. $file_msg;
                   2871: 		$message .= " and can be found in your portfolio space.";
1.418     albertel 2872: 		my ($feedurl,$showsymb) = 
                   2873: 		    &get_feedurl_and_symb($symb,$domain,$stuname);
1.386     raeburn  2874:                 my $restitle = &Apache::lonnet::gettitle($symb);
                   2875: 		my $msgstatus = 
                   2876:                    &Apache::lonmsg::user_normal_msg($stuname,$domain,$subject.
                   2877: 			 ' (File Returned) ['.$restitle.']',$message,undef,
1.418     albertel 2878:                          $feedurl,undef,undef,undef,$showsymb,$restitle);
1.337     banghart 2879:             }
                   2880:         }
1.338     banghart 2881:     return;
1.337     banghart 2882: }
                   2883: 
1.418     albertel 2884: sub get_feedurl_and_symb {
                   2885:     my ($symb,$uname,$udom) = @_;
                   2886:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
                   2887:     $url = &Apache::lonnet::clutter($url);
                   2888:     my $encrypturl=&Apache::lonnet::EXT('resource.0.encrypturl',
                   2889: 					$symb,$udom,$uname);
                   2890:     if ($encrypturl =~ /^yes$/i) {
                   2891: 	&Apache::lonenc::encrypted(\$url,1);
                   2892: 	&Apache::lonenc::encrypted(\$symb,1);
                   2893:     }
                   2894:     return ($url,$symb);
                   2895: }
                   2896: 
1.313     banghart 2897: sub get_submitted_files {
                   2898:     my ($udom,$uname,$partid,$respid,$record) = @_;
                   2899:     my @files;
                   2900:     if ($$record{"resource.$partid.$respid.portfiles"}) {
                   2901:         my $file_url = '/uploaded/'.$udom.'/'.$uname.'/portfolio';
                   2902:         foreach my $file (split(',',$$record{"resource.$partid.$respid.portfiles"})) {
                   2903:     	    push(@files,$file_url.$file);
                   2904:         }
                   2905:     }
                   2906:     if ($$record{"resource.$partid.$respid.uploadedurl"}) {
                   2907:         push(@files,$$record{"resource.$partid.$respid.uploadedurl"});
                   2908:     }
                   2909:     return (\@files);
                   2910: }
1.322     albertel 2911: 
1.269     raeburn  2912: # ----------- Provides number of tries since last reset.
                   2913: sub get_num_tries {
                   2914:     my ($record,$last_reset,$part) = @_;
                   2915:     my $timestamp = '';
                   2916:     my $num_tries = 0;
                   2917:     if ($$record{'version'}) {
                   2918:         for (my $version=$$record{'version'};$version>=1;$version--) {
                   2919:             if (exists($$record{$version.':resource.'.$part.'.solved'})) {
                   2920:                 $timestamp = $$record{$version.':timestamp'};
                   2921:                 if ($timestamp > $last_reset) {
                   2922:                     $num_tries ++;
                   2923:                 } else {
                   2924:                     last;
                   2925:                 }
                   2926:             }
                   2927:         }
                   2928:     }
                   2929:     return $num_tries;
                   2930: }
                   2931: 
                   2932: # ----------- Determine decrements required in aggregate totals 
                   2933: sub decrement_aggs {
                   2934:     my ($symb,$part,$aggregate,$aggtries,$totaltries,$solvedstatus) = @_;
                   2935:     my %decrement = (
                   2936:                         attempts => 0,
                   2937:                         users => 0,
                   2938:                         correct => 0
                   2939:                     );
                   2940:     $decrement{'attempts'} = $aggtries;
                   2941:     if ($solvedstatus =~ /^correct/) {
                   2942:         $decrement{'correct'} = 1;
                   2943:     }
                   2944:     if ($aggtries == $totaltries) {
                   2945:         $decrement{'users'} = 1;
                   2946:     }
1.524     raeburn  2947:     foreach my $type (keys(%decrement)) {
1.269     raeburn  2948:         $$aggregate{$symb."\0".$part."\0".$type} = -$decrement{$type};
                   2949:     }
                   2950:     return;
                   2951: }
                   2952: 
                   2953: # ----------- Determine timestamps for last reset of aggregate totals for parts  
                   2954: sub get_last_resets {
1.270     albertel 2955:     my ($symb,$courseid,$partids) =@_;
                   2956:     my %last_resets;
1.269     raeburn  2957:     my $cdom = $env{'course.'.$courseid.'.domain'};
                   2958:     my $cname = $env{'course.'.$courseid.'.num'};
1.271     albertel 2959:     my @keys;
                   2960:     foreach my $part (@{$partids}) {
                   2961: 	push(@keys,"$symb\0$part\0resettime");
                   2962:     }
                   2963:     my %results=&Apache::lonnet::get('nohist_resourcetracker',\@keys,
                   2964: 				     $cdom,$cname);
                   2965:     foreach my $part (@{$partids}) {
                   2966: 	$last_resets{$part}=$results{"$symb\0$part\0resettime"};
1.269     raeburn  2967:     }
1.270     albertel 2968:     return %last_resets;
1.269     raeburn  2969: }
                   2970: 
1.251     banghart 2971: # ----------- Handles creating versions for portfolio files as answers
                   2972: sub version_portfiles {
1.343     banghart 2973:     my ($record, $parts_graded, $courseid, $symb, $domain, $stu_name, $v_flag) = @_;
1.263     banghart 2974:     my $version_parts = join('|',@$v_flag);
1.343     banghart 2975:     my @returned_keys;
1.255     banghart 2976:     my $parts = join('|', @$parts_graded);
1.517     raeburn  2977:     my $portfolio_root = '/userfiles/portfolio';
1.277     albertel 2978:     foreach my $key (keys(%$record)) {
1.259     banghart 2979:         my $new_portfiles;
1.263     banghart 2980:         if ($key =~ /^resource\.($version_parts)\./ && $key =~ /\.portfiles$/ ) {
1.342     banghart 2981:             my @versioned_portfiles;
1.367     albertel 2982:             my @portfiles = split(/\s*,\s*/,$$record{$key});
1.252     banghart 2983:             foreach my $file (@portfiles) {
1.306     banghart 2984:                 &Apache::lonnet::unmark_as_readonly($domain,$stu_name,[$symb,$env{'request.course.id'}],$file);
1.304     albertel 2985:                 my ($directory,$answer_file) =($file =~ /^(.*?)([^\/]*)$/);
                   2986: 		my ($answer_name,$answer_ver,$answer_ext) =
                   2987: 		    &file_name_version_ext($answer_file);
1.517     raeburn  2988:                 my $getpropath = 1;    
                   2989:                 my @dir_list = &Apache::lonnet::dirlist($portfolio_root.$directory,$domain,$stu_name,$getpropath);
1.342     banghart 2990:                 my $version = &get_next_version($answer_name, $answer_ext, \@dir_list);
1.306     banghart 2991:                 my $new_answer = &version_selected_portfile($domain, $stu_name, $directory, $answer_file, $version);
                   2992:                 if ($new_answer ne 'problem getting file') {
1.342     banghart 2993:                     push(@versioned_portfiles, $directory.$new_answer);
1.306     banghart 2994:                     &Apache::lonnet::mark_as_readonly($domain,$stu_name,
1.367     albertel 2995:                         [$directory.$new_answer],
1.306     banghart 2996:                         [$symb,$env{'request.course.id'},'graded']);
1.259     banghart 2997:                 }
1.252     banghart 2998:             }
1.343     banghart 2999:             $$record{$key} = join(',',@versioned_portfiles);
                   3000:             push(@returned_keys,$key);
1.251     banghart 3001:         }
                   3002:     } 
1.343     banghart 3003:     return (@returned_keys);   
1.305     banghart 3004: }
                   3005: 
1.307     banghart 3006: sub get_next_version {
1.341     banghart 3007:     my ($answer_name, $answer_ext, $dir_list) = @_;
1.307     banghart 3008:     my $version;
                   3009:     foreach my $row (@$dir_list) {
                   3010:         my ($file) = split(/\&/,$row,2);
                   3011:         my ($file_name,$file_version,$file_ext) =
                   3012: 	    &file_name_version_ext($file);
                   3013:         if (($file_name eq $answer_name) && 
                   3014: 	    ($file_ext eq $answer_ext)) {
                   3015:                 # gets here if filename and extension match, regardless of version
                   3016:                 if ($file_version ne '') {
                   3017:                 # a versioned file is found  so save it for later
                   3018:                 if ($file_version > $version) {
                   3019: 		    $version = $file_version;
                   3020: 	        }
                   3021:             }
                   3022:         }
                   3023:     } 
                   3024:     $version ++;
                   3025:     return($version);
                   3026: }
                   3027: 
1.305     banghart 3028: sub version_selected_portfile {
1.306     banghart 3029:     my ($domain,$stu_name,$directory,$file_name,$version) = @_;
                   3030:     my ($answer_name,$answer_ver,$answer_ext) =
                   3031:         &file_name_version_ext($file_name);
                   3032:     my $new_answer;
                   3033:     $env{'form.copy'} = &Apache::lonnet::getfile("/uploaded/$domain/$stu_name/portfolio$directory$file_name");
                   3034:     if($env{'form.copy'} eq '-1') {
                   3035:         $new_answer = 'problem getting file';
                   3036:     } else {
                   3037:         $new_answer = $answer_name.'.'.$version.'.'.$answer_ext;
                   3038:         my $copy_result = &Apache::lonnet::finishuserfileupload(
                   3039:                             $stu_name,$domain,'copy',
                   3040: 		        '/portfolio'.$directory.$new_answer);
                   3041:     }    
                   3042:     return ($new_answer);
1.251     banghart 3043: }
                   3044: 
1.304     albertel 3045: sub file_name_version_ext {
                   3046:     my ($file)=@_;
                   3047:     my @file_parts = split(/\./, $file);
                   3048:     my ($name,$version,$ext);
                   3049:     if (@file_parts > 1) {
                   3050: 	$ext=pop(@file_parts);
                   3051: 	if (@file_parts > 1 && $file_parts[-1] =~ /^\d+$/) {
                   3052: 	    $version=pop(@file_parts);
                   3053: 	}
                   3054: 	$name=join('.',@file_parts);
                   3055:     } else {
                   3056: 	$name=join('.',@file_parts);
                   3057:     }
                   3058:     return($name,$version,$ext);
                   3059: }
                   3060: 
1.44      ng       3061: #--------------------------------------------------------------------------------------
                   3062: #
                   3063: #-------------------------- Next few routines handles grading by section or whole class
                   3064: #
                   3065: #--- Javascript to handle grading by section or whole class
1.42      ng       3066: sub viewgrades_js {
                   3067:     my ($request) = shift;
                   3068: 
1.539     riegler  3069:     my $alertmsg = &mt('A number equal or greater than 0 is expected. Entered value = ');
1.597     wenzelju 3070:     $request->print(&Apache::lonhtmlcommon::scripttag(<<VIEWJAVASCRIPT));
1.45      ng       3071:    function writePoint(partid,weight,point) {
1.125     ng       3072: 	var radioButton = document.classgrade["RADVAL_"+partid];
                   3073: 	var textbox = document.classgrade["TEXTVAL_"+partid];
1.42      ng       3074: 	if (point == "textval") {
1.125     ng       3075: 	    point = document.classgrade["TEXTVAL_"+partid].value;
1.109     matthew  3076: 	    if (isNaN(point) || parseFloat(point) < 0) {
1.539     riegler  3077: 		alert("$alertmsg"+parseFloat(point));
1.42      ng       3078: 		var resetbox = false;
                   3079: 		for (var i=0; i<radioButton.length; i++) {
                   3080: 		    if (radioButton[i].checked) {
                   3081: 			textbox.value = i;
                   3082: 			resetbox = true;
                   3083: 		    }
                   3084: 		}
                   3085: 		if (!resetbox) {
                   3086: 		    textbox.value = "";
                   3087: 		}
                   3088: 		return;
                   3089: 	    }
1.109     matthew  3090: 	    if (parseFloat(point) > parseFloat(weight)) {
                   3091: 		var resp = confirm("You entered a value ("+parseFloat(point)+
1.44      ng       3092: 				   ") greater than the weight for the part. Accept?");
                   3093: 		if (resp == false) {
                   3094: 		    textbox.value = "";
                   3095: 		    return;
                   3096: 		}
                   3097: 	    }
1.42      ng       3098: 	    for (var i=0; i<radioButton.length; i++) {
                   3099: 		radioButton[i].checked=false;
1.109     matthew  3100: 		if (parseFloat(point) == i) {
1.42      ng       3101: 		    radioButton[i].checked=true;
                   3102: 		}
                   3103: 	    }
1.41      ng       3104: 
1.42      ng       3105: 	} else {
1.125     ng       3106: 	    textbox.value = parseFloat(point);
1.42      ng       3107: 	}
1.41      ng       3108: 	for (i=0;i<document.classgrade.total.value;i++) {
1.125     ng       3109: 	    var user = document.classgrade["ctr"+i].value;
1.289     albertel 3110: 	    user = user.replace(new RegExp(':', 'g'),"_");
1.125     ng       3111: 	    var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
                   3112: 	    var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
                   3113: 	    var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
1.42      ng       3114: 	    if (saveval != "correct") {
                   3115: 		scorename.value = point;
1.43      ng       3116: 		if (selname[0].selected != true) {
                   3117: 		    selname[0].selected = true;
                   3118: 		}
1.42      ng       3119: 	    }
                   3120: 	}
1.125     ng       3121: 	document.classgrade["SELVAL_"+partid][0].selected = true;
1.42      ng       3122:     }
                   3123: 
                   3124:     function writeRadText(partid,weight) {
1.125     ng       3125: 	var selval   = document.classgrade["SELVAL_"+partid];
                   3126: 	var radioButton = document.classgrade["RADVAL_"+partid];
1.265     www      3127:         var override = document.classgrade["FORCE_"+partid].checked;
1.125     ng       3128: 	var textbox = document.classgrade["TEXTVAL_"+partid];
                   3129: 	if (selval[1].selected || selval[2].selected) {
1.42      ng       3130: 	    for (var i=0; i<radioButton.length; i++) {
                   3131: 		radioButton[i].checked=false;
                   3132: 
                   3133: 	    }
                   3134: 	    textbox.value = "";
                   3135: 
                   3136: 	    for (i=0;i<document.classgrade.total.value;i++) {
1.125     ng       3137: 		var user = document.classgrade["ctr"+i].value;
1.289     albertel 3138: 		user = user.replace(new RegExp(':', 'g'),"_");
1.125     ng       3139: 		var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
                   3140: 		var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
                   3141: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
1.265     www      3142: 		if ((saveval != "correct") || override) {
1.42      ng       3143: 		    scorename.value = "";
1.125     ng       3144: 		    if (selval[1].selected) {
                   3145: 			selname[1].selected = true;
                   3146: 		    } else {
                   3147: 			selname[2].selected = true;
                   3148: 			if (Number(document.classgrade["GD_"+user+"_"+partid+"_tries"].value)) 
                   3149: 			{document.classgrade["GD_"+user+"_"+partid+"_tries"].value = '0';}
                   3150: 		    }
1.42      ng       3151: 		}
                   3152: 	    }
1.43      ng       3153: 	} else {
                   3154: 	    for (i=0;i<document.classgrade.total.value;i++) {
1.125     ng       3155: 		var user = document.classgrade["ctr"+i].value;
1.289     albertel 3156: 		user = user.replace(new RegExp(':', 'g'),"_");
1.125     ng       3157: 		var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
                   3158: 		var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
                   3159: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
1.265     www      3160: 		if ((saveval != "correct") || override) {
1.125     ng       3161: 		    scorename.value = document.classgrade["GD_"+user+"_"+partid+"_awarded_s"].value;
1.43      ng       3162: 		    selname[0].selected = true;
                   3163: 		}
                   3164: 	    }
                   3165: 	}	    
1.42      ng       3166:     }
                   3167: 
                   3168:     function changeSelect(partid,user) {
1.125     ng       3169: 	var selval = document.classgrade["GD_"+user+'_'+partid+"_solved"];
                   3170: 	var textbox = document.classgrade["GD_"+user+'_'+partid+"_awarded"];
1.44      ng       3171: 	var point  = textbox.value;
1.125     ng       3172: 	var weight = document.classgrade["weight_"+partid].value;
1.44      ng       3173: 
1.109     matthew  3174: 	if (isNaN(point) || parseFloat(point) < 0) {
1.539     riegler  3175: 	    alert("$alertmsg"+parseFloat(point));
1.44      ng       3176: 	    textbox.value = "";
                   3177: 	    return;
                   3178: 	}
1.109     matthew  3179: 	if (parseFloat(point) > parseFloat(weight)) {
                   3180: 	    var resp = confirm("You entered a value ("+parseFloat(point)+
1.44      ng       3181: 			       ") greater than the weight of the part. Accept?");
                   3182: 	    if (resp == false) {
                   3183: 		textbox.value = "";
                   3184: 		return;
                   3185: 	    }
                   3186: 	}
1.42      ng       3187: 	selval[0].selected = true;
                   3188:     }
                   3189: 
                   3190:     function changeOneScore(partid,user) {
1.125     ng       3191: 	var selval = document.classgrade["GD_"+user+'_'+partid+"_solved"];
                   3192: 	if (selval[1].selected || selval[2].selected) {
                   3193: 	    document.classgrade["GD_"+user+'_'+partid+"_awarded"].value = "";
                   3194: 	    if (selval[2].selected) {
                   3195: 		document.classgrade["GD_"+user+'_'+partid+"_tries"].value = "0";
                   3196: 	    }
1.269     raeburn  3197:         }
1.42      ng       3198:     }
                   3199: 
                   3200:     function resetEntry(numpart) {
                   3201: 	for (ctpart=0;ctpart<numpart;ctpart++) {
1.125     ng       3202: 	    var partid = document.classgrade["partid_"+ctpart].value;
                   3203: 	    var radioButton = document.classgrade["RADVAL_"+partid];
                   3204: 	    var textbox = document.classgrade["TEXTVAL_"+partid];
                   3205: 	    var selval  = document.classgrade["SELVAL_"+partid];
1.42      ng       3206: 	    for (var i=0; i<radioButton.length; i++) {
                   3207: 		radioButton[i].checked=false;
                   3208: 
                   3209: 	    }
                   3210: 	    textbox.value = "";
                   3211: 	    selval[0].selected = true;
                   3212: 
                   3213: 	    for (i=0;i<document.classgrade.total.value;i++) {
1.125     ng       3214: 		var user = document.classgrade["ctr"+i].value;
1.289     albertel 3215: 		user = user.replace(new RegExp(':', 'g'),"_");
1.125     ng       3216: 		var resetscore = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
                   3217: 		resetscore.value = document.classgrade["GD_"+user+"_"+partid+"_awarded_s"].value;
                   3218: 		var resettries = document.classgrade["GD_"+user+"_"+partid+"_tries"];
                   3219: 		resettries.value = document.classgrade["GD_"+user+"_"+partid+"_tries_s"].value;
                   3220: 		var saveselval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
                   3221: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
1.42      ng       3222: 		if (saveselval == "excused") {
1.43      ng       3223: 		    if (selname[1].selected == false) { selname[1].selected = true;}
1.42      ng       3224: 		} else {
1.43      ng       3225: 		    if (selname[0].selected == false) {selname[0].selected = true};
1.42      ng       3226: 		}
                   3227: 	    }
1.41      ng       3228: 	}
1.42      ng       3229:     }
                   3230: 
1.41      ng       3231: VIEWJAVASCRIPT
1.42      ng       3232: }
                   3233: 
1.44      ng       3234: #--- show scores for a section or whole class w/ option to change/update a score
1.42      ng       3235: sub viewgrades {
1.608     www      3236:     my ($request,$symb) = @_;
1.42      ng       3237:     &viewgrades_js($request);
1.41      ng       3238: 
1.168     albertel 3239:     #need to make sure we have the correct data for later EXT calls, 
                   3240:     #thus invalidate the cache
                   3241:     &Apache::lonnet::devalidatecourseresdata(
1.257     albertel 3242:                  $env{'course.'.$env{'request.course.id'}.'.num'},
                   3243:                  $env{'course.'.$env{'request.course.id'}.'.domain'});
1.168     albertel 3244:     &Apache::lonnet::clear_EXT_cache_status();
                   3245: 
1.398     albertel 3246:     my $result='<h3><span class="LC_info">'.&mt('Manual Grading').'</span></h3>';
1.41      ng       3247: 
                   3248:     #view individual student submission form - called using Javascript viewOneStudent
1.324     albertel 3249:     $result.=&jscriptNform($symb);
1.41      ng       3250: 
1.44      ng       3251:     #beginning of class grading form
1.442     banghart 3252:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
1.41      ng       3253:     $result.= '<form action="/adm/grades" method="post" name="classgrade">'."\n".
1.418     albertel 3254: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.38      ng       3255: 	'<input type="hidden" name="command" value="editgrades" />'."\n".
1.432     banghart 3256: 	&build_section_inputs().
1.442     banghart 3257: 	'<input type="hidden" name="Status" value="'.$env{'stu_status'}.'" />'."\n".
1.72      ng       3258: 
1.560     raeburn  3259:     my ($common_header,$specific_header);
1.257     albertel 3260:     if ($env{'form.section'} eq 'all') {
1.560     raeburn  3261: 	$common_header = &mt('Assign Common Grade to Class');
                   3262:         $specific_header = &mt('Assign Grade to Specific Students in Class');
1.257     albertel 3263:     } elsif ($env{'form.section'} eq 'none') {
1.560     raeburn  3264:         $common_header = &mt('Assign Common Grade to Students in no Section');
                   3265: 	$specific_header = &mt('Assign Grade to Specific Students in no Section');
1.52      albertel 3266:     } else {
1.560     raeburn  3267:         my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
                   3268:         $common_header = &mt('Assign Common Grade to Students in Section(s) [_1]',$section_display);
                   3269: 	$specific_header = &mt('Assign Grade to Specific Students in Section(s) [_1]',$section_display);
1.52      albertel 3270:     }
1.560     raeburn  3271:     $result.= '<h3>'.$common_header.'</h3>'.&Apache::loncommon::start_data_table();
1.44      ng       3272:     #radio buttons/text box for assigning points for a section or class.
                   3273:     #handles different parts of a problem
1.582     raeburn  3274:     my $res_error;
                   3275:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
                   3276:     if ($res_error) {
                   3277:         return &navmap_errormsg();
                   3278:     }
1.42      ng       3279:     my %weight = ();
                   3280:     my $ctsparts = 0;
1.45      ng       3281:     my %seen = ();
1.375     albertel 3282:     my @part_response_id = &flatten_responseType($responseType);
                   3283:     foreach my $part_response_id (@part_response_id) {
                   3284:     	my ($partid,$respid) = @{ $part_response_id };
                   3285: 	my $part_resp = join('_',@{ $part_response_id });
1.45      ng       3286: 	next if $seen{$partid};
                   3287: 	$seen{$partid}++;
1.375     albertel 3288: 	my $handgrade=$$handgrade{$part_resp};
1.42      ng       3289: 	my $wgt = &Apache::lonnet::EXT('resource.'.$partid.'.weight',$symb);
                   3290: 	$weight{$partid} = $wgt eq '' ? '1' : $wgt;
                   3291: 
1.324     albertel 3292: 	my $display_part=&get_display_part($partid,$symb);
1.485     albertel 3293: 	my $radio.='<table border="0"><tr>';  
1.41      ng       3294: 	my $ctr = 0;
1.42      ng       3295: 	while ($ctr<=$weight{$partid}) { # display radio buttons in a nice table 10 across
1.485     albertel 3296: 	    $radio.= '<td><label><input type="radio" name="RADVAL_'.$partid.'" '.
1.54      albertel 3297: 		'onclick="javascript:writePoint(\''.$partid.'\','.$weight{$partid}.
1.288     albertel 3298: 		','.$ctr.')" />'.$ctr."</label></td>\n";
1.41      ng       3299: 	    $result.=(($ctr+1)%10 == 0 ? '</tr><tr>' : '');
                   3300: 	    $ctr++;
                   3301: 	}
1.485     albertel 3302: 	$radio.='</tr></table>';
                   3303: 	my $line = '<input type="text" name="TEXTVAL_'.
1.589     bisitz   3304: 	    $partid.'" size="4" '.'onchange="javascript:writePoint(\''.
1.54      albertel 3305: 		$partid.'\','.$weight{$partid}.',\'textval\')" /> /'.
1.539     riegler  3306: 	    $weight{$partid}.' '.&mt('(problem weight)').'</td>'."\n";
                   3307: 	$line.= '<td><b>'.&mt('Grade Status').':</b><select name="SELVAL_'.$partid.'"'.
1.589     bisitz   3308: 	    'onchange="javascript:writeRadText(\''.$partid.'\','.
1.59      albertel 3309: 		$weight{$partid}.')"> '.
1.401     albertel 3310: 	    '<option selected="selected"> </option>'.
1.485     albertel 3311: 	    '<option value="excused">'.&mt('excused').'</option>'.
                   3312: 	    '<option value="reset status">'.&mt('reset status').'</option>'.
                   3313: 	    '</select></td>'.
                   3314:             '<td><label><input type="checkbox" name="FORCE_'.$partid.'" />'.&mt('Override "Correct"').'</label>';
                   3315: 	$line.='<input type="hidden" name="partid_'.
                   3316: 	    $ctsparts.'" value="'.$partid.'" />'."\n";
                   3317: 	$line.='<input type="hidden" name="weight_'.
                   3318: 	    $partid.'" value="'.$weight{$partid}.'" />'."\n";
                   3319: 
                   3320: 	$result.=
                   3321: 	    &Apache::loncommon::start_data_table_row()."\n".
1.577     bisitz   3322: 	    '<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 3323: 	    &Apache::loncommon::end_data_table_row()."\n";
1.42      ng       3324: 	$ctsparts++;
1.41      ng       3325:     }
1.474     albertel 3326:     $result.=&Apache::loncommon::end_data_table()."\n".
1.52      albertel 3327: 	'<input type="hidden" name="totalparts" value="'.$ctsparts.'" />';
1.485     albertel 3328:     $result.='<input type="button" value="'.&mt('Revert to Default').'" '.
1.589     bisitz   3329: 	'onclick="javascript:resetEntry('.$ctsparts.');" />';
1.41      ng       3330: 
1.44      ng       3331:     #table listing all the students in a section/class
                   3332:     #header of table
1.560     raeburn  3333:     $result.= '<h3>'.$specific_header.'</h3>'.
                   3334:               &Apache::loncommon::start_data_table().
                   3335: 	      &Apache::loncommon::start_data_table_header_row().
                   3336: 	      '<th>'.&mt('No.').'</th>'.
                   3337: 	      '<th>'.&nameUserString('header')."</th>\n";
1.582     raeburn  3338:     my $partserror;
                   3339:     my (@parts) = sort(&getpartlist($symb,\$partserror));
                   3340:     if ($partserror) {
                   3341:         return &navmap_errormsg();
                   3342:     }
1.324     albertel 3343:     my (undef,undef,$url)=&Apache::lonnet::decode_symb($symb);
1.269     raeburn  3344:     my @partids = ();
1.41      ng       3345:     foreach my $part (@parts) {
                   3346: 	my $display=&Apache::lonnet::metadata($url,$part.'.display');
1.539     riegler  3347:         my $narrowtext = &mt('Tries');
                   3348: 	$display =~ s|^Number of Attempts|$narrowtext <br />|; # makes the column narrower
1.41      ng       3349: 	if  (!$display) { $display = &Apache::lonnet::metadata($url,$part.'.name'); }
1.207     albertel 3350: 	my ($partid) = &split_part_type($part);
1.524     raeburn  3351:         push(@partids,$partid);
1.628     www      3352: #
                   3353: # FIXME: Looks like $display looks at English text
                   3354: #
1.324     albertel 3355: 	my $display_part=&get_display_part($partid,$symb);
1.41      ng       3356: 	if ($display =~ /^Partial Credit Factor/) {
1.485     albertel 3357: 	    $result.='<th>'.
                   3358: 		&mt('Score Part: [_1]<br /> (weight = [_2])',
                   3359: 		    $display_part,$weight{$partid}).'</th>'."\n";
1.41      ng       3360: 	    next;
1.485     albertel 3361: 	    
1.207     albertel 3362: 	} else {
1.485     albertel 3363: 	    if ($display =~ /Problem Status/) {
                   3364: 		my $grade_status_mt = &mt('Grade Status');
                   3365: 		$display =~ s{Problem Status}{$grade_status_mt<br />};
                   3366: 	    }
                   3367: 	    my $part_mt = &mt('Part:');
                   3368: 	    $display =~s{\[Part: \Q$partid\E\]}{$part_mt $display_part};
1.41      ng       3369: 	}
1.485     albertel 3370: 
1.474     albertel 3371: 	$result.='<th>'.$display.'</th>'."\n";
1.41      ng       3372:     }
1.474     albertel 3373:     $result.=&Apache::loncommon::end_data_table_header_row();
1.44      ng       3374: 
1.270     albertel 3375:     my %last_resets = 
                   3376: 	&get_last_resets($symb,$env{'request.course.id'},\@partids);
1.269     raeburn  3377: 
1.41      ng       3378:     #get info for each student
1.44      ng       3379:     #list all the students - with points and grade status
1.257     albertel 3380:     my (undef,undef,$fullname) = &getclasslist($env{'form.section'},'1');
1.41      ng       3381:     my $ctr = 0;
1.294     albertel 3382:     foreach (sort 
                   3383: 	     {
                   3384: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                   3385: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                   3386: 		 }
                   3387: 		 return $a cmp $b;
                   3388: 	     } (keys(%$fullname))) {
1.126     ng       3389: 	$ctr++;
1.324     albertel 3390: 	$result.=&viewstudentgrade($symb,$env{'request.course.id'},
1.269     raeburn  3391: 				   $_,$$fullname{$_},\@parts,\%weight,$ctr,\%last_resets);
1.41      ng       3392:     }
1.474     albertel 3393:     $result.=&Apache::loncommon::end_data_table();
1.41      ng       3394:     $result.='<input type="hidden" name="total" value="'.$ctr.'" />'."\n";
1.485     albertel 3395:     $result.='<input type="button" value="'.&mt('Save').'" '.
1.589     bisitz   3396: 	'onclick="javascript:submit();" target="_self" /></form>'."\n";
1.96      albertel 3397:     if (scalar(%$fullname) eq 0) {
                   3398: 	my $colspan=3+scalar(@parts);
1.433     banghart 3399: 	my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
1.442     banghart 3400:         my $stu_status = join(' or ',&Apache::loncommon::get_env_multiple('form.Status'));
1.433     banghart 3401: 	$result='<span class="LC_warning">'.
1.485     albertel 3402: 	    &mt('There are no students in section(s) [_1] with enrollment status [_2] to modify or grade.',
1.442     banghart 3403: 	        $section_display, $stu_status).
1.433     banghart 3404: 	    '</span>';
1.96      albertel 3405:     }
1.41      ng       3406:     return $result;
                   3407: }
                   3408: 
1.44      ng       3409: #--- call by previous routine to display each student
1.41      ng       3410: sub viewstudentgrade {
1.324     albertel 3411:     my ($symb,$courseid,$student,$fullname,$parts,$weight,$ctr,$last_resets) = @_;
1.44      ng       3412:     my ($uname,$udom) = split(/:/,$student);
                   3413:     my %record=&Apache::lonnet::restore($symb,$courseid,$udom,$uname);
1.269     raeburn  3414:     my %aggregates = (); 
1.474     albertel 3415:     my $result=&Apache::loncommon::start_data_table_row().'<td align="right">'.
1.233     albertel 3416: 	'<input type="hidden" name="ctr'.($ctr-1).'" value="'.$student.'" />'.
                   3417: 	"\n".$ctr.'&nbsp;</td><td>&nbsp;'.
1.44      ng       3418: 	'<a href="javascript:viewOneStudent(\''.$uname.'\',\''.$udom.
1.417     albertel 3419: 	'\');" target="_self">'.$fullname.'</a> '.
1.398     albertel 3420: 	'<span class="LC_internal_info">('.$uname.($env{'user.domain'} eq $udom ? '' : ':'.$udom).')</span></td>'."\n";
1.281     albertel 3421:     $student=~s/:/_/; # colon doen't work in javascript for names
1.63      albertel 3422:     foreach my $apart (@$parts) {
                   3423: 	my ($part,$type) = &split_part_type($apart);
1.41      ng       3424: 	my $score=$record{"resource.$part.$type"};
1.276     albertel 3425:         $result.='<td align="center">';
1.269     raeburn  3426:         my ($aggtries,$totaltries);
                   3427:         unless (exists($aggregates{$part})) {
1.270     albertel 3428: 	    $totaltries = $record{'resource.'.$part.'.tries'};
                   3429: 
                   3430: 	    $aggtries = $totaltries;
1.269     raeburn  3431:             if ($$last_resets{$part}) {  
1.270     albertel 3432:                 $aggtries = &get_num_tries(\%record,$$last_resets{$part},
                   3433: 					   $part);
                   3434:             }
1.269     raeburn  3435:             $result.='<input type="hidden" name="'.
                   3436:                 'GD_'.$student.'_'.$part.'_aggtries" value="'.$aggtries.'" />'."\n";
                   3437:             $result.='<input type="hidden" name="'.
                   3438:                 'GD_'.$student.'_'.$part.'_totaltries" value="'.$totaltries.'" />'."\n";
                   3439:             $aggregates{$part} = 1;
                   3440:         }
1.41      ng       3441: 	if ($type eq 'awarded') {
1.320     albertel 3442: 	    my $pts = $score eq '' ? '' : &compute_points($score,$$weight{$part});
1.42      ng       3443: 	    $result.='<input type="hidden" name="'.
1.89      albertel 3444: 		'GD_'.$student.'_'.$part.'_awarded_s" value="'.$pts.'" />'."\n";
1.233     albertel 3445: 	    $result.='<input type="text" name="'.
1.89      albertel 3446: 		'GD_'.$student.'_'.$part.'_awarded" '.
1.589     bisitz   3447:                 'onchange="javascript:changeSelect(\''.$part.'\',\''.$student.
1.44      ng       3448: 		'\')" value="'.$pts.'" size="4" /></td>'."\n";
1.41      ng       3449: 	} elsif ($type eq 'solved') {
                   3450: 	    my ($status,$foo)=split(/_/,$score,2);
                   3451: 	    $status = 'nothing' if ($status eq '');
1.89      albertel 3452: 	    $result.='<input type="hidden" name="'.'GD_'.$student.'_'.
1.54      albertel 3453: 		$part.'_solved_s" value="'.$status.'" />'."\n";
1.233     albertel 3454: 	    $result.='&nbsp;<select name="'.
1.89      albertel 3455: 		'GD_'.$student.'_'.$part.'_solved" '.
1.589     bisitz   3456:                 'onchange="javascript:changeOneScore(\''.$part.'\',\''.$student.'\')" >'."\n";
1.485     albertel 3457: 	    $result.= (($status eq 'excused') ? '<option> </option><option selected="selected" value="excused">'.&mt('excused').'</option>' 
                   3458: 		: '<option selected="selected"> </option><option value="excused">'.&mt('excused').'</option>')."\n";
                   3459: 	    $result.='<option value="reset status">'.&mt('reset status').'</option>';
1.126     ng       3460: 	    $result.="</select>&nbsp;</td>\n";
1.122     ng       3461: 	} else {
                   3462: 	    $result.='<input type="hidden" name="'.
                   3463: 		'GD_'.$student.'_'.$part.'_'.$type.'_s" value="'.$score.'" />'.
                   3464: 		    "\n";
1.233     albertel 3465: 	    $result.='<input type="text" name="'.
1.122     ng       3466: 		'GD_'.$student.'_'.$part.'_'.$type.'" '.
                   3467: 		'value="'.$score.'" size="4" /></td>'."\n";
1.41      ng       3468: 	}
                   3469:     }
1.474     albertel 3470:     $result.=&Apache::loncommon::end_data_table_row();
1.41      ng       3471:     return $result;
1.38      ng       3472: }
                   3473: 
1.44      ng       3474: #--- change scores for all the students in a section/class
                   3475: #    record does not get update if unchanged
1.38      ng       3476: sub editgrades {
1.608     www      3477:     my ($request,$symb) = @_;
1.41      ng       3478: 
1.433     banghart 3479:     my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
1.477     albertel 3480:     my $title='<h2>'.&mt('Current Grade Status').'</h2>';
1.433     banghart 3481:     $title.='<h4>'.&mt('<b>Section: </b>[_1]',$section_display).'</h4>'."\n";
1.126     ng       3482: 
1.477     albertel 3483:     my $result= &Apache::loncommon::start_data_table().
                   3484: 	&Apache::loncommon::start_data_table_header_row().
                   3485: 	'<th rowspan="2" valign="middle">'.&mt('No.').'</th>'.
                   3486: 	'<th rowspan="2" valign="middle">'.&nameUserString('header')."</th>\n";
1.43      ng       3487:     my %scoreptr = (
                   3488: 		    'correct'  =>'correct_by_override',
                   3489: 		    'incorrect'=>'incorrect_by_override',
                   3490: 		    'excused'  =>'excused',
                   3491: 		    'ungraded' =>'ungraded_attempted',
1.596     raeburn  3492:                     'credited' =>'credit_attempted',
1.43      ng       3493: 		    'nothing'  => '',
                   3494: 		    );
1.257     albertel 3495:     my ($classlist,undef,$fullname) = &getclasslist($env{'form.section'},'0');
1.34      ng       3496: 
1.44      ng       3497:     my (@partid);
                   3498:     my %weight = ();
1.54      albertel 3499:     my %columns = ();
1.44      ng       3500:     my ($i,$ctr,$count,$rec_update) = (0,0,0,0);
1.54      albertel 3501: 
1.582     raeburn  3502:     my $partserror;
                   3503:     my (@parts) = sort(&getpartlist($symb,\$partserror));
                   3504:     if ($partserror) {
                   3505:         return &navmap_errormsg();
                   3506:     }
1.54      albertel 3507:     my $header;
1.257     albertel 3508:     while ($ctr < $env{'form.totalparts'}) {
                   3509: 	my $partid = $env{'form.partid_'.$ctr};
1.524     raeburn  3510: 	push(@partid,$partid);
1.257     albertel 3511: 	$weight{$partid} = $env{'form.weight_'.$partid};
1.44      ng       3512: 	$ctr++;
1.54      albertel 3513:     }
1.324     albertel 3514:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
1.54      albertel 3515:     foreach my $partid (@partid) {
1.478     albertel 3516: 	$header .= '<th align="center">'.&mt('Old Score').'</th>'.
                   3517: 	    '<th align="center">'.&mt('New Score').'</th>';
1.54      albertel 3518: 	$columns{$partid}=2;
                   3519: 	foreach my $stores (@parts) {
                   3520: 	    my ($part,$type) = &split_part_type($stores);
                   3521: 	    if ($part !~ m/^\Q$partid\E/) { next;}
                   3522: 	    if ($type eq 'awarded' || $type eq 'solved') { next; }
                   3523: 	    my $display=&Apache::lonnet::metadata($url,$stores.'.display');
1.551     raeburn  3524: 	    $display =~ s/\[Part: \Q$part\E\]//;
1.539     riegler  3525:             my $narrowtext = &mt('Tries');
                   3526: 	    $display =~ s/Number of Attempts/$narrowtext/;
                   3527: 	    $header .= '<th align="center">'.&mt('Old').' '.$display.'</th>'.
                   3528: 		'<th align="center">'.&mt('New').' '.$display.'</th>';
1.54      albertel 3529: 	    $columns{$partid}+=2;
                   3530: 	}
                   3531:     }
                   3532:     foreach my $partid (@partid) {
1.324     albertel 3533: 	my $display_part=&get_display_part($partid,$symb);
1.478     albertel 3534: 	$result .= '<th colspan="'.$columns{$partid}.'" align="center">'.
                   3535: 	    &mt('Part: [_1] (Weight = [_2])',$display_part,$weight{$partid}).
                   3536: 	    '</th>';
1.54      albertel 3537: 
1.44      ng       3538:     }
1.477     albertel 3539:     $result .= &Apache::loncommon::end_data_table_header_row().
                   3540: 	&Apache::loncommon::start_data_table_header_row().
                   3541: 	$header.
                   3542: 	&Apache::loncommon::end_data_table_header_row();
                   3543:     my @noupdate;
1.126     ng       3544:     my ($updateCtr,$noupdateCtr) = (1,1);
1.257     albertel 3545:     for ($i=0; $i<$env{'form.total'}; $i++) {
1.93      albertel 3546: 	my $line;
1.257     albertel 3547: 	my $user = $env{'form.ctr'.$i};
1.281     albertel 3548: 	my ($uname,$udom)=split(/:/,$user);
1.44      ng       3549: 	my %newrecord;
                   3550: 	my $updateflag = 0;
1.281     albertel 3551: 	$line .= '<td>'.&nameUserString(undef,$$fullname{$user},$uname,$udom).'</td>';
1.108     albertel 3552: 	my $usec=$classlist->{"$uname:$udom"}[5];
1.105     albertel 3553: 	if (!&canmodify($usec)) {
1.126     ng       3554: 	    my $numcols=scalar(@partid)*4+2;
1.477     albertel 3555: 	    push(@noupdate,
1.478     albertel 3556: 		 $line."<td colspan=\"$numcols\"><span class=\"LC_warning\">".
                   3557: 		 &mt('Not allowed to modify student')."</span></td></tr>");
1.105     albertel 3558: 	    next;
                   3559: 	}
1.269     raeburn  3560:         my %aggregate = ();
                   3561:         my $aggregateflag = 0;
1.281     albertel 3562: 	$user=~s/:/_/; # colon doen't work in javascript for names
1.44      ng       3563: 	foreach (@partid) {
1.257     albertel 3564: 	    my $old_aw    = $env{'form.GD_'.$user.'_'.$_.'_awarded_s'};
1.54      albertel 3565: 	    my $old_part_pcr = $old_aw/($weight{$_} ne '0' ? $weight{$_}:1);
                   3566: 	    my $old_part  = $old_aw eq '' ? '' : $old_part_pcr;
1.257     albertel 3567: 	    my $old_score = $scoreptr{$env{'form.GD_'.$user.'_'.$_.'_solved_s'}};
                   3568: 	    my $awarded   = $env{'form.GD_'.$user.'_'.$_.'_awarded'};
1.54      albertel 3569: 	    my $pcr       = $awarded/($weight{$_} ne '0' ? $weight{$_} : 1);
                   3570: 	    my $partial   = $awarded eq '' ? '' : $pcr;
1.44      ng       3571: 	    my $score;
                   3572: 	    if ($partial eq '') {
1.257     albertel 3573: 		$score = $scoreptr{$env{'form.GD_'.$user.'_'.$_.'_solved_s'}};
1.44      ng       3574: 	    } elsif ($partial > 0) {
                   3575: 		$score = 'correct_by_override';
                   3576: 	    } elsif ($partial == 0) {
                   3577: 		$score = 'incorrect_by_override';
                   3578: 	    }
1.257     albertel 3579: 	    my $dropMenu = $env{'form.GD_'.$user.'_'.$_.'_solved'};
1.125     ng       3580: 	    $score = 'excused' if (($dropMenu eq 'excused') && ($score ne 'excused'));
                   3581: 
1.292     albertel 3582: 	    $newrecord{'resource.'.$_.'.regrader'}=
                   3583: 		"$env{'user.name'}:$env{'user.domain'}";
1.125     ng       3584: 	    if ($dropMenu eq 'reset status' &&
                   3585: 		$old_score ne '') { # ignore if no previous attempts => nothing to reset
1.299     albertel 3586: 		$newrecord{'resource.'.$_.'.tries'} = '';
1.125     ng       3587: 		$newrecord{'resource.'.$_.'.solved'} = '';
                   3588: 		$newrecord{'resource.'.$_.'.award'} = '';
1.299     albertel 3589: 		$newrecord{'resource.'.$_.'.awarded'} = '';
1.125     ng       3590: 		$updateflag = 1;
1.269     raeburn  3591:                 if ($env{'form.GD_'.$user.'_'.$_.'_aggtries'} > 0) {
                   3592:                     my $aggtries = $env{'form.GD_'.$user.'_'.$_.'_aggtries'};
                   3593:                     my $totaltries = $env{'form.GD_'.$user.'_'.$_.'_totaltries'};
                   3594:                     my $solvedstatus = $env{'form.GD_'.$user.'_'.$_.'_solved_s'};
                   3595:                     &decrement_aggs($symb,$_,\%aggregate,$aggtries,$totaltries,$solvedstatus);
                   3596:                     $aggregateflag = 1;
                   3597:                 }
1.139     albertel 3598: 	    } elsif (!($old_part eq $partial && $old_score eq $score)) {
                   3599: 		$updateflag = 1;
                   3600: 		$newrecord{'resource.'.$_.'.awarded'}  = $partial if $partial ne '';
                   3601: 		$newrecord{'resource.'.$_.'.solved'}   = $score;
                   3602: 		$rec_update++;
1.125     ng       3603: 	    }
                   3604: 
1.93      albertel 3605: 	    $line .= '<td align="center">'.$old_aw.'&nbsp;</td>'.
1.44      ng       3606: 		'<td align="center">'.$awarded.
                   3607: 		($score eq 'excused' ? $score : '').'&nbsp;</td>';
1.5       albertel 3608: 
1.54      albertel 3609: 
                   3610: 	    my $partid=$_;
                   3611: 	    foreach my $stores (@parts) {
                   3612: 		my ($part,$type) = &split_part_type($stores);
                   3613: 		if ($part !~ m/^\Q$partid\E/) { next;}
                   3614: 		if ($type eq 'awarded' || $type eq 'solved') { next; }
1.257     albertel 3615: 		my $old_aw    = $env{'form.GD_'.$user.'_'.$part.'_'.$type.'_s'};
                   3616: 		my $awarded   = $env{'form.GD_'.$user.'_'.$part.'_'.$type};
1.54      albertel 3617: 		if ($awarded ne '' && $awarded ne $old_aw) {
                   3618: 		    $newrecord{'resource.'.$part.'.'.$type}= $awarded;
1.257     albertel 3619: 		    $newrecord{'resource.'.$part.'.regrader'}="$env{'user.name'}:$env{'user.domain'}";
1.54      albertel 3620: 		    $updateflag=1;
                   3621: 		}
1.93      albertel 3622: 		$line .= '<td align="center">'.$old_aw.'&nbsp;</td>'.
1.54      albertel 3623: 		    '<td align="center">'.$awarded.'&nbsp;</td>';
                   3624: 	    }
1.44      ng       3625: 	}
1.477     albertel 3626: 	$line.="\n";
1.301     albertel 3627: 
                   3628: 	my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   3629: 	my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   3630: 
1.44      ng       3631: 	if ($updateflag) {
                   3632: 	    $count++;
1.257     albertel 3633: 	    &Apache::lonnet::cstore(\%newrecord,$symb,$env{'request.course.id'},
1.89      albertel 3634: 				    $udom,$uname);
1.301     albertel 3635: 
                   3636: 	    if (&Apache::bridgetask::in_queue('gradingqueue',$symb,$cdom,
                   3637: 					      $cnum,$udom,$uname)) {
                   3638: 		# need to figure out if should be in queue.
                   3639: 		my %record =  
                   3640: 		    &Apache::lonnet::restore($symb,$env{'request.course.id'},
                   3641: 					     $udom,$uname);
                   3642: 		my $all_graded = 1;
                   3643: 		my $none_graded = 1;
                   3644: 		foreach my $part (@parts) {
                   3645: 		    if ( $record{'resource.'.$part.'.awarded'} eq '' ) {
                   3646: 			$all_graded = 0;
                   3647: 		    } else {
                   3648: 			$none_graded = 0;
                   3649: 		    }
                   3650: 		}
                   3651: 
                   3652: 		if ($all_graded || $none_graded) {
                   3653: 		    &Apache::bridgetask::remove_from_queue('gradingqueue',
                   3654: 							   $symb,$cdom,$cnum,
                   3655: 							   $udom,$uname);
                   3656: 		}
                   3657: 	    }
                   3658: 
1.477     albertel 3659: 	    $result.=&Apache::loncommon::start_data_table_row().
                   3660: 		'<td align="right">&nbsp;'.$updateCtr.'&nbsp;</td>'.$line.
                   3661: 		&Apache::loncommon::end_data_table_row();
1.126     ng       3662: 	    $updateCtr++;
1.93      albertel 3663: 	} else {
1.477     albertel 3664: 	    push(@noupdate,
                   3665: 		 '<td align="right">&nbsp;'.$noupdateCtr.'&nbsp;</td>'.$line);
1.126     ng       3666: 	    $noupdateCtr++;
1.44      ng       3667: 	}
1.269     raeburn  3668:         if ($aggregateflag) {
                   3669:             &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
1.301     albertel 3670: 				  $cdom,$cnum);
1.269     raeburn  3671:         }
1.93      albertel 3672:     }
1.477     albertel 3673:     if (@noupdate) {
1.126     ng       3674: #	my $numcols=(scalar(@partid)*(scalar(@parts)-1)*2)+3;
                   3675: 	my $numcols=scalar(@partid)*4+2;
1.477     albertel 3676: 	$result .= &Apache::loncommon::start_data_table_row('LC_empty_row').
1.478     albertel 3677: 	    '<td align="center" colspan="'.$numcols.'">'.
                   3678: 	    &mt('No Changes Occurred For the Students Below').
                   3679: 	    '</td>'.
1.477     albertel 3680: 	    &Apache::loncommon::end_data_table_row();
                   3681: 	foreach my $line (@noupdate) {
                   3682: 	    $result.=
                   3683: 		&Apache::loncommon::start_data_table_row().
                   3684: 		$line.
                   3685: 		&Apache::loncommon::end_data_table_row();
                   3686: 	}
1.44      ng       3687:     }
1.614     www      3688:     $result .= &Apache::loncommon::end_data_table();
1.478     albertel 3689:     my $msg = '<p><b>'.
                   3690: 	&mt('Number of records updated = [_1] for [quant,_2,student].',
                   3691: 	    $rec_update,$count).'</b><br />'.
                   3692: 	'<b>'.&mt('Total number of students = [_1]',$env{'form.total'}).
                   3693: 	'</b></p>';
1.44      ng       3694:     return $title.$msg.$result;
1.5       albertel 3695: }
1.54      albertel 3696: 
                   3697: sub split_part_type {
                   3698:     my ($partstr) = @_;
                   3699:     my ($temp,@allparts)=split(/_/,$partstr);
                   3700:     my $type=pop(@allparts);
1.439     albertel 3701:     my $part=join('_',@allparts);
1.54      albertel 3702:     return ($part,$type);
                   3703: }
                   3704: 
1.44      ng       3705: #------------- end of section for handling grading by section/class ---------
                   3706: #
                   3707: #----------------------------------------------------------------------------
                   3708: 
1.5       albertel 3709: 
1.44      ng       3710: #----------------------------------------------------------------------------
                   3711: #
                   3712: #-------------------------- Next few routines handles grading by csv upload
                   3713: #
                   3714: #--- Javascript to handle csv upload
1.27      albertel 3715: sub csvupload_javascript_reverse_associate {
1.573     bisitz   3716:     my $error1=&mt('You need to specify the username or the student/employee ID');
1.246     albertel 3717:     my $error2=&mt('You need to specify at least one grading field');
1.27      albertel 3718:   return(<<ENDPICK);
                   3719:   function verify(vf) {
                   3720:     var foundsomething=0;
                   3721:     var founduname=0;
1.243     albertel 3722:     var foundID=0;
1.27      albertel 3723:     for (i=0;i<=vf.nfields.value;i++) {
                   3724:       tw=eval('vf.f'+i+'.selectedIndex');
1.243     albertel 3725:       if (i==0 && tw!=0) { foundID=1; }
                   3726:       if (i==1 && tw!=0) { founduname=1; }
                   3727:       if (i!=0 && i!=1 && i!=2 && tw!=0) { foundsomething=1; }
1.27      albertel 3728:     }
1.246     albertel 3729:     if (founduname==0 && foundID==0) {
                   3730: 	alert('$error1');
                   3731: 	return;
1.27      albertel 3732:     }
                   3733:     if (foundsomething==0) {
1.246     albertel 3734: 	alert('$error2');
                   3735: 	return;
1.27      albertel 3736:     }
                   3737:     vf.submit();
                   3738:   }
                   3739:   function flip(vf,tf) {
                   3740:     var nw=eval('vf.f'+tf+'.selectedIndex');
                   3741:     var i;
                   3742:     for (i=0;i<=vf.nfields.value;i++) {
                   3743:       //can not pick the same destination field for both name and domain
                   3744:       if (((i ==0)||(i ==1)) && 
                   3745:           ((tf==0)||(tf==1)) && 
                   3746:           (i!=tf) &&
                   3747:           (eval('vf.f'+i+'.selectedIndex')==nw)) {
                   3748:         eval('vf.f'+i+'.selectedIndex=0;')
                   3749:       }
                   3750:     }
                   3751:   }
                   3752: ENDPICK
                   3753: }
                   3754: 
                   3755: sub csvupload_javascript_forward_associate {
1.573     bisitz   3756:     my $error1=&mt('You need to specify the username or the student/employee ID');
1.246     albertel 3757:     my $error2=&mt('You need to specify at least one grading field');
1.27      albertel 3758:   return(<<ENDPICK);
                   3759:   function verify(vf) {
                   3760:     var foundsomething=0;
                   3761:     var founduname=0;
1.243     albertel 3762:     var foundID=0;
1.27      albertel 3763:     for (i=0;i<=vf.nfields.value;i++) {
                   3764:       tw=eval('vf.f'+i+'.selectedIndex');
1.243     albertel 3765:       if (tw==1) { foundID=1; }
                   3766:       if (tw==2) { founduname=1; }
                   3767:       if (tw>3) { foundsomething=1; }
1.27      albertel 3768:     }
1.246     albertel 3769:     if (founduname==0 && foundID==0) {
                   3770: 	alert('$error1');
                   3771: 	return;
1.27      albertel 3772:     }
                   3773:     if (foundsomething==0) {
1.246     albertel 3774: 	alert('$error2');
                   3775: 	return;
1.27      albertel 3776:     }
                   3777:     vf.submit();
                   3778:   }
                   3779:   function flip(vf,tf) {
                   3780:     var nw=eval('vf.f'+tf+'.selectedIndex');
                   3781:     var i;
                   3782:     //can not pick the same destination field twice
                   3783:     for (i=0;i<=vf.nfields.value;i++) {
                   3784:       if ((i!=tf) && (eval('vf.f'+i+'.selectedIndex')==nw)) {
                   3785:         eval('vf.f'+i+'.selectedIndex=0;')
                   3786:       }
                   3787:     }
                   3788:   }
                   3789: ENDPICK
                   3790: }
                   3791: 
1.26      albertel 3792: sub csvuploadmap_header {
1.324     albertel 3793:     my ($request,$symb,$datatoken,$distotal)= @_;
1.41      ng       3794:     my $javascript;
1.257     albertel 3795:     if ($env{'form.upfile_associate'} eq 'reverse') {
1.41      ng       3796: 	$javascript=&csvupload_javascript_reverse_associate();
                   3797:     } else {
                   3798: 	$javascript=&csvupload_javascript_forward_associate();
                   3799:     }
1.45      ng       3800: 
1.418     albertel 3801:     $symb = &Apache::lonenc::check_encrypt($symb);
1.632     www      3802:     $request->print('<form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">'.
                   3803:                     &mt('Total number of records found in file: [_1]',$distotal).'<hr />'.
                   3804:                     &mt('Associate entries from the uploaded file with as many fields as you can.'));
                   3805:     my $reverse=&mt("Reverse Association");
1.41      ng       3806:     $request->print(<<ENDPICK);
1.632     www      3807: <br />
                   3808: <input type="button" value="$reverse" onclick="javascript:this.form.associate.value='Reverse Association';submit(this.form);" />
1.26      albertel 3809: <input type="hidden" name="associate"  value="" />
                   3810: <input type="hidden" name="phase"      value="three" />
                   3811: <input type="hidden" name="datatoken"  value="$datatoken" />
1.257     albertel 3812: <input type="hidden" name="fileupload" value="$env{'form.fileupload'}" />
                   3813: <input type="hidden" name="upfiletype" value="$env{'form.upfiletype'}" />
1.26      albertel 3814: <input type="hidden" name="upfile_associate" 
1.257     albertel 3815:                                        value="$env{'form.upfile_associate'}" />
1.26      albertel 3816: <input type="hidden" name="symb"       value="$symb" />
1.246     albertel 3817: <input type="hidden" name="command"    value="csvuploadoptions" />
1.26      albertel 3818: <hr />
                   3819: ENDPICK
1.597     wenzelju 3820:     $request->print(&Apache::lonhtmlcommon::scripttag($javascript));
1.118     ng       3821:     return '';
1.26      albertel 3822: 
                   3823: }
                   3824: 
                   3825: sub csvupload_fields {
1.582     raeburn  3826:     my ($symb,$errorref) = @_;
                   3827:     my (@parts) = &getpartlist($symb,$errorref);
                   3828:     if (ref($errorref)) {
                   3829:         if ($$errorref) {
                   3830:             return;
                   3831:         }
                   3832:     }
                   3833: 
1.556     weissno  3834:     my @fields=(['ID','Student/Employee ID'],
1.243     albertel 3835: 		['username','Student Username'],
                   3836: 		['domain','Student Domain']);
1.324     albertel 3837:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
1.41      ng       3838:     foreach my $part (sort(@parts)) {
                   3839: 	my @datum;
                   3840: 	my $display=&Apache::lonnet::metadata($url,$part.'.display');
                   3841: 	my $name=$part;
                   3842: 	if  (!$display) { $display = $name; }
                   3843: 	@datum=($name,$display);
1.244     albertel 3844: 	if ($name=~/^stores_(.*)_awarded/) {
                   3845: 	    push(@fields,['stores_'.$1.'_points',"Points [Part: $1]"]);
                   3846: 	}
1.41      ng       3847: 	push(@fields,\@datum);
                   3848:     }
                   3849:     return (@fields);
1.26      albertel 3850: }
                   3851: 
                   3852: sub csvuploadmap_footer {
1.41      ng       3853:     my ($request,$i,$keyfields) =@_;
                   3854:     $request->print(<<ENDPICK);
1.26      albertel 3855: </table>
                   3856: <input type="hidden" name="nfields" value="$i" />
                   3857: <input type="hidden" name="keyfields" value="$keyfields" />
1.589     bisitz   3858: <input type="button" onclick="javascript:verify(this.form)" value="Assign Grades" /><br />
1.26      albertel 3859: </form>
                   3860: ENDPICK
                   3861: }
                   3862: 
1.283     albertel 3863: sub checkforfile_js {
1.634     foxr     3864:     my $alertmsg = &mt('Please use the "Choose File" button to select a file from your local directory.');
1.597     wenzelju 3865:     my $result = &Apache::lonhtmlcommon::scripttag(<<CSVFORMJS);
1.86      ng       3866:     function checkUpload(formname) {
                   3867: 	if (formname.upfile.value == "") {
1.539     riegler  3868: 	    alert("$alertmsg");
1.86      ng       3869: 	    return false;
                   3870: 	}
                   3871: 	formname.submit();
                   3872:     }
                   3873: CSVFORMJS
1.283     albertel 3874:     return $result;
                   3875: }
                   3876: 
                   3877: sub upcsvScores_form {
1.608     www      3878:     my ($request,$symb) = @_;
1.283     albertel 3879:     if (!$symb) {return '';}
                   3880:     my $result=&checkforfile_js();
1.632     www      3881:     $result.=&Apache::loncommon::start_data_table().
                   3882:              &Apache::loncommon::start_data_table_header_row().
                   3883:              '<th>'.&mt('Specify a file containing the class scores for current resource.').'</th>'.
                   3884:              &Apache::loncommon::end_data_table_header_row().
                   3885:              &Apache::loncommon::start_data_table_row().'<td>';
1.370     www      3886:     my $upload=&mt("Upload Scores");
1.86      ng       3887:     my $upfile_select=&Apache::loncommon::upfile_select_html();
1.245     albertel 3888:     my $ignore=&mt('Ignore First Line');
1.418     albertel 3889:     $symb = &Apache::lonenc::check_encrypt($symb);
1.86      ng       3890:     $result.=<<ENDUPFORM;
1.106     albertel 3891: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
1.86      ng       3892: <input type="hidden" name="symb" value="$symb" />
                   3893: <input type="hidden" name="command" value="csvuploadmap" />
                   3894: $upfile_select
1.589     bisitz   3895: <br /><input type="button" onclick="javascript:checkUpload(this.form);" value="$upload" />
1.86      ng       3896: </form>
                   3897: ENDUPFORM
1.370     www      3898:     $result.=&Apache::loncommon::help_open_topic("Course_Convert_To_CSV",
1.632     www      3899:                            &mt("How do I create a CSV file from a spreadsheet")).
                   3900:              '</td>'.
                   3901:             &Apache::loncommon::end_data_table_row().
                   3902:             &Apache::loncommon::end_data_table();
1.86      ng       3903:     return $result;
                   3904: }
                   3905: 
                   3906: 
1.26      albertel 3907: sub csvuploadmap {
1.608     www      3908:     my ($request,$symb)= @_;
1.41      ng       3909:     if (!$symb) {return '';}
1.72      ng       3910: 
1.41      ng       3911:     my $datatoken;
1.257     albertel 3912:     if (!$env{'form.datatoken'}) {
1.41      ng       3913: 	$datatoken=&Apache::loncommon::upfile_store($request);
1.26      albertel 3914:     } else {
1.257     albertel 3915: 	$datatoken=$env{'form.datatoken'};
1.41      ng       3916: 	&Apache::loncommon::load_tmp_file($request);
1.26      albertel 3917:     }
1.41      ng       3918:     my @records=&Apache::loncommon::upfile_record_sep();
1.324     albertel 3919:     &csvuploadmap_header($request,$symb,$datatoken,$#records+1);
1.41      ng       3920:     my ($i,$keyfields);
                   3921:     if (@records) {
1.582     raeburn  3922:         my $fieldserror;
                   3923: 	my @fields=&csvupload_fields($symb,\$fieldserror);
                   3924:         if ($fieldserror) {
                   3925:             $request->print(&navmap_errormsg());
                   3926:             return;
                   3927:         }
1.257     albertel 3928: 	if ($env{'form.upfile_associate'} eq 'reverse') {	
1.41      ng       3929: 	    &Apache::loncommon::csv_print_samples($request,\@records);
                   3930: 	    $i=&Apache::loncommon::csv_print_select_table($request,\@records,
                   3931: 							  \@fields);
                   3932: 	    foreach (@fields) { $keyfields.=$_->[0].','; }
                   3933: 	    chop($keyfields);
                   3934: 	} else {
                   3935: 	    unshift(@fields,['none','']);
                   3936: 	    $i=&Apache::loncommon::csv_samples_select_table($request,\@records,
                   3937: 							    \@fields);
1.311     banghart 3938:             foreach my $rec (@records) {
                   3939:                 my %temp = &Apache::loncommon::record_sep($rec);
                   3940:                 if (%temp) {
                   3941:                     $keyfields=join(',',sort(keys(%temp)));
                   3942:                     last;
                   3943:                 }
                   3944:             }
1.41      ng       3945: 	}
                   3946:     }
                   3947:     &csvuploadmap_footer($request,$i,$keyfields);
1.72      ng       3948: 
1.41      ng       3949:     return '';
1.27      albertel 3950: }
                   3951: 
1.246     albertel 3952: sub csvuploadoptions {
1.608     www      3953:     my ($request,$symb)= @_;
1.632     www      3954:     my $overwrite=&mt('Overwrite any existing score');
1.246     albertel 3955:     $request->print(<<ENDPICK);
                   3956: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
                   3957: <input type="hidden" name="command"    value="csvuploadassign" />
                   3958: <p>
                   3959: <label>
                   3960:    <input type="checkbox" name="overwite_scores" checked="checked" />
1.632     www      3961:    $overwrite
1.246     albertel 3962: </label>
                   3963: </p>
                   3964: ENDPICK
                   3965:     my %fields=&get_fields();
                   3966:     if (!defined($fields{'domain'})) {
1.257     albertel 3967: 	my $domform = &Apache::loncommon::select_dom_form($env{'request.role.domain'},'default_domain');
1.632     www      3968: 	$request->print("\n<p>".&mt('Users are in domain: [_1]',$domform)."</p>\n");
1.246     albertel 3969:     }
1.257     albertel 3970:     foreach my $key (sort(keys(%env))) {
1.246     albertel 3971: 	if ($key !~ /^form\.(.*)$/) { next; }
                   3972: 	my $cleankey=$1;
                   3973: 	if ($cleankey eq 'command') { next; }
                   3974: 	$request->print('<input type="hidden" name="'.$cleankey.
1.257     albertel 3975: 			'"  value="'.$env{$key}.'" />'."\n");
1.246     albertel 3976:     }
                   3977:     # FIXME do a check for any duplicated user ids...
                   3978:     # FIXME do a check for any invalid user ids?...
1.290     albertel 3979:     $request->print('<input type="submit" value="Assign Grades" /><br />
                   3980: <hr /></form>'."\n");
1.246     albertel 3981:     return '';
                   3982: }
                   3983: 
                   3984: sub get_fields {
                   3985:     my %fields;
1.257     albertel 3986:     my @keyfields = split(/\,/,$env{'form.keyfields'});
                   3987:     for (my $i=0; $i<=$env{'form.nfields'}; $i++) {
                   3988: 	if ($env{'form.upfile_associate'} eq 'reverse') {
                   3989: 	    if ($env{'form.f'.$i} ne 'none') {
                   3990: 		$fields{$keyfields[$i]}=$env{'form.f'.$i};
1.41      ng       3991: 	    }
                   3992: 	} else {
1.257     albertel 3993: 	    if ($env{'form.f'.$i} ne 'none') {
                   3994: 		$fields{$env{'form.f'.$i}}=$keyfields[$i];
1.41      ng       3995: 	    }
                   3996: 	}
1.27      albertel 3997:     }
1.246     albertel 3998:     return %fields;
                   3999: }
                   4000: 
                   4001: sub csvuploadassign {
1.608     www      4002:     my ($request,$symb)= @_;
1.246     albertel 4003:     if (!$symb) {return '';}
1.345     bowersj2 4004:     my $error_msg = '';
1.246     albertel 4005:     &Apache::loncommon::load_tmp_file($request);
                   4006:     my @gradedata = &Apache::loncommon::upfile_record_sep();
                   4007:     my %fields=&get_fields();
1.257     albertel 4008:     my $courseid=$env{'request.course.id'};
1.97      albertel 4009:     my ($classlist) = &getclasslist('all',0);
1.106     albertel 4010:     my @notallowed;
1.41      ng       4011:     my @skipped;
                   4012:     my $countdone=0;
                   4013:     foreach my $grade (@gradedata) {
                   4014: 	my %entries=&Apache::loncommon::record_sep($grade);
1.246     albertel 4015: 	my $domain;
                   4016: 	if ($entries{$fields{'domain'}}) {
                   4017: 	    $domain=$entries{$fields{'domain'}};
                   4018: 	} else {
1.257     albertel 4019: 	    $domain=$env{'form.default_domain'};
1.246     albertel 4020: 	}
1.243     albertel 4021: 	$domain=~s/\s//g;
1.41      ng       4022: 	my $username=$entries{$fields{'username'}};
1.160     albertel 4023: 	$username=~s/\s//g;
1.243     albertel 4024: 	if (!$username) {
                   4025: 	    my $id=$entries{$fields{'ID'}};
1.247     albertel 4026: 	    $id=~s/\s//g;
1.243     albertel 4027: 	    my %ids=&Apache::lonnet::idget($domain,$id);
                   4028: 	    $username=$ids{$id};
                   4029: 	}
1.41      ng       4030: 	if (!exists($$classlist{"$username:$domain"})) {
1.247     albertel 4031: 	    my $id=$entries{$fields{'ID'}};
                   4032: 	    $id=~s/\s//g;
                   4033: 	    if ($id) {
                   4034: 		push(@skipped,"$id:$domain");
                   4035: 	    } else {
                   4036: 		push(@skipped,"$username:$domain");
                   4037: 	    }
1.41      ng       4038: 	    next;
                   4039: 	}
1.108     albertel 4040: 	my $usec=$classlist->{"$username:$domain"}[5];
1.106     albertel 4041: 	if (!&canmodify($usec)) {
                   4042: 	    push(@notallowed,"$username:$domain");
                   4043: 	    next;
                   4044: 	}
1.244     albertel 4045: 	my %points;
1.41      ng       4046: 	my %grades;
                   4047: 	foreach my $dest (keys(%fields)) {
1.244     albertel 4048: 	    if ($dest eq 'ID' || $dest eq 'username' ||
                   4049: 		$dest eq 'domain') { next; }
                   4050: 	    if ($entries{$fields{$dest}} =~ /^\s*$/) { next; }
                   4051: 	    if ($dest=~/stores_(.*)_points/) {
                   4052: 		my $part=$1;
                   4053: 		my $wgt =&Apache::lonnet::EXT('resource.'.$part.'.weight',
                   4054: 					      $symb,$domain,$username);
1.345     bowersj2 4055:                 if ($wgt) {
                   4056:                     $entries{$fields{$dest}}=~s/\s//g;
                   4057:                     my $pcr=$entries{$fields{$dest}} / $wgt;
1.463     albertel 4058:                     my $award=($pcr == 0) ? 'incorrect_by_override'
                   4059:                                           : 'correct_by_override';
1.345     bowersj2 4060:                     $grades{"resource.$part.awarded"}=$pcr;
                   4061:                     $grades{"resource.$part.solved"}=$award;
                   4062:                     $points{$part}=1;
                   4063:                 } else {
                   4064:                     $error_msg = "<br />" .
                   4065:                         &mt("Some point values were assigned"
                   4066:                             ." for problems with a weight "
                   4067:                             ."of zero. These values were "
                   4068:                             ."ignored.");
                   4069:                 }
1.244     albertel 4070: 	    } else {
                   4071: 		if ($dest=~/stores_(.*)_awarded/) { if ($points{$1}) {next;} }
                   4072: 		if ($dest=~/stores_(.*)_solved/)  { if ($points{$1}) {next;} }
                   4073: 		my $store_key=$dest;
                   4074: 		$store_key=~s/^stores/resource/;
                   4075: 		$store_key=~s/_/\./g;
                   4076: 		$grades{$store_key}=$entries{$fields{$dest}};
                   4077: 	    }
1.41      ng       4078: 	}
1.508     www      4079: 	if (! %grades) { 
                   4080:            push(@skipped,&mt("[_1]: no data to save","$username:$domain")); 
                   4081:         } else {
                   4082: 	   $grades{"resource.regrader"}="$env{'user.name'}:$env{'user.domain'}";
                   4083: 	   my $result=&Apache::lonnet::cstore(\%grades,$symb,
1.302     albertel 4084: 					   $env{'request.course.id'},
                   4085: 					   $domain,$username);
1.508     www      4086: 	   if ($result eq 'ok') {
1.627     www      4087: # Successfully stored
1.508     www      4088: 	      $request->print('.');
1.627     www      4089: # Remove from grading queue
                   4090:               &Apache::bridgetask::remove_from_queue('gradingqueue',$symb,
                   4091:                                              $env{'course.'.$env{'request.course.id'}.'.domain'},
                   4092:                                              $env{'course.'.$env{'request.course.id'}.'.num'},
                   4093:                                              $domain,$username);
                   4094:               $countdone++;
                   4095:            } else {
1.508     www      4096: 	      $request->print("<p><span class=\"LC_error\">".
                   4097:                               &mt("Failed to save data for student [_1]. Message when trying to save was: [_2]",
                   4098:                                   "$username:$domain",$result)."</span></p>");
                   4099: 	   }
                   4100: 	   $request->rflush();
                   4101:         }
1.41      ng       4102:     }
1.570     www      4103:     $request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt("Saved scores for [quant,_1,student]",$countdone),$countdone==0));
1.41      ng       4104:     if (@skipped) {
1.571     www      4105: 	$request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt('No scores stored for the following username(s):'),1).'<br />');
                   4106:         $request->print(join(', ',@skipped));
1.106     albertel 4107:     }
                   4108:     if (@notallowed) {
1.571     www      4109: 	$request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt('Modification of scores not allowed for the following username(s):'),1).'<br />');
                   4110: 	$request->print(join(', ',@notallowed));
1.41      ng       4111:     }
1.106     albertel 4112:     $request->print("<br />\n");
1.345     bowersj2 4113:     return $error_msg;
1.26      albertel 4114: }
1.44      ng       4115: #------------- end of section for handling csv file upload ---------
                   4116: #
                   4117: #-------------------------------------------------------------------
                   4118: #
1.122     ng       4119: #-------------- Next few routines handle grading by page/sequence
1.72      ng       4120: #
                   4121: #--- Select a page/sequence and a student to grade
1.68      ng       4122: sub pickStudentPage {
1.608     www      4123:     my ($request,$symb) = @_;
1.68      ng       4124: 
1.539     riegler  4125:     my $alertmsg = &mt('Please select the student you wish to grade.');
1.597     wenzelju 4126:     $request->print(&Apache::lonhtmlcommon::scripttag(<<LISTJAVASCRIPT));
1.68      ng       4127: 
                   4128: function checkPickOne(formname) {
1.76      ng       4129:     if (radioSelection(formname.student) == null) {
1.539     riegler  4130: 	alert("$alertmsg");
1.68      ng       4131: 	return;
                   4132:     }
1.125     ng       4133:     ptr = pullDownSelection(formname.selectpage);
                   4134:     formname.page.value = formname["page"+ptr].value;
                   4135:     formname.title.value = formname["title"+ptr].value;
1.68      ng       4136:     formname.submit();
                   4137: }
                   4138: 
                   4139: LISTJAVASCRIPT
1.118     ng       4140:     &commonJSfunctions($request);
1.608     www      4141: 
1.257     albertel 4142:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
                   4143:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
                   4144:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
1.68      ng       4145: 
1.398     albertel 4146:     my $result='<h3><span class="LC_info">&nbsp;'.
1.485     albertel 4147: 	&mt('Manual Grading by Page or Sequence').'</span></h3>';
1.68      ng       4148: 
1.80      ng       4149:     $result.='<form action="/adm/grades" method="post" name="displayPage">'."\n";
1.582     raeburn  4150:     my $map_error;
                   4151:     my ($titles,$symbx) = &getSymbMap($map_error);
                   4152:     if ($map_error) {
                   4153:         $request->print(&navmap_errormsg());
                   4154:         return; 
                   4155:     }
1.137     albertel 4156:     my ($curpage) =&Apache::lonnet::decode_symb($symb); 
                   4157: #    my ($curpage,$mapId) =&Apache::lonnet::decode_symb($symb); 
                   4158: #    my $type=($curpage =~ /\.(page|sequence)/);
1.485     albertel 4159:     my $select = '<select name="selectpage">'."\n";
1.70      ng       4160:     my $ctr=0;
1.68      ng       4161:     foreach (@$titles) {
                   4162: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
1.485     albertel 4163: 	$select.='<option value="'.$ctr.'" '.
1.401     albertel 4164: 	    ($$symbx{$_} =~ /$curpage$/ ? 'selected="selected"' : '').
1.71      ng       4165: 	    '>'.$showtitle.'</option>'."\n";
1.70      ng       4166: 	$ctr++;
1.68      ng       4167:     }
1.485     albertel 4168:     $select.= '</select>';
1.539     riegler  4169:     $result.='&nbsp;<b>'.&mt('Problems from').':</b> '.$select."<br />\n";
1.485     albertel 4170: 
1.70      ng       4171:     $ctr=0;
                   4172:     foreach (@$titles) {
                   4173: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
                   4174: 	$result.='<input type="hidden" name="page'.$ctr.'" value="'.$$symbx{$_}.'" />'."\n";
                   4175: 	$result.='<input type="hidden" name="title'.$ctr.'" value="'.$showtitle.'" />'."\n";
                   4176: 	$ctr++;
                   4177:     }
1.72      ng       4178:     $result.='<input type="hidden" name="page" />'."\n".
                   4179: 	'<input type="hidden" name="title" />'."\n";
1.68      ng       4180: 
1.485     albertel 4181:     my $options =
                   4182: 	'<label><input type="radio" name="vProb" value="no" checked="checked" /> '.&mt('no').' </label>'."\n".
                   4183: 	'<label><input type="radio" name="vProb" value="yes" /> '.&mt('yes').' </label>'."<br />\n";
1.539     riegler  4184:     $result.='&nbsp;<b>'.&mt('View Problem Text').': </b>'.$options;
1.485     albertel 4185: 
                   4186:     $options =
                   4187: 	'<label><input type="radio" name="lastSub" value="none" /> '.&mt('none').' </label>'."\n".
                   4188: 	'<label><input type="radio" name="lastSub" value="datesub" checked="checked" /> '.&mt('by dates and submissions').'</label>'."\n".
                   4189: 	'<label><input type="radio" name="lastSub" value="all" /> '.&mt('all details').' </label>'."\n";
1.539     riegler  4190:     $result.='&nbsp;<b>'.&mt('Submissions').': </b>'.$options;
1.432     banghart 4191:     
                   4192:     $result.=&build_section_inputs();
1.442     banghart 4193:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
                   4194:     $result.='<input type="hidden" name="Status"  value="'.$stu_status.'" />'."\n".
1.72      ng       4195: 	'<input type="hidden" name="command" value="displayPage" />'."\n".
1.613     www      4196: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."<br />\n";
1.72      ng       4197: 
1.539     riegler  4198:     $result.='&nbsp;<b>'.&mt('Use CODE').': </b> <input type="text" name="CODE" value="" /> <br />'."\n";
1.382     albertel 4199: 
1.80      ng       4200:     $result.='&nbsp;<input type="button" '.
1.589     bisitz   4201:              'onclick="javascript:checkPickOne(this.form);" value="'.&mt('Next').' &rarr;" /><br />'."\n";
1.72      ng       4202: 
1.68      ng       4203:     $request->print($result);
                   4204: 
1.485     albertel 4205:     my $studentTable.='&nbsp;<b>'.&mt('Select a student you wish to grade and then click on the Next button.').'</b><br />'.
1.484     albertel 4206: 	&Apache::loncommon::start_data_table().
                   4207: 	&Apache::loncommon::start_data_table_header_row().
1.485     albertel 4208: 	'<th align="right">&nbsp;'.&mt('No.').'</th>'.
1.484     albertel 4209: 	'<th>'.&nameUserString('header').'</th>'.
1.485     albertel 4210: 	'<th align="right">&nbsp;'.&mt('No.').'</th>'.
1.484     albertel 4211: 	'<th>'.&nameUserString('header').'</th>'.
                   4212: 	&Apache::loncommon::end_data_table_header_row();
1.68      ng       4213:  
1.76      ng       4214:     my (undef,undef,$fullname) = &getclasslist($getsec,'1');
1.68      ng       4215:     my $ptr = 1;
1.294     albertel 4216:     foreach my $student (sort 
                   4217: 			 {
                   4218: 			     if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                   4219: 				 return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                   4220: 			     }
                   4221: 			     return $a cmp $b;
                   4222: 			 } (keys(%$fullname))) {
1.68      ng       4223: 	my ($uname,$udom) = split(/:/,$student);
1.484     albertel 4224: 	$studentTable.=($ptr%2==1 ? &Apache::loncommon::start_data_table_row()
                   4225:                                   : '</td>');
1.126     ng       4226: 	$studentTable.='<td align="right">'.$ptr.'&nbsp;</td>';
1.288     albertel 4227: 	$studentTable.='<td>&nbsp;<label><input type="radio" name="student" value="'.$student.'" /> '
                   4228: 	    .&nameUserString(undef,$$fullname{$student},$uname,$udom)."</label>\n";
1.484     albertel 4229: 	$studentTable.=
                   4230: 	    ($ptr%2 == 0 ? '</td>'.&Apache::loncommon::end_data_table_row() 
                   4231:                          : '');
1.68      ng       4232: 	$ptr++;
                   4233:     }
1.484     albertel 4234:     if ($ptr%2 == 0) {
                   4235: 	$studentTable.='</td><td>&nbsp;</td><td>&nbsp;</td>'.
                   4236: 	    &Apache::loncommon::end_data_table_row();
                   4237:     }
                   4238:     $studentTable.=&Apache::loncommon::end_data_table()."\n";
1.126     ng       4239:     $studentTable.='<input type="button" '.
1.589     bisitz   4240:                    'onclick="javascript:checkPickOne(this.form);" value="'.&mt('Next').' &rarr;" /></form>'."\n";
1.68      ng       4241: 
                   4242:     $request->print($studentTable);
                   4243: 
                   4244:     return '';
                   4245: }
                   4246: 
                   4247: sub getSymbMap {
1.582     raeburn  4248:     my ($map_error) = @_;
1.132     bowersj2 4249:     my $navmap = Apache::lonnavmaps::navmap->new();
1.582     raeburn  4250:     unless (ref($navmap)) {
                   4251:         if (ref($map_error)) {
                   4252:             $$map_error = 'navmap';
                   4253:         }
                   4254:         return;
                   4255:     }
1.68      ng       4256:     my %symbx = ();
                   4257:     my @titles = ();
1.117     bowersj2 4258:     my $minder = 0;
                   4259: 
                   4260:     # Gather every sequence that has problems.
1.240     albertel 4261:     my @sequences = $navmap->retrieveResources(undef, sub { shift->is_map(); },
                   4262: 					       1,0,1);
1.117     bowersj2 4263:     for my $sequence ($navmap->getById('0.0'), @sequences) {
1.241     albertel 4264: 	if ($navmap->hasResource($sequence, sub { shift->is_problem(); }, 0) ) {
1.381     albertel 4265: 	    my $title = $minder.'.'.
                   4266: 		&HTML::Entities::encode($sequence->compTitle(),'"\'&');
                   4267: 	    push(@titles, $title); # minder in case two titles are identical
                   4268: 	    $symbx{$title} = &HTML::Entities::encode($sequence->symb(),'"\'&');
1.117     bowersj2 4269: 	    $minder++;
1.241     albertel 4270: 	}
1.68      ng       4271:     }
                   4272:     return \@titles,\%symbx;
                   4273: }
                   4274: 
1.72      ng       4275: #
                   4276: #--- Displays a page/sequence w/wo problems, w/wo submissions
1.68      ng       4277: sub displayPage {
1.608     www      4278:     my ($request,$symb) = @_;
1.257     albertel 4279:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
                   4280:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
                   4281:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
                   4282:     my $pageTitle = $env{'form.page'};
1.103     albertel 4283:     my ($classlist,undef,$fullname) = &getclasslist($getsec,'1');
1.257     albertel 4284:     my ($uname,$udom) = split(/:/,$env{'form.student'});
                   4285:     my $usec=$classlist->{$env{'form.student'}}[5];
1.168     albertel 4286: 
                   4287:     #need to make sure we have the correct data for later EXT calls, 
                   4288:     #thus invalidate the cache
                   4289:     &Apache::lonnet::devalidatecourseresdata(
1.257     albertel 4290:                  $env{'course.'.$env{'request.course.id'}.'.num'},
                   4291:                  $env{'course.'.$env{'request.course.id'}.'.domain'});
1.168     albertel 4292:     &Apache::lonnet::clear_EXT_cache_status();
                   4293: 
1.103     albertel 4294:     if (!&canview($usec)) {
1.485     albertel 4295: 	$request->print('<span class="LC_warning">'.&mt('Unable to view requested student. ([_1])',$env{'form.student'}).'</span>');
1.103     albertel 4296: 	return;
                   4297:     }
1.398     albertel 4298:     my $result='<h3><span class="LC_info">&nbsp;'.$env{'form.title'}.'</span></h3>';
1.485     albertel 4299:     $result.='<h3>&nbsp;'.&mt('Student: [_1]',&nameUserString(undef,$$fullname{$env{'form.student'}},$uname,$udom)).
1.129     ng       4300: 	'</h3>'."\n";
1.500     albertel 4301:     $env{'form.CODE'} = uc($env{'form.CODE'});
1.501     foxr     4302:     if (&Apache::lonnet::validCODE(uc($env{'form.CODE'}))) {
1.485     albertel 4303: 	$result.='<h3>&nbsp;'.&mt('CODE: [_1]',$env{'form.CODE'}).'</h3>'."\n";
1.382     albertel 4304:     } else {
                   4305: 	delete($env{'form.CODE'});
                   4306:     }
1.71      ng       4307:     &sub_page_js($request);
                   4308:     $request->print($result);
                   4309: 
1.132     bowersj2 4310:     my $navmap = Apache::lonnavmaps::navmap->new();
1.582     raeburn  4311:     unless (ref($navmap)) {
                   4312:         $request->print(&navmap_errormsg());
                   4313:         return;
                   4314:     }
1.257     albertel 4315:     my ($mapUrl, $id, $resUrl)=&Apache::lonnet::decode_symb($env{'form.page'});
1.68      ng       4316:     my $map = $navmap->getResourceByUrl($resUrl); # add to navmaps
1.288     albertel 4317:     if (!$map) {
1.485     albertel 4318: 	$request->print('<span class="LC_warning">'.&mt('Unable to view requested sequence. ([_1])',$resUrl).'</span>');
1.288     albertel 4319: 	return; 
                   4320:     }
1.68      ng       4321:     my $iterator = $navmap->getIterator($map->map_start(),
                   4322: 					$map->map_finish());
                   4323: 
1.71      ng       4324:     my $studentTable='<form action="/adm/grades" method="post" name="gradePage">'."\n".
1.72      ng       4325: 	'<input type="hidden" name="command" value="gradeByPage" />'."\n".
1.257     albertel 4326: 	'<input type="hidden" name="fullname" value="'.$$fullname{$env{'form.student'}}.'" />'."\n".
                   4327: 	'<input type="hidden" name="student" value="'.$env{'form.student'}.'" />'."\n".
1.72      ng       4328: 	'<input type="hidden" name="page"    value="'.$pageTitle.'" />'."\n".
1.257     albertel 4329: 	'<input type="hidden" name="title"   value="'.$env{'form.title'}.'" />'."\n".
1.418     albertel 4330: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.613     www      4331: 	'<input type="hidden" name="overRideScore" value="no" />'."\n";
1.71      ng       4332: 
1.382     albertel 4333:     if (defined($env{'form.CODE'})) {
                   4334: 	$studentTable.=
                   4335: 	    '<input type="hidden" name="CODE" value="'.$env{'form.CODE'}.'" />'."\n";
                   4336:     }
1.381     albertel 4337:     my $checkIcon = '<img alt="'.&mt('Check Mark').
1.485     albertel 4338: 	'" src="'.&Apache::loncommon::lonhttpdurl($request->dir_config('lonIconsURL').'/check.gif').'" height="16" border="0" />';
1.71      ng       4339: 
1.594     bisitz   4340:     $studentTable.='&nbsp;<span class="LC_info">'.
                   4341:         &mt('Problems graded correct by the computer are marked with a [_1] symbol.',$checkIcon).
                   4342:         '</span>'."\n".
1.484     albertel 4343: 	&Apache::loncommon::start_data_table().
                   4344: 	&Apache::loncommon::start_data_table_header_row().
                   4345: 	'<th align="center">&nbsp;Prob.&nbsp;</th>'.
1.485     albertel 4346: 	'<th>&nbsp;'.($env{'form.vProb'} eq 'no' ? &mt('Title') : &mt('Problem Text')).'/'.&mt('Grade').'</th>'.
1.484     albertel 4347: 	&Apache::loncommon::end_data_table_header_row();
1.71      ng       4348: 
1.329     albertel 4349:     &Apache::lonxml::clear_problem_counter();
1.196     albertel 4350:     my ($depth,$question,$prob) = (1,1,1);
1.68      ng       4351:     $iterator->next(); # skip the first BEGIN_MAP
                   4352:     my $curRes = $iterator->next(); # for "current resource"
1.101     albertel 4353:     while ($depth > 0) {
1.68      ng       4354:         if($curRes == $iterator->BEGIN_MAP) { $depth++; }
1.100     bowersj2 4355:         if($curRes == $iterator->END_MAP) { $depth--; }
1.68      ng       4356: 
1.385     albertel 4357:         if (ref($curRes) && $curRes->is_problem()) {
1.91      albertel 4358: 	    my $parts = $curRes->parts();
1.68      ng       4359:             my $title = $curRes->compTitle();
1.71      ng       4360: 	    my $symbx = $curRes->symb();
1.484     albertel 4361: 	    $studentTable.=
                   4362: 		&Apache::loncommon::start_data_table_row().
                   4363: 		'<td align="center" valign="top" >'.$prob.
1.485     albertel 4364: 		(scalar(@{$parts}) == 1 ? '' 
                   4365: 		                        : '<br />('.&mt('[_1]&nbsp;parts)',
                   4366: 							scalar(@{$parts}))
                   4367: 		 ).
                   4368: 		 '</td>';
1.71      ng       4369: 	    $studentTable.='<td valign="top">';
1.382     albertel 4370: 	    my %form = ('CODE' => $env{'form.CODE'},);
1.257     albertel 4371: 	    if ($env{'form.vProb'} eq 'yes' ) {
1.144     albertel 4372: 		$studentTable.=&show_problem($request,$symbx,$uname,$udom,1,
1.383     albertel 4373: 					     undef,'both',\%form);
1.71      ng       4374: 	    } else {
1.382     albertel 4375: 		my $companswer = &Apache::loncommon::get_student_answers($symbx,$uname,$udom,$env{'request.course.id'},%form);
1.80      ng       4376: 		$companswer =~ s|<form(.*?)>||g;
                   4377: 		$companswer =~ s|</form>||g;
1.71      ng       4378: #		while ($companswer =~ /(<a href\=\"javascript:newWindow.*?Script Vars<\/a>)/s) { #<a href="javascript:newWindow</a>
1.116     ng       4379: #		    $companswer =~ s/$1/ /ms;
1.326     albertel 4380: #		    $request->print('match='.$1."<br />\n");
1.71      ng       4381: #		}
1.116     ng       4382: #		$companswer =~ s|<table border=\"1\">|<table border=\"0\">|g;
1.539     riegler  4383: 		$studentTable.='&nbsp;<b>'.$title.'</b>&nbsp;<br />&nbsp;<b>'.&mt('Correct answer').':</b><br />'.$companswer;
1.71      ng       4384: 	    }
                   4385: 
1.257     albertel 4386: 	    my %record = &Apache::lonnet::restore($symbx,$env{'request.course.id'},$udom,$uname);
1.125     ng       4387: 
1.257     albertel 4388: 	    if ($env{'form.lastSub'} eq 'datesub') {
1.71      ng       4389: 		if ($record{'version'} eq '') {
1.485     albertel 4390: 		    $studentTable.='<br />&nbsp;<span class="LC_warning">'.&mt('No recorded submission for this problem.').'</span><br />';
1.71      ng       4391: 		} else {
1.116     ng       4392: 		    my %responseType = ();
                   4393: 		    foreach my $partid (@{$parts}) {
1.147     albertel 4394: 			my @responseIds =$curRes->responseIds($partid);
                   4395: 			my @responseType =$curRes->responseType($partid);
                   4396: 			my %responseIds;
                   4397: 			for (my $i=0;$i<=$#responseIds;$i++) {
                   4398: 			    $responseIds{$responseIds[$i]}=$responseType[$i];
                   4399: 			}
                   4400: 			$responseType{$partid} = \%responseIds;
1.116     ng       4401: 		    }
1.148     albertel 4402: 		    $studentTable.= &displaySubByDates($symbx,\%record,$parts,\%responseType,$checkIcon,$uname,$udom);
1.147     albertel 4403: 
1.71      ng       4404: 		}
1.257     albertel 4405: 	    } elsif ($env{'form.lastSub'} eq 'all') {
                   4406: 		my $last = ($env{'form.lastSub'} eq 'last' ? 'last' : '');
1.71      ng       4407: 		$studentTable.=&Apache::loncommon::get_previous_attempt($symbx,$uname,$udom,
1.257     albertel 4408: 									$env{'request.course.id'},
1.71      ng       4409: 									'','.submission');
                   4410:  
                   4411: 	    }
1.103     albertel 4412: 	    if (&canmodify($usec)) {
1.585     bisitz   4413:             $studentTable.=&gradeBox_start();
1.103     albertel 4414: 		foreach my $partid (@{$parts}) {
                   4415: 		    $studentTable.=&gradeBox($request,$symbx,$uname,$udom,$question,$partid,\%record);
                   4416: 		    $studentTable.='<input type="hidden" name="q_'.$question.'" value="'.$partid.'" />'."\n";
                   4417: 		    $question++;
                   4418: 		}
1.585     bisitz   4419:             $studentTable.=&gradeBox_end();
1.196     albertel 4420: 		$prob++;
1.71      ng       4421: 	    }
                   4422: 	    $studentTable.='</td></tr>';
1.68      ng       4423: 
1.103     albertel 4424: 	}
1.68      ng       4425:         $curRes = $iterator->next();
                   4426:     }
                   4427: 
1.589     bisitz   4428:     $studentTable.=
                   4429:         '</table>'."\n".
                   4430:         '<input type="button" value="'.&mt('Save').'" '.
                   4431:         'onclick="javascript:checkSubmitPage(this.form,'.$question.');" />'.
                   4432:         '</form>'."\n";
1.71      ng       4433:     $request->print($studentTable);
                   4434: 
                   4435:     return '';
1.119     ng       4436: }
                   4437: 
                   4438: sub displaySubByDates {
1.148     albertel 4439:     my ($symb,$record,$parts,$responseType,$checkIcon,$uname,$udom) = @_;
1.224     albertel 4440:     my $isCODE=0;
1.335     albertel 4441:     my $isTask = ($symb =~/\.task$/);
1.224     albertel 4442:     if (exists($record->{'resource.CODE'})) { $isCODE=1; }
1.467     albertel 4443:     my $studentTable=&Apache::loncommon::start_data_table().
                   4444: 	&Apache::loncommon::start_data_table_header_row().
                   4445: 	'<th>'.&mt('Date/Time').'</th>'.
                   4446: 	($isCODE?'<th>'.&mt('CODE').'</th>':'').
                   4447: 	'<th>'.&mt('Submission').'</th>'.
                   4448: 	'<th>'.&mt('Status').'</th>'.
                   4449: 	&Apache::loncommon::end_data_table_header_row();
1.119     ng       4450:     my ($version);
                   4451:     my %mark;
1.148     albertel 4452:     my %orders;
1.119     ng       4453:     $mark{'correct_by_student'} = $checkIcon;
1.147     albertel 4454:     if (!exists($$record{'1:timestamp'})) {
1.539     riegler  4455: 	return '<br />&nbsp;<span class="LC_warning">'.&mt('Nothing submitted - no attempts.').'</span><br />';
1.147     albertel 4456:     }
1.335     albertel 4457: 
                   4458:     my $interaction;
1.525     raeburn  4459:     my $no_increment = 1;
1.119     ng       4460:     for ($version=1;$version<=$$record{'version'};$version++) {
1.467     albertel 4461: 	my $timestamp = 
                   4462: 	    &Apache::lonlocal::locallocaltime($$record{$version.':timestamp'});
1.335     albertel 4463: 	if (exists($$record{$version.':resource.0.version'})) {
                   4464: 	    $interaction = $$record{$version.':resource.0.version'};
                   4465: 	}
                   4466: 
                   4467: 	my $where = ($isTask ? "$version:resource.$interaction"
                   4468: 		             : "$version:resource");
1.467     albertel 4469: 	$studentTable.=&Apache::loncommon::start_data_table_row().
                   4470: 	    '<td>'.$timestamp.'</td>';
1.224     albertel 4471: 	if ($isCODE) {
                   4472: 	    $studentTable.='<td>'.$record->{$version.':resource.CODE'}.'</td>';
                   4473: 	}
1.119     ng       4474: 	my @versionKeys = split(/\:/,$$record{$version.':keys'});
                   4475: 	my @displaySub = ();
                   4476: 	foreach my $partid (@{$parts}) {
1.596     raeburn  4477:             my $hidden;
                   4478:             if (($$record{$version.':resource.'.$partid.'.type'} eq 'anonsurvey') ||
                   4479:                 ($$record{$version.':resource.'.$partid.'.type'} eq 'anonsurveycred')) {
                   4480:                 $hidden = 1;
                   4481:             }
1.335     albertel 4482: 	    my @matchKey = ($isTask ? sort(grep /^resource\.\d+\.\Q$partid\E\.award$/,@versionKeys)
                   4483: 			            : sort(grep /^resource\.\Q$partid\E\..*?\.submission$/,@versionKeys));
                   4484: 	    
1.122     ng       4485: #	    next if ($$record{"$version:resource.$partid.solved"} eq '');
1.324     albertel 4486: 	    my $display_part=&get_display_part($partid,$symb);
1.147     albertel 4487: 	    foreach my $matchKey (@matchKey) {
1.198     albertel 4488: 		if (exists($$record{$version.':'.$matchKey}) &&
                   4489: 		    $$record{$version.':'.$matchKey} ne '') {
1.596     raeburn  4490:                     
1.335     albertel 4491: 		    my ($responseId)= ($isTask ? ($matchKey=~ /^resource\.(.*?)\.\Q$partid\E\.award$/)
                   4492: 				               : ($matchKey=~ /^resource\.\Q$partid\E\.(.*?)\.submission$/));
1.577     bisitz   4493:                     $displaySub[0].='<span class="LC_nobreak"';
                   4494:                     $displaySub[0].='<b>'.&mt('Part: [_1]',$display_part).'</b>'
                   4495:                                    .' <span class="LC_internal_info">'
1.625     www      4496:                                    .'('.&mt('Response ID: [_1]',$responseId).')'
1.577     bisitz   4497:                                    .'</span>'
                   4498:                                    .' <b>';
1.596     raeburn  4499:                     if ($hidden) {
                   4500:                         $displaySub[0].= &mt('Anonymous Survey').'</b>';
                   4501:                     } else {
                   4502: 		        if ($$record{"$where.$partid.tries"} eq '') {
                   4503: 			    $displaySub[0].=&mt('Trial not counted');
                   4504: 		        } else {
                   4505: 			    $displaySub[0].=&mt('Trial: [_1]',
1.467     albertel 4506: 					    $$record{"$where.$partid.tries"});
1.596     raeburn  4507: 		        }
                   4508: 		        my $responseType=($isTask ? 'Task'
1.335     albertel 4509:                                               : $responseType->{$partid}->{$responseId});
1.596     raeburn  4510: 		        if (!exists($orders{$partid})) { $orders{$partid}={}; }
                   4511: 		        if (!exists($orders{$partid}->{$responseId})) {
                   4512: 			    $orders{$partid}->{$responseId}=
                   4513: 			        &get_order($partid,$responseId,$symb,$uname,$udom,
                   4514:                                            $no_increment);
                   4515: 		        }
                   4516: 		        $displaySub[0].='</b></span>'; # /nobreak
                   4517: 		        $displaySub[0].='&nbsp; '.
                   4518: 			    &cleanRecord($$record{$version.':'.$matchKey},$responseType,$symb,$partid,$responseId,$record,$orders{$partid}->{$responseId},"$version:",$uname,$udom).'<br />';
                   4519:                     }
1.147     albertel 4520: 		}
                   4521: 	    }
1.335     albertel 4522: 	    if (exists($$record{"$where.$partid.checkedin"})) {
1.485     albertel 4523: 		$displaySub[1].=&mt('Checked in by [_1] into slot [_2]',
                   4524: 				    $$record{"$where.$partid.checkedin"},
                   4525: 				    $$record{"$where.$partid.checkedin.slot"}).
                   4526: 					'<br />';
1.335     albertel 4527: 	    }
                   4528: 	    if (exists $$record{"$where.$partid.award"}) {
1.485     albertel 4529: 		$displaySub[1].='<b>'.&mt('Part:').'</b>&nbsp;'.$display_part.' &nbsp;'.
1.335     albertel 4530: 		    lc($$record{"$where.$partid.award"}).' '.
                   4531: 		    $mark{$$record{"$where.$partid.solved"}}.
1.147     albertel 4532: 		    '<br />';
                   4533: 	    }
1.335     albertel 4534: 	    if (exists $$record{"$where.$partid.regrader"}) {
                   4535: 		$displaySub[2].=$$record{"$where.$partid.regrader"}.
                   4536: 		    ' (<b>'.&mt('Part').':</b> '.$display_part.')';
                   4537: 	    } elsif ($$record{"$version:resource.$partid.regrader"} =~ /\S/) {
                   4538: 		$displaySub[2].=
                   4539: 		    $$record{"$version:resource.$partid.regrader"}.
1.207     albertel 4540: 		    ' (<b>'.&mt('Part').':</b> '.$display_part.')';
1.147     albertel 4541: 	    }
                   4542: 	}
                   4543: 	# needed because old essay regrader has not parts info
                   4544: 	if (exists $$record{"$version:resource.regrader"}) {
                   4545: 	    $displaySub[2].=$$record{"$version:resource.regrader"};
                   4546: 	}
                   4547: 	$studentTable.='<td>'.$displaySub[0].'&nbsp;</td><td>'.$displaySub[1];
                   4548: 	if ($displaySub[2]) {
1.467     albertel 4549: 	    $studentTable.=&mt('Manually graded by [_1]',$displaySub[2]);
1.147     albertel 4550: 	}
1.467     albertel 4551: 	$studentTable.='&nbsp;</td>'.
                   4552: 	    &Apache::loncommon::end_data_table_row();
1.119     ng       4553:     }
1.467     albertel 4554:     $studentTable.=&Apache::loncommon::end_data_table();
1.119     ng       4555:     return $studentTable;
1.71      ng       4556: }
                   4557: 
                   4558: sub updateGradeByPage {
1.608     www      4559:     my ($request,$symb) = @_;
1.71      ng       4560: 
1.257     albertel 4561:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
                   4562:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
                   4563:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
                   4564:     my $pageTitle = $env{'form.page'};
1.103     albertel 4565:     my ($classlist,undef,$fullname) = &getclasslist($getsec,'1');
1.257     albertel 4566:     my ($uname,$udom) = split(/:/,$env{'form.student'});
                   4567:     my $usec=$classlist->{$env{'form.student'}}[5];
1.103     albertel 4568:     if (!&canmodify($usec)) {
1.526     raeburn  4569: 	$request->print('<span class="LC_warning">'.&mt('Unable to modify requested student ([_1])',$env{'form.student'}).'</span>');
1.103     albertel 4570: 	return;
                   4571:     }
1.398     albertel 4572:     my $result='<h3><span class="LC_info">&nbsp;'.$env{'form.title'}.'</span></h3>';
1.526     raeburn  4573:     $result.='<h3>&nbsp;'.&mt('Student: ').&nameUserString(undef,$env{'form.fullname'},$uname,$udom).
1.129     ng       4574: 	'</h3>'."\n";
1.70      ng       4575: 
1.68      ng       4576:     $request->print($result);
                   4577: 
1.582     raeburn  4578: 
1.132     bowersj2 4579:     my $navmap = Apache::lonnavmaps::navmap->new();
1.582     raeburn  4580:     unless (ref($navmap)) {
                   4581:         $request->print(&navmap_errormsg());
                   4582:         return;
                   4583:     }
1.257     albertel 4584:     my ($mapUrl, $id, $resUrl) = &Apache::lonnet::decode_symb( $env{'form.page'});
1.71      ng       4585:     my $map = $navmap->getResourceByUrl($resUrl); # add to navmaps
1.288     albertel 4586:     if (!$map) {
1.527     raeburn  4587: 	$request->print('<span class="LC_warning">'.&mt('Unable to grade requested sequence ([_1]).',$resUrl).'</span>');
1.288     albertel 4588: 	return; 
                   4589:     }
1.71      ng       4590:     my $iterator = $navmap->getIterator($map->map_start(),
                   4591: 					$map->map_finish());
1.70      ng       4592: 
1.484     albertel 4593:     my $studentTable=
                   4594: 	&Apache::loncommon::start_data_table().
                   4595: 	&Apache::loncommon::start_data_table_header_row().
1.485     albertel 4596: 	'<th align="center">&nbsp;'.&mt('Prob.').'&nbsp;</th>'.
                   4597: 	'<th>&nbsp;'.&mt('Title').'&nbsp;</th>'.
                   4598: 	'<th>&nbsp;'.&mt('Previous Score').'&nbsp;</th>'.
                   4599: 	'<th>&nbsp;'.&mt('New Score').'&nbsp;</th>'.
1.484     albertel 4600: 	&Apache::loncommon::end_data_table_header_row();
1.71      ng       4601: 
                   4602:     $iterator->next(); # skip the first BEGIN_MAP
                   4603:     my $curRes = $iterator->next(); # for "current resource"
1.196     albertel 4604:     my ($depth,$question,$prob,$changeflag)= (1,1,1,0);
1.101     albertel 4605:     while ($depth > 0) {
1.71      ng       4606:         if($curRes == $iterator->BEGIN_MAP) { $depth++; }
1.100     bowersj2 4607:         if($curRes == $iterator->END_MAP) { $depth--; }
1.71      ng       4608: 
1.385     albertel 4609:         if (ref($curRes) && $curRes->is_problem()) {
1.91      albertel 4610: 	    my $parts = $curRes->parts();
1.71      ng       4611:             my $title = $curRes->compTitle();
                   4612: 	    my $symbx = $curRes->symb();
1.484     albertel 4613: 	    $studentTable.=
                   4614: 		&Apache::loncommon::start_data_table_row().
                   4615: 		'<td align="center" valign="top" >'.$prob.
1.485     albertel 4616: 		(scalar(@{$parts}) == 1 ? '' 
1.526     raeburn  4617:                                         : '<br />('.&mt('[quant,_1,&nbsp;part]',scalar(@{$parts}))
                   4618: 		.')').'</td>';
1.71      ng       4619: 	    $studentTable.='<td valign="top">&nbsp;<b>'.$title.'</b>&nbsp;</td>';
                   4620: 
                   4621: 	    my %newrecord=();
                   4622: 	    my @displayPts=();
1.269     raeburn  4623:             my %aggregate = ();
                   4624:             my $aggregateflag = 0;
1.71      ng       4625: 	    foreach my $partid (@{$parts}) {
1.257     albertel 4626: 		my $newpts = $env{'form.GD_BOX'.$question.'_'.$partid};
                   4627: 		my $oldpts = $env{'form.oldpts'.$question.'_'.$partid};
1.71      ng       4628: 
1.257     albertel 4629: 		my $wgt = $env{'form.WGT'.$question.'_'.$partid} != 0 ? 
                   4630: 		    $env{'form.WGT'.$question.'_'.$partid} : 1;
1.71      ng       4631: 		my $partial = $newpts/$wgt;
                   4632: 		my $score;
                   4633: 		if ($partial > 0) {
                   4634: 		    $score = 'correct_by_override';
1.125     ng       4635: 		} elsif ($newpts ne '') { #empty is taken as 0
1.71      ng       4636: 		    $score = 'incorrect_by_override';
                   4637: 		}
1.257     albertel 4638: 		my $dropMenu = $env{'form.GD_SEL'.$question.'_'.$partid};
1.125     ng       4639: 		if ($dropMenu eq 'excused') {
1.71      ng       4640: 		    $partial = '';
                   4641: 		    $score = 'excused';
1.125     ng       4642: 		} elsif ($dropMenu eq 'reset status'
1.257     albertel 4643: 			 && $env{'form.solved'.$question.'_'.$partid} ne '') { #update only if previous record exists
1.125     ng       4644: 		    $newrecord{'resource.'.$partid.'.tries'} = 0;
                   4645: 		    $newrecord{'resource.'.$partid.'.solved'} = '';
                   4646: 		    $newrecord{'resource.'.$partid.'.award'} = '';
                   4647: 		    $newrecord{'resource.'.$partid.'.awarded'} = 0;
1.257     albertel 4648: 		    $newrecord{'resource.'.$partid.'.regrader'} = "$env{'user.name'}:$env{'user.domain'}";
1.125     ng       4649: 		    $changeflag++;
                   4650: 		    $newpts = '';
1.269     raeburn  4651:                     
                   4652:                     my $aggtries =  $env{'form.aggtries'.$question.'_'.$partid};
                   4653:                     my $totaltries = $env{'form.totaltries'.$question.'_'.$partid};
                   4654:                     my $solvedstatus = $env{'form.solved'.$question.'_'.$partid};
                   4655:                     if ($aggtries > 0) {
                   4656:                         &decrement_aggs($symbx,$partid,\%aggregate,$aggtries,$totaltries,$solvedstatus);
                   4657:                         $aggregateflag = 1;
                   4658:                     }
1.71      ng       4659: 		}
1.324     albertel 4660: 		my $display_part=&get_display_part($partid,$curRes->symb());
1.257     albertel 4661: 		my $oldstatus = $env{'form.solved'.$question.'_'.$partid};
1.526     raeburn  4662: 		$displayPts[0].='&nbsp;<b>'.&mt('Part').':</b> '.$display_part.' = '.
1.71      ng       4663: 		    (($oldstatus eq 'excused') ? 'excused' : $oldpts).
1.326     albertel 4664: 		    '&nbsp;<br />';
1.526     raeburn  4665: 		$displayPts[1].='&nbsp;<b>'.&mt('Part').':</b> '.$display_part.' = '.
1.125     ng       4666: 		     (($score eq 'excused') ? 'excused' : $newpts).
1.326     albertel 4667: 		    '&nbsp;<br />';
1.71      ng       4668: 		$question++;
1.380     albertel 4669: 		next if ($dropMenu eq 'reset status' || ($newpts eq $oldpts && $score ne 'excused'));
1.125     ng       4670: 
1.71      ng       4671: 		$newrecord{'resource.'.$partid.'.awarded'}  = $partial if $partial ne '';
1.125     ng       4672: 		$newrecord{'resource.'.$partid.'.solved'}   = $score if $score ne '';
1.257     albertel 4673: 		$newrecord{'resource.'.$partid.'.regrader'} = "$env{'user.name'}:$env{'user.domain'}"
1.125     ng       4674: 		    if (scalar(keys(%newrecord)) > 0);
1.71      ng       4675: 
                   4676: 		$changeflag++;
                   4677: 	    }
                   4678: 	    if (scalar(keys(%newrecord)) > 0) {
1.382     albertel 4679: 		my %record = 
                   4680: 		    &Apache::lonnet::restore($symbx,$env{'request.course.id'},
                   4681: 					     $udom,$uname);
                   4682: 
                   4683: 		if (&Apache::lonnet::validCODE($env{'form.CODE'})) {
                   4684: 		    $newrecord{'resource.CODE'} = $env{'form.CODE'};
                   4685: 		} elsif (&Apache::lonnet::validCODE($record{'resource.CODE'})) {
                   4686: 		    $newrecord{'resource.CODE'} = '';
                   4687: 		}
1.257     albertel 4688: 		&Apache::lonnet::cstore(\%newrecord,$symbx,$env{'request.course.id'},
1.71      ng       4689: 					$udom,$uname);
1.382     albertel 4690: 		%record = &Apache::lonnet::restore($symbx,
                   4691: 						   $env{'request.course.id'},
                   4692: 						   $udom,$uname);
1.380     albertel 4693: 		&check_and_remove_from_queue($parts,\%record,undef,$symbx,
                   4694: 					     $cdom,$cnum,$udom,$uname);
1.71      ng       4695: 	    }
1.380     albertel 4696: 	    
1.269     raeburn  4697:             if ($aggregateflag) {
                   4698:                 &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
                   4699:                       $env{'course.'.$env{'request.course.id'}.'.domain'},
                   4700:                       $env{'course.'.$env{'request.course.id'}.'.num'});
                   4701:             }
1.125     ng       4702: 
1.71      ng       4703: 	    $studentTable.='<td valign="top">'.$displayPts[0].'</td>'.
                   4704: 		'<td valign="top">'.$displayPts[1].'</td>'.
1.484     albertel 4705: 		&Apache::loncommon::end_data_table_row();
1.68      ng       4706: 
1.196     albertel 4707: 	    $prob++;
1.68      ng       4708: 	}
1.71      ng       4709:         $curRes = $iterator->next();
1.68      ng       4710:     }
1.98      albertel 4711: 
1.484     albertel 4712:     $studentTable.=&Apache::loncommon::end_data_table();
1.526     raeburn  4713:     my $grademsg=($changeflag == 0 ? &mt('No score was changed or updated.') :
                   4714: 		  &mt('The scores were changed for [quant,_1,problem].',
                   4715: 		  $changeflag));
1.76      ng       4716:     $request->print($grademsg.$studentTable);
1.68      ng       4717: 
1.70      ng       4718:     return '';
                   4719: }
                   4720: 
1.72      ng       4721: #-------- end of section for handling grading by page/sequence ---------
                   4722: #
                   4723: #-------------------------------------------------------------------
                   4724: 
1.581     www      4725: #-------------------- Bubblesheet (Scantron) Grading -------------------
1.75      albertel 4726: #
                   4727: #------ start of section for handling grading by page/sequence ---------
                   4728: 
1.423     albertel 4729: =pod
                   4730: 
                   4731: =head1 Bubble sheet grading routines
                   4732: 
1.424     albertel 4733:   For this documentation:
                   4734: 
                   4735:    'scanline' refers to the full line of characters
                   4736:    from the file that we are parsing that represents one entire sheet
                   4737: 
                   4738:    'bubble line' refers to the data
                   4739:    representing the line of bubbles that are on the physical bubble sheet
                   4740: 
                   4741: 
                   4742: The overall process is that a scanned in bubble sheet data is uploaded
                   4743: into a course. When a user wants to grade, they select a
                   4744: sequence/folder of resources, a file of bubble sheet info, and pick
                   4745: one of the predefined configurations for what each scanline looks
                   4746: like.
                   4747: 
                   4748: Next each scanline is checked for any errors of either 'missing
1.435     foxr     4749: bubbles' (it's an error because it may have been mis-scanned
1.424     albertel 4750: because too light bubbling), 'double bubble' (each bubble line should
                   4751: have no more that one letter picked), invalid or duplicated CODE,
1.556     weissno  4752: invalid student/employee ID
1.424     albertel 4753: 
                   4754: If the CODE option is used that determines the randomization of the
1.556     weissno  4755: homework problems, either way the student/employee ID is looked up into a
1.424     albertel 4756: username:domain.
                   4757: 
                   4758: During the validation phase the instructor can choose to skip scanlines. 
                   4759: 
1.435     foxr     4760: After the validation phase, there are now 3 bubble sheet files
1.424     albertel 4761: 
                   4762:   scantron_original_filename (unmodified original file)
                   4763:   scantron_corrected_filename (file where the corrected information has replaced the original information)
                   4764:   scantron_skipped_filename (contains the exact text of scanlines that where skipped)
                   4765: 
                   4766: Also there is a separate hash nohist_scantrondata that contains extra
                   4767: correction information that isn't representable in the bubble sheet
                   4768: file (see &scantron_getfile() for more information)
                   4769: 
                   4770: After all scanlines are either valid, marked as valid or skipped, then
                   4771: foreach line foreach problem in the picked sequence, an ssi request is
                   4772: made that simulates a user submitting their selected letter(s) against
                   4773: the homework problem.
1.423     albertel 4774: 
                   4775: =over 4
                   4776: 
                   4777: 
                   4778: 
                   4779: =item defaultFormData
                   4780: 
                   4781:   Returns html hidden inputs used to hold context/default values.
                   4782: 
                   4783:  Arguments:
                   4784:   $symb - $symb of the current resource 
                   4785: 
                   4786: =cut
1.422     foxr     4787: 
1.81      albertel 4788: sub defaultFormData {
1.324     albertel 4789:     my ($symb)=@_;
1.613     www      4790:     return '<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />';
1.81      albertel 4791: }
                   4792: 
1.447     foxr     4793: 
1.423     albertel 4794: =pod 
                   4795: 
                   4796: =item getSequenceDropDown
                   4797: 
                   4798:    Return html dropdown of possible sequences to grade
                   4799:  
                   4800:  Arguments:
1.582     raeburn  4801:    $symb - $symb of the current resource
                   4802:    $map_error - ref to scalar which will container error if
                   4803:                 $navmap object is unavailable in &getSymbMap().
1.423     albertel 4804: 
                   4805: =cut
1.422     foxr     4806: 
1.75      albertel 4807: sub getSequenceDropDown {
1.582     raeburn  4808:     my ($symb,$map_error)=@_;
1.75      albertel 4809:     my $result='<select name="selectpage">'."\n";
1.582     raeburn  4810:     my ($titles,$symbx) = &getSymbMap($map_error);
                   4811:     if (ref($map_error)) {
                   4812:         return if ($$map_error);
                   4813:     }
1.137     albertel 4814:     my ($curpage)=&Apache::lonnet::decode_symb($symb); 
1.75      albertel 4815:     my $ctr=0;
                   4816:     foreach (@$titles) {
                   4817: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
                   4818: 	$result.='<option value="'.$$symbx{$_}.'" '.
1.401     albertel 4819: 	    ($$symbx{$_} =~ /$curpage$/ ? 'selected="selected"' : '').
1.75      albertel 4820: 	    '>'.$showtitle.'</option>'."\n";
                   4821: 	$ctr++;
                   4822:     }
                   4823:     $result.= '</select>';
                   4824:     return $result;
                   4825: }
                   4826: 
1.495     albertel 4827: my %bubble_lines_per_response;     # no. bubble lines for each response.
1.554     raeburn  4828:                                    # key is zero-based index - 0, 1, 2 ...
1.495     albertel 4829: 
                   4830: my %first_bubble_line;             # First bubble line no. for each bubble.
                   4831: 
1.509     raeburn  4832: my %subdivided_bubble_lines;       # no. bubble lines for optionresponse, 
                   4833:                                    # matchresponse or rankresponse, where 
                   4834:                                    # an individual response can have multiple 
                   4835:                                    # lines
1.503     raeburn  4836: 
                   4837: my %responsetype_per_response;     # responsetype for each response
                   4838: 
1.495     albertel 4839: # Save and restore the bubble lines array to the form env.
                   4840: 
                   4841: 
                   4842: sub save_bubble_lines {
                   4843:     foreach my $line (keys(%bubble_lines_per_response)) {
                   4844: 	$env{"form.scantron.bubblelines.$line"}  = $bubble_lines_per_response{$line};
                   4845: 	$env{"form.scantron.first_bubble_line.$line"} =
                   4846: 	    $first_bubble_line{$line};
1.503     raeburn  4847:         $env{"form.scantron.sub_bubblelines.$line"} = 
                   4848:             $subdivided_bubble_lines{$line};
                   4849:         $env{"form.scantron.responsetype.$line"} =
                   4850:             $responsetype_per_response{$line};
1.495     albertel 4851:     }
                   4852: }
                   4853: 
                   4854: 
                   4855: sub restore_bubble_lines {
                   4856:     my $line = 0;
                   4857:     %bubble_lines_per_response = ();
                   4858:     while ($env{"form.scantron.bubblelines.$line"}) {
                   4859: 	my $value = $env{"form.scantron.bubblelines.$line"};
                   4860: 	$bubble_lines_per_response{$line} = $value;
                   4861: 	$first_bubble_line{$line}  =
                   4862: 	    $env{"form.scantron.first_bubble_line.$line"};
1.503     raeburn  4863:         $subdivided_bubble_lines{$line} =
                   4864:             $env{"form.scantron.sub_bubblelines.$line"};
                   4865:         $responsetype_per_response{$line} =
                   4866:             $env{"form.scantron.responsetype.$line"};
1.495     albertel 4867: 	$line++;
                   4868:     }
                   4869: }
                   4870: 
                   4871: #  Given the parsed scanline, get the response for 
                   4872: #  'answer' number n:
                   4873: 
                   4874: sub get_response_bubbles {
                   4875:     my ($parsed_line, $response)  = @_;
                   4876: 
                   4877:     my $bubble_line = $first_bubble_line{$response-1} +1;
                   4878:     my $bubble_lines= $bubble_lines_per_response{$response-1};
                   4879:     
                   4880:     my $selected = "";
                   4881: 
                   4882:     for (my $bline = 0; $bline < $bubble_lines; $bline++) {
                   4883: 	$selected .= $$parsed_line{"scantron.$bubble_line.answer"}.":";
                   4884: 	$bubble_line++;
                   4885:     }
                   4886:     return $selected;
                   4887: }
1.423     albertel 4888: 
                   4889: =pod 
                   4890: 
                   4891: =item scantron_filenames
                   4892: 
                   4893:    Returns a list of the scantron files in the current course 
                   4894: 
                   4895: =cut
1.422     foxr     4896: 
1.202     albertel 4897: sub scantron_filenames {
1.257     albertel 4898:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   4899:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
1.517     raeburn  4900:     my $getpropath = 1;
1.157     albertel 4901:     my @files=&Apache::lonnet::dirlist('userfiles',$cdom,$cname,
1.517     raeburn  4902:                                        $getpropath);
1.202     albertel 4903:     my @possiblenames;
1.201     albertel 4904:     foreach my $filename (sort(@files)) {
1.157     albertel 4905: 	($filename)=split(/&/,$filename);
                   4906: 	if ($filename!~/^scantron_orig_/) { next ; }
                   4907: 	$filename=~s/^scantron_orig_//;
1.202     albertel 4908: 	push(@possiblenames,$filename);
                   4909:     }
                   4910:     return @possiblenames;
                   4911: }
                   4912: 
1.423     albertel 4913: =pod 
                   4914: 
                   4915: =item scantron_uploads
                   4916: 
                   4917:    Returns  html drop-down list of scantron files in current course.
                   4918: 
                   4919:  Arguments:
                   4920:    $file2grade - filename to set as selected in the dropdown
                   4921: 
                   4922: =cut
1.422     foxr     4923: 
1.202     albertel 4924: sub scantron_uploads {
1.209     ng       4925:     my ($file2grade) = @_;
1.202     albertel 4926:     my $result=	'<select name="scantron_selectfile">';
                   4927:     $result.="<option></option>";
                   4928:     foreach my $filename (sort(&scantron_filenames())) {
1.401     albertel 4929: 	$result.="<option".($filename eq $file2grade ? ' selected="selected"':'').">$filename</option>\n";
1.81      albertel 4930:     }
                   4931:     $result.="</select>";
                   4932:     return $result;
                   4933: }
                   4934: 
1.423     albertel 4935: =pod 
                   4936: 
                   4937: =item scantron_scantab
                   4938: 
                   4939:   Returns html drop down of the scantron formats in the scantronformat.tab
                   4940:   file.
                   4941: 
                   4942: =cut
1.422     foxr     4943: 
1.82      albertel 4944: sub scantron_scantab {
                   4945:     my $result='<select name="scantron_format">'."\n";
1.191     albertel 4946:     $result.='<option></option>'."\n";
1.518     raeburn  4947:     my @lines = &get_scantronformat_file();
                   4948:     if (@lines > 0) {
                   4949:         foreach my $line (@lines) {
                   4950:             next if (($line =~ /^\#/) || ($line eq ''));
                   4951: 	    my ($name,$descrip)=split(/:/,$line);
                   4952: 	    $result.='<option value="'.$name.'">'.$descrip.'</option>'."\n";
                   4953:         }
1.82      albertel 4954:     }
                   4955:     $result.='</select>'."\n";
1.518     raeburn  4956:     return $result;
                   4957: }
                   4958: 
                   4959: =pod
                   4960: 
                   4961: =item get_scantronformat_file
                   4962: 
                   4963:   Returns an array containing lines from the scantron format file for
                   4964:   the domain of the course.
                   4965: 
                   4966:   If a url for a custom.tab file is listed in domain's configuration.db, 
                   4967:   lines are from this file.
                   4968: 
                   4969:   Otherwise, if a default.tab has been published in RES space by the 
                   4970:   domainconfig user, lines are from this file.
                   4971: 
                   4972:   Otherwise, fall back to getting lines from the legacy file on the
1.519     raeburn  4973:   local server:  /home/httpd/lonTabs/default_scantronformat.tab    
1.82      albertel 4974: 
1.518     raeburn  4975: =cut
                   4976: 
                   4977: sub get_scantronformat_file {
                   4978:     my $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
                   4979:     my %domconfig = &Apache::lonnet::get_dom('configuration',['scantron'],$cdom);
                   4980:     my $gottab = 0;
                   4981:     my @lines;
                   4982:     if (ref($domconfig{'scantron'}) eq 'HASH') {
                   4983:         if ($domconfig{'scantron'}{'scantronformat'} ne '') {
                   4984:             my $formatfile = &Apache::lonnet::getfile($Apache::lonnet::perlvar{'lonDocRoot'}.$domconfig{'scantron'}{'scantronformat'});
                   4985:             if ($formatfile ne '-1') {
                   4986:                 @lines = split("\n",$formatfile,-1);
                   4987:                 $gottab = 1;
                   4988:             }
                   4989:         }
                   4990:     }
                   4991:     if (!$gottab) {
                   4992:         my $confname = $cdom.'-domainconfig';
                   4993:         my $default = $Apache::lonnet::perlvar{'lonDocRoot'}.'/res/'.$cdom.'/'.$confname.'/default.tab';
                   4994:         my $formatfile =  &Apache::lonnet::getfile($default);
                   4995:         if ($formatfile ne '-1') {
                   4996:             @lines = split("\n",$formatfile,-1);
                   4997:             $gottab = 1;
                   4998:         }
                   4999:     }
                   5000:     if (!$gottab) {
1.519     raeburn  5001:         my @domains = &Apache::lonnet::current_machine_domains();
                   5002:         if (grep(/^\Q$cdom\E$/,@domains)) {
                   5003:             my $fh=Apache::File->new($Apache::lonnet::perlvar{'lonTabDir'}.'/scantronformat.tab');
                   5004:             @lines = <$fh>;
                   5005:             close($fh);
                   5006:         } else {
                   5007:             my $fh=Apache::File->new($Apache::lonnet::perlvar{'lonTabDir'}.'/default_scantronformat.tab');
                   5008:             @lines = <$fh>;
                   5009:             close($fh);
                   5010:         }
1.518     raeburn  5011:     }
                   5012:     return @lines;
1.82      albertel 5013: }
                   5014: 
1.423     albertel 5015: =pod 
                   5016: 
                   5017: =item scantron_CODElist
                   5018: 
                   5019:   Returns html drop down of the saved CODE lists from current course,
                   5020:   generated from earlier printings.
                   5021: 
                   5022: =cut
1.422     foxr     5023: 
1.186     albertel 5024: sub scantron_CODElist {
1.257     albertel 5025:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   5026:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
1.186     albertel 5027:     my @names=&Apache::lonnet::getkeys('CODEs',$cdom,$cnum);
                   5028:     my $namechoice='<option></option>';
1.225     albertel 5029:     foreach my $name (sort {uc($a) cmp uc($b)} @names) {
1.191     albertel 5030: 	if ($name =~ /^error: 2 /) { next; }
1.278     albertel 5031: 	if ($name =~ /^type\0/) { next; }
1.186     albertel 5032: 	$namechoice.='<option value="'.$name.'">'.$name.'</option>';
                   5033:     }
                   5034:     $namechoice='<select name="scantron_CODElist">'.$namechoice.'</select>';
                   5035:     return $namechoice;
                   5036: }
                   5037: 
1.423     albertel 5038: =pod 
                   5039: 
                   5040: =item scantron_CODEunique
                   5041: 
                   5042:   Returns the html for "Each CODE to be used once" radio.
                   5043: 
                   5044: =cut
1.422     foxr     5045: 
1.186     albertel 5046: sub scantron_CODEunique {
1.532     bisitz   5047:     my $result='<span class="LC_nobreak">
1.272     albertel 5048:                  <label><input type="radio" name="scantron_CODEunique"
1.423     albertel 5049:                         value="yes" checked="checked" />'.&mt('Yes').' </label>
1.381     albertel 5050:                 </span>
1.532     bisitz   5051:                 <span class="LC_nobreak">
1.272     albertel 5052:                  <label><input type="radio" name="scantron_CODEunique"
1.423     albertel 5053:                         value="no" />'.&mt('No').' </label>
1.381     albertel 5054:                 </span>';
1.186     albertel 5055:     return $result;
                   5056: }
1.423     albertel 5057: 
                   5058: =pod 
                   5059: 
                   5060: =item scantron_selectphase
                   5061: 
                   5062:   Generates the initial screen to start the bubble sheet process.
                   5063:   Allows for - starting a grading run.
1.424     albertel 5064:              - downloading existing scan data (original, corrected
1.423     albertel 5065:                                                 or skipped info)
                   5066: 
                   5067:              - uploading new scan data
                   5068: 
                   5069:  Arguments:
                   5070:   $r          - The Apache request object
                   5071:   $file2grade - name of the file that contain the scanned data to score
                   5072: 
                   5073: =cut
1.186     albertel 5074: 
1.75      albertel 5075: sub scantron_selectphase {
1.608     www      5076:     my ($r,$file2grade,$symb) = @_;
1.75      albertel 5077:     if (!$symb) {return '';}
1.582     raeburn  5078:     my $map_error;
                   5079:     my $sequence_selector=&getSequenceDropDown($symb,\$map_error);
                   5080:     if ($map_error) {
                   5081:         $r->print('<br />'.&navmap_errormsg().'<br />');
                   5082:         return;
                   5083:     }
1.324     albertel 5084:     my $default_form_data=&defaultFormData($symb);
1.209     ng       5085:     my $file_selector=&scantron_uploads($file2grade);
1.82      albertel 5086:     my $format_selector=&scantron_scantab();
1.186     albertel 5087:     my $CODE_selector=&scantron_CODElist();
                   5088:     my $CODE_unique=&scantron_CODEunique();
1.75      albertel 5089:     my $result;
1.422     foxr     5090: 
1.513     foxr     5091:     $ssi_error = 0;
                   5092: 
1.606     wenzelju 5093:     if (&Apache::lonnet::allowed('usc',$env{'request.role.domain'}) ||
                   5094:         &Apache::lonnet::allowed('usc',$env{'request.course.id'})) {
                   5095: 
                   5096: 	# Chunk of form to prompt for a scantron file upload.
                   5097: 
                   5098:         $r->print('
                   5099:     <br />
                   5100:     '.&Apache::loncommon::start_data_table('LC_scantron_action').'
                   5101:        '.&Apache::loncommon::start_data_table_header_row().'
                   5102:             <th>
                   5103:               &nbsp;'.&mt('Specify a bubblesheet data file to upload.').'
                   5104:             </th>
                   5105:        '.&Apache::loncommon::end_data_table_header_row().'
                   5106:        '.&Apache::loncommon::start_data_table_row().'
                   5107:             <td>
                   5108: ');
1.608     www      5109:     my $default_form_data=&defaultFormData($symb);
1.606     wenzelju 5110:     my $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
                   5111:     my $cnum= $env{'course.'.$env{'request.course.id'}.'.num'};
                   5112:     $r->print(&Apache::lonhtmlcommon::scripttag('
                   5113:     function checkUpload(formname) {
                   5114: 	if (formname.upfile.value == "") {
                   5115: 	    alert("'.&mt('Please use the browse button to select a file from your local directory.').'");
                   5116: 	    return false;
                   5117: 	}
                   5118: 	formname.submit();
                   5119:     }'));
                   5120:     $r->print('
                   5121:               <form enctype="multipart/form-data" action="/adm/grades" name="rules" method="post">
                   5122:                 '.$default_form_data.'
                   5123:                 <input name="courseid" type="hidden" value="'.$cnum.'" />
                   5124:                 <input name="domainid" type="hidden" value="'.$cdom.'" />
                   5125:                 <input name="command" value="scantronupload_save" type="hidden" />
                   5126:                 '.&mt('File to upload: [_1]','<input type="file" name="upfile" size="50" />').'
                   5127:                 <br />
                   5128:                 <input type="button" onclick="javascript:checkUpload(this.form);" value="'.&mt('Upload Bubblesheet Data').'" />
                   5129:               </form>
                   5130: ');
                   5131: 
                   5132:         $r->print('
                   5133:             </td>
                   5134:        '.&Apache::loncommon::end_data_table_row().'
                   5135:        '.&Apache::loncommon::end_data_table().'
                   5136: ');
                   5137:     }
                   5138: 
1.422     foxr     5139:     # Chunk of form to prompt for a file to grade and how:
                   5140: 
1.489     albertel 5141:     $result.= '
                   5142:     <br />
                   5143:     <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantron_process">
                   5144:     <input type="hidden" name="command" value="scantron_warning" />
                   5145:     '.$default_form_data.'
                   5146:     '.&Apache::loncommon::start_data_table('LC_scantron_action').'
                   5147:        '.&Apache::loncommon::start_data_table_header_row().'
                   5148:             <th colspan="2">
1.492     albertel 5149:               &nbsp;'.&mt('Specify file and which Folder/Sequence to grade').'
1.489     albertel 5150:             </th>
                   5151:        '.&Apache::loncommon::end_data_table_header_row().'
                   5152:        '.&Apache::loncommon::start_data_table_row().'
1.492     albertel 5153:             <td> '.&mt('Sequence to grade:').' </td><td> '.$sequence_selector.' </td>
1.489     albertel 5154:        '.&Apache::loncommon::end_data_table_row().'
                   5155:        '.&Apache::loncommon::start_data_table_row().'
1.572     www      5156:             <td> '.&mt('Filename of bubblesheet data file:').' </td><td> '.$file_selector.' </td>
1.489     albertel 5157:        '.&Apache::loncommon::end_data_table_row().'
                   5158:        '.&Apache::loncommon::start_data_table_row().'
1.572     www      5159:             <td> '.&mt('Format of bubblesheet data file:').' </td><td> '.$format_selector.' </td>
1.489     albertel 5160:        '.&Apache::loncommon::end_data_table_row().'
                   5161:        '.&Apache::loncommon::start_data_table_row().'
1.492     albertel 5162:             <td> '.&mt('Saved CODEs to validate against:').' </td><td> '.$CODE_selector.' </td>
1.489     albertel 5163:        '.&Apache::loncommon::end_data_table_row().'
                   5164:        '.&Apache::loncommon::start_data_table_row().'
1.492     albertel 5165:             <td> '.&mt('Each CODE is only to be used once:').'</td><td> '.$CODE_unique.' </td>
1.489     albertel 5166:        '.&Apache::loncommon::end_data_table_row().'
                   5167:        '.&Apache::loncommon::start_data_table_row().'
1.492     albertel 5168: 	    <td> '.&mt('Options:').' </td>
1.187     albertel 5169:             <td>
1.492     albertel 5170: 	       <label><input type="checkbox" name="scantron_options_redo" value="redo_skipped"/> '.&mt('Do only previously skipped records').'</label> <br />
                   5171:                <label><input type="checkbox" name="scantron_options_ignore" value="ignore_corrections"/> '.&mt('Remove all existing corrections').'</label> <br />
                   5172:                <label><input type="checkbox" name="scantron_options_hidden" value="ignore_hidden"/> '.&mt('Skip hidden resources when grading').'</label>
1.187     albertel 5173: 	    </td>
1.489     albertel 5174:        '.&Apache::loncommon::end_data_table_row().'
                   5175:        '.&Apache::loncommon::start_data_table_row().'
1.174     albertel 5176:             <td colspan="2">
1.572     www      5177:               <input type="submit" value="'.&mt('Grading: Validate Bubblesheet Records').'" />
1.162     albertel 5178:             </td>
1.489     albertel 5179:        '.&Apache::loncommon::end_data_table_row().'
                   5180:     '.&Apache::loncommon::end_data_table().'
                   5181:     </form>
                   5182: ';
1.162     albertel 5183:    
                   5184:     $r->print($result);
                   5185: 
1.422     foxr     5186: 
                   5187: 
                   5188:     # Chunk of the form that prompts to view a scoring office file,
                   5189:     # corrected file, skipped records in a file.
                   5190: 
1.489     albertel 5191:     $r->print('
                   5192:    <br />
                   5193:    <form action="/adm/grades" name="scantron_download">
                   5194:      '.$default_form_data.'
                   5195:      <input type="hidden" name="command" value="scantron_download" />
                   5196:      '.&Apache::loncommon::start_data_table('LC_scantron_action').'
                   5197:        '.&Apache::loncommon::start_data_table_header_row().'
                   5198:               <th>
1.492     albertel 5199:                 &nbsp;'.&mt('Download a scoring office file').'
1.489     albertel 5200:               </th>
                   5201:        '.&Apache::loncommon::end_data_table_header_row().'
                   5202:        '.&Apache::loncommon::start_data_table_row().'
1.492     albertel 5203:               <td> '.&mt('Filename of scoring office file: [_1]',$file_selector).' 
1.489     albertel 5204:                 <br />
1.492     albertel 5205:                 <input type="submit" value="'.&mt('Download: Show List of Associated Files').'" />
1.489     albertel 5206:        '.&Apache::loncommon::end_data_table_row().'
                   5207:      '.&Apache::loncommon::end_data_table().'
                   5208:    </form>
                   5209:    <br />
                   5210: ');
1.162     albertel 5211: 
1.457     banghart 5212:     &Apache::lonpickcode::code_list($r,2);
1.523     raeburn  5213: 
1.528     raeburn  5214:     $r->print('<br /><form method="post" name="checkscantron">'.
1.523     raeburn  5215:              $default_form_data."\n".
                   5216:              &Apache::loncommon::start_data_table('LC_scantron_action')."\n".
                   5217:              &Apache::loncommon::start_data_table_header_row()."\n".
                   5218:              '<th colspan="2">
1.572     www      5219:               &nbsp;'.&mt('Review bubblesheet data and submissions for a previously graded folder/sequence')."\n".
1.523     raeburn  5220:              '</th>'."\n".
                   5221:               &Apache::loncommon::end_data_table_header_row()."\n".
                   5222:               &Apache::loncommon::start_data_table_row()."\n".
                   5223:               '<td> '.&mt('Graded folder/sequence:').' </td>'."\n".
                   5224:               '<td> '.$sequence_selector.' </td>'.
                   5225:               &Apache::loncommon::end_data_table_row()."\n".
                   5226:               &Apache::loncommon::start_data_table_row()."\n".
                   5227:               '<td> '.&mt('Filename of scoring office file:').' </td>'."\n".
                   5228:               '<td> '.$file_selector.' </td>'."\n".
                   5229:               &Apache::loncommon::end_data_table_row()."\n".
                   5230:               &Apache::loncommon::start_data_table_row()."\n".
                   5231:               '<td> '.&mt('Format of data file:').' </td>'."\n".
                   5232:               '<td> '.$format_selector.' </td>'."\n".
                   5233:               &Apache::loncommon::end_data_table_row()."\n".
                   5234:               &Apache::loncommon::start_data_table_row()."\n".
1.557     raeburn  5235:               '<td> '.&mt('Options').' </td>'."\n".
                   5236:               '<td> <label><input type="checkbox" name="scantron_options_hidden" value="ignore_hidden"/> '.&mt('Skip hidden resources').'</label></td>'.
                   5237:               &Apache::loncommon::end_data_table_row()."\n".
                   5238:               &Apache::loncommon::start_data_table_row()."\n".
1.523     raeburn  5239:               '<td colspan="2">'."\n".
                   5240:               '<input type="hidden" name="command" value="checksubmissions" />'."\n".
1.575     www      5241:               '<input type="submit" value="'.&mt('Review Bubblesheet Data and Submission Records').'" />'."\n".
1.523     raeburn  5242:               '</td>'."\n".
                   5243:               &Apache::loncommon::end_data_table_row()."\n".
                   5244:               &Apache::loncommon::end_data_table()."\n".
                   5245:               '</form><br />');
                   5246:     return;
1.75      albertel 5247: }
                   5248: 
1.423     albertel 5249: =pod
                   5250: 
                   5251: =item get_scantron_config
                   5252: 
                   5253:    Parse and return the scantron configuration line selected as a
                   5254:    hash of configuration file fields.
                   5255: 
                   5256:  Arguments:
                   5257:     which - the name of the configuration to parse from the file.
                   5258: 
                   5259: 
                   5260:  Returns:
                   5261:             If the named configuration is not in the file, an empty
                   5262:             hash is returned.
                   5263:     a hash with the fields
                   5264:       name         - internal name for the this configuration setup
                   5265:       description  - text to display to operator that describes this config
                   5266:       CODElocation - if 0 or the string 'none'
                   5267:                           - no CODE exists for this config
                   5268:                      if -1 || the string 'letter'
                   5269:                           - a CODE exists for this config and is
                   5270:                             a string of letters
                   5271:                      Unsupported value (but planned for future support)
                   5272:                           if a positive integer
                   5273:                                - The CODE exists as the first n items from
                   5274:                                  the question section of the form
                   5275:                           if the string 'number'
                   5276:                                - The CODE exists for this config and is
                   5277:                                  a string of numbers
                   5278:       CODEstart   - (only matter if a CODE exists) column in the line where
                   5279:                      the CODE starts
                   5280:       CODElength  - length of the CODE
1.573     bisitz   5281:       IDstart     - column where the student/employee ID starts
1.556     weissno  5282:       IDlength    - length of the student/employee ID info
1.423     albertel 5283:       Qstart      - column where the information from the bubbled
                   5284:                     'questions' start
                   5285:       Qlength     - number of columns comprising a single bubble line from
                   5286:                     the sheet. (usually either 1 or 10)
1.424     albertel 5287:       Qon         - either a single character representing the character used
1.423     albertel 5288:                     to signal a bubble was chosen in the positional setup, or
                   5289:                     the string 'letter' if the letter of the chosen bubble is
                   5290:                     in the final, or 'number' if a number representing the
                   5291:                     chosen bubble is in the file (1->A 0->J)
1.424     albertel 5292:       Qoff        - the character used to represent that a bubble was
                   5293:                     left blank
1.423     albertel 5294:       PaperID     - if the scanning process generates a unique number for each
                   5295:                     sheet scanned the column that this ID number starts in
                   5296:       PaperIDlength - number of columns that comprise the unique ID number
                   5297:                       for the sheet of paper
1.424     albertel 5298:       FirstName   - column that the first name starts in
1.423     albertel 5299:       FirstNameLength - number of columns that the first name spans
                   5300:  
                   5301:       LastName    - column that the last name starts in
                   5302:       LastNameLength - number of columns that the last name spans
                   5303: 
                   5304: =cut
1.422     foxr     5305: 
1.82      albertel 5306: sub get_scantron_config {
                   5307:     my ($which) = @_;
1.518     raeburn  5308:     my @lines = &get_scantronformat_file();
1.82      albertel 5309:     my %config;
1.157     albertel 5310:     #FIXME probably should move to XML it has already gotten a bit much now
1.518     raeburn  5311:     foreach my $line (@lines) {
1.82      albertel 5312: 	my ($name,$descrip)=split(/:/,$line);
                   5313: 	if ($name ne $which ) { next; }
                   5314: 	chomp($line);
                   5315: 	my @config=split(/:/,$line);
                   5316: 	$config{'name'}=$config[0];
                   5317: 	$config{'description'}=$config[1];
                   5318: 	$config{'CODElocation'}=$config[2];
                   5319: 	$config{'CODEstart'}=$config[3];
                   5320: 	$config{'CODElength'}=$config[4];
                   5321: 	$config{'IDstart'}=$config[5];
                   5322: 	$config{'IDlength'}=$config[6];
                   5323: 	$config{'Qstart'}=$config[7];
1.497     foxr     5324:  	$config{'Qlength'}=$config[8];
1.82      albertel 5325: 	$config{'Qoff'}=$config[9];
                   5326: 	$config{'Qon'}=$config[10];
1.157     albertel 5327: 	$config{'PaperID'}=$config[11];
                   5328: 	$config{'PaperIDlength'}=$config[12];
                   5329: 	$config{'FirstName'}=$config[13];
                   5330: 	$config{'FirstNamelength'}=$config[14];
                   5331: 	$config{'LastName'}=$config[15];
                   5332: 	$config{'LastNamelength'}=$config[16];
1.82      albertel 5333: 	last;
                   5334:     }
                   5335:     return %config;
                   5336: }
                   5337: 
1.423     albertel 5338: =pod 
                   5339: 
                   5340: =item username_to_idmap
                   5341: 
1.556     weissno  5342:     creates a hash keyed by student/employee ID with values of the corresponding
1.423     albertel 5343:     student username:domain.
                   5344: 
                   5345:   Arguments:
                   5346: 
                   5347:     $classlist - reference to the class list hash. This is a hash
                   5348:                  keyed by student name:domain  whose elements are references
1.424     albertel 5349:                  to arrays containing various chunks of information
1.423     albertel 5350:                  about the student. (See loncoursedata for more info).
                   5351: 
                   5352:   Returns
                   5353:     %idmap - the constructed hash
                   5354: 
                   5355: =cut
                   5356: 
1.82      albertel 5357: sub username_to_idmap {
                   5358:     my ($classlist)= @_;
                   5359:     my %idmap;
                   5360:     foreach my $student (keys(%$classlist)) {
                   5361: 	$idmap{$classlist->{$student}->[&Apache::loncoursedata::CL_ID]}=
                   5362: 	    $student;
                   5363:     }
                   5364:     return %idmap;
                   5365: }
1.423     albertel 5366: 
                   5367: =pod
                   5368: 
1.424     albertel 5369: =item scantron_fixup_scanline
1.423     albertel 5370: 
                   5371:    Process a requested correction to a scanline.
                   5372: 
                   5373:   Arguments:
                   5374:     $scantron_config   - hash from &get_scantron_config()
                   5375:     $scan_data         - hash of correction information 
                   5376:                           (see &scantron_getfile())
                   5377:     $line              - existing scanline
                   5378:     $whichline         - line number of the passed in scanline
                   5379:     $field             - type of change to process 
                   5380:                          (either 
1.573     bisitz   5381:                           'ID'     -> correct the student/employee ID
1.423     albertel 5382:                           'CODE'   -> correct the CODE
                   5383:                           'answer' -> fixup the submitted answers)
                   5384:     
                   5385:    $args               - hash of additional info,
                   5386:                           - 'ID' 
                   5387:                                'newid' -> studentID to use in replacement
1.424     albertel 5388:                                           of existing one
1.423     albertel 5389:                           - 'CODE' 
                   5390:                                'CODE_ignore_dup' - set to true if duplicates
                   5391:                                                    should be ignored.
                   5392: 	                       'CODE' - is new code or 'use_unfound'
1.424     albertel 5393:                                         if the existing unfound code should
1.423     albertel 5394:                                         be used as is
                   5395:                           - 'answer'
                   5396:                                'response' - new answer or 'none' if blank
                   5397:                                'question' - the bubble line to change
1.503     raeburn  5398:                                'questionnum' - the question identifier,
                   5399:                                                may include subquestion. 
1.423     albertel 5400: 
                   5401:   Returns:
                   5402:     $line - the modified scanline
                   5403: 
                   5404:   Side effects: 
                   5405:     $scan_data - may be updated
                   5406: 
                   5407: =cut
                   5408: 
1.82      albertel 5409: 
1.157     albertel 5410: sub scantron_fixup_scanline {
                   5411:     my ($scantron_config,$scan_data,$line,$whichline,$field,$args)=@_;
                   5412:     if ($field eq 'ID') {
                   5413: 	if (length($args->{'newid'}) > $$scantron_config{'IDlength'}) {
1.186     albertel 5414: 	    return ($line,1,'New value too large');
1.157     albertel 5415: 	}
                   5416: 	if (length($args->{'newid'}) < $$scantron_config{'IDlength'}) {
                   5417: 	    $args->{'newid'}=sprintf('%-'.$$scantron_config{'IDlength'}.'s',
                   5418: 				     $args->{'newid'});
                   5419: 	}
                   5420: 	substr($line,$$scantron_config{'IDstart'}-1,
                   5421: 	       $$scantron_config{'IDlength'})=$args->{'newid'};
                   5422: 	if ($args->{'newid'}=~/^\s*$/) {
                   5423: 	    &scan_data($scan_data,"$whichline.user",
                   5424: 		       $args->{'username'}.':'.$args->{'domain'});
                   5425: 	}
1.186     albertel 5426:     } elsif ($field eq 'CODE') {
1.192     albertel 5427: 	if ($args->{'CODE_ignore_dup'}) {
                   5428: 	    &scan_data($scan_data,"$whichline.CODE_ignore_dup",'1');
                   5429: 	}
                   5430: 	&scan_data($scan_data,"$whichline.useCODE",'1');
                   5431: 	if ($args->{'CODE'} ne 'use_unfound') {
1.191     albertel 5432: 	    if (length($args->{'CODE'}) > $$scantron_config{'CODElength'}) {
                   5433: 		return ($line,1,'New CODE value too large');
                   5434: 	    }
                   5435: 	    if (length($args->{'CODE'}) < $$scantron_config{'CODElength'}) {
                   5436: 		$args->{'CODE'}=sprintf('%-'.$$scantron_config{'CODElength'}.'s',$args->{'CODE'});
                   5437: 	    }
                   5438: 	    substr($line,$$scantron_config{'CODEstart'}-1,
                   5439: 		   $$scantron_config{'CODElength'})=$args->{'CODE'};
1.186     albertel 5440: 	}
1.157     albertel 5441:     } elsif ($field eq 'answer') {
1.497     foxr     5442: 	my $length=$scantron_config->{'Qlength'};
1.157     albertel 5443: 	my $off=$scantron_config->{'Qoff'};
                   5444: 	my $on=$scantron_config->{'Qon'};
1.497     foxr     5445: 	my $answer=${off}x$length;
                   5446: 	if ($args->{'response'} eq 'none') {
                   5447: 	    &scan_data($scan_data,
1.503     raeburn  5448: 		       "$whichline.no_bubble.".$args->{'questionnum'},'1');
1.497     foxr     5449: 	} else {
                   5450: 	    if ($on eq 'letter') {
                   5451: 		my @alphabet=('A'..'Z');
                   5452: 		$answer=$alphabet[$args->{'response'}];
                   5453: 	    } elsif ($on eq 'number') {
                   5454: 		$answer=$args->{'response'}+1;
                   5455: 		if ($answer == 10) { $answer = '0'; }
1.274     albertel 5456: 	    } else {
1.497     foxr     5457: 		substr($answer,$args->{'response'},1)=$on;
1.274     albertel 5458: 	    }
1.497     foxr     5459: 	    &scan_data($scan_data,
1.503     raeburn  5460: 		       "$whichline.no_bubble.".$args->{'questionnum'},undef,'1');
1.157     albertel 5461: 	}
1.497     foxr     5462: 	my $where=$length*($args->{'question'}-1)+$scantron_config->{'Qstart'};
                   5463: 	substr($line,$where-1,$length)=$answer;
1.157     albertel 5464:     }
                   5465:     return $line;
                   5466: }
1.423     albertel 5467: 
                   5468: =pod
                   5469: 
                   5470: =item scan_data
                   5471: 
                   5472:     Edit or look up  an item in the scan_data hash.
                   5473: 
                   5474:   Arguments:
                   5475:     $scan_data  - The hash (see scantron_getfile)
                   5476:     $key        - shorthand of the key to edit (actual key is
1.424     albertel 5477:                   scantronfilename_key).
1.423     albertel 5478:     $data        - New value of the hash entry.
                   5479:     $delete      - If true, the entry is removed from the hash.
                   5480: 
                   5481:   Returns:
                   5482:     The new value of the hash table field (undefined if deleted).
                   5483: 
                   5484: =cut
                   5485: 
                   5486: 
1.157     albertel 5487: sub scan_data {
                   5488:     my ($scan_data,$key,$value,$delete)=@_;
1.257     albertel 5489:     my $filename=$env{'form.scantron_selectfile'};
1.157     albertel 5490:     if (defined($value)) {
                   5491: 	$scan_data->{$filename.'_'.$key} = $value;
                   5492:     }
                   5493:     if ($delete) { delete($scan_data->{$filename.'_'.$key}); }
                   5494:     return $scan_data->{$filename.'_'.$key};
                   5495: }
1.423     albertel 5496: 
1.495     albertel 5497: # ----- These first few routines are general use routines.----
                   5498: 
                   5499: # Return the number of occurences of a pattern in a string.
                   5500: 
                   5501: sub occurence_count {
                   5502:     my ($string, $pattern) = @_;
                   5503: 
                   5504:     my @matches = ($string =~ /$pattern/g);
                   5505: 
                   5506:     return scalar(@matches);
                   5507: }
                   5508: 
                   5509: 
                   5510: # Take a string known to have digits and convert all the
                   5511: # digits into letters in the range J,A..I.
                   5512: 
                   5513: sub digits_to_letters {
                   5514:     my ($input) = @_;
                   5515: 
                   5516:     my @alphabet = ('J', 'A'..'I');
                   5517: 
                   5518:     my @input    = split(//, $input);
                   5519:     my $output ='';
                   5520:     for (my $i = 0; $i < scalar(@input); $i++) {
                   5521: 	if ($input[$i] =~ /\d/) {
                   5522: 	    $output .= $alphabet[$input[$i]];
                   5523: 	} else {
                   5524: 	    $output .= $input[$i];
                   5525: 	}
                   5526:     }
                   5527:     return $output;
                   5528: }
                   5529: 
1.423     albertel 5530: =pod 
                   5531: 
                   5532: =item scantron_parse_scanline
                   5533: 
                   5534:   Decodes a scanline from the selected scantron file
                   5535: 
                   5536:  Arguments:
                   5537:     line             - The text of the scantron file line to process
                   5538:     whichline        - Line number
                   5539:     scantron_config  - Hash describing the format of the scantron lines.
                   5540:     scan_data        - Hash of extra information about the scanline
                   5541:                        (see scantron_getfile for more information)
                   5542:     just_header      - True if should not process question answers but only
                   5543:                        the stuff to the left of the answers.
                   5544:  Returns:
                   5545:    Hash containing the result of parsing the scanline
                   5546: 
                   5547:    Keys are all proceeded by the string 'scantron.'
                   5548: 
                   5549:        CODE    - the CODE in use for this scanline
                   5550:        useCODE - 1 if the CODE is invalid but it usage has been forced
                   5551:                  by the operator
                   5552:        CODE_ignore_dup - 1 if the CODE is a duplicated use when unique
                   5553:                             CODEs were selected, but the usage has been
                   5554:                             forced by the operator
1.556     weissno  5555:        ID  - student/employee ID
1.423     albertel 5556:        PaperID - if used, the ID number printed on the sheet when the 
                   5557:                  paper was scanned
                   5558:        FirstName - first name from the sheet
                   5559:        LastName  - last name from the sheet
                   5560: 
                   5561:      if just_header was not true these key may also exist
                   5562: 
1.447     foxr     5563:        missingerror - a list of bubble ranges that are considered to be answers
                   5564:                       to a single question that don't have any bubbles filled in.
                   5565:                       Of the form questionnumber:firstbubblenumber:count.
                   5566:        doubleerror  - a list of bubble ranges that are considered to be answers
                   5567:                       to a single question that have more than one bubble filled in.
                   5568:                       Of the form questionnumber::firstbubblenumber:count
                   5569:    
                   5570:                 In the above, count is the number of bubble responses in the
                   5571:                 input line needed to represent the possible answers to the question.
                   5572:                 e.g. a radioresponse with 15 choices in an answer sheet with 10 choices
                   5573:                 per line would have count = 2.
                   5574: 
1.423     albertel 5575:        maxquest     - the number of the last bubble line that was parsed
                   5576: 
                   5577:        (<number> starts at 1)
                   5578:        <number>.answer - zero or more letters representing the selected
                   5579:                          letters from the scanline for the bubble line 
                   5580:                          <number>.
                   5581:                          if blank there was either no bubble or there where
                   5582:                          multiple bubbles, (consult the keys missingerror and
                   5583:                          doubleerror if this is an error condition)
                   5584: 
                   5585: =cut
                   5586: 
1.82      albertel 5587: sub scantron_parse_scanline {
1.423     albertel 5588:     my ($line,$whichline,$scantron_config,$scan_data,$just_header)=@_;
1.470     foxr     5589: 
1.82      albertel 5590:     my %record;
1.550     raeburn  5591:     my $lastpos = $env{'form.scantron_maxbubble'}*$$scantron_config{'Qlength'};
                   5592:     my $questions=substr($line,$$scantron_config{'Qstart'}-1,$lastpos);  # Answers
1.422     foxr     5593:     my $data=substr($line,0,$$scantron_config{'Qstart'}-1);     # earlier stuff
1.278     albertel 5594:     if (!($$scantron_config{'CODElocation'} eq 0 ||
                   5595: 	  $$scantron_config{'CODElocation'} eq 'none')) {
                   5596: 	if ($$scantron_config{'CODElocation'} < 0 ||
                   5597: 	    $$scantron_config{'CODElocation'} eq 'letter' ||
                   5598: 	    $$scantron_config{'CODElocation'} eq 'number') {
1.191     albertel 5599: 	    $record{'scantron.CODE'}=substr($data,
                   5600: 					    $$scantron_config{'CODEstart'}-1,
1.83      albertel 5601: 					    $$scantron_config{'CODElength'});
1.191     albertel 5602: 	    if (&scan_data($scan_data,"$whichline.useCODE")) {
                   5603: 		$record{'scantron.useCODE'}=1;
                   5604: 	    }
1.192     albertel 5605: 	    if (&scan_data($scan_data,"$whichline.CODE_ignore_dup")) {
                   5606: 		$record{'scantron.CODE_ignore_dup'}=1;
                   5607: 	    }
1.82      albertel 5608: 	} else {
                   5609: 	    #FIXME interpret first N questions
                   5610: 	}
                   5611:     }
1.83      albertel 5612:     $record{'scantron.ID'}=substr($data,$$scantron_config{'IDstart'}-1,
                   5613: 				  $$scantron_config{'IDlength'});
1.157     albertel 5614:     $record{'scantron.PaperID'}=
                   5615: 	substr($data,$$scantron_config{'PaperID'}-1,
                   5616: 	       $$scantron_config{'PaperIDlength'});
                   5617:     $record{'scantron.FirstName'}=
                   5618: 	substr($data,$$scantron_config{'FirstName'}-1,
                   5619: 	       $$scantron_config{'FirstNamelength'});
                   5620:     $record{'scantron.LastName'}=
                   5621: 	substr($data,$$scantron_config{'LastName'}-1,
                   5622: 	       $$scantron_config{'LastNamelength'});
1.423     albertel 5623:     if ($just_header) { return \%record; }
1.194     albertel 5624: 
1.82      albertel 5625:     my @alphabet=('A'..'Z');
                   5626:     my $questnum=0;
1.447     foxr     5627:     my $ansnum  =1;		# Multiple 'answer lines'/question.
                   5628: 
1.470     foxr     5629:     chomp($questions);		# Get rid of any trailing \n.
                   5630:     $questions =~ s/\r$//;      # Get rid of trailing \r too (MAC or Win uploads).
                   5631:     while (length($questions)) {
1.447     foxr     5632: 	my $answers_needed = $bubble_lines_per_response{$questnum};
1.503     raeburn  5633:         my $answer_length  = ($$scantron_config{'Qlength'} * $answers_needed)
                   5634:                              || 1;
                   5635:         $questnum++;
                   5636:         my $quest_id = $questnum;
                   5637:         my $currentquest = substr($questions,0,$answer_length);
                   5638:         $questions       = substr($questions,$answer_length);
                   5639:         if (length($currentquest) < $answer_length) { next; }
                   5640: 
                   5641:         if ($subdivided_bubble_lines{$questnum-1} =~ /,/) {
                   5642:             my $subquestnum = 1;
                   5643:             my $subquestions = $currentquest;
                   5644:             my @subanswers_needed = 
                   5645:                 split(/,/,$subdivided_bubble_lines{$questnum-1});  
                   5646:             foreach my $subans (@subanswers_needed) {
                   5647:                 my $subans_length =
                   5648:                     ($$scantron_config{'Qlength'} * $subans)  || 1;
                   5649:                 my $currsubquest = substr($subquestions,0,$subans_length);
                   5650:                 $subquestions   = substr($subquestions,$subans_length);
                   5651:                 $quest_id = "$questnum.$subquestnum";
                   5652:                 if (($$scantron_config{'Qon'} eq 'letter') ||
                   5653:                     ($$scantron_config{'Qon'} eq 'number')) {
                   5654:                     $ansnum = &scantron_validator_lettnum($ansnum, 
                   5655:                         $questnum,$quest_id,$subans,$currsubquest,$whichline,
                   5656:                         \@alphabet,\%record,$scantron_config,$scan_data);
                   5657:                 } else {
                   5658:                     $ansnum = &scantron_validator_positional($ansnum,
                   5659:                         $questnum,$quest_id,$subans,$currsubquest,$whichline,                        \@alphabet,\%record,$scantron_config,$scan_data);
                   5660:                 }
                   5661:                 $subquestnum ++;
                   5662:             }
                   5663:         } else {
                   5664:             if (($$scantron_config{'Qon'} eq 'letter') ||
                   5665:                 ($$scantron_config{'Qon'} eq 'number')) {
                   5666:                 $ansnum = &scantron_validator_lettnum($ansnum,$questnum,
                   5667:                     $quest_id,$answers_needed,$currentquest,$whichline,
                   5668:                     \@alphabet,\%record,$scantron_config,$scan_data);
                   5669:             } else {
                   5670:                 $ansnum = &scantron_validator_positional($ansnum,$questnum,
                   5671:                     $quest_id,$answers_needed,$currentquest,$whichline,
                   5672:                     \@alphabet,\%record,$scantron_config,$scan_data);
                   5673:             }
                   5674:         }
                   5675:     }
                   5676:     $record{'scantron.maxquest'}=$questnum;
                   5677:     return \%record;
                   5678: }
1.447     foxr     5679: 
1.503     raeburn  5680: sub scantron_validator_lettnum {
                   5681:     my ($ansnum,$questnum,$quest_id,$answers_needed,$currquest,$whichline,
                   5682:         $alphabet,$record,$scantron_config,$scan_data) = @_;
                   5683: 
                   5684:     # Qon 'letter' implies for each slot in currquest we have:
                   5685:     #    ? or * for doubles, a letter in A-Z for a bubble, and
                   5686:     #    about anything else (esp. a value of Qoff) for missing
                   5687:     #    bubbles.
                   5688:     #
                   5689:     # Qon 'number' implies each slot gives a digit that indexes the
                   5690:     #    bubbles filled, or Qoff, or a non-number for unbubbled lines,
                   5691:     #    and * or ? for double bubbles on a single line.
                   5692:     #
1.447     foxr     5693: 
1.503     raeburn  5694:     my $matchon;
                   5695:     if ($$scantron_config{'Qon'} eq 'letter') {
                   5696:         $matchon = '[A-Z]';
                   5697:     } elsif ($$scantron_config{'Qon'} eq 'number') {
                   5698:         $matchon = '\d';
                   5699:     }
                   5700:     my $occurrences = 0;
                   5701:     if (($responsetype_per_response{$questnum-1} eq 'essayresponse') ||
                   5702:         ($responsetype_per_response{$questnum-1} eq 'formularesponse') ||
1.510     raeburn  5703:         ($responsetype_per_response{$questnum-1} eq 'stringresponse') ||
                   5704:         ($responsetype_per_response{$questnum-1} eq 'imageresponse') ||
                   5705:         ($responsetype_per_response{$questnum-1} eq 'reactionresponse') ||
                   5706:         ($responsetype_per_response{$questnum-1} eq 'organicresponse')) {
1.503     raeburn  5707:         my @singlelines = split('',$currquest);
                   5708:         foreach my $entry (@singlelines) {
                   5709:             $occurrences = &occurence_count($entry,$matchon);
                   5710:             if ($occurrences > 1) {
                   5711:                 last;
                   5712:             }
                   5713:         } 
                   5714:     } else {
                   5715:         $occurrences = &occurence_count($currquest,$matchon); 
                   5716:     }
                   5717:     if (($currquest =~ /\?/ || $currquest =~ /\*/) || ($occurrences > 1)) {
                   5718:         push(@{$record->{'scantron.doubleerror'}},$quest_id);
                   5719:         for (my $ans=0; $ans<$answers_needed; $ans++) {
                   5720:             my $bubble = substr($currquest,$ans,1);
                   5721:             if ($bubble =~ /$matchon/ ) {
                   5722:                 if ($$scantron_config{'Qon'} eq 'number') {
                   5723:                     if ($bubble == 0) {
                   5724:                         $bubble = 10; 
                   5725:                     }
                   5726:                     $record->{"scantron.$ansnum.answer"} = 
                   5727:                         $alphabet->[$bubble-1];
                   5728:                 } else {
                   5729:                     $record->{"scantron.$ansnum.answer"} = $bubble;
                   5730:                 }
                   5731:             } else {
                   5732:                 $record->{"scantron.$ansnum.answer"}='';
                   5733:             }
                   5734:             $ansnum++;
                   5735:         }
                   5736:     } elsif (!defined($currquest)
                   5737:             || (&occurence_count($currquest, $$scantron_config{'Qoff'}) == length($currquest))
                   5738:             || (&occurence_count($currquest,$matchon) == 0)) {
                   5739:         for (my $ans=0; $ans<$answers_needed; $ans++ ) {
                   5740:             $record->{"scantron.$ansnum.answer"}='';
                   5741:             $ansnum++;
                   5742:         }
                   5743:         if (!&scan_data($scan_data,"$whichline.no_bubble.$quest_id")) {
                   5744:             push(@{$record->{'scantron.missingerror'}},$quest_id);
                   5745:         }
                   5746:     } else {
                   5747:         if ($$scantron_config{'Qon'} eq 'number') {
                   5748:             $currquest = &digits_to_letters($currquest);            
                   5749:         }
                   5750:         for (my $ans=0; $ans<$answers_needed; $ans++) {
                   5751:             my $bubble = substr($currquest,$ans,1);
                   5752:             $record->{"scantron.$ansnum.answer"} = $bubble;
                   5753:             $ansnum++;
                   5754:         }
                   5755:     }
                   5756:     return $ansnum;
                   5757: }
1.447     foxr     5758: 
1.503     raeburn  5759: sub scantron_validator_positional {
                   5760:     my ($ansnum,$questnum,$quest_id,$answers_needed,$currquest,
                   5761:         $whichline,$alphabet,$record,$scantron_config,$scan_data) = @_;
1.447     foxr     5762: 
1.503     raeburn  5763:     # Otherwise there's a positional notation;
                   5764:     # each bubble line requires Qlength items, and there are filled in
                   5765:     # bubbles for each case where there 'Qon' characters.
                   5766:     #
1.447     foxr     5767: 
1.503     raeburn  5768:     my @array=split($$scantron_config{'Qon'},$currquest,-1);
1.447     foxr     5769: 
1.503     raeburn  5770:     # If the split only gives us one element.. the full length of the
                   5771:     # answer string, no bubbles are filled in:
1.447     foxr     5772: 
1.507     raeburn  5773:     if ($answers_needed eq '') {
                   5774:         return;
                   5775:     }
                   5776: 
1.503     raeburn  5777:     if (length($array[0]) eq $$scantron_config{'Qlength'}*$answers_needed) {
                   5778:         for (my $ans=0; $ans<$answers_needed; $ans++ ) {
                   5779:             $record->{"scantron.$ansnum.answer"}='';
                   5780:             $ansnum++;
                   5781:         }
                   5782:         if (!&scan_data($scan_data,"$whichline.no_bubble.$quest_id")) {
                   5783:             push(@{$record->{"scantron.missingerror"}},$quest_id);
                   5784:         }
                   5785:     } elsif (scalar(@array) == 2) {
                   5786:         my $location = length($array[0]);
                   5787:         my $line_num = int($location / $$scantron_config{'Qlength'});
                   5788:         my $bubble   = $alphabet->[$location % $$scantron_config{'Qlength'}];
                   5789:         for (my $ans=0; $ans<$answers_needed; $ans++) {
                   5790:             if ($ans eq $line_num) {
                   5791:                 $record->{"scantron.$ansnum.answer"} = $bubble;
                   5792:             } else {
                   5793:                 $record->{"scantron.$ansnum.answer"} = ' ';
                   5794:             }
                   5795:             $ansnum++;
                   5796:          }
                   5797:     } else {
                   5798:         #  If there's more than one instance of a bubble character
                   5799:         #  That's a double bubble; with positional notation we can
                   5800:         #  record all the bubbles filled in as well as the
                   5801:         #  fact this response consists of multiple bubbles.
                   5802:         #
                   5803:         if (($responsetype_per_response{$questnum-1} eq 'essayresponse') ||
                   5804:             ($responsetype_per_response{$questnum-1} eq 'formularesponse') ||
1.510     raeburn  5805:             ($responsetype_per_response{$questnum-1} eq 'stringresponse') ||
                   5806:             ($responsetype_per_response{$questnum-1} eq 'imageresponse') ||
                   5807:             ($responsetype_per_response{$questnum-1} eq 'reactionresponse') ||
                   5808:             ($responsetype_per_response{$questnum-1} eq 'organicresponse')) {
1.503     raeburn  5809:             my $doubleerror = 0;
                   5810:             while (($currquest >= $$scantron_config{'Qlength'}) && 
                   5811:                    (!$doubleerror)) {
                   5812:                my $currline = substr($currquest,0,$$scantron_config{'Qlength'});
                   5813:                $currquest = substr($currquest,$$scantron_config{'Qlength'});
                   5814:                my @currarray = split($$scantron_config{'Qon'},$currline,-1);
                   5815:                if (length(@currarray) > 2) {
                   5816:                    $doubleerror = 1;
                   5817:                } 
                   5818:             }
                   5819:             if ($doubleerror) {
                   5820:                 push(@{$record->{'scantron.doubleerror'}},$quest_id);
                   5821:             }
                   5822:         } else {
                   5823:             push(@{$record->{'scantron.doubleerror'}},$quest_id);
                   5824:         }
                   5825:         my $item = $ansnum;
                   5826:         for (my $ans=0; $ans<$answers_needed; $ans++) {
                   5827:             $record->{"scantron.$item.answer"} = '';
                   5828:             $item ++;
                   5829:         }
1.447     foxr     5830: 
1.503     raeburn  5831:         my @ans=@array;
                   5832:         my $i=0;
                   5833:         my $increment = 0;
                   5834:         while ($#ans) {
                   5835:             $i+=length($ans[0]) + $increment;
                   5836:             my $line   = int($i/$$scantron_config{'Qlength'} + $ansnum);
                   5837:             my $bubble = $i%$$scantron_config{'Qlength'};
                   5838:             $record->{"scantron.$line.answer"}.=$alphabet->[$bubble];
                   5839:             shift(@ans);
                   5840:             $increment = 1;
                   5841:         }
                   5842:         $ansnum += $answers_needed;
1.82      albertel 5843:     }
1.503     raeburn  5844:     return $ansnum;
1.82      albertel 5845: }
                   5846: 
1.423     albertel 5847: =pod
                   5848: 
                   5849: =item scantron_add_delay
                   5850: 
                   5851:    Adds an error message that occurred during the grading phase to a
                   5852:    queue of messages to be shown after grading pass is complete
                   5853: 
                   5854:  Arguments:
1.424     albertel 5855:    $delayqueue  - arrary ref of hash ref of error messages
1.423     albertel 5856:    $scanline    - the scanline that caused the error
                   5857:    $errormesage - the error message
                   5858:    $errorcode   - a numeric code for the error
                   5859: 
                   5860:  Side Effects:
1.424     albertel 5861:    updates the $delayqueue to have a new hash ref of the error
1.423     albertel 5862: 
                   5863: =cut
                   5864: 
1.82      albertel 5865: sub scantron_add_delay {
1.140     albertel 5866:     my ($delayqueue,$scanline,$errormessage,$errorcode)=@_;
                   5867:     push(@$delayqueue,
                   5868: 	 {'line' => $scanline, 'emsg' => $errormessage,
                   5869: 	  'ecode' => $errorcode }
                   5870: 	 );
1.82      albertel 5871: }
                   5872: 
1.423     albertel 5873: =pod
                   5874: 
                   5875: =item scantron_find_student
                   5876: 
1.424     albertel 5877:    Finds the username for the current scanline
                   5878: 
                   5879:   Arguments:
                   5880:    $scantron_record - hash result from scantron_parse_scanline
                   5881:    $scan_data       - hash of correction information 
                   5882:                       (see &scantron_getfile() form more information)
                   5883:    $idmap           - hash from &username_to_idmap()
                   5884:    $line            - number of current scanline
                   5885:  
                   5886:   Returns:
                   5887:    Either 'username:domain' or undef if unknown
                   5888: 
1.423     albertel 5889: =cut
                   5890: 
1.82      albertel 5891: sub scantron_find_student {
1.157     albertel 5892:     my ($scantron_record,$scan_data,$idmap,$line)=@_;
1.83      albertel 5893:     my $scanID=$$scantron_record{'scantron.ID'};
1.157     albertel 5894:     if ($scanID =~ /^\s*$/) {
                   5895:  	return &scan_data($scan_data,"$line.user");
                   5896:     }
1.83      albertel 5897:     foreach my $id (keys(%$idmap)) {
1.157     albertel 5898:  	if (lc($id) eq lc($scanID)) {
                   5899:  	    return $$idmap{$id};
                   5900:  	}
1.83      albertel 5901:     }
                   5902:     return undef;
                   5903: }
                   5904: 
1.423     albertel 5905: =pod
                   5906: 
                   5907: =item scantron_filter
                   5908: 
1.424     albertel 5909:    Filter sub for lonnavmaps, filters out hidden resources if ignore
                   5910:    hidden resources was selected
                   5911: 
1.423     albertel 5912: =cut
                   5913: 
1.83      albertel 5914: sub scantron_filter {
                   5915:     my ($curres)=@_;
1.331     albertel 5916: 
                   5917:     if (ref($curres) && $curres->is_problem()) {
                   5918: 	# if the user has asked to not have either hidden
                   5919: 	# or 'randomout' controlled resources to be graded
                   5920: 	# don't include them
                   5921: 	if ($env{'form.scantron_options_hidden'} eq 'ignore_hidden'
                   5922: 	    && $curres->randomout) {
                   5923: 	    return 0;
                   5924: 	}
1.83      albertel 5925: 	return 1;
                   5926:     }
                   5927:     return 0;
1.82      albertel 5928: }
                   5929: 
1.423     albertel 5930: =pod
                   5931: 
                   5932: =item scantron_process_corrections
                   5933: 
1.424     albertel 5934:    Gets correction information out of submitted form data and corrects
                   5935:    the scanline
                   5936: 
1.423     albertel 5937: =cut
                   5938: 
1.157     albertel 5939: sub scantron_process_corrections {
                   5940:     my ($r) = @_;
1.257     albertel 5941:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.157     albertel 5942:     my ($scanlines,$scan_data)=&scantron_getfile();
                   5943:     my $classlist=&Apache::loncoursedata::get_classlist();
1.257     albertel 5944:     my $which=$env{'form.scantron_line'};
1.200     albertel 5945:     my $line=&scantron_get_line($scanlines,$scan_data,$which);
1.157     albertel 5946:     my ($skip,$err,$errmsg);
1.257     albertel 5947:     if ($env{'form.scantron_skip_record'}) {
1.157     albertel 5948: 	$skip=1;
1.257     albertel 5949:     } elsif ($env{'form.scantron_corrections'} =~ /^(duplicate|incorrect)ID$/) {
                   5950: 	my $newstudent=$env{'form.scantron_username'}.':'.
                   5951: 	    $env{'form.scantron_domain'};
1.157     albertel 5952: 	my $newid=$classlist->{$newstudent}->[&Apache::loncoursedata::CL_ID];
                   5953: 	($line,$err,$errmsg)=
                   5954: 	    &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,$which,
                   5955: 				     'ID',{'newid'=>$newid,
1.257     albertel 5956: 				    'username'=>$env{'form.scantron_username'},
                   5957: 				    'domain'=>$env{'form.scantron_domain'}});
                   5958:     } elsif ($env{'form.scantron_corrections'} =~ /^(duplicate|incorrect)CODE$/) {
                   5959: 	my $resolution=$env{'form.scantron_CODE_resolution'};
1.190     albertel 5960: 	my $newCODE;
1.192     albertel 5961: 	my %args;
1.190     albertel 5962: 	if      ($resolution eq 'use_unfound') {
1.191     albertel 5963: 	    $newCODE='use_unfound';
1.190     albertel 5964: 	} elsif ($resolution eq 'use_found') {
1.257     albertel 5965: 	    $newCODE=$env{'form.scantron_CODE_selectedvalue'};
1.190     albertel 5966: 	} elsif ($resolution eq 'use_typed') {
1.257     albertel 5967: 	    $newCODE=$env{'form.scantron_CODE_newvalue'};
1.194     albertel 5968: 	} elsif ($resolution =~ /^use_closest_(\d+)/) {
1.257     albertel 5969: 	    $newCODE=$env{"form.scantron_CODE_closest_$1"};
1.190     albertel 5970: 	}
1.257     albertel 5971: 	if ($env{'form.scantron_corrections'} eq 'duplicateCODE') {
1.192     albertel 5972: 	    $args{'CODE_ignore_dup'}=1;
                   5973: 	}
                   5974: 	$args{'CODE'}=$newCODE;
1.186     albertel 5975: 	($line,$err,$errmsg)=
                   5976: 	    &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,$which,
1.192     albertel 5977: 				     'CODE',\%args);
1.257     albertel 5978:     } elsif ($env{'form.scantron_corrections'} =~ /^(missing|double)bubble$/) {
                   5979: 	foreach my $question (split(',',$env{'form.scantron_questions'})) {
1.157     albertel 5980: 	    ($line,$err,$errmsg)=
                   5981: 		&scantron_fixup_scanline(\%scantron_config,$scan_data,$line,
                   5982: 					 $which,'answer',
                   5983: 					 { 'question'=>$question,
1.503     raeburn  5984: 		      		   'response'=>$env{"form.scantron_correct_Q_$question"},
                   5985:                                    'questionnum'=>$env{"form.scantron_questionnum_Q_$question"}});
1.157     albertel 5986: 	    if ($err) { last; }
                   5987: 	}
                   5988:     }
                   5989:     if ($err) {
1.398     albertel 5990: 	$r->print("<span class=\"LC_warning\">Unable to accept last correction, an error occurred :$errmsg:</span>");
1.157     albertel 5991:     } else {
1.200     albertel 5992: 	&scantron_put_line($scanlines,$scan_data,$which,$line,$skip);
1.157     albertel 5993: 	&scantron_putfile($scanlines,$scan_data);
                   5994:     }
                   5995: }
                   5996: 
1.423     albertel 5997: =pod
                   5998: 
                   5999: =item reset_skipping_status
                   6000: 
1.424     albertel 6001:    Forgets the current set of remember skipped scanlines (and thus
                   6002:    reverts back to considering all lines in the
                   6003:    scantron_skipped_<filename> file)
                   6004: 
1.423     albertel 6005: =cut
                   6006: 
1.200     albertel 6007: sub reset_skipping_status {
                   6008:     my ($scanlines,$scan_data)=&scantron_getfile();
                   6009:     &scan_data($scan_data,'remember_skipping',undef,1);
                   6010:     &scantron_putfile(undef,$scan_data);
                   6011: }
                   6012: 
1.423     albertel 6013: =pod
                   6014: 
                   6015: =item start_skipping
                   6016: 
1.424     albertel 6017:    Marks a scanline to be skipped. 
                   6018: 
1.423     albertel 6019: =cut
                   6020: 
1.376     albertel 6021: sub start_skipping {
1.200     albertel 6022:     my ($scan_data,$i)=@_;
                   6023:     my %remembered=split(':',&scan_data($scan_data,'remember_skipping'));
1.376     albertel 6024:     if ($env{'form.scantron_options_redo'} =~ /^redo_/) {
                   6025: 	$remembered{$i}=2;
                   6026:     } else {
                   6027: 	$remembered{$i}=1;
                   6028:     }
1.200     albertel 6029:     &scan_data($scan_data,'remember_skipping',join(':',%remembered));
                   6030: }
                   6031: 
1.423     albertel 6032: =pod
                   6033: 
                   6034: =item should_be_skipped
                   6035: 
1.424     albertel 6036:    Checks whether a scanline should be skipped.
                   6037: 
1.423     albertel 6038: =cut
                   6039: 
1.200     albertel 6040: sub should_be_skipped {
1.376     albertel 6041:     my ($scanlines,$scan_data,$i)=@_;
1.257     albertel 6042:     if ($env{'form.scantron_options_redo'} !~ /^redo_/) {
1.200     albertel 6043: 	# not redoing old skips
1.376     albertel 6044: 	if ($scanlines->{'skipped'}[$i]) { return 1; }
1.200     albertel 6045: 	return 0;
                   6046:     }
                   6047:     my %remembered=split(':',&scan_data($scan_data,'remember_skipping'));
1.376     albertel 6048: 
                   6049:     if (exists($remembered{$i}) && $remembered{$i} != 2 ) {
                   6050: 	return 0;
                   6051:     }
1.200     albertel 6052:     return 1;
                   6053: }
                   6054: 
1.423     albertel 6055: =pod
                   6056: 
                   6057: =item remember_current_skipped
                   6058: 
1.424     albertel 6059:    Discovers what scanlines are in the scantron_skipped_<filename>
                   6060:    file and remembers them into scan_data for later use.
                   6061: 
1.423     albertel 6062: =cut
                   6063: 
1.200     albertel 6064: sub remember_current_skipped {
                   6065:     my ($scanlines,$scan_data)=&scantron_getfile();
                   6066:     my %to_remember;
                   6067:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
                   6068: 	if ($scanlines->{'skipped'}[$i]) {
                   6069: 	    $to_remember{$i}=1;
                   6070: 	}
                   6071:     }
1.376     albertel 6072: 
1.200     albertel 6073:     &scan_data($scan_data,'remember_skipping',join(':',%to_remember));
                   6074:     &scantron_putfile(undef,$scan_data);
                   6075: }
                   6076: 
1.423     albertel 6077: =pod
                   6078: 
                   6079: =item check_for_error
                   6080: 
1.424     albertel 6081:     Checks if there was an error when attempting to remove a specific
                   6082:     scantron_.. bubble sheet data file. Prints out an error if
                   6083:     something went wrong.
                   6084: 
1.423     albertel 6085: =cut
                   6086: 
1.200     albertel 6087: sub check_for_error {
                   6088:     my ($r,$result)=@_;
                   6089:     if ($result ne 'ok' && $result ne 'not_found' ) {
1.492     albertel 6090: 	$r->print(&mt("An error occurred ([_1]) when trying to remove the existing corrections.",$result));
1.200     albertel 6091:     }
                   6092: }
1.157     albertel 6093: 
1.423     albertel 6094: =pod
                   6095: 
                   6096: =item scantron_warning_screen
                   6097: 
1.424     albertel 6098:    Interstitial screen to make sure the operator has selected the
                   6099:    correct options before we start the validation phase.
                   6100: 
1.423     albertel 6101: =cut
                   6102: 
1.203     albertel 6103: sub scantron_warning_screen {
                   6104:     my ($button_text)=@_;
1.257     albertel 6105:     my $title=&Apache::lonnet::gettitle($env{'form.selectpage'});
1.284     albertel 6106:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.373     albertel 6107:     my $CODElist;
1.284     albertel 6108:     if ($scantron_config{'CODElocation'} &&
                   6109: 	$scantron_config{'CODEstart'} &&
                   6110: 	$scantron_config{'CODElength'}) {
                   6111: 	$CODElist=$env{'form.scantron_CODElist'};
1.398     albertel 6112: 	if ($env{'form.scantron_CODElist'} eq '') { $CODElist='<span class="LC_warning">None</span>'; }
1.284     albertel 6113: 	$CODElist=
1.492     albertel 6114: 	    '<tr><td><b>'.&mt('List of CODES to validate against:').'</b></td><td><tt>'.
1.373     albertel 6115: 	    $env{'form.scantron_CODElist'}.'</tt></td></tr>';
1.284     albertel 6116:     }
1.492     albertel 6117:     return ('
1.203     albertel 6118: <p>
1.492     albertel 6119: <span class="LC_warning">
                   6120: '.&mt('Please double check the information below before clicking on \'[_1]\'',&mt($button_text)).'</span>
1.203     albertel 6121: </p>
                   6122: <table>
1.492     albertel 6123: <tr><td><b>'.&mt('Sequence to be Graded:').'</b></td><td>'.$title.'</td></tr>
                   6124: <tr><td><b>'.&mt('Data File that will be used:').'</b></td><td><tt>'.$env{'form.scantron_selectfile'}.'</tt></td></tr>
                   6125: '.$CODElist.'
1.203     albertel 6126: </table>
                   6127: <br />
1.492     albertel 6128: <p> '.&mt('If this information is correct, please click on \'[_1]\'.',&mt($button_text)).'</p>
                   6129: <p> '.&mt('If something is incorrect, please click the \'Grading Menu\' button to start over.').'</p>
1.203     albertel 6130: 
                   6131: <br />
1.492     albertel 6132: ');
1.203     albertel 6133: }
                   6134: 
1.423     albertel 6135: =pod
                   6136: 
                   6137: =item scantron_do_warning
                   6138: 
1.424     albertel 6139:    Check if the operator has picked something for all required
                   6140:    fields. Error out if something is missing.
                   6141: 
1.423     albertel 6142: =cut
                   6143: 
1.203     albertel 6144: sub scantron_do_warning {
1.608     www      6145:     my ($r,$symb)=@_;
1.203     albertel 6146:     if (!$symb) {return '';}
1.324     albertel 6147:     my $default_form_data=&defaultFormData($symb);
1.203     albertel 6148:     $r->print(&scantron_form_start().$default_form_data);
1.257     albertel 6149:     if ( $env{'form.selectpage'} eq '' ||
                   6150: 	 $env{'form.scantron_selectfile'} eq '' ||
                   6151: 	 $env{'form.scantron_format'} eq '' ) {
1.492     albertel 6152: 	$r->print("<p>".&mt('You have forgetten to specify some information. Please go Back and try again.')."</p>");
1.257     albertel 6153: 	if ( $env{'form.selectpage'} eq '') {
1.492     albertel 6154: 	    $r->print('<p><span class="LC_error">'.&mt('You have not selected a Sequence to grade').'</span></p>');
1.237     albertel 6155: 	} 
1.257     albertel 6156: 	if ( $env{'form.scantron_selectfile'} eq '') {
1.492     albertel 6157: 	    $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 6158: 	} 
1.257     albertel 6159: 	if ( $env{'form.scantron_format'} eq '') {
1.492     albertel 6160: 	    $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 6161: 	} 
                   6162:     } else {
1.265     www      6163: 	my $warning=&scantron_warning_screen('Grading: Validate Records');
1.492     albertel 6164: 	$r->print('
                   6165: '.$warning.'
                   6166: <input type="submit" name="submit" value="'.&mt('Grading: Validate Records').'" />
1.203     albertel 6167: <input type="hidden" name="command" value="scantron_validate" />
1.492     albertel 6168: ');
1.237     albertel 6169:     }
1.614     www      6170:     $r->print("</form><br />");
1.203     albertel 6171:     return '';
                   6172: }
                   6173: 
1.423     albertel 6174: =pod
                   6175: 
                   6176: =item scantron_form_start
                   6177: 
1.424     albertel 6178:     html hidden input for remembering all selected grading options
                   6179: 
1.423     albertel 6180: =cut
                   6181: 
1.203     albertel 6182: sub scantron_form_start {
                   6183:     my ($max_bubble)=@_;
                   6184:     my $result= <<SCANTRONFORM;
                   6185: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantronupload">
1.257     albertel 6186:   <input type="hidden" name="selectpage" value="$env{'form.selectpage'}" />
                   6187:   <input type="hidden" name="scantron_format" value="$env{'form.scantron_format'}" />
                   6188:   <input type="hidden" name="scantron_selectfile" value="$env{'form.scantron_selectfile'}" />
1.218     albertel 6189:   <input type="hidden" name="scantron_maxbubble" value="$max_bubble" />
1.257     albertel 6190:   <input type="hidden" name="scantron_CODElist" value="$env{'form.scantron_CODElist'}" />
                   6191:   <input type="hidden" name="scantron_CODEunique" value="$env{'form.scantron_CODEunique'}" />
                   6192:   <input type="hidden" name="scantron_options_redo" value="$env{'form.scantron_options_redo'}" />
                   6193:   <input type="hidden" name="scantron_options_ignore" value="$env{'form.scantron_options_ignore'}" />
1.331     albertel 6194:   <input type="hidden" name="scantron_options_hidden" value="$env{'form.scantron_options_hidden'}" />
1.203     albertel 6195: SCANTRONFORM
1.447     foxr     6196: 
                   6197:   my $line = 0;
                   6198:     while (defined($env{"form.scantron.bubblelines.$line"})) {
                   6199:        my $chunk =
                   6200: 	   '<input type="hidden" name="scantron.bubblelines.'.$line.'" value="'.$env{"form.scantron.bubblelines.$line"}.'" />'."\n";
1.448     foxr     6201:        $chunk .=
                   6202: 	   '<input type="hidden" name="scantron.first_bubble_line.'.$line.'" value="'.$env{"form.scantron.first_bubble_line.$line"}.'" />'."\n";
1.503     raeburn  6203:        $chunk .= 
                   6204:            '<input type="hidden" name="scantron.sub_bubblelines.'.$line.'" value="'.$env{"form.scantron.sub_bubblelines.$line"}.'" />'."\n";
1.504     raeburn  6205:        $chunk .=
                   6206:            '<input type="hidden" name="scantron.responsetype.'.$line.'" value="'.$env{"form.scantron.responsetype.$line"}.'" />'."\n";
1.447     foxr     6207:        $result .= $chunk;
                   6208:        $line++;
                   6209:    }
1.203     albertel 6210:     return $result;
                   6211: }
                   6212: 
1.423     albertel 6213: =pod
                   6214: 
                   6215: =item scantron_validate_file
                   6216: 
1.424     albertel 6217:     Dispatch routine for doing validation of a bubble sheet data file.
                   6218: 
                   6219:     Also processes any necessary information resets that need to
                   6220:     occur before validation begins (ignore previous corrections,
                   6221:     restarting the skipped records processing)
                   6222: 
1.423     albertel 6223: =cut
                   6224: 
1.157     albertel 6225: sub scantron_validate_file {
1.608     www      6226:     my ($r,$symb) = @_;
1.157     albertel 6227:     if (!$symb) {return '';}
1.324     albertel 6228:     my $default_form_data=&defaultFormData($symb);
1.200     albertel 6229:     
                   6230:     # do the detection of only doing skipped records first befroe we delete
1.424     albertel 6231:     # them when doing the corrections reset
1.257     albertel 6232:     if ($env{'form.scantron_options_redo'} ne 'redo_skipped_ready') {
1.200     albertel 6233: 	&reset_skipping_status();
                   6234:     }
1.257     albertel 6235:     if ($env{'form.scantron_options_redo'} eq 'redo_skipped') {
1.200     albertel 6236: 	&remember_current_skipped();
1.257     albertel 6237: 	$env{'form.scantron_options_redo'}='redo_skipped_ready';
1.200     albertel 6238:     }
                   6239: 
1.257     albertel 6240:     if ($env{'form.scantron_options_ignore'} eq 'ignore_corrections') {
1.200     albertel 6241: 	&check_for_error($r,&scantron_remove_file('corrected'));
                   6242: 	&check_for_error($r,&scantron_remove_file('skipped'));
                   6243: 	&check_for_error($r,&scantron_remove_scan_data());
1.257     albertel 6244: 	$env{'form.scantron_options_ignore'}='done';
1.192     albertel 6245:     }
1.200     albertel 6246: 
1.257     albertel 6247:     if ($env{'form.scantron_corrections'}) {
1.157     albertel 6248: 	&scantron_process_corrections($r);
                   6249:     }
1.503     raeburn  6250:     $r->print('<p>'.&mt('Gathering necessary information.').'</p>');$r->rflush();
1.157     albertel 6251:     #get the student pick code ready
                   6252:     $r->print(&Apache::loncommon::studentbrowser_javascript());
1.582     raeburn  6253:     my $nav_error;
                   6254:     my $max_bubble=&scantron_get_maxbubble(\$nav_error);
                   6255:     if ($nav_error) {
                   6256:         $r->print(&navmap_errormsg());
                   6257:         return '';
                   6258:     }
1.203     albertel 6259:     my $result=&scantron_form_start($max_bubble).$default_form_data;
1.157     albertel 6260:     $r->print($result);
                   6261:     
1.334     albertel 6262:     my @validate_phases=( 'sequence',
                   6263: 			  'ID',
1.157     albertel 6264: 			  'CODE',
                   6265: 			  'doublebubble',
                   6266: 			  'missingbubbles');
1.257     albertel 6267:     if (!$env{'form.validatepass'}) {
                   6268: 	$env{'form.validatepass'} = 0;
1.157     albertel 6269:     }
1.257     albertel 6270:     my $currentphase=$env{'form.validatepass'};
1.157     albertel 6271: 
1.448     foxr     6272: 
1.157     albertel 6273:     my $stop=0;
                   6274:     while (!$stop && $currentphase < scalar(@validate_phases)) {
1.503     raeburn  6275: 	$r->print(&mt('Validating '.$validate_phases[$currentphase]).'<br />');
1.157     albertel 6276: 	$r->rflush();
                   6277: 	my $which="scantron_validate_".$validate_phases[$currentphase];
                   6278: 	{
                   6279: 	    no strict 'refs';
                   6280: 	    ($stop,$currentphase)=&$which($r,$currentphase);
                   6281: 	}
                   6282:     }
                   6283:     if (!$stop) {
1.203     albertel 6284: 	my $warning=&scantron_warning_screen('Start Grading');
1.542     raeburn  6285: 	$r->print(&mt('Validation process complete.').'<br />'.
                   6286:                   $warning.
                   6287:                   &mt('Perform verification for each student after storage of submissions?').
                   6288:                   '&nbsp;<span class="LC_nobreak"><label>'.
                   6289:                   '<input type="radio" name="verifyrecord" value="1" />'.&mt('Yes').'</label>'.
                   6290:                   ('&nbsp;'x3).'<label>'.
                   6291:                   '<input type="radio" name="verifyrecord" value="0" checked="checked" />'.&mt('No').
                   6292:                   '</label></span><br />'.
                   6293:                   &mt('Grading will take longer if you use verification.').'<br />'.
1.572     www      6294:                   &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  6295:                   '<input type="submit" name="submit" value="'.&mt('Start Grading').'" />'.
                   6296:                   '<input type="hidden" name="command" value="scantron_process" />'."\n");
1.157     albertel 6297:     } else {
                   6298: 	$r->print('<input type="hidden" name="command" value="scantron_validate" />');
                   6299: 	$r->print("<input type='hidden' name='validatepass' value='".$currentphase."' />");
                   6300:     }
                   6301:     if ($stop) {
1.334     albertel 6302: 	if ($validate_phases[$currentphase] eq 'sequence') {
1.539     riegler  6303: 	    $r->print('<input type="submit" name="submit" value="'.&mt('Ignore').' &rarr; " />');
1.492     albertel 6304: 	    $r->print(' '.&mt('this error').' <br />');
1.334     albertel 6305: 
1.492     albertel 6306: 	    $r->print(" <p>".&mt("Or click the 'Grading Menu' button to start over.")."</p>");
1.334     albertel 6307: 	} else {
1.503     raeburn  6308:             if ($validate_phases[$currentphase] eq 'doublebubble' || $validate_phases[$currentphase] eq 'missingbubbles') {
1.539     riegler  6309: 	        $r->print('<input type="button" name="submitbutton" value="'.&mt('Continue').' &rarr;" onclick="javascript:verify_bubble_radio(this.form)" />');
1.503     raeburn  6310:             } else {
1.539     riegler  6311:                 $r->print('<input type="submit" name="submit" value="'.&mt('Continue').' &rarr;" />');
1.503     raeburn  6312:             }
1.492     albertel 6313: 	    $r->print(' '.&mt('using corrected info').' <br />');
                   6314: 	    $r->print("<input type='submit' value='".&mt("Skip")."' name='scantron_skip_record' />");
                   6315: 	    $r->print(" ".&mt("this scanline saving it for later."));
1.334     albertel 6316: 	}
1.157     albertel 6317:     }
1.614     www      6318:     $r->print(" </form><br />");
1.157     albertel 6319:     return '';
                   6320: }
                   6321: 
1.423     albertel 6322: 
                   6323: =pod
                   6324: 
                   6325: =item scantron_remove_file
                   6326: 
1.424     albertel 6327:    Removes the requested bubble sheet data file, makes sure that
                   6328:    scantron_original_<filename> is never removed
                   6329: 
                   6330: 
1.423     albertel 6331: =cut
                   6332: 
1.200     albertel 6333: sub scantron_remove_file {
1.192     albertel 6334:     my ($which)=@_;
1.257     albertel 6335:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   6336:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.192     albertel 6337:     my $file='scantron_';
1.200     albertel 6338:     if ($which eq 'corrected' || $which eq 'skipped') {
                   6339: 	$file.=$which.'_';
1.192     albertel 6340:     } else {
                   6341: 	return 'refused';
                   6342:     }
1.257     albertel 6343:     $file.=$env{'form.scantron_selectfile'};
1.200     albertel 6344:     return &Apache::lonnet::removeuserfile($cname,$cdom,$file);
                   6345: }
                   6346: 
1.423     albertel 6347: 
                   6348: =pod
                   6349: 
                   6350: =item scantron_remove_scan_data
                   6351: 
1.424     albertel 6352:    Removes all scan_data correction for the requested bubble sheet
                   6353:    data file.  (In the case that both the are doing skipped records we need
                   6354:    to remember the old skipped lines for the time being so that element
                   6355:    persists for a while.)
                   6356: 
1.423     albertel 6357: =cut
                   6358: 
1.200     albertel 6359: sub scantron_remove_scan_data {
1.257     albertel 6360:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   6361:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.192     albertel 6362:     my @keys=&Apache::lonnet::getkeys('nohist_scantrondata',$cdom,$cname);
                   6363:     my @todelete;
1.257     albertel 6364:     my $filename=$env{'form.scantron_selectfile'};
1.192     albertel 6365:     foreach my $key (@keys) {
                   6366: 	if ($key=~/^\Q$filename\E_/) {
1.257     albertel 6367: 	    if ($env{'form.scantron_options_redo'} eq 'redo_skipped_ready' &&
1.200     albertel 6368: 		$key=~/remember_skipping/) {
                   6369: 		next;
                   6370: 	    }
1.192     albertel 6371: 	    push(@todelete,$key);
                   6372: 	}
                   6373:     }
1.200     albertel 6374:     my $result;
1.192     albertel 6375:     if (@todelete) {
1.491     albertel 6376: 	$result = &Apache::lonnet::del('nohist_scantrondata',
                   6377: 				       \@todelete,$cdom,$cname);
                   6378:     } else {
                   6379: 	$result = 'ok';
1.192     albertel 6380:     }
                   6381:     return $result;
                   6382: }
                   6383: 
1.423     albertel 6384: 
                   6385: =pod
                   6386: 
                   6387: =item scantron_getfile
                   6388: 
1.424     albertel 6389:     Fetches the requested bubble sheet data file (all 3 versions), and
                   6390:     the scan_data hash
                   6391:   
                   6392:   Arguments:
                   6393:     None
                   6394: 
                   6395:   Returns:
                   6396:     2 hash references
                   6397: 
                   6398:      - first one has 
                   6399:          orig      -
                   6400:          corrected -
                   6401:          skipped   -  each of which points to an array ref of the specified
                   6402:                       file broken up into individual lines
                   6403:          count     - number of scanlines
                   6404:  
                   6405:      - second is the scan_data hash possible keys are
1.425     albertel 6406:        ($number refers to scanline numbered $number and thus the key affects
                   6407:         only that scanline
                   6408:         $bubline refers to the specific bubble line element and the aspects
                   6409:         refers to that specific bubble line element)
                   6410: 
                   6411:        $number.user - username:domain to use
                   6412:        $number.CODE_ignore_dup 
                   6413:                     - ignore the duplicate CODE error 
                   6414:        $number.useCODE
                   6415:                     - use the CODE in the scanline as is
                   6416:        $number.no_bubble.$bubline
                   6417:                     - it is valid that there is no bubbled in bubble
                   6418:                       at $number $bubline
                   6419:        remember_skipping
                   6420:                     - a frozen hash containing keys of $number and values
                   6421:                       of either 
                   6422:                         1 - we are on a 'do skipped records pass' and plan
                   6423:                             on processing this line
                   6424:                         2 - we are on a 'do skipped records pass' and this
                   6425:                             scanline has been marked to skip yet again
1.424     albertel 6426: 
1.423     albertel 6427: =cut
                   6428: 
1.157     albertel 6429: sub scantron_getfile {
1.200     albertel 6430:     #FIXME really would prefer a scantron directory
1.257     albertel 6431:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   6432:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.157     albertel 6433:     my $lines;
                   6434:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
1.257     albertel 6435: 		       'scantron_orig_'.$env{'form.scantron_selectfile'});
1.157     albertel 6436:     my %scanlines;
                   6437:     $scanlines{'orig'}=[(split("\n",$lines,-1))];
                   6438:     my $temp=$scanlines{'orig'};
                   6439:     $scanlines{'count'}=$#$temp;
                   6440: 
                   6441:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
1.257     albertel 6442: 		       'scantron_corrected_'.$env{'form.scantron_selectfile'});
1.157     albertel 6443:     if ($lines eq '-1') {
                   6444: 	$scanlines{'corrected'}=[];
                   6445:     } else {
                   6446: 	$scanlines{'corrected'}=[(split("\n",$lines,-1))];
                   6447:     }
                   6448:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
1.257     albertel 6449: 		       'scantron_skipped_'.$env{'form.scantron_selectfile'});
1.157     albertel 6450:     if ($lines eq '-1') {
                   6451: 	$scanlines{'skipped'}=[];
                   6452:     } else {
                   6453: 	$scanlines{'skipped'}=[(split("\n",$lines,-1))];
                   6454:     }
1.175     albertel 6455:     my @tmp=&Apache::lonnet::dump('nohist_scantrondata',$cdom,$cname);
1.157     albertel 6456:     if ($tmp[0] =~ /^(error:|no_such_host)/) { @tmp=(); }
                   6457:     my %scan_data = @tmp;
                   6458:     return (\%scanlines,\%scan_data);
                   6459: }
                   6460: 
1.423     albertel 6461: =pod
                   6462: 
                   6463: =item lonnet_putfile
                   6464: 
1.424     albertel 6465:    Wrapper routine to call &Apache::lonnet::finishuserfileupload
                   6466: 
                   6467:  Arguments:
                   6468:    $contents - data to store
                   6469:    $filename - filename to store $contents into
                   6470: 
                   6471:  Returns:
                   6472:    result value from &Apache::lonnet::finishuserfileupload
                   6473: 
1.423     albertel 6474: =cut
                   6475: 
1.157     albertel 6476: sub lonnet_putfile {
                   6477:     my ($contents,$filename)=@_;
1.257     albertel 6478:     my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   6479:     my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   6480:     $env{'form.sillywaytopassafilearound'}=$contents;
1.275     albertel 6481:     &Apache::lonnet::finishuserfileupload($docuname,$docudom,'sillywaytopassafilearound',$filename);
1.157     albertel 6482: 
                   6483: }
                   6484: 
1.423     albertel 6485: =pod
                   6486: 
                   6487: =item scantron_putfile
                   6488: 
1.424     albertel 6489:     Stores the current version of the bubble sheet data files, and the
                   6490:     scan_data hash. (Does not modify the original version only the
                   6491:     corrected and skipped versions.
                   6492: 
                   6493:  Arguments:
                   6494:     $scanlines - hash ref that looks like the first return value from
                   6495:                  &scantron_getfile()
                   6496:     $scan_data - hash ref that looks like the second return value from
                   6497:                  &scantron_getfile()
                   6498: 
1.423     albertel 6499: =cut
                   6500: 
1.157     albertel 6501: sub scantron_putfile {
                   6502:     my ($scanlines,$scan_data) = @_;
1.200     albertel 6503:     #FIXME really would prefer a scantron directory
1.257     albertel 6504:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   6505:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.200     albertel 6506:     if ($scanlines) {
                   6507: 	my $prefix='scantron_';
1.157     albertel 6508: # no need to update orig, shouldn't change
                   6509: #   &lonnet_putfile(join("\n",@{$scanlines->{'orig'}}),$prefix.'orig_'.
1.257     albertel 6510: #		    $env{'form.scantron_selectfile'});
1.200     albertel 6511: 	&lonnet_putfile(join("\n",@{$scanlines->{'corrected'}}),
                   6512: 			$prefix.'corrected_'.
1.257     albertel 6513: 			$env{'form.scantron_selectfile'});
1.200     albertel 6514: 	&lonnet_putfile(join("\n",@{$scanlines->{'skipped'}}),
                   6515: 			$prefix.'skipped_'.
1.257     albertel 6516: 			$env{'form.scantron_selectfile'});
1.200     albertel 6517:     }
1.175     albertel 6518:     &Apache::lonnet::put('nohist_scantrondata',$scan_data,$cdom,$cname);
1.157     albertel 6519: }
                   6520: 
1.423     albertel 6521: =pod
                   6522: 
                   6523: =item scantron_get_line
                   6524: 
1.424     albertel 6525:    Returns the correct version of the scanline
                   6526: 
                   6527:  Arguments:
                   6528:     $scanlines - hash ref that looks like the first return value from
                   6529:                  &scantron_getfile()
                   6530:     $scan_data - hash ref that looks like the second return value from
                   6531:                  &scantron_getfile()
                   6532:     $i         - number of the requested line (starts at 0)
                   6533: 
                   6534:  Returns:
                   6535:    A scanline, (either the original or the corrected one if it
                   6536:    exists), or undef if the requested scanline should be
                   6537:    skipped. (Either because it's an skipped scanline, or it's an
                   6538:    unskipped scanline and we are not doing a 'do skipped scanlines'
                   6539:    pass.
                   6540: 
1.423     albertel 6541: =cut
                   6542: 
1.157     albertel 6543: sub scantron_get_line {
1.200     albertel 6544:     my ($scanlines,$scan_data,$i)=@_;
1.376     albertel 6545:     if (&should_be_skipped($scanlines,$scan_data,$i)) { return undef; }
                   6546:     #if ($scanlines->{'skipped'}[$i]) { return undef; }
1.157     albertel 6547:     if ($scanlines->{'corrected'}[$i]) {return $scanlines->{'corrected'}[$i];}
                   6548:     return $scanlines->{'orig'}[$i]; 
                   6549: }
                   6550: 
1.423     albertel 6551: =pod
                   6552: 
                   6553: =item scantron_todo_count
                   6554: 
1.424     albertel 6555:     Counts the number of scanlines that need processing.
                   6556: 
                   6557:  Arguments:
                   6558:     $scanlines - hash ref that looks like the first return value from
                   6559:                  &scantron_getfile()
                   6560:     $scan_data - hash ref that looks like the second return value from
                   6561:                  &scantron_getfile()
                   6562: 
                   6563:  Returns:
                   6564:     $count - number of scanlines to process
                   6565: 
1.423     albertel 6566: =cut
                   6567: 
1.200     albertel 6568: sub get_todo_count {
                   6569:     my ($scanlines,$scan_data)=@_;
                   6570:     my $count=0;
                   6571:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
                   6572: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
                   6573: 	if ($line=~/^[\s\cz]*$/) { next; }
                   6574: 	$count++;
                   6575:     }
                   6576:     return $count;
                   6577: }
                   6578: 
1.423     albertel 6579: =pod
                   6580: 
                   6581: =item scantron_put_line
                   6582: 
1.424     albertel 6583:     Updates the 'corrected' or 'skipped' versions of the bubble sheet
                   6584:     data file.
                   6585: 
                   6586:  Arguments:
                   6587:     $scanlines - hash ref that looks like the first return value from
                   6588:                  &scantron_getfile()
                   6589:     $scan_data - hash ref that looks like the second return value from
                   6590:                  &scantron_getfile()
                   6591:     $i         - line number to update
                   6592:     $newline   - contents of the updated scanline
                   6593:     $skip      - if true make the line for skipping and update the
                   6594:                  'skipped' file
                   6595: 
1.423     albertel 6596: =cut
                   6597: 
1.157     albertel 6598: sub scantron_put_line {
1.200     albertel 6599:     my ($scanlines,$scan_data,$i,$newline,$skip)=@_;
1.157     albertel 6600:     if ($skip) {
                   6601: 	$scanlines->{'skipped'}[$i]=$newline;
1.376     albertel 6602: 	&start_skipping($scan_data,$i);
1.157     albertel 6603: 	return;
                   6604:     }
                   6605:     $scanlines->{'corrected'}[$i]=$newline;
                   6606: }
                   6607: 
1.423     albertel 6608: =pod
                   6609: 
                   6610: =item scantron_clear_skip
                   6611: 
1.424     albertel 6612:    Remove a line from the 'skipped' file
                   6613: 
                   6614:  Arguments:
                   6615:     $scanlines - hash ref that looks like the first return value from
                   6616:                  &scantron_getfile()
                   6617:     $scan_data - hash ref that looks like the second return value from
                   6618:                  &scantron_getfile()
                   6619:     $i         - line number to update
                   6620: 
1.423     albertel 6621: =cut
                   6622: 
1.376     albertel 6623: sub scantron_clear_skip {
                   6624:     my ($scanlines,$scan_data,$i)=@_;
                   6625:     if (exists($scanlines->{'skipped'}[$i])) {
                   6626: 	undef($scanlines->{'skipped'}[$i]);
                   6627: 	return 1;
                   6628:     }
                   6629:     return 0;
                   6630: }
                   6631: 
1.423     albertel 6632: =pod
                   6633: 
                   6634: =item scantron_filter_not_exam
                   6635: 
1.424     albertel 6636:    Filter routine used by &Apache::lonnavmaps::retrieveResources(), to
                   6637:    filter out resources that are not marked as 'exam' mode
                   6638: 
1.423     albertel 6639: =cut
                   6640: 
1.334     albertel 6641: sub scantron_filter_not_exam {
                   6642:     my ($curres)=@_;
                   6643:     
                   6644:     if (ref($curres) && $curres->is_problem() && !$curres->is_exam()) {
                   6645: 	# if the user has asked to not have either hidden
                   6646: 	# or 'randomout' controlled resources to be graded
                   6647: 	# don't include them
                   6648: 	if ($env{'form.scantron_options_hidden'} eq 'ignore_hidden'
                   6649: 	    && $curres->randomout) {
                   6650: 	    return 0;
                   6651: 	}
                   6652: 	return 1;
                   6653:     }
                   6654:     return 0;
                   6655: }
                   6656: 
1.423     albertel 6657: =pod
                   6658: 
                   6659: =item scantron_validate_sequence
                   6660: 
1.424     albertel 6661:     Validates the selected sequence, checking for resource that are
                   6662:     not set to exam mode.
                   6663: 
1.423     albertel 6664: =cut
                   6665: 
1.334     albertel 6666: sub scantron_validate_sequence {
                   6667:     my ($r,$currentphase) = @_;
                   6668: 
                   6669:     my $navmap=Apache::lonnavmaps::navmap->new();
1.582     raeburn  6670:     unless (ref($navmap)) {
                   6671:         $r->print(&navmap_errormsg());
                   6672:         return (1,$currentphase);
                   6673:     }
1.334     albertel 6674:     my (undef,undef,$sequence)=
                   6675: 	&Apache::lonnet::decode_symb($env{'form.selectpage'});
                   6676: 
                   6677:     my $map=$navmap->getResourceByUrl($sequence);
                   6678: 
                   6679:     $r->print('<input type="hidden" name="validate_sequence_exam"
                   6680:                                     value="ignore" />');
                   6681:     if ($env{'form.validate_sequence_exam'} ne 'ignore') {
                   6682: 	my @resources=
                   6683: 	    $navmap->retrieveResources($map,\&scantron_filter_not_exam,1,0);
                   6684: 	if (@resources) {
1.357     banghart 6685: 	    $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 6686: 	    return (1,$currentphase);
                   6687: 	}
                   6688:     }
                   6689: 
                   6690:     return (0,$currentphase+1);
                   6691: }
                   6692: 
1.423     albertel 6693: 
                   6694: 
1.157     albertel 6695: sub scantron_validate_ID {
                   6696:     my ($r,$currentphase) = @_;
                   6697:     
                   6698:     #get student info
                   6699:     my $classlist=&Apache::loncoursedata::get_classlist();
                   6700:     my %idmap=&username_to_idmap($classlist);
                   6701: 
                   6702:     #get scantron line setup
1.257     albertel 6703:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.157     albertel 6704:     my ($scanlines,$scan_data)=&scantron_getfile();
1.582     raeburn  6705: 
                   6706:     my $nav_error;
                   6707:     &scantron_get_maxbubble(\$nav_error); # parse needs the bubble_lines.. array.
                   6708:     if ($nav_error) {
                   6709:         $r->print(&navmap_errormsg());
                   6710:         return(1,$currentphase);
                   6711:     }
1.157     albertel 6712: 
                   6713:     my %found=('ids'=>{},'usernames'=>{});
                   6714:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
1.200     albertel 6715: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.157     albertel 6716: 	if ($line=~/^[\s\cz]*$/) { next; }
                   6717: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
                   6718: 						 $scan_data);
                   6719: 	my $id=$$scan_record{'scantron.ID'};
                   6720: 	my $found;
                   6721: 	foreach my $checkid (keys(%idmap)) {
                   6722: 	    if (lc($checkid) eq lc($id)) { $found=$checkid;last; }
                   6723: 	}
                   6724: 	if ($found) {
                   6725: 	    my $username=$idmap{$found};
                   6726: 	    if ($found{'ids'}{$found}) {
                   6727: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
                   6728: 					 $line,'duplicateID',$found);
1.194     albertel 6729: 		return(1,$currentphase);
1.157     albertel 6730: 	    } elsif ($found{'usernames'}{$username}) {
                   6731: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
                   6732: 					 $line,'duplicateID',$username);
1.194     albertel 6733: 		return(1,$currentphase);
1.157     albertel 6734: 	    }
1.186     albertel 6735: 	    #FIXME store away line we previously saw the ID on to use above
1.157     albertel 6736: 	    $found{'ids'}{$found}++;
                   6737: 	    $found{'usernames'}{$username}++;
                   6738: 	} else {
                   6739: 	    if ($id =~ /^\s*$/) {
1.158     albertel 6740: 		my $username=&scan_data($scan_data,"$i.user");
1.157     albertel 6741: 		if (defined($username) && $found{'usernames'}{$username}) {
                   6742: 		    &scantron_get_correction($r,$i,$scan_record,
                   6743: 					     \%scantron_config,
                   6744: 					     $line,'duplicateID',$username);
1.194     albertel 6745: 		    return(1,$currentphase);
1.157     albertel 6746: 		} elsif (!defined($username)) {
                   6747: 		    &scantron_get_correction($r,$i,$scan_record,
                   6748: 					     \%scantron_config,
                   6749: 					     $line,'incorrectID');
1.194     albertel 6750: 		    return(1,$currentphase);
1.157     albertel 6751: 		}
                   6752: 		$found{'usernames'}{$username}++;
                   6753: 	    } else {
                   6754: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
                   6755: 					 $line,'incorrectID');
1.194     albertel 6756: 		return(1,$currentphase);
1.157     albertel 6757: 	    }
                   6758: 	}
                   6759:     }
                   6760: 
                   6761:     return (0,$currentphase+1);
                   6762: }
                   6763: 
1.423     albertel 6764: 
1.157     albertel 6765: sub scantron_get_correction {
                   6766:     my ($r,$i,$scan_record,$scan_config,$line,$error,$arg)=@_;
1.454     banghart 6767: #FIXME in the case of a duplicated ID the previous line, probably need
1.157     albertel 6768: #to show both the current line and the previous one and allow skipping
                   6769: #the previous one or the current one
                   6770: 
1.333     albertel 6771:     if ( $$scan_record{'scantron.PaperID'} =~ /\S/) {
1.492     albertel 6772: 	$r->print("<p>".&mt("<b>An error was detected ($error)</b>".
                   6773: 			    " for PaperID <tt>[_1]</tt>",
                   6774: 			    $$scan_record{'scantron.PaperID'})."</p> \n");
1.157     albertel 6775:     } else {
1.492     albertel 6776: 	$r->print("<p>".&mt("<b>An error was detected ($error)</b>".
                   6777: 			    " in scanline [_1] <pre>[_2]</pre>",
                   6778: 			    $i,$line)."</p> \n");
                   6779:     }
                   6780:     my $message="<p>".&mt("The ID on the form is  <tt>[_1]</tt><br />".
                   6781: 			  "The name on the paper is [_2],[_3]",
                   6782: 			  $$scan_record{'scantron.ID'},
                   6783: 			  $$scan_record{'scantron.LastName'},
                   6784: 			  $$scan_record{'scantron.FirstName'})."</p>";
1.242     albertel 6785: 
1.157     albertel 6786:     $r->print('<input type="hidden" name="scantron_corrections" value="'.$error.'" />'."\n");
                   6787:     $r->print('<input type="hidden" name="scantron_line" value="'.$i.'" />'."\n");
1.503     raeburn  6788:                            # Array populated for doublebubble or
                   6789:     my @lines_to_correct;  # missingbubble errors to build javascript
                   6790:                            # to validate radio button checking   
                   6791: 
1.157     albertel 6792:     if ($error =~ /ID$/) {
1.186     albertel 6793: 	if ($error eq 'incorrectID') {
1.492     albertel 6794: 	    $r->print("<p>".&mt("The encoded ID is not in the classlist").
                   6795: 		      "</p>\n");
1.157     albertel 6796: 	} elsif ($error eq 'duplicateID') {
1.492     albertel 6797: 	    $r->print("<p>".&mt("The encoded ID has also been used by a previous paper [_1]",$arg)."</p>\n");
1.157     albertel 6798: 	}
1.242     albertel 6799: 	$r->print($message);
1.492     albertel 6800: 	$r->print("<p>".&mt("How should I handle this?")." <br /> \n");
1.157     albertel 6801: 	$r->print("\n<ul><li> ");
                   6802: 	#FIXME it would be nice if this sent back the user ID and
                   6803: 	#could do partial userID matches
                   6804: 	$r->print(&Apache::loncommon::selectstudent_link('scantronupload',
                   6805: 				       'scantron_username','scantron_domain'));
                   6806: 	$r->print(": <input type='text' name='scantron_username' value='' />");
                   6807: 	$r->print("\n@".
1.257     albertel 6808: 		 &Apache::loncommon::select_dom_form($env{'request.role.domain'},'scantron_domain'));
1.157     albertel 6809: 
                   6810: 	$r->print('</li>');
1.186     albertel 6811:     } elsif ($error =~ /CODE$/) {
                   6812: 	if ($error eq 'incorrectCODE') {
1.492     albertel 6813: 	    $r->print("<p>".&mt("The encoded CODE is not in the list of possible CODEs.")."</p>\n");
1.186     albertel 6814: 	} elsif ($error eq 'duplicateCODE') {
1.492     albertel 6815: 	    $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 6816: 	}
1.492     albertel 6817: 	$r->print("<p>".&mt("The CODE on the form is  <tt>'[_1]'</tt>",
                   6818: 			    $$scan_record{'scantron.CODE'})."<br />\n");
1.242     albertel 6819: 	$r->print($message);
1.492     albertel 6820: 	$r->print("<p>".&mt("How should I handle this?")." <br /> \n");
1.187     albertel 6821: 	$r->print("\n<br /> ");
1.194     albertel 6822: 	my $i=0;
1.273     albertel 6823: 	if ($error eq 'incorrectCODE' 
                   6824: 	    && $$scan_record{'scantron.CODE'}=~/\S/ ) {
1.194     albertel 6825: 	    my ($max,$closest)=&scantron_get_closely_matching_CODEs($arg,$$scan_record{'scantron.CODE'});
1.278     albertel 6826: 	    if ($closest > 0) {
                   6827: 		foreach my $testcode (@{$closest}) {
                   6828: 		    my $checked='';
1.569     bisitz   6829: 		    if (!$i) { $checked=' checked="checked"'; }
1.492     albertel 6830: 		    $r->print("
                   6831:    <label>
1.569     bisitz   6832:        <input type='radio' name='scantron_CODE_resolution' value='use_closest_$i'$checked />
1.492     albertel 6833:        ".&mt("Use the similar CODE [_1] instead.",
                   6834: 	    "<b><tt>".$testcode."</tt></b>")."
                   6835:     </label>
                   6836:     <input type='hidden' name='scantron_CODE_closest_$i' value='$testcode' />");
1.278     albertel 6837: 		    $r->print("\n<br />");
                   6838: 		    $i++;
                   6839: 		}
1.194     albertel 6840: 	    }
                   6841: 	}
1.273     albertel 6842: 	if ($$scan_record{'scantron.CODE'}=~/\S/ ) {
1.569     bisitz   6843: 	    my $checked; if (!$i) { $checked=' checked="checked"'; }
1.492     albertel 6844: 	    $r->print("
                   6845:     <label>
1.569     bisitz   6846:         <input type='radio' name='scantron_CODE_resolution' value='use_unfound'$checked />
1.492     albertel 6847:        ".&mt("Use the CODE [_1] that is was on the paper, ignoring the error.",
                   6848: 	     "<b><tt>".$$scan_record{'scantron.CODE'}."</tt></b>")."
                   6849:     </label>");
1.273     albertel 6850: 	    $r->print("\n<br />");
                   6851: 	}
1.194     albertel 6852: 
1.597     wenzelju 6853: 	$r->print(&Apache::lonhtmlcommon::scripttag(<<ENDSCRIPT));
1.188     albertel 6854: function change_radio(field) {
1.190     albertel 6855:     var slct=document.scantronupload.scantron_CODE_resolution;
1.188     albertel 6856:     var i;
                   6857:     for (i=0;i<slct.length;i++) {
                   6858:         if (slct[i].value==field) { slct[i].checked=true; }
                   6859:     }
                   6860: }
                   6861: ENDSCRIPT
1.187     albertel 6862: 	my $href="/adm/pickcode?".
1.359     www      6863: 	   "form=".&escape("scantronupload").
                   6864: 	   "&scantron_format=".&escape($env{'form.scantron_format'}).
                   6865: 	   "&scantron_CODElist=".&escape($env{'form.scantron_CODElist'}).
                   6866: 	   "&curCODE=".&escape($$scan_record{'scantron.CODE'}).
                   6867: 	   "&scantron_selectfile=".&escape($env{'form.scantron_selectfile'});
1.332     albertel 6868: 	if ($env{'form.scantron_CODElist'} =~ /\S/) { 
1.492     albertel 6869: 	    $r->print("
                   6870:     <label>
                   6871:        <input type='radio' name='scantron_CODE_resolution' value='use_found' />
                   6872:        ".&mt("[_1]Select[_2] a CODE from the list of all CODEs and use it.",
                   6873: 	     "<a target='_blank' href='$href'>","</a>")."
                   6874:     </label> 
1.558     bisitz   6875:     ".&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 6876: 	    $r->print("\n<br />");
                   6877: 	}
1.492     albertel 6878: 	$r->print("
                   6879:     <label>
                   6880:        <input type='radio' name='scantron_CODE_resolution' value='use_typed' />
                   6881:        ".&mt("Use [_1] as the CODE.",
                   6882: 	     "</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 6883: 	$r->print("\n<br /><br />");
1.157     albertel 6884:     } elsif ($error eq 'doublebubble') {
1.503     raeburn  6885: 	$r->print("<p>".&mt("There have been multiple bubbles scanned for some question(s)")."</p>\n");
1.497     foxr     6886: 
                   6887: 	# The form field scantron_questions is acutally a list of line numbers.
                   6888: 	# represented by this form so:
                   6889: 
                   6890: 	my $line_list = &questions_to_line_list($arg);
                   6891: 
1.157     albertel 6892: 	$r->print('<input type="hidden" name="scantron_questions" value="'.
1.497     foxr     6893: 		  $line_list.'" />');
1.242     albertel 6894: 	$r->print($message);
1.492     albertel 6895: 	$r->print("<p>".&mt("Please indicate which bubble should be used for grading")."</p>");
1.157     albertel 6896: 	foreach my $question (@{$arg}) {
1.503     raeburn  6897: 	    my @linenums = &prompt_for_corrections($r,$question,$scan_config,
                   6898:                                                    $scan_record, $error);
1.524     raeburn  6899:             push(@lines_to_correct,@linenums);
1.157     albertel 6900: 	}
1.503     raeburn  6901:         $r->print(&verify_bubbles_checked(@lines_to_correct));
1.157     albertel 6902:     } elsif ($error eq 'missingbubble') {
1.492     albertel 6903: 	$r->print("<p>".&mt("There have been <b>no</b> bubbles scanned for some question(s)")."</p>\n");
1.242     albertel 6904: 	$r->print($message);
1.492     albertel 6905: 	$r->print("<p>".&mt("Please indicate which bubble should be used for grading.")."</p>");
1.503     raeburn  6906: 	$r->print(&mt("Some questions have no scanned bubbles.")."\n");
1.497     foxr     6907: 
1.503     raeburn  6908: 	# The form field scantron_questions is actually a list of line numbers not
1.497     foxr     6909: 	# a list of question numbers. Therefore:
                   6910: 	#
                   6911: 	
                   6912: 	my $line_list = &questions_to_line_list($arg);
                   6913: 
1.157     albertel 6914: 	$r->print('<input type="hidden" name="scantron_questions" value="'.
1.497     foxr     6915: 		  $line_list.'" />');
1.157     albertel 6916: 	foreach my $question (@{$arg}) {
1.503     raeburn  6917: 	    my @linenums = &prompt_for_corrections($r,$question,$scan_config,
                   6918:                                                    $scan_record, $error);
1.524     raeburn  6919:             push(@lines_to_correct,@linenums);
1.157     albertel 6920: 	}
1.503     raeburn  6921:         $r->print(&verify_bubbles_checked(@lines_to_correct));
1.157     albertel 6922:     } else {
                   6923: 	$r->print("\n<ul>");
                   6924:     }
                   6925:     $r->print("\n</li></ul>");
1.497     foxr     6926: }
                   6927: 
1.503     raeburn  6928: sub verify_bubbles_checked {
                   6929:     my (@ansnums) = @_;
                   6930:     my $ansnumstr = join('","',@ansnums);
                   6931:     my $warning = &mt("A bubble or 'No bubble' selection has not been made for one or more lines.");
1.597     wenzelju 6932:     my $output = &Apache::lonhtmlcommon::scripttag((<<ENDSCRIPT));
1.503     raeburn  6933: function verify_bubble_radio(form) {
                   6934:     var ansnumArray = new Array ("$ansnumstr");
                   6935:     var need_bubble_count = 0;
                   6936:     for (var i=0; i<ansnumArray.length; i++) {
                   6937:         if (form.elements["scantron_correct_Q_"+ansnumArray[i]].length > 1) {
                   6938:             var bubble_picked = 0; 
                   6939:             for (var j=0; j<form.elements["scantron_correct_Q_"+ansnumArray[i]].length; j++) {
                   6940:                 if (form.elements["scantron_correct_Q_"+ansnumArray[i]][j].checked == true) {
                   6941:                     bubble_picked = 1;
                   6942:                 }
                   6943:             }
                   6944:             if (bubble_picked == 0) {
                   6945:                 need_bubble_count ++;
                   6946:             }
                   6947:         }
                   6948:     }
                   6949:     if (need_bubble_count) {
                   6950:         alert("$warning");
                   6951:         return;
                   6952:     }
                   6953:     form.submit(); 
                   6954: }
                   6955: ENDSCRIPT
                   6956:     return $output;
                   6957: }
                   6958: 
1.497     foxr     6959: =pod
                   6960: 
                   6961: =item  questions_to_line_list
1.157     albertel 6962: 
1.497     foxr     6963: Converts a list of questions into a string of comma separated
                   6964: line numbers in the answer sheet used by the questions.  This is
                   6965: used to fill in the scantron_questions form field.
                   6966: 
                   6967:   Arguments:
                   6968:      questions    - Reference to an array of questions.
                   6969: 
                   6970: =cut
                   6971: 
                   6972: 
                   6973: sub questions_to_line_list {
                   6974:     my ($questions) = @_;
                   6975:     my @lines;
                   6976: 
1.503     raeburn  6977:     foreach my $item (@{$questions}) {
                   6978:         my $question = $item;
                   6979:         my ($first,$count,$last);
                   6980:         if ($item =~ /^(\d+)\.(\d+)$/) {
                   6981:             $question = $1;
                   6982:             my $subquestion = $2;
                   6983:             $first = $first_bubble_line{$question-1} + 1;
                   6984:             my @subans = split(/,/,$subdivided_bubble_lines{$question-1});
                   6985:             my $subcount = 1;
                   6986:             while ($subcount<$subquestion) {
                   6987:                 $first += $subans[$subcount-1];
                   6988:                 $subcount ++;
                   6989:             }
                   6990:             $count = $subans[$subquestion-1];
                   6991:         } else {
                   6992: 	    $first   = $first_bubble_line{$question-1} + 1;
                   6993: 	    $count   = $bubble_lines_per_response{$question-1};
                   6994:         }
1.506     raeburn  6995:         $last = $first+$count-1;
1.503     raeburn  6996:         push(@lines, ($first..$last));
1.497     foxr     6997:     }
                   6998:     return join(',', @lines);
                   6999: }
                   7000: 
                   7001: =pod 
                   7002: 
                   7003: =item prompt_for_corrections
                   7004: 
                   7005: Prompts for a potentially multiline correction to the
                   7006: user's bubbling (factors out common code from scantron_get_correction
                   7007: for multi and missing bubble cases).
                   7008: 
                   7009:  Arguments:
                   7010:    $r           - Apache request object.
                   7011:    $question    - The question number to prompt for.
                   7012:    $scan_config - The scantron file configuration hash.
                   7013:    $scan_record - Reference to the hash that has the the parsed scanlines.
1.503     raeburn  7014:    $error       - Type of error
1.497     foxr     7015: 
                   7016:  Implicit inputs:
                   7017:    %bubble_lines_per_response   - Starting line numbers for each question.
                   7018:                                   Numbered from 0 (but question numbers are from
                   7019:                                   1.
                   7020:    %first_bubble_line           - Starting bubble line for each question.
1.509     raeburn  7021:    %subdivided_bubble_lines     - optionresponse, matchresponse and rankresponse 
                   7022:                                   type problems render as separate sub-questions, 
1.503     raeburn  7023:                                   in exam mode. This hash contains a 
                   7024:                                   comma-separated list of the lines per 
                   7025:                                   sub-question.
1.510     raeburn  7026:    %responsetype_per_response   - essayresponse, formularesponse,
                   7027:                                   stringresponse, imageresponse, reactionresponse,
                   7028:                                   and organicresponse type problem parts can have
1.503     raeburn  7029:                                   multiple lines per response if the weight
                   7030:                                   assigned exceeds 10.  In this case, only
                   7031:                                   one bubble per line is permitted, but more 
                   7032:                                   than one line might contain bubbles, e.g.
                   7033:                                   bubbling of: line 1 - J, line 2 - J, 
                   7034:                                   line 3 - B would assign 22 points.  
1.497     foxr     7035: 
                   7036: =cut
                   7037: 
                   7038: sub prompt_for_corrections {
1.503     raeburn  7039:     my ($r, $question, $scan_config, $scan_record, $error) = @_;
                   7040:     my ($current_line,$lines);
                   7041:     my @linenums;
                   7042:     my $questionnum = $question;
                   7043:     if ($question =~ /^(\d+)\.(\d+)$/) {
                   7044:         $question = $1;
                   7045:         $current_line = $first_bubble_line{$question-1} + 1 ;
                   7046:         my $subquestion = $2;
                   7047:         my @subans = split(/,/,$subdivided_bubble_lines{$question-1});
                   7048:         my $subcount = 1;
                   7049:         while ($subcount<$subquestion) {
                   7050:             $current_line += $subans[$subcount-1];
                   7051:             $subcount ++;
                   7052:         }
                   7053:         $lines = $subans[$subquestion-1];
                   7054:     } else {
                   7055:         $current_line = $first_bubble_line{$question-1} + 1 ;
                   7056:         $lines        = $bubble_lines_per_response{$question-1};
                   7057:     }
1.497     foxr     7058:     if ($lines > 1) {
1.503     raeburn  7059:         $r->print(&mt('The group of bubble lines below responds to a single question.').'<br />');
                   7060:         if (($responsetype_per_response{$question-1} eq 'essayresponse') ||
                   7061:             ($responsetype_per_response{$question-1} eq 'formularesponse') ||
1.510     raeburn  7062:             ($responsetype_per_response{$question-1} eq 'stringresponse') ||
                   7063:             ($responsetype_per_response{$question-1} eq 'imageresponse') ||
                   7064:             ($responsetype_per_response{$question-1} eq 'reactionresponse') ||
                   7065:             ($responsetype_per_response{$question-1} eq 'organicresponse')) {
1.572     www      7066:             $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  7067:         } else {
                   7068:             $r->print(&mt("Select at most one bubble in a single line and select 'No Bubble' in all the other lines. ")."<br />");
                   7069:         }
1.497     foxr     7070:     }
                   7071:     for (my $i =0; $i < $lines; $i++) {
1.503     raeburn  7072:         my $selected = $$scan_record{"scantron.$current_line.answer"};
                   7073: 	&scantron_bubble_selector($r,$scan_config,$current_line, 
                   7074: 	        		  $questionnum,$error,split('', $selected));
1.524     raeburn  7075:         push(@linenums,$current_line);
1.497     foxr     7076: 	$current_line++;
                   7077:     }
                   7078:     if ($lines > 1) {
                   7079: 	$r->print("<hr /><br />");
                   7080:     }
1.503     raeburn  7081:     return @linenums;
1.157     albertel 7082: }
1.423     albertel 7083: 
                   7084: =pod
                   7085: 
                   7086: =item scantron_bubble_selector
                   7087:   
                   7088:    Generates the html radiobuttons to correct a single bubble line
1.424     albertel 7089:    possibly showing the existing the selected bubbles if known
1.423     albertel 7090: 
                   7091:  Arguments:
                   7092:     $r           - Apache request object
                   7093:     $scan_config - hash from &get_scantron_config()
1.497     foxr     7094:     $line        - Number of the line being displayed.
1.503     raeburn  7095:     $questionnum - Question number (may include subquestion)
                   7096:     $error       - Type of error.
1.497     foxr     7097:     @selected    - Array of bubbles picked on this line.
1.423     albertel 7098: 
                   7099: =cut
                   7100: 
1.157     albertel 7101: sub scantron_bubble_selector {
1.503     raeburn  7102:     my ($r,$scan_config,$line,$questionnum,$error,@selected)=@_;
1.157     albertel 7103:     my $max=$$scan_config{'Qlength'};
1.274     albertel 7104: 
                   7105:     my $scmode=$$scan_config{'Qon'};
                   7106:     if ($scmode eq 'number' || $scmode eq 'letter') { $max=10; }	     
                   7107: 
1.157     albertel 7108:     my @alphabet=('A'..'Z');
1.503     raeburn  7109:     $r->print(&Apache::loncommon::start_data_table().
                   7110:               &Apache::loncommon::start_data_table_row());
                   7111:     $r->print('<td rowspan="2" class="LC_leftcol_header">'.$line.'</td>');
1.497     foxr     7112:     for (my $i=0;$i<$max+1;$i++) {
                   7113: 	$r->print("\n".'<td align="center">');
                   7114: 	if ($selected[0] eq $alphabet[$i]) { $r->print('X'); shift(@selected) }
                   7115: 	else { $r->print('&nbsp;'); }
                   7116: 	$r->print('</td>');
                   7117:     }
1.503     raeburn  7118:     $r->print(&Apache::loncommon::end_data_table_row().
                   7119:               &Apache::loncommon::start_data_table_row());
1.497     foxr     7120:     for (my $i=0;$i<$max;$i++) {
                   7121: 	$r->print("\n".
                   7122: 		  '<td><label><input type="radio" name="scantron_correct_Q_'.
                   7123: 		  $line.'" value="'.$i.'" />'.$alphabet[$i]."</label></td>");
                   7124:     }
1.503     raeburn  7125:     my $nobub_checked = ' ';
                   7126:     if ($error eq 'missingbubble') {
                   7127:         $nobub_checked = ' checked = "checked" ';
                   7128:     }
                   7129:     $r->print("\n".'<td><label><input type="radio" name="scantron_correct_Q_'.
                   7130: 	      $line.'" value="none"'.$nobub_checked.'/>'.&mt('No bubble').
                   7131:               '</label>'."\n".'<input type="hidden" name="scantron_questionnum_Q_'.
                   7132:               $line.'" value="'.$questionnum.'" /></td>');
                   7133:     $r->print(&Apache::loncommon::end_data_table_row().
                   7134:               &Apache::loncommon::end_data_table());
1.157     albertel 7135: }
                   7136: 
1.423     albertel 7137: =pod
                   7138: 
                   7139: =item num_matches
                   7140: 
1.424     albertel 7141:    Counts the number of characters that are the same between the two arguments.
                   7142: 
                   7143:  Arguments:
                   7144:    $orig - CODE from the scanline
                   7145:    $code - CODE to match against
                   7146: 
                   7147:  Returns:
                   7148:    $count - integer count of the number of same characters between the
                   7149:             two arguments
                   7150: 
1.423     albertel 7151: =cut
                   7152: 
1.194     albertel 7153: sub num_matches {
                   7154:     my ($orig,$code) = @_;
                   7155:     my @code=split(//,$code);
                   7156:     my @orig=split(//,$orig);
                   7157:     my $same=0;
                   7158:     for (my $i=0;$i<scalar(@code);$i++) {
                   7159: 	if ($code[$i] eq $orig[$i]) { $same++; }
                   7160:     }
                   7161:     return $same;
                   7162: }
                   7163: 
1.423     albertel 7164: =pod
                   7165: 
                   7166: =item scantron_get_closely_matching_CODEs
                   7167: 
1.424     albertel 7168:    Cycles through all CODEs and finds the set that has the greatest
                   7169:    number of same characters as the provided CODE
                   7170: 
                   7171:  Arguments:
                   7172:    $allcodes - hash ref returned by &get_codes()
                   7173:    $CODE     - CODE from the current scanline
                   7174: 
                   7175:  Returns:
                   7176:    2 element list
                   7177:     - first elements is number of how closely matching the best fit is 
                   7178:       (5 means best set has 5 matching characters)
                   7179:     - second element is an arrary ref containing the set of valid CODEs
                   7180:       that best fit the passed in CODE
                   7181: 
1.423     albertel 7182: =cut
                   7183: 
1.194     albertel 7184: sub scantron_get_closely_matching_CODEs {
                   7185:     my ($allcodes,$CODE)=@_;
                   7186:     my @CODEs;
                   7187:     foreach my $testcode (sort(keys(%{$allcodes}))) {
                   7188: 	push(@{$CODEs[&num_matches($CODE,$testcode)]},$testcode);
                   7189:     }
                   7190: 
                   7191:     return ($#CODEs,$CODEs[-1]);
                   7192: }
                   7193: 
1.423     albertel 7194: =pod
                   7195: 
                   7196: =item get_codes
                   7197: 
1.424     albertel 7198:    Builds a hash which has keys of all of the valid CODEs from the selected
                   7199:    set of remembered CODEs.
                   7200: 
                   7201:  Arguments:
                   7202:   $old_name - name of the set of remembered CODEs
                   7203:   $cdom     - domain of the course
                   7204:   $cnum     - internal course name
                   7205: 
                   7206:  Returns:
                   7207:   %allcodes - keys are the valid CODEs, values are all 1
                   7208: 
1.423     albertel 7209: =cut
                   7210: 
1.194     albertel 7211: sub get_codes {
1.280     foxr     7212:     my ($old_name, $cdom, $cnum) = @_;
                   7213:     if (!$old_name) {
                   7214: 	$old_name=$env{'form.scantron_CODElist'};
                   7215:     }
                   7216:     if (!$cdom) {
                   7217: 	$cdom =$env{'course.'.$env{'request.course.id'}.'.domain'};
                   7218:     }
                   7219:     if (!$cnum) {
                   7220: 	$cnum =$env{'course.'.$env{'request.course.id'}.'.num'};
                   7221:     }
1.278     albertel 7222:     my %result=&Apache::lonnet::get('CODEs',[$old_name,"type\0$old_name"],
                   7223: 				    $cdom,$cnum);
                   7224:     my %allcodes;
                   7225:     if ($result{"type\0$old_name"} eq 'number') {
                   7226: 	%allcodes=map {($_,1)} split(',',$result{$old_name});
                   7227:     } else {
                   7228: 	%allcodes=map {(&Apache::lonprintout::num_to_letters($_),1)} split(',',$result{$old_name});
                   7229:     }
1.194     albertel 7230:     return %allcodes;
                   7231: }
                   7232: 
1.423     albertel 7233: =pod
                   7234: 
                   7235: =item scantron_validate_CODE
                   7236: 
1.424     albertel 7237:    Validates all scanlines in the selected file to not have any
                   7238:    invalid or underspecified CODEs and that none of the codes are
                   7239:    duplicated if this was requested.
                   7240: 
1.423     albertel 7241: =cut
                   7242: 
1.157     albertel 7243: sub scantron_validate_CODE {
                   7244:     my ($r,$currentphase) = @_;
1.257     albertel 7245:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.186     albertel 7246:     if ($scantron_config{'CODElocation'} &&
                   7247: 	$scantron_config{'CODEstart'} &&
                   7248: 	$scantron_config{'CODElength'}) {
1.257     albertel 7249: 	if (!defined($env{'form.scantron_CODElist'})) {
1.186     albertel 7250: 	    &FIXME_blow_up()
                   7251: 	}
                   7252:     } else {
                   7253: 	return (0,$currentphase+1);
                   7254:     }
                   7255:     
                   7256:     my %usedCODEs;
                   7257: 
1.194     albertel 7258:     my %allcodes=&get_codes();
1.186     albertel 7259: 
1.582     raeburn  7260:     my $nav_error;
                   7261:     &scantron_get_maxbubble(\$nav_error); # parse needs the lines per response array.
                   7262:     if ($nav_error) {
                   7263:         $r->print(&navmap_errormsg());
                   7264:         return(1,$currentphase);
                   7265:     }
1.447     foxr     7266: 
1.186     albertel 7267:     my ($scanlines,$scan_data)=&scantron_getfile();
                   7268:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
1.200     albertel 7269: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.186     albertel 7270: 	if ($line=~/^[\s\cz]*$/) { next; }
                   7271: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
                   7272: 						 $scan_data);
                   7273: 	my $CODE=$$scan_record{'scantron.CODE'};
                   7274: 	my $error=0;
1.224     albertel 7275: 	if (!&Apache::lonnet::validCODE($CODE)) {
                   7276: 	    &scantron_get_correction($r,$i,$scan_record,
                   7277: 				     \%scantron_config,
                   7278: 				     $line,'incorrectCODE',\%allcodes);
                   7279: 	    return(1,$currentphase);
                   7280: 	}
1.221     albertel 7281: 	if (%allcodes && !exists($allcodes{$CODE}) 
                   7282: 	    && !$$scan_record{'scantron.useCODE'}) {
1.186     albertel 7283: 	    &scantron_get_correction($r,$i,$scan_record,
                   7284: 				     \%scantron_config,
1.194     albertel 7285: 				     $line,'incorrectCODE',\%allcodes);
                   7286: 	    return(1,$currentphase);
1.186     albertel 7287: 	}
1.214     albertel 7288: 	if (exists($usedCODEs{$CODE}) 
1.257     albertel 7289: 	    && $env{'form.scantron_CODEunique'} eq 'yes'
1.192     albertel 7290: 	    && !$$scan_record{'scantron.CODE_ignore_dup'}) {
1.186     albertel 7291: 	    &scantron_get_correction($r,$i,$scan_record,
                   7292: 				     \%scantron_config,
1.194     albertel 7293: 				     $line,'duplicateCODE',$usedCODEs{$CODE});
                   7294: 	    return(1,$currentphase);
1.186     albertel 7295: 	}
1.524     raeburn  7296: 	push(@{$usedCODEs{$CODE}},$$scan_record{'scantron.PaperID'});
1.186     albertel 7297:     }
1.157     albertel 7298:     return (0,$currentphase+1);
                   7299: }
                   7300: 
1.423     albertel 7301: =pod
                   7302: 
                   7303: =item scantron_validate_doublebubble
                   7304: 
1.424     albertel 7305:    Validates all scanlines in the selected file to not have any
                   7306:    bubble lines with multiple bubbles marked.
                   7307: 
1.423     albertel 7308: =cut
                   7309: 
1.157     albertel 7310: sub scantron_validate_doublebubble {
                   7311:     my ($r,$currentphase) = @_;
                   7312:     #get student info
                   7313:     my $classlist=&Apache::loncoursedata::get_classlist();
                   7314:     my %idmap=&username_to_idmap($classlist);
                   7315: 
                   7316:     #get scantron line setup
1.257     albertel 7317:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.157     albertel 7318:     my ($scanlines,$scan_data)=&scantron_getfile();
1.583     raeburn  7319:     my $nav_error;
                   7320:     &scantron_get_maxbubble(\$nav_error); # parse needs the bubble line array.
                   7321:     if ($nav_error) {
                   7322:         $r->print(&navmap_errormsg());
                   7323:         return(1,$currentphase);
                   7324:     }
1.447     foxr     7325: 
1.157     albertel 7326:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
1.200     albertel 7327: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.157     albertel 7328: 	if ($line=~/^[\s\cz]*$/) { next; }
                   7329: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
                   7330: 						 $scan_data);
                   7331: 	if (!defined($$scan_record{'scantron.doubleerror'})) { next; }
                   7332: 	&scantron_get_correction($r,$i,$scan_record,\%scantron_config,$line,
                   7333: 				 'doublebubble',
                   7334: 				 $$scan_record{'scantron.doubleerror'});
                   7335:     	return (1,$currentphase);
                   7336:     }
                   7337:     return (0,$currentphase+1);
                   7338: }
                   7339: 
1.423     albertel 7340: 
1.503     raeburn  7341: sub scantron_get_maxbubble {
1.582     raeburn  7342:     my ($nav_error) = @_;
1.257     albertel 7343:     if (defined($env{'form.scantron_maxbubble'}) &&
                   7344: 	$env{'form.scantron_maxbubble'}) {
1.447     foxr     7345: 	&restore_bubble_lines();
1.257     albertel 7346: 	return $env{'form.scantron_maxbubble'};
1.191     albertel 7347:     }
1.330     albertel 7348: 
1.447     foxr     7349:     my (undef, undef, $sequence) =
1.257     albertel 7350: 	&Apache::lonnet::decode_symb($env{'form.selectpage'});
1.330     albertel 7351: 
1.447     foxr     7352:     my $navmap=Apache::lonnavmaps::navmap->new();
1.582     raeburn  7353:     unless (ref($navmap)) {
                   7354:         if (ref($nav_error)) {
                   7355:             $$nav_error = 1;
                   7356:         }
1.591     raeburn  7357:         return;
1.582     raeburn  7358:     }
1.191     albertel 7359:     my $map=$navmap->getResourceByUrl($sequence);
                   7360:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
1.330     albertel 7361: 
                   7362:     &Apache::lonxml::clear_problem_counter();
                   7363: 
1.557     raeburn  7364:     my $uname       = $env{'user.name'};
                   7365:     my $udom        = $env{'user.domain'};
1.435     foxr     7366:     my $cid         = $env{'request.course.id'};
                   7367:     my $total_lines = 0;
                   7368:     %bubble_lines_per_response = ();
1.447     foxr     7369:     %first_bubble_line         = ();
1.503     raeburn  7370:     %subdivided_bubble_lines   = ();
                   7371:     %responsetype_per_response = ();
1.554     raeburn  7372: 
1.447     foxr     7373:     my $response_number = 0;
                   7374:     my $bubble_line     = 0;
1.191     albertel 7375:     foreach my $resource (@resources) {
1.542     raeburn  7376:         my ($analysis,$parts) = &scantron_partids_tograde($resource,$cid,$uname,$udom);
                   7377:         if ((ref($analysis) eq 'HASH') && (ref($parts) eq 'ARRAY')) {
                   7378: 	    foreach my $part_id (@{$parts}) {
                   7379:                 my $lines;
                   7380: 
                   7381: 	        # TODO - make this a persistent hash not an array.
                   7382: 
                   7383:                 # optionresponse, matchresponse and rankresponse type items 
                   7384:                 # render as separate sub-questions in exam mode.
                   7385:                 if (($analysis->{$part_id.'.type'} eq 'optionresponse') ||
                   7386:                     ($analysis->{$part_id.'.type'} eq 'matchresponse') ||
                   7387:                     ($analysis->{$part_id.'.type'} eq 'rankresponse')) {
                   7388:                     my ($numbub,$numshown);
                   7389:                     if ($analysis->{$part_id.'.type'} eq 'optionresponse') {
                   7390:                         if (ref($analysis->{$part_id.'.options'}) eq 'ARRAY') {
                   7391:                             $numbub = scalar(@{$analysis->{$part_id.'.options'}});
                   7392:                         }
                   7393:                     } elsif ($analysis->{$part_id.'.type'} eq 'matchresponse') {
                   7394:                         if (ref($analysis->{$part_id.'.items'}) eq 'ARRAY') {
                   7395:                             $numbub = scalar(@{$analysis->{$part_id.'.items'}});
                   7396:                         }
                   7397:                     } elsif ($analysis->{$part_id.'.type'} eq 'rankresponse') {
                   7398:                         if (ref($analysis->{$part_id.'.foils'}) eq 'ARRAY') {
                   7399:                             $numbub = scalar(@{$analysis->{$part_id.'.foils'}});
                   7400:                         }
                   7401:                     }
                   7402:                     if (ref($analysis->{$part_id.'.shown'}) eq 'ARRAY') {
                   7403:                         $numshown = scalar(@{$analysis->{$part_id.'.shown'}});
                   7404:                     }
                   7405:                     my $bubbles_per_line = 10;
                   7406:                     my $inner_bubble_lines = int($numbub/$bubbles_per_line);
                   7407:                     if (($numbub % $bubbles_per_line) != 0) {
                   7408:                         $inner_bubble_lines++;
                   7409:                     }
                   7410:                     for (my $i=0; $i<$numshown; $i++) {
                   7411:                         $subdivided_bubble_lines{$response_number} .= 
                   7412:                             $inner_bubble_lines.',';
                   7413:                     }
                   7414:                     $subdivided_bubble_lines{$response_number} =~ s/,$//;
                   7415:                     $lines = $numshown * $inner_bubble_lines;
                   7416:                 } else {
                   7417:                     $lines = $analysis->{"$part_id.bubble_lines"};
                   7418:                 } 
                   7419: 
                   7420:                 $first_bubble_line{$response_number} = $bubble_line;
                   7421: 	        $bubble_lines_per_response{$response_number} = $lines;
                   7422:                 $responsetype_per_response{$response_number} = 
                   7423:                     $analysis->{$part_id.'.type'};
                   7424: 	        $response_number++;
                   7425: 
                   7426: 	        $bubble_line +=  $lines;
                   7427: 	        $total_lines +=  $lines;
                   7428: 	    }
                   7429:         }
                   7430:     }
1.552     raeburn  7431:     &Apache::lonnet::delenv('scantron.');
1.542     raeburn  7432: 
                   7433:     &save_bubble_lines();
                   7434:     $env{'form.scantron_maxbubble'} =
                   7435: 	$total_lines;
                   7436:     return $env{'form.scantron_maxbubble'};
                   7437: }
1.523     raeburn  7438: 
1.157     albertel 7439: sub scantron_validate_missingbubbles {
                   7440:     my ($r,$currentphase) = @_;
                   7441:     #get student info
                   7442:     my $classlist=&Apache::loncoursedata::get_classlist();
                   7443:     my %idmap=&username_to_idmap($classlist);
                   7444: 
                   7445:     #get scantron line setup
1.257     albertel 7446:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.157     albertel 7447:     my ($scanlines,$scan_data)=&scantron_getfile();
1.582     raeburn  7448:     my $nav_error;
                   7449:     my $max_bubble=&scantron_get_maxbubble(\$nav_error);
                   7450:     if ($nav_error) {
                   7451:         return(1,$currentphase);
                   7452:     }
1.157     albertel 7453:     if (!$max_bubble) { $max_bubble=2**31; }
                   7454:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
1.200     albertel 7455: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.157     albertel 7456: 	if ($line=~/^[\s\cz]*$/) { next; }
                   7457: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
                   7458: 						 $scan_data);
                   7459: 	if (!defined($$scan_record{'scantron.missingerror'})) { next; }
                   7460: 	my @to_correct;
1.470     foxr     7461: 	
                   7462: 	# Probably here's where the error is...
                   7463: 
1.157     albertel 7464: 	foreach my $missing (@{$$scan_record{'scantron.missingerror'}}) {
1.505     raeburn  7465:             my $lastbubble;
                   7466:             if ($missing =~ /^(\d+)\.(\d+)$/) {
                   7467:                my $question = $1;
                   7468:                my $subquestion = $2;
                   7469:                if (!defined($first_bubble_line{$question -1})) { next; }
                   7470:                my $first = $first_bubble_line{$question-1};
                   7471:                my @subans = split(/,/,$subdivided_bubble_lines{$question-1});
                   7472:                my $subcount = 1;
                   7473:                while ($subcount<$subquestion) {
                   7474:                    $first += $subans[$subcount-1];
                   7475:                    $subcount ++;
                   7476:                }
                   7477:                my $count = $subans[$subquestion-1];
                   7478:                $lastbubble = $first + $count;
                   7479:             } else {
                   7480:                 if (!defined($first_bubble_line{$missing - 1})) { next; }
                   7481:                 $lastbubble = $first_bubble_line{$missing - 1} + $bubble_lines_per_response{$missing - 1};
                   7482:             }
                   7483:             if ($lastbubble > $max_bubble) { next; }
1.157     albertel 7484: 	    push(@to_correct,$missing);
                   7485: 	}
                   7486: 	if (@to_correct) {
                   7487: 	    &scantron_get_correction($r,$i,$scan_record,\%scantron_config,
                   7488: 				     $line,'missingbubble',\@to_correct);
                   7489: 	    return (1,$currentphase);
                   7490: 	}
                   7491: 
                   7492:     }
                   7493:     return (0,$currentphase+1);
                   7494: }
                   7495: 
1.423     albertel 7496: 
1.82      albertel 7497: sub scantron_process_students {
1.608     www      7498:     my ($r,$symb) = @_;
1.513     foxr     7499: 
1.257     albertel 7500:     my (undef,undef,$sequence)=&Apache::lonnet::decode_symb($env{'form.selectpage'});
1.513     foxr     7501:     if (!$symb) {
                   7502: 	return '';
                   7503:     }
1.324     albertel 7504:     my $default_form_data=&defaultFormData($symb);
1.82      albertel 7505: 
1.257     albertel 7506:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.157     albertel 7507:     my ($scanlines,$scan_data)=&scantron_getfile();
1.82      albertel 7508:     my $classlist=&Apache::loncoursedata::get_classlist();
                   7509:     my %idmap=&username_to_idmap($classlist);
1.132     bowersj2 7510:     my $navmap=Apache::lonnavmaps::navmap->new();
1.582     raeburn  7511:     unless (ref($navmap)) {
                   7512:         $r->print(&navmap_errormsg());
                   7513:         return '';
                   7514:     }  
1.83      albertel 7515:     my $map=$navmap->getResourceByUrl($sequence);
                   7516:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
1.557     raeburn  7517:     my (%grader_partids_by_symb,%grader_randomlists_by_symb);
                   7518:     &graders_resources_pass(\@resources,\%grader_partids_by_symb,
                   7519:                             \%grader_randomlists_by_symb);
1.586     raeburn  7520:     my $resource_error;
1.557     raeburn  7521:     foreach my $resource (@resources) {
1.586     raeburn  7522:         my $ressymb;
                   7523:         if (ref($resource)) {
                   7524:             $ressymb = $resource->symb();
                   7525:         } else {
                   7526:             $resource_error = 1;
                   7527:             last;
                   7528:         }
1.557     raeburn  7529:         my ($analysis,$parts) =
                   7530:             &scantron_partids_tograde($resource,$env{'request.course.id'},
                   7531:                                       $env{'user.name'},$env{'user.domain'},1);
                   7532:         $grader_partids_by_symb{$ressymb} = $parts;
                   7533:         if (ref($analysis) eq 'HASH') {
                   7534:             if (ref($analysis->{'parts_withrandomlist'}) eq 'ARRAY') {
                   7535:                 $grader_randomlists_by_symb{$ressymb} = 
                   7536:                     $analysis->{'parts_withrandomlist'};
                   7537:             }
                   7538:         }
                   7539:     }
1.586     raeburn  7540:     if ($resource_error) {
                   7541:         $r->print(&navmap_errormsg());
                   7542:         return '';
                   7543:     }
1.557     raeburn  7544: 
1.554     raeburn  7545:     my ($uname,$udom);
1.82      albertel 7546:     my $result= <<SCANTRONFORM;
1.81      albertel 7547: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantronupload">
                   7548:   <input type="hidden" name="command" value="scantron_configphase" />
                   7549:   $default_form_data
                   7550: SCANTRONFORM
1.82      albertel 7551:     $r->print($result);
                   7552: 
                   7553:     my @delayqueue;
1.542     raeburn  7554:     my (%completedstudents,%scandata);
1.140     albertel 7555:     
1.520     www      7556:     my $lock=&Apache::lonnet::set_lock(&mt('Grading bubblesheet exam'));
1.200     albertel 7557:     my $count=&get_todo_count($scanlines,$scan_data);
1.575     www      7558:     my %prog_state=&Apache::lonhtmlcommon::Create_PrgWin($r,'Bubblesheet Status',
                   7559:  				    'Bubblesheet Progress',$count,
1.195     albertel 7560: 				    'inline',undef,'scantronupload');
1.140     albertel 7561:     &Apache::lonhtmlcommon::Update_PrgWin($r,\%prog_state,
                   7562: 					  'Processing first student');
1.542     raeburn  7563:     $r->print('<br />');
1.140     albertel 7564:     my $start=&Time::HiRes::time();
1.158     albertel 7565:     my $i=-1;
1.542     raeburn  7566:     my $started;
1.447     foxr     7567: 
1.582     raeburn  7568:     my $nav_error;
                   7569:     &scantron_get_maxbubble(\$nav_error); # Need the bubble lines array to parse.
                   7570:     if ($nav_error) {
                   7571:         $r->print(&navmap_errormsg());
                   7572:         return '';
                   7573:     }
                   7574: 
1.513     foxr     7575:     # If an ssi failed in scantron_get_maxbubble, put an error message out to
                   7576:     # the user and return.
                   7577: 
                   7578:     if ($ssi_error) {
                   7579: 	$r->print("</form>");
                   7580: 	&ssi_print_error($r);
1.520     www      7581:         &Apache::lonnet::remove_lock($lock);
1.513     foxr     7582: 	return '';		# Dunno why the other returns return '' rather than just returning.
                   7583:     }
1.447     foxr     7584: 
1.542     raeburn  7585:     my %lettdig = &letter_to_digits();
                   7586:     my $numletts = scalar(keys(%lettdig));
                   7587: 
1.157     albertel 7588:     while ($i<$scanlines->{'count'}) {
                   7589:  	($uname,$udom)=('','');
                   7590:  	$i++;
1.200     albertel 7591:  	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.157     albertel 7592:  	if ($line=~/^[\s\cz]*$/) { next; }
1.200     albertel 7593: 	if ($started) {
                   7594: 	    &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state,
                   7595: 						     'last student');
                   7596: 	}
                   7597: 	$started=1;
1.157     albertel 7598:  	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
                   7599:  						 $scan_data);
                   7600:  	unless ($uname=&scantron_find_student($scan_record,$scan_data,
                   7601:  					      \%idmap,$i)) {
                   7602:   	    &scantron_add_delay(\@delayqueue,$line,
                   7603:  				'Unable to find a student that matches',1);
                   7604:  	    next;
                   7605:   	}
                   7606:  	if (exists $completedstudents{$uname}) {
                   7607:  	    &scantron_add_delay(\@delayqueue,$line,
                   7608:  				'Student '.$uname.' has multiple sheets',2);
                   7609:  	    next;
                   7610:  	}
                   7611:   	($uname,$udom)=split(/:/,$uname);
1.330     albertel 7612: 
1.586     raeburn  7613:         my (%partids_by_symb,$res_error);
1.554     raeburn  7614:         foreach my $resource (@resources) {
1.586     raeburn  7615:             my $ressymb;
                   7616:             if (ref($resource)) {
                   7617:                 $ressymb = $resource->symb();
                   7618:             } else {
                   7619:                 $res_error = 1;
                   7620:                 last;
                   7621:             }
1.557     raeburn  7622:             if ((exists($grader_randomlists_by_symb{$ressymb})) ||
                   7623:                 (ref($grader_partids_by_symb{$ressymb}) ne 'ARRAY')) {
                   7624:                 my ($analysis,$parts) =
                   7625:                     &scantron_partids_tograde($resource,$env{'request.course.id'},$uname,$udom);
                   7626:                 $partids_by_symb{$ressymb} = $parts;
                   7627:             } else {
                   7628:                 $partids_by_symb{$ressymb} = $grader_partids_by_symb{$ressymb};
                   7629:             }
1.554     raeburn  7630:         }
                   7631: 
1.586     raeburn  7632:         if ($res_error) {
                   7633:             &scantron_add_delay(\@delayqueue,$line,
                   7634:                                 'An error occurred while grading student '.$uname,2);
                   7635:             next;
                   7636:         }
                   7637: 
1.330     albertel 7638: 	&Apache::lonxml::clear_problem_counter();
1.514     raeburn  7639:   	&Apache::lonnet::appenv($scan_record);
1.376     albertel 7640: 
                   7641: 	if (&scantron_clear_skip($scanlines,$scan_data,$i)) {
                   7642: 	    &scantron_putfile($scanlines,$scan_data);
                   7643: 	}
1.161     albertel 7644: 	
1.542     raeburn  7645:         my $scancode;
                   7646:         if ((exists($scan_record->{'scantron.CODE'})) &&
                   7647:             (&Apache::lonnet::validCODE($scan_record->{'scantron.CODE'}))) {
                   7648:             $scancode = $scan_record->{'scantron.CODE'};
                   7649:         } else {
                   7650:             $scancode = '';
                   7651:         }
                   7652: 
                   7653:         if (&grade_student_bubbles($r,$uname,$udom,$scan_record,$scancode,
1.554     raeburn  7654:                                    \@resources,\%partids_by_symb) eq 'ssi_error') {
1.542     raeburn  7655:             $ssi_error = 0; # So end of handler error message does not trigger.
                   7656:             $r->print("</form>");
                   7657:             &ssi_print_error($r);
                   7658:             &Apache::lonnet::remove_lock($lock);
                   7659:             return '';      # Why return ''?  Beats me.
                   7660:         }
1.513     foxr     7661: 
1.140     albertel 7662: 	$completedstudents{$uname}={'line'=>$line};
1.542     raeburn  7663:         if ($env{'form.verifyrecord'}) {
                   7664:             my $lastpos = $env{'form.scantron_maxbubble'}*$scantron_config{'Qlength'};
                   7665:             my $studentdata = substr($line,$scantron_config{'Qstart'}-1,$lastpos);
                   7666:             chomp($studentdata);
                   7667:             $studentdata =~ s/\r$//;
                   7668:             my $studentrecord = '';
                   7669:             my $counter = -1;
                   7670:             foreach my $resource (@resources) {
1.554     raeburn  7671:                 my $ressymb = $resource->symb();
1.542     raeburn  7672:                 ($counter,my $recording) =
                   7673:                     &verify_scantron_grading($resource,$udom,$uname,$env{'request.course.id'},
1.554     raeburn  7674:                                              $counter,$studentdata,$partids_by_symb{$ressymb},
1.542     raeburn  7675:                                              \%scantron_config,\%lettdig,$numletts);
                   7676:                 $studentrecord .= $recording;
                   7677:             }
                   7678:             if ($studentrecord ne $studentdata) {
1.554     raeburn  7679:                 &Apache::lonxml::clear_problem_counter();
                   7680:                 if (&grade_student_bubbles($r,$uname,$udom,$scan_record,$scancode,
                   7681:                                            \@resources,\%partids_by_symb) eq 'ssi_error') {
                   7682:                     $ssi_error = 0; # So end of handler error message does not trigger.
                   7683:                     $r->print("</form>");
                   7684:                     &ssi_print_error($r);
                   7685:                     &Apache::lonnet::remove_lock($lock);
                   7686:                     delete($completedstudents{$uname});
                   7687:                     return '';
                   7688:                 }
1.542     raeburn  7689:                 $counter = -1;
                   7690:                 $studentrecord = '';
                   7691:                 foreach my $resource (@resources) {
1.554     raeburn  7692:                     my $ressymb = $resource->symb();
1.542     raeburn  7693:                     ($counter,my $recording) =
                   7694:                         &verify_scantron_grading($resource,$udom,$uname,$env{'request.course.id'},
1.554     raeburn  7695:                                                  $counter,$studentdata,$partids_by_symb{$ressymb},
1.542     raeburn  7696:                                                  \%scantron_config,\%lettdig,$numletts);
                   7697:                     $studentrecord .= $recording;
                   7698:                 }
                   7699:                 if ($studentrecord ne $studentdata) {
                   7700:                     $r->print('<p><span class="LC_error">');
                   7701:                     if ($scancode eq '') {
                   7702:                         $r->print(&mt('Mismatch grading bubble sheet for user: [_1] with ID: [_2].',
                   7703:                                   $uname.':'.$udom,$scan_record->{'scantron.ID'}));
                   7704:                     } else {
                   7705:                         $r->print(&mt('Mismatch grading bubble sheet for user: [_1] with ID: [_2] and CODE: [_3].',
                   7706:                                   $uname.':'.$udom,$scan_record->{'scantron.ID'},$scancode));
                   7707:                     }
                   7708:                     $r->print('</span><br />'.&Apache::loncommon::start_data_table()."\n".
                   7709:                               &Apache::loncommon::start_data_table_header_row()."\n".
                   7710:                               '<th>'.&mt('Source').'</th><th>'.&mt('Bubbled responses').'</th>'.
                   7711:                               &Apache::loncommon::end_data_table_header_row()."\n".
                   7712:                               &Apache::loncommon::start_data_table_row().
                   7713:                               '<td>'.&mt('Bubble Sheet').'</td>'.
                   7714:                               '<td><span class="LC_nobreak">'.$studentdata.'</span></td>'.
                   7715:                               &Apache::loncommon::end_data_table_row().
                   7716:                               &Apache::loncommon::start_data_table_row().
                   7717:                               '<td>Stored submissions</td>'.
                   7718:                               '<td><span class="LC_nobreak">'.$studentrecord.'</span></td>'."\n".
                   7719:                               &Apache::loncommon::end_data_table_row().
                   7720:                               &Apache::loncommon::end_data_table().'</p>');
                   7721:                 } else {
                   7722:                     $r->print('<br /><span class="LC_warning">'.
                   7723:                              &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 />'.
                   7724:                              &mt("As a consequence, this user's submission history records two tries.").
                   7725:                                  '</span><br />');
                   7726:                 }
                   7727:             }
                   7728:         }
1.543     raeburn  7729:         if (&Apache::loncommon::connection_aborted($r)) { last; }
1.140     albertel 7730:     } continue {
1.330     albertel 7731: 	&Apache::lonxml::clear_problem_counter();
1.552     raeburn  7732: 	&Apache::lonnet::delenv('scantron.');
1.82      albertel 7733:     }
1.140     albertel 7734:     &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
1.520     www      7735:     &Apache::lonnet::remove_lock($lock);
1.172     albertel 7736: #    my $lasttime = &Time::HiRes::time()-$start;
                   7737: #    $r->print("<p>took $lasttime</p>");
1.140     albertel 7738: 
1.200     albertel 7739:     $r->print("</form>");
1.157     albertel 7740:     return '';
1.75      albertel 7741: }
1.157     albertel 7742: 
1.557     raeburn  7743: sub graders_resources_pass {
                   7744:     my ($resources,$grader_partids_by_symb,$grader_randomlists_by_symb) = @_;
                   7745:     if ((ref($resources) eq 'ARRAY') && (ref($grader_partids_by_symb)) && 
                   7746:         (ref($grader_randomlists_by_symb) eq 'HASH')) {
                   7747:         foreach my $resource (@{$resources}) {
                   7748:             my $ressymb = $resource->symb();
                   7749:             my ($analysis,$parts) =
                   7750:                 &scantron_partids_tograde($resource,$env{'request.course.id'},
                   7751:                                           $env{'user.name'},$env{'user.domain'},1);
                   7752:             $grader_partids_by_symb->{$ressymb} = $parts;
                   7753:             if (ref($analysis) eq 'HASH') {
                   7754:                 if (ref($analysis->{'parts_withrandomlist'}) eq 'ARRAY') {
                   7755:                     $grader_randomlists_by_symb->{$ressymb} =
                   7756:                         $analysis->{'parts_withrandomlist'};
                   7757:                 }
                   7758:             }
                   7759:         }
                   7760:     }
                   7761:     return;
                   7762: }
                   7763: 
1.542     raeburn  7764: sub grade_student_bubbles {
1.554     raeburn  7765:     my ($r,$uname,$udom,$scan_record,$scancode,$resources,$parts) = @_;
                   7766:     if (ref($resources) eq 'ARRAY') {
                   7767:         my $count = 0;
                   7768:         foreach my $resource (@{$resources}) {
                   7769:             my $ressymb = $resource->symb();
                   7770:             my %form = ('submitted'      => 'scantron',
                   7771:                         'grade_target'   => 'grade',
                   7772:                         'grade_username' => $uname,
                   7773:                         'grade_domain'   => $udom,
                   7774:                         'grade_courseid' => $env{'request.course.id'},
                   7775:                         'grade_symb'     => $ressymb,
                   7776:                         'CODE'           => $scancode
                   7777:                        );
                   7778:             if (ref($parts) eq 'HASH') {
                   7779:                 if (ref($parts->{$ressymb}) eq 'ARRAY') {
                   7780:                     foreach my $part (@{$parts->{$ressymb}}) {
                   7781:                         $form{'scantron_questnum_start.'.$part} =
                   7782:                             1+$env{'form.scantron.first_bubble_line.'.$count};
                   7783:                         $count++;
                   7784:                     }
                   7785:                 }
                   7786:             }
                   7787:             my $result=&ssi_with_retries($resource->src(),$ssi_retries,%form);
                   7788:             return 'ssi_error' if ($ssi_error);
                   7789:             last if (&Apache::loncommon::connection_aborted($r));
                   7790:         }
1.542     raeburn  7791:     }
                   7792:     return;
                   7793: }
                   7794: 
1.157     albertel 7795: sub scantron_upload_scantron_data {
1.608     www      7796:     my ($r,$symb)=@_;
1.565     raeburn  7797:     my $dom = $env{'request.role.domain'};
                   7798:     my $domdesc = &Apache::lonnet::domain($dom,'description');
                   7799:     $r->print(&Apache::loncommon::coursebrowser_javascript($dom));
1.157     albertel 7800:     my $select_link=&Apache::loncommon::selectcourse_link('rules','courseid',
1.181     albertel 7801: 							  'domainid',
1.565     raeburn  7802: 							  'coursename',$dom);
                   7803:     my $syllabuslink = '<a href="javascript:ToSyllabus();">'.&mt('Syllabus').'</a>'.
                   7804:                        ('&nbsp'x2).&mt('(shows course personnel)'); 
1.608     www      7805:     my $default_form_data=&defaultFormData($symb);
1.579     raeburn  7806:     my $nofile_alert = &mt('Please use the browse button to select a file from your local directory.');
                   7807:     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 7808:     $r->print(&Apache::lonhtmlcommon::scripttag('
1.157     albertel 7809:     function checkUpload(formname) {
                   7810: 	if (formname.upfile.value == "") {
1.579     raeburn  7811: 	    alert("'.$nofile_alert.'");
1.157     albertel 7812: 	    return false;
                   7813: 	}
1.565     raeburn  7814:         if (formname.courseid.value == "") {
1.579     raeburn  7815:             alert("'.$nocourseid_alert.'");
1.565     raeburn  7816:             return false;
                   7817:         }
1.157     albertel 7818: 	formname.submit();
                   7819:     }
1.565     raeburn  7820: 
                   7821:     function ToSyllabus() {
                   7822:         var cdom = '."'$dom'".';
                   7823:         var cnum = document.rules.courseid.value;
                   7824:         if (cdom == "" || cdom == null) {
                   7825:             return;
                   7826:         }
                   7827:         if (cnum == "" || cnum == null) {
                   7828:            return;
                   7829:         }
                   7830:         syllwin=window.open("/public/"+cdom+"/"+cnum+"/syllabus","LONCAPASyllabus",
                   7831:                             "height=350,width=350,scrollbars=yes,menubar=no");
                   7832:         return;
                   7833:     }
                   7834: 
1.597     wenzelju 7835: '));
                   7836:     $r->print('
1.566     raeburn  7837: <h3>'.&mt('Send scanned bubblesheet data to a course').'</h3>
                   7838: 
1.492     albertel 7839: <form enctype="multipart/form-data" action="/adm/grades" name="rules" method="post">
1.565     raeburn  7840: '.$default_form_data.
                   7841:   &Apache::lonhtmlcommon::start_pick_box().
                   7842:   &Apache::lonhtmlcommon::row_title(&mt('Course ID')).
                   7843:   '<input name="courseid" type="text" size="30" />'.$select_link.
                   7844:   &Apache::lonhtmlcommon::row_closure().
                   7845:   &Apache::lonhtmlcommon::row_title(&mt('Course Name')).
                   7846:   '<input name="coursename" type="text" size="30" />'.$syllabuslink.
                   7847:   &Apache::lonhtmlcommon::row_closure().
                   7848:   &Apache::lonhtmlcommon::row_title(&mt('Domain')).
                   7849:   '<input name="domainid" type="hidden" />'.$domdesc.
                   7850:   &Apache::lonhtmlcommon::row_closure().
                   7851:   &Apache::lonhtmlcommon::row_title(&mt('File to upload')).
                   7852:   '<input type="file" name="upfile" size="50" />'.
                   7853:   &Apache::lonhtmlcommon::row_closure(1).
                   7854:   &Apache::lonhtmlcommon::end_pick_box().'<br />
                   7855: 
1.492     albertel 7856: <input name="command" value="scantronupload_save" type="hidden" />
1.589     bisitz   7857: <input type="button" onclick="javascript:checkUpload(this.form);" value="'.&mt('Upload Bubblesheet Data').'" />
1.157     albertel 7858: </form>
1.492     albertel 7859: ');
1.157     albertel 7860:     return '';
                   7861: }
                   7862: 
1.423     albertel 7863: 
1.157     albertel 7864: sub scantron_upload_scantron_data_save {
1.608     www      7865:     my($r,$symb)=@_;
1.182     albertel 7866:     my $doanotherupload=
                   7867: 	'<br /><form action="/adm/grades" method="post">'."\n".
                   7868: 	'<input type="hidden" name="command" value="scantronupload" />'."\n".
1.492     albertel 7869: 	'<input type="submit" name="submit" value="'.&mt('Do Another Upload').'" />'."\n".
1.182     albertel 7870: 	'</form>'."\n";
1.257     albertel 7871:     if (!&Apache::lonnet::allowed('usc',$env{'form.domainid'}) &&
1.162     albertel 7872: 	!&Apache::lonnet::allowed('usc',
1.257     albertel 7873: 			    $env{'form.domainid'}.'_'.$env{'form.courseid'})) {
1.575     www      7874: 	$r->print(&mt("You are not allowed to upload bubblesheet data to the requested course.")."<br />");
1.614     www      7875: 	unless ($symb) {
1.182     albertel 7876: 	    $r->print($doanotherupload);
                   7877: 	}
1.162     albertel 7878: 	return '';
                   7879:     }
1.257     albertel 7880:     my %coursedata=&Apache::lonnet::coursedescription($env{'form.domainid'}.'_'.$env{'form.courseid'});
1.568     raeburn  7881:     my $uploadedfile;
1.567     raeburn  7882:     $r->print('<h3>'.&mt("Uploading file to [_1]",$coursedata{'description'}).'</h3>');
1.257     albertel 7883:     if (length($env{'form.upfile'}) < 2) {
1.568     raeburn  7884:         $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 7885:     } else {
1.568     raeburn  7886:         my $result = 
                   7887:             &Apache::lonnet::userfileupload('upfile','','scantron','','','',
                   7888:                                             $env{'form.courseid'},$env{'form.domainid'});
                   7889: 	if ($result =~ m{^/uploaded/}) {
1.567     raeburn  7890: 	    $r->print(&mt('[_1]Success:[_2] Successfully uploaded [_3] bytes of data into location: [_4]',
                   7891:                           '<span class="LC_success">','</span>',(length($env{'form.upfile'})-1),
                   7892: 			  '<span class="LC_filename">'.$result.'</span>'));
1.568     raeburn  7893:             ($uploadedfile) = ($result =~ m{/([^/]+)$});
1.567     raeburn  7894:             $r->print(&validate_uploaded_scantron_file($env{'form.domainid'},
1.568     raeburn  7895:                                                        $env{'form.courseid'},$uploadedfile));
1.210     albertel 7896: 	} else {
1.567     raeburn  7897: 	    $r->print(&mt('[_1]Error:[_2] An error ([_3]) occurred when attempting to upload the file, [_4]',
                   7898:                           '<span class="LC_error">','</span>',$result,
1.568     raeburn  7899: 			  '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>'));
1.183     albertel 7900: 	}
                   7901:     }
1.174     albertel 7902:     if ($symb) {
1.612     www      7903: 	$r->print(&scantron_selectphase($r,$uploadedfile,$symb));
1.174     albertel 7904:     } else {
1.182     albertel 7905: 	$r->print($doanotherupload);
1.174     albertel 7906:     }
1.157     albertel 7907:     return '';
                   7908: }
                   7909: 
1.567     raeburn  7910: sub validate_uploaded_scantron_file {
                   7911:     my ($cdom,$cname,$fname) = @_;
                   7912:     my $scanlines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.$fname);
                   7913:     my @lines;
                   7914:     if ($scanlines ne '-1') {
                   7915:         @lines=split("\n",$scanlines,-1);
                   7916:     }
                   7917:     my $output;
                   7918:     if (@lines) {
                   7919:         my (%counts,$max_match_format);
                   7920:         my ($max_match_count,$max_match_pct) = (0,0);
                   7921:         my $classlist = &Apache::loncoursedata::get_classlist($cdom,$cname);
                   7922:         my %idmap = &username_to_idmap($classlist);
                   7923:         foreach my $key (keys(%idmap)) {
                   7924:             my $lckey = lc($key);
                   7925:             $idmap{$lckey} = $idmap{$key};
                   7926:         }
                   7927:         my %unique_formats;
                   7928:         my @formatlines = &get_scantronformat_file();
                   7929:         foreach my $line (@formatlines) {
                   7930:             chomp($line);
                   7931:             my @config = split(/:/,$line);
                   7932:             my $idstart = $config[5];
                   7933:             my $idlength = $config[6];
                   7934:             if (($idstart ne '') && ($idlength > 0)) {
                   7935:                 if (ref($unique_formats{$idstart.':'.$idlength}) eq 'ARRAY') {
                   7936:                     push(@{$unique_formats{$idstart.':'.$idlength}},$config[0].':'.$config[1]); 
                   7937:                 } else {
                   7938:                     $unique_formats{$idstart.':'.$idlength} = [$config[0].':'.$config[1]];
                   7939:                 }
                   7940:             }
                   7941:         }
                   7942:         foreach my $key (keys(%unique_formats)) {
                   7943:             my ($idstart,$idlength) = split(':',$key);
                   7944:             %{$counts{$key}} = (
                   7945:                                'found'   => 0,
                   7946:                                'total'   => 0,
                   7947:                               );
                   7948:             foreach my $line (@lines) {
                   7949:                 next if ($line =~ /^#/);
                   7950:                 next if ($line =~ /^[\s\cz]*$/);
                   7951:                 my $id = substr($line,$idstart-1,$idlength);
                   7952:                 $id = lc($id);
                   7953:                 if (exists($idmap{$id})) {
                   7954:                     $counts{$key}{'found'} ++;
                   7955:                 }
                   7956:                 $counts{$key}{'total'} ++;
                   7957:             }
                   7958:             if ($counts{$key}{'total'}) {
                   7959:                 my $percent_match = (100*$counts{$key}{'found'})/($counts{$key}{'total'});
                   7960:                 if (($max_match_format eq '') || ($percent_match > $max_match_pct)) {
                   7961:                     $max_match_pct = $percent_match;
                   7962:                     $max_match_format = $key;
                   7963:                     $max_match_count = $counts{$key}{'total'};
                   7964:                 }
                   7965:             }
                   7966:         }
                   7967:         if (ref($unique_formats{$max_match_format}) eq 'ARRAY') {
                   7968:             my $format_descs;
                   7969:             my $numwithformat = @{$unique_formats{$max_match_format}};
                   7970:             for (my $i=0; $i<$numwithformat; $i++) {
                   7971:                 my ($name,$desc) = split(':',$unique_formats{$max_match_format}[$i]);
                   7972:                 if ($i<$numwithformat-2) {
                   7973:                     $format_descs .= '"<i>'.$desc.'</i>", ';
                   7974:                 } elsif ($i==$numwithformat-2) {
                   7975:                     $format_descs .= '"<i>'.$desc.'</i>" '.&mt('and').' ';
                   7976:                 } elsif ($i==$numwithformat-1) {
                   7977:                     $format_descs .= '"<i>'.$desc.'</i>"';
                   7978:                 }
                   7979:             }
                   7980:             my $showpct = sprintf("%.0f",$max_match_pct).'%';
                   7981:             $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).
                   7982:                        '<br />'.&mt('A low percentage of matches results from one of the following:').'<ul>'.
                   7983:                        '<li>'.&mt('The file was uploaded to the wrong course').'</li>'.
                   7984:                        '<li>'.&mt('The data are not in the format expected for the domain: [_1]',
                   7985:                                   '<i>'.$cdom.'</i>').'</li>'.
                   7986:                        '<li>'.&mt('Students did not bubble their IDs, or mis-bubbled them').'</li>'.
                   7987:                        '<li>'.&mt('The course roster is not up to date').'</li>'.
                   7988:                        '</ul>';
                   7989:         }
                   7990:     } else {
                   7991:         $output = '<span class="LC_warning">'.&mt('Uploaded file contained no data').'</span>';
                   7992:     }
                   7993:     return $output;
                   7994: }
                   7995: 
1.202     albertel 7996: sub valid_file {
                   7997:     my ($requested_file)=@_;
                   7998:     foreach my $filename (sort(&scantron_filenames())) {
                   7999: 	if ($requested_file eq $filename) { return 1; }
                   8000:     }
                   8001:     return 0;
                   8002: }
                   8003: 
                   8004: sub scantron_download_scantron_data {
1.608     www      8005:     my ($r,$symb)=@_;
                   8006:     my $default_form_data=&defaultFormData($symb);
1.257     albertel 8007:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   8008:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   8009:     my $file=$env{'form.scantron_selectfile'};
1.202     albertel 8010:     if (! &valid_file($file)) {
1.492     albertel 8011: 	$r->print('
1.202     albertel 8012: 	<p>
1.492     albertel 8013: 	    '.&mt('The requested file name was invalid.').'
1.202     albertel 8014:         </p>
1.492     albertel 8015: ');
1.202     albertel 8016: 	return;
                   8017:     }
                   8018:     my $orig='/uploaded/'.$cdom.'/'.$cname.'/scantron_orig_'.$file;
                   8019:     my $corrected='/uploaded/'.$cdom.'/'.$cname.'/scantron_corrected_'.$file;
                   8020:     my $skipped='/uploaded/'.$cdom.'/'.$cname.'/scantron_skipped_'.$file;
                   8021:     &Apache::lonnet::allowuploaded('/adm/grades',$orig);
                   8022:     &Apache::lonnet::allowuploaded('/adm/grades',$corrected);
                   8023:     &Apache::lonnet::allowuploaded('/adm/grades',$skipped);
1.492     albertel 8024:     $r->print('
1.202     albertel 8025:     <p>
1.492     albertel 8026: 	'.&mt('[_1]Original[_2] file as uploaded by the scantron office.',
                   8027: 	      '<a href="'.$orig.'">','</a>').'
1.202     albertel 8028:     </p>
                   8029:     <p>
1.492     albertel 8030: 	'.&mt('[_1]Corrections[_2], a file of corrected records that were used in grading.',
                   8031: 	      '<a href="'.$corrected.'">','</a>').'
1.202     albertel 8032:     </p>
                   8033:     <p>
1.492     albertel 8034: 	'.&mt('[_1]Skipped[_2], a file of records that were skipped.',
                   8035: 	      '<a href="'.$skipped.'">','</a>').'
1.202     albertel 8036:     </p>
1.492     albertel 8037: ');
1.202     albertel 8038:     return '';
                   8039: }
1.157     albertel 8040: 
1.523     raeburn  8041: sub checkscantron_results {
1.608     www      8042:     my ($r,$symb) = @_;
1.523     raeburn  8043:     if (!$symb) {return '';}
                   8044:     my $cid = $env{'request.course.id'};
1.542     raeburn  8045:     my %lettdig = &letter_to_digits();
1.523     raeburn  8046:     my $numletts = scalar(keys(%lettdig));
                   8047:     my $cnum = $env{'course.'.$cid.'.num'};
                   8048:     my $cdom = $env{'course.'.$cid.'.domain'};
                   8049:     my (undef, undef, $sequence) = &Apache::lonnet::decode_symb($env{'form.selectpage'});
                   8050:     my %record;
                   8051:     my %scantron_config =
                   8052:         &Apache::grades::get_scantron_config($env{'form.scantron_format'});
                   8053:     my ($scanlines,$scan_data)=&Apache::grades::scantron_getfile();
                   8054:     my $classlist=&Apache::loncoursedata::get_classlist();
                   8055:     my %idmap=&Apache::grades::username_to_idmap($classlist);
                   8056:     my $navmap=Apache::lonnavmaps::navmap->new();
1.582     raeburn  8057:     unless (ref($navmap)) {
                   8058:         $r->print(&navmap_errormsg());
                   8059:         return '';
                   8060:     }
1.523     raeburn  8061:     my $map=$navmap->getResourceByUrl($sequence);
1.557     raeburn  8062:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
                   8063:     my (%grader_partids_by_symb,%grader_randomlists_by_symb);
                   8064:     &graders_resources_pass(\@resources,\%grader_partids_by_symb,                             \%grader_randomlists_by_symb);
                   8065: 
1.554     raeburn  8066:     my ($uname,$udom);
1.523     raeburn  8067:     my (%scandata,%lastname,%bylast);
                   8068:     $r->print('
                   8069: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="checkscantron">'."\n");
                   8070: 
                   8071:     my @delayqueue;
                   8072:     my %completedstudents;
                   8073: 
                   8074:     my $count=&Apache::grades::get_todo_count($scanlines,$scan_data);
1.581     www      8075:     my %prog_state=&Apache::lonhtmlcommon::Create_PrgWin($r,'Bubblesheet/Submissions Comparison Status',
                   8076:                                     'Progress of Bubblesheet Data/Submission Records Comparison',$count,
1.523     raeburn  8077:                                     'inline',undef,'checkscantron');
1.546     raeburn  8078:     my ($username,$domain,$started);
1.582     raeburn  8079:     my $nav_error;
                   8080:     &scantron_get_maxbubble(\$nav_error); # Need the bubble lines array to parse.
                   8081:     if ($nav_error) {
                   8082:         $r->print(&navmap_errormsg());
                   8083:         return '';
                   8084:     }
1.523     raeburn  8085: 
                   8086:     &Apache::lonhtmlcommon::Update_PrgWin($r,\%prog_state,
                   8087:                                           'Processing first student');
                   8088:     my $start=&Time::HiRes::time();
                   8089:     my $i=-1;
                   8090: 
                   8091:     while ($i<$scanlines->{'count'}) {
                   8092:         ($username,$domain,$uname)=('','','');
                   8093:         $i++;
                   8094:         my $line=&Apache::grades::scantron_get_line($scanlines,$scan_data,$i);
                   8095:         if ($line=~/^[\s\cz]*$/) { next; }
                   8096:         if ($started) {
                   8097:             &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state,
                   8098:                                                      'last student');
                   8099:         }
                   8100:         $started=1;
                   8101:         my $scan_record=
                   8102:             &Apache::grades::scantron_parse_scanline($line,$i,\%scantron_config,
                   8103:                                                      $scan_data);
                   8104:         unless ($uname=&Apache::grades::scantron_find_student($scan_record,$scan_data,
                   8105:                                                               \%idmap,$i)) {
                   8106:             &Apache::grades::scantron_add_delay(\@delayqueue,$line,
                   8107:                                 'Unable to find a student that matches',1);
                   8108:             next;
                   8109:         }
                   8110:         if (exists $completedstudents{$uname}) {
                   8111:             &Apache::grades::scantron_add_delay(\@delayqueue,$line,
                   8112:                                 'Student '.$uname.' has multiple sheets',2);
                   8113:             next;
                   8114:         }
                   8115:         my $pid = $scan_record->{'scantron.ID'};
                   8116:         $lastname{$pid} = $scan_record->{'scantron.LastName'};
                   8117:         push(@{$bylast{$lastname{$pid}}},$pid);
                   8118:         my $lastpos = $env{'form.scantron_maxbubble'}*$scantron_config{'Qlength'};
                   8119:         $scandata{$pid} = substr($line,$scantron_config{'Qstart'}-1,$lastpos);
                   8120:         chomp($scandata{$pid});
                   8121:         $scandata{$pid} =~ s/\r$//;
                   8122:         ($username,$domain)=split(/:/,$uname);
                   8123:         my $counter = -1;
                   8124:         foreach my $resource (@resources) {
1.557     raeburn  8125:             my $parts;
1.554     raeburn  8126:             my $ressymb = $resource->symb();
1.557     raeburn  8127:             if ((exists($grader_randomlists_by_symb{$ressymb})) ||
                   8128:                 (ref($grader_partids_by_symb{$ressymb}) ne 'ARRAY')) {
                   8129:                 (my $analysis,$parts) =
                   8130:                     &scantron_partids_tograde($resource,$env{'request.course.id'},$username,$domain);
                   8131:             } else {
                   8132:                 $parts = $grader_partids_by_symb{$ressymb};
                   8133:             }
1.542     raeburn  8134:             ($counter,my $recording) =
                   8135:                 &verify_scantron_grading($resource,$domain,$username,$cid,$counter,
1.554     raeburn  8136:                                          $scandata{$pid},$parts,
1.542     raeburn  8137:                                          \%scantron_config,\%lettdig,$numletts);
                   8138:             $record{$pid} .= $recording;
1.523     raeburn  8139:         }
                   8140:     }
                   8141:     &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
                   8142:     $r->print('<br />');
                   8143:     my ($okstudents,$badstudents,$numstudents,$passed,$failed);
                   8144:     $passed = 0;
                   8145:     $failed = 0;
                   8146:     $numstudents = 0;
                   8147:     foreach my $last (sort(keys(%bylast))) {
                   8148:         if (ref($bylast{$last}) eq 'ARRAY') {
                   8149:             foreach my $pid (sort(@{$bylast{$last}})) {
                   8150:                 my $showscandata = $scandata{$pid};
                   8151:                 my $showrecord = $record{$pid};
                   8152:                 $showscandata =~ s/\s/&nbsp;/g;
                   8153:                 $showrecord =~ s/\s/&nbsp;/g;
                   8154:                 if ($scandata{$pid} eq $record{$pid}) {
                   8155:                     my $css_class = ($passed % 2)?'LC_odd_row':'LC_even_row';
                   8156:                     $okstudents .= '<tr class="'.$css_class.'">'.
1.581     www      8157: '<td>'.&mt('Bubblesheet').'</td><td>'.$showscandata.'</td><td rowspan="2">'.$last.'</td><td rowspan="2">'.$pid.'</td>'."\n".
1.523     raeburn  8158: '</tr>'."\n".
                   8159: '<tr class="'.$css_class.'">'."\n".
                   8160: '<td>Submissions</td><td>'.$showrecord.'</td></tr>'."\n";
                   8161:                     $passed ++;
                   8162:                 } else {
                   8163:                     my $css_class = ($failed % 2)?'LC_odd_row':'LC_even_row';
1.581     www      8164:                     $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  8165: '</tr>'."\n".
                   8166: '<tr class="'.$css_class.'">'."\n".
                   8167: '<td>Submissions</td><td><span class="LC_nobreak">'.$record{$pid}.'</span></td>'."\n".
                   8168: '</tr>'."\n";
                   8169:                     $failed ++;
                   8170:                 }
                   8171:                 $numstudents ++;
                   8172:             }
                   8173:         }
                   8174:     }
1.572     www      8175:     $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  8176:     $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>');
                   8177:     if ($passed) {
1.572     www      8178:         $r->print(&mt('Students with exact correspondence between bubblesheet data and submissions are as follows:').'<br /><br />');
1.523     raeburn  8179:         $r->print(&Apache::loncommon::start_data_table()."\n".
                   8180:                  &Apache::loncommon::start_data_table_header_row()."\n".
                   8181:                  '<th>'.&mt('Source').'</th><th>'.&mt('Bubble records').'</th><th>'.&mt('Name').'</th><th>'.&mt('ID').'</th>'.
                   8182:                  &Apache::loncommon::end_data_table_header_row()."\n".
                   8183:                  $okstudents."\n".
                   8184:                  &Apache::loncommon::end_data_table().'<br />');
                   8185:     }
                   8186:     if ($failed) {
1.572     www      8187:         $r->print(&mt('Students with differences between bubblesheet data and submissions are as follows:').'<br /><br />');
1.523     raeburn  8188:         $r->print(&Apache::loncommon::start_data_table()."\n".
                   8189:                  &Apache::loncommon::start_data_table_header_row()."\n".
                   8190:                  '<th>'.&mt('Source').'</th><th>'.&mt('Bubble records').'</th><th>'.&mt('Name').'</th><th>'.&mt('ID').'</th>'.
                   8191:                  &Apache::loncommon::end_data_table_header_row()."\n".
                   8192:                  $badstudents."\n".
                   8193:                  &Apache::loncommon::end_data_table()).'<br />'.
1.572     www      8194:                  &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  8195:     }
1.614     www      8196:     $r->print('</form><br />');
1.523     raeburn  8197:     return;
                   8198: }
                   8199: 
1.542     raeburn  8200: sub verify_scantron_grading {
1.554     raeburn  8201:     my ($resource,$domain,$username,$cid,$counter,$scandata,$partids,
1.542     raeburn  8202:         $scantron_config,$lettdig,$numletts) = @_;
                   8203:     my ($record,%expected,%startpos);
                   8204:     return ($counter,$record) if (!ref($resource));
                   8205:     return ($counter,$record) if (!$resource->is_problem());
                   8206:     my $symb = $resource->symb();
1.554     raeburn  8207:     return ($counter,$record) if (ref($partids) ne 'ARRAY');
                   8208:     foreach my $part_id (@{$partids}) {
1.542     raeburn  8209:         $counter ++;
                   8210:         $expected{$part_id} = 0;
                   8211:         if ($env{"form.scantron.sub_bubblelines.$counter"}) {
                   8212:             my @sub_lines = split(/,/,$env{"form.scantron.sub_bubblelines.$counter"});
                   8213:             foreach my $item (@sub_lines) {
                   8214:                 $expected{$part_id} += $item;
                   8215:             }
                   8216:         } else {
                   8217:             $expected{$part_id} = $env{"form.scantron.bubblelines.$counter"};
                   8218:         }
                   8219:         $startpos{$part_id} = $env{"form.scantron.first_bubble_line.$counter"};
                   8220:     }
                   8221:     if ($symb) {
                   8222:         my %recorded;
                   8223:         my (%returnhash) = &Apache::lonnet::restore($symb,$cid,$domain,$username);
                   8224:         if ($returnhash{'version'}) {
                   8225:             my %lasthash=();
                   8226:             my $version;
                   8227:             for ($version=1;$version<=$returnhash{'version'};$version++) {
                   8228:                 foreach my $key (sort(split(/\:/,$returnhash{$version.':keys'}))) {
                   8229:                     $lasthash{$key}=$returnhash{$version.':'.$key};
                   8230:                 }
                   8231:             }
                   8232:             foreach my $key (keys(%lasthash)) {
                   8233:                 if ($key =~ /\.scantron$/) {
                   8234:                     my $value = &unescape($lasthash{$key});
                   8235:                     my ($part_id) = ($key =~ /^resource\.(.+)\.scantron$/);
                   8236:                     if ($value eq '') {
                   8237:                         for (my $i=0; $i<$expected{$part_id}; $i++) {
                   8238:                             for (my $j=0; $j<$scantron_config->{'length'}; $j++) {
                   8239:                                 $recorded{$part_id} .= $scantron_config->{'Qoff'};
                   8240:                             }
                   8241:                         }
                   8242:                     } else {
                   8243:                         my @tocheck;
                   8244:                         my @items = split(//,$value);
                   8245:                         if (($scantron_config->{'Qon'} eq 'letter') ||
                   8246:                             ($scantron_config->{'Qon'} eq 'number')) {
                   8247:                             if (@items < $expected{$part_id}) {
                   8248:                                 my $fragment = substr($scandata,$startpos{$part_id},$expected{$part_id});
                   8249:                                 my @singles = split(//,$fragment);
                   8250:                                 foreach my $pos (@singles) {
                   8251:                                     if ($pos eq ' ') {
                   8252:                                         push(@tocheck,$pos);
                   8253:                                     } else {
                   8254:                                         my $next = shift(@items);
                   8255:                                         push(@tocheck,$next);
                   8256:                                     }
                   8257:                                 }
                   8258:                             } else {
                   8259:                                 @tocheck = @items;
                   8260:                             }
                   8261:                             foreach my $letter (@tocheck) {
                   8262:                                 if ($scantron_config->{'Qon'} eq 'letter') {
                   8263:                                     if ($letter !~ /^[A-J]$/) {
                   8264:                                         $letter = $scantron_config->{'Qoff'};
                   8265:                                     }
                   8266:                                     $recorded{$part_id} .= $letter;
                   8267:                                 } elsif ($scantron_config->{'Qon'} eq 'number') {
                   8268:                                     my $digit;
                   8269:                                     if ($letter !~ /^[A-J]$/) {
                   8270:                                         $digit = $scantron_config->{'Qoff'};
                   8271:                                     } else {
                   8272:                                         $digit = $lettdig->{$letter};
                   8273:                                     }
                   8274:                                     $recorded{$part_id} .= $digit;
                   8275:                                 }
                   8276:                             }
                   8277:                         } else {
                   8278:                             @tocheck = @items;
                   8279:                             for (my $i=0; $i<$expected{$part_id}; $i++) {
                   8280:                                 my $curr_sub = shift(@tocheck);
                   8281:                                 my $digit;
                   8282:                                 if ($curr_sub =~ /^[A-J]$/) {
                   8283:                                     $digit = $lettdig->{$curr_sub}-1;
                   8284:                                 }
                   8285:                                 if ($curr_sub eq 'J') {
                   8286:                                     $digit += scalar($numletts);
                   8287:                                 }
                   8288:                                 for (my $j=0; $j<$scantron_config->{'Qlength'}; $j++) {
                   8289:                                     if ($j == $digit) {
                   8290:                                         $recorded{$part_id} .= $scantron_config->{'Qon'};
                   8291:                                     } else {
                   8292:                                         $recorded{$part_id} .= $scantron_config->{'Qoff'};
                   8293:                                     }
                   8294:                                 }
                   8295:                             }
                   8296:                         }
                   8297:                     }
                   8298:                 }
                   8299:             }
                   8300:         }
1.554     raeburn  8301:         foreach my $part_id (@{$partids}) {
1.542     raeburn  8302:             if ($recorded{$part_id} eq '') {
                   8303:                 for (my $i=0; $i<$expected{$part_id}; $i++) {
                   8304:                     for (my $j=0; $j<$scantron_config->{'Qlength'}; $j++) {
                   8305:                         $recorded{$part_id} .= $scantron_config->{'Qoff'};
                   8306:                     }
                   8307:                 }
                   8308:             }
                   8309:             $record .= $recorded{$part_id};
                   8310:         }
                   8311:     }
                   8312:     return ($counter,$record);
                   8313: }
                   8314: 
                   8315: sub letter_to_digits { 
                   8316:     my %lettdig = (
                   8317:                     A => 1,
                   8318:                     B => 2,
                   8319:                     C => 3,
                   8320:                     D => 4,
                   8321:                     E => 5,
                   8322:                     F => 6,
                   8323:                     G => 7,
                   8324:                     H => 8,
                   8325:                     I => 9,
                   8326:                     J => 0,
                   8327:                   );
                   8328:     return %lettdig;
                   8329: }
                   8330: 
1.423     albertel 8331: 
1.75      albertel 8332: #-------- end of section for handling grading scantron forms -------
                   8333: #
                   8334: #-------------------------------------------------------------------
                   8335: 
1.72      ng       8336: #-------------------------- Menu interface -------------------------
                   8337: #
1.614     www      8338: #--- Href with symb and command ---
                   8339: 
                   8340: sub href_symb_cmd {
                   8341:     my ($symb,$cmd)=@_;
                   8342:     return '/adm/grades?symb='.&HTML::Entities::encode(&Apache::lonenc::check_encrypt($symb),'<>&"').'&command='.$cmd;
1.72      ng       8343: }
                   8344: 
1.443     banghart 8345: sub grading_menu {
1.608     www      8346:     my ($request,$symb) = @_;
1.443     banghart 8347:     if (!$symb) {return '';}
                   8348: 
                   8349:     my %fields = ('symb'=>&Apache::lonenc::check_encrypt($symb),
1.618     www      8350:                   'command'=>'individual');
1.538     schulted 8351:     
1.598     www      8352:     my $url1a = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   8353: 
                   8354:     $fields{'command'}='ungraded';
                   8355:     my $url1b=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   8356: 
                   8357:     $fields{'command'}='table';
                   8358:     my $url1c=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   8359: 
                   8360:     $fields{'command'}='all_for_one';
                   8361:     my $url1d=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   8362: 
1.621     www      8363:     $fields{'command'}='downloadfilesselect';
                   8364:     my $url1e=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   8365: 
1.443     banghart 8366:     $fields{'command'} = 'csvform';
1.538     schulted 8367:     my $url2 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   8368:     
1.443     banghart 8369:     $fields{'command'} = 'processclicker';
1.538     schulted 8370:     my $url3 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   8371:     
1.443     banghart 8372:     $fields{'command'} = 'scantron_selectphase';
1.538     schulted 8373:     my $url4 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
1.602     www      8374: 
                   8375:     $fields{'command'} = 'initialverifyreceipt';
                   8376:     my $url5 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
1.538     schulted 8377:     
1.598     www      8378:     my @menu = ({	categorytitle=>'Hand Grading',
1.538     schulted 8379:             items =>[
1.598     www      8380:                         {	linktext => 'Select individual students to grade',
                   8381:                     		url => $url1a,
1.538     schulted 8382:                     		permission => 'F',
1.636     wenzelju 8383:                     		icon => 'grade_students.png',
1.598     www      8384:                     		linktitle => 'Grade current resource for a selection of students.'
                   8385:                         }, 
                   8386:                         {       linktext => 'Grade ungraded submissions.',
                   8387:                                 url => $url1b,
                   8388:                                 permission => 'F',
1.636     wenzelju 8389:                                 icon => 'ungrade_sub.png',
1.598     www      8390:                                 linktitle => 'Grade all submissions that have not been graded yet.'
1.538     schulted 8391:                         },
1.598     www      8392: 
                   8393:                         {       linktext => 'Grading table',
                   8394:                                 url => $url1c,
                   8395:                                 permission => 'F',
1.636     wenzelju 8396:                                 icon => 'grading_table.png',
1.598     www      8397:                                 linktitle => 'Grade current resource for all students.'
                   8398:                         },
1.615     www      8399:                         {       linktext => 'Grade page/folder for one student',
1.598     www      8400:                                 url => $url1d,
                   8401:                                 permission => 'F',
1.636     wenzelju 8402:                                 icon => 'grade_PageFolder.png',
1.598     www      8403:                                 linktitle => 'Grade all resources in current page/sequence/folder for one student.'
1.621     www      8404:                         },
                   8405:                         {       linktext => 'Download submissions',
                   8406:                                 url => $url1e,
                   8407:                                 permission => 'F',
1.636     wenzelju 8408:                                 icon => 'download_sub.png',
1.621     www      8409:                                 linktitle => 'Download all students submissions.'
1.598     www      8410:                         }]},
                   8411:                          { categorytitle=>'Automated Grading',
                   8412:                items =>[
                   8413: 
1.538     schulted 8414:                 	    {	linktext => 'Upload Scores',
                   8415:                     		url => $url2,
                   8416:                     		permission => 'F',
                   8417:                     		icon => 'uploadscores.png',
                   8418:                     		linktitle => 'Specify a file containing the class scores for current resource.'
                   8419:                 	    },
                   8420:                 	    {	linktext => 'Process Clicker',
                   8421:                     		url => $url3,
                   8422:                     		permission => 'F',
                   8423:                     		icon => 'addClickerInfoFile.png',
                   8424:                     		linktitle => 'Specify a file containing the clicker information for this resource.'
                   8425:                 	    },
1.587     raeburn  8426:                 	    {	linktext => 'Grade/Manage/Review Bubblesheets',
1.538     schulted 8427:                     		url => $url4,
                   8428:                     		permission => 'F',
1.636     wenzelju 8429:                     		icon => 'bubblesheet.png',
1.538     schulted 8430:                     		linktitle => 'Grade scantron exams, upload/download scantron data files, and review previously graded scantron exams.'
1.602     www      8431:                 	    },
1.616     www      8432:                             {   linktext => 'Verify Receipt Number',
1.602     www      8433:                                 url => $url5,
                   8434:                                 permission => 'F',
1.636     wenzelju 8435:                                 icon => 'receipt_number.png',
1.602     www      8436:                                 linktitle => 'Verify a system-generated receipt number for correct problem solution.'
                   8437:                             }
                   8438: 
1.538     schulted 8439:                     ]
                   8440:             });
                   8441: 
1.443     banghart 8442:     # Create the menu
                   8443:     my $Str;
1.445     banghart 8444:     $Str .= '<form method="post" action="" name="gradingMenu">';
                   8445:     $Str .= '<input type="hidden" name="command" value="" />'.
1.618     www      8446:     	'<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
1.445     banghart 8447: 
1.602     www      8448:     $Str .= &Apache::lonhtmlcommon::generate_menu(@menu);
1.443     banghart 8449:     return $Str;    
                   8450: }
                   8451: 
1.598     www      8452: 
                   8453: sub ungraded {
                   8454:     my ($request)=@_;
                   8455:     &submit_options($request);
                   8456: }
                   8457: 
1.599     www      8458: sub submit_options_sequence {
1.608     www      8459:     my ($request,$symb) = @_;
1.599     www      8460:     if (!$symb) {return '';}
1.600     www      8461:     &commonJSfunctions($request);
                   8462:     my $result;
1.599     www      8463: 
1.600     www      8464:     $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
1.618     www      8465:         '<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
1.632     www      8466:     $result.=&selectfield(0).
1.601     www      8467:             '<input type="hidden" name="command" value="pickStudentPage" />
1.600     www      8468:             <div>
                   8469:               <input type="submit" value="'.&mt('Next').' &rarr;" />
                   8470:             </div>
                   8471:         </div>
                   8472:   </form>';
                   8473:     return $result;
                   8474: }
                   8475: 
                   8476: sub submit_options_table {
1.608     www      8477:     my ($request,$symb) = @_;
1.600     www      8478:     if (!$symb) {return '';}
1.599     www      8479:     &commonJSfunctions($request);
                   8480:     my $result;
                   8481: 
                   8482:     $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
1.618     www      8483:         '<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
1.599     www      8484: 
1.632     www      8485:     $result.=&selectfield(0).
1.601     www      8486:             '<input type="hidden" name="command" value="viewgrades" />
1.599     www      8487:             <div>
                   8488:               <input type="submit" value="'.&mt('Next').' &rarr;" />
                   8489:             </div>
                   8490:         </div>
                   8491:   </form>';
                   8492:     return $result;
                   8493: }
1.443     banghart 8494: 
1.621     www      8495: sub submit_options_download {
                   8496:     my ($request,$symb) = @_;
                   8497:     if (!$symb) {return '';}
                   8498: 
                   8499:     &commonJSfunctions($request);
                   8500: 
                   8501:     my $result='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
                   8502:         '<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
                   8503:     $result.='
                   8504: <h2>
                   8505:   '.&mt('Select Students for Which to Download Submissions').'
                   8506: </h2>'.&selectfield(1).'
                   8507:                 <input type="hidden" name="command" value="downloadfileslink" /> 
                   8508:               <input type="submit" value="'.&mt('Next').' &rarr;" />
                   8509:             </div>
                   8510:           </div>
1.600     www      8511: 
                   8512: 
1.621     www      8513:   </form>';
                   8514:     return $result;
                   8515: }
                   8516: 
1.443     banghart 8517: #--- Displays the submissions first page -------
                   8518: sub submit_options {
1.608     www      8519:     my ($request,$symb) = @_;
1.72      ng       8520:     if (!$symb) {return '';}
                   8521: 
1.118     ng       8522:     &commonJSfunctions($request);
1.473     albertel 8523:     my $result;
1.533     bisitz   8524: 
1.72      ng       8525:     $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
1.618     www      8526: 	'<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
1.632     www      8527:     $result.=&selectfield(1).'
1.601     www      8528:                 <input type="hidden" name="command" value="submission" /> 
                   8529: 	      <input type="submit" value="'.&mt('Next').' &rarr;" />
                   8530:             </div>
                   8531:           </div>
                   8532: 
                   8533: 
                   8534:   </form>';
                   8535:     return $result;
                   8536: }
1.533     bisitz   8537: 
1.601     www      8538: sub selectfield {
                   8539:    my ($full)=@_;
1.635     raeburn  8540:    my %options = 
                   8541:           (&Apache::lonlocal::texthash(
                   8542:              'yes'       => 'with submissions',
                   8543:              'queued'    => 'in grading queue',
                   8544:              'graded'    => 'with ungraded submissions',
                   8545:              'incorrect' => 'with incorrect submissions',
                   8546:              'all'       => 'with any status'),
                   8547:              'select_form_order' => ['yes','queued','graded','incorrect','all']);
1.601     www      8548:    my $result='<div class="LC_columnSection">
1.537     harmsja  8549:   
1.533     bisitz   8550:     <fieldset>
                   8551:       <legend>
                   8552:        '.&mt('Sections').'
                   8553:       </legend>
1.601     www      8554:       '.&Apache::lonstatistics::SectionSelect('section','multiple',5).'
1.533     bisitz   8555:     </fieldset>
1.537     harmsja  8556:   
1.533     bisitz   8557:     <fieldset>
                   8558:       <legend>
                   8559:         '.&mt('Groups').'
                   8560:       </legend>
                   8561:       '.&Apache::lonstatistics::GroupSelect('group','multiple',5).'
                   8562:     </fieldset>
1.537     harmsja  8563:   
1.533     bisitz   8564:     <fieldset>
                   8565:       <legend>
                   8566:         '.&mt('Access Status').'
                   8567:       </legend>
1.601     www      8568:       '.&Apache::lonhtmlcommon::StatusOptions(undef,undef,5,undef,'mult').'
                   8569:     </fieldset>';
                   8570:     if ($full) {
                   8571:        $result.='
1.533     bisitz   8572:     <fieldset>
                   8573:       <legend>
                   8574:         '.&mt('Submission Status').'
1.601     www      8575:       </legend>'.
1.635     raeburn  8576:        &Apache::loncommon::select_form('all','submitonly',\%options).
1.601     www      8577:    '</fieldset>';
                   8578:     }
                   8579:     $result.='</div><br />';
1.44      ng       8580:     return $result;
1.2       albertel 8581: }
                   8582: 
1.285     albertel 8583: sub reset_perm {
                   8584:     undef(%perm);
                   8585: }
                   8586: 
                   8587: sub init_perm {
                   8588:     &reset_perm();
1.300     albertel 8589:     foreach my $test_perm ('vgr','mgr','opa') {
                   8590: 
                   8591: 	my $scope = $env{'request.course.id'};
                   8592: 	if (!($perm{$test_perm}=&Apache::lonnet::allowed($test_perm,$scope))) {
                   8593: 
                   8594: 	    $scope .= '/'.$env{'request.course.sec'};
                   8595: 	    if ( $perm{$test_perm}=
                   8596: 		 &Apache::lonnet::allowed($test_perm,$scope)) {
                   8597: 		$perm{$test_perm.'_section'}=$env{'request.course.sec'};
                   8598: 	    } else {
                   8599: 		delete($perm{$test_perm});
                   8600: 	    }
1.285     albertel 8601: 	}
                   8602:     }
                   8603: }
                   8604: 
1.400     www      8605: sub gather_clicker_ids {
1.408     albertel 8606:     my %clicker_ids;
1.400     www      8607: 
                   8608:     my $classlist = &Apache::loncoursedata::get_classlist();
                   8609: 
                   8610:     # Set up a couple variables.
1.407     albertel 8611:     my $username_idx = &Apache::loncoursedata::CL_SNAME();
                   8612:     my $domain_idx   = &Apache::loncoursedata::CL_SDOM();
1.438     www      8613:     my $status_idx   = &Apache::loncoursedata::CL_STATUS();
1.400     www      8614: 
1.407     albertel 8615:     foreach my $student (keys(%$classlist)) {
1.438     www      8616:         if ($classlist->{$student}->[$status_idx] ne 'Active') { next; }
1.407     albertel 8617:         my $username = $classlist->{$student}->[$username_idx];
                   8618:         my $domain   = $classlist->{$student}->[$domain_idx];
1.400     www      8619:         my $clickers =
1.408     albertel 8620: 	    (&Apache::lonnet::userenvironment($domain,$username,'clickers'))[1];
1.400     www      8621:         foreach my $id (split(/\,/,$clickers)) {
1.414     www      8622:             $id=~s/^[\#0]+//;
1.421     www      8623:             $id=~s/[\-\:]//g;
1.407     albertel 8624:             if (exists($clicker_ids{$id})) {
1.408     albertel 8625: 		$clicker_ids{$id}.=','.$username.':'.$domain;
1.400     www      8626:             } else {
1.408     albertel 8627: 		$clicker_ids{$id}=$username.':'.$domain;
1.400     www      8628:             }
                   8629:         }
                   8630:     }
1.407     albertel 8631:     return %clicker_ids;
1.400     www      8632: }
                   8633: 
1.402     www      8634: sub gather_adv_clicker_ids {
1.408     albertel 8635:     my %clicker_ids;
1.402     www      8636:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
                   8637:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   8638:     my %coursepersonnel=&Apache::lonnet::get_course_adv_roles($cdom.'/'.$cnum);
1.409     albertel 8639:     foreach my $element (sort(keys(%coursepersonnel))) {
1.402     www      8640:         foreach my $person (split(/\,/,$coursepersonnel{$element})) {
                   8641:             my ($puname,$pudom)=split(/\:/,$person);
                   8642:             my $clickers =
1.408     albertel 8643: 		(&Apache::lonnet::userenvironment($pudom,$puname,'clickers'))[1];
1.405     www      8644:             foreach my $id (split(/\,/,$clickers)) {
1.414     www      8645: 		$id=~s/^[\#0]+//;
1.421     www      8646:                 $id=~s/[\-\:]//g;
1.408     albertel 8647: 		if (exists($clicker_ids{$id})) {
                   8648: 		    $clicker_ids{$id}.=','.$puname.':'.$pudom;
                   8649: 		} else {
                   8650: 		    $clicker_ids{$id}=$puname.':'.$pudom;
                   8651: 		}
1.405     www      8652:             }
1.402     www      8653:         }
                   8654:     }
1.407     albertel 8655:     return %clicker_ids;
1.402     www      8656: }
                   8657: 
1.413     www      8658: sub clicker_grading_parameters {
                   8659:     return ('gradingmechanism' => 'scalar',
                   8660:             'upfiletype' => 'scalar',
                   8661:             'specificid' => 'scalar',
                   8662:             'pcorrect' => 'scalar',
                   8663:             'pincorrect' => 'scalar');
                   8664: }
                   8665: 
1.400     www      8666: sub process_clicker {
1.608     www      8667:     my ($r,$symb)=@_;
1.400     www      8668:     if (!$symb) {return '';}
                   8669:     my $result=&checkforfile_js();
1.632     www      8670:     $result.=&Apache::loncommon::start_data_table().
                   8671:              &Apache::loncommon::start_data_table_header_row().
                   8672:              '<th>'.&mt('Specify a file containing clicker information and set grading options.').'</th>'.
                   8673:              &Apache::loncommon::end_data_table_header_row().
                   8674:              &Apache::loncommon::start_data_table_row()."<td>\n";
1.413     www      8675: # Attempt to restore parameters from last session, set defaults if not present
                   8676:     my %Saveable_Parameters=&clicker_grading_parameters();
                   8677:     &Apache::loncommon::restore_course_settings('grades_clicker',
                   8678:                                                  \%Saveable_Parameters);
                   8679:     if (!$env{'form.pcorrect'}) { $env{'form.pcorrect'}=100; }
                   8680:     if (!$env{'form.pincorrect'}) { $env{'form.pincorrect'}=100; }
                   8681:     if (!$env{'form.gradingmechanism'}) { $env{'form.gradingmechanism'}='attendance'; }
                   8682:     if (!$env{'form.upfiletype'}) { $env{'form.upfiletype'}='iclicker'; }
                   8683: 
                   8684:     my %checked;
1.521     www      8685:     foreach my $gradingmechanism ('attendance','personnel','specific','given') {
1.413     www      8686:        if ($env{'form.gradingmechanism'} eq $gradingmechanism) {
1.569     bisitz   8687:           $checked{$gradingmechanism}=' checked="checked"';
1.413     www      8688:        }
                   8689:     }
                   8690: 
1.632     www      8691:     my $upload=&mt("Evaluate File");
1.400     www      8692:     my $type=&mt("Type");
1.402     www      8693:     my $attendance=&mt("Award points just for participation");
                   8694:     my $personnel=&mt("Correctness determined from response by course personnel");
1.414     www      8695:     my $specific=&mt("Correctness determined from response with clicker ID(s)"); 
1.521     www      8696:     my $given=&mt("Correctness determined from given list of answers").' '.
                   8697:               '<font size="-2"><tt>('.&mt("Provide comma-separated list. Use '*' for any answer correct, '-' for skip").')</tt></font>';
1.402     www      8698:     my $pcorrect=&mt("Percentage points for correct solution");
                   8699:     my $pincorrect=&mt("Percentage points for incorrect solution");
1.413     www      8700:     my $selectform=&Apache::loncommon::select_form($env{'form.upfiletype'},'upfiletype',
1.635     raeburn  8701: 						   {'iclicker' => 'i>clicker',
                   8702:                                                     'interwrite' => 'interwrite PRS'});
1.418     albertel 8703:     $symb = &Apache::lonenc::check_encrypt($symb);
1.597     wenzelju 8704:     $result.= &Apache::lonhtmlcommon::scripttag(<<ENDUPFORM);
1.402     www      8705: function sanitycheck() {
                   8706: // Accept only integer percentages
                   8707:    document.forms.gradesupload.pcorrect.value=Math.round(document.forms.gradesupload.pcorrect.value);
                   8708:    document.forms.gradesupload.pincorrect.value=Math.round(document.forms.gradesupload.pincorrect.value);
                   8709: // Find out grading choice
                   8710:    for (i=0; i<document.forms.gradesupload.gradingmechanism.length; i++) {
                   8711:       if (document.forms.gradesupload.gradingmechanism[i].checked) {
                   8712:          gradingchoice=document.forms.gradesupload.gradingmechanism[i].value;
                   8713:       }
                   8714:    }
                   8715: // By default, new choice equals user selection
                   8716:    newgradingchoice=gradingchoice;
                   8717: // Not good to give more points for false answers than correct ones
                   8718:    if (Math.round(document.forms.gradesupload.pcorrect.value)<Math.round(document.forms.gradesupload.pincorrect.value)) {
                   8719:       document.forms.gradesupload.pcorrect.value=document.forms.gradesupload.pincorrect.value;
                   8720:    }
                   8721: // If new choice is attendance only, and old choice was correctness-based, restore defaults
                   8722:    if ((gradingchoice=='attendance') && (document.forms.gradesupload.waschecked.value!='attendance')) {
                   8723:       document.forms.gradesupload.pcorrect.value=100;
                   8724:       document.forms.gradesupload.pincorrect.value=100;
                   8725:    }
                   8726: // If the values are different, cannot be attendance only
                   8727:    if ((Math.round(document.forms.gradesupload.pcorrect.value)!=Math.round(document.forms.gradesupload.pincorrect.value)) &&
                   8728:        (gradingchoice=='attendance')) {
                   8729:        newgradingchoice='personnel';
                   8730:    }
                   8731: // Change grading choice to new one
                   8732:    for (i=0; i<document.forms.gradesupload.gradingmechanism.length; i++) {
                   8733:       if (document.forms.gradesupload.gradingmechanism[i].value==newgradingchoice) {
                   8734:          document.forms.gradesupload.gradingmechanism[i].checked=true;
                   8735:       } else {
                   8736:          document.forms.gradesupload.gradingmechanism[i].checked=false;
                   8737:       }
                   8738:    }
                   8739: // Remember the old state
                   8740:    document.forms.gradesupload.waschecked.value=newgradingchoice;
                   8741: }
1.597     wenzelju 8742: ENDUPFORM
                   8743:     $result.= <<ENDUPFORM;
1.400     www      8744: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
                   8745: <input type="hidden" name="symb" value="$symb" />
                   8746: <input type="hidden" name="command" value="processclickerfile" />
                   8747: <input type="file" name="upfile" size="50" />
                   8748: <br /><label>$type: $selectform</label>
1.632     www      8749: ENDUPFORM
                   8750:     $result.='</td>'.&Apache::loncommon::end_data_table_row().
                   8751:                      &Apache::loncommon::start_data_table_row().'<td>'.(<<ENDGRADINGFORM);
                   8752:       <label><input type="radio" name="gradingmechanism" value="attendance"$checked{'attendance'} onclick="sanitycheck()" />$attendance </label>
1.589     bisitz   8753: <br /><label><input type="radio" name="gradingmechanism" value="personnel"$checked{'personnel'} onclick="sanitycheck()" />$personnel</label>
                   8754: <br /><label><input type="radio" name="gradingmechanism" value="specific"$checked{'specific'} onclick="sanitycheck()" />$specific </label>
1.414     www      8755: <input type="text" name="specificid" value="$env{'form.specificid'}" size="20" />
1.589     bisitz   8756: <br /><label><input type="radio" name="gradingmechanism" value="given"$checked{'given'} onclick="sanitycheck()" />$given </label>
1.521     www      8757: <br />&nbsp;&nbsp;&nbsp;
                   8758: <input type="text" name="givenanswer" size="50" />
1.413     www      8759: <input type="hidden" name="waschecked" value="$env{'form.gradingmechanism'}" />
1.632     www      8760: ENDGRADINGFORM
                   8761:          $result.='</td>'.&Apache::loncommon::end_data_table_row().
                   8762:                      &Apache::loncommon::start_data_table_row().'<td>'.(<<ENDPERCFORM);
                   8763:       <label>$pcorrect: <input type="text" name="pcorrect" size="4" value="$env{'form.pcorrect'}" onchange="sanitycheck()" /></label>
1.589     bisitz   8764: <br /><label>$pincorrect: <input type="text" name="pincorrect" size="4" value="$env{'form.pincorrect'}" onchange="sanitycheck()" /></label>
                   8765: <br /><input type="button" onclick="javascript:checkUpload(this.form);" value="$upload" />
1.597     wenzelju 8766: </form>'
1.632     www      8767: ENDPERCFORM
                   8768:     $result.='</td>'.
                   8769:              &Apache::loncommon::end_data_table_row().
                   8770:              &Apache::loncommon::end_data_table();
1.400     www      8771:     return $result;
                   8772: }
                   8773: 
                   8774: sub process_clicker_file {
1.608     www      8775:     my ($r,$symb)=@_;
1.400     www      8776:     if (!$symb) {return '';}
1.413     www      8777: 
                   8778:     my %Saveable_Parameters=&clicker_grading_parameters();
                   8779:     &Apache::loncommon::store_course_settings('grades_clicker',
                   8780:                                               \%Saveable_Parameters);
1.598     www      8781:     my $result='';
1.404     www      8782:     if (($env{'form.gradingmechanism'} eq 'specific') && ($env{'form.specificid'}!~/\w/)) {
1.408     albertel 8783: 	$result.='<span class="LC_error">'.&mt('You need to specify a clicker ID for the correct answer').'</span>';
1.614     www      8784: 	return $result;
1.404     www      8785:     }
1.522     www      8786:     if (($env{'form.gradingmechanism'} eq 'given') && ($env{'form.givenanswer'}!~/\S/)) {
1.521     www      8787:         $result.='<span class="LC_error">'.&mt('You need to specify the correct answer').'</span>';
1.614     www      8788:         return $result;
1.521     www      8789:     }
1.522     www      8790:     my $foundgiven=0;
1.521     www      8791:     if ($env{'form.gradingmechanism'} eq 'given') {
                   8792:         $env{'form.givenanswer'}=~s/^\s*//gs;
                   8793:         $env{'form.givenanswer'}=~s/\s*$//gs;
                   8794:         $env{'form.givenanswer'}=~s/[^a-zA-Z0-9\.\*\-]+/\,/g;
                   8795:         $env{'form.givenanswer'}=uc($env{'form.givenanswer'});
1.522     www      8796:         my @answers=split(/\,/,$env{'form.givenanswer'});
                   8797:         $foundgiven=$#answers+1;
1.521     www      8798:     }
1.407     albertel 8799:     my %clicker_ids=&gather_clicker_ids();
1.408     albertel 8800:     my %correct_ids;
1.404     www      8801:     if ($env{'form.gradingmechanism'} eq 'personnel') {
1.408     albertel 8802: 	%correct_ids=&gather_adv_clicker_ids();
1.404     www      8803:     }
                   8804:     if ($env{'form.gradingmechanism'} eq 'specific') {
1.414     www      8805: 	foreach my $correct_id (split(/[\s\,]/,$env{'form.specificid'})) {;
                   8806: 	   $correct_id=~tr/a-z/A-Z/;
                   8807: 	   $correct_id=~s/\s//gs;
                   8808: 	   $correct_id=~s/^[\#0]+//;
1.421     www      8809:            $correct_id=~s/[\-\:]//g;
1.414     www      8810:            if ($correct_id) {
                   8811: 	      $correct_ids{$correct_id}='specified';
                   8812:            }
                   8813:         }
1.400     www      8814:     }
1.404     www      8815:     if ($env{'form.gradingmechanism'} eq 'attendance') {
1.408     albertel 8816: 	$result.=&mt('Score based on attendance only');
1.521     www      8817:     } elsif ($env{'form.gradingmechanism'} eq 'given') {
1.522     www      8818:         $result.=&mt('Score based on [_1] ([_2] answers)','<tt>'.$env{'form.givenanswer'}.'</tt>',$foundgiven);
1.404     www      8819:     } else {
1.408     albertel 8820: 	my $number=0;
1.411     www      8821: 	$result.='<p><b>'.&mt('Correctness determined by the following IDs').'</b>';
1.408     albertel 8822: 	foreach my $id (sort(keys(%correct_ids))) {
1.411     www      8823: 	    $result.='<br /><tt>'.$id.'</tt> - ';
1.408     albertel 8824: 	    if ($correct_ids{$id} eq 'specified') {
                   8825: 		$result.=&mt('specified');
                   8826: 	    } else {
                   8827: 		my ($uname,$udom)=split(/\:/,$correct_ids{$id});
                   8828: 		$result.=&Apache::loncommon::plainname($uname,$udom);
                   8829: 	    }
                   8830: 	    $number++;
                   8831: 	}
1.411     www      8832:         $result.="</p>\n";
1.408     albertel 8833: 	if ($number==0) {
                   8834: 	    $result.='<span class="LC_error">'.&mt('No IDs found to determine correct answer').'</span>';
1.614     www      8835: 	    return $result;
1.408     albertel 8836: 	}
1.404     www      8837:     }
1.405     www      8838:     if (length($env{'form.upfile'}) < 2) {
1.407     albertel 8839:         $result.=&mt('[_1] Error: [_2] The file you attempted to upload, [_3] contained no information. Please check that you entered the correct filename.',
                   8840: 		     '<span class="LC_error">',
                   8841: 		     '</span>',
                   8842: 		     '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>');
1.614     www      8843:         return $result;
1.405     www      8844:     }
1.410     www      8845: 
                   8846: # Were able to get all the info needed, now analyze the file
                   8847: 
1.411     www      8848:     $result.=&Apache::loncommon::studentbrowser_javascript();
1.418     albertel 8849:     $symb = &Apache::lonenc::check_encrypt($symb);
1.632     www      8850:     $result.=&Apache::loncommon::start_data_table().
                   8851:              &Apache::loncommon::start_data_table_header_row().
                   8852:              '<th>'.&mt('Evaluate clicker file').'</th>'.
                   8853:              &Apache::loncommon::end_data_table_header_row().
                   8854:              &Apache::loncommon::start_data_table_row().(<<ENDHEADER);
                   8855: <td>
1.410     www      8856: <form method="post" action="/adm/grades" name="clickeranalysis">
                   8857: <input type="hidden" name="symb" value="$symb" />
                   8858: <input type="hidden" name="command" value="assignclickergrades" />
1.411     www      8859: <input type="hidden" name="gradingmechanism" value="$env{'form.gradingmechanism'}" />
                   8860: <input type="hidden" name="pcorrect" value="$env{'form.pcorrect'}" />
                   8861: <input type="hidden" name="pincorrect" value="$env{'form.pincorrect'}" />
1.410     www      8862: ENDHEADER
1.522     www      8863:     if ($env{'form.gradingmechanism'} eq 'given') {
                   8864:        $result.='<input type="hidden" name="correct:given" value="'.$env{'form.givenanswer'}.'" />';
                   8865:     } 
1.408     albertel 8866:     my %responses;
                   8867:     my @questiontitles;
1.405     www      8868:     my $errormsg='';
                   8869:     my $number=0;
                   8870:     if ($env{'form.upfiletype'} eq 'iclicker') {
1.408     albertel 8871: 	($errormsg,$number)=&iclicker_eval(\@questiontitles,\%responses);
1.406     www      8872:     }
1.419     www      8873:     if ($env{'form.upfiletype'} eq 'interwrite') {
                   8874:         ($errormsg,$number)=&interwrite_eval(\@questiontitles,\%responses);
                   8875:     }
1.411     www      8876:     $result.='<br />'.&mt('Found [_1] question(s)',$number).'<br />'.
                   8877:              '<input type="hidden" name="number" value="'.$number.'" />'.
                   8878:              &mt('Awarding [_1] percent for correct and [_2] percent for incorrect responses',
                   8879:                  $env{'form.pcorrect'},$env{'form.pincorrect'}).
                   8880:              '<br />';
1.522     www      8881:     if (($env{'form.gradingmechanism'} eq 'given') && ($number!=$foundgiven)) {
                   8882:        $result.='<span class="LC_error">'.&mt('Number of given answers does not agree with number of questions in file.').'</span>';
1.614     www      8883:        return $result;
1.522     www      8884:     } 
1.414     www      8885: # Remember Question Titles
                   8886: # FIXME: Possibly need delimiter other than ":"
                   8887:     for (my $i=0;$i<$number;$i++) {
                   8888:         $result.='<input type="hidden" name="question:'.$i.'" value="'.
                   8889:                  &HTML::Entities::encode($questiontitles[$i],'"&<>').'" />';
                   8890:     }
1.411     www      8891:     my $correct_count=0;
                   8892:     my $student_count=0;
                   8893:     my $unknown_count=0;
1.414     www      8894: # Match answers with usernames
                   8895: # FIXME: Possibly need delimiter other than ":"
1.409     albertel 8896:     foreach my $id (keys(%responses)) {
1.410     www      8897:        if ($correct_ids{$id}) {
1.414     www      8898:           $result.="\n".'<input type="hidden" name="correct:'.$correct_count.':'.$correct_ids{$id}.'" value="'.$responses{$id}.'" />';
1.411     www      8899:           $correct_count++;
1.410     www      8900:        } elsif ($clicker_ids{$id}) {
1.437     www      8901:           if ($clicker_ids{$id}=~/\,/) {
                   8902: # More than one user with the same clicker!
1.632     www      8903:              $result.="</td>".&Apache::loncommon::end_data_table_row().
                   8904:                            &Apache::loncommon::start_data_table_row()."<td>".
                   8905:                        &mt('Clicker registered more than once').": <tt>".$id."</tt><br />";
1.437     www      8906:              $result.="\n".'<input type="hidden" name="unknown:'.$id.'" value="'.$responses{$id}.'" />'.
                   8907:                            "<select name='multi".$id."'>";
                   8908:              foreach my $reguser (sort(split(/\,/,$clicker_ids{$id}))) {
                   8909:                  $result.="<option value='".$reguser."'>".&Apache::loncommon::plainname(split(/\:/,$reguser)).' ('.$reguser.')</option>';
                   8910:              }
                   8911:              $result.='</select>';
                   8912:              $unknown_count++;
                   8913:           } else {
                   8914: # Good: found one and only one user with the right clicker
                   8915:              $result.="\n".'<input type="hidden" name="student:'.$clicker_ids{$id}.'" value="'.$responses{$id}.'" />';
                   8916:              $student_count++;
                   8917:           }
1.410     www      8918:        } else {
1.632     www      8919:           $result.="</td>".&Apache::loncommon::end_data_table_row().
                   8920:                            &Apache::loncommon::start_data_table_row()."<td>".
                   8921:                     &mt('Unregistered Clicker')." <tt>".$id."</tt><br />";
1.411     www      8922:           $result.="\n".'<input type="hidden" name="unknown:'.$id.'" value="'.$responses{$id}.'" />'.
                   8923:                    "\n".&mt("Username").": <input type='text' name='uname".$id."' />&nbsp;".
                   8924:                    "\n".&mt("Domain").": ".
                   8925:                    &Apache::loncommon::select_dom_form($env{'course.'.$env{'request.course.id'}.'.domain'},'udom'.$id).'&nbsp;'.
                   8926:                    &Apache::loncommon::selectstudent_link('clickeranalysis','uname'.$id,'udom'.$id);
                   8927:           $unknown_count++;
1.410     www      8928:        }
1.405     www      8929:     }
1.412     www      8930:     $result.='<hr />'.
                   8931:              &mt('Found [_1] registered and [_2] unregistered clickers.',$student_count,$unknown_count);
1.521     www      8932:     if (($env{'form.gradingmechanism'} ne 'attendance') && ($env{'form.gradingmechanism'} ne 'given')) {
1.412     www      8933:        if ($correct_count==0) {
                   8934:           $errormsg.="Found no correct answers answers for grading!";
                   8935:        } elsif ($correct_count>1) {
1.414     www      8936:           $result.='<br /><span class="LC_warning">'.&mt("Found [_1] entries for grading!",$correct_count).'</span>';
1.412     www      8937:        }
                   8938:     }
1.428     www      8939:     if ($number<1) {
                   8940:        $errormsg.="Found no questions.";
                   8941:     }
1.412     www      8942:     if ($errormsg) {
                   8943:        $result.='<br /><span class="LC_error">'.&mt($errormsg).'</span>';
                   8944:     } else {
                   8945:        $result.='<br /><input type="submit" name="finalize" value="'.&mt('Finalize Grading').'" />';
                   8946:     }
1.632     www      8947:     $result.='</form></td>'.
                   8948:              &Apache::loncommon::end_data_table_row().
                   8949:              &Apache::loncommon::end_data_table();
1.614     www      8950:     return $result;
1.400     www      8951: }
                   8952: 
1.405     www      8953: sub iclicker_eval {
1.406     www      8954:     my ($questiontitles,$responses)=@_;
1.405     www      8955:     my $number=0;
                   8956:     my $errormsg='';
                   8957:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
1.410     www      8958:         my %components=&Apache::loncommon::record_sep($line);
                   8959:         my @entries=map {$components{$_}} (sort(keys(%components)));
1.408     albertel 8960: 	if ($entries[0] eq 'Question') {
                   8961: 	    for (my $i=3;$i<$#entries;$i+=6) {
                   8962: 		$$questiontitles[$number]=$entries[$i];
                   8963: 		$number++;
                   8964: 	    }
                   8965: 	}
                   8966: 	if ($entries[0]=~/^\#/) {
                   8967: 	    my $id=$entries[0];
                   8968: 	    my @idresponses;
                   8969: 	    $id=~s/^[\#0]+//;
                   8970: 	    for (my $i=0;$i<$number;$i++) {
                   8971: 		my $idx=3+$i*6;
                   8972: 		push(@idresponses,$entries[$idx]);
                   8973: 	    }
                   8974: 	    $$responses{$id}=join(',',@idresponses);
                   8975: 	}
1.405     www      8976:     }
                   8977:     return ($errormsg,$number);
                   8978: }
                   8979: 
1.419     www      8980: sub interwrite_eval {
                   8981:     my ($questiontitles,$responses)=@_;
                   8982:     my $number=0;
                   8983:     my $errormsg='';
1.420     www      8984:     my $skipline=1;
                   8985:     my $questionnumber=0;
                   8986:     my %idresponses=();
1.419     www      8987:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
                   8988:         my %components=&Apache::loncommon::record_sep($line);
                   8989:         my @entries=map {$components{$_}} (sort(keys(%components)));
1.420     www      8990:         if ($entries[1] eq 'Time') { $skipline=0; next; }
                   8991:         if ($entries[1] eq 'Response') { $skipline=1; }
                   8992:         next if $skipline;
                   8993:         if ($entries[0]!=$questionnumber) {
                   8994:            $questionnumber=$entries[0];
                   8995:            $$questiontitles[$number]=&mt('Question [_1]',$questionnumber);
                   8996:            $number++;
1.419     www      8997:         }
1.420     www      8998:         my $id=$entries[4];
                   8999:         $id=~s/^[\#0]+//;
1.421     www      9000:         $id=~s/^v\d*\://i;
                   9001:         $id=~s/[\-\:]//g;
1.420     www      9002:         $idresponses{$id}[$number]=$entries[6];
                   9003:     }
1.524     raeburn  9004:     foreach my $id (keys(%idresponses)) {
1.420     www      9005:        $$responses{$id}=join(',',@{$idresponses{$id}});
                   9006:        $$responses{$id}=~s/^\s*\,//;
1.419     www      9007:     }
                   9008:     return ($errormsg,$number);
                   9009: }
                   9010: 
1.414     www      9011: sub assign_clicker_grades {
1.608     www      9012:     my ($r,$symb)=@_;
1.414     www      9013:     if (!$symb) {return '';}
1.416     www      9014: # See which part we are saving to
1.582     raeburn  9015:     my $res_error;
                   9016:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
                   9017:     if ($res_error) {
                   9018:         return &navmap_errormsg();
                   9019:     }
1.416     www      9020: # FIXME: This should probably look for the first handgradeable part
                   9021:     my $part=$$partlist[0];
                   9022: # Start screen output
1.632     www      9023:     my $result=&Apache::loncommon::start_data_table().
                   9024:              &Apache::loncommon::start_data_table_header_row().
                   9025:              '<th>'.&mt('Assigning grades based on clicker file').'</th>'.
                   9026:              &Apache::loncommon::end_data_table_header_row().
                   9027:              &Apache::loncommon::start_data_table_row().'<td>';
1.414     www      9028: # Get correct result
                   9029: # FIXME: Possibly need delimiter other than ":"
                   9030:     my @correct=();
1.415     www      9031:     my $gradingmechanism=$env{'form.gradingmechanism'};
                   9032:     my $number=$env{'form.number'};
                   9033:     if ($gradingmechanism ne 'attendance') {
1.414     www      9034:        foreach my $key (keys(%env)) {
                   9035:           if ($key=~/^form\.correct\:/) {
                   9036:              my @input=split(/\,/,$env{$key});
                   9037:              for (my $i=0;$i<=$#input;$i++) {
                   9038:                  if (($correct[$i]) && ($input[$i]) &&
                   9039:                      ($correct[$i] ne $input[$i])) {
                   9040:                     $result.='<br /><span class="LC_warning">'.
                   9041:                              &mt('More than one correct result given for question "[_1]": [_2] versus [_3].',
                   9042:                                  $env{'form.question:'.$i},$correct[$i],$input[$i]).'</span>';
                   9043:                  } elsif ($input[$i]) {
                   9044:                     $correct[$i]=$input[$i];
                   9045:                  }
                   9046:              }
                   9047:           }
                   9048:        }
1.415     www      9049:        for (my $i=0;$i<$number;$i++) {
1.414     www      9050:           if (!$correct[$i]) {
                   9051:              $result.='<br /><span class="LC_error">'.
                   9052:                       &mt('No correct result given for question "[_1]"!',
                   9053:                           $env{'form.question:'.$i}).'</span>';
                   9054:           }
                   9055:        }
                   9056:        $result.='<br />'.&mt("Correct answer: [_1]",join(', ',map { ($_?$_:'-') } @correct));
                   9057:     }
                   9058: # Start grading
1.415     www      9059:     my $pcorrect=$env{'form.pcorrect'};
                   9060:     my $pincorrect=$env{'form.pincorrect'};
1.416     www      9061:     my $storecount=0;
1.632     www      9062:     my %users=();
1.415     www      9063:     foreach my $key (keys(%env)) {
1.420     www      9064:        my $user='';
1.415     www      9065:        if ($key=~/^form\.student\:(.*)$/) {
1.420     www      9066:           $user=$1;
                   9067:        }
                   9068:        if ($key=~/^form\.unknown\:(.*)$/) {
                   9069:           my $id=$1;
                   9070:           if (($env{'form.uname'.$id}) && ($env{'form.udom'.$id})) {
                   9071:              $user=$env{'form.uname'.$id}.':'.$env{'form.udom'.$id};
1.437     www      9072:           } elsif ($env{'form.multi'.$id}) {
                   9073:              $user=$env{'form.multi'.$id};
1.420     www      9074:           }
                   9075:        }
1.632     www      9076:        if ($user) {
                   9077:           if ($users{$user}) {
                   9078:              $result.='<br /><span class="LC_warning">'.
                   9079:                       &mt("More than one entry found for <tt>[_1]</tt>!",$user).
                   9080:                       '</span><br />';
                   9081:           }
                   9082:           $users{$user}=1; 
1.415     www      9083:           my @answer=split(/\,/,$env{$key});
                   9084:           my $sum=0;
1.522     www      9085:           my $realnumber=$number;
1.415     www      9086:           for (my $i=0;$i<$number;$i++) {
1.576     www      9087:              if  ($correct[$i] eq '-') {
                   9088:                 $realnumber--;
                   9089:              } elsif ($answer[$i]) {
1.415     www      9090:                 if ($gradingmechanism eq 'attendance') {
                   9091:                    $sum+=$pcorrect;
1.576     www      9092:                 } elsif ($correct[$i] eq '*') {
1.522     www      9093:                    $sum+=$pcorrect;
1.415     www      9094:                 } else {
                   9095:                    if ($answer[$i] eq $correct[$i]) {
                   9096:                       $sum+=$pcorrect;
                   9097:                    } else {
                   9098:                       $sum+=$pincorrect;
                   9099:                    }
                   9100:                 }
                   9101:              }
                   9102:           }
1.522     www      9103:           my $ave=$sum/(100*$realnumber);
1.416     www      9104: # Store
                   9105:           my ($username,$domain)=split(/\:/,$user);
                   9106:           my %grades=();
                   9107:           $grades{"resource.$part.solved"}='correct_by_override';
                   9108:           $grades{"resource.$part.awarded"}=$ave;
                   9109:           $grades{"resource.regrader"}="$env{'user.name'}:$env{'user.domain'}";
                   9110:           my $returncode=&Apache::lonnet::cstore(\%grades,$symb,
                   9111:                                                  $env{'request.course.id'},
                   9112:                                                  $domain,$username);
                   9113:           if ($returncode ne 'ok') {
                   9114:              $result.="<br /><span class=\"LC_error\">Failed to save student $username:$domain. Message when trying to save was ($returncode)</span>";
                   9115:           } else {
                   9116:              $storecount++;
                   9117:           }
1.415     www      9118:        }
                   9119:     }
                   9120: # We are done
1.549     hauer    9121:     $result.='<br />'.&mt('Successfully stored grades for [quant,_1,student].',$storecount).
1.632     www      9122:              '</td>'.
                   9123:              &Apache::loncommon::end_data_table_row().
                   9124:              &Apache::loncommon::end_data_table();
1.614     www      9125:     return $result;
1.414     www      9126: }
                   9127: 
1.582     raeburn  9128: sub navmap_errormsg {
                   9129:     return '<div class="LC_error">'.
                   9130:            &mt('An error occurred retrieving information about resources in the course.').'<br />'.
1.595     raeburn  9131:            &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  9132:            '</div>';
                   9133: }
1.607     droeschl 9134: 
1.609     www      9135: sub startpage {
1.613     www      9136:     my ($r,$symb,$crumbs,$onlyfolderflag,$nodisplayflag) = @_;
1.614     www      9137:     unshift(@$crumbs,{href=>&href_symb_cmd($symb,'gradingmenu'),text=>"Grading"});
1.607     droeschl 9138:     $r->print(&Apache::loncommon::start_page('Grading',undef,
1.610     www      9139:                                           {'bread_crumbs' => $crumbs}));
1.632     www      9140:     $r->print('<h3>'.$$crumbs[-1]{'text'}.'</h3>');
1.613     www      9141:     unless ($nodisplayflag) {
                   9142:        $r->print(&Apache::lonhtmlcommon::resource_info_box($symb,$onlyfolderflag));
                   9143:     }
1.607     droeschl 9144: }
1.582     raeburn  9145: 
1.622     www      9146: sub select_problem {
                   9147:     my ($r)=@_;
1.632     www      9148:     $r->print('<h3>'.&mt('Select the problem or one of the problems you want to grade').'</h3><form action="/adm/grades">');
1.622     www      9149:     $r->print(&Apache::lonstathelpers::problem_selector('.',undef,1));
                   9150:     $r->print('<input type="hidden" name="command" value="gradingmenu" />');
                   9151:     $r->print('<input type="submit" value="'.&mt('Next').' &rarr;" /></form>');
                   9152: }
                   9153: 
1.1       albertel 9154: sub handler {
1.41      ng       9155:     my $request=$_[0];
1.434     albertel 9156:     &reset_caches();
1.257     albertel 9157:     if ($env{'browser.mathml'}) {
1.141     www      9158: 	&Apache::loncommon::content_type($request,'text/xml');
1.41      ng       9159:     } else {
1.141     www      9160: 	&Apache::loncommon::content_type($request,'text/html');
1.41      ng       9161:     }
                   9162:     $request->send_http_header;
1.44      ng       9163:     return '' if $request->header_only;
1.41      ng       9164:     &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'});
1.608     www      9165: 
                   9166: # see what command we need to execute
                   9167: 
1.160     albertel 9168:     my @commands=&Apache::loncommon::get_env_multiple('form.command');
                   9169:     my $command=$commands[0];
1.447     foxr     9170: 
1.160     albertel 9171:     if ($#commands > 0) {
                   9172: 	&Apache::lonnet::logthis("grades got multiple commands ".join(':',@commands));
                   9173:     }
1.608     www      9174: 
                   9175: # see what the symb is
                   9176: 
                   9177:     my $symb=$env{'form.symb'};
                   9178:     unless ($symb) {
                   9179:        (my $url=$env{'form.url'}) =~ s-^https*://($ENV{'SERVER_NAME'}|$ENV{'HTTP_HOST'})--;
                   9180:        $symb=&Apache::lonnet::symbread($url);
                   9181:     }
                   9182:     &Apache::lonenc::check_decrypt(\$symb);                             
                   9183: 
1.513     foxr     9184:     $ssi_error = 0;
1.637   ! www      9185:     if (($symb eq '' || $command eq '') && ($env{'request.course.id'})) {
1.601     www      9186: #
1.637   ! www      9187: # Not called from a resource, but inside a course
1.601     www      9188: #    
1.622     www      9189:         &startpage($request,undef,[],1,1);
                   9190:         &select_problem($request);
1.41      ng       9191:     } else {
1.285     albertel 9192: 	&init_perm();
1.104     albertel 9193: 	if ($command eq 'submission' && $perm{'vgr'}) {
1.608     www      9194:             &startpage($request,$symb,[{href=>"", text=>"Student Submissions"}]);
1.611     www      9195: 	    ($env{'form.student'} eq '' ? &listStudents($request,$symb) : &submission($request,0,0,$symb));
1.103     albertel 9196: 	} elsif ($command eq 'pickStudentPage' && $perm{'vgr'}) {
1.615     www      9197:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,'all_for_one'),text=>'Grade page/folder for one student'},
                   9198:                                        {href=>'',text=>'Select student'}],1,1);
1.608     www      9199: 	    &pickStudentPage($request,$symb);
1.103     albertel 9200: 	} elsif ($command eq 'displayPage' && $perm{'vgr'}) {
1.615     www      9201:             &startpage($request,$symb,
                   9202:                                       [{href=>&href_symb_cmd($symb,'all_for_one'),text=>'Grade page/folder for one student'},
                   9203:                                        {href=>'',text=>'Select student'},
                   9204:                                        {href=>'',text=>'Grade student'}],1,1);
1.608     www      9205: 	    &displayPage($request,$symb);
1.104     albertel 9206: 	} elsif ($command eq 'gradeByPage' && $perm{'mgr'}) {
1.616     www      9207:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,'all_for_one'),text=>'Grade page/folder for one student'},
                   9208:                                        {href=>'',text=>'Select student'},
                   9209:                                        {href=>'',text=>'Grade student'},
                   9210:                                        {href=>'',text=>'Store grades'}],1,1);
1.608     www      9211: 	    &updateGradeByPage($request,$symb);
1.104     albertel 9212: 	} elsif ($command eq 'processGroup' && $perm{'vgr'}) {
1.619     www      9213:             &startpage($request,$symb,[{href=>'',text=>'...'},
                   9214:                                        {href=>'',text=>'Modify grades'}]);
1.608     www      9215: 	    &processGroup($request,$symb);
1.104     albertel 9216: 	} elsif ($command eq 'gradingmenu' && $perm{'vgr'}) {
1.608     www      9217:             &startpage($request,$symb);
                   9218: 	    $request->print(&grading_menu($request,$symb));
1.598     www      9219: 	} elsif ($command eq 'individual' && $perm{'vgr'}) {
1.617     www      9220:             &startpage($request,$symb,[{href=>'',text=>'Select individual students to grade'}]);
1.608     www      9221: 	    $request->print(&submit_options($request,$symb));
1.598     www      9222:         } elsif ($command eq 'ungraded' && $perm{'vgr'}) {
1.617     www      9223:             &startpage($request,$symb,[{href=>'',text=>'Grade ungraded submissions'}]);
                   9224:             $request->print(&listStudents($request,$symb,'graded'));
1.598     www      9225:         } elsif ($command eq 'table' && $perm{'vgr'}) {
1.614     www      9226:             &startpage($request,$symb,[{href=>"", text=>"Grading table"}]);
1.611     www      9227:             $request->print(&submit_options_table($request,$symb));
1.598     www      9228:         } elsif ($command eq 'all_for_one' && $perm{'vgr'}) {
1.615     www      9229:             &startpage($request,$symb,[{href=>'',text=>'Grade page/folder for one student'}],1,1);
1.608     www      9230:             $request->print(&submit_options_sequence($request,$symb));
1.104     albertel 9231: 	} elsif ($command eq 'viewgrades' && $perm{'vgr'}) {
1.614     www      9232:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,"table"), text=>"Grading table"},{href=>'', text=>"Modify grades"}]);
1.608     www      9233: 	    $request->print(&viewgrades($request,$symb));
1.104     albertel 9234: 	} elsif ($command eq 'handgrade' && $perm{'mgr'}) {
1.620     www      9235:             &startpage($request,$symb,[{href=>'',text=>'...'},
                   9236:                                        {href=>'',text=>'Store grades'}]);
1.608     www      9237: 	    $request->print(&processHandGrade($request,$symb));
1.106     albertel 9238: 	} elsif ($command eq 'editgrades' && $perm{'mgr'}) {
1.614     www      9239:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,"table"), text=>"Grading table"},
                   9240:                                        {href=>&href_symb_cmd($symb,'viewgrades').'&group=all&section=all&Status=Active',
                   9241:                                                                              text=>"Modify grades"},
                   9242:                                        {href=>'', text=>"Store grades"}]);
1.608     www      9243: 	    $request->print(&editgrades($request,$symb));
1.602     www      9244:         } elsif ($command eq 'initialverifyreceipt' && $perm{'vgr'}) {
1.616     www      9245:             &startpage($request,$symb,[{href=>'',text=>'Verify Receipt Number'}]);
1.611     www      9246:             $request->print(&initialverifyreceipt($request,$symb));
1.106     albertel 9247: 	} elsif ($command eq 'verify' && $perm{'vgr'}) {
1.616     www      9248:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,"initialverifyreceipt"),text=>'Verify Receipt Number'},
                   9249:                                        {href=>'',text=>'Verification Result'}]);
1.608     www      9250: 	    $request->print(&verifyreceipt($request,$symb));
1.400     www      9251:         } elsif ($command eq 'processclicker' && $perm{'mgr'}) {
1.615     www      9252:             &startpage($request,$symb,[{href=>'', text=>'Process clicker'}]);
1.608     www      9253:             $request->print(&process_clicker($request,$symb));
1.400     www      9254:         } elsif ($command eq 'processclickerfile' && $perm{'mgr'}) {
1.615     www      9255:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,'processclicker'), text=>'Process clicker'},
                   9256:                                        {href=>'', text=>'Process clicker file'}]);
1.608     www      9257:             $request->print(&process_clicker_file($request,$symb));
1.414     www      9258:         } elsif ($command eq 'assignclickergrades' && $perm{'mgr'}) {
1.615     www      9259:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,'processclicker'), text=>'Process clicker'},
                   9260:                                        {href=>'', text=>'Process clicker file'},
                   9261:                                        {href=>'', text=>'Store grades'}]);
1.608     www      9262:             $request->print(&assign_clicker_grades($request,$symb));
1.106     albertel 9263: 	} elsif ($command eq 'csvform' && $perm{'mgr'}) {
1.627     www      9264:             &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
1.608     www      9265: 	    $request->print(&upcsvScores_form($request,$symb));
1.106     albertel 9266: 	} elsif ($command eq 'csvupload' && $perm{'mgr'}) {
1.627     www      9267:             &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
1.608     www      9268: 	    $request->print(&csvupload($request,$symb));
1.106     albertel 9269: 	} elsif ($command eq 'csvuploadmap' && $perm{'mgr'} ) {
1.627     www      9270:             &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
1.608     www      9271: 	    $request->print(&csvuploadmap($request,$symb));
1.246     albertel 9272: 	} elsif ($command eq 'csvuploadoptions' && $perm{'mgr'}) {
1.257     albertel 9273: 	    if ($env{'form.associate'} ne 'Reverse Association') {
1.627     www      9274:                 &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
1.608     www      9275: 		$request->print(&csvuploadoptions($request,$symb));
1.41      ng       9276: 	    } else {
1.257     albertel 9277: 		if ( $env{'form.upfile_associate'} ne 'reverse' ) {
                   9278: 		    $env{'form.upfile_associate'} = 'reverse';
1.41      ng       9279: 		} else {
1.257     albertel 9280: 		    $env{'form.upfile_associate'} = 'forward';
1.41      ng       9281: 		}
1.627     www      9282:                 &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
1.608     www      9283: 		$request->print(&csvuploadmap($request,$symb));
1.41      ng       9284: 	    }
1.246     albertel 9285: 	} elsif ($command eq 'csvuploadassign' && $perm{'mgr'} ) {
1.627     www      9286:             &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
1.608     www      9287: 	    $request->print(&csvuploadassign($request,$symb));
1.106     albertel 9288: 	} elsif ($command eq 'scantron_selectphase' && $perm{'mgr'}) {
1.616     www      9289:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
1.612     www      9290: 	    $request->print(&scantron_selectphase($request,undef,$symb));
1.203     albertel 9291:  	} elsif ($command eq 'scantron_warning' && $perm{'mgr'}) {
1.616     www      9292:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
1.608     www      9293:  	    $request->print(&scantron_do_warning($request,$symb));
1.142     albertel 9294: 	} elsif ($command eq 'scantron_validate' && $perm{'mgr'}) {
1.616     www      9295:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
1.608     www      9296: 	    $request->print(&scantron_validate_file($request,$symb));
1.106     albertel 9297: 	} elsif ($command eq 'scantron_process' && $perm{'mgr'}) {
1.616     www      9298:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
1.608     www      9299: 	    $request->print(&scantron_process_students($request,$symb));
1.157     albertel 9300:  	} elsif ($command eq 'scantronupload' && 
1.257     albertel 9301:  		 (&Apache::lonnet::allowed('usc',$env{'request.role.domain'})||
                   9302: 		  &Apache::lonnet::allowed('usc',$env{'request.course.id'}))) {
1.616     www      9303:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
1.608     www      9304:  	    $request->print(&scantron_upload_scantron_data($request,$symb)); 
1.157     albertel 9305:  	} elsif ($command eq 'scantronupload_save' &&
1.257     albertel 9306:  		 (&Apache::lonnet::allowed('usc',$env{'request.role.domain'})||
                   9307: 		  &Apache::lonnet::allowed('usc',$env{'request.course.id'}))) {
1.616     www      9308:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
1.608     www      9309:  	    $request->print(&scantron_upload_scantron_data_save($request,$symb));
1.202     albertel 9310:  	} elsif ($command eq 'scantron_download' &&
1.257     albertel 9311: 		 &Apache::lonnet::allowed('usc',$env{'request.course.id'})) {
1.616     www      9312:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
1.608     www      9313:  	    $request->print(&scantron_download_scantron_data($request,$symb));
1.523     raeburn  9314:         } elsif ($command eq 'checksubmissions' && $perm{'vgr'}) {
1.616     www      9315:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
1.621     www      9316:             $request->print(&checkscantron_results($request,$symb));
                   9317:         } elsif ($command eq 'downloadfilesselect' && $perm{'vgr'}) {
                   9318:             &startpage($request,$symb,[{href=>'', text=>'Select which submissions to download'}]);
                   9319:             $request->print(&submit_options_download($request,$symb));
                   9320:          } elsif ($command eq 'downloadfileslink' && $perm{'vgr'}) {
                   9321:             &startpage($request,$symb,
                   9322:    [{href=>&href_symb_cmd($symb,'downloadfilesselect'), text=>'Select which submissions to download'},
                   9323:     {href=>'', text=>'Download submissions'}]);
                   9324:             &submit_download_link($request,$symb);
1.106     albertel 9325: 	} elsif ($command) {
1.620     www      9326:             &startpage($request,$symb,[{href=>'', text=>'Access denied'}]);
1.562     bisitz   9327: 	    $request->print('<p class="LC_error">'.&mt('Access Denied ([_1])',$command).'</p>');
1.26      albertel 9328: 	}
1.2       albertel 9329:     }
1.513     foxr     9330:     if ($ssi_error) {
                   9331: 	&ssi_print_error($request);
                   9332:     }
1.353     albertel 9333:     $request->print(&Apache::loncommon::end_page());
1.434     albertel 9334:     &reset_caches();
1.44      ng       9335:     return '';
                   9336: }
                   9337: 
1.1       albertel 9338: 1;
                   9339: 
1.13      albertel 9340: __END__;
1.531     jms      9341: 
                   9342: 
                   9343: =head1 NAME
                   9344: 
                   9345: Apache::grades
                   9346: 
                   9347: =head1 SYNOPSIS
                   9348: 
                   9349: Handles the viewing of grades.
                   9350: 
                   9351: This is part of the LearningOnline Network with CAPA project
                   9352: described at http://www.lon-capa.org.
                   9353: 
                   9354: =head1 OVERVIEW
                   9355: 
                   9356: Do an ssi with retries:
                   9357: While I'd love to factor out this with the vesrion in lonprintout,
                   9358: 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
                   9359: I'm not quite ready to invent (e.g. an ssi_with_retry object).
                   9360: 
                   9361: At least the logic that drives this has been pulled out into loncommon.
                   9362: 
                   9363: 
                   9364: 
                   9365: ssi_with_retries - Does the server side include of a resource.
                   9366:                      if the ssi call returns an error we'll retry it up to
                   9367:                      the number of times requested by the caller.
                   9368:                      If we still have a proble, no text is appended to the
                   9369:                      output and we set some global variables.
                   9370:                      to indicate to the caller an SSI error occurred.  
                   9371:                      All of this is supposed to deal with the issues described
                   9372:                      in LonCAPA BZ 5631 see:
                   9373:                      http://bugs.lon-capa.org/show_bug.cgi?id=5631
                   9374:                      by informing the user that this happened.
                   9375: 
                   9376: Parameters:
                   9377:   resource   - The resource to include.  This is passed directly, without
                   9378:                interpretation to lonnet::ssi.
                   9379:   form       - The form hash parameters that guide the interpretation of the resource
                   9380:                
                   9381:   retries    - Number of retries allowed before giving up completely.
                   9382: Returns:
                   9383:   On success, returns the rendered resource identified by the resource parameter.
                   9384: Side Effects:
                   9385:   The following global variables can be set:
                   9386:    ssi_error                - If an unrecoverable error occurred this becomes true.
                   9387:                               It is up to the caller to initialize this to false
                   9388:                               if desired.
                   9389:    ssi_error_resource  - If an unrecoverable error occurred, this is the value
                   9390:                               of the resource that could not be rendered by the ssi
                   9391:                               call.
                   9392:    ssi_error_message   - The error string fetched from the ssi response
                   9393:                               in the event of an error.
                   9394: 
                   9395: 
                   9396: =head1 HANDLER SUBROUTINE
                   9397: 
                   9398: ssi_with_retries()
                   9399: 
                   9400: =head1 SUBROUTINES
                   9401: 
                   9402: =over
                   9403: 
                   9404: =item scantron_get_correction() : 
                   9405: 
                   9406:    Builds the interface screen to interact with the operator to fix a
                   9407:    specific error condition in a specific scanline
                   9408: 
                   9409:  Arguments:
                   9410:     $r           - Apache request object
                   9411:     $i           - number of the current scanline
                   9412:     $scan_record - hash ref as returned from &scantron_parse_scanline()
                   9413:     $scan_config - hash ref as returned from &get_scantron_config()
                   9414:     $line        - full contents of the current scanline
                   9415:     $error       - error condition, valid values are
                   9416:                    'incorrectCODE', 'duplicateCODE',
                   9417:                    'doublebubble', 'missingbubble',
                   9418:                    'duplicateID', 'incorrectID'
                   9419:     $arg         - extra information needed
                   9420:        For errors:
                   9421:          - duplicateID   - paper number that this studentID was seen before on
                   9422:          - duplicateCODE - array ref of the paper numbers this CODE was
                   9423:                            seen on before
                   9424:          - incorrectCODE - current incorrect CODE 
                   9425:          - doublebubble  - array ref of the bubble lines that have double
                   9426:                            bubble errors
                   9427:          - missingbubble - array ref of the bubble lines that have missing
                   9428:                            bubble errors
                   9429: 
                   9430: =item  scantron_get_maxbubble() : 
                   9431: 
1.582     raeburn  9432:    Arguments:
                   9433:        $nav_error  - Reference to scalar which is a flag to indicate a
                   9434:                       failure to retrieve a navmap object.
                   9435:        if $nav_error is set to 1 by scantron_get_maxbubble(), the 
                   9436:        calling routine should trap the error condition and display the warning
                   9437:        found in &navmap_errormsg().
                   9438: 
1.531     jms      9439:    Returns the maximum number of bubble lines that are expected to
                   9440:    occur. Does this by walking the selected sequence rendering the
                   9441:    resource and then checking &Apache::lonxml::get_problem_counter()
                   9442:    for what the current value of the problem counter is.
                   9443: 
                   9444:    Caches the results to $env{'form.scantron_maxbubble'},
                   9445:    $env{'form.scantron.bubble_lines.n'}, 
                   9446:    $env{'form.scantron.first_bubble_line.n'} and
                   9447:    $env{"form.scantron.sub_bubblelines.n"}
                   9448:    which are the total number of bubble, lines, the number of bubble
                   9449:    lines for response n and number of the first bubble line for response n,
                   9450:    and a comma separated list of numbers of bubble lines for sub-questions
                   9451:    (for optionresponse, matchresponse, and rankresponse items), for response n.  
                   9452: 
                   9453: 
                   9454: =item  scantron_validate_missingbubbles() : 
                   9455: 
                   9456:    Validates all scanlines in the selected file to not have any
                   9457:     answers that don't have bubbles that have not been verified
                   9458:     to be bubble free.
                   9459: 
                   9460: =item  scantron_process_students() : 
                   9461: 
                   9462:    Routine that does the actual grading of the bubble sheet information.
                   9463: 
                   9464:    The parsed scanline hash is added to %env 
                   9465: 
                   9466:    Then foreach unskipped scanline it does an &Apache::lonnet::ssi()
                   9467:    foreach resource , with the form data of
                   9468: 
                   9469: 	'submitted'     =>'scantron' 
                   9470: 	'grade_target'  =>'grade',
                   9471: 	'grade_username'=> username of student
                   9472: 	'grade_domain'  => domain of student
                   9473: 	'grade_courseid'=> of course
                   9474: 	'grade_symb'    => symb of resource to grade
                   9475: 
                   9476:     This triggers a grading pass. The problem grading code takes care
                   9477:     of converting the bubbled letter information (now in %env) into a
                   9478:     valid submission.
                   9479: 
                   9480: =item  scantron_upload_scantron_data() :
                   9481: 
                   9482:     Creates the screen for adding a new bubble sheet data file to a course.
                   9483: 
                   9484: =item  scantron_upload_scantron_data_save() : 
                   9485: 
                   9486:    Adds a provided bubble information data file to the course if user
                   9487:    has the correct privileges to do so. 
                   9488: 
                   9489: =item  valid_file() :
                   9490: 
                   9491:    Validates that the requested bubble data file exists in the course.
                   9492: 
                   9493: =item  scantron_download_scantron_data() : 
                   9494: 
                   9495:    Shows a list of the three internal files (original, corrected,
                   9496:    skipped) for a specific bubble sheet data file that exists in the
                   9497:    course.
                   9498: 
                   9499: =item  scantron_validate_ID() : 
                   9500: 
                   9501:    Validates all scanlines in the selected file to not have any
1.556     weissno  9502:    invalid or underspecified student/employee IDs
1.531     jms      9503: 
1.582     raeburn  9504: =item navmap_errormsg() :
                   9505: 
                   9506:    Returns HTML mark-up inside a <div></div> with a link to re-initialize the course.
                   9507:    Should be called whenever the request to instantiate a navmap object fails.  
                   9508: 
1.531     jms      9509: =back
                   9510: 
                   9511: =cut

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