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

1.17      albertel    1: # The LearningOnline Network with CAPA
1.13      albertel    2: # The LON-CAPA Grading handler
1.17      albertel    3: #
1.631   ! www         4: # $Id: grades.pm,v 1.630 2010/04/22 13:00:24 www Exp $
1.17      albertel    5: #
                      6: # Copyright Michigan State University Board of Trustees
                      7: #
                      8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
                      9: #
                     10: # LON-CAPA is free software; you can redistribute it and/or modify
                     11: # it under the terms of the GNU General Public License as published by
                     12: # the Free Software Foundation; either version 2 of the License, or
                     13: # (at your option) any later version.
                     14: #
                     15: # LON-CAPA is distributed in the hope that it will be useful,
                     16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
                     17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
                     18: # GNU General Public License for more details.
                     19: #
                     20: # You should have received a copy of the GNU General Public License
                     21: # along with LON-CAPA; if not, write to the Free Software
                     22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
                     23: #
                     24: # /home/httpd/html/adm/gpl.txt
                     25: #
                     26: # http://www.lon-capa.org/
                     27: #
1.1       albertel   28: 
1.529     jms        29: 
                     30: 
1.1       albertel   31: package Apache::grades;
                     32: use strict;
                     33: use Apache::style;
                     34: use Apache::lonxml;
                     35: use Apache::lonnet;
1.3       albertel   36: use Apache::loncommon;
1.112     ng         37: use Apache::lonhtmlcommon;
1.68      ng         38: use Apache::lonnavmaps;
1.1       albertel   39: use Apache::lonhomework;
1.456     banghart   40: use Apache::lonpickcode;
1.55      matthew    41: use Apache::loncoursedata;
1.362     albertel   42: use Apache::lonmsg();
1.1       albertel   43: use Apache::Constants qw(:common);
1.167     sakharuk   44: use Apache::lonlocal;
1.386     raeburn    45: use Apache::lonenc;
1.622     www        46: use Apache::lonstathelpers;
1.170     albertel   47: use String::Similarity;
1.359     www        48: use LONCAPA;
                     49: 
1.315     bowersj2   50: use POSIX qw(floor);
1.87      www        51: 
1.435     foxr       52: 
1.513     foxr       53: 
1.435     foxr       54: my %perm=();
1.447     foxr       55: 
1.513     foxr       56: #  These variables are used to recover from ssi errors
                     57: 
                     58: my $ssi_retries = 5;
                     59: my $ssi_error;
                     60: my $ssi_error_resource;
                     61: my $ssi_error_message;
                     62: 
                     63: 
                     64: sub ssi_with_retries {
                     65:     my ($resource, $retries, %form) = @_;
                     66:     my ($content, $response) = &Apache::loncommon::ssi_with_retries($resource, $retries, %form);
                     67:     if ($response->is_error) {
                     68: 	$ssi_error          = 1;
                     69: 	$ssi_error_resource = $resource;
                     70: 	$ssi_error_message  = $response->code . " " . $response->message;
                     71:     }
                     72: 
                     73:     return $content;
                     74: 
                     75: }
                     76: #
                     77: #  Prodcuces an ssi retry failure error message to the user:
                     78: #
                     79: 
                     80: sub ssi_print_error {
                     81:     my ($r) = @_;
1.516     raeburn    82:     my $helpurl = &Apache::loncommon::top_nav_help('Helpdesk');
                     83:     $r->print('
                     84: <br />
                     85: <h2>'.&mt('An unrecoverable network error occurred:').'</h2>
                     86: <p>
                     87: '.&mt('Unable to retrieve a resource from a server:').'<br />
                     88: '.&mt('Resource:').' '.$ssi_error_resource.'<br />
                     89: '.&mt('Error:').' '.$ssi_error_message.'
                     90: </p>
                     91: <p>'.
                     92: &mt('It is recommended that you try again later, as this error may mean the server was just temporarily unavailable, or is down for maintenance.').'<br />'.
                     93: &mt('If the error persists, please contact the [_1] for assistance.',$helpurl).
                     94: '</p>');
                     95:     return;
1.513     foxr       96: }
                     97: 
1.44      ng         98: #
1.146     albertel   99: # --- Retrieve the parts from the metadata file.---
1.598     www       100: # Returns an array of everything that the resources stores away
                    101: #
                    102: 
1.44      ng        103: sub getpartlist {
1.582     raeburn   104:     my ($symb,$errorref) = @_;
1.439     albertel  105: 
                    106:     my $navmap   = Apache::lonnavmaps::navmap->new();
1.582     raeburn   107:     unless (ref($navmap)) {
                    108:         if (ref($errorref)) { 
                    109:             $$errorref = 'navmap';
                    110:             return;
                    111:         }
                    112:     }
1.439     albertel  113:     my $res      = $navmap->getBySymb($symb);
                    114:     my $partlist = $res->parts();
                    115:     my $url      = $res->src();
                    116:     my @metakeys = split(/,/,&Apache::lonnet::metadata($url,'keys'));
                    117: 
1.146     albertel  118:     my @stores;
1.439     albertel  119:     foreach my $part (@{ $partlist }) {
1.146     albertel  120: 	foreach my $key (@metakeys) {
                    121: 	    if ($key =~ m/^stores_\Q$part\E_/) { push(@stores,$key); }
                    122: 	}
                    123:     }
                    124:     return @stores;
1.2       albertel  125: }
                    126: 
1.129     ng        127: #--- Format fullname, username:domain if different for display
                    128: #--- Use anywhere where the student names are listed
                    129: sub nameUserString {
                    130:     my ($type,$fullname,$uname,$udom) = @_;
                    131:     if ($type eq 'header') {
1.485     albertel  132: 	return '<b>&nbsp;'.&mt('Fullname').'&nbsp;</b><span class="LC_internal_info">('.&mt('Username').')</span>';
1.129     ng        133:     } else {
1.398     albertel  134: 	return '&nbsp;'.$fullname.'<span class="LC_internal_info">&nbsp;('.$uname.
                    135: 	    ($env{'user.domain'} eq $udom ? '' : ' ('.$udom.')').')</span>';
1.129     ng        136:     }
                    137: }
                    138: 
1.44      ng        139: #--- Get the partlist and the response type for a given problem. ---
                    140: #--- Indicate if a response type is coded handgraded or not. ---
1.623     www       141: #--- Sets response_error pointer to "1" if navmaps object broken ---
1.39      ng        142: sub response_type {
1.582     raeburn   143:     my ($symb,$response_error) = @_;
1.377     albertel  144: 
                    145:     my $navmap = Apache::lonnavmaps::navmap->new();
1.582     raeburn   146:     unless (ref($navmap)) {
                    147:         if (ref($response_error)) {
                    148:             $$response_error = 1;
                    149:         }
                    150:         return;
                    151:     }
1.377     albertel  152:     my $res = $navmap->getBySymb($symb);
1.593     raeburn   153:     unless (ref($res)) {
                    154:         $$response_error = 1;
                    155:         return;
                    156:     }
1.377     albertel  157:     my $partlist = $res->parts();
1.392     albertel  158:     my %vPart = 
                    159: 	map { $_ => 1 } (&Apache::loncommon::get_env_multiple('form.vPart'));
1.377     albertel  160:     my (%response_types,%handgrade);
                    161:     foreach my $part (@{ $partlist }) {
1.392     albertel  162: 	next if (%vPart && !exists($vPart{$part}));
                    163: 
1.377     albertel  164: 	my @types = $res->responseType($part);
                    165: 	my @ids = $res->responseIds($part);
                    166: 	for (my $i=0; $i < scalar(@ids); $i++) {
                    167: 	    $response_types{$part}{$ids[$i]} = $types[$i];
                    168: 	    $handgrade{$part.'_'.$ids[$i]} = 
                    169: 		&Apache::lonnet::EXT('resource.'.$part.'_'.$ids[$i].
                    170: 				     '.handgrade',$symb);
1.41      ng        171: 	}
                    172:     }
1.377     albertel  173:     return ($partlist,\%handgrade,\%response_types);
1.39      ng        174: }
                    175: 
1.375     albertel  176: sub flatten_responseType {
                    177:     my ($responseType) = @_;
                    178:     my @part_response_id =
                    179: 	map { 
                    180: 	    my $part = $_;
                    181: 	    map {
                    182: 		[$part,$_]
                    183: 		} sort(keys(%{ $responseType->{$part} }));
                    184: 	} sort(keys(%$responseType));
                    185:     return @part_response_id;
                    186: }
                    187: 
1.207     albertel  188: sub get_display_part {
1.324     albertel  189:     my ($partID,$symb)=@_;
1.207     albertel  190:     my $display=&Apache::lonnet::EXT('resource.'.$partID.'.display',$symb);
                    191:     if (defined($display) and $display ne '') {
1.577     bisitz    192:         $display.= ' (<span class="LC_internal_info">'
                    193:                   .&mt('Part ID: [_1]',$partID).'</span>)';
1.207     albertel  194:     } else {
                    195: 	$display=$partID;
                    196:     }
                    197:     return $display;
                    198: }
1.269     raeburn   199: 
1.434     albertel  200: sub reset_caches {
                    201:     &reset_analyze_cache();
                    202:     &reset_perm();
                    203: }
                    204: 
                    205: {
                    206:     my %analyze_cache;
1.557     raeburn   207:     my %analyze_cache_formkeys;
1.148     albertel  208: 
1.434     albertel  209:     sub reset_analyze_cache {
                    210: 	undef(%analyze_cache);
1.557     raeburn   211:         undef(%analyze_cache_formkeys);
1.434     albertel  212:     }
                    213: 
                    214:     sub get_analyze {
1.557     raeburn   215: 	my ($symb,$uname,$udom,$no_increment,$add_to_hash)=@_;
1.434     albertel  216: 	my $key = "$symb\0$uname\0$udom";
1.557     raeburn   217: 	if (exists($analyze_cache{$key})) {
                    218:             my $getupdate = 0;
                    219:             if (ref($add_to_hash) eq 'HASH') {
                    220:                 foreach my $item (keys(%{$add_to_hash})) {
                    221:                     if (ref($analyze_cache_formkeys{$key}) eq 'HASH') {
                    222:                         if (!exists($analyze_cache_formkeys{$key}{$item})) {
                    223:                             $getupdate = 1;
                    224:                             last;
                    225:                         }
                    226:                     } else {
                    227:                         $getupdate = 1;
                    228:                     }
                    229:                 }
                    230:             }
                    231:             if (!$getupdate) {
                    232:                 return $analyze_cache{$key};
                    233:             }
                    234:         }
1.434     albertel  235: 
                    236: 	my (undef,undef,$url)=&Apache::lonnet::decode_symb($symb);
                    237: 	$url=&Apache::lonnet::clutter($url);
1.557     raeburn   238:         my %form = ('grade_target'      => 'analyze',
                    239:                     'grade_domain'      => $udom,
                    240:                     'grade_symb'        => $symb,
                    241:                     'grade_courseid'    =>  $env{'request.course.id'},
                    242:                     'grade_username'    => $uname,
                    243:                     'grade_noincrement' => $no_increment);
                    244:         if (ref($add_to_hash)) {
                    245:             %form = (%form,%{$add_to_hash});
                    246:         } 
                    247: 	my $subresult=&ssi_with_retries($url, $ssi_retries,%form);
1.434     albertel  248: 	(undef,$subresult)=split(/_HASH_REF__/,$subresult,2);
                    249: 	my %analyze=&Apache::lonnet::str2hash($subresult);
1.557     raeburn   250:         if (ref($add_to_hash) eq 'HASH') {
                    251:             $analyze_cache_formkeys{$key} = $add_to_hash;
                    252:         } else {
                    253:             $analyze_cache_formkeys{$key} = {};
                    254:         }
1.434     albertel  255: 	return $analyze_cache{$key} = \%analyze;
                    256:     }
                    257: 
                    258:     sub get_order {
1.525     raeburn   259: 	my ($partid,$respid,$symb,$uname,$udom,$no_increment)=@_;
                    260: 	my $analyze = &get_analyze($symb,$uname,$udom,$no_increment);
1.434     albertel  261: 	return $analyze->{"$partid.$respid.shown"};
                    262:     }
                    263: 
                    264:     sub get_radiobutton_correct_foil {
                    265: 	my ($partid,$respid,$symb,$uname,$udom)=@_;
                    266: 	my $analyze = &get_analyze($symb,$uname,$udom);
1.555     raeburn   267:         my $foils = &get_order($partid,$respid,$symb,$uname,$udom);
                    268:         if (ref($foils) eq 'ARRAY') {
                    269: 	    foreach my $foil (@{$foils}) {
                    270: 	        if ($analyze->{"$partid.$respid.foil.value.$foil"} eq 'true') {
                    271: 		    return $foil;
                    272: 	        }
1.434     albertel  273: 	    }
                    274: 	}
                    275:     }
1.554     raeburn   276: 
                    277:     sub scantron_partids_tograde {
1.557     raeburn   278:         my ($resource,$cid,$uname,$udom,$check_for_randomlist) = @_;
1.554     raeburn   279:         my (%analysis,@parts);
                    280:         if (ref($resource)) {
                    281:             my $symb = $resource->symb();
1.557     raeburn   282:             my $add_to_form;
                    283:             if ($check_for_randomlist) {
                    284:                 $add_to_form = { 'check_parts_withrandomlist' => 1,};
                    285:             }
                    286:             my $analyze = &get_analyze($symb,$uname,$udom,undef,$add_to_form);
1.554     raeburn   287:             if (ref($analyze) eq 'HASH') {
                    288:                 %analysis = %{$analyze};
                    289:             }
                    290:             if (ref($analysis{'parts'}) eq 'ARRAY') {
                    291:                 foreach my $part (@{$analysis{'parts'}}) {
                    292:                     my ($id,$respid) = split(/\./,$part);
                    293:                     if (!&Apache::loncommon::check_if_partid_hidden($id,$symb,$udom,$uname)) {
                    294:                         push(@parts,$part);
                    295:                     }
                    296:                 }
                    297:             }
                    298:         }
                    299:         return (\%analysis,\@parts);
                    300:     }
                    301: 
1.148     albertel  302: }
1.434     albertel  303: 
1.118     ng        304: #--- Clean response type for display
1.335     albertel  305: #--- Currently filters option/rank/radiobutton/match/essay/Task
                    306: #        response types only.
1.118     ng        307: sub cleanRecord {
1.336     albertel  308:     my ($answer,$response,$symb,$partid,$respid,$record,$order,$version,
                    309: 	$uname,$udom) = @_;
1.398     albertel  310:     my $grayFont = '<span class="LC_internal_info">';
1.148     albertel  311:     if ($response =~ /^(option|rank)$/) {
                    312: 	my %answer=&Apache::lonnet::str2hash($answer);
                    313: 	my %grading=&Apache::lonnet::str2hash($record->{$version."resource.$partid.$respid.submissiongrading"});
                    314: 	my ($toprow,$bottomrow);
                    315: 	foreach my $foil (@$order) {
                    316: 	    if ($grading{$foil} == 1) {
                    317: 		$toprow.='<td><b>'.$answer{$foil}.'&nbsp;</b></td>';
                    318: 	    } else {
                    319: 		$toprow.='<td><i>'.$answer{$foil}.'&nbsp;</i></td>';
                    320: 	    }
1.398     albertel  321: 	    $bottomrow.='<td>'.$grayFont.$foil.'</span>&nbsp;</td>';
1.148     albertel  322: 	}
                    323: 	return '<blockquote><table border="1">'.
1.466     albertel  324: 	    '<tr valign="top"><td>'.&mt('Answer').'</td>'.$toprow.'</tr>'.
                    325: 	    '<tr valign="top"><td>'.$grayFont.&mt('Option ID').'</span></td>'.
1.148     albertel  326: 	    $grayFont.$bottomrow.'</tr>'.'</table></blockquote>';
                    327:     } elsif ($response eq 'match') {
                    328: 	my %answer=&Apache::lonnet::str2hash($answer);
                    329: 	my %grading=&Apache::lonnet::str2hash($record->{$version."resource.$partid.$respid.submissiongrading"});
                    330: 	my @items=&Apache::lonnet::str2array($record->{$version."resource.$partid.$respid.submissionitems"});
                    331: 	my ($toprow,$middlerow,$bottomrow);
                    332: 	foreach my $foil (@$order) {
                    333: 	    my $item=shift(@items);
                    334: 	    if ($grading{$foil} == 1) {
                    335: 		$toprow.='<td><b>'.$item.'&nbsp;</b></td>';
1.398     albertel  336: 		$middlerow.='<td><b>'.$grayFont.$answer{$foil}.'&nbsp;</span></b></td>';
1.148     albertel  337: 	    } else {
                    338: 		$toprow.='<td><i>'.$item.'&nbsp;</i></td>';
1.398     albertel  339: 		$middlerow.='<td><i>'.$grayFont.$answer{$foil}.'&nbsp;</span></i></td>';
1.148     albertel  340: 	    }
1.398     albertel  341: 	    $bottomrow.='<td>'.$grayFont.$foil.'</span>&nbsp;</td>';
1.118     ng        342: 	}
1.126     ng        343: 	return '<blockquote><table border="1">'.
1.466     albertel  344: 	    '<tr valign="top"><td>'.&mt('Answer').'</td>'.$toprow.'</tr>'.
                    345: 	    '<tr valign="top"><td>'.$grayFont.&mt('Item ID').'</span></td>'.
1.148     albertel  346: 	    $middlerow.'</tr>'.
1.466     albertel  347: 	    '<tr valign="top"><td>'.$grayFont.&mt('Option ID').'</span></td>'.
1.148     albertel  348: 	    $bottomrow.'</tr>'.'</table></blockquote>';
                    349:     } elsif ($response eq 'radiobutton') {
                    350: 	my %answer=&Apache::lonnet::str2hash($answer);
                    351: 	my ($toprow,$bottomrow);
1.434     albertel  352: 	my $correct = 
                    353: 	    &get_radiobutton_correct_foil($partid,$respid,$symb,$uname,$udom);
                    354: 	foreach my $foil (@$order) {
1.148     albertel  355: 	    if (exists($answer{$foil})) {
1.434     albertel  356: 		if ($foil eq $correct) {
1.466     albertel  357: 		    $toprow.='<td><b>'.&mt('true').'</b></td>';
1.148     albertel  358: 		} else {
1.466     albertel  359: 		    $toprow.='<td><i>'.&mt('true').'</i></td>';
1.148     albertel  360: 		}
                    361: 	    } else {
1.466     albertel  362: 		$toprow.='<td>'.&mt('false').'</td>';
1.148     albertel  363: 	    }
1.398     albertel  364: 	    $bottomrow.='<td>'.$grayFont.$foil.'</span>&nbsp;</td>';
1.148     albertel  365: 	}
                    366: 	return '<blockquote><table border="1">'.
1.466     albertel  367: 	    '<tr valign="top"><td>'.&mt('Answer').'</td>'.$toprow.'</tr>'.
                    368: 	    '<tr valign="top"><td>'.$grayFont.&mt('Option ID').'</span></td>'.
1.597     wenzelju  369: 	    $bottomrow.'</tr>'.'</table></blockquote>';
1.148     albertel  370:     } elsif ($response eq 'essay') {
1.257     albertel  371: 	if (! exists ($env{'form.'.$symb})) {
1.122     ng        372: 	    my (%keyhash) = &Apache::lonnet::dump('nohist_handgrade',
1.257     albertel  373: 						  $env{'course.'.$env{'request.course.id'}.'.domain'},
                    374: 						  $env{'course.'.$env{'request.course.id'}.'.num'});
1.122     ng        375: 
1.257     albertel  376: 	    my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
                    377: 	    $env{'form.keywords'} = $keyhash{$symb.'_keywords'} ne '' ? $keyhash{$symb.'_keywords'} : '';
                    378: 	    $env{'form.kwclr'}    = $keyhash{$loginuser.'_kwclr'} ne '' ? $keyhash{$loginuser.'_kwclr'} : 'red';
                    379: 	    $env{'form.kwsize'}   = $keyhash{$loginuser.'_kwsize'} ne '' ? $keyhash{$loginuser.'_kwsize'} : '0';
                    380: 	    $env{'form.kwstyle'}  = $keyhash{$loginuser.'_kwstyle'} ne '' ? $keyhash{$loginuser.'_kwstyle'} : '';
                    381: 	    $env{'form.'.$symb} = 1; # so that we don't have to read it from disk for multiple sub of the same prob.
1.122     ng        382: 	}
1.166     albertel  383: 	$answer =~ s-\n-<br />-g;
                    384: 	return '<br /><br /><blockquote><tt>'.&keywords_highlight($answer).'</tt></blockquote>';
1.268     albertel  385:     } elsif ( $response eq 'organic') {
                    386: 	my $result='Smile representation: "<tt>'.$answer.'</tt>"';
                    387: 	my $jme=$record->{$version."resource.$partid.$respid.molecule"};
                    388: 	$result.=&Apache::chemresponse::jme_img($jme,$answer,400);
                    389: 	return $result;
1.335     albertel  390:     } elsif ( $response eq 'Task') {
                    391: 	if ( $answer eq 'SUBMITTED') {
                    392: 	    my $files = $record->{$version."resource.$respid.$partid.bridgetask.portfiles"};
1.336     albertel  393: 	    my $result = &Apache::bridgetask::file_list($files,$uname,$udom);
1.335     albertel  394: 	    return $result;
                    395: 	} elsif ( grep(/^\Q$version\E.*?\.instance$/, keys(%{$record})) ) {
                    396: 	    my @matches = grep(/^\Q$version\E.*?\.instance$/,
                    397: 			       keys(%{$record}));
                    398: 	    return join('<br />',($version,@matches));
                    399: 			       
                    400: 			       
                    401: 	} else {
                    402: 	    my $result =
                    403: 		'<p>'
                    404: 		.&mt('Overall result: [_1]',
                    405: 		     $record->{$version."resource.$respid.$partid.status"})
                    406: 		.'</p>';
                    407: 	    
                    408: 	    $result .= '<ul>';
                    409: 	    my @grade = grep(/^\Q${version}resource.$respid.$partid.\E[^.]*[.]status$/,
                    410: 			     keys(%{$record}));
                    411: 	    foreach my $grade (sort(@grade)) {
                    412: 		my ($dim) = ($grade =~/[.]([^.]+)[.]status$/);
                    413: 		$result.= '<li>'.&mt("Dimension: [_1], status [_2] ",
                    414: 				     $dim, $record->{$grade}).
                    415: 			  '</li>';
                    416: 	    }
                    417: 	    $result.='</ul>';
                    418: 	    return $result;
                    419: 	}
1.440     albertel  420:     } elsif ( $response =~ m/(?:numerical|formula)/) {
                    421: 	$answer = 
                    422: 	    &Apache::loncommon::format_previous_attempt_value('submission',
                    423: 							      $answer);
1.122     ng        424:     }
1.118     ng        425:     return $answer;
                    426: }
                    427: 
                    428: #-- A couple of common js functions
                    429: sub commonJSfunctions {
                    430:     my $request = shift;
1.597     wenzelju  431:     $request->print(&Apache::lonhtmlcommon::scripttag(<<COMMONJSFUNCTIONS));
1.118     ng        432:     function radioSelection(radioButton) {
                    433: 	var selection=null;
                    434: 	if (radioButton.length > 1) {
                    435: 	    for (var i=0; i<radioButton.length; i++) {
                    436: 		if (radioButton[i].checked) {
                    437: 		    return radioButton[i].value;
                    438: 		}
                    439: 	    }
                    440: 	} else {
                    441: 	    if (radioButton.checked) return radioButton.value;
                    442: 	}
                    443: 	return selection;
                    444:     }
                    445: 
                    446:     function pullDownSelection(selectOne) {
                    447: 	var selection="";
                    448: 	if (selectOne.length > 1) {
                    449: 	    for (var i=0; i<selectOne.length; i++) {
                    450: 		if (selectOne[i].selected) {
                    451: 		    return selectOne[i].value;
                    452: 		}
                    453: 	    }
                    454: 	} else {
1.138     albertel  455:             // only one value it must be the selected one
                    456: 	    return selectOne.value;
1.118     ng        457: 	}
                    458:     }
                    459: COMMONJSFUNCTIONS
                    460: }
                    461: 
1.44      ng        462: #--- Dumps the class list with usernames,list of sections,
                    463: #--- section, ids and fullnames for each user.
                    464: sub getclasslist {
1.449     banghart  465:     my ($getsec,$filterlist,$getgroup) = @_;
1.291     albertel  466:     my @getsec;
1.450     banghart  467:     my @getgroup;
1.442     banghart  468:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
1.291     albertel  469:     if (!ref($getsec)) {
                    470: 	if ($getsec ne '' && $getsec ne 'all') {
                    471: 	    @getsec=($getsec);
                    472: 	}
                    473:     } else {
                    474: 	@getsec=@{$getsec};
                    475:     }
                    476:     if (grep(/^all$/,@getsec)) { undef(@getsec); }
1.450     banghart  477:     if (!ref($getgroup)) {
                    478: 	if ($getgroup ne '' && $getgroup ne 'all') {
                    479: 	    @getgroup=($getgroup);
                    480: 	}
                    481:     } else {
                    482: 	@getgroup=@{$getgroup};
                    483:     }
                    484:     if (grep(/^all$/,@getgroup)) { undef(@getgroup); }
1.291     albertel  485: 
1.449     banghart  486:     my ($classlist,$keylist)=&Apache::loncoursedata::get_classlist();
1.49      albertel  487:     # Bail out if we were unable to get the classlist
1.56      matthew   488:     return if (! defined($classlist));
1.449     banghart  489:     &Apache::loncoursedata::get_group_memberships($classlist,$keylist);
1.56      matthew   490:     #
                    491:     my %sections;
                    492:     my %fullnames;
1.205     matthew   493:     foreach my $student (keys(%$classlist)) {
                    494:         my $end      = 
                    495:             $classlist->{$student}->[&Apache::loncoursedata::CL_END()];
                    496:         my $start    = 
                    497:             $classlist->{$student}->[&Apache::loncoursedata::CL_START()];
                    498:         my $id       = 
                    499:             $classlist->{$student}->[&Apache::loncoursedata::CL_ID()];
                    500:         my $section  = 
                    501:             $classlist->{$student}->[&Apache::loncoursedata::CL_SECTION()];
                    502:         my $fullname = 
                    503:             $classlist->{$student}->[&Apache::loncoursedata::CL_FULLNAME()];
                    504:         my $status   = 
                    505:             $classlist->{$student}->[&Apache::loncoursedata::CL_STATUS()];
1.449     banghart  506:         my $group   = 
                    507:             $classlist->{$student}->[&Apache::loncoursedata::CL_GROUP()];
1.76      ng        508: 	# filter students according to status selected
1.442     banghart  509: 	if ($filterlist && (!($stu_status =~ /Any/))) {
                    510: 	    if (!($stu_status =~ $status)) {
1.450     banghart  511: 		delete($classlist->{$student});
1.76      ng        512: 		next;
                    513: 	    }
                    514: 	}
1.450     banghart  515: 	# filter students according to groups selected
1.453     banghart  516: 	my @stu_groups = split(/,/,$group);
1.450     banghart  517: 	if (@getgroup) {
                    518: 	    my $exclude = 1;
1.454     banghart  519: 	    foreach my $grp (@getgroup) {
                    520: 	        foreach my $stu_group (@stu_groups) {
1.453     banghart  521: 	            if ($stu_group eq $grp) {
                    522: 	                $exclude = 0;
                    523:     	            } 
1.450     banghart  524: 	        }
1.453     banghart  525:     	        if (($grp eq 'none') && !$group) {
                    526:         	        $exclude = 0;
                    527:         	}
1.450     banghart  528: 	    }
                    529: 	    if ($exclude) {
                    530: 	        delete($classlist->{$student});
                    531: 	    }
                    532: 	}
1.205     matthew   533: 	$section = ($section ne '' ? $section : 'none');
1.106     albertel  534: 	if (&canview($section)) {
1.291     albertel  535: 	    if (!@getsec || grep(/^\Q$section\E$/,@getsec)) {
1.103     albertel  536: 		$sections{$section}++;
1.450     banghart  537: 		if ($classlist->{$student}) {
                    538: 		    $fullnames{$student}=$fullname;
                    539: 		}
1.103     albertel  540: 	    } else {
1.205     matthew   541: 		delete($classlist->{$student});
1.103     albertel  542: 	    }
                    543: 	} else {
1.205     matthew   544: 	    delete($classlist->{$student});
1.103     albertel  545: 	}
1.44      ng        546:     }
                    547:     my %seen = ();
1.56      matthew   548:     my @sections = sort(keys(%sections));
                    549:     return ($classlist,\@sections,\%fullnames);
1.44      ng        550: }
                    551: 
1.103     albertel  552: sub canmodify {
                    553:     my ($sec)=@_;
                    554:     if ($perm{'mgr'}) {
                    555: 	if (!defined($perm{'mgr_section'})) {
                    556: 	    # can modify whole class
                    557: 	    return 1;
                    558: 	} else {
                    559: 	    if ($sec eq $perm{'mgr_section'}) {
                    560: 		#can modify the requested section
                    561: 		return 1;
                    562: 	    } else {
                    563: 		# can't modify the request section
                    564: 		return 0;
                    565: 	    }
                    566: 	}
                    567:     }
                    568:     #can't modify
                    569:     return 0;
                    570: }
                    571: 
                    572: sub canview {
                    573:     my ($sec)=@_;
                    574:     if ($perm{'vgr'}) {
                    575: 	if (!defined($perm{'vgr_section'})) {
                    576: 	    # can modify whole class
                    577: 	    return 1;
                    578: 	} else {
                    579: 	    if ($sec eq $perm{'vgr_section'}) {
                    580: 		#can modify the requested section
                    581: 		return 1;
                    582: 	    } else {
                    583: 		# can't modify the request section
                    584: 		return 0;
                    585: 	    }
                    586: 	}
                    587:     }
                    588:     #can't modify
                    589:     return 0;
                    590: }
                    591: 
1.44      ng        592: #--- Retrieve the grade status of a student for all the parts
                    593: sub student_gradeStatus {
1.324     albertel  594:     my ($symb,$udom,$uname,$partlist) = @_;
1.257     albertel  595:     my %record     = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
1.44      ng        596:     my %partstatus = ();
                    597:     foreach (@$partlist) {
1.128     ng        598: 	my ($status,undef)   = split(/_/,$record{"resource.$_.solved"},2);
1.44      ng        599: 	$status              = 'nothing' if ($status eq '');
                    600: 	$partstatus{$_}      = $status;
                    601: 	my $subkey           = "resource.$_.submitted_by";
                    602: 	$partstatus{$subkey} = $record{$subkey} if ($record{$subkey} ne '');
                    603:     }
                    604:     return %partstatus;
                    605: }
                    606: 
1.45      ng        607: # hidden form and javascript that calls the form
                    608: # Use by verifyscript and viewgrades
                    609: # Shows a student's view of problem and submission
                    610: sub jscriptNform {
1.324     albertel  611:     my ($symb) = @_;
1.442     banghart  612:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
1.597     wenzelju  613:     my $jscript= &Apache::lonhtmlcommon::scripttag(
1.45      ng        614: 	'    function viewOneStudent(user,domain) {'."\n".
                    615: 	'	document.onestudent.student.value = user;'."\n".
                    616: 	'	document.onestudent.userdom.value = domain;'."\n".
                    617: 	'	document.onestudent.submit();'."\n".
                    618: 	'    }'."\n".
1.597     wenzelju  619: 	"\n");
1.45      ng        620:     $jscript.= '<form action="/adm/grades" method="post" name="onestudent">'."\n".
1.418     albertel  621: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.442     banghart  622: 	'<input type="hidden" name="Status"  value="'.$stu_status.'" />'."\n".
1.45      ng        623: 	'<input type="hidden" name="command" value="submission" />'."\n".
                    624: 	'<input type="hidden" name="student" value="" />'."\n".
                    625: 	'<input type="hidden" name="userdom" value="" />'."\n".
                    626: 	'</form>'."\n";
                    627:     return $jscript;
                    628: }
1.39      ng        629: 
1.447     foxr      630: 
                    631: 
1.315     bowersj2  632: # Given the score (as a number [0-1] and the weight) what is the final
                    633: # point value? This function will round to the nearest tenth, third,
                    634: # or quarter if one of those is within the tolerance of .00001.
1.316     albertel  635: sub compute_points {
1.315     bowersj2  636:     my ($score, $weight) = @_;
                    637:     
                    638:     my $tolerance = .00001;
                    639:     my $points = $score * $weight;
                    640: 
                    641:     # Check for nearness to 1/x.
                    642:     my $check_for_nearness = sub {
                    643:         my ($factor) = @_;
                    644:         my $num = ($points * $factor) + $tolerance;
                    645:         my $floored_num = floor($num);
1.316     albertel  646:         if ($num - $floored_num < 2 * $tolerance * $factor) {
1.315     bowersj2  647:             return $floored_num / $factor;
                    648:         }
                    649:         return $points;
                    650:     };
                    651: 
                    652:     $points = $check_for_nearness->(10);
                    653:     $points = $check_for_nearness->(3);
                    654:     $points = $check_for_nearness->(4);
                    655:     
                    656:     return $points;
                    657: }
                    658: 
1.44      ng        659: #------------------ End of general use routines --------------------
1.87      www       660: 
                    661: #
                    662: # Find most similar essay
                    663: #
                    664: 
                    665: sub most_similar {
1.426     albertel  666:     my ($uname,$udom,$uessay,$old_essays)=@_;
1.87      www       667: 
                    668: # ignore spaces and punctuation
                    669: 
                    670:     $uessay=~s/\W+/ /gs;
                    671: 
1.282     www       672: # ignore empty submissions (occuring when only files are sent)
                    673: 
1.598     www       674:     unless ($uessay=~/\w+/s) { return ''; }
1.282     www       675: 
1.87      www       676: # these will be returned. Do not care if not at least 50 percent similar
1.88      www       677:     my $limit=0.6;
1.87      www       678:     my $sname='';
                    679:     my $sdom='';
                    680:     my $scrsid='';
                    681:     my $sessay='';
                    682: # go through all essays ...
1.426     albertel  683:     foreach my $tkey (keys(%$old_essays)) {
                    684: 	my ($tname,$tdom,$tcrsid)=map {&unescape($_)} (split(/\./,$tkey));
1.87      www       685: # ... except the same student
1.426     albertel  686:         next if (($tname eq $uname) && ($tdom eq $udom));
                    687: 	my $tessay=$old_essays->{$tkey};
                    688: 	$tessay=~s/\W+/ /gs;
1.87      www       689: # String similarity gives up if not even limit
1.426     albertel  690: 	my $tsimilar=&String::Similarity::similarity($uessay,$tessay,$limit);
1.87      www       691: # Found one
1.426     albertel  692: 	if ($tsimilar>$limit) {
                    693: 	    $limit=$tsimilar;
                    694: 	    $sname=$tname;
                    695: 	    $sdom=$tdom;
                    696: 	    $scrsid=$tcrsid;
                    697: 	    $sessay=$old_essays->{$tkey};
                    698: 	}
1.87      www       699:     }
1.88      www       700:     if ($limit>0.6) {
1.87      www       701:        return ($sname,$sdom,$scrsid,$sessay,$limit);
                    702:     } else {
                    703:        return ('','','','',0);
                    704:     }
                    705: }
                    706: 
1.44      ng        707: #-------------------------------------------------------------------
                    708: 
                    709: #------------------------------------ Receipt Verification Routines
1.45      ng        710: #
1.602     www       711: 
                    712: sub initialverifyreceipt {
1.608     www       713:    my ($request,$symb) = @_;
1.602     www       714:    &commonJSfunctions($request);
1.605     www       715:    return '<form name="gradingMenu"><input type="submit" value="'.&mt('Verify Receipt Number.').'" />'.
1.602     www       716:         &Apache::lonnet::recprefix($env{'request.course.id'}).
                    717:         '-<input type="text" name="receipt" size="4" />'.
1.603     www       718:         '<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
                    719:         '<input type="hidden" name="command" value="verify" />'.
                    720:         "</form>\n";
1.602     www       721: }
                    722: 
1.44      ng        723: #--- Check whether a receipt number is valid.---
                    724: sub verifyreceipt {
1.608     www       725:     my ($request,$symb)  = @_;
1.44      ng        726: 
1.257     albertel  727:     my $courseid = $env{'request.course.id'};
1.184     www       728:     my $receipt  = &Apache::lonnet::recprefix($courseid).'-'.
1.257     albertel  729: 	$env{'form.receipt'};
1.44      ng        730:     $receipt     =~ s/[^\-\d]//g;
                    731: 
1.487     albertel  732:     my $title.=
                    733: 	'<h3><span class="LC_info">'.
1.605     www       734: 	&mt('Verifying Receipt Number [_1]',$receipt).
                    735: 	'</span></h3>'."\n";
1.44      ng        736: 
                    737:     my ($string,$contents,$matches) = ('','',0);
1.56      matthew   738:     my (undef,undef,$fullname) = &getclasslist('all','0');
1.177     albertel  739:     
                    740:     my $receiptparts=0;
1.390     albertel  741:     if ($env{"course.$courseid.receiptalg"} eq 'receipt2' ||
                    742: 	$env{"course.$courseid.receiptalg"} eq 'receipt3') { $receiptparts=1; }
1.177     albertel  743:     my $parts=['0'];
1.582     raeburn   744:     if ($receiptparts) {
                    745:         my $res_error; 
                    746:         ($parts)=&response_type($symb,\$res_error);
                    747:         if ($res_error) {
                    748:             return &navmap_errormsg();
                    749:         } 
                    750:     }
1.486     albertel  751:     
                    752:     my $header = 
                    753: 	&Apache::loncommon::start_data_table().
                    754: 	&Apache::loncommon::start_data_table_header_row().
1.487     albertel  755: 	'<th>&nbsp;'.&mt('Fullname').'&nbsp;</th>'."\n".
                    756: 	'<th>&nbsp;'.&mt('Username').'&nbsp;</th>'."\n".
                    757: 	'<th>&nbsp;'.&mt('Domain').'&nbsp;</th>';
1.486     albertel  758:     if ($receiptparts) {
1.487     albertel  759: 	$header.='<th>&nbsp;'.&mt('Problem Part').'&nbsp;</th>';
1.486     albertel  760:     }
                    761:     $header.=
                    762: 	&Apache::loncommon::end_data_table_header_row();
                    763: 
1.294     albertel  764:     foreach (sort 
                    765: 	     {
                    766: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                    767: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                    768: 		 }
                    769: 		 return $a cmp $b;
                    770: 	     } (keys(%$fullname))) {
1.44      ng        771: 	my ($uname,$udom)=split(/\:/);
1.177     albertel  772: 	foreach my $part (@$parts) {
                    773: 	    if ($receipt eq &Apache::lonnet::ireceipt($uname,$udom,$courseid,$symb,$part)) {
1.486     albertel  774: 		$contents.=
                    775: 		    &Apache::loncommon::start_data_table_row().
                    776: 		    '<td>&nbsp;'."\n".
1.177     albertel  777: 		    '<a href="javascript:viewOneStudent(\''.$uname.'\',\''.$udom.
1.417     albertel  778: 		    '\');" target="_self">'.$$fullname{$_}.'</a>&nbsp;</td>'."\n".
1.177     albertel  779: 		    '<td>&nbsp;'.$uname.'&nbsp;</td>'.
                    780: 		    '<td>&nbsp;'.$udom.'&nbsp;</td>';
                    781: 		if ($receiptparts) {
                    782: 		    $contents.='<td>&nbsp;'.$part.'&nbsp;</td>';
                    783: 		}
1.486     albertel  784: 		$contents.= 
                    785: 		    &Apache::loncommon::end_data_table_row()."\n";
1.177     albertel  786: 		
                    787: 		$matches++;
                    788: 	    }
1.44      ng        789: 	}
                    790:     }
                    791:     if ($matches == 0) {
1.584     bisitz    792:         $string = $title
                    793:                  .'<p class="LC_warning">'
                    794:                  .&mt('No match found for the above receipt number.')
                    795:                  .'</p>';
1.44      ng        796:     } else {
1.324     albertel  797: 	$string = &jscriptNform($symb).$title.
1.487     albertel  798: 	    '<p>'.
1.584     bisitz    799: 	    &mt('The above receipt number matches the following [quant,_1,student].',$matches).
1.487     albertel  800: 	    '</p>'.
1.486     albertel  801: 	    $header.
                    802: 	    $contents.
                    803: 	    &Apache::loncommon::end_data_table()."\n";
1.44      ng        804:     }
1.614     www       805:     return $string;
1.44      ng        806: }
                    807: 
                    808: #--- This is called by a number of programs.
                    809: #--- Called from the Grading Menu - View/Grade an individual student
                    810: #--- Also called directly when one clicks on the subm button 
                    811: #    on the problem page.
1.30      ng        812: sub listStudents {
1.617     www       813:     my ($request,$symb,$submitonly) = @_;
1.49      albertel  814: 
1.257     albertel  815:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
                    816:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
                    817:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
1.449     banghart  818:     my $getgroup  = $env{'form.group'} eq '' ? 'all' : $env{'form.group'};
1.617     www       819:     unless ($submitonly) {
                    820:        $submitonly= $env{'form.submitonly'} eq '' ? 'all' : $env{'form.submitonly'};
                    821:     }
1.49      albertel  822: 
1.548     bisitz    823:     my $result='<h3><span class="LC_info">&nbsp;'
1.618     www       824: 	.&mt("View/Grade/Regrade Submissions for a Student or a Group of Students")
1.485     albertel  825: 	.'</span></h3>';
1.623     www       826:     my $res_error;
                    827:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
1.49      albertel  828: 
1.559     raeburn   829:     my %lt = &Apache::lonlocal::texthash (
                    830: 		'multiple' => 'Please select a student or group of students before clicking on the Next button.',
                    831: 		'single'   => 'Please select the student before clicking on the Next button.',
                    832: 	     );
1.597     wenzelju  833:     $request->print(&Apache::lonhtmlcommon::scripttag(<<LISTJAVASCRIPT));
1.110     ng        834:     function checkSelect(checkBox) {
                    835: 	var ctr=0;
                    836: 	var sense="";
                    837: 	if (checkBox.length > 1) {
                    838: 	    for (var i=0; i<checkBox.length; i++) {
                    839: 		if (checkBox[i].checked) {
                    840: 		    ctr++;
                    841: 		}
                    842: 	    }
1.485     albertel  843: 	    sense = '$lt{'multiple'}';
1.110     ng        844: 	} else {
                    845: 	    if (checkBox.checked) {
                    846: 		ctr = 1;
                    847: 	    }
1.485     albertel  848: 	    sense = '$lt{'single'}';
1.110     ng        849: 	}
                    850: 	if (ctr == 0) {
1.485     albertel  851: 	    alert(sense);
1.110     ng        852: 	    return false;
                    853: 	}
                    854: 	document.gradesub.submit();
                    855:     }
                    856: 
                    857:     function reLoadList(formname) {
1.112     ng        858: 	if (formname.saveStatusOld.value == pullDownSelection(formname.Status)) {return;}
1.110     ng        859: 	formname.command.value = 'submission';
                    860: 	formname.submit();
                    861:     }
1.45      ng        862: LISTJAVASCRIPT
                    863: 
1.118     ng        864:     &commonJSfunctions($request);
1.41      ng        865:     $request->print($result);
1.39      ng        866: 
1.154     albertel  867:     my $gradeTable='<form action="/adm/grades" method="post" name="gradesub">'.
1.598     www       868: 	"\n";
1.485     albertel  869: 	
1.561     bisitz    870:     $gradeTable .= &Apache::lonhtmlcommon::start_pick_box();
                    871:     $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('View Problem Text'))
                    872:                   .'<label><input type="radio" name="vProb" value="no" checked="checked" /> '.&mt('no').' </label>'."\n"
                    873:                   .'<label><input type="radio" name="vProb" value="yes" /> '.&mt('one student').' </label>'."\n"
                    874:                   .'<label><input type="radio" name="vProb" value="all" /> '.&mt('all students').' </label><br />'."\n"
                    875:                   .&Apache::lonhtmlcommon::row_closure();
                    876:     $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('View Answer'))
                    877:                   .'<label><input type="radio" name="vAns" value="no"  /> '.&mt('no').' </label>'."\n"
                    878:                   .'<label><input type="radio" name="vAns" value="yes" /> '.&mt('one student').' </label>'."\n"
                    879:                   .'<label><input type="radio" name="vAns" value="all" checked="checked" /> '.&mt('all students').' </label><br />'."\n"
                    880:                   .&Apache::lonhtmlcommon::row_closure();
1.485     albertel  881: 
                    882:     my $submission_options;
1.442     banghart  883:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
                    884:     my $saveStatus = $stu_status eq '' ? 'Active' : $stu_status;
1.257     albertel  885:     $env{'form.Status'} = $saveStatus;
1.485     albertel  886:     $submission_options.=
1.592     bisitz    887:         '<span class="LC_nobreak">'.
1.624     www       888:         '<label><input type="radio" name="lastSub" value="lastonly" /> '.
1.592     bisitz    889:         &mt('last submission only').' </label></span>'."\n".
                    890:         '<span class="LC_nobreak">'.
                    891:         '<label><input type="radio" name="lastSub" value="last" /> '.
                    892:         &mt('last submission &amp; parts info').' </label></span>'."\n".
                    893:         '<span class="LC_nobreak">'.
1.628     www       894:         '<label><input type="radio" name="lastSub" value="datesub" checked="checked" /> '.
1.592     bisitz    895:         &mt('by dates and submissions').'</label></span>'."\n".
                    896:         '<span class="LC_nobreak">'.
                    897:         '<label><input type="radio" name="lastSub" value="all" /> '.
                    898:         &mt('all details').'</label></span>';
1.561     bisitz    899:     $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('Submissions'))
                    900:                   .$submission_options
                    901:                   .&Apache::lonhtmlcommon::row_closure();
                    902: 
                    903:     $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('Grading Increments'))
                    904:                   .'<select name="increment">'
                    905:                   .'<option value="1">'.&mt('Whole Points').'</option>'
                    906:                   .'<option value=".5">'.&mt('Half Points').'</option>'
                    907:                   .'<option value=".25">'.&mt('Quarter Points').'</option>'
                    908:                   .'<option value=".1">'.&mt('Tenths of a Point').'</option>'
                    909:                   .'</select>'
                    910:                   .&Apache::lonhtmlcommon::row_closure();
1.485     albertel  911: 
                    912:     $gradeTable .= 
1.432     banghart  913:         &build_section_inputs().
1.45      ng        914: 	'<input type="hidden" name="submitonly"  value="'.$submitonly.'" />'."\n".
1.418     albertel  915: 	'<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.110     ng        916: 	'<input type="hidden" name="saveStatusOld" value="'.$saveStatus.'" />'."\n";
                    917: 
1.618     www       918:     if (exists($env{'form.Status'})) {
1.561     bisitz    919: 	$gradeTable .= '<input type="hidden" name="Status" value="'.$stu_status.'" />'."\n";
1.124     ng        920:     } else {
1.561     bisitz    921:         $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('Student Status'))
                    922:                       .&Apache::lonhtmlcommon::StatusOptions(
                    923:                            $saveStatus,undef,1,'javascript:reLoadList(this.form);')
                    924:                       .&Apache::lonhtmlcommon::row_closure();
1.124     ng        925:     }
1.112     ng        926: 
1.561     bisitz    927:     $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('Check For Plagiarism'))
                    928:                   .'<input type="checkbox" name="checkPlag" checked="checked" />'
                    929:                   .&Apache::lonhtmlcommon::row_closure(1)
                    930:                   .&Apache::lonhtmlcommon::end_pick_box();
                    931: 
                    932:     $gradeTable .= '<p>'
1.618     www       933:                   .&mt("To view/grade/regrade a submission or a group of submissions, click on the check box(es) next to the student's name(s). Then click on the Next button.")."\n"
1.561     bisitz    934:                   .'<input type="hidden" name="command" value="processGroup" />'
                    935:                   .'</p>';
1.249     albertel  936: 
                    937: # checkall buttons
                    938:     $gradeTable.=&check_script('gradesub', 'stuinfo');
1.110     ng        939:     $gradeTable.='<input type="button" '."\n".
1.589     bisitz    940:         'onclick="javascript:checkSelect(this.form.stuinfo);" '."\n".
                    941:         'value="'.&mt('Next').' &rarr;" /> <br />'."\n";
1.249     albertel  942:     $gradeTable.=&check_buttons();
1.450     banghart  943:     my ($classlist, undef, $fullname) = &getclasslist($getsec,'1',$getgroup);
1.474     albertel  944:     $gradeTable.= &Apache::loncommon::start_data_table().
                    945: 	&Apache::loncommon::start_data_table_header_row();
1.110     ng        946:     my $loop = 0;
                    947:     while ($loop < 2) {
1.485     albertel  948: 	$gradeTable.='<th>'.&mt('No.').'</th><th>'.&mt('Select').'</th>'.
                    949: 	    '<th>'.&nameUserString('header').'&nbsp;'.&mt('Section/Group').'</th>';
1.618     www       950: 	if (($submitonly ne 'queued') && ($submitonly ne 'all')) {
1.485     albertel  951: 	    foreach my $part (sort(@$partlist)) {
                    952: 		my $display_part=
                    953: 		    &get_display_part((split(/_/,$part))[0],$symb);
                    954: 		$gradeTable.=
                    955: 		    '<th>'.&mt('Part: [_1] Status',$display_part).'</th>';
1.110     ng        956: 	    }
1.301     albertel  957: 	} elsif ($submitonly eq 'queued') {
1.474     albertel  958: 	    $gradeTable.='<th>'.&mt('Queue Status').'&nbsp;</th>';
1.110     ng        959: 	}
                    960: 	$loop++;
1.126     ng        961: #	$gradeTable.='<td></td>' if ($loop%2 ==1);
1.41      ng        962:     }
1.474     albertel  963:     $gradeTable.=&Apache::loncommon::end_data_table_header_row()."\n";
1.41      ng        964: 
1.45      ng        965:     my $ctr = 0;
1.294     albertel  966:     foreach my $student (sort 
                    967: 			 {
                    968: 			     if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                    969: 				 return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                    970: 			     }
                    971: 			     return $a cmp $b;
                    972: 			 }
                    973: 			 (keys(%$fullname))) {
1.41      ng        974: 	my ($uname,$udom) = split(/:/,$student);
1.301     albertel  975: 
1.110     ng        976: 	my %status = ();
1.301     albertel  977: 
                    978: 	if ($submitonly eq 'queued') {
                    979: 	    my %queue_status = 
                    980: 		&Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
                    981: 							$udom,$uname);
                    982: 	    next if (!defined($queue_status{'gradingqueue'}));
                    983: 	    $status{'gradingqueue'} = $queue_status{'gradingqueue'};
                    984: 	}
                    985: 
1.618     www       986: 	if (($submitonly ne 'queued') && ($submitonly ne 'all')) {
1.324     albertel  987: 	    (%status) =&student_gradeStatus($symb,$udom,$uname,$partlist);
1.145     albertel  988: 	    my $submitted = 0;
1.164     albertel  989: 	    my $graded = 0;
1.248     albertel  990: 	    my $incorrect = 0;
1.110     ng        991: 	    foreach (keys(%status)) {
1.145     albertel  992: 		$submitted = 1 if ($status{$_} ne 'nothing');
1.248     albertel  993: 		$graded = 1 if ($status{$_} =~ /^ungraded/);
                    994: 		$incorrect = 1 if ($status{$_} =~ /^incorrect/);
                    995: 		
1.110     ng        996: 		my ($foo,$partid,$foo1) = split(/\./,$_);
                    997: 		if ($status{'resource.'.$partid.'.submitted_by'} ne '') {
1.145     albertel  998: 		    $submitted = 0;
1.150     albertel  999: 		    my ($part)=split(/\./,$partid);
1.110     ng       1000: 		    $gradeTable.='<input type="hidden" name="'.
1.150     albertel 1001: 			$student.':'.$part.':submitted_by" value="'.
1.110     ng       1002: 			$status{'resource.'.$partid.'.submitted_by'}.'" />';
                   1003: 		}
1.41      ng       1004: 	    }
1.248     albertel 1005: 	    
1.156     albertel 1006: 	    next if (!$submitted && ($submitonly eq 'yes' ||
                   1007: 				     $submitonly eq 'incorrect' ||
                   1008: 				     $submitonly eq 'graded'));
1.248     albertel 1009: 	    next if (!$graded && ($submitonly eq 'graded'));
                   1010: 	    next if (!$incorrect && $submitonly eq 'incorrect');
1.41      ng       1011: 	}
1.34      ng       1012: 
1.45      ng       1013: 	$ctr++;
1.249     albertel 1014: 	my $section = $classlist->{$student}->[&Apache::loncoursedata::CL_SECTION()];
1.452     banghart 1015:         my $group = $classlist->{$student}->[&Apache::loncoursedata::CL_GROUP()];
1.104     albertel 1016: 	if ( $perm{'vgr'} eq 'F' ) {
1.474     albertel 1017: 	    if ($ctr%2 ==1) {
                   1018: 		$gradeTable.= &Apache::loncommon::start_data_table_row();
                   1019: 	    }
1.126     ng       1020: 	    $gradeTable.='<td align="right">'.$ctr.'&nbsp;</td>'.
1.563     bisitz   1021:                '<td align="center"><label><input type="checkbox" name="stuinfo" value="'.
1.249     albertel 1022:                $student.':'.$$fullname{$student}.':::SECTION'.$section.
                   1023: 	       ')&nbsp;" />&nbsp;&nbsp;</label></td>'."\n".'<td>'.
                   1024: 	       &nameUserString(undef,$$fullname{$student},$uname,$udom).
1.474     albertel 1025: 	       '&nbsp;'.$section.($group ne '' ?'/'.$group:'').'</td>'."\n";
1.110     ng       1026: 
1.618     www      1027: 	    if ($submitonly ne 'all') {
1.524     raeburn  1028: 		foreach (sort(keys(%status))) {
1.485     albertel 1029: 		    next if ($_ =~ /^resource.*?submitted_by$/);
                   1030: 		    $gradeTable.='<td align="center">&nbsp;'.&mt($status{$_}).'&nbsp;</td>'."\n";
1.110     ng       1031: 		}
1.41      ng       1032: 	    }
1.126     ng       1033: #	    $gradeTable.='<td></td>' if ($ctr%2 ==1);
1.474     albertel 1034: 	    if ($ctr%2 ==0) {
                   1035: 		$gradeTable.=&Apache::loncommon::end_data_table_row()."\n";
                   1036: 	    }
1.41      ng       1037: 	}
                   1038:     }
1.110     ng       1039:     if ($ctr%2 ==1) {
1.126     ng       1040: 	$gradeTable.='<td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td>';
1.618     www      1041: 	    if (($submitonly ne 'queued') && ($submitonly ne 'all')) {
1.110     ng       1042: 		foreach (@$partlist) {
                   1043: 		    $gradeTable.='<td>&nbsp;</td>';
                   1044: 		}
1.301     albertel 1045: 	    } elsif ($submitonly eq 'queued') {
                   1046: 		$gradeTable.='<td>&nbsp;</td>';
1.110     ng       1047: 	    }
1.474     albertel 1048: 	$gradeTable.=&Apache::loncommon::end_data_table_row();
1.110     ng       1049:     }
                   1050: 
1.474     albertel 1051:     $gradeTable.=&Apache::loncommon::end_data_table()."\n".
1.589     bisitz   1052:         '<input type="button" '.
                   1053:         'onclick="javascript:checkSelect(this.form.stuinfo);" '.
                   1054:         'value="'.&mt('Next').' &rarr;" /></form>'."\n";
1.45      ng       1055:     if ($ctr == 0) {
1.96      albertel 1056: 	my $num_students=(scalar(keys(%$fullname)));
                   1057: 	if ($num_students eq 0) {
1.485     albertel 1058: 	    $gradeTable='<br />&nbsp;<span class="LC_warning">'.&mt('There are no students currently enrolled.').'</span>';
1.96      albertel 1059: 	} else {
1.171     albertel 1060: 	    my $submissions='submissions';
                   1061: 	    if ($submitonly eq 'incorrect') { $submissions = 'incorrect submissions'; }
                   1062: 	    if ($submitonly eq 'graded'   ) { $submissions = 'ungraded submissions'; }
1.301     albertel 1063: 	    if ($submitonly eq 'queued'   ) { $submissions = 'queued submissions'; }
1.398     albertel 1064: 	    $gradeTable='<br />&nbsp;<span class="LC_warning">'.
1.485     albertel 1065: 		&mt('No '.$submissions.' found for this resource for any students. ([_1] students checked for '.$submissions.')',
                   1066: 		    $num_students).
                   1067: 		'</span><br />';
1.96      albertel 1068: 	}
1.46      ng       1069:     } elsif ($ctr == 1) {
1.474     albertel 1070: 	$gradeTable =~ s/type="checkbox"/type="checkbox" checked="checked"/;
1.45      ng       1071:     }
                   1072:     $request->print($gradeTable);
1.44      ng       1073:     return '';
1.10      ng       1074: }
                   1075: 
1.44      ng       1076: #---- Called from the listStudents routine
1.249     albertel 1077: 
                   1078: sub check_script {
                   1079:     my ($form, $type)=@_;
1.597     wenzelju 1080:     my $chkallscript= &Apache::lonhtmlcommon::scripttag('
1.249     albertel 1081:     function checkall() {
                   1082:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
                   1083:             ele = document.forms.'.$form.'.elements[i];
                   1084:             if (ele.name == "'.$type.'") {
                   1085:             document.forms.'.$form.'.elements[i].checked=true;
                   1086:                                        }
                   1087:         }
                   1088:     }
                   1089: 
                   1090:     function checksec() {
                   1091:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
                   1092:             ele = document.forms.'.$form.'.elements[i];
                   1093:            string = document.forms.'.$form.'.chksec.value;
                   1094:            if
                   1095:           (ele.value.indexOf(":::SECTION"+string)>0) {
                   1096:               document.forms.'.$form.'.elements[i].checked=true;
                   1097:             }
                   1098:         }
                   1099:     }
                   1100: 
                   1101: 
                   1102:     function uncheckall() {
                   1103:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
                   1104:             ele = document.forms.'.$form.'.elements[i];
                   1105:             if (ele.name == "'.$type.'") {
                   1106:             document.forms.'.$form.'.elements[i].checked=false;
                   1107:                                        }
                   1108:         }
                   1109:     }
                   1110: 
1.597     wenzelju 1111: '."\n");
1.249     albertel 1112:     return $chkallscript;
                   1113: }
                   1114: 
                   1115: sub check_buttons {
1.485     albertel 1116:     my $buttons.='<input type="button" onclick="checkall()" value="'.&mt('Check All').'" />';
                   1117:     $buttons.='<input type="button" onclick="uncheckall()" value="'.&mt('Uncheck All').'" />&nbsp;';
                   1118:     $buttons.='<input type="button" onclick="checksec()" value="'.&mt('Check Section/Group').'" />';
1.249     albertel 1119:     $buttons.='<input type="text" size="5" name="chksec" />&nbsp;';
                   1120:     return $buttons;
                   1121: }
                   1122: 
1.44      ng       1123: #     Displays the submissions for one student or a group of students
1.34      ng       1124: sub processGroup {
1.619     www      1125:     my ($request,$symb)  = @_;
1.41      ng       1126:     my $ctr        = 0;
1.155     albertel 1127:     my @stuchecked = &Apache::loncommon::get_env_multiple('form.stuinfo');
1.41      ng       1128:     my $total      = scalar(@stuchecked)-1;
1.45      ng       1129: 
1.396     banghart 1130:     foreach my $student (@stuchecked) {
                   1131: 	my ($uname,$udom,$fullname) = split(/:/,$student);
1.257     albertel 1132: 	$env{'form.student'}        = $uname;
                   1133: 	$env{'form.userdom'}        = $udom;
                   1134: 	$env{'form.fullname'}       = $fullname;
1.619     www      1135: 	&submission($request,$ctr,$total,$symb);
1.41      ng       1136: 	$ctr++;
                   1137:     }
                   1138:     return '';
1.35      ng       1139: }
1.34      ng       1140: 
1.44      ng       1141: #------------------------------------------------------------------------------------
                   1142: #
                   1143: #-------------------------- Next few routines handles grading by student, essentially
                   1144: #                           handles essay response type problem/part
                   1145: #
                   1146: #--- Javascript to handle the submission page functionality ---
                   1147: sub sub_page_js {
                   1148:     my $request = shift;
1.539     riegler  1149: 	    my $alertmsg = &mt('A number equal or greater than 0 is expected. Entered value = ');
1.597     wenzelju 1150:     $request->print(&Apache::lonhtmlcommon::scripttag(<<SUBJAVASCRIPT));
1.71      ng       1151:     function updateRadio(formname,id,weight) {
1.125     ng       1152: 	var gradeBox = formname["GD_BOX"+id];
                   1153: 	var radioButton = formname["RADVAL"+id];
                   1154: 	var oldpts = formname["oldpts"+id].value;
1.72      ng       1155: 	var pts = checkSolved(formname,id) == 'update' ? gradeBox.value : oldpts;
1.71      ng       1156: 	gradeBox.value = pts;
                   1157: 	var resetbox = false;
                   1158: 	if (isNaN(pts) || pts < 0) {
1.539     riegler  1159: 	    alert("$alertmsg"+pts);
1.71      ng       1160: 	    for (var i=0; i<radioButton.length; i++) {
                   1161: 		if (radioButton[i].checked) {
                   1162: 		    gradeBox.value = i;
                   1163: 		    resetbox = true;
                   1164: 		}
                   1165: 	    }
                   1166: 	    if (!resetbox) {
                   1167: 		formtextbox.value = "";
                   1168: 	    }
                   1169: 	    return;
1.44      ng       1170: 	}
1.71      ng       1171: 
                   1172: 	if (pts > weight) {
                   1173: 	    var resp = confirm("You entered a value ("+pts+
                   1174: 			       ") greater than the weight for the part. Accept?");
                   1175: 	    if (resp == false) {
1.125     ng       1176: 		gradeBox.value = oldpts;
1.71      ng       1177: 		return;
                   1178: 	    }
1.44      ng       1179: 	}
1.13      albertel 1180: 
1.71      ng       1181: 	for (var i=0; i<radioButton.length; i++) {
                   1182: 	    radioButton[i].checked=false;
                   1183: 	    if (pts == i && pts != "") {
                   1184: 		radioButton[i].checked=true;
                   1185: 	    }
                   1186: 	}
                   1187: 	updateSelect(formname,id);
1.125     ng       1188: 	formname["stores"+id].value = "0";
1.41      ng       1189:     }
1.5       albertel 1190: 
1.72      ng       1191:     function writeBox(formname,id,pts) {
1.125     ng       1192: 	var gradeBox = formname["GD_BOX"+id];
1.71      ng       1193: 	if (checkSolved(formname,id) == 'update') {
                   1194: 	    gradeBox.value = pts;
                   1195: 	} else {
1.125     ng       1196: 	    var oldpts = formname["oldpts"+id].value;
1.72      ng       1197: 	    gradeBox.value = oldpts;
1.125     ng       1198: 	    var radioButton = formname["RADVAL"+id];
1.71      ng       1199: 	    for (var i=0; i<radioButton.length; i++) {
                   1200: 		radioButton[i].checked=false;
1.72      ng       1201: 		if (i == oldpts) {
1.71      ng       1202: 		    radioButton[i].checked=true;
                   1203: 		}
                   1204: 	    }
1.41      ng       1205: 	}
1.125     ng       1206: 	formname["stores"+id].value = "0";
1.71      ng       1207: 	updateSelect(formname,id);
                   1208: 	return;
1.41      ng       1209:     }
1.44      ng       1210: 
1.71      ng       1211:     function clearRadBox(formname,id) {
                   1212: 	if (checkSolved(formname,id) == 'noupdate') {
                   1213: 	    updateSelect(formname,id);
                   1214: 	    return;
                   1215: 	}
1.125     ng       1216: 	gradeSelect = formname["GD_SEL"+id];
1.71      ng       1217: 	for (var i=0; i<gradeSelect.length; i++) {
                   1218: 	    if (gradeSelect[i].selected) {
                   1219: 		var selectx=i;
                   1220: 	    }
                   1221: 	}
1.125     ng       1222: 	var stores = formname["stores"+id];
1.71      ng       1223: 	if (selectx == stores.value) { return };
1.125     ng       1224: 	var gradeBox = formname["GD_BOX"+id];
1.71      ng       1225: 	gradeBox.value = "";
1.125     ng       1226: 	var radioButton = formname["RADVAL"+id];
1.71      ng       1227: 	for (var i=0; i<radioButton.length; i++) {
                   1228: 	    radioButton[i].checked=false;
                   1229: 	}
                   1230: 	stores.value = selectx;
                   1231:     }
1.5       albertel 1232: 
1.71      ng       1233:     function checkSolved(formname,id) {
1.125     ng       1234: 	if (formname["solved"+id].value == "correct_by_student" && formname.overRideScore.value == 'no') {
1.118     ng       1235: 	    var reply = confirm("This problem has been graded correct by the computer. Do you want to change the score?");
                   1236: 	    if (!reply) {return "noupdate";}
1.120     ng       1237: 	    formname.overRideScore.value = 'yes';
1.41      ng       1238: 	}
1.71      ng       1239: 	return "update";
1.13      albertel 1240:     }
1.71      ng       1241: 
                   1242:     function updateSelect(formname,id) {
1.125     ng       1243: 	formname["GD_SEL"+id][0].selected = true;
1.71      ng       1244: 	return;
1.41      ng       1245:     }
1.33      ng       1246: 
1.121     ng       1247: //=========== Check that a point is assigned for all the parts  ============
1.71      ng       1248:     function checksubmit(formname,val,total,parttot) {
1.121     ng       1249: 	formname.gradeOpt.value = val;
1.71      ng       1250: 	if (val == "Save & Next") {
                   1251: 	    for (i=0;i<=total;i++) {
                   1252: 		for (j=0;j<parttot;j++) {
1.125     ng       1253: 		    var partid = formname["partid"+i+"_"+j].value;
1.127     ng       1254: 		    if (formname["GD_SEL"+i+"_"+partid][0].selected) {
1.125     ng       1255: 			var points = formname["GD_BOX"+i+"_"+partid].value;
1.71      ng       1256: 			if (points == "") {
1.125     ng       1257: 			    var name = formname["name"+i].value;
1.129     ng       1258: 			    var studentID = (name != '' ? name : formname["unamedom"+i].value);
                   1259: 			    var resp = confirm("You did not assign a score for "+studentID+
                   1260: 					       ", part "+partid+". Continue?");
1.71      ng       1261: 			    if (resp == false) {
1.125     ng       1262: 				formname["GD_BOX"+i+"_"+partid].focus();
1.71      ng       1263: 				return false;
                   1264: 			    }
                   1265: 			}
                   1266: 		    }
                   1267: 		    
                   1268: 		}
                   1269: 	    }
                   1270: 	    
                   1271: 	}
1.121     ng       1272: 	if (val == "Grade Student") {
                   1273: 	    if (formname.Status.value == "") {
                   1274: 		formname.Status.value = "Active";
                   1275: 	    }
                   1276: 	    formname.studentNo.value = total;
                   1277: 	}
1.120     ng       1278: 	formname.submit();
                   1279:     }
                   1280: 
1.71      ng       1281: //======= Check that a score is assigned for all the problems (page/sequence grading only) =========
                   1282:     function checkSubmitPage(formname,total) {
                   1283: 	noscore = new Array(100);
                   1284: 	var ptr = 0;
                   1285: 	for (i=1;i<total;i++) {
1.125     ng       1286: 	    var partid = formname["q_"+i].value;
1.127     ng       1287: 	    if (formname["GD_SEL"+i+"_"+partid][0].selected) {
1.125     ng       1288: 		var points = formname["GD_BOX"+i+"_"+partid].value;
                   1289: 		var status = formname["solved"+i+"_"+partid].value;
1.71      ng       1290: 		if (points == "" && status != "correct_by_student") {
                   1291: 		    noscore[ptr] = i;
                   1292: 		    ptr++;
                   1293: 		}
                   1294: 	    }
                   1295: 	}
                   1296: 	if (ptr != 0) {
                   1297: 	    var sense = ptr == 1 ? ": " : "s: ";
                   1298: 	    var prolist = "";
                   1299: 	    if (ptr == 1) {
                   1300: 		prolist = noscore[0];
                   1301: 	    } else {
                   1302: 		var i = 0;
                   1303: 		while (i < ptr-1) {
                   1304: 		    prolist += noscore[i]+", ";
                   1305: 		    i++;
                   1306: 		}
                   1307: 		prolist += "and "+noscore[i];
                   1308: 	    }
                   1309: 	    var resp = confirm("You did not assign any score for the following problem"+sense+prolist+". Continue?");
                   1310: 	    if (resp == false) {
                   1311: 		return false;
                   1312: 	    }
                   1313: 	}
1.45      ng       1314: 
1.71      ng       1315: 	formname.submit();
                   1316:     }
                   1317: SUBJAVASCRIPT
                   1318: }
1.45      ng       1319: 
1.71      ng       1320: #--- javascript for essay type problem --
                   1321: sub sub_page_kw_js {
                   1322:     my $request = shift;
1.80      ng       1323:     my $iconpath = $request->dir_config('lonIconsURL');
1.118     ng       1324:     &commonJSfunctions($request);
1.350     albertel 1325: 
1.629     www      1326:     my $inner_js_msg_central= (<<INNERJS);
                   1327: <script type="text/javascript">
1.350     albertel 1328:     function checkInput() {
                   1329:       opener.document.SCORE.msgsub.value = opener.checkEntities(document.msgcenter.msgsub.value);
                   1330:       var nmsg   = opener.document.SCORE.savemsgN.value;
                   1331:       var usrctr = document.msgcenter.usrctr.value;
                   1332:       var newval = opener.document.SCORE["newmsg"+usrctr];
                   1333:       newval.value = opener.checkEntities(document.msgcenter.newmsg.value);
                   1334: 
                   1335:       var msgchk = "";
                   1336:       if (document.msgcenter.subchk.checked) {
                   1337:          msgchk = "msgsub,";
                   1338:       }
                   1339:       var includemsg = 0;
                   1340:       for (var i=1; i<=nmsg; i++) {
                   1341:           var opnmsg = opener.document.SCORE["savemsg"+i];
                   1342:           var frmmsg = document.msgcenter["msg"+i];
                   1343:           opnmsg.value = opener.checkEntities(frmmsg.value);
                   1344:           var showflg = opener.document.SCORE["shownOnce"+i];
                   1345:           showflg.value = "1";
                   1346:           var chkbox = document.msgcenter["msgn"+i];
                   1347:           if (chkbox.checked) {
                   1348:              msgchk += "savemsg"+i+",";
                   1349:              includemsg = 1;
                   1350:           }
                   1351:       }
                   1352:       if (document.msgcenter.newmsgchk.checked) {
                   1353:          msgchk += "newmsg"+usrctr;
                   1354:          includemsg = 1;
                   1355:       }
                   1356:       imgformname = opener.document.SCORE["mailicon"+usrctr];
                   1357:       imgformname.src = "$iconpath/"+((includemsg) ? "mailto.gif" : "mailbkgrd.gif");
                   1358:       var includemsg = opener.document.SCORE["includemsg"+usrctr];
                   1359:       includemsg.value = msgchk;
                   1360: 
                   1361:       self.close()
                   1362: 
                   1363:     }
1.629     www      1364: </script>
1.350     albertel 1365: INNERJS
                   1366: 
1.629     www      1367:     my $inner_js_highlight_central= (<<INNERJS);
                   1368: <script type="text/javascript">
1.351     albertel 1369:     function updateChoice(flag) {
                   1370:       opener.document.SCORE.kwclr.value = opener.radioSelection(document.hlCenter.kwdclr);
                   1371:       opener.document.SCORE.kwsize.value = opener.radioSelection(document.hlCenter.kwdsize);
                   1372:       opener.document.SCORE.kwstyle.value = opener.radioSelection(document.hlCenter.kwdstyle);
                   1373:       opener.document.SCORE.refresh.value = "on";
                   1374:       if (opener.document.SCORE.keywords.value!=""){
                   1375:          opener.document.SCORE.submit();
                   1376:       }
                   1377:       self.close()
                   1378:     }
1.629     www      1379: </script>
1.351     albertel 1380: INNERJS
                   1381: 
                   1382:     my $start_page_msg_central = 
                   1383:         &Apache::loncommon::start_page('Message Central',$inner_js_msg_central,
                   1384: 				       {'js_ready'  => 1,
                   1385: 					'only_body' => 1,
                   1386: 					'bgcolor'   =>'#FFFFFF',});
                   1387:     my $end_page_msg_central = 
                   1388: 	&Apache::loncommon::end_page({'js_ready' => 1});
                   1389: 
                   1390: 
                   1391:     my $start_page_highlight_central = 
                   1392:         &Apache::loncommon::start_page('Highlight Central',
                   1393: 				       $inner_js_highlight_central,
1.350     albertel 1394: 				       {'js_ready'  => 1,
                   1395: 					'only_body' => 1,
                   1396: 					'bgcolor'   =>'#FFFFFF',});
1.351     albertel 1397:     my $end_page_highlight_central = 
1.350     albertel 1398: 	&Apache::loncommon::end_page({'js_ready' => 1});
                   1399: 
1.219     www      1400:     my $docopen=&Apache::lonhtmlcommon::javascript_docopen();
1.236     albertel 1401:     $docopen=~s/^document\.//;
1.539     riegler  1402:     my $alertmsg = &mt('Please select a word or group of words from document and then click this link.');
1.597     wenzelju 1403:     $request->print(&Apache::lonhtmlcommon::scripttag(<<SUBJAVASCRIPT));
1.45      ng       1404: 
1.44      ng       1405: //===================== Show list of keywords ====================
1.122     ng       1406:   function keywords(formname) {
                   1407:     var nret = prompt("Keywords list, separated by a space. Add/delete to list if desired.",formname.keywords.value);
1.44      ng       1408:     if (nret==null) return;
1.122     ng       1409:     formname.keywords.value = nret;
1.44      ng       1410: 
1.122     ng       1411:     if (formname.keywords.value != "") {
1.128     ng       1412: 	formname.refresh.value = "on";
1.122     ng       1413: 	formname.submit();
1.44      ng       1414:     }
                   1415:     return;
                   1416:   }
                   1417: 
                   1418: //===================== Script to view submitted by ==================
                   1419:   function viewSubmitter(submitter) {
                   1420:     document.SCORE.refresh.value = "on";
                   1421:     document.SCORE.NCT.value = "1";
                   1422:     document.SCORE.unamedom0.value = submitter;
                   1423:     document.SCORE.submit();
                   1424:     return;
                   1425:   }
                   1426: 
                   1427: //===================== Script to add keyword(s) ==================
                   1428:   function getSel() {
                   1429:     if (document.getSelection) txt = document.getSelection();
                   1430:     else if (document.selection) txt = document.selection.createRange().text;
                   1431:     else return;
                   1432:     var cleantxt = txt.replace(new RegExp('([\\f\\n\\r\\t\\v ])+', 'g')," ");
                   1433:     if (cleantxt=="") {
1.539     riegler  1434: 	alert("$alertmsg");
1.44      ng       1435: 	return;
                   1436:     }
                   1437:     var nret = prompt("Add selection to keyword list? Edit if desired.",cleantxt);
                   1438:     if (nret==null) return;
1.127     ng       1439:     document.SCORE.keywords.value = document.SCORE.keywords.value+" "+nret;
1.44      ng       1440:     if (document.SCORE.keywords.value != "") {
1.127     ng       1441: 	document.SCORE.refresh.value = "on";
1.44      ng       1442: 	document.SCORE.submit();
                   1443:     }
                   1444:     return;
                   1445:   }
                   1446: 
                   1447: //====================== Script for composing message ==============
1.80      ng       1448:    // preload images
                   1449:    img1 = new Image();
                   1450:    img1.src = "$iconpath/mailbkgrd.gif";
                   1451:    img2 = new Image();
                   1452:    img2.src = "$iconpath/mailto.gif";
                   1453: 
1.44      ng       1454:   function msgCenter(msgform,usrctr,fullname) {
                   1455:     var Nmsg  = msgform.savemsgN.value;
                   1456:     savedMsgHeader(Nmsg,usrctr,fullname);
                   1457:     var subject = msgform.msgsub.value;
1.127     ng       1458:     var msgchk = document.SCORE["includemsg"+usrctr].value;
1.44      ng       1459:     re = /msgsub/;
                   1460:     var shwsel = "";
                   1461:     if (re.test(msgchk)) { shwsel = "checked" }
1.123     ng       1462:     subject = (document.SCORE.shownSub.value == 0 ? checkEntities(subject) : subject);
                   1463:     displaySubject(checkEntities(subject),shwsel);
1.44      ng       1464:     for (var i=1; i<=Nmsg; i++) {
1.123     ng       1465: 	var testmsg = "savemsg"+i+",";
                   1466: 	re = new RegExp(testmsg,"g");
1.44      ng       1467: 	shwsel = "";
                   1468: 	if (re.test(msgchk)) { shwsel = "checked" }
1.125     ng       1469: 	var message = document.SCORE["savemsg"+i].value;
1.126     ng       1470: 	message = (document.SCORE["shownOnce"+i].value == 0 ? checkEntities(message) : message);
1.123     ng       1471: 	displaySavedMsg(i,message,shwsel); //I do not get it. w/o checkEntities on saved messages,
                   1472: 	                                   //any &lt; is already converted to <, etc. However, only once!!
1.44      ng       1473:     }
1.125     ng       1474:     newmsg = document.SCORE["newmsg"+usrctr].value;
1.44      ng       1475:     shwsel = "";
                   1476:     re = /newmsg/;
                   1477:     if (re.test(msgchk)) { shwsel = "checked" }
                   1478:     newMsg(newmsg,shwsel);
                   1479:     msgTail(); 
                   1480:     return;
                   1481:   }
                   1482: 
1.123     ng       1483:   function checkEntities(strx) {
                   1484:     if (strx.length == 0) return strx;
                   1485:     var orgStr = ["&", "<", ">", '"']; 
                   1486:     var newStr = ["&amp;", "&lt;", "&gt;", "&quot;"];
                   1487:     var counter = 0;
                   1488:     while (counter < 4) {
                   1489: 	strx = strReplace(strx,orgStr[counter],newStr[counter]);
                   1490: 	counter++;
                   1491:     }
                   1492:     return strx;
                   1493:   }
                   1494: 
                   1495:   function strReplace(strx, orgStr, newStr) {
                   1496:     return strx.split(orgStr).join(newStr);
                   1497:   }
                   1498: 
1.44      ng       1499:   function savedMsgHeader(Nmsg,usrctr,fullname) {
1.76      ng       1500:     var height = 70*Nmsg+250;
1.44      ng       1501:     var scrollbar = "no";
                   1502:     if (height > 600) {
                   1503: 	height = 600;
                   1504: 	scrollbar = "yes";
                   1505:     }
1.118     ng       1506:     var xpos = (screen.width-600)/2;
                   1507:     xpos = (xpos < 0) ? '0' : xpos;
                   1508:     var ypos = (screen.height-height)/2-30;
                   1509:     ypos = (ypos < 0) ? '0' : ypos;
                   1510: 
1.206     albertel 1511:     pWin = window.open('', 'MessageCenter', 'resizable=yes,toolbar=no,location=no,scrollbars='+scrollbar+',screenx='+xpos+',screeny='+ypos+',width=600,height='+height);
1.76      ng       1512:     pWin.focus();
                   1513:     pDoc = pWin.document;
1.219     www      1514:     pDoc.$docopen;
1.351     albertel 1515:     pDoc.write('$start_page_msg_central');
1.76      ng       1516: 
                   1517:     pDoc.write("<form action=\\"inactive\\" name=\\"msgcenter\\">");
                   1518:     pDoc.write("<input value=\\""+usrctr+"\\" name=\\"usrctr\\" type=\\"hidden\\">");
1.465     albertel 1519:     pDoc.write("<h3><span class=\\"LC_info\\">&nbsp;Compose Message for \"+fullname+\"<\\/span><\\/h3><br /><br />");
1.76      ng       1520: 
1.564     bisitz   1521:     pDoc.write('<table border="0" width="100%"><tr><td bgcolor="#777777">');
                   1522:     pDoc.write('<table border="0" width="100%"><tr bgcolor="#DDFFFF">');
1.465     albertel 1523:     pDoc.write("<td><b>Type<\\/b><\\/td><td><b>Include<\\/b><\\/td><td><b>Message<\\/td><\\/tr>");
1.44      ng       1524: }
                   1525:     function displaySubject(msg,shwsel) {
1.76      ng       1526:     pDoc = pWin.document;
                   1527:     pDoc.write("<tr bgcolor=\\"#ffffdd\\">");
1.465     albertel 1528:     pDoc.write("<td>Subject<\\/td>");
                   1529:     pDoc.write("<td align=\\"center\\"><input name=\\"subchk\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
                   1530:     pDoc.write("<td><input name=\\"msgsub\\" type=\\"text\\" value=\\""+msg+"\\"size=\\"60\\" maxlength=\\"80\\"><\\/td><\\/tr>");
1.44      ng       1531: }
                   1532: 
1.72      ng       1533:   function displaySavedMsg(ctr,msg,shwsel) {
1.76      ng       1534:     pDoc = pWin.document;
                   1535:     pDoc.write("<tr bgcolor=\\"#ffffdd\\">");
1.465     albertel 1536:     pDoc.write("<td align=\\"center\\">"+ctr+"<\\/td>");
                   1537:     pDoc.write("<td align=\\"center\\"><input name=\\"msgn"+ctr+"\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
                   1538:     pDoc.write("<td><textarea name=\\"msg"+ctr+"\\" cols=\\"60\\" rows=\\"3\\">"+msg+"<\\/textarea><\\/td><\\/tr>");
1.44      ng       1539: }
                   1540: 
                   1541:   function newMsg(newmsg,shwsel) {
1.76      ng       1542:     pDoc = pWin.document;
                   1543:     pDoc.write("<tr bgcolor=\\"#ffffdd\\">");
1.465     albertel 1544:     pDoc.write("<td align=\\"center\\">New<\\/td>");
                   1545:     pDoc.write("<td align=\\"center\\"><input name=\\"newmsgchk\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
                   1546:     pDoc.write("<td><textarea name=\\"newmsg\\" cols=\\"60\\" rows=\\"3\\" onchange=\\"javascript:this.form.newmsgchk.checked=true\\" >"+newmsg+"<\\/textarea><\\/td><\\/tr>");
1.44      ng       1547: }
                   1548: 
                   1549:   function msgTail() {
1.76      ng       1550:     pDoc = pWin.document;
1.465     albertel 1551:     pDoc.write("<\\/table>");
                   1552:     pDoc.write("<\\/td><\\/tr><\\/table>&nbsp;");
1.589     bisitz   1553:     pDoc.write("<input type=\\"button\\" value=\\"Save\\" onclick=\\"javascript:checkInput()\\">&nbsp;&nbsp;");
                   1554:     pDoc.write("<input type=\\"button\\" value=\\"Cancel\\" onclick=\\"self.close()\\"><br /><br />");
1.465     albertel 1555:     pDoc.write("<\\/form>");
1.351     albertel 1556:     pDoc.write('$end_page_msg_central');
1.128     ng       1557:     pDoc.close();
1.44      ng       1558: }
                   1559: 
                   1560: //====================== Script for keyword highlight options ==============
                   1561:   function kwhighlight() {
                   1562:     var kwclr    = document.SCORE.kwclr.value;
                   1563:     var kwsize   = document.SCORE.kwsize.value;
                   1564:     var kwstyle  = document.SCORE.kwstyle.value;
                   1565:     var redsel = "";
                   1566:     var grnsel = "";
                   1567:     var blusel = "";
                   1568:     if (kwclr=="red")   {var redsel="checked"};
                   1569:     if (kwclr=="green") {var grnsel="checked"};
                   1570:     if (kwclr=="blue")  {var blusel="checked"};
                   1571:     var sznsel = "";
                   1572:     var sz1sel = "";
                   1573:     var sz2sel = "";
                   1574:     if (kwsize=="0")  {var sznsel="checked"};
                   1575:     if (kwsize=="+1") {var sz1sel="checked"};
                   1576:     if (kwsize=="+2") {var sz2sel="checked"};
                   1577:     var synsel = "";
                   1578:     var syisel = "";
                   1579:     var sybsel = "";
                   1580:     if (kwstyle=="")    {var synsel="checked"};
                   1581:     if (kwstyle=="<i>") {var syisel="checked"};
                   1582:     if (kwstyle=="<b>") {var sybsel="checked"};
                   1583:     highlightCentral();
                   1584:     highlightbody('red','red',redsel,'0','normal',sznsel,'','normal',synsel);
                   1585:     highlightbody('green','green',grnsel,'+1','+1',sz1sel,'<i>','italic',syisel);
                   1586:     highlightbody('blue','blue',blusel,'+2','+2',sz2sel,'<b>','bold',sybsel);
                   1587:     highlightend();
                   1588:     return;
                   1589:   }
                   1590: 
                   1591:   function highlightCentral() {
1.76      ng       1592: //    if (window.hwdWin) window.hwdWin.close();
1.118     ng       1593:     var xpos = (screen.width-400)/2;
                   1594:     xpos = (xpos < 0) ? '0' : xpos;
                   1595:     var ypos = (screen.height-330)/2-30;
                   1596:     ypos = (ypos < 0) ? '0' : ypos;
                   1597: 
1.206     albertel 1598:     hwdWin = window.open('', 'KeywordHighlightCentral', 'resizeable=yes,toolbar=no,location=no,scrollbars=no,width=400,height=300,screenx='+xpos+',screeny='+ypos);
1.76      ng       1599:     hwdWin.focus();
                   1600:     var hDoc = hwdWin.document;
1.219     www      1601:     hDoc.$docopen;
1.351     albertel 1602:     hDoc.write('$start_page_highlight_central');
1.76      ng       1603:     hDoc.write("<form action=\\"inactive\\" name=\\"hlCenter\\">");
1.465     albertel 1604:     hDoc.write("<h3><span class=\\"LC_info\\">&nbsp;Keyword Highlight Options<\\/span><\\/h3><br /><br />");
1.76      ng       1605: 
1.564     bisitz   1606:     hDoc.write('<table border="0" width="100%"><tr><td bgcolor="#777777">');
                   1607:     hDoc.write('<table border="0" width="100%"><tr bgcolor="#DDFFFF">');
1.465     albertel 1608:     hDoc.write("<td><b>Text Color<\\/b><\\/td><td><b>Font Size<\\/b><\\/td><td><b>Font Style<\\/td><\\/tr>");
1.44      ng       1609:   }
                   1610: 
                   1611:   function highlightbody(clrval,clrtxt,clrsel,szval,sztxt,szsel,syval,sytxt,sysel) { 
1.76      ng       1612:     var hDoc = hwdWin.document;
                   1613:     hDoc.write("<tr bgcolor=\\"#ffffdd\\">");
                   1614:     hDoc.write("<td align=\\"left\\">");
1.465     albertel 1615:     hDoc.write("<input name=\\"kwdclr\\" type=\\"radio\\" value=\\""+clrval+"\\" "+clrsel+">&nbsp;"+clrtxt+"<\\/td>");
1.76      ng       1616:     hDoc.write("<td align=\\"left\\">");
1.465     albertel 1617:     hDoc.write("<input name=\\"kwdsize\\" type=\\"radio\\" value=\\""+szval+"\\" "+szsel+">&nbsp;"+sztxt+"<\\/td>");
1.76      ng       1618:     hDoc.write("<td align=\\"left\\">");
1.465     albertel 1619:     hDoc.write("<input name=\\"kwdstyle\\" type=\\"radio\\" value=\\""+syval+"\\" "+sysel+">&nbsp;"+sytxt+"<\\/td>");
                   1620:     hDoc.write("<\\/tr>");
1.44      ng       1621:   }
                   1622: 
                   1623:   function highlightend() { 
1.76      ng       1624:     var hDoc = hwdWin.document;
1.465     albertel 1625:     hDoc.write("<\\/table>");
                   1626:     hDoc.write("<\\/td><\\/tr><\\/table>&nbsp;");
1.589     bisitz   1627:     hDoc.write("<input type=\\"button\\" value=\\"Save\\" onclick=\\"javascript:updateChoice(1)\\">&nbsp;&nbsp;");
                   1628:     hDoc.write("<input type=\\"button\\" value=\\"Cancel\\" onclick=\\"self.close()\\"><br /><br />");
1.465     albertel 1629:     hDoc.write("<\\/form>");
1.351     albertel 1630:     hDoc.write('$end_page_highlight_central');
1.128     ng       1631:     hDoc.close();
1.44      ng       1632:   }
                   1633: 
                   1634: SUBJAVASCRIPT
                   1635: }
                   1636: 
1.349     albertel 1637: sub get_increment {
1.348     bowersj2 1638:     my $increment = $env{'form.increment'};
                   1639:     if ($increment != 1 && $increment != .5 && $increment != .25 &&
                   1640:         $increment != .1) {
                   1641:         $increment = 1;
                   1642:     }
                   1643:     return $increment;
                   1644: }
                   1645: 
1.585     bisitz   1646: sub gradeBox_start {
                   1647:     return (
                   1648:         &Apache::loncommon::start_data_table()
                   1649:        .&Apache::loncommon::start_data_table_header_row()
                   1650:        .'<th>'.&mt('Part').'</th>'
                   1651:        .'<th>'.&mt('Points').'</th>'
                   1652:        .'<th>&nbsp;</th>'
                   1653:        .'<th>'.&mt('Assign Grade').'</th>'
                   1654:        .'<th>'.&mt('Weight').'</th>'
                   1655:        .'<th>'.&mt('Grade Status').'</th>'
                   1656:        .&Apache::loncommon::end_data_table_header_row()
                   1657:     );
                   1658: }
                   1659: 
                   1660: sub gradeBox_end {
                   1661:     return (
                   1662:         &Apache::loncommon::end_data_table()
                   1663:     );
                   1664: }
1.71      ng       1665: #--- displays the grading box, used in essay type problem and grading by page/sequence
                   1666: sub gradeBox {
1.322     albertel 1667:     my ($request,$symb,$uname,$udom,$counter,$partid,$record) = @_;
1.381     albertel 1668:     my $checkIcon = '<img alt="'.&mt('Check Mark').
1.485     albertel 1669: 	'" src="'.&Apache::loncommon::lonhttpdurl($request->dir_config('lonIconsURL').'/check.gif').'" height="16" border="0" />';
1.71      ng       1670:     my $wgt    = &Apache::lonnet::EXT('resource.'.$partid.'.weight',$symb,$udom,$uname);
1.466     albertel 1671:     my $wgtmsg = ($wgt > 0) ? &mt('(problem weight)') 
                   1672:                            : '<span class="LC_info">'.&mt('problem weight assigned by computer').'</span>';
1.71      ng       1673:     $wgt       = ($wgt > 0 ? $wgt : '1');
                   1674:     my $score  = ($$record{'resource.'.$partid.'.awarded'} eq '' ?
1.320     albertel 1675: 		  '' : &compute_points($$record{'resource.'.$partid.'.awarded'},$wgt));
1.71      ng       1676:     my $result='<input type="hidden" name="WGT'.$counter.'_'.$partid.'" value="'.$wgt.'" />'."\n";
1.466     albertel 1677:     my $display_part= &get_display_part($partid,$symb);
1.270     albertel 1678:     my %last_resets = &get_last_resets($symb,$env{'request.course.id'},
                   1679: 				       [$partid]);
                   1680:     my $aggtries = $$record{'resource.'.$partid.'.tries'};
1.269     raeburn  1681:     if ($last_resets{$partid}) {
                   1682:         $aggtries = &get_num_tries($record,$last_resets{$partid},$partid);
                   1683:     }
1.585     bisitz   1684:     $result.=&Apache::loncommon::start_data_table_row();
1.71      ng       1685:     my $ctr = 0;
1.348     bowersj2 1686:     my $thisweight = 0;
1.349     albertel 1687:     my $increment = &get_increment();
1.485     albertel 1688: 
                   1689:     my $radio.='<table border="0"><tr>'."\n";  # display radio buttons in a nice table 10 across
1.348     bowersj2 1690:     while ($thisweight<=$wgt) {
1.532     bisitz   1691: 	$radio.= '<td><span class="LC_nobreak"><label><input type="radio" name="RADVAL'.$counter.'_'.$partid.'" '.
1.589     bisitz   1692:         'onclick="javascript:writeBox(this.form,\''.$counter.'_'.$partid.'\','.
1.348     bowersj2 1693: 	    $thisweight.')" value="'.$thisweight.'" '.
1.401     albertel 1694: 	    ($score eq $thisweight ? 'checked="checked"':'').' /> '.$thisweight."</label></span></td>\n";
1.485     albertel 1695: 	$radio.=(($ctr+1)%10 == 0 ? '</tr><tr>' : '');
1.348     bowersj2 1696:         $thisweight += $increment;
1.71      ng       1697: 	$ctr++;
                   1698:     }
1.485     albertel 1699:     $radio.='</tr></table>';
                   1700: 
                   1701:     my $line.='<input type="text" name="GD_BOX'.$counter.'_'.$partid.'"'.
1.71      ng       1702: 	($score ne ''? ' value = "'.$score.'"':'').' size="4" '.
1.589     bisitz   1703: 	'onchange="javascript:updateRadio(this.form,\''.$counter.'_'.$partid.'\','.
1.71      ng       1704: 	$wgt.')" /></td>'."\n";
1.485     albertel 1705:     $line.='<td>/'.$wgt.' '.$wgtmsg.
1.71      ng       1706: 	($$record{'resource.'.$partid.'.solved'} eq 'correct_by_student' ? '&nbsp;'.$checkIcon : '').
1.585     bisitz   1707: 	' </td>'."\n";
                   1708:     $line.='<td><select name="GD_SEL'.$counter.'_'.$partid.'" '.
1.589     bisitz   1709: 	'onchange="javascript:clearRadBox(this.form,\''.$counter.'_'.$partid.'\')" >'."\n";
1.71      ng       1710:     if ($$record{'resource.'.$partid.'.solved'} eq 'excused') {
1.485     albertel 1711: 	$line.='<option></option>'.
                   1712: 	    '<option value="excused" selected="selected">'.&mt('excused').'</option>';
1.71      ng       1713:     } else {
1.485     albertel 1714: 	$line.='<option selected="selected"></option>'.
                   1715: 	    '<option value="excused" >'.&mt('excused').'</option>';
1.71      ng       1716:     }
1.485     albertel 1717:     $line.='<option value="reset status">'.&mt('reset status').'</option></select>'."\n";
                   1718: 
                   1719: 
                   1720:     $result .= 
1.585     bisitz   1721: 	    '<td>'.$display_part.'</td><td>'.$radio.'</td><td>'.&mt('or').'</td><td>'.$line.'</td>';
                   1722:     $result.=&Apache::loncommon::end_data_table_row();
1.71      ng       1723:     $result.='<input type="hidden" name="stores'.$counter.'_'.$partid.'" value="" />'."\n".
                   1724: 	'<input type="hidden" name="oldpts'.$counter.'_'.$partid.'" value="'.$score.'" />'."\n".
                   1725: 	'<input type="hidden" name="solved'.$counter.'_'.$partid.'" value="'.
1.269     raeburn  1726: 	$$record{'resource.'.$partid.'.solved'}.'" />'."\n".
                   1727:         '<input type="hidden" name="totaltries'.$counter.'_'.$partid.'" value="'.
                   1728:         $$record{'resource.'.$partid.'.tries'}.'" />'."\n".
                   1729:         '<input type="hidden" name="aggtries'.$counter.'_'.$partid.'" value="'.
                   1730:         $aggtries.'" />'."\n";
1.582     raeburn  1731:     my $res_error;
                   1732:     $result.=&handback_box($symb,$uname,$udom,$counter,$partid,$record,\$res_error);
                   1733:     if ($res_error) {
                   1734:         return &navmap_errormsg();
                   1735:     }
1.318     banghart 1736:     return $result;
                   1737: }
1.322     albertel 1738: 
                   1739: sub handback_box {
1.623     www      1740:     my ($symb,$uname,$udom,$counter,$partid,$record,$res_error_pointer) = @_;
                   1741:     my ($partlist,$handgrade,$responseType) = &response_type($symb,$res_error_pointer);
1.323     banghart 1742:     my (@respids);
1.375     albertel 1743:      my @part_response_id = &flatten_responseType($responseType);
                   1744:     foreach my $part_response_id (@part_response_id) {
                   1745:     	my ($part,$resp) = @{ $part_response_id };
1.323     banghart 1746:         if ($part eq $partid) {
1.375     albertel 1747:             push(@respids,$resp);
1.323     banghart 1748:         }
                   1749:     }
1.318     banghart 1750:     my $result;
1.323     banghart 1751:     foreach my $respid (@respids) {
1.322     albertel 1752: 	my $prefix = $counter.'_'.$partid.'_'.$respid.'_';
                   1753: 	my $files=&get_submitted_files($udom,$uname,$partid,$respid,$record);
                   1754: 	next if (!@$files);
                   1755: 	my $file_counter = 1;
1.313     banghart 1756: 	foreach my $file (@$files) {
1.368     banghart 1757: 	    if ($file =~ /\/portfolio\//) {
                   1758:     	        my ($file_path, $file_disp) = ($file =~ m|(.+/)(.+)$|);
                   1759:     	        my ($name,$version,$ext) = &file_name_version_ext($file_disp);
                   1760:     	        $file_disp = "$name.$ext";
                   1761:     	        $file = $file_path.$file_disp;
                   1762:     	        $result.=&mt('Return commented version of [_1] to student.',
                   1763:     			 '<span class="LC_filename">'.$file_disp.'</span>');
                   1764:     	        $result.='<input type="file"   name="'.$prefix.'returndoc'.$file_counter.'" />'."\n";
                   1765:     	        $result.='<input type="hidden" name="'.$prefix.'origdoc'.$file_counter.'" value="'.$file.'" /><br />';
1.485     albertel 1766:     	        $result.='('.&mt('File will be uploaded when you click on Save &amp; Next below.').')<br />';
1.368     banghart 1767:     	        $file_counter++;
                   1768: 	    }
1.322     albertel 1769: 	}
1.313     banghart 1770:     }
1.318     banghart 1771:     return $result;    
1.71      ng       1772: }
1.44      ng       1773: 
1.58      albertel 1774: sub show_problem {
1.382     albertel 1775:     my ($request,$symb,$uname,$udom,$removeform,$viewon,$mode,$form) = @_;
1.144     albertel 1776:     my $rendered;
1.382     albertel 1777:     my %form = ((ref($form) eq 'HASH')? %{$form} : ());
1.329     albertel 1778:     &Apache::lonxml::remember_problem_counter();
1.144     albertel 1779:     if ($mode eq 'both' or $mode eq 'text') {
                   1780: 	$rendered=&Apache::loncommon::get_student_view($symb,$uname,$udom,
1.382     albertel 1781: 						       $env{'request.course.id'},
                   1782: 						       undef,\%form);
1.144     albertel 1783:     }
1.58      albertel 1784:     if ($removeform) {
                   1785: 	$rendered=~s|<form(.*?)>||g;
                   1786: 	$rendered=~s|</form>||g;
1.374     albertel 1787: 	$rendered=~s|(<input[^>]*name\s*=\s*"?)(\w+)("?)|$1would_have_been_$2$3|g;
1.58      albertel 1788:     }
1.144     albertel 1789:     my $companswer;
                   1790:     if ($mode eq 'both' or $mode eq 'answer') {
1.329     albertel 1791: 	&Apache::lonxml::restore_problem_counter();
1.382     albertel 1792: 	$companswer=
                   1793: 	    &Apache::loncommon::get_student_answers($symb,$uname,$udom,
                   1794: 						    $env{'request.course.id'},
                   1795: 						    %form);
1.144     albertel 1796:     }
1.58      albertel 1797:     if ($removeform) {
                   1798: 	$companswer=~s|<form(.*?)>||g;
                   1799: 	$companswer=~s|</form>||g;
1.144     albertel 1800: 	$companswer=~s|name="submit"|name="would_have_been_submit"|g;
1.58      albertel 1801:     }
1.468     albertel 1802:     $rendered=
1.588     bisitz   1803:         '<div class="LC_Box">'
                   1804:        .'<h3 class="LC_hcell">'.&mt('View of the problem').'</h3>'
                   1805:        .$rendered
                   1806:        .'</div>';
1.468     albertel 1807:     $companswer=
1.588     bisitz   1808:         '<div class="LC_Box">'
                   1809:        .'<h3 class="LC_hcell">'.&mt('Correct answer').'</h3>'
                   1810:        .$companswer
                   1811:        .'</div>';
1.468     albertel 1812:     my $result;
1.144     albertel 1813:     if ($mode eq 'both') {
1.588     bisitz   1814:         $result=$rendered.$companswer;
1.144     albertel 1815:     } elsif ($mode eq 'text') {
1.588     bisitz   1816:         $result=$rendered;
1.144     albertel 1817:     } elsif ($mode eq 'answer') {
1.588     bisitz   1818:         $result=$companswer;
1.144     albertel 1819:     }
1.71      ng       1820:     return $result;
1.58      albertel 1821: }
1.397     albertel 1822: 
1.396     banghart 1823: sub files_exist {
                   1824:     my ($r, $symb) = @_;
                   1825:     my @students = &Apache::loncommon::get_env_multiple('form.stuinfo');
1.397     albertel 1826: 
1.396     banghart 1827:     foreach my $student (@students) {
                   1828:         my ($uname,$udom,$fullname) = split(/:/,$student);
1.397     albertel 1829:         my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},
                   1830: 					      $udom,$uname);
1.396     banghart 1831:         my ($string,$timestamp)= &get_last_submission(\%record);
1.397     albertel 1832:         foreach my $submission (@$string) {
                   1833:             my ($partid,$respid) =
                   1834: 		($submission =~ /^resource\.([^\.]*)\.([^\.]*)\.submission/);
                   1835:             my $files=&get_submitted_files($udom,$uname,$partid,$respid,
                   1836: 					   \%record);
                   1837:             return 1 if (@$files);
1.396     banghart 1838:         }
                   1839:     }
1.397     albertel 1840:     return 0;
1.396     banghart 1841: }
1.397     albertel 1842: 
1.394     banghart 1843: sub download_all_link {
                   1844:     my ($r,$symb) = @_;
1.621     www      1845:     unless (&files_exist($r, $symb)) {
                   1846:        $r->print(&mt('There are currently no submitted documents.'));
                   1847:        return;
                   1848:     }
                   1849: 
1.395     albertel 1850:     my $all_students = 
                   1851: 	join("\n", &Apache::loncommon::get_env_multiple('form.stuinfo'));
                   1852: 
                   1853:     my $parts =
                   1854: 	join("\n",&Apache::loncommon::get_env_multiple('form.vPart'));
                   1855: 
1.394     banghart 1856:     my $identifier = &Apache::loncommon::get_cgi_id();
1.514     raeburn  1857:     &Apache::lonnet::appenv({'cgi.'.$identifier.'.students' => $all_students,
                   1858:                              'cgi.'.$identifier.'.symb' => $symb,
                   1859:                              'cgi.'.$identifier.'.parts' => $parts,});
1.395     albertel 1860:     $r->print('<a href="/cgi-bin/multidownload.pl?'.$identifier.'">'.
                   1861: 	      &mt('Download All Submitted Documents').'</a>');
1.621     www      1862:     return;
                   1863: }
                   1864: 
                   1865: sub submit_download_link {
                   1866:     my ($request,$symb) = @_;
                   1867:     if (!$symb) { return ''; }
                   1868: #FIXME: Figure out which type of problem this is and provide appropriate download
                   1869:     &download_all_link($request,$symb);
1.394     banghart 1870: }
1.395     albertel 1871: 
1.432     banghart 1872: sub build_section_inputs {
                   1873:     my $section_inputs;
                   1874:     if ($env{'form.section'} eq '') {
                   1875:         $section_inputs .= '<input type="hidden" name="section" value="all" />'."\n";
                   1876:     } else {
                   1877:         my @sections = &Apache::loncommon::get_env_multiple('form.section');
1.434     albertel 1878:         foreach my $section (@sections) {
1.432     banghart 1879:             $section_inputs .= '<input type="hidden" name="section" value="'.$section.'" />'."\n";
                   1880:         }
                   1881:     }
                   1882:     return $section_inputs;
                   1883: }
                   1884: 
1.44      ng       1885: # --------------------------- show submissions of a student, option to grade 
                   1886: sub submission {
1.608     www      1887:     my ($request,$counter,$total,$symb) = @_;
1.257     albertel 1888:     my ($uname,$udom)     = ($env{'form.student'},$env{'form.userdom'});
                   1889:     $udom = ($udom eq '' ? $env{'user.domain'} : $udom); #has form.userdom changed for a student?
                   1890:     my $usec = &Apache::lonnet::getsection($udom,$uname,$env{'request.course.id'});
                   1891:     $env{'form.fullname'} = &Apache::loncommon::plainname($uname,$udom,'lastname') if $env{'form.fullname'} eq '';
1.608     www      1892: 
1.605     www      1893:     my $probtitle=&Apache::lonnet::gettitle($symb); 
1.324     albertel 1894:     if ($symb eq '') { $request->print("Unable to handle ambiguous references:."); return ''; }
1.104     albertel 1895: 
                   1896:     if (!&canview($usec)) {
1.398     albertel 1897: 	$request->print('<span class="LC_warning">Unable to view requested student.('.
                   1898: 			$uname.':'.$udom.' in section '.$usec.' in course id '.
                   1899: 			$env{'request.course.id'}.')</span>');
1.104     albertel 1900: 	return;
                   1901:     }
                   1902: 
1.257     albertel 1903:     if (!$env{'form.lastSub'}) { $env{'form.lastSub'} = 'datesub'; }
                   1904:     if (!$env{'form.vProb'}) { $env{'form.vProb'} = 'yes'; }
                   1905:     if (!$env{'form.vAns'}) { $env{'form.vAns'} = 'yes'; }
                   1906:     my $last = ($env{'form.lastSub'} eq 'last' ? 'last' : '');
1.381     albertel 1907:     my $checkIcon = '<img alt="'.&mt('Check Mark').
                   1908: 	'" src="'.$request->dir_config('lonIconsURL').
1.122     ng       1909: 	'/check.gif" height="16" border="0" />';
1.41      ng       1910: 
1.426     albertel 1911:     my %old_essays;
1.41      ng       1912:     # header info
                   1913:     if ($counter == 0) {
                   1914: 	&sub_page_js($request);
1.621     www      1915: 	&sub_page_kw_js($request);
1.605     www      1916: 	$request->print('<h3>&nbsp;<span class="LC_info">'.&mt('Submission Record').'</span></h3>');
1.118     ng       1917: 
1.44      ng       1918: 	# option to display problem, only once else it cause problems 
                   1919:         # with the form later since the problem has a form.
1.257     albertel 1920: 	if ($env{'form.vProb'} eq 'yes' or $env{'form.vAns'} eq 'yes') {
1.144     albertel 1921: 	    my $mode;
1.257     albertel 1922: 	    if ($env{'form.vProb'} eq 'yes' && $env{'form.vAns'} eq 'yes') {
1.144     albertel 1923: 		$mode='both';
1.257     albertel 1924: 	    } elsif ($env{'form.vProb'} eq 'yes') {
1.144     albertel 1925: 		$mode='text';
1.257     albertel 1926: 	    } elsif ($env{'form.vAns'} eq 'yes') {
1.144     albertel 1927: 		$mode='answer';
                   1928: 	    }
1.329     albertel 1929: 	    &Apache::lonxml::clear_problem_counter();
1.144     albertel 1930: 	    $request->print(&show_problem($request,$symb,$uname,$udom,0,1,$mode));
1.41      ng       1931: 	}
1.441     www      1932: 
1.44      ng       1933: 	# kwclr is the only variable that is guaranteed to be non blank 
                   1934:         # if this subroutine has been called once.
1.41      ng       1935: 	my %keyhash = ();
1.624     www      1936: #	if ($env{'form.kwclr'} eq '' && $env{'form.handgrade'} eq 'yes') {
                   1937:         if (1) {
1.41      ng       1938: 	    %keyhash = &Apache::lonnet::dump('nohist_handgrade',
1.257     albertel 1939: 					     $env{'course.'.$env{'request.course.id'}.'.domain'},
                   1940: 					     $env{'course.'.$env{'request.course.id'}.'.num'});
1.41      ng       1941: 
1.257     albertel 1942: 	    my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
                   1943: 	    $env{'form.keywords'} = $keyhash{$symb.'_keywords'} ne '' ? $keyhash{$symb.'_keywords'} : '';
                   1944: 	    $env{'form.kwclr'}    = $keyhash{$loginuser.'_kwclr'} ne '' ? $keyhash{$loginuser.'_kwclr'} : 'red';
                   1945: 	    $env{'form.kwsize'}   = $keyhash{$loginuser.'_kwsize'} ne '' ? $keyhash{$loginuser.'_kwsize'} : '0';
                   1946: 	    $env{'form.kwstyle'}  = $keyhash{$loginuser.'_kwstyle'} ne '' ? $keyhash{$loginuser.'_kwstyle'} : '';
                   1947: 	    $env{'form.msgsub'}   = $keyhash{$symb.'_subject'} ne '' ? 
1.605     www      1948: 		$keyhash{$symb.'_subject'} : $probtitle;
1.257     albertel 1949: 	    $env{'form.savemsgN'} = $keyhash{$symb.'_savemsgN'} ne '' ? $keyhash{$symb.'_savemsgN'} : '0';
1.41      ng       1950: 	}
1.257     albertel 1951: 	my $overRideScore = $env{'form.overRideScore'} eq '' ? 'no' : $env{'form.overRideScore'};
1.442     banghart 1952: 	my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
1.303     banghart 1953: 	$request->print('<form action="/adm/grades" method="post" name="SCORE" enctype="multipart/form-data">'."\n".
1.41      ng       1954: 			'<input type="hidden" name="command"    value="handgrade" />'."\n".
1.442     banghart 1955: 			'<input type="hidden" name="Status"     value="'.$stu_status.'" />'."\n".
1.120     ng       1956: 			'<input type="hidden" name="overRideScore" value="'.$overRideScore.'" />'."\n".
1.41      ng       1957: 			'<input type="hidden" name="refresh"    value="off" />'."\n".
1.120     ng       1958: 			'<input type="hidden" name="studentNo"  value="" />'."\n".
                   1959: 			'<input type="hidden" name="gradeOpt"   value="" />'."\n".
1.418     albertel 1960: 			'<input type="hidden" name="symb"       value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.257     albertel 1961: 			'<input type="hidden" name="vProb"      value="'.$env{'form.vProb'}.'" />'."\n".
                   1962: 			'<input type="hidden" name="vAns"       value="'.$env{'form.vAns'}.'" />'."\n".
                   1963: 			'<input type="hidden" name="lastSub"    value="'.$env{'form.lastSub'}.'" />'."\n".
1.432     banghart 1964: 			&build_section_inputs().
1.326     albertel 1965: 			'<input type="hidden" name="submitonly" value="'.$env{'form.submitonly'}.'" />'."\n".
1.41      ng       1966: 			'<input type="hidden" name="NCT"'.
1.257     albertel 1967: 			' value="'.($env{'form.NTSTU'} ne '' ? $env{'form.NTSTU'} : $total+1).'" />'."\n");
1.624     www      1968: #	if ($env{'form.handgrade'} eq 'yes') {
                   1969:         if (1) {
1.257     albertel 1970: 	    $request->print('<input type="hidden" name="keywords" value="'.$env{'form.keywords'}.'" />'."\n".
                   1971: 			    '<input type="hidden" name="kwclr"    value="'.$env{'form.kwclr'}.'" />'."\n".
                   1972: 			    '<input type="hidden" name="kwsize"   value="'.$env{'form.kwsize'}.'" />'."\n".
                   1973: 			    '<input type="hidden" name="kwstyle"  value="'.$env{'form.kwstyle'}.'" />'."\n".
                   1974: 			    '<input type="hidden" name="msgsub"   value="'.$env{'form.msgsub'}.'" />'."\n".
1.123     ng       1975: 			    '<input type="hidden" name="shownSub" value="0" />'."\n".
1.257     albertel 1976: 			    '<input type="hidden" name="savemsgN" value="'.$env{'form.savemsgN'}.'" />'."\n");
1.154     albertel 1977: 	    foreach my $partid (&Apache::loncommon::get_env_multiple('form.vPart')) {
                   1978: 		$request->print('<input type="hidden" name="vPart" value="'.$partid.'" />'."\n");
                   1979: 	    }
1.123     ng       1980: 	}
1.41      ng       1981: 	
                   1982: 	my ($cts,$prnmsg) = (1,'');
1.257     albertel 1983: 	while ($cts <= $env{'form.savemsgN'}) {
1.41      ng       1984: 	    $prnmsg.='<input type="hidden" name="savemsg'.$cts.'" value="'.
1.123     ng       1985: 		(!exists($keyhash{$symb.'_savemsg'.$cts}) ? 
1.257     albertel 1986: 		 &Apache::lonfeedback::clear_out_html($env{'form.savemsg'.$cts}) :
1.80      ng       1987: 		 &Apache::lonfeedback::clear_out_html($keyhash{$symb.'_savemsg'.$cts})).
1.123     ng       1988: 		'" />'."\n".
                   1989: 		'<input type="hidden" name="shownOnce'.$cts.'" value="0" />'."\n";
1.41      ng       1990: 	    $cts++;
                   1991: 	}
                   1992: 	$request->print($prnmsg);
1.32      ng       1993: 
1.624     www      1994: #	if ($env{'form.handgrade'} eq 'yes') {
                   1995:         if (1) {
1.88      www      1996: #
                   1997: # Print out the keyword options line
                   1998: #
1.41      ng       1999: 	    $request->print(<<KEYWORDS);
1.38      ng       2000: &nbsp;<b>Keyword Options:</b>&nbsp;
1.417     albertel 2001: <a href="javascript:keywords(document.SCORE);" target="_self">List</a>&nbsp; &nbsp;
1.589     bisitz   2002: <a href="#" onmousedown="javascript:getSel(); return false"
1.38      ng       2003:  CLASS="page">Paste Selection to List</a>&nbsp; &nbsp;
1.417     albertel 2004: <a href="javascript:kwhighlight();" target="_self">Highlight Attribute</a><br /><br />
1.38      ng       2005: KEYWORDS
1.88      www      2006: #
                   2007: # Load the other essays for similarity check
                   2008: #
1.324     albertel 2009:             my (undef,undef,$essayurl) = &Apache::lonnet::decode_symb($symb);
1.384     albertel 2010: 	    my ($adom,$aname,$apath)=($essayurl=~/^($LONCAPA::domain_re)\/($LONCAPA::username_re)\/(.*)$/);
1.359     www      2011: 	    $apath=&escape($apath);
1.88      www      2012: 	    $apath=~s/\W/\_/gs;
1.426     albertel 2013: 	    %old_essays=&Apache::lonnet::dump('nohist_essay_'.$apath,$adom,$aname);
1.41      ng       2014:         }
                   2015:     }
1.44      ng       2016: 
1.441     www      2017: # This is where output for one specific student would start
1.592     bisitz   2018:     my $add_class = ($counter%2) ? ' LC_grade_show_user_odd_row' : '';
                   2019:     $request->print(
                   2020:         "\n\n"
                   2021:        .'<div class="LC_grade_show_user'.$add_class.'">'
                   2022:        .'<h2>'.&nameUserString(undef,$env{'form.fullname'},$uname,$udom).'</h2>'
                   2023:        ."\n"
                   2024:     );
1.441     www      2025: 
1.592     bisitz   2026:     # Show additional functions if allowed
                   2027:     if ($perm{'vgr'}) {
                   2028:         $request->print(
                   2029:             &Apache::loncommon::track_student_link(
                   2030:                 &mt('View recent activity'),
                   2031:                 $uname,$udom,'check')
                   2032:            .' '
                   2033:         );
                   2034:     }
                   2035:     if ($perm{'opa'}) {
                   2036:         $request->print(
                   2037:             &Apache::loncommon::pprmlink(
                   2038:                 &mt('Set/Change parameters'),
                   2039:                 $uname,$udom,$symb,'check'));
                   2040:     }
                   2041: 
                   2042:     # Show Problem
1.257     albertel 2043:     if ($env{'form.vProb'} eq 'all' or $env{'form.vAns'} eq 'all') {
1.144     albertel 2044: 	my $mode;
1.257     albertel 2045: 	if ($env{'form.vProb'} eq 'all' && $env{'form.vAns'} eq 'all') {
1.144     albertel 2046: 	    $mode='both';
1.257     albertel 2047: 	} elsif ($env{'form.vProb'} eq 'all' ) {
1.144     albertel 2048: 	    $mode='text';
1.257     albertel 2049: 	} elsif ($env{'form.vAns'} eq 'all') {
1.144     albertel 2050: 	    $mode='answer';
                   2051: 	}
1.329     albertel 2052: 	&Apache::lonxml::clear_problem_counter();
1.475     albertel 2053: 	$request->print(&show_problem($request,$symb,$uname,$udom,1,1,$mode,{'request.prefix' => 'ctr'.$counter}));
1.58      albertel 2054:     }
1.144     albertel 2055: 
1.257     albertel 2056:     my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
1.582     raeburn  2057:     my $res_error;
                   2058:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
                   2059:     if ($res_error) {
                   2060:         $request->print(&navmap_errormsg());
                   2061:         return;
                   2062:     }
1.41      ng       2063: 
1.44      ng       2064:     # Display student info
1.41      ng       2065:     $request->print(($counter == 0 ? '' : '<br />'));
1.590     bisitz   2066: 
                   2067:     my $result='<div class="LC_Box">'
                   2068:               .'<h3 class="LC_hcell">'.&mt('Submissions').'</h3>';
1.45      ng       2069:     $result.='<input type="hidden" name="name'.$counter.
1.588     bisitz   2070:              '" value="'.$env{'form.fullname'}.'" />'."\n";
1.624     www      2071: #    if ($env{'form.handgrade'} eq 'no') {
                   2072:     if (1) {
1.588     bisitz   2073:         $result.='<p class="LC_info">'
                   2074:                 .&mt('Part(s) graded correct by the computer is marked with a [_1] symbol.',$checkIcon)
                   2075:                 ."</p>\n";
1.469     albertel 2076:     }
                   2077: 
1.118     ng       2078:     # If any part of the problem is an essay-response (handgraded), then check for collaborators
1.464     albertel 2079:     my $fullname;
                   2080:     my $col_fullnames = [];
1.624     www      2081: #    if ($env{'form.handgrade'} eq 'yes') {
                   2082:     if (1) {
1.464     albertel 2083: 	(my $sub_result,$fullname,$col_fullnames)=
                   2084: 	    &check_collaborators($symb,$uname,$udom,\%record,$handgrade,
                   2085: 				 $counter);
                   2086: 	$result.=$sub_result;
1.41      ng       2087:     }
1.44      ng       2088:     $request->print($result."\n");
1.588     bisitz   2089: 
1.44      ng       2090:     # print student answer/submission
1.588     bisitz   2091:     # Options are (1) Handgraded submission only
1.44      ng       2092:     #             (2) Last submission, includes submission that is not handgraded 
                   2093:     #                  (for multi-response type part)
                   2094:     #             (3) Last submission plus the parts info
                   2095:     #             (4) The whole record for this student
1.257     albertel 2096:     if ($env{'form.lastSub'} =~ /^(lastonly|hdgrade)$/) {
1.151     albertel 2097: 	my ($string,$timestamp)= &get_last_submission(\%record);
1.468     albertel 2098: 	
                   2099: 	my $lastsubonly;
                   2100: 
1.588     bisitz   2101:         if ($$timestamp eq '') {
                   2102:             $lastsubonly.='<div class="LC_grade_submissions_body">'.$$string[0].'</div>'; 
                   2103:         } else {
1.592     bisitz   2104:             $lastsubonly =
                   2105:                 '<div class="LC_grade_submissions_body">'
                   2106:                .'<b>'.&mt('Date Submitted:').'</b> '.$$timestamp."\n";
1.468     albertel 2107: 
1.151     albertel 2108: 	    my %seenparts;
1.375     albertel 2109: 	    my @part_response_id = &flatten_responseType($responseType);
                   2110: 	    foreach my $part (@part_response_id) {
1.393     albertel 2111: 		next if ($env{'form.lastSub'} eq 'hdgrade' 
                   2112: 			 && $$handgrade{$$part[0].'_'.$$part[1]} ne 'yes');
                   2113: 
1.375     albertel 2114: 		my ($partid,$respid) = @{ $part };
1.324     albertel 2115: 		my $display_part=&get_display_part($partid,$symb);
1.257     albertel 2116: 		if ($env{"form.$uname:$udom:$partid:submitted_by"}) {
1.151     albertel 2117: 		    if (exists($seenparts{$partid})) { next; }
                   2118: 		    $seenparts{$partid}=1;
1.207     albertel 2119: 		    my $submitby='<b>Part:</b> '.$display_part.
                   2120: 			' <b>Collaborative submission by:</b> '.
1.151     albertel 2121: 			'<a href="javascript:viewSubmitter(\''.
1.257     albertel 2122: 			$env{"form.$uname:$udom:$partid:submitted_by"}.
1.417     albertel 2123: 			'\');" target="_self">'.
1.257     albertel 2124: 			$$fullname{$env{"form.$uname:$udom:$partid:submitted_by"}}.'</a><br />';
1.151     albertel 2125: 		    $request->print($submitby);
                   2126: 		    next;
                   2127: 		}
                   2128: 		my $responsetype = $responseType->{$partid}->{$respid};
                   2129: 		if (!exists($record{"resource.$partid.$respid.submission"})) {
1.577     bisitz   2130:                     $lastsubonly.="\n".'<div class="LC_grade_submission_part">'.
                   2131:                         '<b>'.&mt('Part: [_1]',$display_part).'</b>'.
                   2132:                         ' <span class="LC_internal_info">'.
1.623     www      2133:                         '('.&mt('Response ID: [_1]',$respid).')'.
1.577     bisitz   2134:                         '</span>&nbsp; &nbsp;'.
1.539     riegler  2135: 			'<span class="LC_warning">'.&mt('Nothing submitted - no attempts.').'</span><br /><br /></div>';
1.151     albertel 2136: 		    next;
                   2137: 		}
1.468     albertel 2138: 		foreach my $submission (@$string) {
                   2139: 		    my ($partid,$respid) = ($submission =~ /^resource\.([^\.]*)\.([^\.]*)\.submission/);
1.375     albertel 2140: 		    if (join('_',@{$part}) ne ($partid.'_'.$respid)) { next; }
1.596     raeburn  2141: 		    my ($ressub,$hide,$subval) = split(/:/,$submission,3);
1.151     albertel 2142: 		    # Similarity check
                   2143: 		    my $similar='';
1.257     albertel 2144: 		    if($env{'form.checkPlag'}){
1.151     albertel 2145: 			my ($oname,$odom,$ocrsid,$oessay,$osim)=
1.426     albertel 2146: 			    &most_similar($uname,$udom,$subval,\%old_essays);
1.151     albertel 2147: 			if ($osim) {
                   2148: 			    $osim=int($osim*100.0);
1.426     albertel 2149: 			    my %old_course_desc = 
                   2150: 				&Apache::lonnet::coursedescription($ocrsid,
                   2151: 								   {'one_time' => 1});
                   2152: 
1.596     raeburn  2153:                             if ($hide) {
                   2154:                                 $similar='<hr /><span class="LC_warning">'.&mt("Essay was found to be similar to another essay submitted for this assignment.").'<br />'.
                   2155:                                          &mt('As the current submission is for an anonymous survey, no other details are available.').'</span><hr />';
                   2156:                             } else {
                   2157: 			        $similar="<hr /><h3><span class=\"LC_warning\">".
                   2158: 				    &mt('Essay is [_1]% similar to an essay by [_2] in course [_3] (course id [_4]:[_5])',
                   2159: 				        $osim,
                   2160: 				        &Apache::loncommon::plainname($oname,$odom).' ('.$oname.':'.$odom.')',
                   2161: 				        $old_course_desc{'description'},
                   2162: 				        $old_course_desc{'num'},
                   2163: 				        $old_course_desc{'domain'}).
                   2164: 				    '</span></h3><blockquote><i>'.
                   2165: 				    &keywords_highlight($oessay).
                   2166: 				    '</i></blockquote><hr />';
                   2167:                             }
1.151     albertel 2168: 			}
1.150     albertel 2169: 		    }
1.151     albertel 2170: 		    my $order=&get_order($partid,$respid,$symb,$uname,$udom);
1.257     albertel 2171: 		    if ($env{'form.lastSub'} eq 'lastonly' || 
                   2172: 			($env{'form.lastSub'} eq 'hdgrade' && 
1.377     albertel 2173: 			 $$handgrade{$$part[0].'_'.$$part[1]} eq 'yes')) {
1.324     albertel 2174: 			my $display_part=&get_display_part($partid,$symb);
1.577     bisitz   2175:                         $lastsubonly.='<div class="LC_grade_submission_part">'.
                   2176:                             '<b>'.&mt('Part: [_1]',$display_part).'</b>'.
                   2177:                             ' <span class="LC_internal_info">'.
1.623     www      2178:                             '('.&mt('Response ID: [_1]',$respid).')'.
1.597     wenzelju 2179:                             '</span>&nbsp; &nbsp;';
1.313     banghart 2180: 			my $files=&get_submitted_files($udom,$uname,$partid,$respid,\%record);
                   2181: 			if (@$files) {
1.596     raeburn  2182:                             if ($hide) {
                   2183:                                 $lastsubonly.='<br />'.&mt('[quant,_1,file] uploaded to this anonymous survey',scalar(@{$files}));
                   2184:                             } else {
                   2185:                                 $lastsubonly.='<br /><span class="LC_warning">'.&mt('Like all files provided by users, this file may contain viruses').'</span><br />';
                   2186:                                 foreach my $file (@$files) {
                   2187:                                     &Apache::lonnet::allowuploaded('/adm/grades',$file);
                   2188:                                     $lastsubonly.='<br /><a href="'.$file.'?rawmode=1" target="lonGRDs"><img src="'.&Apache::loncommon::icon($file).'" border="0" /> '.$file.'</a>';
                   2189:                                 }
                   2190:                             }
1.236     albertel 2191: 			    $lastsubonly.='<br />';
1.41      ng       2192: 			}
1.596     raeburn  2193:                         if ($hide) {
                   2194:                             $lastsubonly.='<b>'.&mt('Anonymous Survey').'</b>'; 
                   2195:                         } else {
                   2196: 			    $lastsubonly.='<b>'.&mt('Submitted Answer:').' </b>'.
                   2197: 			        &cleanRecord($subval,$responsetype,$symb,$partid,
                   2198: 					     $respid,\%record,$order,undef,$uname,$udom);
                   2199:                         }
1.151     albertel 2200: 			if ($similar) {$lastsubonly.="<br /><br />$similar\n";}
1.468     albertel 2201: 			$lastsubonly.='</div>';
1.41      ng       2202: 		    }
                   2203: 		}
                   2204: 	    }
1.588     bisitz   2205: 	    $lastsubonly.='</div>'."\n"; # End: LC_grade_submissions_body
1.151     albertel 2206: 	}
                   2207: 	$request->print($lastsubonly);
1.468     albertel 2208:    } elsif ($env{'form.lastSub'} eq 'datesub') {
1.623     www      2209:         my ($parts,$handgrade,$responseType) = &response_type($symb,\$res_error);
1.148     albertel 2210: 	$request->print(&displaySubByDates($symb,\%record,$parts,$responseType,$checkIcon,$uname,$udom));
1.257     albertel 2211:     } elsif ($env{'form.lastSub'} =~ /^(last|all)$/) {
1.41      ng       2212: 	$request->print(&Apache::loncommon::get_previous_attempt($symb,$uname,$udom,
1.257     albertel 2213: 								 $env{'request.course.id'},
1.44      ng       2214: 								 $last,'.submission',
                   2215: 								 'Apache::grades::keywords_highlight'));
1.41      ng       2216:     }
1.121     ng       2217:     $request->print('<input type="hidden" name="unamedom'.$counter.'" value="'.$uname.':'
                   2218: 	.$udom.'" />'."\n");
1.44      ng       2219:     # return if view submission with no grading option
1.619     www      2220: # FIXME: the logic seems off here. Why show the grade button if you cannot grade?
1.618     www      2221:     if (!&canmodify($usec)) {
1.120     ng       2222: 	my $toGrade.='<input type="button" value="Grade Student" '.
1.589     bisitz   2223: 	    'onclick="javascript:checksubmit(this.form,\'Grade Student\',\''
1.417     albertel 2224: 	    .$counter.'\');" target="_self" /> &nbsp;'."\n" if (&canmodify($usec));
1.468     albertel 2225: 	$toGrade.='</div>'."\n";
1.180     albertel 2226: 	$request->print($toGrade);
1.41      ng       2227: 	return;
1.180     albertel 2228:     } else {
1.468     albertel 2229: 	$request->print('</div>'."\n");
1.41      ng       2230:     }
1.33      ng       2231: 
1.121     ng       2232:     # essay grading message center
1.624     www      2233: #    if ($env{'form.handgrade'} eq 'yes') {
                   2234:     if (1) {
1.468     albertel 2235: 	my $result='<div class="LC_grade_message_center">';
                   2236:     
                   2237: 	$result.='<div class="LC_grade_message_center_header">'.
                   2238: 	    &mt('Send Message').'</div><div class="LC_grade_message_center_body">';
1.257     albertel 2239: 	my ($lastname,$givenn) = split(/,/,$env{'form.fullname'});
1.118     ng       2240: 	my $msgfor = $givenn.' '.$lastname;
1.464     albertel 2241: 	if (scalar(@$col_fullnames) > 0) {
                   2242: 	    my $lastone = pop(@$col_fullnames);
                   2243: 	    $msgfor .= ', '.(join ', ',@$col_fullnames).' and '.$lastone.'.';
1.118     ng       2244: 	}
                   2245: 	$msgfor =~ s/\'/\\'/g; #' stupid emacs - no! javascript
1.468     albertel 2246: 	$result.='<input type="hidden" name="includemsg'.$counter.'" value="" />'."\n".
1.121     ng       2247: 	    '<input type="hidden" name="newmsg'.$counter.'" value="" />'."\n";
                   2248: 	$result.='&nbsp;<a href="javascript:msgCenter(document.SCORE,'.$counter.
1.417     albertel 2249: 	    ',\''.$msgfor.'\');" target="_self">'.
1.464     albertel 2250: 	    &mt('Compose message to student').(scalar(@$col_fullnames) >= 1 ? 's' : '').'</a><label> ('.
1.350     albertel 2251: 	    &mt('incl. grades').' <input type="checkbox" name="withgrades'.$counter.'" /></label>)'.
1.118     ng       2252: 	    '<img src="'.$request->dir_config('lonIconsURL').
                   2253: 	    '/mailbkgrd.gif" width="14" height="10" name="mailicon'.$counter.'" />'."\n".
1.298     www      2254: 	    '<br />&nbsp;('.
1.468     albertel 2255: 	    &mt('Message will be sent when you click on Save &amp; Next below.').")\n";
                   2256: 	$result.='</div></div>';
1.121     ng       2257: 	$request->print($result);
1.118     ng       2258:     }
1.41      ng       2259: 
                   2260:     my %seen = ();
                   2261:     my @partlist;
1.129     ng       2262:     my @gradePartRespid;
1.375     albertel 2263:     my @part_response_id = &flatten_responseType($responseType);
1.585     bisitz   2264:     $request->print(
1.588     bisitz   2265:         '<div class="LC_Box">'
                   2266:        .'<h3 class="LC_hcell">'.&mt('Assign Grades').'</h3>'
1.585     bisitz   2267:     );
1.592     bisitz   2268:     $request->print(&gradeBox_start());
1.375     albertel 2269:     foreach my $part_response_id (@part_response_id) {
                   2270:     	my ($partid,$respid) = @{ $part_response_id };
                   2271: 	my $part_resp = join('_',@{ $part_response_id });
1.322     albertel 2272: 	next if ($seen{$partid} > 0);
1.41      ng       2273: 	$seen{$partid}++;
1.393     albertel 2274: 	next if ($$handgrade{$part_resp} ne 'yes' 
                   2275: 		 && $env{'form.lastSub'} eq 'hdgrade');
1.524     raeburn  2276: 	push(@partlist,$partid);
                   2277: 	push(@gradePartRespid,$partid.'.'.$respid);
1.322     albertel 2278: 	$request->print(&gradeBox($request,$symb,$uname,$udom,$counter,$partid,\%record));
1.41      ng       2279:     }
1.585     bisitz   2280:     $request->print(&gradeBox_end()); # </div>
                   2281:     $request->print('</div>');
1.468     albertel 2282: 
                   2283:     $request->print('<div class="LC_grade_info_links">');
                   2284:     $request->print('</div>');
                   2285: 
1.45      ng       2286:     $result='<input type="hidden" name="partlist'.$counter.
                   2287: 	'" value="'.(join ":",@partlist).'" />'."\n";
1.129     ng       2288:     $result.='<input type="hidden" name="gradePartRespid'.
                   2289: 	'" value="'.(join ":",@gradePartRespid).'" />'."\n" if ($counter == 0);
1.45      ng       2290:     my $ctr = 0;
                   2291:     while ($ctr < scalar(@partlist)) {
                   2292: 	$result.='<input type="hidden" name="partid'.$counter.'_'.$ctr.'" value="'.
                   2293: 	    $partlist[$ctr].'" />'."\n";
                   2294: 	$ctr++;
                   2295:     }
1.468     albertel 2296:     $request->print($result.''."\n");
1.41      ng       2297: 
1.441     www      2298: # Done with printing info for one student
                   2299: 
1.468     albertel 2300:     $request->print('</div>');#LC_grade_show_user
1.441     www      2301: 
                   2302: 
1.41      ng       2303:     # print end of form
                   2304:     if ($counter == $total) {
1.592     bisitz   2305:         my $endform='<br /><hr /><table border="0"><tr><td>'."\n";
1.485     albertel 2306: 	$endform.='<input type="button" value="'.&mt('Save &amp; Next').'" '.
1.589     bisitz   2307: 	    'onclick="javascript:checksubmit(this.form,\'Save & Next\','.
1.417     albertel 2308: 	    $total.','.scalar(@partlist).');" target="_self" /> &nbsp;'."\n";
1.119     ng       2309: 	my $ntstu ='<select name="NTSTU">'.
                   2310: 	    '<option>1</option><option>2</option>'.
                   2311: 	    '<option>3</option><option>5</option>'.
                   2312: 	    '<option>7</option><option>10</option></select>'."\n";
1.257     albertel 2313: 	my $nsel = ($env{'form.NTSTU'} ne '' ? $env{'form.NTSTU'} : '1');
1.401     albertel 2314: 	$ntstu =~ s/<option>$nsel</<option selected="selected">$nsel</;
1.578     raeburn  2315:         $endform.=&mt('[_1]student(s)',$ntstu);
1.485     albertel 2316: 	$endform.='&nbsp;&nbsp;<input type="button" value="'.&mt('Previous').'" '.
1.589     bisitz   2317: 	    'onclick="javascript:checksubmit(this.form,\'Previous\');" target="_self" /> &nbsp;'."\n".
1.485     albertel 2318: 	    '<input type="button" value="'.&mt('Next').'" '.
1.589     bisitz   2319: 	    'onclick="javascript:checksubmit(this.form,\'Next\');" target="_self" /> &nbsp;';
1.592     bisitz   2320:         $endform.='<span class="LC_warning">'.
                   2321:                   &mt('(Next and Previous (student) do not save the scores.)').
                   2322:                   '</span>'."\n" ;
1.349     albertel 2323:         $endform.="<input type='hidden' value='".&get_increment().
1.348     bowersj2 2324:             "' name='increment' />";
1.485     albertel 2325: 	$endform.='</td></tr></table></form>';
1.41      ng       2326: 	$request->print($endform);
                   2327:     }
                   2328:     return '';
1.38      ng       2329: }
                   2330: 
1.464     albertel 2331: sub check_collaborators {
                   2332:     my ($symb,$uname,$udom,$record,$handgrade,$counter) = @_;
                   2333:     my ($result,@col_fullnames);
                   2334:     my ($classlist,undef,$fullname) = &getclasslist('all','0');
                   2335:     foreach my $part (keys(%$handgrade)) {
                   2336: 	my $ncol = &Apache::lonnet::EXT('resource.'.$part.
                   2337: 					'.maxcollaborators',
                   2338: 					$symb,$udom,$uname);
                   2339: 	next if ($ncol <= 0);
                   2340: 	$part =~ s/\_/\./g;
                   2341: 	next if ($record->{'resource.'.$part.'.collaborators'} eq '');
                   2342: 	my (@good_collaborators, @bad_collaborators);
                   2343: 	foreach my $possible_collaborator
1.630     www      2344: 	    (split(/[,;\s]+/,$record->{'resource.'.$part.'.collaborators'})) { 
1.464     albertel 2345: 	    $possible_collaborator =~ s/[\$\^\(\)]//g;
                   2346: 	    next if ($possible_collaborator eq '');
1.631   ! www      2347: 	    my ($co_name,$co_dom) = split(/:/,$possible_collaborator);
1.464     albertel 2348: 	    $co_dom = $udom if (! defined($co_dom) || $co_dom =~ /^domain$/i);
                   2349: 	    next if ($co_name eq $uname && $co_dom eq $udom);
                   2350: 	    # Doing this grep allows 'fuzzy' specification
                   2351: 	    my @matches = grep(/^\Q$co_name\E:\Q$co_dom\E$/i, 
                   2352: 			       keys(%$classlist));
                   2353: 	    if (! scalar(@matches)) {
                   2354: 		push(@bad_collaborators, $possible_collaborator);
                   2355: 	    } else {
                   2356: 		push(@good_collaborators, @matches);
                   2357: 	    }
                   2358: 	}
                   2359: 	if (scalar(@good_collaborators) != 0) {
1.630     www      2360: 	    $result.='<br />'.&mt('Collaborators:').'<ol>';
1.464     albertel 2361: 	    foreach my $name (@good_collaborators) {
                   2362: 		my ($lastname,$givenn) = split(/,/,$$fullname{$name});
                   2363: 		push(@col_fullnames, $givenn.' '.$lastname);
1.630     www      2364: 		$result.='<li>'.$fullname->{$name}.'</li>';
1.464     albertel 2365: 	    }
1.630     www      2366: 	    $result.='</ol><br />'."\n";
1.466     albertel 2367: 	    my ($part)=split(/\./,$part);
1.464     albertel 2368: 	    $result.='<input type="hidden" name="collaborator'.$counter.
                   2369: 		'" value="'.$part.':'.(join ':',@good_collaborators).'" />'.
                   2370: 		"\n";
                   2371: 	}
                   2372: 	if (scalar(@bad_collaborators) > 0) {
1.466     albertel 2373: 	    $result.='<div class="LC_warning">';
1.464     albertel 2374: 	    $result.=&mt('This student has submitted [quant,_1,invalid collaborator]: [_2]',scalar(@bad_collaborators),join(', ',@bad_collaborators));
                   2375: 	    $result .= '</div>';
                   2376: 	}         
                   2377: 	if (scalar(@bad_collaborators > $ncol)) {
1.466     albertel 2378: 	    $result .= '<div class="LC_warning">';
1.464     albertel 2379: 	    $result .= &mt('This student has submitted too many '.
                   2380: 		'collaborators.  Maximum is [_1].',$ncol);
                   2381: 	    $result .= '</div>';
                   2382: 	}
                   2383:     }
                   2384:     return ($result,$fullname,\@col_fullnames);
                   2385: }
                   2386: 
1.44      ng       2387: #--- Retrieve the last submission for all the parts
1.38      ng       2388: sub get_last_submission {
1.119     ng       2389:     my ($returnhash)=@_;
1.596     raeburn  2390:     my (@string,$timestamp,%lasthidden);
1.119     ng       2391:     if ($$returnhash{'version'}) {
1.46      ng       2392: 	my %lasthash=();
                   2393: 	my ($version);
1.119     ng       2394: 	for ($version=1;$version<=$$returnhash{'version'};$version++) {
1.397     albertel 2395: 	    foreach my $key (sort(split(/\:/,
                   2396: 					$$returnhash{$version.':keys'}))) {
                   2397: 		$lasthash{$key}=$$returnhash{$version.':'.$key};
                   2398: 		$timestamp = 
1.545     raeburn  2399: 		    &Apache::lonlocal::locallocaltime($$returnhash{$version.':timestamp'});
1.46      ng       2400: 	    }
                   2401: 	}
1.596     raeburn  2402:         my %typeparts;
                   2403:         my $showsurv = 
                   2404:             &Apache::lonnet::allowed('vas',$env{'request.course.id'});
                   2405:         foreach my $key (sort(keys(%lasthash))) {
                   2406:             if ($key =~ /\.type$/) {
                   2407:                 if (($lasthash{$key} eq 'anonsurvey') || 
                   2408:                     ($lasthash{$key} eq 'anonsurveycred')) {
                   2409:                     my ($ign,@parts) = split(/\./,$key);
                   2410:                     pop(@parts);
                   2411:                     unless ($showsurv) {
                   2412:                         my $id = join(',',@parts);
                   2413:                         $typeparts{$ign.'.'.$id} = $lasthash{$key};
                   2414:                     }
                   2415:                     delete($lasthash{$key});
                   2416:                 }
                   2417:             }
                   2418:         }
                   2419:         my @hidden = keys(%typeparts);
1.397     albertel 2420: 	foreach my $key (keys(%lasthash)) {
                   2421: 	    next if ($key !~ /\.submission$/);
1.596     raeburn  2422:             my $hide;
                   2423:             if (@hidden) {
                   2424:                 foreach my $id (@hidden) {
                   2425:                     if ($key =~ /^\Q$id\E/) {
                   2426:                         $hide = 1;
                   2427:                         last;
                   2428:                     }
                   2429:                 }
                   2430:             }
1.397     albertel 2431: 	    my ($partid,$foo) = split(/submission$/,$key);
                   2432: 	    my $draft  = $lasthash{$partid.'awarddetail'} eq 'DRAFT' ?
1.398     albertel 2433: 		'<span class="LC_warning">Draft Copy</span> ' : '';
1.596     raeburn  2434: 	    push(@string, join(':', $key, $hide, $draft.$lasthash{$key}));
1.41      ng       2435: 	}
                   2436:     }
1.397     albertel 2437:     if (!@string) {
                   2438: 	$string[0] =
1.539     riegler  2439: 	    '<span class="LC_warning">'.&mt('Nothing submitted - no attempts.').'</span>';
1.397     albertel 2440:     }
                   2441:     return (\@string,\$timestamp);
1.38      ng       2442: }
1.35      ng       2443: 
1.44      ng       2444: #--- High light keywords, with style choosen by user.
1.38      ng       2445: sub keywords_highlight {
1.44      ng       2446:     my $string    = shift;
1.257     albertel 2447:     my $size      = $env{'form.kwsize'} eq '0' ? '' : 'size='.$env{'form.kwsize'};
                   2448:     my $styleon   = $env{'form.kwstyle'} eq ''  ? '' : $env{'form.kwstyle'};
1.41      ng       2449:     (my $styleoff = $styleon) =~ s/\</\<\//;
1.257     albertel 2450:     my @keylist   = split(/[,\s+]/,$env{'form.keywords'});
1.398     albertel 2451:     foreach my $keyword (@keylist) {
                   2452: 	$string =~ s/\b\Q$keyword\E(\b|\.)/<font color\=$env{'form.kwclr'} $size\>$styleon$keyword$styleoff<\/font>/gi;
1.41      ng       2453:     }
                   2454:     return $string;
1.38      ng       2455: }
1.36      ng       2456: 
1.44      ng       2457: #--- Called from submission routine
1.38      ng       2458: sub processHandGrade {
1.608     www      2459:     my ($request,$symb) = @_;
1.324     albertel 2460:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
1.257     albertel 2461:     my $button = $env{'form.gradeOpt'};
                   2462:     my $ngrade = $env{'form.NCT'};
                   2463:     my $ntstu  = $env{'form.NTSTU'};
1.301     albertel 2464:     my $cdom   = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   2465:     my $cnum   = $env{'course.'.$env{'request.course.id'}.'.num'};
                   2466: 
1.44      ng       2467:     if ($button eq 'Save & Next') {
                   2468: 	my $ctr = 0;
                   2469: 	while ($ctr < $ngrade) {
1.257     albertel 2470: 	    my ($uname,$udom) = split(/:/,$env{'form.unamedom'.$ctr});
1.324     albertel 2471: 	    my ($errorflag,$pts,$wgt) = &saveHandGrade($request,$symb,$uname,$udom,$ctr);
1.71      ng       2472: 	    if ($errorflag eq 'no_score') {
                   2473: 		$ctr++;
                   2474: 		next;
                   2475: 	    }
1.104     albertel 2476: 	    if ($errorflag eq 'not_allowed') {
1.398     albertel 2477: 		$request->print("<span class=\"LC_warning\">Not allowed to modify grades for $uname:$udom</span>");
1.104     albertel 2478: 		$ctr++;
                   2479: 		next;
                   2480: 	    }
1.257     albertel 2481: 	    my $includemsg = $env{'form.includemsg'.$ctr};
1.44      ng       2482: 	    my ($subject,$message,$msgstatus) = ('','','');
1.418     albertel 2483: 	    my $restitle = &Apache::lonnet::gettitle($symb);
                   2484:             my ($feedurl,$showsymb) =
                   2485: 		&get_feedurl_and_symb($symb,$uname,$udom);
                   2486: 	    my $messagetail;
1.62      albertel 2487: 	    if ($includemsg =~ /savemsg|newmsg\Q$ctr\E/) {
1.298     www      2488: 		$subject = $env{'form.msgsub'} if ($includemsg =~ /msgsub/);
1.295     www      2489: 		unless ($subject=~/\w/) { $subject=&mt('Grading Feedback'); }
1.386     raeburn  2490: 		$subject.=' ['.$restitle.']';
1.44      ng       2491: 		my (@msgnum) = split(/,/,$includemsg);
                   2492: 		foreach (@msgnum) {
1.257     albertel 2493: 		    $message.=$env{'form.'.$_} if ($_ =~ /savemsg|newmsg/ && $_ ne '');
1.44      ng       2494: 		}
1.80      ng       2495: 		$message =&Apache::lonfeedback::clear_out_html($message);
1.298     www      2496: 		if ($env{'form.withgrades'.$ctr}) {
                   2497: 		    $message.="\n\nPoint".($pts > 1 ? 's':'').' awarded = '.$pts.' out of '.$wgt;
1.386     raeburn  2498: 		    $messagetail = " for <a href=\"".
1.605     www      2499: 		                   $feedurl."?symb=$showsymb\">$restitle</a>";
1.386     raeburn  2500: 		}
                   2501: 		$msgstatus = 
                   2502:                     &Apache::lonmsg::user_normal_msg($uname,$udom,$subject,
                   2503: 						     $message.$messagetail,
1.418     albertel 2504:                                                      undef,$feedurl,undef,
1.386     raeburn  2505:                                                      undef,undef,$showsymb,
                   2506:                                                      $restitle);
1.574     bisitz   2507: 		$request->print('<br />'.&mt('Sending message to [_1]',$uname.':'.$udom).': '.
1.296     www      2508: 				$msgstatus);
1.44      ng       2509: 	    }
1.257     albertel 2510: 	    if ($env{'form.collaborator'.$ctr}) {
1.155     albertel 2511: 		my @collabstrs=&Apache::loncommon::get_env_multiple("form.collaborator$ctr");
1.150     albertel 2512: 		foreach my $collabstr (@collabstrs) {
                   2513: 		    my ($part,@collaborators) = split(/:/,$collabstr);
1.310     banghart 2514: 		    foreach my $collaborator (@collaborators) {
1.150     albertel 2515: 			my ($errorflag,$pts,$wgt) = 
1.324     albertel 2516: 			    &saveHandGrade($request,$symb,$collaborator,$udom,$ctr,
1.257     albertel 2517: 					   $env{'form.unamedom'.$ctr},$part);
1.150     albertel 2518: 			if ($errorflag eq 'not_allowed') {
1.362     albertel 2519: 			    $request->print("<span class=\"LC_error\">".&mt('Not allowed to modify grades for [_1]',"$collaborator:$udom")."</span>");
1.150     albertel 2520: 			    next;
1.418     albertel 2521: 			} elsif ($message ne '') {
                   2522: 			    my ($baseurl,$showsymb) = 
                   2523: 				&get_feedurl_and_symb($symb,$collaborator,
                   2524: 						      $udom);
                   2525: 			    if ($env{'form.withgrades'.$ctr}) {
                   2526: 				$messagetail = " for <a href=\"".
1.605     www      2527:                                     $baseurl."?symb=$showsymb\">$restitle</a>";
1.150     albertel 2528: 			    }
1.418     albertel 2529: 			    $msgstatus = 
                   2530: 				&Apache::lonmsg::user_normal_msg($collaborator,$udom,$subject,$message.$messagetail,undef,$baseurl,undef,undef,undef,$showsymb,$restitle);
1.104     albertel 2531: 			}
1.44      ng       2532: 		    }
                   2533: 		}
                   2534: 	    }
                   2535: 	    $ctr++;
                   2536: 	}
                   2537:     }
                   2538: 
1.624     www      2539: #    if ($env{'form.handgrade'} eq 'yes') {
                   2540:     if (1) {
1.119     ng       2541: 	# Keywords sorted in alphabatical order
1.257     albertel 2542: 	my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
1.119     ng       2543: 	my %keyhash = ();
1.257     albertel 2544: 	$env{'form.keywords'}           =~ s/,\s{0,}|\s+/ /g;
                   2545: 	$env{'form.keywords'}           =~ s/^\s+|\s+$//;
                   2546: 	my (@keywords) = sort(split(/\s+/,$env{'form.keywords'}));
                   2547: 	$env{'form.keywords'} = join(' ',@keywords);
                   2548: 	$keyhash{$symb.'_keywords'}     = $env{'form.keywords'};
                   2549: 	$keyhash{$symb.'_subject'}      = $env{'form.msgsub'};
                   2550: 	$keyhash{$loginuser.'_kwclr'}   = $env{'form.kwclr'};
                   2551: 	$keyhash{$loginuser.'_kwsize'}  = $env{'form.kwsize'};
                   2552: 	$keyhash{$loginuser.'_kwstyle'} = $env{'form.kwstyle'};
1.119     ng       2553: 
                   2554: 	# message center - Order of message gets changed. Blank line is eliminated.
1.257     albertel 2555: 	# New messages are saved in env for the next student.
1.119     ng       2556: 	# All messages are saved in nohist_handgrade.db
                   2557: 	my ($ctr,$idx) = (1,1);
1.257     albertel 2558: 	while ($ctr <= $env{'form.savemsgN'}) {
                   2559: 	    if ($env{'form.savemsg'.$ctr} ne '') {
                   2560: 		$keyhash{$symb.'_savemsg'.$idx} = $env{'form.savemsg'.$ctr};
1.119     ng       2561: 		$idx++;
                   2562: 	    }
                   2563: 	    $ctr++;
1.41      ng       2564: 	}
1.119     ng       2565: 	$ctr = 0;
                   2566: 	while ($ctr < $ngrade) {
1.257     albertel 2567: 	    if ($env{'form.newmsg'.$ctr} ne '') {
                   2568: 		$keyhash{$symb.'_savemsg'.$idx} = $env{'form.newmsg'.$ctr};
                   2569: 		$env{'form.savemsg'.$idx} = $env{'form.newmsg'.$ctr};
1.119     ng       2570: 		$idx++;
                   2571: 	    }
                   2572: 	    $ctr++;
1.41      ng       2573: 	}
1.257     albertel 2574: 	$env{'form.savemsgN'} = --$idx;
                   2575: 	$keyhash{$symb.'_savemsgN'} = $env{'form.savemsgN'};
1.119     ng       2576: 	my $putresult = &Apache::lonnet::put
1.301     albertel 2577: 	    ('nohist_handgrade',\%keyhash,$cdom,$cnum);
1.41      ng       2578:     }
1.44      ng       2579:     # Called by Save & Refresh from Highlight Attribute Window
1.257     albertel 2580:     my (undef,undef,$fullname) = &getclasslist($env{'form.section'},'1');
                   2581:     if ($env{'form.refresh'} eq 'on') {
1.86      ng       2582: 	my ($ctr,$total) = (0,0);
                   2583: 	while ($ctr < $ngrade) {
1.257     albertel 2584: 	    $total++ if  $env{'form.unamedom'.$ctr} ne '';
1.86      ng       2585: 	    $ctr++;
                   2586: 	}
1.257     albertel 2587: 	$env{'form.NTSTU'}=$ngrade;
1.86      ng       2588: 	$ctr = 0;
                   2589: 	while ($ctr < $total) {
1.257     albertel 2590: 	    my $processUser = $env{'form.unamedom'.$ctr};
                   2591: 	    ($env{'form.student'},$env{'form.userdom'}) = split(/:/,$processUser);
                   2592: 	    $env{'form.fullname'} = $$fullname{$processUser};
1.625     www      2593: 	    &submission($request,$ctr,$total-1,$symb);
1.41      ng       2594: 	    $ctr++;
                   2595: 	}
                   2596: 	return '';
                   2597:     }
1.36      ng       2598: 
1.121     ng       2599: # Go directly to grade student - from submission or link from chart page
1.625     www      2600: # FIXME: looks like reading off the button label!
1.120     ng       2601:     if ($button eq 'Grade Student') {
1.257     albertel 2602: 	my $processUser = $env{'form.unamedom'.$env{'form.studentNo'}};
                   2603: 	($env{'form.student'},$env{'form.userdom'}) = split(/:/,$processUser);
                   2604: 	$env{'form.fullname'} = $$fullname{$processUser};
1.625     www      2605: 	&submission($request,0,0,$symb);
1.120     ng       2606: 	return '';
                   2607:     }
                   2608: 
1.44      ng       2609:     # Get the next/previous one or group of students
1.257     albertel 2610:     my $firststu = $env{'form.unamedom0'};
                   2611:     my $laststu = $env{'form.unamedom'.($ngrade-1)};
1.119     ng       2612:     my $ctr = 2;
1.41      ng       2613:     while ($laststu eq '') {
1.257     albertel 2614: 	$laststu  = $env{'form.unamedom'.($ngrade-$ctr)};
1.41      ng       2615: 	$ctr++;
                   2616: 	$laststu = $firststu if ($ctr > $ngrade);
                   2617:     }
1.44      ng       2618: 
1.41      ng       2619:     my (@parsedlist,@nextlist);
                   2620:     my ($nextflg) = 0;
1.524     raeburn  2621:     foreach my $item (sort 
1.294     albertel 2622: 	     {
                   2623: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                   2624: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                   2625: 		 }
                   2626: 		 return $a cmp $b;
                   2627: 	     } (keys(%$fullname))) {
1.605     www      2628: # FIXME: this is fishy, looks like the button label
1.41      ng       2629: 	if ($nextflg == 1 && $button =~ /Next$/) {
1.524     raeburn  2630: 	    push(@parsedlist,$item);
1.41      ng       2631: 	}
1.524     raeburn  2632: 	$nextflg = 1 if ($item eq $laststu);
1.41      ng       2633: 	if ($button eq 'Previous') {
1.524     raeburn  2634: 	    last if ($item eq $firststu);
                   2635: 	    push(@parsedlist,$item);
1.41      ng       2636: 	}
                   2637:     }
                   2638:     $ctr = 0;
1.605     www      2639: # FIXME: this is fishy, looks like the button label
1.41      ng       2640:     @parsedlist = reverse @parsedlist if ($button eq 'Previous');
1.582     raeburn  2641:     my $res_error;
                   2642:     my ($partlist) = &response_type($symb,\$res_error);
                   2643:     if ($res_error) {
                   2644:         $request->print(&navmap_errormsg());
                   2645:         return;
                   2646:     }
1.41      ng       2647:     foreach my $student (@parsedlist) {
1.257     albertel 2648: 	my $submitonly=$env{'form.submitonly'};
1.41      ng       2649: 	my ($uname,$udom) = split(/:/,$student);
1.301     albertel 2650: 	
                   2651: 	if ($submitonly eq 'queued') {
                   2652: 	    my %queue_status = 
                   2653: 		&Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
                   2654: 							$udom,$uname);
                   2655: 	    next if (!defined($queue_status{'gradingqueue'}));
                   2656: 	}
                   2657: 
1.156     albertel 2658: 	if ($submitonly =~ /^(yes|graded|incorrect)$/) {
1.257     albertel 2659: #	    my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
1.324     albertel 2660: 	    my %status=&student_gradeStatus($symb,$udom,$uname,$partlist);
1.145     albertel 2661: 	    my $submitted = 0;
1.248     albertel 2662: 	    my $ungraded = 0;
                   2663: 	    my $incorrect = 0;
1.524     raeburn  2664: 	    foreach my $item (keys(%status)) {
                   2665: 		$submitted = 1 if ($status{$item} ne 'nothing');
                   2666: 		$ungraded = 1 if ($status{$item} =~ /^ungraded/);
                   2667: 		$incorrect = 1 if ($status{$item} =~ /^incorrect/);
                   2668: 		my ($foo,$partid,$foo1) = split(/\./,$item);
1.145     albertel 2669: 		if ($status{'resource.'.$partid.'.submitted_by'} ne '') {
                   2670: 		    $submitted = 0;
                   2671: 		}
1.41      ng       2672: 	    }
1.156     albertel 2673: 	    next if (!$submitted && ($submitonly eq 'yes' ||
                   2674: 				     $submitonly eq 'incorrect' ||
                   2675: 				     $submitonly eq 'graded'));
1.248     albertel 2676: 	    next if (!$ungraded && ($submitonly eq 'graded'));
                   2677: 	    next if (!$incorrect && $submitonly eq 'incorrect');
1.41      ng       2678: 	}
1.524     raeburn  2679: 	push(@nextlist,$student) if ($ctr < $ntstu);
1.129     ng       2680: 	last if ($ctr == $ntstu);
1.41      ng       2681: 	$ctr++;
                   2682:     }
1.36      ng       2683: 
1.41      ng       2684:     $ctr = 0;
                   2685:     my $total = scalar(@nextlist)-1;
1.39      ng       2686: 
1.524     raeburn  2687:     foreach (sort(@nextlist)) {
1.41      ng       2688: 	my ($uname,$udom,$submitter) = split(/:/);
1.257     albertel 2689: 	$env{'form.student'}  = $uname;
                   2690: 	$env{'form.userdom'}  = $udom;
                   2691: 	$env{'form.fullname'} = $$fullname{$_};
1.625     www      2692: 	&submission($request,$ctr,$total,$symb);
1.41      ng       2693: 	$ctr++;
                   2694:     }
                   2695:     if ($total < 0) {
1.485     albertel 2696: 	my $the_end = '<h3><span class="LC_info">'.&mt('LON-CAPA User Message').'</span></h3><br />'."\n";
                   2697: 	$the_end.=&mt('<b>Message: </b> No more students for this section or class.').'<br /><br />'."\n";
                   2698: 	$the_end.=&mt('Click on the button below to return to the grading menu.').'<br /><br />'."\n";
1.41      ng       2699: 	$request->print($the_end);
                   2700:     }
                   2701:     return '';
1.38      ng       2702: }
1.36      ng       2703: 
1.44      ng       2704: #---- Save the score and award for each student, if changed
1.38      ng       2705: sub saveHandGrade {
1.324     albertel 2706:     my ($request,$symb,$stuname,$domain,$newflg,$submitter,$part) = @_;
1.342     banghart 2707:     my @version_parts;
1.104     albertel 2708:     my $usec = &Apache::lonnet::getsection($domain,$stuname,
1.257     albertel 2709: 					   $env{'request.course.id'});
1.104     albertel 2710:     if (!&canmodify($usec)) { return('not_allowed'); }
1.337     banghart 2711:     my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$domain,$stuname);
1.251     banghart 2712:     my @parts_graded;
1.77      ng       2713:     my %newrecord  = ();
                   2714:     my ($pts,$wgt) = ('','');
1.269     raeburn  2715:     my %aggregate = ();
                   2716:     my $aggregateflag = 0;
1.301     albertel 2717:     my @parts = split(/:/,$env{'form.partlist'.$newflg});
                   2718:     foreach my $new_part (@parts) {
1.337     banghart 2719: 	#collaborator ($submi may vary for different parts
1.259     banghart 2720: 	if ($submitter && $new_part ne $part) { next; }
                   2721: 	my $dropMenu = $env{'form.GD_SEL'.$newflg.'_'.$new_part};
1.125     ng       2722: 	if ($dropMenu eq 'excused') {
1.259     banghart 2723: 	    if ($record{'resource.'.$new_part.'.solved'} ne 'excused') {
                   2724: 		$newrecord{'resource.'.$new_part.'.solved'} = 'excused';
                   2725: 		if (exists($record{'resource.'.$new_part.'.awarded'})) {
                   2726: 		    $newrecord{'resource.'.$new_part.'.awarded'} = '';
1.58      albertel 2727: 		}
1.364     banghart 2728: 	        $newrecord{'resource.'.$new_part.'.regrader'}="$env{'user.name'}:$env{'user.domain'}";
1.58      albertel 2729: 	    }
1.125     ng       2730: 	} elsif ($dropMenu eq 'reset status'
1.259     banghart 2731: 		 && exists($record{'resource.'.$new_part.'.solved'})) { #don't bother if no old records -> no attempts
1.524     raeburn  2732: 	    foreach my $key (keys(%record)) {
1.259     banghart 2733: 		if ($key=~/^resource\.\Q$new_part\E\./) { $newrecord{$key} = ''; }
1.197     albertel 2734: 	    }
1.259     banghart 2735: 	    $newrecord{'resource.'.$new_part.'.regrader'}=
1.257     albertel 2736: 		"$env{'user.name'}:$env{'user.domain'}";
1.270     albertel 2737:             my $totaltries = $record{'resource.'.$part.'.tries'};
                   2738: 
                   2739:             my %last_resets = &get_last_resets($symb,$env{'request.course.id'},
                   2740: 					       [$new_part]);
                   2741:             my $aggtries =$totaltries;
1.269     raeburn  2742:             if ($last_resets{$new_part}) {
1.270     albertel 2743:                 $aggtries = &get_num_tries(\%record,$last_resets{$new_part},
                   2744: 					   $new_part);
1.269     raeburn  2745:             }
1.270     albertel 2746: 
                   2747:             my $solvedstatus = $record{'resource.'.$new_part.'.solved'};
1.269     raeburn  2748:             if ($aggtries > 0) {
1.327     albertel 2749:                 &decrement_aggs($symb,$new_part,\%aggregate,$aggtries,$totaltries,$solvedstatus);
1.269     raeburn  2750:                 $aggregateflag = 1;
                   2751:             }
1.125     ng       2752: 	} elsif ($dropMenu eq '') {
1.259     banghart 2753: 	    $pts = ($env{'form.GD_BOX'.$newflg.'_'.$new_part} ne '' ? 
                   2754: 		    $env{'form.GD_BOX'.$newflg.'_'.$new_part} : 
                   2755: 		    $env{'form.RADVAL'.$newflg.'_'.$new_part});
                   2756: 	    if ($pts eq '' && $env{'form.GD_SEL'.$newflg.'_'.$new_part} eq '') {
1.153     albertel 2757: 		next;
                   2758: 	    }
1.259     banghart 2759: 	    $wgt = $env{'form.WGT'.$newflg.'_'.$new_part} eq '' ? 1 : 
                   2760: 		$env{'form.WGT'.$newflg.'_'.$new_part};
1.41      ng       2761: 	    my $partial= $pts/$wgt;
1.259     banghart 2762: 	    if ($partial eq $record{'resource.'.$new_part.'.awarded'}) {
1.153     albertel 2763: 		#do not update score for part if not changed.
1.346     banghart 2764:                 &handback_files($request,$symb,$stuname,$domain,$newflg,$new_part,\%newrecord);
1.153     albertel 2765: 		next;
1.251     banghart 2766: 	    } else {
1.524     raeburn  2767: 	        push(@parts_graded,$new_part);
1.153     albertel 2768: 	    }
1.259     banghart 2769: 	    if ($record{'resource.'.$new_part.'.awarded'} ne $partial) {
                   2770: 		$newrecord{'resource.'.$new_part.'.awarded'}  = $partial;
1.153     albertel 2771: 	    }
1.259     banghart 2772: 	    my $reckey = 'resource.'.$new_part.'.solved';
1.41      ng       2773: 	    if ($partial == 0) {
1.153     albertel 2774: 		if ($record{$reckey} ne 'incorrect_by_override') {
                   2775: 		    $newrecord{$reckey} = 'incorrect_by_override';
                   2776: 		}
1.41      ng       2777: 	    } else {
1.153     albertel 2778: 		if ($record{$reckey} ne 'correct_by_override') {
                   2779: 		    $newrecord{$reckey} = 'correct_by_override';
                   2780: 		}
                   2781: 	    }	    
                   2782: 	    if ($submitter && 
1.259     banghart 2783: 		($record{'resource.'.$new_part.'.submitted_by'} ne $submitter)) {
                   2784: 		$newrecord{'resource.'.$new_part.'.submitted_by'} = $submitter;
1.41      ng       2785: 	    }
1.259     banghart 2786: 	    $newrecord{'resource.'.$new_part.'.regrader'}=
1.257     albertel 2787: 		"$env{'user.name'}:$env{'user.domain'}";
1.41      ng       2788: 	}
1.259     banghart 2789: 	# unless problem has been graded, set flag to version the submitted files
1.305     banghart 2790: 	unless ($record{'resource.'.$new_part.'.solved'} =~ /^correct_/  || 
                   2791: 	        $record{'resource.'.$new_part.'.solved'} eq 'incorrect_by_override' ||
                   2792: 	        $dropMenu eq 'reset status')
                   2793: 	   {
1.524     raeburn  2794: 	    push(@version_parts,$new_part);
1.259     banghart 2795: 	}
1.41      ng       2796:     }
1.301     albertel 2797:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   2798:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   2799: 
1.344     albertel 2800:     if (%newrecord) {
                   2801:         if (@version_parts) {
1.364     banghart 2802:             my @changed_keys = &version_portfiles(\%record, \@parts_graded, 
                   2803:                                 $env{'request.course.id'}, $symb, $domain, $stuname, \@version_parts);
1.344     albertel 2804: 	    @newrecord{@changed_keys} = @record{@changed_keys};
1.367     albertel 2805: 	    foreach my $new_part (@version_parts) {
                   2806: 		&handback_files($request,$symb,$stuname,$domain,$newflg,
                   2807: 				$new_part,\%newrecord);
                   2808: 	    }
1.259     banghart 2809:         }
1.44      ng       2810: 	&Apache::lonnet::cstore(\%newrecord,$symb,
1.257     albertel 2811: 				$env{'request.course.id'},$domain,$stuname);
1.380     albertel 2812: 	&check_and_remove_from_queue(\@parts,\%record,\%newrecord,$symb,
                   2813: 				     $cdom,$cnum,$domain,$stuname);
1.41      ng       2814:     }
1.269     raeburn  2815:     if ($aggregateflag) {
                   2816:         &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
1.301     albertel 2817: 			      $cdom,$cnum);
1.269     raeburn  2818:     }
1.301     albertel 2819:     return ('',$pts,$wgt);
1.36      ng       2820: }
1.322     albertel 2821: 
1.380     albertel 2822: sub check_and_remove_from_queue {
                   2823:     my ($parts,$record,$newrecord,$symb,$cdom,$cnum,$domain,$stuname) = @_;
                   2824:     my @ungraded_parts;
                   2825:     foreach my $part (@{$parts}) {
                   2826: 	if (    $record->{   'resource.'.$part.'.awarded'} eq ''
                   2827: 	     && $record->{   'resource.'.$part.'.solved' } ne 'excused'
                   2828: 	     && $newrecord->{'resource.'.$part.'.awarded'} eq ''
                   2829: 	     && $newrecord->{'resource.'.$part.'.solved' } ne 'excused'
                   2830: 		) {
                   2831: 	    push(@ungraded_parts, $part);
                   2832: 	}
                   2833:     }
                   2834:     if ( !@ungraded_parts ) {
                   2835: 	&Apache::bridgetask::remove_from_queue('gradingqueue',$symb,$cdom,
                   2836: 					       $cnum,$domain,$stuname);
                   2837:     }
                   2838: }
                   2839: 
1.337     banghart 2840: sub handback_files {
                   2841:     my ($request,$symb,$stuname,$domain,$newflg,$new_part,$newrecord) = @_;
1.517     raeburn  2842:     my $portfolio_root = '/userfiles/portfolio';
1.582     raeburn  2843:     my $res_error;
                   2844:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
                   2845:     if ($res_error) {
                   2846:         $request->print('<br />'.&navmap_errormsg().'<br />');
                   2847:         return;
                   2848:     }
1.375     albertel 2849:     my @part_response_id = &flatten_responseType($responseType);
                   2850:     foreach my $part_response_id (@part_response_id) {
                   2851:     	my ($part_id,$resp_id) = @{ $part_response_id };
                   2852: 	my $part_resp = join('_',@{ $part_response_id });
1.337     banghart 2853:             if (($env{'form.'.$newflg.'_'.$part_resp.'_returndoc1'}) && ($new_part == $part_id)) {
                   2854:                 # if multiple files are uploaded names will be 'returndoc2','returndoc3'
                   2855:                 my $file_counter = 1;
1.367     albertel 2856: 		my $file_msg;
1.337     banghart 2857:                 while ($env{'form.'.$newflg.'_'.$part_resp.'_returndoc'.$file_counter}) {
                   2858:                     my $fname=$env{'form.'.$newflg.'_'.$part_resp.'_returndoc'.$file_counter.'.filename'};
1.338     banghart 2859:                     my ($directory,$answer_file) = 
                   2860:                         ($env{'form.'.$newflg.'_'.$part_resp.'_origdoc'.$file_counter} =~ /^(.*?)([^\/]*)$/);
                   2861:                     my ($answer_name,$answer_ver,$answer_ext) =
                   2862: 		        &file_name_version_ext($answer_file);
1.355     banghart 2863: 		    my ($portfolio_path) = ($directory =~ /^.+$stuname\/portfolio(.*)/);
1.517     raeburn  2864:                     my $getpropath = 1;
                   2865: 		    my @dir_list = &Apache::lonnet::dirlist($portfolio_root.$portfolio_path,$domain,$stuname,$getpropath);
1.338     banghart 2866: 		    my $version = &get_next_version($answer_name, $answer_ext, \@dir_list);
1.355     banghart 2867:                     # fix file name
                   2868:                     my ($save_file_name) = (($directory.$answer_name.".$version.".$answer_ext) =~ /^.+\/${stuname}\/(.*)/);
                   2869:                     my $result=&Apache::lonnet::finishuserfileupload($stuname,$domain,
                   2870:             	                                $newflg.'_'.$part_resp.'_returndoc'.$file_counter,
                   2871:             	                                $save_file_name);
1.337     banghart 2872:                     if ($result !~ m|^/uploaded/|) {
1.536     raeburn  2873:                         $request->print('<br /><span class="LC_error">'.
                   2874:                             &mt('An error occurred ([_1]) while trying to upload [_2].',
                   2875:                                 $result,$newflg.'_'.$part_resp.'_returndoc'.$file_counter).
                   2876:                                         '</span>');
1.356     banghart 2877:                     } else {
1.360     banghart 2878:                         # mark the file as read only
                   2879:                         my @files = ($save_file_name);
1.372     albertel 2880:                         my @what = ($symb,$env{'request.course.id'},'handback');
1.360     banghart 2881:                         &Apache::lonnet::mark_as_readonly($domain,$stuname,\@files,\@what);
1.367     albertel 2882: 			if (exists($$newrecord{"resource.$new_part.$resp_id.handback"})) {
                   2883: 			    $$newrecord{"resource.$new_part.$resp_id.handback"}.=',';
                   2884: 			}
                   2885:                         $$newrecord{"resource.$new_part.$resp_id.handback"} .= $save_file_name;
                   2886: 			$file_msg.= "\n".'<br /><span class="LC_filename"><a href="/uploaded/'."$domain/$stuname/".$save_file_name.'">'.$save_file_name."</a></span><br />";
                   2887: 
1.337     banghart 2888:                     }
                   2889:                     $request->print("<br />".$fname." will be the uploaded file name");
1.354     albertel 2890:                     $request->print(" ".$env{'form.'.$newflg.'_'.$part_resp.'_origdoc'.$file_counter});
1.337     banghart 2891:                     $file_counter++;
                   2892:                 }
1.367     albertel 2893: 		my $subject = "File Handed Back by Instructor ";
                   2894: 		my $message = "A file has been returned that was originally submitted in reponse to: <br />";
                   2895: 		$message .= "<strong>".&Apache::lonnet::gettitle($symb)."</strong><br />";
                   2896: 		$message .= ' The returned file(s) are named: '. $file_msg;
                   2897: 		$message .= " and can be found in your portfolio space.";
1.418     albertel 2898: 		my ($feedurl,$showsymb) = 
                   2899: 		    &get_feedurl_and_symb($symb,$domain,$stuname);
1.386     raeburn  2900:                 my $restitle = &Apache::lonnet::gettitle($symb);
                   2901: 		my $msgstatus = 
                   2902:                    &Apache::lonmsg::user_normal_msg($stuname,$domain,$subject.
                   2903: 			 ' (File Returned) ['.$restitle.']',$message,undef,
1.418     albertel 2904:                          $feedurl,undef,undef,undef,$showsymb,$restitle);
1.337     banghart 2905:             }
                   2906:         }
1.338     banghart 2907:     return;
1.337     banghart 2908: }
                   2909: 
1.418     albertel 2910: sub get_feedurl_and_symb {
                   2911:     my ($symb,$uname,$udom) = @_;
                   2912:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
                   2913:     $url = &Apache::lonnet::clutter($url);
                   2914:     my $encrypturl=&Apache::lonnet::EXT('resource.0.encrypturl',
                   2915: 					$symb,$udom,$uname);
                   2916:     if ($encrypturl =~ /^yes$/i) {
                   2917: 	&Apache::lonenc::encrypted(\$url,1);
                   2918: 	&Apache::lonenc::encrypted(\$symb,1);
                   2919:     }
                   2920:     return ($url,$symb);
                   2921: }
                   2922: 
1.313     banghart 2923: sub get_submitted_files {
                   2924:     my ($udom,$uname,$partid,$respid,$record) = @_;
                   2925:     my @files;
                   2926:     if ($$record{"resource.$partid.$respid.portfiles"}) {
                   2927:         my $file_url = '/uploaded/'.$udom.'/'.$uname.'/portfolio';
                   2928:         foreach my $file (split(',',$$record{"resource.$partid.$respid.portfiles"})) {
                   2929:     	    push(@files,$file_url.$file);
                   2930:         }
                   2931:     }
                   2932:     if ($$record{"resource.$partid.$respid.uploadedurl"}) {
                   2933:         push(@files,$$record{"resource.$partid.$respid.uploadedurl"});
                   2934:     }
                   2935:     return (\@files);
                   2936: }
1.322     albertel 2937: 
1.269     raeburn  2938: # ----------- Provides number of tries since last reset.
                   2939: sub get_num_tries {
                   2940:     my ($record,$last_reset,$part) = @_;
                   2941:     my $timestamp = '';
                   2942:     my $num_tries = 0;
                   2943:     if ($$record{'version'}) {
                   2944:         for (my $version=$$record{'version'};$version>=1;$version--) {
                   2945:             if (exists($$record{$version.':resource.'.$part.'.solved'})) {
                   2946:                 $timestamp = $$record{$version.':timestamp'};
                   2947:                 if ($timestamp > $last_reset) {
                   2948:                     $num_tries ++;
                   2949:                 } else {
                   2950:                     last;
                   2951:                 }
                   2952:             }
                   2953:         }
                   2954:     }
                   2955:     return $num_tries;
                   2956: }
                   2957: 
                   2958: # ----------- Determine decrements required in aggregate totals 
                   2959: sub decrement_aggs {
                   2960:     my ($symb,$part,$aggregate,$aggtries,$totaltries,$solvedstatus) = @_;
                   2961:     my %decrement = (
                   2962:                         attempts => 0,
                   2963:                         users => 0,
                   2964:                         correct => 0
                   2965:                     );
                   2966:     $decrement{'attempts'} = $aggtries;
                   2967:     if ($solvedstatus =~ /^correct/) {
                   2968:         $decrement{'correct'} = 1;
                   2969:     }
                   2970:     if ($aggtries == $totaltries) {
                   2971:         $decrement{'users'} = 1;
                   2972:     }
1.524     raeburn  2973:     foreach my $type (keys(%decrement)) {
1.269     raeburn  2974:         $$aggregate{$symb."\0".$part."\0".$type} = -$decrement{$type};
                   2975:     }
                   2976:     return;
                   2977: }
                   2978: 
                   2979: # ----------- Determine timestamps for last reset of aggregate totals for parts  
                   2980: sub get_last_resets {
1.270     albertel 2981:     my ($symb,$courseid,$partids) =@_;
                   2982:     my %last_resets;
1.269     raeburn  2983:     my $cdom = $env{'course.'.$courseid.'.domain'};
                   2984:     my $cname = $env{'course.'.$courseid.'.num'};
1.271     albertel 2985:     my @keys;
                   2986:     foreach my $part (@{$partids}) {
                   2987: 	push(@keys,"$symb\0$part\0resettime");
                   2988:     }
                   2989:     my %results=&Apache::lonnet::get('nohist_resourcetracker',\@keys,
                   2990: 				     $cdom,$cname);
                   2991:     foreach my $part (@{$partids}) {
                   2992: 	$last_resets{$part}=$results{"$symb\0$part\0resettime"};
1.269     raeburn  2993:     }
1.270     albertel 2994:     return %last_resets;
1.269     raeburn  2995: }
                   2996: 
1.251     banghart 2997: # ----------- Handles creating versions for portfolio files as answers
                   2998: sub version_portfiles {
1.343     banghart 2999:     my ($record, $parts_graded, $courseid, $symb, $domain, $stu_name, $v_flag) = @_;
1.263     banghart 3000:     my $version_parts = join('|',@$v_flag);
1.343     banghart 3001:     my @returned_keys;
1.255     banghart 3002:     my $parts = join('|', @$parts_graded);
1.517     raeburn  3003:     my $portfolio_root = '/userfiles/portfolio';
1.277     albertel 3004:     foreach my $key (keys(%$record)) {
1.259     banghart 3005:         my $new_portfiles;
1.263     banghart 3006:         if ($key =~ /^resource\.($version_parts)\./ && $key =~ /\.portfiles$/ ) {
1.342     banghart 3007:             my @versioned_portfiles;
1.367     albertel 3008:             my @portfiles = split(/\s*,\s*/,$$record{$key});
1.252     banghart 3009:             foreach my $file (@portfiles) {
1.306     banghart 3010:                 &Apache::lonnet::unmark_as_readonly($domain,$stu_name,[$symb,$env{'request.course.id'}],$file);
1.304     albertel 3011:                 my ($directory,$answer_file) =($file =~ /^(.*?)([^\/]*)$/);
                   3012: 		my ($answer_name,$answer_ver,$answer_ext) =
                   3013: 		    &file_name_version_ext($answer_file);
1.517     raeburn  3014:                 my $getpropath = 1;    
                   3015:                 my @dir_list = &Apache::lonnet::dirlist($portfolio_root.$directory,$domain,$stu_name,$getpropath);
1.342     banghart 3016:                 my $version = &get_next_version($answer_name, $answer_ext, \@dir_list);
1.306     banghart 3017:                 my $new_answer = &version_selected_portfile($domain, $stu_name, $directory, $answer_file, $version);
                   3018:                 if ($new_answer ne 'problem getting file') {
1.342     banghart 3019:                     push(@versioned_portfiles, $directory.$new_answer);
1.306     banghart 3020:                     &Apache::lonnet::mark_as_readonly($domain,$stu_name,
1.367     albertel 3021:                         [$directory.$new_answer],
1.306     banghart 3022:                         [$symb,$env{'request.course.id'},'graded']);
1.259     banghart 3023:                 }
1.252     banghart 3024:             }
1.343     banghart 3025:             $$record{$key} = join(',',@versioned_portfiles);
                   3026:             push(@returned_keys,$key);
1.251     banghart 3027:         }
                   3028:     } 
1.343     banghart 3029:     return (@returned_keys);   
1.305     banghart 3030: }
                   3031: 
1.307     banghart 3032: sub get_next_version {
1.341     banghart 3033:     my ($answer_name, $answer_ext, $dir_list) = @_;
1.307     banghart 3034:     my $version;
                   3035:     foreach my $row (@$dir_list) {
                   3036:         my ($file) = split(/\&/,$row,2);
                   3037:         my ($file_name,$file_version,$file_ext) =
                   3038: 	    &file_name_version_ext($file);
                   3039:         if (($file_name eq $answer_name) && 
                   3040: 	    ($file_ext eq $answer_ext)) {
                   3041:                 # gets here if filename and extension match, regardless of version
                   3042:                 if ($file_version ne '') {
                   3043:                 # a versioned file is found  so save it for later
                   3044:                 if ($file_version > $version) {
                   3045: 		    $version = $file_version;
                   3046: 	        }
                   3047:             }
                   3048:         }
                   3049:     } 
                   3050:     $version ++;
                   3051:     return($version);
                   3052: }
                   3053: 
1.305     banghart 3054: sub version_selected_portfile {
1.306     banghart 3055:     my ($domain,$stu_name,$directory,$file_name,$version) = @_;
                   3056:     my ($answer_name,$answer_ver,$answer_ext) =
                   3057:         &file_name_version_ext($file_name);
                   3058:     my $new_answer;
                   3059:     $env{'form.copy'} = &Apache::lonnet::getfile("/uploaded/$domain/$stu_name/portfolio$directory$file_name");
                   3060:     if($env{'form.copy'} eq '-1') {
                   3061:         $new_answer = 'problem getting file';
                   3062:     } else {
                   3063:         $new_answer = $answer_name.'.'.$version.'.'.$answer_ext;
                   3064:         my $copy_result = &Apache::lonnet::finishuserfileupload(
                   3065:                             $stu_name,$domain,'copy',
                   3066: 		        '/portfolio'.$directory.$new_answer);
                   3067:     }    
                   3068:     return ($new_answer);
1.251     banghart 3069: }
                   3070: 
1.304     albertel 3071: sub file_name_version_ext {
                   3072:     my ($file)=@_;
                   3073:     my @file_parts = split(/\./, $file);
                   3074:     my ($name,$version,$ext);
                   3075:     if (@file_parts > 1) {
                   3076: 	$ext=pop(@file_parts);
                   3077: 	if (@file_parts > 1 && $file_parts[-1] =~ /^\d+$/) {
                   3078: 	    $version=pop(@file_parts);
                   3079: 	}
                   3080: 	$name=join('.',@file_parts);
                   3081:     } else {
                   3082: 	$name=join('.',@file_parts);
                   3083:     }
                   3084:     return($name,$version,$ext);
                   3085: }
                   3086: 
1.44      ng       3087: #--------------------------------------------------------------------------------------
                   3088: #
                   3089: #-------------------------- Next few routines handles grading by section or whole class
                   3090: #
                   3091: #--- Javascript to handle grading by section or whole class
1.42      ng       3092: sub viewgrades_js {
                   3093:     my ($request) = shift;
                   3094: 
1.539     riegler  3095:     my $alertmsg = &mt('A number equal or greater than 0 is expected. Entered value = ');
1.597     wenzelju 3096:     $request->print(&Apache::lonhtmlcommon::scripttag(<<VIEWJAVASCRIPT));
1.45      ng       3097:    function writePoint(partid,weight,point) {
1.125     ng       3098: 	var radioButton = document.classgrade["RADVAL_"+partid];
                   3099: 	var textbox = document.classgrade["TEXTVAL_"+partid];
1.42      ng       3100: 	if (point == "textval") {
1.125     ng       3101: 	    point = document.classgrade["TEXTVAL_"+partid].value;
1.109     matthew  3102: 	    if (isNaN(point) || parseFloat(point) < 0) {
1.539     riegler  3103: 		alert("$alertmsg"+parseFloat(point));
1.42      ng       3104: 		var resetbox = false;
                   3105: 		for (var i=0; i<radioButton.length; i++) {
                   3106: 		    if (radioButton[i].checked) {
                   3107: 			textbox.value = i;
                   3108: 			resetbox = true;
                   3109: 		    }
                   3110: 		}
                   3111: 		if (!resetbox) {
                   3112: 		    textbox.value = "";
                   3113: 		}
                   3114: 		return;
                   3115: 	    }
1.109     matthew  3116: 	    if (parseFloat(point) > parseFloat(weight)) {
                   3117: 		var resp = confirm("You entered a value ("+parseFloat(point)+
1.44      ng       3118: 				   ") greater than the weight for the part. Accept?");
                   3119: 		if (resp == false) {
                   3120: 		    textbox.value = "";
                   3121: 		    return;
                   3122: 		}
                   3123: 	    }
1.42      ng       3124: 	    for (var i=0; i<radioButton.length; i++) {
                   3125: 		radioButton[i].checked=false;
1.109     matthew  3126: 		if (parseFloat(point) == i) {
1.42      ng       3127: 		    radioButton[i].checked=true;
                   3128: 		}
                   3129: 	    }
1.41      ng       3130: 
1.42      ng       3131: 	} else {
1.125     ng       3132: 	    textbox.value = parseFloat(point);
1.42      ng       3133: 	}
1.41      ng       3134: 	for (i=0;i<document.classgrade.total.value;i++) {
1.125     ng       3135: 	    var user = document.classgrade["ctr"+i].value;
1.289     albertel 3136: 	    user = user.replace(new RegExp(':', 'g'),"_");
1.125     ng       3137: 	    var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
                   3138: 	    var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
                   3139: 	    var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
1.42      ng       3140: 	    if (saveval != "correct") {
                   3141: 		scorename.value = point;
1.43      ng       3142: 		if (selname[0].selected != true) {
                   3143: 		    selname[0].selected = true;
                   3144: 		}
1.42      ng       3145: 	    }
                   3146: 	}
1.125     ng       3147: 	document.classgrade["SELVAL_"+partid][0].selected = true;
1.42      ng       3148:     }
                   3149: 
                   3150:     function writeRadText(partid,weight) {
1.125     ng       3151: 	var selval   = document.classgrade["SELVAL_"+partid];
                   3152: 	var radioButton = document.classgrade["RADVAL_"+partid];
1.265     www      3153:         var override = document.classgrade["FORCE_"+partid].checked;
1.125     ng       3154: 	var textbox = document.classgrade["TEXTVAL_"+partid];
                   3155: 	if (selval[1].selected || selval[2].selected) {
1.42      ng       3156: 	    for (var i=0; i<radioButton.length; i++) {
                   3157: 		radioButton[i].checked=false;
                   3158: 
                   3159: 	    }
                   3160: 	    textbox.value = "";
                   3161: 
                   3162: 	    for (i=0;i<document.classgrade.total.value;i++) {
1.125     ng       3163: 		var user = document.classgrade["ctr"+i].value;
1.289     albertel 3164: 		user = user.replace(new RegExp(':', 'g'),"_");
1.125     ng       3165: 		var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
                   3166: 		var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
                   3167: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
1.265     www      3168: 		if ((saveval != "correct") || override) {
1.42      ng       3169: 		    scorename.value = "";
1.125     ng       3170: 		    if (selval[1].selected) {
                   3171: 			selname[1].selected = true;
                   3172: 		    } else {
                   3173: 			selname[2].selected = true;
                   3174: 			if (Number(document.classgrade["GD_"+user+"_"+partid+"_tries"].value)) 
                   3175: 			{document.classgrade["GD_"+user+"_"+partid+"_tries"].value = '0';}
                   3176: 		    }
1.42      ng       3177: 		}
                   3178: 	    }
1.43      ng       3179: 	} else {
                   3180: 	    for (i=0;i<document.classgrade.total.value;i++) {
1.125     ng       3181: 		var user = document.classgrade["ctr"+i].value;
1.289     albertel 3182: 		user = user.replace(new RegExp(':', 'g'),"_");
1.125     ng       3183: 		var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
                   3184: 		var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
                   3185: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
1.265     www      3186: 		if ((saveval != "correct") || override) {
1.125     ng       3187: 		    scorename.value = document.classgrade["GD_"+user+"_"+partid+"_awarded_s"].value;
1.43      ng       3188: 		    selname[0].selected = true;
                   3189: 		}
                   3190: 	    }
                   3191: 	}	    
1.42      ng       3192:     }
                   3193: 
                   3194:     function changeSelect(partid,user) {
1.125     ng       3195: 	var selval = document.classgrade["GD_"+user+'_'+partid+"_solved"];
                   3196: 	var textbox = document.classgrade["GD_"+user+'_'+partid+"_awarded"];
1.44      ng       3197: 	var point  = textbox.value;
1.125     ng       3198: 	var weight = document.classgrade["weight_"+partid].value;
1.44      ng       3199: 
1.109     matthew  3200: 	if (isNaN(point) || parseFloat(point) < 0) {
1.539     riegler  3201: 	    alert("$alertmsg"+parseFloat(point));
1.44      ng       3202: 	    textbox.value = "";
                   3203: 	    return;
                   3204: 	}
1.109     matthew  3205: 	if (parseFloat(point) > parseFloat(weight)) {
                   3206: 	    var resp = confirm("You entered a value ("+parseFloat(point)+
1.44      ng       3207: 			       ") greater than the weight of the part. Accept?");
                   3208: 	    if (resp == false) {
                   3209: 		textbox.value = "";
                   3210: 		return;
                   3211: 	    }
                   3212: 	}
1.42      ng       3213: 	selval[0].selected = true;
                   3214:     }
                   3215: 
                   3216:     function changeOneScore(partid,user) {
1.125     ng       3217: 	var selval = document.classgrade["GD_"+user+'_'+partid+"_solved"];
                   3218: 	if (selval[1].selected || selval[2].selected) {
                   3219: 	    document.classgrade["GD_"+user+'_'+partid+"_awarded"].value = "";
                   3220: 	    if (selval[2].selected) {
                   3221: 		document.classgrade["GD_"+user+'_'+partid+"_tries"].value = "0";
                   3222: 	    }
1.269     raeburn  3223:         }
1.42      ng       3224:     }
                   3225: 
                   3226:     function resetEntry(numpart) {
                   3227: 	for (ctpart=0;ctpart<numpart;ctpart++) {
1.125     ng       3228: 	    var partid = document.classgrade["partid_"+ctpart].value;
                   3229: 	    var radioButton = document.classgrade["RADVAL_"+partid];
                   3230: 	    var textbox = document.classgrade["TEXTVAL_"+partid];
                   3231: 	    var selval  = document.classgrade["SELVAL_"+partid];
1.42      ng       3232: 	    for (var i=0; i<radioButton.length; i++) {
                   3233: 		radioButton[i].checked=false;
                   3234: 
                   3235: 	    }
                   3236: 	    textbox.value = "";
                   3237: 	    selval[0].selected = true;
                   3238: 
                   3239: 	    for (i=0;i<document.classgrade.total.value;i++) {
1.125     ng       3240: 		var user = document.classgrade["ctr"+i].value;
1.289     albertel 3241: 		user = user.replace(new RegExp(':', 'g'),"_");
1.125     ng       3242: 		var resetscore = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
                   3243: 		resetscore.value = document.classgrade["GD_"+user+"_"+partid+"_awarded_s"].value;
                   3244: 		var resettries = document.classgrade["GD_"+user+"_"+partid+"_tries"];
                   3245: 		resettries.value = document.classgrade["GD_"+user+"_"+partid+"_tries_s"].value;
                   3246: 		var saveselval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
                   3247: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
1.42      ng       3248: 		if (saveselval == "excused") {
1.43      ng       3249: 		    if (selname[1].selected == false) { selname[1].selected = true;}
1.42      ng       3250: 		} else {
1.43      ng       3251: 		    if (selname[0].selected == false) {selname[0].selected = true};
1.42      ng       3252: 		}
                   3253: 	    }
1.41      ng       3254: 	}
1.42      ng       3255:     }
                   3256: 
1.41      ng       3257: VIEWJAVASCRIPT
1.42      ng       3258: }
                   3259: 
1.44      ng       3260: #--- show scores for a section or whole class w/ option to change/update a score
1.42      ng       3261: sub viewgrades {
1.608     www      3262:     my ($request,$symb) = @_;
1.42      ng       3263:     &viewgrades_js($request);
1.41      ng       3264: 
1.168     albertel 3265:     #need to make sure we have the correct data for later EXT calls, 
                   3266:     #thus invalidate the cache
                   3267:     &Apache::lonnet::devalidatecourseresdata(
1.257     albertel 3268:                  $env{'course.'.$env{'request.course.id'}.'.num'},
                   3269:                  $env{'course.'.$env{'request.course.id'}.'.domain'});
1.168     albertel 3270:     &Apache::lonnet::clear_EXT_cache_status();
                   3271: 
1.398     albertel 3272:     my $result='<h3><span class="LC_info">'.&mt('Manual Grading').'</span></h3>';
1.41      ng       3273: 
                   3274:     #view individual student submission form - called using Javascript viewOneStudent
1.324     albertel 3275:     $result.=&jscriptNform($symb);
1.41      ng       3276: 
1.44      ng       3277:     #beginning of class grading form
1.442     banghart 3278:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
1.41      ng       3279:     $result.= '<form action="/adm/grades" method="post" name="classgrade">'."\n".
1.418     albertel 3280: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.38      ng       3281: 	'<input type="hidden" name="command" value="editgrades" />'."\n".
1.432     banghart 3282: 	&build_section_inputs().
1.442     banghart 3283: 	'<input type="hidden" name="Status" value="'.$env{'stu_status'}.'" />'."\n".
1.72      ng       3284: 
1.560     raeburn  3285:     my ($common_header,$specific_header);
1.257     albertel 3286:     if ($env{'form.section'} eq 'all') {
1.560     raeburn  3287: 	$common_header = &mt('Assign Common Grade to Class');
                   3288:         $specific_header = &mt('Assign Grade to Specific Students in Class');
1.257     albertel 3289:     } elsif ($env{'form.section'} eq 'none') {
1.560     raeburn  3290:         $common_header = &mt('Assign Common Grade to Students in no Section');
                   3291: 	$specific_header = &mt('Assign Grade to Specific Students in no Section');
1.52      albertel 3292:     } else {
1.560     raeburn  3293:         my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
                   3294:         $common_header = &mt('Assign Common Grade to Students in Section(s) [_1]',$section_display);
                   3295: 	$specific_header = &mt('Assign Grade to Specific Students in Section(s) [_1]',$section_display);
1.52      albertel 3296:     }
1.560     raeburn  3297:     $result.= '<h3>'.$common_header.'</h3>'.&Apache::loncommon::start_data_table();
1.44      ng       3298:     #radio buttons/text box for assigning points for a section or class.
                   3299:     #handles different parts of a problem
1.582     raeburn  3300:     my $res_error;
                   3301:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
                   3302:     if ($res_error) {
                   3303:         return &navmap_errormsg();
                   3304:     }
1.42      ng       3305:     my %weight = ();
                   3306:     my $ctsparts = 0;
1.45      ng       3307:     my %seen = ();
1.375     albertel 3308:     my @part_response_id = &flatten_responseType($responseType);
                   3309:     foreach my $part_response_id (@part_response_id) {
                   3310:     	my ($partid,$respid) = @{ $part_response_id };
                   3311: 	my $part_resp = join('_',@{ $part_response_id });
1.45      ng       3312: 	next if $seen{$partid};
                   3313: 	$seen{$partid}++;
1.375     albertel 3314: 	my $handgrade=$$handgrade{$part_resp};
1.42      ng       3315: 	my $wgt = &Apache::lonnet::EXT('resource.'.$partid.'.weight',$symb);
                   3316: 	$weight{$partid} = $wgt eq '' ? '1' : $wgt;
                   3317: 
1.324     albertel 3318: 	my $display_part=&get_display_part($partid,$symb);
1.485     albertel 3319: 	my $radio.='<table border="0"><tr>';  
1.41      ng       3320: 	my $ctr = 0;
1.42      ng       3321: 	while ($ctr<=$weight{$partid}) { # display radio buttons in a nice table 10 across
1.485     albertel 3322: 	    $radio.= '<td><label><input type="radio" name="RADVAL_'.$partid.'" '.
1.54      albertel 3323: 		'onclick="javascript:writePoint(\''.$partid.'\','.$weight{$partid}.
1.288     albertel 3324: 		','.$ctr.')" />'.$ctr."</label></td>\n";
1.41      ng       3325: 	    $result.=(($ctr+1)%10 == 0 ? '</tr><tr>' : '');
                   3326: 	    $ctr++;
                   3327: 	}
1.485     albertel 3328: 	$radio.='</tr></table>';
                   3329: 	my $line = '<input type="text" name="TEXTVAL_'.
1.589     bisitz   3330: 	    $partid.'" size="4" '.'onchange="javascript:writePoint(\''.
1.54      albertel 3331: 		$partid.'\','.$weight{$partid}.',\'textval\')" /> /'.
1.539     riegler  3332: 	    $weight{$partid}.' '.&mt('(problem weight)').'</td>'."\n";
                   3333: 	$line.= '<td><b>'.&mt('Grade Status').':</b><select name="SELVAL_'.$partid.'"'.
1.589     bisitz   3334: 	    'onchange="javascript:writeRadText(\''.$partid.'\','.
1.59      albertel 3335: 		$weight{$partid}.')"> '.
1.401     albertel 3336: 	    '<option selected="selected"> </option>'.
1.485     albertel 3337: 	    '<option value="excused">'.&mt('excused').'</option>'.
                   3338: 	    '<option value="reset status">'.&mt('reset status').'</option>'.
                   3339: 	    '</select></td>'.
                   3340:             '<td><label><input type="checkbox" name="FORCE_'.$partid.'" />'.&mt('Override "Correct"').'</label>';
                   3341: 	$line.='<input type="hidden" name="partid_'.
                   3342: 	    $ctsparts.'" value="'.$partid.'" />'."\n";
                   3343: 	$line.='<input type="hidden" name="weight_'.
                   3344: 	    $partid.'" value="'.$weight{$partid}.'" />'."\n";
                   3345: 
                   3346: 	$result.=
                   3347: 	    &Apache::loncommon::start_data_table_row()."\n".
1.577     bisitz   3348: 	    '<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 3349: 	    &Apache::loncommon::end_data_table_row()."\n";
1.42      ng       3350: 	$ctsparts++;
1.41      ng       3351:     }
1.474     albertel 3352:     $result.=&Apache::loncommon::end_data_table()."\n".
1.52      albertel 3353: 	'<input type="hidden" name="totalparts" value="'.$ctsparts.'" />';
1.485     albertel 3354:     $result.='<input type="button" value="'.&mt('Revert to Default').'" '.
1.589     bisitz   3355: 	'onclick="javascript:resetEntry('.$ctsparts.');" />';
1.41      ng       3356: 
1.44      ng       3357:     #table listing all the students in a section/class
                   3358:     #header of table
1.560     raeburn  3359:     $result.= '<h3>'.$specific_header.'</h3>'.
                   3360:               &Apache::loncommon::start_data_table().
                   3361: 	      &Apache::loncommon::start_data_table_header_row().
                   3362: 	      '<th>'.&mt('No.').'</th>'.
                   3363: 	      '<th>'.&nameUserString('header')."</th>\n";
1.582     raeburn  3364:     my $partserror;
                   3365:     my (@parts) = sort(&getpartlist($symb,\$partserror));
                   3366:     if ($partserror) {
                   3367:         return &navmap_errormsg();
                   3368:     }
1.324     albertel 3369:     my (undef,undef,$url)=&Apache::lonnet::decode_symb($symb);
1.269     raeburn  3370:     my @partids = ();
1.41      ng       3371:     foreach my $part (@parts) {
                   3372: 	my $display=&Apache::lonnet::metadata($url,$part.'.display');
1.539     riegler  3373:         my $narrowtext = &mt('Tries');
                   3374: 	$display =~ s|^Number of Attempts|$narrowtext <br />|; # makes the column narrower
1.41      ng       3375: 	if  (!$display) { $display = &Apache::lonnet::metadata($url,$part.'.name'); }
1.207     albertel 3376: 	my ($partid) = &split_part_type($part);
1.524     raeburn  3377:         push(@partids,$partid);
1.628     www      3378: #
                   3379: # FIXME: Looks like $display looks at English text
                   3380: #
1.324     albertel 3381: 	my $display_part=&get_display_part($partid,$symb);
1.41      ng       3382: 	if ($display =~ /^Partial Credit Factor/) {
1.485     albertel 3383: 	    $result.='<th>'.
                   3384: 		&mt('Score Part: [_1]<br /> (weight = [_2])',
                   3385: 		    $display_part,$weight{$partid}).'</th>'."\n";
1.41      ng       3386: 	    next;
1.485     albertel 3387: 	    
1.207     albertel 3388: 	} else {
1.485     albertel 3389: 	    if ($display =~ /Problem Status/) {
                   3390: 		my $grade_status_mt = &mt('Grade Status');
                   3391: 		$display =~ s{Problem Status}{$grade_status_mt<br />};
                   3392: 	    }
                   3393: 	    my $part_mt = &mt('Part:');
                   3394: 	    $display =~s{\[Part: \Q$partid\E\]}{$part_mt $display_part};
1.41      ng       3395: 	}
1.485     albertel 3396: 
1.474     albertel 3397: 	$result.='<th>'.$display.'</th>'."\n";
1.41      ng       3398:     }
1.474     albertel 3399:     $result.=&Apache::loncommon::end_data_table_header_row();
1.44      ng       3400: 
1.270     albertel 3401:     my %last_resets = 
                   3402: 	&get_last_resets($symb,$env{'request.course.id'},\@partids);
1.269     raeburn  3403: 
1.41      ng       3404:     #get info for each student
1.44      ng       3405:     #list all the students - with points and grade status
1.257     albertel 3406:     my (undef,undef,$fullname) = &getclasslist($env{'form.section'},'1');
1.41      ng       3407:     my $ctr = 0;
1.294     albertel 3408:     foreach (sort 
                   3409: 	     {
                   3410: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                   3411: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                   3412: 		 }
                   3413: 		 return $a cmp $b;
                   3414: 	     } (keys(%$fullname))) {
1.126     ng       3415: 	$ctr++;
1.324     albertel 3416: 	$result.=&viewstudentgrade($symb,$env{'request.course.id'},
1.269     raeburn  3417: 				   $_,$$fullname{$_},\@parts,\%weight,$ctr,\%last_resets);
1.41      ng       3418:     }
1.474     albertel 3419:     $result.=&Apache::loncommon::end_data_table();
1.41      ng       3420:     $result.='<input type="hidden" name="total" value="'.$ctr.'" />'."\n";
1.485     albertel 3421:     $result.='<input type="button" value="'.&mt('Save').'" '.
1.589     bisitz   3422: 	'onclick="javascript:submit();" target="_self" /></form>'."\n";
1.96      albertel 3423:     if (scalar(%$fullname) eq 0) {
                   3424: 	my $colspan=3+scalar(@parts);
1.433     banghart 3425: 	my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
1.442     banghart 3426:         my $stu_status = join(' or ',&Apache::loncommon::get_env_multiple('form.Status'));
1.433     banghart 3427: 	$result='<span class="LC_warning">'.
1.485     albertel 3428: 	    &mt('There are no students in section(s) [_1] with enrollment status [_2] to modify or grade.',
1.442     banghart 3429: 	        $section_display, $stu_status).
1.433     banghart 3430: 	    '</span>';
1.96      albertel 3431:     }
1.41      ng       3432:     return $result;
                   3433: }
                   3434: 
1.44      ng       3435: #--- call by previous routine to display each student
1.41      ng       3436: sub viewstudentgrade {
1.324     albertel 3437:     my ($symb,$courseid,$student,$fullname,$parts,$weight,$ctr,$last_resets) = @_;
1.44      ng       3438:     my ($uname,$udom) = split(/:/,$student);
                   3439:     my %record=&Apache::lonnet::restore($symb,$courseid,$udom,$uname);
1.269     raeburn  3440:     my %aggregates = (); 
1.474     albertel 3441:     my $result=&Apache::loncommon::start_data_table_row().'<td align="right">'.
1.233     albertel 3442: 	'<input type="hidden" name="ctr'.($ctr-1).'" value="'.$student.'" />'.
                   3443: 	"\n".$ctr.'&nbsp;</td><td>&nbsp;'.
1.44      ng       3444: 	'<a href="javascript:viewOneStudent(\''.$uname.'\',\''.$udom.
1.417     albertel 3445: 	'\');" target="_self">'.$fullname.'</a> '.
1.398     albertel 3446: 	'<span class="LC_internal_info">('.$uname.($env{'user.domain'} eq $udom ? '' : ':'.$udom).')</span></td>'."\n";
1.281     albertel 3447:     $student=~s/:/_/; # colon doen't work in javascript for names
1.63      albertel 3448:     foreach my $apart (@$parts) {
                   3449: 	my ($part,$type) = &split_part_type($apart);
1.41      ng       3450: 	my $score=$record{"resource.$part.$type"};
1.276     albertel 3451:         $result.='<td align="center">';
1.269     raeburn  3452:         my ($aggtries,$totaltries);
                   3453:         unless (exists($aggregates{$part})) {
1.270     albertel 3454: 	    $totaltries = $record{'resource.'.$part.'.tries'};
                   3455: 
                   3456: 	    $aggtries = $totaltries;
1.269     raeburn  3457:             if ($$last_resets{$part}) {  
1.270     albertel 3458:                 $aggtries = &get_num_tries(\%record,$$last_resets{$part},
                   3459: 					   $part);
                   3460:             }
1.269     raeburn  3461:             $result.='<input type="hidden" name="'.
                   3462:                 'GD_'.$student.'_'.$part.'_aggtries" value="'.$aggtries.'" />'."\n";
                   3463:             $result.='<input type="hidden" name="'.
                   3464:                 'GD_'.$student.'_'.$part.'_totaltries" value="'.$totaltries.'" />'."\n";
                   3465:             $aggregates{$part} = 1;
                   3466:         }
1.41      ng       3467: 	if ($type eq 'awarded') {
1.320     albertel 3468: 	    my $pts = $score eq '' ? '' : &compute_points($score,$$weight{$part});
1.42      ng       3469: 	    $result.='<input type="hidden" name="'.
1.89      albertel 3470: 		'GD_'.$student.'_'.$part.'_awarded_s" value="'.$pts.'" />'."\n";
1.233     albertel 3471: 	    $result.='<input type="text" name="'.
1.89      albertel 3472: 		'GD_'.$student.'_'.$part.'_awarded" '.
1.589     bisitz   3473:                 'onchange="javascript:changeSelect(\''.$part.'\',\''.$student.
1.44      ng       3474: 		'\')" value="'.$pts.'" size="4" /></td>'."\n";
1.41      ng       3475: 	} elsif ($type eq 'solved') {
                   3476: 	    my ($status,$foo)=split(/_/,$score,2);
                   3477: 	    $status = 'nothing' if ($status eq '');
1.89      albertel 3478: 	    $result.='<input type="hidden" name="'.'GD_'.$student.'_'.
1.54      albertel 3479: 		$part.'_solved_s" value="'.$status.'" />'."\n";
1.233     albertel 3480: 	    $result.='&nbsp;<select name="'.
1.89      albertel 3481: 		'GD_'.$student.'_'.$part.'_solved" '.
1.589     bisitz   3482:                 'onchange="javascript:changeOneScore(\''.$part.'\',\''.$student.'\')" >'."\n";
1.485     albertel 3483: 	    $result.= (($status eq 'excused') ? '<option> </option><option selected="selected" value="excused">'.&mt('excused').'</option>' 
                   3484: 		: '<option selected="selected"> </option><option value="excused">'.&mt('excused').'</option>')."\n";
                   3485: 	    $result.='<option value="reset status">'.&mt('reset status').'</option>';
1.126     ng       3486: 	    $result.="</select>&nbsp;</td>\n";
1.122     ng       3487: 	} else {
                   3488: 	    $result.='<input type="hidden" name="'.
                   3489: 		'GD_'.$student.'_'.$part.'_'.$type.'_s" value="'.$score.'" />'.
                   3490: 		    "\n";
1.233     albertel 3491: 	    $result.='<input type="text" name="'.
1.122     ng       3492: 		'GD_'.$student.'_'.$part.'_'.$type.'" '.
                   3493: 		'value="'.$score.'" size="4" /></td>'."\n";
1.41      ng       3494: 	}
                   3495:     }
1.474     albertel 3496:     $result.=&Apache::loncommon::end_data_table_row();
1.41      ng       3497:     return $result;
1.38      ng       3498: }
                   3499: 
1.44      ng       3500: #--- change scores for all the students in a section/class
                   3501: #    record does not get update if unchanged
1.38      ng       3502: sub editgrades {
1.608     www      3503:     my ($request,$symb) = @_;
1.41      ng       3504: 
1.433     banghart 3505:     my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
1.477     albertel 3506:     my $title='<h2>'.&mt('Current Grade Status').'</h2>';
1.433     banghart 3507:     $title.='<h4>'.&mt('<b>Section: </b>[_1]',$section_display).'</h4>'."\n";
1.126     ng       3508: 
1.477     albertel 3509:     my $result= &Apache::loncommon::start_data_table().
                   3510: 	&Apache::loncommon::start_data_table_header_row().
                   3511: 	'<th rowspan="2" valign="middle">'.&mt('No.').'</th>'.
                   3512: 	'<th rowspan="2" valign="middle">'.&nameUserString('header')."</th>\n";
1.43      ng       3513:     my %scoreptr = (
                   3514: 		    'correct'  =>'correct_by_override',
                   3515: 		    'incorrect'=>'incorrect_by_override',
                   3516: 		    'excused'  =>'excused',
                   3517: 		    'ungraded' =>'ungraded_attempted',
1.596     raeburn  3518:                     'credited' =>'credit_attempted',
1.43      ng       3519: 		    'nothing'  => '',
                   3520: 		    );
1.257     albertel 3521:     my ($classlist,undef,$fullname) = &getclasslist($env{'form.section'},'0');
1.34      ng       3522: 
1.44      ng       3523:     my (@partid);
                   3524:     my %weight = ();
1.54      albertel 3525:     my %columns = ();
1.44      ng       3526:     my ($i,$ctr,$count,$rec_update) = (0,0,0,0);
1.54      albertel 3527: 
1.582     raeburn  3528:     my $partserror;
                   3529:     my (@parts) = sort(&getpartlist($symb,\$partserror));
                   3530:     if ($partserror) {
                   3531:         return &navmap_errormsg();
                   3532:     }
1.54      albertel 3533:     my $header;
1.257     albertel 3534:     while ($ctr < $env{'form.totalparts'}) {
                   3535: 	my $partid = $env{'form.partid_'.$ctr};
1.524     raeburn  3536: 	push(@partid,$partid);
1.257     albertel 3537: 	$weight{$partid} = $env{'form.weight_'.$partid};
1.44      ng       3538: 	$ctr++;
1.54      albertel 3539:     }
1.324     albertel 3540:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
1.54      albertel 3541:     foreach my $partid (@partid) {
1.478     albertel 3542: 	$header .= '<th align="center">'.&mt('Old Score').'</th>'.
                   3543: 	    '<th align="center">'.&mt('New Score').'</th>';
1.54      albertel 3544: 	$columns{$partid}=2;
                   3545: 	foreach my $stores (@parts) {
                   3546: 	    my ($part,$type) = &split_part_type($stores);
                   3547: 	    if ($part !~ m/^\Q$partid\E/) { next;}
                   3548: 	    if ($type eq 'awarded' || $type eq 'solved') { next; }
                   3549: 	    my $display=&Apache::lonnet::metadata($url,$stores.'.display');
1.551     raeburn  3550: 	    $display =~ s/\[Part: \Q$part\E\]//;
1.539     riegler  3551:             my $narrowtext = &mt('Tries');
                   3552: 	    $display =~ s/Number of Attempts/$narrowtext/;
                   3553: 	    $header .= '<th align="center">'.&mt('Old').' '.$display.'</th>'.
                   3554: 		'<th align="center">'.&mt('New').' '.$display.'</th>';
1.54      albertel 3555: 	    $columns{$partid}+=2;
                   3556: 	}
                   3557:     }
                   3558:     foreach my $partid (@partid) {
1.324     albertel 3559: 	my $display_part=&get_display_part($partid,$symb);
1.478     albertel 3560: 	$result .= '<th colspan="'.$columns{$partid}.'" align="center">'.
                   3561: 	    &mt('Part: [_1] (Weight = [_2])',$display_part,$weight{$partid}).
                   3562: 	    '</th>';
1.54      albertel 3563: 
1.44      ng       3564:     }
1.477     albertel 3565:     $result .= &Apache::loncommon::end_data_table_header_row().
                   3566: 	&Apache::loncommon::start_data_table_header_row().
                   3567: 	$header.
                   3568: 	&Apache::loncommon::end_data_table_header_row();
                   3569:     my @noupdate;
1.126     ng       3570:     my ($updateCtr,$noupdateCtr) = (1,1);
1.257     albertel 3571:     for ($i=0; $i<$env{'form.total'}; $i++) {
1.93      albertel 3572: 	my $line;
1.257     albertel 3573: 	my $user = $env{'form.ctr'.$i};
1.281     albertel 3574: 	my ($uname,$udom)=split(/:/,$user);
1.44      ng       3575: 	my %newrecord;
                   3576: 	my $updateflag = 0;
1.281     albertel 3577: 	$line .= '<td>'.&nameUserString(undef,$$fullname{$user},$uname,$udom).'</td>';
1.108     albertel 3578: 	my $usec=$classlist->{"$uname:$udom"}[5];
1.105     albertel 3579: 	if (!&canmodify($usec)) {
1.126     ng       3580: 	    my $numcols=scalar(@partid)*4+2;
1.477     albertel 3581: 	    push(@noupdate,
1.478     albertel 3582: 		 $line."<td colspan=\"$numcols\"><span class=\"LC_warning\">".
                   3583: 		 &mt('Not allowed to modify student')."</span></td></tr>");
1.105     albertel 3584: 	    next;
                   3585: 	}
1.269     raeburn  3586:         my %aggregate = ();
                   3587:         my $aggregateflag = 0;
1.281     albertel 3588: 	$user=~s/:/_/; # colon doen't work in javascript for names
1.44      ng       3589: 	foreach (@partid) {
1.257     albertel 3590: 	    my $old_aw    = $env{'form.GD_'.$user.'_'.$_.'_awarded_s'};
1.54      albertel 3591: 	    my $old_part_pcr = $old_aw/($weight{$_} ne '0' ? $weight{$_}:1);
                   3592: 	    my $old_part  = $old_aw eq '' ? '' : $old_part_pcr;
1.257     albertel 3593: 	    my $old_score = $scoreptr{$env{'form.GD_'.$user.'_'.$_.'_solved_s'}};
                   3594: 	    my $awarded   = $env{'form.GD_'.$user.'_'.$_.'_awarded'};
1.54      albertel 3595: 	    my $pcr       = $awarded/($weight{$_} ne '0' ? $weight{$_} : 1);
                   3596: 	    my $partial   = $awarded eq '' ? '' : $pcr;
1.44      ng       3597: 	    my $score;
                   3598: 	    if ($partial eq '') {
1.257     albertel 3599: 		$score = $scoreptr{$env{'form.GD_'.$user.'_'.$_.'_solved_s'}};
1.44      ng       3600: 	    } elsif ($partial > 0) {
                   3601: 		$score = 'correct_by_override';
                   3602: 	    } elsif ($partial == 0) {
                   3603: 		$score = 'incorrect_by_override';
                   3604: 	    }
1.257     albertel 3605: 	    my $dropMenu = $env{'form.GD_'.$user.'_'.$_.'_solved'};
1.125     ng       3606: 	    $score = 'excused' if (($dropMenu eq 'excused') && ($score ne 'excused'));
                   3607: 
1.292     albertel 3608: 	    $newrecord{'resource.'.$_.'.regrader'}=
                   3609: 		"$env{'user.name'}:$env{'user.domain'}";
1.125     ng       3610: 	    if ($dropMenu eq 'reset status' &&
                   3611: 		$old_score ne '') { # ignore if no previous attempts => nothing to reset
1.299     albertel 3612: 		$newrecord{'resource.'.$_.'.tries'} = '';
1.125     ng       3613: 		$newrecord{'resource.'.$_.'.solved'} = '';
                   3614: 		$newrecord{'resource.'.$_.'.award'} = '';
1.299     albertel 3615: 		$newrecord{'resource.'.$_.'.awarded'} = '';
1.125     ng       3616: 		$updateflag = 1;
1.269     raeburn  3617:                 if ($env{'form.GD_'.$user.'_'.$_.'_aggtries'} > 0) {
                   3618:                     my $aggtries = $env{'form.GD_'.$user.'_'.$_.'_aggtries'};
                   3619:                     my $totaltries = $env{'form.GD_'.$user.'_'.$_.'_totaltries'};
                   3620:                     my $solvedstatus = $env{'form.GD_'.$user.'_'.$_.'_solved_s'};
                   3621:                     &decrement_aggs($symb,$_,\%aggregate,$aggtries,$totaltries,$solvedstatus);
                   3622:                     $aggregateflag = 1;
                   3623:                 }
1.139     albertel 3624: 	    } elsif (!($old_part eq $partial && $old_score eq $score)) {
                   3625: 		$updateflag = 1;
                   3626: 		$newrecord{'resource.'.$_.'.awarded'}  = $partial if $partial ne '';
                   3627: 		$newrecord{'resource.'.$_.'.solved'}   = $score;
                   3628: 		$rec_update++;
1.125     ng       3629: 	    }
                   3630: 
1.93      albertel 3631: 	    $line .= '<td align="center">'.$old_aw.'&nbsp;</td>'.
1.44      ng       3632: 		'<td align="center">'.$awarded.
                   3633: 		($score eq 'excused' ? $score : '').'&nbsp;</td>';
1.5       albertel 3634: 
1.54      albertel 3635: 
                   3636: 	    my $partid=$_;
                   3637: 	    foreach my $stores (@parts) {
                   3638: 		my ($part,$type) = &split_part_type($stores);
                   3639: 		if ($part !~ m/^\Q$partid\E/) { next;}
                   3640: 		if ($type eq 'awarded' || $type eq 'solved') { next; }
1.257     albertel 3641: 		my $old_aw    = $env{'form.GD_'.$user.'_'.$part.'_'.$type.'_s'};
                   3642: 		my $awarded   = $env{'form.GD_'.$user.'_'.$part.'_'.$type};
1.54      albertel 3643: 		if ($awarded ne '' && $awarded ne $old_aw) {
                   3644: 		    $newrecord{'resource.'.$part.'.'.$type}= $awarded;
1.257     albertel 3645: 		    $newrecord{'resource.'.$part.'.regrader'}="$env{'user.name'}:$env{'user.domain'}";
1.54      albertel 3646: 		    $updateflag=1;
                   3647: 		}
1.93      albertel 3648: 		$line .= '<td align="center">'.$old_aw.'&nbsp;</td>'.
1.54      albertel 3649: 		    '<td align="center">'.$awarded.'&nbsp;</td>';
                   3650: 	    }
1.44      ng       3651: 	}
1.477     albertel 3652: 	$line.="\n";
1.301     albertel 3653: 
                   3654: 	my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   3655: 	my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   3656: 
1.44      ng       3657: 	if ($updateflag) {
                   3658: 	    $count++;
1.257     albertel 3659: 	    &Apache::lonnet::cstore(\%newrecord,$symb,$env{'request.course.id'},
1.89      albertel 3660: 				    $udom,$uname);
1.301     albertel 3661: 
                   3662: 	    if (&Apache::bridgetask::in_queue('gradingqueue',$symb,$cdom,
                   3663: 					      $cnum,$udom,$uname)) {
                   3664: 		# need to figure out if should be in queue.
                   3665: 		my %record =  
                   3666: 		    &Apache::lonnet::restore($symb,$env{'request.course.id'},
                   3667: 					     $udom,$uname);
                   3668: 		my $all_graded = 1;
                   3669: 		my $none_graded = 1;
                   3670: 		foreach my $part (@parts) {
                   3671: 		    if ( $record{'resource.'.$part.'.awarded'} eq '' ) {
                   3672: 			$all_graded = 0;
                   3673: 		    } else {
                   3674: 			$none_graded = 0;
                   3675: 		    }
                   3676: 		}
                   3677: 
                   3678: 		if ($all_graded || $none_graded) {
                   3679: 		    &Apache::bridgetask::remove_from_queue('gradingqueue',
                   3680: 							   $symb,$cdom,$cnum,
                   3681: 							   $udom,$uname);
                   3682: 		}
                   3683: 	    }
                   3684: 
1.477     albertel 3685: 	    $result.=&Apache::loncommon::start_data_table_row().
                   3686: 		'<td align="right">&nbsp;'.$updateCtr.'&nbsp;</td>'.$line.
                   3687: 		&Apache::loncommon::end_data_table_row();
1.126     ng       3688: 	    $updateCtr++;
1.93      albertel 3689: 	} else {
1.477     albertel 3690: 	    push(@noupdate,
                   3691: 		 '<td align="right">&nbsp;'.$noupdateCtr.'&nbsp;</td>'.$line);
1.126     ng       3692: 	    $noupdateCtr++;
1.44      ng       3693: 	}
1.269     raeburn  3694:         if ($aggregateflag) {
                   3695:             &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
1.301     albertel 3696: 				  $cdom,$cnum);
1.269     raeburn  3697:         }
1.93      albertel 3698:     }
1.477     albertel 3699:     if (@noupdate) {
1.126     ng       3700: #	my $numcols=(scalar(@partid)*(scalar(@parts)-1)*2)+3;
                   3701: 	my $numcols=scalar(@partid)*4+2;
1.477     albertel 3702: 	$result .= &Apache::loncommon::start_data_table_row('LC_empty_row').
1.478     albertel 3703: 	    '<td align="center" colspan="'.$numcols.'">'.
                   3704: 	    &mt('No Changes Occurred For the Students Below').
                   3705: 	    '</td>'.
1.477     albertel 3706: 	    &Apache::loncommon::end_data_table_row();
                   3707: 	foreach my $line (@noupdate) {
                   3708: 	    $result.=
                   3709: 		&Apache::loncommon::start_data_table_row().
                   3710: 		$line.
                   3711: 		&Apache::loncommon::end_data_table_row();
                   3712: 	}
1.44      ng       3713:     }
1.614     www      3714:     $result .= &Apache::loncommon::end_data_table();
1.478     albertel 3715:     my $msg = '<p><b>'.
                   3716: 	&mt('Number of records updated = [_1] for [quant,_2,student].',
                   3717: 	    $rec_update,$count).'</b><br />'.
                   3718: 	'<b>'.&mt('Total number of students = [_1]',$env{'form.total'}).
                   3719: 	'</b></p>';
1.44      ng       3720:     return $title.$msg.$result;
1.5       albertel 3721: }
1.54      albertel 3722: 
                   3723: sub split_part_type {
                   3724:     my ($partstr) = @_;
                   3725:     my ($temp,@allparts)=split(/_/,$partstr);
                   3726:     my $type=pop(@allparts);
1.439     albertel 3727:     my $part=join('_',@allparts);
1.54      albertel 3728:     return ($part,$type);
                   3729: }
                   3730: 
1.44      ng       3731: #------------- end of section for handling grading by section/class ---------
                   3732: #
                   3733: #----------------------------------------------------------------------------
                   3734: 
1.5       albertel 3735: 
1.44      ng       3736: #----------------------------------------------------------------------------
                   3737: #
                   3738: #-------------------------- Next few routines handles grading by csv upload
                   3739: #
                   3740: #--- Javascript to handle csv upload
1.27      albertel 3741: sub csvupload_javascript_reverse_associate {
1.573     bisitz   3742:     my $error1=&mt('You need to specify the username or the student/employee ID');
1.246     albertel 3743:     my $error2=&mt('You need to specify at least one grading field');
1.27      albertel 3744:   return(<<ENDPICK);
                   3745:   function verify(vf) {
                   3746:     var foundsomething=0;
                   3747:     var founduname=0;
1.243     albertel 3748:     var foundID=0;
1.27      albertel 3749:     for (i=0;i<=vf.nfields.value;i++) {
                   3750:       tw=eval('vf.f'+i+'.selectedIndex');
1.243     albertel 3751:       if (i==0 && tw!=0) { foundID=1; }
                   3752:       if (i==1 && tw!=0) { founduname=1; }
                   3753:       if (i!=0 && i!=1 && i!=2 && tw!=0) { foundsomething=1; }
1.27      albertel 3754:     }
1.246     albertel 3755:     if (founduname==0 && foundID==0) {
                   3756: 	alert('$error1');
                   3757: 	return;
1.27      albertel 3758:     }
                   3759:     if (foundsomething==0) {
1.246     albertel 3760: 	alert('$error2');
                   3761: 	return;
1.27      albertel 3762:     }
                   3763:     vf.submit();
                   3764:   }
                   3765:   function flip(vf,tf) {
                   3766:     var nw=eval('vf.f'+tf+'.selectedIndex');
                   3767:     var i;
                   3768:     for (i=0;i<=vf.nfields.value;i++) {
                   3769:       //can not pick the same destination field for both name and domain
                   3770:       if (((i ==0)||(i ==1)) && 
                   3771:           ((tf==0)||(tf==1)) && 
                   3772:           (i!=tf) &&
                   3773:           (eval('vf.f'+i+'.selectedIndex')==nw)) {
                   3774:         eval('vf.f'+i+'.selectedIndex=0;')
                   3775:       }
                   3776:     }
                   3777:   }
                   3778: ENDPICK
                   3779: }
                   3780: 
                   3781: sub csvupload_javascript_forward_associate {
1.573     bisitz   3782:     my $error1=&mt('You need to specify the username or the student/employee ID');
1.246     albertel 3783:     my $error2=&mt('You need to specify at least one grading field');
1.27      albertel 3784:   return(<<ENDPICK);
                   3785:   function verify(vf) {
                   3786:     var foundsomething=0;
                   3787:     var founduname=0;
1.243     albertel 3788:     var foundID=0;
1.27      albertel 3789:     for (i=0;i<=vf.nfields.value;i++) {
                   3790:       tw=eval('vf.f'+i+'.selectedIndex');
1.243     albertel 3791:       if (tw==1) { foundID=1; }
                   3792:       if (tw==2) { founduname=1; }
                   3793:       if (tw>3) { foundsomething=1; }
1.27      albertel 3794:     }
1.246     albertel 3795:     if (founduname==0 && foundID==0) {
                   3796: 	alert('$error1');
                   3797: 	return;
1.27      albertel 3798:     }
                   3799:     if (foundsomething==0) {
1.246     albertel 3800: 	alert('$error2');
                   3801: 	return;
1.27      albertel 3802:     }
                   3803:     vf.submit();
                   3804:   }
                   3805:   function flip(vf,tf) {
                   3806:     var nw=eval('vf.f'+tf+'.selectedIndex');
                   3807:     var i;
                   3808:     //can not pick the same destination field twice
                   3809:     for (i=0;i<=vf.nfields.value;i++) {
                   3810:       if ((i!=tf) && (eval('vf.f'+i+'.selectedIndex')==nw)) {
                   3811:         eval('vf.f'+i+'.selectedIndex=0;')
                   3812:       }
                   3813:     }
                   3814:   }
                   3815: ENDPICK
                   3816: }
                   3817: 
1.26      albertel 3818: sub csvuploadmap_header {
1.324     albertel 3819:     my ($request,$symb,$datatoken,$distotal)= @_;
1.41      ng       3820:     my $javascript;
1.257     albertel 3821:     if ($env{'form.upfile_associate'} eq 'reverse') {
1.41      ng       3822: 	$javascript=&csvupload_javascript_reverse_associate();
                   3823:     } else {
                   3824: 	$javascript=&csvupload_javascript_forward_associate();
                   3825:     }
1.45      ng       3826: 
1.598     www      3827:     my $result='';
1.418     albertel 3828:     $symb = &Apache::lonenc::check_encrypt($symb);
1.41      ng       3829:     $request->print(<<ENDPICK);
1.26      albertel 3830: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
1.398     albertel 3831: <h3><span class="LC_info">Uploading Class Grades</span></h3>
1.45      ng       3832: $result
1.326     albertel 3833: <hr />
1.26      albertel 3834: <h3>Identify fields</h3>
                   3835: Total number of records found in file: $distotal <hr />
                   3836: Enter as many fields as you can. The system will inform you and bring you back
                   3837: to this page if the data selected is insufficient to run your class.<hr />
1.589     bisitz   3838: <input type="button" value="Reverse Association" onclick="javascript:this.form.associate.value='Reverse Association';submit(this.form);" />
1.26      albertel 3839: <input type="hidden" name="associate"  value="" />
                   3840: <input type="hidden" name="phase"      value="three" />
                   3841: <input type="hidden" name="datatoken"  value="$datatoken" />
1.257     albertel 3842: <input type="hidden" name="fileupload" value="$env{'form.fileupload'}" />
                   3843: <input type="hidden" name="upfiletype" value="$env{'form.upfiletype'}" />
1.26      albertel 3844: <input type="hidden" name="upfile_associate" 
1.257     albertel 3845:                                        value="$env{'form.upfile_associate'}" />
1.26      albertel 3846: <input type="hidden" name="symb"       value="$symb" />
1.246     albertel 3847: <input type="hidden" name="command"    value="csvuploadoptions" />
1.26      albertel 3848: <hr />
                   3849: ENDPICK
1.597     wenzelju 3850:     $request->print(&Apache::lonhtmlcommon::scripttag($javascript));
1.118     ng       3851:     return '';
1.26      albertel 3852: 
                   3853: }
                   3854: 
                   3855: sub csvupload_fields {
1.582     raeburn  3856:     my ($symb,$errorref) = @_;
                   3857:     my (@parts) = &getpartlist($symb,$errorref);
                   3858:     if (ref($errorref)) {
                   3859:         if ($$errorref) {
                   3860:             return;
                   3861:         }
                   3862:     }
                   3863: 
1.556     weissno  3864:     my @fields=(['ID','Student/Employee ID'],
1.243     albertel 3865: 		['username','Student Username'],
                   3866: 		['domain','Student Domain']);
1.324     albertel 3867:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
1.41      ng       3868:     foreach my $part (sort(@parts)) {
                   3869: 	my @datum;
                   3870: 	my $display=&Apache::lonnet::metadata($url,$part.'.display');
                   3871: 	my $name=$part;
                   3872: 	if  (!$display) { $display = $name; }
                   3873: 	@datum=($name,$display);
1.244     albertel 3874: 	if ($name=~/^stores_(.*)_awarded/) {
                   3875: 	    push(@fields,['stores_'.$1.'_points',"Points [Part: $1]"]);
                   3876: 	}
1.41      ng       3877: 	push(@fields,\@datum);
                   3878:     }
                   3879:     return (@fields);
1.26      albertel 3880: }
                   3881: 
                   3882: sub csvuploadmap_footer {
1.41      ng       3883:     my ($request,$i,$keyfields) =@_;
                   3884:     $request->print(<<ENDPICK);
1.26      albertel 3885: </table>
                   3886: <input type="hidden" name="nfields" value="$i" />
                   3887: <input type="hidden" name="keyfields" value="$keyfields" />
1.589     bisitz   3888: <input type="button" onclick="javascript:verify(this.form)" value="Assign Grades" /><br />
1.26      albertel 3889: </form>
                   3890: ENDPICK
                   3891: }
                   3892: 
1.283     albertel 3893: sub checkforfile_js {
1.539     riegler  3894:     my $alertmsg = &mt('Please use the browse button to select a file from your local directory.');
1.597     wenzelju 3895:     my $result = &Apache::lonhtmlcommon::scripttag(<<CSVFORMJS);
1.86      ng       3896:     function checkUpload(formname) {
                   3897: 	if (formname.upfile.value == "") {
1.539     riegler  3898: 	    alert("$alertmsg");
1.86      ng       3899: 	    return false;
                   3900: 	}
                   3901: 	formname.submit();
                   3902:     }
                   3903: CSVFORMJS
1.283     albertel 3904:     return $result;
                   3905: }
                   3906: 
                   3907: sub upcsvScores_form {
1.608     www      3908:     my ($request,$symb) = @_;
1.283     albertel 3909:     if (!$symb) {return '';}
                   3910:     my $result=&checkforfile_js();
1.326     albertel 3911:     $result.='<br /><table width="100%" border="0"><tr><td bgcolor="#777777">'."\n";
                   3912:     $result.='<table width="100%" border="0"><tr bgcolor="#e6ffff"><td>'."\n";
1.538     schulted 3913:     $result.='&nbsp;<b>'.&mt('Specify a file containing the class scores for current resource.').
                   3914: 	'</b></td></tr>'."\n";
1.86      ng       3915:     $result.='<tr bgcolor=#ffffe6><td>'."\n";
1.370     www      3916:     my $upload=&mt("Upload Scores");
1.86      ng       3917:     my $upfile_select=&Apache::loncommon::upfile_select_html();
1.245     albertel 3918:     my $ignore=&mt('Ignore First Line');
1.418     albertel 3919:     $symb = &Apache::lonenc::check_encrypt($symb);
1.86      ng       3920:     $result.=<<ENDUPFORM;
1.106     albertel 3921: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
1.86      ng       3922: <input type="hidden" name="symb" value="$symb" />
                   3923: <input type="hidden" name="command" value="csvuploadmap" />
                   3924: $upfile_select
1.589     bisitz   3925: <br /><input type="button" onclick="javascript:checkUpload(this.form);" value="$upload" />
1.86      ng       3926: </form>
                   3927: ENDUPFORM
1.370     www      3928:     $result.=&Apache::loncommon::help_open_topic("Course_Convert_To_CSV",
                   3929:                            &mt("How do I create a CSV file from a spreadsheet"))
                   3930:     .'</td></tr></table>'."\n";
1.86      ng       3931:     $result.='</td></tr></table><br /><br />'."\n";
                   3932:     return $result;
                   3933: }
                   3934: 
                   3935: 
1.26      albertel 3936: sub csvuploadmap {
1.608     www      3937:     my ($request,$symb)= @_;
1.41      ng       3938:     if (!$symb) {return '';}
1.72      ng       3939: 
1.41      ng       3940:     my $datatoken;
1.257     albertel 3941:     if (!$env{'form.datatoken'}) {
1.41      ng       3942: 	$datatoken=&Apache::loncommon::upfile_store($request);
1.26      albertel 3943:     } else {
1.257     albertel 3944: 	$datatoken=$env{'form.datatoken'};
1.41      ng       3945: 	&Apache::loncommon::load_tmp_file($request);
1.26      albertel 3946:     }
1.41      ng       3947:     my @records=&Apache::loncommon::upfile_record_sep();
1.324     albertel 3948:     &csvuploadmap_header($request,$symb,$datatoken,$#records+1);
1.41      ng       3949:     my ($i,$keyfields);
                   3950:     if (@records) {
1.582     raeburn  3951:         my $fieldserror;
                   3952: 	my @fields=&csvupload_fields($symb,\$fieldserror);
                   3953:         if ($fieldserror) {
                   3954:             $request->print(&navmap_errormsg());
                   3955:             return;
                   3956:         }
1.257     albertel 3957: 	if ($env{'form.upfile_associate'} eq 'reverse') {	
1.41      ng       3958: 	    &Apache::loncommon::csv_print_samples($request,\@records);
                   3959: 	    $i=&Apache::loncommon::csv_print_select_table($request,\@records,
                   3960: 							  \@fields);
                   3961: 	    foreach (@fields) { $keyfields.=$_->[0].','; }
                   3962: 	    chop($keyfields);
                   3963: 	} else {
                   3964: 	    unshift(@fields,['none','']);
                   3965: 	    $i=&Apache::loncommon::csv_samples_select_table($request,\@records,
                   3966: 							    \@fields);
1.311     banghart 3967:             foreach my $rec (@records) {
                   3968:                 my %temp = &Apache::loncommon::record_sep($rec);
                   3969:                 if (%temp) {
                   3970:                     $keyfields=join(',',sort(keys(%temp)));
                   3971:                     last;
                   3972:                 }
                   3973:             }
1.41      ng       3974: 	}
                   3975:     }
                   3976:     &csvuploadmap_footer($request,$i,$keyfields);
1.72      ng       3977: 
1.41      ng       3978:     return '';
1.27      albertel 3979: }
                   3980: 
1.246     albertel 3981: sub csvuploadoptions {
1.608     www      3982:     my ($request,$symb)= @_;
1.246     albertel 3983:     $request->print(<<ENDPICK);
                   3984: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
1.398     albertel 3985: <h3><span class="LC_info">Uploading Class Grade Options</span></h3>
1.246     albertel 3986: <input type="hidden" name="command"    value="csvuploadassign" />
1.302     albertel 3987: <!--
1.246     albertel 3988: <p>
                   3989: <label>
                   3990:    <input type="checkbox" name="show_full_results" />
                   3991:    Show a table of all changes
                   3992: </label>
                   3993: </p>
1.302     albertel 3994: -->
1.246     albertel 3995: <p>
                   3996: <label>
                   3997:    <input type="checkbox" name="overwite_scores" checked="checked" />
                   3998:    Overwrite any existing score
                   3999: </label>
                   4000: </p>
                   4001: ENDPICK
                   4002:     my %fields=&get_fields();
                   4003:     if (!defined($fields{'domain'})) {
1.257     albertel 4004: 	my $domform = &Apache::loncommon::select_dom_form($env{'request.role.domain'},'default_domain');
1.246     albertel 4005: 	$request->print("\n<p> Users are in domain: ".$domform."</p>\n");
                   4006:     }
1.257     albertel 4007:     foreach my $key (sort(keys(%env))) {
1.246     albertel 4008: 	if ($key !~ /^form\.(.*)$/) { next; }
                   4009: 	my $cleankey=$1;
                   4010: 	if ($cleankey eq 'command') { next; }
                   4011: 	$request->print('<input type="hidden" name="'.$cleankey.
1.257     albertel 4012: 			'"  value="'.$env{$key}.'" />'."\n");
1.246     albertel 4013:     }
                   4014:     # FIXME do a check for any duplicated user ids...
                   4015:     # FIXME do a check for any invalid user ids?...
1.290     albertel 4016:     $request->print('<input type="submit" value="Assign Grades" /><br />
                   4017: <hr /></form>'."\n");
1.246     albertel 4018:     return '';
                   4019: }
                   4020: 
                   4021: sub get_fields {
                   4022:     my %fields;
1.257     albertel 4023:     my @keyfields = split(/\,/,$env{'form.keyfields'});
                   4024:     for (my $i=0; $i<=$env{'form.nfields'}; $i++) {
                   4025: 	if ($env{'form.upfile_associate'} eq 'reverse') {
                   4026: 	    if ($env{'form.f'.$i} ne 'none') {
                   4027: 		$fields{$keyfields[$i]}=$env{'form.f'.$i};
1.41      ng       4028: 	    }
                   4029: 	} else {
1.257     albertel 4030: 	    if ($env{'form.f'.$i} ne 'none') {
                   4031: 		$fields{$env{'form.f'.$i}}=$keyfields[$i];
1.41      ng       4032: 	    }
                   4033: 	}
1.27      albertel 4034:     }
1.246     albertel 4035:     return %fields;
                   4036: }
                   4037: 
                   4038: sub csvuploadassign {
1.608     www      4039:     my ($request,$symb)= @_;
1.246     albertel 4040:     if (!$symb) {return '';}
1.345     bowersj2 4041:     my $error_msg = '';
1.246     albertel 4042:     &Apache::loncommon::load_tmp_file($request);
                   4043:     my @gradedata = &Apache::loncommon::upfile_record_sep();
                   4044:     my %fields=&get_fields();
1.41      ng       4045:     $request->print('<h3>Assigning Grades</h3>');
1.257     albertel 4046:     my $courseid=$env{'request.course.id'};
1.97      albertel 4047:     my ($classlist) = &getclasslist('all',0);
1.106     albertel 4048:     my @notallowed;
1.41      ng       4049:     my @skipped;
                   4050:     my $countdone=0;
                   4051:     foreach my $grade (@gradedata) {
                   4052: 	my %entries=&Apache::loncommon::record_sep($grade);
1.246     albertel 4053: 	my $domain;
                   4054: 	if ($entries{$fields{'domain'}}) {
                   4055: 	    $domain=$entries{$fields{'domain'}};
                   4056: 	} else {
1.257     albertel 4057: 	    $domain=$env{'form.default_domain'};
1.246     albertel 4058: 	}
1.243     albertel 4059: 	$domain=~s/\s//g;
1.41      ng       4060: 	my $username=$entries{$fields{'username'}};
1.160     albertel 4061: 	$username=~s/\s//g;
1.243     albertel 4062: 	if (!$username) {
                   4063: 	    my $id=$entries{$fields{'ID'}};
1.247     albertel 4064: 	    $id=~s/\s//g;
1.243     albertel 4065: 	    my %ids=&Apache::lonnet::idget($domain,$id);
                   4066: 	    $username=$ids{$id};
                   4067: 	}
1.41      ng       4068: 	if (!exists($$classlist{"$username:$domain"})) {
1.247     albertel 4069: 	    my $id=$entries{$fields{'ID'}};
                   4070: 	    $id=~s/\s//g;
                   4071: 	    if ($id) {
                   4072: 		push(@skipped,"$id:$domain");
                   4073: 	    } else {
                   4074: 		push(@skipped,"$username:$domain");
                   4075: 	    }
1.41      ng       4076: 	    next;
                   4077: 	}
1.108     albertel 4078: 	my $usec=$classlist->{"$username:$domain"}[5];
1.106     albertel 4079: 	if (!&canmodify($usec)) {
                   4080: 	    push(@notallowed,"$username:$domain");
                   4081: 	    next;
                   4082: 	}
1.244     albertel 4083: 	my %points;
1.41      ng       4084: 	my %grades;
                   4085: 	foreach my $dest (keys(%fields)) {
1.244     albertel 4086: 	    if ($dest eq 'ID' || $dest eq 'username' ||
                   4087: 		$dest eq 'domain') { next; }
                   4088: 	    if ($entries{$fields{$dest}} =~ /^\s*$/) { next; }
                   4089: 	    if ($dest=~/stores_(.*)_points/) {
                   4090: 		my $part=$1;
                   4091: 		my $wgt =&Apache::lonnet::EXT('resource.'.$part.'.weight',
                   4092: 					      $symb,$domain,$username);
1.345     bowersj2 4093:                 if ($wgt) {
                   4094:                     $entries{$fields{$dest}}=~s/\s//g;
                   4095:                     my $pcr=$entries{$fields{$dest}} / $wgt;
1.463     albertel 4096:                     my $award=($pcr == 0) ? 'incorrect_by_override'
                   4097:                                           : 'correct_by_override';
1.345     bowersj2 4098:                     $grades{"resource.$part.awarded"}=$pcr;
                   4099:                     $grades{"resource.$part.solved"}=$award;
                   4100:                     $points{$part}=1;
                   4101:                 } else {
                   4102:                     $error_msg = "<br />" .
                   4103:                         &mt("Some point values were assigned"
                   4104:                             ." for problems with a weight "
                   4105:                             ."of zero. These values were "
                   4106:                             ."ignored.");
                   4107:                 }
1.244     albertel 4108: 	    } else {
                   4109: 		if ($dest=~/stores_(.*)_awarded/) { if ($points{$1}) {next;} }
                   4110: 		if ($dest=~/stores_(.*)_solved/)  { if ($points{$1}) {next;} }
                   4111: 		my $store_key=$dest;
                   4112: 		$store_key=~s/^stores/resource/;
                   4113: 		$store_key=~s/_/\./g;
                   4114: 		$grades{$store_key}=$entries{$fields{$dest}};
                   4115: 	    }
1.41      ng       4116: 	}
1.508     www      4117: 	if (! %grades) { 
                   4118:            push(@skipped,&mt("[_1]: no data to save","$username:$domain")); 
                   4119:         } else {
                   4120: 	   $grades{"resource.regrader"}="$env{'user.name'}:$env{'user.domain'}";
                   4121: 	   my $result=&Apache::lonnet::cstore(\%grades,$symb,
1.302     albertel 4122: 					   $env{'request.course.id'},
                   4123: 					   $domain,$username);
1.508     www      4124: 	   if ($result eq 'ok') {
1.627     www      4125: # Successfully stored
1.508     www      4126: 	      $request->print('.');
1.627     www      4127: # Remove from grading queue
                   4128:               &Apache::bridgetask::remove_from_queue('gradingqueue',$symb,
                   4129:                                              $env{'course.'.$env{'request.course.id'}.'.domain'},
                   4130:                                              $env{'course.'.$env{'request.course.id'}.'.num'},
                   4131:                                              $domain,$username);
                   4132:               $countdone++;
                   4133:            } else {
1.508     www      4134: 	      $request->print("<p><span class=\"LC_error\">".
                   4135:                               &mt("Failed to save data for student [_1]. Message when trying to save was: [_2]",
                   4136:                                   "$username:$domain",$result)."</span></p>");
                   4137: 	   }
                   4138: 	   $request->rflush();
                   4139:         }
1.41      ng       4140:     }
1.570     www      4141:     $request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt("Saved scores for [quant,_1,student]",$countdone),$countdone==0));
1.41      ng       4142:     if (@skipped) {
1.571     www      4143: 	$request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt('No scores stored for the following username(s):'),1).'<br />');
                   4144:         $request->print(join(', ',@skipped));
1.106     albertel 4145:     }
                   4146:     if (@notallowed) {
1.571     www      4147: 	$request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt('Modification of scores not allowed for the following username(s):'),1).'<br />');
                   4148: 	$request->print(join(', ',@notallowed));
1.41      ng       4149:     }
1.106     albertel 4150:     $request->print("<br />\n");
1.345     bowersj2 4151:     return $error_msg;
1.26      albertel 4152: }
1.44      ng       4153: #------------- end of section for handling csv file upload ---------
                   4154: #
                   4155: #-------------------------------------------------------------------
                   4156: #
1.122     ng       4157: #-------------- Next few routines handle grading by page/sequence
1.72      ng       4158: #
                   4159: #--- Select a page/sequence and a student to grade
1.68      ng       4160: sub pickStudentPage {
1.608     www      4161:     my ($request,$symb) = @_;
1.68      ng       4162: 
1.539     riegler  4163:     my $alertmsg = &mt('Please select the student you wish to grade.');
1.597     wenzelju 4164:     $request->print(&Apache::lonhtmlcommon::scripttag(<<LISTJAVASCRIPT));
1.68      ng       4165: 
                   4166: function checkPickOne(formname) {
1.76      ng       4167:     if (radioSelection(formname.student) == null) {
1.539     riegler  4168: 	alert("$alertmsg");
1.68      ng       4169: 	return;
                   4170:     }
1.125     ng       4171:     ptr = pullDownSelection(formname.selectpage);
                   4172:     formname.page.value = formname["page"+ptr].value;
                   4173:     formname.title.value = formname["title"+ptr].value;
1.68      ng       4174:     formname.submit();
                   4175: }
                   4176: 
                   4177: LISTJAVASCRIPT
1.118     ng       4178:     &commonJSfunctions($request);
1.608     www      4179: 
1.257     albertel 4180:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
                   4181:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
                   4182:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
1.68      ng       4183: 
1.398     albertel 4184:     my $result='<h3><span class="LC_info">&nbsp;'.
1.485     albertel 4185: 	&mt('Manual Grading by Page or Sequence').'</span></h3>';
1.68      ng       4186: 
1.80      ng       4187:     $result.='<form action="/adm/grades" method="post" name="displayPage">'."\n";
1.582     raeburn  4188:     my $map_error;
                   4189:     my ($titles,$symbx) = &getSymbMap($map_error);
                   4190:     if ($map_error) {
                   4191:         $request->print(&navmap_errormsg());
                   4192:         return; 
                   4193:     }
1.137     albertel 4194:     my ($curpage) =&Apache::lonnet::decode_symb($symb); 
                   4195: #    my ($curpage,$mapId) =&Apache::lonnet::decode_symb($symb); 
                   4196: #    my $type=($curpage =~ /\.(page|sequence)/);
1.485     albertel 4197:     my $select = '<select name="selectpage">'."\n";
1.70      ng       4198:     my $ctr=0;
1.68      ng       4199:     foreach (@$titles) {
                   4200: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
1.485     albertel 4201: 	$select.='<option value="'.$ctr.'" '.
1.401     albertel 4202: 	    ($$symbx{$_} =~ /$curpage$/ ? 'selected="selected"' : '').
1.71      ng       4203: 	    '>'.$showtitle.'</option>'."\n";
1.70      ng       4204: 	$ctr++;
1.68      ng       4205:     }
1.485     albertel 4206:     $select.= '</select>';
1.539     riegler  4207:     $result.='&nbsp;<b>'.&mt('Problems from').':</b> '.$select."<br />\n";
1.485     albertel 4208: 
1.70      ng       4209:     $ctr=0;
                   4210:     foreach (@$titles) {
                   4211: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
                   4212: 	$result.='<input type="hidden" name="page'.$ctr.'" value="'.$$symbx{$_}.'" />'."\n";
                   4213: 	$result.='<input type="hidden" name="title'.$ctr.'" value="'.$showtitle.'" />'."\n";
                   4214: 	$ctr++;
                   4215:     }
1.72      ng       4216:     $result.='<input type="hidden" name="page" />'."\n".
                   4217: 	'<input type="hidden" name="title" />'."\n";
1.68      ng       4218: 
1.485     albertel 4219:     my $options =
                   4220: 	'<label><input type="radio" name="vProb" value="no" checked="checked" /> '.&mt('no').' </label>'."\n".
                   4221: 	'<label><input type="radio" name="vProb" value="yes" /> '.&mt('yes').' </label>'."<br />\n";
1.539     riegler  4222:     $result.='&nbsp;<b>'.&mt('View Problem Text').': </b>'.$options;
1.485     albertel 4223: 
                   4224:     $options =
                   4225: 	'<label><input type="radio" name="lastSub" value="none" /> '.&mt('none').' </label>'."\n".
                   4226: 	'<label><input type="radio" name="lastSub" value="datesub" checked="checked" /> '.&mt('by dates and submissions').'</label>'."\n".
                   4227: 	'<label><input type="radio" name="lastSub" value="all" /> '.&mt('all details').' </label>'."\n";
1.539     riegler  4228:     $result.='&nbsp;<b>'.&mt('Submissions').': </b>'.$options;
1.432     banghart 4229:     
                   4230:     $result.=&build_section_inputs();
1.442     banghart 4231:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
                   4232:     $result.='<input type="hidden" name="Status"  value="'.$stu_status.'" />'."\n".
1.72      ng       4233: 	'<input type="hidden" name="command" value="displayPage" />'."\n".
1.613     www      4234: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."<br />\n";
1.72      ng       4235: 
1.539     riegler  4236:     $result.='&nbsp;<b>'.&mt('Use CODE').': </b> <input type="text" name="CODE" value="" /> <br />'."\n";
1.382     albertel 4237: 
1.80      ng       4238:     $result.='&nbsp;<input type="button" '.
1.589     bisitz   4239:              'onclick="javascript:checkPickOne(this.form);" value="'.&mt('Next').' &rarr;" /><br />'."\n";
1.72      ng       4240: 
1.68      ng       4241:     $request->print($result);
                   4242: 
1.485     albertel 4243:     my $studentTable.='&nbsp;<b>'.&mt('Select a student you wish to grade and then click on the Next button.').'</b><br />'.
1.484     albertel 4244: 	&Apache::loncommon::start_data_table().
                   4245: 	&Apache::loncommon::start_data_table_header_row().
1.485     albertel 4246: 	'<th align="right">&nbsp;'.&mt('No.').'</th>'.
1.484     albertel 4247: 	'<th>'.&nameUserString('header').'</th>'.
1.485     albertel 4248: 	'<th align="right">&nbsp;'.&mt('No.').'</th>'.
1.484     albertel 4249: 	'<th>'.&nameUserString('header').'</th>'.
                   4250: 	&Apache::loncommon::end_data_table_header_row();
1.68      ng       4251:  
1.76      ng       4252:     my (undef,undef,$fullname) = &getclasslist($getsec,'1');
1.68      ng       4253:     my $ptr = 1;
1.294     albertel 4254:     foreach my $student (sort 
                   4255: 			 {
                   4256: 			     if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                   4257: 				 return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                   4258: 			     }
                   4259: 			     return $a cmp $b;
                   4260: 			 } (keys(%$fullname))) {
1.68      ng       4261: 	my ($uname,$udom) = split(/:/,$student);
1.484     albertel 4262: 	$studentTable.=($ptr%2==1 ? &Apache::loncommon::start_data_table_row()
                   4263:                                   : '</td>');
1.126     ng       4264: 	$studentTable.='<td align="right">'.$ptr.'&nbsp;</td>';
1.288     albertel 4265: 	$studentTable.='<td>&nbsp;<label><input type="radio" name="student" value="'.$student.'" /> '
                   4266: 	    .&nameUserString(undef,$$fullname{$student},$uname,$udom)."</label>\n";
1.484     albertel 4267: 	$studentTable.=
                   4268: 	    ($ptr%2 == 0 ? '</td>'.&Apache::loncommon::end_data_table_row() 
                   4269:                          : '');
1.68      ng       4270: 	$ptr++;
                   4271:     }
1.484     albertel 4272:     if ($ptr%2 == 0) {
                   4273: 	$studentTable.='</td><td>&nbsp;</td><td>&nbsp;</td>'.
                   4274: 	    &Apache::loncommon::end_data_table_row();
                   4275:     }
                   4276:     $studentTable.=&Apache::loncommon::end_data_table()."\n";
1.126     ng       4277:     $studentTable.='<input type="button" '.
1.589     bisitz   4278:                    'onclick="javascript:checkPickOne(this.form);" value="'.&mt('Next').' &rarr;" /></form>'."\n";
1.68      ng       4279: 
                   4280:     $request->print($studentTable);
                   4281: 
                   4282:     return '';
                   4283: }
                   4284: 
                   4285: sub getSymbMap {
1.582     raeburn  4286:     my ($map_error) = @_;
1.132     bowersj2 4287:     my $navmap = Apache::lonnavmaps::navmap->new();
1.582     raeburn  4288:     unless (ref($navmap)) {
                   4289:         if (ref($map_error)) {
                   4290:             $$map_error = 'navmap';
                   4291:         }
                   4292:         return;
                   4293:     }
1.68      ng       4294:     my %symbx = ();
                   4295:     my @titles = ();
1.117     bowersj2 4296:     my $minder = 0;
                   4297: 
                   4298:     # Gather every sequence that has problems.
1.240     albertel 4299:     my @sequences = $navmap->retrieveResources(undef, sub { shift->is_map(); },
                   4300: 					       1,0,1);
1.117     bowersj2 4301:     for my $sequence ($navmap->getById('0.0'), @sequences) {
1.241     albertel 4302: 	if ($navmap->hasResource($sequence, sub { shift->is_problem(); }, 0) ) {
1.381     albertel 4303: 	    my $title = $minder.'.'.
                   4304: 		&HTML::Entities::encode($sequence->compTitle(),'"\'&');
                   4305: 	    push(@titles, $title); # minder in case two titles are identical
                   4306: 	    $symbx{$title} = &HTML::Entities::encode($sequence->symb(),'"\'&');
1.117     bowersj2 4307: 	    $minder++;
1.241     albertel 4308: 	}
1.68      ng       4309:     }
                   4310:     return \@titles,\%symbx;
                   4311: }
                   4312: 
1.72      ng       4313: #
                   4314: #--- Displays a page/sequence w/wo problems, w/wo submissions
1.68      ng       4315: sub displayPage {
1.608     www      4316:     my ($request,$symb) = @_;
1.257     albertel 4317:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
                   4318:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
                   4319:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
                   4320:     my $pageTitle = $env{'form.page'};
1.103     albertel 4321:     my ($classlist,undef,$fullname) = &getclasslist($getsec,'1');
1.257     albertel 4322:     my ($uname,$udom) = split(/:/,$env{'form.student'});
                   4323:     my $usec=$classlist->{$env{'form.student'}}[5];
1.168     albertel 4324: 
                   4325:     #need to make sure we have the correct data for later EXT calls, 
                   4326:     #thus invalidate the cache
                   4327:     &Apache::lonnet::devalidatecourseresdata(
1.257     albertel 4328:                  $env{'course.'.$env{'request.course.id'}.'.num'},
                   4329:                  $env{'course.'.$env{'request.course.id'}.'.domain'});
1.168     albertel 4330:     &Apache::lonnet::clear_EXT_cache_status();
                   4331: 
1.103     albertel 4332:     if (!&canview($usec)) {
1.485     albertel 4333: 	$request->print('<span class="LC_warning">'.&mt('Unable to view requested student. ([_1])',$env{'form.student'}).'</span>');
1.103     albertel 4334: 	return;
                   4335:     }
1.398     albertel 4336:     my $result='<h3><span class="LC_info">&nbsp;'.$env{'form.title'}.'</span></h3>';
1.485     albertel 4337:     $result.='<h3>&nbsp;'.&mt('Student: [_1]',&nameUserString(undef,$$fullname{$env{'form.student'}},$uname,$udom)).
1.129     ng       4338: 	'</h3>'."\n";
1.500     albertel 4339:     $env{'form.CODE'} = uc($env{'form.CODE'});
1.501     foxr     4340:     if (&Apache::lonnet::validCODE(uc($env{'form.CODE'}))) {
1.485     albertel 4341: 	$result.='<h3>&nbsp;'.&mt('CODE: [_1]',$env{'form.CODE'}).'</h3>'."\n";
1.382     albertel 4342:     } else {
                   4343: 	delete($env{'form.CODE'});
                   4344:     }
1.71      ng       4345:     &sub_page_js($request);
                   4346:     $request->print($result);
                   4347: 
1.132     bowersj2 4348:     my $navmap = Apache::lonnavmaps::navmap->new();
1.582     raeburn  4349:     unless (ref($navmap)) {
                   4350:         $request->print(&navmap_errormsg());
                   4351:         return;
                   4352:     }
1.257     albertel 4353:     my ($mapUrl, $id, $resUrl)=&Apache::lonnet::decode_symb($env{'form.page'});
1.68      ng       4354:     my $map = $navmap->getResourceByUrl($resUrl); # add to navmaps
1.288     albertel 4355:     if (!$map) {
1.485     albertel 4356: 	$request->print('<span class="LC_warning">'.&mt('Unable to view requested sequence. ([_1])',$resUrl).'</span>');
1.288     albertel 4357: 	return; 
                   4358:     }
1.68      ng       4359:     my $iterator = $navmap->getIterator($map->map_start(),
                   4360: 					$map->map_finish());
                   4361: 
1.71      ng       4362:     my $studentTable='<form action="/adm/grades" method="post" name="gradePage">'."\n".
1.72      ng       4363: 	'<input type="hidden" name="command" value="gradeByPage" />'."\n".
1.257     albertel 4364: 	'<input type="hidden" name="fullname" value="'.$$fullname{$env{'form.student'}}.'" />'."\n".
                   4365: 	'<input type="hidden" name="student" value="'.$env{'form.student'}.'" />'."\n".
1.72      ng       4366: 	'<input type="hidden" name="page"    value="'.$pageTitle.'" />'."\n".
1.257     albertel 4367: 	'<input type="hidden" name="title"   value="'.$env{'form.title'}.'" />'."\n".
1.418     albertel 4368: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.613     www      4369: 	'<input type="hidden" name="overRideScore" value="no" />'."\n";
1.71      ng       4370: 
1.382     albertel 4371:     if (defined($env{'form.CODE'})) {
                   4372: 	$studentTable.=
                   4373: 	    '<input type="hidden" name="CODE" value="'.$env{'form.CODE'}.'" />'."\n";
                   4374:     }
1.381     albertel 4375:     my $checkIcon = '<img alt="'.&mt('Check Mark').
1.485     albertel 4376: 	'" src="'.&Apache::loncommon::lonhttpdurl($request->dir_config('lonIconsURL').'/check.gif').'" height="16" border="0" />';
1.71      ng       4377: 
1.594     bisitz   4378:     $studentTable.='&nbsp;<span class="LC_info">'.
                   4379:         &mt('Problems graded correct by the computer are marked with a [_1] symbol.',$checkIcon).
                   4380:         '</span>'."\n".
1.484     albertel 4381: 	&Apache::loncommon::start_data_table().
                   4382: 	&Apache::loncommon::start_data_table_header_row().
                   4383: 	'<th align="center">&nbsp;Prob.&nbsp;</th>'.
1.485     albertel 4384: 	'<th>&nbsp;'.($env{'form.vProb'} eq 'no' ? &mt('Title') : &mt('Problem Text')).'/'.&mt('Grade').'</th>'.
1.484     albertel 4385: 	&Apache::loncommon::end_data_table_header_row();
1.71      ng       4386: 
1.329     albertel 4387:     &Apache::lonxml::clear_problem_counter();
1.196     albertel 4388:     my ($depth,$question,$prob) = (1,1,1);
1.68      ng       4389:     $iterator->next(); # skip the first BEGIN_MAP
                   4390:     my $curRes = $iterator->next(); # for "current resource"
1.101     albertel 4391:     while ($depth > 0) {
1.68      ng       4392:         if($curRes == $iterator->BEGIN_MAP) { $depth++; }
1.100     bowersj2 4393:         if($curRes == $iterator->END_MAP) { $depth--; }
1.68      ng       4394: 
1.385     albertel 4395:         if (ref($curRes) && $curRes->is_problem()) {
1.91      albertel 4396: 	    my $parts = $curRes->parts();
1.68      ng       4397:             my $title = $curRes->compTitle();
1.71      ng       4398: 	    my $symbx = $curRes->symb();
1.484     albertel 4399: 	    $studentTable.=
                   4400: 		&Apache::loncommon::start_data_table_row().
                   4401: 		'<td align="center" valign="top" >'.$prob.
1.485     albertel 4402: 		(scalar(@{$parts}) == 1 ? '' 
                   4403: 		                        : '<br />('.&mt('[_1]&nbsp;parts)',
                   4404: 							scalar(@{$parts}))
                   4405: 		 ).
                   4406: 		 '</td>';
1.71      ng       4407: 	    $studentTable.='<td valign="top">';
1.382     albertel 4408: 	    my %form = ('CODE' => $env{'form.CODE'},);
1.257     albertel 4409: 	    if ($env{'form.vProb'} eq 'yes' ) {
1.144     albertel 4410: 		$studentTable.=&show_problem($request,$symbx,$uname,$udom,1,
1.383     albertel 4411: 					     undef,'both',\%form);
1.71      ng       4412: 	    } else {
1.382     albertel 4413: 		my $companswer = &Apache::loncommon::get_student_answers($symbx,$uname,$udom,$env{'request.course.id'},%form);
1.80      ng       4414: 		$companswer =~ s|<form(.*?)>||g;
                   4415: 		$companswer =~ s|</form>||g;
1.71      ng       4416: #		while ($companswer =~ /(<a href\=\"javascript:newWindow.*?Script Vars<\/a>)/s) { #<a href="javascript:newWindow</a>
1.116     ng       4417: #		    $companswer =~ s/$1/ /ms;
1.326     albertel 4418: #		    $request->print('match='.$1."<br />\n");
1.71      ng       4419: #		}
1.116     ng       4420: #		$companswer =~ s|<table border=\"1\">|<table border=\"0\">|g;
1.539     riegler  4421: 		$studentTable.='&nbsp;<b>'.$title.'</b>&nbsp;<br />&nbsp;<b>'.&mt('Correct answer').':</b><br />'.$companswer;
1.71      ng       4422: 	    }
                   4423: 
1.257     albertel 4424: 	    my %record = &Apache::lonnet::restore($symbx,$env{'request.course.id'},$udom,$uname);
1.125     ng       4425: 
1.257     albertel 4426: 	    if ($env{'form.lastSub'} eq 'datesub') {
1.71      ng       4427: 		if ($record{'version'} eq '') {
1.485     albertel 4428: 		    $studentTable.='<br />&nbsp;<span class="LC_warning">'.&mt('No recorded submission for this problem.').'</span><br />';
1.71      ng       4429: 		} else {
1.116     ng       4430: 		    my %responseType = ();
                   4431: 		    foreach my $partid (@{$parts}) {
1.147     albertel 4432: 			my @responseIds =$curRes->responseIds($partid);
                   4433: 			my @responseType =$curRes->responseType($partid);
                   4434: 			my %responseIds;
                   4435: 			for (my $i=0;$i<=$#responseIds;$i++) {
                   4436: 			    $responseIds{$responseIds[$i]}=$responseType[$i];
                   4437: 			}
                   4438: 			$responseType{$partid} = \%responseIds;
1.116     ng       4439: 		    }
1.148     albertel 4440: 		    $studentTable.= &displaySubByDates($symbx,\%record,$parts,\%responseType,$checkIcon,$uname,$udom);
1.147     albertel 4441: 
1.71      ng       4442: 		}
1.257     albertel 4443: 	    } elsif ($env{'form.lastSub'} eq 'all') {
                   4444: 		my $last = ($env{'form.lastSub'} eq 'last' ? 'last' : '');
1.71      ng       4445: 		$studentTable.=&Apache::loncommon::get_previous_attempt($symbx,$uname,$udom,
1.257     albertel 4446: 									$env{'request.course.id'},
1.71      ng       4447: 									'','.submission');
                   4448:  
                   4449: 	    }
1.103     albertel 4450: 	    if (&canmodify($usec)) {
1.585     bisitz   4451:             $studentTable.=&gradeBox_start();
1.103     albertel 4452: 		foreach my $partid (@{$parts}) {
                   4453: 		    $studentTable.=&gradeBox($request,$symbx,$uname,$udom,$question,$partid,\%record);
                   4454: 		    $studentTable.='<input type="hidden" name="q_'.$question.'" value="'.$partid.'" />'."\n";
                   4455: 		    $question++;
                   4456: 		}
1.585     bisitz   4457:             $studentTable.=&gradeBox_end();
1.196     albertel 4458: 		$prob++;
1.71      ng       4459: 	    }
                   4460: 	    $studentTable.='</td></tr>';
1.68      ng       4461: 
1.103     albertel 4462: 	}
1.68      ng       4463:         $curRes = $iterator->next();
                   4464:     }
                   4465: 
1.589     bisitz   4466:     $studentTable.=
                   4467:         '</table>'."\n".
                   4468:         '<input type="button" value="'.&mt('Save').'" '.
                   4469:         'onclick="javascript:checkSubmitPage(this.form,'.$question.');" />'.
                   4470:         '</form>'."\n";
1.71      ng       4471:     $request->print($studentTable);
                   4472: 
                   4473:     return '';
1.119     ng       4474: }
                   4475: 
                   4476: sub displaySubByDates {
1.148     albertel 4477:     my ($symb,$record,$parts,$responseType,$checkIcon,$uname,$udom) = @_;
1.224     albertel 4478:     my $isCODE=0;
1.335     albertel 4479:     my $isTask = ($symb =~/\.task$/);
1.224     albertel 4480:     if (exists($record->{'resource.CODE'})) { $isCODE=1; }
1.467     albertel 4481:     my $studentTable=&Apache::loncommon::start_data_table().
                   4482: 	&Apache::loncommon::start_data_table_header_row().
                   4483: 	'<th>'.&mt('Date/Time').'</th>'.
                   4484: 	($isCODE?'<th>'.&mt('CODE').'</th>':'').
                   4485: 	'<th>'.&mt('Submission').'</th>'.
                   4486: 	'<th>'.&mt('Status').'</th>'.
                   4487: 	&Apache::loncommon::end_data_table_header_row();
1.119     ng       4488:     my ($version);
                   4489:     my %mark;
1.148     albertel 4490:     my %orders;
1.119     ng       4491:     $mark{'correct_by_student'} = $checkIcon;
1.147     albertel 4492:     if (!exists($$record{'1:timestamp'})) {
1.539     riegler  4493: 	return '<br />&nbsp;<span class="LC_warning">'.&mt('Nothing submitted - no attempts.').'</span><br />';
1.147     albertel 4494:     }
1.335     albertel 4495: 
                   4496:     my $interaction;
1.525     raeburn  4497:     my $no_increment = 1;
1.119     ng       4498:     for ($version=1;$version<=$$record{'version'};$version++) {
1.467     albertel 4499: 	my $timestamp = 
                   4500: 	    &Apache::lonlocal::locallocaltime($$record{$version.':timestamp'});
1.335     albertel 4501: 	if (exists($$record{$version.':resource.0.version'})) {
                   4502: 	    $interaction = $$record{$version.':resource.0.version'};
                   4503: 	}
                   4504: 
                   4505: 	my $where = ($isTask ? "$version:resource.$interaction"
                   4506: 		             : "$version:resource");
1.467     albertel 4507: 	$studentTable.=&Apache::loncommon::start_data_table_row().
                   4508: 	    '<td>'.$timestamp.'</td>';
1.224     albertel 4509: 	if ($isCODE) {
                   4510: 	    $studentTable.='<td>'.$record->{$version.':resource.CODE'}.'</td>';
                   4511: 	}
1.119     ng       4512: 	my @versionKeys = split(/\:/,$$record{$version.':keys'});
                   4513: 	my @displaySub = ();
                   4514: 	foreach my $partid (@{$parts}) {
1.596     raeburn  4515:             my $hidden;
                   4516:             if (($$record{$version.':resource.'.$partid.'.type'} eq 'anonsurvey') ||
                   4517:                 ($$record{$version.':resource.'.$partid.'.type'} eq 'anonsurveycred')) {
                   4518:                 $hidden = 1;
                   4519:             }
1.335     albertel 4520: 	    my @matchKey = ($isTask ? sort(grep /^resource\.\d+\.\Q$partid\E\.award$/,@versionKeys)
                   4521: 			            : sort(grep /^resource\.\Q$partid\E\..*?\.submission$/,@versionKeys));
                   4522: 	    
1.122     ng       4523: #	    next if ($$record{"$version:resource.$partid.solved"} eq '');
1.324     albertel 4524: 	    my $display_part=&get_display_part($partid,$symb);
1.147     albertel 4525: 	    foreach my $matchKey (@matchKey) {
1.198     albertel 4526: 		if (exists($$record{$version.':'.$matchKey}) &&
                   4527: 		    $$record{$version.':'.$matchKey} ne '') {
1.596     raeburn  4528:                     
1.335     albertel 4529: 		    my ($responseId)= ($isTask ? ($matchKey=~ /^resource\.(.*?)\.\Q$partid\E\.award$/)
                   4530: 				               : ($matchKey=~ /^resource\.\Q$partid\E\.(.*?)\.submission$/));
1.577     bisitz   4531:                     $displaySub[0].='<span class="LC_nobreak"';
                   4532:                     $displaySub[0].='<b>'.&mt('Part: [_1]',$display_part).'</b>'
                   4533:                                    .' <span class="LC_internal_info">'
1.625     www      4534:                                    .'('.&mt('Response ID: [_1]',$responseId).')'
1.577     bisitz   4535:                                    .'</span>'
                   4536:                                    .' <b>';
1.596     raeburn  4537:                     if ($hidden) {
                   4538:                         $displaySub[0].= &mt('Anonymous Survey').'</b>';
                   4539:                     } else {
                   4540: 		        if ($$record{"$where.$partid.tries"} eq '') {
                   4541: 			    $displaySub[0].=&mt('Trial not counted');
                   4542: 		        } else {
                   4543: 			    $displaySub[0].=&mt('Trial: [_1]',
1.467     albertel 4544: 					    $$record{"$where.$partid.tries"});
1.596     raeburn  4545: 		        }
                   4546: 		        my $responseType=($isTask ? 'Task'
1.335     albertel 4547:                                               : $responseType->{$partid}->{$responseId});
1.596     raeburn  4548: 		        if (!exists($orders{$partid})) { $orders{$partid}={}; }
                   4549: 		        if (!exists($orders{$partid}->{$responseId})) {
                   4550: 			    $orders{$partid}->{$responseId}=
                   4551: 			        &get_order($partid,$responseId,$symb,$uname,$udom,
                   4552:                                            $no_increment);
                   4553: 		        }
                   4554: 		        $displaySub[0].='</b></span>'; # /nobreak
                   4555: 		        $displaySub[0].='&nbsp; '.
                   4556: 			    &cleanRecord($$record{$version.':'.$matchKey},$responseType,$symb,$partid,$responseId,$record,$orders{$partid}->{$responseId},"$version:",$uname,$udom).'<br />';
                   4557:                     }
1.147     albertel 4558: 		}
                   4559: 	    }
1.335     albertel 4560: 	    if (exists($$record{"$where.$partid.checkedin"})) {
1.485     albertel 4561: 		$displaySub[1].=&mt('Checked in by [_1] into slot [_2]',
                   4562: 				    $$record{"$where.$partid.checkedin"},
                   4563: 				    $$record{"$where.$partid.checkedin.slot"}).
                   4564: 					'<br />';
1.335     albertel 4565: 	    }
                   4566: 	    if (exists $$record{"$where.$partid.award"}) {
1.485     albertel 4567: 		$displaySub[1].='<b>'.&mt('Part:').'</b>&nbsp;'.$display_part.' &nbsp;'.
1.335     albertel 4568: 		    lc($$record{"$where.$partid.award"}).' '.
                   4569: 		    $mark{$$record{"$where.$partid.solved"}}.
1.147     albertel 4570: 		    '<br />';
                   4571: 	    }
1.335     albertel 4572: 	    if (exists $$record{"$where.$partid.regrader"}) {
                   4573: 		$displaySub[2].=$$record{"$where.$partid.regrader"}.
                   4574: 		    ' (<b>'.&mt('Part').':</b> '.$display_part.')';
                   4575: 	    } elsif ($$record{"$version:resource.$partid.regrader"} =~ /\S/) {
                   4576: 		$displaySub[2].=
                   4577: 		    $$record{"$version:resource.$partid.regrader"}.
1.207     albertel 4578: 		    ' (<b>'.&mt('Part').':</b> '.$display_part.')';
1.147     albertel 4579: 	    }
                   4580: 	}
                   4581: 	# needed because old essay regrader has not parts info
                   4582: 	if (exists $$record{"$version:resource.regrader"}) {
                   4583: 	    $displaySub[2].=$$record{"$version:resource.regrader"};
                   4584: 	}
                   4585: 	$studentTable.='<td>'.$displaySub[0].'&nbsp;</td><td>'.$displaySub[1];
                   4586: 	if ($displaySub[2]) {
1.467     albertel 4587: 	    $studentTable.=&mt('Manually graded by [_1]',$displaySub[2]);
1.147     albertel 4588: 	}
1.467     albertel 4589: 	$studentTable.='&nbsp;</td>'.
                   4590: 	    &Apache::loncommon::end_data_table_row();
1.119     ng       4591:     }
1.467     albertel 4592:     $studentTable.=&Apache::loncommon::end_data_table();
1.119     ng       4593:     return $studentTable;
1.71      ng       4594: }
                   4595: 
                   4596: sub updateGradeByPage {
1.608     www      4597:     my ($request,$symb) = @_;
1.71      ng       4598: 
1.257     albertel 4599:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
                   4600:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
                   4601:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
                   4602:     my $pageTitle = $env{'form.page'};
1.103     albertel 4603:     my ($classlist,undef,$fullname) = &getclasslist($getsec,'1');
1.257     albertel 4604:     my ($uname,$udom) = split(/:/,$env{'form.student'});
                   4605:     my $usec=$classlist->{$env{'form.student'}}[5];
1.103     albertel 4606:     if (!&canmodify($usec)) {
1.526     raeburn  4607: 	$request->print('<span class="LC_warning">'.&mt('Unable to modify requested student ([_1])',$env{'form.student'}).'</span>');
1.103     albertel 4608: 	return;
                   4609:     }
1.398     albertel 4610:     my $result='<h3><span class="LC_info">&nbsp;'.$env{'form.title'}.'</span></h3>';
1.526     raeburn  4611:     $result.='<h3>&nbsp;'.&mt('Student: ').&nameUserString(undef,$env{'form.fullname'},$uname,$udom).
1.129     ng       4612: 	'</h3>'."\n";
1.70      ng       4613: 
1.68      ng       4614:     $request->print($result);
                   4615: 
1.582     raeburn  4616: 
1.132     bowersj2 4617:     my $navmap = Apache::lonnavmaps::navmap->new();
1.582     raeburn  4618:     unless (ref($navmap)) {
                   4619:         $request->print(&navmap_errormsg());
                   4620:         return;
                   4621:     }
1.257     albertel 4622:     my ($mapUrl, $id, $resUrl) = &Apache::lonnet::decode_symb( $env{'form.page'});
1.71      ng       4623:     my $map = $navmap->getResourceByUrl($resUrl); # add to navmaps
1.288     albertel 4624:     if (!$map) {
1.527     raeburn  4625: 	$request->print('<span class="LC_warning">'.&mt('Unable to grade requested sequence ([_1]).',$resUrl).'</span>');
1.288     albertel 4626: 	return; 
                   4627:     }
1.71      ng       4628:     my $iterator = $navmap->getIterator($map->map_start(),
                   4629: 					$map->map_finish());
1.70      ng       4630: 
1.484     albertel 4631:     my $studentTable=
                   4632: 	&Apache::loncommon::start_data_table().
                   4633: 	&Apache::loncommon::start_data_table_header_row().
1.485     albertel 4634: 	'<th align="center">&nbsp;'.&mt('Prob.').'&nbsp;</th>'.
                   4635: 	'<th>&nbsp;'.&mt('Title').'&nbsp;</th>'.
                   4636: 	'<th>&nbsp;'.&mt('Previous Score').'&nbsp;</th>'.
                   4637: 	'<th>&nbsp;'.&mt('New Score').'&nbsp;</th>'.
1.484     albertel 4638: 	&Apache::loncommon::end_data_table_header_row();
1.71      ng       4639: 
                   4640:     $iterator->next(); # skip the first BEGIN_MAP
                   4641:     my $curRes = $iterator->next(); # for "current resource"
1.196     albertel 4642:     my ($depth,$question,$prob,$changeflag)= (1,1,1,0);
1.101     albertel 4643:     while ($depth > 0) {
1.71      ng       4644:         if($curRes == $iterator->BEGIN_MAP) { $depth++; }
1.100     bowersj2 4645:         if($curRes == $iterator->END_MAP) { $depth--; }
1.71      ng       4646: 
1.385     albertel 4647:         if (ref($curRes) && $curRes->is_problem()) {
1.91      albertel 4648: 	    my $parts = $curRes->parts();
1.71      ng       4649:             my $title = $curRes->compTitle();
                   4650: 	    my $symbx = $curRes->symb();
1.484     albertel 4651: 	    $studentTable.=
                   4652: 		&Apache::loncommon::start_data_table_row().
                   4653: 		'<td align="center" valign="top" >'.$prob.
1.485     albertel 4654: 		(scalar(@{$parts}) == 1 ? '' 
1.526     raeburn  4655:                                         : '<br />('.&mt('[quant,_1,&nbsp;part]',scalar(@{$parts}))
                   4656: 		.')').'</td>';
1.71      ng       4657: 	    $studentTable.='<td valign="top">&nbsp;<b>'.$title.'</b>&nbsp;</td>';
                   4658: 
                   4659: 	    my %newrecord=();
                   4660: 	    my @displayPts=();
1.269     raeburn  4661:             my %aggregate = ();
                   4662:             my $aggregateflag = 0;
1.71      ng       4663: 	    foreach my $partid (@{$parts}) {
1.257     albertel 4664: 		my $newpts = $env{'form.GD_BOX'.$question.'_'.$partid};
                   4665: 		my $oldpts = $env{'form.oldpts'.$question.'_'.$partid};
1.71      ng       4666: 
1.257     albertel 4667: 		my $wgt = $env{'form.WGT'.$question.'_'.$partid} != 0 ? 
                   4668: 		    $env{'form.WGT'.$question.'_'.$partid} : 1;
1.71      ng       4669: 		my $partial = $newpts/$wgt;
                   4670: 		my $score;
                   4671: 		if ($partial > 0) {
                   4672: 		    $score = 'correct_by_override';
1.125     ng       4673: 		} elsif ($newpts ne '') { #empty is taken as 0
1.71      ng       4674: 		    $score = 'incorrect_by_override';
                   4675: 		}
1.257     albertel 4676: 		my $dropMenu = $env{'form.GD_SEL'.$question.'_'.$partid};
1.125     ng       4677: 		if ($dropMenu eq 'excused') {
1.71      ng       4678: 		    $partial = '';
                   4679: 		    $score = 'excused';
1.125     ng       4680: 		} elsif ($dropMenu eq 'reset status'
1.257     albertel 4681: 			 && $env{'form.solved'.$question.'_'.$partid} ne '') { #update only if previous record exists
1.125     ng       4682: 		    $newrecord{'resource.'.$partid.'.tries'} = 0;
                   4683: 		    $newrecord{'resource.'.$partid.'.solved'} = '';
                   4684: 		    $newrecord{'resource.'.$partid.'.award'} = '';
                   4685: 		    $newrecord{'resource.'.$partid.'.awarded'} = 0;
1.257     albertel 4686: 		    $newrecord{'resource.'.$partid.'.regrader'} = "$env{'user.name'}:$env{'user.domain'}";
1.125     ng       4687: 		    $changeflag++;
                   4688: 		    $newpts = '';
1.269     raeburn  4689:                     
                   4690:                     my $aggtries =  $env{'form.aggtries'.$question.'_'.$partid};
                   4691:                     my $totaltries = $env{'form.totaltries'.$question.'_'.$partid};
                   4692:                     my $solvedstatus = $env{'form.solved'.$question.'_'.$partid};
                   4693:                     if ($aggtries > 0) {
                   4694:                         &decrement_aggs($symbx,$partid,\%aggregate,$aggtries,$totaltries,$solvedstatus);
                   4695:                         $aggregateflag = 1;
                   4696:                     }
1.71      ng       4697: 		}
1.324     albertel 4698: 		my $display_part=&get_display_part($partid,$curRes->symb());
1.257     albertel 4699: 		my $oldstatus = $env{'form.solved'.$question.'_'.$partid};
1.526     raeburn  4700: 		$displayPts[0].='&nbsp;<b>'.&mt('Part').':</b> '.$display_part.' = '.
1.71      ng       4701: 		    (($oldstatus eq 'excused') ? 'excused' : $oldpts).
1.326     albertel 4702: 		    '&nbsp;<br />';
1.526     raeburn  4703: 		$displayPts[1].='&nbsp;<b>'.&mt('Part').':</b> '.$display_part.' = '.
1.125     ng       4704: 		     (($score eq 'excused') ? 'excused' : $newpts).
1.326     albertel 4705: 		    '&nbsp;<br />';
1.71      ng       4706: 		$question++;
1.380     albertel 4707: 		next if ($dropMenu eq 'reset status' || ($newpts eq $oldpts && $score ne 'excused'));
1.125     ng       4708: 
1.71      ng       4709: 		$newrecord{'resource.'.$partid.'.awarded'}  = $partial if $partial ne '';
1.125     ng       4710: 		$newrecord{'resource.'.$partid.'.solved'}   = $score if $score ne '';
1.257     albertel 4711: 		$newrecord{'resource.'.$partid.'.regrader'} = "$env{'user.name'}:$env{'user.domain'}"
1.125     ng       4712: 		    if (scalar(keys(%newrecord)) > 0);
1.71      ng       4713: 
                   4714: 		$changeflag++;
                   4715: 	    }
                   4716: 	    if (scalar(keys(%newrecord)) > 0) {
1.382     albertel 4717: 		my %record = 
                   4718: 		    &Apache::lonnet::restore($symbx,$env{'request.course.id'},
                   4719: 					     $udom,$uname);
                   4720: 
                   4721: 		if (&Apache::lonnet::validCODE($env{'form.CODE'})) {
                   4722: 		    $newrecord{'resource.CODE'} = $env{'form.CODE'};
                   4723: 		} elsif (&Apache::lonnet::validCODE($record{'resource.CODE'})) {
                   4724: 		    $newrecord{'resource.CODE'} = '';
                   4725: 		}
1.257     albertel 4726: 		&Apache::lonnet::cstore(\%newrecord,$symbx,$env{'request.course.id'},
1.71      ng       4727: 					$udom,$uname);
1.382     albertel 4728: 		%record = &Apache::lonnet::restore($symbx,
                   4729: 						   $env{'request.course.id'},
                   4730: 						   $udom,$uname);
1.380     albertel 4731: 		&check_and_remove_from_queue($parts,\%record,undef,$symbx,
                   4732: 					     $cdom,$cnum,$udom,$uname);
1.71      ng       4733: 	    }
1.380     albertel 4734: 	    
1.269     raeburn  4735:             if ($aggregateflag) {
                   4736:                 &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
                   4737:                       $env{'course.'.$env{'request.course.id'}.'.domain'},
                   4738:                       $env{'course.'.$env{'request.course.id'}.'.num'});
                   4739:             }
1.125     ng       4740: 
1.71      ng       4741: 	    $studentTable.='<td valign="top">'.$displayPts[0].'</td>'.
                   4742: 		'<td valign="top">'.$displayPts[1].'</td>'.
1.484     albertel 4743: 		&Apache::loncommon::end_data_table_row();
1.68      ng       4744: 
1.196     albertel 4745: 	    $prob++;
1.68      ng       4746: 	}
1.71      ng       4747:         $curRes = $iterator->next();
1.68      ng       4748:     }
1.98      albertel 4749: 
1.484     albertel 4750:     $studentTable.=&Apache::loncommon::end_data_table();
1.526     raeburn  4751:     my $grademsg=($changeflag == 0 ? &mt('No score was changed or updated.') :
                   4752: 		  &mt('The scores were changed for [quant,_1,problem].',
                   4753: 		  $changeflag));
1.76      ng       4754:     $request->print($grademsg.$studentTable);
1.68      ng       4755: 
1.70      ng       4756:     return '';
                   4757: }
                   4758: 
1.72      ng       4759: #-------- end of section for handling grading by page/sequence ---------
                   4760: #
                   4761: #-------------------------------------------------------------------
                   4762: 
1.581     www      4763: #-------------------- Bubblesheet (Scantron) Grading -------------------
1.75      albertel 4764: #
                   4765: #------ start of section for handling grading by page/sequence ---------
                   4766: 
1.423     albertel 4767: =pod
                   4768: 
                   4769: =head1 Bubble sheet grading routines
                   4770: 
1.424     albertel 4771:   For this documentation:
                   4772: 
                   4773:    'scanline' refers to the full line of characters
                   4774:    from the file that we are parsing that represents one entire sheet
                   4775: 
                   4776:    'bubble line' refers to the data
                   4777:    representing the line of bubbles that are on the physical bubble sheet
                   4778: 
                   4779: 
                   4780: The overall process is that a scanned in bubble sheet data is uploaded
                   4781: into a course. When a user wants to grade, they select a
                   4782: sequence/folder of resources, a file of bubble sheet info, and pick
                   4783: one of the predefined configurations for what each scanline looks
                   4784: like.
                   4785: 
                   4786: Next each scanline is checked for any errors of either 'missing
1.435     foxr     4787: bubbles' (it's an error because it may have been mis-scanned
1.424     albertel 4788: because too light bubbling), 'double bubble' (each bubble line should
                   4789: have no more that one letter picked), invalid or duplicated CODE,
1.556     weissno  4790: invalid student/employee ID
1.424     albertel 4791: 
                   4792: If the CODE option is used that determines the randomization of the
1.556     weissno  4793: homework problems, either way the student/employee ID is looked up into a
1.424     albertel 4794: username:domain.
                   4795: 
                   4796: During the validation phase the instructor can choose to skip scanlines. 
                   4797: 
1.435     foxr     4798: After the validation phase, there are now 3 bubble sheet files
1.424     albertel 4799: 
                   4800:   scantron_original_filename (unmodified original file)
                   4801:   scantron_corrected_filename (file where the corrected information has replaced the original information)
                   4802:   scantron_skipped_filename (contains the exact text of scanlines that where skipped)
                   4803: 
                   4804: Also there is a separate hash nohist_scantrondata that contains extra
                   4805: correction information that isn't representable in the bubble sheet
                   4806: file (see &scantron_getfile() for more information)
                   4807: 
                   4808: After all scanlines are either valid, marked as valid or skipped, then
                   4809: foreach line foreach problem in the picked sequence, an ssi request is
                   4810: made that simulates a user submitting their selected letter(s) against
                   4811: the homework problem.
1.423     albertel 4812: 
                   4813: =over 4
                   4814: 
                   4815: 
                   4816: 
                   4817: =item defaultFormData
                   4818: 
                   4819:   Returns html hidden inputs used to hold context/default values.
                   4820: 
                   4821:  Arguments:
                   4822:   $symb - $symb of the current resource 
                   4823: 
                   4824: =cut
1.422     foxr     4825: 
1.81      albertel 4826: sub defaultFormData {
1.324     albertel 4827:     my ($symb)=@_;
1.613     www      4828:     return '<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />';
1.81      albertel 4829: }
                   4830: 
1.447     foxr     4831: 
1.423     albertel 4832: =pod 
                   4833: 
                   4834: =item getSequenceDropDown
                   4835: 
                   4836:    Return html dropdown of possible sequences to grade
                   4837:  
                   4838:  Arguments:
1.582     raeburn  4839:    $symb - $symb of the current resource
                   4840:    $map_error - ref to scalar which will container error if
                   4841:                 $navmap object is unavailable in &getSymbMap().
1.423     albertel 4842: 
                   4843: =cut
1.422     foxr     4844: 
1.75      albertel 4845: sub getSequenceDropDown {
1.582     raeburn  4846:     my ($symb,$map_error)=@_;
1.75      albertel 4847:     my $result='<select name="selectpage">'."\n";
1.582     raeburn  4848:     my ($titles,$symbx) = &getSymbMap($map_error);
                   4849:     if (ref($map_error)) {
                   4850:         return if ($$map_error);
                   4851:     }
1.137     albertel 4852:     my ($curpage)=&Apache::lonnet::decode_symb($symb); 
1.75      albertel 4853:     my $ctr=0;
                   4854:     foreach (@$titles) {
                   4855: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
                   4856: 	$result.='<option value="'.$$symbx{$_}.'" '.
1.401     albertel 4857: 	    ($$symbx{$_} =~ /$curpage$/ ? 'selected="selected"' : '').
1.75      albertel 4858: 	    '>'.$showtitle.'</option>'."\n";
                   4859: 	$ctr++;
                   4860:     }
                   4861:     $result.= '</select>';
                   4862:     return $result;
                   4863: }
                   4864: 
1.495     albertel 4865: my %bubble_lines_per_response;     # no. bubble lines for each response.
1.554     raeburn  4866:                                    # key is zero-based index - 0, 1, 2 ...
1.495     albertel 4867: 
                   4868: my %first_bubble_line;             # First bubble line no. for each bubble.
                   4869: 
1.509     raeburn  4870: my %subdivided_bubble_lines;       # no. bubble lines for optionresponse, 
                   4871:                                    # matchresponse or rankresponse, where 
                   4872:                                    # an individual response can have multiple 
                   4873:                                    # lines
1.503     raeburn  4874: 
                   4875: my %responsetype_per_response;     # responsetype for each response
                   4876: 
1.495     albertel 4877: # Save and restore the bubble lines array to the form env.
                   4878: 
                   4879: 
                   4880: sub save_bubble_lines {
                   4881:     foreach my $line (keys(%bubble_lines_per_response)) {
                   4882: 	$env{"form.scantron.bubblelines.$line"}  = $bubble_lines_per_response{$line};
                   4883: 	$env{"form.scantron.first_bubble_line.$line"} =
                   4884: 	    $first_bubble_line{$line};
1.503     raeburn  4885:         $env{"form.scantron.sub_bubblelines.$line"} = 
                   4886:             $subdivided_bubble_lines{$line};
                   4887:         $env{"form.scantron.responsetype.$line"} =
                   4888:             $responsetype_per_response{$line};
1.495     albertel 4889:     }
                   4890: }
                   4891: 
                   4892: 
                   4893: sub restore_bubble_lines {
                   4894:     my $line = 0;
                   4895:     %bubble_lines_per_response = ();
                   4896:     while ($env{"form.scantron.bubblelines.$line"}) {
                   4897: 	my $value = $env{"form.scantron.bubblelines.$line"};
                   4898: 	$bubble_lines_per_response{$line} = $value;
                   4899: 	$first_bubble_line{$line}  =
                   4900: 	    $env{"form.scantron.first_bubble_line.$line"};
1.503     raeburn  4901:         $subdivided_bubble_lines{$line} =
                   4902:             $env{"form.scantron.sub_bubblelines.$line"};
                   4903:         $responsetype_per_response{$line} =
                   4904:             $env{"form.scantron.responsetype.$line"};
1.495     albertel 4905: 	$line++;
                   4906:     }
                   4907: }
                   4908: 
                   4909: #  Given the parsed scanline, get the response for 
                   4910: #  'answer' number n:
                   4911: 
                   4912: sub get_response_bubbles {
                   4913:     my ($parsed_line, $response)  = @_;
                   4914: 
                   4915:     my $bubble_line = $first_bubble_line{$response-1} +1;
                   4916:     my $bubble_lines= $bubble_lines_per_response{$response-1};
                   4917:     
                   4918:     my $selected = "";
                   4919: 
                   4920:     for (my $bline = 0; $bline < $bubble_lines; $bline++) {
                   4921: 	$selected .= $$parsed_line{"scantron.$bubble_line.answer"}.":";
                   4922: 	$bubble_line++;
                   4923:     }
                   4924:     return $selected;
                   4925: }
1.423     albertel 4926: 
                   4927: =pod 
                   4928: 
                   4929: =item scantron_filenames
                   4930: 
                   4931:    Returns a list of the scantron files in the current course 
                   4932: 
                   4933: =cut
1.422     foxr     4934: 
1.202     albertel 4935: sub scantron_filenames {
1.257     albertel 4936:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   4937:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
1.517     raeburn  4938:     my $getpropath = 1;
1.157     albertel 4939:     my @files=&Apache::lonnet::dirlist('userfiles',$cdom,$cname,
1.517     raeburn  4940:                                        $getpropath);
1.202     albertel 4941:     my @possiblenames;
1.201     albertel 4942:     foreach my $filename (sort(@files)) {
1.157     albertel 4943: 	($filename)=split(/&/,$filename);
                   4944: 	if ($filename!~/^scantron_orig_/) { next ; }
                   4945: 	$filename=~s/^scantron_orig_//;
1.202     albertel 4946: 	push(@possiblenames,$filename);
                   4947:     }
                   4948:     return @possiblenames;
                   4949: }
                   4950: 
1.423     albertel 4951: =pod 
                   4952: 
                   4953: =item scantron_uploads
                   4954: 
                   4955:    Returns  html drop-down list of scantron files in current course.
                   4956: 
                   4957:  Arguments:
                   4958:    $file2grade - filename to set as selected in the dropdown
                   4959: 
                   4960: =cut
1.422     foxr     4961: 
1.202     albertel 4962: sub scantron_uploads {
1.209     ng       4963:     my ($file2grade) = @_;
1.202     albertel 4964:     my $result=	'<select name="scantron_selectfile">';
                   4965:     $result.="<option></option>";
                   4966:     foreach my $filename (sort(&scantron_filenames())) {
1.401     albertel 4967: 	$result.="<option".($filename eq $file2grade ? ' selected="selected"':'').">$filename</option>\n";
1.81      albertel 4968:     }
                   4969:     $result.="</select>";
                   4970:     return $result;
                   4971: }
                   4972: 
1.423     albertel 4973: =pod 
                   4974: 
                   4975: =item scantron_scantab
                   4976: 
                   4977:   Returns html drop down of the scantron formats in the scantronformat.tab
                   4978:   file.
                   4979: 
                   4980: =cut
1.422     foxr     4981: 
1.82      albertel 4982: sub scantron_scantab {
                   4983:     my $result='<select name="scantron_format">'."\n";
1.191     albertel 4984:     $result.='<option></option>'."\n";
1.518     raeburn  4985:     my @lines = &get_scantronformat_file();
                   4986:     if (@lines > 0) {
                   4987:         foreach my $line (@lines) {
                   4988:             next if (($line =~ /^\#/) || ($line eq ''));
                   4989: 	    my ($name,$descrip)=split(/:/,$line);
                   4990: 	    $result.='<option value="'.$name.'">'.$descrip.'</option>'."\n";
                   4991:         }
1.82      albertel 4992:     }
                   4993:     $result.='</select>'."\n";
1.518     raeburn  4994:     return $result;
                   4995: }
                   4996: 
                   4997: =pod
                   4998: 
                   4999: =item get_scantronformat_file
                   5000: 
                   5001:   Returns an array containing lines from the scantron format file for
                   5002:   the domain of the course.
                   5003: 
                   5004:   If a url for a custom.tab file is listed in domain's configuration.db, 
                   5005:   lines are from this file.
                   5006: 
                   5007:   Otherwise, if a default.tab has been published in RES space by the 
                   5008:   domainconfig user, lines are from this file.
                   5009: 
                   5010:   Otherwise, fall back to getting lines from the legacy file on the
1.519     raeburn  5011:   local server:  /home/httpd/lonTabs/default_scantronformat.tab    
1.82      albertel 5012: 
1.518     raeburn  5013: =cut
                   5014: 
                   5015: sub get_scantronformat_file {
                   5016:     my $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
                   5017:     my %domconfig = &Apache::lonnet::get_dom('configuration',['scantron'],$cdom);
                   5018:     my $gottab = 0;
                   5019:     my @lines;
                   5020:     if (ref($domconfig{'scantron'}) eq 'HASH') {
                   5021:         if ($domconfig{'scantron'}{'scantronformat'} ne '') {
                   5022:             my $formatfile = &Apache::lonnet::getfile($Apache::lonnet::perlvar{'lonDocRoot'}.$domconfig{'scantron'}{'scantronformat'});
                   5023:             if ($formatfile ne '-1') {
                   5024:                 @lines = split("\n",$formatfile,-1);
                   5025:                 $gottab = 1;
                   5026:             }
                   5027:         }
                   5028:     }
                   5029:     if (!$gottab) {
                   5030:         my $confname = $cdom.'-domainconfig';
                   5031:         my $default = $Apache::lonnet::perlvar{'lonDocRoot'}.'/res/'.$cdom.'/'.$confname.'/default.tab';
                   5032:         my $formatfile =  &Apache::lonnet::getfile($default);
                   5033:         if ($formatfile ne '-1') {
                   5034:             @lines = split("\n",$formatfile,-1);
                   5035:             $gottab = 1;
                   5036:         }
                   5037:     }
                   5038:     if (!$gottab) {
1.519     raeburn  5039:         my @domains = &Apache::lonnet::current_machine_domains();
                   5040:         if (grep(/^\Q$cdom\E$/,@domains)) {
                   5041:             my $fh=Apache::File->new($Apache::lonnet::perlvar{'lonTabDir'}.'/scantronformat.tab');
                   5042:             @lines = <$fh>;
                   5043:             close($fh);
                   5044:         } else {
                   5045:             my $fh=Apache::File->new($Apache::lonnet::perlvar{'lonTabDir'}.'/default_scantronformat.tab');
                   5046:             @lines = <$fh>;
                   5047:             close($fh);
                   5048:         }
1.518     raeburn  5049:     }
                   5050:     return @lines;
1.82      albertel 5051: }
                   5052: 
1.423     albertel 5053: =pod 
                   5054: 
                   5055: =item scantron_CODElist
                   5056: 
                   5057:   Returns html drop down of the saved CODE lists from current course,
                   5058:   generated from earlier printings.
                   5059: 
                   5060: =cut
1.422     foxr     5061: 
1.186     albertel 5062: sub scantron_CODElist {
1.257     albertel 5063:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   5064:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
1.186     albertel 5065:     my @names=&Apache::lonnet::getkeys('CODEs',$cdom,$cnum);
                   5066:     my $namechoice='<option></option>';
1.225     albertel 5067:     foreach my $name (sort {uc($a) cmp uc($b)} @names) {
1.191     albertel 5068: 	if ($name =~ /^error: 2 /) { next; }
1.278     albertel 5069: 	if ($name =~ /^type\0/) { next; }
1.186     albertel 5070: 	$namechoice.='<option value="'.$name.'">'.$name.'</option>';
                   5071:     }
                   5072:     $namechoice='<select name="scantron_CODElist">'.$namechoice.'</select>';
                   5073:     return $namechoice;
                   5074: }
                   5075: 
1.423     albertel 5076: =pod 
                   5077: 
                   5078: =item scantron_CODEunique
                   5079: 
                   5080:   Returns the html for "Each CODE to be used once" radio.
                   5081: 
                   5082: =cut
1.422     foxr     5083: 
1.186     albertel 5084: sub scantron_CODEunique {
1.532     bisitz   5085:     my $result='<span class="LC_nobreak">
1.272     albertel 5086:                  <label><input type="radio" name="scantron_CODEunique"
1.423     albertel 5087:                         value="yes" checked="checked" />'.&mt('Yes').' </label>
1.381     albertel 5088:                 </span>
1.532     bisitz   5089:                 <span class="LC_nobreak">
1.272     albertel 5090:                  <label><input type="radio" name="scantron_CODEunique"
1.423     albertel 5091:                         value="no" />'.&mt('No').' </label>
1.381     albertel 5092:                 </span>';
1.186     albertel 5093:     return $result;
                   5094: }
1.423     albertel 5095: 
                   5096: =pod 
                   5097: 
                   5098: =item scantron_selectphase
                   5099: 
                   5100:   Generates the initial screen to start the bubble sheet process.
                   5101:   Allows for - starting a grading run.
1.424     albertel 5102:              - downloading existing scan data (original, corrected
1.423     albertel 5103:                                                 or skipped info)
                   5104: 
                   5105:              - uploading new scan data
                   5106: 
                   5107:  Arguments:
                   5108:   $r          - The Apache request object
                   5109:   $file2grade - name of the file that contain the scanned data to score
                   5110: 
                   5111: =cut
1.186     albertel 5112: 
1.75      albertel 5113: sub scantron_selectphase {
1.608     www      5114:     my ($r,$file2grade,$symb) = @_;
1.75      albertel 5115:     if (!$symb) {return '';}
1.582     raeburn  5116:     my $map_error;
                   5117:     my $sequence_selector=&getSequenceDropDown($symb,\$map_error);
                   5118:     if ($map_error) {
                   5119:         $r->print('<br />'.&navmap_errormsg().'<br />');
                   5120:         return;
                   5121:     }
1.324     albertel 5122:     my $default_form_data=&defaultFormData($symb);
1.209     ng       5123:     my $file_selector=&scantron_uploads($file2grade);
1.82      albertel 5124:     my $format_selector=&scantron_scantab();
1.186     albertel 5125:     my $CODE_selector=&scantron_CODElist();
                   5126:     my $CODE_unique=&scantron_CODEunique();
1.75      albertel 5127:     my $result;
1.422     foxr     5128: 
1.513     foxr     5129:     $ssi_error = 0;
                   5130: 
1.606     wenzelju 5131:     if (&Apache::lonnet::allowed('usc',$env{'request.role.domain'}) ||
                   5132:         &Apache::lonnet::allowed('usc',$env{'request.course.id'})) {
                   5133: 
                   5134: 	# Chunk of form to prompt for a scantron file upload.
                   5135: 
                   5136:         $r->print('
                   5137:     <br />
                   5138:     '.&Apache::loncommon::start_data_table('LC_scantron_action').'
                   5139:        '.&Apache::loncommon::start_data_table_header_row().'
                   5140:             <th>
                   5141:               &nbsp;'.&mt('Specify a bubblesheet data file to upload.').'
                   5142:             </th>
                   5143:        '.&Apache::loncommon::end_data_table_header_row().'
                   5144:        '.&Apache::loncommon::start_data_table_row().'
                   5145:             <td>
                   5146: ');
1.608     www      5147:     my $default_form_data=&defaultFormData($symb);
1.606     wenzelju 5148:     my $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
                   5149:     my $cnum= $env{'course.'.$env{'request.course.id'}.'.num'};
                   5150:     $r->print(&Apache::lonhtmlcommon::scripttag('
                   5151:     function checkUpload(formname) {
                   5152: 	if (formname.upfile.value == "") {
                   5153: 	    alert("'.&mt('Please use the browse button to select a file from your local directory.').'");
                   5154: 	    return false;
                   5155: 	}
                   5156: 	formname.submit();
                   5157:     }'));
                   5158:     $r->print('
                   5159:               <form enctype="multipart/form-data" action="/adm/grades" name="rules" method="post">
                   5160:                 '.$default_form_data.'
                   5161:                 <input name="courseid" type="hidden" value="'.$cnum.'" />
                   5162:                 <input name="domainid" type="hidden" value="'.$cdom.'" />
                   5163:                 <input name="command" value="scantronupload_save" type="hidden" />
                   5164:                 '.&mt('File to upload: [_1]','<input type="file" name="upfile" size="50" />').'
                   5165:                 <br />
                   5166:                 <input type="button" onclick="javascript:checkUpload(this.form);" value="'.&mt('Upload Bubblesheet Data').'" />
                   5167:               </form>
                   5168: ');
                   5169: 
                   5170:         $r->print('
                   5171:             </td>
                   5172:        '.&Apache::loncommon::end_data_table_row().'
                   5173:        '.&Apache::loncommon::end_data_table().'
                   5174: ');
                   5175:     }
                   5176: 
1.422     foxr     5177:     # Chunk of form to prompt for a file to grade and how:
                   5178: 
1.489     albertel 5179:     $result.= '
                   5180:     <br />
                   5181:     <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantron_process">
                   5182:     <input type="hidden" name="command" value="scantron_warning" />
                   5183:     '.$default_form_data.'
                   5184:     '.&Apache::loncommon::start_data_table('LC_scantron_action').'
                   5185:        '.&Apache::loncommon::start_data_table_header_row().'
                   5186:             <th colspan="2">
1.492     albertel 5187:               &nbsp;'.&mt('Specify file and which Folder/Sequence to grade').'
1.489     albertel 5188:             </th>
                   5189:        '.&Apache::loncommon::end_data_table_header_row().'
                   5190:        '.&Apache::loncommon::start_data_table_row().'
1.492     albertel 5191:             <td> '.&mt('Sequence to grade:').' </td><td> '.$sequence_selector.' </td>
1.489     albertel 5192:        '.&Apache::loncommon::end_data_table_row().'
                   5193:        '.&Apache::loncommon::start_data_table_row().'
1.572     www      5194:             <td> '.&mt('Filename of bubblesheet data file:').' </td><td> '.$file_selector.' </td>
1.489     albertel 5195:        '.&Apache::loncommon::end_data_table_row().'
                   5196:        '.&Apache::loncommon::start_data_table_row().'
1.572     www      5197:             <td> '.&mt('Format of bubblesheet data file:').' </td><td> '.$format_selector.' </td>
1.489     albertel 5198:        '.&Apache::loncommon::end_data_table_row().'
                   5199:        '.&Apache::loncommon::start_data_table_row().'
1.492     albertel 5200:             <td> '.&mt('Saved CODEs to validate against:').' </td><td> '.$CODE_selector.' </td>
1.489     albertel 5201:        '.&Apache::loncommon::end_data_table_row().'
                   5202:        '.&Apache::loncommon::start_data_table_row().'
1.492     albertel 5203:             <td> '.&mt('Each CODE is only to be used once:').'</td><td> '.$CODE_unique.' </td>
1.489     albertel 5204:        '.&Apache::loncommon::end_data_table_row().'
                   5205:        '.&Apache::loncommon::start_data_table_row().'
1.492     albertel 5206: 	    <td> '.&mt('Options:').' </td>
1.187     albertel 5207:             <td>
1.492     albertel 5208: 	       <label><input type="checkbox" name="scantron_options_redo" value="redo_skipped"/> '.&mt('Do only previously skipped records').'</label> <br />
                   5209:                <label><input type="checkbox" name="scantron_options_ignore" value="ignore_corrections"/> '.&mt('Remove all existing corrections').'</label> <br />
                   5210:                <label><input type="checkbox" name="scantron_options_hidden" value="ignore_hidden"/> '.&mt('Skip hidden resources when grading').'</label>
1.187     albertel 5211: 	    </td>
1.489     albertel 5212:        '.&Apache::loncommon::end_data_table_row().'
                   5213:        '.&Apache::loncommon::start_data_table_row().'
1.174     albertel 5214:             <td colspan="2">
1.572     www      5215:               <input type="submit" value="'.&mt('Grading: Validate Bubblesheet Records').'" />
1.162     albertel 5216:             </td>
1.489     albertel 5217:        '.&Apache::loncommon::end_data_table_row().'
                   5218:     '.&Apache::loncommon::end_data_table().'
                   5219:     </form>
                   5220: ';
1.162     albertel 5221:    
                   5222:     $r->print($result);
                   5223: 
1.422     foxr     5224: 
                   5225: 
                   5226:     # Chunk of the form that prompts to view a scoring office file,
                   5227:     # corrected file, skipped records in a file.
                   5228: 
1.489     albertel 5229:     $r->print('
                   5230:    <br />
                   5231:    <form action="/adm/grades" name="scantron_download">
                   5232:      '.$default_form_data.'
                   5233:      <input type="hidden" name="command" value="scantron_download" />
                   5234:      '.&Apache::loncommon::start_data_table('LC_scantron_action').'
                   5235:        '.&Apache::loncommon::start_data_table_header_row().'
                   5236:               <th>
1.492     albertel 5237:                 &nbsp;'.&mt('Download a scoring office file').'
1.489     albertel 5238:               </th>
                   5239:        '.&Apache::loncommon::end_data_table_header_row().'
                   5240:        '.&Apache::loncommon::start_data_table_row().'
1.492     albertel 5241:               <td> '.&mt('Filename of scoring office file: [_1]',$file_selector).' 
1.489     albertel 5242:                 <br />
1.492     albertel 5243:                 <input type="submit" value="'.&mt('Download: Show List of Associated Files').'" />
1.489     albertel 5244:        '.&Apache::loncommon::end_data_table_row().'
                   5245:      '.&Apache::loncommon::end_data_table().'
                   5246:    </form>
                   5247:    <br />
                   5248: ');
1.162     albertel 5249: 
1.457     banghart 5250:     &Apache::lonpickcode::code_list($r,2);
1.523     raeburn  5251: 
1.528     raeburn  5252:     $r->print('<br /><form method="post" name="checkscantron">'.
1.523     raeburn  5253:              $default_form_data."\n".
                   5254:              &Apache::loncommon::start_data_table('LC_scantron_action')."\n".
                   5255:              &Apache::loncommon::start_data_table_header_row()."\n".
                   5256:              '<th colspan="2">
1.572     www      5257:               &nbsp;'.&mt('Review bubblesheet data and submissions for a previously graded folder/sequence')."\n".
1.523     raeburn  5258:              '</th>'."\n".
                   5259:               &Apache::loncommon::end_data_table_header_row()."\n".
                   5260:               &Apache::loncommon::start_data_table_row()."\n".
                   5261:               '<td> '.&mt('Graded folder/sequence:').' </td>'."\n".
                   5262:               '<td> '.$sequence_selector.' </td>'.
                   5263:               &Apache::loncommon::end_data_table_row()."\n".
                   5264:               &Apache::loncommon::start_data_table_row()."\n".
                   5265:               '<td> '.&mt('Filename of scoring office file:').' </td>'."\n".
                   5266:               '<td> '.$file_selector.' </td>'."\n".
                   5267:               &Apache::loncommon::end_data_table_row()."\n".
                   5268:               &Apache::loncommon::start_data_table_row()."\n".
                   5269:               '<td> '.&mt('Format of data file:').' </td>'."\n".
                   5270:               '<td> '.$format_selector.' </td>'."\n".
                   5271:               &Apache::loncommon::end_data_table_row()."\n".
                   5272:               &Apache::loncommon::start_data_table_row()."\n".
1.557     raeburn  5273:               '<td> '.&mt('Options').' </td>'."\n".
                   5274:               '<td> <label><input type="checkbox" name="scantron_options_hidden" value="ignore_hidden"/> '.&mt('Skip hidden resources').'</label></td>'.
                   5275:               &Apache::loncommon::end_data_table_row()."\n".
                   5276:               &Apache::loncommon::start_data_table_row()."\n".
1.523     raeburn  5277:               '<td colspan="2">'."\n".
                   5278:               '<input type="hidden" name="command" value="checksubmissions" />'."\n".
1.575     www      5279:               '<input type="submit" value="'.&mt('Review Bubblesheet Data and Submission Records').'" />'."\n".
1.523     raeburn  5280:               '</td>'."\n".
                   5281:               &Apache::loncommon::end_data_table_row()."\n".
                   5282:               &Apache::loncommon::end_data_table()."\n".
                   5283:               '</form><br />');
                   5284:     return;
1.75      albertel 5285: }
                   5286: 
1.423     albertel 5287: =pod
                   5288: 
                   5289: =item get_scantron_config
                   5290: 
                   5291:    Parse and return the scantron configuration line selected as a
                   5292:    hash of configuration file fields.
                   5293: 
                   5294:  Arguments:
                   5295:     which - the name of the configuration to parse from the file.
                   5296: 
                   5297: 
                   5298:  Returns:
                   5299:             If the named configuration is not in the file, an empty
                   5300:             hash is returned.
                   5301:     a hash with the fields
                   5302:       name         - internal name for the this configuration setup
                   5303:       description  - text to display to operator that describes this config
                   5304:       CODElocation - if 0 or the string 'none'
                   5305:                           - no CODE exists for this config
                   5306:                      if -1 || the string 'letter'
                   5307:                           - a CODE exists for this config and is
                   5308:                             a string of letters
                   5309:                      Unsupported value (but planned for future support)
                   5310:                           if a positive integer
                   5311:                                - The CODE exists as the first n items from
                   5312:                                  the question section of the form
                   5313:                           if the string 'number'
                   5314:                                - The CODE exists for this config and is
                   5315:                                  a string of numbers
                   5316:       CODEstart   - (only matter if a CODE exists) column in the line where
                   5317:                      the CODE starts
                   5318:       CODElength  - length of the CODE
1.573     bisitz   5319:       IDstart     - column where the student/employee ID starts
1.556     weissno  5320:       IDlength    - length of the student/employee ID info
1.423     albertel 5321:       Qstart      - column where the information from the bubbled
                   5322:                     'questions' start
                   5323:       Qlength     - number of columns comprising a single bubble line from
                   5324:                     the sheet. (usually either 1 or 10)
1.424     albertel 5325:       Qon         - either a single character representing the character used
1.423     albertel 5326:                     to signal a bubble was chosen in the positional setup, or
                   5327:                     the string 'letter' if the letter of the chosen bubble is
                   5328:                     in the final, or 'number' if a number representing the
                   5329:                     chosen bubble is in the file (1->A 0->J)
1.424     albertel 5330:       Qoff        - the character used to represent that a bubble was
                   5331:                     left blank
1.423     albertel 5332:       PaperID     - if the scanning process generates a unique number for each
                   5333:                     sheet scanned the column that this ID number starts in
                   5334:       PaperIDlength - number of columns that comprise the unique ID number
                   5335:                       for the sheet of paper
1.424     albertel 5336:       FirstName   - column that the first name starts in
1.423     albertel 5337:       FirstNameLength - number of columns that the first name spans
                   5338:  
                   5339:       LastName    - column that the last name starts in
                   5340:       LastNameLength - number of columns that the last name spans
                   5341: 
                   5342: =cut
1.422     foxr     5343: 
1.82      albertel 5344: sub get_scantron_config {
                   5345:     my ($which) = @_;
1.518     raeburn  5346:     my @lines = &get_scantronformat_file();
1.82      albertel 5347:     my %config;
1.157     albertel 5348:     #FIXME probably should move to XML it has already gotten a bit much now
1.518     raeburn  5349:     foreach my $line (@lines) {
1.82      albertel 5350: 	my ($name,$descrip)=split(/:/,$line);
                   5351: 	if ($name ne $which ) { next; }
                   5352: 	chomp($line);
                   5353: 	my @config=split(/:/,$line);
                   5354: 	$config{'name'}=$config[0];
                   5355: 	$config{'description'}=$config[1];
                   5356: 	$config{'CODElocation'}=$config[2];
                   5357: 	$config{'CODEstart'}=$config[3];
                   5358: 	$config{'CODElength'}=$config[4];
                   5359: 	$config{'IDstart'}=$config[5];
                   5360: 	$config{'IDlength'}=$config[6];
                   5361: 	$config{'Qstart'}=$config[7];
1.497     foxr     5362:  	$config{'Qlength'}=$config[8];
1.82      albertel 5363: 	$config{'Qoff'}=$config[9];
                   5364: 	$config{'Qon'}=$config[10];
1.157     albertel 5365: 	$config{'PaperID'}=$config[11];
                   5366: 	$config{'PaperIDlength'}=$config[12];
                   5367: 	$config{'FirstName'}=$config[13];
                   5368: 	$config{'FirstNamelength'}=$config[14];
                   5369: 	$config{'LastName'}=$config[15];
                   5370: 	$config{'LastNamelength'}=$config[16];
1.82      albertel 5371: 	last;
                   5372:     }
                   5373:     return %config;
                   5374: }
                   5375: 
1.423     albertel 5376: =pod 
                   5377: 
                   5378: =item username_to_idmap
                   5379: 
1.556     weissno  5380:     creates a hash keyed by student/employee ID with values of the corresponding
1.423     albertel 5381:     student username:domain.
                   5382: 
                   5383:   Arguments:
                   5384: 
                   5385:     $classlist - reference to the class list hash. This is a hash
                   5386:                  keyed by student name:domain  whose elements are references
1.424     albertel 5387:                  to arrays containing various chunks of information
1.423     albertel 5388:                  about the student. (See loncoursedata for more info).
                   5389: 
                   5390:   Returns
                   5391:     %idmap - the constructed hash
                   5392: 
                   5393: =cut
                   5394: 
1.82      albertel 5395: sub username_to_idmap {
                   5396:     my ($classlist)= @_;
                   5397:     my %idmap;
                   5398:     foreach my $student (keys(%$classlist)) {
                   5399: 	$idmap{$classlist->{$student}->[&Apache::loncoursedata::CL_ID]}=
                   5400: 	    $student;
                   5401:     }
                   5402:     return %idmap;
                   5403: }
1.423     albertel 5404: 
                   5405: =pod
                   5406: 
1.424     albertel 5407: =item scantron_fixup_scanline
1.423     albertel 5408: 
                   5409:    Process a requested correction to a scanline.
                   5410: 
                   5411:   Arguments:
                   5412:     $scantron_config   - hash from &get_scantron_config()
                   5413:     $scan_data         - hash of correction information 
                   5414:                           (see &scantron_getfile())
                   5415:     $line              - existing scanline
                   5416:     $whichline         - line number of the passed in scanline
                   5417:     $field             - type of change to process 
                   5418:                          (either 
1.573     bisitz   5419:                           'ID'     -> correct the student/employee ID
1.423     albertel 5420:                           'CODE'   -> correct the CODE
                   5421:                           'answer' -> fixup the submitted answers)
                   5422:     
                   5423:    $args               - hash of additional info,
                   5424:                           - 'ID' 
                   5425:                                'newid' -> studentID to use in replacement
1.424     albertel 5426:                                           of existing one
1.423     albertel 5427:                           - 'CODE' 
                   5428:                                'CODE_ignore_dup' - set to true if duplicates
                   5429:                                                    should be ignored.
                   5430: 	                       'CODE' - is new code or 'use_unfound'
1.424     albertel 5431:                                         if the existing unfound code should
1.423     albertel 5432:                                         be used as is
                   5433:                           - 'answer'
                   5434:                                'response' - new answer or 'none' if blank
                   5435:                                'question' - the bubble line to change
1.503     raeburn  5436:                                'questionnum' - the question identifier,
                   5437:                                                may include subquestion. 
1.423     albertel 5438: 
                   5439:   Returns:
                   5440:     $line - the modified scanline
                   5441: 
                   5442:   Side effects: 
                   5443:     $scan_data - may be updated
                   5444: 
                   5445: =cut
                   5446: 
1.82      albertel 5447: 
1.157     albertel 5448: sub scantron_fixup_scanline {
                   5449:     my ($scantron_config,$scan_data,$line,$whichline,$field,$args)=@_;
                   5450:     if ($field eq 'ID') {
                   5451: 	if (length($args->{'newid'}) > $$scantron_config{'IDlength'}) {
1.186     albertel 5452: 	    return ($line,1,'New value too large');
1.157     albertel 5453: 	}
                   5454: 	if (length($args->{'newid'}) < $$scantron_config{'IDlength'}) {
                   5455: 	    $args->{'newid'}=sprintf('%-'.$$scantron_config{'IDlength'}.'s',
                   5456: 				     $args->{'newid'});
                   5457: 	}
                   5458: 	substr($line,$$scantron_config{'IDstart'}-1,
                   5459: 	       $$scantron_config{'IDlength'})=$args->{'newid'};
                   5460: 	if ($args->{'newid'}=~/^\s*$/) {
                   5461: 	    &scan_data($scan_data,"$whichline.user",
                   5462: 		       $args->{'username'}.':'.$args->{'domain'});
                   5463: 	}
1.186     albertel 5464:     } elsif ($field eq 'CODE') {
1.192     albertel 5465: 	if ($args->{'CODE_ignore_dup'}) {
                   5466: 	    &scan_data($scan_data,"$whichline.CODE_ignore_dup",'1');
                   5467: 	}
                   5468: 	&scan_data($scan_data,"$whichline.useCODE",'1');
                   5469: 	if ($args->{'CODE'} ne 'use_unfound') {
1.191     albertel 5470: 	    if (length($args->{'CODE'}) > $$scantron_config{'CODElength'}) {
                   5471: 		return ($line,1,'New CODE value too large');
                   5472: 	    }
                   5473: 	    if (length($args->{'CODE'}) < $$scantron_config{'CODElength'}) {
                   5474: 		$args->{'CODE'}=sprintf('%-'.$$scantron_config{'CODElength'}.'s',$args->{'CODE'});
                   5475: 	    }
                   5476: 	    substr($line,$$scantron_config{'CODEstart'}-1,
                   5477: 		   $$scantron_config{'CODElength'})=$args->{'CODE'};
1.186     albertel 5478: 	}
1.157     albertel 5479:     } elsif ($field eq 'answer') {
1.497     foxr     5480: 	my $length=$scantron_config->{'Qlength'};
1.157     albertel 5481: 	my $off=$scantron_config->{'Qoff'};
                   5482: 	my $on=$scantron_config->{'Qon'};
1.497     foxr     5483: 	my $answer=${off}x$length;
                   5484: 	if ($args->{'response'} eq 'none') {
                   5485: 	    &scan_data($scan_data,
1.503     raeburn  5486: 		       "$whichline.no_bubble.".$args->{'questionnum'},'1');
1.497     foxr     5487: 	} else {
                   5488: 	    if ($on eq 'letter') {
                   5489: 		my @alphabet=('A'..'Z');
                   5490: 		$answer=$alphabet[$args->{'response'}];
                   5491: 	    } elsif ($on eq 'number') {
                   5492: 		$answer=$args->{'response'}+1;
                   5493: 		if ($answer == 10) { $answer = '0'; }
1.274     albertel 5494: 	    } else {
1.497     foxr     5495: 		substr($answer,$args->{'response'},1)=$on;
1.274     albertel 5496: 	    }
1.497     foxr     5497: 	    &scan_data($scan_data,
1.503     raeburn  5498: 		       "$whichline.no_bubble.".$args->{'questionnum'},undef,'1');
1.157     albertel 5499: 	}
1.497     foxr     5500: 	my $where=$length*($args->{'question'}-1)+$scantron_config->{'Qstart'};
                   5501: 	substr($line,$where-1,$length)=$answer;
1.157     albertel 5502:     }
                   5503:     return $line;
                   5504: }
1.423     albertel 5505: 
                   5506: =pod
                   5507: 
                   5508: =item scan_data
                   5509: 
                   5510:     Edit or look up  an item in the scan_data hash.
                   5511: 
                   5512:   Arguments:
                   5513:     $scan_data  - The hash (see scantron_getfile)
                   5514:     $key        - shorthand of the key to edit (actual key is
1.424     albertel 5515:                   scantronfilename_key).
1.423     albertel 5516:     $data        - New value of the hash entry.
                   5517:     $delete      - If true, the entry is removed from the hash.
                   5518: 
                   5519:   Returns:
                   5520:     The new value of the hash table field (undefined if deleted).
                   5521: 
                   5522: =cut
                   5523: 
                   5524: 
1.157     albertel 5525: sub scan_data {
                   5526:     my ($scan_data,$key,$value,$delete)=@_;
1.257     albertel 5527:     my $filename=$env{'form.scantron_selectfile'};
1.157     albertel 5528:     if (defined($value)) {
                   5529: 	$scan_data->{$filename.'_'.$key} = $value;
                   5530:     }
                   5531:     if ($delete) { delete($scan_data->{$filename.'_'.$key}); }
                   5532:     return $scan_data->{$filename.'_'.$key};
                   5533: }
1.423     albertel 5534: 
1.495     albertel 5535: # ----- These first few routines are general use routines.----
                   5536: 
                   5537: # Return the number of occurences of a pattern in a string.
                   5538: 
                   5539: sub occurence_count {
                   5540:     my ($string, $pattern) = @_;
                   5541: 
                   5542:     my @matches = ($string =~ /$pattern/g);
                   5543: 
                   5544:     return scalar(@matches);
                   5545: }
                   5546: 
                   5547: 
                   5548: # Take a string known to have digits and convert all the
                   5549: # digits into letters in the range J,A..I.
                   5550: 
                   5551: sub digits_to_letters {
                   5552:     my ($input) = @_;
                   5553: 
                   5554:     my @alphabet = ('J', 'A'..'I');
                   5555: 
                   5556:     my @input    = split(//, $input);
                   5557:     my $output ='';
                   5558:     for (my $i = 0; $i < scalar(@input); $i++) {
                   5559: 	if ($input[$i] =~ /\d/) {
                   5560: 	    $output .= $alphabet[$input[$i]];
                   5561: 	} else {
                   5562: 	    $output .= $input[$i];
                   5563: 	}
                   5564:     }
                   5565:     return $output;
                   5566: }
                   5567: 
1.423     albertel 5568: =pod 
                   5569: 
                   5570: =item scantron_parse_scanline
                   5571: 
                   5572:   Decodes a scanline from the selected scantron file
                   5573: 
                   5574:  Arguments:
                   5575:     line             - The text of the scantron file line to process
                   5576:     whichline        - Line number
                   5577:     scantron_config  - Hash describing the format of the scantron lines.
                   5578:     scan_data        - Hash of extra information about the scanline
                   5579:                        (see scantron_getfile for more information)
                   5580:     just_header      - True if should not process question answers but only
                   5581:                        the stuff to the left of the answers.
                   5582:  Returns:
                   5583:    Hash containing the result of parsing the scanline
                   5584: 
                   5585:    Keys are all proceeded by the string 'scantron.'
                   5586: 
                   5587:        CODE    - the CODE in use for this scanline
                   5588:        useCODE - 1 if the CODE is invalid but it usage has been forced
                   5589:                  by the operator
                   5590:        CODE_ignore_dup - 1 if the CODE is a duplicated use when unique
                   5591:                             CODEs were selected, but the usage has been
                   5592:                             forced by the operator
1.556     weissno  5593:        ID  - student/employee ID
1.423     albertel 5594:        PaperID - if used, the ID number printed on the sheet when the 
                   5595:                  paper was scanned
                   5596:        FirstName - first name from the sheet
                   5597:        LastName  - last name from the sheet
                   5598: 
                   5599:      if just_header was not true these key may also exist
                   5600: 
1.447     foxr     5601:        missingerror - a list of bubble ranges that are considered to be answers
                   5602:                       to a single question that don't have any bubbles filled in.
                   5603:                       Of the form questionnumber:firstbubblenumber:count.
                   5604:        doubleerror  - a list of bubble ranges that are considered to be answers
                   5605:                       to a single question that have more than one bubble filled in.
                   5606:                       Of the form questionnumber::firstbubblenumber:count
                   5607:    
                   5608:                 In the above, count is the number of bubble responses in the
                   5609:                 input line needed to represent the possible answers to the question.
                   5610:                 e.g. a radioresponse with 15 choices in an answer sheet with 10 choices
                   5611:                 per line would have count = 2.
                   5612: 
1.423     albertel 5613:        maxquest     - the number of the last bubble line that was parsed
                   5614: 
                   5615:        (<number> starts at 1)
                   5616:        <number>.answer - zero or more letters representing the selected
                   5617:                          letters from the scanline for the bubble line 
                   5618:                          <number>.
                   5619:                          if blank there was either no bubble or there where
                   5620:                          multiple bubbles, (consult the keys missingerror and
                   5621:                          doubleerror if this is an error condition)
                   5622: 
                   5623: =cut
                   5624: 
1.82      albertel 5625: sub scantron_parse_scanline {
1.423     albertel 5626:     my ($line,$whichline,$scantron_config,$scan_data,$just_header)=@_;
1.470     foxr     5627: 
1.82      albertel 5628:     my %record;
1.550     raeburn  5629:     my $lastpos = $env{'form.scantron_maxbubble'}*$$scantron_config{'Qlength'};
                   5630:     my $questions=substr($line,$$scantron_config{'Qstart'}-1,$lastpos);  # Answers
1.422     foxr     5631:     my $data=substr($line,0,$$scantron_config{'Qstart'}-1);     # earlier stuff
1.278     albertel 5632:     if (!($$scantron_config{'CODElocation'} eq 0 ||
                   5633: 	  $$scantron_config{'CODElocation'} eq 'none')) {
                   5634: 	if ($$scantron_config{'CODElocation'} < 0 ||
                   5635: 	    $$scantron_config{'CODElocation'} eq 'letter' ||
                   5636: 	    $$scantron_config{'CODElocation'} eq 'number') {
1.191     albertel 5637: 	    $record{'scantron.CODE'}=substr($data,
                   5638: 					    $$scantron_config{'CODEstart'}-1,
1.83      albertel 5639: 					    $$scantron_config{'CODElength'});
1.191     albertel 5640: 	    if (&scan_data($scan_data,"$whichline.useCODE")) {
                   5641: 		$record{'scantron.useCODE'}=1;
                   5642: 	    }
1.192     albertel 5643: 	    if (&scan_data($scan_data,"$whichline.CODE_ignore_dup")) {
                   5644: 		$record{'scantron.CODE_ignore_dup'}=1;
                   5645: 	    }
1.82      albertel 5646: 	} else {
                   5647: 	    #FIXME interpret first N questions
                   5648: 	}
                   5649:     }
1.83      albertel 5650:     $record{'scantron.ID'}=substr($data,$$scantron_config{'IDstart'}-1,
                   5651: 				  $$scantron_config{'IDlength'});
1.157     albertel 5652:     $record{'scantron.PaperID'}=
                   5653: 	substr($data,$$scantron_config{'PaperID'}-1,
                   5654: 	       $$scantron_config{'PaperIDlength'});
                   5655:     $record{'scantron.FirstName'}=
                   5656: 	substr($data,$$scantron_config{'FirstName'}-1,
                   5657: 	       $$scantron_config{'FirstNamelength'});
                   5658:     $record{'scantron.LastName'}=
                   5659: 	substr($data,$$scantron_config{'LastName'}-1,
                   5660: 	       $$scantron_config{'LastNamelength'});
1.423     albertel 5661:     if ($just_header) { return \%record; }
1.194     albertel 5662: 
1.82      albertel 5663:     my @alphabet=('A'..'Z');
                   5664:     my $questnum=0;
1.447     foxr     5665:     my $ansnum  =1;		# Multiple 'answer lines'/question.
                   5666: 
1.470     foxr     5667:     chomp($questions);		# Get rid of any trailing \n.
                   5668:     $questions =~ s/\r$//;      # Get rid of trailing \r too (MAC or Win uploads).
                   5669:     while (length($questions)) {
1.447     foxr     5670: 	my $answers_needed = $bubble_lines_per_response{$questnum};
1.503     raeburn  5671:         my $answer_length  = ($$scantron_config{'Qlength'} * $answers_needed)
                   5672:                              || 1;
                   5673:         $questnum++;
                   5674:         my $quest_id = $questnum;
                   5675:         my $currentquest = substr($questions,0,$answer_length);
                   5676:         $questions       = substr($questions,$answer_length);
                   5677:         if (length($currentquest) < $answer_length) { next; }
                   5678: 
                   5679:         if ($subdivided_bubble_lines{$questnum-1} =~ /,/) {
                   5680:             my $subquestnum = 1;
                   5681:             my $subquestions = $currentquest;
                   5682:             my @subanswers_needed = 
                   5683:                 split(/,/,$subdivided_bubble_lines{$questnum-1});  
                   5684:             foreach my $subans (@subanswers_needed) {
                   5685:                 my $subans_length =
                   5686:                     ($$scantron_config{'Qlength'} * $subans)  || 1;
                   5687:                 my $currsubquest = substr($subquestions,0,$subans_length);
                   5688:                 $subquestions   = substr($subquestions,$subans_length);
                   5689:                 $quest_id = "$questnum.$subquestnum";
                   5690:                 if (($$scantron_config{'Qon'} eq 'letter') ||
                   5691:                     ($$scantron_config{'Qon'} eq 'number')) {
                   5692:                     $ansnum = &scantron_validator_lettnum($ansnum, 
                   5693:                         $questnum,$quest_id,$subans,$currsubquest,$whichline,
                   5694:                         \@alphabet,\%record,$scantron_config,$scan_data);
                   5695:                 } else {
                   5696:                     $ansnum = &scantron_validator_positional($ansnum,
                   5697:                         $questnum,$quest_id,$subans,$currsubquest,$whichline,                        \@alphabet,\%record,$scantron_config,$scan_data);
                   5698:                 }
                   5699:                 $subquestnum ++;
                   5700:             }
                   5701:         } else {
                   5702:             if (($$scantron_config{'Qon'} eq 'letter') ||
                   5703:                 ($$scantron_config{'Qon'} eq 'number')) {
                   5704:                 $ansnum = &scantron_validator_lettnum($ansnum,$questnum,
                   5705:                     $quest_id,$answers_needed,$currentquest,$whichline,
                   5706:                     \@alphabet,\%record,$scantron_config,$scan_data);
                   5707:             } else {
                   5708:                 $ansnum = &scantron_validator_positional($ansnum,$questnum,
                   5709:                     $quest_id,$answers_needed,$currentquest,$whichline,
                   5710:                     \@alphabet,\%record,$scantron_config,$scan_data);
                   5711:             }
                   5712:         }
                   5713:     }
                   5714:     $record{'scantron.maxquest'}=$questnum;
                   5715:     return \%record;
                   5716: }
1.447     foxr     5717: 
1.503     raeburn  5718: sub scantron_validator_lettnum {
                   5719:     my ($ansnum,$questnum,$quest_id,$answers_needed,$currquest,$whichline,
                   5720:         $alphabet,$record,$scantron_config,$scan_data) = @_;
                   5721: 
                   5722:     # Qon 'letter' implies for each slot in currquest we have:
                   5723:     #    ? or * for doubles, a letter in A-Z for a bubble, and
                   5724:     #    about anything else (esp. a value of Qoff) for missing
                   5725:     #    bubbles.
                   5726:     #
                   5727:     # Qon 'number' implies each slot gives a digit that indexes the
                   5728:     #    bubbles filled, or Qoff, or a non-number for unbubbled lines,
                   5729:     #    and * or ? for double bubbles on a single line.
                   5730:     #
1.447     foxr     5731: 
1.503     raeburn  5732:     my $matchon;
                   5733:     if ($$scantron_config{'Qon'} eq 'letter') {
                   5734:         $matchon = '[A-Z]';
                   5735:     } elsif ($$scantron_config{'Qon'} eq 'number') {
                   5736:         $matchon = '\d';
                   5737:     }
                   5738:     my $occurrences = 0;
                   5739:     if (($responsetype_per_response{$questnum-1} eq 'essayresponse') ||
                   5740:         ($responsetype_per_response{$questnum-1} eq 'formularesponse') ||
1.510     raeburn  5741:         ($responsetype_per_response{$questnum-1} eq 'stringresponse') ||
                   5742:         ($responsetype_per_response{$questnum-1} eq 'imageresponse') ||
                   5743:         ($responsetype_per_response{$questnum-1} eq 'reactionresponse') ||
                   5744:         ($responsetype_per_response{$questnum-1} eq 'organicresponse')) {
1.503     raeburn  5745:         my @singlelines = split('',$currquest);
                   5746:         foreach my $entry (@singlelines) {
                   5747:             $occurrences = &occurence_count($entry,$matchon);
                   5748:             if ($occurrences > 1) {
                   5749:                 last;
                   5750:             }
                   5751:         } 
                   5752:     } else {
                   5753:         $occurrences = &occurence_count($currquest,$matchon); 
                   5754:     }
                   5755:     if (($currquest =~ /\?/ || $currquest =~ /\*/) || ($occurrences > 1)) {
                   5756:         push(@{$record->{'scantron.doubleerror'}},$quest_id);
                   5757:         for (my $ans=0; $ans<$answers_needed; $ans++) {
                   5758:             my $bubble = substr($currquest,$ans,1);
                   5759:             if ($bubble =~ /$matchon/ ) {
                   5760:                 if ($$scantron_config{'Qon'} eq 'number') {
                   5761:                     if ($bubble == 0) {
                   5762:                         $bubble = 10; 
                   5763:                     }
                   5764:                     $record->{"scantron.$ansnum.answer"} = 
                   5765:                         $alphabet->[$bubble-1];
                   5766:                 } else {
                   5767:                     $record->{"scantron.$ansnum.answer"} = $bubble;
                   5768:                 }
                   5769:             } else {
                   5770:                 $record->{"scantron.$ansnum.answer"}='';
                   5771:             }
                   5772:             $ansnum++;
                   5773:         }
                   5774:     } elsif (!defined($currquest)
                   5775:             || (&occurence_count($currquest, $$scantron_config{'Qoff'}) == length($currquest))
                   5776:             || (&occurence_count($currquest,$matchon) == 0)) {
                   5777:         for (my $ans=0; $ans<$answers_needed; $ans++ ) {
                   5778:             $record->{"scantron.$ansnum.answer"}='';
                   5779:             $ansnum++;
                   5780:         }
                   5781:         if (!&scan_data($scan_data,"$whichline.no_bubble.$quest_id")) {
                   5782:             push(@{$record->{'scantron.missingerror'}},$quest_id);
                   5783:         }
                   5784:     } else {
                   5785:         if ($$scantron_config{'Qon'} eq 'number') {
                   5786:             $currquest = &digits_to_letters($currquest);            
                   5787:         }
                   5788:         for (my $ans=0; $ans<$answers_needed; $ans++) {
                   5789:             my $bubble = substr($currquest,$ans,1);
                   5790:             $record->{"scantron.$ansnum.answer"} = $bubble;
                   5791:             $ansnum++;
                   5792:         }
                   5793:     }
                   5794:     return $ansnum;
                   5795: }
1.447     foxr     5796: 
1.503     raeburn  5797: sub scantron_validator_positional {
                   5798:     my ($ansnum,$questnum,$quest_id,$answers_needed,$currquest,
                   5799:         $whichline,$alphabet,$record,$scantron_config,$scan_data) = @_;
1.447     foxr     5800: 
1.503     raeburn  5801:     # Otherwise there's a positional notation;
                   5802:     # each bubble line requires Qlength items, and there are filled in
                   5803:     # bubbles for each case where there 'Qon' characters.
                   5804:     #
1.447     foxr     5805: 
1.503     raeburn  5806:     my @array=split($$scantron_config{'Qon'},$currquest,-1);
1.447     foxr     5807: 
1.503     raeburn  5808:     # If the split only gives us one element.. the full length of the
                   5809:     # answer string, no bubbles are filled in:
1.447     foxr     5810: 
1.507     raeburn  5811:     if ($answers_needed eq '') {
                   5812:         return;
                   5813:     }
                   5814: 
1.503     raeburn  5815:     if (length($array[0]) eq $$scantron_config{'Qlength'}*$answers_needed) {
                   5816:         for (my $ans=0; $ans<$answers_needed; $ans++ ) {
                   5817:             $record->{"scantron.$ansnum.answer"}='';
                   5818:             $ansnum++;
                   5819:         }
                   5820:         if (!&scan_data($scan_data,"$whichline.no_bubble.$quest_id")) {
                   5821:             push(@{$record->{"scantron.missingerror"}},$quest_id);
                   5822:         }
                   5823:     } elsif (scalar(@array) == 2) {
                   5824:         my $location = length($array[0]);
                   5825:         my $line_num = int($location / $$scantron_config{'Qlength'});
                   5826:         my $bubble   = $alphabet->[$location % $$scantron_config{'Qlength'}];
                   5827:         for (my $ans=0; $ans<$answers_needed; $ans++) {
                   5828:             if ($ans eq $line_num) {
                   5829:                 $record->{"scantron.$ansnum.answer"} = $bubble;
                   5830:             } else {
                   5831:                 $record->{"scantron.$ansnum.answer"} = ' ';
                   5832:             }
                   5833:             $ansnum++;
                   5834:          }
                   5835:     } else {
                   5836:         #  If there's more than one instance of a bubble character
                   5837:         #  That's a double bubble; with positional notation we can
                   5838:         #  record all the bubbles filled in as well as the
                   5839:         #  fact this response consists of multiple bubbles.
                   5840:         #
                   5841:         if (($responsetype_per_response{$questnum-1} eq 'essayresponse') ||
                   5842:             ($responsetype_per_response{$questnum-1} eq 'formularesponse') ||
1.510     raeburn  5843:             ($responsetype_per_response{$questnum-1} eq 'stringresponse') ||
                   5844:             ($responsetype_per_response{$questnum-1} eq 'imageresponse') ||
                   5845:             ($responsetype_per_response{$questnum-1} eq 'reactionresponse') ||
                   5846:             ($responsetype_per_response{$questnum-1} eq 'organicresponse')) {
1.503     raeburn  5847:             my $doubleerror = 0;
                   5848:             while (($currquest >= $$scantron_config{'Qlength'}) && 
                   5849:                    (!$doubleerror)) {
                   5850:                my $currline = substr($currquest,0,$$scantron_config{'Qlength'});
                   5851:                $currquest = substr($currquest,$$scantron_config{'Qlength'});
                   5852:                my @currarray = split($$scantron_config{'Qon'},$currline,-1);
                   5853:                if (length(@currarray) > 2) {
                   5854:                    $doubleerror = 1;
                   5855:                } 
                   5856:             }
                   5857:             if ($doubleerror) {
                   5858:                 push(@{$record->{'scantron.doubleerror'}},$quest_id);
                   5859:             }
                   5860:         } else {
                   5861:             push(@{$record->{'scantron.doubleerror'}},$quest_id);
                   5862:         }
                   5863:         my $item = $ansnum;
                   5864:         for (my $ans=0; $ans<$answers_needed; $ans++) {
                   5865:             $record->{"scantron.$item.answer"} = '';
                   5866:             $item ++;
                   5867:         }
1.447     foxr     5868: 
1.503     raeburn  5869:         my @ans=@array;
                   5870:         my $i=0;
                   5871:         my $increment = 0;
                   5872:         while ($#ans) {
                   5873:             $i+=length($ans[0]) + $increment;
                   5874:             my $line   = int($i/$$scantron_config{'Qlength'} + $ansnum);
                   5875:             my $bubble = $i%$$scantron_config{'Qlength'};
                   5876:             $record->{"scantron.$line.answer"}.=$alphabet->[$bubble];
                   5877:             shift(@ans);
                   5878:             $increment = 1;
                   5879:         }
                   5880:         $ansnum += $answers_needed;
1.82      albertel 5881:     }
1.503     raeburn  5882:     return $ansnum;
1.82      albertel 5883: }
                   5884: 
1.423     albertel 5885: =pod
                   5886: 
                   5887: =item scantron_add_delay
                   5888: 
                   5889:    Adds an error message that occurred during the grading phase to a
                   5890:    queue of messages to be shown after grading pass is complete
                   5891: 
                   5892:  Arguments:
1.424     albertel 5893:    $delayqueue  - arrary ref of hash ref of error messages
1.423     albertel 5894:    $scanline    - the scanline that caused the error
                   5895:    $errormesage - the error message
                   5896:    $errorcode   - a numeric code for the error
                   5897: 
                   5898:  Side Effects:
1.424     albertel 5899:    updates the $delayqueue to have a new hash ref of the error
1.423     albertel 5900: 
                   5901: =cut
                   5902: 
1.82      albertel 5903: sub scantron_add_delay {
1.140     albertel 5904:     my ($delayqueue,$scanline,$errormessage,$errorcode)=@_;
                   5905:     push(@$delayqueue,
                   5906: 	 {'line' => $scanline, 'emsg' => $errormessage,
                   5907: 	  'ecode' => $errorcode }
                   5908: 	 );
1.82      albertel 5909: }
                   5910: 
1.423     albertel 5911: =pod
                   5912: 
                   5913: =item scantron_find_student
                   5914: 
1.424     albertel 5915:    Finds the username for the current scanline
                   5916: 
                   5917:   Arguments:
                   5918:    $scantron_record - hash result from scantron_parse_scanline
                   5919:    $scan_data       - hash of correction information 
                   5920:                       (see &scantron_getfile() form more information)
                   5921:    $idmap           - hash from &username_to_idmap()
                   5922:    $line            - number of current scanline
                   5923:  
                   5924:   Returns:
                   5925:    Either 'username:domain' or undef if unknown
                   5926: 
1.423     albertel 5927: =cut
                   5928: 
1.82      albertel 5929: sub scantron_find_student {
1.157     albertel 5930:     my ($scantron_record,$scan_data,$idmap,$line)=@_;
1.83      albertel 5931:     my $scanID=$$scantron_record{'scantron.ID'};
1.157     albertel 5932:     if ($scanID =~ /^\s*$/) {
                   5933:  	return &scan_data($scan_data,"$line.user");
                   5934:     }
1.83      albertel 5935:     foreach my $id (keys(%$idmap)) {
1.157     albertel 5936:  	if (lc($id) eq lc($scanID)) {
                   5937:  	    return $$idmap{$id};
                   5938:  	}
1.83      albertel 5939:     }
                   5940:     return undef;
                   5941: }
                   5942: 
1.423     albertel 5943: =pod
                   5944: 
                   5945: =item scantron_filter
                   5946: 
1.424     albertel 5947:    Filter sub for lonnavmaps, filters out hidden resources if ignore
                   5948:    hidden resources was selected
                   5949: 
1.423     albertel 5950: =cut
                   5951: 
1.83      albertel 5952: sub scantron_filter {
                   5953:     my ($curres)=@_;
1.331     albertel 5954: 
                   5955:     if (ref($curres) && $curres->is_problem()) {
                   5956: 	# if the user has asked to not have either hidden
                   5957: 	# or 'randomout' controlled resources to be graded
                   5958: 	# don't include them
                   5959: 	if ($env{'form.scantron_options_hidden'} eq 'ignore_hidden'
                   5960: 	    && $curres->randomout) {
                   5961: 	    return 0;
                   5962: 	}
1.83      albertel 5963: 	return 1;
                   5964:     }
                   5965:     return 0;
1.82      albertel 5966: }
                   5967: 
1.423     albertel 5968: =pod
                   5969: 
                   5970: =item scantron_process_corrections
                   5971: 
1.424     albertel 5972:    Gets correction information out of submitted form data and corrects
                   5973:    the scanline
                   5974: 
1.423     albertel 5975: =cut
                   5976: 
1.157     albertel 5977: sub scantron_process_corrections {
                   5978:     my ($r) = @_;
1.257     albertel 5979:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.157     albertel 5980:     my ($scanlines,$scan_data)=&scantron_getfile();
                   5981:     my $classlist=&Apache::loncoursedata::get_classlist();
1.257     albertel 5982:     my $which=$env{'form.scantron_line'};
1.200     albertel 5983:     my $line=&scantron_get_line($scanlines,$scan_data,$which);
1.157     albertel 5984:     my ($skip,$err,$errmsg);
1.257     albertel 5985:     if ($env{'form.scantron_skip_record'}) {
1.157     albertel 5986: 	$skip=1;
1.257     albertel 5987:     } elsif ($env{'form.scantron_corrections'} =~ /^(duplicate|incorrect)ID$/) {
                   5988: 	my $newstudent=$env{'form.scantron_username'}.':'.
                   5989: 	    $env{'form.scantron_domain'};
1.157     albertel 5990: 	my $newid=$classlist->{$newstudent}->[&Apache::loncoursedata::CL_ID];
                   5991: 	($line,$err,$errmsg)=
                   5992: 	    &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,$which,
                   5993: 				     'ID',{'newid'=>$newid,
1.257     albertel 5994: 				    'username'=>$env{'form.scantron_username'},
                   5995: 				    'domain'=>$env{'form.scantron_domain'}});
                   5996:     } elsif ($env{'form.scantron_corrections'} =~ /^(duplicate|incorrect)CODE$/) {
                   5997: 	my $resolution=$env{'form.scantron_CODE_resolution'};
1.190     albertel 5998: 	my $newCODE;
1.192     albertel 5999: 	my %args;
1.190     albertel 6000: 	if      ($resolution eq 'use_unfound') {
1.191     albertel 6001: 	    $newCODE='use_unfound';
1.190     albertel 6002: 	} elsif ($resolution eq 'use_found') {
1.257     albertel 6003: 	    $newCODE=$env{'form.scantron_CODE_selectedvalue'};
1.190     albertel 6004: 	} elsif ($resolution eq 'use_typed') {
1.257     albertel 6005: 	    $newCODE=$env{'form.scantron_CODE_newvalue'};
1.194     albertel 6006: 	} elsif ($resolution =~ /^use_closest_(\d+)/) {
1.257     albertel 6007: 	    $newCODE=$env{"form.scantron_CODE_closest_$1"};
1.190     albertel 6008: 	}
1.257     albertel 6009: 	if ($env{'form.scantron_corrections'} eq 'duplicateCODE') {
1.192     albertel 6010: 	    $args{'CODE_ignore_dup'}=1;
                   6011: 	}
                   6012: 	$args{'CODE'}=$newCODE;
1.186     albertel 6013: 	($line,$err,$errmsg)=
                   6014: 	    &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,$which,
1.192     albertel 6015: 				     'CODE',\%args);
1.257     albertel 6016:     } elsif ($env{'form.scantron_corrections'} =~ /^(missing|double)bubble$/) {
                   6017: 	foreach my $question (split(',',$env{'form.scantron_questions'})) {
1.157     albertel 6018: 	    ($line,$err,$errmsg)=
                   6019: 		&scantron_fixup_scanline(\%scantron_config,$scan_data,$line,
                   6020: 					 $which,'answer',
                   6021: 					 { 'question'=>$question,
1.503     raeburn  6022: 		      		   'response'=>$env{"form.scantron_correct_Q_$question"},
                   6023:                                    'questionnum'=>$env{"form.scantron_questionnum_Q_$question"}});
1.157     albertel 6024: 	    if ($err) { last; }
                   6025: 	}
                   6026:     }
                   6027:     if ($err) {
1.398     albertel 6028: 	$r->print("<span class=\"LC_warning\">Unable to accept last correction, an error occurred :$errmsg:</span>");
1.157     albertel 6029:     } else {
1.200     albertel 6030: 	&scantron_put_line($scanlines,$scan_data,$which,$line,$skip);
1.157     albertel 6031: 	&scantron_putfile($scanlines,$scan_data);
                   6032:     }
                   6033: }
                   6034: 
1.423     albertel 6035: =pod
                   6036: 
                   6037: =item reset_skipping_status
                   6038: 
1.424     albertel 6039:    Forgets the current set of remember skipped scanlines (and thus
                   6040:    reverts back to considering all lines in the
                   6041:    scantron_skipped_<filename> file)
                   6042: 
1.423     albertel 6043: =cut
                   6044: 
1.200     albertel 6045: sub reset_skipping_status {
                   6046:     my ($scanlines,$scan_data)=&scantron_getfile();
                   6047:     &scan_data($scan_data,'remember_skipping',undef,1);
                   6048:     &scantron_putfile(undef,$scan_data);
                   6049: }
                   6050: 
1.423     albertel 6051: =pod
                   6052: 
                   6053: =item start_skipping
                   6054: 
1.424     albertel 6055:    Marks a scanline to be skipped. 
                   6056: 
1.423     albertel 6057: =cut
                   6058: 
1.376     albertel 6059: sub start_skipping {
1.200     albertel 6060:     my ($scan_data,$i)=@_;
                   6061:     my %remembered=split(':',&scan_data($scan_data,'remember_skipping'));
1.376     albertel 6062:     if ($env{'form.scantron_options_redo'} =~ /^redo_/) {
                   6063: 	$remembered{$i}=2;
                   6064:     } else {
                   6065: 	$remembered{$i}=1;
                   6066:     }
1.200     albertel 6067:     &scan_data($scan_data,'remember_skipping',join(':',%remembered));
                   6068: }
                   6069: 
1.423     albertel 6070: =pod
                   6071: 
                   6072: =item should_be_skipped
                   6073: 
1.424     albertel 6074:    Checks whether a scanline should be skipped.
                   6075: 
1.423     albertel 6076: =cut
                   6077: 
1.200     albertel 6078: sub should_be_skipped {
1.376     albertel 6079:     my ($scanlines,$scan_data,$i)=@_;
1.257     albertel 6080:     if ($env{'form.scantron_options_redo'} !~ /^redo_/) {
1.200     albertel 6081: 	# not redoing old skips
1.376     albertel 6082: 	if ($scanlines->{'skipped'}[$i]) { return 1; }
1.200     albertel 6083: 	return 0;
                   6084:     }
                   6085:     my %remembered=split(':',&scan_data($scan_data,'remember_skipping'));
1.376     albertel 6086: 
                   6087:     if (exists($remembered{$i}) && $remembered{$i} != 2 ) {
                   6088: 	return 0;
                   6089:     }
1.200     albertel 6090:     return 1;
                   6091: }
                   6092: 
1.423     albertel 6093: =pod
                   6094: 
                   6095: =item remember_current_skipped
                   6096: 
1.424     albertel 6097:    Discovers what scanlines are in the scantron_skipped_<filename>
                   6098:    file and remembers them into scan_data for later use.
                   6099: 
1.423     albertel 6100: =cut
                   6101: 
1.200     albertel 6102: sub remember_current_skipped {
                   6103:     my ($scanlines,$scan_data)=&scantron_getfile();
                   6104:     my %to_remember;
                   6105:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
                   6106: 	if ($scanlines->{'skipped'}[$i]) {
                   6107: 	    $to_remember{$i}=1;
                   6108: 	}
                   6109:     }
1.376     albertel 6110: 
1.200     albertel 6111:     &scan_data($scan_data,'remember_skipping',join(':',%to_remember));
                   6112:     &scantron_putfile(undef,$scan_data);
                   6113: }
                   6114: 
1.423     albertel 6115: =pod
                   6116: 
                   6117: =item check_for_error
                   6118: 
1.424     albertel 6119:     Checks if there was an error when attempting to remove a specific
                   6120:     scantron_.. bubble sheet data file. Prints out an error if
                   6121:     something went wrong.
                   6122: 
1.423     albertel 6123: =cut
                   6124: 
1.200     albertel 6125: sub check_for_error {
                   6126:     my ($r,$result)=@_;
                   6127:     if ($result ne 'ok' && $result ne 'not_found' ) {
1.492     albertel 6128: 	$r->print(&mt("An error occurred ([_1]) when trying to remove the existing corrections.",$result));
1.200     albertel 6129:     }
                   6130: }
1.157     albertel 6131: 
1.423     albertel 6132: =pod
                   6133: 
                   6134: =item scantron_warning_screen
                   6135: 
1.424     albertel 6136:    Interstitial screen to make sure the operator has selected the
                   6137:    correct options before we start the validation phase.
                   6138: 
1.423     albertel 6139: =cut
                   6140: 
1.203     albertel 6141: sub scantron_warning_screen {
                   6142:     my ($button_text)=@_;
1.257     albertel 6143:     my $title=&Apache::lonnet::gettitle($env{'form.selectpage'});
1.284     albertel 6144:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.373     albertel 6145:     my $CODElist;
1.284     albertel 6146:     if ($scantron_config{'CODElocation'} &&
                   6147: 	$scantron_config{'CODEstart'} &&
                   6148: 	$scantron_config{'CODElength'}) {
                   6149: 	$CODElist=$env{'form.scantron_CODElist'};
1.398     albertel 6150: 	if ($env{'form.scantron_CODElist'} eq '') { $CODElist='<span class="LC_warning">None</span>'; }
1.284     albertel 6151: 	$CODElist=
1.492     albertel 6152: 	    '<tr><td><b>'.&mt('List of CODES to validate against:').'</b></td><td><tt>'.
1.373     albertel 6153: 	    $env{'form.scantron_CODElist'}.'</tt></td></tr>';
1.284     albertel 6154:     }
1.492     albertel 6155:     return ('
1.203     albertel 6156: <p>
1.492     albertel 6157: <span class="LC_warning">
                   6158: '.&mt('Please double check the information below before clicking on \'[_1]\'',&mt($button_text)).'</span>
1.203     albertel 6159: </p>
                   6160: <table>
1.492     albertel 6161: <tr><td><b>'.&mt('Sequence to be Graded:').'</b></td><td>'.$title.'</td></tr>
                   6162: <tr><td><b>'.&mt('Data File that will be used:').'</b></td><td><tt>'.$env{'form.scantron_selectfile'}.'</tt></td></tr>
                   6163: '.$CODElist.'
1.203     albertel 6164: </table>
                   6165: <br />
1.492     albertel 6166: <p> '.&mt('If this information is correct, please click on \'[_1]\'.',&mt($button_text)).'</p>
                   6167: <p> '.&mt('If something is incorrect, please click the \'Grading Menu\' button to start over.').'</p>
1.203     albertel 6168: 
                   6169: <br />
1.492     albertel 6170: ');
1.203     albertel 6171: }
                   6172: 
1.423     albertel 6173: =pod
                   6174: 
                   6175: =item scantron_do_warning
                   6176: 
1.424     albertel 6177:    Check if the operator has picked something for all required
                   6178:    fields. Error out if something is missing.
                   6179: 
1.423     albertel 6180: =cut
                   6181: 
1.203     albertel 6182: sub scantron_do_warning {
1.608     www      6183:     my ($r,$symb)=@_;
1.203     albertel 6184:     if (!$symb) {return '';}
1.324     albertel 6185:     my $default_form_data=&defaultFormData($symb);
1.203     albertel 6186:     $r->print(&scantron_form_start().$default_form_data);
1.257     albertel 6187:     if ( $env{'form.selectpage'} eq '' ||
                   6188: 	 $env{'form.scantron_selectfile'} eq '' ||
                   6189: 	 $env{'form.scantron_format'} eq '' ) {
1.492     albertel 6190: 	$r->print("<p>".&mt('You have forgetten to specify some information. Please go Back and try again.')."</p>");
1.257     albertel 6191: 	if ( $env{'form.selectpage'} eq '') {
1.492     albertel 6192: 	    $r->print('<p><span class="LC_error">'.&mt('You have not selected a Sequence to grade').'</span></p>');
1.237     albertel 6193: 	} 
1.257     albertel 6194: 	if ( $env{'form.scantron_selectfile'} eq '') {
1.492     albertel 6195: 	    $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 6196: 	} 
1.257     albertel 6197: 	if ( $env{'form.scantron_format'} eq '') {
1.492     albertel 6198: 	    $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 6199: 	} 
                   6200:     } else {
1.265     www      6201: 	my $warning=&scantron_warning_screen('Grading: Validate Records');
1.492     albertel 6202: 	$r->print('
                   6203: '.$warning.'
                   6204: <input type="submit" name="submit" value="'.&mt('Grading: Validate Records').'" />
1.203     albertel 6205: <input type="hidden" name="command" value="scantron_validate" />
1.492     albertel 6206: ');
1.237     albertel 6207:     }
1.614     www      6208:     $r->print("</form><br />");
1.203     albertel 6209:     return '';
                   6210: }
                   6211: 
1.423     albertel 6212: =pod
                   6213: 
                   6214: =item scantron_form_start
                   6215: 
1.424     albertel 6216:     html hidden input for remembering all selected grading options
                   6217: 
1.423     albertel 6218: =cut
                   6219: 
1.203     albertel 6220: sub scantron_form_start {
                   6221:     my ($max_bubble)=@_;
                   6222:     my $result= <<SCANTRONFORM;
                   6223: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantronupload">
1.257     albertel 6224:   <input type="hidden" name="selectpage" value="$env{'form.selectpage'}" />
                   6225:   <input type="hidden" name="scantron_format" value="$env{'form.scantron_format'}" />
                   6226:   <input type="hidden" name="scantron_selectfile" value="$env{'form.scantron_selectfile'}" />
1.218     albertel 6227:   <input type="hidden" name="scantron_maxbubble" value="$max_bubble" />
1.257     albertel 6228:   <input type="hidden" name="scantron_CODElist" value="$env{'form.scantron_CODElist'}" />
                   6229:   <input type="hidden" name="scantron_CODEunique" value="$env{'form.scantron_CODEunique'}" />
                   6230:   <input type="hidden" name="scantron_options_redo" value="$env{'form.scantron_options_redo'}" />
                   6231:   <input type="hidden" name="scantron_options_ignore" value="$env{'form.scantron_options_ignore'}" />
1.331     albertel 6232:   <input type="hidden" name="scantron_options_hidden" value="$env{'form.scantron_options_hidden'}" />
1.203     albertel 6233: SCANTRONFORM
1.447     foxr     6234: 
                   6235:   my $line = 0;
                   6236:     while (defined($env{"form.scantron.bubblelines.$line"})) {
                   6237:        my $chunk =
                   6238: 	   '<input type="hidden" name="scantron.bubblelines.'.$line.'" value="'.$env{"form.scantron.bubblelines.$line"}.'" />'."\n";
1.448     foxr     6239:        $chunk .=
                   6240: 	   '<input type="hidden" name="scantron.first_bubble_line.'.$line.'" value="'.$env{"form.scantron.first_bubble_line.$line"}.'" />'."\n";
1.503     raeburn  6241:        $chunk .= 
                   6242:            '<input type="hidden" name="scantron.sub_bubblelines.'.$line.'" value="'.$env{"form.scantron.sub_bubblelines.$line"}.'" />'."\n";
1.504     raeburn  6243:        $chunk .=
                   6244:            '<input type="hidden" name="scantron.responsetype.'.$line.'" value="'.$env{"form.scantron.responsetype.$line"}.'" />'."\n";
1.447     foxr     6245:        $result .= $chunk;
                   6246:        $line++;
                   6247:    }
1.203     albertel 6248:     return $result;
                   6249: }
                   6250: 
1.423     albertel 6251: =pod
                   6252: 
                   6253: =item scantron_validate_file
                   6254: 
1.424     albertel 6255:     Dispatch routine for doing validation of a bubble sheet data file.
                   6256: 
                   6257:     Also processes any necessary information resets that need to
                   6258:     occur before validation begins (ignore previous corrections,
                   6259:     restarting the skipped records processing)
                   6260: 
1.423     albertel 6261: =cut
                   6262: 
1.157     albertel 6263: sub scantron_validate_file {
1.608     www      6264:     my ($r,$symb) = @_;
1.157     albertel 6265:     if (!$symb) {return '';}
1.324     albertel 6266:     my $default_form_data=&defaultFormData($symb);
1.200     albertel 6267:     
                   6268:     # do the detection of only doing skipped records first befroe we delete
1.424     albertel 6269:     # them when doing the corrections reset
1.257     albertel 6270:     if ($env{'form.scantron_options_redo'} ne 'redo_skipped_ready') {
1.200     albertel 6271: 	&reset_skipping_status();
                   6272:     }
1.257     albertel 6273:     if ($env{'form.scantron_options_redo'} eq 'redo_skipped') {
1.200     albertel 6274: 	&remember_current_skipped();
1.257     albertel 6275: 	$env{'form.scantron_options_redo'}='redo_skipped_ready';
1.200     albertel 6276:     }
                   6277: 
1.257     albertel 6278:     if ($env{'form.scantron_options_ignore'} eq 'ignore_corrections') {
1.200     albertel 6279: 	&check_for_error($r,&scantron_remove_file('corrected'));
                   6280: 	&check_for_error($r,&scantron_remove_file('skipped'));
                   6281: 	&check_for_error($r,&scantron_remove_scan_data());
1.257     albertel 6282: 	$env{'form.scantron_options_ignore'}='done';
1.192     albertel 6283:     }
1.200     albertel 6284: 
1.257     albertel 6285:     if ($env{'form.scantron_corrections'}) {
1.157     albertel 6286: 	&scantron_process_corrections($r);
                   6287:     }
1.503     raeburn  6288:     $r->print('<p>'.&mt('Gathering necessary information.').'</p>');$r->rflush();
1.157     albertel 6289:     #get the student pick code ready
                   6290:     $r->print(&Apache::loncommon::studentbrowser_javascript());
1.582     raeburn  6291:     my $nav_error;
                   6292:     my $max_bubble=&scantron_get_maxbubble(\$nav_error);
                   6293:     if ($nav_error) {
                   6294:         $r->print(&navmap_errormsg());
                   6295:         return '';
                   6296:     }
1.203     albertel 6297:     my $result=&scantron_form_start($max_bubble).$default_form_data;
1.157     albertel 6298:     $r->print($result);
                   6299:     
1.334     albertel 6300:     my @validate_phases=( 'sequence',
                   6301: 			  'ID',
1.157     albertel 6302: 			  'CODE',
                   6303: 			  'doublebubble',
                   6304: 			  'missingbubbles');
1.257     albertel 6305:     if (!$env{'form.validatepass'}) {
                   6306: 	$env{'form.validatepass'} = 0;
1.157     albertel 6307:     }
1.257     albertel 6308:     my $currentphase=$env{'form.validatepass'};
1.157     albertel 6309: 
1.448     foxr     6310: 
1.157     albertel 6311:     my $stop=0;
                   6312:     while (!$stop && $currentphase < scalar(@validate_phases)) {
1.503     raeburn  6313: 	$r->print(&mt('Validating '.$validate_phases[$currentphase]).'<br />');
1.157     albertel 6314: 	$r->rflush();
                   6315: 	my $which="scantron_validate_".$validate_phases[$currentphase];
                   6316: 	{
                   6317: 	    no strict 'refs';
                   6318: 	    ($stop,$currentphase)=&$which($r,$currentphase);
                   6319: 	}
                   6320:     }
                   6321:     if (!$stop) {
1.203     albertel 6322: 	my $warning=&scantron_warning_screen('Start Grading');
1.542     raeburn  6323: 	$r->print(&mt('Validation process complete.').'<br />'.
                   6324:                   $warning.
                   6325:                   &mt('Perform verification for each student after storage of submissions?').
                   6326:                   '&nbsp;<span class="LC_nobreak"><label>'.
                   6327:                   '<input type="radio" name="verifyrecord" value="1" />'.&mt('Yes').'</label>'.
                   6328:                   ('&nbsp;'x3).'<label>'.
                   6329:                   '<input type="radio" name="verifyrecord" value="0" checked="checked" />'.&mt('No').
                   6330:                   '</label></span><br />'.
                   6331:                   &mt('Grading will take longer if you use verification.').'<br />'.
1.572     www      6332:                   &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  6333:                   '<input type="submit" name="submit" value="'.&mt('Start Grading').'" />'.
                   6334:                   '<input type="hidden" name="command" value="scantron_process" />'."\n");
1.157     albertel 6335:     } else {
                   6336: 	$r->print('<input type="hidden" name="command" value="scantron_validate" />');
                   6337: 	$r->print("<input type='hidden' name='validatepass' value='".$currentphase."' />");
                   6338:     }
                   6339:     if ($stop) {
1.334     albertel 6340: 	if ($validate_phases[$currentphase] eq 'sequence') {
1.539     riegler  6341: 	    $r->print('<input type="submit" name="submit" value="'.&mt('Ignore').' &rarr; " />');
1.492     albertel 6342: 	    $r->print(' '.&mt('this error').' <br />');
1.334     albertel 6343: 
1.492     albertel 6344: 	    $r->print(" <p>".&mt("Or click the 'Grading Menu' button to start over.")."</p>");
1.334     albertel 6345: 	} else {
1.503     raeburn  6346:             if ($validate_phases[$currentphase] eq 'doublebubble' || $validate_phases[$currentphase] eq 'missingbubbles') {
1.539     riegler  6347: 	        $r->print('<input type="button" name="submitbutton" value="'.&mt('Continue').' &rarr;" onclick="javascript:verify_bubble_radio(this.form)" />');
1.503     raeburn  6348:             } else {
1.539     riegler  6349:                 $r->print('<input type="submit" name="submit" value="'.&mt('Continue').' &rarr;" />');
1.503     raeburn  6350:             }
1.492     albertel 6351: 	    $r->print(' '.&mt('using corrected info').' <br />');
                   6352: 	    $r->print("<input type='submit' value='".&mt("Skip")."' name='scantron_skip_record' />");
                   6353: 	    $r->print(" ".&mt("this scanline saving it for later."));
1.334     albertel 6354: 	}
1.157     albertel 6355:     }
1.614     www      6356:     $r->print(" </form><br />");
1.157     albertel 6357:     return '';
                   6358: }
                   6359: 
1.423     albertel 6360: 
                   6361: =pod
                   6362: 
                   6363: =item scantron_remove_file
                   6364: 
1.424     albertel 6365:    Removes the requested bubble sheet data file, makes sure that
                   6366:    scantron_original_<filename> is never removed
                   6367: 
                   6368: 
1.423     albertel 6369: =cut
                   6370: 
1.200     albertel 6371: sub scantron_remove_file {
1.192     albertel 6372:     my ($which)=@_;
1.257     albertel 6373:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   6374:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.192     albertel 6375:     my $file='scantron_';
1.200     albertel 6376:     if ($which eq 'corrected' || $which eq 'skipped') {
                   6377: 	$file.=$which.'_';
1.192     albertel 6378:     } else {
                   6379: 	return 'refused';
                   6380:     }
1.257     albertel 6381:     $file.=$env{'form.scantron_selectfile'};
1.200     albertel 6382:     return &Apache::lonnet::removeuserfile($cname,$cdom,$file);
                   6383: }
                   6384: 
1.423     albertel 6385: 
                   6386: =pod
                   6387: 
                   6388: =item scantron_remove_scan_data
                   6389: 
1.424     albertel 6390:    Removes all scan_data correction for the requested bubble sheet
                   6391:    data file.  (In the case that both the are doing skipped records we need
                   6392:    to remember the old skipped lines for the time being so that element
                   6393:    persists for a while.)
                   6394: 
1.423     albertel 6395: =cut
                   6396: 
1.200     albertel 6397: sub scantron_remove_scan_data {
1.257     albertel 6398:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   6399:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.192     albertel 6400:     my @keys=&Apache::lonnet::getkeys('nohist_scantrondata',$cdom,$cname);
                   6401:     my @todelete;
1.257     albertel 6402:     my $filename=$env{'form.scantron_selectfile'};
1.192     albertel 6403:     foreach my $key (@keys) {
                   6404: 	if ($key=~/^\Q$filename\E_/) {
1.257     albertel 6405: 	    if ($env{'form.scantron_options_redo'} eq 'redo_skipped_ready' &&
1.200     albertel 6406: 		$key=~/remember_skipping/) {
                   6407: 		next;
                   6408: 	    }
1.192     albertel 6409: 	    push(@todelete,$key);
                   6410: 	}
                   6411:     }
1.200     albertel 6412:     my $result;
1.192     albertel 6413:     if (@todelete) {
1.491     albertel 6414: 	$result = &Apache::lonnet::del('nohist_scantrondata',
                   6415: 				       \@todelete,$cdom,$cname);
                   6416:     } else {
                   6417: 	$result = 'ok';
1.192     albertel 6418:     }
                   6419:     return $result;
                   6420: }
                   6421: 
1.423     albertel 6422: 
                   6423: =pod
                   6424: 
                   6425: =item scantron_getfile
                   6426: 
1.424     albertel 6427:     Fetches the requested bubble sheet data file (all 3 versions), and
                   6428:     the scan_data hash
                   6429:   
                   6430:   Arguments:
                   6431:     None
                   6432: 
                   6433:   Returns:
                   6434:     2 hash references
                   6435: 
                   6436:      - first one has 
                   6437:          orig      -
                   6438:          corrected -
                   6439:          skipped   -  each of which points to an array ref of the specified
                   6440:                       file broken up into individual lines
                   6441:          count     - number of scanlines
                   6442:  
                   6443:      - second is the scan_data hash possible keys are
1.425     albertel 6444:        ($number refers to scanline numbered $number and thus the key affects
                   6445:         only that scanline
                   6446:         $bubline refers to the specific bubble line element and the aspects
                   6447:         refers to that specific bubble line element)
                   6448: 
                   6449:        $number.user - username:domain to use
                   6450:        $number.CODE_ignore_dup 
                   6451:                     - ignore the duplicate CODE error 
                   6452:        $number.useCODE
                   6453:                     - use the CODE in the scanline as is
                   6454:        $number.no_bubble.$bubline
                   6455:                     - it is valid that there is no bubbled in bubble
                   6456:                       at $number $bubline
                   6457:        remember_skipping
                   6458:                     - a frozen hash containing keys of $number and values
                   6459:                       of either 
                   6460:                         1 - we are on a 'do skipped records pass' and plan
                   6461:                             on processing this line
                   6462:                         2 - we are on a 'do skipped records pass' and this
                   6463:                             scanline has been marked to skip yet again
1.424     albertel 6464: 
1.423     albertel 6465: =cut
                   6466: 
1.157     albertel 6467: sub scantron_getfile {
1.200     albertel 6468:     #FIXME really would prefer a scantron directory
1.257     albertel 6469:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   6470:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.157     albertel 6471:     my $lines;
                   6472:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
1.257     albertel 6473: 		       'scantron_orig_'.$env{'form.scantron_selectfile'});
1.157     albertel 6474:     my %scanlines;
                   6475:     $scanlines{'orig'}=[(split("\n",$lines,-1))];
                   6476:     my $temp=$scanlines{'orig'};
                   6477:     $scanlines{'count'}=$#$temp;
                   6478: 
                   6479:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
1.257     albertel 6480: 		       'scantron_corrected_'.$env{'form.scantron_selectfile'});
1.157     albertel 6481:     if ($lines eq '-1') {
                   6482: 	$scanlines{'corrected'}=[];
                   6483:     } else {
                   6484: 	$scanlines{'corrected'}=[(split("\n",$lines,-1))];
                   6485:     }
                   6486:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
1.257     albertel 6487: 		       'scantron_skipped_'.$env{'form.scantron_selectfile'});
1.157     albertel 6488:     if ($lines eq '-1') {
                   6489: 	$scanlines{'skipped'}=[];
                   6490:     } else {
                   6491: 	$scanlines{'skipped'}=[(split("\n",$lines,-1))];
                   6492:     }
1.175     albertel 6493:     my @tmp=&Apache::lonnet::dump('nohist_scantrondata',$cdom,$cname);
1.157     albertel 6494:     if ($tmp[0] =~ /^(error:|no_such_host)/) { @tmp=(); }
                   6495:     my %scan_data = @tmp;
                   6496:     return (\%scanlines,\%scan_data);
                   6497: }
                   6498: 
1.423     albertel 6499: =pod
                   6500: 
                   6501: =item lonnet_putfile
                   6502: 
1.424     albertel 6503:    Wrapper routine to call &Apache::lonnet::finishuserfileupload
                   6504: 
                   6505:  Arguments:
                   6506:    $contents - data to store
                   6507:    $filename - filename to store $contents into
                   6508: 
                   6509:  Returns:
                   6510:    result value from &Apache::lonnet::finishuserfileupload
                   6511: 
1.423     albertel 6512: =cut
                   6513: 
1.157     albertel 6514: sub lonnet_putfile {
                   6515:     my ($contents,$filename)=@_;
1.257     albertel 6516:     my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   6517:     my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   6518:     $env{'form.sillywaytopassafilearound'}=$contents;
1.275     albertel 6519:     &Apache::lonnet::finishuserfileupload($docuname,$docudom,'sillywaytopassafilearound',$filename);
1.157     albertel 6520: 
                   6521: }
                   6522: 
1.423     albertel 6523: =pod
                   6524: 
                   6525: =item scantron_putfile
                   6526: 
1.424     albertel 6527:     Stores the current version of the bubble sheet data files, and the
                   6528:     scan_data hash. (Does not modify the original version only the
                   6529:     corrected and skipped versions.
                   6530: 
                   6531:  Arguments:
                   6532:     $scanlines - hash ref that looks like the first return value from
                   6533:                  &scantron_getfile()
                   6534:     $scan_data - hash ref that looks like the second return value from
                   6535:                  &scantron_getfile()
                   6536: 
1.423     albertel 6537: =cut
                   6538: 
1.157     albertel 6539: sub scantron_putfile {
                   6540:     my ($scanlines,$scan_data) = @_;
1.200     albertel 6541:     #FIXME really would prefer a scantron directory
1.257     albertel 6542:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   6543:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.200     albertel 6544:     if ($scanlines) {
                   6545: 	my $prefix='scantron_';
1.157     albertel 6546: # no need to update orig, shouldn't change
                   6547: #   &lonnet_putfile(join("\n",@{$scanlines->{'orig'}}),$prefix.'orig_'.
1.257     albertel 6548: #		    $env{'form.scantron_selectfile'});
1.200     albertel 6549: 	&lonnet_putfile(join("\n",@{$scanlines->{'corrected'}}),
                   6550: 			$prefix.'corrected_'.
1.257     albertel 6551: 			$env{'form.scantron_selectfile'});
1.200     albertel 6552: 	&lonnet_putfile(join("\n",@{$scanlines->{'skipped'}}),
                   6553: 			$prefix.'skipped_'.
1.257     albertel 6554: 			$env{'form.scantron_selectfile'});
1.200     albertel 6555:     }
1.175     albertel 6556:     &Apache::lonnet::put('nohist_scantrondata',$scan_data,$cdom,$cname);
1.157     albertel 6557: }
                   6558: 
1.423     albertel 6559: =pod
                   6560: 
                   6561: =item scantron_get_line
                   6562: 
1.424     albertel 6563:    Returns the correct version of the scanline
                   6564: 
                   6565:  Arguments:
                   6566:     $scanlines - hash ref that looks like the first return value from
                   6567:                  &scantron_getfile()
                   6568:     $scan_data - hash ref that looks like the second return value from
                   6569:                  &scantron_getfile()
                   6570:     $i         - number of the requested line (starts at 0)
                   6571: 
                   6572:  Returns:
                   6573:    A scanline, (either the original or the corrected one if it
                   6574:    exists), or undef if the requested scanline should be
                   6575:    skipped. (Either because it's an skipped scanline, or it's an
                   6576:    unskipped scanline and we are not doing a 'do skipped scanlines'
                   6577:    pass.
                   6578: 
1.423     albertel 6579: =cut
                   6580: 
1.157     albertel 6581: sub scantron_get_line {
1.200     albertel 6582:     my ($scanlines,$scan_data,$i)=@_;
1.376     albertel 6583:     if (&should_be_skipped($scanlines,$scan_data,$i)) { return undef; }
                   6584:     #if ($scanlines->{'skipped'}[$i]) { return undef; }
1.157     albertel 6585:     if ($scanlines->{'corrected'}[$i]) {return $scanlines->{'corrected'}[$i];}
                   6586:     return $scanlines->{'orig'}[$i]; 
                   6587: }
                   6588: 
1.423     albertel 6589: =pod
                   6590: 
                   6591: =item scantron_todo_count
                   6592: 
1.424     albertel 6593:     Counts the number of scanlines that need processing.
                   6594: 
                   6595:  Arguments:
                   6596:     $scanlines - hash ref that looks like the first return value from
                   6597:                  &scantron_getfile()
                   6598:     $scan_data - hash ref that looks like the second return value from
                   6599:                  &scantron_getfile()
                   6600: 
                   6601:  Returns:
                   6602:     $count - number of scanlines to process
                   6603: 
1.423     albertel 6604: =cut
                   6605: 
1.200     albertel 6606: sub get_todo_count {
                   6607:     my ($scanlines,$scan_data)=@_;
                   6608:     my $count=0;
                   6609:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
                   6610: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
                   6611: 	if ($line=~/^[\s\cz]*$/) { next; }
                   6612: 	$count++;
                   6613:     }
                   6614:     return $count;
                   6615: }
                   6616: 
1.423     albertel 6617: =pod
                   6618: 
                   6619: =item scantron_put_line
                   6620: 
1.424     albertel 6621:     Updates the 'corrected' or 'skipped' versions of the bubble sheet
                   6622:     data file.
                   6623: 
                   6624:  Arguments:
                   6625:     $scanlines - hash ref that looks like the first return value from
                   6626:                  &scantron_getfile()
                   6627:     $scan_data - hash ref that looks like the second return value from
                   6628:                  &scantron_getfile()
                   6629:     $i         - line number to update
                   6630:     $newline   - contents of the updated scanline
                   6631:     $skip      - if true make the line for skipping and update the
                   6632:                  'skipped' file
                   6633: 
1.423     albertel 6634: =cut
                   6635: 
1.157     albertel 6636: sub scantron_put_line {
1.200     albertel 6637:     my ($scanlines,$scan_data,$i,$newline,$skip)=@_;
1.157     albertel 6638:     if ($skip) {
                   6639: 	$scanlines->{'skipped'}[$i]=$newline;
1.376     albertel 6640: 	&start_skipping($scan_data,$i);
1.157     albertel 6641: 	return;
                   6642:     }
                   6643:     $scanlines->{'corrected'}[$i]=$newline;
                   6644: }
                   6645: 
1.423     albertel 6646: =pod
                   6647: 
                   6648: =item scantron_clear_skip
                   6649: 
1.424     albertel 6650:    Remove a line from the 'skipped' file
                   6651: 
                   6652:  Arguments:
                   6653:     $scanlines - hash ref that looks like the first return value from
                   6654:                  &scantron_getfile()
                   6655:     $scan_data - hash ref that looks like the second return value from
                   6656:                  &scantron_getfile()
                   6657:     $i         - line number to update
                   6658: 
1.423     albertel 6659: =cut
                   6660: 
1.376     albertel 6661: sub scantron_clear_skip {
                   6662:     my ($scanlines,$scan_data,$i)=@_;
                   6663:     if (exists($scanlines->{'skipped'}[$i])) {
                   6664: 	undef($scanlines->{'skipped'}[$i]);
                   6665: 	return 1;
                   6666:     }
                   6667:     return 0;
                   6668: }
                   6669: 
1.423     albertel 6670: =pod
                   6671: 
                   6672: =item scantron_filter_not_exam
                   6673: 
1.424     albertel 6674:    Filter routine used by &Apache::lonnavmaps::retrieveResources(), to
                   6675:    filter out resources that are not marked as 'exam' mode
                   6676: 
1.423     albertel 6677: =cut
                   6678: 
1.334     albertel 6679: sub scantron_filter_not_exam {
                   6680:     my ($curres)=@_;
                   6681:     
                   6682:     if (ref($curres) && $curres->is_problem() && !$curres->is_exam()) {
                   6683: 	# if the user has asked to not have either hidden
                   6684: 	# or 'randomout' controlled resources to be graded
                   6685: 	# don't include them
                   6686: 	if ($env{'form.scantron_options_hidden'} eq 'ignore_hidden'
                   6687: 	    && $curres->randomout) {
                   6688: 	    return 0;
                   6689: 	}
                   6690: 	return 1;
                   6691:     }
                   6692:     return 0;
                   6693: }
                   6694: 
1.423     albertel 6695: =pod
                   6696: 
                   6697: =item scantron_validate_sequence
                   6698: 
1.424     albertel 6699:     Validates the selected sequence, checking for resource that are
                   6700:     not set to exam mode.
                   6701: 
1.423     albertel 6702: =cut
                   6703: 
1.334     albertel 6704: sub scantron_validate_sequence {
                   6705:     my ($r,$currentphase) = @_;
                   6706: 
                   6707:     my $navmap=Apache::lonnavmaps::navmap->new();
1.582     raeburn  6708:     unless (ref($navmap)) {
                   6709:         $r->print(&navmap_errormsg());
                   6710:         return (1,$currentphase);
                   6711:     }
1.334     albertel 6712:     my (undef,undef,$sequence)=
                   6713: 	&Apache::lonnet::decode_symb($env{'form.selectpage'});
                   6714: 
                   6715:     my $map=$navmap->getResourceByUrl($sequence);
                   6716: 
                   6717:     $r->print('<input type="hidden" name="validate_sequence_exam"
                   6718:                                     value="ignore" />');
                   6719:     if ($env{'form.validate_sequence_exam'} ne 'ignore') {
                   6720: 	my @resources=
                   6721: 	    $navmap->retrieveResources($map,\&scantron_filter_not_exam,1,0);
                   6722: 	if (@resources) {
1.357     banghart 6723: 	    $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 6724: 	    return (1,$currentphase);
                   6725: 	}
                   6726:     }
                   6727: 
                   6728:     return (0,$currentphase+1);
                   6729: }
                   6730: 
1.423     albertel 6731: 
                   6732: 
1.157     albertel 6733: sub scantron_validate_ID {
                   6734:     my ($r,$currentphase) = @_;
                   6735:     
                   6736:     #get student info
                   6737:     my $classlist=&Apache::loncoursedata::get_classlist();
                   6738:     my %idmap=&username_to_idmap($classlist);
                   6739: 
                   6740:     #get scantron line setup
1.257     albertel 6741:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.157     albertel 6742:     my ($scanlines,$scan_data)=&scantron_getfile();
1.582     raeburn  6743: 
                   6744:     my $nav_error;
                   6745:     &scantron_get_maxbubble(\$nav_error); # parse needs the bubble_lines.. array.
                   6746:     if ($nav_error) {
                   6747:         $r->print(&navmap_errormsg());
                   6748:         return(1,$currentphase);
                   6749:     }
1.157     albertel 6750: 
                   6751:     my %found=('ids'=>{},'usernames'=>{});
                   6752:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
1.200     albertel 6753: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.157     albertel 6754: 	if ($line=~/^[\s\cz]*$/) { next; }
                   6755: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
                   6756: 						 $scan_data);
                   6757: 	my $id=$$scan_record{'scantron.ID'};
                   6758: 	my $found;
                   6759: 	foreach my $checkid (keys(%idmap)) {
                   6760: 	    if (lc($checkid) eq lc($id)) { $found=$checkid;last; }
                   6761: 	}
                   6762: 	if ($found) {
                   6763: 	    my $username=$idmap{$found};
                   6764: 	    if ($found{'ids'}{$found}) {
                   6765: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
                   6766: 					 $line,'duplicateID',$found);
1.194     albertel 6767: 		return(1,$currentphase);
1.157     albertel 6768: 	    } elsif ($found{'usernames'}{$username}) {
                   6769: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
                   6770: 					 $line,'duplicateID',$username);
1.194     albertel 6771: 		return(1,$currentphase);
1.157     albertel 6772: 	    }
1.186     albertel 6773: 	    #FIXME store away line we previously saw the ID on to use above
1.157     albertel 6774: 	    $found{'ids'}{$found}++;
                   6775: 	    $found{'usernames'}{$username}++;
                   6776: 	} else {
                   6777: 	    if ($id =~ /^\s*$/) {
1.158     albertel 6778: 		my $username=&scan_data($scan_data,"$i.user");
1.157     albertel 6779: 		if (defined($username) && $found{'usernames'}{$username}) {
                   6780: 		    &scantron_get_correction($r,$i,$scan_record,
                   6781: 					     \%scantron_config,
                   6782: 					     $line,'duplicateID',$username);
1.194     albertel 6783: 		    return(1,$currentphase);
1.157     albertel 6784: 		} elsif (!defined($username)) {
                   6785: 		    &scantron_get_correction($r,$i,$scan_record,
                   6786: 					     \%scantron_config,
                   6787: 					     $line,'incorrectID');
1.194     albertel 6788: 		    return(1,$currentphase);
1.157     albertel 6789: 		}
                   6790: 		$found{'usernames'}{$username}++;
                   6791: 	    } else {
                   6792: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
                   6793: 					 $line,'incorrectID');
1.194     albertel 6794: 		return(1,$currentphase);
1.157     albertel 6795: 	    }
                   6796: 	}
                   6797:     }
                   6798: 
                   6799:     return (0,$currentphase+1);
                   6800: }
                   6801: 
1.423     albertel 6802: 
1.157     albertel 6803: sub scantron_get_correction {
                   6804:     my ($r,$i,$scan_record,$scan_config,$line,$error,$arg)=@_;
1.454     banghart 6805: #FIXME in the case of a duplicated ID the previous line, probably need
1.157     albertel 6806: #to show both the current line and the previous one and allow skipping
                   6807: #the previous one or the current one
                   6808: 
1.333     albertel 6809:     if ( $$scan_record{'scantron.PaperID'} =~ /\S/) {
1.492     albertel 6810: 	$r->print("<p>".&mt("<b>An error was detected ($error)</b>".
                   6811: 			    " for PaperID <tt>[_1]</tt>",
                   6812: 			    $$scan_record{'scantron.PaperID'})."</p> \n");
1.157     albertel 6813:     } else {
1.492     albertel 6814: 	$r->print("<p>".&mt("<b>An error was detected ($error)</b>".
                   6815: 			    " in scanline [_1] <pre>[_2]</pre>",
                   6816: 			    $i,$line)."</p> \n");
                   6817:     }
                   6818:     my $message="<p>".&mt("The ID on the form is  <tt>[_1]</tt><br />".
                   6819: 			  "The name on the paper is [_2],[_3]",
                   6820: 			  $$scan_record{'scantron.ID'},
                   6821: 			  $$scan_record{'scantron.LastName'},
                   6822: 			  $$scan_record{'scantron.FirstName'})."</p>";
1.242     albertel 6823: 
1.157     albertel 6824:     $r->print('<input type="hidden" name="scantron_corrections" value="'.$error.'" />'."\n");
                   6825:     $r->print('<input type="hidden" name="scantron_line" value="'.$i.'" />'."\n");
1.503     raeburn  6826:                            # Array populated for doublebubble or
                   6827:     my @lines_to_correct;  # missingbubble errors to build javascript
                   6828:                            # to validate radio button checking   
                   6829: 
1.157     albertel 6830:     if ($error =~ /ID$/) {
1.186     albertel 6831: 	if ($error eq 'incorrectID') {
1.492     albertel 6832: 	    $r->print("<p>".&mt("The encoded ID is not in the classlist").
                   6833: 		      "</p>\n");
1.157     albertel 6834: 	} elsif ($error eq 'duplicateID') {
1.492     albertel 6835: 	    $r->print("<p>".&mt("The encoded ID has also been used by a previous paper [_1]",$arg)."</p>\n");
1.157     albertel 6836: 	}
1.242     albertel 6837: 	$r->print($message);
1.492     albertel 6838: 	$r->print("<p>".&mt("How should I handle this?")." <br /> \n");
1.157     albertel 6839: 	$r->print("\n<ul><li> ");
                   6840: 	#FIXME it would be nice if this sent back the user ID and
                   6841: 	#could do partial userID matches
                   6842: 	$r->print(&Apache::loncommon::selectstudent_link('scantronupload',
                   6843: 				       'scantron_username','scantron_domain'));
                   6844: 	$r->print(": <input type='text' name='scantron_username' value='' />");
                   6845: 	$r->print("\n@".
1.257     albertel 6846: 		 &Apache::loncommon::select_dom_form($env{'request.role.domain'},'scantron_domain'));
1.157     albertel 6847: 
                   6848: 	$r->print('</li>');
1.186     albertel 6849:     } elsif ($error =~ /CODE$/) {
                   6850: 	if ($error eq 'incorrectCODE') {
1.492     albertel 6851: 	    $r->print("<p>".&mt("The encoded CODE is not in the list of possible CODEs.")."</p>\n");
1.186     albertel 6852: 	} elsif ($error eq 'duplicateCODE') {
1.492     albertel 6853: 	    $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 6854: 	}
1.492     albertel 6855: 	$r->print("<p>".&mt("The CODE on the form is  <tt>'[_1]'</tt>",
                   6856: 			    $$scan_record{'scantron.CODE'})."<br />\n");
1.242     albertel 6857: 	$r->print($message);
1.492     albertel 6858: 	$r->print("<p>".&mt("How should I handle this?")." <br /> \n");
1.187     albertel 6859: 	$r->print("\n<br /> ");
1.194     albertel 6860: 	my $i=0;
1.273     albertel 6861: 	if ($error eq 'incorrectCODE' 
                   6862: 	    && $$scan_record{'scantron.CODE'}=~/\S/ ) {
1.194     albertel 6863: 	    my ($max,$closest)=&scantron_get_closely_matching_CODEs($arg,$$scan_record{'scantron.CODE'});
1.278     albertel 6864: 	    if ($closest > 0) {
                   6865: 		foreach my $testcode (@{$closest}) {
                   6866: 		    my $checked='';
1.569     bisitz   6867: 		    if (!$i) { $checked=' checked="checked"'; }
1.492     albertel 6868: 		    $r->print("
                   6869:    <label>
1.569     bisitz   6870:        <input type='radio' name='scantron_CODE_resolution' value='use_closest_$i'$checked />
1.492     albertel 6871:        ".&mt("Use the similar CODE [_1] instead.",
                   6872: 	    "<b><tt>".$testcode."</tt></b>")."
                   6873:     </label>
                   6874:     <input type='hidden' name='scantron_CODE_closest_$i' value='$testcode' />");
1.278     albertel 6875: 		    $r->print("\n<br />");
                   6876: 		    $i++;
                   6877: 		}
1.194     albertel 6878: 	    }
                   6879: 	}
1.273     albertel 6880: 	if ($$scan_record{'scantron.CODE'}=~/\S/ ) {
1.569     bisitz   6881: 	    my $checked; if (!$i) { $checked=' checked="checked"'; }
1.492     albertel 6882: 	    $r->print("
                   6883:     <label>
1.569     bisitz   6884:         <input type='radio' name='scantron_CODE_resolution' value='use_unfound'$checked />
1.492     albertel 6885:        ".&mt("Use the CODE [_1] that is was on the paper, ignoring the error.",
                   6886: 	     "<b><tt>".$$scan_record{'scantron.CODE'}."</tt></b>")."
                   6887:     </label>");
1.273     albertel 6888: 	    $r->print("\n<br />");
                   6889: 	}
1.194     albertel 6890: 
1.597     wenzelju 6891: 	$r->print(&Apache::lonhtmlcommon::scripttag(<<ENDSCRIPT));
1.188     albertel 6892: function change_radio(field) {
1.190     albertel 6893:     var slct=document.scantronupload.scantron_CODE_resolution;
1.188     albertel 6894:     var i;
                   6895:     for (i=0;i<slct.length;i++) {
                   6896:         if (slct[i].value==field) { slct[i].checked=true; }
                   6897:     }
                   6898: }
                   6899: ENDSCRIPT
1.187     albertel 6900: 	my $href="/adm/pickcode?".
1.359     www      6901: 	   "form=".&escape("scantronupload").
                   6902: 	   "&scantron_format=".&escape($env{'form.scantron_format'}).
                   6903: 	   "&scantron_CODElist=".&escape($env{'form.scantron_CODElist'}).
                   6904: 	   "&curCODE=".&escape($$scan_record{'scantron.CODE'}).
                   6905: 	   "&scantron_selectfile=".&escape($env{'form.scantron_selectfile'});
1.332     albertel 6906: 	if ($env{'form.scantron_CODElist'} =~ /\S/) { 
1.492     albertel 6907: 	    $r->print("
                   6908:     <label>
                   6909:        <input type='radio' name='scantron_CODE_resolution' value='use_found' />
                   6910:        ".&mt("[_1]Select[_2] a CODE from the list of all CODEs and use it.",
                   6911: 	     "<a target='_blank' href='$href'>","</a>")."
                   6912:     </label> 
1.558     bisitz   6913:     ".&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 6914: 	    $r->print("\n<br />");
                   6915: 	}
1.492     albertel 6916: 	$r->print("
                   6917:     <label>
                   6918:        <input type='radio' name='scantron_CODE_resolution' value='use_typed' />
                   6919:        ".&mt("Use [_1] as the CODE.",
                   6920: 	     "</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 6921: 	$r->print("\n<br /><br />");
1.157     albertel 6922:     } elsif ($error eq 'doublebubble') {
1.503     raeburn  6923: 	$r->print("<p>".&mt("There have been multiple bubbles scanned for some question(s)")."</p>\n");
1.497     foxr     6924: 
                   6925: 	# The form field scantron_questions is acutally a list of line numbers.
                   6926: 	# represented by this form so:
                   6927: 
                   6928: 	my $line_list = &questions_to_line_list($arg);
                   6929: 
1.157     albertel 6930: 	$r->print('<input type="hidden" name="scantron_questions" value="'.
1.497     foxr     6931: 		  $line_list.'" />');
1.242     albertel 6932: 	$r->print($message);
1.492     albertel 6933: 	$r->print("<p>".&mt("Please indicate which bubble should be used for grading")."</p>");
1.157     albertel 6934: 	foreach my $question (@{$arg}) {
1.503     raeburn  6935: 	    my @linenums = &prompt_for_corrections($r,$question,$scan_config,
                   6936:                                                    $scan_record, $error);
1.524     raeburn  6937:             push(@lines_to_correct,@linenums);
1.157     albertel 6938: 	}
1.503     raeburn  6939:         $r->print(&verify_bubbles_checked(@lines_to_correct));
1.157     albertel 6940:     } elsif ($error eq 'missingbubble') {
1.492     albertel 6941: 	$r->print("<p>".&mt("There have been <b>no</b> bubbles scanned for some question(s)")."</p>\n");
1.242     albertel 6942: 	$r->print($message);
1.492     albertel 6943: 	$r->print("<p>".&mt("Please indicate which bubble should be used for grading.")."</p>");
1.503     raeburn  6944: 	$r->print(&mt("Some questions have no scanned bubbles.")."\n");
1.497     foxr     6945: 
1.503     raeburn  6946: 	# The form field scantron_questions is actually a list of line numbers not
1.497     foxr     6947: 	# a list of question numbers. Therefore:
                   6948: 	#
                   6949: 	
                   6950: 	my $line_list = &questions_to_line_list($arg);
                   6951: 
1.157     albertel 6952: 	$r->print('<input type="hidden" name="scantron_questions" value="'.
1.497     foxr     6953: 		  $line_list.'" />');
1.157     albertel 6954: 	foreach my $question (@{$arg}) {
1.503     raeburn  6955: 	    my @linenums = &prompt_for_corrections($r,$question,$scan_config,
                   6956:                                                    $scan_record, $error);
1.524     raeburn  6957:             push(@lines_to_correct,@linenums);
1.157     albertel 6958: 	}
1.503     raeburn  6959:         $r->print(&verify_bubbles_checked(@lines_to_correct));
1.157     albertel 6960:     } else {
                   6961: 	$r->print("\n<ul>");
                   6962:     }
                   6963:     $r->print("\n</li></ul>");
1.497     foxr     6964: }
                   6965: 
1.503     raeburn  6966: sub verify_bubbles_checked {
                   6967:     my (@ansnums) = @_;
                   6968:     my $ansnumstr = join('","',@ansnums);
                   6969:     my $warning = &mt("A bubble or 'No bubble' selection has not been made for one or more lines.");
1.597     wenzelju 6970:     my $output = &Apache::lonhtmlcommon::scripttag((<<ENDSCRIPT));
1.503     raeburn  6971: function verify_bubble_radio(form) {
                   6972:     var ansnumArray = new Array ("$ansnumstr");
                   6973:     var need_bubble_count = 0;
                   6974:     for (var i=0; i<ansnumArray.length; i++) {
                   6975:         if (form.elements["scantron_correct_Q_"+ansnumArray[i]].length > 1) {
                   6976:             var bubble_picked = 0; 
                   6977:             for (var j=0; j<form.elements["scantron_correct_Q_"+ansnumArray[i]].length; j++) {
                   6978:                 if (form.elements["scantron_correct_Q_"+ansnumArray[i]][j].checked == true) {
                   6979:                     bubble_picked = 1;
                   6980:                 }
                   6981:             }
                   6982:             if (bubble_picked == 0) {
                   6983:                 need_bubble_count ++;
                   6984:             }
                   6985:         }
                   6986:     }
                   6987:     if (need_bubble_count) {
                   6988:         alert("$warning");
                   6989:         return;
                   6990:     }
                   6991:     form.submit(); 
                   6992: }
                   6993: ENDSCRIPT
                   6994:     return $output;
                   6995: }
                   6996: 
1.497     foxr     6997: =pod
                   6998: 
                   6999: =item  questions_to_line_list
1.157     albertel 7000: 
1.497     foxr     7001: Converts a list of questions into a string of comma separated
                   7002: line numbers in the answer sheet used by the questions.  This is
                   7003: used to fill in the scantron_questions form field.
                   7004: 
                   7005:   Arguments:
                   7006:      questions    - Reference to an array of questions.
                   7007: 
                   7008: =cut
                   7009: 
                   7010: 
                   7011: sub questions_to_line_list {
                   7012:     my ($questions) = @_;
                   7013:     my @lines;
                   7014: 
1.503     raeburn  7015:     foreach my $item (@{$questions}) {
                   7016:         my $question = $item;
                   7017:         my ($first,$count,$last);
                   7018:         if ($item =~ /^(\d+)\.(\d+)$/) {
                   7019:             $question = $1;
                   7020:             my $subquestion = $2;
                   7021:             $first = $first_bubble_line{$question-1} + 1;
                   7022:             my @subans = split(/,/,$subdivided_bubble_lines{$question-1});
                   7023:             my $subcount = 1;
                   7024:             while ($subcount<$subquestion) {
                   7025:                 $first += $subans[$subcount-1];
                   7026:                 $subcount ++;
                   7027:             }
                   7028:             $count = $subans[$subquestion-1];
                   7029:         } else {
                   7030: 	    $first   = $first_bubble_line{$question-1} + 1;
                   7031: 	    $count   = $bubble_lines_per_response{$question-1};
                   7032:         }
1.506     raeburn  7033:         $last = $first+$count-1;
1.503     raeburn  7034:         push(@lines, ($first..$last));
1.497     foxr     7035:     }
                   7036:     return join(',', @lines);
                   7037: }
                   7038: 
                   7039: =pod 
                   7040: 
                   7041: =item prompt_for_corrections
                   7042: 
                   7043: Prompts for a potentially multiline correction to the
                   7044: user's bubbling (factors out common code from scantron_get_correction
                   7045: for multi and missing bubble cases).
                   7046: 
                   7047:  Arguments:
                   7048:    $r           - Apache request object.
                   7049:    $question    - The question number to prompt for.
                   7050:    $scan_config - The scantron file configuration hash.
                   7051:    $scan_record - Reference to the hash that has the the parsed scanlines.
1.503     raeburn  7052:    $error       - Type of error
1.497     foxr     7053: 
                   7054:  Implicit inputs:
                   7055:    %bubble_lines_per_response   - Starting line numbers for each question.
                   7056:                                   Numbered from 0 (but question numbers are from
                   7057:                                   1.
                   7058:    %first_bubble_line           - Starting bubble line for each question.
1.509     raeburn  7059:    %subdivided_bubble_lines     - optionresponse, matchresponse and rankresponse 
                   7060:                                   type problems render as separate sub-questions, 
1.503     raeburn  7061:                                   in exam mode. This hash contains a 
                   7062:                                   comma-separated list of the lines per 
                   7063:                                   sub-question.
1.510     raeburn  7064:    %responsetype_per_response   - essayresponse, formularesponse,
                   7065:                                   stringresponse, imageresponse, reactionresponse,
                   7066:                                   and organicresponse type problem parts can have
1.503     raeburn  7067:                                   multiple lines per response if the weight
                   7068:                                   assigned exceeds 10.  In this case, only
                   7069:                                   one bubble per line is permitted, but more 
                   7070:                                   than one line might contain bubbles, e.g.
                   7071:                                   bubbling of: line 1 - J, line 2 - J, 
                   7072:                                   line 3 - B would assign 22 points.  
1.497     foxr     7073: 
                   7074: =cut
                   7075: 
                   7076: sub prompt_for_corrections {
1.503     raeburn  7077:     my ($r, $question, $scan_config, $scan_record, $error) = @_;
                   7078:     my ($current_line,$lines);
                   7079:     my @linenums;
                   7080:     my $questionnum = $question;
                   7081:     if ($question =~ /^(\d+)\.(\d+)$/) {
                   7082:         $question = $1;
                   7083:         $current_line = $first_bubble_line{$question-1} + 1 ;
                   7084:         my $subquestion = $2;
                   7085:         my @subans = split(/,/,$subdivided_bubble_lines{$question-1});
                   7086:         my $subcount = 1;
                   7087:         while ($subcount<$subquestion) {
                   7088:             $current_line += $subans[$subcount-1];
                   7089:             $subcount ++;
                   7090:         }
                   7091:         $lines = $subans[$subquestion-1];
                   7092:     } else {
                   7093:         $current_line = $first_bubble_line{$question-1} + 1 ;
                   7094:         $lines        = $bubble_lines_per_response{$question-1};
                   7095:     }
1.497     foxr     7096:     if ($lines > 1) {
1.503     raeburn  7097:         $r->print(&mt('The group of bubble lines below responds to a single question.').'<br />');
                   7098:         if (($responsetype_per_response{$question-1} eq 'essayresponse') ||
                   7099:             ($responsetype_per_response{$question-1} eq 'formularesponse') ||
1.510     raeburn  7100:             ($responsetype_per_response{$question-1} eq 'stringresponse') ||
                   7101:             ($responsetype_per_response{$question-1} eq 'imageresponse') ||
                   7102:             ($responsetype_per_response{$question-1} eq 'reactionresponse') ||
                   7103:             ($responsetype_per_response{$question-1} eq 'organicresponse')) {
1.572     www      7104:             $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  7105:         } else {
                   7106:             $r->print(&mt("Select at most one bubble in a single line and select 'No Bubble' in all the other lines. ")."<br />");
                   7107:         }
1.497     foxr     7108:     }
                   7109:     for (my $i =0; $i < $lines; $i++) {
1.503     raeburn  7110:         my $selected = $$scan_record{"scantron.$current_line.answer"};
                   7111: 	&scantron_bubble_selector($r,$scan_config,$current_line, 
                   7112: 	        		  $questionnum,$error,split('', $selected));
1.524     raeburn  7113:         push(@linenums,$current_line);
1.497     foxr     7114: 	$current_line++;
                   7115:     }
                   7116:     if ($lines > 1) {
                   7117: 	$r->print("<hr /><br />");
                   7118:     }
1.503     raeburn  7119:     return @linenums;
1.157     albertel 7120: }
1.423     albertel 7121: 
                   7122: =pod
                   7123: 
                   7124: =item scantron_bubble_selector
                   7125:   
                   7126:    Generates the html radiobuttons to correct a single bubble line
1.424     albertel 7127:    possibly showing the existing the selected bubbles if known
1.423     albertel 7128: 
                   7129:  Arguments:
                   7130:     $r           - Apache request object
                   7131:     $scan_config - hash from &get_scantron_config()
1.497     foxr     7132:     $line        - Number of the line being displayed.
1.503     raeburn  7133:     $questionnum - Question number (may include subquestion)
                   7134:     $error       - Type of error.
1.497     foxr     7135:     @selected    - Array of bubbles picked on this line.
1.423     albertel 7136: 
                   7137: =cut
                   7138: 
1.157     albertel 7139: sub scantron_bubble_selector {
1.503     raeburn  7140:     my ($r,$scan_config,$line,$questionnum,$error,@selected)=@_;
1.157     albertel 7141:     my $max=$$scan_config{'Qlength'};
1.274     albertel 7142: 
                   7143:     my $scmode=$$scan_config{'Qon'};
                   7144:     if ($scmode eq 'number' || $scmode eq 'letter') { $max=10; }	     
                   7145: 
1.157     albertel 7146:     my @alphabet=('A'..'Z');
1.503     raeburn  7147:     $r->print(&Apache::loncommon::start_data_table().
                   7148:               &Apache::loncommon::start_data_table_row());
                   7149:     $r->print('<td rowspan="2" class="LC_leftcol_header">'.$line.'</td>');
1.497     foxr     7150:     for (my $i=0;$i<$max+1;$i++) {
                   7151: 	$r->print("\n".'<td align="center">');
                   7152: 	if ($selected[0] eq $alphabet[$i]) { $r->print('X'); shift(@selected) }
                   7153: 	else { $r->print('&nbsp;'); }
                   7154: 	$r->print('</td>');
                   7155:     }
1.503     raeburn  7156:     $r->print(&Apache::loncommon::end_data_table_row().
                   7157:               &Apache::loncommon::start_data_table_row());
1.497     foxr     7158:     for (my $i=0;$i<$max;$i++) {
                   7159: 	$r->print("\n".
                   7160: 		  '<td><label><input type="radio" name="scantron_correct_Q_'.
                   7161: 		  $line.'" value="'.$i.'" />'.$alphabet[$i]."</label></td>");
                   7162:     }
1.503     raeburn  7163:     my $nobub_checked = ' ';
                   7164:     if ($error eq 'missingbubble') {
                   7165:         $nobub_checked = ' checked = "checked" ';
                   7166:     }
                   7167:     $r->print("\n".'<td><label><input type="radio" name="scantron_correct_Q_'.
                   7168: 	      $line.'" value="none"'.$nobub_checked.'/>'.&mt('No bubble').
                   7169:               '</label>'."\n".'<input type="hidden" name="scantron_questionnum_Q_'.
                   7170:               $line.'" value="'.$questionnum.'" /></td>');
                   7171:     $r->print(&Apache::loncommon::end_data_table_row().
                   7172:               &Apache::loncommon::end_data_table());
1.157     albertel 7173: }
                   7174: 
1.423     albertel 7175: =pod
                   7176: 
                   7177: =item num_matches
                   7178: 
1.424     albertel 7179:    Counts the number of characters that are the same between the two arguments.
                   7180: 
                   7181:  Arguments:
                   7182:    $orig - CODE from the scanline
                   7183:    $code - CODE to match against
                   7184: 
                   7185:  Returns:
                   7186:    $count - integer count of the number of same characters between the
                   7187:             two arguments
                   7188: 
1.423     albertel 7189: =cut
                   7190: 
1.194     albertel 7191: sub num_matches {
                   7192:     my ($orig,$code) = @_;
                   7193:     my @code=split(//,$code);
                   7194:     my @orig=split(//,$orig);
                   7195:     my $same=0;
                   7196:     for (my $i=0;$i<scalar(@code);$i++) {
                   7197: 	if ($code[$i] eq $orig[$i]) { $same++; }
                   7198:     }
                   7199:     return $same;
                   7200: }
                   7201: 
1.423     albertel 7202: =pod
                   7203: 
                   7204: =item scantron_get_closely_matching_CODEs
                   7205: 
1.424     albertel 7206:    Cycles through all CODEs and finds the set that has the greatest
                   7207:    number of same characters as the provided CODE
                   7208: 
                   7209:  Arguments:
                   7210:    $allcodes - hash ref returned by &get_codes()
                   7211:    $CODE     - CODE from the current scanline
                   7212: 
                   7213:  Returns:
                   7214:    2 element list
                   7215:     - first elements is number of how closely matching the best fit is 
                   7216:       (5 means best set has 5 matching characters)
                   7217:     - second element is an arrary ref containing the set of valid CODEs
                   7218:       that best fit the passed in CODE
                   7219: 
1.423     albertel 7220: =cut
                   7221: 
1.194     albertel 7222: sub scantron_get_closely_matching_CODEs {
                   7223:     my ($allcodes,$CODE)=@_;
                   7224:     my @CODEs;
                   7225:     foreach my $testcode (sort(keys(%{$allcodes}))) {
                   7226: 	push(@{$CODEs[&num_matches($CODE,$testcode)]},$testcode);
                   7227:     }
                   7228: 
                   7229:     return ($#CODEs,$CODEs[-1]);
                   7230: }
                   7231: 
1.423     albertel 7232: =pod
                   7233: 
                   7234: =item get_codes
                   7235: 
1.424     albertel 7236:    Builds a hash which has keys of all of the valid CODEs from the selected
                   7237:    set of remembered CODEs.
                   7238: 
                   7239:  Arguments:
                   7240:   $old_name - name of the set of remembered CODEs
                   7241:   $cdom     - domain of the course
                   7242:   $cnum     - internal course name
                   7243: 
                   7244:  Returns:
                   7245:   %allcodes - keys are the valid CODEs, values are all 1
                   7246: 
1.423     albertel 7247: =cut
                   7248: 
1.194     albertel 7249: sub get_codes {
1.280     foxr     7250:     my ($old_name, $cdom, $cnum) = @_;
                   7251:     if (!$old_name) {
                   7252: 	$old_name=$env{'form.scantron_CODElist'};
                   7253:     }
                   7254:     if (!$cdom) {
                   7255: 	$cdom =$env{'course.'.$env{'request.course.id'}.'.domain'};
                   7256:     }
                   7257:     if (!$cnum) {
                   7258: 	$cnum =$env{'course.'.$env{'request.course.id'}.'.num'};
                   7259:     }
1.278     albertel 7260:     my %result=&Apache::lonnet::get('CODEs',[$old_name,"type\0$old_name"],
                   7261: 				    $cdom,$cnum);
                   7262:     my %allcodes;
                   7263:     if ($result{"type\0$old_name"} eq 'number') {
                   7264: 	%allcodes=map {($_,1)} split(',',$result{$old_name});
                   7265:     } else {
                   7266: 	%allcodes=map {(&Apache::lonprintout::num_to_letters($_),1)} split(',',$result{$old_name});
                   7267:     }
1.194     albertel 7268:     return %allcodes;
                   7269: }
                   7270: 
1.423     albertel 7271: =pod
                   7272: 
                   7273: =item scantron_validate_CODE
                   7274: 
1.424     albertel 7275:    Validates all scanlines in the selected file to not have any
                   7276:    invalid or underspecified CODEs and that none of the codes are
                   7277:    duplicated if this was requested.
                   7278: 
1.423     albertel 7279: =cut
                   7280: 
1.157     albertel 7281: sub scantron_validate_CODE {
                   7282:     my ($r,$currentphase) = @_;
1.257     albertel 7283:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.186     albertel 7284:     if ($scantron_config{'CODElocation'} &&
                   7285: 	$scantron_config{'CODEstart'} &&
                   7286: 	$scantron_config{'CODElength'}) {
1.257     albertel 7287: 	if (!defined($env{'form.scantron_CODElist'})) {
1.186     albertel 7288: 	    &FIXME_blow_up()
                   7289: 	}
                   7290:     } else {
                   7291: 	return (0,$currentphase+1);
                   7292:     }
                   7293:     
                   7294:     my %usedCODEs;
                   7295: 
1.194     albertel 7296:     my %allcodes=&get_codes();
1.186     albertel 7297: 
1.582     raeburn  7298:     my $nav_error;
                   7299:     &scantron_get_maxbubble(\$nav_error); # parse needs the lines per response array.
                   7300:     if ($nav_error) {
                   7301:         $r->print(&navmap_errormsg());
                   7302:         return(1,$currentphase);
                   7303:     }
1.447     foxr     7304: 
1.186     albertel 7305:     my ($scanlines,$scan_data)=&scantron_getfile();
                   7306:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
1.200     albertel 7307: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.186     albertel 7308: 	if ($line=~/^[\s\cz]*$/) { next; }
                   7309: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
                   7310: 						 $scan_data);
                   7311: 	my $CODE=$$scan_record{'scantron.CODE'};
                   7312: 	my $error=0;
1.224     albertel 7313: 	if (!&Apache::lonnet::validCODE($CODE)) {
                   7314: 	    &scantron_get_correction($r,$i,$scan_record,
                   7315: 				     \%scantron_config,
                   7316: 				     $line,'incorrectCODE',\%allcodes);
                   7317: 	    return(1,$currentphase);
                   7318: 	}
1.221     albertel 7319: 	if (%allcodes && !exists($allcodes{$CODE}) 
                   7320: 	    && !$$scan_record{'scantron.useCODE'}) {
1.186     albertel 7321: 	    &scantron_get_correction($r,$i,$scan_record,
                   7322: 				     \%scantron_config,
1.194     albertel 7323: 				     $line,'incorrectCODE',\%allcodes);
                   7324: 	    return(1,$currentphase);
1.186     albertel 7325: 	}
1.214     albertel 7326: 	if (exists($usedCODEs{$CODE}) 
1.257     albertel 7327: 	    && $env{'form.scantron_CODEunique'} eq 'yes'
1.192     albertel 7328: 	    && !$$scan_record{'scantron.CODE_ignore_dup'}) {
1.186     albertel 7329: 	    &scantron_get_correction($r,$i,$scan_record,
                   7330: 				     \%scantron_config,
1.194     albertel 7331: 				     $line,'duplicateCODE',$usedCODEs{$CODE});
                   7332: 	    return(1,$currentphase);
1.186     albertel 7333: 	}
1.524     raeburn  7334: 	push(@{$usedCODEs{$CODE}},$$scan_record{'scantron.PaperID'});
1.186     albertel 7335:     }
1.157     albertel 7336:     return (0,$currentphase+1);
                   7337: }
                   7338: 
1.423     albertel 7339: =pod
                   7340: 
                   7341: =item scantron_validate_doublebubble
                   7342: 
1.424     albertel 7343:    Validates all scanlines in the selected file to not have any
                   7344:    bubble lines with multiple bubbles marked.
                   7345: 
1.423     albertel 7346: =cut
                   7347: 
1.157     albertel 7348: sub scantron_validate_doublebubble {
                   7349:     my ($r,$currentphase) = @_;
                   7350:     #get student info
                   7351:     my $classlist=&Apache::loncoursedata::get_classlist();
                   7352:     my %idmap=&username_to_idmap($classlist);
                   7353: 
                   7354:     #get scantron line setup
1.257     albertel 7355:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.157     albertel 7356:     my ($scanlines,$scan_data)=&scantron_getfile();
1.583     raeburn  7357:     my $nav_error;
                   7358:     &scantron_get_maxbubble(\$nav_error); # parse needs the bubble line array.
                   7359:     if ($nav_error) {
                   7360:         $r->print(&navmap_errormsg());
                   7361:         return(1,$currentphase);
                   7362:     }
1.447     foxr     7363: 
1.157     albertel 7364:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
1.200     albertel 7365: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.157     albertel 7366: 	if ($line=~/^[\s\cz]*$/) { next; }
                   7367: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
                   7368: 						 $scan_data);
                   7369: 	if (!defined($$scan_record{'scantron.doubleerror'})) { next; }
                   7370: 	&scantron_get_correction($r,$i,$scan_record,\%scantron_config,$line,
                   7371: 				 'doublebubble',
                   7372: 				 $$scan_record{'scantron.doubleerror'});
                   7373:     	return (1,$currentphase);
                   7374:     }
                   7375:     return (0,$currentphase+1);
                   7376: }
                   7377: 
1.423     albertel 7378: 
1.503     raeburn  7379: sub scantron_get_maxbubble {
1.582     raeburn  7380:     my ($nav_error) = @_;
1.257     albertel 7381:     if (defined($env{'form.scantron_maxbubble'}) &&
                   7382: 	$env{'form.scantron_maxbubble'}) {
1.447     foxr     7383: 	&restore_bubble_lines();
1.257     albertel 7384: 	return $env{'form.scantron_maxbubble'};
1.191     albertel 7385:     }
1.330     albertel 7386: 
1.447     foxr     7387:     my (undef, undef, $sequence) =
1.257     albertel 7388: 	&Apache::lonnet::decode_symb($env{'form.selectpage'});
1.330     albertel 7389: 
1.447     foxr     7390:     my $navmap=Apache::lonnavmaps::navmap->new();
1.582     raeburn  7391:     unless (ref($navmap)) {
                   7392:         if (ref($nav_error)) {
                   7393:             $$nav_error = 1;
                   7394:         }
1.591     raeburn  7395:         return;
1.582     raeburn  7396:     }
1.191     albertel 7397:     my $map=$navmap->getResourceByUrl($sequence);
                   7398:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
1.330     albertel 7399: 
                   7400:     &Apache::lonxml::clear_problem_counter();
                   7401: 
1.557     raeburn  7402:     my $uname       = $env{'user.name'};
                   7403:     my $udom        = $env{'user.domain'};
1.435     foxr     7404:     my $cid         = $env{'request.course.id'};
                   7405:     my $total_lines = 0;
                   7406:     %bubble_lines_per_response = ();
1.447     foxr     7407:     %first_bubble_line         = ();
1.503     raeburn  7408:     %subdivided_bubble_lines   = ();
                   7409:     %responsetype_per_response = ();
1.554     raeburn  7410: 
1.447     foxr     7411:     my $response_number = 0;
                   7412:     my $bubble_line     = 0;
1.191     albertel 7413:     foreach my $resource (@resources) {
1.542     raeburn  7414:         my ($analysis,$parts) = &scantron_partids_tograde($resource,$cid,$uname,$udom);
                   7415:         if ((ref($analysis) eq 'HASH') && (ref($parts) eq 'ARRAY')) {
                   7416: 	    foreach my $part_id (@{$parts}) {
                   7417:                 my $lines;
                   7418: 
                   7419: 	        # TODO - make this a persistent hash not an array.
                   7420: 
                   7421:                 # optionresponse, matchresponse and rankresponse type items 
                   7422:                 # render as separate sub-questions in exam mode.
                   7423:                 if (($analysis->{$part_id.'.type'} eq 'optionresponse') ||
                   7424:                     ($analysis->{$part_id.'.type'} eq 'matchresponse') ||
                   7425:                     ($analysis->{$part_id.'.type'} eq 'rankresponse')) {
                   7426:                     my ($numbub,$numshown);
                   7427:                     if ($analysis->{$part_id.'.type'} eq 'optionresponse') {
                   7428:                         if (ref($analysis->{$part_id.'.options'}) eq 'ARRAY') {
                   7429:                             $numbub = scalar(@{$analysis->{$part_id.'.options'}});
                   7430:                         }
                   7431:                     } elsif ($analysis->{$part_id.'.type'} eq 'matchresponse') {
                   7432:                         if (ref($analysis->{$part_id.'.items'}) eq 'ARRAY') {
                   7433:                             $numbub = scalar(@{$analysis->{$part_id.'.items'}});
                   7434:                         }
                   7435:                     } elsif ($analysis->{$part_id.'.type'} eq 'rankresponse') {
                   7436:                         if (ref($analysis->{$part_id.'.foils'}) eq 'ARRAY') {
                   7437:                             $numbub = scalar(@{$analysis->{$part_id.'.foils'}});
                   7438:                         }
                   7439:                     }
                   7440:                     if (ref($analysis->{$part_id.'.shown'}) eq 'ARRAY') {
                   7441:                         $numshown = scalar(@{$analysis->{$part_id.'.shown'}});
                   7442:                     }
                   7443:                     my $bubbles_per_line = 10;
                   7444:                     my $inner_bubble_lines = int($numbub/$bubbles_per_line);
                   7445:                     if (($numbub % $bubbles_per_line) != 0) {
                   7446:                         $inner_bubble_lines++;
                   7447:                     }
                   7448:                     for (my $i=0; $i<$numshown; $i++) {
                   7449:                         $subdivided_bubble_lines{$response_number} .= 
                   7450:                             $inner_bubble_lines.',';
                   7451:                     }
                   7452:                     $subdivided_bubble_lines{$response_number} =~ s/,$//;
                   7453:                     $lines = $numshown * $inner_bubble_lines;
                   7454:                 } else {
                   7455:                     $lines = $analysis->{"$part_id.bubble_lines"};
                   7456:                 } 
                   7457: 
                   7458:                 $first_bubble_line{$response_number} = $bubble_line;
                   7459: 	        $bubble_lines_per_response{$response_number} = $lines;
                   7460:                 $responsetype_per_response{$response_number} = 
                   7461:                     $analysis->{$part_id.'.type'};
                   7462: 	        $response_number++;
                   7463: 
                   7464: 	        $bubble_line +=  $lines;
                   7465: 	        $total_lines +=  $lines;
                   7466: 	    }
                   7467:         }
                   7468:     }
1.552     raeburn  7469:     &Apache::lonnet::delenv('scantron.');
1.542     raeburn  7470: 
                   7471:     &save_bubble_lines();
                   7472:     $env{'form.scantron_maxbubble'} =
                   7473: 	$total_lines;
                   7474:     return $env{'form.scantron_maxbubble'};
                   7475: }
1.523     raeburn  7476: 
1.157     albertel 7477: sub scantron_validate_missingbubbles {
                   7478:     my ($r,$currentphase) = @_;
                   7479:     #get student info
                   7480:     my $classlist=&Apache::loncoursedata::get_classlist();
                   7481:     my %idmap=&username_to_idmap($classlist);
                   7482: 
                   7483:     #get scantron line setup
1.257     albertel 7484:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.157     albertel 7485:     my ($scanlines,$scan_data)=&scantron_getfile();
1.582     raeburn  7486:     my $nav_error;
                   7487:     my $max_bubble=&scantron_get_maxbubble(\$nav_error);
                   7488:     if ($nav_error) {
                   7489:         return(1,$currentphase);
                   7490:     }
1.157     albertel 7491:     if (!$max_bubble) { $max_bubble=2**31; }
                   7492:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
1.200     albertel 7493: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.157     albertel 7494: 	if ($line=~/^[\s\cz]*$/) { next; }
                   7495: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
                   7496: 						 $scan_data);
                   7497: 	if (!defined($$scan_record{'scantron.missingerror'})) { next; }
                   7498: 	my @to_correct;
1.470     foxr     7499: 	
                   7500: 	# Probably here's where the error is...
                   7501: 
1.157     albertel 7502: 	foreach my $missing (@{$$scan_record{'scantron.missingerror'}}) {
1.505     raeburn  7503:             my $lastbubble;
                   7504:             if ($missing =~ /^(\d+)\.(\d+)$/) {
                   7505:                my $question = $1;
                   7506:                my $subquestion = $2;
                   7507:                if (!defined($first_bubble_line{$question -1})) { next; }
                   7508:                my $first = $first_bubble_line{$question-1};
                   7509:                my @subans = split(/,/,$subdivided_bubble_lines{$question-1});
                   7510:                my $subcount = 1;
                   7511:                while ($subcount<$subquestion) {
                   7512:                    $first += $subans[$subcount-1];
                   7513:                    $subcount ++;
                   7514:                }
                   7515:                my $count = $subans[$subquestion-1];
                   7516:                $lastbubble = $first + $count;
                   7517:             } else {
                   7518:                 if (!defined($first_bubble_line{$missing - 1})) { next; }
                   7519:                 $lastbubble = $first_bubble_line{$missing - 1} + $bubble_lines_per_response{$missing - 1};
                   7520:             }
                   7521:             if ($lastbubble > $max_bubble) { next; }
1.157     albertel 7522: 	    push(@to_correct,$missing);
                   7523: 	}
                   7524: 	if (@to_correct) {
                   7525: 	    &scantron_get_correction($r,$i,$scan_record,\%scantron_config,
                   7526: 				     $line,'missingbubble',\@to_correct);
                   7527: 	    return (1,$currentphase);
                   7528: 	}
                   7529: 
                   7530:     }
                   7531:     return (0,$currentphase+1);
                   7532: }
                   7533: 
1.423     albertel 7534: 
1.82      albertel 7535: sub scantron_process_students {
1.608     www      7536:     my ($r,$symb) = @_;
1.513     foxr     7537: 
1.257     albertel 7538:     my (undef,undef,$sequence)=&Apache::lonnet::decode_symb($env{'form.selectpage'});
1.513     foxr     7539:     if (!$symb) {
                   7540: 	return '';
                   7541:     }
1.324     albertel 7542:     my $default_form_data=&defaultFormData($symb);
1.82      albertel 7543: 
1.257     albertel 7544:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.157     albertel 7545:     my ($scanlines,$scan_data)=&scantron_getfile();
1.82      albertel 7546:     my $classlist=&Apache::loncoursedata::get_classlist();
                   7547:     my %idmap=&username_to_idmap($classlist);
1.132     bowersj2 7548:     my $navmap=Apache::lonnavmaps::navmap->new();
1.582     raeburn  7549:     unless (ref($navmap)) {
                   7550:         $r->print(&navmap_errormsg());
                   7551:         return '';
                   7552:     }  
1.83      albertel 7553:     my $map=$navmap->getResourceByUrl($sequence);
                   7554:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
1.557     raeburn  7555:     my (%grader_partids_by_symb,%grader_randomlists_by_symb);
                   7556:     &graders_resources_pass(\@resources,\%grader_partids_by_symb,
                   7557:                             \%grader_randomlists_by_symb);
1.586     raeburn  7558:     my $resource_error;
1.557     raeburn  7559:     foreach my $resource (@resources) {
1.586     raeburn  7560:         my $ressymb;
                   7561:         if (ref($resource)) {
                   7562:             $ressymb = $resource->symb();
                   7563:         } else {
                   7564:             $resource_error = 1;
                   7565:             last;
                   7566:         }
1.557     raeburn  7567:         my ($analysis,$parts) =
                   7568:             &scantron_partids_tograde($resource,$env{'request.course.id'},
                   7569:                                       $env{'user.name'},$env{'user.domain'},1);
                   7570:         $grader_partids_by_symb{$ressymb} = $parts;
                   7571:         if (ref($analysis) eq 'HASH') {
                   7572:             if (ref($analysis->{'parts_withrandomlist'}) eq 'ARRAY') {
                   7573:                 $grader_randomlists_by_symb{$ressymb} = 
                   7574:                     $analysis->{'parts_withrandomlist'};
                   7575:             }
                   7576:         }
                   7577:     }
1.586     raeburn  7578:     if ($resource_error) {
                   7579:         $r->print(&navmap_errormsg());
                   7580:         return '';
                   7581:     }
1.557     raeburn  7582: 
1.554     raeburn  7583:     my ($uname,$udom);
1.82      albertel 7584:     my $result= <<SCANTRONFORM;
1.81      albertel 7585: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantronupload">
                   7586:   <input type="hidden" name="command" value="scantron_configphase" />
                   7587:   $default_form_data
                   7588: SCANTRONFORM
1.82      albertel 7589:     $r->print($result);
                   7590: 
                   7591:     my @delayqueue;
1.542     raeburn  7592:     my (%completedstudents,%scandata);
1.140     albertel 7593:     
1.520     www      7594:     my $lock=&Apache::lonnet::set_lock(&mt('Grading bubblesheet exam'));
1.200     albertel 7595:     my $count=&get_todo_count($scanlines,$scan_data);
1.575     www      7596:     my %prog_state=&Apache::lonhtmlcommon::Create_PrgWin($r,'Bubblesheet Status',
                   7597:  				    'Bubblesheet Progress',$count,
1.195     albertel 7598: 				    'inline',undef,'scantronupload');
1.140     albertel 7599:     &Apache::lonhtmlcommon::Update_PrgWin($r,\%prog_state,
                   7600: 					  'Processing first student');
1.542     raeburn  7601:     $r->print('<br />');
1.140     albertel 7602:     my $start=&Time::HiRes::time();
1.158     albertel 7603:     my $i=-1;
1.542     raeburn  7604:     my $started;
1.447     foxr     7605: 
1.582     raeburn  7606:     my $nav_error;
                   7607:     &scantron_get_maxbubble(\$nav_error); # Need the bubble lines array to parse.
                   7608:     if ($nav_error) {
                   7609:         $r->print(&navmap_errormsg());
                   7610:         return '';
                   7611:     }
                   7612: 
1.513     foxr     7613:     # If an ssi failed in scantron_get_maxbubble, put an error message out to
                   7614:     # the user and return.
                   7615: 
                   7616:     if ($ssi_error) {
                   7617: 	$r->print("</form>");
                   7618: 	&ssi_print_error($r);
1.520     www      7619:         &Apache::lonnet::remove_lock($lock);
1.513     foxr     7620: 	return '';		# Dunno why the other returns return '' rather than just returning.
                   7621:     }
1.447     foxr     7622: 
1.542     raeburn  7623:     my %lettdig = &letter_to_digits();
                   7624:     my $numletts = scalar(keys(%lettdig));
                   7625: 
1.157     albertel 7626:     while ($i<$scanlines->{'count'}) {
                   7627:  	($uname,$udom)=('','');
                   7628:  	$i++;
1.200     albertel 7629:  	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.157     albertel 7630:  	if ($line=~/^[\s\cz]*$/) { next; }
1.200     albertel 7631: 	if ($started) {
                   7632: 	    &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state,
                   7633: 						     'last student');
                   7634: 	}
                   7635: 	$started=1;
1.157     albertel 7636:  	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
                   7637:  						 $scan_data);
                   7638:  	unless ($uname=&scantron_find_student($scan_record,$scan_data,
                   7639:  					      \%idmap,$i)) {
                   7640:   	    &scantron_add_delay(\@delayqueue,$line,
                   7641:  				'Unable to find a student that matches',1);
                   7642:  	    next;
                   7643:   	}
                   7644:  	if (exists $completedstudents{$uname}) {
                   7645:  	    &scantron_add_delay(\@delayqueue,$line,
                   7646:  				'Student '.$uname.' has multiple sheets',2);
                   7647:  	    next;
                   7648:  	}
                   7649:   	($uname,$udom)=split(/:/,$uname);
1.330     albertel 7650: 
1.586     raeburn  7651:         my (%partids_by_symb,$res_error);
1.554     raeburn  7652:         foreach my $resource (@resources) {
1.586     raeburn  7653:             my $ressymb;
                   7654:             if (ref($resource)) {
                   7655:                 $ressymb = $resource->symb();
                   7656:             } else {
                   7657:                 $res_error = 1;
                   7658:                 last;
                   7659:             }
1.557     raeburn  7660:             if ((exists($grader_randomlists_by_symb{$ressymb})) ||
                   7661:                 (ref($grader_partids_by_symb{$ressymb}) ne 'ARRAY')) {
                   7662:                 my ($analysis,$parts) =
                   7663:                     &scantron_partids_tograde($resource,$env{'request.course.id'},$uname,$udom);
                   7664:                 $partids_by_symb{$ressymb} = $parts;
                   7665:             } else {
                   7666:                 $partids_by_symb{$ressymb} = $grader_partids_by_symb{$ressymb};
                   7667:             }
1.554     raeburn  7668:         }
                   7669: 
1.586     raeburn  7670:         if ($res_error) {
                   7671:             &scantron_add_delay(\@delayqueue,$line,
                   7672:                                 'An error occurred while grading student '.$uname,2);
                   7673:             next;
                   7674:         }
                   7675: 
1.330     albertel 7676: 	&Apache::lonxml::clear_problem_counter();
1.514     raeburn  7677:   	&Apache::lonnet::appenv($scan_record);
1.376     albertel 7678: 
                   7679: 	if (&scantron_clear_skip($scanlines,$scan_data,$i)) {
                   7680: 	    &scantron_putfile($scanlines,$scan_data);
                   7681: 	}
1.161     albertel 7682: 	
1.542     raeburn  7683:         my $scancode;
                   7684:         if ((exists($scan_record->{'scantron.CODE'})) &&
                   7685:             (&Apache::lonnet::validCODE($scan_record->{'scantron.CODE'}))) {
                   7686:             $scancode = $scan_record->{'scantron.CODE'};
                   7687:         } else {
                   7688:             $scancode = '';
                   7689:         }
                   7690: 
                   7691:         if (&grade_student_bubbles($r,$uname,$udom,$scan_record,$scancode,
1.554     raeburn  7692:                                    \@resources,\%partids_by_symb) eq 'ssi_error') {
1.542     raeburn  7693:             $ssi_error = 0; # So end of handler error message does not trigger.
                   7694:             $r->print("</form>");
                   7695:             &ssi_print_error($r);
                   7696:             &Apache::lonnet::remove_lock($lock);
                   7697:             return '';      # Why return ''?  Beats me.
                   7698:         }
1.513     foxr     7699: 
1.140     albertel 7700: 	$completedstudents{$uname}={'line'=>$line};
1.542     raeburn  7701:         if ($env{'form.verifyrecord'}) {
                   7702:             my $lastpos = $env{'form.scantron_maxbubble'}*$scantron_config{'Qlength'};
                   7703:             my $studentdata = substr($line,$scantron_config{'Qstart'}-1,$lastpos);
                   7704:             chomp($studentdata);
                   7705:             $studentdata =~ s/\r$//;
                   7706:             my $studentrecord = '';
                   7707:             my $counter = -1;
                   7708:             foreach my $resource (@resources) {
1.554     raeburn  7709:                 my $ressymb = $resource->symb();
1.542     raeburn  7710:                 ($counter,my $recording) =
                   7711:                     &verify_scantron_grading($resource,$udom,$uname,$env{'request.course.id'},
1.554     raeburn  7712:                                              $counter,$studentdata,$partids_by_symb{$ressymb},
1.542     raeburn  7713:                                              \%scantron_config,\%lettdig,$numletts);
                   7714:                 $studentrecord .= $recording;
                   7715:             }
                   7716:             if ($studentrecord ne $studentdata) {
1.554     raeburn  7717:                 &Apache::lonxml::clear_problem_counter();
                   7718:                 if (&grade_student_bubbles($r,$uname,$udom,$scan_record,$scancode,
                   7719:                                            \@resources,\%partids_by_symb) eq 'ssi_error') {
                   7720:                     $ssi_error = 0; # So end of handler error message does not trigger.
                   7721:                     $r->print("</form>");
                   7722:                     &ssi_print_error($r);
                   7723:                     &Apache::lonnet::remove_lock($lock);
                   7724:                     delete($completedstudents{$uname});
                   7725:                     return '';
                   7726:                 }
1.542     raeburn  7727:                 $counter = -1;
                   7728:                 $studentrecord = '';
                   7729:                 foreach my $resource (@resources) {
1.554     raeburn  7730:                     my $ressymb = $resource->symb();
1.542     raeburn  7731:                     ($counter,my $recording) =
                   7732:                         &verify_scantron_grading($resource,$udom,$uname,$env{'request.course.id'},
1.554     raeburn  7733:                                                  $counter,$studentdata,$partids_by_symb{$ressymb},
1.542     raeburn  7734:                                                  \%scantron_config,\%lettdig,$numletts);
                   7735:                     $studentrecord .= $recording;
                   7736:                 }
                   7737:                 if ($studentrecord ne $studentdata) {
                   7738:                     $r->print('<p><span class="LC_error">');
                   7739:                     if ($scancode eq '') {
                   7740:                         $r->print(&mt('Mismatch grading bubble sheet for user: [_1] with ID: [_2].',
                   7741:                                   $uname.':'.$udom,$scan_record->{'scantron.ID'}));
                   7742:                     } else {
                   7743:                         $r->print(&mt('Mismatch grading bubble sheet for user: [_1] with ID: [_2] and CODE: [_3].',
                   7744:                                   $uname.':'.$udom,$scan_record->{'scantron.ID'},$scancode));
                   7745:                     }
                   7746:                     $r->print('</span><br />'.&Apache::loncommon::start_data_table()."\n".
                   7747:                               &Apache::loncommon::start_data_table_header_row()."\n".
                   7748:                               '<th>'.&mt('Source').'</th><th>'.&mt('Bubbled responses').'</th>'.
                   7749:                               &Apache::loncommon::end_data_table_header_row()."\n".
                   7750:                               &Apache::loncommon::start_data_table_row().
                   7751:                               '<td>'.&mt('Bubble Sheet').'</td>'.
                   7752:                               '<td><span class="LC_nobreak">'.$studentdata.'</span></td>'.
                   7753:                               &Apache::loncommon::end_data_table_row().
                   7754:                               &Apache::loncommon::start_data_table_row().
                   7755:                               '<td>Stored submissions</td>'.
                   7756:                               '<td><span class="LC_nobreak">'.$studentrecord.'</span></td>'."\n".
                   7757:                               &Apache::loncommon::end_data_table_row().
                   7758:                               &Apache::loncommon::end_data_table().'</p>');
                   7759:                 } else {
                   7760:                     $r->print('<br /><span class="LC_warning">'.
                   7761:                              &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 />'.
                   7762:                              &mt("As a consequence, this user's submission history records two tries.").
                   7763:                                  '</span><br />');
                   7764:                 }
                   7765:             }
                   7766:         }
1.543     raeburn  7767:         if (&Apache::loncommon::connection_aborted($r)) { last; }
1.140     albertel 7768:     } continue {
1.330     albertel 7769: 	&Apache::lonxml::clear_problem_counter();
1.552     raeburn  7770: 	&Apache::lonnet::delenv('scantron.');
1.82      albertel 7771:     }
1.140     albertel 7772:     &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
1.520     www      7773:     &Apache::lonnet::remove_lock($lock);
1.172     albertel 7774: #    my $lasttime = &Time::HiRes::time()-$start;
                   7775: #    $r->print("<p>took $lasttime</p>");
1.140     albertel 7776: 
1.200     albertel 7777:     $r->print("</form>");
1.157     albertel 7778:     return '';
1.75      albertel 7779: }
1.157     albertel 7780: 
1.557     raeburn  7781: sub graders_resources_pass {
                   7782:     my ($resources,$grader_partids_by_symb,$grader_randomlists_by_symb) = @_;
                   7783:     if ((ref($resources) eq 'ARRAY') && (ref($grader_partids_by_symb)) && 
                   7784:         (ref($grader_randomlists_by_symb) eq 'HASH')) {
                   7785:         foreach my $resource (@{$resources}) {
                   7786:             my $ressymb = $resource->symb();
                   7787:             my ($analysis,$parts) =
                   7788:                 &scantron_partids_tograde($resource,$env{'request.course.id'},
                   7789:                                           $env{'user.name'},$env{'user.domain'},1);
                   7790:             $grader_partids_by_symb->{$ressymb} = $parts;
                   7791:             if (ref($analysis) eq 'HASH') {
                   7792:                 if (ref($analysis->{'parts_withrandomlist'}) eq 'ARRAY') {
                   7793:                     $grader_randomlists_by_symb->{$ressymb} =
                   7794:                         $analysis->{'parts_withrandomlist'};
                   7795:                 }
                   7796:             }
                   7797:         }
                   7798:     }
                   7799:     return;
                   7800: }
                   7801: 
1.542     raeburn  7802: sub grade_student_bubbles {
1.554     raeburn  7803:     my ($r,$uname,$udom,$scan_record,$scancode,$resources,$parts) = @_;
                   7804:     if (ref($resources) eq 'ARRAY') {
                   7805:         my $count = 0;
                   7806:         foreach my $resource (@{$resources}) {
                   7807:             my $ressymb = $resource->symb();
                   7808:             my %form = ('submitted'      => 'scantron',
                   7809:                         'grade_target'   => 'grade',
                   7810:                         'grade_username' => $uname,
                   7811:                         'grade_domain'   => $udom,
                   7812:                         'grade_courseid' => $env{'request.course.id'},
                   7813:                         'grade_symb'     => $ressymb,
                   7814:                         'CODE'           => $scancode
                   7815:                        );
                   7816:             if (ref($parts) eq 'HASH') {
                   7817:                 if (ref($parts->{$ressymb}) eq 'ARRAY') {
                   7818:                     foreach my $part (@{$parts->{$ressymb}}) {
                   7819:                         $form{'scantron_questnum_start.'.$part} =
                   7820:                             1+$env{'form.scantron.first_bubble_line.'.$count};
                   7821:                         $count++;
                   7822:                     }
                   7823:                 }
                   7824:             }
                   7825:             my $result=&ssi_with_retries($resource->src(),$ssi_retries,%form);
                   7826:             return 'ssi_error' if ($ssi_error);
                   7827:             last if (&Apache::loncommon::connection_aborted($r));
                   7828:         }
1.542     raeburn  7829:     }
                   7830:     return;
                   7831: }
                   7832: 
1.157     albertel 7833: sub scantron_upload_scantron_data {
1.608     www      7834:     my ($r,$symb)=@_;
1.565     raeburn  7835:     my $dom = $env{'request.role.domain'};
                   7836:     my $domdesc = &Apache::lonnet::domain($dom,'description');
                   7837:     $r->print(&Apache::loncommon::coursebrowser_javascript($dom));
1.157     albertel 7838:     my $select_link=&Apache::loncommon::selectcourse_link('rules','courseid',
1.181     albertel 7839: 							  'domainid',
1.565     raeburn  7840: 							  'coursename',$dom);
                   7841:     my $syllabuslink = '<a href="javascript:ToSyllabus();">'.&mt('Syllabus').'</a>'.
                   7842:                        ('&nbsp'x2).&mt('(shows course personnel)'); 
1.608     www      7843:     my $default_form_data=&defaultFormData($symb);
1.579     raeburn  7844:     my $nofile_alert = &mt('Please use the browse button to select a file from your local directory.');
                   7845:     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 7846:     $r->print(&Apache::lonhtmlcommon::scripttag('
1.157     albertel 7847:     function checkUpload(formname) {
                   7848: 	if (formname.upfile.value == "") {
1.579     raeburn  7849: 	    alert("'.$nofile_alert.'");
1.157     albertel 7850: 	    return false;
                   7851: 	}
1.565     raeburn  7852:         if (formname.courseid.value == "") {
1.579     raeburn  7853:             alert("'.$nocourseid_alert.'");
1.565     raeburn  7854:             return false;
                   7855:         }
1.157     albertel 7856: 	formname.submit();
                   7857:     }
1.565     raeburn  7858: 
                   7859:     function ToSyllabus() {
                   7860:         var cdom = '."'$dom'".';
                   7861:         var cnum = document.rules.courseid.value;
                   7862:         if (cdom == "" || cdom == null) {
                   7863:             return;
                   7864:         }
                   7865:         if (cnum == "" || cnum == null) {
                   7866:            return;
                   7867:         }
                   7868:         syllwin=window.open("/public/"+cdom+"/"+cnum+"/syllabus","LONCAPASyllabus",
                   7869:                             "height=350,width=350,scrollbars=yes,menubar=no");
                   7870:         return;
                   7871:     }
                   7872: 
1.597     wenzelju 7873: '));
                   7874:     $r->print('
1.566     raeburn  7875: <h3>'.&mt('Send scanned bubblesheet data to a course').'</h3>
                   7876: 
1.492     albertel 7877: <form enctype="multipart/form-data" action="/adm/grades" name="rules" method="post">
1.565     raeburn  7878: '.$default_form_data.
                   7879:   &Apache::lonhtmlcommon::start_pick_box().
                   7880:   &Apache::lonhtmlcommon::row_title(&mt('Course ID')).
                   7881:   '<input name="courseid" type="text" size="30" />'.$select_link.
                   7882:   &Apache::lonhtmlcommon::row_closure().
                   7883:   &Apache::lonhtmlcommon::row_title(&mt('Course Name')).
                   7884:   '<input name="coursename" type="text" size="30" />'.$syllabuslink.
                   7885:   &Apache::lonhtmlcommon::row_closure().
                   7886:   &Apache::lonhtmlcommon::row_title(&mt('Domain')).
                   7887:   '<input name="domainid" type="hidden" />'.$domdesc.
                   7888:   &Apache::lonhtmlcommon::row_closure().
                   7889:   &Apache::lonhtmlcommon::row_title(&mt('File to upload')).
                   7890:   '<input type="file" name="upfile" size="50" />'.
                   7891:   &Apache::lonhtmlcommon::row_closure(1).
                   7892:   &Apache::lonhtmlcommon::end_pick_box().'<br />
                   7893: 
1.492     albertel 7894: <input name="command" value="scantronupload_save" type="hidden" />
1.589     bisitz   7895: <input type="button" onclick="javascript:checkUpload(this.form);" value="'.&mt('Upload Bubblesheet Data').'" />
1.157     albertel 7896: </form>
1.492     albertel 7897: ');
1.157     albertel 7898:     return '';
                   7899: }
                   7900: 
1.423     albertel 7901: 
1.157     albertel 7902: sub scantron_upload_scantron_data_save {
1.608     www      7903:     my($r,$symb)=@_;
1.182     albertel 7904:     my $doanotherupload=
                   7905: 	'<br /><form action="/adm/grades" method="post">'."\n".
                   7906: 	'<input type="hidden" name="command" value="scantronupload" />'."\n".
1.492     albertel 7907: 	'<input type="submit" name="submit" value="'.&mt('Do Another Upload').'" />'."\n".
1.182     albertel 7908: 	'</form>'."\n";
1.257     albertel 7909:     if (!&Apache::lonnet::allowed('usc',$env{'form.domainid'}) &&
1.162     albertel 7910: 	!&Apache::lonnet::allowed('usc',
1.257     albertel 7911: 			    $env{'form.domainid'}.'_'.$env{'form.courseid'})) {
1.575     www      7912: 	$r->print(&mt("You are not allowed to upload bubblesheet data to the requested course.")."<br />");
1.614     www      7913: 	unless ($symb) {
1.182     albertel 7914: 	    $r->print($doanotherupload);
                   7915: 	}
1.162     albertel 7916: 	return '';
                   7917:     }
1.257     albertel 7918:     my %coursedata=&Apache::lonnet::coursedescription($env{'form.domainid'}.'_'.$env{'form.courseid'});
1.568     raeburn  7919:     my $uploadedfile;
1.567     raeburn  7920:     $r->print('<h3>'.&mt("Uploading file to [_1]",$coursedata{'description'}).'</h3>');
1.257     albertel 7921:     if (length($env{'form.upfile'}) < 2) {
1.568     raeburn  7922:         $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 7923:     } else {
1.568     raeburn  7924:         my $result = 
                   7925:             &Apache::lonnet::userfileupload('upfile','','scantron','','','',
                   7926:                                             $env{'form.courseid'},$env{'form.domainid'});
                   7927: 	if ($result =~ m{^/uploaded/}) {
1.567     raeburn  7928: 	    $r->print(&mt('[_1]Success:[_2] Successfully uploaded [_3] bytes of data into location: [_4]',
                   7929:                           '<span class="LC_success">','</span>',(length($env{'form.upfile'})-1),
                   7930: 			  '<span class="LC_filename">'.$result.'</span>'));
1.568     raeburn  7931:             ($uploadedfile) = ($result =~ m{/([^/]+)$});
1.567     raeburn  7932:             $r->print(&validate_uploaded_scantron_file($env{'form.domainid'},
1.568     raeburn  7933:                                                        $env{'form.courseid'},$uploadedfile));
1.210     albertel 7934: 	} else {
1.567     raeburn  7935: 	    $r->print(&mt('[_1]Error:[_2] An error ([_3]) occurred when attempting to upload the file, [_4]',
                   7936:                           '<span class="LC_error">','</span>',$result,
1.568     raeburn  7937: 			  '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>'));
1.183     albertel 7938: 	}
                   7939:     }
1.174     albertel 7940:     if ($symb) {
1.612     www      7941: 	$r->print(&scantron_selectphase($r,$uploadedfile,$symb));
1.174     albertel 7942:     } else {
1.182     albertel 7943: 	$r->print($doanotherupload);
1.174     albertel 7944:     }
1.157     albertel 7945:     return '';
                   7946: }
                   7947: 
1.567     raeburn  7948: sub validate_uploaded_scantron_file {
                   7949:     my ($cdom,$cname,$fname) = @_;
                   7950:     my $scanlines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.$fname);
                   7951:     my @lines;
                   7952:     if ($scanlines ne '-1') {
                   7953:         @lines=split("\n",$scanlines,-1);
                   7954:     }
                   7955:     my $output;
                   7956:     if (@lines) {
                   7957:         my (%counts,$max_match_format);
                   7958:         my ($max_match_count,$max_match_pct) = (0,0);
                   7959:         my $classlist = &Apache::loncoursedata::get_classlist($cdom,$cname);
                   7960:         my %idmap = &username_to_idmap($classlist);
                   7961:         foreach my $key (keys(%idmap)) {
                   7962:             my $lckey = lc($key);
                   7963:             $idmap{$lckey} = $idmap{$key};
                   7964:         }
                   7965:         my %unique_formats;
                   7966:         my @formatlines = &get_scantronformat_file();
                   7967:         foreach my $line (@formatlines) {
                   7968:             chomp($line);
                   7969:             my @config = split(/:/,$line);
                   7970:             my $idstart = $config[5];
                   7971:             my $idlength = $config[6];
                   7972:             if (($idstart ne '') && ($idlength > 0)) {
                   7973:                 if (ref($unique_formats{$idstart.':'.$idlength}) eq 'ARRAY') {
                   7974:                     push(@{$unique_formats{$idstart.':'.$idlength}},$config[0].':'.$config[1]); 
                   7975:                 } else {
                   7976:                     $unique_formats{$idstart.':'.$idlength} = [$config[0].':'.$config[1]];
                   7977:                 }
                   7978:             }
                   7979:         }
                   7980:         foreach my $key (keys(%unique_formats)) {
                   7981:             my ($idstart,$idlength) = split(':',$key);
                   7982:             %{$counts{$key}} = (
                   7983:                                'found'   => 0,
                   7984:                                'total'   => 0,
                   7985:                               );
                   7986:             foreach my $line (@lines) {
                   7987:                 next if ($line =~ /^#/);
                   7988:                 next if ($line =~ /^[\s\cz]*$/);
                   7989:                 my $id = substr($line,$idstart-1,$idlength);
                   7990:                 $id = lc($id);
                   7991:                 if (exists($idmap{$id})) {
                   7992:                     $counts{$key}{'found'} ++;
                   7993:                 }
                   7994:                 $counts{$key}{'total'} ++;
                   7995:             }
                   7996:             if ($counts{$key}{'total'}) {
                   7997:                 my $percent_match = (100*$counts{$key}{'found'})/($counts{$key}{'total'});
                   7998:                 if (($max_match_format eq '') || ($percent_match > $max_match_pct)) {
                   7999:                     $max_match_pct = $percent_match;
                   8000:                     $max_match_format = $key;
                   8001:                     $max_match_count = $counts{$key}{'total'};
                   8002:                 }
                   8003:             }
                   8004:         }
                   8005:         if (ref($unique_formats{$max_match_format}) eq 'ARRAY') {
                   8006:             my $format_descs;
                   8007:             my $numwithformat = @{$unique_formats{$max_match_format}};
                   8008:             for (my $i=0; $i<$numwithformat; $i++) {
                   8009:                 my ($name,$desc) = split(':',$unique_formats{$max_match_format}[$i]);
                   8010:                 if ($i<$numwithformat-2) {
                   8011:                     $format_descs .= '"<i>'.$desc.'</i>", ';
                   8012:                 } elsif ($i==$numwithformat-2) {
                   8013:                     $format_descs .= '"<i>'.$desc.'</i>" '.&mt('and').' ';
                   8014:                 } elsif ($i==$numwithformat-1) {
                   8015:                     $format_descs .= '"<i>'.$desc.'</i>"';
                   8016:                 }
                   8017:             }
                   8018:             my $showpct = sprintf("%.0f",$max_match_pct).'%';
                   8019:             $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).
                   8020:                        '<br />'.&mt('A low percentage of matches results from one of the following:').'<ul>'.
                   8021:                        '<li>'.&mt('The file was uploaded to the wrong course').'</li>'.
                   8022:                        '<li>'.&mt('The data are not in the format expected for the domain: [_1]',
                   8023:                                   '<i>'.$cdom.'</i>').'</li>'.
                   8024:                        '<li>'.&mt('Students did not bubble their IDs, or mis-bubbled them').'</li>'.
                   8025:                        '<li>'.&mt('The course roster is not up to date').'</li>'.
                   8026:                        '</ul>';
                   8027:         }
                   8028:     } else {
                   8029:         $output = '<span class="LC_warning">'.&mt('Uploaded file contained no data').'</span>';
                   8030:     }
                   8031:     return $output;
                   8032: }
                   8033: 
1.202     albertel 8034: sub valid_file {
                   8035:     my ($requested_file)=@_;
                   8036:     foreach my $filename (sort(&scantron_filenames())) {
                   8037: 	if ($requested_file eq $filename) { return 1; }
                   8038:     }
                   8039:     return 0;
                   8040: }
                   8041: 
                   8042: sub scantron_download_scantron_data {
1.608     www      8043:     my ($r,$symb)=@_;
                   8044:     my $default_form_data=&defaultFormData($symb);
1.257     albertel 8045:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   8046:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   8047:     my $file=$env{'form.scantron_selectfile'};
1.202     albertel 8048:     if (! &valid_file($file)) {
1.492     albertel 8049: 	$r->print('
1.202     albertel 8050: 	<p>
1.492     albertel 8051: 	    '.&mt('The requested file name was invalid.').'
1.202     albertel 8052:         </p>
1.492     albertel 8053: ');
1.202     albertel 8054: 	return;
                   8055:     }
                   8056:     my $orig='/uploaded/'.$cdom.'/'.$cname.'/scantron_orig_'.$file;
                   8057:     my $corrected='/uploaded/'.$cdom.'/'.$cname.'/scantron_corrected_'.$file;
                   8058:     my $skipped='/uploaded/'.$cdom.'/'.$cname.'/scantron_skipped_'.$file;
                   8059:     &Apache::lonnet::allowuploaded('/adm/grades',$orig);
                   8060:     &Apache::lonnet::allowuploaded('/adm/grades',$corrected);
                   8061:     &Apache::lonnet::allowuploaded('/adm/grades',$skipped);
1.492     albertel 8062:     $r->print('
1.202     albertel 8063:     <p>
1.492     albertel 8064: 	'.&mt('[_1]Original[_2] file as uploaded by the scantron office.',
                   8065: 	      '<a href="'.$orig.'">','</a>').'
1.202     albertel 8066:     </p>
                   8067:     <p>
1.492     albertel 8068: 	'.&mt('[_1]Corrections[_2], a file of corrected records that were used in grading.',
                   8069: 	      '<a href="'.$corrected.'">','</a>').'
1.202     albertel 8070:     </p>
                   8071:     <p>
1.492     albertel 8072: 	'.&mt('[_1]Skipped[_2], a file of records that were skipped.',
                   8073: 	      '<a href="'.$skipped.'">','</a>').'
1.202     albertel 8074:     </p>
1.492     albertel 8075: ');
1.202     albertel 8076:     return '';
                   8077: }
1.157     albertel 8078: 
1.523     raeburn  8079: sub checkscantron_results {
1.608     www      8080:     my ($r,$symb) = @_;
1.523     raeburn  8081:     if (!$symb) {return '';}
                   8082:     my $cid = $env{'request.course.id'};
1.542     raeburn  8083:     my %lettdig = &letter_to_digits();
1.523     raeburn  8084:     my $numletts = scalar(keys(%lettdig));
                   8085:     my $cnum = $env{'course.'.$cid.'.num'};
                   8086:     my $cdom = $env{'course.'.$cid.'.domain'};
                   8087:     my (undef, undef, $sequence) = &Apache::lonnet::decode_symb($env{'form.selectpage'});
                   8088:     my %record;
                   8089:     my %scantron_config =
                   8090:         &Apache::grades::get_scantron_config($env{'form.scantron_format'});
                   8091:     my ($scanlines,$scan_data)=&Apache::grades::scantron_getfile();
                   8092:     my $classlist=&Apache::loncoursedata::get_classlist();
                   8093:     my %idmap=&Apache::grades::username_to_idmap($classlist);
                   8094:     my $navmap=Apache::lonnavmaps::navmap->new();
1.582     raeburn  8095:     unless (ref($navmap)) {
                   8096:         $r->print(&navmap_errormsg());
                   8097:         return '';
                   8098:     }
1.523     raeburn  8099:     my $map=$navmap->getResourceByUrl($sequence);
1.557     raeburn  8100:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
                   8101:     my (%grader_partids_by_symb,%grader_randomlists_by_symb);
                   8102:     &graders_resources_pass(\@resources,\%grader_partids_by_symb,                             \%grader_randomlists_by_symb);
                   8103: 
1.554     raeburn  8104:     my ($uname,$udom);
1.523     raeburn  8105:     my (%scandata,%lastname,%bylast);
                   8106:     $r->print('
                   8107: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="checkscantron">'."\n");
                   8108: 
                   8109:     my @delayqueue;
                   8110:     my %completedstudents;
                   8111: 
                   8112:     my $count=&Apache::grades::get_todo_count($scanlines,$scan_data);
1.581     www      8113:     my %prog_state=&Apache::lonhtmlcommon::Create_PrgWin($r,'Bubblesheet/Submissions Comparison Status',
                   8114:                                     'Progress of Bubblesheet Data/Submission Records Comparison',$count,
1.523     raeburn  8115:                                     'inline',undef,'checkscantron');
1.546     raeburn  8116:     my ($username,$domain,$started);
1.582     raeburn  8117:     my $nav_error;
                   8118:     &scantron_get_maxbubble(\$nav_error); # Need the bubble lines array to parse.
                   8119:     if ($nav_error) {
                   8120:         $r->print(&navmap_errormsg());
                   8121:         return '';
                   8122:     }
1.523     raeburn  8123: 
                   8124:     &Apache::lonhtmlcommon::Update_PrgWin($r,\%prog_state,
                   8125:                                           'Processing first student');
                   8126:     my $start=&Time::HiRes::time();
                   8127:     my $i=-1;
                   8128: 
                   8129:     while ($i<$scanlines->{'count'}) {
                   8130:         ($username,$domain,$uname)=('','','');
                   8131:         $i++;
                   8132:         my $line=&Apache::grades::scantron_get_line($scanlines,$scan_data,$i);
                   8133:         if ($line=~/^[\s\cz]*$/) { next; }
                   8134:         if ($started) {
                   8135:             &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state,
                   8136:                                                      'last student');
                   8137:         }
                   8138:         $started=1;
                   8139:         my $scan_record=
                   8140:             &Apache::grades::scantron_parse_scanline($line,$i,\%scantron_config,
                   8141:                                                      $scan_data);
                   8142:         unless ($uname=&Apache::grades::scantron_find_student($scan_record,$scan_data,
                   8143:                                                               \%idmap,$i)) {
                   8144:             &Apache::grades::scantron_add_delay(\@delayqueue,$line,
                   8145:                                 'Unable to find a student that matches',1);
                   8146:             next;
                   8147:         }
                   8148:         if (exists $completedstudents{$uname}) {
                   8149:             &Apache::grades::scantron_add_delay(\@delayqueue,$line,
                   8150:                                 'Student '.$uname.' has multiple sheets',2);
                   8151:             next;
                   8152:         }
                   8153:         my $pid = $scan_record->{'scantron.ID'};
                   8154:         $lastname{$pid} = $scan_record->{'scantron.LastName'};
                   8155:         push(@{$bylast{$lastname{$pid}}},$pid);
                   8156:         my $lastpos = $env{'form.scantron_maxbubble'}*$scantron_config{'Qlength'};
                   8157:         $scandata{$pid} = substr($line,$scantron_config{'Qstart'}-1,$lastpos);
                   8158:         chomp($scandata{$pid});
                   8159:         $scandata{$pid} =~ s/\r$//;
                   8160:         ($username,$domain)=split(/:/,$uname);
                   8161:         my $counter = -1;
                   8162:         foreach my $resource (@resources) {
1.557     raeburn  8163:             my $parts;
1.554     raeburn  8164:             my $ressymb = $resource->symb();
1.557     raeburn  8165:             if ((exists($grader_randomlists_by_symb{$ressymb})) ||
                   8166:                 (ref($grader_partids_by_symb{$ressymb}) ne 'ARRAY')) {
                   8167:                 (my $analysis,$parts) =
                   8168:                     &scantron_partids_tograde($resource,$env{'request.course.id'},$username,$domain);
                   8169:             } else {
                   8170:                 $parts = $grader_partids_by_symb{$ressymb};
                   8171:             }
1.542     raeburn  8172:             ($counter,my $recording) =
                   8173:                 &verify_scantron_grading($resource,$domain,$username,$cid,$counter,
1.554     raeburn  8174:                                          $scandata{$pid},$parts,
1.542     raeburn  8175:                                          \%scantron_config,\%lettdig,$numletts);
                   8176:             $record{$pid} .= $recording;
1.523     raeburn  8177:         }
                   8178:     }
                   8179:     &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
                   8180:     $r->print('<br />');
                   8181:     my ($okstudents,$badstudents,$numstudents,$passed,$failed);
                   8182:     $passed = 0;
                   8183:     $failed = 0;
                   8184:     $numstudents = 0;
                   8185:     foreach my $last (sort(keys(%bylast))) {
                   8186:         if (ref($bylast{$last}) eq 'ARRAY') {
                   8187:             foreach my $pid (sort(@{$bylast{$last}})) {
                   8188:                 my $showscandata = $scandata{$pid};
                   8189:                 my $showrecord = $record{$pid};
                   8190:                 $showscandata =~ s/\s/&nbsp;/g;
                   8191:                 $showrecord =~ s/\s/&nbsp;/g;
                   8192:                 if ($scandata{$pid} eq $record{$pid}) {
                   8193:                     my $css_class = ($passed % 2)?'LC_odd_row':'LC_even_row';
                   8194:                     $okstudents .= '<tr class="'.$css_class.'">'.
1.581     www      8195: '<td>'.&mt('Bubblesheet').'</td><td>'.$showscandata.'</td><td rowspan="2">'.$last.'</td><td rowspan="2">'.$pid.'</td>'."\n".
1.523     raeburn  8196: '</tr>'."\n".
                   8197: '<tr class="'.$css_class.'">'."\n".
                   8198: '<td>Submissions</td><td>'.$showrecord.'</td></tr>'."\n";
                   8199:                     $passed ++;
                   8200:                 } else {
                   8201:                     my $css_class = ($failed % 2)?'LC_odd_row':'LC_even_row';
1.581     www      8202:                     $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  8203: '</tr>'."\n".
                   8204: '<tr class="'.$css_class.'">'."\n".
                   8205: '<td>Submissions</td><td><span class="LC_nobreak">'.$record{$pid}.'</span></td>'."\n".
                   8206: '</tr>'."\n";
                   8207:                     $failed ++;
                   8208:                 }
                   8209:                 $numstudents ++;
                   8210:             }
                   8211:         }
                   8212:     }
1.572     www      8213:     $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  8214:     $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>');
                   8215:     if ($passed) {
1.572     www      8216:         $r->print(&mt('Students with exact correspondence between bubblesheet data and submissions are as follows:').'<br /><br />');
1.523     raeburn  8217:         $r->print(&Apache::loncommon::start_data_table()."\n".
                   8218:                  &Apache::loncommon::start_data_table_header_row()."\n".
                   8219:                  '<th>'.&mt('Source').'</th><th>'.&mt('Bubble records').'</th><th>'.&mt('Name').'</th><th>'.&mt('ID').'</th>'.
                   8220:                  &Apache::loncommon::end_data_table_header_row()."\n".
                   8221:                  $okstudents."\n".
                   8222:                  &Apache::loncommon::end_data_table().'<br />');
                   8223:     }
                   8224:     if ($failed) {
1.572     www      8225:         $r->print(&mt('Students with differences between bubblesheet data and submissions are as follows:').'<br /><br />');
1.523     raeburn  8226:         $r->print(&Apache::loncommon::start_data_table()."\n".
                   8227:                  &Apache::loncommon::start_data_table_header_row()."\n".
                   8228:                  '<th>'.&mt('Source').'</th><th>'.&mt('Bubble records').'</th><th>'.&mt('Name').'</th><th>'.&mt('ID').'</th>'.
                   8229:                  &Apache::loncommon::end_data_table_header_row()."\n".
                   8230:                  $badstudents."\n".
                   8231:                  &Apache::loncommon::end_data_table()).'<br />'.
1.572     www      8232:                  &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  8233:     }
1.614     www      8234:     $r->print('</form><br />');
1.523     raeburn  8235:     return;
                   8236: }
                   8237: 
1.542     raeburn  8238: sub verify_scantron_grading {
1.554     raeburn  8239:     my ($resource,$domain,$username,$cid,$counter,$scandata,$partids,
1.542     raeburn  8240:         $scantron_config,$lettdig,$numletts) = @_;
                   8241:     my ($record,%expected,%startpos);
                   8242:     return ($counter,$record) if (!ref($resource));
                   8243:     return ($counter,$record) if (!$resource->is_problem());
                   8244:     my $symb = $resource->symb();
1.554     raeburn  8245:     return ($counter,$record) if (ref($partids) ne 'ARRAY');
                   8246:     foreach my $part_id (@{$partids}) {
1.542     raeburn  8247:         $counter ++;
                   8248:         $expected{$part_id} = 0;
                   8249:         if ($env{"form.scantron.sub_bubblelines.$counter"}) {
                   8250:             my @sub_lines = split(/,/,$env{"form.scantron.sub_bubblelines.$counter"});
                   8251:             foreach my $item (@sub_lines) {
                   8252:                 $expected{$part_id} += $item;
                   8253:             }
                   8254:         } else {
                   8255:             $expected{$part_id} = $env{"form.scantron.bubblelines.$counter"};
                   8256:         }
                   8257:         $startpos{$part_id} = $env{"form.scantron.first_bubble_line.$counter"};
                   8258:     }
                   8259:     if ($symb) {
                   8260:         my %recorded;
                   8261:         my (%returnhash) = &Apache::lonnet::restore($symb,$cid,$domain,$username);
                   8262:         if ($returnhash{'version'}) {
                   8263:             my %lasthash=();
                   8264:             my $version;
                   8265:             for ($version=1;$version<=$returnhash{'version'};$version++) {
                   8266:                 foreach my $key (sort(split(/\:/,$returnhash{$version.':keys'}))) {
                   8267:                     $lasthash{$key}=$returnhash{$version.':'.$key};
                   8268:                 }
                   8269:             }
                   8270:             foreach my $key (keys(%lasthash)) {
                   8271:                 if ($key =~ /\.scantron$/) {
                   8272:                     my $value = &unescape($lasthash{$key});
                   8273:                     my ($part_id) = ($key =~ /^resource\.(.+)\.scantron$/);
                   8274:                     if ($value eq '') {
                   8275:                         for (my $i=0; $i<$expected{$part_id}; $i++) {
                   8276:                             for (my $j=0; $j<$scantron_config->{'length'}; $j++) {
                   8277:                                 $recorded{$part_id} .= $scantron_config->{'Qoff'};
                   8278:                             }
                   8279:                         }
                   8280:                     } else {
                   8281:                         my @tocheck;
                   8282:                         my @items = split(//,$value);
                   8283:                         if (($scantron_config->{'Qon'} eq 'letter') ||
                   8284:                             ($scantron_config->{'Qon'} eq 'number')) {
                   8285:                             if (@items < $expected{$part_id}) {
                   8286:                                 my $fragment = substr($scandata,$startpos{$part_id},$expected{$part_id});
                   8287:                                 my @singles = split(//,$fragment);
                   8288:                                 foreach my $pos (@singles) {
                   8289:                                     if ($pos eq ' ') {
                   8290:                                         push(@tocheck,$pos);
                   8291:                                     } else {
                   8292:                                         my $next = shift(@items);
                   8293:                                         push(@tocheck,$next);
                   8294:                                     }
                   8295:                                 }
                   8296:                             } else {
                   8297:                                 @tocheck = @items;
                   8298:                             }
                   8299:                             foreach my $letter (@tocheck) {
                   8300:                                 if ($scantron_config->{'Qon'} eq 'letter') {
                   8301:                                     if ($letter !~ /^[A-J]$/) {
                   8302:                                         $letter = $scantron_config->{'Qoff'};
                   8303:                                     }
                   8304:                                     $recorded{$part_id} .= $letter;
                   8305:                                 } elsif ($scantron_config->{'Qon'} eq 'number') {
                   8306:                                     my $digit;
                   8307:                                     if ($letter !~ /^[A-J]$/) {
                   8308:                                         $digit = $scantron_config->{'Qoff'};
                   8309:                                     } else {
                   8310:                                         $digit = $lettdig->{$letter};
                   8311:                                     }
                   8312:                                     $recorded{$part_id} .= $digit;
                   8313:                                 }
                   8314:                             }
                   8315:                         } else {
                   8316:                             @tocheck = @items;
                   8317:                             for (my $i=0; $i<$expected{$part_id}; $i++) {
                   8318:                                 my $curr_sub = shift(@tocheck);
                   8319:                                 my $digit;
                   8320:                                 if ($curr_sub =~ /^[A-J]$/) {
                   8321:                                     $digit = $lettdig->{$curr_sub}-1;
                   8322:                                 }
                   8323:                                 if ($curr_sub eq 'J') {
                   8324:                                     $digit += scalar($numletts);
                   8325:                                 }
                   8326:                                 for (my $j=0; $j<$scantron_config->{'Qlength'}; $j++) {
                   8327:                                     if ($j == $digit) {
                   8328:                                         $recorded{$part_id} .= $scantron_config->{'Qon'};
                   8329:                                     } else {
                   8330:                                         $recorded{$part_id} .= $scantron_config->{'Qoff'};
                   8331:                                     }
                   8332:                                 }
                   8333:                             }
                   8334:                         }
                   8335:                     }
                   8336:                 }
                   8337:             }
                   8338:         }
1.554     raeburn  8339:         foreach my $part_id (@{$partids}) {
1.542     raeburn  8340:             if ($recorded{$part_id} eq '') {
                   8341:                 for (my $i=0; $i<$expected{$part_id}; $i++) {
                   8342:                     for (my $j=0; $j<$scantron_config->{'Qlength'}; $j++) {
                   8343:                         $recorded{$part_id} .= $scantron_config->{'Qoff'};
                   8344:                     }
                   8345:                 }
                   8346:             }
                   8347:             $record .= $recorded{$part_id};
                   8348:         }
                   8349:     }
                   8350:     return ($counter,$record);
                   8351: }
                   8352: 
                   8353: sub letter_to_digits { 
                   8354:     my %lettdig = (
                   8355:                     A => 1,
                   8356:                     B => 2,
                   8357:                     C => 3,
                   8358:                     D => 4,
                   8359:                     E => 5,
                   8360:                     F => 6,
                   8361:                     G => 7,
                   8362:                     H => 8,
                   8363:                     I => 9,
                   8364:                     J => 0,
                   8365:                   );
                   8366:     return %lettdig;
                   8367: }
                   8368: 
1.423     albertel 8369: 
1.75      albertel 8370: #-------- end of section for handling grading scantron forms -------
                   8371: #
                   8372: #-------------------------------------------------------------------
                   8373: 
1.72      ng       8374: #-------------------------- Menu interface -------------------------
                   8375: #
1.614     www      8376: #--- Href with symb and command ---
                   8377: 
                   8378: sub href_symb_cmd {
                   8379:     my ($symb,$cmd)=@_;
                   8380:     return '/adm/grades?symb='.&HTML::Entities::encode(&Apache::lonenc::check_encrypt($symb),'<>&"').'&command='.$cmd;
1.72      ng       8381: }
                   8382: 
1.443     banghart 8383: sub grading_menu {
1.608     www      8384:     my ($request,$symb) = @_;
1.443     banghart 8385:     if (!$symb) {return '';}
                   8386: 
                   8387:     my %fields = ('symb'=>&Apache::lonenc::check_encrypt($symb),
1.618     www      8388:                   'command'=>'individual');
1.538     schulted 8389:     
1.598     www      8390:     my $url1a = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   8391: 
                   8392:     $fields{'command'}='ungraded';
                   8393:     my $url1b=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   8394: 
                   8395:     $fields{'command'}='table';
                   8396:     my $url1c=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   8397: 
                   8398:     $fields{'command'}='all_for_one';
                   8399:     my $url1d=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   8400: 
1.621     www      8401:     $fields{'command'}='downloadfilesselect';
                   8402:     my $url1e=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   8403: 
1.443     banghart 8404:     $fields{'command'} = 'csvform';
1.538     schulted 8405:     my $url2 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   8406:     
1.443     banghart 8407:     $fields{'command'} = 'processclicker';
1.538     schulted 8408:     my $url3 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   8409:     
1.443     banghart 8410:     $fields{'command'} = 'scantron_selectphase';
1.538     schulted 8411:     my $url4 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
1.602     www      8412: 
                   8413:     $fields{'command'} = 'initialverifyreceipt';
                   8414:     my $url5 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
1.538     schulted 8415:     
1.598     www      8416:     my @menu = ({	categorytitle=>'Hand Grading',
1.538     schulted 8417:             items =>[
1.598     www      8418:                         {	linktext => 'Select individual students to grade',
                   8419:                     		url => $url1a,
1.538     schulted 8420:                     		permission => 'F',
                   8421:                     		icon => 'edit-find-replace.png',
1.598     www      8422:                     		linktitle => 'Grade current resource for a selection of students.'
                   8423:                         }, 
                   8424:                         {       linktext => 'Grade ungraded submissions.',
                   8425:                                 url => $url1b,
                   8426:                                 permission => 'F',
                   8427:                                 icon => 'edit-find-replace.png',
                   8428:                                 linktitle => 'Grade all submissions that have not been graded yet.'
1.538     schulted 8429:                         },
1.598     www      8430: 
                   8431:                         {       linktext => 'Grading table',
                   8432:                                 url => $url1c,
                   8433:                                 permission => 'F',
                   8434:                                 icon => 'edit-find-replace.png',
                   8435:                                 linktitle => 'Grade current resource for all students.'
                   8436:                         },
1.615     www      8437:                         {       linktext => 'Grade page/folder for one student',
1.598     www      8438:                                 url => $url1d,
                   8439:                                 permission => 'F',
                   8440:                                 icon => 'edit-find-replace.png',
                   8441:                                 linktitle => 'Grade all resources in current page/sequence/folder for one student.'
1.621     www      8442:                         },
                   8443:                         {       linktext => 'Download submissions',
                   8444:                                 url => $url1e,
                   8445:                                 permission => 'F',
                   8446:                                 icon => 'edit-find-replace.png',
                   8447:                                 linktitle => 'Download all students submissions.'
1.598     www      8448:                         }]},
                   8449:                          { categorytitle=>'Automated Grading',
                   8450:                items =>[
                   8451: 
1.538     schulted 8452:                 	    {	linktext => 'Upload Scores',
                   8453:                     		url => $url2,
                   8454:                     		permission => 'F',
                   8455:                     		icon => 'uploadscores.png',
                   8456:                     		linktitle => 'Specify a file containing the class scores for current resource.'
                   8457:                 	    },
                   8458:                 	    {	linktext => 'Process Clicker',
                   8459:                     		url => $url3,
                   8460:                     		permission => 'F',
                   8461:                     		icon => 'addClickerInfoFile.png',
                   8462:                     		linktitle => 'Specify a file containing the clicker information for this resource.'
                   8463:                 	    },
1.587     raeburn  8464:                 	    {	linktext => 'Grade/Manage/Review Bubblesheets',
1.538     schulted 8465:                     		url => $url4,
                   8466:                     		permission => 'F',
                   8467:                     		icon => 'stat.png',
                   8468:                     		linktitle => 'Grade scantron exams, upload/download scantron data files, and review previously graded scantron exams.'
1.602     www      8469:                 	    },
1.616     www      8470:                             {   linktext => 'Verify Receipt Number',
1.602     www      8471:                                 url => $url5,
                   8472:                                 permission => 'F',
                   8473:                                 icon => 'edit-find-replace.png',
                   8474:                                 linktitle => 'Verify a system-generated receipt number for correct problem solution.'
                   8475:                             }
                   8476: 
1.538     schulted 8477:                     ]
                   8478:             });
                   8479: 
1.443     banghart 8480:     # Create the menu
                   8481:     my $Str;
1.445     banghart 8482:     $Str .= '<form method="post" action="" name="gradingMenu">';
                   8483:     $Str .= '<input type="hidden" name="command" value="" />'.
1.618     www      8484:     	'<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
1.445     banghart 8485: 
1.602     www      8486:     $Str .= &Apache::lonhtmlcommon::generate_menu(@menu);
1.443     banghart 8487:     return $Str;    
                   8488: }
                   8489: 
1.598     www      8490: 
                   8491: sub ungraded {
                   8492:     my ($request)=@_;
                   8493:     &submit_options($request);
                   8494: }
                   8495: 
1.599     www      8496: sub submit_options_sequence {
1.608     www      8497:     my ($request,$symb) = @_;
1.599     www      8498:     if (!$symb) {return '';}
1.600     www      8499:     &commonJSfunctions($request);
                   8500:     my $result;
1.599     www      8501: 
1.600     www      8502:     $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
1.618     www      8503:         '<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
1.600     www      8504:     $result.='
                   8505: <h2>
1.615     www      8506:   '.&mt('Grade page/folder for one student').'
1.601     www      8507: </h2>'.
                   8508:             &selectfield(0).
                   8509:             '<input type="hidden" name="command" value="pickStudentPage" />
1.600     www      8510:             <div>
                   8511:               <input type="submit" value="'.&mt('Next').' &rarr;" />
                   8512:             </div>
                   8513:         </div>
                   8514:   </form>';
                   8515:     return $result;
                   8516: }
                   8517: 
                   8518: sub submit_options_table {
1.608     www      8519:     my ($request,$symb) = @_;
1.600     www      8520:     if (!$symb) {return '';}
1.599     www      8521:     &commonJSfunctions($request);
                   8522:     my $result;
                   8523: 
                   8524:     $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
1.618     www      8525:         '<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
1.599     www      8526: 
                   8527:     $result.='
                   8528: <h2>
1.600     www      8529:   '.&mt('Grading table').'
1.601     www      8530: </h2>'.
                   8531:             &selectfield(0).
                   8532:             '<input type="hidden" name="command" value="viewgrades" />
1.599     www      8533:             <div>
                   8534:               <input type="submit" value="'.&mt('Next').' &rarr;" />
                   8535:             </div>
                   8536:         </div>
                   8537:   </form>';
                   8538:     return $result;
                   8539: }
1.443     banghart 8540: 
1.621     www      8541: sub submit_options_download {
                   8542:     my ($request,$symb) = @_;
                   8543:     if (!$symb) {return '';}
                   8544: 
                   8545:     &commonJSfunctions($request);
                   8546: 
                   8547:     my $result='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
                   8548:         '<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
                   8549:     $result.='
                   8550: <h2>
                   8551:   '.&mt('Select Students for Which to Download Submissions').'
                   8552: </h2>'.&selectfield(1).'
                   8553:                 <input type="hidden" name="command" value="downloadfileslink" /> 
                   8554:               <input type="submit" value="'.&mt('Next').' &rarr;" />
                   8555:             </div>
                   8556:           </div>
1.600     www      8557: 
                   8558: 
1.621     www      8559:   </form>';
                   8560:     return $result;
                   8561: }
                   8562: 
1.443     banghart 8563: #--- Displays the submissions first page -------
                   8564: sub submit_options {
1.608     www      8565:     my ($request,$symb) = @_;
1.72      ng       8566:     if (!$symb) {return '';}
                   8567: 
1.118     ng       8568:     &commonJSfunctions($request);
1.473     albertel 8569:     my $result;
1.533     bisitz   8570: 
1.72      ng       8571:     $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
1.618     www      8572: 	'<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
1.472     albertel 8573:     $result.='
1.533     bisitz   8574: <h2>
1.600     www      8575:   '.&mt('Select individual students to grade').'
1.601     www      8576: </h2>'.&selectfield(1).'
                   8577:                 <input type="hidden" name="command" value="submission" /> 
                   8578: 	      <input type="submit" value="'.&mt('Next').' &rarr;" />
                   8579:             </div>
                   8580:           </div>
                   8581: 
                   8582: 
                   8583:   </form>';
                   8584:     return $result;
                   8585: }
1.533     bisitz   8586: 
1.601     www      8587: sub selectfield {
                   8588:    my ($full)=@_;
                   8589:    my $result='<div class="LC_columnSection">
1.537     harmsja  8590:   
1.533     bisitz   8591:     <fieldset>
                   8592:       <legend>
                   8593:        '.&mt('Sections').'
                   8594:       </legend>
1.601     www      8595:       '.&Apache::lonstatistics::SectionSelect('section','multiple',5).'
1.533     bisitz   8596:     </fieldset>
1.537     harmsja  8597:   
1.533     bisitz   8598:     <fieldset>
                   8599:       <legend>
                   8600:         '.&mt('Groups').'
                   8601:       </legend>
                   8602:       '.&Apache::lonstatistics::GroupSelect('group','multiple',5).'
                   8603:     </fieldset>
1.537     harmsja  8604:   
1.533     bisitz   8605:     <fieldset>
                   8606:       <legend>
                   8607:         '.&mt('Access Status').'
                   8608:       </legend>
1.601     www      8609:       '.&Apache::lonhtmlcommon::StatusOptions(undef,undef,5,undef,'mult').'
                   8610:     </fieldset>';
                   8611:     if ($full) {
                   8612:        $result.='
1.533     bisitz   8613:     <fieldset>
                   8614:       <legend>
                   8615:         '.&mt('Submission Status').'
1.601     www      8616:       </legend>'.
                   8617:        &Apache::loncommon::select_form('all','submitonly',
                   8618:           (&Apache::lonlocal::texthash(
                   8619:              'yes'       => 'with submissions',
                   8620:              'queued'    => 'in grading queue',
                   8621:              'graded'    => 'with ungraded submissions',
                   8622:              'incorrect' => 'with incorrect submissions',
                   8623:              'all'       => 'with any status'),
                   8624:              'select_form_order' => ['yes','queued','graded','incorrect','all'])).
                   8625:    '</fieldset>';
                   8626:     }
                   8627:     $result.='</div><br />';
1.44      ng       8628:     return $result;
1.2       albertel 8629: }
                   8630: 
1.285     albertel 8631: sub reset_perm {
                   8632:     undef(%perm);
                   8633: }
                   8634: 
                   8635: sub init_perm {
                   8636:     &reset_perm();
1.300     albertel 8637:     foreach my $test_perm ('vgr','mgr','opa') {
                   8638: 
                   8639: 	my $scope = $env{'request.course.id'};
                   8640: 	if (!($perm{$test_perm}=&Apache::lonnet::allowed($test_perm,$scope))) {
                   8641: 
                   8642: 	    $scope .= '/'.$env{'request.course.sec'};
                   8643: 	    if ( $perm{$test_perm}=
                   8644: 		 &Apache::lonnet::allowed($test_perm,$scope)) {
                   8645: 		$perm{$test_perm.'_section'}=$env{'request.course.sec'};
                   8646: 	    } else {
                   8647: 		delete($perm{$test_perm});
                   8648: 	    }
1.285     albertel 8649: 	}
                   8650:     }
                   8651: }
                   8652: 
1.400     www      8653: sub gather_clicker_ids {
1.408     albertel 8654:     my %clicker_ids;
1.400     www      8655: 
                   8656:     my $classlist = &Apache::loncoursedata::get_classlist();
                   8657: 
                   8658:     # Set up a couple variables.
1.407     albertel 8659:     my $username_idx = &Apache::loncoursedata::CL_SNAME();
                   8660:     my $domain_idx   = &Apache::loncoursedata::CL_SDOM();
1.438     www      8661:     my $status_idx   = &Apache::loncoursedata::CL_STATUS();
1.400     www      8662: 
1.407     albertel 8663:     foreach my $student (keys(%$classlist)) {
1.438     www      8664:         if ($classlist->{$student}->[$status_idx] ne 'Active') { next; }
1.407     albertel 8665:         my $username = $classlist->{$student}->[$username_idx];
                   8666:         my $domain   = $classlist->{$student}->[$domain_idx];
1.400     www      8667:         my $clickers =
1.408     albertel 8668: 	    (&Apache::lonnet::userenvironment($domain,$username,'clickers'))[1];
1.400     www      8669:         foreach my $id (split(/\,/,$clickers)) {
1.414     www      8670:             $id=~s/^[\#0]+//;
1.421     www      8671:             $id=~s/[\-\:]//g;
1.407     albertel 8672:             if (exists($clicker_ids{$id})) {
1.408     albertel 8673: 		$clicker_ids{$id}.=','.$username.':'.$domain;
1.400     www      8674:             } else {
1.408     albertel 8675: 		$clicker_ids{$id}=$username.':'.$domain;
1.400     www      8676:             }
                   8677:         }
                   8678:     }
1.407     albertel 8679:     return %clicker_ids;
1.400     www      8680: }
                   8681: 
1.402     www      8682: sub gather_adv_clicker_ids {
1.408     albertel 8683:     my %clicker_ids;
1.402     www      8684:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
                   8685:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   8686:     my %coursepersonnel=&Apache::lonnet::get_course_adv_roles($cdom.'/'.$cnum);
1.409     albertel 8687:     foreach my $element (sort(keys(%coursepersonnel))) {
1.402     www      8688:         foreach my $person (split(/\,/,$coursepersonnel{$element})) {
                   8689:             my ($puname,$pudom)=split(/\:/,$person);
                   8690:             my $clickers =
1.408     albertel 8691: 		(&Apache::lonnet::userenvironment($pudom,$puname,'clickers'))[1];
1.405     www      8692:             foreach my $id (split(/\,/,$clickers)) {
1.414     www      8693: 		$id=~s/^[\#0]+//;
1.421     www      8694:                 $id=~s/[\-\:]//g;
1.408     albertel 8695: 		if (exists($clicker_ids{$id})) {
                   8696: 		    $clicker_ids{$id}.=','.$puname.':'.$pudom;
                   8697: 		} else {
                   8698: 		    $clicker_ids{$id}=$puname.':'.$pudom;
                   8699: 		}
1.405     www      8700:             }
1.402     www      8701:         }
                   8702:     }
1.407     albertel 8703:     return %clicker_ids;
1.402     www      8704: }
                   8705: 
1.413     www      8706: sub clicker_grading_parameters {
                   8707:     return ('gradingmechanism' => 'scalar',
                   8708:             'upfiletype' => 'scalar',
                   8709:             'specificid' => 'scalar',
                   8710:             'pcorrect' => 'scalar',
                   8711:             'pincorrect' => 'scalar');
                   8712: }
                   8713: 
1.400     www      8714: sub process_clicker {
1.608     www      8715:     my ($r,$symb)=@_;
1.400     www      8716:     if (!$symb) {return '';}
                   8717:     my $result=&checkforfile_js();
                   8718:     $result.='<br /><table width="100%" border="0"><tr><td bgcolor="#777777">'."\n";
                   8719:     $result.='<table width="100%" border="0"><tr bgcolor="#e6ffff"><td>'."\n";
1.538     schulted 8720:     $result.='&nbsp;<b>'.&mt('Specify a file containing the clicker information for this resource.').
                   8721:         '</b></td></tr>'."\n";
1.601     www      8722:     $result.='<tr bgcolor="#ffffe6"><td>'."\n";
1.413     www      8723: # Attempt to restore parameters from last session, set defaults if not present
                   8724:     my %Saveable_Parameters=&clicker_grading_parameters();
                   8725:     &Apache::loncommon::restore_course_settings('grades_clicker',
                   8726:                                                  \%Saveable_Parameters);
                   8727:     if (!$env{'form.pcorrect'}) { $env{'form.pcorrect'}=100; }
                   8728:     if (!$env{'form.pincorrect'}) { $env{'form.pincorrect'}=100; }
                   8729:     if (!$env{'form.gradingmechanism'}) { $env{'form.gradingmechanism'}='attendance'; }
                   8730:     if (!$env{'form.upfiletype'}) { $env{'form.upfiletype'}='iclicker'; }
                   8731: 
                   8732:     my %checked;
1.521     www      8733:     foreach my $gradingmechanism ('attendance','personnel','specific','given') {
1.413     www      8734:        if ($env{'form.gradingmechanism'} eq $gradingmechanism) {
1.569     bisitz   8735:           $checked{$gradingmechanism}=' checked="checked"';
1.413     www      8736:        }
                   8737:     }
                   8738: 
1.400     www      8739:     my $upload=&mt("Upload File");
                   8740:     my $type=&mt("Type");
1.402     www      8741:     my $attendance=&mt("Award points just for participation");
                   8742:     my $personnel=&mt("Correctness determined from response by course personnel");
1.414     www      8743:     my $specific=&mt("Correctness determined from response with clicker ID(s)"); 
1.521     www      8744:     my $given=&mt("Correctness determined from given list of answers").' '.
                   8745:               '<font size="-2"><tt>('.&mt("Provide comma-separated list. Use '*' for any answer correct, '-' for skip").')</tt></font>';
1.402     www      8746:     my $pcorrect=&mt("Percentage points for correct solution");
                   8747:     my $pincorrect=&mt("Percentage points for incorrect solution");
1.413     www      8748:     my $selectform=&Apache::loncommon::select_form($env{'form.upfiletype'},'upfiletype',
1.419     www      8749: 						   ('iclicker' => 'i>clicker',
                   8750:                                                     'interwrite' => 'interwrite PRS'));
1.418     albertel 8751:     $symb = &Apache::lonenc::check_encrypt($symb);
1.597     wenzelju 8752:     $result.= &Apache::lonhtmlcommon::scripttag(<<ENDUPFORM);
1.402     www      8753: function sanitycheck() {
                   8754: // Accept only integer percentages
                   8755:    document.forms.gradesupload.pcorrect.value=Math.round(document.forms.gradesupload.pcorrect.value);
                   8756:    document.forms.gradesupload.pincorrect.value=Math.round(document.forms.gradesupload.pincorrect.value);
                   8757: // Find out grading choice
                   8758:    for (i=0; i<document.forms.gradesupload.gradingmechanism.length; i++) {
                   8759:       if (document.forms.gradesupload.gradingmechanism[i].checked) {
                   8760:          gradingchoice=document.forms.gradesupload.gradingmechanism[i].value;
                   8761:       }
                   8762:    }
                   8763: // By default, new choice equals user selection
                   8764:    newgradingchoice=gradingchoice;
                   8765: // Not good to give more points for false answers than correct ones
                   8766:    if (Math.round(document.forms.gradesupload.pcorrect.value)<Math.round(document.forms.gradesupload.pincorrect.value)) {
                   8767:       document.forms.gradesupload.pcorrect.value=document.forms.gradesupload.pincorrect.value;
                   8768:    }
                   8769: // If new choice is attendance only, and old choice was correctness-based, restore defaults
                   8770:    if ((gradingchoice=='attendance') && (document.forms.gradesupload.waschecked.value!='attendance')) {
                   8771:       document.forms.gradesupload.pcorrect.value=100;
                   8772:       document.forms.gradesupload.pincorrect.value=100;
                   8773:    }
                   8774: // If the values are different, cannot be attendance only
                   8775:    if ((Math.round(document.forms.gradesupload.pcorrect.value)!=Math.round(document.forms.gradesupload.pincorrect.value)) &&
                   8776:        (gradingchoice=='attendance')) {
                   8777:        newgradingchoice='personnel';
                   8778:    }
                   8779: // Change grading choice to new one
                   8780:    for (i=0; i<document.forms.gradesupload.gradingmechanism.length; i++) {
                   8781:       if (document.forms.gradesupload.gradingmechanism[i].value==newgradingchoice) {
                   8782:          document.forms.gradesupload.gradingmechanism[i].checked=true;
                   8783:       } else {
                   8784:          document.forms.gradesupload.gradingmechanism[i].checked=false;
                   8785:       }
                   8786:    }
                   8787: // Remember the old state
                   8788:    document.forms.gradesupload.waschecked.value=newgradingchoice;
                   8789: }
1.597     wenzelju 8790: ENDUPFORM
                   8791:     $result.= <<ENDUPFORM;
1.400     www      8792: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
                   8793: <input type="hidden" name="symb" value="$symb" />
                   8794: <input type="hidden" name="command" value="processclickerfile" />
                   8795: <input type="file" name="upfile" size="50" />
                   8796: <br /><label>$type: $selectform</label>
1.589     bisitz   8797: <br /><label><input type="radio" name="gradingmechanism" value="attendance"$checked{'attendance'} onclick="sanitycheck()" />$attendance </label>
                   8798: <br /><label><input type="radio" name="gradingmechanism" value="personnel"$checked{'personnel'} onclick="sanitycheck()" />$personnel</label>
                   8799: <br /><label><input type="radio" name="gradingmechanism" value="specific"$checked{'specific'} onclick="sanitycheck()" />$specific </label>
1.414     www      8800: <input type="text" name="specificid" value="$env{'form.specificid'}" size="20" />
1.589     bisitz   8801: <br /><label><input type="radio" name="gradingmechanism" value="given"$checked{'given'} onclick="sanitycheck()" />$given </label>
1.521     www      8802: <br />&nbsp;&nbsp;&nbsp;
                   8803: <input type="text" name="givenanswer" size="50" />
1.413     www      8804: <input type="hidden" name="waschecked" value="$env{'form.gradingmechanism'}" />
1.589     bisitz   8805: <br /><label>$pcorrect: <input type="text" name="pcorrect" size="4" value="$env{'form.pcorrect'}" onchange="sanitycheck()" /></label>
                   8806: <br /><label>$pincorrect: <input type="text" name="pincorrect" size="4" value="$env{'form.pincorrect'}" onchange="sanitycheck()" /></label>
                   8807: <br /><input type="button" onclick="javascript:checkUpload(this.form);" value="$upload" />
1.597     wenzelju 8808: </form>'
1.400     www      8809: ENDUPFORM
                   8810:     $result.='</td></tr></table>'."\n".
                   8811:              '</td></tr></table><br /><br />'."\n";
                   8812:     return $result;
                   8813: }
                   8814: 
                   8815: sub process_clicker_file {
1.608     www      8816:     my ($r,$symb)=@_;
1.400     www      8817:     if (!$symb) {return '';}
1.413     www      8818: 
                   8819:     my %Saveable_Parameters=&clicker_grading_parameters();
                   8820:     &Apache::loncommon::store_course_settings('grades_clicker',
                   8821:                                               \%Saveable_Parameters);
1.598     www      8822:     my $result='';
1.404     www      8823:     if (($env{'form.gradingmechanism'} eq 'specific') && ($env{'form.specificid'}!~/\w/)) {
1.408     albertel 8824: 	$result.='<span class="LC_error">'.&mt('You need to specify a clicker ID for the correct answer').'</span>';
1.614     www      8825: 	return $result;
1.404     www      8826:     }
1.522     www      8827:     if (($env{'form.gradingmechanism'} eq 'given') && ($env{'form.givenanswer'}!~/\S/)) {
1.521     www      8828:         $result.='<span class="LC_error">'.&mt('You need to specify the correct answer').'</span>';
1.614     www      8829:         return $result;
1.521     www      8830:     }
1.522     www      8831:     my $foundgiven=0;
1.521     www      8832:     if ($env{'form.gradingmechanism'} eq 'given') {
                   8833:         $env{'form.givenanswer'}=~s/^\s*//gs;
                   8834:         $env{'form.givenanswer'}=~s/\s*$//gs;
                   8835:         $env{'form.givenanswer'}=~s/[^a-zA-Z0-9\.\*\-]+/\,/g;
                   8836:         $env{'form.givenanswer'}=uc($env{'form.givenanswer'});
1.522     www      8837:         my @answers=split(/\,/,$env{'form.givenanswer'});
                   8838:         $foundgiven=$#answers+1;
1.521     www      8839:     }
1.407     albertel 8840:     my %clicker_ids=&gather_clicker_ids();
1.408     albertel 8841:     my %correct_ids;
1.404     www      8842:     if ($env{'form.gradingmechanism'} eq 'personnel') {
1.408     albertel 8843: 	%correct_ids=&gather_adv_clicker_ids();
1.404     www      8844:     }
                   8845:     if ($env{'form.gradingmechanism'} eq 'specific') {
1.414     www      8846: 	foreach my $correct_id (split(/[\s\,]/,$env{'form.specificid'})) {;
                   8847: 	   $correct_id=~tr/a-z/A-Z/;
                   8848: 	   $correct_id=~s/\s//gs;
                   8849: 	   $correct_id=~s/^[\#0]+//;
1.421     www      8850:            $correct_id=~s/[\-\:]//g;
1.414     www      8851:            if ($correct_id) {
                   8852: 	      $correct_ids{$correct_id}='specified';
                   8853:            }
                   8854:         }
1.400     www      8855:     }
1.404     www      8856:     if ($env{'form.gradingmechanism'} eq 'attendance') {
1.408     albertel 8857: 	$result.=&mt('Score based on attendance only');
1.521     www      8858:     } elsif ($env{'form.gradingmechanism'} eq 'given') {
1.522     www      8859:         $result.=&mt('Score based on [_1] ([_2] answers)','<tt>'.$env{'form.givenanswer'}.'</tt>',$foundgiven);
1.404     www      8860:     } else {
1.408     albertel 8861: 	my $number=0;
1.411     www      8862: 	$result.='<p><b>'.&mt('Correctness determined by the following IDs').'</b>';
1.408     albertel 8863: 	foreach my $id (sort(keys(%correct_ids))) {
1.411     www      8864: 	    $result.='<br /><tt>'.$id.'</tt> - ';
1.408     albertel 8865: 	    if ($correct_ids{$id} eq 'specified') {
                   8866: 		$result.=&mt('specified');
                   8867: 	    } else {
                   8868: 		my ($uname,$udom)=split(/\:/,$correct_ids{$id});
                   8869: 		$result.=&Apache::loncommon::plainname($uname,$udom);
                   8870: 	    }
                   8871: 	    $number++;
                   8872: 	}
1.411     www      8873:         $result.="</p>\n";
1.408     albertel 8874: 	if ($number==0) {
                   8875: 	    $result.='<span class="LC_error">'.&mt('No IDs found to determine correct answer').'</span>';
1.614     www      8876: 	    return $result;
1.408     albertel 8877: 	}
1.404     www      8878:     }
1.405     www      8879:     if (length($env{'form.upfile'}) < 2) {
1.407     albertel 8880:         $result.=&mt('[_1] Error: [_2] The file you attempted to upload, [_3] contained no information. Please check that you entered the correct filename.',
                   8881: 		     '<span class="LC_error">',
                   8882: 		     '</span>',
                   8883: 		     '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>');
1.614     www      8884:         return $result;
1.405     www      8885:     }
1.410     www      8886: 
                   8887: # Were able to get all the info needed, now analyze the file
                   8888: 
1.411     www      8889:     $result.=&Apache::loncommon::studentbrowser_javascript();
1.418     albertel 8890:     $symb = &Apache::lonenc::check_encrypt($symb);
1.410     www      8891:     my $heading=&mt('Scanning clicker file');
                   8892:     $result.=(<<ENDHEADER);
                   8893: <br /><table width="100%" border="0"><tr><td bgcolor="#777777">
                   8894: <table width="100%" border="0"><tr bgcolor="#e6ffff"><td>
                   8895: <b>$heading</b></td></tr><tr bgcolor=#ffffe6><td>
                   8896: <form method="post" action="/adm/grades" name="clickeranalysis">
                   8897: <input type="hidden" name="symb" value="$symb" />
                   8898: <input type="hidden" name="command" value="assignclickergrades" />
1.411     www      8899: <input type="hidden" name="gradingmechanism" value="$env{'form.gradingmechanism'}" />
                   8900: <input type="hidden" name="pcorrect" value="$env{'form.pcorrect'}" />
                   8901: <input type="hidden" name="pincorrect" value="$env{'form.pincorrect'}" />
1.410     www      8902: ENDHEADER
1.522     www      8903:     if ($env{'form.gradingmechanism'} eq 'given') {
                   8904:        $result.='<input type="hidden" name="correct:given" value="'.$env{'form.givenanswer'}.'" />';
                   8905:     } 
1.408     albertel 8906:     my %responses;
                   8907:     my @questiontitles;
1.405     www      8908:     my $errormsg='';
                   8909:     my $number=0;
                   8910:     if ($env{'form.upfiletype'} eq 'iclicker') {
1.408     albertel 8911: 	($errormsg,$number)=&iclicker_eval(\@questiontitles,\%responses);
1.406     www      8912:     }
1.419     www      8913:     if ($env{'form.upfiletype'} eq 'interwrite') {
                   8914:         ($errormsg,$number)=&interwrite_eval(\@questiontitles,\%responses);
                   8915:     }
1.411     www      8916:     $result.='<br />'.&mt('Found [_1] question(s)',$number).'<br />'.
                   8917:              '<input type="hidden" name="number" value="'.$number.'" />'.
                   8918:              &mt('Awarding [_1] percent for correct and [_2] percent for incorrect responses',
                   8919:                  $env{'form.pcorrect'},$env{'form.pincorrect'}).
                   8920:              '<br />';
1.522     www      8921:     if (($env{'form.gradingmechanism'} eq 'given') && ($number!=$foundgiven)) {
                   8922:        $result.='<span class="LC_error">'.&mt('Number of given answers does not agree with number of questions in file.').'</span>';
1.614     www      8923:        return $result;
1.522     www      8924:     } 
1.414     www      8925: # Remember Question Titles
                   8926: # FIXME: Possibly need delimiter other than ":"
                   8927:     for (my $i=0;$i<$number;$i++) {
                   8928:         $result.='<input type="hidden" name="question:'.$i.'" value="'.
                   8929:                  &HTML::Entities::encode($questiontitles[$i],'"&<>').'" />';
                   8930:     }
1.411     www      8931:     my $correct_count=0;
                   8932:     my $student_count=0;
                   8933:     my $unknown_count=0;
1.414     www      8934: # Match answers with usernames
                   8935: # FIXME: Possibly need delimiter other than ":"
1.409     albertel 8936:     foreach my $id (keys(%responses)) {
1.410     www      8937:        if ($correct_ids{$id}) {
1.414     www      8938:           $result.="\n".'<input type="hidden" name="correct:'.$correct_count.':'.$correct_ids{$id}.'" value="'.$responses{$id}.'" />';
1.411     www      8939:           $correct_count++;
1.410     www      8940:        } elsif ($clicker_ids{$id}) {
1.437     www      8941:           if ($clicker_ids{$id}=~/\,/) {
                   8942: # More than one user with the same clicker!
                   8943:              $result.="\n<hr />".&mt('Clicker registered more than once').": <tt>".$id."</tt><br />";
                   8944:              $result.="\n".'<input type="hidden" name="unknown:'.$id.'" value="'.$responses{$id}.'" />'.
                   8945:                            "<select name='multi".$id."'>";
                   8946:              foreach my $reguser (sort(split(/\,/,$clicker_ids{$id}))) {
                   8947:                  $result.="<option value='".$reguser."'>".&Apache::loncommon::plainname(split(/\:/,$reguser)).' ('.$reguser.')</option>';
                   8948:              }
                   8949:              $result.='</select>';
                   8950:              $unknown_count++;
                   8951:           } else {
                   8952: # Good: found one and only one user with the right clicker
                   8953:              $result.="\n".'<input type="hidden" name="student:'.$clicker_ids{$id}.'" value="'.$responses{$id}.'" />';
                   8954:              $student_count++;
                   8955:           }
1.410     www      8956:        } else {
1.411     www      8957:           $result.="\n<hr />".&mt('Unregistered Clicker')." <tt>".$id."</tt><br />";
                   8958:           $result.="\n".'<input type="hidden" name="unknown:'.$id.'" value="'.$responses{$id}.'" />'.
                   8959:                    "\n".&mt("Username").": <input type='text' name='uname".$id."' />&nbsp;".
                   8960:                    "\n".&mt("Domain").": ".
                   8961:                    &Apache::loncommon::select_dom_form($env{'course.'.$env{'request.course.id'}.'.domain'},'udom'.$id).'&nbsp;'.
                   8962:                    &Apache::loncommon::selectstudent_link('clickeranalysis','uname'.$id,'udom'.$id);
                   8963:           $unknown_count++;
1.410     www      8964:        }
1.405     www      8965:     }
1.412     www      8966:     $result.='<hr />'.
                   8967:              &mt('Found [_1] registered and [_2] unregistered clickers.',$student_count,$unknown_count);
1.521     www      8968:     if (($env{'form.gradingmechanism'} ne 'attendance') && ($env{'form.gradingmechanism'} ne 'given')) {
1.412     www      8969:        if ($correct_count==0) {
                   8970:           $errormsg.="Found no correct answers answers for grading!";
                   8971:        } elsif ($correct_count>1) {
1.414     www      8972:           $result.='<br /><span class="LC_warning">'.&mt("Found [_1] entries for grading!",$correct_count).'</span>';
1.412     www      8973:        }
                   8974:     }
1.428     www      8975:     if ($number<1) {
                   8976:        $errormsg.="Found no questions.";
                   8977:     }
1.412     www      8978:     if ($errormsg) {
                   8979:        $result.='<br /><span class="LC_error">'.&mt($errormsg).'</span>';
                   8980:     } else {
                   8981:        $result.='<br /><input type="submit" name="finalize" value="'.&mt('Finalize Grading').'" />';
                   8982:     }
                   8983:     $result.='</form></td></tr></table>'."\n".
1.410     www      8984:              '</td></tr></table><br /><br />'."\n";
1.614     www      8985:     return $result;
1.400     www      8986: }
                   8987: 
1.405     www      8988: sub iclicker_eval {
1.406     www      8989:     my ($questiontitles,$responses)=@_;
1.405     www      8990:     my $number=0;
                   8991:     my $errormsg='';
                   8992:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
1.410     www      8993:         my %components=&Apache::loncommon::record_sep($line);
                   8994:         my @entries=map {$components{$_}} (sort(keys(%components)));
1.408     albertel 8995: 	if ($entries[0] eq 'Question') {
                   8996: 	    for (my $i=3;$i<$#entries;$i+=6) {
                   8997: 		$$questiontitles[$number]=$entries[$i];
                   8998: 		$number++;
                   8999: 	    }
                   9000: 	}
                   9001: 	if ($entries[0]=~/^\#/) {
                   9002: 	    my $id=$entries[0];
                   9003: 	    my @idresponses;
                   9004: 	    $id=~s/^[\#0]+//;
                   9005: 	    for (my $i=0;$i<$number;$i++) {
                   9006: 		my $idx=3+$i*6;
                   9007: 		push(@idresponses,$entries[$idx]);
                   9008: 	    }
                   9009: 	    $$responses{$id}=join(',',@idresponses);
                   9010: 	}
1.405     www      9011:     }
                   9012:     return ($errormsg,$number);
                   9013: }
                   9014: 
1.419     www      9015: sub interwrite_eval {
                   9016:     my ($questiontitles,$responses)=@_;
                   9017:     my $number=0;
                   9018:     my $errormsg='';
1.420     www      9019:     my $skipline=1;
                   9020:     my $questionnumber=0;
                   9021:     my %idresponses=();
1.419     www      9022:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
                   9023:         my %components=&Apache::loncommon::record_sep($line);
                   9024:         my @entries=map {$components{$_}} (sort(keys(%components)));
1.420     www      9025:         if ($entries[1] eq 'Time') { $skipline=0; next; }
                   9026:         if ($entries[1] eq 'Response') { $skipline=1; }
                   9027:         next if $skipline;
                   9028:         if ($entries[0]!=$questionnumber) {
                   9029:            $questionnumber=$entries[0];
                   9030:            $$questiontitles[$number]=&mt('Question [_1]',$questionnumber);
                   9031:            $number++;
1.419     www      9032:         }
1.420     www      9033:         my $id=$entries[4];
                   9034:         $id=~s/^[\#0]+//;
1.421     www      9035:         $id=~s/^v\d*\://i;
                   9036:         $id=~s/[\-\:]//g;
1.420     www      9037:         $idresponses{$id}[$number]=$entries[6];
                   9038:     }
1.524     raeburn  9039:     foreach my $id (keys(%idresponses)) {
1.420     www      9040:        $$responses{$id}=join(',',@{$idresponses{$id}});
                   9041:        $$responses{$id}=~s/^\s*\,//;
1.419     www      9042:     }
                   9043:     return ($errormsg,$number);
                   9044: }
                   9045: 
1.414     www      9046: sub assign_clicker_grades {
1.608     www      9047:     my ($r,$symb)=@_;
1.414     www      9048:     if (!$symb) {return '';}
1.416     www      9049: # See which part we are saving to
1.582     raeburn  9050:     my $res_error;
                   9051:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
                   9052:     if ($res_error) {
                   9053:         return &navmap_errormsg();
                   9054:     }
1.416     www      9055: # FIXME: This should probably look for the first handgradeable part
                   9056:     my $part=$$partlist[0];
                   9057: # Start screen output
1.598     www      9058:     my $result='';
1.416     www      9059: 
1.414     www      9060:     my $heading=&mt('Assigning grades based on clicker file');
                   9061:     $result.=(<<ENDHEADER);
                   9062: <br /><table width="100%" border="0"><tr><td bgcolor="#777777">
                   9063: <table width="100%" border="0"><tr bgcolor="#e6ffff"><td>
                   9064: <b>$heading</b></td></tr><tr bgcolor=#ffffe6><td>
                   9065: ENDHEADER
                   9066: # Get correct result
                   9067: # FIXME: Possibly need delimiter other than ":"
                   9068:     my @correct=();
1.415     www      9069:     my $gradingmechanism=$env{'form.gradingmechanism'};
                   9070:     my $number=$env{'form.number'};
                   9071:     if ($gradingmechanism ne 'attendance') {
1.414     www      9072:        foreach my $key (keys(%env)) {
                   9073:           if ($key=~/^form\.correct\:/) {
                   9074:              my @input=split(/\,/,$env{$key});
                   9075:              for (my $i=0;$i<=$#input;$i++) {
                   9076:                  if (($correct[$i]) && ($input[$i]) &&
                   9077:                      ($correct[$i] ne $input[$i])) {
                   9078:                     $result.='<br /><span class="LC_warning">'.
                   9079:                              &mt('More than one correct result given for question "[_1]": [_2] versus [_3].',
                   9080:                                  $env{'form.question:'.$i},$correct[$i],$input[$i]).'</span>';
                   9081:                  } elsif ($input[$i]) {
                   9082:                     $correct[$i]=$input[$i];
                   9083:                  }
                   9084:              }
                   9085:           }
                   9086:        }
1.415     www      9087:        for (my $i=0;$i<$number;$i++) {
1.414     www      9088:           if (!$correct[$i]) {
                   9089:              $result.='<br /><span class="LC_error">'.
                   9090:                       &mt('No correct result given for question "[_1]"!',
                   9091:                           $env{'form.question:'.$i}).'</span>';
                   9092:           }
                   9093:        }
                   9094:        $result.='<br />'.&mt("Correct answer: [_1]",join(', ',map { ($_?$_:'-') } @correct));
                   9095:     }
                   9096: # Start grading
1.415     www      9097:     my $pcorrect=$env{'form.pcorrect'};
                   9098:     my $pincorrect=$env{'form.pincorrect'};
1.416     www      9099:     my $storecount=0;
1.415     www      9100:     foreach my $key (keys(%env)) {
1.420     www      9101:        my $user='';
1.415     www      9102:        if ($key=~/^form\.student\:(.*)$/) {
1.420     www      9103:           $user=$1;
                   9104:        }
                   9105:        if ($key=~/^form\.unknown\:(.*)$/) {
                   9106:           my $id=$1;
                   9107:           if (($env{'form.uname'.$id}) && ($env{'form.udom'.$id})) {
                   9108:              $user=$env{'form.uname'.$id}.':'.$env{'form.udom'.$id};
1.437     www      9109:           } elsif ($env{'form.multi'.$id}) {
                   9110:              $user=$env{'form.multi'.$id};
1.420     www      9111:           }
                   9112:        }
                   9113:        if ($user) { 
1.415     www      9114:           my @answer=split(/\,/,$env{$key});
                   9115:           my $sum=0;
1.522     www      9116:           my $realnumber=$number;
1.415     www      9117:           for (my $i=0;$i<$number;$i++) {
1.576     www      9118:              if  ($correct[$i] eq '-') {
                   9119:                 $realnumber--;
                   9120:              } elsif ($answer[$i]) {
1.415     www      9121:                 if ($gradingmechanism eq 'attendance') {
                   9122:                    $sum+=$pcorrect;
1.576     www      9123:                 } elsif ($correct[$i] eq '*') {
1.522     www      9124:                    $sum+=$pcorrect;
1.415     www      9125:                 } else {
                   9126:                    if ($answer[$i] eq $correct[$i]) {
                   9127:                       $sum+=$pcorrect;
                   9128:                    } else {
                   9129:                       $sum+=$pincorrect;
                   9130:                    }
                   9131:                 }
                   9132:              }
                   9133:           }
1.522     www      9134:           my $ave=$sum/(100*$realnumber);
1.416     www      9135: # Store
                   9136:           my ($username,$domain)=split(/\:/,$user);
                   9137:           my %grades=();
                   9138:           $grades{"resource.$part.solved"}='correct_by_override';
                   9139:           $grades{"resource.$part.awarded"}=$ave;
                   9140:           $grades{"resource.regrader"}="$env{'user.name'}:$env{'user.domain'}";
                   9141:           my $returncode=&Apache::lonnet::cstore(\%grades,$symb,
                   9142:                                                  $env{'request.course.id'},
                   9143:                                                  $domain,$username);
                   9144:           if ($returncode ne 'ok') {
                   9145:              $result.="<br /><span class=\"LC_error\">Failed to save student $username:$domain. Message when trying to save was ($returncode)</span>";
                   9146:           } else {
                   9147:              $storecount++;
                   9148:           }
1.415     www      9149:        }
                   9150:     }
                   9151: # We are done
1.549     hauer    9152:     $result.='<br />'.&mt('Successfully stored grades for [quant,_1,student].',$storecount).
1.416     www      9153:              '</td></tr></table>'."\n".
1.414     www      9154:              '</td></tr></table><br /><br />'."\n";
1.614     www      9155:     return $result;
1.414     www      9156: }
                   9157: 
1.582     raeburn  9158: sub navmap_errormsg {
                   9159:     return '<div class="LC_error">'.
                   9160:            &mt('An error occurred retrieving information about resources in the course.').'<br />'.
1.595     raeburn  9161:            &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  9162:            '</div>';
                   9163: }
1.607     droeschl 9164: 
1.609     www      9165: sub startpage {
1.613     www      9166:     my ($r,$symb,$crumbs,$onlyfolderflag,$nodisplayflag) = @_;
1.614     www      9167:     unshift(@$crumbs,{href=>&href_symb_cmd($symb,'gradingmenu'),text=>"Grading"});
1.607     droeschl 9168:     $r->print(&Apache::loncommon::start_page('Grading',undef,
1.610     www      9169:                                           {'bread_crumbs' => $crumbs}));
1.613     www      9170:     unless ($nodisplayflag) {
                   9171:        $r->print(&Apache::lonhtmlcommon::resource_info_box($symb,$onlyfolderflag));
                   9172:     }
1.607     droeschl 9173: }
1.582     raeburn  9174: 
1.622     www      9175: sub select_problem {
                   9176:     my ($r)=@_;
1.623     www      9177:     $r->print('<h2>'.&mt('Select the problem or one of the problems you want to grade').'</h2><form action="/adm/grades">');
1.622     www      9178:     $r->print(&Apache::lonstathelpers::problem_selector('.',undef,1));
                   9179:     $r->print('<input type="hidden" name="command" value="gradingmenu" />');
                   9180:     $r->print('<input type="submit" value="'.&mt('Next').' &rarr;" /></form>');
                   9181: }
                   9182: 
1.1       albertel 9183: sub handler {
1.41      ng       9184:     my $request=$_[0];
1.434     albertel 9185:     &reset_caches();
1.257     albertel 9186:     if ($env{'browser.mathml'}) {
1.141     www      9187: 	&Apache::loncommon::content_type($request,'text/xml');
1.41      ng       9188:     } else {
1.141     www      9189: 	&Apache::loncommon::content_type($request,'text/html');
1.41      ng       9190:     }
                   9191:     $request->send_http_header;
1.44      ng       9192:     return '' if $request->header_only;
1.41      ng       9193:     &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'});
1.608     www      9194: 
                   9195: # see what command we need to execute
                   9196: 
1.160     albertel 9197:     my @commands=&Apache::loncommon::get_env_multiple('form.command');
                   9198:     my $command=$commands[0];
1.447     foxr     9199: 
1.160     albertel 9200:     if ($#commands > 0) {
                   9201: 	&Apache::lonnet::logthis("grades got multiple commands ".join(':',@commands));
                   9202:     }
1.608     www      9203: 
                   9204: # see what the symb is
                   9205: 
                   9206:     my $symb=$env{'form.symb'};
                   9207:     unless ($symb) {
                   9208:        (my $url=$env{'form.url'}) =~ s-^https*://($ENV{'SERVER_NAME'}|$ENV{'HTTP_HOST'})--;
                   9209:        $symb=&Apache::lonnet::symbread($url);
                   9210:     }
                   9211:     &Apache::lonenc::check_decrypt(\$symb);                             
                   9212: 
1.513     foxr     9213:     $ssi_error = 0;
1.622     www      9214:     if ($symb eq '' || $command eq '') {
1.601     www      9215: #
                   9216: # Not called from a resource
                   9217: #    
1.622     www      9218:         &startpage($request,undef,[],1,1);
                   9219:         &select_problem($request);
1.41      ng       9220:     } else {
1.285     albertel 9221: 	&init_perm();
1.104     albertel 9222: 	if ($command eq 'submission' && $perm{'vgr'}) {
1.608     www      9223:             &startpage($request,$symb,[{href=>"", text=>"Student Submissions"}]);
1.611     www      9224: 	    ($env{'form.student'} eq '' ? &listStudents($request,$symb) : &submission($request,0,0,$symb));
1.103     albertel 9225: 	} elsif ($command eq 'pickStudentPage' && $perm{'vgr'}) {
1.615     www      9226:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,'all_for_one'),text=>'Grade page/folder for one student'},
                   9227:                                        {href=>'',text=>'Select student'}],1,1);
1.608     www      9228: 	    &pickStudentPage($request,$symb);
1.103     albertel 9229: 	} elsif ($command eq 'displayPage' && $perm{'vgr'}) {
1.615     www      9230:             &startpage($request,$symb,
                   9231:                                       [{href=>&href_symb_cmd($symb,'all_for_one'),text=>'Grade page/folder for one student'},
                   9232:                                        {href=>'',text=>'Select student'},
                   9233:                                        {href=>'',text=>'Grade student'}],1,1);
1.608     www      9234: 	    &displayPage($request,$symb);
1.104     albertel 9235: 	} elsif ($command eq 'gradeByPage' && $perm{'mgr'}) {
1.616     www      9236:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,'all_for_one'),text=>'Grade page/folder for one student'},
                   9237:                                        {href=>'',text=>'Select student'},
                   9238:                                        {href=>'',text=>'Grade student'},
                   9239:                                        {href=>'',text=>'Store grades'}],1,1);
1.608     www      9240: 	    &updateGradeByPage($request,$symb);
1.104     albertel 9241: 	} elsif ($command eq 'processGroup' && $perm{'vgr'}) {
1.619     www      9242:             &startpage($request,$symb,[{href=>'',text=>'...'},
                   9243:                                        {href=>'',text=>'Modify grades'}]);
1.608     www      9244: 	    &processGroup($request,$symb);
1.104     albertel 9245: 	} elsif ($command eq 'gradingmenu' && $perm{'vgr'}) {
1.608     www      9246:             &startpage($request,$symb);
                   9247: 	    $request->print(&grading_menu($request,$symb));
1.598     www      9248: 	} elsif ($command eq 'individual' && $perm{'vgr'}) {
1.617     www      9249:             &startpage($request,$symb,[{href=>'',text=>'Select individual students to grade'}]);
1.608     www      9250: 	    $request->print(&submit_options($request,$symb));
1.598     www      9251:         } elsif ($command eq 'ungraded' && $perm{'vgr'}) {
1.617     www      9252:             &startpage($request,$symb,[{href=>'',text=>'Grade ungraded submissions'}]);
                   9253:             $request->print(&listStudents($request,$symb,'graded'));
1.598     www      9254:         } elsif ($command eq 'table' && $perm{'vgr'}) {
1.614     www      9255:             &startpage($request,$symb,[{href=>"", text=>"Grading table"}]);
1.611     www      9256:             $request->print(&submit_options_table($request,$symb));
1.598     www      9257:         } elsif ($command eq 'all_for_one' && $perm{'vgr'}) {
1.615     www      9258:             &startpage($request,$symb,[{href=>'',text=>'Grade page/folder for one student'}],1,1);
1.608     www      9259:             $request->print(&submit_options_sequence($request,$symb));
1.104     albertel 9260: 	} elsif ($command eq 'viewgrades' && $perm{'vgr'}) {
1.614     www      9261:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,"table"), text=>"Grading table"},{href=>'', text=>"Modify grades"}]);
1.608     www      9262: 	    $request->print(&viewgrades($request,$symb));
1.104     albertel 9263: 	} elsif ($command eq 'handgrade' && $perm{'mgr'}) {
1.620     www      9264:             &startpage($request,$symb,[{href=>'',text=>'...'},
                   9265:                                        {href=>'',text=>'Store grades'}]);
1.608     www      9266: 	    $request->print(&processHandGrade($request,$symb));
1.106     albertel 9267: 	} elsif ($command eq 'editgrades' && $perm{'mgr'}) {
1.614     www      9268:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,"table"), text=>"Grading table"},
                   9269:                                        {href=>&href_symb_cmd($symb,'viewgrades').'&group=all&section=all&Status=Active',
                   9270:                                                                              text=>"Modify grades"},
                   9271:                                        {href=>'', text=>"Store grades"}]);
1.608     www      9272: 	    $request->print(&editgrades($request,$symb));
1.602     www      9273:         } elsif ($command eq 'initialverifyreceipt' && $perm{'vgr'}) {
1.616     www      9274:             &startpage($request,$symb,[{href=>'',text=>'Verify Receipt Number'}]);
1.611     www      9275:             $request->print(&initialverifyreceipt($request,$symb));
1.106     albertel 9276: 	} elsif ($command eq 'verify' && $perm{'vgr'}) {
1.616     www      9277:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,"initialverifyreceipt"),text=>'Verify Receipt Number'},
                   9278:                                        {href=>'',text=>'Verification Result'}]);
1.608     www      9279: 	    $request->print(&verifyreceipt($request,$symb));
1.400     www      9280:         } elsif ($command eq 'processclicker' && $perm{'mgr'}) {
1.615     www      9281:             &startpage($request,$symb,[{href=>'', text=>'Process clicker'}]);
1.608     www      9282:             $request->print(&process_clicker($request,$symb));
1.400     www      9283:         } elsif ($command eq 'processclickerfile' && $perm{'mgr'}) {
1.615     www      9284:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,'processclicker'), text=>'Process clicker'},
                   9285:                                        {href=>'', text=>'Process clicker file'}]);
1.608     www      9286:             $request->print(&process_clicker_file($request,$symb));
1.414     www      9287:         } elsif ($command eq 'assignclickergrades' && $perm{'mgr'}) {
1.615     www      9288:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,'processclicker'), text=>'Process clicker'},
                   9289:                                        {href=>'', text=>'Process clicker file'},
                   9290:                                        {href=>'', text=>'Store grades'}]);
1.608     www      9291:             $request->print(&assign_clicker_grades($request,$symb));
1.106     albertel 9292: 	} elsif ($command eq 'csvform' && $perm{'mgr'}) {
1.627     www      9293:             &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
1.608     www      9294: 	    $request->print(&upcsvScores_form($request,$symb));
1.106     albertel 9295: 	} elsif ($command eq 'csvupload' && $perm{'mgr'}) {
1.627     www      9296:             &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
1.608     www      9297: 	    $request->print(&csvupload($request,$symb));
1.106     albertel 9298: 	} elsif ($command eq 'csvuploadmap' && $perm{'mgr'} ) {
1.627     www      9299:             &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
1.608     www      9300: 	    $request->print(&csvuploadmap($request,$symb));
1.246     albertel 9301: 	} elsif ($command eq 'csvuploadoptions' && $perm{'mgr'}) {
1.257     albertel 9302: 	    if ($env{'form.associate'} ne 'Reverse Association') {
1.627     www      9303:                 &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
1.608     www      9304: 		$request->print(&csvuploadoptions($request,$symb));
1.41      ng       9305: 	    } else {
1.257     albertel 9306: 		if ( $env{'form.upfile_associate'} ne 'reverse' ) {
                   9307: 		    $env{'form.upfile_associate'} = 'reverse';
1.41      ng       9308: 		} else {
1.257     albertel 9309: 		    $env{'form.upfile_associate'} = 'forward';
1.41      ng       9310: 		}
1.627     www      9311:                 &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
1.608     www      9312: 		$request->print(&csvuploadmap($request,$symb));
1.41      ng       9313: 	    }
1.246     albertel 9314: 	} elsif ($command eq 'csvuploadassign' && $perm{'mgr'} ) {
1.627     www      9315:             &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
1.608     www      9316: 	    $request->print(&csvuploadassign($request,$symb));
1.106     albertel 9317: 	} elsif ($command eq 'scantron_selectphase' && $perm{'mgr'}) {
1.616     www      9318:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
1.612     www      9319: 	    $request->print(&scantron_selectphase($request,undef,$symb));
1.203     albertel 9320:  	} elsif ($command eq 'scantron_warning' && $perm{'mgr'}) {
1.616     www      9321:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
1.608     www      9322:  	    $request->print(&scantron_do_warning($request,$symb));
1.142     albertel 9323: 	} elsif ($command eq 'scantron_validate' && $perm{'mgr'}) {
1.616     www      9324:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
1.608     www      9325: 	    $request->print(&scantron_validate_file($request,$symb));
1.106     albertel 9326: 	} elsif ($command eq 'scantron_process' && $perm{'mgr'}) {
1.616     www      9327:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
1.608     www      9328: 	    $request->print(&scantron_process_students($request,$symb));
1.157     albertel 9329:  	} elsif ($command eq 'scantronupload' && 
1.257     albertel 9330:  		 (&Apache::lonnet::allowed('usc',$env{'request.role.domain'})||
                   9331: 		  &Apache::lonnet::allowed('usc',$env{'request.course.id'}))) {
1.616     www      9332:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
1.608     www      9333:  	    $request->print(&scantron_upload_scantron_data($request,$symb)); 
1.157     albertel 9334:  	} elsif ($command eq 'scantronupload_save' &&
1.257     albertel 9335:  		 (&Apache::lonnet::allowed('usc',$env{'request.role.domain'})||
                   9336: 		  &Apache::lonnet::allowed('usc',$env{'request.course.id'}))) {
1.616     www      9337:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
1.608     www      9338:  	    $request->print(&scantron_upload_scantron_data_save($request,$symb));
1.202     albertel 9339:  	} elsif ($command eq 'scantron_download' &&
1.257     albertel 9340: 		 &Apache::lonnet::allowed('usc',$env{'request.course.id'})) {
1.616     www      9341:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
1.608     www      9342:  	    $request->print(&scantron_download_scantron_data($request,$symb));
1.523     raeburn  9343:         } elsif ($command eq 'checksubmissions' && $perm{'vgr'}) {
1.616     www      9344:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
1.621     www      9345:             $request->print(&checkscantron_results($request,$symb));
                   9346:         } elsif ($command eq 'downloadfilesselect' && $perm{'vgr'}) {
                   9347:             &startpage($request,$symb,[{href=>'', text=>'Select which submissions to download'}]);
                   9348:             $request->print(&submit_options_download($request,$symb));
                   9349:          } elsif ($command eq 'downloadfileslink' && $perm{'vgr'}) {
                   9350:             &startpage($request,$symb,
                   9351:    [{href=>&href_symb_cmd($symb,'downloadfilesselect'), text=>'Select which submissions to download'},
                   9352:     {href=>'', text=>'Download submissions'}]);
                   9353:             &submit_download_link($request,$symb);
1.106     albertel 9354: 	} elsif ($command) {
1.620     www      9355:             &startpage($request,$symb,[{href=>'', text=>'Access denied'}]);
1.562     bisitz   9356: 	    $request->print('<p class="LC_error">'.&mt('Access Denied ([_1])',$command).'</p>');
1.26      albertel 9357: 	}
1.2       albertel 9358:     }
1.513     foxr     9359:     if ($ssi_error) {
                   9360: 	&ssi_print_error($request);
                   9361:     }
1.353     albertel 9362:     $request->print(&Apache::loncommon::end_page());
1.434     albertel 9363:     &reset_caches();
1.44      ng       9364:     return '';
                   9365: }
                   9366: 
1.1       albertel 9367: 1;
                   9368: 
1.13      albertel 9369: __END__;
1.531     jms      9370: 
                   9371: 
                   9372: =head1 NAME
                   9373: 
                   9374: Apache::grades
                   9375: 
                   9376: =head1 SYNOPSIS
                   9377: 
                   9378: Handles the viewing of grades.
                   9379: 
                   9380: This is part of the LearningOnline Network with CAPA project
                   9381: described at http://www.lon-capa.org.
                   9382: 
                   9383: =head1 OVERVIEW
                   9384: 
                   9385: Do an ssi with retries:
                   9386: While I'd love to factor out this with the vesrion in lonprintout,
                   9387: 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
                   9388: I'm not quite ready to invent (e.g. an ssi_with_retry object).
                   9389: 
                   9390: At least the logic that drives this has been pulled out into loncommon.
                   9391: 
                   9392: 
                   9393: 
                   9394: ssi_with_retries - Does the server side include of a resource.
                   9395:                      if the ssi call returns an error we'll retry it up to
                   9396:                      the number of times requested by the caller.
                   9397:                      If we still have a proble, no text is appended to the
                   9398:                      output and we set some global variables.
                   9399:                      to indicate to the caller an SSI error occurred.  
                   9400:                      All of this is supposed to deal with the issues described
                   9401:                      in LonCAPA BZ 5631 see:
                   9402:                      http://bugs.lon-capa.org/show_bug.cgi?id=5631
                   9403:                      by informing the user that this happened.
                   9404: 
                   9405: Parameters:
                   9406:   resource   - The resource to include.  This is passed directly, without
                   9407:                interpretation to lonnet::ssi.
                   9408:   form       - The form hash parameters that guide the interpretation of the resource
                   9409:                
                   9410:   retries    - Number of retries allowed before giving up completely.
                   9411: Returns:
                   9412:   On success, returns the rendered resource identified by the resource parameter.
                   9413: Side Effects:
                   9414:   The following global variables can be set:
                   9415:    ssi_error                - If an unrecoverable error occurred this becomes true.
                   9416:                               It is up to the caller to initialize this to false
                   9417:                               if desired.
                   9418:    ssi_error_resource  - If an unrecoverable error occurred, this is the value
                   9419:                               of the resource that could not be rendered by the ssi
                   9420:                               call.
                   9421:    ssi_error_message   - The error string fetched from the ssi response
                   9422:                               in the event of an error.
                   9423: 
                   9424: 
                   9425: =head1 HANDLER SUBROUTINE
                   9426: 
                   9427: ssi_with_retries()
                   9428: 
                   9429: =head1 SUBROUTINES
                   9430: 
                   9431: =over
                   9432: 
                   9433: =item scantron_get_correction() : 
                   9434: 
                   9435:    Builds the interface screen to interact with the operator to fix a
                   9436:    specific error condition in a specific scanline
                   9437: 
                   9438:  Arguments:
                   9439:     $r           - Apache request object
                   9440:     $i           - number of the current scanline
                   9441:     $scan_record - hash ref as returned from &scantron_parse_scanline()
                   9442:     $scan_config - hash ref as returned from &get_scantron_config()
                   9443:     $line        - full contents of the current scanline
                   9444:     $error       - error condition, valid values are
                   9445:                    'incorrectCODE', 'duplicateCODE',
                   9446:                    'doublebubble', 'missingbubble',
                   9447:                    'duplicateID', 'incorrectID'
                   9448:     $arg         - extra information needed
                   9449:        For errors:
                   9450:          - duplicateID   - paper number that this studentID was seen before on
                   9451:          - duplicateCODE - array ref of the paper numbers this CODE was
                   9452:                            seen on before
                   9453:          - incorrectCODE - current incorrect CODE 
                   9454:          - doublebubble  - array ref of the bubble lines that have double
                   9455:                            bubble errors
                   9456:          - missingbubble - array ref of the bubble lines that have missing
                   9457:                            bubble errors
                   9458: 
                   9459: =item  scantron_get_maxbubble() : 
                   9460: 
1.582     raeburn  9461:    Arguments:
                   9462:        $nav_error  - Reference to scalar which is a flag to indicate a
                   9463:                       failure to retrieve a navmap object.
                   9464:        if $nav_error is set to 1 by scantron_get_maxbubble(), the 
                   9465:        calling routine should trap the error condition and display the warning
                   9466:        found in &navmap_errormsg().
                   9467: 
1.531     jms      9468:    Returns the maximum number of bubble lines that are expected to
                   9469:    occur. Does this by walking the selected sequence rendering the
                   9470:    resource and then checking &Apache::lonxml::get_problem_counter()
                   9471:    for what the current value of the problem counter is.
                   9472: 
                   9473:    Caches the results to $env{'form.scantron_maxbubble'},
                   9474:    $env{'form.scantron.bubble_lines.n'}, 
                   9475:    $env{'form.scantron.first_bubble_line.n'} and
                   9476:    $env{"form.scantron.sub_bubblelines.n"}
                   9477:    which are the total number of bubble, lines, the number of bubble
                   9478:    lines for response n and number of the first bubble line for response n,
                   9479:    and a comma separated list of numbers of bubble lines for sub-questions
                   9480:    (for optionresponse, matchresponse, and rankresponse items), for response n.  
                   9481: 
                   9482: 
                   9483: =item  scantron_validate_missingbubbles() : 
                   9484: 
                   9485:    Validates all scanlines in the selected file to not have any
                   9486:     answers that don't have bubbles that have not been verified
                   9487:     to be bubble free.
                   9488: 
                   9489: =item  scantron_process_students() : 
                   9490: 
                   9491:    Routine that does the actual grading of the bubble sheet information.
                   9492: 
                   9493:    The parsed scanline hash is added to %env 
                   9494: 
                   9495:    Then foreach unskipped scanline it does an &Apache::lonnet::ssi()
                   9496:    foreach resource , with the form data of
                   9497: 
                   9498: 	'submitted'     =>'scantron' 
                   9499: 	'grade_target'  =>'grade',
                   9500: 	'grade_username'=> username of student
                   9501: 	'grade_domain'  => domain of student
                   9502: 	'grade_courseid'=> of course
                   9503: 	'grade_symb'    => symb of resource to grade
                   9504: 
                   9505:     This triggers a grading pass. The problem grading code takes care
                   9506:     of converting the bubbled letter information (now in %env) into a
                   9507:     valid submission.
                   9508: 
                   9509: =item  scantron_upload_scantron_data() :
                   9510: 
                   9511:     Creates the screen for adding a new bubble sheet data file to a course.
                   9512: 
                   9513: =item  scantron_upload_scantron_data_save() : 
                   9514: 
                   9515:    Adds a provided bubble information data file to the course if user
                   9516:    has the correct privileges to do so. 
                   9517: 
                   9518: =item  valid_file() :
                   9519: 
                   9520:    Validates that the requested bubble data file exists in the course.
                   9521: 
                   9522: =item  scantron_download_scantron_data() : 
                   9523: 
                   9524:    Shows a list of the three internal files (original, corrected,
                   9525:    skipped) for a specific bubble sheet data file that exists in the
                   9526:    course.
                   9527: 
                   9528: =item  scantron_validate_ID() : 
                   9529: 
                   9530:    Validates all scanlines in the selected file to not have any
1.556     weissno  9531:    invalid or underspecified student/employee IDs
1.531     jms      9532: 
1.582     raeburn  9533: =item navmap_errormsg() :
                   9534: 
                   9535:    Returns HTML mark-up inside a <div></div> with a link to re-initialize the course.
                   9536:    Should be called whenever the request to instantiate a navmap object fails.  
                   9537: 
1.531     jms      9538: =back
                   9539: 
                   9540: =cut

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