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

1.17      albertel    1: # The LearningOnline Network with CAPA
1.13      albertel    2: # The LON-CAPA Grading handler
1.17      albertel    3: #
1.607   ! droeschl    4: # $Id: grades.pm,v 1.606 2010/04/07 15:32:32 wenzelju Exp $
1.17      albertel    5: #
                      6: # Copyright Michigan State University Board of Trustees
                      7: #
                      8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
                      9: #
                     10: # LON-CAPA is free software; you can redistribute it and/or modify
                     11: # it under the terms of the GNU General Public License as published by
                     12: # the Free Software Foundation; either version 2 of the License, or
                     13: # (at your option) any later version.
                     14: #
                     15: # LON-CAPA is distributed in the hope that it will be useful,
                     16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
                     17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
                     18: # GNU General Public License for more details.
                     19: #
                     20: # You should have received a copy of the GNU General Public License
                     21: # along with LON-CAPA; if not, write to the Free Software
                     22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
                     23: #
                     24: # /home/httpd/html/adm/gpl.txt
                     25: #
                     26: # http://www.lon-capa.org/
                     27: #
1.1       albertel   28: 
1.529     jms        29: 
                     30: 
1.1       albertel   31: package Apache::grades;
                     32: use strict;
                     33: use Apache::style;
                     34: use Apache::lonxml;
                     35: use Apache::lonnet;
1.3       albertel   36: use Apache::loncommon;
1.112     ng         37: use Apache::lonhtmlcommon;
1.68      ng         38: use Apache::lonnavmaps;
1.1       albertel   39: use Apache::lonhomework;
1.456     banghart   40: use Apache::lonpickcode;
1.55      matthew    41: use Apache::loncoursedata;
1.362     albertel   42: use Apache::lonmsg();
1.1       albertel   43: use Apache::Constants qw(:common);
1.167     sakharuk   44: use Apache::lonlocal;
1.386     raeburn    45: use Apache::lonenc;
1.170     albertel   46: use String::Similarity;
1.359     www        47: use LONCAPA;
                     48: 
1.315     bowersj2   49: use POSIX qw(floor);
1.87      www        50: 
1.435     foxr       51: 
1.513     foxr       52: 
1.435     foxr       53: my %perm=();
1.447     foxr       54: 
1.513     foxr       55: #  These variables are used to recover from ssi errors
                     56: 
                     57: my $ssi_retries = 5;
                     58: my $ssi_error;
                     59: my $ssi_error_resource;
                     60: my $ssi_error_message;
                     61: 
                     62: 
                     63: sub ssi_with_retries {
                     64:     my ($resource, $retries, %form) = @_;
                     65:     my ($content, $response) = &Apache::loncommon::ssi_with_retries($resource, $retries, %form);
                     66:     if ($response->is_error) {
                     67: 	$ssi_error          = 1;
                     68: 	$ssi_error_resource = $resource;
                     69: 	$ssi_error_message  = $response->code . " " . $response->message;
                     70:     }
                     71: 
                     72:     return $content;
                     73: 
                     74: }
                     75: #
                     76: #  Prodcuces an ssi retry failure error message to the user:
                     77: #
                     78: 
                     79: sub ssi_print_error {
                     80:     my ($r) = @_;
1.516     raeburn    81:     my $helpurl = &Apache::loncommon::top_nav_help('Helpdesk');
                     82:     $r->print('
                     83: <br />
                     84: <h2>'.&mt('An unrecoverable network error occurred:').'</h2>
                     85: <p>
                     86: '.&mt('Unable to retrieve a resource from a server:').'<br />
                     87: '.&mt('Resource:').' '.$ssi_error_resource.'<br />
                     88: '.&mt('Error:').' '.$ssi_error_message.'
                     89: </p>
                     90: <p>'.
                     91: &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 />'.
                     92: &mt('If the error persists, please contact the [_1] for assistance.',$helpurl).
                     93: '</p>');
                     94:     return;
1.513     foxr       95: }
                     96: 
1.44      ng         97: #
1.146     albertel   98: # --- Retrieve the parts from the metadata file.---
1.598     www        99: # Returns an array of everything that the resources stores away
                    100: #
                    101: 
1.44      ng        102: sub getpartlist {
1.582     raeburn   103:     my ($symb,$errorref) = @_;
1.439     albertel  104: 
                    105:     my $navmap   = Apache::lonnavmaps::navmap->new();
1.582     raeburn   106:     unless (ref($navmap)) {
                    107:         if (ref($errorref)) { 
                    108:             $$errorref = 'navmap';
                    109:             return;
                    110:         }
                    111:     }
1.439     albertel  112:     my $res      = $navmap->getBySymb($symb);
                    113:     my $partlist = $res->parts();
                    114:     my $url      = $res->src();
                    115:     my @metakeys = split(/,/,&Apache::lonnet::metadata($url,'keys'));
                    116: 
1.146     albertel  117:     my @stores;
1.439     albertel  118:     foreach my $part (@{ $partlist }) {
1.146     albertel  119: 	foreach my $key (@metakeys) {
                    120: 	    if ($key =~ m/^stores_\Q$part\E_/) { push(@stores,$key); }
                    121: 	}
                    122:     }
                    123:     return @stores;
1.2       albertel  124: }
                    125: 
1.44      ng        126: # --- Get the symbolic name of a problem and the url
1.598     www       127: # Generate an error message if symb could not be found unless silent flag is set
                    128: # Takes $env{'form.symb'} by default; if not present, takes $env{'form.url'} and tries to get symb from that
                    129: #
                    130:  
1.324     albertel  131: sub get_symb {
1.173     albertel  132:     my ($request,$silent) = @_;
1.257     albertel  133:     (my $url=$env{'form.url'}) =~ s-^http://($ENV{'SERVER_NAME'}|$ENV{'HTTP_HOST'})--;
                    134:     my $symb=($env{'form.symb'} ne '' ? $env{'form.symb'} : (&Apache::lonnet::symbread($url)));
1.173     albertel  135:     if ($symb eq '') { 
                    136: 	if (!$silent) {
1.598     www       137: 	    $request->print(&mt("Unable to handle ambiguous references: [_1].",$url));
1.173     albertel  138: 	    return ();
                    139: 	}
                    140:     }
1.418     albertel  141:     &Apache::lonenc::check_decrypt(\$symb);
1.324     albertel  142:     return ($symb);
1.32      ng        143: }
                    144: 
1.129     ng        145: #--- Format fullname, username:domain if different for display
                    146: #--- Use anywhere where the student names are listed
                    147: sub nameUserString {
                    148:     my ($type,$fullname,$uname,$udom) = @_;
                    149:     if ($type eq 'header') {
1.485     albertel  150: 	return '<b>&nbsp;'.&mt('Fullname').'&nbsp;</b><span class="LC_internal_info">('.&mt('Username').')</span>';
1.129     ng        151:     } else {
1.398     albertel  152: 	return '&nbsp;'.$fullname.'<span class="LC_internal_info">&nbsp;('.$uname.
                    153: 	    ($env{'user.domain'} eq $udom ? '' : ' ('.$udom.')').')</span>';
1.129     ng        154:     }
                    155: }
                    156: 
1.44      ng        157: #--- Get the partlist and the response type for a given problem. ---
                    158: #--- Indicate if a response type is coded handgraded or not. ---
1.39      ng        159: sub response_type {
1.582     raeburn   160:     my ($symb,$response_error) = @_;
1.377     albertel  161: 
                    162:     my $navmap = Apache::lonnavmaps::navmap->new();
1.582     raeburn   163:     unless (ref($navmap)) {
                    164:         if (ref($response_error)) {
                    165:             $$response_error = 1;
                    166:         }
                    167:         return;
                    168:     }
1.377     albertel  169:     my $res = $navmap->getBySymb($symb);
1.593     raeburn   170:     unless (ref($res)) {
                    171:         $$response_error = 1;
                    172:         return;
                    173:     }
1.377     albertel  174:     my $partlist = $res->parts();
1.392     albertel  175:     my %vPart = 
                    176: 	map { $_ => 1 } (&Apache::loncommon::get_env_multiple('form.vPart'));
1.377     albertel  177:     my (%response_types,%handgrade);
                    178:     foreach my $part (@{ $partlist }) {
1.392     albertel  179: 	next if (%vPart && !exists($vPart{$part}));
                    180: 
1.377     albertel  181: 	my @types = $res->responseType($part);
                    182: 	my @ids = $res->responseIds($part);
                    183: 	for (my $i=0; $i < scalar(@ids); $i++) {
                    184: 	    $response_types{$part}{$ids[$i]} = $types[$i];
                    185: 	    $handgrade{$part.'_'.$ids[$i]} = 
                    186: 		&Apache::lonnet::EXT('resource.'.$part.'_'.$ids[$i].
                    187: 				     '.handgrade',$symb);
1.41      ng        188: 	}
                    189:     }
1.377     albertel  190:     return ($partlist,\%handgrade,\%response_types);
1.39      ng        191: }
                    192: 
1.375     albertel  193: sub flatten_responseType {
                    194:     my ($responseType) = @_;
                    195:     my @part_response_id =
                    196: 	map { 
                    197: 	    my $part = $_;
                    198: 	    map {
                    199: 		[$part,$_]
                    200: 		} sort(keys(%{ $responseType->{$part} }));
                    201: 	} sort(keys(%$responseType));
                    202:     return @part_response_id;
                    203: }
                    204: 
1.207     albertel  205: sub get_display_part {
1.324     albertel  206:     my ($partID,$symb)=@_;
1.207     albertel  207:     my $display=&Apache::lonnet::EXT('resource.'.$partID.'.display',$symb);
                    208:     if (defined($display) and $display ne '') {
1.577     bisitz    209:         $display.= ' (<span class="LC_internal_info">'
                    210:                   .&mt('Part ID: [_1]',$partID).'</span>)';
1.207     albertel  211:     } else {
                    212: 	$display=$partID;
                    213:     }
                    214:     return $display;
                    215: }
1.269     raeburn   216: 
1.434     albertel  217: sub reset_caches {
                    218:     &reset_analyze_cache();
                    219:     &reset_perm();
                    220: }
                    221: 
                    222: {
                    223:     my %analyze_cache;
1.557     raeburn   224:     my %analyze_cache_formkeys;
1.148     albertel  225: 
1.434     albertel  226:     sub reset_analyze_cache {
                    227: 	undef(%analyze_cache);
1.557     raeburn   228:         undef(%analyze_cache_formkeys);
1.434     albertel  229:     }
                    230: 
                    231:     sub get_analyze {
1.557     raeburn   232: 	my ($symb,$uname,$udom,$no_increment,$add_to_hash)=@_;
1.434     albertel  233: 	my $key = "$symb\0$uname\0$udom";
1.557     raeburn   234: 	if (exists($analyze_cache{$key})) {
                    235:             my $getupdate = 0;
                    236:             if (ref($add_to_hash) eq 'HASH') {
                    237:                 foreach my $item (keys(%{$add_to_hash})) {
                    238:                     if (ref($analyze_cache_formkeys{$key}) eq 'HASH') {
                    239:                         if (!exists($analyze_cache_formkeys{$key}{$item})) {
                    240:                             $getupdate = 1;
                    241:                             last;
                    242:                         }
                    243:                     } else {
                    244:                         $getupdate = 1;
                    245:                     }
                    246:                 }
                    247:             }
                    248:             if (!$getupdate) {
                    249:                 return $analyze_cache{$key};
                    250:             }
                    251:         }
1.434     albertel  252: 
                    253: 	my (undef,undef,$url)=&Apache::lonnet::decode_symb($symb);
                    254: 	$url=&Apache::lonnet::clutter($url);
1.557     raeburn   255:         my %form = ('grade_target'      => 'analyze',
                    256:                     'grade_domain'      => $udom,
                    257:                     'grade_symb'        => $symb,
                    258:                     'grade_courseid'    =>  $env{'request.course.id'},
                    259:                     'grade_username'    => $uname,
                    260:                     'grade_noincrement' => $no_increment);
                    261:         if (ref($add_to_hash)) {
                    262:             %form = (%form,%{$add_to_hash});
                    263:         } 
                    264: 	my $subresult=&ssi_with_retries($url, $ssi_retries,%form);
1.434     albertel  265: 	(undef,$subresult)=split(/_HASH_REF__/,$subresult,2);
                    266: 	my %analyze=&Apache::lonnet::str2hash($subresult);
1.557     raeburn   267:         if (ref($add_to_hash) eq 'HASH') {
                    268:             $analyze_cache_formkeys{$key} = $add_to_hash;
                    269:         } else {
                    270:             $analyze_cache_formkeys{$key} = {};
                    271:         }
1.434     albertel  272: 	return $analyze_cache{$key} = \%analyze;
                    273:     }
                    274: 
                    275:     sub get_order {
1.525     raeburn   276: 	my ($partid,$respid,$symb,$uname,$udom,$no_increment)=@_;
                    277: 	my $analyze = &get_analyze($symb,$uname,$udom,$no_increment);
1.434     albertel  278: 	return $analyze->{"$partid.$respid.shown"};
                    279:     }
                    280: 
                    281:     sub get_radiobutton_correct_foil {
                    282: 	my ($partid,$respid,$symb,$uname,$udom)=@_;
                    283: 	my $analyze = &get_analyze($symb,$uname,$udom);
1.555     raeburn   284:         my $foils = &get_order($partid,$respid,$symb,$uname,$udom);
                    285:         if (ref($foils) eq 'ARRAY') {
                    286: 	    foreach my $foil (@{$foils}) {
                    287: 	        if ($analyze->{"$partid.$respid.foil.value.$foil"} eq 'true') {
                    288: 		    return $foil;
                    289: 	        }
1.434     albertel  290: 	    }
                    291: 	}
                    292:     }
1.554     raeburn   293: 
                    294:     sub scantron_partids_tograde {
1.557     raeburn   295:         my ($resource,$cid,$uname,$udom,$check_for_randomlist) = @_;
1.554     raeburn   296:         my (%analysis,@parts);
                    297:         if (ref($resource)) {
                    298:             my $symb = $resource->symb();
1.557     raeburn   299:             my $add_to_form;
                    300:             if ($check_for_randomlist) {
                    301:                 $add_to_form = { 'check_parts_withrandomlist' => 1,};
                    302:             }
                    303:             my $analyze = &get_analyze($symb,$uname,$udom,undef,$add_to_form);
1.554     raeburn   304:             if (ref($analyze) eq 'HASH') {
                    305:                 %analysis = %{$analyze};
                    306:             }
                    307:             if (ref($analysis{'parts'}) eq 'ARRAY') {
                    308:                 foreach my $part (@{$analysis{'parts'}}) {
                    309:                     my ($id,$respid) = split(/\./,$part);
                    310:                     if (!&Apache::loncommon::check_if_partid_hidden($id,$symb,$udom,$uname)) {
                    311:                         push(@parts,$part);
                    312:                     }
                    313:                 }
                    314:             }
                    315:         }
                    316:         return (\%analysis,\@parts);
                    317:     }
                    318: 
1.148     albertel  319: }
1.434     albertel  320: 
1.118     ng        321: #--- Clean response type for display
1.335     albertel  322: #--- Currently filters option/rank/radiobutton/match/essay/Task
                    323: #        response types only.
1.118     ng        324: sub cleanRecord {
1.336     albertel  325:     my ($answer,$response,$symb,$partid,$respid,$record,$order,$version,
                    326: 	$uname,$udom) = @_;
1.398     albertel  327:     my $grayFont = '<span class="LC_internal_info">';
1.148     albertel  328:     if ($response =~ /^(option|rank)$/) {
                    329: 	my %answer=&Apache::lonnet::str2hash($answer);
                    330: 	my %grading=&Apache::lonnet::str2hash($record->{$version."resource.$partid.$respid.submissiongrading"});
                    331: 	my ($toprow,$bottomrow);
                    332: 	foreach my $foil (@$order) {
                    333: 	    if ($grading{$foil} == 1) {
                    334: 		$toprow.='<td><b>'.$answer{$foil}.'&nbsp;</b></td>';
                    335: 	    } else {
                    336: 		$toprow.='<td><i>'.$answer{$foil}.'&nbsp;</i></td>';
                    337: 	    }
1.398     albertel  338: 	    $bottomrow.='<td>'.$grayFont.$foil.'</span>&nbsp;</td>';
1.148     albertel  339: 	}
                    340: 	return '<blockquote><table border="1">'.
1.466     albertel  341: 	    '<tr valign="top"><td>'.&mt('Answer').'</td>'.$toprow.'</tr>'.
                    342: 	    '<tr valign="top"><td>'.$grayFont.&mt('Option ID').'</span></td>'.
1.148     albertel  343: 	    $grayFont.$bottomrow.'</tr>'.'</table></blockquote>';
                    344:     } elsif ($response eq 'match') {
                    345: 	my %answer=&Apache::lonnet::str2hash($answer);
                    346: 	my %grading=&Apache::lonnet::str2hash($record->{$version."resource.$partid.$respid.submissiongrading"});
                    347: 	my @items=&Apache::lonnet::str2array($record->{$version."resource.$partid.$respid.submissionitems"});
                    348: 	my ($toprow,$middlerow,$bottomrow);
                    349: 	foreach my $foil (@$order) {
                    350: 	    my $item=shift(@items);
                    351: 	    if ($grading{$foil} == 1) {
                    352: 		$toprow.='<td><b>'.$item.'&nbsp;</b></td>';
1.398     albertel  353: 		$middlerow.='<td><b>'.$grayFont.$answer{$foil}.'&nbsp;</span></b></td>';
1.148     albertel  354: 	    } else {
                    355: 		$toprow.='<td><i>'.$item.'&nbsp;</i></td>';
1.398     albertel  356: 		$middlerow.='<td><i>'.$grayFont.$answer{$foil}.'&nbsp;</span></i></td>';
1.148     albertel  357: 	    }
1.398     albertel  358: 	    $bottomrow.='<td>'.$grayFont.$foil.'</span>&nbsp;</td>';
1.118     ng        359: 	}
1.126     ng        360: 	return '<blockquote><table border="1">'.
1.466     albertel  361: 	    '<tr valign="top"><td>'.&mt('Answer').'</td>'.$toprow.'</tr>'.
                    362: 	    '<tr valign="top"><td>'.$grayFont.&mt('Item ID').'</span></td>'.
1.148     albertel  363: 	    $middlerow.'</tr>'.
1.466     albertel  364: 	    '<tr valign="top"><td>'.$grayFont.&mt('Option ID').'</span></td>'.
1.148     albertel  365: 	    $bottomrow.'</tr>'.'</table></blockquote>';
                    366:     } elsif ($response eq 'radiobutton') {
                    367: 	my %answer=&Apache::lonnet::str2hash($answer);
                    368: 	my ($toprow,$bottomrow);
1.434     albertel  369: 	my $correct = 
                    370: 	    &get_radiobutton_correct_foil($partid,$respid,$symb,$uname,$udom);
                    371: 	foreach my $foil (@$order) {
1.148     albertel  372: 	    if (exists($answer{$foil})) {
1.434     albertel  373: 		if ($foil eq $correct) {
1.466     albertel  374: 		    $toprow.='<td><b>'.&mt('true').'</b></td>';
1.148     albertel  375: 		} else {
1.466     albertel  376: 		    $toprow.='<td><i>'.&mt('true').'</i></td>';
1.148     albertel  377: 		}
                    378: 	    } else {
1.466     albertel  379: 		$toprow.='<td>'.&mt('false').'</td>';
1.148     albertel  380: 	    }
1.398     albertel  381: 	    $bottomrow.='<td>'.$grayFont.$foil.'</span>&nbsp;</td>';
1.148     albertel  382: 	}
                    383: 	return '<blockquote><table border="1">'.
1.466     albertel  384: 	    '<tr valign="top"><td>'.&mt('Answer').'</td>'.$toprow.'</tr>'.
                    385: 	    '<tr valign="top"><td>'.$grayFont.&mt('Option ID').'</span></td>'.
1.597     wenzelju  386: 	    $bottomrow.'</tr>'.'</table></blockquote>';
1.148     albertel  387:     } elsif ($response eq 'essay') {
1.257     albertel  388: 	if (! exists ($env{'form.'.$symb})) {
1.122     ng        389: 	    my (%keyhash) = &Apache::lonnet::dump('nohist_handgrade',
1.257     albertel  390: 						  $env{'course.'.$env{'request.course.id'}.'.domain'},
                    391: 						  $env{'course.'.$env{'request.course.id'}.'.num'});
1.122     ng        392: 
1.257     albertel  393: 	    my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
                    394: 	    $env{'form.keywords'} = $keyhash{$symb.'_keywords'} ne '' ? $keyhash{$symb.'_keywords'} : '';
                    395: 	    $env{'form.kwclr'}    = $keyhash{$loginuser.'_kwclr'} ne '' ? $keyhash{$loginuser.'_kwclr'} : 'red';
                    396: 	    $env{'form.kwsize'}   = $keyhash{$loginuser.'_kwsize'} ne '' ? $keyhash{$loginuser.'_kwsize'} : '0';
                    397: 	    $env{'form.kwstyle'}  = $keyhash{$loginuser.'_kwstyle'} ne '' ? $keyhash{$loginuser.'_kwstyle'} : '';
                    398: 	    $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        399: 	}
1.166     albertel  400: 	$answer =~ s-\n-<br />-g;
                    401: 	return '<br /><br /><blockquote><tt>'.&keywords_highlight($answer).'</tt></blockquote>';
1.268     albertel  402:     } elsif ( $response eq 'organic') {
                    403: 	my $result='Smile representation: "<tt>'.$answer.'</tt>"';
                    404: 	my $jme=$record->{$version."resource.$partid.$respid.molecule"};
                    405: 	$result.=&Apache::chemresponse::jme_img($jme,$answer,400);
                    406: 	return $result;
1.335     albertel  407:     } elsif ( $response eq 'Task') {
                    408: 	if ( $answer eq 'SUBMITTED') {
                    409: 	    my $files = $record->{$version."resource.$respid.$partid.bridgetask.portfiles"};
1.336     albertel  410: 	    my $result = &Apache::bridgetask::file_list($files,$uname,$udom);
1.335     albertel  411: 	    return $result;
                    412: 	} elsif ( grep(/^\Q$version\E.*?\.instance$/, keys(%{$record})) ) {
                    413: 	    my @matches = grep(/^\Q$version\E.*?\.instance$/,
                    414: 			       keys(%{$record}));
                    415: 	    return join('<br />',($version,@matches));
                    416: 			       
                    417: 			       
                    418: 	} else {
                    419: 	    my $result =
                    420: 		'<p>'
                    421: 		.&mt('Overall result: [_1]',
                    422: 		     $record->{$version."resource.$respid.$partid.status"})
                    423: 		.'</p>';
                    424: 	    
                    425: 	    $result .= '<ul>';
                    426: 	    my @grade = grep(/^\Q${version}resource.$respid.$partid.\E[^.]*[.]status$/,
                    427: 			     keys(%{$record}));
                    428: 	    foreach my $grade (sort(@grade)) {
                    429: 		my ($dim) = ($grade =~/[.]([^.]+)[.]status$/);
                    430: 		$result.= '<li>'.&mt("Dimension: [_1], status [_2] ",
                    431: 				     $dim, $record->{$grade}).
                    432: 			  '</li>';
                    433: 	    }
                    434: 	    $result.='</ul>';
                    435: 	    return $result;
                    436: 	}
1.440     albertel  437:     } elsif ( $response =~ m/(?:numerical|formula)/) {
                    438: 	$answer = 
                    439: 	    &Apache::loncommon::format_previous_attempt_value('submission',
                    440: 							      $answer);
1.122     ng        441:     }
1.118     ng        442:     return $answer;
                    443: }
                    444: 
                    445: #-- A couple of common js functions
                    446: sub commonJSfunctions {
                    447:     my $request = shift;
1.597     wenzelju  448:     $request->print(&Apache::lonhtmlcommon::scripttag(<<COMMONJSFUNCTIONS));
1.118     ng        449:     function radioSelection(radioButton) {
                    450: 	var selection=null;
                    451: 	if (radioButton.length > 1) {
                    452: 	    for (var i=0; i<radioButton.length; i++) {
                    453: 		if (radioButton[i].checked) {
                    454: 		    return radioButton[i].value;
                    455: 		}
                    456: 	    }
                    457: 	} else {
                    458: 	    if (radioButton.checked) return radioButton.value;
                    459: 	}
                    460: 	return selection;
                    461:     }
                    462: 
                    463:     function pullDownSelection(selectOne) {
                    464: 	var selection="";
                    465: 	if (selectOne.length > 1) {
                    466: 	    for (var i=0; i<selectOne.length; i++) {
                    467: 		if (selectOne[i].selected) {
                    468: 		    return selectOne[i].value;
                    469: 		}
                    470: 	    }
                    471: 	} else {
1.138     albertel  472:             // only one value it must be the selected one
                    473: 	    return selectOne.value;
1.118     ng        474: 	}
                    475:     }
                    476: COMMONJSFUNCTIONS
                    477: }
                    478: 
1.44      ng        479: #--- Dumps the class list with usernames,list of sections,
                    480: #--- section, ids and fullnames for each user.
                    481: sub getclasslist {
1.449     banghart  482:     my ($getsec,$filterlist,$getgroup) = @_;
1.291     albertel  483:     my @getsec;
1.450     banghart  484:     my @getgroup;
1.442     banghart  485:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
1.291     albertel  486:     if (!ref($getsec)) {
                    487: 	if ($getsec ne '' && $getsec ne 'all') {
                    488: 	    @getsec=($getsec);
                    489: 	}
                    490:     } else {
                    491: 	@getsec=@{$getsec};
                    492:     }
                    493:     if (grep(/^all$/,@getsec)) { undef(@getsec); }
1.450     banghart  494:     if (!ref($getgroup)) {
                    495: 	if ($getgroup ne '' && $getgroup ne 'all') {
                    496: 	    @getgroup=($getgroup);
                    497: 	}
                    498:     } else {
                    499: 	@getgroup=@{$getgroup};
                    500:     }
                    501:     if (grep(/^all$/,@getgroup)) { undef(@getgroup); }
1.291     albertel  502: 
1.449     banghart  503:     my ($classlist,$keylist)=&Apache::loncoursedata::get_classlist();
1.49      albertel  504:     # Bail out if we were unable to get the classlist
1.56      matthew   505:     return if (! defined($classlist));
1.449     banghart  506:     &Apache::loncoursedata::get_group_memberships($classlist,$keylist);
1.56      matthew   507:     #
                    508:     my %sections;
                    509:     my %fullnames;
1.205     matthew   510:     foreach my $student (keys(%$classlist)) {
                    511:         my $end      = 
                    512:             $classlist->{$student}->[&Apache::loncoursedata::CL_END()];
                    513:         my $start    = 
                    514:             $classlist->{$student}->[&Apache::loncoursedata::CL_START()];
                    515:         my $id       = 
                    516:             $classlist->{$student}->[&Apache::loncoursedata::CL_ID()];
                    517:         my $section  = 
                    518:             $classlist->{$student}->[&Apache::loncoursedata::CL_SECTION()];
                    519:         my $fullname = 
                    520:             $classlist->{$student}->[&Apache::loncoursedata::CL_FULLNAME()];
                    521:         my $status   = 
                    522:             $classlist->{$student}->[&Apache::loncoursedata::CL_STATUS()];
1.449     banghart  523:         my $group   = 
                    524:             $classlist->{$student}->[&Apache::loncoursedata::CL_GROUP()];
1.76      ng        525: 	# filter students according to status selected
1.442     banghart  526: 	if ($filterlist && (!($stu_status =~ /Any/))) {
                    527: 	    if (!($stu_status =~ $status)) {
1.450     banghart  528: 		delete($classlist->{$student});
1.76      ng        529: 		next;
                    530: 	    }
                    531: 	}
1.450     banghart  532: 	# filter students according to groups selected
1.453     banghart  533: 	my @stu_groups = split(/,/,$group);
1.450     banghart  534: 	if (@getgroup) {
                    535: 	    my $exclude = 1;
1.454     banghart  536: 	    foreach my $grp (@getgroup) {
                    537: 	        foreach my $stu_group (@stu_groups) {
1.453     banghart  538: 	            if ($stu_group eq $grp) {
                    539: 	                $exclude = 0;
                    540:     	            } 
1.450     banghart  541: 	        }
1.453     banghart  542:     	        if (($grp eq 'none') && !$group) {
                    543:         	        $exclude = 0;
                    544:         	}
1.450     banghart  545: 	    }
                    546: 	    if ($exclude) {
                    547: 	        delete($classlist->{$student});
                    548: 	    }
                    549: 	}
1.205     matthew   550: 	$section = ($section ne '' ? $section : 'none');
1.106     albertel  551: 	if (&canview($section)) {
1.291     albertel  552: 	    if (!@getsec || grep(/^\Q$section\E$/,@getsec)) {
1.103     albertel  553: 		$sections{$section}++;
1.450     banghart  554: 		if ($classlist->{$student}) {
                    555: 		    $fullnames{$student}=$fullname;
                    556: 		}
1.103     albertel  557: 	    } else {
1.205     matthew   558: 		delete($classlist->{$student});
1.103     albertel  559: 	    }
                    560: 	} else {
1.205     matthew   561: 	    delete($classlist->{$student});
1.103     albertel  562: 	}
1.44      ng        563:     }
                    564:     my %seen = ();
1.56      matthew   565:     my @sections = sort(keys(%sections));
                    566:     return ($classlist,\@sections,\%fullnames);
1.44      ng        567: }
                    568: 
1.103     albertel  569: sub canmodify {
                    570:     my ($sec)=@_;
                    571:     if ($perm{'mgr'}) {
                    572: 	if (!defined($perm{'mgr_section'})) {
                    573: 	    # can modify whole class
                    574: 	    return 1;
                    575: 	} else {
                    576: 	    if ($sec eq $perm{'mgr_section'}) {
                    577: 		#can modify the requested section
                    578: 		return 1;
                    579: 	    } else {
                    580: 		# can't modify the request section
                    581: 		return 0;
                    582: 	    }
                    583: 	}
                    584:     }
                    585:     #can't modify
                    586:     return 0;
                    587: }
                    588: 
                    589: sub canview {
                    590:     my ($sec)=@_;
                    591:     if ($perm{'vgr'}) {
                    592: 	if (!defined($perm{'vgr_section'})) {
                    593: 	    # can modify whole class
                    594: 	    return 1;
                    595: 	} else {
                    596: 	    if ($sec eq $perm{'vgr_section'}) {
                    597: 		#can modify the requested section
                    598: 		return 1;
                    599: 	    } else {
                    600: 		# can't modify the request section
                    601: 		return 0;
                    602: 	    }
                    603: 	}
                    604:     }
                    605:     #can't modify
                    606:     return 0;
                    607: }
                    608: 
1.44      ng        609: #--- Retrieve the grade status of a student for all the parts
                    610: sub student_gradeStatus {
1.324     albertel  611:     my ($symb,$udom,$uname,$partlist) = @_;
1.257     albertel  612:     my %record     = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
1.44      ng        613:     my %partstatus = ();
                    614:     foreach (@$partlist) {
1.128     ng        615: 	my ($status,undef)   = split(/_/,$record{"resource.$_.solved"},2);
1.44      ng        616: 	$status              = 'nothing' if ($status eq '');
                    617: 	$partstatus{$_}      = $status;
                    618: 	my $subkey           = "resource.$_.submitted_by";
                    619: 	$partstatus{$subkey} = $record{$subkey} if ($record{$subkey} ne '');
                    620:     }
                    621:     return %partstatus;
                    622: }
                    623: 
1.45      ng        624: # hidden form and javascript that calls the form
                    625: # Use by verifyscript and viewgrades
                    626: # Shows a student's view of problem and submission
                    627: sub jscriptNform {
1.324     albertel  628:     my ($symb) = @_;
1.442     banghart  629:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
1.597     wenzelju  630:     my $jscript= &Apache::lonhtmlcommon::scripttag(
1.45      ng        631: 	'    function viewOneStudent(user,domain) {'."\n".
                    632: 	'	document.onestudent.student.value = user;'."\n".
                    633: 	'	document.onestudent.userdom.value = domain;'."\n".
                    634: 	'	document.onestudent.submit();'."\n".
                    635: 	'    }'."\n".
1.597     wenzelju  636: 	"\n");
1.45      ng        637:     $jscript.= '<form action="/adm/grades" method="post" name="onestudent">'."\n".
1.418     albertel  638: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.257     albertel  639: 	'<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n".
1.442     banghart  640: 	'<input type="hidden" name="Status"  value="'.$stu_status.'" />'."\n".
1.45      ng        641: 	'<input type="hidden" name="command" value="submission" />'."\n".
                    642: 	'<input type="hidden" name="student" value="" />'."\n".
                    643: 	'<input type="hidden" name="userdom" value="" />'."\n".
                    644: 	'</form>'."\n";
                    645:     return $jscript;
                    646: }
1.39      ng        647: 
1.447     foxr      648: 
                    649: 
1.315     bowersj2  650: # Given the score (as a number [0-1] and the weight) what is the final
                    651: # point value? This function will round to the nearest tenth, third,
                    652: # or quarter if one of those is within the tolerance of .00001.
1.316     albertel  653: sub compute_points {
1.315     bowersj2  654:     my ($score, $weight) = @_;
                    655:     
                    656:     my $tolerance = .00001;
                    657:     my $points = $score * $weight;
                    658: 
                    659:     # Check for nearness to 1/x.
                    660:     my $check_for_nearness = sub {
                    661:         my ($factor) = @_;
                    662:         my $num = ($points * $factor) + $tolerance;
                    663:         my $floored_num = floor($num);
1.316     albertel  664:         if ($num - $floored_num < 2 * $tolerance * $factor) {
1.315     bowersj2  665:             return $floored_num / $factor;
                    666:         }
                    667:         return $points;
                    668:     };
                    669: 
                    670:     $points = $check_for_nearness->(10);
                    671:     $points = $check_for_nearness->(3);
                    672:     $points = $check_for_nearness->(4);
                    673:     
                    674:     return $points;
                    675: }
                    676: 
1.44      ng        677: #------------------ End of general use routines --------------------
1.87      www       678: 
                    679: #
                    680: # Find most similar essay
                    681: #
                    682: 
                    683: sub most_similar {
1.426     albertel  684:     my ($uname,$udom,$uessay,$old_essays)=@_;
1.87      www       685: 
                    686: # ignore spaces and punctuation
                    687: 
                    688:     $uessay=~s/\W+/ /gs;
                    689: 
1.282     www       690: # ignore empty submissions (occuring when only files are sent)
                    691: 
1.598     www       692:     unless ($uessay=~/\w+/s) { return ''; }
1.282     www       693: 
1.87      www       694: # these will be returned. Do not care if not at least 50 percent similar
1.88      www       695:     my $limit=0.6;
1.87      www       696:     my $sname='';
                    697:     my $sdom='';
                    698:     my $scrsid='';
                    699:     my $sessay='';
                    700: # go through all essays ...
1.426     albertel  701:     foreach my $tkey (keys(%$old_essays)) {
                    702: 	my ($tname,$tdom,$tcrsid)=map {&unescape($_)} (split(/\./,$tkey));
1.87      www       703: # ... except the same student
1.426     albertel  704:         next if (($tname eq $uname) && ($tdom eq $udom));
                    705: 	my $tessay=$old_essays->{$tkey};
                    706: 	$tessay=~s/\W+/ /gs;
1.87      www       707: # String similarity gives up if not even limit
1.426     albertel  708: 	my $tsimilar=&String::Similarity::similarity($uessay,$tessay,$limit);
1.87      www       709: # Found one
1.426     albertel  710: 	if ($tsimilar>$limit) {
                    711: 	    $limit=$tsimilar;
                    712: 	    $sname=$tname;
                    713: 	    $sdom=$tdom;
                    714: 	    $scrsid=$tcrsid;
                    715: 	    $sessay=$old_essays->{$tkey};
                    716: 	}
1.87      www       717:     }
1.88      www       718:     if ($limit>0.6) {
1.87      www       719:        return ($sname,$sdom,$scrsid,$sessay,$limit);
                    720:     } else {
                    721:        return ('','','','',0);
                    722:     }
                    723: }
                    724: 
1.44      ng        725: #-------------------------------------------------------------------
                    726: 
                    727: #------------------------------------ Receipt Verification Routines
1.45      ng        728: #
1.602     www       729: 
                    730: sub initialverifyreceipt {
                    731:    my $request = shift;
                    732:    &commonJSfunctions($request);
1.603     www       733:    my ($symb)   = &get_symb($request);
1.605     www       734:    return '<form name="gradingMenu"><input type="submit" value="'.&mt('Verify Receipt Number.').'" />'.
1.602     www       735:         &Apache::lonnet::recprefix($env{'request.course.id'}).
                    736:         '-<input type="text" name="receipt" size="4" />'.
1.603     www       737:         '<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
                    738:         '<input type="hidden" name="command" value="verify" />'.
                    739:         "</form>\n";
1.602     www       740: }
                    741: 
1.44      ng        742: #--- Check whether a receipt number is valid.---
                    743: sub verifyreceipt {
                    744:     my $request  = shift;
                    745: 
1.257     albertel  746:     my $courseid = $env{'request.course.id'};
1.184     www       747:     my $receipt  = &Apache::lonnet::recprefix($courseid).'-'.
1.257     albertel  748: 	$env{'form.receipt'};
1.44      ng        749:     $receipt     =~ s/[^\-\d]//g;
1.378     albertel  750:     my ($symb)   = &get_symb($request);
1.44      ng        751: 
1.487     albertel  752:     my $title.=
                    753: 	'<h3><span class="LC_info">'.
1.605     www       754: 	&mt('Verifying Receipt Number [_1]',$receipt).
                    755: 	'</span></h3>'."\n";
1.44      ng        756: 
                    757:     my ($string,$contents,$matches) = ('','',0);
1.56      matthew   758:     my (undef,undef,$fullname) = &getclasslist('all','0');
1.177     albertel  759:     
                    760:     my $receiptparts=0;
1.390     albertel  761:     if ($env{"course.$courseid.receiptalg"} eq 'receipt2' ||
                    762: 	$env{"course.$courseid.receiptalg"} eq 'receipt3') { $receiptparts=1; }
1.177     albertel  763:     my $parts=['0'];
1.582     raeburn   764:     if ($receiptparts) {
                    765:         my $res_error; 
                    766:         ($parts)=&response_type($symb,\$res_error);
                    767:         if ($res_error) {
                    768:             return &navmap_errormsg();
                    769:         } 
                    770:     }
1.486     albertel  771:     
                    772:     my $header = 
                    773: 	&Apache::loncommon::start_data_table().
                    774: 	&Apache::loncommon::start_data_table_header_row().
1.487     albertel  775: 	'<th>&nbsp;'.&mt('Fullname').'&nbsp;</th>'."\n".
                    776: 	'<th>&nbsp;'.&mt('Username').'&nbsp;</th>'."\n".
                    777: 	'<th>&nbsp;'.&mt('Domain').'&nbsp;</th>';
1.486     albertel  778:     if ($receiptparts) {
1.487     albertel  779: 	$header.='<th>&nbsp;'.&mt('Problem Part').'&nbsp;</th>';
1.486     albertel  780:     }
                    781:     $header.=
                    782: 	&Apache::loncommon::end_data_table_header_row();
                    783: 
1.294     albertel  784:     foreach (sort 
                    785: 	     {
                    786: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                    787: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                    788: 		 }
                    789: 		 return $a cmp $b;
                    790: 	     } (keys(%$fullname))) {
1.44      ng        791: 	my ($uname,$udom)=split(/\:/);
1.177     albertel  792: 	foreach my $part (@$parts) {
                    793: 	    if ($receipt eq &Apache::lonnet::ireceipt($uname,$udom,$courseid,$symb,$part)) {
1.486     albertel  794: 		$contents.=
                    795: 		    &Apache::loncommon::start_data_table_row().
                    796: 		    '<td>&nbsp;'."\n".
1.177     albertel  797: 		    '<a href="javascript:viewOneStudent(\''.$uname.'\',\''.$udom.
1.417     albertel  798: 		    '\');" target="_self">'.$$fullname{$_}.'</a>&nbsp;</td>'."\n".
1.177     albertel  799: 		    '<td>&nbsp;'.$uname.'&nbsp;</td>'.
                    800: 		    '<td>&nbsp;'.$udom.'&nbsp;</td>';
                    801: 		if ($receiptparts) {
                    802: 		    $contents.='<td>&nbsp;'.$part.'&nbsp;</td>';
                    803: 		}
1.486     albertel  804: 		$contents.= 
                    805: 		    &Apache::loncommon::end_data_table_row()."\n";
1.177     albertel  806: 		
                    807: 		$matches++;
                    808: 	    }
1.44      ng        809: 	}
                    810:     }
                    811:     if ($matches == 0) {
1.584     bisitz    812:         $string = $title
                    813:                  .'<p class="LC_warning">'
                    814:                  .&mt('No match found for the above receipt number.')
                    815:                  .'</p>';
1.44      ng        816:     } else {
1.324     albertel  817: 	$string = &jscriptNform($symb).$title.
1.487     albertel  818: 	    '<p>'.
1.584     bisitz    819: 	    &mt('The above receipt number matches the following [quant,_1,student].',$matches).
1.487     albertel  820: 	    '</p>'.
1.486     albertel  821: 	    $header.
                    822: 	    $contents.
                    823: 	    &Apache::loncommon::end_data_table()."\n";
1.44      ng        824:     }
1.324     albertel  825:     return $string.&show_grading_menu_form($symb);
1.44      ng        826: }
                    827: 
                    828: #--- This is called by a number of programs.
                    829: #--- Called from the Grading Menu - View/Grade an individual student
                    830: #--- Also called directly when one clicks on the subm button 
                    831: #    on the problem page.
1.30      ng        832: sub listStudents {
1.41      ng        833:     my ($request) = shift;
1.49      albertel  834: 
1.324     albertel  835:     my ($symb) = &get_symb($request);
1.257     albertel  836:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
                    837:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
                    838:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
1.449     banghart  839:     my $getgroup  = $env{'form.group'} eq '' ? 'all' : $env{'form.group'};
1.257     albertel  840:     my $submitonly= $env{'form.submitonly'} eq '' ? 'all' : $env{'form.submitonly'};
1.548     bisitz    841:     my $viewgrade = $env{'form.showgrading'} eq 'yes' ? 'View/Grade/Regrade' : 'View';
1.49      albertel  842: 
1.548     bisitz    843:     my $result='<h3><span class="LC_info">&nbsp;'
                    844: 	.&mt("$viewgrade Submissions for a Student or a Group of Students")
1.485     albertel  845: 	.'</span></h3>';
1.118     ng        846: 
1.598     www       847:     my ($partlist,$handgrade,$responseType) = &response_type($symb
                    848: #,$res_error
                    849:     );
1.49      albertel  850: 
1.559     raeburn   851:     my %lt = &Apache::lonlocal::texthash (
                    852: 		'multiple' => 'Please select a student or group of students before clicking on the Next button.',
                    853: 		'single'   => 'Please select the student before clicking on the Next button.',
                    854: 	     );
1.597     wenzelju  855:     $request->print(&Apache::lonhtmlcommon::scripttag(<<LISTJAVASCRIPT));
1.110     ng        856:     function checkSelect(checkBox) {
                    857: 	var ctr=0;
                    858: 	var sense="";
                    859: 	if (checkBox.length > 1) {
                    860: 	    for (var i=0; i<checkBox.length; i++) {
                    861: 		if (checkBox[i].checked) {
                    862: 		    ctr++;
                    863: 		}
                    864: 	    }
1.485     albertel  865: 	    sense = '$lt{'multiple'}';
1.110     ng        866: 	} else {
                    867: 	    if (checkBox.checked) {
                    868: 		ctr = 1;
                    869: 	    }
1.485     albertel  870: 	    sense = '$lt{'single'}';
1.110     ng        871: 	}
                    872: 	if (ctr == 0) {
1.485     albertel  873: 	    alert(sense);
1.110     ng        874: 	    return false;
                    875: 	}
                    876: 	document.gradesub.submit();
                    877:     }
                    878: 
                    879:     function reLoadList(formname) {
1.112     ng        880: 	if (formname.saveStatusOld.value == pullDownSelection(formname.Status)) {return;}
1.110     ng        881: 	formname.command.value = 'submission';
                    882: 	formname.submit();
                    883:     }
1.45      ng        884: LISTJAVASCRIPT
                    885: 
1.118     ng        886:     &commonJSfunctions($request);
1.41      ng        887:     $request->print($result);
1.39      ng        888: 
1.401     albertel  889:     my $checkhdgrade = ($env{'form.handgrade'} eq 'yes' && scalar(@$partlist) > 1 ) ? 'checked="checked"' : '';
                    890:     my $checklastsub = $checkhdgrade eq '' ? 'checked="checked"' : '';
1.154     albertel  891:     my $gradeTable='<form action="/adm/grades" method="post" name="gradesub">'.
1.598     www       892: 	"\n";
1.485     albertel  893: 	
1.561     bisitz    894:     $gradeTable .= &Apache::lonhtmlcommon::start_pick_box();
                    895:     $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('View Problem Text'))
                    896:                   .'<label><input type="radio" name="vProb" value="no" checked="checked" /> '.&mt('no').' </label>'."\n"
                    897:                   .'<label><input type="radio" name="vProb" value="yes" /> '.&mt('one student').' </label>'."\n"
                    898:                   .'<label><input type="radio" name="vProb" value="all" /> '.&mt('all students').' </label><br />'."\n"
                    899:                   .&Apache::lonhtmlcommon::row_closure();
                    900:     $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('View Answer'))
                    901:                   .'<label><input type="radio" name="vAns" value="no"  /> '.&mt('no').' </label>'."\n"
                    902:                   .'<label><input type="radio" name="vAns" value="yes" /> '.&mt('one student').' </label>'."\n"
                    903:                   .'<label><input type="radio" name="vAns" value="all" checked="checked" /> '.&mt('all students').' </label><br />'."\n"
                    904:                   .&Apache::lonhtmlcommon::row_closure();
1.485     albertel  905: 
                    906:     my $submission_options;
1.257     albertel  907:     if ($env{'form.handgrade'} eq 'yes' && scalar(@$partlist) > 1) {
1.485     albertel  908: 	$submission_options.=
                    909: 	    '<label><input type="radio" name="lastSub" value="hdgrade" '.$checkhdgrade.' /> '.&mt('essay part only').' </label>'."\n";
1.49      albertel  910:     }
1.442     banghart  911:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
                    912:     my $saveStatus = $stu_status eq '' ? 'Active' : $stu_status;
1.257     albertel  913:     $env{'form.Status'} = $saveStatus;
1.485     albertel  914:     $submission_options.=
1.592     bisitz    915:         '<span class="LC_nobreak">'.
                    916:         '<label><input type="radio" name="lastSub" value="lastonly" '.$checklastsub.' /> '.
                    917:         &mt('last submission only').' </label></span>'."\n".
                    918:         '<span class="LC_nobreak">'.
                    919:         '<label><input type="radio" name="lastSub" value="last" /> '.
                    920:         &mt('last submission &amp; parts info').' </label></span>'."\n".
                    921:         '<span class="LC_nobreak">'.
                    922:         '<label><input type="radio" name="lastSub" value="datesub" /> '.
                    923:         &mt('by dates and submissions').'</label></span>'."\n".
                    924:         '<span class="LC_nobreak">'.
                    925:         '<label><input type="radio" name="lastSub" value="all" /> '.
                    926:         &mt('all details').'</label></span>';
1.561     bisitz    927:     $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('Submissions'))
                    928:                   .$submission_options
                    929:                   .&Apache::lonhtmlcommon::row_closure();
                    930: 
                    931:     $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('Grading Increments'))
                    932:                   .'<select name="increment">'
                    933:                   .'<option value="1">'.&mt('Whole Points').'</option>'
                    934:                   .'<option value=".5">'.&mt('Half Points').'</option>'
                    935:                   .'<option value=".25">'.&mt('Quarter Points').'</option>'
                    936:                   .'<option value=".1">'.&mt('Tenths of a Point').'</option>'
                    937:                   .'</select>'
                    938:                   .&Apache::lonhtmlcommon::row_closure();
1.485     albertel  939: 
                    940:     $gradeTable .= 
1.432     banghart  941:         &build_section_inputs().
1.45      ng        942: 	'<input type="hidden" name="submitonly"  value="'.$submitonly.'" />'."\n".
1.257     albertel  943: 	'<input type="hidden" name="handgrade"   value="'.$env{'form.handgrade'}.'" /><br />'."\n".
                    944: 	'<input type="hidden" name="showgrading" value="'.$env{'form.showgrading'}.'" /><br />'."\n".
                    945: 	'<input type="hidden" name="saveState"   value="'.$env{'form.saveState'}.'" />'."\n".
1.418     albertel  946: 	'<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.110     ng        947: 	'<input type="hidden" name="saveStatusOld" value="'.$saveStatus.'" />'."\n";
                    948: 
1.257     albertel  949:     if (exists($env{'form.gradingMenu'}) && exists($env{'form.Status'})) {
1.561     bisitz    950: 	$gradeTable .= '<input type="hidden" name="Status" value="'.$stu_status.'" />'."\n";
1.124     ng        951:     } else {
1.561     bisitz    952:         $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('Student Status'))
                    953:                       .&Apache::lonhtmlcommon::StatusOptions(
                    954:                            $saveStatus,undef,1,'javascript:reLoadList(this.form);')
                    955:                       .&Apache::lonhtmlcommon::row_closure();
1.124     ng        956:     }
1.112     ng        957: 
1.561     bisitz    958:     $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('Check For Plagiarism'))
                    959:                   .'<input type="checkbox" name="checkPlag" checked="checked" />'
                    960:                   .&Apache::lonhtmlcommon::row_closure(1)
                    961:                   .&Apache::lonhtmlcommon::end_pick_box();
                    962: 
                    963:     $gradeTable .= '<p>'
                    964:                   .&mt('To '.lc($viewgrade)." 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"
                    965:                   .'<input type="hidden" name="command" value="processGroup" />'
                    966:                   .'</p>';
1.249     albertel  967: 
                    968: # checkall buttons
                    969:     $gradeTable.=&check_script('gradesub', 'stuinfo');
1.110     ng        970:     $gradeTable.='<input type="button" '."\n".
1.589     bisitz    971:         'onclick="javascript:checkSelect(this.form.stuinfo);" '."\n".
                    972:         'value="'.&mt('Next').' &rarr;" /> <br />'."\n";
1.249     albertel  973:     $gradeTable.=&check_buttons();
1.450     banghart  974:     my ($classlist, undef, $fullname) = &getclasslist($getsec,'1',$getgroup);
1.474     albertel  975:     $gradeTable.= &Apache::loncommon::start_data_table().
                    976: 	&Apache::loncommon::start_data_table_header_row();
1.110     ng        977:     my $loop = 0;
                    978:     while ($loop < 2) {
1.485     albertel  979: 	$gradeTable.='<th>'.&mt('No.').'</th><th>'.&mt('Select').'</th>'.
                    980: 	    '<th>'.&nameUserString('header').'&nbsp;'.&mt('Section/Group').'</th>';
1.301     albertel  981: 	if ($env{'form.showgrading'} eq 'yes' 
                    982: 	    && $submitonly ne 'queued'
                    983: 	    && $submitonly ne 'all') {
1.485     albertel  984: 	    foreach my $part (sort(@$partlist)) {
                    985: 		my $display_part=
                    986: 		    &get_display_part((split(/_/,$part))[0],$symb);
                    987: 		$gradeTable.=
                    988: 		    '<th>'.&mt('Part: [_1] Status',$display_part).'</th>';
1.110     ng        989: 	    }
1.301     albertel  990: 	} elsif ($submitonly eq 'queued') {
1.474     albertel  991: 	    $gradeTable.='<th>'.&mt('Queue Status').'&nbsp;</th>';
1.110     ng        992: 	}
                    993: 	$loop++;
1.126     ng        994: #	$gradeTable.='<td></td>' if ($loop%2 ==1);
1.41      ng        995:     }
1.474     albertel  996:     $gradeTable.=&Apache::loncommon::end_data_table_header_row()."\n";
1.41      ng        997: 
1.45      ng        998:     my $ctr = 0;
1.294     albertel  999:     foreach my $student (sort 
                   1000: 			 {
                   1001: 			     if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                   1002: 				 return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                   1003: 			     }
                   1004: 			     return $a cmp $b;
                   1005: 			 }
                   1006: 			 (keys(%$fullname))) {
1.41      ng       1007: 	my ($uname,$udom) = split(/:/,$student);
1.301     albertel 1008: 
1.110     ng       1009: 	my %status = ();
1.301     albertel 1010: 
                   1011: 	if ($submitonly eq 'queued') {
                   1012: 	    my %queue_status = 
                   1013: 		&Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
                   1014: 							$udom,$uname);
                   1015: 	    next if (!defined($queue_status{'gradingqueue'}));
                   1016: 	    $status{'gradingqueue'} = $queue_status{'gradingqueue'};
                   1017: 	}
                   1018: 
                   1019: 	if ($env{'form.showgrading'} eq 'yes' 
                   1020: 	    && $submitonly ne 'queued'
                   1021: 	    && $submitonly ne 'all') {
1.324     albertel 1022: 	    (%status) =&student_gradeStatus($symb,$udom,$uname,$partlist);
1.145     albertel 1023: 	    my $submitted = 0;
1.164     albertel 1024: 	    my $graded = 0;
1.248     albertel 1025: 	    my $incorrect = 0;
1.110     ng       1026: 	    foreach (keys(%status)) {
1.145     albertel 1027: 		$submitted = 1 if ($status{$_} ne 'nothing');
1.248     albertel 1028: 		$graded = 1 if ($status{$_} =~ /^ungraded/);
                   1029: 		$incorrect = 1 if ($status{$_} =~ /^incorrect/);
                   1030: 		
1.110     ng       1031: 		my ($foo,$partid,$foo1) = split(/\./,$_);
                   1032: 		if ($status{'resource.'.$partid.'.submitted_by'} ne '') {
1.145     albertel 1033: 		    $submitted = 0;
1.150     albertel 1034: 		    my ($part)=split(/\./,$partid);
1.110     ng       1035: 		    $gradeTable.='<input type="hidden" name="'.
1.150     albertel 1036: 			$student.':'.$part.':submitted_by" value="'.
1.110     ng       1037: 			$status{'resource.'.$partid.'.submitted_by'}.'" />';
                   1038: 		}
1.41      ng       1039: 	    }
1.248     albertel 1040: 	    
1.156     albertel 1041: 	    next if (!$submitted && ($submitonly eq 'yes' ||
                   1042: 				     $submitonly eq 'incorrect' ||
                   1043: 				     $submitonly eq 'graded'));
1.248     albertel 1044: 	    next if (!$graded && ($submitonly eq 'graded'));
                   1045: 	    next if (!$incorrect && $submitonly eq 'incorrect');
1.41      ng       1046: 	}
1.34      ng       1047: 
1.45      ng       1048: 	$ctr++;
1.249     albertel 1049: 	my $section = $classlist->{$student}->[&Apache::loncoursedata::CL_SECTION()];
1.452     banghart 1050:         my $group = $classlist->{$student}->[&Apache::loncoursedata::CL_GROUP()];
1.104     albertel 1051: 	if ( $perm{'vgr'} eq 'F' ) {
1.474     albertel 1052: 	    if ($ctr%2 ==1) {
                   1053: 		$gradeTable.= &Apache::loncommon::start_data_table_row();
                   1054: 	    }
1.126     ng       1055: 	    $gradeTable.='<td align="right">'.$ctr.'&nbsp;</td>'.
1.563     bisitz   1056:                '<td align="center"><label><input type="checkbox" name="stuinfo" value="'.
1.249     albertel 1057:                $student.':'.$$fullname{$student}.':::SECTION'.$section.
                   1058: 	       ')&nbsp;" />&nbsp;&nbsp;</label></td>'."\n".'<td>'.
                   1059: 	       &nameUserString(undef,$$fullname{$student},$uname,$udom).
1.474     albertel 1060: 	       '&nbsp;'.$section.($group ne '' ?'/'.$group:'').'</td>'."\n";
1.110     ng       1061: 
1.257     albertel 1062: 	    if ($env{'form.showgrading'} eq 'yes' && $submitonly ne 'all') {
1.524     raeburn  1063: 		foreach (sort(keys(%status))) {
1.485     albertel 1064: 		    next if ($_ =~ /^resource.*?submitted_by$/);
                   1065: 		    $gradeTable.='<td align="center">&nbsp;'.&mt($status{$_}).'&nbsp;</td>'."\n";
1.110     ng       1066: 		}
1.41      ng       1067: 	    }
1.126     ng       1068: #	    $gradeTable.='<td></td>' if ($ctr%2 ==1);
1.474     albertel 1069: 	    if ($ctr%2 ==0) {
                   1070: 		$gradeTable.=&Apache::loncommon::end_data_table_row()."\n";
                   1071: 	    }
1.41      ng       1072: 	}
                   1073:     }
1.110     ng       1074:     if ($ctr%2 ==1) {
1.126     ng       1075: 	$gradeTable.='<td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td>';
1.301     albertel 1076: 	    if ($env{'form.showgrading'} eq 'yes' 
                   1077: 		&& $submitonly ne 'queued'
                   1078: 		&& $submitonly ne 'all') {
1.110     ng       1079: 		foreach (@$partlist) {
                   1080: 		    $gradeTable.='<td>&nbsp;</td>';
                   1081: 		}
1.301     albertel 1082: 	    } elsif ($submitonly eq 'queued') {
                   1083: 		$gradeTable.='<td>&nbsp;</td>';
1.110     ng       1084: 	    }
1.474     albertel 1085: 	$gradeTable.=&Apache::loncommon::end_data_table_row();
1.110     ng       1086:     }
                   1087: 
1.474     albertel 1088:     $gradeTable.=&Apache::loncommon::end_data_table()."\n".
1.589     bisitz   1089:         '<input type="button" '.
                   1090:         'onclick="javascript:checkSelect(this.form.stuinfo);" '.
                   1091:         'value="'.&mt('Next').' &rarr;" /></form>'."\n";
1.45      ng       1092:     if ($ctr == 0) {
1.96      albertel 1093: 	my $num_students=(scalar(keys(%$fullname)));
                   1094: 	if ($num_students eq 0) {
1.485     albertel 1095: 	    $gradeTable='<br />&nbsp;<span class="LC_warning">'.&mt('There are no students currently enrolled.').'</span>';
1.96      albertel 1096: 	} else {
1.171     albertel 1097: 	    my $submissions='submissions';
                   1098: 	    if ($submitonly eq 'incorrect') { $submissions = 'incorrect submissions'; }
                   1099: 	    if ($submitonly eq 'graded'   ) { $submissions = 'ungraded submissions'; }
1.301     albertel 1100: 	    if ($submitonly eq 'queued'   ) { $submissions = 'queued submissions'; }
1.398     albertel 1101: 	    $gradeTable='<br />&nbsp;<span class="LC_warning">'.
1.485     albertel 1102: 		&mt('No '.$submissions.' found for this resource for any students. ([_1] students checked for '.$submissions.')',
                   1103: 		    $num_students).
                   1104: 		'</span><br />';
1.96      albertel 1105: 	}
1.46      ng       1106:     } elsif ($ctr == 1) {
1.474     albertel 1107: 	$gradeTable =~ s/type="checkbox"/type="checkbox" checked="checked"/;
1.45      ng       1108:     }
1.324     albertel 1109:     $gradeTable.=&show_grading_menu_form($symb);
1.45      ng       1110:     $request->print($gradeTable);
1.44      ng       1111:     return '';
1.10      ng       1112: }
                   1113: 
1.44      ng       1114: #---- Called from the listStudents routine
1.249     albertel 1115: 
                   1116: sub check_script {
                   1117:     my ($form, $type)=@_;
1.597     wenzelju 1118:     my $chkallscript= &Apache::lonhtmlcommon::scripttag('
1.249     albertel 1119:     function checkall() {
                   1120:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
                   1121:             ele = document.forms.'.$form.'.elements[i];
                   1122:             if (ele.name == "'.$type.'") {
                   1123:             document.forms.'.$form.'.elements[i].checked=true;
                   1124:                                        }
                   1125:         }
                   1126:     }
                   1127: 
                   1128:     function checksec() {
                   1129:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
                   1130:             ele = document.forms.'.$form.'.elements[i];
                   1131:            string = document.forms.'.$form.'.chksec.value;
                   1132:            if
                   1133:           (ele.value.indexOf(":::SECTION"+string)>0) {
                   1134:               document.forms.'.$form.'.elements[i].checked=true;
                   1135:             }
                   1136:         }
                   1137:     }
                   1138: 
                   1139: 
                   1140:     function uncheckall() {
                   1141:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
                   1142:             ele = document.forms.'.$form.'.elements[i];
                   1143:             if (ele.name == "'.$type.'") {
                   1144:             document.forms.'.$form.'.elements[i].checked=false;
                   1145:                                        }
                   1146:         }
                   1147:     }
                   1148: 
1.597     wenzelju 1149: '."\n");
1.249     albertel 1150:     return $chkallscript;
                   1151: }
                   1152: 
                   1153: sub check_buttons {
1.485     albertel 1154:     my $buttons.='<input type="button" onclick="checkall()" value="'.&mt('Check All').'" />';
                   1155:     $buttons.='<input type="button" onclick="uncheckall()" value="'.&mt('Uncheck All').'" />&nbsp;';
                   1156:     $buttons.='<input type="button" onclick="checksec()" value="'.&mt('Check Section/Group').'" />';
1.249     albertel 1157:     $buttons.='<input type="text" size="5" name="chksec" />&nbsp;';
                   1158:     return $buttons;
                   1159: }
                   1160: 
1.44      ng       1161: #     Displays the submissions for one student or a group of students
1.34      ng       1162: sub processGroup {
1.41      ng       1163:     my ($request)  = shift;
                   1164:     my $ctr        = 0;
1.155     albertel 1165:     my @stuchecked = &Apache::loncommon::get_env_multiple('form.stuinfo');
1.41      ng       1166:     my $total      = scalar(@stuchecked)-1;
1.45      ng       1167: 
1.396     banghart 1168:     foreach my $student (@stuchecked) {
                   1169: 	my ($uname,$udom,$fullname) = split(/:/,$student);
1.257     albertel 1170: 	$env{'form.student'}        = $uname;
                   1171: 	$env{'form.userdom'}        = $udom;
                   1172: 	$env{'form.fullname'}       = $fullname;
1.41      ng       1173: 	&submission($request,$ctr,$total);
                   1174: 	$ctr++;
                   1175:     }
                   1176:     return '';
1.35      ng       1177: }
1.34      ng       1178: 
1.44      ng       1179: #------------------------------------------------------------------------------------
                   1180: #
                   1181: #-------------------------- Next few routines handles grading by student, essentially
                   1182: #                           handles essay response type problem/part
                   1183: #
                   1184: #--- Javascript to handle the submission page functionality ---
                   1185: sub sub_page_js {
                   1186:     my $request = shift;
1.539     riegler  1187: 	    my $alertmsg = &mt('A number equal or greater than 0 is expected. Entered value = ');
1.597     wenzelju 1188:     $request->print(&Apache::lonhtmlcommon::scripttag(<<SUBJAVASCRIPT));
1.71      ng       1189:     function updateRadio(formname,id,weight) {
1.125     ng       1190: 	var gradeBox = formname["GD_BOX"+id];
                   1191: 	var radioButton = formname["RADVAL"+id];
                   1192: 	var oldpts = formname["oldpts"+id].value;
1.72      ng       1193: 	var pts = checkSolved(formname,id) == 'update' ? gradeBox.value : oldpts;
1.71      ng       1194: 	gradeBox.value = pts;
                   1195: 	var resetbox = false;
                   1196: 	if (isNaN(pts) || pts < 0) {
1.539     riegler  1197: 	    alert("$alertmsg"+pts);
1.71      ng       1198: 	    for (var i=0; i<radioButton.length; i++) {
                   1199: 		if (radioButton[i].checked) {
                   1200: 		    gradeBox.value = i;
                   1201: 		    resetbox = true;
                   1202: 		}
                   1203: 	    }
                   1204: 	    if (!resetbox) {
                   1205: 		formtextbox.value = "";
                   1206: 	    }
                   1207: 	    return;
1.44      ng       1208: 	}
1.71      ng       1209: 
                   1210: 	if (pts > weight) {
                   1211: 	    var resp = confirm("You entered a value ("+pts+
                   1212: 			       ") greater than the weight for the part. Accept?");
                   1213: 	    if (resp == false) {
1.125     ng       1214: 		gradeBox.value = oldpts;
1.71      ng       1215: 		return;
                   1216: 	    }
1.44      ng       1217: 	}
1.13      albertel 1218: 
1.71      ng       1219: 	for (var i=0; i<radioButton.length; i++) {
                   1220: 	    radioButton[i].checked=false;
                   1221: 	    if (pts == i && pts != "") {
                   1222: 		radioButton[i].checked=true;
                   1223: 	    }
                   1224: 	}
                   1225: 	updateSelect(formname,id);
1.125     ng       1226: 	formname["stores"+id].value = "0";
1.41      ng       1227:     }
1.5       albertel 1228: 
1.72      ng       1229:     function writeBox(formname,id,pts) {
1.125     ng       1230: 	var gradeBox = formname["GD_BOX"+id];
1.71      ng       1231: 	if (checkSolved(formname,id) == 'update') {
                   1232: 	    gradeBox.value = pts;
                   1233: 	} else {
1.125     ng       1234: 	    var oldpts = formname["oldpts"+id].value;
1.72      ng       1235: 	    gradeBox.value = oldpts;
1.125     ng       1236: 	    var radioButton = formname["RADVAL"+id];
1.71      ng       1237: 	    for (var i=0; i<radioButton.length; i++) {
                   1238: 		radioButton[i].checked=false;
1.72      ng       1239: 		if (i == oldpts) {
1.71      ng       1240: 		    radioButton[i].checked=true;
                   1241: 		}
                   1242: 	    }
1.41      ng       1243: 	}
1.125     ng       1244: 	formname["stores"+id].value = "0";
1.71      ng       1245: 	updateSelect(formname,id);
                   1246: 	return;
1.41      ng       1247:     }
1.44      ng       1248: 
1.71      ng       1249:     function clearRadBox(formname,id) {
                   1250: 	if (checkSolved(formname,id) == 'noupdate') {
                   1251: 	    updateSelect(formname,id);
                   1252: 	    return;
                   1253: 	}
1.125     ng       1254: 	gradeSelect = formname["GD_SEL"+id];
1.71      ng       1255: 	for (var i=0; i<gradeSelect.length; i++) {
                   1256: 	    if (gradeSelect[i].selected) {
                   1257: 		var selectx=i;
                   1258: 	    }
                   1259: 	}
1.125     ng       1260: 	var stores = formname["stores"+id];
1.71      ng       1261: 	if (selectx == stores.value) { return };
1.125     ng       1262: 	var gradeBox = formname["GD_BOX"+id];
1.71      ng       1263: 	gradeBox.value = "";
1.125     ng       1264: 	var radioButton = formname["RADVAL"+id];
1.71      ng       1265: 	for (var i=0; i<radioButton.length; i++) {
                   1266: 	    radioButton[i].checked=false;
                   1267: 	}
                   1268: 	stores.value = selectx;
                   1269:     }
1.5       albertel 1270: 
1.71      ng       1271:     function checkSolved(formname,id) {
1.125     ng       1272: 	if (formname["solved"+id].value == "correct_by_student" && formname.overRideScore.value == 'no') {
1.118     ng       1273: 	    var reply = confirm("This problem has been graded correct by the computer. Do you want to change the score?");
                   1274: 	    if (!reply) {return "noupdate";}
1.120     ng       1275: 	    formname.overRideScore.value = 'yes';
1.41      ng       1276: 	}
1.71      ng       1277: 	return "update";
1.13      albertel 1278:     }
1.71      ng       1279: 
                   1280:     function updateSelect(formname,id) {
1.125     ng       1281: 	formname["GD_SEL"+id][0].selected = true;
1.71      ng       1282: 	return;
1.41      ng       1283:     }
1.33      ng       1284: 
1.121     ng       1285: //=========== Check that a point is assigned for all the parts  ============
1.71      ng       1286:     function checksubmit(formname,val,total,parttot) {
1.121     ng       1287: 	formname.gradeOpt.value = val;
1.71      ng       1288: 	if (val == "Save & Next") {
                   1289: 	    for (i=0;i<=total;i++) {
                   1290: 		for (j=0;j<parttot;j++) {
1.125     ng       1291: 		    var partid = formname["partid"+i+"_"+j].value;
1.127     ng       1292: 		    if (formname["GD_SEL"+i+"_"+partid][0].selected) {
1.125     ng       1293: 			var points = formname["GD_BOX"+i+"_"+partid].value;
1.71      ng       1294: 			if (points == "") {
1.125     ng       1295: 			    var name = formname["name"+i].value;
1.129     ng       1296: 			    var studentID = (name != '' ? name : formname["unamedom"+i].value);
                   1297: 			    var resp = confirm("You did not assign a score for "+studentID+
                   1298: 					       ", part "+partid+". Continue?");
1.71      ng       1299: 			    if (resp == false) {
1.125     ng       1300: 				formname["GD_BOX"+i+"_"+partid].focus();
1.71      ng       1301: 				return false;
                   1302: 			    }
                   1303: 			}
                   1304: 		    }
                   1305: 		    
                   1306: 		}
                   1307: 	    }
                   1308: 	    
                   1309: 	}
1.121     ng       1310: 	if (val == "Grade Student") {
                   1311: 	    formname.showgrading.value = "yes";
                   1312: 	    if (formname.Status.value == "") {
                   1313: 		formname.Status.value = "Active";
                   1314: 	    }
                   1315: 	    formname.studentNo.value = total;
                   1316: 	}
1.120     ng       1317: 	formname.submit();
                   1318:     }
                   1319: 
1.71      ng       1320: //======= Check that a score is assigned for all the problems (page/sequence grading only) =========
                   1321:     function checkSubmitPage(formname,total) {
                   1322: 	noscore = new Array(100);
                   1323: 	var ptr = 0;
                   1324: 	for (i=1;i<total;i++) {
1.125     ng       1325: 	    var partid = formname["q_"+i].value;
1.127     ng       1326: 	    if (formname["GD_SEL"+i+"_"+partid][0].selected) {
1.125     ng       1327: 		var points = formname["GD_BOX"+i+"_"+partid].value;
                   1328: 		var status = formname["solved"+i+"_"+partid].value;
1.71      ng       1329: 		if (points == "" && status != "correct_by_student") {
                   1330: 		    noscore[ptr] = i;
                   1331: 		    ptr++;
                   1332: 		}
                   1333: 	    }
                   1334: 	}
                   1335: 	if (ptr != 0) {
                   1336: 	    var sense = ptr == 1 ? ": " : "s: ";
                   1337: 	    var prolist = "";
                   1338: 	    if (ptr == 1) {
                   1339: 		prolist = noscore[0];
                   1340: 	    } else {
                   1341: 		var i = 0;
                   1342: 		while (i < ptr-1) {
                   1343: 		    prolist += noscore[i]+", ";
                   1344: 		    i++;
                   1345: 		}
                   1346: 		prolist += "and "+noscore[i];
                   1347: 	    }
                   1348: 	    var resp = confirm("You did not assign any score for the following problem"+sense+prolist+". Continue?");
                   1349: 	    if (resp == false) {
                   1350: 		return false;
                   1351: 	    }
                   1352: 	}
1.45      ng       1353: 
1.71      ng       1354: 	formname.submit();
                   1355:     }
                   1356: SUBJAVASCRIPT
                   1357: }
1.45      ng       1358: 
1.71      ng       1359: #--- javascript for essay type problem --
                   1360: sub sub_page_kw_js {
                   1361:     my $request = shift;
1.80      ng       1362:     my $iconpath = $request->dir_config('lonIconsURL');
1.118     ng       1363:     &commonJSfunctions($request);
1.350     albertel 1364: 
1.597     wenzelju 1365:     my $inner_js_msg_central= &Apache::lonhtmlcommon::scripttag(<<INNERJS);
1.350     albertel 1366:     function checkInput() {
                   1367:       opener.document.SCORE.msgsub.value = opener.checkEntities(document.msgcenter.msgsub.value);
                   1368:       var nmsg   = opener.document.SCORE.savemsgN.value;
                   1369:       var usrctr = document.msgcenter.usrctr.value;
                   1370:       var newval = opener.document.SCORE["newmsg"+usrctr];
                   1371:       newval.value = opener.checkEntities(document.msgcenter.newmsg.value);
                   1372: 
                   1373:       var msgchk = "";
                   1374:       if (document.msgcenter.subchk.checked) {
                   1375:          msgchk = "msgsub,";
                   1376:       }
                   1377:       var includemsg = 0;
                   1378:       for (var i=1; i<=nmsg; i++) {
                   1379:           var opnmsg = opener.document.SCORE["savemsg"+i];
                   1380:           var frmmsg = document.msgcenter["msg"+i];
                   1381:           opnmsg.value = opener.checkEntities(frmmsg.value);
                   1382:           var showflg = opener.document.SCORE["shownOnce"+i];
                   1383:           showflg.value = "1";
                   1384:           var chkbox = document.msgcenter["msgn"+i];
                   1385:           if (chkbox.checked) {
                   1386:              msgchk += "savemsg"+i+",";
                   1387:              includemsg = 1;
                   1388:           }
                   1389:       }
                   1390:       if (document.msgcenter.newmsgchk.checked) {
                   1391:          msgchk += "newmsg"+usrctr;
                   1392:          includemsg = 1;
                   1393:       }
                   1394:       imgformname = opener.document.SCORE["mailicon"+usrctr];
                   1395:       imgformname.src = "$iconpath/"+((includemsg) ? "mailto.gif" : "mailbkgrd.gif");
                   1396:       var includemsg = opener.document.SCORE["includemsg"+usrctr];
                   1397:       includemsg.value = msgchk;
                   1398: 
                   1399:       self.close()
                   1400: 
                   1401:     }
                   1402: INNERJS
                   1403: 
1.597     wenzelju 1404:     my $inner_js_highlight_central= &Apache::lonhtmlcommon::scripttag(<<INNERJS);
1.351     albertel 1405:     function updateChoice(flag) {
                   1406:       opener.document.SCORE.kwclr.value = opener.radioSelection(document.hlCenter.kwdclr);
                   1407:       opener.document.SCORE.kwsize.value = opener.radioSelection(document.hlCenter.kwdsize);
                   1408:       opener.document.SCORE.kwstyle.value = opener.radioSelection(document.hlCenter.kwdstyle);
                   1409:       opener.document.SCORE.refresh.value = "on";
                   1410:       if (opener.document.SCORE.keywords.value!=""){
                   1411:          opener.document.SCORE.submit();
                   1412:       }
                   1413:       self.close()
                   1414:     }
                   1415: INNERJS
                   1416: 
                   1417:     my $start_page_msg_central = 
                   1418:         &Apache::loncommon::start_page('Message Central',$inner_js_msg_central,
                   1419: 				       {'js_ready'  => 1,
                   1420: 					'only_body' => 1,
                   1421: 					'bgcolor'   =>'#FFFFFF',});
                   1422:     my $end_page_msg_central = 
                   1423: 	&Apache::loncommon::end_page({'js_ready' => 1});
                   1424: 
                   1425: 
                   1426:     my $start_page_highlight_central = 
                   1427:         &Apache::loncommon::start_page('Highlight Central',
                   1428: 				       $inner_js_highlight_central,
1.350     albertel 1429: 				       {'js_ready'  => 1,
                   1430: 					'only_body' => 1,
                   1431: 					'bgcolor'   =>'#FFFFFF',});
1.351     albertel 1432:     my $end_page_highlight_central = 
1.350     albertel 1433: 	&Apache::loncommon::end_page({'js_ready' => 1});
                   1434: 
1.219     www      1435:     my $docopen=&Apache::lonhtmlcommon::javascript_docopen();
1.236     albertel 1436:     $docopen=~s/^document\.//;
1.539     riegler  1437:     my $alertmsg = &mt('Please select a word or group of words from document and then click this link.');
1.597     wenzelju 1438:     $request->print(&Apache::lonhtmlcommon::scripttag(<<SUBJAVASCRIPT));
1.45      ng       1439: 
1.44      ng       1440: //===================== Show list of keywords ====================
1.122     ng       1441:   function keywords(formname) {
                   1442:     var nret = prompt("Keywords list, separated by a space. Add/delete to list if desired.",formname.keywords.value);
1.44      ng       1443:     if (nret==null) return;
1.122     ng       1444:     formname.keywords.value = nret;
1.44      ng       1445: 
1.122     ng       1446:     if (formname.keywords.value != "") {
1.128     ng       1447: 	formname.refresh.value = "on";
1.122     ng       1448: 	formname.submit();
1.44      ng       1449:     }
                   1450:     return;
                   1451:   }
                   1452: 
                   1453: //===================== Script to view submitted by ==================
                   1454:   function viewSubmitter(submitter) {
                   1455:     document.SCORE.refresh.value = "on";
                   1456:     document.SCORE.NCT.value = "1";
                   1457:     document.SCORE.unamedom0.value = submitter;
                   1458:     document.SCORE.submit();
                   1459:     return;
                   1460:   }
                   1461: 
                   1462: //===================== Script to add keyword(s) ==================
                   1463:   function getSel() {
                   1464:     if (document.getSelection) txt = document.getSelection();
                   1465:     else if (document.selection) txt = document.selection.createRange().text;
                   1466:     else return;
                   1467:     var cleantxt = txt.replace(new RegExp('([\\f\\n\\r\\t\\v ])+', 'g')," ");
                   1468:     if (cleantxt=="") {
1.539     riegler  1469: 	alert("$alertmsg");
1.44      ng       1470: 	return;
                   1471:     }
                   1472:     var nret = prompt("Add selection to keyword list? Edit if desired.",cleantxt);
                   1473:     if (nret==null) return;
1.127     ng       1474:     document.SCORE.keywords.value = document.SCORE.keywords.value+" "+nret;
1.44      ng       1475:     if (document.SCORE.keywords.value != "") {
1.127     ng       1476: 	document.SCORE.refresh.value = "on";
1.44      ng       1477: 	document.SCORE.submit();
                   1478:     }
                   1479:     return;
                   1480:   }
                   1481: 
                   1482: //====================== Script for composing message ==============
1.80      ng       1483:    // preload images
                   1484:    img1 = new Image();
                   1485:    img1.src = "$iconpath/mailbkgrd.gif";
                   1486:    img2 = new Image();
                   1487:    img2.src = "$iconpath/mailto.gif";
                   1488: 
1.44      ng       1489:   function msgCenter(msgform,usrctr,fullname) {
                   1490:     var Nmsg  = msgform.savemsgN.value;
                   1491:     savedMsgHeader(Nmsg,usrctr,fullname);
                   1492:     var subject = msgform.msgsub.value;
1.127     ng       1493:     var msgchk = document.SCORE["includemsg"+usrctr].value;
1.44      ng       1494:     re = /msgsub/;
                   1495:     var shwsel = "";
                   1496:     if (re.test(msgchk)) { shwsel = "checked" }
1.123     ng       1497:     subject = (document.SCORE.shownSub.value == 0 ? checkEntities(subject) : subject);
                   1498:     displaySubject(checkEntities(subject),shwsel);
1.44      ng       1499:     for (var i=1; i<=Nmsg; i++) {
1.123     ng       1500: 	var testmsg = "savemsg"+i+",";
                   1501: 	re = new RegExp(testmsg,"g");
1.44      ng       1502: 	shwsel = "";
                   1503: 	if (re.test(msgchk)) { shwsel = "checked" }
1.125     ng       1504: 	var message = document.SCORE["savemsg"+i].value;
1.126     ng       1505: 	message = (document.SCORE["shownOnce"+i].value == 0 ? checkEntities(message) : message);
1.123     ng       1506: 	displaySavedMsg(i,message,shwsel); //I do not get it. w/o checkEntities on saved messages,
                   1507: 	                                   //any &lt; is already converted to <, etc. However, only once!!
1.44      ng       1508:     }
1.125     ng       1509:     newmsg = document.SCORE["newmsg"+usrctr].value;
1.44      ng       1510:     shwsel = "";
                   1511:     re = /newmsg/;
                   1512:     if (re.test(msgchk)) { shwsel = "checked" }
                   1513:     newMsg(newmsg,shwsel);
                   1514:     msgTail(); 
                   1515:     return;
                   1516:   }
                   1517: 
1.123     ng       1518:   function checkEntities(strx) {
                   1519:     if (strx.length == 0) return strx;
                   1520:     var orgStr = ["&", "<", ">", '"']; 
                   1521:     var newStr = ["&amp;", "&lt;", "&gt;", "&quot;"];
                   1522:     var counter = 0;
                   1523:     while (counter < 4) {
                   1524: 	strx = strReplace(strx,orgStr[counter],newStr[counter]);
                   1525: 	counter++;
                   1526:     }
                   1527:     return strx;
                   1528:   }
                   1529: 
                   1530:   function strReplace(strx, orgStr, newStr) {
                   1531:     return strx.split(orgStr).join(newStr);
                   1532:   }
                   1533: 
1.44      ng       1534:   function savedMsgHeader(Nmsg,usrctr,fullname) {
1.76      ng       1535:     var height = 70*Nmsg+250;
1.44      ng       1536:     var scrollbar = "no";
                   1537:     if (height > 600) {
                   1538: 	height = 600;
                   1539: 	scrollbar = "yes";
                   1540:     }
1.118     ng       1541:     var xpos = (screen.width-600)/2;
                   1542:     xpos = (xpos < 0) ? '0' : xpos;
                   1543:     var ypos = (screen.height-height)/2-30;
                   1544:     ypos = (ypos < 0) ? '0' : ypos;
                   1545: 
1.206     albertel 1546:     pWin = window.open('', 'MessageCenter', 'resizable=yes,toolbar=no,location=no,scrollbars='+scrollbar+',screenx='+xpos+',screeny='+ypos+',width=600,height='+height);
1.76      ng       1547:     pWin.focus();
                   1548:     pDoc = pWin.document;
1.219     www      1549:     pDoc.$docopen;
1.351     albertel 1550:     pDoc.write('$start_page_msg_central');
1.76      ng       1551: 
                   1552:     pDoc.write("<form action=\\"inactive\\" name=\\"msgcenter\\">");
                   1553:     pDoc.write("<input value=\\""+usrctr+"\\" name=\\"usrctr\\" type=\\"hidden\\">");
1.465     albertel 1554:     pDoc.write("<h3><span class=\\"LC_info\\">&nbsp;Compose Message for \"+fullname+\"<\\/span><\\/h3><br /><br />");
1.76      ng       1555: 
1.564     bisitz   1556:     pDoc.write('<table border="0" width="100%"><tr><td bgcolor="#777777">');
                   1557:     pDoc.write('<table border="0" width="100%"><tr bgcolor="#DDFFFF">');
1.465     albertel 1558:     pDoc.write("<td><b>Type<\\/b><\\/td><td><b>Include<\\/b><\\/td><td><b>Message<\\/td><\\/tr>");
1.44      ng       1559: }
                   1560:     function displaySubject(msg,shwsel) {
1.76      ng       1561:     pDoc = pWin.document;
                   1562:     pDoc.write("<tr bgcolor=\\"#ffffdd\\">");
1.465     albertel 1563:     pDoc.write("<td>Subject<\\/td>");
                   1564:     pDoc.write("<td align=\\"center\\"><input name=\\"subchk\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
                   1565:     pDoc.write("<td><input name=\\"msgsub\\" type=\\"text\\" value=\\""+msg+"\\"size=\\"60\\" maxlength=\\"80\\"><\\/td><\\/tr>");
1.44      ng       1566: }
                   1567: 
1.72      ng       1568:   function displaySavedMsg(ctr,msg,shwsel) {
1.76      ng       1569:     pDoc = pWin.document;
                   1570:     pDoc.write("<tr bgcolor=\\"#ffffdd\\">");
1.465     albertel 1571:     pDoc.write("<td align=\\"center\\">"+ctr+"<\\/td>");
                   1572:     pDoc.write("<td align=\\"center\\"><input name=\\"msgn"+ctr+"\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
                   1573:     pDoc.write("<td><textarea name=\\"msg"+ctr+"\\" cols=\\"60\\" rows=\\"3\\">"+msg+"<\\/textarea><\\/td><\\/tr>");
1.44      ng       1574: }
                   1575: 
                   1576:   function newMsg(newmsg,shwsel) {
1.76      ng       1577:     pDoc = pWin.document;
                   1578:     pDoc.write("<tr bgcolor=\\"#ffffdd\\">");
1.465     albertel 1579:     pDoc.write("<td align=\\"center\\">New<\\/td>");
                   1580:     pDoc.write("<td align=\\"center\\"><input name=\\"newmsgchk\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
                   1581:     pDoc.write("<td><textarea name=\\"newmsg\\" cols=\\"60\\" rows=\\"3\\" onchange=\\"javascript:this.form.newmsgchk.checked=true\\" >"+newmsg+"<\\/textarea><\\/td><\\/tr>");
1.44      ng       1582: }
                   1583: 
                   1584:   function msgTail() {
1.76      ng       1585:     pDoc = pWin.document;
1.465     albertel 1586:     pDoc.write("<\\/table>");
                   1587:     pDoc.write("<\\/td><\\/tr><\\/table>&nbsp;");
1.589     bisitz   1588:     pDoc.write("<input type=\\"button\\" value=\\"Save\\" onclick=\\"javascript:checkInput()\\">&nbsp;&nbsp;");
                   1589:     pDoc.write("<input type=\\"button\\" value=\\"Cancel\\" onclick=\\"self.close()\\"><br /><br />");
1.465     albertel 1590:     pDoc.write("<\\/form>");
1.351     albertel 1591:     pDoc.write('$end_page_msg_central');
1.128     ng       1592:     pDoc.close();
1.44      ng       1593: }
                   1594: 
                   1595: //====================== Script for keyword highlight options ==============
                   1596:   function kwhighlight() {
                   1597:     var kwclr    = document.SCORE.kwclr.value;
                   1598:     var kwsize   = document.SCORE.kwsize.value;
                   1599:     var kwstyle  = document.SCORE.kwstyle.value;
                   1600:     var redsel = "";
                   1601:     var grnsel = "";
                   1602:     var blusel = "";
                   1603:     if (kwclr=="red")   {var redsel="checked"};
                   1604:     if (kwclr=="green") {var grnsel="checked"};
                   1605:     if (kwclr=="blue")  {var blusel="checked"};
                   1606:     var sznsel = "";
                   1607:     var sz1sel = "";
                   1608:     var sz2sel = "";
                   1609:     if (kwsize=="0")  {var sznsel="checked"};
                   1610:     if (kwsize=="+1") {var sz1sel="checked"};
                   1611:     if (kwsize=="+2") {var sz2sel="checked"};
                   1612:     var synsel = "";
                   1613:     var syisel = "";
                   1614:     var sybsel = "";
                   1615:     if (kwstyle=="")    {var synsel="checked"};
                   1616:     if (kwstyle=="<i>") {var syisel="checked"};
                   1617:     if (kwstyle=="<b>") {var sybsel="checked"};
                   1618:     highlightCentral();
                   1619:     highlightbody('red','red',redsel,'0','normal',sznsel,'','normal',synsel);
                   1620:     highlightbody('green','green',grnsel,'+1','+1',sz1sel,'<i>','italic',syisel);
                   1621:     highlightbody('blue','blue',blusel,'+2','+2',sz2sel,'<b>','bold',sybsel);
                   1622:     highlightend();
                   1623:     return;
                   1624:   }
                   1625: 
                   1626:   function highlightCentral() {
1.76      ng       1627: //    if (window.hwdWin) window.hwdWin.close();
1.118     ng       1628:     var xpos = (screen.width-400)/2;
                   1629:     xpos = (xpos < 0) ? '0' : xpos;
                   1630:     var ypos = (screen.height-330)/2-30;
                   1631:     ypos = (ypos < 0) ? '0' : ypos;
                   1632: 
1.206     albertel 1633:     hwdWin = window.open('', 'KeywordHighlightCentral', 'resizeable=yes,toolbar=no,location=no,scrollbars=no,width=400,height=300,screenx='+xpos+',screeny='+ypos);
1.76      ng       1634:     hwdWin.focus();
                   1635:     var hDoc = hwdWin.document;
1.219     www      1636:     hDoc.$docopen;
1.351     albertel 1637:     hDoc.write('$start_page_highlight_central');
1.76      ng       1638:     hDoc.write("<form action=\\"inactive\\" name=\\"hlCenter\\">");
1.465     albertel 1639:     hDoc.write("<h3><span class=\\"LC_info\\">&nbsp;Keyword Highlight Options<\\/span><\\/h3><br /><br />");
1.76      ng       1640: 
1.564     bisitz   1641:     hDoc.write('<table border="0" width="100%"><tr><td bgcolor="#777777">');
                   1642:     hDoc.write('<table border="0" width="100%"><tr bgcolor="#DDFFFF">');
1.465     albertel 1643:     hDoc.write("<td><b>Text Color<\\/b><\\/td><td><b>Font Size<\\/b><\\/td><td><b>Font Style<\\/td><\\/tr>");
1.44      ng       1644:   }
                   1645: 
                   1646:   function highlightbody(clrval,clrtxt,clrsel,szval,sztxt,szsel,syval,sytxt,sysel) { 
1.76      ng       1647:     var hDoc = hwdWin.document;
                   1648:     hDoc.write("<tr bgcolor=\\"#ffffdd\\">");
                   1649:     hDoc.write("<td align=\\"left\\">");
1.465     albertel 1650:     hDoc.write("<input name=\\"kwdclr\\" type=\\"radio\\" value=\\""+clrval+"\\" "+clrsel+">&nbsp;"+clrtxt+"<\\/td>");
1.76      ng       1651:     hDoc.write("<td align=\\"left\\">");
1.465     albertel 1652:     hDoc.write("<input name=\\"kwdsize\\" type=\\"radio\\" value=\\""+szval+"\\" "+szsel+">&nbsp;"+sztxt+"<\\/td>");
1.76      ng       1653:     hDoc.write("<td align=\\"left\\">");
1.465     albertel 1654:     hDoc.write("<input name=\\"kwdstyle\\" type=\\"radio\\" value=\\""+syval+"\\" "+sysel+">&nbsp;"+sytxt+"<\\/td>");
                   1655:     hDoc.write("<\\/tr>");
1.44      ng       1656:   }
                   1657: 
                   1658:   function highlightend() { 
1.76      ng       1659:     var hDoc = hwdWin.document;
1.465     albertel 1660:     hDoc.write("<\\/table>");
                   1661:     hDoc.write("<\\/td><\\/tr><\\/table>&nbsp;");
1.589     bisitz   1662:     hDoc.write("<input type=\\"button\\" value=\\"Save\\" onclick=\\"javascript:updateChoice(1)\\">&nbsp;&nbsp;");
                   1663:     hDoc.write("<input type=\\"button\\" value=\\"Cancel\\" onclick=\\"self.close()\\"><br /><br />");
1.465     albertel 1664:     hDoc.write("<\\/form>");
1.351     albertel 1665:     hDoc.write('$end_page_highlight_central');
1.128     ng       1666:     hDoc.close();
1.44      ng       1667:   }
                   1668: 
                   1669: SUBJAVASCRIPT
                   1670: }
                   1671: 
1.349     albertel 1672: sub get_increment {
1.348     bowersj2 1673:     my $increment = $env{'form.increment'};
                   1674:     if ($increment != 1 && $increment != .5 && $increment != .25 &&
                   1675:         $increment != .1) {
                   1676:         $increment = 1;
                   1677:     }
                   1678:     return $increment;
                   1679: }
                   1680: 
1.585     bisitz   1681: sub gradeBox_start {
                   1682:     return (
                   1683:         &Apache::loncommon::start_data_table()
                   1684:        .&Apache::loncommon::start_data_table_header_row()
                   1685:        .'<th>'.&mt('Part').'</th>'
                   1686:        .'<th>'.&mt('Points').'</th>'
                   1687:        .'<th>&nbsp;</th>'
                   1688:        .'<th>'.&mt('Assign Grade').'</th>'
                   1689:        .'<th>'.&mt('Weight').'</th>'
                   1690:        .'<th>'.&mt('Grade Status').'</th>'
                   1691:        .&Apache::loncommon::end_data_table_header_row()
                   1692:     );
                   1693: }
                   1694: 
                   1695: sub gradeBox_end {
                   1696:     return (
                   1697:         &Apache::loncommon::end_data_table()
                   1698:     );
                   1699: }
1.71      ng       1700: #--- displays the grading box, used in essay type problem and grading by page/sequence
                   1701: sub gradeBox {
1.322     albertel 1702:     my ($request,$symb,$uname,$udom,$counter,$partid,$record) = @_;
1.381     albertel 1703:     my $checkIcon = '<img alt="'.&mt('Check Mark').
1.485     albertel 1704: 	'" src="'.&Apache::loncommon::lonhttpdurl($request->dir_config('lonIconsURL').'/check.gif').'" height="16" border="0" />';
1.71      ng       1705:     my $wgt    = &Apache::lonnet::EXT('resource.'.$partid.'.weight',$symb,$udom,$uname);
1.466     albertel 1706:     my $wgtmsg = ($wgt > 0) ? &mt('(problem weight)') 
                   1707:                            : '<span class="LC_info">'.&mt('problem weight assigned by computer').'</span>';
1.71      ng       1708:     $wgt       = ($wgt > 0 ? $wgt : '1');
                   1709:     my $score  = ($$record{'resource.'.$partid.'.awarded'} eq '' ?
1.320     albertel 1710: 		  '' : &compute_points($$record{'resource.'.$partid.'.awarded'},$wgt));
1.71      ng       1711:     my $result='<input type="hidden" name="WGT'.$counter.'_'.$partid.'" value="'.$wgt.'" />'."\n";
1.466     albertel 1712:     my $display_part= &get_display_part($partid,$symb);
1.270     albertel 1713:     my %last_resets = &get_last_resets($symb,$env{'request.course.id'},
                   1714: 				       [$partid]);
                   1715:     my $aggtries = $$record{'resource.'.$partid.'.tries'};
1.269     raeburn  1716:     if ($last_resets{$partid}) {
                   1717:         $aggtries = &get_num_tries($record,$last_resets{$partid},$partid);
                   1718:     }
1.585     bisitz   1719:     $result.=&Apache::loncommon::start_data_table_row();
1.71      ng       1720:     my $ctr = 0;
1.348     bowersj2 1721:     my $thisweight = 0;
1.349     albertel 1722:     my $increment = &get_increment();
1.485     albertel 1723: 
                   1724:     my $radio.='<table border="0"><tr>'."\n";  # display radio buttons in a nice table 10 across
1.348     bowersj2 1725:     while ($thisweight<=$wgt) {
1.532     bisitz   1726: 	$radio.= '<td><span class="LC_nobreak"><label><input type="radio" name="RADVAL'.$counter.'_'.$partid.'" '.
1.589     bisitz   1727:         'onclick="javascript:writeBox(this.form,\''.$counter.'_'.$partid.'\','.
1.348     bowersj2 1728: 	    $thisweight.')" value="'.$thisweight.'" '.
1.401     albertel 1729: 	    ($score eq $thisweight ? 'checked="checked"':'').' /> '.$thisweight."</label></span></td>\n";
1.485     albertel 1730: 	$radio.=(($ctr+1)%10 == 0 ? '</tr><tr>' : '');
1.348     bowersj2 1731:         $thisweight += $increment;
1.71      ng       1732: 	$ctr++;
                   1733:     }
1.485     albertel 1734:     $radio.='</tr></table>';
                   1735: 
                   1736:     my $line.='<input type="text" name="GD_BOX'.$counter.'_'.$partid.'"'.
1.71      ng       1737: 	($score ne ''? ' value = "'.$score.'"':'').' size="4" '.
1.589     bisitz   1738: 	'onchange="javascript:updateRadio(this.form,\''.$counter.'_'.$partid.'\','.
1.71      ng       1739: 	$wgt.')" /></td>'."\n";
1.485     albertel 1740:     $line.='<td>/'.$wgt.' '.$wgtmsg.
1.71      ng       1741: 	($$record{'resource.'.$partid.'.solved'} eq 'correct_by_student' ? '&nbsp;'.$checkIcon : '').
1.585     bisitz   1742: 	' </td>'."\n";
                   1743:     $line.='<td><select name="GD_SEL'.$counter.'_'.$partid.'" '.
1.589     bisitz   1744: 	'onchange="javascript:clearRadBox(this.form,\''.$counter.'_'.$partid.'\')" >'."\n";
1.71      ng       1745:     if ($$record{'resource.'.$partid.'.solved'} eq 'excused') {
1.485     albertel 1746: 	$line.='<option></option>'.
                   1747: 	    '<option value="excused" selected="selected">'.&mt('excused').'</option>';
1.71      ng       1748:     } else {
1.485     albertel 1749: 	$line.='<option selected="selected"></option>'.
                   1750: 	    '<option value="excused" >'.&mt('excused').'</option>';
1.71      ng       1751:     }
1.485     albertel 1752:     $line.='<option value="reset status">'.&mt('reset status').'</option></select>'."\n";
                   1753: 
                   1754: 
                   1755:     $result .= 
1.585     bisitz   1756: 	    '<td>'.$display_part.'</td><td>'.$radio.'</td><td>'.&mt('or').'</td><td>'.$line.'</td>';
                   1757:     $result.=&Apache::loncommon::end_data_table_row();
1.71      ng       1758:     $result.='<input type="hidden" name="stores'.$counter.'_'.$partid.'" value="" />'."\n".
                   1759: 	'<input type="hidden" name="oldpts'.$counter.'_'.$partid.'" value="'.$score.'" />'."\n".
                   1760: 	'<input type="hidden" name="solved'.$counter.'_'.$partid.'" value="'.
1.269     raeburn  1761: 	$$record{'resource.'.$partid.'.solved'}.'" />'."\n".
                   1762:         '<input type="hidden" name="totaltries'.$counter.'_'.$partid.'" value="'.
                   1763:         $$record{'resource.'.$partid.'.tries'}.'" />'."\n".
                   1764:         '<input type="hidden" name="aggtries'.$counter.'_'.$partid.'" value="'.
                   1765:         $aggtries.'" />'."\n";
1.582     raeburn  1766:     my $res_error;
                   1767:     $result.=&handback_box($symb,$uname,$udom,$counter,$partid,$record,\$res_error);
                   1768:     if ($res_error) {
                   1769:         return &navmap_errormsg();
                   1770:     }
1.318     banghart 1771:     return $result;
                   1772: }
1.322     albertel 1773: 
                   1774: sub handback_box {
1.582     raeburn  1775:     my ($symb,$uname,$udom,$counter,$partid,$record,$res_error) = @_;
                   1776:     my ($partlist,$handgrade,$responseType) = &response_type($symb,$res_error);
1.323     banghart 1777:     my (@respids);
1.375     albertel 1778:      my @part_response_id = &flatten_responseType($responseType);
                   1779:     foreach my $part_response_id (@part_response_id) {
                   1780:     	my ($part,$resp) = @{ $part_response_id };
1.323     banghart 1781:         if ($part eq $partid) {
1.375     albertel 1782:             push(@respids,$resp);
1.323     banghart 1783:         }
                   1784:     }
1.318     banghart 1785:     my $result;
1.323     banghart 1786:     foreach my $respid (@respids) {
1.322     albertel 1787: 	my $prefix = $counter.'_'.$partid.'_'.$respid.'_';
                   1788: 	my $files=&get_submitted_files($udom,$uname,$partid,$respid,$record);
                   1789: 	next if (!@$files);
                   1790: 	my $file_counter = 1;
1.313     banghart 1791: 	foreach my $file (@$files) {
1.368     banghart 1792: 	    if ($file =~ /\/portfolio\//) {
                   1793:     	        my ($file_path, $file_disp) = ($file =~ m|(.+/)(.+)$|);
                   1794:     	        my ($name,$version,$ext) = &file_name_version_ext($file_disp);
                   1795:     	        $file_disp = "$name.$ext";
                   1796:     	        $file = $file_path.$file_disp;
                   1797:     	        $result.=&mt('Return commented version of [_1] to student.',
                   1798:     			 '<span class="LC_filename">'.$file_disp.'</span>');
                   1799:     	        $result.='<input type="file"   name="'.$prefix.'returndoc'.$file_counter.'" />'."\n";
                   1800:     	        $result.='<input type="hidden" name="'.$prefix.'origdoc'.$file_counter.'" value="'.$file.'" /><br />';
1.485     albertel 1801:     	        $result.='('.&mt('File will be uploaded when you click on Save &amp; Next below.').')<br />';
1.368     banghart 1802:     	        $file_counter++;
                   1803: 	    }
1.322     albertel 1804: 	}
1.313     banghart 1805:     }
1.318     banghart 1806:     return $result;    
1.71      ng       1807: }
1.44      ng       1808: 
1.58      albertel 1809: sub show_problem {
1.382     albertel 1810:     my ($request,$symb,$uname,$udom,$removeform,$viewon,$mode,$form) = @_;
1.144     albertel 1811:     my $rendered;
1.382     albertel 1812:     my %form = ((ref($form) eq 'HASH')? %{$form} : ());
1.329     albertel 1813:     &Apache::lonxml::remember_problem_counter();
1.144     albertel 1814:     if ($mode eq 'both' or $mode eq 'text') {
                   1815: 	$rendered=&Apache::loncommon::get_student_view($symb,$uname,$udom,
1.382     albertel 1816: 						       $env{'request.course.id'},
                   1817: 						       undef,\%form);
1.144     albertel 1818:     }
1.58      albertel 1819:     if ($removeform) {
                   1820: 	$rendered=~s|<form(.*?)>||g;
                   1821: 	$rendered=~s|</form>||g;
1.374     albertel 1822: 	$rendered=~s|(<input[^>]*name\s*=\s*"?)(\w+)("?)|$1would_have_been_$2$3|g;
1.58      albertel 1823:     }
1.144     albertel 1824:     my $companswer;
                   1825:     if ($mode eq 'both' or $mode eq 'answer') {
1.329     albertel 1826: 	&Apache::lonxml::restore_problem_counter();
1.382     albertel 1827: 	$companswer=
                   1828: 	    &Apache::loncommon::get_student_answers($symb,$uname,$udom,
                   1829: 						    $env{'request.course.id'},
                   1830: 						    %form);
1.144     albertel 1831:     }
1.58      albertel 1832:     if ($removeform) {
                   1833: 	$companswer=~s|<form(.*?)>||g;
                   1834: 	$companswer=~s|</form>||g;
1.144     albertel 1835: 	$companswer=~s|name="submit"|name="would_have_been_submit"|g;
1.58      albertel 1836:     }
1.468     albertel 1837:     $rendered=
1.588     bisitz   1838:         '<div class="LC_Box">'
                   1839:        .'<h3 class="LC_hcell">'.&mt('View of the problem').'</h3>'
                   1840:        .$rendered
                   1841:        .'</div>';
1.468     albertel 1842:     $companswer=
1.588     bisitz   1843:         '<div class="LC_Box">'
                   1844:        .'<h3 class="LC_hcell">'.&mt('Correct answer').'</h3>'
                   1845:        .$companswer
                   1846:        .'</div>';
1.468     albertel 1847:     my $result;
1.144     albertel 1848:     if ($mode eq 'both') {
1.588     bisitz   1849:         $result=$rendered.$companswer;
1.144     albertel 1850:     } elsif ($mode eq 'text') {
1.588     bisitz   1851:         $result=$rendered;
1.144     albertel 1852:     } elsif ($mode eq 'answer') {
1.588     bisitz   1853:         $result=$companswer;
1.144     albertel 1854:     }
1.71      ng       1855:     return $result;
1.58      albertel 1856: }
1.397     albertel 1857: 
1.396     banghart 1858: sub files_exist {
                   1859:     my ($r, $symb) = @_;
                   1860:     my @students = &Apache::loncommon::get_env_multiple('form.stuinfo');
1.397     albertel 1861: 
1.396     banghart 1862:     foreach my $student (@students) {
                   1863:         my ($uname,$udom,$fullname) = split(/:/,$student);
1.397     albertel 1864:         my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},
                   1865: 					      $udom,$uname);
1.396     banghart 1866:         my ($string,$timestamp)= &get_last_submission(\%record);
1.397     albertel 1867:         foreach my $submission (@$string) {
                   1868:             my ($partid,$respid) =
                   1869: 		($submission =~ /^resource\.([^\.]*)\.([^\.]*)\.submission/);
                   1870:             my $files=&get_submitted_files($udom,$uname,$partid,$respid,
                   1871: 					   \%record);
                   1872:             return 1 if (@$files);
1.396     banghart 1873:         }
                   1874:     }
1.397     albertel 1875:     return 0;
1.396     banghart 1876: }
1.397     albertel 1877: 
1.394     banghart 1878: sub download_all_link {
                   1879:     my ($r,$symb) = @_;
1.395     albertel 1880:     my $all_students = 
                   1881: 	join("\n", &Apache::loncommon::get_env_multiple('form.stuinfo'));
                   1882: 
                   1883:     my $parts =
                   1884: 	join("\n",&Apache::loncommon::get_env_multiple('form.vPart'));
                   1885: 
1.394     banghart 1886:     my $identifier = &Apache::loncommon::get_cgi_id();
1.514     raeburn  1887:     &Apache::lonnet::appenv({'cgi.'.$identifier.'.students' => $all_students,
                   1888:                              'cgi.'.$identifier.'.symb' => $symb,
                   1889:                              'cgi.'.$identifier.'.parts' => $parts,});
1.395     albertel 1890:     $r->print('<a href="/cgi-bin/multidownload.pl?'.$identifier.'">'.
                   1891: 	      &mt('Download All Submitted Documents').'</a>');
1.394     banghart 1892:     return
                   1893: }
1.395     albertel 1894: 
1.432     banghart 1895: sub build_section_inputs {
                   1896:     my $section_inputs;
                   1897:     if ($env{'form.section'} eq '') {
                   1898:         $section_inputs .= '<input type="hidden" name="section" value="all" />'."\n";
                   1899:     } else {
                   1900:         my @sections = &Apache::loncommon::get_env_multiple('form.section');
1.434     albertel 1901:         foreach my $section (@sections) {
1.432     banghart 1902:             $section_inputs .= '<input type="hidden" name="section" value="'.$section.'" />'."\n";
                   1903:         }
                   1904:     }
                   1905:     return $section_inputs;
                   1906: }
                   1907: 
1.44      ng       1908: # --------------------------- show submissions of a student, option to grade 
                   1909: sub submission {
                   1910:     my ($request,$counter,$total) = @_;
1.257     albertel 1911:     my ($uname,$udom)     = ($env{'form.student'},$env{'form.userdom'});
                   1912:     $udom = ($udom eq '' ? $env{'user.domain'} : $udom); #has form.userdom changed for a student?
                   1913:     my $usec = &Apache::lonnet::getsection($udom,$uname,$env{'request.course.id'});
                   1914:     $env{'form.fullname'} = &Apache::loncommon::plainname($uname,$udom,'lastname') if $env{'form.fullname'} eq '';
1.605     www      1915:     my $symb = &get_symb($request);
                   1916:     my $probtitle=&Apache::lonnet::gettitle($symb); 
1.324     albertel 1917:     if ($symb eq '') { $request->print("Unable to handle ambiguous references:."); return ''; }
1.104     albertel 1918: 
                   1919:     if (!&canview($usec)) {
1.398     albertel 1920: 	$request->print('<span class="LC_warning">Unable to view requested student.('.
                   1921: 			$uname.':'.$udom.' in section '.$usec.' in course id '.
                   1922: 			$env{'request.course.id'}.')</span>');
1.324     albertel 1923: 	$request->print(&show_grading_menu_form($symb));
1.104     albertel 1924: 	return;
                   1925:     }
                   1926: 
1.257     albertel 1927:     if (!$env{'form.lastSub'}) { $env{'form.lastSub'} = 'datesub'; }
                   1928:     if (!$env{'form.vProb'}) { $env{'form.vProb'} = 'yes'; }
                   1929:     if (!$env{'form.vAns'}) { $env{'form.vAns'} = 'yes'; }
                   1930:     my $last = ($env{'form.lastSub'} eq 'last' ? 'last' : '');
1.381     albertel 1931:     my $checkIcon = '<img alt="'.&mt('Check Mark').
                   1932: 	'" src="'.$request->dir_config('lonIconsURL').
1.122     ng       1933: 	'/check.gif" height="16" border="0" />';
1.41      ng       1934: 
1.426     albertel 1935:     my %old_essays;
1.41      ng       1936:     # header info
                   1937:     if ($counter == 0) {
                   1938: 	&sub_page_js($request);
1.257     albertel 1939: 	&sub_page_kw_js($request) if ($env{'form.handgrade'} eq 'yes');
1.397     albertel 1940: 	if ($env{'form.handgrade'} eq 'yes' && &files_exist($request, $symb)) {
1.396     banghart 1941: 	    &download_all_link($request, $symb);
                   1942: 	}
1.605     www      1943: 	$request->print('<h3>&nbsp;<span class="LC_info">'.&mt('Submission Record').'</span></h3>');
1.118     ng       1944: 
1.44      ng       1945: 	# option to display problem, only once else it cause problems 
                   1946:         # with the form later since the problem has a form.
1.257     albertel 1947: 	if ($env{'form.vProb'} eq 'yes' or $env{'form.vAns'} eq 'yes') {
1.144     albertel 1948: 	    my $mode;
1.257     albertel 1949: 	    if ($env{'form.vProb'} eq 'yes' && $env{'form.vAns'} eq 'yes') {
1.144     albertel 1950: 		$mode='both';
1.257     albertel 1951: 	    } elsif ($env{'form.vProb'} eq 'yes') {
1.144     albertel 1952: 		$mode='text';
1.257     albertel 1953: 	    } elsif ($env{'form.vAns'} eq 'yes') {
1.144     albertel 1954: 		$mode='answer';
                   1955: 	    }
1.329     albertel 1956: 	    &Apache::lonxml::clear_problem_counter();
1.144     albertel 1957: 	    $request->print(&show_problem($request,$symb,$uname,$udom,0,1,$mode));
1.41      ng       1958: 	}
1.441     www      1959: 
1.44      ng       1960: 	# kwclr is the only variable that is guaranteed to be non blank 
                   1961:         # if this subroutine has been called once.
1.41      ng       1962: 	my %keyhash = ();
1.257     albertel 1963: 	if ($env{'form.kwclr'} eq '' && $env{'form.handgrade'} eq 'yes') {
1.41      ng       1964: 	    %keyhash = &Apache::lonnet::dump('nohist_handgrade',
1.257     albertel 1965: 					     $env{'course.'.$env{'request.course.id'}.'.domain'},
                   1966: 					     $env{'course.'.$env{'request.course.id'}.'.num'});
1.41      ng       1967: 
1.257     albertel 1968: 	    my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
                   1969: 	    $env{'form.keywords'} = $keyhash{$symb.'_keywords'} ne '' ? $keyhash{$symb.'_keywords'} : '';
                   1970: 	    $env{'form.kwclr'}    = $keyhash{$loginuser.'_kwclr'} ne '' ? $keyhash{$loginuser.'_kwclr'} : 'red';
                   1971: 	    $env{'form.kwsize'}   = $keyhash{$loginuser.'_kwsize'} ne '' ? $keyhash{$loginuser.'_kwsize'} : '0';
                   1972: 	    $env{'form.kwstyle'}  = $keyhash{$loginuser.'_kwstyle'} ne '' ? $keyhash{$loginuser.'_kwstyle'} : '';
                   1973: 	    $env{'form.msgsub'}   = $keyhash{$symb.'_subject'} ne '' ? 
1.605     www      1974: 		$keyhash{$symb.'_subject'} : $probtitle;
1.257     albertel 1975: 	    $env{'form.savemsgN'} = $keyhash{$symb.'_savemsgN'} ne '' ? $keyhash{$symb.'_savemsgN'} : '0';
1.41      ng       1976: 	}
1.257     albertel 1977: 	my $overRideScore = $env{'form.overRideScore'} eq '' ? 'no' : $env{'form.overRideScore'};
1.442     banghart 1978: 	my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
1.303     banghart 1979: 	$request->print('<form action="/adm/grades" method="post" name="SCORE" enctype="multipart/form-data">'."\n".
1.41      ng       1980: 			'<input type="hidden" name="command"    value="handgrade" />'."\n".
1.257     albertel 1981: 			'<input type="hidden" name="saveState"  value="'.$env{'form.saveState'}.'" />'."\n".
1.442     banghart 1982: 			'<input type="hidden" name="Status"     value="'.$stu_status.'" />'."\n".
1.120     ng       1983: 			'<input type="hidden" name="overRideScore" value="'.$overRideScore.'" />'."\n".
1.41      ng       1984: 			'<input type="hidden" name="refresh"    value="off" />'."\n".
1.120     ng       1985: 			'<input type="hidden" name="studentNo"  value="" />'."\n".
                   1986: 			'<input type="hidden" name="gradeOpt"   value="" />'."\n".
1.418     albertel 1987: 			'<input type="hidden" name="symb"       value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.257     albertel 1988: 			'<input type="hidden" name="showgrading" value="'.$env{'form.showgrading'}.'" />'."\n".
                   1989: 			'<input type="hidden" name="vProb"      value="'.$env{'form.vProb'}.'" />'."\n".
                   1990: 			'<input type="hidden" name="vAns"       value="'.$env{'form.vAns'}.'" />'."\n".
                   1991: 			'<input type="hidden" name="lastSub"    value="'.$env{'form.lastSub'}.'" />'."\n".
1.432     banghart 1992: 			&build_section_inputs().
1.326     albertel 1993: 			'<input type="hidden" name="submitonly" value="'.$env{'form.submitonly'}.'" />'."\n".
                   1994: 			'<input type="hidden" name="handgrade"  value="'.$env{'form.handgrade'}.'" />'."\n".
1.41      ng       1995: 			'<input type="hidden" name="NCT"'.
1.257     albertel 1996: 			' value="'.($env{'form.NTSTU'} ne '' ? $env{'form.NTSTU'} : $total+1).'" />'."\n");
                   1997: 	if ($env{'form.handgrade'} eq 'yes') {
                   1998: 	    $request->print('<input type="hidden" name="keywords" value="'.$env{'form.keywords'}.'" />'."\n".
                   1999: 			    '<input type="hidden" name="kwclr"    value="'.$env{'form.kwclr'}.'" />'."\n".
                   2000: 			    '<input type="hidden" name="kwsize"   value="'.$env{'form.kwsize'}.'" />'."\n".
                   2001: 			    '<input type="hidden" name="kwstyle"  value="'.$env{'form.kwstyle'}.'" />'."\n".
                   2002: 			    '<input type="hidden" name="msgsub"   value="'.$env{'form.msgsub'}.'" />'."\n".
1.123     ng       2003: 			    '<input type="hidden" name="shownSub" value="0" />'."\n".
1.257     albertel 2004: 			    '<input type="hidden" name="savemsgN" value="'.$env{'form.savemsgN'}.'" />'."\n");
1.154     albertel 2005: 	    foreach my $partid (&Apache::loncommon::get_env_multiple('form.vPart')) {
                   2006: 		$request->print('<input type="hidden" name="vPart" value="'.$partid.'" />'."\n");
                   2007: 	    }
1.123     ng       2008: 	}
1.41      ng       2009: 	
                   2010: 	my ($cts,$prnmsg) = (1,'');
1.257     albertel 2011: 	while ($cts <= $env{'form.savemsgN'}) {
1.41      ng       2012: 	    $prnmsg.='<input type="hidden" name="savemsg'.$cts.'" value="'.
1.123     ng       2013: 		(!exists($keyhash{$symb.'_savemsg'.$cts}) ? 
1.257     albertel 2014: 		 &Apache::lonfeedback::clear_out_html($env{'form.savemsg'.$cts}) :
1.80      ng       2015: 		 &Apache::lonfeedback::clear_out_html($keyhash{$symb.'_savemsg'.$cts})).
1.123     ng       2016: 		'" />'."\n".
                   2017: 		'<input type="hidden" name="shownOnce'.$cts.'" value="0" />'."\n";
1.41      ng       2018: 	    $cts++;
                   2019: 	}
                   2020: 	$request->print($prnmsg);
1.32      ng       2021: 
1.257     albertel 2022: 	if ($env{'form.handgrade'} eq 'yes' && $env{'form.showgrading'} eq 'yes') {
1.88      www      2023: #
                   2024: # Print out the keyword options line
                   2025: #
1.41      ng       2026: 	    $request->print(<<KEYWORDS);
1.38      ng       2027: &nbsp;<b>Keyword Options:</b>&nbsp;
1.417     albertel 2028: <a href="javascript:keywords(document.SCORE);" target="_self">List</a>&nbsp; &nbsp;
1.589     bisitz   2029: <a href="#" onmousedown="javascript:getSel(); return false"
1.38      ng       2030:  CLASS="page">Paste Selection to List</a>&nbsp; &nbsp;
1.417     albertel 2031: <a href="javascript:kwhighlight();" target="_self">Highlight Attribute</a><br /><br />
1.38      ng       2032: KEYWORDS
1.88      www      2033: #
                   2034: # Load the other essays for similarity check
                   2035: #
1.324     albertel 2036:             my (undef,undef,$essayurl) = &Apache::lonnet::decode_symb($symb);
1.384     albertel 2037: 	    my ($adom,$aname,$apath)=($essayurl=~/^($LONCAPA::domain_re)\/($LONCAPA::username_re)\/(.*)$/);
1.359     www      2038: 	    $apath=&escape($apath);
1.88      www      2039: 	    $apath=~s/\W/\_/gs;
1.426     albertel 2040: 	    %old_essays=&Apache::lonnet::dump('nohist_essay_'.$apath,$adom,$aname);
1.41      ng       2041:         }
                   2042:     }
1.44      ng       2043: 
1.441     www      2044: # This is where output for one specific student would start
1.592     bisitz   2045:     my $add_class = ($counter%2) ? ' LC_grade_show_user_odd_row' : '';
                   2046:     $request->print(
                   2047:         "\n\n"
                   2048:        .'<div class="LC_grade_show_user'.$add_class.'">'
                   2049:        .'<h2>'.&nameUserString(undef,$env{'form.fullname'},$uname,$udom).'</h2>'
                   2050:        ."\n"
                   2051:     );
1.441     www      2052: 
1.592     bisitz   2053:     # Show additional functions if allowed
                   2054:     if ($perm{'vgr'}) {
                   2055:         $request->print(
                   2056:             &Apache::loncommon::track_student_link(
                   2057:                 &mt('View recent activity'),
                   2058:                 $uname,$udom,'check')
                   2059:            .' '
                   2060:         );
                   2061:     }
                   2062:     if ($perm{'opa'}) {
                   2063:         $request->print(
                   2064:             &Apache::loncommon::pprmlink(
                   2065:                 &mt('Set/Change parameters'),
                   2066:                 $uname,$udom,$symb,'check'));
                   2067:     }
                   2068: 
                   2069:     # Show Problem
1.257     albertel 2070:     if ($env{'form.vProb'} eq 'all' or $env{'form.vAns'} eq 'all') {
1.144     albertel 2071: 	my $mode;
1.257     albertel 2072: 	if ($env{'form.vProb'} eq 'all' && $env{'form.vAns'} eq 'all') {
1.144     albertel 2073: 	    $mode='both';
1.257     albertel 2074: 	} elsif ($env{'form.vProb'} eq 'all' ) {
1.144     albertel 2075: 	    $mode='text';
1.257     albertel 2076: 	} elsif ($env{'form.vAns'} eq 'all') {
1.144     albertel 2077: 	    $mode='answer';
                   2078: 	}
1.329     albertel 2079: 	&Apache::lonxml::clear_problem_counter();
1.475     albertel 2080: 	$request->print(&show_problem($request,$symb,$uname,$udom,1,1,$mode,{'request.prefix' => 'ctr'.$counter}));
1.58      albertel 2081:     }
1.144     albertel 2082: 
1.257     albertel 2083:     my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
1.582     raeburn  2084:     my $res_error;
                   2085:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
                   2086:     if ($res_error) {
                   2087:         $request->print(&navmap_errormsg());
                   2088:         return;
                   2089:     }
1.41      ng       2090: 
1.44      ng       2091:     # Display student info
1.41      ng       2092:     $request->print(($counter == 0 ? '' : '<br />'));
1.590     bisitz   2093: 
                   2094:     my $result='<div class="LC_Box">'
                   2095:               .'<h3 class="LC_hcell">'.&mt('Submissions').'</h3>';
1.45      ng       2096:     $result.='<input type="hidden" name="name'.$counter.
1.588     bisitz   2097:              '" value="'.$env{'form.fullname'}.'" />'."\n";
1.469     albertel 2098:     if ($env{'form.handgrade'} eq 'no') {
1.588     bisitz   2099:         $result.='<p class="LC_info">'
                   2100:                 .&mt('Part(s) graded correct by the computer is marked with a [_1] symbol.',$checkIcon)
                   2101:                 ."</p>\n";
1.469     albertel 2102:     }
                   2103: 
1.118     ng       2104:     # If any part of the problem is an essay-response (handgraded), then check for collaborators
1.464     albertel 2105:     my $fullname;
                   2106:     my $col_fullnames = [];
1.257     albertel 2107:     if ($env{'form.handgrade'} eq 'yes') {
1.464     albertel 2108: 	(my $sub_result,$fullname,$col_fullnames)=
                   2109: 	    &check_collaborators($symb,$uname,$udom,\%record,$handgrade,
                   2110: 				 $counter);
                   2111: 	$result.=$sub_result;
1.41      ng       2112:     }
1.44      ng       2113:     $request->print($result."\n");
1.588     bisitz   2114: 
1.44      ng       2115:     # print student answer/submission
1.588     bisitz   2116:     # Options are (1) Handgraded submission only
1.44      ng       2117:     #             (2) Last submission, includes submission that is not handgraded 
                   2118:     #                  (for multi-response type part)
                   2119:     #             (3) Last submission plus the parts info
                   2120:     #             (4) The whole record for this student
1.257     albertel 2121:     if ($env{'form.lastSub'} =~ /^(lastonly|hdgrade)$/) {
1.151     albertel 2122: 	my ($string,$timestamp)= &get_last_submission(\%record);
1.468     albertel 2123: 	
                   2124: 	my $lastsubonly;
                   2125: 
1.588     bisitz   2126:         if ($$timestamp eq '') {
                   2127:             $lastsubonly.='<div class="LC_grade_submissions_body">'.$$string[0].'</div>'; 
                   2128:         } else {
1.592     bisitz   2129:             $lastsubonly =
                   2130:                 '<div class="LC_grade_submissions_body">'
                   2131:                .'<b>'.&mt('Date Submitted:').'</b> '.$$timestamp."\n";
1.468     albertel 2132: 
1.151     albertel 2133: 	    my %seenparts;
1.375     albertel 2134: 	    my @part_response_id = &flatten_responseType($responseType);
                   2135: 	    foreach my $part (@part_response_id) {
1.393     albertel 2136: 		next if ($env{'form.lastSub'} eq 'hdgrade' 
                   2137: 			 && $$handgrade{$$part[0].'_'.$$part[1]} ne 'yes');
                   2138: 
1.375     albertel 2139: 		my ($partid,$respid) = @{ $part };
1.324     albertel 2140: 		my $display_part=&get_display_part($partid,$symb);
1.257     albertel 2141: 		if ($env{"form.$uname:$udom:$partid:submitted_by"}) {
1.151     albertel 2142: 		    if (exists($seenparts{$partid})) { next; }
                   2143: 		    $seenparts{$partid}=1;
1.207     albertel 2144: 		    my $submitby='<b>Part:</b> '.$display_part.
                   2145: 			' <b>Collaborative submission by:</b> '.
1.151     albertel 2146: 			'<a href="javascript:viewSubmitter(\''.
1.257     albertel 2147: 			$env{"form.$uname:$udom:$partid:submitted_by"}.
1.417     albertel 2148: 			'\');" target="_self">'.
1.257     albertel 2149: 			$$fullname{$env{"form.$uname:$udom:$partid:submitted_by"}}.'</a><br />';
1.151     albertel 2150: 		    $request->print($submitby);
                   2151: 		    next;
                   2152: 		}
                   2153: 		my $responsetype = $responseType->{$partid}->{$respid};
                   2154: 		if (!exists($record{"resource.$partid.$respid.submission"})) {
1.577     bisitz   2155:                     $lastsubonly.="\n".'<div class="LC_grade_submission_part">'.
                   2156:                         '<b>'.&mt('Part: [_1]',$display_part).'</b>'.
                   2157:                         ' <span class="LC_internal_info">'.
1.597     wenzelju 2158:                         '('.&mt('Part ID: [_1]',$respid).')'.
1.577     bisitz   2159:                         '</span>&nbsp; &nbsp;'.
1.539     riegler  2160: 			'<span class="LC_warning">'.&mt('Nothing submitted - no attempts.').'</span><br /><br /></div>';
1.151     albertel 2161: 		    next;
                   2162: 		}
1.468     albertel 2163: 		foreach my $submission (@$string) {
                   2164: 		    my ($partid,$respid) = ($submission =~ /^resource\.([^\.]*)\.([^\.]*)\.submission/);
1.375     albertel 2165: 		    if (join('_',@{$part}) ne ($partid.'_'.$respid)) { next; }
1.596     raeburn  2166: 		    my ($ressub,$hide,$subval) = split(/:/,$submission,3);
1.151     albertel 2167: 		    # Similarity check
                   2168: 		    my $similar='';
1.257     albertel 2169: 		    if($env{'form.checkPlag'}){
1.151     albertel 2170: 			my ($oname,$odom,$ocrsid,$oessay,$osim)=
1.426     albertel 2171: 			    &most_similar($uname,$udom,$subval,\%old_essays);
1.151     albertel 2172: 			if ($osim) {
                   2173: 			    $osim=int($osim*100.0);
1.426     albertel 2174: 			    my %old_course_desc = 
                   2175: 				&Apache::lonnet::coursedescription($ocrsid,
                   2176: 								   {'one_time' => 1});
                   2177: 
1.596     raeburn  2178:                             if ($hide) {
                   2179:                                 $similar='<hr /><span class="LC_warning">'.&mt("Essay was found to be similar to another essay submitted for this assignment.").'<br />'.
                   2180:                                          &mt('As the current submission is for an anonymous survey, no other details are available.').'</span><hr />';
                   2181:                             } else {
                   2182: 			        $similar="<hr /><h3><span class=\"LC_warning\">".
                   2183: 				    &mt('Essay is [_1]% similar to an essay by [_2] in course [_3] (course id [_4]:[_5])',
                   2184: 				        $osim,
                   2185: 				        &Apache::loncommon::plainname($oname,$odom).' ('.$oname.':'.$odom.')',
                   2186: 				        $old_course_desc{'description'},
                   2187: 				        $old_course_desc{'num'},
                   2188: 				        $old_course_desc{'domain'}).
                   2189: 				    '</span></h3><blockquote><i>'.
                   2190: 				    &keywords_highlight($oessay).
                   2191: 				    '</i></blockquote><hr />';
                   2192:                             }
1.151     albertel 2193: 			}
1.150     albertel 2194: 		    }
1.151     albertel 2195: 		    my $order=&get_order($partid,$respid,$symb,$uname,$udom);
1.257     albertel 2196: 		    if ($env{'form.lastSub'} eq 'lastonly' || 
                   2197: 			($env{'form.lastSub'} eq 'hdgrade' && 
1.377     albertel 2198: 			 $$handgrade{$$part[0].'_'.$$part[1]} eq 'yes')) {
1.324     albertel 2199: 			my $display_part=&get_display_part($partid,$symb);
1.577     bisitz   2200:                         $lastsubonly.='<div class="LC_grade_submission_part">'.
                   2201:                             '<b>'.&mt('Part: [_1]',$display_part).'</b>'.
                   2202:                             ' <span class="LC_internal_info">'.
                   2203:                             '('.&mt('Part ID: [_1]',$respid).')'.
1.597     wenzelju 2204:                             '</span>&nbsp; &nbsp;';
1.313     banghart 2205: 			my $files=&get_submitted_files($udom,$uname,$partid,$respid,\%record);
                   2206: 			if (@$files) {
1.596     raeburn  2207:                             if ($hide) {
                   2208:                                 $lastsubonly.='<br />'.&mt('[quant,_1,file] uploaded to this anonymous survey',scalar(@{$files}));
                   2209:                             } else {
                   2210:                                 $lastsubonly.='<br /><span class="LC_warning">'.&mt('Like all files provided by users, this file may contain viruses').'</span><br />';
                   2211:                                 foreach my $file (@$files) {
                   2212:                                     &Apache::lonnet::allowuploaded('/adm/grades',$file);
                   2213:                                     $lastsubonly.='<br /><a href="'.$file.'?rawmode=1" target="lonGRDs"><img src="'.&Apache::loncommon::icon($file).'" border="0" /> '.$file.'</a>';
                   2214:                                 }
                   2215:                             }
1.236     albertel 2216: 			    $lastsubonly.='<br />';
1.41      ng       2217: 			}
1.596     raeburn  2218:                         if ($hide) {
                   2219:                             $lastsubonly.='<b>'.&mt('Anonymous Survey').'</b>'; 
                   2220:                         } else {
                   2221: 			    $lastsubonly.='<b>'.&mt('Submitted Answer:').' </b>'.
                   2222: 			        &cleanRecord($subval,$responsetype,$symb,$partid,
                   2223: 					     $respid,\%record,$order,undef,$uname,$udom);
                   2224:                         }
1.151     albertel 2225: 			if ($similar) {$lastsubonly.="<br /><br />$similar\n";}
1.468     albertel 2226: 			$lastsubonly.='</div>';
1.41      ng       2227: 		    }
                   2228: 		}
                   2229: 	    }
1.588     bisitz   2230: 	    $lastsubonly.='</div>'."\n"; # End: LC_grade_submissions_body
1.151     albertel 2231: 	}
                   2232: 	$request->print($lastsubonly);
1.468     albertel 2233:    } elsif ($env{'form.lastSub'} eq 'datesub') {
1.598     www      2234: #	my (undef,$responseType,undef,$parts) = &showResourceInfo($symb);
                   2235:     my ($parts,$handgrade,$responseType) = &response_type($symb);
                   2236: 
1.148     albertel 2237: 	$request->print(&displaySubByDates($symb,\%record,$parts,$responseType,$checkIcon,$uname,$udom));
1.257     albertel 2238:     } elsif ($env{'form.lastSub'} =~ /^(last|all)$/) {
1.41      ng       2239: 	$request->print(&Apache::loncommon::get_previous_attempt($symb,$uname,$udom,
1.257     albertel 2240: 								 $env{'request.course.id'},
1.44      ng       2241: 								 $last,'.submission',
                   2242: 								 'Apache::grades::keywords_highlight'));
1.41      ng       2243:     }
1.120     ng       2244: 
1.121     ng       2245:     $request->print('<input type="hidden" name="unamedom'.$counter.'" value="'.$uname.':'
                   2246: 	.$udom.'" />'."\n");
1.44      ng       2247:     # return if view submission with no grading option
1.257     albertel 2248:     if ($env{'form.showgrading'} eq '' || (!&canmodify($usec))) {
1.120     ng       2249: 	my $toGrade.='<input type="button" value="Grade Student" '.
1.589     bisitz   2250: 	    'onclick="javascript:checksubmit(this.form,\'Grade Student\',\''
1.417     albertel 2251: 	    .$counter.'\');" target="_self" /> &nbsp;'."\n" if (&canmodify($usec));
1.468     albertel 2252: 	$toGrade.='</div>'."\n";
1.257     albertel 2253: 	if (($env{'form.command'} eq 'submission') || 
                   2254: 	    ($env{'form.command'} eq 'processGroup' && $counter == $total)) {
1.324     albertel 2255: 	    $toGrade.='</form>'.&show_grading_menu_form($symb); 
1.169     albertel 2256: 	}
1.180     albertel 2257: 	$request->print($toGrade);
1.41      ng       2258: 	return;
1.180     albertel 2259:     } else {
1.468     albertel 2260: 	$request->print('</div>'."\n");
1.41      ng       2261:     }
1.33      ng       2262: 
1.121     ng       2263:     # essay grading message center
1.257     albertel 2264:     if ($env{'form.handgrade'} eq 'yes') {
1.468     albertel 2265: 	my $result='<div class="LC_grade_message_center">';
                   2266:     
                   2267: 	$result.='<div class="LC_grade_message_center_header">'.
                   2268: 	    &mt('Send Message').'</div><div class="LC_grade_message_center_body">';
1.257     albertel 2269: 	my ($lastname,$givenn) = split(/,/,$env{'form.fullname'});
1.118     ng       2270: 	my $msgfor = $givenn.' '.$lastname;
1.464     albertel 2271: 	if (scalar(@$col_fullnames) > 0) {
                   2272: 	    my $lastone = pop(@$col_fullnames);
                   2273: 	    $msgfor .= ', '.(join ', ',@$col_fullnames).' and '.$lastone.'.';
1.118     ng       2274: 	}
                   2275: 	$msgfor =~ s/\'/\\'/g; #' stupid emacs - no! javascript
1.468     albertel 2276: 	$result.='<input type="hidden" name="includemsg'.$counter.'" value="" />'."\n".
1.121     ng       2277: 	    '<input type="hidden" name="newmsg'.$counter.'" value="" />'."\n";
                   2278: 	$result.='&nbsp;<a href="javascript:msgCenter(document.SCORE,'.$counter.
1.417     albertel 2279: 	    ',\''.$msgfor.'\');" target="_self">'.
1.464     albertel 2280: 	    &mt('Compose message to student').(scalar(@$col_fullnames) >= 1 ? 's' : '').'</a><label> ('.
1.350     albertel 2281: 	    &mt('incl. grades').' <input type="checkbox" name="withgrades'.$counter.'" /></label>)'.
1.118     ng       2282: 	    '<img src="'.$request->dir_config('lonIconsURL').
                   2283: 	    '/mailbkgrd.gif" width="14" height="10" name="mailicon'.$counter.'" />'."\n".
1.298     www      2284: 	    '<br />&nbsp;('.
1.468     albertel 2285: 	    &mt('Message will be sent when you click on Save &amp; Next below.').")\n";
                   2286: 	$result.='</div></div>';
1.121     ng       2287: 	$request->print($result);
1.118     ng       2288:     }
1.41      ng       2289: 
                   2290:     my %seen = ();
                   2291:     my @partlist;
1.129     ng       2292:     my @gradePartRespid;
1.375     albertel 2293:     my @part_response_id = &flatten_responseType($responseType);
1.585     bisitz   2294:     $request->print(
1.588     bisitz   2295:         '<div class="LC_Box">'
                   2296:        .'<h3 class="LC_hcell">'.&mt('Assign Grades').'</h3>'
1.585     bisitz   2297:     );
1.592     bisitz   2298:     $request->print(&gradeBox_start());
1.375     albertel 2299:     foreach my $part_response_id (@part_response_id) {
                   2300:     	my ($partid,$respid) = @{ $part_response_id };
                   2301: 	my $part_resp = join('_',@{ $part_response_id });
1.322     albertel 2302: 	next if ($seen{$partid} > 0);
1.41      ng       2303: 	$seen{$partid}++;
1.393     albertel 2304: 	next if ($$handgrade{$part_resp} ne 'yes' 
                   2305: 		 && $env{'form.lastSub'} eq 'hdgrade');
1.524     raeburn  2306: 	push(@partlist,$partid);
                   2307: 	push(@gradePartRespid,$partid.'.'.$respid);
1.322     albertel 2308: 	$request->print(&gradeBox($request,$symb,$uname,$udom,$counter,$partid,\%record));
1.41      ng       2309:     }
1.585     bisitz   2310:     $request->print(&gradeBox_end()); # </div>
                   2311:     $request->print('</div>');
1.468     albertel 2312: 
                   2313:     $request->print('<div class="LC_grade_info_links">');
                   2314:     $request->print('</div>');
                   2315: 
1.45      ng       2316:     $result='<input type="hidden" name="partlist'.$counter.
                   2317: 	'" value="'.(join ":",@partlist).'" />'."\n";
1.129     ng       2318:     $result.='<input type="hidden" name="gradePartRespid'.
                   2319: 	'" value="'.(join ":",@gradePartRespid).'" />'."\n" if ($counter == 0);
1.45      ng       2320:     my $ctr = 0;
                   2321:     while ($ctr < scalar(@partlist)) {
                   2322: 	$result.='<input type="hidden" name="partid'.$counter.'_'.$ctr.'" value="'.
                   2323: 	    $partlist[$ctr].'" />'."\n";
                   2324: 	$ctr++;
                   2325:     }
1.468     albertel 2326:     $request->print($result.''."\n");
1.41      ng       2327: 
1.441     www      2328: # Done with printing info for one student
                   2329: 
1.468     albertel 2330:     $request->print('</div>');#LC_grade_show_user
1.441     www      2331: 
                   2332: 
1.41      ng       2333:     # print end of form
                   2334:     if ($counter == $total) {
1.592     bisitz   2335:         my $endform='<br /><hr /><table border="0"><tr><td>'."\n";
1.485     albertel 2336: 	$endform.='<input type="button" value="'.&mt('Save &amp; Next').'" '.
1.589     bisitz   2337: 	    'onclick="javascript:checksubmit(this.form,\'Save & Next\','.
1.417     albertel 2338: 	    $total.','.scalar(@partlist).');" target="_self" /> &nbsp;'."\n";
1.119     ng       2339: 	my $ntstu ='<select name="NTSTU">'.
                   2340: 	    '<option>1</option><option>2</option>'.
                   2341: 	    '<option>3</option><option>5</option>'.
                   2342: 	    '<option>7</option><option>10</option></select>'."\n";
1.257     albertel 2343: 	my $nsel = ($env{'form.NTSTU'} ne '' ? $env{'form.NTSTU'} : '1');
1.401     albertel 2344: 	$ntstu =~ s/<option>$nsel</<option selected="selected">$nsel</;
1.578     raeburn  2345:         $endform.=&mt('[_1]student(s)',$ntstu);
1.485     albertel 2346: 	$endform.='&nbsp;&nbsp;<input type="button" value="'.&mt('Previous').'" '.
1.589     bisitz   2347: 	    'onclick="javascript:checksubmit(this.form,\'Previous\');" target="_self" /> &nbsp;'."\n".
1.485     albertel 2348: 	    '<input type="button" value="'.&mt('Next').'" '.
1.589     bisitz   2349: 	    'onclick="javascript:checksubmit(this.form,\'Next\');" target="_self" /> &nbsp;';
1.592     bisitz   2350:         $endform.='<span class="LC_warning">'.
                   2351:                   &mt('(Next and Previous (student) do not save the scores.)').
                   2352:                   '</span>'."\n" ;
1.349     albertel 2353:         $endform.="<input type='hidden' value='".&get_increment().
1.348     bowersj2 2354:             "' name='increment' />";
1.485     albertel 2355: 	$endform.='</td></tr></table></form>';
1.324     albertel 2356: 	$endform.=&show_grading_menu_form($symb);
1.41      ng       2357: 	$request->print($endform);
                   2358:     }
                   2359:     return '';
1.38      ng       2360: }
                   2361: 
1.464     albertel 2362: sub check_collaborators {
                   2363:     my ($symb,$uname,$udom,$record,$handgrade,$counter) = @_;
                   2364:     my ($result,@col_fullnames);
                   2365:     my ($classlist,undef,$fullname) = &getclasslist('all','0');
                   2366:     foreach my $part (keys(%$handgrade)) {
                   2367: 	my $ncol = &Apache::lonnet::EXT('resource.'.$part.
                   2368: 					'.maxcollaborators',
                   2369: 					$symb,$udom,$uname);
                   2370: 	next if ($ncol <= 0);
                   2371: 	$part =~ s/\_/\./g;
                   2372: 	next if ($record->{'resource.'.$part.'.collaborators'} eq '');
                   2373: 	my (@good_collaborators, @bad_collaborators);
                   2374: 	foreach my $possible_collaborator
                   2375: 	    (split(/,?\s+/,$record->{'resource.'.$part.'.collaborators'})) { 
                   2376: 	    $possible_collaborator =~ s/[\$\^\(\)]//g;
                   2377: 	    next if ($possible_collaborator eq '');
                   2378: 	    my ($co_name,$co_dom) = split(/\@|:/,$possible_collaborator);
                   2379: 	    $co_dom = $udom if (! defined($co_dom) || $co_dom =~ /^domain$/i);
                   2380: 	    next if ($co_name eq $uname && $co_dom eq $udom);
                   2381: 	    # Doing this grep allows 'fuzzy' specification
                   2382: 	    my @matches = grep(/^\Q$co_name\E:\Q$co_dom\E$/i, 
                   2383: 			       keys(%$classlist));
                   2384: 	    if (! scalar(@matches)) {
                   2385: 		push(@bad_collaborators, $possible_collaborator);
                   2386: 	    } else {
                   2387: 		push(@good_collaborators, @matches);
                   2388: 	    }
                   2389: 	}
                   2390: 	if (scalar(@good_collaborators) != 0) {
1.466     albertel 2391: 	    $result.='<br />'.&mt('Collaborators: ');
1.464     albertel 2392: 	    foreach my $name (@good_collaborators) {
                   2393: 		my ($lastname,$givenn) = split(/,/,$$fullname{$name});
                   2394: 		push(@col_fullnames, $givenn.' '.$lastname);
                   2395: 		$result.=$fullname->{$name}.'&nbsp; &nbsp; &nbsp;';
                   2396: 	    }
                   2397: 	    $result.='<br />'."\n";
1.466     albertel 2398: 	    my ($part)=split(/\./,$part);
1.464     albertel 2399: 	    $result.='<input type="hidden" name="collaborator'.$counter.
                   2400: 		'" value="'.$part.':'.(join ':',@good_collaborators).'" />'.
                   2401: 		"\n";
                   2402: 	}
                   2403: 	if (scalar(@bad_collaborators) > 0) {
1.466     albertel 2404: 	    $result.='<div class="LC_warning">';
1.464     albertel 2405: 	    $result.=&mt('This student has submitted [quant,_1,invalid collaborator]: [_2]',scalar(@bad_collaborators),join(', ',@bad_collaborators));
                   2406: 	    $result .= '</div>';
                   2407: 	}         
                   2408: 	if (scalar(@bad_collaborators > $ncol)) {
1.466     albertel 2409: 	    $result .= '<div class="LC_warning">';
1.464     albertel 2410: 	    $result .= &mt('This student has submitted too many '.
                   2411: 		'collaborators.  Maximum is [_1].',$ncol);
                   2412: 	    $result .= '</div>';
                   2413: 	}
                   2414:     }
                   2415:     return ($result,$fullname,\@col_fullnames);
                   2416: }
                   2417: 
1.44      ng       2418: #--- Retrieve the last submission for all the parts
1.38      ng       2419: sub get_last_submission {
1.119     ng       2420:     my ($returnhash)=@_;
1.596     raeburn  2421:     my (@string,$timestamp,%lasthidden);
1.119     ng       2422:     if ($$returnhash{'version'}) {
1.46      ng       2423: 	my %lasthash=();
                   2424: 	my ($version);
1.119     ng       2425: 	for ($version=1;$version<=$$returnhash{'version'};$version++) {
1.397     albertel 2426: 	    foreach my $key (sort(split(/\:/,
                   2427: 					$$returnhash{$version.':keys'}))) {
                   2428: 		$lasthash{$key}=$$returnhash{$version.':'.$key};
                   2429: 		$timestamp = 
1.545     raeburn  2430: 		    &Apache::lonlocal::locallocaltime($$returnhash{$version.':timestamp'});
1.46      ng       2431: 	    }
                   2432: 	}
1.596     raeburn  2433:         my %typeparts;
                   2434:         my $showsurv = 
                   2435:             &Apache::lonnet::allowed('vas',$env{'request.course.id'});
                   2436:         foreach my $key (sort(keys(%lasthash))) {
                   2437:             if ($key =~ /\.type$/) {
                   2438:                 if (($lasthash{$key} eq 'anonsurvey') || 
                   2439:                     ($lasthash{$key} eq 'anonsurveycred')) {
                   2440:                     my ($ign,@parts) = split(/\./,$key);
                   2441:                     pop(@parts);
                   2442:                     unless ($showsurv) {
                   2443:                         my $id = join(',',@parts);
                   2444:                         $typeparts{$ign.'.'.$id} = $lasthash{$key};
                   2445:                     }
                   2446:                     delete($lasthash{$key});
                   2447:                 }
                   2448:             }
                   2449:         }
                   2450:         my @hidden = keys(%typeparts);
1.397     albertel 2451: 	foreach my $key (keys(%lasthash)) {
                   2452: 	    next if ($key !~ /\.submission$/);
1.596     raeburn  2453:             my $hide;
                   2454:             if (@hidden) {
                   2455:                 foreach my $id (@hidden) {
                   2456:                     if ($key =~ /^\Q$id\E/) {
                   2457:                         $hide = 1;
                   2458:                         last;
                   2459:                     }
                   2460:                 }
                   2461:             }
1.397     albertel 2462: 	    my ($partid,$foo) = split(/submission$/,$key);
                   2463: 	    my $draft  = $lasthash{$partid.'awarddetail'} eq 'DRAFT' ?
1.398     albertel 2464: 		'<span class="LC_warning">Draft Copy</span> ' : '';
1.596     raeburn  2465: 	    push(@string, join(':', $key, $hide, $draft.$lasthash{$key}));
1.41      ng       2466: 	}
                   2467:     }
1.397     albertel 2468:     if (!@string) {
                   2469: 	$string[0] =
1.539     riegler  2470: 	    '<span class="LC_warning">'.&mt('Nothing submitted - no attempts.').'</span>';
1.397     albertel 2471:     }
                   2472:     return (\@string,\$timestamp);
1.38      ng       2473: }
1.35      ng       2474: 
1.44      ng       2475: #--- High light keywords, with style choosen by user.
1.38      ng       2476: sub keywords_highlight {
1.44      ng       2477:     my $string    = shift;
1.257     albertel 2478:     my $size      = $env{'form.kwsize'} eq '0' ? '' : 'size='.$env{'form.kwsize'};
                   2479:     my $styleon   = $env{'form.kwstyle'} eq ''  ? '' : $env{'form.kwstyle'};
1.41      ng       2480:     (my $styleoff = $styleon) =~ s/\</\<\//;
1.257     albertel 2481:     my @keylist   = split(/[,\s+]/,$env{'form.keywords'});
1.398     albertel 2482:     foreach my $keyword (@keylist) {
                   2483: 	$string =~ s/\b\Q$keyword\E(\b|\.)/<font color\=$env{'form.kwclr'} $size\>$styleon$keyword$styleoff<\/font>/gi;
1.41      ng       2484:     }
                   2485:     return $string;
1.38      ng       2486: }
1.36      ng       2487: 
1.44      ng       2488: #--- Called from submission routine
1.38      ng       2489: sub processHandGrade {
1.41      ng       2490:     my ($request) = shift;
1.324     albertel 2491:     my $symb   = &get_symb($request);
                   2492:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
1.257     albertel 2493:     my $button = $env{'form.gradeOpt'};
                   2494:     my $ngrade = $env{'form.NCT'};
                   2495:     my $ntstu  = $env{'form.NTSTU'};
1.301     albertel 2496:     my $cdom   = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   2497:     my $cnum   = $env{'course.'.$env{'request.course.id'}.'.num'};
                   2498: 
1.44      ng       2499:     if ($button eq 'Save & Next') {
                   2500: 	my $ctr = 0;
                   2501: 	while ($ctr < $ngrade) {
1.257     albertel 2502: 	    my ($uname,$udom) = split(/:/,$env{'form.unamedom'.$ctr});
1.324     albertel 2503: 	    my ($errorflag,$pts,$wgt) = &saveHandGrade($request,$symb,$uname,$udom,$ctr);
1.71      ng       2504: 	    if ($errorflag eq 'no_score') {
                   2505: 		$ctr++;
                   2506: 		next;
                   2507: 	    }
1.104     albertel 2508: 	    if ($errorflag eq 'not_allowed') {
1.398     albertel 2509: 		$request->print("<span class=\"LC_warning\">Not allowed to modify grades for $uname:$udom</span>");
1.104     albertel 2510: 		$ctr++;
                   2511: 		next;
                   2512: 	    }
1.257     albertel 2513: 	    my $includemsg = $env{'form.includemsg'.$ctr};
1.44      ng       2514: 	    my ($subject,$message,$msgstatus) = ('','','');
1.418     albertel 2515: 	    my $restitle = &Apache::lonnet::gettitle($symb);
                   2516:             my ($feedurl,$showsymb) =
                   2517: 		&get_feedurl_and_symb($symb,$uname,$udom);
                   2518: 	    my $messagetail;
1.62      albertel 2519: 	    if ($includemsg =~ /savemsg|newmsg\Q$ctr\E/) {
1.298     www      2520: 		$subject = $env{'form.msgsub'} if ($includemsg =~ /msgsub/);
1.295     www      2521: 		unless ($subject=~/\w/) { $subject=&mt('Grading Feedback'); }
1.386     raeburn  2522: 		$subject.=' ['.$restitle.']';
1.44      ng       2523: 		my (@msgnum) = split(/,/,$includemsg);
                   2524: 		foreach (@msgnum) {
1.257     albertel 2525: 		    $message.=$env{'form.'.$_} if ($_ =~ /savemsg|newmsg/ && $_ ne '');
1.44      ng       2526: 		}
1.80      ng       2527: 		$message =&Apache::lonfeedback::clear_out_html($message);
1.298     www      2528: 		if ($env{'form.withgrades'.$ctr}) {
                   2529: 		    $message.="\n\nPoint".($pts > 1 ? 's':'').' awarded = '.$pts.' out of '.$wgt;
1.386     raeburn  2530: 		    $messagetail = " for <a href=\"".
1.605     www      2531: 		                   $feedurl."?symb=$showsymb\">$restitle</a>";
1.386     raeburn  2532: 		}
                   2533: 		$msgstatus = 
                   2534:                     &Apache::lonmsg::user_normal_msg($uname,$udom,$subject,
                   2535: 						     $message.$messagetail,
1.418     albertel 2536:                                                      undef,$feedurl,undef,
1.386     raeburn  2537:                                                      undef,undef,$showsymb,
                   2538:                                                      $restitle);
1.574     bisitz   2539: 		$request->print('<br />'.&mt('Sending message to [_1]',$uname.':'.$udom).': '.
1.296     www      2540: 				$msgstatus);
1.44      ng       2541: 	    }
1.257     albertel 2542: 	    if ($env{'form.collaborator'.$ctr}) {
1.155     albertel 2543: 		my @collabstrs=&Apache::loncommon::get_env_multiple("form.collaborator$ctr");
1.150     albertel 2544: 		foreach my $collabstr (@collabstrs) {
                   2545: 		    my ($part,@collaborators) = split(/:/,$collabstr);
1.310     banghart 2546: 		    foreach my $collaborator (@collaborators) {
1.150     albertel 2547: 			my ($errorflag,$pts,$wgt) = 
1.324     albertel 2548: 			    &saveHandGrade($request,$symb,$collaborator,$udom,$ctr,
1.257     albertel 2549: 					   $env{'form.unamedom'.$ctr},$part);
1.150     albertel 2550: 			if ($errorflag eq 'not_allowed') {
1.362     albertel 2551: 			    $request->print("<span class=\"LC_error\">".&mt('Not allowed to modify grades for [_1]',"$collaborator:$udom")."</span>");
1.150     albertel 2552: 			    next;
1.418     albertel 2553: 			} elsif ($message ne '') {
                   2554: 			    my ($baseurl,$showsymb) = 
                   2555: 				&get_feedurl_and_symb($symb,$collaborator,
                   2556: 						      $udom);
                   2557: 			    if ($env{'form.withgrades'.$ctr}) {
                   2558: 				$messagetail = " for <a href=\"".
1.605     www      2559:                                     $baseurl."?symb=$showsymb\">$restitle</a>";
1.150     albertel 2560: 			    }
1.418     albertel 2561: 			    $msgstatus = 
                   2562: 				&Apache::lonmsg::user_normal_msg($collaborator,$udom,$subject,$message.$messagetail,undef,$baseurl,undef,undef,undef,$showsymb,$restitle);
1.104     albertel 2563: 			}
1.44      ng       2564: 		    }
                   2565: 		}
                   2566: 	    }
                   2567: 	    $ctr++;
                   2568: 	}
                   2569:     }
                   2570: 
1.257     albertel 2571:     if ($env{'form.handgrade'} eq 'yes') {
1.119     ng       2572: 	# Keywords sorted in alphabatical order
1.257     albertel 2573: 	my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
1.119     ng       2574: 	my %keyhash = ();
1.257     albertel 2575: 	$env{'form.keywords'}           =~ s/,\s{0,}|\s+/ /g;
                   2576: 	$env{'form.keywords'}           =~ s/^\s+|\s+$//;
                   2577: 	my (@keywords) = sort(split(/\s+/,$env{'form.keywords'}));
                   2578: 	$env{'form.keywords'} = join(' ',@keywords);
                   2579: 	$keyhash{$symb.'_keywords'}     = $env{'form.keywords'};
                   2580: 	$keyhash{$symb.'_subject'}      = $env{'form.msgsub'};
                   2581: 	$keyhash{$loginuser.'_kwclr'}   = $env{'form.kwclr'};
                   2582: 	$keyhash{$loginuser.'_kwsize'}  = $env{'form.kwsize'};
                   2583: 	$keyhash{$loginuser.'_kwstyle'} = $env{'form.kwstyle'};
1.119     ng       2584: 
                   2585: 	# message center - Order of message gets changed. Blank line is eliminated.
1.257     albertel 2586: 	# New messages are saved in env for the next student.
1.119     ng       2587: 	# All messages are saved in nohist_handgrade.db
                   2588: 	my ($ctr,$idx) = (1,1);
1.257     albertel 2589: 	while ($ctr <= $env{'form.savemsgN'}) {
                   2590: 	    if ($env{'form.savemsg'.$ctr} ne '') {
                   2591: 		$keyhash{$symb.'_savemsg'.$idx} = $env{'form.savemsg'.$ctr};
1.119     ng       2592: 		$idx++;
                   2593: 	    }
                   2594: 	    $ctr++;
1.41      ng       2595: 	}
1.119     ng       2596: 	$ctr = 0;
                   2597: 	while ($ctr < $ngrade) {
1.257     albertel 2598: 	    if ($env{'form.newmsg'.$ctr} ne '') {
                   2599: 		$keyhash{$symb.'_savemsg'.$idx} = $env{'form.newmsg'.$ctr};
                   2600: 		$env{'form.savemsg'.$idx} = $env{'form.newmsg'.$ctr};
1.119     ng       2601: 		$idx++;
                   2602: 	    }
                   2603: 	    $ctr++;
1.41      ng       2604: 	}
1.257     albertel 2605: 	$env{'form.savemsgN'} = --$idx;
                   2606: 	$keyhash{$symb.'_savemsgN'} = $env{'form.savemsgN'};
1.119     ng       2607: 	my $putresult = &Apache::lonnet::put
1.301     albertel 2608: 	    ('nohist_handgrade',\%keyhash,$cdom,$cnum);
1.41      ng       2609:     }
1.44      ng       2610:     # Called by Save & Refresh from Highlight Attribute Window
1.257     albertel 2611:     my (undef,undef,$fullname) = &getclasslist($env{'form.section'},'1');
                   2612:     if ($env{'form.refresh'} eq 'on') {
1.86      ng       2613: 	my ($ctr,$total) = (0,0);
                   2614: 	while ($ctr < $ngrade) {
1.257     albertel 2615: 	    $total++ if  $env{'form.unamedom'.$ctr} ne '';
1.86      ng       2616: 	    $ctr++;
                   2617: 	}
1.257     albertel 2618: 	$env{'form.NTSTU'}=$ngrade;
1.86      ng       2619: 	$ctr = 0;
                   2620: 	while ($ctr < $total) {
1.257     albertel 2621: 	    my $processUser = $env{'form.unamedom'.$ctr};
                   2622: 	    ($env{'form.student'},$env{'form.userdom'}) = split(/:/,$processUser);
                   2623: 	    $env{'form.fullname'} = $$fullname{$processUser};
1.86      ng       2624: 	    &submission($request,$ctr,$total-1);
1.41      ng       2625: 	    $ctr++;
                   2626: 	}
                   2627: 	return '';
                   2628:     }
1.36      ng       2629: 
1.121     ng       2630: # Go directly to grade student - from submission or link from chart page
1.120     ng       2631:     if ($button eq 'Grade Student') {
1.598     www      2632: #	(undef,undef,$env{'form.handgrade'},undef,undef) = &showResourceInfo($symb);
1.257     albertel 2633: 	my $processUser = $env{'form.unamedom'.$env{'form.studentNo'}};
                   2634: 	($env{'form.student'},$env{'form.userdom'}) = split(/:/,$processUser);
                   2635: 	$env{'form.fullname'} = $$fullname{$processUser};
1.120     ng       2636: 	&submission($request,0,0);
                   2637: 	return '';
                   2638:     }
                   2639: 
1.44      ng       2640:     # Get the next/previous one or group of students
1.257     albertel 2641:     my $firststu = $env{'form.unamedom0'};
                   2642:     my $laststu = $env{'form.unamedom'.($ngrade-1)};
1.119     ng       2643:     my $ctr = 2;
1.41      ng       2644:     while ($laststu eq '') {
1.257     albertel 2645: 	$laststu  = $env{'form.unamedom'.($ngrade-$ctr)};
1.41      ng       2646: 	$ctr++;
                   2647: 	$laststu = $firststu if ($ctr > $ngrade);
                   2648:     }
1.44      ng       2649: 
1.41      ng       2650:     my (@parsedlist,@nextlist);
                   2651:     my ($nextflg) = 0;
1.524     raeburn  2652:     foreach my $item (sort 
1.294     albertel 2653: 	     {
                   2654: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                   2655: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                   2656: 		 }
                   2657: 		 return $a cmp $b;
                   2658: 	     } (keys(%$fullname))) {
1.605     www      2659: # FIXME: this is fishy, looks like the button label
1.41      ng       2660: 	if ($nextflg == 1 && $button =~ /Next$/) {
1.524     raeburn  2661: 	    push(@parsedlist,$item);
1.41      ng       2662: 	}
1.524     raeburn  2663: 	$nextflg = 1 if ($item eq $laststu);
1.41      ng       2664: 	if ($button eq 'Previous') {
1.524     raeburn  2665: 	    last if ($item eq $firststu);
                   2666: 	    push(@parsedlist,$item);
1.41      ng       2667: 	}
                   2668:     }
                   2669:     $ctr = 0;
1.605     www      2670: # FIXME: this is fishy, looks like the button label
1.41      ng       2671:     @parsedlist = reverse @parsedlist if ($button eq 'Previous');
1.582     raeburn  2672:     my $res_error;
                   2673:     my ($partlist) = &response_type($symb,\$res_error);
                   2674:     if ($res_error) {
                   2675:         $request->print(&navmap_errormsg());
                   2676:         return;
                   2677:     }
1.41      ng       2678:     foreach my $student (@parsedlist) {
1.257     albertel 2679: 	my $submitonly=$env{'form.submitonly'};
1.41      ng       2680: 	my ($uname,$udom) = split(/:/,$student);
1.301     albertel 2681: 	
                   2682: 	if ($submitonly eq 'queued') {
                   2683: 	    my %queue_status = 
                   2684: 		&Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
                   2685: 							$udom,$uname);
                   2686: 	    next if (!defined($queue_status{'gradingqueue'}));
                   2687: 	}
                   2688: 
1.156     albertel 2689: 	if ($submitonly =~ /^(yes|graded|incorrect)$/) {
1.257     albertel 2690: #	    my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
1.324     albertel 2691: 	    my %status=&student_gradeStatus($symb,$udom,$uname,$partlist);
1.145     albertel 2692: 	    my $submitted = 0;
1.248     albertel 2693: 	    my $ungraded = 0;
                   2694: 	    my $incorrect = 0;
1.524     raeburn  2695: 	    foreach my $item (keys(%status)) {
                   2696: 		$submitted = 1 if ($status{$item} ne 'nothing');
                   2697: 		$ungraded = 1 if ($status{$item} =~ /^ungraded/);
                   2698: 		$incorrect = 1 if ($status{$item} =~ /^incorrect/);
                   2699: 		my ($foo,$partid,$foo1) = split(/\./,$item);
1.145     albertel 2700: 		if ($status{'resource.'.$partid.'.submitted_by'} ne '') {
                   2701: 		    $submitted = 0;
                   2702: 		}
1.41      ng       2703: 	    }
1.156     albertel 2704: 	    next if (!$submitted && ($submitonly eq 'yes' ||
                   2705: 				     $submitonly eq 'incorrect' ||
                   2706: 				     $submitonly eq 'graded'));
1.248     albertel 2707: 	    next if (!$ungraded && ($submitonly eq 'graded'));
                   2708: 	    next if (!$incorrect && $submitonly eq 'incorrect');
1.41      ng       2709: 	}
1.524     raeburn  2710: 	push(@nextlist,$student) if ($ctr < $ntstu);
1.129     ng       2711: 	last if ($ctr == $ntstu);
1.41      ng       2712: 	$ctr++;
                   2713:     }
1.36      ng       2714: 
1.41      ng       2715:     $ctr = 0;
                   2716:     my $total = scalar(@nextlist)-1;
1.39      ng       2717: 
1.524     raeburn  2718:     foreach (sort(@nextlist)) {
1.41      ng       2719: 	my ($uname,$udom,$submitter) = split(/:/);
1.257     albertel 2720: 	$env{'form.student'}  = $uname;
                   2721: 	$env{'form.userdom'}  = $udom;
                   2722: 	$env{'form.fullname'} = $$fullname{$_};
1.41      ng       2723: 	&submission($request,$ctr,$total);
                   2724: 	$ctr++;
                   2725:     }
                   2726:     if ($total < 0) {
1.485     albertel 2727: 	my $the_end = '<h3><span class="LC_info">'.&mt('LON-CAPA User Message').'</span></h3><br />'."\n";
                   2728: 	$the_end.=&mt('<b>Message: </b> No more students for this section or class.').'<br /><br />'."\n";
                   2729: 	$the_end.=&mt('Click on the button below to return to the grading menu.').'<br /><br />'."\n";
1.324     albertel 2730: 	$the_end.=&show_grading_menu_form($symb);
1.41      ng       2731: 	$request->print($the_end);
                   2732:     }
                   2733:     return '';
1.38      ng       2734: }
1.36      ng       2735: 
1.44      ng       2736: #---- Save the score and award for each student, if changed
1.38      ng       2737: sub saveHandGrade {
1.324     albertel 2738:     my ($request,$symb,$stuname,$domain,$newflg,$submitter,$part) = @_;
1.342     banghart 2739:     my @version_parts;
1.104     albertel 2740:     my $usec = &Apache::lonnet::getsection($domain,$stuname,
1.257     albertel 2741: 					   $env{'request.course.id'});
1.104     albertel 2742:     if (!&canmodify($usec)) { return('not_allowed'); }
1.337     banghart 2743:     my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$domain,$stuname);
1.251     banghart 2744:     my @parts_graded;
1.77      ng       2745:     my %newrecord  = ();
                   2746:     my ($pts,$wgt) = ('','');
1.269     raeburn  2747:     my %aggregate = ();
                   2748:     my $aggregateflag = 0;
1.301     albertel 2749:     my @parts = split(/:/,$env{'form.partlist'.$newflg});
                   2750:     foreach my $new_part (@parts) {
1.337     banghart 2751: 	#collaborator ($submi may vary for different parts
1.259     banghart 2752: 	if ($submitter && $new_part ne $part) { next; }
                   2753: 	my $dropMenu = $env{'form.GD_SEL'.$newflg.'_'.$new_part};
1.125     ng       2754: 	if ($dropMenu eq 'excused') {
1.259     banghart 2755: 	    if ($record{'resource.'.$new_part.'.solved'} ne 'excused') {
                   2756: 		$newrecord{'resource.'.$new_part.'.solved'} = 'excused';
                   2757: 		if (exists($record{'resource.'.$new_part.'.awarded'})) {
                   2758: 		    $newrecord{'resource.'.$new_part.'.awarded'} = '';
1.58      albertel 2759: 		}
1.364     banghart 2760: 	        $newrecord{'resource.'.$new_part.'.regrader'}="$env{'user.name'}:$env{'user.domain'}";
1.58      albertel 2761: 	    }
1.125     ng       2762: 	} elsif ($dropMenu eq 'reset status'
1.259     banghart 2763: 		 && exists($record{'resource.'.$new_part.'.solved'})) { #don't bother if no old records -> no attempts
1.524     raeburn  2764: 	    foreach my $key (keys(%record)) {
1.259     banghart 2765: 		if ($key=~/^resource\.\Q$new_part\E\./) { $newrecord{$key} = ''; }
1.197     albertel 2766: 	    }
1.259     banghart 2767: 	    $newrecord{'resource.'.$new_part.'.regrader'}=
1.257     albertel 2768: 		"$env{'user.name'}:$env{'user.domain'}";
1.270     albertel 2769:             my $totaltries = $record{'resource.'.$part.'.tries'};
                   2770: 
                   2771:             my %last_resets = &get_last_resets($symb,$env{'request.course.id'},
                   2772: 					       [$new_part]);
                   2773:             my $aggtries =$totaltries;
1.269     raeburn  2774:             if ($last_resets{$new_part}) {
1.270     albertel 2775:                 $aggtries = &get_num_tries(\%record,$last_resets{$new_part},
                   2776: 					   $new_part);
1.269     raeburn  2777:             }
1.270     albertel 2778: 
                   2779:             my $solvedstatus = $record{'resource.'.$new_part.'.solved'};
1.269     raeburn  2780:             if ($aggtries > 0) {
1.327     albertel 2781:                 &decrement_aggs($symb,$new_part,\%aggregate,$aggtries,$totaltries,$solvedstatus);
1.269     raeburn  2782:                 $aggregateflag = 1;
                   2783:             }
1.125     ng       2784: 	} elsif ($dropMenu eq '') {
1.259     banghart 2785: 	    $pts = ($env{'form.GD_BOX'.$newflg.'_'.$new_part} ne '' ? 
                   2786: 		    $env{'form.GD_BOX'.$newflg.'_'.$new_part} : 
                   2787: 		    $env{'form.RADVAL'.$newflg.'_'.$new_part});
                   2788: 	    if ($pts eq '' && $env{'form.GD_SEL'.$newflg.'_'.$new_part} eq '') {
1.153     albertel 2789: 		next;
                   2790: 	    }
1.259     banghart 2791: 	    $wgt = $env{'form.WGT'.$newflg.'_'.$new_part} eq '' ? 1 : 
                   2792: 		$env{'form.WGT'.$newflg.'_'.$new_part};
1.41      ng       2793: 	    my $partial= $pts/$wgt;
1.259     banghart 2794: 	    if ($partial eq $record{'resource.'.$new_part.'.awarded'}) {
1.153     albertel 2795: 		#do not update score for part if not changed.
1.346     banghart 2796:                 &handback_files($request,$symb,$stuname,$domain,$newflg,$new_part,\%newrecord);
1.153     albertel 2797: 		next;
1.251     banghart 2798: 	    } else {
1.524     raeburn  2799: 	        push(@parts_graded,$new_part);
1.153     albertel 2800: 	    }
1.259     banghart 2801: 	    if ($record{'resource.'.$new_part.'.awarded'} ne $partial) {
                   2802: 		$newrecord{'resource.'.$new_part.'.awarded'}  = $partial;
1.153     albertel 2803: 	    }
1.259     banghart 2804: 	    my $reckey = 'resource.'.$new_part.'.solved';
1.41      ng       2805: 	    if ($partial == 0) {
1.153     albertel 2806: 		if ($record{$reckey} ne 'incorrect_by_override') {
                   2807: 		    $newrecord{$reckey} = 'incorrect_by_override';
                   2808: 		}
1.41      ng       2809: 	    } else {
1.153     albertel 2810: 		if ($record{$reckey} ne 'correct_by_override') {
                   2811: 		    $newrecord{$reckey} = 'correct_by_override';
                   2812: 		}
                   2813: 	    }	    
                   2814: 	    if ($submitter && 
1.259     banghart 2815: 		($record{'resource.'.$new_part.'.submitted_by'} ne $submitter)) {
                   2816: 		$newrecord{'resource.'.$new_part.'.submitted_by'} = $submitter;
1.41      ng       2817: 	    }
1.259     banghart 2818: 	    $newrecord{'resource.'.$new_part.'.regrader'}=
1.257     albertel 2819: 		"$env{'user.name'}:$env{'user.domain'}";
1.41      ng       2820: 	}
1.259     banghart 2821: 	# unless problem has been graded, set flag to version the submitted files
1.305     banghart 2822: 	unless ($record{'resource.'.$new_part.'.solved'} =~ /^correct_/  || 
                   2823: 	        $record{'resource.'.$new_part.'.solved'} eq 'incorrect_by_override' ||
                   2824: 	        $dropMenu eq 'reset status')
                   2825: 	   {
1.524     raeburn  2826: 	    push(@version_parts,$new_part);
1.259     banghart 2827: 	}
1.41      ng       2828:     }
1.301     albertel 2829:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   2830:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   2831: 
1.344     albertel 2832:     if (%newrecord) {
                   2833:         if (@version_parts) {
1.364     banghart 2834:             my @changed_keys = &version_portfiles(\%record, \@parts_graded, 
                   2835:                                 $env{'request.course.id'}, $symb, $domain, $stuname, \@version_parts);
1.344     albertel 2836: 	    @newrecord{@changed_keys} = @record{@changed_keys};
1.367     albertel 2837: 	    foreach my $new_part (@version_parts) {
                   2838: 		&handback_files($request,$symb,$stuname,$domain,$newflg,
                   2839: 				$new_part,\%newrecord);
                   2840: 	    }
1.259     banghart 2841:         }
1.44      ng       2842: 	&Apache::lonnet::cstore(\%newrecord,$symb,
1.257     albertel 2843: 				$env{'request.course.id'},$domain,$stuname);
1.380     albertel 2844: 	&check_and_remove_from_queue(\@parts,\%record,\%newrecord,$symb,
                   2845: 				     $cdom,$cnum,$domain,$stuname);
1.41      ng       2846:     }
1.269     raeburn  2847:     if ($aggregateflag) {
                   2848:         &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
1.301     albertel 2849: 			      $cdom,$cnum);
1.269     raeburn  2850:     }
1.301     albertel 2851:     return ('',$pts,$wgt);
1.36      ng       2852: }
1.322     albertel 2853: 
1.380     albertel 2854: sub check_and_remove_from_queue {
                   2855:     my ($parts,$record,$newrecord,$symb,$cdom,$cnum,$domain,$stuname) = @_;
                   2856:     my @ungraded_parts;
                   2857:     foreach my $part (@{$parts}) {
                   2858: 	if (    $record->{   'resource.'.$part.'.awarded'} eq ''
                   2859: 	     && $record->{   'resource.'.$part.'.solved' } ne 'excused'
                   2860: 	     && $newrecord->{'resource.'.$part.'.awarded'} eq ''
                   2861: 	     && $newrecord->{'resource.'.$part.'.solved' } ne 'excused'
                   2862: 		) {
                   2863: 	    push(@ungraded_parts, $part);
                   2864: 	}
                   2865:     }
                   2866:     if ( !@ungraded_parts ) {
                   2867: 	&Apache::bridgetask::remove_from_queue('gradingqueue',$symb,$cdom,
                   2868: 					       $cnum,$domain,$stuname);
                   2869:     }
                   2870: }
                   2871: 
1.337     banghart 2872: sub handback_files {
                   2873:     my ($request,$symb,$stuname,$domain,$newflg,$new_part,$newrecord) = @_;
1.517     raeburn  2874:     my $portfolio_root = '/userfiles/portfolio';
1.582     raeburn  2875:     my $res_error;
                   2876:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
                   2877:     if ($res_error) {
                   2878:         $request->print('<br />'.&navmap_errormsg().'<br />');
                   2879:         return;
                   2880:     }
1.375     albertel 2881:     my @part_response_id = &flatten_responseType($responseType);
                   2882:     foreach my $part_response_id (@part_response_id) {
                   2883:     	my ($part_id,$resp_id) = @{ $part_response_id };
                   2884: 	my $part_resp = join('_',@{ $part_response_id });
1.337     banghart 2885:             if (($env{'form.'.$newflg.'_'.$part_resp.'_returndoc1'}) && ($new_part == $part_id)) {
                   2886:                 # if multiple files are uploaded names will be 'returndoc2','returndoc3'
                   2887:                 my $file_counter = 1;
1.367     albertel 2888: 		my $file_msg;
1.337     banghart 2889:                 while ($env{'form.'.$newflg.'_'.$part_resp.'_returndoc'.$file_counter}) {
                   2890:                     my $fname=$env{'form.'.$newflg.'_'.$part_resp.'_returndoc'.$file_counter.'.filename'};
1.338     banghart 2891:                     my ($directory,$answer_file) = 
                   2892:                         ($env{'form.'.$newflg.'_'.$part_resp.'_origdoc'.$file_counter} =~ /^(.*?)([^\/]*)$/);
                   2893:                     my ($answer_name,$answer_ver,$answer_ext) =
                   2894: 		        &file_name_version_ext($answer_file);
1.355     banghart 2895: 		    my ($portfolio_path) = ($directory =~ /^.+$stuname\/portfolio(.*)/);
1.517     raeburn  2896:                     my $getpropath = 1;
                   2897: 		    my @dir_list = &Apache::lonnet::dirlist($portfolio_root.$portfolio_path,$domain,$stuname,$getpropath);
1.338     banghart 2898: 		    my $version = &get_next_version($answer_name, $answer_ext, \@dir_list);
1.355     banghart 2899:                     # fix file name
                   2900:                     my ($save_file_name) = (($directory.$answer_name.".$version.".$answer_ext) =~ /^.+\/${stuname}\/(.*)/);
                   2901:                     my $result=&Apache::lonnet::finishuserfileupload($stuname,$domain,
                   2902:             	                                $newflg.'_'.$part_resp.'_returndoc'.$file_counter,
                   2903:             	                                $save_file_name);
1.337     banghart 2904:                     if ($result !~ m|^/uploaded/|) {
1.536     raeburn  2905:                         $request->print('<br /><span class="LC_error">'.
                   2906:                             &mt('An error occurred ([_1]) while trying to upload [_2].',
                   2907:                                 $result,$newflg.'_'.$part_resp.'_returndoc'.$file_counter).
                   2908:                                         '</span>');
1.356     banghart 2909:                     } else {
1.360     banghart 2910:                         # mark the file as read only
                   2911:                         my @files = ($save_file_name);
1.372     albertel 2912:                         my @what = ($symb,$env{'request.course.id'},'handback');
1.360     banghart 2913:                         &Apache::lonnet::mark_as_readonly($domain,$stuname,\@files,\@what);
1.367     albertel 2914: 			if (exists($$newrecord{"resource.$new_part.$resp_id.handback"})) {
                   2915: 			    $$newrecord{"resource.$new_part.$resp_id.handback"}.=',';
                   2916: 			}
                   2917:                         $$newrecord{"resource.$new_part.$resp_id.handback"} .= $save_file_name;
                   2918: 			$file_msg.= "\n".'<br /><span class="LC_filename"><a href="/uploaded/'."$domain/$stuname/".$save_file_name.'">'.$save_file_name."</a></span><br />";
                   2919: 
1.337     banghart 2920:                     }
                   2921:                     $request->print("<br />".$fname." will be the uploaded file name");
1.354     albertel 2922:                     $request->print(" ".$env{'form.'.$newflg.'_'.$part_resp.'_origdoc'.$file_counter});
1.337     banghart 2923:                     $file_counter++;
                   2924:                 }
1.367     albertel 2925: 		my $subject = "File Handed Back by Instructor ";
                   2926: 		my $message = "A file has been returned that was originally submitted in reponse to: <br />";
                   2927: 		$message .= "<strong>".&Apache::lonnet::gettitle($symb)."</strong><br />";
                   2928: 		$message .= ' The returned file(s) are named: '. $file_msg;
                   2929: 		$message .= " and can be found in your portfolio space.";
1.418     albertel 2930: 		my ($feedurl,$showsymb) = 
                   2931: 		    &get_feedurl_and_symb($symb,$domain,$stuname);
1.386     raeburn  2932:                 my $restitle = &Apache::lonnet::gettitle($symb);
                   2933: 		my $msgstatus = 
                   2934:                    &Apache::lonmsg::user_normal_msg($stuname,$domain,$subject.
                   2935: 			 ' (File Returned) ['.$restitle.']',$message,undef,
1.418     albertel 2936:                          $feedurl,undef,undef,undef,$showsymb,$restitle);
1.337     banghart 2937:             }
                   2938:         }
1.338     banghart 2939:     return;
1.337     banghart 2940: }
                   2941: 
1.418     albertel 2942: sub get_feedurl_and_symb {
                   2943:     my ($symb,$uname,$udom) = @_;
                   2944:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
                   2945:     $url = &Apache::lonnet::clutter($url);
                   2946:     my $encrypturl=&Apache::lonnet::EXT('resource.0.encrypturl',
                   2947: 					$symb,$udom,$uname);
                   2948:     if ($encrypturl =~ /^yes$/i) {
                   2949: 	&Apache::lonenc::encrypted(\$url,1);
                   2950: 	&Apache::lonenc::encrypted(\$symb,1);
                   2951:     }
                   2952:     return ($url,$symb);
                   2953: }
                   2954: 
1.313     banghart 2955: sub get_submitted_files {
                   2956:     my ($udom,$uname,$partid,$respid,$record) = @_;
                   2957:     my @files;
                   2958:     if ($$record{"resource.$partid.$respid.portfiles"}) {
                   2959:         my $file_url = '/uploaded/'.$udom.'/'.$uname.'/portfolio';
                   2960:         foreach my $file (split(',',$$record{"resource.$partid.$respid.portfiles"})) {
                   2961:     	    push(@files,$file_url.$file);
                   2962:         }
                   2963:     }
                   2964:     if ($$record{"resource.$partid.$respid.uploadedurl"}) {
                   2965:         push(@files,$$record{"resource.$partid.$respid.uploadedurl"});
                   2966:     }
                   2967:     return (\@files);
                   2968: }
1.322     albertel 2969: 
1.269     raeburn  2970: # ----------- Provides number of tries since last reset.
                   2971: sub get_num_tries {
                   2972:     my ($record,$last_reset,$part) = @_;
                   2973:     my $timestamp = '';
                   2974:     my $num_tries = 0;
                   2975:     if ($$record{'version'}) {
                   2976:         for (my $version=$$record{'version'};$version>=1;$version--) {
                   2977:             if (exists($$record{$version.':resource.'.$part.'.solved'})) {
                   2978:                 $timestamp = $$record{$version.':timestamp'};
                   2979:                 if ($timestamp > $last_reset) {
                   2980:                     $num_tries ++;
                   2981:                 } else {
                   2982:                     last;
                   2983:                 }
                   2984:             }
                   2985:         }
                   2986:     }
                   2987:     return $num_tries;
                   2988: }
                   2989: 
                   2990: # ----------- Determine decrements required in aggregate totals 
                   2991: sub decrement_aggs {
                   2992:     my ($symb,$part,$aggregate,$aggtries,$totaltries,$solvedstatus) = @_;
                   2993:     my %decrement = (
                   2994:                         attempts => 0,
                   2995:                         users => 0,
                   2996:                         correct => 0
                   2997:                     );
                   2998:     $decrement{'attempts'} = $aggtries;
                   2999:     if ($solvedstatus =~ /^correct/) {
                   3000:         $decrement{'correct'} = 1;
                   3001:     }
                   3002:     if ($aggtries == $totaltries) {
                   3003:         $decrement{'users'} = 1;
                   3004:     }
1.524     raeburn  3005:     foreach my $type (keys(%decrement)) {
1.269     raeburn  3006:         $$aggregate{$symb."\0".$part."\0".$type} = -$decrement{$type};
                   3007:     }
                   3008:     return;
                   3009: }
                   3010: 
                   3011: # ----------- Determine timestamps for last reset of aggregate totals for parts  
                   3012: sub get_last_resets {
1.270     albertel 3013:     my ($symb,$courseid,$partids) =@_;
                   3014:     my %last_resets;
1.269     raeburn  3015:     my $cdom = $env{'course.'.$courseid.'.domain'};
                   3016:     my $cname = $env{'course.'.$courseid.'.num'};
1.271     albertel 3017:     my @keys;
                   3018:     foreach my $part (@{$partids}) {
                   3019: 	push(@keys,"$symb\0$part\0resettime");
                   3020:     }
                   3021:     my %results=&Apache::lonnet::get('nohist_resourcetracker',\@keys,
                   3022: 				     $cdom,$cname);
                   3023:     foreach my $part (@{$partids}) {
                   3024: 	$last_resets{$part}=$results{"$symb\0$part\0resettime"};
1.269     raeburn  3025:     }
1.270     albertel 3026:     return %last_resets;
1.269     raeburn  3027: }
                   3028: 
1.251     banghart 3029: # ----------- Handles creating versions for portfolio files as answers
                   3030: sub version_portfiles {
1.343     banghart 3031:     my ($record, $parts_graded, $courseid, $symb, $domain, $stu_name, $v_flag) = @_;
1.263     banghart 3032:     my $version_parts = join('|',@$v_flag);
1.343     banghart 3033:     my @returned_keys;
1.255     banghart 3034:     my $parts = join('|', @$parts_graded);
1.517     raeburn  3035:     my $portfolio_root = '/userfiles/portfolio';
1.277     albertel 3036:     foreach my $key (keys(%$record)) {
1.259     banghart 3037:         my $new_portfiles;
1.263     banghart 3038:         if ($key =~ /^resource\.($version_parts)\./ && $key =~ /\.portfiles$/ ) {
1.342     banghart 3039:             my @versioned_portfiles;
1.367     albertel 3040:             my @portfiles = split(/\s*,\s*/,$$record{$key});
1.252     banghart 3041:             foreach my $file (@portfiles) {
1.306     banghart 3042:                 &Apache::lonnet::unmark_as_readonly($domain,$stu_name,[$symb,$env{'request.course.id'}],$file);
1.304     albertel 3043:                 my ($directory,$answer_file) =($file =~ /^(.*?)([^\/]*)$/);
                   3044: 		my ($answer_name,$answer_ver,$answer_ext) =
                   3045: 		    &file_name_version_ext($answer_file);
1.517     raeburn  3046:                 my $getpropath = 1;    
                   3047:                 my @dir_list = &Apache::lonnet::dirlist($portfolio_root.$directory,$domain,$stu_name,$getpropath);
1.342     banghart 3048:                 my $version = &get_next_version($answer_name, $answer_ext, \@dir_list);
1.306     banghart 3049:                 my $new_answer = &version_selected_portfile($domain, $stu_name, $directory, $answer_file, $version);
                   3050:                 if ($new_answer ne 'problem getting file') {
1.342     banghart 3051:                     push(@versioned_portfiles, $directory.$new_answer);
1.306     banghart 3052:                     &Apache::lonnet::mark_as_readonly($domain,$stu_name,
1.367     albertel 3053:                         [$directory.$new_answer],
1.306     banghart 3054:                         [$symb,$env{'request.course.id'},'graded']);
1.259     banghart 3055:                 }
1.252     banghart 3056:             }
1.343     banghart 3057:             $$record{$key} = join(',',@versioned_portfiles);
                   3058:             push(@returned_keys,$key);
1.251     banghart 3059:         }
                   3060:     } 
1.343     banghart 3061:     return (@returned_keys);   
1.305     banghart 3062: }
                   3063: 
1.307     banghart 3064: sub get_next_version {
1.341     banghart 3065:     my ($answer_name, $answer_ext, $dir_list) = @_;
1.307     banghart 3066:     my $version;
                   3067:     foreach my $row (@$dir_list) {
                   3068:         my ($file) = split(/\&/,$row,2);
                   3069:         my ($file_name,$file_version,$file_ext) =
                   3070: 	    &file_name_version_ext($file);
                   3071:         if (($file_name eq $answer_name) && 
                   3072: 	    ($file_ext eq $answer_ext)) {
                   3073:                 # gets here if filename and extension match, regardless of version
                   3074:                 if ($file_version ne '') {
                   3075:                 # a versioned file is found  so save it for later
                   3076:                 if ($file_version > $version) {
                   3077: 		    $version = $file_version;
                   3078: 	        }
                   3079:             }
                   3080:         }
                   3081:     } 
                   3082:     $version ++;
                   3083:     return($version);
                   3084: }
                   3085: 
1.305     banghart 3086: sub version_selected_portfile {
1.306     banghart 3087:     my ($domain,$stu_name,$directory,$file_name,$version) = @_;
                   3088:     my ($answer_name,$answer_ver,$answer_ext) =
                   3089:         &file_name_version_ext($file_name);
                   3090:     my $new_answer;
                   3091:     $env{'form.copy'} = &Apache::lonnet::getfile("/uploaded/$domain/$stu_name/portfolio$directory$file_name");
                   3092:     if($env{'form.copy'} eq '-1') {
                   3093:         $new_answer = 'problem getting file';
                   3094:     } else {
                   3095:         $new_answer = $answer_name.'.'.$version.'.'.$answer_ext;
                   3096:         my $copy_result = &Apache::lonnet::finishuserfileupload(
                   3097:                             $stu_name,$domain,'copy',
                   3098: 		        '/portfolio'.$directory.$new_answer);
                   3099:     }    
                   3100:     return ($new_answer);
1.251     banghart 3101: }
                   3102: 
1.304     albertel 3103: sub file_name_version_ext {
                   3104:     my ($file)=@_;
                   3105:     my @file_parts = split(/\./, $file);
                   3106:     my ($name,$version,$ext);
                   3107:     if (@file_parts > 1) {
                   3108: 	$ext=pop(@file_parts);
                   3109: 	if (@file_parts > 1 && $file_parts[-1] =~ /^\d+$/) {
                   3110: 	    $version=pop(@file_parts);
                   3111: 	}
                   3112: 	$name=join('.',@file_parts);
                   3113:     } else {
                   3114: 	$name=join('.',@file_parts);
                   3115:     }
                   3116:     return($name,$version,$ext);
                   3117: }
                   3118: 
1.44      ng       3119: #--------------------------------------------------------------------------------------
                   3120: #
                   3121: #-------------------------- Next few routines handles grading by section or whole class
                   3122: #
                   3123: #--- Javascript to handle grading by section or whole class
1.42      ng       3124: sub viewgrades_js {
                   3125:     my ($request) = shift;
                   3126: 
1.539     riegler  3127:     my $alertmsg = &mt('A number equal or greater than 0 is expected. Entered value = ');
1.597     wenzelju 3128:     $request->print(&Apache::lonhtmlcommon::scripttag(<<VIEWJAVASCRIPT));
1.45      ng       3129:    function writePoint(partid,weight,point) {
1.125     ng       3130: 	var radioButton = document.classgrade["RADVAL_"+partid];
                   3131: 	var textbox = document.classgrade["TEXTVAL_"+partid];
1.42      ng       3132: 	if (point == "textval") {
1.125     ng       3133: 	    point = document.classgrade["TEXTVAL_"+partid].value;
1.109     matthew  3134: 	    if (isNaN(point) || parseFloat(point) < 0) {
1.539     riegler  3135: 		alert("$alertmsg"+parseFloat(point));
1.42      ng       3136: 		var resetbox = false;
                   3137: 		for (var i=0; i<radioButton.length; i++) {
                   3138: 		    if (radioButton[i].checked) {
                   3139: 			textbox.value = i;
                   3140: 			resetbox = true;
                   3141: 		    }
                   3142: 		}
                   3143: 		if (!resetbox) {
                   3144: 		    textbox.value = "";
                   3145: 		}
                   3146: 		return;
                   3147: 	    }
1.109     matthew  3148: 	    if (parseFloat(point) > parseFloat(weight)) {
                   3149: 		var resp = confirm("You entered a value ("+parseFloat(point)+
1.44      ng       3150: 				   ") greater than the weight for the part. Accept?");
                   3151: 		if (resp == false) {
                   3152: 		    textbox.value = "";
                   3153: 		    return;
                   3154: 		}
                   3155: 	    }
1.42      ng       3156: 	    for (var i=0; i<radioButton.length; i++) {
                   3157: 		radioButton[i].checked=false;
1.109     matthew  3158: 		if (parseFloat(point) == i) {
1.42      ng       3159: 		    radioButton[i].checked=true;
                   3160: 		}
                   3161: 	    }
1.41      ng       3162: 
1.42      ng       3163: 	} else {
1.125     ng       3164: 	    textbox.value = parseFloat(point);
1.42      ng       3165: 	}
1.41      ng       3166: 	for (i=0;i<document.classgrade.total.value;i++) {
1.125     ng       3167: 	    var user = document.classgrade["ctr"+i].value;
1.289     albertel 3168: 	    user = user.replace(new RegExp(':', 'g'),"_");
1.125     ng       3169: 	    var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
                   3170: 	    var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
                   3171: 	    var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
1.42      ng       3172: 	    if (saveval != "correct") {
                   3173: 		scorename.value = point;
1.43      ng       3174: 		if (selname[0].selected != true) {
                   3175: 		    selname[0].selected = true;
                   3176: 		}
1.42      ng       3177: 	    }
                   3178: 	}
1.125     ng       3179: 	document.classgrade["SELVAL_"+partid][0].selected = true;
1.42      ng       3180:     }
                   3181: 
                   3182:     function writeRadText(partid,weight) {
1.125     ng       3183: 	var selval   = document.classgrade["SELVAL_"+partid];
                   3184: 	var radioButton = document.classgrade["RADVAL_"+partid];
1.265     www      3185:         var override = document.classgrade["FORCE_"+partid].checked;
1.125     ng       3186: 	var textbox = document.classgrade["TEXTVAL_"+partid];
                   3187: 	if (selval[1].selected || selval[2].selected) {
1.42      ng       3188: 	    for (var i=0; i<radioButton.length; i++) {
                   3189: 		radioButton[i].checked=false;
                   3190: 
                   3191: 	    }
                   3192: 	    textbox.value = "";
                   3193: 
                   3194: 	    for (i=0;i<document.classgrade.total.value;i++) {
1.125     ng       3195: 		var user = document.classgrade["ctr"+i].value;
1.289     albertel 3196: 		user = user.replace(new RegExp(':', 'g'),"_");
1.125     ng       3197: 		var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
                   3198: 		var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
                   3199: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
1.265     www      3200: 		if ((saveval != "correct") || override) {
1.42      ng       3201: 		    scorename.value = "";
1.125     ng       3202: 		    if (selval[1].selected) {
                   3203: 			selname[1].selected = true;
                   3204: 		    } else {
                   3205: 			selname[2].selected = true;
                   3206: 			if (Number(document.classgrade["GD_"+user+"_"+partid+"_tries"].value)) 
                   3207: 			{document.classgrade["GD_"+user+"_"+partid+"_tries"].value = '0';}
                   3208: 		    }
1.42      ng       3209: 		}
                   3210: 	    }
1.43      ng       3211: 	} else {
                   3212: 	    for (i=0;i<document.classgrade.total.value;i++) {
1.125     ng       3213: 		var user = document.classgrade["ctr"+i].value;
1.289     albertel 3214: 		user = user.replace(new RegExp(':', 'g'),"_");
1.125     ng       3215: 		var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
                   3216: 		var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
                   3217: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
1.265     www      3218: 		if ((saveval != "correct") || override) {
1.125     ng       3219: 		    scorename.value = document.classgrade["GD_"+user+"_"+partid+"_awarded_s"].value;
1.43      ng       3220: 		    selname[0].selected = true;
                   3221: 		}
                   3222: 	    }
                   3223: 	}	    
1.42      ng       3224:     }
                   3225: 
                   3226:     function changeSelect(partid,user) {
1.125     ng       3227: 	var selval = document.classgrade["GD_"+user+'_'+partid+"_solved"];
                   3228: 	var textbox = document.classgrade["GD_"+user+'_'+partid+"_awarded"];
1.44      ng       3229: 	var point  = textbox.value;
1.125     ng       3230: 	var weight = document.classgrade["weight_"+partid].value;
1.44      ng       3231: 
1.109     matthew  3232: 	if (isNaN(point) || parseFloat(point) < 0) {
1.539     riegler  3233: 	    alert("$alertmsg"+parseFloat(point));
1.44      ng       3234: 	    textbox.value = "";
                   3235: 	    return;
                   3236: 	}
1.109     matthew  3237: 	if (parseFloat(point) > parseFloat(weight)) {
                   3238: 	    var resp = confirm("You entered a value ("+parseFloat(point)+
1.44      ng       3239: 			       ") greater than the weight of the part. Accept?");
                   3240: 	    if (resp == false) {
                   3241: 		textbox.value = "";
                   3242: 		return;
                   3243: 	    }
                   3244: 	}
1.42      ng       3245: 	selval[0].selected = true;
                   3246:     }
                   3247: 
                   3248:     function changeOneScore(partid,user) {
1.125     ng       3249: 	var selval = document.classgrade["GD_"+user+'_'+partid+"_solved"];
                   3250: 	if (selval[1].selected || selval[2].selected) {
                   3251: 	    document.classgrade["GD_"+user+'_'+partid+"_awarded"].value = "";
                   3252: 	    if (selval[2].selected) {
                   3253: 		document.classgrade["GD_"+user+'_'+partid+"_tries"].value = "0";
                   3254: 	    }
1.269     raeburn  3255:         }
1.42      ng       3256:     }
                   3257: 
                   3258:     function resetEntry(numpart) {
                   3259: 	for (ctpart=0;ctpart<numpart;ctpart++) {
1.125     ng       3260: 	    var partid = document.classgrade["partid_"+ctpart].value;
                   3261: 	    var radioButton = document.classgrade["RADVAL_"+partid];
                   3262: 	    var textbox = document.classgrade["TEXTVAL_"+partid];
                   3263: 	    var selval  = document.classgrade["SELVAL_"+partid];
1.42      ng       3264: 	    for (var i=0; i<radioButton.length; i++) {
                   3265: 		radioButton[i].checked=false;
                   3266: 
                   3267: 	    }
                   3268: 	    textbox.value = "";
                   3269: 	    selval[0].selected = true;
                   3270: 
                   3271: 	    for (i=0;i<document.classgrade.total.value;i++) {
1.125     ng       3272: 		var user = document.classgrade["ctr"+i].value;
1.289     albertel 3273: 		user = user.replace(new RegExp(':', 'g'),"_");
1.125     ng       3274: 		var resetscore = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
                   3275: 		resetscore.value = document.classgrade["GD_"+user+"_"+partid+"_awarded_s"].value;
                   3276: 		var resettries = document.classgrade["GD_"+user+"_"+partid+"_tries"];
                   3277: 		resettries.value = document.classgrade["GD_"+user+"_"+partid+"_tries_s"].value;
                   3278: 		var saveselval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
                   3279: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
1.42      ng       3280: 		if (saveselval == "excused") {
1.43      ng       3281: 		    if (selname[1].selected == false) { selname[1].selected = true;}
1.42      ng       3282: 		} else {
1.43      ng       3283: 		    if (selname[0].selected == false) {selname[0].selected = true};
1.42      ng       3284: 		}
                   3285: 	    }
1.41      ng       3286: 	}
1.42      ng       3287:     }
                   3288: 
1.41      ng       3289: VIEWJAVASCRIPT
1.42      ng       3290: }
                   3291: 
1.44      ng       3292: #--- show scores for a section or whole class w/ option to change/update a score
1.42      ng       3293: sub viewgrades {
                   3294:     my ($request) = shift;
                   3295:     &viewgrades_js($request);
1.41      ng       3296: 
1.324     albertel 3297:     my ($symb) = &get_symb($request);
1.168     albertel 3298:     #need to make sure we have the correct data for later EXT calls, 
                   3299:     #thus invalidate the cache
                   3300:     &Apache::lonnet::devalidatecourseresdata(
1.257     albertel 3301:                  $env{'course.'.$env{'request.course.id'}.'.num'},
                   3302:                  $env{'course.'.$env{'request.course.id'}.'.domain'});
1.168     albertel 3303:     &Apache::lonnet::clear_EXT_cache_status();
                   3304: 
1.398     albertel 3305:     my $result='<h3><span class="LC_info">'.&mt('Manual Grading').'</span></h3>';
1.41      ng       3306: 
                   3307:     #view individual student submission form - called using Javascript viewOneStudent
1.324     albertel 3308:     $result.=&jscriptNform($symb);
1.41      ng       3309: 
1.44      ng       3310:     #beginning of class grading form
1.442     banghart 3311:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
1.41      ng       3312:     $result.= '<form action="/adm/grades" method="post" name="classgrade">'."\n".
1.418     albertel 3313: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.38      ng       3314: 	'<input type="hidden" name="command" value="editgrades" />'."\n".
1.432     banghart 3315: 	&build_section_inputs().
1.257     albertel 3316: 	'<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n".
1.442     banghart 3317: 	'<input type="hidden" name="Status" value="'.$env{'stu_status'}.'" />'."\n".
1.72      ng       3318: 
1.560     raeburn  3319:     my ($common_header,$specific_header);
1.257     albertel 3320:     if ($env{'form.section'} eq 'all') {
1.560     raeburn  3321: 	$common_header = &mt('Assign Common Grade to Class');
                   3322:         $specific_header = &mt('Assign Grade to Specific Students in Class');
1.257     albertel 3323:     } elsif ($env{'form.section'} eq 'none') {
1.560     raeburn  3324:         $common_header = &mt('Assign Common Grade to Students in no Section');
                   3325: 	$specific_header = &mt('Assign Grade to Specific Students in no Section');
1.52      albertel 3326:     } else {
1.560     raeburn  3327:         my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
                   3328:         $common_header = &mt('Assign Common Grade to Students in Section(s) [_1]',$section_display);
                   3329: 	$specific_header = &mt('Assign Grade to Specific Students in Section(s) [_1]',$section_display);
1.52      albertel 3330:     }
1.560     raeburn  3331:     $result.= '<h3>'.$common_header.'</h3>'.&Apache::loncommon::start_data_table();
1.44      ng       3332:     #radio buttons/text box for assigning points for a section or class.
                   3333:     #handles different parts of a problem
1.582     raeburn  3334:     my $res_error;
                   3335:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
                   3336:     if ($res_error) {
                   3337:         return &navmap_errormsg();
                   3338:     }
1.42      ng       3339:     my %weight = ();
                   3340:     my $ctsparts = 0;
1.45      ng       3341:     my %seen = ();
1.375     albertel 3342:     my @part_response_id = &flatten_responseType($responseType);
                   3343:     foreach my $part_response_id (@part_response_id) {
                   3344:     	my ($partid,$respid) = @{ $part_response_id };
                   3345: 	my $part_resp = join('_',@{ $part_response_id });
1.45      ng       3346: 	next if $seen{$partid};
                   3347: 	$seen{$partid}++;
1.375     albertel 3348: 	my $handgrade=$$handgrade{$part_resp};
1.42      ng       3349: 	my $wgt = &Apache::lonnet::EXT('resource.'.$partid.'.weight',$symb);
                   3350: 	$weight{$partid} = $wgt eq '' ? '1' : $wgt;
                   3351: 
1.324     albertel 3352: 	my $display_part=&get_display_part($partid,$symb);
1.485     albertel 3353: 	my $radio.='<table border="0"><tr>';  
1.41      ng       3354: 	my $ctr = 0;
1.42      ng       3355: 	while ($ctr<=$weight{$partid}) { # display radio buttons in a nice table 10 across
1.485     albertel 3356: 	    $radio.= '<td><label><input type="radio" name="RADVAL_'.$partid.'" '.
1.54      albertel 3357: 		'onclick="javascript:writePoint(\''.$partid.'\','.$weight{$partid}.
1.288     albertel 3358: 		','.$ctr.')" />'.$ctr."</label></td>\n";
1.41      ng       3359: 	    $result.=(($ctr+1)%10 == 0 ? '</tr><tr>' : '');
                   3360: 	    $ctr++;
                   3361: 	}
1.485     albertel 3362: 	$radio.='</tr></table>';
                   3363: 	my $line = '<input type="text" name="TEXTVAL_'.
1.589     bisitz   3364: 	    $partid.'" size="4" '.'onchange="javascript:writePoint(\''.
1.54      albertel 3365: 		$partid.'\','.$weight{$partid}.',\'textval\')" /> /'.
1.539     riegler  3366: 	    $weight{$partid}.' '.&mt('(problem weight)').'</td>'."\n";
                   3367: 	$line.= '<td><b>'.&mt('Grade Status').':</b><select name="SELVAL_'.$partid.'"'.
1.589     bisitz   3368: 	    'onchange="javascript:writeRadText(\''.$partid.'\','.
1.59      albertel 3369: 		$weight{$partid}.')"> '.
1.401     albertel 3370: 	    '<option selected="selected"> </option>'.
1.485     albertel 3371: 	    '<option value="excused">'.&mt('excused').'</option>'.
                   3372: 	    '<option value="reset status">'.&mt('reset status').'</option>'.
                   3373: 	    '</select></td>'.
                   3374:             '<td><label><input type="checkbox" name="FORCE_'.$partid.'" />'.&mt('Override "Correct"').'</label>';
                   3375: 	$line.='<input type="hidden" name="partid_'.
                   3376: 	    $ctsparts.'" value="'.$partid.'" />'."\n";
                   3377: 	$line.='<input type="hidden" name="weight_'.
                   3378: 	    $partid.'" value="'.$weight{$partid}.'" />'."\n";
                   3379: 
                   3380: 	$result.=
                   3381: 	    &Apache::loncommon::start_data_table_row()."\n".
1.577     bisitz   3382: 	    '<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 3383: 	    &Apache::loncommon::end_data_table_row()."\n";
1.42      ng       3384: 	$ctsparts++;
1.41      ng       3385:     }
1.474     albertel 3386:     $result.=&Apache::loncommon::end_data_table()."\n".
1.52      albertel 3387: 	'<input type="hidden" name="totalparts" value="'.$ctsparts.'" />';
1.485     albertel 3388:     $result.='<input type="button" value="'.&mt('Revert to Default').'" '.
1.589     bisitz   3389: 	'onclick="javascript:resetEntry('.$ctsparts.');" />';
1.41      ng       3390: 
1.44      ng       3391:     #table listing all the students in a section/class
                   3392:     #header of table
1.560     raeburn  3393:     $result.= '<h3>'.$specific_header.'</h3>'.
                   3394:               &Apache::loncommon::start_data_table().
                   3395: 	      &Apache::loncommon::start_data_table_header_row().
                   3396: 	      '<th>'.&mt('No.').'</th>'.
                   3397: 	      '<th>'.&nameUserString('header')."</th>\n";
1.582     raeburn  3398:     my $partserror;
                   3399:     my (@parts) = sort(&getpartlist($symb,\$partserror));
                   3400:     if ($partserror) {
                   3401:         return &navmap_errormsg();
                   3402:     }
1.324     albertel 3403:     my (undef,undef,$url)=&Apache::lonnet::decode_symb($symb);
1.269     raeburn  3404:     my @partids = ();
1.41      ng       3405:     foreach my $part (@parts) {
                   3406: 	my $display=&Apache::lonnet::metadata($url,$part.'.display');
1.539     riegler  3407:         my $narrowtext = &mt('Tries');
                   3408: 	$display =~ s|^Number of Attempts|$narrowtext <br />|; # makes the column narrower
1.41      ng       3409: 	if  (!$display) { $display = &Apache::lonnet::metadata($url,$part.'.name'); }
1.207     albertel 3410: 	my ($partid) = &split_part_type($part);
1.524     raeburn  3411:         push(@partids,$partid);
1.324     albertel 3412: 	my $display_part=&get_display_part($partid,$symb);
1.41      ng       3413: 	if ($display =~ /^Partial Credit Factor/) {
1.485     albertel 3414: 	    $result.='<th>'.
                   3415: 		&mt('Score Part: [_1]<br /> (weight = [_2])',
                   3416: 		    $display_part,$weight{$partid}).'</th>'."\n";
1.41      ng       3417: 	    next;
1.485     albertel 3418: 	    
1.207     albertel 3419: 	} else {
1.485     albertel 3420: 	    if ($display =~ /Problem Status/) {
                   3421: 		my $grade_status_mt = &mt('Grade Status');
                   3422: 		$display =~ s{Problem Status}{$grade_status_mt<br />};
                   3423: 	    }
                   3424: 	    my $part_mt = &mt('Part:');
                   3425: 	    $display =~s{\[Part: \Q$partid\E\]}{$part_mt $display_part};
1.41      ng       3426: 	}
1.485     albertel 3427: 
1.474     albertel 3428: 	$result.='<th>'.$display.'</th>'."\n";
1.41      ng       3429:     }
1.474     albertel 3430:     $result.=&Apache::loncommon::end_data_table_header_row();
1.44      ng       3431: 
1.270     albertel 3432:     my %last_resets = 
                   3433: 	&get_last_resets($symb,$env{'request.course.id'},\@partids);
1.269     raeburn  3434: 
1.41      ng       3435:     #get info for each student
1.44      ng       3436:     #list all the students - with points and grade status
1.257     albertel 3437:     my (undef,undef,$fullname) = &getclasslist($env{'form.section'},'1');
1.41      ng       3438:     my $ctr = 0;
1.294     albertel 3439:     foreach (sort 
                   3440: 	     {
                   3441: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                   3442: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                   3443: 		 }
                   3444: 		 return $a cmp $b;
                   3445: 	     } (keys(%$fullname))) {
1.126     ng       3446: 	$ctr++;
1.324     albertel 3447: 	$result.=&viewstudentgrade($symb,$env{'request.course.id'},
1.269     raeburn  3448: 				   $_,$$fullname{$_},\@parts,\%weight,$ctr,\%last_resets);
1.41      ng       3449:     }
1.474     albertel 3450:     $result.=&Apache::loncommon::end_data_table();
1.41      ng       3451:     $result.='<input type="hidden" name="total" value="'.$ctr.'" />'."\n";
1.485     albertel 3452:     $result.='<input type="button" value="'.&mt('Save').'" '.
1.589     bisitz   3453: 	'onclick="javascript:submit();" target="_self" /></form>'."\n";
1.96      albertel 3454:     if (scalar(%$fullname) eq 0) {
                   3455: 	my $colspan=3+scalar(@parts);
1.433     banghart 3456: 	my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
1.442     banghart 3457:         my $stu_status = join(' or ',&Apache::loncommon::get_env_multiple('form.Status'));
1.433     banghart 3458: 	$result='<span class="LC_warning">'.
1.485     albertel 3459: 	    &mt('There are no students in section(s) [_1] with enrollment status [_2] to modify or grade.',
1.442     banghart 3460: 	        $section_display, $stu_status).
1.433     banghart 3461: 	    '</span>';
1.96      albertel 3462:     }
1.324     albertel 3463:     $result.=&show_grading_menu_form($symb);
1.41      ng       3464:     return $result;
                   3465: }
                   3466: 
1.44      ng       3467: #--- call by previous routine to display each student
1.41      ng       3468: sub viewstudentgrade {
1.324     albertel 3469:     my ($symb,$courseid,$student,$fullname,$parts,$weight,$ctr,$last_resets) = @_;
1.44      ng       3470:     my ($uname,$udom) = split(/:/,$student);
                   3471:     my %record=&Apache::lonnet::restore($symb,$courseid,$udom,$uname);
1.269     raeburn  3472:     my %aggregates = (); 
1.474     albertel 3473:     my $result=&Apache::loncommon::start_data_table_row().'<td align="right">'.
1.233     albertel 3474: 	'<input type="hidden" name="ctr'.($ctr-1).'" value="'.$student.'" />'.
                   3475: 	"\n".$ctr.'&nbsp;</td><td>&nbsp;'.
1.44      ng       3476: 	'<a href="javascript:viewOneStudent(\''.$uname.'\',\''.$udom.
1.417     albertel 3477: 	'\');" target="_self">'.$fullname.'</a> '.
1.398     albertel 3478: 	'<span class="LC_internal_info">('.$uname.($env{'user.domain'} eq $udom ? '' : ':'.$udom).')</span></td>'."\n";
1.281     albertel 3479:     $student=~s/:/_/; # colon doen't work in javascript for names
1.63      albertel 3480:     foreach my $apart (@$parts) {
                   3481: 	my ($part,$type) = &split_part_type($apart);
1.41      ng       3482: 	my $score=$record{"resource.$part.$type"};
1.276     albertel 3483:         $result.='<td align="center">';
1.269     raeburn  3484:         my ($aggtries,$totaltries);
                   3485:         unless (exists($aggregates{$part})) {
1.270     albertel 3486: 	    $totaltries = $record{'resource.'.$part.'.tries'};
                   3487: 
                   3488: 	    $aggtries = $totaltries;
1.269     raeburn  3489:             if ($$last_resets{$part}) {  
1.270     albertel 3490:                 $aggtries = &get_num_tries(\%record,$$last_resets{$part},
                   3491: 					   $part);
                   3492:             }
1.269     raeburn  3493:             $result.='<input type="hidden" name="'.
                   3494:                 'GD_'.$student.'_'.$part.'_aggtries" value="'.$aggtries.'" />'."\n";
                   3495:             $result.='<input type="hidden" name="'.
                   3496:                 'GD_'.$student.'_'.$part.'_totaltries" value="'.$totaltries.'" />'."\n";
                   3497:             $aggregates{$part} = 1;
                   3498:         }
1.41      ng       3499: 	if ($type eq 'awarded') {
1.320     albertel 3500: 	    my $pts = $score eq '' ? '' : &compute_points($score,$$weight{$part});
1.42      ng       3501: 	    $result.='<input type="hidden" name="'.
1.89      albertel 3502: 		'GD_'.$student.'_'.$part.'_awarded_s" value="'.$pts.'" />'."\n";
1.233     albertel 3503: 	    $result.='<input type="text" name="'.
1.89      albertel 3504: 		'GD_'.$student.'_'.$part.'_awarded" '.
1.589     bisitz   3505:                 'onchange="javascript:changeSelect(\''.$part.'\',\''.$student.
1.44      ng       3506: 		'\')" value="'.$pts.'" size="4" /></td>'."\n";
1.41      ng       3507: 	} elsif ($type eq 'solved') {
                   3508: 	    my ($status,$foo)=split(/_/,$score,2);
                   3509: 	    $status = 'nothing' if ($status eq '');
1.89      albertel 3510: 	    $result.='<input type="hidden" name="'.'GD_'.$student.'_'.
1.54      albertel 3511: 		$part.'_solved_s" value="'.$status.'" />'."\n";
1.233     albertel 3512: 	    $result.='&nbsp;<select name="'.
1.89      albertel 3513: 		'GD_'.$student.'_'.$part.'_solved" '.
1.589     bisitz   3514:                 'onchange="javascript:changeOneScore(\''.$part.'\',\''.$student.'\')" >'."\n";
1.485     albertel 3515: 	    $result.= (($status eq 'excused') ? '<option> </option><option selected="selected" value="excused">'.&mt('excused').'</option>' 
                   3516: 		: '<option selected="selected"> </option><option value="excused">'.&mt('excused').'</option>')."\n";
                   3517: 	    $result.='<option value="reset status">'.&mt('reset status').'</option>';
1.126     ng       3518: 	    $result.="</select>&nbsp;</td>\n";
1.122     ng       3519: 	} else {
                   3520: 	    $result.='<input type="hidden" name="'.
                   3521: 		'GD_'.$student.'_'.$part.'_'.$type.'_s" value="'.$score.'" />'.
                   3522: 		    "\n";
1.233     albertel 3523: 	    $result.='<input type="text" name="'.
1.122     ng       3524: 		'GD_'.$student.'_'.$part.'_'.$type.'" '.
                   3525: 		'value="'.$score.'" size="4" /></td>'."\n";
1.41      ng       3526: 	}
                   3527:     }
1.474     albertel 3528:     $result.=&Apache::loncommon::end_data_table_row();
1.41      ng       3529:     return $result;
1.38      ng       3530: }
                   3531: 
1.44      ng       3532: #--- change scores for all the students in a section/class
                   3533: #    record does not get update if unchanged
1.38      ng       3534: sub editgrades {
1.41      ng       3535:     my ($request) = @_;
                   3536: 
1.324     albertel 3537:     my $symb=&get_symb($request);
1.433     banghart 3538:     my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
1.477     albertel 3539:     my $title='<h2>'.&mt('Current Grade Status').'</h2>';
1.433     banghart 3540:     $title.='<h4>'.&mt('<b>Section: </b>[_1]',$section_display).'</h4>'."\n";
1.126     ng       3541: 
1.477     albertel 3542:     my $result= &Apache::loncommon::start_data_table().
                   3543: 	&Apache::loncommon::start_data_table_header_row().
                   3544: 	'<th rowspan="2" valign="middle">'.&mt('No.').'</th>'.
                   3545: 	'<th rowspan="2" valign="middle">'.&nameUserString('header')."</th>\n";
1.43      ng       3546:     my %scoreptr = (
                   3547: 		    'correct'  =>'correct_by_override',
                   3548: 		    'incorrect'=>'incorrect_by_override',
                   3549: 		    'excused'  =>'excused',
                   3550: 		    'ungraded' =>'ungraded_attempted',
1.596     raeburn  3551:                     'credited' =>'credit_attempted',
1.43      ng       3552: 		    'nothing'  => '',
                   3553: 		    );
1.257     albertel 3554:     my ($classlist,undef,$fullname) = &getclasslist($env{'form.section'},'0');
1.34      ng       3555: 
1.44      ng       3556:     my (@partid);
                   3557:     my %weight = ();
1.54      albertel 3558:     my %columns = ();
1.44      ng       3559:     my ($i,$ctr,$count,$rec_update) = (0,0,0,0);
1.54      albertel 3560: 
1.582     raeburn  3561:     my $partserror;
                   3562:     my (@parts) = sort(&getpartlist($symb,\$partserror));
                   3563:     if ($partserror) {
                   3564:         return &navmap_errormsg();
                   3565:     }
1.54      albertel 3566:     my $header;
1.257     albertel 3567:     while ($ctr < $env{'form.totalparts'}) {
                   3568: 	my $partid = $env{'form.partid_'.$ctr};
1.524     raeburn  3569: 	push(@partid,$partid);
1.257     albertel 3570: 	$weight{$partid} = $env{'form.weight_'.$partid};
1.44      ng       3571: 	$ctr++;
1.54      albertel 3572:     }
1.324     albertel 3573:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
1.54      albertel 3574:     foreach my $partid (@partid) {
1.478     albertel 3575: 	$header .= '<th align="center">'.&mt('Old Score').'</th>'.
                   3576: 	    '<th align="center">'.&mt('New Score').'</th>';
1.54      albertel 3577: 	$columns{$partid}=2;
                   3578: 	foreach my $stores (@parts) {
                   3579: 	    my ($part,$type) = &split_part_type($stores);
                   3580: 	    if ($part !~ m/^\Q$partid\E/) { next;}
                   3581: 	    if ($type eq 'awarded' || $type eq 'solved') { next; }
                   3582: 	    my $display=&Apache::lonnet::metadata($url,$stores.'.display');
1.551     raeburn  3583: 	    $display =~ s/\[Part: \Q$part\E\]//;
1.539     riegler  3584:             my $narrowtext = &mt('Tries');
                   3585: 	    $display =~ s/Number of Attempts/$narrowtext/;
                   3586: 	    $header .= '<th align="center">'.&mt('Old').' '.$display.'</th>'.
                   3587: 		'<th align="center">'.&mt('New').' '.$display.'</th>';
1.54      albertel 3588: 	    $columns{$partid}+=2;
                   3589: 	}
                   3590:     }
                   3591:     foreach my $partid (@partid) {
1.324     albertel 3592: 	my $display_part=&get_display_part($partid,$symb);
1.478     albertel 3593: 	$result .= '<th colspan="'.$columns{$partid}.'" align="center">'.
                   3594: 	    &mt('Part: [_1] (Weight = [_2])',$display_part,$weight{$partid}).
                   3595: 	    '</th>';
1.54      albertel 3596: 
1.44      ng       3597:     }
1.477     albertel 3598:     $result .= &Apache::loncommon::end_data_table_header_row().
                   3599: 	&Apache::loncommon::start_data_table_header_row().
                   3600: 	$header.
                   3601: 	&Apache::loncommon::end_data_table_header_row();
                   3602:     my @noupdate;
1.126     ng       3603:     my ($updateCtr,$noupdateCtr) = (1,1);
1.257     albertel 3604:     for ($i=0; $i<$env{'form.total'}; $i++) {
1.93      albertel 3605: 	my $line;
1.257     albertel 3606: 	my $user = $env{'form.ctr'.$i};
1.281     albertel 3607: 	my ($uname,$udom)=split(/:/,$user);
1.44      ng       3608: 	my %newrecord;
                   3609: 	my $updateflag = 0;
1.281     albertel 3610: 	$line .= '<td>'.&nameUserString(undef,$$fullname{$user},$uname,$udom).'</td>';
1.108     albertel 3611: 	my $usec=$classlist->{"$uname:$udom"}[5];
1.105     albertel 3612: 	if (!&canmodify($usec)) {
1.126     ng       3613: 	    my $numcols=scalar(@partid)*4+2;
1.477     albertel 3614: 	    push(@noupdate,
1.478     albertel 3615: 		 $line."<td colspan=\"$numcols\"><span class=\"LC_warning\">".
                   3616: 		 &mt('Not allowed to modify student')."</span></td></tr>");
1.105     albertel 3617: 	    next;
                   3618: 	}
1.269     raeburn  3619:         my %aggregate = ();
                   3620:         my $aggregateflag = 0;
1.281     albertel 3621: 	$user=~s/:/_/; # colon doen't work in javascript for names
1.44      ng       3622: 	foreach (@partid) {
1.257     albertel 3623: 	    my $old_aw    = $env{'form.GD_'.$user.'_'.$_.'_awarded_s'};
1.54      albertel 3624: 	    my $old_part_pcr = $old_aw/($weight{$_} ne '0' ? $weight{$_}:1);
                   3625: 	    my $old_part  = $old_aw eq '' ? '' : $old_part_pcr;
1.257     albertel 3626: 	    my $old_score = $scoreptr{$env{'form.GD_'.$user.'_'.$_.'_solved_s'}};
                   3627: 	    my $awarded   = $env{'form.GD_'.$user.'_'.$_.'_awarded'};
1.54      albertel 3628: 	    my $pcr       = $awarded/($weight{$_} ne '0' ? $weight{$_} : 1);
                   3629: 	    my $partial   = $awarded eq '' ? '' : $pcr;
1.44      ng       3630: 	    my $score;
                   3631: 	    if ($partial eq '') {
1.257     albertel 3632: 		$score = $scoreptr{$env{'form.GD_'.$user.'_'.$_.'_solved_s'}};
1.44      ng       3633: 	    } elsif ($partial > 0) {
                   3634: 		$score = 'correct_by_override';
                   3635: 	    } elsif ($partial == 0) {
                   3636: 		$score = 'incorrect_by_override';
                   3637: 	    }
1.257     albertel 3638: 	    my $dropMenu = $env{'form.GD_'.$user.'_'.$_.'_solved'};
1.125     ng       3639: 	    $score = 'excused' if (($dropMenu eq 'excused') && ($score ne 'excused'));
                   3640: 
1.292     albertel 3641: 	    $newrecord{'resource.'.$_.'.regrader'}=
                   3642: 		"$env{'user.name'}:$env{'user.domain'}";
1.125     ng       3643: 	    if ($dropMenu eq 'reset status' &&
                   3644: 		$old_score ne '') { # ignore if no previous attempts => nothing to reset
1.299     albertel 3645: 		$newrecord{'resource.'.$_.'.tries'} = '';
1.125     ng       3646: 		$newrecord{'resource.'.$_.'.solved'} = '';
                   3647: 		$newrecord{'resource.'.$_.'.award'} = '';
1.299     albertel 3648: 		$newrecord{'resource.'.$_.'.awarded'} = '';
1.125     ng       3649: 		$updateflag = 1;
1.269     raeburn  3650:                 if ($env{'form.GD_'.$user.'_'.$_.'_aggtries'} > 0) {
                   3651:                     my $aggtries = $env{'form.GD_'.$user.'_'.$_.'_aggtries'};
                   3652:                     my $totaltries = $env{'form.GD_'.$user.'_'.$_.'_totaltries'};
                   3653:                     my $solvedstatus = $env{'form.GD_'.$user.'_'.$_.'_solved_s'};
                   3654:                     &decrement_aggs($symb,$_,\%aggregate,$aggtries,$totaltries,$solvedstatus);
                   3655:                     $aggregateflag = 1;
                   3656:                 }
1.139     albertel 3657: 	    } elsif (!($old_part eq $partial && $old_score eq $score)) {
                   3658: 		$updateflag = 1;
                   3659: 		$newrecord{'resource.'.$_.'.awarded'}  = $partial if $partial ne '';
                   3660: 		$newrecord{'resource.'.$_.'.solved'}   = $score;
                   3661: 		$rec_update++;
1.125     ng       3662: 	    }
                   3663: 
1.93      albertel 3664: 	    $line .= '<td align="center">'.$old_aw.'&nbsp;</td>'.
1.44      ng       3665: 		'<td align="center">'.$awarded.
                   3666: 		($score eq 'excused' ? $score : '').'&nbsp;</td>';
1.5       albertel 3667: 
1.54      albertel 3668: 
                   3669: 	    my $partid=$_;
                   3670: 	    foreach my $stores (@parts) {
                   3671: 		my ($part,$type) = &split_part_type($stores);
                   3672: 		if ($part !~ m/^\Q$partid\E/) { next;}
                   3673: 		if ($type eq 'awarded' || $type eq 'solved') { next; }
1.257     albertel 3674: 		my $old_aw    = $env{'form.GD_'.$user.'_'.$part.'_'.$type.'_s'};
                   3675: 		my $awarded   = $env{'form.GD_'.$user.'_'.$part.'_'.$type};
1.54      albertel 3676: 		if ($awarded ne '' && $awarded ne $old_aw) {
                   3677: 		    $newrecord{'resource.'.$part.'.'.$type}= $awarded;
1.257     albertel 3678: 		    $newrecord{'resource.'.$part.'.regrader'}="$env{'user.name'}:$env{'user.domain'}";
1.54      albertel 3679: 		    $updateflag=1;
                   3680: 		}
1.93      albertel 3681: 		$line .= '<td align="center">'.$old_aw.'&nbsp;</td>'.
1.54      albertel 3682: 		    '<td align="center">'.$awarded.'&nbsp;</td>';
                   3683: 	    }
1.44      ng       3684: 	}
1.477     albertel 3685: 	$line.="\n";
1.301     albertel 3686: 
                   3687: 	my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   3688: 	my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   3689: 
1.44      ng       3690: 	if ($updateflag) {
                   3691: 	    $count++;
1.257     albertel 3692: 	    &Apache::lonnet::cstore(\%newrecord,$symb,$env{'request.course.id'},
1.89      albertel 3693: 				    $udom,$uname);
1.301     albertel 3694: 
                   3695: 	    if (&Apache::bridgetask::in_queue('gradingqueue',$symb,$cdom,
                   3696: 					      $cnum,$udom,$uname)) {
                   3697: 		# need to figure out if should be in queue.
                   3698: 		my %record =  
                   3699: 		    &Apache::lonnet::restore($symb,$env{'request.course.id'},
                   3700: 					     $udom,$uname);
                   3701: 		my $all_graded = 1;
                   3702: 		my $none_graded = 1;
                   3703: 		foreach my $part (@parts) {
                   3704: 		    if ( $record{'resource.'.$part.'.awarded'} eq '' ) {
                   3705: 			$all_graded = 0;
                   3706: 		    } else {
                   3707: 			$none_graded = 0;
                   3708: 		    }
                   3709: 		}
                   3710: 
                   3711: 		if ($all_graded || $none_graded) {
                   3712: 		    &Apache::bridgetask::remove_from_queue('gradingqueue',
                   3713: 							   $symb,$cdom,$cnum,
                   3714: 							   $udom,$uname);
                   3715: 		}
                   3716: 	    }
                   3717: 
1.477     albertel 3718: 	    $result.=&Apache::loncommon::start_data_table_row().
                   3719: 		'<td align="right">&nbsp;'.$updateCtr.'&nbsp;</td>'.$line.
                   3720: 		&Apache::loncommon::end_data_table_row();
1.126     ng       3721: 	    $updateCtr++;
1.93      albertel 3722: 	} else {
1.477     albertel 3723: 	    push(@noupdate,
                   3724: 		 '<td align="right">&nbsp;'.$noupdateCtr.'&nbsp;</td>'.$line);
1.126     ng       3725: 	    $noupdateCtr++;
1.44      ng       3726: 	}
1.269     raeburn  3727:         if ($aggregateflag) {
                   3728:             &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
1.301     albertel 3729: 				  $cdom,$cnum);
1.269     raeburn  3730:         }
1.93      albertel 3731:     }
1.477     albertel 3732:     if (@noupdate) {
1.126     ng       3733: #	my $numcols=(scalar(@partid)*(scalar(@parts)-1)*2)+3;
                   3734: 	my $numcols=scalar(@partid)*4+2;
1.477     albertel 3735: 	$result .= &Apache::loncommon::start_data_table_row('LC_empty_row').
1.478     albertel 3736: 	    '<td align="center" colspan="'.$numcols.'">'.
                   3737: 	    &mt('No Changes Occurred For the Students Below').
                   3738: 	    '</td>'.
1.477     albertel 3739: 	    &Apache::loncommon::end_data_table_row();
                   3740: 	foreach my $line (@noupdate) {
                   3741: 	    $result.=
                   3742: 		&Apache::loncommon::start_data_table_row().
                   3743: 		$line.
                   3744: 		&Apache::loncommon::end_data_table_row();
                   3745: 	}
1.44      ng       3746:     }
1.477     albertel 3747:     $result .= &Apache::loncommon::end_data_table().
                   3748: 	&show_grading_menu_form($symb);
1.478     albertel 3749:     my $msg = '<p><b>'.
                   3750: 	&mt('Number of records updated = [_1] for [quant,_2,student].',
                   3751: 	    $rec_update,$count).'</b><br />'.
                   3752: 	'<b>'.&mt('Total number of students = [_1]',$env{'form.total'}).
                   3753: 	'</b></p>';
1.44      ng       3754:     return $title.$msg.$result;
1.5       albertel 3755: }
1.54      albertel 3756: 
                   3757: sub split_part_type {
                   3758:     my ($partstr) = @_;
                   3759:     my ($temp,@allparts)=split(/_/,$partstr);
                   3760:     my $type=pop(@allparts);
1.439     albertel 3761:     my $part=join('_',@allparts);
1.54      albertel 3762:     return ($part,$type);
                   3763: }
                   3764: 
1.44      ng       3765: #------------- end of section for handling grading by section/class ---------
                   3766: #
                   3767: #----------------------------------------------------------------------------
                   3768: 
1.5       albertel 3769: 
1.44      ng       3770: #----------------------------------------------------------------------------
                   3771: #
                   3772: #-------------------------- Next few routines handles grading by csv upload
                   3773: #
                   3774: #--- Javascript to handle csv upload
1.27      albertel 3775: sub csvupload_javascript_reverse_associate {
1.573     bisitz   3776:     my $error1=&mt('You need to specify the username or the student/employee ID');
1.246     albertel 3777:     my $error2=&mt('You need to specify at least one grading field');
1.27      albertel 3778:   return(<<ENDPICK);
                   3779:   function verify(vf) {
                   3780:     var foundsomething=0;
                   3781:     var founduname=0;
1.243     albertel 3782:     var foundID=0;
1.27      albertel 3783:     for (i=0;i<=vf.nfields.value;i++) {
                   3784:       tw=eval('vf.f'+i+'.selectedIndex');
1.243     albertel 3785:       if (i==0 && tw!=0) { foundID=1; }
                   3786:       if (i==1 && tw!=0) { founduname=1; }
                   3787:       if (i!=0 && i!=1 && i!=2 && tw!=0) { foundsomething=1; }
1.27      albertel 3788:     }
1.246     albertel 3789:     if (founduname==0 && foundID==0) {
                   3790: 	alert('$error1');
                   3791: 	return;
1.27      albertel 3792:     }
                   3793:     if (foundsomething==0) {
1.246     albertel 3794: 	alert('$error2');
                   3795: 	return;
1.27      albertel 3796:     }
                   3797:     vf.submit();
                   3798:   }
                   3799:   function flip(vf,tf) {
                   3800:     var nw=eval('vf.f'+tf+'.selectedIndex');
                   3801:     var i;
                   3802:     for (i=0;i<=vf.nfields.value;i++) {
                   3803:       //can not pick the same destination field for both name and domain
                   3804:       if (((i ==0)||(i ==1)) && 
                   3805:           ((tf==0)||(tf==1)) && 
                   3806:           (i!=tf) &&
                   3807:           (eval('vf.f'+i+'.selectedIndex')==nw)) {
                   3808:         eval('vf.f'+i+'.selectedIndex=0;')
                   3809:       }
                   3810:     }
                   3811:   }
                   3812: ENDPICK
                   3813: }
                   3814: 
                   3815: sub csvupload_javascript_forward_associate {
1.573     bisitz   3816:     my $error1=&mt('You need to specify the username or the student/employee ID');
1.246     albertel 3817:     my $error2=&mt('You need to specify at least one grading field');
1.27      albertel 3818:   return(<<ENDPICK);
                   3819:   function verify(vf) {
                   3820:     var foundsomething=0;
                   3821:     var founduname=0;
1.243     albertel 3822:     var foundID=0;
1.27      albertel 3823:     for (i=0;i<=vf.nfields.value;i++) {
                   3824:       tw=eval('vf.f'+i+'.selectedIndex');
1.243     albertel 3825:       if (tw==1) { foundID=1; }
                   3826:       if (tw==2) { founduname=1; }
                   3827:       if (tw>3) { foundsomething=1; }
1.27      albertel 3828:     }
1.246     albertel 3829:     if (founduname==0 && foundID==0) {
                   3830: 	alert('$error1');
                   3831: 	return;
1.27      albertel 3832:     }
                   3833:     if (foundsomething==0) {
1.246     albertel 3834: 	alert('$error2');
                   3835: 	return;
1.27      albertel 3836:     }
                   3837:     vf.submit();
                   3838:   }
                   3839:   function flip(vf,tf) {
                   3840:     var nw=eval('vf.f'+tf+'.selectedIndex');
                   3841:     var i;
                   3842:     //can not pick the same destination field twice
                   3843:     for (i=0;i<=vf.nfields.value;i++) {
                   3844:       if ((i!=tf) && (eval('vf.f'+i+'.selectedIndex')==nw)) {
                   3845:         eval('vf.f'+i+'.selectedIndex=0;')
                   3846:       }
                   3847:     }
                   3848:   }
                   3849: ENDPICK
                   3850: }
                   3851: 
1.26      albertel 3852: sub csvuploadmap_header {
1.324     albertel 3853:     my ($request,$symb,$datatoken,$distotal)= @_;
1.41      ng       3854:     my $javascript;
1.257     albertel 3855:     if ($env{'form.upfile_associate'} eq 'reverse') {
1.41      ng       3856: 	$javascript=&csvupload_javascript_reverse_associate();
                   3857:     } else {
                   3858: 	$javascript=&csvupload_javascript_forward_associate();
                   3859:     }
1.45      ng       3860: 
1.598     www      3861:     my $result='';
1.257     albertel 3862:     my $checked=(($env{'form.noFirstLine'})?' checked="checked"':'');
1.245     albertel 3863:     my $ignore=&mt('Ignore First Line');
1.418     albertel 3864:     $symb = &Apache::lonenc::check_encrypt($symb);
1.41      ng       3865:     $request->print(<<ENDPICK);
1.26      albertel 3866: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
1.398     albertel 3867: <h3><span class="LC_info">Uploading Class Grades</span></h3>
1.45      ng       3868: $result
1.326     albertel 3869: <hr />
1.26      albertel 3870: <h3>Identify fields</h3>
                   3871: Total number of records found in file: $distotal <hr />
                   3872: Enter as many fields as you can. The system will inform you and bring you back
                   3873: to this page if the data selected is insufficient to run your class.<hr />
1.589     bisitz   3874: <input type="button" value="Reverse Association" onclick="javascript:this.form.associate.value='Reverse Association';submit(this.form);" />
1.245     albertel 3875: <label><input type="checkbox" name="noFirstLine" $checked />$ignore</label>
1.26      albertel 3876: <input type="hidden" name="associate"  value="" />
                   3877: <input type="hidden" name="phase"      value="three" />
                   3878: <input type="hidden" name="datatoken"  value="$datatoken" />
1.257     albertel 3879: <input type="hidden" name="fileupload" value="$env{'form.fileupload'}" />
                   3880: <input type="hidden" name="upfiletype" value="$env{'form.upfiletype'}" />
1.26      albertel 3881: <input type="hidden" name="upfile_associate" 
1.257     albertel 3882:                                        value="$env{'form.upfile_associate'}" />
1.26      albertel 3883: <input type="hidden" name="symb"       value="$symb" />
1.257     albertel 3884: <input type="hidden" name="saveState"  value="$env{'form.saveState'}" />
1.246     albertel 3885: <input type="hidden" name="command"    value="csvuploadoptions" />
1.26      albertel 3886: <hr />
                   3887: ENDPICK
1.597     wenzelju 3888:     $request->print(&Apache::lonhtmlcommon::scripttag($javascript));
1.118     ng       3889:     return '';
1.26      albertel 3890: 
                   3891: }
                   3892: 
                   3893: sub csvupload_fields {
1.582     raeburn  3894:     my ($symb,$errorref) = @_;
                   3895:     my (@parts) = &getpartlist($symb,$errorref);
                   3896:     if (ref($errorref)) {
                   3897:         if ($$errorref) {
                   3898:             return;
                   3899:         }
                   3900:     }
                   3901: 
1.556     weissno  3902:     my @fields=(['ID','Student/Employee ID'],
1.243     albertel 3903: 		['username','Student Username'],
                   3904: 		['domain','Student Domain']);
1.324     albertel 3905:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
1.41      ng       3906:     foreach my $part (sort(@parts)) {
                   3907: 	my @datum;
                   3908: 	my $display=&Apache::lonnet::metadata($url,$part.'.display');
                   3909: 	my $name=$part;
                   3910: 	if  (!$display) { $display = $name; }
                   3911: 	@datum=($name,$display);
1.244     albertel 3912: 	if ($name=~/^stores_(.*)_awarded/) {
                   3913: 	    push(@fields,['stores_'.$1.'_points',"Points [Part: $1]"]);
                   3914: 	}
1.41      ng       3915: 	push(@fields,\@datum);
                   3916:     }
                   3917:     return (@fields);
1.26      albertel 3918: }
                   3919: 
                   3920: sub csvuploadmap_footer {
1.41      ng       3921:     my ($request,$i,$keyfields) =@_;
                   3922:     $request->print(<<ENDPICK);
1.26      albertel 3923: </table>
                   3924: <input type="hidden" name="nfields" value="$i" />
                   3925: <input type="hidden" name="keyfields" value="$keyfields" />
1.589     bisitz   3926: <input type="button" onclick="javascript:verify(this.form)" value="Assign Grades" /><br />
1.26      albertel 3927: </form>
                   3928: ENDPICK
                   3929: }
                   3930: 
1.283     albertel 3931: sub checkforfile_js {
1.539     riegler  3932:     my $alertmsg = &mt('Please use the browse button to select a file from your local directory.');
1.597     wenzelju 3933:     my $result = &Apache::lonhtmlcommon::scripttag(<<CSVFORMJS);
1.86      ng       3934:     function checkUpload(formname) {
                   3935: 	if (formname.upfile.value == "") {
1.539     riegler  3936: 	    alert("$alertmsg");
1.86      ng       3937: 	    return false;
                   3938: 	}
                   3939: 	formname.submit();
                   3940:     }
                   3941: CSVFORMJS
1.283     albertel 3942:     return $result;
                   3943: }
                   3944: 
                   3945: sub upcsvScores_form {
                   3946:     my ($request) = shift;
1.324     albertel 3947:     my ($symb)=&get_symb($request);
1.283     albertel 3948:     if (!$symb) {return '';}
                   3949:     my $result=&checkforfile_js();
1.326     albertel 3950:     $result.='<br /><table width="100%" border="0"><tr><td bgcolor="#777777">'."\n";
                   3951:     $result.='<table width="100%" border="0"><tr bgcolor="#e6ffff"><td>'."\n";
1.538     schulted 3952:     $result.='&nbsp;<b>'.&mt('Specify a file containing the class scores for current resource.').
                   3953: 	'</b></td></tr>'."\n";
1.86      ng       3954:     $result.='<tr bgcolor=#ffffe6><td>'."\n";
1.370     www      3955:     my $upload=&mt("Upload Scores");
1.86      ng       3956:     my $upfile_select=&Apache::loncommon::upfile_select_html();
1.245     albertel 3957:     my $ignore=&mt('Ignore First Line');
1.418     albertel 3958:     $symb = &Apache::lonenc::check_encrypt($symb);
1.86      ng       3959:     $result.=<<ENDUPFORM;
1.106     albertel 3960: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
1.86      ng       3961: <input type="hidden" name="symb" value="$symb" />
                   3962: <input type="hidden" name="command" value="csvuploadmap" />
1.257     albertel 3963: <input type="hidden" name="saveState"  value="$env{'form.saveState'}" />
1.86      ng       3964: $upfile_select
1.589     bisitz   3965: <br /><input type="button" onclick="javascript:checkUpload(this.form);" value="$upload" />
1.283     albertel 3966: <label><input type="checkbox" name="noFirstLine" />$ignore</label>
1.86      ng       3967: </form>
                   3968: ENDUPFORM
1.370     www      3969:     $result.=&Apache::loncommon::help_open_topic("Course_Convert_To_CSV",
                   3970:                            &mt("How do I create a CSV file from a spreadsheet"))
                   3971:     .'</td></tr></table>'."\n";
1.86      ng       3972:     $result.='</td></tr></table><br /><br />'."\n";
1.324     albertel 3973:     $result.=&show_grading_menu_form($symb);
1.86      ng       3974:     return $result;
                   3975: }
                   3976: 
                   3977: 
1.26      albertel 3978: sub csvuploadmap {
1.41      ng       3979:     my ($request)= @_;
1.324     albertel 3980:     my ($symb)=&get_symb($request);
1.41      ng       3981:     if (!$symb) {return '';}
1.72      ng       3982: 
1.41      ng       3983:     my $datatoken;
1.257     albertel 3984:     if (!$env{'form.datatoken'}) {
1.41      ng       3985: 	$datatoken=&Apache::loncommon::upfile_store($request);
1.26      albertel 3986:     } else {
1.257     albertel 3987: 	$datatoken=$env{'form.datatoken'};
1.41      ng       3988: 	&Apache::loncommon::load_tmp_file($request);
1.26      albertel 3989:     }
1.41      ng       3990:     my @records=&Apache::loncommon::upfile_record_sep();
1.257     albertel 3991:     if ($env{'form.noFirstLine'}) { shift(@records); }
1.324     albertel 3992:     &csvuploadmap_header($request,$symb,$datatoken,$#records+1);
1.41      ng       3993:     my ($i,$keyfields);
                   3994:     if (@records) {
1.582     raeburn  3995:         my $fieldserror;
                   3996: 	my @fields=&csvupload_fields($symb,\$fieldserror);
                   3997:         if ($fieldserror) {
                   3998:             $request->print(&navmap_errormsg());
                   3999:             return;
                   4000:         }
1.257     albertel 4001: 	if ($env{'form.upfile_associate'} eq 'reverse') {	
1.41      ng       4002: 	    &Apache::loncommon::csv_print_samples($request,\@records);
                   4003: 	    $i=&Apache::loncommon::csv_print_select_table($request,\@records,
                   4004: 							  \@fields);
                   4005: 	    foreach (@fields) { $keyfields.=$_->[0].','; }
                   4006: 	    chop($keyfields);
                   4007: 	} else {
                   4008: 	    unshift(@fields,['none','']);
                   4009: 	    $i=&Apache::loncommon::csv_samples_select_table($request,\@records,
                   4010: 							    \@fields);
1.311     banghart 4011:             foreach my $rec (@records) {
                   4012:                 my %temp = &Apache::loncommon::record_sep($rec);
                   4013:                 if (%temp) {
                   4014:                     $keyfields=join(',',sort(keys(%temp)));
                   4015:                     last;
                   4016:                 }
                   4017:             }
1.41      ng       4018: 	}
                   4019:     }
                   4020:     &csvuploadmap_footer($request,$i,$keyfields);
1.324     albertel 4021:     $request->print(&show_grading_menu_form($symb));
1.72      ng       4022: 
1.41      ng       4023:     return '';
1.27      albertel 4024: }
                   4025: 
1.246     albertel 4026: sub csvuploadoptions {
1.41      ng       4027:     my ($request)= @_;
1.324     albertel 4028:     my ($symb)=&get_symb($request);
1.257     albertel 4029:     my $checked=(($env{'form.noFirstLine'})?'1':'0');
1.246     albertel 4030:     my $ignore=&mt('Ignore First Line');
                   4031:     $request->print(<<ENDPICK);
                   4032: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
1.398     albertel 4033: <h3><span class="LC_info">Uploading Class Grade Options</span></h3>
1.246     albertel 4034: <input type="hidden" name="command"    value="csvuploadassign" />
1.302     albertel 4035: <!--
1.246     albertel 4036: <p>
                   4037: <label>
                   4038:    <input type="checkbox" name="show_full_results" />
                   4039:    Show a table of all changes
                   4040: </label>
                   4041: </p>
1.302     albertel 4042: -->
1.246     albertel 4043: <p>
                   4044: <label>
                   4045:    <input type="checkbox" name="overwite_scores" checked="checked" />
                   4046:    Overwrite any existing score
                   4047: </label>
                   4048: </p>
                   4049: ENDPICK
                   4050:     my %fields=&get_fields();
                   4051:     if (!defined($fields{'domain'})) {
1.257     albertel 4052: 	my $domform = &Apache::loncommon::select_dom_form($env{'request.role.domain'},'default_domain');
1.246     albertel 4053: 	$request->print("\n<p> Users are in domain: ".$domform."</p>\n");
                   4054:     }
1.257     albertel 4055:     foreach my $key (sort(keys(%env))) {
1.246     albertel 4056: 	if ($key !~ /^form\.(.*)$/) { next; }
                   4057: 	my $cleankey=$1;
                   4058: 	if ($cleankey eq 'command') { next; }
                   4059: 	$request->print('<input type="hidden" name="'.$cleankey.
1.257     albertel 4060: 			'"  value="'.$env{$key}.'" />'."\n");
1.246     albertel 4061:     }
                   4062:     # FIXME do a check for any duplicated user ids...
                   4063:     # FIXME do a check for any invalid user ids?...
1.290     albertel 4064:     $request->print('<input type="submit" value="Assign Grades" /><br />
                   4065: <hr /></form>'."\n");
1.324     albertel 4066:     $request->print(&show_grading_menu_form($symb));
1.246     albertel 4067:     return '';
                   4068: }
                   4069: 
                   4070: sub get_fields {
                   4071:     my %fields;
1.257     albertel 4072:     my @keyfields = split(/\,/,$env{'form.keyfields'});
                   4073:     for (my $i=0; $i<=$env{'form.nfields'}; $i++) {
                   4074: 	if ($env{'form.upfile_associate'} eq 'reverse') {
                   4075: 	    if ($env{'form.f'.$i} ne 'none') {
                   4076: 		$fields{$keyfields[$i]}=$env{'form.f'.$i};
1.41      ng       4077: 	    }
                   4078: 	} else {
1.257     albertel 4079: 	    if ($env{'form.f'.$i} ne 'none') {
                   4080: 		$fields{$env{'form.f'.$i}}=$keyfields[$i];
1.41      ng       4081: 	    }
                   4082: 	}
1.27      albertel 4083:     }
1.246     albertel 4084:     return %fields;
                   4085: }
                   4086: 
                   4087: sub csvuploadassign {
                   4088:     my ($request)= @_;
1.324     albertel 4089:     my ($symb)=&get_symb($request);
1.246     albertel 4090:     if (!$symb) {return '';}
1.345     bowersj2 4091:     my $error_msg = '';
1.246     albertel 4092:     &Apache::loncommon::load_tmp_file($request);
                   4093:     my @gradedata = &Apache::loncommon::upfile_record_sep();
1.257     albertel 4094:     if ($env{'form.noFirstLine'}) { shift(@gradedata); }
1.246     albertel 4095:     my %fields=&get_fields();
1.41      ng       4096:     $request->print('<h3>Assigning Grades</h3>');
1.257     albertel 4097:     my $courseid=$env{'request.course.id'};
1.97      albertel 4098:     my ($classlist) = &getclasslist('all',0);
1.106     albertel 4099:     my @notallowed;
1.41      ng       4100:     my @skipped;
                   4101:     my $countdone=0;
                   4102:     foreach my $grade (@gradedata) {
                   4103: 	my %entries=&Apache::loncommon::record_sep($grade);
1.246     albertel 4104: 	my $domain;
                   4105: 	if ($entries{$fields{'domain'}}) {
                   4106: 	    $domain=$entries{$fields{'domain'}};
                   4107: 	} else {
1.257     albertel 4108: 	    $domain=$env{'form.default_domain'};
1.246     albertel 4109: 	}
1.243     albertel 4110: 	$domain=~s/\s//g;
1.41      ng       4111: 	my $username=$entries{$fields{'username'}};
1.160     albertel 4112: 	$username=~s/\s//g;
1.243     albertel 4113: 	if (!$username) {
                   4114: 	    my $id=$entries{$fields{'ID'}};
1.247     albertel 4115: 	    $id=~s/\s//g;
1.243     albertel 4116: 	    my %ids=&Apache::lonnet::idget($domain,$id);
                   4117: 	    $username=$ids{$id};
                   4118: 	}
1.41      ng       4119: 	if (!exists($$classlist{"$username:$domain"})) {
1.247     albertel 4120: 	    my $id=$entries{$fields{'ID'}};
                   4121: 	    $id=~s/\s//g;
                   4122: 	    if ($id) {
                   4123: 		push(@skipped,"$id:$domain");
                   4124: 	    } else {
                   4125: 		push(@skipped,"$username:$domain");
                   4126: 	    }
1.41      ng       4127: 	    next;
                   4128: 	}
1.108     albertel 4129: 	my $usec=$classlist->{"$username:$domain"}[5];
1.106     albertel 4130: 	if (!&canmodify($usec)) {
                   4131: 	    push(@notallowed,"$username:$domain");
                   4132: 	    next;
                   4133: 	}
1.244     albertel 4134: 	my %points;
1.41      ng       4135: 	my %grades;
                   4136: 	foreach my $dest (keys(%fields)) {
1.244     albertel 4137: 	    if ($dest eq 'ID' || $dest eq 'username' ||
                   4138: 		$dest eq 'domain') { next; }
                   4139: 	    if ($entries{$fields{$dest}} =~ /^\s*$/) { next; }
                   4140: 	    if ($dest=~/stores_(.*)_points/) {
                   4141: 		my $part=$1;
                   4142: 		my $wgt =&Apache::lonnet::EXT('resource.'.$part.'.weight',
                   4143: 					      $symb,$domain,$username);
1.345     bowersj2 4144:                 if ($wgt) {
                   4145:                     $entries{$fields{$dest}}=~s/\s//g;
                   4146:                     my $pcr=$entries{$fields{$dest}} / $wgt;
1.463     albertel 4147:                     my $award=($pcr == 0) ? 'incorrect_by_override'
                   4148:                                           : 'correct_by_override';
1.345     bowersj2 4149:                     $grades{"resource.$part.awarded"}=$pcr;
                   4150:                     $grades{"resource.$part.solved"}=$award;
                   4151:                     $points{$part}=1;
                   4152:                 } else {
                   4153:                     $error_msg = "<br />" .
                   4154:                         &mt("Some point values were assigned"
                   4155:                             ." for problems with a weight "
                   4156:                             ."of zero. These values were "
                   4157:                             ."ignored.");
                   4158:                 }
1.244     albertel 4159: 	    } else {
                   4160: 		if ($dest=~/stores_(.*)_awarded/) { if ($points{$1}) {next;} }
                   4161: 		if ($dest=~/stores_(.*)_solved/)  { if ($points{$1}) {next;} }
                   4162: 		my $store_key=$dest;
                   4163: 		$store_key=~s/^stores/resource/;
                   4164: 		$store_key=~s/_/\./g;
                   4165: 		$grades{$store_key}=$entries{$fields{$dest}};
                   4166: 	    }
1.41      ng       4167: 	}
1.508     www      4168: 	if (! %grades) { 
                   4169:            push(@skipped,&mt("[_1]: no data to save","$username:$domain")); 
                   4170:         } else {
                   4171: 	   $grades{"resource.regrader"}="$env{'user.name'}:$env{'user.domain'}";
                   4172: 	   my $result=&Apache::lonnet::cstore(\%grades,$symb,
1.302     albertel 4173: 					   $env{'request.course.id'},
                   4174: 					   $domain,$username);
1.508     www      4175: 	   if ($result eq 'ok') {
                   4176: 	      $request->print('.');
                   4177: 	   } else {
                   4178: 	      $request->print("<p><span class=\"LC_error\">".
                   4179:                               &mt("Failed to save data for student [_1]. Message when trying to save was: [_2]",
                   4180:                                   "$username:$domain",$result)."</span></p>");
                   4181: 	   }
                   4182: 	   $request->rflush();
                   4183: 	   $countdone++;
                   4184:         }
1.41      ng       4185:     }
1.570     www      4186:     $request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt("Saved scores for [quant,_1,student]",$countdone),$countdone==0));
1.41      ng       4187:     if (@skipped) {
1.571     www      4188: 	$request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt('No scores stored for the following username(s):'),1).'<br />');
                   4189:         $request->print(join(', ',@skipped));
1.106     albertel 4190:     }
                   4191:     if (@notallowed) {
1.571     www      4192: 	$request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt('Modification of scores not allowed for the following username(s):'),1).'<br />');
                   4193: 	$request->print(join(', ',@notallowed));
1.41      ng       4194:     }
1.106     albertel 4195:     $request->print("<br />\n");
1.324     albertel 4196:     $request->print(&show_grading_menu_form($symb));
1.345     bowersj2 4197:     return $error_msg;
1.26      albertel 4198: }
1.44      ng       4199: #------------- end of section for handling csv file upload ---------
                   4200: #
                   4201: #-------------------------------------------------------------------
                   4202: #
1.122     ng       4203: #-------------- Next few routines handle grading by page/sequence
1.72      ng       4204: #
                   4205: #--- Select a page/sequence and a student to grade
1.68      ng       4206: sub pickStudentPage {
                   4207:     my ($request) = shift;
                   4208: 
1.539     riegler  4209:     my $alertmsg = &mt('Please select the student you wish to grade.');
1.597     wenzelju 4210:     $request->print(&Apache::lonhtmlcommon::scripttag(<<LISTJAVASCRIPT));
1.68      ng       4211: 
                   4212: function checkPickOne(formname) {
1.76      ng       4213:     if (radioSelection(formname.student) == null) {
1.539     riegler  4214: 	alert("$alertmsg");
1.68      ng       4215: 	return;
                   4216:     }
1.125     ng       4217:     ptr = pullDownSelection(formname.selectpage);
                   4218:     formname.page.value = formname["page"+ptr].value;
                   4219:     formname.title.value = formname["title"+ptr].value;
1.68      ng       4220:     formname.submit();
                   4221: }
                   4222: 
                   4223: LISTJAVASCRIPT
1.118     ng       4224:     &commonJSfunctions($request);
1.324     albertel 4225:     my ($symb) = &get_symb($request);
1.257     albertel 4226:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
                   4227:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
                   4228:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
1.68      ng       4229: 
1.398     albertel 4230:     my $result='<h3><span class="LC_info">&nbsp;'.
1.485     albertel 4231: 	&mt('Manual Grading by Page or Sequence').'</span></h3>';
1.68      ng       4232: 
1.80      ng       4233:     $result.='<form action="/adm/grades" method="post" name="displayPage">'."\n";
1.582     raeburn  4234:     my $map_error;
                   4235:     my ($titles,$symbx) = &getSymbMap($map_error);
                   4236:     if ($map_error) {
                   4237:         $request->print(&navmap_errormsg());
                   4238:         return; 
                   4239:     }
1.137     albertel 4240:     my ($curpage) =&Apache::lonnet::decode_symb($symb); 
                   4241: #    my ($curpage,$mapId) =&Apache::lonnet::decode_symb($symb); 
                   4242: #    my $type=($curpage =~ /\.(page|sequence)/);
1.485     albertel 4243:     my $select = '<select name="selectpage">'."\n";
1.70      ng       4244:     my $ctr=0;
1.68      ng       4245:     foreach (@$titles) {
                   4246: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
1.485     albertel 4247: 	$select.='<option value="'.$ctr.'" '.
1.401     albertel 4248: 	    ($$symbx{$_} =~ /$curpage$/ ? 'selected="selected"' : '').
1.71      ng       4249: 	    '>'.$showtitle.'</option>'."\n";
1.70      ng       4250: 	$ctr++;
1.68      ng       4251:     }
1.485     albertel 4252:     $select.= '</select>';
1.539     riegler  4253:     $result.='&nbsp;<b>'.&mt('Problems from').':</b> '.$select."<br />\n";
1.485     albertel 4254: 
1.70      ng       4255:     $ctr=0;
                   4256:     foreach (@$titles) {
                   4257: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
                   4258: 	$result.='<input type="hidden" name="page'.$ctr.'" value="'.$$symbx{$_}.'" />'."\n";
                   4259: 	$result.='<input type="hidden" name="title'.$ctr.'" value="'.$showtitle.'" />'."\n";
                   4260: 	$ctr++;
                   4261:     }
1.72      ng       4262:     $result.='<input type="hidden" name="page" />'."\n".
                   4263: 	'<input type="hidden" name="title" />'."\n";
1.68      ng       4264: 
1.485     albertel 4265:     my $options =
                   4266: 	'<label><input type="radio" name="vProb" value="no" checked="checked" /> '.&mt('no').' </label>'."\n".
                   4267: 	'<label><input type="radio" name="vProb" value="yes" /> '.&mt('yes').' </label>'."<br />\n";
1.539     riegler  4268:     $result.='&nbsp;<b>'.&mt('View Problem Text').': </b>'.$options;
1.485     albertel 4269: 
                   4270:     $options =
                   4271: 	'<label><input type="radio" name="lastSub" value="none" /> '.&mt('none').' </label>'."\n".
                   4272: 	'<label><input type="radio" name="lastSub" value="datesub" checked="checked" /> '.&mt('by dates and submissions').'</label>'."\n".
                   4273: 	'<label><input type="radio" name="lastSub" value="all" /> '.&mt('all details').' </label>'."\n";
1.539     riegler  4274:     $result.='&nbsp;<b>'.&mt('Submissions').': </b>'.$options;
1.432     banghart 4275:     
                   4276:     $result.=&build_section_inputs();
1.442     banghart 4277:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
                   4278:     $result.='<input type="hidden" name="Status"  value="'.$stu_status.'" />'."\n".
1.72      ng       4279: 	'<input type="hidden" name="command" value="displayPage" />'."\n".
1.418     albertel 4280: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.257     albertel 4281: 	'<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."<br />\n";
1.72      ng       4282: 
1.539     riegler  4283:     $result.='&nbsp;<b>'.&mt('Use CODE').': </b> <input type="text" name="CODE" value="" /> <br />'."\n";
1.382     albertel 4284: 
1.80      ng       4285:     $result.='&nbsp;<input type="button" '.
1.589     bisitz   4286:              'onclick="javascript:checkPickOne(this.form);" value="'.&mt('Next').' &rarr;" /><br />'."\n";
1.72      ng       4287: 
1.68      ng       4288:     $request->print($result);
                   4289: 
1.485     albertel 4290:     my $studentTable.='&nbsp;<b>'.&mt('Select a student you wish to grade and then click on the Next button.').'</b><br />'.
1.484     albertel 4291: 	&Apache::loncommon::start_data_table().
                   4292: 	&Apache::loncommon::start_data_table_header_row().
1.485     albertel 4293: 	'<th align="right">&nbsp;'.&mt('No.').'</th>'.
1.484     albertel 4294: 	'<th>'.&nameUserString('header').'</th>'.
1.485     albertel 4295: 	'<th align="right">&nbsp;'.&mt('No.').'</th>'.
1.484     albertel 4296: 	'<th>'.&nameUserString('header').'</th>'.
                   4297: 	&Apache::loncommon::end_data_table_header_row();
1.68      ng       4298:  
1.76      ng       4299:     my (undef,undef,$fullname) = &getclasslist($getsec,'1');
1.68      ng       4300:     my $ptr = 1;
1.294     albertel 4301:     foreach my $student (sort 
                   4302: 			 {
                   4303: 			     if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                   4304: 				 return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                   4305: 			     }
                   4306: 			     return $a cmp $b;
                   4307: 			 } (keys(%$fullname))) {
1.68      ng       4308: 	my ($uname,$udom) = split(/:/,$student);
1.484     albertel 4309: 	$studentTable.=($ptr%2==1 ? &Apache::loncommon::start_data_table_row()
                   4310:                                   : '</td>');
1.126     ng       4311: 	$studentTable.='<td align="right">'.$ptr.'&nbsp;</td>';
1.288     albertel 4312: 	$studentTable.='<td>&nbsp;<label><input type="radio" name="student" value="'.$student.'" /> '
                   4313: 	    .&nameUserString(undef,$$fullname{$student},$uname,$udom)."</label>\n";
1.484     albertel 4314: 	$studentTable.=
                   4315: 	    ($ptr%2 == 0 ? '</td>'.&Apache::loncommon::end_data_table_row() 
                   4316:                          : '');
1.68      ng       4317: 	$ptr++;
                   4318:     }
1.484     albertel 4319:     if ($ptr%2 == 0) {
                   4320: 	$studentTable.='</td><td>&nbsp;</td><td>&nbsp;</td>'.
                   4321: 	    &Apache::loncommon::end_data_table_row();
                   4322:     }
                   4323:     $studentTable.=&Apache::loncommon::end_data_table()."\n";
1.126     ng       4324:     $studentTable.='<input type="button" '.
1.589     bisitz   4325:                    'onclick="javascript:checkPickOne(this.form);" value="'.&mt('Next').' &rarr;" /></form>'."\n";
1.68      ng       4326: 
1.324     albertel 4327:     $studentTable.=&show_grading_menu_form($symb);
1.68      ng       4328:     $request->print($studentTable);
                   4329: 
                   4330:     return '';
                   4331: }
                   4332: 
                   4333: sub getSymbMap {
1.582     raeburn  4334:     my ($map_error) = @_;
1.132     bowersj2 4335:     my $navmap = Apache::lonnavmaps::navmap->new();
1.582     raeburn  4336:     unless (ref($navmap)) {
                   4337:         if (ref($map_error)) {
                   4338:             $$map_error = 'navmap';
                   4339:         }
                   4340:         return;
                   4341:     }
1.68      ng       4342:     my %symbx = ();
                   4343:     my @titles = ();
1.117     bowersj2 4344:     my $minder = 0;
                   4345: 
                   4346:     # Gather every sequence that has problems.
1.240     albertel 4347:     my @sequences = $navmap->retrieveResources(undef, sub { shift->is_map(); },
                   4348: 					       1,0,1);
1.117     bowersj2 4349:     for my $sequence ($navmap->getById('0.0'), @sequences) {
1.241     albertel 4350: 	if ($navmap->hasResource($sequence, sub { shift->is_problem(); }, 0) ) {
1.381     albertel 4351: 	    my $title = $minder.'.'.
                   4352: 		&HTML::Entities::encode($sequence->compTitle(),'"\'&');
                   4353: 	    push(@titles, $title); # minder in case two titles are identical
                   4354: 	    $symbx{$title} = &HTML::Entities::encode($sequence->symb(),'"\'&');
1.117     bowersj2 4355: 	    $minder++;
1.241     albertel 4356: 	}
1.68      ng       4357:     }
                   4358:     return \@titles,\%symbx;
                   4359: }
                   4360: 
1.72      ng       4361: #
                   4362: #--- Displays a page/sequence w/wo problems, w/wo submissions
1.68      ng       4363: sub displayPage {
                   4364:     my ($request) = shift;
                   4365: 
1.324     albertel 4366:     my ($symb) = &get_symb($request);
1.257     albertel 4367:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
                   4368:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
                   4369:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
                   4370:     my $pageTitle = $env{'form.page'};
1.103     albertel 4371:     my ($classlist,undef,$fullname) = &getclasslist($getsec,'1');
1.257     albertel 4372:     my ($uname,$udom) = split(/:/,$env{'form.student'});
                   4373:     my $usec=$classlist->{$env{'form.student'}}[5];
1.168     albertel 4374: 
                   4375:     #need to make sure we have the correct data for later EXT calls, 
                   4376:     #thus invalidate the cache
                   4377:     &Apache::lonnet::devalidatecourseresdata(
1.257     albertel 4378:                  $env{'course.'.$env{'request.course.id'}.'.num'},
                   4379:                  $env{'course.'.$env{'request.course.id'}.'.domain'});
1.168     albertel 4380:     &Apache::lonnet::clear_EXT_cache_status();
                   4381: 
1.103     albertel 4382:     if (!&canview($usec)) {
1.485     albertel 4383: 	$request->print('<span class="LC_warning">'.&mt('Unable to view requested student. ([_1])',$env{'form.student'}).'</span>');
1.324     albertel 4384: 	$request->print(&show_grading_menu_form($symb));
1.103     albertel 4385: 	return;
                   4386:     }
1.398     albertel 4387:     my $result='<h3><span class="LC_info">&nbsp;'.$env{'form.title'}.'</span></h3>';
1.485     albertel 4388:     $result.='<h3>&nbsp;'.&mt('Student: [_1]',&nameUserString(undef,$$fullname{$env{'form.student'}},$uname,$udom)).
1.129     ng       4389: 	'</h3>'."\n";
1.500     albertel 4390:     $env{'form.CODE'} = uc($env{'form.CODE'});
1.501     foxr     4391:     if (&Apache::lonnet::validCODE(uc($env{'form.CODE'}))) {
1.485     albertel 4392: 	$result.='<h3>&nbsp;'.&mt('CODE: [_1]',$env{'form.CODE'}).'</h3>'."\n";
1.382     albertel 4393:     } else {
                   4394: 	delete($env{'form.CODE'});
                   4395:     }
1.71      ng       4396:     &sub_page_js($request);
                   4397:     $request->print($result);
                   4398: 
1.132     bowersj2 4399:     my $navmap = Apache::lonnavmaps::navmap->new();
1.582     raeburn  4400:     unless (ref($navmap)) {
                   4401:         $request->print(&navmap_errormsg());
                   4402:         $request->print(&show_grading_menu_form($symb));
                   4403:         return;
                   4404:     }
1.257     albertel 4405:     my ($mapUrl, $id, $resUrl)=&Apache::lonnet::decode_symb($env{'form.page'});
1.68      ng       4406:     my $map = $navmap->getResourceByUrl($resUrl); # add to navmaps
1.288     albertel 4407:     if (!$map) {
1.485     albertel 4408: 	$request->print('<span class="LC_warning">'.&mt('Unable to view requested sequence. ([_1])',$resUrl).'</span>');
1.324     albertel 4409: 	$request->print(&show_grading_menu_form($symb));
1.288     albertel 4410: 	return; 
                   4411:     }
1.68      ng       4412:     my $iterator = $navmap->getIterator($map->map_start(),
                   4413: 					$map->map_finish());
                   4414: 
1.71      ng       4415:     my $studentTable='<form action="/adm/grades" method="post" name="gradePage">'."\n".
1.72      ng       4416: 	'<input type="hidden" name="command" value="gradeByPage" />'."\n".
1.257     albertel 4417: 	'<input type="hidden" name="fullname" value="'.$$fullname{$env{'form.student'}}.'" />'."\n".
                   4418: 	'<input type="hidden" name="student" value="'.$env{'form.student'}.'" />'."\n".
1.72      ng       4419: 	'<input type="hidden" name="page"    value="'.$pageTitle.'" />'."\n".
1.257     albertel 4420: 	'<input type="hidden" name="title"   value="'.$env{'form.title'}.'" />'."\n".
1.418     albertel 4421: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.125     ng       4422: 	'<input type="hidden" name="overRideScore" value="no" />'."\n".
1.257     albertel 4423: 	'<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n";
1.71      ng       4424: 
1.382     albertel 4425:     if (defined($env{'form.CODE'})) {
                   4426: 	$studentTable.=
                   4427: 	    '<input type="hidden" name="CODE" value="'.$env{'form.CODE'}.'" />'."\n";
                   4428:     }
1.381     albertel 4429:     my $checkIcon = '<img alt="'.&mt('Check Mark').
1.485     albertel 4430: 	'" src="'.&Apache::loncommon::lonhttpdurl($request->dir_config('lonIconsURL').'/check.gif').'" height="16" border="0" />';
1.71      ng       4431: 
1.594     bisitz   4432:     $studentTable.='&nbsp;<span class="LC_info">'.
                   4433:         &mt('Problems graded correct by the computer are marked with a [_1] symbol.',$checkIcon).
                   4434:         '</span>'."\n".
1.484     albertel 4435: 	&Apache::loncommon::start_data_table().
                   4436: 	&Apache::loncommon::start_data_table_header_row().
                   4437: 	'<th align="center">&nbsp;Prob.&nbsp;</th>'.
1.485     albertel 4438: 	'<th>&nbsp;'.($env{'form.vProb'} eq 'no' ? &mt('Title') : &mt('Problem Text')).'/'.&mt('Grade').'</th>'.
1.484     albertel 4439: 	&Apache::loncommon::end_data_table_header_row();
1.71      ng       4440: 
1.329     albertel 4441:     &Apache::lonxml::clear_problem_counter();
1.196     albertel 4442:     my ($depth,$question,$prob) = (1,1,1);
1.68      ng       4443:     $iterator->next(); # skip the first BEGIN_MAP
                   4444:     my $curRes = $iterator->next(); # for "current resource"
1.101     albertel 4445:     while ($depth > 0) {
1.68      ng       4446:         if($curRes == $iterator->BEGIN_MAP) { $depth++; }
1.100     bowersj2 4447:         if($curRes == $iterator->END_MAP) { $depth--; }
1.68      ng       4448: 
1.385     albertel 4449:         if (ref($curRes) && $curRes->is_problem()) {
1.91      albertel 4450: 	    my $parts = $curRes->parts();
1.68      ng       4451:             my $title = $curRes->compTitle();
1.71      ng       4452: 	    my $symbx = $curRes->symb();
1.484     albertel 4453: 	    $studentTable.=
                   4454: 		&Apache::loncommon::start_data_table_row().
                   4455: 		'<td align="center" valign="top" >'.$prob.
1.485     albertel 4456: 		(scalar(@{$parts}) == 1 ? '' 
                   4457: 		                        : '<br />('.&mt('[_1]&nbsp;parts)',
                   4458: 							scalar(@{$parts}))
                   4459: 		 ).
                   4460: 		 '</td>';
1.71      ng       4461: 	    $studentTable.='<td valign="top">';
1.382     albertel 4462: 	    my %form = ('CODE' => $env{'form.CODE'},);
1.257     albertel 4463: 	    if ($env{'form.vProb'} eq 'yes' ) {
1.144     albertel 4464: 		$studentTable.=&show_problem($request,$symbx,$uname,$udom,1,
1.383     albertel 4465: 					     undef,'both',\%form);
1.71      ng       4466: 	    } else {
1.382     albertel 4467: 		my $companswer = &Apache::loncommon::get_student_answers($symbx,$uname,$udom,$env{'request.course.id'},%form);
1.80      ng       4468: 		$companswer =~ s|<form(.*?)>||g;
                   4469: 		$companswer =~ s|</form>||g;
1.71      ng       4470: #		while ($companswer =~ /(<a href\=\"javascript:newWindow.*?Script Vars<\/a>)/s) { #<a href="javascript:newWindow</a>
1.116     ng       4471: #		    $companswer =~ s/$1/ /ms;
1.326     albertel 4472: #		    $request->print('match='.$1."<br />\n");
1.71      ng       4473: #		}
1.116     ng       4474: #		$companswer =~ s|<table border=\"1\">|<table border=\"0\">|g;
1.539     riegler  4475: 		$studentTable.='&nbsp;<b>'.$title.'</b>&nbsp;<br />&nbsp;<b>'.&mt('Correct answer').':</b><br />'.$companswer;
1.71      ng       4476: 	    }
                   4477: 
1.257     albertel 4478: 	    my %record = &Apache::lonnet::restore($symbx,$env{'request.course.id'},$udom,$uname);
1.125     ng       4479: 
1.257     albertel 4480: 	    if ($env{'form.lastSub'} eq 'datesub') {
1.71      ng       4481: 		if ($record{'version'} eq '') {
1.485     albertel 4482: 		    $studentTable.='<br />&nbsp;<span class="LC_warning">'.&mt('No recorded submission for this problem.').'</span><br />';
1.71      ng       4483: 		} else {
1.116     ng       4484: 		    my %responseType = ();
                   4485: 		    foreach my $partid (@{$parts}) {
1.147     albertel 4486: 			my @responseIds =$curRes->responseIds($partid);
                   4487: 			my @responseType =$curRes->responseType($partid);
                   4488: 			my %responseIds;
                   4489: 			for (my $i=0;$i<=$#responseIds;$i++) {
                   4490: 			    $responseIds{$responseIds[$i]}=$responseType[$i];
                   4491: 			}
                   4492: 			$responseType{$partid} = \%responseIds;
1.116     ng       4493: 		    }
1.148     albertel 4494: 		    $studentTable.= &displaySubByDates($symbx,\%record,$parts,\%responseType,$checkIcon,$uname,$udom);
1.147     albertel 4495: 
1.71      ng       4496: 		}
1.257     albertel 4497: 	    } elsif ($env{'form.lastSub'} eq 'all') {
                   4498: 		my $last = ($env{'form.lastSub'} eq 'last' ? 'last' : '');
1.71      ng       4499: 		$studentTable.=&Apache::loncommon::get_previous_attempt($symbx,$uname,$udom,
1.257     albertel 4500: 									$env{'request.course.id'},
1.71      ng       4501: 									'','.submission');
                   4502:  
                   4503: 	    }
1.103     albertel 4504: 	    if (&canmodify($usec)) {
1.585     bisitz   4505:             $studentTable.=&gradeBox_start();
1.103     albertel 4506: 		foreach my $partid (@{$parts}) {
                   4507: 		    $studentTable.=&gradeBox($request,$symbx,$uname,$udom,$question,$partid,\%record);
                   4508: 		    $studentTable.='<input type="hidden" name="q_'.$question.'" value="'.$partid.'" />'."\n";
                   4509: 		    $question++;
                   4510: 		}
1.585     bisitz   4511:             $studentTable.=&gradeBox_end();
1.196     albertel 4512: 		$prob++;
1.71      ng       4513: 	    }
                   4514: 	    $studentTable.='</td></tr>';
1.68      ng       4515: 
1.103     albertel 4516: 	}
1.68      ng       4517:         $curRes = $iterator->next();
                   4518:     }
                   4519: 
1.589     bisitz   4520:     $studentTable.=
                   4521:         '</table>'."\n".
                   4522:         '<input type="button" value="'.&mt('Save').'" '.
                   4523:         'onclick="javascript:checkSubmitPage(this.form,'.$question.');" />'.
                   4524:         '</form>'."\n";
1.324     albertel 4525:     $studentTable.=&show_grading_menu_form($symb);
1.71      ng       4526:     $request->print($studentTable);
                   4527: 
                   4528:     return '';
1.119     ng       4529: }
                   4530: 
                   4531: sub displaySubByDates {
1.148     albertel 4532:     my ($symb,$record,$parts,$responseType,$checkIcon,$uname,$udom) = @_;
1.224     albertel 4533:     my $isCODE=0;
1.335     albertel 4534:     my $isTask = ($symb =~/\.task$/);
1.224     albertel 4535:     if (exists($record->{'resource.CODE'})) { $isCODE=1; }
1.467     albertel 4536:     my $studentTable=&Apache::loncommon::start_data_table().
                   4537: 	&Apache::loncommon::start_data_table_header_row().
                   4538: 	'<th>'.&mt('Date/Time').'</th>'.
                   4539: 	($isCODE?'<th>'.&mt('CODE').'</th>':'').
                   4540: 	'<th>'.&mt('Submission').'</th>'.
                   4541: 	'<th>'.&mt('Status').'</th>'.
                   4542: 	&Apache::loncommon::end_data_table_header_row();
1.119     ng       4543:     my ($version);
                   4544:     my %mark;
1.148     albertel 4545:     my %orders;
1.119     ng       4546:     $mark{'correct_by_student'} = $checkIcon;
1.147     albertel 4547:     if (!exists($$record{'1:timestamp'})) {
1.539     riegler  4548: 	return '<br />&nbsp;<span class="LC_warning">'.&mt('Nothing submitted - no attempts.').'</span><br />';
1.147     albertel 4549:     }
1.335     albertel 4550: 
                   4551:     my $interaction;
1.525     raeburn  4552:     my $no_increment = 1;
1.119     ng       4553:     for ($version=1;$version<=$$record{'version'};$version++) {
1.467     albertel 4554: 	my $timestamp = 
                   4555: 	    &Apache::lonlocal::locallocaltime($$record{$version.':timestamp'});
1.335     albertel 4556: 	if (exists($$record{$version.':resource.0.version'})) {
                   4557: 	    $interaction = $$record{$version.':resource.0.version'};
                   4558: 	}
                   4559: 
                   4560: 	my $where = ($isTask ? "$version:resource.$interaction"
                   4561: 		             : "$version:resource");
1.467     albertel 4562: 	$studentTable.=&Apache::loncommon::start_data_table_row().
                   4563: 	    '<td>'.$timestamp.'</td>';
1.224     albertel 4564: 	if ($isCODE) {
                   4565: 	    $studentTable.='<td>'.$record->{$version.':resource.CODE'}.'</td>';
                   4566: 	}
1.119     ng       4567: 	my @versionKeys = split(/\:/,$$record{$version.':keys'});
                   4568: 	my @displaySub = ();
                   4569: 	foreach my $partid (@{$parts}) {
1.596     raeburn  4570:             my $hidden;
                   4571:             if (($$record{$version.':resource.'.$partid.'.type'} eq 'anonsurvey') ||
                   4572:                 ($$record{$version.':resource.'.$partid.'.type'} eq 'anonsurveycred')) {
                   4573:                 $hidden = 1;
                   4574:             }
1.335     albertel 4575: 	    my @matchKey = ($isTask ? sort(grep /^resource\.\d+\.\Q$partid\E\.award$/,@versionKeys)
                   4576: 			            : sort(grep /^resource\.\Q$partid\E\..*?\.submission$/,@versionKeys));
                   4577: 	    
1.122     ng       4578: #	    next if ($$record{"$version:resource.$partid.solved"} eq '');
1.324     albertel 4579: 	    my $display_part=&get_display_part($partid,$symb);
1.147     albertel 4580: 	    foreach my $matchKey (@matchKey) {
1.198     albertel 4581: 		if (exists($$record{$version.':'.$matchKey}) &&
                   4582: 		    $$record{$version.':'.$matchKey} ne '') {
1.596     raeburn  4583:                     
1.335     albertel 4584: 		    my ($responseId)= ($isTask ? ($matchKey=~ /^resource\.(.*?)\.\Q$partid\E\.award$/)
                   4585: 				               : ($matchKey=~ /^resource\.\Q$partid\E\.(.*?)\.submission$/));
1.577     bisitz   4586:                     $displaySub[0].='<span class="LC_nobreak"';
                   4587:                     $displaySub[0].='<b>'.&mt('Part: [_1]',$display_part).'</b>'
                   4588:                                    .' <span class="LC_internal_info">'
                   4589:                                    .'('.&mt('Part ID: [_1]',$responseId).')'
                   4590:                                    .'</span>'
                   4591:                                    .' <b>';
1.596     raeburn  4592:                     if ($hidden) {
                   4593:                         $displaySub[0].= &mt('Anonymous Survey').'</b>';
                   4594:                     } else {
                   4595: 		        if ($$record{"$where.$partid.tries"} eq '') {
                   4596: 			    $displaySub[0].=&mt('Trial not counted');
                   4597: 		        } else {
                   4598: 			    $displaySub[0].=&mt('Trial: [_1]',
1.467     albertel 4599: 					    $$record{"$where.$partid.tries"});
1.596     raeburn  4600: 		        }
                   4601: 		        my $responseType=($isTask ? 'Task'
1.335     albertel 4602:                                               : $responseType->{$partid}->{$responseId});
1.596     raeburn  4603: 		        if (!exists($orders{$partid})) { $orders{$partid}={}; }
                   4604: 		        if (!exists($orders{$partid}->{$responseId})) {
                   4605: 			    $orders{$partid}->{$responseId}=
                   4606: 			        &get_order($partid,$responseId,$symb,$uname,$udom,
                   4607:                                            $no_increment);
                   4608: 		        }
                   4609: 		        $displaySub[0].='</b></span>'; # /nobreak
                   4610: 		        $displaySub[0].='&nbsp; '.
                   4611: 			    &cleanRecord($$record{$version.':'.$matchKey},$responseType,$symb,$partid,$responseId,$record,$orders{$partid}->{$responseId},"$version:",$uname,$udom).'<br />';
                   4612:                     }
1.147     albertel 4613: 		}
                   4614: 	    }
1.335     albertel 4615: 	    if (exists($$record{"$where.$partid.checkedin"})) {
1.485     albertel 4616: 		$displaySub[1].=&mt('Checked in by [_1] into slot [_2]',
                   4617: 				    $$record{"$where.$partid.checkedin"},
                   4618: 				    $$record{"$where.$partid.checkedin.slot"}).
                   4619: 					'<br />';
1.335     albertel 4620: 	    }
                   4621: 	    if (exists $$record{"$where.$partid.award"}) {
1.485     albertel 4622: 		$displaySub[1].='<b>'.&mt('Part:').'</b>&nbsp;'.$display_part.' &nbsp;'.
1.335     albertel 4623: 		    lc($$record{"$where.$partid.award"}).' '.
                   4624: 		    $mark{$$record{"$where.$partid.solved"}}.
1.147     albertel 4625: 		    '<br />';
                   4626: 	    }
1.335     albertel 4627: 	    if (exists $$record{"$where.$partid.regrader"}) {
                   4628: 		$displaySub[2].=$$record{"$where.$partid.regrader"}.
                   4629: 		    ' (<b>'.&mt('Part').':</b> '.$display_part.')';
                   4630: 	    } elsif ($$record{"$version:resource.$partid.regrader"} =~ /\S/) {
                   4631: 		$displaySub[2].=
                   4632: 		    $$record{"$version:resource.$partid.regrader"}.
1.207     albertel 4633: 		    ' (<b>'.&mt('Part').':</b> '.$display_part.')';
1.147     albertel 4634: 	    }
                   4635: 	}
                   4636: 	# needed because old essay regrader has not parts info
                   4637: 	if (exists $$record{"$version:resource.regrader"}) {
                   4638: 	    $displaySub[2].=$$record{"$version:resource.regrader"};
                   4639: 	}
                   4640: 	$studentTable.='<td>'.$displaySub[0].'&nbsp;</td><td>'.$displaySub[1];
                   4641: 	if ($displaySub[2]) {
1.467     albertel 4642: 	    $studentTable.=&mt('Manually graded by [_1]',$displaySub[2]);
1.147     albertel 4643: 	}
1.467     albertel 4644: 	$studentTable.='&nbsp;</td>'.
                   4645: 	    &Apache::loncommon::end_data_table_row();
1.119     ng       4646:     }
1.467     albertel 4647:     $studentTable.=&Apache::loncommon::end_data_table();
1.119     ng       4648:     return $studentTable;
1.71      ng       4649: }
                   4650: 
                   4651: sub updateGradeByPage {
                   4652:     my ($request) = shift;
                   4653: 
1.257     albertel 4654:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
                   4655:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
                   4656:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
                   4657:     my $pageTitle = $env{'form.page'};
1.103     albertel 4658:     my ($classlist,undef,$fullname) = &getclasslist($getsec,'1');
1.257     albertel 4659:     my ($uname,$udom) = split(/:/,$env{'form.student'});
                   4660:     my $usec=$classlist->{$env{'form.student'}}[5];
1.103     albertel 4661:     if (!&canmodify($usec)) {
1.526     raeburn  4662: 	$request->print('<span class="LC_warning">'.&mt('Unable to modify requested student ([_1])',$env{'form.student'}).'</span>');
1.324     albertel 4663: 	$request->print(&show_grading_menu_form($env{'form.symb'}));
1.103     albertel 4664: 	return;
                   4665:     }
1.398     albertel 4666:     my $result='<h3><span class="LC_info">&nbsp;'.$env{'form.title'}.'</span></h3>';
1.526     raeburn  4667:     $result.='<h3>&nbsp;'.&mt('Student: ').&nameUserString(undef,$env{'form.fullname'},$uname,$udom).
1.129     ng       4668: 	'</h3>'."\n";
1.70      ng       4669: 
1.68      ng       4670:     $request->print($result);
                   4671: 
1.582     raeburn  4672: 
1.132     bowersj2 4673:     my $navmap = Apache::lonnavmaps::navmap->new();
1.582     raeburn  4674:     unless (ref($navmap)) {
                   4675:         $request->print(&navmap_errormsg());
                   4676:         return;
                   4677:     }
1.257     albertel 4678:     my ($mapUrl, $id, $resUrl) = &Apache::lonnet::decode_symb( $env{'form.page'});
1.71      ng       4679:     my $map = $navmap->getResourceByUrl($resUrl); # add to navmaps
1.288     albertel 4680:     if (!$map) {
1.527     raeburn  4681: 	$request->print('<span class="LC_warning">'.&mt('Unable to grade requested sequence ([_1]).',$resUrl).'</span>');
1.324     albertel 4682: 	my ($symb)=&get_symb($request);
                   4683: 	$request->print(&show_grading_menu_form($symb));
1.288     albertel 4684: 	return; 
                   4685:     }
1.71      ng       4686:     my $iterator = $navmap->getIterator($map->map_start(),
                   4687: 					$map->map_finish());
1.70      ng       4688: 
1.484     albertel 4689:     my $studentTable=
                   4690: 	&Apache::loncommon::start_data_table().
                   4691: 	&Apache::loncommon::start_data_table_header_row().
1.485     albertel 4692: 	'<th align="center">&nbsp;'.&mt('Prob.').'&nbsp;</th>'.
                   4693: 	'<th>&nbsp;'.&mt('Title').'&nbsp;</th>'.
                   4694: 	'<th>&nbsp;'.&mt('Previous Score').'&nbsp;</th>'.
                   4695: 	'<th>&nbsp;'.&mt('New Score').'&nbsp;</th>'.
1.484     albertel 4696: 	&Apache::loncommon::end_data_table_header_row();
1.71      ng       4697: 
                   4698:     $iterator->next(); # skip the first BEGIN_MAP
                   4699:     my $curRes = $iterator->next(); # for "current resource"
1.196     albertel 4700:     my ($depth,$question,$prob,$changeflag)= (1,1,1,0);
1.101     albertel 4701:     while ($depth > 0) {
1.71      ng       4702:         if($curRes == $iterator->BEGIN_MAP) { $depth++; }
1.100     bowersj2 4703:         if($curRes == $iterator->END_MAP) { $depth--; }
1.71      ng       4704: 
1.385     albertel 4705:         if (ref($curRes) && $curRes->is_problem()) {
1.91      albertel 4706: 	    my $parts = $curRes->parts();
1.71      ng       4707:             my $title = $curRes->compTitle();
                   4708: 	    my $symbx = $curRes->symb();
1.484     albertel 4709: 	    $studentTable.=
                   4710: 		&Apache::loncommon::start_data_table_row().
                   4711: 		'<td align="center" valign="top" >'.$prob.
1.485     albertel 4712: 		(scalar(@{$parts}) == 1 ? '' 
1.526     raeburn  4713:                                         : '<br />('.&mt('[quant,_1,&nbsp;part]',scalar(@{$parts}))
                   4714: 		.')').'</td>';
1.71      ng       4715: 	    $studentTable.='<td valign="top">&nbsp;<b>'.$title.'</b>&nbsp;</td>';
                   4716: 
                   4717: 	    my %newrecord=();
                   4718: 	    my @displayPts=();
1.269     raeburn  4719:             my %aggregate = ();
                   4720:             my $aggregateflag = 0;
1.71      ng       4721: 	    foreach my $partid (@{$parts}) {
1.257     albertel 4722: 		my $newpts = $env{'form.GD_BOX'.$question.'_'.$partid};
                   4723: 		my $oldpts = $env{'form.oldpts'.$question.'_'.$partid};
1.71      ng       4724: 
1.257     albertel 4725: 		my $wgt = $env{'form.WGT'.$question.'_'.$partid} != 0 ? 
                   4726: 		    $env{'form.WGT'.$question.'_'.$partid} : 1;
1.71      ng       4727: 		my $partial = $newpts/$wgt;
                   4728: 		my $score;
                   4729: 		if ($partial > 0) {
                   4730: 		    $score = 'correct_by_override';
1.125     ng       4731: 		} elsif ($newpts ne '') { #empty is taken as 0
1.71      ng       4732: 		    $score = 'incorrect_by_override';
                   4733: 		}
1.257     albertel 4734: 		my $dropMenu = $env{'form.GD_SEL'.$question.'_'.$partid};
1.125     ng       4735: 		if ($dropMenu eq 'excused') {
1.71      ng       4736: 		    $partial = '';
                   4737: 		    $score = 'excused';
1.125     ng       4738: 		} elsif ($dropMenu eq 'reset status'
1.257     albertel 4739: 			 && $env{'form.solved'.$question.'_'.$partid} ne '') { #update only if previous record exists
1.125     ng       4740: 		    $newrecord{'resource.'.$partid.'.tries'} = 0;
                   4741: 		    $newrecord{'resource.'.$partid.'.solved'} = '';
                   4742: 		    $newrecord{'resource.'.$partid.'.award'} = '';
                   4743: 		    $newrecord{'resource.'.$partid.'.awarded'} = 0;
1.257     albertel 4744: 		    $newrecord{'resource.'.$partid.'.regrader'} = "$env{'user.name'}:$env{'user.domain'}";
1.125     ng       4745: 		    $changeflag++;
                   4746: 		    $newpts = '';
1.269     raeburn  4747:                     
                   4748:                     my $aggtries =  $env{'form.aggtries'.$question.'_'.$partid};
                   4749:                     my $totaltries = $env{'form.totaltries'.$question.'_'.$partid};
                   4750:                     my $solvedstatus = $env{'form.solved'.$question.'_'.$partid};
                   4751:                     if ($aggtries > 0) {
                   4752:                         &decrement_aggs($symbx,$partid,\%aggregate,$aggtries,$totaltries,$solvedstatus);
                   4753:                         $aggregateflag = 1;
                   4754:                     }
1.71      ng       4755: 		}
1.324     albertel 4756: 		my $display_part=&get_display_part($partid,$curRes->symb());
1.257     albertel 4757: 		my $oldstatus = $env{'form.solved'.$question.'_'.$partid};
1.526     raeburn  4758: 		$displayPts[0].='&nbsp;<b>'.&mt('Part').':</b> '.$display_part.' = '.
1.71      ng       4759: 		    (($oldstatus eq 'excused') ? 'excused' : $oldpts).
1.326     albertel 4760: 		    '&nbsp;<br />';
1.526     raeburn  4761: 		$displayPts[1].='&nbsp;<b>'.&mt('Part').':</b> '.$display_part.' = '.
1.125     ng       4762: 		     (($score eq 'excused') ? 'excused' : $newpts).
1.326     albertel 4763: 		    '&nbsp;<br />';
1.71      ng       4764: 		$question++;
1.380     albertel 4765: 		next if ($dropMenu eq 'reset status' || ($newpts eq $oldpts && $score ne 'excused'));
1.125     ng       4766: 
1.71      ng       4767: 		$newrecord{'resource.'.$partid.'.awarded'}  = $partial if $partial ne '';
1.125     ng       4768: 		$newrecord{'resource.'.$partid.'.solved'}   = $score if $score ne '';
1.257     albertel 4769: 		$newrecord{'resource.'.$partid.'.regrader'} = "$env{'user.name'}:$env{'user.domain'}"
1.125     ng       4770: 		    if (scalar(keys(%newrecord)) > 0);
1.71      ng       4771: 
                   4772: 		$changeflag++;
                   4773: 	    }
                   4774: 	    if (scalar(keys(%newrecord)) > 0) {
1.382     albertel 4775: 		my %record = 
                   4776: 		    &Apache::lonnet::restore($symbx,$env{'request.course.id'},
                   4777: 					     $udom,$uname);
                   4778: 
                   4779: 		if (&Apache::lonnet::validCODE($env{'form.CODE'})) {
                   4780: 		    $newrecord{'resource.CODE'} = $env{'form.CODE'};
                   4781: 		} elsif (&Apache::lonnet::validCODE($record{'resource.CODE'})) {
                   4782: 		    $newrecord{'resource.CODE'} = '';
                   4783: 		}
1.257     albertel 4784: 		&Apache::lonnet::cstore(\%newrecord,$symbx,$env{'request.course.id'},
1.71      ng       4785: 					$udom,$uname);
1.382     albertel 4786: 		%record = &Apache::lonnet::restore($symbx,
                   4787: 						   $env{'request.course.id'},
                   4788: 						   $udom,$uname);
1.380     albertel 4789: 		&check_and_remove_from_queue($parts,\%record,undef,$symbx,
                   4790: 					     $cdom,$cnum,$udom,$uname);
1.71      ng       4791: 	    }
1.380     albertel 4792: 	    
1.269     raeburn  4793:             if ($aggregateflag) {
                   4794:                 &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
                   4795:                       $env{'course.'.$env{'request.course.id'}.'.domain'},
                   4796:                       $env{'course.'.$env{'request.course.id'}.'.num'});
                   4797:             }
1.125     ng       4798: 
1.71      ng       4799: 	    $studentTable.='<td valign="top">'.$displayPts[0].'</td>'.
                   4800: 		'<td valign="top">'.$displayPts[1].'</td>'.
1.484     albertel 4801: 		&Apache::loncommon::end_data_table_row();
1.68      ng       4802: 
1.196     albertel 4803: 	    $prob++;
1.68      ng       4804: 	}
1.71      ng       4805:         $curRes = $iterator->next();
1.68      ng       4806:     }
1.98      albertel 4807: 
1.484     albertel 4808:     $studentTable.=&Apache::loncommon::end_data_table();
1.324     albertel 4809:     $studentTable.=&show_grading_menu_form($env{'form.symb'});
1.526     raeburn  4810:     my $grademsg=($changeflag == 0 ? &mt('No score was changed or updated.') :
                   4811: 		  &mt('The scores were changed for [quant,_1,problem].',
                   4812: 		  $changeflag));
1.76      ng       4813:     $request->print($grademsg.$studentTable);
1.68      ng       4814: 
1.70      ng       4815:     return '';
                   4816: }
                   4817: 
1.72      ng       4818: #-------- end of section for handling grading by page/sequence ---------
                   4819: #
                   4820: #-------------------------------------------------------------------
                   4821: 
1.581     www      4822: #-------------------- Bubblesheet (Scantron) Grading -------------------
1.75      albertel 4823: #
                   4824: #------ start of section for handling grading by page/sequence ---------
                   4825: 
1.423     albertel 4826: =pod
                   4827: 
                   4828: =head1 Bubble sheet grading routines
                   4829: 
1.424     albertel 4830:   For this documentation:
                   4831: 
                   4832:    'scanline' refers to the full line of characters
                   4833:    from the file that we are parsing that represents one entire sheet
                   4834: 
                   4835:    'bubble line' refers to the data
                   4836:    representing the line of bubbles that are on the physical bubble sheet
                   4837: 
                   4838: 
                   4839: The overall process is that a scanned in bubble sheet data is uploaded
                   4840: into a course. When a user wants to grade, they select a
                   4841: sequence/folder of resources, a file of bubble sheet info, and pick
                   4842: one of the predefined configurations for what each scanline looks
                   4843: like.
                   4844: 
                   4845: Next each scanline is checked for any errors of either 'missing
1.435     foxr     4846: bubbles' (it's an error because it may have been mis-scanned
1.424     albertel 4847: because too light bubbling), 'double bubble' (each bubble line should
                   4848: have no more that one letter picked), invalid or duplicated CODE,
1.556     weissno  4849: invalid student/employee ID
1.424     albertel 4850: 
                   4851: If the CODE option is used that determines the randomization of the
1.556     weissno  4852: homework problems, either way the student/employee ID is looked up into a
1.424     albertel 4853: username:domain.
                   4854: 
                   4855: During the validation phase the instructor can choose to skip scanlines. 
                   4856: 
1.435     foxr     4857: After the validation phase, there are now 3 bubble sheet files
1.424     albertel 4858: 
                   4859:   scantron_original_filename (unmodified original file)
                   4860:   scantron_corrected_filename (file where the corrected information has replaced the original information)
                   4861:   scantron_skipped_filename (contains the exact text of scanlines that where skipped)
                   4862: 
                   4863: Also there is a separate hash nohist_scantrondata that contains extra
                   4864: correction information that isn't representable in the bubble sheet
                   4865: file (see &scantron_getfile() for more information)
                   4866: 
                   4867: After all scanlines are either valid, marked as valid or skipped, then
                   4868: foreach line foreach problem in the picked sequence, an ssi request is
                   4869: made that simulates a user submitting their selected letter(s) against
                   4870: the homework problem.
1.423     albertel 4871: 
                   4872: =over 4
                   4873: 
                   4874: 
                   4875: 
                   4876: =item defaultFormData
                   4877: 
                   4878:   Returns html hidden inputs used to hold context/default values.
                   4879: 
                   4880:  Arguments:
                   4881:   $symb - $symb of the current resource 
                   4882: 
                   4883: =cut
1.422     foxr     4884: 
1.81      albertel 4885: sub defaultFormData {
1.324     albertel 4886:     my ($symb)=@_;
1.447     foxr     4887:     return '<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.605     www      4888:      '<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />';
1.81      albertel 4889: }
                   4890: 
1.447     foxr     4891: 
1.423     albertel 4892: =pod 
                   4893: 
                   4894: =item getSequenceDropDown
                   4895: 
                   4896:    Return html dropdown of possible sequences to grade
                   4897:  
                   4898:  Arguments:
1.582     raeburn  4899:    $symb - $symb of the current resource
                   4900:    $map_error - ref to scalar which will container error if
                   4901:                 $navmap object is unavailable in &getSymbMap().
1.423     albertel 4902: 
                   4903: =cut
1.422     foxr     4904: 
1.75      albertel 4905: sub getSequenceDropDown {
1.582     raeburn  4906:     my ($symb,$map_error)=@_;
1.75      albertel 4907:     my $result='<select name="selectpage">'."\n";
1.582     raeburn  4908:     my ($titles,$symbx) = &getSymbMap($map_error);
                   4909:     if (ref($map_error)) {
                   4910:         return if ($$map_error);
                   4911:     }
1.137     albertel 4912:     my ($curpage)=&Apache::lonnet::decode_symb($symb); 
1.75      albertel 4913:     my $ctr=0;
                   4914:     foreach (@$titles) {
                   4915: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
                   4916: 	$result.='<option value="'.$$symbx{$_}.'" '.
1.401     albertel 4917: 	    ($$symbx{$_} =~ /$curpage$/ ? 'selected="selected"' : '').
1.75      albertel 4918: 	    '>'.$showtitle.'</option>'."\n";
                   4919: 	$ctr++;
                   4920:     }
                   4921:     $result.= '</select>';
                   4922:     return $result;
                   4923: }
                   4924: 
1.495     albertel 4925: my %bubble_lines_per_response;     # no. bubble lines for each response.
1.554     raeburn  4926:                                    # key is zero-based index - 0, 1, 2 ...
1.495     albertel 4927: 
                   4928: my %first_bubble_line;             # First bubble line no. for each bubble.
                   4929: 
1.509     raeburn  4930: my %subdivided_bubble_lines;       # no. bubble lines for optionresponse, 
                   4931:                                    # matchresponse or rankresponse, where 
                   4932:                                    # an individual response can have multiple 
                   4933:                                    # lines
1.503     raeburn  4934: 
                   4935: my %responsetype_per_response;     # responsetype for each response
                   4936: 
1.495     albertel 4937: # Save and restore the bubble lines array to the form env.
                   4938: 
                   4939: 
                   4940: sub save_bubble_lines {
                   4941:     foreach my $line (keys(%bubble_lines_per_response)) {
                   4942: 	$env{"form.scantron.bubblelines.$line"}  = $bubble_lines_per_response{$line};
                   4943: 	$env{"form.scantron.first_bubble_line.$line"} =
                   4944: 	    $first_bubble_line{$line};
1.503     raeburn  4945:         $env{"form.scantron.sub_bubblelines.$line"} = 
                   4946:             $subdivided_bubble_lines{$line};
                   4947:         $env{"form.scantron.responsetype.$line"} =
                   4948:             $responsetype_per_response{$line};
1.495     albertel 4949:     }
                   4950: }
                   4951: 
                   4952: 
                   4953: sub restore_bubble_lines {
                   4954:     my $line = 0;
                   4955:     %bubble_lines_per_response = ();
                   4956:     while ($env{"form.scantron.bubblelines.$line"}) {
                   4957: 	my $value = $env{"form.scantron.bubblelines.$line"};
                   4958: 	$bubble_lines_per_response{$line} = $value;
                   4959: 	$first_bubble_line{$line}  =
                   4960: 	    $env{"form.scantron.first_bubble_line.$line"};
1.503     raeburn  4961:         $subdivided_bubble_lines{$line} =
                   4962:             $env{"form.scantron.sub_bubblelines.$line"};
                   4963:         $responsetype_per_response{$line} =
                   4964:             $env{"form.scantron.responsetype.$line"};
1.495     albertel 4965: 	$line++;
                   4966:     }
                   4967: }
                   4968: 
                   4969: #  Given the parsed scanline, get the response for 
                   4970: #  'answer' number n:
                   4971: 
                   4972: sub get_response_bubbles {
                   4973:     my ($parsed_line, $response)  = @_;
                   4974: 
                   4975:     my $bubble_line = $first_bubble_line{$response-1} +1;
                   4976:     my $bubble_lines= $bubble_lines_per_response{$response-1};
                   4977:     
                   4978:     my $selected = "";
                   4979: 
                   4980:     for (my $bline = 0; $bline < $bubble_lines; $bline++) {
                   4981: 	$selected .= $$parsed_line{"scantron.$bubble_line.answer"}.":";
                   4982: 	$bubble_line++;
                   4983:     }
                   4984:     return $selected;
                   4985: }
1.423     albertel 4986: 
                   4987: =pod 
                   4988: 
                   4989: =item scantron_filenames
                   4990: 
                   4991:    Returns a list of the scantron files in the current course 
                   4992: 
                   4993: =cut
1.422     foxr     4994: 
1.202     albertel 4995: sub scantron_filenames {
1.257     albertel 4996:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   4997:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
1.517     raeburn  4998:     my $getpropath = 1;
1.157     albertel 4999:     my @files=&Apache::lonnet::dirlist('userfiles',$cdom,$cname,
1.517     raeburn  5000:                                        $getpropath);
1.202     albertel 5001:     my @possiblenames;
1.201     albertel 5002:     foreach my $filename (sort(@files)) {
1.157     albertel 5003: 	($filename)=split(/&/,$filename);
                   5004: 	if ($filename!~/^scantron_orig_/) { next ; }
                   5005: 	$filename=~s/^scantron_orig_//;
1.202     albertel 5006: 	push(@possiblenames,$filename);
                   5007:     }
                   5008:     return @possiblenames;
                   5009: }
                   5010: 
1.423     albertel 5011: =pod 
                   5012: 
                   5013: =item scantron_uploads
                   5014: 
                   5015:    Returns  html drop-down list of scantron files in current course.
                   5016: 
                   5017:  Arguments:
                   5018:    $file2grade - filename to set as selected in the dropdown
                   5019: 
                   5020: =cut
1.422     foxr     5021: 
1.202     albertel 5022: sub scantron_uploads {
1.209     ng       5023:     my ($file2grade) = @_;
1.202     albertel 5024:     my $result=	'<select name="scantron_selectfile">';
                   5025:     $result.="<option></option>";
                   5026:     foreach my $filename (sort(&scantron_filenames())) {
1.401     albertel 5027: 	$result.="<option".($filename eq $file2grade ? ' selected="selected"':'').">$filename</option>\n";
1.81      albertel 5028:     }
                   5029:     $result.="</select>";
                   5030:     return $result;
                   5031: }
                   5032: 
1.423     albertel 5033: =pod 
                   5034: 
                   5035: =item scantron_scantab
                   5036: 
                   5037:   Returns html drop down of the scantron formats in the scantronformat.tab
                   5038:   file.
                   5039: 
                   5040: =cut
1.422     foxr     5041: 
1.82      albertel 5042: sub scantron_scantab {
                   5043:     my $result='<select name="scantron_format">'."\n";
1.191     albertel 5044:     $result.='<option></option>'."\n";
1.518     raeburn  5045:     my @lines = &get_scantronformat_file();
                   5046:     if (@lines > 0) {
                   5047:         foreach my $line (@lines) {
                   5048:             next if (($line =~ /^\#/) || ($line eq ''));
                   5049: 	    my ($name,$descrip)=split(/:/,$line);
                   5050: 	    $result.='<option value="'.$name.'">'.$descrip.'</option>'."\n";
                   5051:         }
1.82      albertel 5052:     }
                   5053:     $result.='</select>'."\n";
1.518     raeburn  5054:     return $result;
                   5055: }
                   5056: 
                   5057: =pod
                   5058: 
                   5059: =item get_scantronformat_file
                   5060: 
                   5061:   Returns an array containing lines from the scantron format file for
                   5062:   the domain of the course.
                   5063: 
                   5064:   If a url for a custom.tab file is listed in domain's configuration.db, 
                   5065:   lines are from this file.
                   5066: 
                   5067:   Otherwise, if a default.tab has been published in RES space by the 
                   5068:   domainconfig user, lines are from this file.
                   5069: 
                   5070:   Otherwise, fall back to getting lines from the legacy file on the
1.519     raeburn  5071:   local server:  /home/httpd/lonTabs/default_scantronformat.tab    
1.82      albertel 5072: 
1.518     raeburn  5073: =cut
                   5074: 
                   5075: sub get_scantronformat_file {
                   5076:     my $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
                   5077:     my %domconfig = &Apache::lonnet::get_dom('configuration',['scantron'],$cdom);
                   5078:     my $gottab = 0;
                   5079:     my @lines;
                   5080:     if (ref($domconfig{'scantron'}) eq 'HASH') {
                   5081:         if ($domconfig{'scantron'}{'scantronformat'} ne '') {
                   5082:             my $formatfile = &Apache::lonnet::getfile($Apache::lonnet::perlvar{'lonDocRoot'}.$domconfig{'scantron'}{'scantronformat'});
                   5083:             if ($formatfile ne '-1') {
                   5084:                 @lines = split("\n",$formatfile,-1);
                   5085:                 $gottab = 1;
                   5086:             }
                   5087:         }
                   5088:     }
                   5089:     if (!$gottab) {
                   5090:         my $confname = $cdom.'-domainconfig';
                   5091:         my $default = $Apache::lonnet::perlvar{'lonDocRoot'}.'/res/'.$cdom.'/'.$confname.'/default.tab';
                   5092:         my $formatfile =  &Apache::lonnet::getfile($default);
                   5093:         if ($formatfile ne '-1') {
                   5094:             @lines = split("\n",$formatfile,-1);
                   5095:             $gottab = 1;
                   5096:         }
                   5097:     }
                   5098:     if (!$gottab) {
1.519     raeburn  5099:         my @domains = &Apache::lonnet::current_machine_domains();
                   5100:         if (grep(/^\Q$cdom\E$/,@domains)) {
                   5101:             my $fh=Apache::File->new($Apache::lonnet::perlvar{'lonTabDir'}.'/scantronformat.tab');
                   5102:             @lines = <$fh>;
                   5103:             close($fh);
                   5104:         } else {
                   5105:             my $fh=Apache::File->new($Apache::lonnet::perlvar{'lonTabDir'}.'/default_scantronformat.tab');
                   5106:             @lines = <$fh>;
                   5107:             close($fh);
                   5108:         }
1.518     raeburn  5109:     }
                   5110:     return @lines;
1.82      albertel 5111: }
                   5112: 
1.423     albertel 5113: =pod 
                   5114: 
                   5115: =item scantron_CODElist
                   5116: 
                   5117:   Returns html drop down of the saved CODE lists from current course,
                   5118:   generated from earlier printings.
                   5119: 
                   5120: =cut
1.422     foxr     5121: 
1.186     albertel 5122: sub scantron_CODElist {
1.257     albertel 5123:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   5124:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
1.186     albertel 5125:     my @names=&Apache::lonnet::getkeys('CODEs',$cdom,$cnum);
                   5126:     my $namechoice='<option></option>';
1.225     albertel 5127:     foreach my $name (sort {uc($a) cmp uc($b)} @names) {
1.191     albertel 5128: 	if ($name =~ /^error: 2 /) { next; }
1.278     albertel 5129: 	if ($name =~ /^type\0/) { next; }
1.186     albertel 5130: 	$namechoice.='<option value="'.$name.'">'.$name.'</option>';
                   5131:     }
                   5132:     $namechoice='<select name="scantron_CODElist">'.$namechoice.'</select>';
                   5133:     return $namechoice;
                   5134: }
                   5135: 
1.423     albertel 5136: =pod 
                   5137: 
                   5138: =item scantron_CODEunique
                   5139: 
                   5140:   Returns the html for "Each CODE to be used once" radio.
                   5141: 
                   5142: =cut
1.422     foxr     5143: 
1.186     albertel 5144: sub scantron_CODEunique {
1.532     bisitz   5145:     my $result='<span class="LC_nobreak">
1.272     albertel 5146:                  <label><input type="radio" name="scantron_CODEunique"
1.423     albertel 5147:                         value="yes" checked="checked" />'.&mt('Yes').' </label>
1.381     albertel 5148:                 </span>
1.532     bisitz   5149:                 <span class="LC_nobreak">
1.272     albertel 5150:                  <label><input type="radio" name="scantron_CODEunique"
1.423     albertel 5151:                         value="no" />'.&mt('No').' </label>
1.381     albertel 5152:                 </span>';
1.186     albertel 5153:     return $result;
                   5154: }
1.423     albertel 5155: 
                   5156: =pod 
                   5157: 
                   5158: =item scantron_selectphase
                   5159: 
                   5160:   Generates the initial screen to start the bubble sheet process.
                   5161:   Allows for - starting a grading run.
1.424     albertel 5162:              - downloading existing scan data (original, corrected
1.423     albertel 5163:                                                 or skipped info)
                   5164: 
                   5165:              - uploading new scan data
                   5166: 
                   5167:  Arguments:
                   5168:   $r          - The Apache request object
                   5169:   $file2grade - name of the file that contain the scanned data to score
                   5170: 
                   5171: =cut
1.186     albertel 5172: 
1.75      albertel 5173: sub scantron_selectphase {
1.209     ng       5174:     my ($r,$file2grade) = @_;
1.324     albertel 5175:     my ($symb)=&get_symb($r);
1.75      albertel 5176:     if (!$symb) {return '';}
1.582     raeburn  5177:     my $map_error;
                   5178:     my $sequence_selector=&getSequenceDropDown($symb,\$map_error);
                   5179:     if ($map_error) {
                   5180:         $r->print('<br />'.&navmap_errormsg().'<br />');
                   5181:         return;
                   5182:     }
1.324     albertel 5183:     my $default_form_data=&defaultFormData($symb);
                   5184:     my $grading_menu_button=&show_grading_menu_form($symb);
1.209     ng       5185:     my $file_selector=&scantron_uploads($file2grade);
1.82      albertel 5186:     my $format_selector=&scantron_scantab();
1.186     albertel 5187:     my $CODE_selector=&scantron_CODElist();
                   5188:     my $CODE_unique=&scantron_CODEunique();
1.75      albertel 5189:     my $result;
1.422     foxr     5190: 
1.513     foxr     5191:     $ssi_error = 0;
                   5192: 
1.606     wenzelju 5193:     if (&Apache::lonnet::allowed('usc',$env{'request.role.domain'}) ||
                   5194:         &Apache::lonnet::allowed('usc',$env{'request.course.id'})) {
                   5195: 
                   5196: 	# Chunk of form to prompt for a scantron file upload.
                   5197: 
                   5198:         $r->print('
                   5199:     <br />
                   5200:     '.&Apache::loncommon::start_data_table('LC_scantron_action').'
                   5201:        '.&Apache::loncommon::start_data_table_header_row().'
                   5202:             <th>
                   5203:               &nbsp;'.&mt('Specify a bubblesheet data file to upload.').'
                   5204:             </th>
                   5205:        '.&Apache::loncommon::end_data_table_header_row().'
                   5206:        '.&Apache::loncommon::start_data_table_row().'
                   5207:             <td>
                   5208: ');
                   5209:     my $default_form_data=&defaultFormData(&get_symb($r,1));
                   5210:     my $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
                   5211:     my $cnum= $env{'course.'.$env{'request.course.id'}.'.num'};
                   5212:     $r->print(&Apache::lonhtmlcommon::scripttag('
                   5213:     function checkUpload(formname) {
                   5214: 	if (formname.upfile.value == "") {
                   5215: 	    alert("'.&mt('Please use the browse button to select a file from your local directory.').'");
                   5216: 	    return false;
                   5217: 	}
                   5218: 	formname.submit();
                   5219:     }'));
                   5220:     $r->print('
                   5221:               <form enctype="multipart/form-data" action="/adm/grades" name="rules" method="post">
                   5222:                 '.$default_form_data.'
                   5223:                 <input name="courseid" type="hidden" value="'.$cnum.'" />
                   5224:                 <input name="domainid" type="hidden" value="'.$cdom.'" />
                   5225:                 <input name="command" value="scantronupload_save" type="hidden" />
                   5226:                 '.&mt('File to upload: [_1]','<input type="file" name="upfile" size="50" />').'
                   5227:                 <br />
                   5228:                 <input type="button" onclick="javascript:checkUpload(this.form);" value="'.&mt('Upload Bubblesheet Data').'" />
                   5229:               </form>
                   5230: ');
                   5231: 
                   5232:         $r->print('
                   5233:             </td>
                   5234:        '.&Apache::loncommon::end_data_table_row().'
                   5235:        '.&Apache::loncommon::end_data_table().'
                   5236: ');
                   5237:     }
                   5238: 
1.422     foxr     5239:     # Chunk of form to prompt for a file to grade and how:
                   5240: 
1.489     albertel 5241:     $result.= '
                   5242:     <br />
                   5243:     <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantron_process">
                   5244:     <input type="hidden" name="command" value="scantron_warning" />
                   5245:     '.$default_form_data.'
                   5246:     '.&Apache::loncommon::start_data_table('LC_scantron_action').'
                   5247:        '.&Apache::loncommon::start_data_table_header_row().'
                   5248:             <th colspan="2">
1.492     albertel 5249:               &nbsp;'.&mt('Specify file and which Folder/Sequence to grade').'
1.489     albertel 5250:             </th>
                   5251:        '.&Apache::loncommon::end_data_table_header_row().'
                   5252:        '.&Apache::loncommon::start_data_table_row().'
1.492     albertel 5253:             <td> '.&mt('Sequence to grade:').' </td><td> '.$sequence_selector.' </td>
1.489     albertel 5254:        '.&Apache::loncommon::end_data_table_row().'
                   5255:        '.&Apache::loncommon::start_data_table_row().'
1.572     www      5256:             <td> '.&mt('Filename of bubblesheet data file:').' </td><td> '.$file_selector.' </td>
1.489     albertel 5257:        '.&Apache::loncommon::end_data_table_row().'
                   5258:        '.&Apache::loncommon::start_data_table_row().'
1.572     www      5259:             <td> '.&mt('Format of bubblesheet data file:').' </td><td> '.$format_selector.' </td>
1.489     albertel 5260:        '.&Apache::loncommon::end_data_table_row().'
                   5261:        '.&Apache::loncommon::start_data_table_row().'
1.492     albertel 5262:             <td> '.&mt('Saved CODEs to validate against:').' </td><td> '.$CODE_selector.' </td>
1.489     albertel 5263:        '.&Apache::loncommon::end_data_table_row().'
                   5264:        '.&Apache::loncommon::start_data_table_row().'
1.492     albertel 5265:             <td> '.&mt('Each CODE is only to be used once:').'</td><td> '.$CODE_unique.' </td>
1.489     albertel 5266:        '.&Apache::loncommon::end_data_table_row().'
                   5267:        '.&Apache::loncommon::start_data_table_row().'
1.492     albertel 5268: 	    <td> '.&mt('Options:').' </td>
1.187     albertel 5269:             <td>
1.492     albertel 5270: 	       <label><input type="checkbox" name="scantron_options_redo" value="redo_skipped"/> '.&mt('Do only previously skipped records').'</label> <br />
                   5271:                <label><input type="checkbox" name="scantron_options_ignore" value="ignore_corrections"/> '.&mt('Remove all existing corrections').'</label> <br />
                   5272:                <label><input type="checkbox" name="scantron_options_hidden" value="ignore_hidden"/> '.&mt('Skip hidden resources when grading').'</label>
1.187     albertel 5273: 	    </td>
1.489     albertel 5274:        '.&Apache::loncommon::end_data_table_row().'
                   5275:        '.&Apache::loncommon::start_data_table_row().'
1.174     albertel 5276:             <td colspan="2">
1.572     www      5277:               <input type="submit" value="'.&mt('Grading: Validate Bubblesheet Records').'" />
1.162     albertel 5278:             </td>
1.489     albertel 5279:        '.&Apache::loncommon::end_data_table_row().'
                   5280:     '.&Apache::loncommon::end_data_table().'
                   5281:     </form>
                   5282: ';
1.162     albertel 5283:    
                   5284:     $r->print($result);
                   5285: 
1.422     foxr     5286: 
                   5287: 
                   5288:     # Chunk of the form that prompts to view a scoring office file,
                   5289:     # corrected file, skipped records in a file.
                   5290: 
1.489     albertel 5291:     $r->print('
                   5292:    <br />
                   5293:    <form action="/adm/grades" name="scantron_download">
                   5294:      '.$default_form_data.'
                   5295:      <input type="hidden" name="command" value="scantron_download" />
                   5296:      '.&Apache::loncommon::start_data_table('LC_scantron_action').'
                   5297:        '.&Apache::loncommon::start_data_table_header_row().'
                   5298:               <th>
1.492     albertel 5299:                 &nbsp;'.&mt('Download a scoring office file').'
1.489     albertel 5300:               </th>
                   5301:        '.&Apache::loncommon::end_data_table_header_row().'
                   5302:        '.&Apache::loncommon::start_data_table_row().'
1.492     albertel 5303:               <td> '.&mt('Filename of scoring office file: [_1]',$file_selector).' 
1.489     albertel 5304:                 <br />
1.492     albertel 5305:                 <input type="submit" value="'.&mt('Download: Show List of Associated Files').'" />
1.489     albertel 5306:        '.&Apache::loncommon::end_data_table_row().'
                   5307:      '.&Apache::loncommon::end_data_table().'
                   5308:    </form>
                   5309:    <br />
                   5310: ');
1.162     albertel 5311: 
1.457     banghart 5312:     &Apache::lonpickcode::code_list($r,2);
1.523     raeburn  5313: 
1.528     raeburn  5314:     $r->print('<br /><form method="post" name="checkscantron">'.
1.523     raeburn  5315:              $default_form_data."\n".
                   5316:              &Apache::loncommon::start_data_table('LC_scantron_action')."\n".
                   5317:              &Apache::loncommon::start_data_table_header_row()."\n".
                   5318:              '<th colspan="2">
1.572     www      5319:               &nbsp;'.&mt('Review bubblesheet data and submissions for a previously graded folder/sequence')."\n".
1.523     raeburn  5320:              '</th>'."\n".
                   5321:               &Apache::loncommon::end_data_table_header_row()."\n".
                   5322:               &Apache::loncommon::start_data_table_row()."\n".
                   5323:               '<td> '.&mt('Graded folder/sequence:').' </td>'."\n".
                   5324:               '<td> '.$sequence_selector.' </td>'.
                   5325:               &Apache::loncommon::end_data_table_row()."\n".
                   5326:               &Apache::loncommon::start_data_table_row()."\n".
                   5327:               '<td> '.&mt('Filename of scoring office file:').' </td>'."\n".
                   5328:               '<td> '.$file_selector.' </td>'."\n".
                   5329:               &Apache::loncommon::end_data_table_row()."\n".
                   5330:               &Apache::loncommon::start_data_table_row()."\n".
                   5331:               '<td> '.&mt('Format of data file:').' </td>'."\n".
                   5332:               '<td> '.$format_selector.' </td>'."\n".
                   5333:               &Apache::loncommon::end_data_table_row()."\n".
                   5334:               &Apache::loncommon::start_data_table_row()."\n".
1.557     raeburn  5335:               '<td> '.&mt('Options').' </td>'."\n".
                   5336:               '<td> <label><input type="checkbox" name="scantron_options_hidden" value="ignore_hidden"/> '.&mt('Skip hidden resources').'</label></td>'.
                   5337:               &Apache::loncommon::end_data_table_row()."\n".
                   5338:               &Apache::loncommon::start_data_table_row()."\n".
1.523     raeburn  5339:               '<td colspan="2">'."\n".
                   5340:               '<input type="hidden" name="command" value="checksubmissions" />'."\n".
1.575     www      5341:               '<input type="submit" value="'.&mt('Review Bubblesheet Data and Submission Records').'" />'."\n".
1.523     raeburn  5342:               '</td>'."\n".
                   5343:               &Apache::loncommon::end_data_table_row()."\n".
                   5344:               &Apache::loncommon::end_data_table()."\n".
                   5345:               '</form><br />');
1.457     banghart 5346:     $r->print($grading_menu_button);
1.523     raeburn  5347:     return;
1.75      albertel 5348: }
                   5349: 
1.423     albertel 5350: =pod
                   5351: 
                   5352: =item get_scantron_config
                   5353: 
                   5354:    Parse and return the scantron configuration line selected as a
                   5355:    hash of configuration file fields.
                   5356: 
                   5357:  Arguments:
                   5358:     which - the name of the configuration to parse from the file.
                   5359: 
                   5360: 
                   5361:  Returns:
                   5362:             If the named configuration is not in the file, an empty
                   5363:             hash is returned.
                   5364:     a hash with the fields
                   5365:       name         - internal name for the this configuration setup
                   5366:       description  - text to display to operator that describes this config
                   5367:       CODElocation - if 0 or the string 'none'
                   5368:                           - no CODE exists for this config
                   5369:                      if -1 || the string 'letter'
                   5370:                           - a CODE exists for this config and is
                   5371:                             a string of letters
                   5372:                      Unsupported value (but planned for future support)
                   5373:                           if a positive integer
                   5374:                                - The CODE exists as the first n items from
                   5375:                                  the question section of the form
                   5376:                           if the string 'number'
                   5377:                                - The CODE exists for this config and is
                   5378:                                  a string of numbers
                   5379:       CODEstart   - (only matter if a CODE exists) column in the line where
                   5380:                      the CODE starts
                   5381:       CODElength  - length of the CODE
1.573     bisitz   5382:       IDstart     - column where the student/employee ID starts
1.556     weissno  5383:       IDlength    - length of the student/employee ID info
1.423     albertel 5384:       Qstart      - column where the information from the bubbled
                   5385:                     'questions' start
                   5386:       Qlength     - number of columns comprising a single bubble line from
                   5387:                     the sheet. (usually either 1 or 10)
1.424     albertel 5388:       Qon         - either a single character representing the character used
1.423     albertel 5389:                     to signal a bubble was chosen in the positional setup, or
                   5390:                     the string 'letter' if the letter of the chosen bubble is
                   5391:                     in the final, or 'number' if a number representing the
                   5392:                     chosen bubble is in the file (1->A 0->J)
1.424     albertel 5393:       Qoff        - the character used to represent that a bubble was
                   5394:                     left blank
1.423     albertel 5395:       PaperID     - if the scanning process generates a unique number for each
                   5396:                     sheet scanned the column that this ID number starts in
                   5397:       PaperIDlength - number of columns that comprise the unique ID number
                   5398:                       for the sheet of paper
1.424     albertel 5399:       FirstName   - column that the first name starts in
1.423     albertel 5400:       FirstNameLength - number of columns that the first name spans
                   5401:  
                   5402:       LastName    - column that the last name starts in
                   5403:       LastNameLength - number of columns that the last name spans
                   5404: 
                   5405: =cut
1.422     foxr     5406: 
1.82      albertel 5407: sub get_scantron_config {
                   5408:     my ($which) = @_;
1.518     raeburn  5409:     my @lines = &get_scantronformat_file();
1.82      albertel 5410:     my %config;
1.157     albertel 5411:     #FIXME probably should move to XML it has already gotten a bit much now
1.518     raeburn  5412:     foreach my $line (@lines) {
1.82      albertel 5413: 	my ($name,$descrip)=split(/:/,$line);
                   5414: 	if ($name ne $which ) { next; }
                   5415: 	chomp($line);
                   5416: 	my @config=split(/:/,$line);
                   5417: 	$config{'name'}=$config[0];
                   5418: 	$config{'description'}=$config[1];
                   5419: 	$config{'CODElocation'}=$config[2];
                   5420: 	$config{'CODEstart'}=$config[3];
                   5421: 	$config{'CODElength'}=$config[4];
                   5422: 	$config{'IDstart'}=$config[5];
                   5423: 	$config{'IDlength'}=$config[6];
                   5424: 	$config{'Qstart'}=$config[7];
1.497     foxr     5425:  	$config{'Qlength'}=$config[8];
1.82      albertel 5426: 	$config{'Qoff'}=$config[9];
                   5427: 	$config{'Qon'}=$config[10];
1.157     albertel 5428: 	$config{'PaperID'}=$config[11];
                   5429: 	$config{'PaperIDlength'}=$config[12];
                   5430: 	$config{'FirstName'}=$config[13];
                   5431: 	$config{'FirstNamelength'}=$config[14];
                   5432: 	$config{'LastName'}=$config[15];
                   5433: 	$config{'LastNamelength'}=$config[16];
1.82      albertel 5434: 	last;
                   5435:     }
                   5436:     return %config;
                   5437: }
                   5438: 
1.423     albertel 5439: =pod 
                   5440: 
                   5441: =item username_to_idmap
                   5442: 
1.556     weissno  5443:     creates a hash keyed by student/employee ID with values of the corresponding
1.423     albertel 5444:     student username:domain.
                   5445: 
                   5446:   Arguments:
                   5447: 
                   5448:     $classlist - reference to the class list hash. This is a hash
                   5449:                  keyed by student name:domain  whose elements are references
1.424     albertel 5450:                  to arrays containing various chunks of information
1.423     albertel 5451:                  about the student. (See loncoursedata for more info).
                   5452: 
                   5453:   Returns
                   5454:     %idmap - the constructed hash
                   5455: 
                   5456: =cut
                   5457: 
1.82      albertel 5458: sub username_to_idmap {
                   5459:     my ($classlist)= @_;
                   5460:     my %idmap;
                   5461:     foreach my $student (keys(%$classlist)) {
                   5462: 	$idmap{$classlist->{$student}->[&Apache::loncoursedata::CL_ID]}=
                   5463: 	    $student;
                   5464:     }
                   5465:     return %idmap;
                   5466: }
1.423     albertel 5467: 
                   5468: =pod
                   5469: 
1.424     albertel 5470: =item scantron_fixup_scanline
1.423     albertel 5471: 
                   5472:    Process a requested correction to a scanline.
                   5473: 
                   5474:   Arguments:
                   5475:     $scantron_config   - hash from &get_scantron_config()
                   5476:     $scan_data         - hash of correction information 
                   5477:                           (see &scantron_getfile())
                   5478:     $line              - existing scanline
                   5479:     $whichline         - line number of the passed in scanline
                   5480:     $field             - type of change to process 
                   5481:                          (either 
1.573     bisitz   5482:                           'ID'     -> correct the student/employee ID
1.423     albertel 5483:                           'CODE'   -> correct the CODE
                   5484:                           'answer' -> fixup the submitted answers)
                   5485:     
                   5486:    $args               - hash of additional info,
                   5487:                           - 'ID' 
                   5488:                                'newid' -> studentID to use in replacement
1.424     albertel 5489:                                           of existing one
1.423     albertel 5490:                           - 'CODE' 
                   5491:                                'CODE_ignore_dup' - set to true if duplicates
                   5492:                                                    should be ignored.
                   5493: 	                       'CODE' - is new code or 'use_unfound'
1.424     albertel 5494:                                         if the existing unfound code should
1.423     albertel 5495:                                         be used as is
                   5496:                           - 'answer'
                   5497:                                'response' - new answer or 'none' if blank
                   5498:                                'question' - the bubble line to change
1.503     raeburn  5499:                                'questionnum' - the question identifier,
                   5500:                                                may include subquestion. 
1.423     albertel 5501: 
                   5502:   Returns:
                   5503:     $line - the modified scanline
                   5504: 
                   5505:   Side effects: 
                   5506:     $scan_data - may be updated
                   5507: 
                   5508: =cut
                   5509: 
1.82      albertel 5510: 
1.157     albertel 5511: sub scantron_fixup_scanline {
                   5512:     my ($scantron_config,$scan_data,$line,$whichline,$field,$args)=@_;
                   5513:     if ($field eq 'ID') {
                   5514: 	if (length($args->{'newid'}) > $$scantron_config{'IDlength'}) {
1.186     albertel 5515: 	    return ($line,1,'New value too large');
1.157     albertel 5516: 	}
                   5517: 	if (length($args->{'newid'}) < $$scantron_config{'IDlength'}) {
                   5518: 	    $args->{'newid'}=sprintf('%-'.$$scantron_config{'IDlength'}.'s',
                   5519: 				     $args->{'newid'});
                   5520: 	}
                   5521: 	substr($line,$$scantron_config{'IDstart'}-1,
                   5522: 	       $$scantron_config{'IDlength'})=$args->{'newid'};
                   5523: 	if ($args->{'newid'}=~/^\s*$/) {
                   5524: 	    &scan_data($scan_data,"$whichline.user",
                   5525: 		       $args->{'username'}.':'.$args->{'domain'});
                   5526: 	}
1.186     albertel 5527:     } elsif ($field eq 'CODE') {
1.192     albertel 5528: 	if ($args->{'CODE_ignore_dup'}) {
                   5529: 	    &scan_data($scan_data,"$whichline.CODE_ignore_dup",'1');
                   5530: 	}
                   5531: 	&scan_data($scan_data,"$whichline.useCODE",'1');
                   5532: 	if ($args->{'CODE'} ne 'use_unfound') {
1.191     albertel 5533: 	    if (length($args->{'CODE'}) > $$scantron_config{'CODElength'}) {
                   5534: 		return ($line,1,'New CODE value too large');
                   5535: 	    }
                   5536: 	    if (length($args->{'CODE'}) < $$scantron_config{'CODElength'}) {
                   5537: 		$args->{'CODE'}=sprintf('%-'.$$scantron_config{'CODElength'}.'s',$args->{'CODE'});
                   5538: 	    }
                   5539: 	    substr($line,$$scantron_config{'CODEstart'}-1,
                   5540: 		   $$scantron_config{'CODElength'})=$args->{'CODE'};
1.186     albertel 5541: 	}
1.157     albertel 5542:     } elsif ($field eq 'answer') {
1.497     foxr     5543: 	my $length=$scantron_config->{'Qlength'};
1.157     albertel 5544: 	my $off=$scantron_config->{'Qoff'};
                   5545: 	my $on=$scantron_config->{'Qon'};
1.497     foxr     5546: 	my $answer=${off}x$length;
                   5547: 	if ($args->{'response'} eq 'none') {
                   5548: 	    &scan_data($scan_data,
1.503     raeburn  5549: 		       "$whichline.no_bubble.".$args->{'questionnum'},'1');
1.497     foxr     5550: 	} else {
                   5551: 	    if ($on eq 'letter') {
                   5552: 		my @alphabet=('A'..'Z');
                   5553: 		$answer=$alphabet[$args->{'response'}];
                   5554: 	    } elsif ($on eq 'number') {
                   5555: 		$answer=$args->{'response'}+1;
                   5556: 		if ($answer == 10) { $answer = '0'; }
1.274     albertel 5557: 	    } else {
1.497     foxr     5558: 		substr($answer,$args->{'response'},1)=$on;
1.274     albertel 5559: 	    }
1.497     foxr     5560: 	    &scan_data($scan_data,
1.503     raeburn  5561: 		       "$whichline.no_bubble.".$args->{'questionnum'},undef,'1');
1.157     albertel 5562: 	}
1.497     foxr     5563: 	my $where=$length*($args->{'question'}-1)+$scantron_config->{'Qstart'};
                   5564: 	substr($line,$where-1,$length)=$answer;
1.157     albertel 5565:     }
                   5566:     return $line;
                   5567: }
1.423     albertel 5568: 
                   5569: =pod
                   5570: 
                   5571: =item scan_data
                   5572: 
                   5573:     Edit or look up  an item in the scan_data hash.
                   5574: 
                   5575:   Arguments:
                   5576:     $scan_data  - The hash (see scantron_getfile)
                   5577:     $key        - shorthand of the key to edit (actual key is
1.424     albertel 5578:                   scantronfilename_key).
1.423     albertel 5579:     $data        - New value of the hash entry.
                   5580:     $delete      - If true, the entry is removed from the hash.
                   5581: 
                   5582:   Returns:
                   5583:     The new value of the hash table field (undefined if deleted).
                   5584: 
                   5585: =cut
                   5586: 
                   5587: 
1.157     albertel 5588: sub scan_data {
                   5589:     my ($scan_data,$key,$value,$delete)=@_;
1.257     albertel 5590:     my $filename=$env{'form.scantron_selectfile'};
1.157     albertel 5591:     if (defined($value)) {
                   5592: 	$scan_data->{$filename.'_'.$key} = $value;
                   5593:     }
                   5594:     if ($delete) { delete($scan_data->{$filename.'_'.$key}); }
                   5595:     return $scan_data->{$filename.'_'.$key};
                   5596: }
1.423     albertel 5597: 
1.495     albertel 5598: # ----- These first few routines are general use routines.----
                   5599: 
                   5600: # Return the number of occurences of a pattern in a string.
                   5601: 
                   5602: sub occurence_count {
                   5603:     my ($string, $pattern) = @_;
                   5604: 
                   5605:     my @matches = ($string =~ /$pattern/g);
                   5606: 
                   5607:     return scalar(@matches);
                   5608: }
                   5609: 
                   5610: 
                   5611: # Take a string known to have digits and convert all the
                   5612: # digits into letters in the range J,A..I.
                   5613: 
                   5614: sub digits_to_letters {
                   5615:     my ($input) = @_;
                   5616: 
                   5617:     my @alphabet = ('J', 'A'..'I');
                   5618: 
                   5619:     my @input    = split(//, $input);
                   5620:     my $output ='';
                   5621:     for (my $i = 0; $i < scalar(@input); $i++) {
                   5622: 	if ($input[$i] =~ /\d/) {
                   5623: 	    $output .= $alphabet[$input[$i]];
                   5624: 	} else {
                   5625: 	    $output .= $input[$i];
                   5626: 	}
                   5627:     }
                   5628:     return $output;
                   5629: }
                   5630: 
1.423     albertel 5631: =pod 
                   5632: 
                   5633: =item scantron_parse_scanline
                   5634: 
                   5635:   Decodes a scanline from the selected scantron file
                   5636: 
                   5637:  Arguments:
                   5638:     line             - The text of the scantron file line to process
                   5639:     whichline        - Line number
                   5640:     scantron_config  - Hash describing the format of the scantron lines.
                   5641:     scan_data        - Hash of extra information about the scanline
                   5642:                        (see scantron_getfile for more information)
                   5643:     just_header      - True if should not process question answers but only
                   5644:                        the stuff to the left of the answers.
                   5645:  Returns:
                   5646:    Hash containing the result of parsing the scanline
                   5647: 
                   5648:    Keys are all proceeded by the string 'scantron.'
                   5649: 
                   5650:        CODE    - the CODE in use for this scanline
                   5651:        useCODE - 1 if the CODE is invalid but it usage has been forced
                   5652:                  by the operator
                   5653:        CODE_ignore_dup - 1 if the CODE is a duplicated use when unique
                   5654:                             CODEs were selected, but the usage has been
                   5655:                             forced by the operator
1.556     weissno  5656:        ID  - student/employee ID
1.423     albertel 5657:        PaperID - if used, the ID number printed on the sheet when the 
                   5658:                  paper was scanned
                   5659:        FirstName - first name from the sheet
                   5660:        LastName  - last name from the sheet
                   5661: 
                   5662:      if just_header was not true these key may also exist
                   5663: 
1.447     foxr     5664:        missingerror - a list of bubble ranges that are considered to be answers
                   5665:                       to a single question that don't have any bubbles filled in.
                   5666:                       Of the form questionnumber:firstbubblenumber:count.
                   5667:        doubleerror  - a list of bubble ranges that are considered to be answers
                   5668:                       to a single question that have more than one bubble filled in.
                   5669:                       Of the form questionnumber::firstbubblenumber:count
                   5670:    
                   5671:                 In the above, count is the number of bubble responses in the
                   5672:                 input line needed to represent the possible answers to the question.
                   5673:                 e.g. a radioresponse with 15 choices in an answer sheet with 10 choices
                   5674:                 per line would have count = 2.
                   5675: 
1.423     albertel 5676:        maxquest     - the number of the last bubble line that was parsed
                   5677: 
                   5678:        (<number> starts at 1)
                   5679:        <number>.answer - zero or more letters representing the selected
                   5680:                          letters from the scanline for the bubble line 
                   5681:                          <number>.
                   5682:                          if blank there was either no bubble or there where
                   5683:                          multiple bubbles, (consult the keys missingerror and
                   5684:                          doubleerror if this is an error condition)
                   5685: 
                   5686: =cut
                   5687: 
1.82      albertel 5688: sub scantron_parse_scanline {
1.423     albertel 5689:     my ($line,$whichline,$scantron_config,$scan_data,$just_header)=@_;
1.470     foxr     5690: 
1.82      albertel 5691:     my %record;
1.550     raeburn  5692:     my $lastpos = $env{'form.scantron_maxbubble'}*$$scantron_config{'Qlength'};
                   5693:     my $questions=substr($line,$$scantron_config{'Qstart'}-1,$lastpos);  # Answers
1.422     foxr     5694:     my $data=substr($line,0,$$scantron_config{'Qstart'}-1);     # earlier stuff
1.278     albertel 5695:     if (!($$scantron_config{'CODElocation'} eq 0 ||
                   5696: 	  $$scantron_config{'CODElocation'} eq 'none')) {
                   5697: 	if ($$scantron_config{'CODElocation'} < 0 ||
                   5698: 	    $$scantron_config{'CODElocation'} eq 'letter' ||
                   5699: 	    $$scantron_config{'CODElocation'} eq 'number') {
1.191     albertel 5700: 	    $record{'scantron.CODE'}=substr($data,
                   5701: 					    $$scantron_config{'CODEstart'}-1,
1.83      albertel 5702: 					    $$scantron_config{'CODElength'});
1.191     albertel 5703: 	    if (&scan_data($scan_data,"$whichline.useCODE")) {
                   5704: 		$record{'scantron.useCODE'}=1;
                   5705: 	    }
1.192     albertel 5706: 	    if (&scan_data($scan_data,"$whichline.CODE_ignore_dup")) {
                   5707: 		$record{'scantron.CODE_ignore_dup'}=1;
                   5708: 	    }
1.82      albertel 5709: 	} else {
                   5710: 	    #FIXME interpret first N questions
                   5711: 	}
                   5712:     }
1.83      albertel 5713:     $record{'scantron.ID'}=substr($data,$$scantron_config{'IDstart'}-1,
                   5714: 				  $$scantron_config{'IDlength'});
1.157     albertel 5715:     $record{'scantron.PaperID'}=
                   5716: 	substr($data,$$scantron_config{'PaperID'}-1,
                   5717: 	       $$scantron_config{'PaperIDlength'});
                   5718:     $record{'scantron.FirstName'}=
                   5719: 	substr($data,$$scantron_config{'FirstName'}-1,
                   5720: 	       $$scantron_config{'FirstNamelength'});
                   5721:     $record{'scantron.LastName'}=
                   5722: 	substr($data,$$scantron_config{'LastName'}-1,
                   5723: 	       $$scantron_config{'LastNamelength'});
1.423     albertel 5724:     if ($just_header) { return \%record; }
1.194     albertel 5725: 
1.82      albertel 5726:     my @alphabet=('A'..'Z');
                   5727:     my $questnum=0;
1.447     foxr     5728:     my $ansnum  =1;		# Multiple 'answer lines'/question.
                   5729: 
1.470     foxr     5730:     chomp($questions);		# Get rid of any trailing \n.
                   5731:     $questions =~ s/\r$//;      # Get rid of trailing \r too (MAC or Win uploads).
                   5732:     while (length($questions)) {
1.447     foxr     5733: 	my $answers_needed = $bubble_lines_per_response{$questnum};
1.503     raeburn  5734:         my $answer_length  = ($$scantron_config{'Qlength'} * $answers_needed)
                   5735:                              || 1;
                   5736:         $questnum++;
                   5737:         my $quest_id = $questnum;
                   5738:         my $currentquest = substr($questions,0,$answer_length);
                   5739:         $questions       = substr($questions,$answer_length);
                   5740:         if (length($currentquest) < $answer_length) { next; }
                   5741: 
                   5742:         if ($subdivided_bubble_lines{$questnum-1} =~ /,/) {
                   5743:             my $subquestnum = 1;
                   5744:             my $subquestions = $currentquest;
                   5745:             my @subanswers_needed = 
                   5746:                 split(/,/,$subdivided_bubble_lines{$questnum-1});  
                   5747:             foreach my $subans (@subanswers_needed) {
                   5748:                 my $subans_length =
                   5749:                     ($$scantron_config{'Qlength'} * $subans)  || 1;
                   5750:                 my $currsubquest = substr($subquestions,0,$subans_length);
                   5751:                 $subquestions   = substr($subquestions,$subans_length);
                   5752:                 $quest_id = "$questnum.$subquestnum";
                   5753:                 if (($$scantron_config{'Qon'} eq 'letter') ||
                   5754:                     ($$scantron_config{'Qon'} eq 'number')) {
                   5755:                     $ansnum = &scantron_validator_lettnum($ansnum, 
                   5756:                         $questnum,$quest_id,$subans,$currsubquest,$whichline,
                   5757:                         \@alphabet,\%record,$scantron_config,$scan_data);
                   5758:                 } else {
                   5759:                     $ansnum = &scantron_validator_positional($ansnum,
                   5760:                         $questnum,$quest_id,$subans,$currsubquest,$whichline,                        \@alphabet,\%record,$scantron_config,$scan_data);
                   5761:                 }
                   5762:                 $subquestnum ++;
                   5763:             }
                   5764:         } else {
                   5765:             if (($$scantron_config{'Qon'} eq 'letter') ||
                   5766:                 ($$scantron_config{'Qon'} eq 'number')) {
                   5767:                 $ansnum = &scantron_validator_lettnum($ansnum,$questnum,
                   5768:                     $quest_id,$answers_needed,$currentquest,$whichline,
                   5769:                     \@alphabet,\%record,$scantron_config,$scan_data);
                   5770:             } else {
                   5771:                 $ansnum = &scantron_validator_positional($ansnum,$questnum,
                   5772:                     $quest_id,$answers_needed,$currentquest,$whichline,
                   5773:                     \@alphabet,\%record,$scantron_config,$scan_data);
                   5774:             }
                   5775:         }
                   5776:     }
                   5777:     $record{'scantron.maxquest'}=$questnum;
                   5778:     return \%record;
                   5779: }
1.447     foxr     5780: 
1.503     raeburn  5781: sub scantron_validator_lettnum {
                   5782:     my ($ansnum,$questnum,$quest_id,$answers_needed,$currquest,$whichline,
                   5783:         $alphabet,$record,$scantron_config,$scan_data) = @_;
                   5784: 
                   5785:     # Qon 'letter' implies for each slot in currquest we have:
                   5786:     #    ? or * for doubles, a letter in A-Z for a bubble, and
                   5787:     #    about anything else (esp. a value of Qoff) for missing
                   5788:     #    bubbles.
                   5789:     #
                   5790:     # Qon 'number' implies each slot gives a digit that indexes the
                   5791:     #    bubbles filled, or Qoff, or a non-number for unbubbled lines,
                   5792:     #    and * or ? for double bubbles on a single line.
                   5793:     #
1.447     foxr     5794: 
1.503     raeburn  5795:     my $matchon;
                   5796:     if ($$scantron_config{'Qon'} eq 'letter') {
                   5797:         $matchon = '[A-Z]';
                   5798:     } elsif ($$scantron_config{'Qon'} eq 'number') {
                   5799:         $matchon = '\d';
                   5800:     }
                   5801:     my $occurrences = 0;
                   5802:     if (($responsetype_per_response{$questnum-1} eq 'essayresponse') ||
                   5803:         ($responsetype_per_response{$questnum-1} eq 'formularesponse') ||
1.510     raeburn  5804:         ($responsetype_per_response{$questnum-1} eq 'stringresponse') ||
                   5805:         ($responsetype_per_response{$questnum-1} eq 'imageresponse') ||
                   5806:         ($responsetype_per_response{$questnum-1} eq 'reactionresponse') ||
                   5807:         ($responsetype_per_response{$questnum-1} eq 'organicresponse')) {
1.503     raeburn  5808:         my @singlelines = split('',$currquest);
                   5809:         foreach my $entry (@singlelines) {
                   5810:             $occurrences = &occurence_count($entry,$matchon);
                   5811:             if ($occurrences > 1) {
                   5812:                 last;
                   5813:             }
                   5814:         } 
                   5815:     } else {
                   5816:         $occurrences = &occurence_count($currquest,$matchon); 
                   5817:     }
                   5818:     if (($currquest =~ /\?/ || $currquest =~ /\*/) || ($occurrences > 1)) {
                   5819:         push(@{$record->{'scantron.doubleerror'}},$quest_id);
                   5820:         for (my $ans=0; $ans<$answers_needed; $ans++) {
                   5821:             my $bubble = substr($currquest,$ans,1);
                   5822:             if ($bubble =~ /$matchon/ ) {
                   5823:                 if ($$scantron_config{'Qon'} eq 'number') {
                   5824:                     if ($bubble == 0) {
                   5825:                         $bubble = 10; 
                   5826:                     }
                   5827:                     $record->{"scantron.$ansnum.answer"} = 
                   5828:                         $alphabet->[$bubble-1];
                   5829:                 } else {
                   5830:                     $record->{"scantron.$ansnum.answer"} = $bubble;
                   5831:                 }
                   5832:             } else {
                   5833:                 $record->{"scantron.$ansnum.answer"}='';
                   5834:             }
                   5835:             $ansnum++;
                   5836:         }
                   5837:     } elsif (!defined($currquest)
                   5838:             || (&occurence_count($currquest, $$scantron_config{'Qoff'}) == length($currquest))
                   5839:             || (&occurence_count($currquest,$matchon) == 0)) {
                   5840:         for (my $ans=0; $ans<$answers_needed; $ans++ ) {
                   5841:             $record->{"scantron.$ansnum.answer"}='';
                   5842:             $ansnum++;
                   5843:         }
                   5844:         if (!&scan_data($scan_data,"$whichline.no_bubble.$quest_id")) {
                   5845:             push(@{$record->{'scantron.missingerror'}},$quest_id);
                   5846:         }
                   5847:     } else {
                   5848:         if ($$scantron_config{'Qon'} eq 'number') {
                   5849:             $currquest = &digits_to_letters($currquest);            
                   5850:         }
                   5851:         for (my $ans=0; $ans<$answers_needed; $ans++) {
                   5852:             my $bubble = substr($currquest,$ans,1);
                   5853:             $record->{"scantron.$ansnum.answer"} = $bubble;
                   5854:             $ansnum++;
                   5855:         }
                   5856:     }
                   5857:     return $ansnum;
                   5858: }
1.447     foxr     5859: 
1.503     raeburn  5860: sub scantron_validator_positional {
                   5861:     my ($ansnum,$questnum,$quest_id,$answers_needed,$currquest,
                   5862:         $whichline,$alphabet,$record,$scantron_config,$scan_data) = @_;
1.447     foxr     5863: 
1.503     raeburn  5864:     # Otherwise there's a positional notation;
                   5865:     # each bubble line requires Qlength items, and there are filled in
                   5866:     # bubbles for each case where there 'Qon' characters.
                   5867:     #
1.447     foxr     5868: 
1.503     raeburn  5869:     my @array=split($$scantron_config{'Qon'},$currquest,-1);
1.447     foxr     5870: 
1.503     raeburn  5871:     # If the split only gives us one element.. the full length of the
                   5872:     # answer string, no bubbles are filled in:
1.447     foxr     5873: 
1.507     raeburn  5874:     if ($answers_needed eq '') {
                   5875:         return;
                   5876:     }
                   5877: 
1.503     raeburn  5878:     if (length($array[0]) eq $$scantron_config{'Qlength'}*$answers_needed) {
                   5879:         for (my $ans=0; $ans<$answers_needed; $ans++ ) {
                   5880:             $record->{"scantron.$ansnum.answer"}='';
                   5881:             $ansnum++;
                   5882:         }
                   5883:         if (!&scan_data($scan_data,"$whichline.no_bubble.$quest_id")) {
                   5884:             push(@{$record->{"scantron.missingerror"}},$quest_id);
                   5885:         }
                   5886:     } elsif (scalar(@array) == 2) {
                   5887:         my $location = length($array[0]);
                   5888:         my $line_num = int($location / $$scantron_config{'Qlength'});
                   5889:         my $bubble   = $alphabet->[$location % $$scantron_config{'Qlength'}];
                   5890:         for (my $ans=0; $ans<$answers_needed; $ans++) {
                   5891:             if ($ans eq $line_num) {
                   5892:                 $record->{"scantron.$ansnum.answer"} = $bubble;
                   5893:             } else {
                   5894:                 $record->{"scantron.$ansnum.answer"} = ' ';
                   5895:             }
                   5896:             $ansnum++;
                   5897:          }
                   5898:     } else {
                   5899:         #  If there's more than one instance of a bubble character
                   5900:         #  That's a double bubble; with positional notation we can
                   5901:         #  record all the bubbles filled in as well as the
                   5902:         #  fact this response consists of multiple bubbles.
                   5903:         #
                   5904:         if (($responsetype_per_response{$questnum-1} eq 'essayresponse') ||
                   5905:             ($responsetype_per_response{$questnum-1} eq 'formularesponse') ||
1.510     raeburn  5906:             ($responsetype_per_response{$questnum-1} eq 'stringresponse') ||
                   5907:             ($responsetype_per_response{$questnum-1} eq 'imageresponse') ||
                   5908:             ($responsetype_per_response{$questnum-1} eq 'reactionresponse') ||
                   5909:             ($responsetype_per_response{$questnum-1} eq 'organicresponse')) {
1.503     raeburn  5910:             my $doubleerror = 0;
                   5911:             while (($currquest >= $$scantron_config{'Qlength'}) && 
                   5912:                    (!$doubleerror)) {
                   5913:                my $currline = substr($currquest,0,$$scantron_config{'Qlength'});
                   5914:                $currquest = substr($currquest,$$scantron_config{'Qlength'});
                   5915:                my @currarray = split($$scantron_config{'Qon'},$currline,-1);
                   5916:                if (length(@currarray) > 2) {
                   5917:                    $doubleerror = 1;
                   5918:                } 
                   5919:             }
                   5920:             if ($doubleerror) {
                   5921:                 push(@{$record->{'scantron.doubleerror'}},$quest_id);
                   5922:             }
                   5923:         } else {
                   5924:             push(@{$record->{'scantron.doubleerror'}},$quest_id);
                   5925:         }
                   5926:         my $item = $ansnum;
                   5927:         for (my $ans=0; $ans<$answers_needed; $ans++) {
                   5928:             $record->{"scantron.$item.answer"} = '';
                   5929:             $item ++;
                   5930:         }
1.447     foxr     5931: 
1.503     raeburn  5932:         my @ans=@array;
                   5933:         my $i=0;
                   5934:         my $increment = 0;
                   5935:         while ($#ans) {
                   5936:             $i+=length($ans[0]) + $increment;
                   5937:             my $line   = int($i/$$scantron_config{'Qlength'} + $ansnum);
                   5938:             my $bubble = $i%$$scantron_config{'Qlength'};
                   5939:             $record->{"scantron.$line.answer"}.=$alphabet->[$bubble];
                   5940:             shift(@ans);
                   5941:             $increment = 1;
                   5942:         }
                   5943:         $ansnum += $answers_needed;
1.82      albertel 5944:     }
1.503     raeburn  5945:     return $ansnum;
1.82      albertel 5946: }
                   5947: 
1.423     albertel 5948: =pod
                   5949: 
                   5950: =item scantron_add_delay
                   5951: 
                   5952:    Adds an error message that occurred during the grading phase to a
                   5953:    queue of messages to be shown after grading pass is complete
                   5954: 
                   5955:  Arguments:
1.424     albertel 5956:    $delayqueue  - arrary ref of hash ref of error messages
1.423     albertel 5957:    $scanline    - the scanline that caused the error
                   5958:    $errormesage - the error message
                   5959:    $errorcode   - a numeric code for the error
                   5960: 
                   5961:  Side Effects:
1.424     albertel 5962:    updates the $delayqueue to have a new hash ref of the error
1.423     albertel 5963: 
                   5964: =cut
                   5965: 
1.82      albertel 5966: sub scantron_add_delay {
1.140     albertel 5967:     my ($delayqueue,$scanline,$errormessage,$errorcode)=@_;
                   5968:     push(@$delayqueue,
                   5969: 	 {'line' => $scanline, 'emsg' => $errormessage,
                   5970: 	  'ecode' => $errorcode }
                   5971: 	 );
1.82      albertel 5972: }
                   5973: 
1.423     albertel 5974: =pod
                   5975: 
                   5976: =item scantron_find_student
                   5977: 
1.424     albertel 5978:    Finds the username for the current scanline
                   5979: 
                   5980:   Arguments:
                   5981:    $scantron_record - hash result from scantron_parse_scanline
                   5982:    $scan_data       - hash of correction information 
                   5983:                       (see &scantron_getfile() form more information)
                   5984:    $idmap           - hash from &username_to_idmap()
                   5985:    $line            - number of current scanline
                   5986:  
                   5987:   Returns:
                   5988:    Either 'username:domain' or undef if unknown
                   5989: 
1.423     albertel 5990: =cut
                   5991: 
1.82      albertel 5992: sub scantron_find_student {
1.157     albertel 5993:     my ($scantron_record,$scan_data,$idmap,$line)=@_;
1.83      albertel 5994:     my $scanID=$$scantron_record{'scantron.ID'};
1.157     albertel 5995:     if ($scanID =~ /^\s*$/) {
                   5996:  	return &scan_data($scan_data,"$line.user");
                   5997:     }
1.83      albertel 5998:     foreach my $id (keys(%$idmap)) {
1.157     albertel 5999:  	if (lc($id) eq lc($scanID)) {
                   6000:  	    return $$idmap{$id};
                   6001:  	}
1.83      albertel 6002:     }
                   6003:     return undef;
                   6004: }
                   6005: 
1.423     albertel 6006: =pod
                   6007: 
                   6008: =item scantron_filter
                   6009: 
1.424     albertel 6010:    Filter sub for lonnavmaps, filters out hidden resources if ignore
                   6011:    hidden resources was selected
                   6012: 
1.423     albertel 6013: =cut
                   6014: 
1.83      albertel 6015: sub scantron_filter {
                   6016:     my ($curres)=@_;
1.331     albertel 6017: 
                   6018:     if (ref($curres) && $curres->is_problem()) {
                   6019: 	# if the user has asked to not have either hidden
                   6020: 	# or 'randomout' controlled resources to be graded
                   6021: 	# don't include them
                   6022: 	if ($env{'form.scantron_options_hidden'} eq 'ignore_hidden'
                   6023: 	    && $curres->randomout) {
                   6024: 	    return 0;
                   6025: 	}
1.83      albertel 6026: 	return 1;
                   6027:     }
                   6028:     return 0;
1.82      albertel 6029: }
                   6030: 
1.423     albertel 6031: =pod
                   6032: 
                   6033: =item scantron_process_corrections
                   6034: 
1.424     albertel 6035:    Gets correction information out of submitted form data and corrects
                   6036:    the scanline
                   6037: 
1.423     albertel 6038: =cut
                   6039: 
1.157     albertel 6040: sub scantron_process_corrections {
                   6041:     my ($r) = @_;
1.257     albertel 6042:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.157     albertel 6043:     my ($scanlines,$scan_data)=&scantron_getfile();
                   6044:     my $classlist=&Apache::loncoursedata::get_classlist();
1.257     albertel 6045:     my $which=$env{'form.scantron_line'};
1.200     albertel 6046:     my $line=&scantron_get_line($scanlines,$scan_data,$which);
1.157     albertel 6047:     my ($skip,$err,$errmsg);
1.257     albertel 6048:     if ($env{'form.scantron_skip_record'}) {
1.157     albertel 6049: 	$skip=1;
1.257     albertel 6050:     } elsif ($env{'form.scantron_corrections'} =~ /^(duplicate|incorrect)ID$/) {
                   6051: 	my $newstudent=$env{'form.scantron_username'}.':'.
                   6052: 	    $env{'form.scantron_domain'};
1.157     albertel 6053: 	my $newid=$classlist->{$newstudent}->[&Apache::loncoursedata::CL_ID];
                   6054: 	($line,$err,$errmsg)=
                   6055: 	    &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,$which,
                   6056: 				     'ID',{'newid'=>$newid,
1.257     albertel 6057: 				    'username'=>$env{'form.scantron_username'},
                   6058: 				    'domain'=>$env{'form.scantron_domain'}});
                   6059:     } elsif ($env{'form.scantron_corrections'} =~ /^(duplicate|incorrect)CODE$/) {
                   6060: 	my $resolution=$env{'form.scantron_CODE_resolution'};
1.190     albertel 6061: 	my $newCODE;
1.192     albertel 6062: 	my %args;
1.190     albertel 6063: 	if      ($resolution eq 'use_unfound') {
1.191     albertel 6064: 	    $newCODE='use_unfound';
1.190     albertel 6065: 	} elsif ($resolution eq 'use_found') {
1.257     albertel 6066: 	    $newCODE=$env{'form.scantron_CODE_selectedvalue'};
1.190     albertel 6067: 	} elsif ($resolution eq 'use_typed') {
1.257     albertel 6068: 	    $newCODE=$env{'form.scantron_CODE_newvalue'};
1.194     albertel 6069: 	} elsif ($resolution =~ /^use_closest_(\d+)/) {
1.257     albertel 6070: 	    $newCODE=$env{"form.scantron_CODE_closest_$1"};
1.190     albertel 6071: 	}
1.257     albertel 6072: 	if ($env{'form.scantron_corrections'} eq 'duplicateCODE') {
1.192     albertel 6073: 	    $args{'CODE_ignore_dup'}=1;
                   6074: 	}
                   6075: 	$args{'CODE'}=$newCODE;
1.186     albertel 6076: 	($line,$err,$errmsg)=
                   6077: 	    &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,$which,
1.192     albertel 6078: 				     'CODE',\%args);
1.257     albertel 6079:     } elsif ($env{'form.scantron_corrections'} =~ /^(missing|double)bubble$/) {
                   6080: 	foreach my $question (split(',',$env{'form.scantron_questions'})) {
1.157     albertel 6081: 	    ($line,$err,$errmsg)=
                   6082: 		&scantron_fixup_scanline(\%scantron_config,$scan_data,$line,
                   6083: 					 $which,'answer',
                   6084: 					 { 'question'=>$question,
1.503     raeburn  6085: 		      		   'response'=>$env{"form.scantron_correct_Q_$question"},
                   6086:                                    'questionnum'=>$env{"form.scantron_questionnum_Q_$question"}});
1.157     albertel 6087: 	    if ($err) { last; }
                   6088: 	}
                   6089:     }
                   6090:     if ($err) {
1.398     albertel 6091: 	$r->print("<span class=\"LC_warning\">Unable to accept last correction, an error occurred :$errmsg:</span>");
1.157     albertel 6092:     } else {
1.200     albertel 6093: 	&scantron_put_line($scanlines,$scan_data,$which,$line,$skip);
1.157     albertel 6094: 	&scantron_putfile($scanlines,$scan_data);
                   6095:     }
                   6096: }
                   6097: 
1.423     albertel 6098: =pod
                   6099: 
                   6100: =item reset_skipping_status
                   6101: 
1.424     albertel 6102:    Forgets the current set of remember skipped scanlines (and thus
                   6103:    reverts back to considering all lines in the
                   6104:    scantron_skipped_<filename> file)
                   6105: 
1.423     albertel 6106: =cut
                   6107: 
1.200     albertel 6108: sub reset_skipping_status {
                   6109:     my ($scanlines,$scan_data)=&scantron_getfile();
                   6110:     &scan_data($scan_data,'remember_skipping',undef,1);
                   6111:     &scantron_putfile(undef,$scan_data);
                   6112: }
                   6113: 
1.423     albertel 6114: =pod
                   6115: 
                   6116: =item start_skipping
                   6117: 
1.424     albertel 6118:    Marks a scanline to be skipped. 
                   6119: 
1.423     albertel 6120: =cut
                   6121: 
1.376     albertel 6122: sub start_skipping {
1.200     albertel 6123:     my ($scan_data,$i)=@_;
                   6124:     my %remembered=split(':',&scan_data($scan_data,'remember_skipping'));
1.376     albertel 6125:     if ($env{'form.scantron_options_redo'} =~ /^redo_/) {
                   6126: 	$remembered{$i}=2;
                   6127:     } else {
                   6128: 	$remembered{$i}=1;
                   6129:     }
1.200     albertel 6130:     &scan_data($scan_data,'remember_skipping',join(':',%remembered));
                   6131: }
                   6132: 
1.423     albertel 6133: =pod
                   6134: 
                   6135: =item should_be_skipped
                   6136: 
1.424     albertel 6137:    Checks whether a scanline should be skipped.
                   6138: 
1.423     albertel 6139: =cut
                   6140: 
1.200     albertel 6141: sub should_be_skipped {
1.376     albertel 6142:     my ($scanlines,$scan_data,$i)=@_;
1.257     albertel 6143:     if ($env{'form.scantron_options_redo'} !~ /^redo_/) {
1.200     albertel 6144: 	# not redoing old skips
1.376     albertel 6145: 	if ($scanlines->{'skipped'}[$i]) { return 1; }
1.200     albertel 6146: 	return 0;
                   6147:     }
                   6148:     my %remembered=split(':',&scan_data($scan_data,'remember_skipping'));
1.376     albertel 6149: 
                   6150:     if (exists($remembered{$i}) && $remembered{$i} != 2 ) {
                   6151: 	return 0;
                   6152:     }
1.200     albertel 6153:     return 1;
                   6154: }
                   6155: 
1.423     albertel 6156: =pod
                   6157: 
                   6158: =item remember_current_skipped
                   6159: 
1.424     albertel 6160:    Discovers what scanlines are in the scantron_skipped_<filename>
                   6161:    file and remembers them into scan_data for later use.
                   6162: 
1.423     albertel 6163: =cut
                   6164: 
1.200     albertel 6165: sub remember_current_skipped {
                   6166:     my ($scanlines,$scan_data)=&scantron_getfile();
                   6167:     my %to_remember;
                   6168:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
                   6169: 	if ($scanlines->{'skipped'}[$i]) {
                   6170: 	    $to_remember{$i}=1;
                   6171: 	}
                   6172:     }
1.376     albertel 6173: 
1.200     albertel 6174:     &scan_data($scan_data,'remember_skipping',join(':',%to_remember));
                   6175:     &scantron_putfile(undef,$scan_data);
                   6176: }
                   6177: 
1.423     albertel 6178: =pod
                   6179: 
                   6180: =item check_for_error
                   6181: 
1.424     albertel 6182:     Checks if there was an error when attempting to remove a specific
                   6183:     scantron_.. bubble sheet data file. Prints out an error if
                   6184:     something went wrong.
                   6185: 
1.423     albertel 6186: =cut
                   6187: 
1.200     albertel 6188: sub check_for_error {
                   6189:     my ($r,$result)=@_;
                   6190:     if ($result ne 'ok' && $result ne 'not_found' ) {
1.492     albertel 6191: 	$r->print(&mt("An error occurred ([_1]) when trying to remove the existing corrections.",$result));
1.200     albertel 6192:     }
                   6193: }
1.157     albertel 6194: 
1.423     albertel 6195: =pod
                   6196: 
                   6197: =item scantron_warning_screen
                   6198: 
1.424     albertel 6199:    Interstitial screen to make sure the operator has selected the
                   6200:    correct options before we start the validation phase.
                   6201: 
1.423     albertel 6202: =cut
                   6203: 
1.203     albertel 6204: sub scantron_warning_screen {
                   6205:     my ($button_text)=@_;
1.257     albertel 6206:     my $title=&Apache::lonnet::gettitle($env{'form.selectpage'});
1.284     albertel 6207:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.373     albertel 6208:     my $CODElist;
1.284     albertel 6209:     if ($scantron_config{'CODElocation'} &&
                   6210: 	$scantron_config{'CODEstart'} &&
                   6211: 	$scantron_config{'CODElength'}) {
                   6212: 	$CODElist=$env{'form.scantron_CODElist'};
1.398     albertel 6213: 	if ($env{'form.scantron_CODElist'} eq '') { $CODElist='<span class="LC_warning">None</span>'; }
1.284     albertel 6214: 	$CODElist=
1.492     albertel 6215: 	    '<tr><td><b>'.&mt('List of CODES to validate against:').'</b></td><td><tt>'.
1.373     albertel 6216: 	    $env{'form.scantron_CODElist'}.'</tt></td></tr>';
1.284     albertel 6217:     }
1.492     albertel 6218:     return ('
1.203     albertel 6219: <p>
1.492     albertel 6220: <span class="LC_warning">
                   6221: '.&mt('Please double check the information below before clicking on \'[_1]\'',&mt($button_text)).'</span>
1.203     albertel 6222: </p>
                   6223: <table>
1.492     albertel 6224: <tr><td><b>'.&mt('Sequence to be Graded:').'</b></td><td>'.$title.'</td></tr>
                   6225: <tr><td><b>'.&mt('Data File that will be used:').'</b></td><td><tt>'.$env{'form.scantron_selectfile'}.'</tt></td></tr>
                   6226: '.$CODElist.'
1.203     albertel 6227: </table>
                   6228: <br />
1.492     albertel 6229: <p> '.&mt('If this information is correct, please click on \'[_1]\'.',&mt($button_text)).'</p>
                   6230: <p> '.&mt('If something is incorrect, please click the \'Grading Menu\' button to start over.').'</p>
1.203     albertel 6231: 
                   6232: <br />
1.492     albertel 6233: ');
1.203     albertel 6234: }
                   6235: 
1.423     albertel 6236: =pod
                   6237: 
                   6238: =item scantron_do_warning
                   6239: 
1.424     albertel 6240:    Check if the operator has picked something for all required
                   6241:    fields. Error out if something is missing.
                   6242: 
1.423     albertel 6243: =cut
                   6244: 
1.203     albertel 6245: sub scantron_do_warning {
                   6246:     my ($r)=@_;
1.324     albertel 6247:     my ($symb)=&get_symb($r);
1.203     albertel 6248:     if (!$symb) {return '';}
1.324     albertel 6249:     my $default_form_data=&defaultFormData($symb);
1.203     albertel 6250:     $r->print(&scantron_form_start().$default_form_data);
1.257     albertel 6251:     if ( $env{'form.selectpage'} eq '' ||
                   6252: 	 $env{'form.scantron_selectfile'} eq '' ||
                   6253: 	 $env{'form.scantron_format'} eq '' ) {
1.492     albertel 6254: 	$r->print("<p>".&mt('You have forgetten to specify some information. Please go Back and try again.')."</p>");
1.257     albertel 6255: 	if ( $env{'form.selectpage'} eq '') {
1.492     albertel 6256: 	    $r->print('<p><span class="LC_error">'.&mt('You have not selected a Sequence to grade').'</span></p>');
1.237     albertel 6257: 	} 
1.257     albertel 6258: 	if ( $env{'form.scantron_selectfile'} eq '') {
1.492     albertel 6259: 	    $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 6260: 	} 
1.257     albertel 6261: 	if ( $env{'form.scantron_format'} eq '') {
1.492     albertel 6262: 	    $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 6263: 	} 
                   6264:     } else {
1.265     www      6265: 	my $warning=&scantron_warning_screen('Grading: Validate Records');
1.492     albertel 6266: 	$r->print('
                   6267: '.$warning.'
                   6268: <input type="submit" name="submit" value="'.&mt('Grading: Validate Records').'" />
1.203     albertel 6269: <input type="hidden" name="command" value="scantron_validate" />
1.492     albertel 6270: ');
1.237     albertel 6271:     }
1.352     albertel 6272:     $r->print("</form><br />".&show_grading_menu_form($symb));
1.203     albertel 6273:     return '';
                   6274: }
                   6275: 
1.423     albertel 6276: =pod
                   6277: 
                   6278: =item scantron_form_start
                   6279: 
1.424     albertel 6280:     html hidden input for remembering all selected grading options
                   6281: 
1.423     albertel 6282: =cut
                   6283: 
1.203     albertel 6284: sub scantron_form_start {
                   6285:     my ($max_bubble)=@_;
                   6286:     my $result= <<SCANTRONFORM;
                   6287: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantronupload">
1.257     albertel 6288:   <input type="hidden" name="selectpage" value="$env{'form.selectpage'}" />
                   6289:   <input type="hidden" name="scantron_format" value="$env{'form.scantron_format'}" />
                   6290:   <input type="hidden" name="scantron_selectfile" value="$env{'form.scantron_selectfile'}" />
1.218     albertel 6291:   <input type="hidden" name="scantron_maxbubble" value="$max_bubble" />
1.257     albertel 6292:   <input type="hidden" name="scantron_CODElist" value="$env{'form.scantron_CODElist'}" />
                   6293:   <input type="hidden" name="scantron_CODEunique" value="$env{'form.scantron_CODEunique'}" />
                   6294:   <input type="hidden" name="scantron_options_redo" value="$env{'form.scantron_options_redo'}" />
                   6295:   <input type="hidden" name="scantron_options_ignore" value="$env{'form.scantron_options_ignore'}" />
1.331     albertel 6296:   <input type="hidden" name="scantron_options_hidden" value="$env{'form.scantron_options_hidden'}" />
1.203     albertel 6297: SCANTRONFORM
1.447     foxr     6298: 
                   6299:   my $line = 0;
                   6300:     while (defined($env{"form.scantron.bubblelines.$line"})) {
                   6301:        my $chunk =
                   6302: 	   '<input type="hidden" name="scantron.bubblelines.'.$line.'" value="'.$env{"form.scantron.bubblelines.$line"}.'" />'."\n";
1.448     foxr     6303:        $chunk .=
                   6304: 	   '<input type="hidden" name="scantron.first_bubble_line.'.$line.'" value="'.$env{"form.scantron.first_bubble_line.$line"}.'" />'."\n";
1.503     raeburn  6305:        $chunk .= 
                   6306:            '<input type="hidden" name="scantron.sub_bubblelines.'.$line.'" value="'.$env{"form.scantron.sub_bubblelines.$line"}.'" />'."\n";
1.504     raeburn  6307:        $chunk .=
                   6308:            '<input type="hidden" name="scantron.responsetype.'.$line.'" value="'.$env{"form.scantron.responsetype.$line"}.'" />'."\n";
1.447     foxr     6309:        $result .= $chunk;
                   6310:        $line++;
                   6311:    }
1.203     albertel 6312:     return $result;
                   6313: }
                   6314: 
1.423     albertel 6315: =pod
                   6316: 
                   6317: =item scantron_validate_file
                   6318: 
1.424     albertel 6319:     Dispatch routine for doing validation of a bubble sheet data file.
                   6320: 
                   6321:     Also processes any necessary information resets that need to
                   6322:     occur before validation begins (ignore previous corrections,
                   6323:     restarting the skipped records processing)
                   6324: 
1.423     albertel 6325: =cut
                   6326: 
1.157     albertel 6327: sub scantron_validate_file {
                   6328:     my ($r) = @_;
1.324     albertel 6329:     my ($symb)=&get_symb($r);
1.157     albertel 6330:     if (!$symb) {return '';}
1.324     albertel 6331:     my $default_form_data=&defaultFormData($symb);
1.200     albertel 6332:     
                   6333:     # do the detection of only doing skipped records first befroe we delete
1.424     albertel 6334:     # them when doing the corrections reset
1.257     albertel 6335:     if ($env{'form.scantron_options_redo'} ne 'redo_skipped_ready') {
1.200     albertel 6336: 	&reset_skipping_status();
                   6337:     }
1.257     albertel 6338:     if ($env{'form.scantron_options_redo'} eq 'redo_skipped') {
1.200     albertel 6339: 	&remember_current_skipped();
1.257     albertel 6340: 	$env{'form.scantron_options_redo'}='redo_skipped_ready';
1.200     albertel 6341:     }
                   6342: 
1.257     albertel 6343:     if ($env{'form.scantron_options_ignore'} eq 'ignore_corrections') {
1.200     albertel 6344: 	&check_for_error($r,&scantron_remove_file('corrected'));
                   6345: 	&check_for_error($r,&scantron_remove_file('skipped'));
                   6346: 	&check_for_error($r,&scantron_remove_scan_data());
1.257     albertel 6347: 	$env{'form.scantron_options_ignore'}='done';
1.192     albertel 6348:     }
1.200     albertel 6349: 
1.257     albertel 6350:     if ($env{'form.scantron_corrections'}) {
1.157     albertel 6351: 	&scantron_process_corrections($r);
                   6352:     }
1.503     raeburn  6353:     $r->print('<p>'.&mt('Gathering necessary information.').'</p>');$r->rflush();
1.157     albertel 6354:     #get the student pick code ready
                   6355:     $r->print(&Apache::loncommon::studentbrowser_javascript());
1.582     raeburn  6356:     my $nav_error;
                   6357:     my $max_bubble=&scantron_get_maxbubble(\$nav_error);
                   6358:     if ($nav_error) {
                   6359:         $r->print(&navmap_errormsg());
                   6360:         return '';
                   6361:     }
1.203     albertel 6362:     my $result=&scantron_form_start($max_bubble).$default_form_data;
1.157     albertel 6363:     $r->print($result);
                   6364:     
1.334     albertel 6365:     my @validate_phases=( 'sequence',
                   6366: 			  'ID',
1.157     albertel 6367: 			  'CODE',
                   6368: 			  'doublebubble',
                   6369: 			  'missingbubbles');
1.257     albertel 6370:     if (!$env{'form.validatepass'}) {
                   6371: 	$env{'form.validatepass'} = 0;
1.157     albertel 6372:     }
1.257     albertel 6373:     my $currentphase=$env{'form.validatepass'};
1.157     albertel 6374: 
1.448     foxr     6375: 
1.157     albertel 6376:     my $stop=0;
                   6377:     while (!$stop && $currentphase < scalar(@validate_phases)) {
1.503     raeburn  6378: 	$r->print(&mt('Validating '.$validate_phases[$currentphase]).'<br />');
1.157     albertel 6379: 	$r->rflush();
                   6380: 	my $which="scantron_validate_".$validate_phases[$currentphase];
                   6381: 	{
                   6382: 	    no strict 'refs';
                   6383: 	    ($stop,$currentphase)=&$which($r,$currentphase);
                   6384: 	}
                   6385:     }
                   6386:     if (!$stop) {
1.203     albertel 6387: 	my $warning=&scantron_warning_screen('Start Grading');
1.542     raeburn  6388: 	$r->print(&mt('Validation process complete.').'<br />'.
                   6389:                   $warning.
                   6390:                   &mt('Perform verification for each student after storage of submissions?').
                   6391:                   '&nbsp;<span class="LC_nobreak"><label>'.
                   6392:                   '<input type="radio" name="verifyrecord" value="1" />'.&mt('Yes').'</label>'.
                   6393:                   ('&nbsp;'x3).'<label>'.
                   6394:                   '<input type="radio" name="verifyrecord" value="0" checked="checked" />'.&mt('No').
                   6395:                   '</label></span><br />'.
                   6396:                   &mt('Grading will take longer if you use verification.').'<br />'.
1.572     www      6397:                   &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  6398:                   '<input type="submit" name="submit" value="'.&mt('Start Grading').'" />'.
                   6399:                   '<input type="hidden" name="command" value="scantron_process" />'."\n");
1.157     albertel 6400:     } else {
                   6401: 	$r->print('<input type="hidden" name="command" value="scantron_validate" />');
                   6402: 	$r->print("<input type='hidden' name='validatepass' value='".$currentphase."' />");
                   6403:     }
                   6404:     if ($stop) {
1.334     albertel 6405: 	if ($validate_phases[$currentphase] eq 'sequence') {
1.539     riegler  6406: 	    $r->print('<input type="submit" name="submit" value="'.&mt('Ignore').' &rarr; " />');
1.492     albertel 6407: 	    $r->print(' '.&mt('this error').' <br />');
1.334     albertel 6408: 
1.492     albertel 6409: 	    $r->print(" <p>".&mt("Or click the 'Grading Menu' button to start over.")."</p>");
1.334     albertel 6410: 	} else {
1.503     raeburn  6411:             if ($validate_phases[$currentphase] eq 'doublebubble' || $validate_phases[$currentphase] eq 'missingbubbles') {
1.539     riegler  6412: 	        $r->print('<input type="button" name="submitbutton" value="'.&mt('Continue').' &rarr;" onclick="javascript:verify_bubble_radio(this.form)" />');
1.503     raeburn  6413:             } else {
1.539     riegler  6414:                 $r->print('<input type="submit" name="submit" value="'.&mt('Continue').' &rarr;" />');
1.503     raeburn  6415:             }
1.492     albertel 6416: 	    $r->print(' '.&mt('using corrected info').' <br />');
                   6417: 	    $r->print("<input type='submit' value='".&mt("Skip")."' name='scantron_skip_record' />");
                   6418: 	    $r->print(" ".&mt("this scanline saving it for later."));
1.334     albertel 6419: 	}
1.157     albertel 6420:     }
1.352     albertel 6421:     $r->print(" </form><br />".&show_grading_menu_form($symb));
1.157     albertel 6422:     return '';
                   6423: }
                   6424: 
1.423     albertel 6425: 
                   6426: =pod
                   6427: 
                   6428: =item scantron_remove_file
                   6429: 
1.424     albertel 6430:    Removes the requested bubble sheet data file, makes sure that
                   6431:    scantron_original_<filename> is never removed
                   6432: 
                   6433: 
1.423     albertel 6434: =cut
                   6435: 
1.200     albertel 6436: sub scantron_remove_file {
1.192     albertel 6437:     my ($which)=@_;
1.257     albertel 6438:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   6439:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.192     albertel 6440:     my $file='scantron_';
1.200     albertel 6441:     if ($which eq 'corrected' || $which eq 'skipped') {
                   6442: 	$file.=$which.'_';
1.192     albertel 6443:     } else {
                   6444: 	return 'refused';
                   6445:     }
1.257     albertel 6446:     $file.=$env{'form.scantron_selectfile'};
1.200     albertel 6447:     return &Apache::lonnet::removeuserfile($cname,$cdom,$file);
                   6448: }
                   6449: 
1.423     albertel 6450: 
                   6451: =pod
                   6452: 
                   6453: =item scantron_remove_scan_data
                   6454: 
1.424     albertel 6455:    Removes all scan_data correction for the requested bubble sheet
                   6456:    data file.  (In the case that both the are doing skipped records we need
                   6457:    to remember the old skipped lines for the time being so that element
                   6458:    persists for a while.)
                   6459: 
1.423     albertel 6460: =cut
                   6461: 
1.200     albertel 6462: sub scantron_remove_scan_data {
1.257     albertel 6463:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   6464:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.192     albertel 6465:     my @keys=&Apache::lonnet::getkeys('nohist_scantrondata',$cdom,$cname);
                   6466:     my @todelete;
1.257     albertel 6467:     my $filename=$env{'form.scantron_selectfile'};
1.192     albertel 6468:     foreach my $key (@keys) {
                   6469: 	if ($key=~/^\Q$filename\E_/) {
1.257     albertel 6470: 	    if ($env{'form.scantron_options_redo'} eq 'redo_skipped_ready' &&
1.200     albertel 6471: 		$key=~/remember_skipping/) {
                   6472: 		next;
                   6473: 	    }
1.192     albertel 6474: 	    push(@todelete,$key);
                   6475: 	}
                   6476:     }
1.200     albertel 6477:     my $result;
1.192     albertel 6478:     if (@todelete) {
1.491     albertel 6479: 	$result = &Apache::lonnet::del('nohist_scantrondata',
                   6480: 				       \@todelete,$cdom,$cname);
                   6481:     } else {
                   6482: 	$result = 'ok';
1.192     albertel 6483:     }
                   6484:     return $result;
                   6485: }
                   6486: 
1.423     albertel 6487: 
                   6488: =pod
                   6489: 
                   6490: =item scantron_getfile
                   6491: 
1.424     albertel 6492:     Fetches the requested bubble sheet data file (all 3 versions), and
                   6493:     the scan_data hash
                   6494:   
                   6495:   Arguments:
                   6496:     None
                   6497: 
                   6498:   Returns:
                   6499:     2 hash references
                   6500: 
                   6501:      - first one has 
                   6502:          orig      -
                   6503:          corrected -
                   6504:          skipped   -  each of which points to an array ref of the specified
                   6505:                       file broken up into individual lines
                   6506:          count     - number of scanlines
                   6507:  
                   6508:      - second is the scan_data hash possible keys are
1.425     albertel 6509:        ($number refers to scanline numbered $number and thus the key affects
                   6510:         only that scanline
                   6511:         $bubline refers to the specific bubble line element and the aspects
                   6512:         refers to that specific bubble line element)
                   6513: 
                   6514:        $number.user - username:domain to use
                   6515:        $number.CODE_ignore_dup 
                   6516:                     - ignore the duplicate CODE error 
                   6517:        $number.useCODE
                   6518:                     - use the CODE in the scanline as is
                   6519:        $number.no_bubble.$bubline
                   6520:                     - it is valid that there is no bubbled in bubble
                   6521:                       at $number $bubline
                   6522:        remember_skipping
                   6523:                     - a frozen hash containing keys of $number and values
                   6524:                       of either 
                   6525:                         1 - we are on a 'do skipped records pass' and plan
                   6526:                             on processing this line
                   6527:                         2 - we are on a 'do skipped records pass' and this
                   6528:                             scanline has been marked to skip yet again
1.424     albertel 6529: 
1.423     albertel 6530: =cut
                   6531: 
1.157     albertel 6532: sub scantron_getfile {
1.200     albertel 6533:     #FIXME really would prefer a scantron directory
1.257     albertel 6534:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   6535:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.157     albertel 6536:     my $lines;
                   6537:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
1.257     albertel 6538: 		       'scantron_orig_'.$env{'form.scantron_selectfile'});
1.157     albertel 6539:     my %scanlines;
                   6540:     $scanlines{'orig'}=[(split("\n",$lines,-1))];
                   6541:     my $temp=$scanlines{'orig'};
                   6542:     $scanlines{'count'}=$#$temp;
                   6543: 
                   6544:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
1.257     albertel 6545: 		       'scantron_corrected_'.$env{'form.scantron_selectfile'});
1.157     albertel 6546:     if ($lines eq '-1') {
                   6547: 	$scanlines{'corrected'}=[];
                   6548:     } else {
                   6549: 	$scanlines{'corrected'}=[(split("\n",$lines,-1))];
                   6550:     }
                   6551:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
1.257     albertel 6552: 		       'scantron_skipped_'.$env{'form.scantron_selectfile'});
1.157     albertel 6553:     if ($lines eq '-1') {
                   6554: 	$scanlines{'skipped'}=[];
                   6555:     } else {
                   6556: 	$scanlines{'skipped'}=[(split("\n",$lines,-1))];
                   6557:     }
1.175     albertel 6558:     my @tmp=&Apache::lonnet::dump('nohist_scantrondata',$cdom,$cname);
1.157     albertel 6559:     if ($tmp[0] =~ /^(error:|no_such_host)/) { @tmp=(); }
                   6560:     my %scan_data = @tmp;
                   6561:     return (\%scanlines,\%scan_data);
                   6562: }
                   6563: 
1.423     albertel 6564: =pod
                   6565: 
                   6566: =item lonnet_putfile
                   6567: 
1.424     albertel 6568:    Wrapper routine to call &Apache::lonnet::finishuserfileupload
                   6569: 
                   6570:  Arguments:
                   6571:    $contents - data to store
                   6572:    $filename - filename to store $contents into
                   6573: 
                   6574:  Returns:
                   6575:    result value from &Apache::lonnet::finishuserfileupload
                   6576: 
1.423     albertel 6577: =cut
                   6578: 
1.157     albertel 6579: sub lonnet_putfile {
                   6580:     my ($contents,$filename)=@_;
1.257     albertel 6581:     my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   6582:     my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   6583:     $env{'form.sillywaytopassafilearound'}=$contents;
1.275     albertel 6584:     &Apache::lonnet::finishuserfileupload($docuname,$docudom,'sillywaytopassafilearound',$filename);
1.157     albertel 6585: 
                   6586: }
                   6587: 
1.423     albertel 6588: =pod
                   6589: 
                   6590: =item scantron_putfile
                   6591: 
1.424     albertel 6592:     Stores the current version of the bubble sheet data files, and the
                   6593:     scan_data hash. (Does not modify the original version only the
                   6594:     corrected and skipped versions.
                   6595: 
                   6596:  Arguments:
                   6597:     $scanlines - hash ref that looks like the first return value from
                   6598:                  &scantron_getfile()
                   6599:     $scan_data - hash ref that looks like the second return value from
                   6600:                  &scantron_getfile()
                   6601: 
1.423     albertel 6602: =cut
                   6603: 
1.157     albertel 6604: sub scantron_putfile {
                   6605:     my ($scanlines,$scan_data) = @_;
1.200     albertel 6606:     #FIXME really would prefer a scantron directory
1.257     albertel 6607:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   6608:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.200     albertel 6609:     if ($scanlines) {
                   6610: 	my $prefix='scantron_';
1.157     albertel 6611: # no need to update orig, shouldn't change
                   6612: #   &lonnet_putfile(join("\n",@{$scanlines->{'orig'}}),$prefix.'orig_'.
1.257     albertel 6613: #		    $env{'form.scantron_selectfile'});
1.200     albertel 6614: 	&lonnet_putfile(join("\n",@{$scanlines->{'corrected'}}),
                   6615: 			$prefix.'corrected_'.
1.257     albertel 6616: 			$env{'form.scantron_selectfile'});
1.200     albertel 6617: 	&lonnet_putfile(join("\n",@{$scanlines->{'skipped'}}),
                   6618: 			$prefix.'skipped_'.
1.257     albertel 6619: 			$env{'form.scantron_selectfile'});
1.200     albertel 6620:     }
1.175     albertel 6621:     &Apache::lonnet::put('nohist_scantrondata',$scan_data,$cdom,$cname);
1.157     albertel 6622: }
                   6623: 
1.423     albertel 6624: =pod
                   6625: 
                   6626: =item scantron_get_line
                   6627: 
1.424     albertel 6628:    Returns the correct version of the scanline
                   6629: 
                   6630:  Arguments:
                   6631:     $scanlines - hash ref that looks like the first return value from
                   6632:                  &scantron_getfile()
                   6633:     $scan_data - hash ref that looks like the second return value from
                   6634:                  &scantron_getfile()
                   6635:     $i         - number of the requested line (starts at 0)
                   6636: 
                   6637:  Returns:
                   6638:    A scanline, (either the original or the corrected one if it
                   6639:    exists), or undef if the requested scanline should be
                   6640:    skipped. (Either because it's an skipped scanline, or it's an
                   6641:    unskipped scanline and we are not doing a 'do skipped scanlines'
                   6642:    pass.
                   6643: 
1.423     albertel 6644: =cut
                   6645: 
1.157     albertel 6646: sub scantron_get_line {
1.200     albertel 6647:     my ($scanlines,$scan_data,$i)=@_;
1.376     albertel 6648:     if (&should_be_skipped($scanlines,$scan_data,$i)) { return undef; }
                   6649:     #if ($scanlines->{'skipped'}[$i]) { return undef; }
1.157     albertel 6650:     if ($scanlines->{'corrected'}[$i]) {return $scanlines->{'corrected'}[$i];}
                   6651:     return $scanlines->{'orig'}[$i]; 
                   6652: }
                   6653: 
1.423     albertel 6654: =pod
                   6655: 
                   6656: =item scantron_todo_count
                   6657: 
1.424     albertel 6658:     Counts the number of scanlines that need processing.
                   6659: 
                   6660:  Arguments:
                   6661:     $scanlines - hash ref that looks like the first return value from
                   6662:                  &scantron_getfile()
                   6663:     $scan_data - hash ref that looks like the second return value from
                   6664:                  &scantron_getfile()
                   6665: 
                   6666:  Returns:
                   6667:     $count - number of scanlines to process
                   6668: 
1.423     albertel 6669: =cut
                   6670: 
1.200     albertel 6671: sub get_todo_count {
                   6672:     my ($scanlines,$scan_data)=@_;
                   6673:     my $count=0;
                   6674:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
                   6675: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
                   6676: 	if ($line=~/^[\s\cz]*$/) { next; }
                   6677: 	$count++;
                   6678:     }
                   6679:     return $count;
                   6680: }
                   6681: 
1.423     albertel 6682: =pod
                   6683: 
                   6684: =item scantron_put_line
                   6685: 
1.424     albertel 6686:     Updates the 'corrected' or 'skipped' versions of the bubble sheet
                   6687:     data file.
                   6688: 
                   6689:  Arguments:
                   6690:     $scanlines - hash ref that looks like the first return value from
                   6691:                  &scantron_getfile()
                   6692:     $scan_data - hash ref that looks like the second return value from
                   6693:                  &scantron_getfile()
                   6694:     $i         - line number to update
                   6695:     $newline   - contents of the updated scanline
                   6696:     $skip      - if true make the line for skipping and update the
                   6697:                  'skipped' file
                   6698: 
1.423     albertel 6699: =cut
                   6700: 
1.157     albertel 6701: sub scantron_put_line {
1.200     albertel 6702:     my ($scanlines,$scan_data,$i,$newline,$skip)=@_;
1.157     albertel 6703:     if ($skip) {
                   6704: 	$scanlines->{'skipped'}[$i]=$newline;
1.376     albertel 6705: 	&start_skipping($scan_data,$i);
1.157     albertel 6706: 	return;
                   6707:     }
                   6708:     $scanlines->{'corrected'}[$i]=$newline;
                   6709: }
                   6710: 
1.423     albertel 6711: =pod
                   6712: 
                   6713: =item scantron_clear_skip
                   6714: 
1.424     albertel 6715:    Remove a line from the 'skipped' file
                   6716: 
                   6717:  Arguments:
                   6718:     $scanlines - hash ref that looks like the first return value from
                   6719:                  &scantron_getfile()
                   6720:     $scan_data - hash ref that looks like the second return value from
                   6721:                  &scantron_getfile()
                   6722:     $i         - line number to update
                   6723: 
1.423     albertel 6724: =cut
                   6725: 
1.376     albertel 6726: sub scantron_clear_skip {
                   6727:     my ($scanlines,$scan_data,$i)=@_;
                   6728:     if (exists($scanlines->{'skipped'}[$i])) {
                   6729: 	undef($scanlines->{'skipped'}[$i]);
                   6730: 	return 1;
                   6731:     }
                   6732:     return 0;
                   6733: }
                   6734: 
1.423     albertel 6735: =pod
                   6736: 
                   6737: =item scantron_filter_not_exam
                   6738: 
1.424     albertel 6739:    Filter routine used by &Apache::lonnavmaps::retrieveResources(), to
                   6740:    filter out resources that are not marked as 'exam' mode
                   6741: 
1.423     albertel 6742: =cut
                   6743: 
1.334     albertel 6744: sub scantron_filter_not_exam {
                   6745:     my ($curres)=@_;
                   6746:     
                   6747:     if (ref($curres) && $curres->is_problem() && !$curres->is_exam()) {
                   6748: 	# if the user has asked to not have either hidden
                   6749: 	# or 'randomout' controlled resources to be graded
                   6750: 	# don't include them
                   6751: 	if ($env{'form.scantron_options_hidden'} eq 'ignore_hidden'
                   6752: 	    && $curres->randomout) {
                   6753: 	    return 0;
                   6754: 	}
                   6755: 	return 1;
                   6756:     }
                   6757:     return 0;
                   6758: }
                   6759: 
1.423     albertel 6760: =pod
                   6761: 
                   6762: =item scantron_validate_sequence
                   6763: 
1.424     albertel 6764:     Validates the selected sequence, checking for resource that are
                   6765:     not set to exam mode.
                   6766: 
1.423     albertel 6767: =cut
                   6768: 
1.334     albertel 6769: sub scantron_validate_sequence {
                   6770:     my ($r,$currentphase) = @_;
                   6771: 
                   6772:     my $navmap=Apache::lonnavmaps::navmap->new();
1.582     raeburn  6773:     unless (ref($navmap)) {
                   6774:         $r->print(&navmap_errormsg());
                   6775:         return (1,$currentphase);
                   6776:     }
1.334     albertel 6777:     my (undef,undef,$sequence)=
                   6778: 	&Apache::lonnet::decode_symb($env{'form.selectpage'});
                   6779: 
                   6780:     my $map=$navmap->getResourceByUrl($sequence);
                   6781: 
                   6782:     $r->print('<input type="hidden" name="validate_sequence_exam"
                   6783:                                     value="ignore" />');
                   6784:     if ($env{'form.validate_sequence_exam'} ne 'ignore') {
                   6785: 	my @resources=
                   6786: 	    $navmap->retrieveResources($map,\&scantron_filter_not_exam,1,0);
                   6787: 	if (@resources) {
1.357     banghart 6788: 	    $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 6789: 	    return (1,$currentphase);
                   6790: 	}
                   6791:     }
                   6792: 
                   6793:     return (0,$currentphase+1);
                   6794: }
                   6795: 
1.423     albertel 6796: 
                   6797: 
1.157     albertel 6798: sub scantron_validate_ID {
                   6799:     my ($r,$currentphase) = @_;
                   6800:     
                   6801:     #get student info
                   6802:     my $classlist=&Apache::loncoursedata::get_classlist();
                   6803:     my %idmap=&username_to_idmap($classlist);
                   6804: 
                   6805:     #get scantron line setup
1.257     albertel 6806:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.157     albertel 6807:     my ($scanlines,$scan_data)=&scantron_getfile();
1.582     raeburn  6808: 
                   6809:     my $nav_error;
                   6810:     &scantron_get_maxbubble(\$nav_error); # parse needs the bubble_lines.. array.
                   6811:     if ($nav_error) {
                   6812:         $r->print(&navmap_errormsg());
                   6813:         return(1,$currentphase);
                   6814:     }
1.157     albertel 6815: 
                   6816:     my %found=('ids'=>{},'usernames'=>{});
                   6817:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
1.200     albertel 6818: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.157     albertel 6819: 	if ($line=~/^[\s\cz]*$/) { next; }
                   6820: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
                   6821: 						 $scan_data);
                   6822: 	my $id=$$scan_record{'scantron.ID'};
                   6823: 	my $found;
                   6824: 	foreach my $checkid (keys(%idmap)) {
                   6825: 	    if (lc($checkid) eq lc($id)) { $found=$checkid;last; }
                   6826: 	}
                   6827: 	if ($found) {
                   6828: 	    my $username=$idmap{$found};
                   6829: 	    if ($found{'ids'}{$found}) {
                   6830: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
                   6831: 					 $line,'duplicateID',$found);
1.194     albertel 6832: 		return(1,$currentphase);
1.157     albertel 6833: 	    } elsif ($found{'usernames'}{$username}) {
                   6834: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
                   6835: 					 $line,'duplicateID',$username);
1.194     albertel 6836: 		return(1,$currentphase);
1.157     albertel 6837: 	    }
1.186     albertel 6838: 	    #FIXME store away line we previously saw the ID on to use above
1.157     albertel 6839: 	    $found{'ids'}{$found}++;
                   6840: 	    $found{'usernames'}{$username}++;
                   6841: 	} else {
                   6842: 	    if ($id =~ /^\s*$/) {
1.158     albertel 6843: 		my $username=&scan_data($scan_data,"$i.user");
1.157     albertel 6844: 		if (defined($username) && $found{'usernames'}{$username}) {
                   6845: 		    &scantron_get_correction($r,$i,$scan_record,
                   6846: 					     \%scantron_config,
                   6847: 					     $line,'duplicateID',$username);
1.194     albertel 6848: 		    return(1,$currentphase);
1.157     albertel 6849: 		} elsif (!defined($username)) {
                   6850: 		    &scantron_get_correction($r,$i,$scan_record,
                   6851: 					     \%scantron_config,
                   6852: 					     $line,'incorrectID');
1.194     albertel 6853: 		    return(1,$currentphase);
1.157     albertel 6854: 		}
                   6855: 		$found{'usernames'}{$username}++;
                   6856: 	    } else {
                   6857: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
                   6858: 					 $line,'incorrectID');
1.194     albertel 6859: 		return(1,$currentphase);
1.157     albertel 6860: 	    }
                   6861: 	}
                   6862:     }
                   6863: 
                   6864:     return (0,$currentphase+1);
                   6865: }
                   6866: 
1.423     albertel 6867: 
1.157     albertel 6868: sub scantron_get_correction {
                   6869:     my ($r,$i,$scan_record,$scan_config,$line,$error,$arg)=@_;
1.454     banghart 6870: #FIXME in the case of a duplicated ID the previous line, probably need
1.157     albertel 6871: #to show both the current line and the previous one and allow skipping
                   6872: #the previous one or the current one
                   6873: 
1.333     albertel 6874:     if ( $$scan_record{'scantron.PaperID'} =~ /\S/) {
1.492     albertel 6875: 	$r->print("<p>".&mt("<b>An error was detected ($error)</b>".
                   6876: 			    " for PaperID <tt>[_1]</tt>",
                   6877: 			    $$scan_record{'scantron.PaperID'})."</p> \n");
1.157     albertel 6878:     } else {
1.492     albertel 6879: 	$r->print("<p>".&mt("<b>An error was detected ($error)</b>".
                   6880: 			    " in scanline [_1] <pre>[_2]</pre>",
                   6881: 			    $i,$line)."</p> \n");
                   6882:     }
                   6883:     my $message="<p>".&mt("The ID on the form is  <tt>[_1]</tt><br />".
                   6884: 			  "The name on the paper is [_2],[_3]",
                   6885: 			  $$scan_record{'scantron.ID'},
                   6886: 			  $$scan_record{'scantron.LastName'},
                   6887: 			  $$scan_record{'scantron.FirstName'})."</p>";
1.242     albertel 6888: 
1.157     albertel 6889:     $r->print('<input type="hidden" name="scantron_corrections" value="'.$error.'" />'."\n");
                   6890:     $r->print('<input type="hidden" name="scantron_line" value="'.$i.'" />'."\n");
1.503     raeburn  6891:                            # Array populated for doublebubble or
                   6892:     my @lines_to_correct;  # missingbubble errors to build javascript
                   6893:                            # to validate radio button checking   
                   6894: 
1.157     albertel 6895:     if ($error =~ /ID$/) {
1.186     albertel 6896: 	if ($error eq 'incorrectID') {
1.492     albertel 6897: 	    $r->print("<p>".&mt("The encoded ID is not in the classlist").
                   6898: 		      "</p>\n");
1.157     albertel 6899: 	} elsif ($error eq 'duplicateID') {
1.492     albertel 6900: 	    $r->print("<p>".&mt("The encoded ID has also been used by a previous paper [_1]",$arg)."</p>\n");
1.157     albertel 6901: 	}
1.242     albertel 6902: 	$r->print($message);
1.492     albertel 6903: 	$r->print("<p>".&mt("How should I handle this?")." <br /> \n");
1.157     albertel 6904: 	$r->print("\n<ul><li> ");
                   6905: 	#FIXME it would be nice if this sent back the user ID and
                   6906: 	#could do partial userID matches
                   6907: 	$r->print(&Apache::loncommon::selectstudent_link('scantronupload',
                   6908: 				       'scantron_username','scantron_domain'));
                   6909: 	$r->print(": <input type='text' name='scantron_username' value='' />");
                   6910: 	$r->print("\n@".
1.257     albertel 6911: 		 &Apache::loncommon::select_dom_form($env{'request.role.domain'},'scantron_domain'));
1.157     albertel 6912: 
                   6913: 	$r->print('</li>');
1.186     albertel 6914:     } elsif ($error =~ /CODE$/) {
                   6915: 	if ($error eq 'incorrectCODE') {
1.492     albertel 6916: 	    $r->print("<p>".&mt("The encoded CODE is not in the list of possible CODEs.")."</p>\n");
1.186     albertel 6917: 	} elsif ($error eq 'duplicateCODE') {
1.492     albertel 6918: 	    $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 6919: 	}
1.492     albertel 6920: 	$r->print("<p>".&mt("The CODE on the form is  <tt>'[_1]'</tt>",
                   6921: 			    $$scan_record{'scantron.CODE'})."<br />\n");
1.242     albertel 6922: 	$r->print($message);
1.492     albertel 6923: 	$r->print("<p>".&mt("How should I handle this?")." <br /> \n");
1.187     albertel 6924: 	$r->print("\n<br /> ");
1.194     albertel 6925: 	my $i=0;
1.273     albertel 6926: 	if ($error eq 'incorrectCODE' 
                   6927: 	    && $$scan_record{'scantron.CODE'}=~/\S/ ) {
1.194     albertel 6928: 	    my ($max,$closest)=&scantron_get_closely_matching_CODEs($arg,$$scan_record{'scantron.CODE'});
1.278     albertel 6929: 	    if ($closest > 0) {
                   6930: 		foreach my $testcode (@{$closest}) {
                   6931: 		    my $checked='';
1.569     bisitz   6932: 		    if (!$i) { $checked=' checked="checked"'; }
1.492     albertel 6933: 		    $r->print("
                   6934:    <label>
1.569     bisitz   6935:        <input type='radio' name='scantron_CODE_resolution' value='use_closest_$i'$checked />
1.492     albertel 6936:        ".&mt("Use the similar CODE [_1] instead.",
                   6937: 	    "<b><tt>".$testcode."</tt></b>")."
                   6938:     </label>
                   6939:     <input type='hidden' name='scantron_CODE_closest_$i' value='$testcode' />");
1.278     albertel 6940: 		    $r->print("\n<br />");
                   6941: 		    $i++;
                   6942: 		}
1.194     albertel 6943: 	    }
                   6944: 	}
1.273     albertel 6945: 	if ($$scan_record{'scantron.CODE'}=~/\S/ ) {
1.569     bisitz   6946: 	    my $checked; if (!$i) { $checked=' checked="checked"'; }
1.492     albertel 6947: 	    $r->print("
                   6948:     <label>
1.569     bisitz   6949:         <input type='radio' name='scantron_CODE_resolution' value='use_unfound'$checked />
1.492     albertel 6950:        ".&mt("Use the CODE [_1] that is was on the paper, ignoring the error.",
                   6951: 	     "<b><tt>".$$scan_record{'scantron.CODE'}."</tt></b>")."
                   6952:     </label>");
1.273     albertel 6953: 	    $r->print("\n<br />");
                   6954: 	}
1.194     albertel 6955: 
1.597     wenzelju 6956: 	$r->print(&Apache::lonhtmlcommon::scripttag(<<ENDSCRIPT));
1.188     albertel 6957: function change_radio(field) {
1.190     albertel 6958:     var slct=document.scantronupload.scantron_CODE_resolution;
1.188     albertel 6959:     var i;
                   6960:     for (i=0;i<slct.length;i++) {
                   6961:         if (slct[i].value==field) { slct[i].checked=true; }
                   6962:     }
                   6963: }
                   6964: ENDSCRIPT
1.187     albertel 6965: 	my $href="/adm/pickcode?".
1.359     www      6966: 	   "form=".&escape("scantronupload").
                   6967: 	   "&scantron_format=".&escape($env{'form.scantron_format'}).
                   6968: 	   "&scantron_CODElist=".&escape($env{'form.scantron_CODElist'}).
                   6969: 	   "&curCODE=".&escape($$scan_record{'scantron.CODE'}).
                   6970: 	   "&scantron_selectfile=".&escape($env{'form.scantron_selectfile'});
1.332     albertel 6971: 	if ($env{'form.scantron_CODElist'} =~ /\S/) { 
1.492     albertel 6972: 	    $r->print("
                   6973:     <label>
                   6974:        <input type='radio' name='scantron_CODE_resolution' value='use_found' />
                   6975:        ".&mt("[_1]Select[_2] a CODE from the list of all CODEs and use it.",
                   6976: 	     "<a target='_blank' href='$href'>","</a>")."
                   6977:     </label> 
1.558     bisitz   6978:     ".&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 6979: 	    $r->print("\n<br />");
                   6980: 	}
1.492     albertel 6981: 	$r->print("
                   6982:     <label>
                   6983:        <input type='radio' name='scantron_CODE_resolution' value='use_typed' />
                   6984:        ".&mt("Use [_1] as the CODE.",
                   6985: 	     "</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 6986: 	$r->print("\n<br /><br />");
1.157     albertel 6987:     } elsif ($error eq 'doublebubble') {
1.503     raeburn  6988: 	$r->print("<p>".&mt("There have been multiple bubbles scanned for some question(s)")."</p>\n");
1.497     foxr     6989: 
                   6990: 	# The form field scantron_questions is acutally a list of line numbers.
                   6991: 	# represented by this form so:
                   6992: 
                   6993: 	my $line_list = &questions_to_line_list($arg);
                   6994: 
1.157     albertel 6995: 	$r->print('<input type="hidden" name="scantron_questions" value="'.
1.497     foxr     6996: 		  $line_list.'" />');
1.242     albertel 6997: 	$r->print($message);
1.492     albertel 6998: 	$r->print("<p>".&mt("Please indicate which bubble should be used for grading")."</p>");
1.157     albertel 6999: 	foreach my $question (@{$arg}) {
1.503     raeburn  7000: 	    my @linenums = &prompt_for_corrections($r,$question,$scan_config,
                   7001:                                                    $scan_record, $error);
1.524     raeburn  7002:             push(@lines_to_correct,@linenums);
1.157     albertel 7003: 	}
1.503     raeburn  7004:         $r->print(&verify_bubbles_checked(@lines_to_correct));
1.157     albertel 7005:     } elsif ($error eq 'missingbubble') {
1.492     albertel 7006: 	$r->print("<p>".&mt("There have been <b>no</b> bubbles scanned for some question(s)")."</p>\n");
1.242     albertel 7007: 	$r->print($message);
1.492     albertel 7008: 	$r->print("<p>".&mt("Please indicate which bubble should be used for grading.")."</p>");
1.503     raeburn  7009: 	$r->print(&mt("Some questions have no scanned bubbles.")."\n");
1.497     foxr     7010: 
1.503     raeburn  7011: 	# The form field scantron_questions is actually a list of line numbers not
1.497     foxr     7012: 	# a list of question numbers. Therefore:
                   7013: 	#
                   7014: 	
                   7015: 	my $line_list = &questions_to_line_list($arg);
                   7016: 
1.157     albertel 7017: 	$r->print('<input type="hidden" name="scantron_questions" value="'.
1.497     foxr     7018: 		  $line_list.'" />');
1.157     albertel 7019: 	foreach my $question (@{$arg}) {
1.503     raeburn  7020: 	    my @linenums = &prompt_for_corrections($r,$question,$scan_config,
                   7021:                                                    $scan_record, $error);
1.524     raeburn  7022:             push(@lines_to_correct,@linenums);
1.157     albertel 7023: 	}
1.503     raeburn  7024:         $r->print(&verify_bubbles_checked(@lines_to_correct));
1.157     albertel 7025:     } else {
                   7026: 	$r->print("\n<ul>");
                   7027:     }
                   7028:     $r->print("\n</li></ul>");
1.497     foxr     7029: }
                   7030: 
1.503     raeburn  7031: sub verify_bubbles_checked {
                   7032:     my (@ansnums) = @_;
                   7033:     my $ansnumstr = join('","',@ansnums);
                   7034:     my $warning = &mt("A bubble or 'No bubble' selection has not been made for one or more lines.");
1.597     wenzelju 7035:     my $output = &Apache::lonhtmlcommon::scripttag((<<ENDSCRIPT));
1.503     raeburn  7036: function verify_bubble_radio(form) {
                   7037:     var ansnumArray = new Array ("$ansnumstr");
                   7038:     var need_bubble_count = 0;
                   7039:     for (var i=0; i<ansnumArray.length; i++) {
                   7040:         if (form.elements["scantron_correct_Q_"+ansnumArray[i]].length > 1) {
                   7041:             var bubble_picked = 0; 
                   7042:             for (var j=0; j<form.elements["scantron_correct_Q_"+ansnumArray[i]].length; j++) {
                   7043:                 if (form.elements["scantron_correct_Q_"+ansnumArray[i]][j].checked == true) {
                   7044:                     bubble_picked = 1;
                   7045:                 }
                   7046:             }
                   7047:             if (bubble_picked == 0) {
                   7048:                 need_bubble_count ++;
                   7049:             }
                   7050:         }
                   7051:     }
                   7052:     if (need_bubble_count) {
                   7053:         alert("$warning");
                   7054:         return;
                   7055:     }
                   7056:     form.submit(); 
                   7057: }
                   7058: ENDSCRIPT
                   7059:     return $output;
                   7060: }
                   7061: 
1.497     foxr     7062: =pod
                   7063: 
                   7064: =item  questions_to_line_list
1.157     albertel 7065: 
1.497     foxr     7066: Converts a list of questions into a string of comma separated
                   7067: line numbers in the answer sheet used by the questions.  This is
                   7068: used to fill in the scantron_questions form field.
                   7069: 
                   7070:   Arguments:
                   7071:      questions    - Reference to an array of questions.
                   7072: 
                   7073: =cut
                   7074: 
                   7075: 
                   7076: sub questions_to_line_list {
                   7077:     my ($questions) = @_;
                   7078:     my @lines;
                   7079: 
1.503     raeburn  7080:     foreach my $item (@{$questions}) {
                   7081:         my $question = $item;
                   7082:         my ($first,$count,$last);
                   7083:         if ($item =~ /^(\d+)\.(\d+)$/) {
                   7084:             $question = $1;
                   7085:             my $subquestion = $2;
                   7086:             $first = $first_bubble_line{$question-1} + 1;
                   7087:             my @subans = split(/,/,$subdivided_bubble_lines{$question-1});
                   7088:             my $subcount = 1;
                   7089:             while ($subcount<$subquestion) {
                   7090:                 $first += $subans[$subcount-1];
                   7091:                 $subcount ++;
                   7092:             }
                   7093:             $count = $subans[$subquestion-1];
                   7094:         } else {
                   7095: 	    $first   = $first_bubble_line{$question-1} + 1;
                   7096: 	    $count   = $bubble_lines_per_response{$question-1};
                   7097:         }
1.506     raeburn  7098:         $last = $first+$count-1;
1.503     raeburn  7099:         push(@lines, ($first..$last));
1.497     foxr     7100:     }
                   7101:     return join(',', @lines);
                   7102: }
                   7103: 
                   7104: =pod 
                   7105: 
                   7106: =item prompt_for_corrections
                   7107: 
                   7108: Prompts for a potentially multiline correction to the
                   7109: user's bubbling (factors out common code from scantron_get_correction
                   7110: for multi and missing bubble cases).
                   7111: 
                   7112:  Arguments:
                   7113:    $r           - Apache request object.
                   7114:    $question    - The question number to prompt for.
                   7115:    $scan_config - The scantron file configuration hash.
                   7116:    $scan_record - Reference to the hash that has the the parsed scanlines.
1.503     raeburn  7117:    $error       - Type of error
1.497     foxr     7118: 
                   7119:  Implicit inputs:
                   7120:    %bubble_lines_per_response   - Starting line numbers for each question.
                   7121:                                   Numbered from 0 (but question numbers are from
                   7122:                                   1.
                   7123:    %first_bubble_line           - Starting bubble line for each question.
1.509     raeburn  7124:    %subdivided_bubble_lines     - optionresponse, matchresponse and rankresponse 
                   7125:                                   type problems render as separate sub-questions, 
1.503     raeburn  7126:                                   in exam mode. This hash contains a 
                   7127:                                   comma-separated list of the lines per 
                   7128:                                   sub-question.
1.510     raeburn  7129:    %responsetype_per_response   - essayresponse, formularesponse,
                   7130:                                   stringresponse, imageresponse, reactionresponse,
                   7131:                                   and organicresponse type problem parts can have
1.503     raeburn  7132:                                   multiple lines per response if the weight
                   7133:                                   assigned exceeds 10.  In this case, only
                   7134:                                   one bubble per line is permitted, but more 
                   7135:                                   than one line might contain bubbles, e.g.
                   7136:                                   bubbling of: line 1 - J, line 2 - J, 
                   7137:                                   line 3 - B would assign 22 points.  
1.497     foxr     7138: 
                   7139: =cut
                   7140: 
                   7141: sub prompt_for_corrections {
1.503     raeburn  7142:     my ($r, $question, $scan_config, $scan_record, $error) = @_;
                   7143:     my ($current_line,$lines);
                   7144:     my @linenums;
                   7145:     my $questionnum = $question;
                   7146:     if ($question =~ /^(\d+)\.(\d+)$/) {
                   7147:         $question = $1;
                   7148:         $current_line = $first_bubble_line{$question-1} + 1 ;
                   7149:         my $subquestion = $2;
                   7150:         my @subans = split(/,/,$subdivided_bubble_lines{$question-1});
                   7151:         my $subcount = 1;
                   7152:         while ($subcount<$subquestion) {
                   7153:             $current_line += $subans[$subcount-1];
                   7154:             $subcount ++;
                   7155:         }
                   7156:         $lines = $subans[$subquestion-1];
                   7157:     } else {
                   7158:         $current_line = $first_bubble_line{$question-1} + 1 ;
                   7159:         $lines        = $bubble_lines_per_response{$question-1};
                   7160:     }
1.497     foxr     7161:     if ($lines > 1) {
1.503     raeburn  7162:         $r->print(&mt('The group of bubble lines below responds to a single question.').'<br />');
                   7163:         if (($responsetype_per_response{$question-1} eq 'essayresponse') ||
                   7164:             ($responsetype_per_response{$question-1} eq 'formularesponse') ||
1.510     raeburn  7165:             ($responsetype_per_response{$question-1} eq 'stringresponse') ||
                   7166:             ($responsetype_per_response{$question-1} eq 'imageresponse') ||
                   7167:             ($responsetype_per_response{$question-1} eq 'reactionresponse') ||
                   7168:             ($responsetype_per_response{$question-1} eq 'organicresponse')) {
1.572     www      7169:             $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  7170:         } else {
                   7171:             $r->print(&mt("Select at most one bubble in a single line and select 'No Bubble' in all the other lines. ")."<br />");
                   7172:         }
1.497     foxr     7173:     }
                   7174:     for (my $i =0; $i < $lines; $i++) {
1.503     raeburn  7175:         my $selected = $$scan_record{"scantron.$current_line.answer"};
                   7176: 	&scantron_bubble_selector($r,$scan_config,$current_line, 
                   7177: 	        		  $questionnum,$error,split('', $selected));
1.524     raeburn  7178:         push(@linenums,$current_line);
1.497     foxr     7179: 	$current_line++;
                   7180:     }
                   7181:     if ($lines > 1) {
                   7182: 	$r->print("<hr /><br />");
                   7183:     }
1.503     raeburn  7184:     return @linenums;
1.157     albertel 7185: }
1.423     albertel 7186: 
                   7187: =pod
                   7188: 
                   7189: =item scantron_bubble_selector
                   7190:   
                   7191:    Generates the html radiobuttons to correct a single bubble line
1.424     albertel 7192:    possibly showing the existing the selected bubbles if known
1.423     albertel 7193: 
                   7194:  Arguments:
                   7195:     $r           - Apache request object
                   7196:     $scan_config - hash from &get_scantron_config()
1.497     foxr     7197:     $line        - Number of the line being displayed.
1.503     raeburn  7198:     $questionnum - Question number (may include subquestion)
                   7199:     $error       - Type of error.
1.497     foxr     7200:     @selected    - Array of bubbles picked on this line.
1.423     albertel 7201: 
                   7202: =cut
                   7203: 
1.157     albertel 7204: sub scantron_bubble_selector {
1.503     raeburn  7205:     my ($r,$scan_config,$line,$questionnum,$error,@selected)=@_;
1.157     albertel 7206:     my $max=$$scan_config{'Qlength'};
1.274     albertel 7207: 
                   7208:     my $scmode=$$scan_config{'Qon'};
                   7209:     if ($scmode eq 'number' || $scmode eq 'letter') { $max=10; }	     
                   7210: 
1.157     albertel 7211:     my @alphabet=('A'..'Z');
1.503     raeburn  7212:     $r->print(&Apache::loncommon::start_data_table().
                   7213:               &Apache::loncommon::start_data_table_row());
                   7214:     $r->print('<td rowspan="2" class="LC_leftcol_header">'.$line.'</td>');
1.497     foxr     7215:     for (my $i=0;$i<$max+1;$i++) {
                   7216: 	$r->print("\n".'<td align="center">');
                   7217: 	if ($selected[0] eq $alphabet[$i]) { $r->print('X'); shift(@selected) }
                   7218: 	else { $r->print('&nbsp;'); }
                   7219: 	$r->print('</td>');
                   7220:     }
1.503     raeburn  7221:     $r->print(&Apache::loncommon::end_data_table_row().
                   7222:               &Apache::loncommon::start_data_table_row());
1.497     foxr     7223:     for (my $i=0;$i<$max;$i++) {
                   7224: 	$r->print("\n".
                   7225: 		  '<td><label><input type="radio" name="scantron_correct_Q_'.
                   7226: 		  $line.'" value="'.$i.'" />'.$alphabet[$i]."</label></td>");
                   7227:     }
1.503     raeburn  7228:     my $nobub_checked = ' ';
                   7229:     if ($error eq 'missingbubble') {
                   7230:         $nobub_checked = ' checked = "checked" ';
                   7231:     }
                   7232:     $r->print("\n".'<td><label><input type="radio" name="scantron_correct_Q_'.
                   7233: 	      $line.'" value="none"'.$nobub_checked.'/>'.&mt('No bubble').
                   7234:               '</label>'."\n".'<input type="hidden" name="scantron_questionnum_Q_'.
                   7235:               $line.'" value="'.$questionnum.'" /></td>');
                   7236:     $r->print(&Apache::loncommon::end_data_table_row().
                   7237:               &Apache::loncommon::end_data_table());
1.157     albertel 7238: }
                   7239: 
1.423     albertel 7240: =pod
                   7241: 
                   7242: =item num_matches
                   7243: 
1.424     albertel 7244:    Counts the number of characters that are the same between the two arguments.
                   7245: 
                   7246:  Arguments:
                   7247:    $orig - CODE from the scanline
                   7248:    $code - CODE to match against
                   7249: 
                   7250:  Returns:
                   7251:    $count - integer count of the number of same characters between the
                   7252:             two arguments
                   7253: 
1.423     albertel 7254: =cut
                   7255: 
1.194     albertel 7256: sub num_matches {
                   7257:     my ($orig,$code) = @_;
                   7258:     my @code=split(//,$code);
                   7259:     my @orig=split(//,$orig);
                   7260:     my $same=0;
                   7261:     for (my $i=0;$i<scalar(@code);$i++) {
                   7262: 	if ($code[$i] eq $orig[$i]) { $same++; }
                   7263:     }
                   7264:     return $same;
                   7265: }
                   7266: 
1.423     albertel 7267: =pod
                   7268: 
                   7269: =item scantron_get_closely_matching_CODEs
                   7270: 
1.424     albertel 7271:    Cycles through all CODEs and finds the set that has the greatest
                   7272:    number of same characters as the provided CODE
                   7273: 
                   7274:  Arguments:
                   7275:    $allcodes - hash ref returned by &get_codes()
                   7276:    $CODE     - CODE from the current scanline
                   7277: 
                   7278:  Returns:
                   7279:    2 element list
                   7280:     - first elements is number of how closely matching the best fit is 
                   7281:       (5 means best set has 5 matching characters)
                   7282:     - second element is an arrary ref containing the set of valid CODEs
                   7283:       that best fit the passed in CODE
                   7284: 
1.423     albertel 7285: =cut
                   7286: 
1.194     albertel 7287: sub scantron_get_closely_matching_CODEs {
                   7288:     my ($allcodes,$CODE)=@_;
                   7289:     my @CODEs;
                   7290:     foreach my $testcode (sort(keys(%{$allcodes}))) {
                   7291: 	push(@{$CODEs[&num_matches($CODE,$testcode)]},$testcode);
                   7292:     }
                   7293: 
                   7294:     return ($#CODEs,$CODEs[-1]);
                   7295: }
                   7296: 
1.423     albertel 7297: =pod
                   7298: 
                   7299: =item get_codes
                   7300: 
1.424     albertel 7301:    Builds a hash which has keys of all of the valid CODEs from the selected
                   7302:    set of remembered CODEs.
                   7303: 
                   7304:  Arguments:
                   7305:   $old_name - name of the set of remembered CODEs
                   7306:   $cdom     - domain of the course
                   7307:   $cnum     - internal course name
                   7308: 
                   7309:  Returns:
                   7310:   %allcodes - keys are the valid CODEs, values are all 1
                   7311: 
1.423     albertel 7312: =cut
                   7313: 
1.194     albertel 7314: sub get_codes {
1.280     foxr     7315:     my ($old_name, $cdom, $cnum) = @_;
                   7316:     if (!$old_name) {
                   7317: 	$old_name=$env{'form.scantron_CODElist'};
                   7318:     }
                   7319:     if (!$cdom) {
                   7320: 	$cdom =$env{'course.'.$env{'request.course.id'}.'.domain'};
                   7321:     }
                   7322:     if (!$cnum) {
                   7323: 	$cnum =$env{'course.'.$env{'request.course.id'}.'.num'};
                   7324:     }
1.278     albertel 7325:     my %result=&Apache::lonnet::get('CODEs',[$old_name,"type\0$old_name"],
                   7326: 				    $cdom,$cnum);
                   7327:     my %allcodes;
                   7328:     if ($result{"type\0$old_name"} eq 'number') {
                   7329: 	%allcodes=map {($_,1)} split(',',$result{$old_name});
                   7330:     } else {
                   7331: 	%allcodes=map {(&Apache::lonprintout::num_to_letters($_),1)} split(',',$result{$old_name});
                   7332:     }
1.194     albertel 7333:     return %allcodes;
                   7334: }
                   7335: 
1.423     albertel 7336: =pod
                   7337: 
                   7338: =item scantron_validate_CODE
                   7339: 
1.424     albertel 7340:    Validates all scanlines in the selected file to not have any
                   7341:    invalid or underspecified CODEs and that none of the codes are
                   7342:    duplicated if this was requested.
                   7343: 
1.423     albertel 7344: =cut
                   7345: 
1.157     albertel 7346: sub scantron_validate_CODE {
                   7347:     my ($r,$currentphase) = @_;
1.257     albertel 7348:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.186     albertel 7349:     if ($scantron_config{'CODElocation'} &&
                   7350: 	$scantron_config{'CODEstart'} &&
                   7351: 	$scantron_config{'CODElength'}) {
1.257     albertel 7352: 	if (!defined($env{'form.scantron_CODElist'})) {
1.186     albertel 7353: 	    &FIXME_blow_up()
                   7354: 	}
                   7355:     } else {
                   7356: 	return (0,$currentphase+1);
                   7357:     }
                   7358:     
                   7359:     my %usedCODEs;
                   7360: 
1.194     albertel 7361:     my %allcodes=&get_codes();
1.186     albertel 7362: 
1.582     raeburn  7363:     my $nav_error;
                   7364:     &scantron_get_maxbubble(\$nav_error); # parse needs the lines per response array.
                   7365:     if ($nav_error) {
                   7366:         $r->print(&navmap_errormsg());
                   7367:         return(1,$currentphase);
                   7368:     }
1.447     foxr     7369: 
1.186     albertel 7370:     my ($scanlines,$scan_data)=&scantron_getfile();
                   7371:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
1.200     albertel 7372: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.186     albertel 7373: 	if ($line=~/^[\s\cz]*$/) { next; }
                   7374: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
                   7375: 						 $scan_data);
                   7376: 	my $CODE=$$scan_record{'scantron.CODE'};
                   7377: 	my $error=0;
1.224     albertel 7378: 	if (!&Apache::lonnet::validCODE($CODE)) {
                   7379: 	    &scantron_get_correction($r,$i,$scan_record,
                   7380: 				     \%scantron_config,
                   7381: 				     $line,'incorrectCODE',\%allcodes);
                   7382: 	    return(1,$currentphase);
                   7383: 	}
1.221     albertel 7384: 	if (%allcodes && !exists($allcodes{$CODE}) 
                   7385: 	    && !$$scan_record{'scantron.useCODE'}) {
1.186     albertel 7386: 	    &scantron_get_correction($r,$i,$scan_record,
                   7387: 				     \%scantron_config,
1.194     albertel 7388: 				     $line,'incorrectCODE',\%allcodes);
                   7389: 	    return(1,$currentphase);
1.186     albertel 7390: 	}
1.214     albertel 7391: 	if (exists($usedCODEs{$CODE}) 
1.257     albertel 7392: 	    && $env{'form.scantron_CODEunique'} eq 'yes'
1.192     albertel 7393: 	    && !$$scan_record{'scantron.CODE_ignore_dup'}) {
1.186     albertel 7394: 	    &scantron_get_correction($r,$i,$scan_record,
                   7395: 				     \%scantron_config,
1.194     albertel 7396: 				     $line,'duplicateCODE',$usedCODEs{$CODE});
                   7397: 	    return(1,$currentphase);
1.186     albertel 7398: 	}
1.524     raeburn  7399: 	push(@{$usedCODEs{$CODE}},$$scan_record{'scantron.PaperID'});
1.186     albertel 7400:     }
1.157     albertel 7401:     return (0,$currentphase+1);
                   7402: }
                   7403: 
1.423     albertel 7404: =pod
                   7405: 
                   7406: =item scantron_validate_doublebubble
                   7407: 
1.424     albertel 7408:    Validates all scanlines in the selected file to not have any
                   7409:    bubble lines with multiple bubbles marked.
                   7410: 
1.423     albertel 7411: =cut
                   7412: 
1.157     albertel 7413: sub scantron_validate_doublebubble {
                   7414:     my ($r,$currentphase) = @_;
                   7415:     #get student info
                   7416:     my $classlist=&Apache::loncoursedata::get_classlist();
                   7417:     my %idmap=&username_to_idmap($classlist);
                   7418: 
                   7419:     #get scantron line setup
1.257     albertel 7420:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.157     albertel 7421:     my ($scanlines,$scan_data)=&scantron_getfile();
1.583     raeburn  7422:     my $nav_error;
                   7423:     &scantron_get_maxbubble(\$nav_error); # parse needs the bubble line array.
                   7424:     if ($nav_error) {
                   7425:         $r->print(&navmap_errormsg());
                   7426:         return(1,$currentphase);
                   7427:     }
1.447     foxr     7428: 
1.157     albertel 7429:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
1.200     albertel 7430: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.157     albertel 7431: 	if ($line=~/^[\s\cz]*$/) { next; }
                   7432: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
                   7433: 						 $scan_data);
                   7434: 	if (!defined($$scan_record{'scantron.doubleerror'})) { next; }
                   7435: 	&scantron_get_correction($r,$i,$scan_record,\%scantron_config,$line,
                   7436: 				 'doublebubble',
                   7437: 				 $$scan_record{'scantron.doubleerror'});
                   7438:     	return (1,$currentphase);
                   7439:     }
                   7440:     return (0,$currentphase+1);
                   7441: }
                   7442: 
1.423     albertel 7443: 
1.503     raeburn  7444: sub scantron_get_maxbubble {
1.582     raeburn  7445:     my ($nav_error) = @_;
1.257     albertel 7446:     if (defined($env{'form.scantron_maxbubble'}) &&
                   7447: 	$env{'form.scantron_maxbubble'}) {
1.447     foxr     7448: 	&restore_bubble_lines();
1.257     albertel 7449: 	return $env{'form.scantron_maxbubble'};
1.191     albertel 7450:     }
1.330     albertel 7451: 
1.447     foxr     7452:     my (undef, undef, $sequence) =
1.257     albertel 7453: 	&Apache::lonnet::decode_symb($env{'form.selectpage'});
1.330     albertel 7454: 
1.447     foxr     7455:     my $navmap=Apache::lonnavmaps::navmap->new();
1.582     raeburn  7456:     unless (ref($navmap)) {
                   7457:         if (ref($nav_error)) {
                   7458:             $$nav_error = 1;
                   7459:         }
1.591     raeburn  7460:         return;
1.582     raeburn  7461:     }
1.191     albertel 7462:     my $map=$navmap->getResourceByUrl($sequence);
                   7463:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
1.330     albertel 7464: 
                   7465:     &Apache::lonxml::clear_problem_counter();
                   7466: 
1.557     raeburn  7467:     my $uname       = $env{'user.name'};
                   7468:     my $udom        = $env{'user.domain'};
1.435     foxr     7469:     my $cid         = $env{'request.course.id'};
                   7470:     my $total_lines = 0;
                   7471:     %bubble_lines_per_response = ();
1.447     foxr     7472:     %first_bubble_line         = ();
1.503     raeburn  7473:     %subdivided_bubble_lines   = ();
                   7474:     %responsetype_per_response = ();
1.554     raeburn  7475: 
1.447     foxr     7476:     my $response_number = 0;
                   7477:     my $bubble_line     = 0;
1.191     albertel 7478:     foreach my $resource (@resources) {
1.542     raeburn  7479:         my ($analysis,$parts) = &scantron_partids_tograde($resource,$cid,$uname,$udom);
                   7480:         if ((ref($analysis) eq 'HASH') && (ref($parts) eq 'ARRAY')) {
                   7481: 	    foreach my $part_id (@{$parts}) {
                   7482:                 my $lines;
                   7483: 
                   7484: 	        # TODO - make this a persistent hash not an array.
                   7485: 
                   7486:                 # optionresponse, matchresponse and rankresponse type items 
                   7487:                 # render as separate sub-questions in exam mode.
                   7488:                 if (($analysis->{$part_id.'.type'} eq 'optionresponse') ||
                   7489:                     ($analysis->{$part_id.'.type'} eq 'matchresponse') ||
                   7490:                     ($analysis->{$part_id.'.type'} eq 'rankresponse')) {
                   7491:                     my ($numbub,$numshown);
                   7492:                     if ($analysis->{$part_id.'.type'} eq 'optionresponse') {
                   7493:                         if (ref($analysis->{$part_id.'.options'}) eq 'ARRAY') {
                   7494:                             $numbub = scalar(@{$analysis->{$part_id.'.options'}});
                   7495:                         }
                   7496:                     } elsif ($analysis->{$part_id.'.type'} eq 'matchresponse') {
                   7497:                         if (ref($analysis->{$part_id.'.items'}) eq 'ARRAY') {
                   7498:                             $numbub = scalar(@{$analysis->{$part_id.'.items'}});
                   7499:                         }
                   7500:                     } elsif ($analysis->{$part_id.'.type'} eq 'rankresponse') {
                   7501:                         if (ref($analysis->{$part_id.'.foils'}) eq 'ARRAY') {
                   7502:                             $numbub = scalar(@{$analysis->{$part_id.'.foils'}});
                   7503:                         }
                   7504:                     }
                   7505:                     if (ref($analysis->{$part_id.'.shown'}) eq 'ARRAY') {
                   7506:                         $numshown = scalar(@{$analysis->{$part_id.'.shown'}});
                   7507:                     }
                   7508:                     my $bubbles_per_line = 10;
                   7509:                     my $inner_bubble_lines = int($numbub/$bubbles_per_line);
                   7510:                     if (($numbub % $bubbles_per_line) != 0) {
                   7511:                         $inner_bubble_lines++;
                   7512:                     }
                   7513:                     for (my $i=0; $i<$numshown; $i++) {
                   7514:                         $subdivided_bubble_lines{$response_number} .= 
                   7515:                             $inner_bubble_lines.',';
                   7516:                     }
                   7517:                     $subdivided_bubble_lines{$response_number} =~ s/,$//;
                   7518:                     $lines = $numshown * $inner_bubble_lines;
                   7519:                 } else {
                   7520:                     $lines = $analysis->{"$part_id.bubble_lines"};
                   7521:                 } 
                   7522: 
                   7523:                 $first_bubble_line{$response_number} = $bubble_line;
                   7524: 	        $bubble_lines_per_response{$response_number} = $lines;
                   7525:                 $responsetype_per_response{$response_number} = 
                   7526:                     $analysis->{$part_id.'.type'};
                   7527: 	        $response_number++;
                   7528: 
                   7529: 	        $bubble_line +=  $lines;
                   7530: 	        $total_lines +=  $lines;
                   7531: 	    }
                   7532:         }
                   7533:     }
1.552     raeburn  7534:     &Apache::lonnet::delenv('scantron.');
1.542     raeburn  7535: 
                   7536:     &save_bubble_lines();
                   7537:     $env{'form.scantron_maxbubble'} =
                   7538: 	$total_lines;
                   7539:     return $env{'form.scantron_maxbubble'};
                   7540: }
1.523     raeburn  7541: 
1.157     albertel 7542: sub scantron_validate_missingbubbles {
                   7543:     my ($r,$currentphase) = @_;
                   7544:     #get student info
                   7545:     my $classlist=&Apache::loncoursedata::get_classlist();
                   7546:     my %idmap=&username_to_idmap($classlist);
                   7547: 
                   7548:     #get scantron line setup
1.257     albertel 7549:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.157     albertel 7550:     my ($scanlines,$scan_data)=&scantron_getfile();
1.582     raeburn  7551:     my $nav_error;
                   7552:     my $max_bubble=&scantron_get_maxbubble(\$nav_error);
                   7553:     if ($nav_error) {
                   7554:         return(1,$currentphase);
                   7555:     }
1.157     albertel 7556:     if (!$max_bubble) { $max_bubble=2**31; }
                   7557:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
1.200     albertel 7558: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.157     albertel 7559: 	if ($line=~/^[\s\cz]*$/) { next; }
                   7560: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
                   7561: 						 $scan_data);
                   7562: 	if (!defined($$scan_record{'scantron.missingerror'})) { next; }
                   7563: 	my @to_correct;
1.470     foxr     7564: 	
                   7565: 	# Probably here's where the error is...
                   7566: 
1.157     albertel 7567: 	foreach my $missing (@{$$scan_record{'scantron.missingerror'}}) {
1.505     raeburn  7568:             my $lastbubble;
                   7569:             if ($missing =~ /^(\d+)\.(\d+)$/) {
                   7570:                my $question = $1;
                   7571:                my $subquestion = $2;
                   7572:                if (!defined($first_bubble_line{$question -1})) { next; }
                   7573:                my $first = $first_bubble_line{$question-1};
                   7574:                my @subans = split(/,/,$subdivided_bubble_lines{$question-1});
                   7575:                my $subcount = 1;
                   7576:                while ($subcount<$subquestion) {
                   7577:                    $first += $subans[$subcount-1];
                   7578:                    $subcount ++;
                   7579:                }
                   7580:                my $count = $subans[$subquestion-1];
                   7581:                $lastbubble = $first + $count;
                   7582:             } else {
                   7583:                 if (!defined($first_bubble_line{$missing - 1})) { next; }
                   7584:                 $lastbubble = $first_bubble_line{$missing - 1} + $bubble_lines_per_response{$missing - 1};
                   7585:             }
                   7586:             if ($lastbubble > $max_bubble) { next; }
1.157     albertel 7587: 	    push(@to_correct,$missing);
                   7588: 	}
                   7589: 	if (@to_correct) {
                   7590: 	    &scantron_get_correction($r,$i,$scan_record,\%scantron_config,
                   7591: 				     $line,'missingbubble',\@to_correct);
                   7592: 	    return (1,$currentphase);
                   7593: 	}
                   7594: 
                   7595:     }
                   7596:     return (0,$currentphase+1);
                   7597: }
                   7598: 
1.423     albertel 7599: 
1.82      albertel 7600: sub scantron_process_students {
1.75      albertel 7601:     my ($r) = @_;
1.513     foxr     7602: 
1.257     albertel 7603:     my (undef,undef,$sequence)=&Apache::lonnet::decode_symb($env{'form.selectpage'});
1.324     albertel 7604:     my ($symb)=&get_symb($r);
1.513     foxr     7605:     if (!$symb) {
                   7606: 	return '';
                   7607:     }
1.324     albertel 7608:     my $default_form_data=&defaultFormData($symb);
1.82      albertel 7609: 
1.257     albertel 7610:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.157     albertel 7611:     my ($scanlines,$scan_data)=&scantron_getfile();
1.82      albertel 7612:     my $classlist=&Apache::loncoursedata::get_classlist();
                   7613:     my %idmap=&username_to_idmap($classlist);
1.132     bowersj2 7614:     my $navmap=Apache::lonnavmaps::navmap->new();
1.582     raeburn  7615:     unless (ref($navmap)) {
                   7616:         $r->print(&navmap_errormsg());
                   7617:         return '';
                   7618:     }  
1.83      albertel 7619:     my $map=$navmap->getResourceByUrl($sequence);
                   7620:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
1.557     raeburn  7621:     my (%grader_partids_by_symb,%grader_randomlists_by_symb);
                   7622:     &graders_resources_pass(\@resources,\%grader_partids_by_symb,
                   7623:                             \%grader_randomlists_by_symb);
1.586     raeburn  7624:     my $resource_error;
1.557     raeburn  7625:     foreach my $resource (@resources) {
1.586     raeburn  7626:         my $ressymb;
                   7627:         if (ref($resource)) {
                   7628:             $ressymb = $resource->symb();
                   7629:         } else {
                   7630:             $resource_error = 1;
                   7631:             last;
                   7632:         }
1.557     raeburn  7633:         my ($analysis,$parts) =
                   7634:             &scantron_partids_tograde($resource,$env{'request.course.id'},
                   7635:                                       $env{'user.name'},$env{'user.domain'},1);
                   7636:         $grader_partids_by_symb{$ressymb} = $parts;
                   7637:         if (ref($analysis) eq 'HASH') {
                   7638:             if (ref($analysis->{'parts_withrandomlist'}) eq 'ARRAY') {
                   7639:                 $grader_randomlists_by_symb{$ressymb} = 
                   7640:                     $analysis->{'parts_withrandomlist'};
                   7641:             }
                   7642:         }
                   7643:     }
1.586     raeburn  7644:     if ($resource_error) {
                   7645:         $r->print(&navmap_errormsg());
                   7646:         return '';
                   7647:     }
1.557     raeburn  7648: 
1.554     raeburn  7649:     my ($uname,$udom);
1.82      albertel 7650:     my $result= <<SCANTRONFORM;
1.81      albertel 7651: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantronupload">
                   7652:   <input type="hidden" name="command" value="scantron_configphase" />
                   7653:   $default_form_data
                   7654: SCANTRONFORM
1.82      albertel 7655:     $r->print($result);
                   7656: 
                   7657:     my @delayqueue;
1.542     raeburn  7658:     my (%completedstudents,%scandata);
1.140     albertel 7659:     
1.520     www      7660:     my $lock=&Apache::lonnet::set_lock(&mt('Grading bubblesheet exam'));
1.200     albertel 7661:     my $count=&get_todo_count($scanlines,$scan_data);
1.575     www      7662:     my %prog_state=&Apache::lonhtmlcommon::Create_PrgWin($r,'Bubblesheet Status',
                   7663:  				    'Bubblesheet Progress',$count,
1.195     albertel 7664: 				    'inline',undef,'scantronupload');
1.140     albertel 7665:     &Apache::lonhtmlcommon::Update_PrgWin($r,\%prog_state,
                   7666: 					  'Processing first student');
1.542     raeburn  7667:     $r->print('<br />');
1.140     albertel 7668:     my $start=&Time::HiRes::time();
1.158     albertel 7669:     my $i=-1;
1.542     raeburn  7670:     my $started;
1.447     foxr     7671: 
1.582     raeburn  7672:     my $nav_error;
                   7673:     &scantron_get_maxbubble(\$nav_error); # Need the bubble lines array to parse.
                   7674:     if ($nav_error) {
                   7675:         $r->print(&navmap_errormsg());
                   7676:         return '';
                   7677:     }
                   7678: 
1.513     foxr     7679:     # If an ssi failed in scantron_get_maxbubble, put an error message out to
                   7680:     # the user and return.
                   7681: 
                   7682:     if ($ssi_error) {
                   7683: 	$r->print("</form>");
                   7684: 	&ssi_print_error($r);
                   7685: 	$r->print(&show_grading_menu_form($symb));
1.520     www      7686:         &Apache::lonnet::remove_lock($lock);
1.513     foxr     7687: 	return '';		# Dunno why the other returns return '' rather than just returning.
                   7688:     }
1.447     foxr     7689: 
1.542     raeburn  7690:     my %lettdig = &letter_to_digits();
                   7691:     my $numletts = scalar(keys(%lettdig));
                   7692: 
1.157     albertel 7693:     while ($i<$scanlines->{'count'}) {
                   7694:  	($uname,$udom)=('','');
                   7695:  	$i++;
1.200     albertel 7696:  	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.157     albertel 7697:  	if ($line=~/^[\s\cz]*$/) { next; }
1.200     albertel 7698: 	if ($started) {
                   7699: 	    &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state,
                   7700: 						     'last student');
                   7701: 	}
                   7702: 	$started=1;
1.157     albertel 7703:  	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
                   7704:  						 $scan_data);
                   7705:  	unless ($uname=&scantron_find_student($scan_record,$scan_data,
                   7706:  					      \%idmap,$i)) {
                   7707:   	    &scantron_add_delay(\@delayqueue,$line,
                   7708:  				'Unable to find a student that matches',1);
                   7709:  	    next;
                   7710:   	}
                   7711:  	if (exists $completedstudents{$uname}) {
                   7712:  	    &scantron_add_delay(\@delayqueue,$line,
                   7713:  				'Student '.$uname.' has multiple sheets',2);
                   7714:  	    next;
                   7715:  	}
                   7716:   	($uname,$udom)=split(/:/,$uname);
1.330     albertel 7717: 
1.586     raeburn  7718:         my (%partids_by_symb,$res_error);
1.554     raeburn  7719:         foreach my $resource (@resources) {
1.586     raeburn  7720:             my $ressymb;
                   7721:             if (ref($resource)) {
                   7722:                 $ressymb = $resource->symb();
                   7723:             } else {
                   7724:                 $res_error = 1;
                   7725:                 last;
                   7726:             }
1.557     raeburn  7727:             if ((exists($grader_randomlists_by_symb{$ressymb})) ||
                   7728:                 (ref($grader_partids_by_symb{$ressymb}) ne 'ARRAY')) {
                   7729:                 my ($analysis,$parts) =
                   7730:                     &scantron_partids_tograde($resource,$env{'request.course.id'},$uname,$udom);
                   7731:                 $partids_by_symb{$ressymb} = $parts;
                   7732:             } else {
                   7733:                 $partids_by_symb{$ressymb} = $grader_partids_by_symb{$ressymb};
                   7734:             }
1.554     raeburn  7735:         }
                   7736: 
1.586     raeburn  7737:         if ($res_error) {
                   7738:             &scantron_add_delay(\@delayqueue,$line,
                   7739:                                 'An error occurred while grading student '.$uname,2);
                   7740:             next;
                   7741:         }
                   7742: 
1.330     albertel 7743: 	&Apache::lonxml::clear_problem_counter();
1.514     raeburn  7744:   	&Apache::lonnet::appenv($scan_record);
1.376     albertel 7745: 
                   7746: 	if (&scantron_clear_skip($scanlines,$scan_data,$i)) {
                   7747: 	    &scantron_putfile($scanlines,$scan_data);
                   7748: 	}
1.161     albertel 7749: 	
1.542     raeburn  7750:         my $scancode;
                   7751:         if ((exists($scan_record->{'scantron.CODE'})) &&
                   7752:             (&Apache::lonnet::validCODE($scan_record->{'scantron.CODE'}))) {
                   7753:             $scancode = $scan_record->{'scantron.CODE'};
                   7754:         } else {
                   7755:             $scancode = '';
                   7756:         }
                   7757: 
                   7758:         if (&grade_student_bubbles($r,$uname,$udom,$scan_record,$scancode,
1.554     raeburn  7759:                                    \@resources,\%partids_by_symb) eq 'ssi_error') {
1.542     raeburn  7760:             $ssi_error = 0; # So end of handler error message does not trigger.
                   7761:             $r->print("</form>");
                   7762:             &ssi_print_error($r);
                   7763:             $r->print(&show_grading_menu_form($symb));
                   7764:             &Apache::lonnet::remove_lock($lock);
                   7765:             return '';      # Why return ''?  Beats me.
                   7766:         }
1.513     foxr     7767: 
1.140     albertel 7768: 	$completedstudents{$uname}={'line'=>$line};
1.542     raeburn  7769:         if ($env{'form.verifyrecord'}) {
                   7770:             my $lastpos = $env{'form.scantron_maxbubble'}*$scantron_config{'Qlength'};
                   7771:             my $studentdata = substr($line,$scantron_config{'Qstart'}-1,$lastpos);
                   7772:             chomp($studentdata);
                   7773:             $studentdata =~ s/\r$//;
                   7774:             my $studentrecord = '';
                   7775:             my $counter = -1;
                   7776:             foreach my $resource (@resources) {
1.554     raeburn  7777:                 my $ressymb = $resource->symb();
1.542     raeburn  7778:                 ($counter,my $recording) =
                   7779:                     &verify_scantron_grading($resource,$udom,$uname,$env{'request.course.id'},
1.554     raeburn  7780:                                              $counter,$studentdata,$partids_by_symb{$ressymb},
1.542     raeburn  7781:                                              \%scantron_config,\%lettdig,$numletts);
                   7782:                 $studentrecord .= $recording;
                   7783:             }
                   7784:             if ($studentrecord ne $studentdata) {
1.554     raeburn  7785:                 &Apache::lonxml::clear_problem_counter();
                   7786:                 if (&grade_student_bubbles($r,$uname,$udom,$scan_record,$scancode,
                   7787:                                            \@resources,\%partids_by_symb) eq 'ssi_error') {
                   7788:                     $ssi_error = 0; # So end of handler error message does not trigger.
                   7789:                     $r->print("</form>");
                   7790:                     &ssi_print_error($r);
                   7791:                     $r->print(&show_grading_menu_form($symb));
                   7792:                     &Apache::lonnet::remove_lock($lock);
                   7793:                     delete($completedstudents{$uname});
                   7794:                     return '';
                   7795:                 }
1.542     raeburn  7796:                 $counter = -1;
                   7797:                 $studentrecord = '';
                   7798:                 foreach my $resource (@resources) {
1.554     raeburn  7799:                     my $ressymb = $resource->symb();
1.542     raeburn  7800:                     ($counter,my $recording) =
                   7801:                         &verify_scantron_grading($resource,$udom,$uname,$env{'request.course.id'},
1.554     raeburn  7802:                                                  $counter,$studentdata,$partids_by_symb{$ressymb},
1.542     raeburn  7803:                                                  \%scantron_config,\%lettdig,$numletts);
                   7804:                     $studentrecord .= $recording;
                   7805:                 }
                   7806:                 if ($studentrecord ne $studentdata) {
                   7807:                     $r->print('<p><span class="LC_error">');
                   7808:                     if ($scancode eq '') {
                   7809:                         $r->print(&mt('Mismatch grading bubble sheet for user: [_1] with ID: [_2].',
                   7810:                                   $uname.':'.$udom,$scan_record->{'scantron.ID'}));
                   7811:                     } else {
                   7812:                         $r->print(&mt('Mismatch grading bubble sheet for user: [_1] with ID: [_2] and CODE: [_3].',
                   7813:                                   $uname.':'.$udom,$scan_record->{'scantron.ID'},$scancode));
                   7814:                     }
                   7815:                     $r->print('</span><br />'.&Apache::loncommon::start_data_table()."\n".
                   7816:                               &Apache::loncommon::start_data_table_header_row()."\n".
                   7817:                               '<th>'.&mt('Source').'</th><th>'.&mt('Bubbled responses').'</th>'.
                   7818:                               &Apache::loncommon::end_data_table_header_row()."\n".
                   7819:                               &Apache::loncommon::start_data_table_row().
                   7820:                               '<td>'.&mt('Bubble Sheet').'</td>'.
                   7821:                               '<td><span class="LC_nobreak">'.$studentdata.'</span></td>'.
                   7822:                               &Apache::loncommon::end_data_table_row().
                   7823:                               &Apache::loncommon::start_data_table_row().
                   7824:                               '<td>Stored submissions</td>'.
                   7825:                               '<td><span class="LC_nobreak">'.$studentrecord.'</span></td>'."\n".
                   7826:                               &Apache::loncommon::end_data_table_row().
                   7827:                               &Apache::loncommon::end_data_table().'</p>');
                   7828:                 } else {
                   7829:                     $r->print('<br /><span class="LC_warning">'.
                   7830:                              &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 />'.
                   7831:                              &mt("As a consequence, this user's submission history records two tries.").
                   7832:                                  '</span><br />');
                   7833:                 }
                   7834:             }
                   7835:         }
1.543     raeburn  7836:         if (&Apache::loncommon::connection_aborted($r)) { last; }
1.140     albertel 7837:     } continue {
1.330     albertel 7838: 	&Apache::lonxml::clear_problem_counter();
1.552     raeburn  7839: 	&Apache::lonnet::delenv('scantron.');
1.82      albertel 7840:     }
1.140     albertel 7841:     &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
1.520     www      7842:     &Apache::lonnet::remove_lock($lock);
1.172     albertel 7843: #    my $lasttime = &Time::HiRes::time()-$start;
                   7844: #    $r->print("<p>took $lasttime</p>");
1.140     albertel 7845: 
1.200     albertel 7846:     $r->print("</form>");
1.324     albertel 7847:     $r->print(&show_grading_menu_form($symb));
1.157     albertel 7848:     return '';
1.75      albertel 7849: }
1.157     albertel 7850: 
1.557     raeburn  7851: sub graders_resources_pass {
                   7852:     my ($resources,$grader_partids_by_symb,$grader_randomlists_by_symb) = @_;
                   7853:     if ((ref($resources) eq 'ARRAY') && (ref($grader_partids_by_symb)) && 
                   7854:         (ref($grader_randomlists_by_symb) eq 'HASH')) {
                   7855:         foreach my $resource (@{$resources}) {
                   7856:             my $ressymb = $resource->symb();
                   7857:             my ($analysis,$parts) =
                   7858:                 &scantron_partids_tograde($resource,$env{'request.course.id'},
                   7859:                                           $env{'user.name'},$env{'user.domain'},1);
                   7860:             $grader_partids_by_symb->{$ressymb} = $parts;
                   7861:             if (ref($analysis) eq 'HASH') {
                   7862:                 if (ref($analysis->{'parts_withrandomlist'}) eq 'ARRAY') {
                   7863:                     $grader_randomlists_by_symb->{$ressymb} =
                   7864:                         $analysis->{'parts_withrandomlist'};
                   7865:                 }
                   7866:             }
                   7867:         }
                   7868:     }
                   7869:     return;
                   7870: }
                   7871: 
1.542     raeburn  7872: sub grade_student_bubbles {
1.554     raeburn  7873:     my ($r,$uname,$udom,$scan_record,$scancode,$resources,$parts) = @_;
                   7874:     if (ref($resources) eq 'ARRAY') {
                   7875:         my $count = 0;
                   7876:         foreach my $resource (@{$resources}) {
                   7877:             my $ressymb = $resource->symb();
                   7878:             my %form = ('submitted'      => 'scantron',
                   7879:                         'grade_target'   => 'grade',
                   7880:                         'grade_username' => $uname,
                   7881:                         'grade_domain'   => $udom,
                   7882:                         'grade_courseid' => $env{'request.course.id'},
                   7883:                         'grade_symb'     => $ressymb,
                   7884:                         'CODE'           => $scancode
                   7885:                        );
                   7886:             if (ref($parts) eq 'HASH') {
                   7887:                 if (ref($parts->{$ressymb}) eq 'ARRAY') {
                   7888:                     foreach my $part (@{$parts->{$ressymb}}) {
                   7889:                         $form{'scantron_questnum_start.'.$part} =
                   7890:                             1+$env{'form.scantron.first_bubble_line.'.$count};
                   7891:                         $count++;
                   7892:                     }
                   7893:                 }
                   7894:             }
                   7895:             my $result=&ssi_with_retries($resource->src(),$ssi_retries,%form);
                   7896:             return 'ssi_error' if ($ssi_error);
                   7897:             last if (&Apache::loncommon::connection_aborted($r));
                   7898:         }
1.542     raeburn  7899:     }
                   7900:     return;
                   7901: }
                   7902: 
1.157     albertel 7903: sub scantron_upload_scantron_data {
                   7904:     my ($r)=@_;
1.565     raeburn  7905:     my $dom = $env{'request.role.domain'};
                   7906:     my $domdesc = &Apache::lonnet::domain($dom,'description');
                   7907:     $r->print(&Apache::loncommon::coursebrowser_javascript($dom));
1.157     albertel 7908:     my $select_link=&Apache::loncommon::selectcourse_link('rules','courseid',
1.181     albertel 7909: 							  'domainid',
1.565     raeburn  7910: 							  'coursename',$dom);
                   7911:     my $syllabuslink = '<a href="javascript:ToSyllabus();">'.&mt('Syllabus').'</a>'.
                   7912:                        ('&nbsp'x2).&mt('(shows course personnel)'); 
1.324     albertel 7913:     my $default_form_data=&defaultFormData(&get_symb($r,1));
1.579     raeburn  7914:     my $nofile_alert = &mt('Please use the browse button to select a file from your local directory.');
                   7915:     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 7916:     $r->print(&Apache::lonhtmlcommon::scripttag('
1.157     albertel 7917:     function checkUpload(formname) {
                   7918: 	if (formname.upfile.value == "") {
1.579     raeburn  7919: 	    alert("'.$nofile_alert.'");
1.157     albertel 7920: 	    return false;
                   7921: 	}
1.565     raeburn  7922:         if (formname.courseid.value == "") {
1.579     raeburn  7923:             alert("'.$nocourseid_alert.'");
1.565     raeburn  7924:             return false;
                   7925:         }
1.157     albertel 7926: 	formname.submit();
                   7927:     }
1.565     raeburn  7928: 
                   7929:     function ToSyllabus() {
                   7930:         var cdom = '."'$dom'".';
                   7931:         var cnum = document.rules.courseid.value;
                   7932:         if (cdom == "" || cdom == null) {
                   7933:             return;
                   7934:         }
                   7935:         if (cnum == "" || cnum == null) {
                   7936:            return;
                   7937:         }
                   7938:         syllwin=window.open("/public/"+cdom+"/"+cnum+"/syllabus","LONCAPASyllabus",
                   7939:                             "height=350,width=350,scrollbars=yes,menubar=no");
                   7940:         return;
                   7941:     }
                   7942: 
1.597     wenzelju 7943: '));
                   7944:     $r->print('
1.566     raeburn  7945: <h3>'.&mt('Send scanned bubblesheet data to a course').'</h3>
                   7946: 
1.492     albertel 7947: <form enctype="multipart/form-data" action="/adm/grades" name="rules" method="post">
1.565     raeburn  7948: '.$default_form_data.
                   7949:   &Apache::lonhtmlcommon::start_pick_box().
                   7950:   &Apache::lonhtmlcommon::row_title(&mt('Course ID')).
                   7951:   '<input name="courseid" type="text" size="30" />'.$select_link.
                   7952:   &Apache::lonhtmlcommon::row_closure().
                   7953:   &Apache::lonhtmlcommon::row_title(&mt('Course Name')).
                   7954:   '<input name="coursename" type="text" size="30" />'.$syllabuslink.
                   7955:   &Apache::lonhtmlcommon::row_closure().
                   7956:   &Apache::lonhtmlcommon::row_title(&mt('Domain')).
                   7957:   '<input name="domainid" type="hidden" />'.$domdesc.
                   7958:   &Apache::lonhtmlcommon::row_closure().
                   7959:   &Apache::lonhtmlcommon::row_title(&mt('File to upload')).
                   7960:   '<input type="file" name="upfile" size="50" />'.
                   7961:   &Apache::lonhtmlcommon::row_closure(1).
                   7962:   &Apache::lonhtmlcommon::end_pick_box().'<br />
                   7963: 
1.492     albertel 7964: <input name="command" value="scantronupload_save" type="hidden" />
1.589     bisitz   7965: <input type="button" onclick="javascript:checkUpload(this.form);" value="'.&mt('Upload Bubblesheet Data').'" />
1.157     albertel 7966: </form>
1.492     albertel 7967: ');
1.157     albertel 7968:     return '';
                   7969: }
                   7970: 
1.423     albertel 7971: 
1.157     albertel 7972: sub scantron_upload_scantron_data_save {
                   7973:     my($r)=@_;
1.324     albertel 7974:     my ($symb)=&get_symb($r,1);
1.182     albertel 7975:     my $doanotherupload=
                   7976: 	'<br /><form action="/adm/grades" method="post">'."\n".
                   7977: 	'<input type="hidden" name="command" value="scantronupload" />'."\n".
1.492     albertel 7978: 	'<input type="submit" name="submit" value="'.&mt('Do Another Upload').'" />'."\n".
1.182     albertel 7979: 	'</form>'."\n";
1.257     albertel 7980:     if (!&Apache::lonnet::allowed('usc',$env{'form.domainid'}) &&
1.162     albertel 7981: 	!&Apache::lonnet::allowed('usc',
1.257     albertel 7982: 			    $env{'form.domainid'}.'_'.$env{'form.courseid'})) {
1.575     www      7983: 	$r->print(&mt("You are not allowed to upload bubblesheet data to the requested course.")."<br />");
1.182     albertel 7984: 	if ($symb) {
1.324     albertel 7985: 	    $r->print(&show_grading_menu_form($symb));
1.182     albertel 7986: 	} else {
                   7987: 	    $r->print($doanotherupload);
                   7988: 	}
1.162     albertel 7989: 	return '';
                   7990:     }
1.257     albertel 7991:     my %coursedata=&Apache::lonnet::coursedescription($env{'form.domainid'}.'_'.$env{'form.courseid'});
1.568     raeburn  7992:     my $uploadedfile;
1.567     raeburn  7993:     $r->print('<h3>'.&mt("Uploading file to [_1]",$coursedata{'description'}).'</h3>');
1.257     albertel 7994:     if (length($env{'form.upfile'}) < 2) {
1.568     raeburn  7995:         $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 7996:     } else {
1.568     raeburn  7997:         my $result = 
                   7998:             &Apache::lonnet::userfileupload('upfile','','scantron','','','',
                   7999:                                             $env{'form.courseid'},$env{'form.domainid'});
                   8000: 	if ($result =~ m{^/uploaded/}) {
1.567     raeburn  8001: 	    $r->print(&mt('[_1]Success:[_2] Successfully uploaded [_3] bytes of data into location: [_4]',
                   8002:                           '<span class="LC_success">','</span>',(length($env{'form.upfile'})-1),
                   8003: 			  '<span class="LC_filename">'.$result.'</span>'));
1.568     raeburn  8004:             ($uploadedfile) = ($result =~ m{/([^/]+)$});
1.567     raeburn  8005:             $r->print(&validate_uploaded_scantron_file($env{'form.domainid'},
1.568     raeburn  8006:                                                        $env{'form.courseid'},$uploadedfile));
1.210     albertel 8007: 	} else {
1.567     raeburn  8008: 	    $r->print(&mt('[_1]Error:[_2] An error ([_3]) occurred when attempting to upload the file, [_4]',
                   8009:                           '<span class="LC_error">','</span>',$result,
1.568     raeburn  8010: 			  '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>'));
1.183     albertel 8011: 	}
                   8012:     }
1.174     albertel 8013:     if ($symb) {
1.209     ng       8014: 	$r->print(&scantron_selectphase($r,$uploadedfile));
1.174     albertel 8015:     } else {
1.182     albertel 8016: 	$r->print($doanotherupload);
1.174     albertel 8017:     }
1.157     albertel 8018:     return '';
                   8019: }
                   8020: 
1.567     raeburn  8021: sub validate_uploaded_scantron_file {
                   8022:     my ($cdom,$cname,$fname) = @_;
                   8023:     my $scanlines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.$fname);
                   8024:     my @lines;
                   8025:     if ($scanlines ne '-1') {
                   8026:         @lines=split("\n",$scanlines,-1);
                   8027:     }
                   8028:     my $output;
                   8029:     if (@lines) {
                   8030:         my (%counts,$max_match_format);
                   8031:         my ($max_match_count,$max_match_pct) = (0,0);
                   8032:         my $classlist = &Apache::loncoursedata::get_classlist($cdom,$cname);
                   8033:         my %idmap = &username_to_idmap($classlist);
                   8034:         foreach my $key (keys(%idmap)) {
                   8035:             my $lckey = lc($key);
                   8036:             $idmap{$lckey} = $idmap{$key};
                   8037:         }
                   8038:         my %unique_formats;
                   8039:         my @formatlines = &get_scantronformat_file();
                   8040:         foreach my $line (@formatlines) {
                   8041:             chomp($line);
                   8042:             my @config = split(/:/,$line);
                   8043:             my $idstart = $config[5];
                   8044:             my $idlength = $config[6];
                   8045:             if (($idstart ne '') && ($idlength > 0)) {
                   8046:                 if (ref($unique_formats{$idstart.':'.$idlength}) eq 'ARRAY') {
                   8047:                     push(@{$unique_formats{$idstart.':'.$idlength}},$config[0].':'.$config[1]); 
                   8048:                 } else {
                   8049:                     $unique_formats{$idstart.':'.$idlength} = [$config[0].':'.$config[1]];
                   8050:                 }
                   8051:             }
                   8052:         }
                   8053:         foreach my $key (keys(%unique_formats)) {
                   8054:             my ($idstart,$idlength) = split(':',$key);
                   8055:             %{$counts{$key}} = (
                   8056:                                'found'   => 0,
                   8057:                                'total'   => 0,
                   8058:                               );
                   8059:             foreach my $line (@lines) {
                   8060:                 next if ($line =~ /^#/);
                   8061:                 next if ($line =~ /^[\s\cz]*$/);
                   8062:                 my $id = substr($line,$idstart-1,$idlength);
                   8063:                 $id = lc($id);
                   8064:                 if (exists($idmap{$id})) {
                   8065:                     $counts{$key}{'found'} ++;
                   8066:                 }
                   8067:                 $counts{$key}{'total'} ++;
                   8068:             }
                   8069:             if ($counts{$key}{'total'}) {
                   8070:                 my $percent_match = (100*$counts{$key}{'found'})/($counts{$key}{'total'});
                   8071:                 if (($max_match_format eq '') || ($percent_match > $max_match_pct)) {
                   8072:                     $max_match_pct = $percent_match;
                   8073:                     $max_match_format = $key;
                   8074:                     $max_match_count = $counts{$key}{'total'};
                   8075:                 }
                   8076:             }
                   8077:         }
                   8078:         if (ref($unique_formats{$max_match_format}) eq 'ARRAY') {
                   8079:             my $format_descs;
                   8080:             my $numwithformat = @{$unique_formats{$max_match_format}};
                   8081:             for (my $i=0; $i<$numwithformat; $i++) {
                   8082:                 my ($name,$desc) = split(':',$unique_formats{$max_match_format}[$i]);
                   8083:                 if ($i<$numwithformat-2) {
                   8084:                     $format_descs .= '"<i>'.$desc.'</i>", ';
                   8085:                 } elsif ($i==$numwithformat-2) {
                   8086:                     $format_descs .= '"<i>'.$desc.'</i>" '.&mt('and').' ';
                   8087:                 } elsif ($i==$numwithformat-1) {
                   8088:                     $format_descs .= '"<i>'.$desc.'</i>"';
                   8089:                 }
                   8090:             }
                   8091:             my $showpct = sprintf("%.0f",$max_match_pct).'%';
                   8092:             $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).
                   8093:                        '<br />'.&mt('A low percentage of matches results from one of the following:').'<ul>'.
                   8094:                        '<li>'.&mt('The file was uploaded to the wrong course').'</li>'.
                   8095:                        '<li>'.&mt('The data are not in the format expected for the domain: [_1]',
                   8096:                                   '<i>'.$cdom.'</i>').'</li>'.
                   8097:                        '<li>'.&mt('Students did not bubble their IDs, or mis-bubbled them').'</li>'.
                   8098:                        '<li>'.&mt('The course roster is not up to date').'</li>'.
                   8099:                        '</ul>';
                   8100:         }
                   8101:     } else {
                   8102:         $output = '<span class="LC_warning">'.&mt('Uploaded file contained no data').'</span>';
                   8103:     }
                   8104:     return $output;
                   8105: }
                   8106: 
1.202     albertel 8107: sub valid_file {
                   8108:     my ($requested_file)=@_;
                   8109:     foreach my $filename (sort(&scantron_filenames())) {
                   8110: 	if ($requested_file eq $filename) { return 1; }
                   8111:     }
                   8112:     return 0;
                   8113: }
                   8114: 
                   8115: sub scantron_download_scantron_data {
                   8116:     my ($r)=@_;
1.324     albertel 8117:     my $default_form_data=&defaultFormData(&get_symb($r,1));
1.257     albertel 8118:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   8119:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   8120:     my $file=$env{'form.scantron_selectfile'};
1.202     albertel 8121:     if (! &valid_file($file)) {
1.492     albertel 8122: 	$r->print('
1.202     albertel 8123: 	<p>
1.492     albertel 8124: 	    '.&mt('The requested file name was invalid.').'
1.202     albertel 8125:         </p>
1.492     albertel 8126: ');
1.324     albertel 8127: 	$r->print(&show_grading_menu_form(&get_symb($r,1)));
1.202     albertel 8128: 	return;
                   8129:     }
                   8130:     my $orig='/uploaded/'.$cdom.'/'.$cname.'/scantron_orig_'.$file;
                   8131:     my $corrected='/uploaded/'.$cdom.'/'.$cname.'/scantron_corrected_'.$file;
                   8132:     my $skipped='/uploaded/'.$cdom.'/'.$cname.'/scantron_skipped_'.$file;
                   8133:     &Apache::lonnet::allowuploaded('/adm/grades',$orig);
                   8134:     &Apache::lonnet::allowuploaded('/adm/grades',$corrected);
                   8135:     &Apache::lonnet::allowuploaded('/adm/grades',$skipped);
1.492     albertel 8136:     $r->print('
1.202     albertel 8137:     <p>
1.492     albertel 8138: 	'.&mt('[_1]Original[_2] file as uploaded by the scantron office.',
                   8139: 	      '<a href="'.$orig.'">','</a>').'
1.202     albertel 8140:     </p>
                   8141:     <p>
1.492     albertel 8142: 	'.&mt('[_1]Corrections[_2], a file of corrected records that were used in grading.',
                   8143: 	      '<a href="'.$corrected.'">','</a>').'
1.202     albertel 8144:     </p>
                   8145:     <p>
1.492     albertel 8146: 	'.&mt('[_1]Skipped[_2], a file of records that were skipped.',
                   8147: 	      '<a href="'.$skipped.'">','</a>').'
1.202     albertel 8148:     </p>
1.492     albertel 8149: ');
1.324     albertel 8150:     $r->print(&show_grading_menu_form(&get_symb($r,1)));
1.202     albertel 8151:     return '';
                   8152: }
1.157     albertel 8153: 
1.523     raeburn  8154: sub checkscantron_results {
                   8155:     my ($r) = @_;
                   8156:     my ($symb)=&get_symb($r);
                   8157:     if (!$symb) {return '';}
                   8158:     my $grading_menu_button=&show_grading_menu_form($symb);
                   8159:     my $cid = $env{'request.course.id'};
1.542     raeburn  8160:     my %lettdig = &letter_to_digits();
1.523     raeburn  8161:     my $numletts = scalar(keys(%lettdig));
                   8162:     my $cnum = $env{'course.'.$cid.'.num'};
                   8163:     my $cdom = $env{'course.'.$cid.'.domain'};
                   8164:     my (undef, undef, $sequence) = &Apache::lonnet::decode_symb($env{'form.selectpage'});
                   8165:     my %record;
                   8166:     my %scantron_config =
                   8167:         &Apache::grades::get_scantron_config($env{'form.scantron_format'});
                   8168:     my ($scanlines,$scan_data)=&Apache::grades::scantron_getfile();
                   8169:     my $classlist=&Apache::loncoursedata::get_classlist();
                   8170:     my %idmap=&Apache::grades::username_to_idmap($classlist);
                   8171:     my $navmap=Apache::lonnavmaps::navmap->new();
1.582     raeburn  8172:     unless (ref($navmap)) {
                   8173:         $r->print(&navmap_errormsg());
                   8174:         return '';
                   8175:     }
1.523     raeburn  8176:     my $map=$navmap->getResourceByUrl($sequence);
1.557     raeburn  8177:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
                   8178:     my (%grader_partids_by_symb,%grader_randomlists_by_symb);
                   8179:     &graders_resources_pass(\@resources,\%grader_partids_by_symb,                             \%grader_randomlists_by_symb);
                   8180: 
1.554     raeburn  8181:     my ($uname,$udom);
1.523     raeburn  8182:     my (%scandata,%lastname,%bylast);
                   8183:     $r->print('
                   8184: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="checkscantron">'."\n");
                   8185: 
                   8186:     my @delayqueue;
                   8187:     my %completedstudents;
                   8188: 
                   8189:     my $count=&Apache::grades::get_todo_count($scanlines,$scan_data);
1.581     www      8190:     my %prog_state=&Apache::lonhtmlcommon::Create_PrgWin($r,'Bubblesheet/Submissions Comparison Status',
                   8191:                                     'Progress of Bubblesheet Data/Submission Records Comparison',$count,
1.523     raeburn  8192:                                     'inline',undef,'checkscantron');
1.546     raeburn  8193:     my ($username,$domain,$started);
1.582     raeburn  8194:     my $nav_error;
                   8195:     &scantron_get_maxbubble(\$nav_error); # Need the bubble lines array to parse.
                   8196:     if ($nav_error) {
                   8197:         $r->print(&navmap_errormsg());
                   8198:         return '';
                   8199:     }
1.523     raeburn  8200: 
                   8201:     &Apache::lonhtmlcommon::Update_PrgWin($r,\%prog_state,
                   8202:                                           'Processing first student');
                   8203:     my $start=&Time::HiRes::time();
                   8204:     my $i=-1;
                   8205: 
                   8206:     while ($i<$scanlines->{'count'}) {
                   8207:         ($username,$domain,$uname)=('','','');
                   8208:         $i++;
                   8209:         my $line=&Apache::grades::scantron_get_line($scanlines,$scan_data,$i);
                   8210:         if ($line=~/^[\s\cz]*$/) { next; }
                   8211:         if ($started) {
                   8212:             &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state,
                   8213:                                                      'last student');
                   8214:         }
                   8215:         $started=1;
                   8216:         my $scan_record=
                   8217:             &Apache::grades::scantron_parse_scanline($line,$i,\%scantron_config,
                   8218:                                                      $scan_data);
                   8219:         unless ($uname=&Apache::grades::scantron_find_student($scan_record,$scan_data,
                   8220:                                                               \%idmap,$i)) {
                   8221:             &Apache::grades::scantron_add_delay(\@delayqueue,$line,
                   8222:                                 'Unable to find a student that matches',1);
                   8223:             next;
                   8224:         }
                   8225:         if (exists $completedstudents{$uname}) {
                   8226:             &Apache::grades::scantron_add_delay(\@delayqueue,$line,
                   8227:                                 'Student '.$uname.' has multiple sheets',2);
                   8228:             next;
                   8229:         }
                   8230:         my $pid = $scan_record->{'scantron.ID'};
                   8231:         $lastname{$pid} = $scan_record->{'scantron.LastName'};
                   8232:         push(@{$bylast{$lastname{$pid}}},$pid);
                   8233:         my $lastpos = $env{'form.scantron_maxbubble'}*$scantron_config{'Qlength'};
                   8234:         $scandata{$pid} = substr($line,$scantron_config{'Qstart'}-1,$lastpos);
                   8235:         chomp($scandata{$pid});
                   8236:         $scandata{$pid} =~ s/\r$//;
                   8237:         ($username,$domain)=split(/:/,$uname);
                   8238:         my $counter = -1;
                   8239:         foreach my $resource (@resources) {
1.557     raeburn  8240:             my $parts;
1.554     raeburn  8241:             my $ressymb = $resource->symb();
1.557     raeburn  8242:             if ((exists($grader_randomlists_by_symb{$ressymb})) ||
                   8243:                 (ref($grader_partids_by_symb{$ressymb}) ne 'ARRAY')) {
                   8244:                 (my $analysis,$parts) =
                   8245:                     &scantron_partids_tograde($resource,$env{'request.course.id'},$username,$domain);
                   8246:             } else {
                   8247:                 $parts = $grader_partids_by_symb{$ressymb};
                   8248:             }
1.542     raeburn  8249:             ($counter,my $recording) =
                   8250:                 &verify_scantron_grading($resource,$domain,$username,$cid,$counter,
1.554     raeburn  8251:                                          $scandata{$pid},$parts,
1.542     raeburn  8252:                                          \%scantron_config,\%lettdig,$numletts);
                   8253:             $record{$pid} .= $recording;
1.523     raeburn  8254:         }
                   8255:     }
                   8256:     &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
                   8257:     $r->print('<br />');
                   8258:     my ($okstudents,$badstudents,$numstudents,$passed,$failed);
                   8259:     $passed = 0;
                   8260:     $failed = 0;
                   8261:     $numstudents = 0;
                   8262:     foreach my $last (sort(keys(%bylast))) {
                   8263:         if (ref($bylast{$last}) eq 'ARRAY') {
                   8264:             foreach my $pid (sort(@{$bylast{$last}})) {
                   8265:                 my $showscandata = $scandata{$pid};
                   8266:                 my $showrecord = $record{$pid};
                   8267:                 $showscandata =~ s/\s/&nbsp;/g;
                   8268:                 $showrecord =~ s/\s/&nbsp;/g;
                   8269:                 if ($scandata{$pid} eq $record{$pid}) {
                   8270:                     my $css_class = ($passed % 2)?'LC_odd_row':'LC_even_row';
                   8271:                     $okstudents .= '<tr class="'.$css_class.'">'.
1.581     www      8272: '<td>'.&mt('Bubblesheet').'</td><td>'.$showscandata.'</td><td rowspan="2">'.$last.'</td><td rowspan="2">'.$pid.'</td>'."\n".
1.523     raeburn  8273: '</tr>'."\n".
                   8274: '<tr class="'.$css_class.'">'."\n".
                   8275: '<td>Submissions</td><td>'.$showrecord.'</td></tr>'."\n";
                   8276:                     $passed ++;
                   8277:                 } else {
                   8278:                     my $css_class = ($failed % 2)?'LC_odd_row':'LC_even_row';
1.581     www      8279:                     $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  8280: '</tr>'."\n".
                   8281: '<tr class="'.$css_class.'">'."\n".
                   8282: '<td>Submissions</td><td><span class="LC_nobreak">'.$record{$pid}.'</span></td>'."\n".
                   8283: '</tr>'."\n";
                   8284:                     $failed ++;
                   8285:                 }
                   8286:                 $numstudents ++;
                   8287:             }
                   8288:         }
                   8289:     }
1.572     www      8290:     $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  8291:     $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>');
                   8292:     if ($passed) {
1.572     www      8293:         $r->print(&mt('Students with exact correspondence between bubblesheet data and submissions are as follows:').'<br /><br />');
1.523     raeburn  8294:         $r->print(&Apache::loncommon::start_data_table()."\n".
                   8295:                  &Apache::loncommon::start_data_table_header_row()."\n".
                   8296:                  '<th>'.&mt('Source').'</th><th>'.&mt('Bubble records').'</th><th>'.&mt('Name').'</th><th>'.&mt('ID').'</th>'.
                   8297:                  &Apache::loncommon::end_data_table_header_row()."\n".
                   8298:                  $okstudents."\n".
                   8299:                  &Apache::loncommon::end_data_table().'<br />');
                   8300:     }
                   8301:     if ($failed) {
1.572     www      8302:         $r->print(&mt('Students with differences between bubblesheet data and submissions are as follows:').'<br /><br />');
1.523     raeburn  8303:         $r->print(&Apache::loncommon::start_data_table()."\n".
                   8304:                  &Apache::loncommon::start_data_table_header_row()."\n".
                   8305:                  '<th>'.&mt('Source').'</th><th>'.&mt('Bubble records').'</th><th>'.&mt('Name').'</th><th>'.&mt('ID').'</th>'.
                   8306:                  &Apache::loncommon::end_data_table_header_row()."\n".
                   8307:                  $badstudents."\n".
                   8308:                  &Apache::loncommon::end_data_table()).'<br />'.
1.572     www      8309:                  &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  8310:     }
                   8311:     $r->print('</form><br />'.$grading_menu_button);
                   8312:     return;
                   8313: }
                   8314: 
1.542     raeburn  8315: sub verify_scantron_grading {
1.554     raeburn  8316:     my ($resource,$domain,$username,$cid,$counter,$scandata,$partids,
1.542     raeburn  8317:         $scantron_config,$lettdig,$numletts) = @_;
                   8318:     my ($record,%expected,%startpos);
                   8319:     return ($counter,$record) if (!ref($resource));
                   8320:     return ($counter,$record) if (!$resource->is_problem());
                   8321:     my $symb = $resource->symb();
1.554     raeburn  8322:     return ($counter,$record) if (ref($partids) ne 'ARRAY');
                   8323:     foreach my $part_id (@{$partids}) {
1.542     raeburn  8324:         $counter ++;
                   8325:         $expected{$part_id} = 0;
                   8326:         if ($env{"form.scantron.sub_bubblelines.$counter"}) {
                   8327:             my @sub_lines = split(/,/,$env{"form.scantron.sub_bubblelines.$counter"});
                   8328:             foreach my $item (@sub_lines) {
                   8329:                 $expected{$part_id} += $item;
                   8330:             }
                   8331:         } else {
                   8332:             $expected{$part_id} = $env{"form.scantron.bubblelines.$counter"};
                   8333:         }
                   8334:         $startpos{$part_id} = $env{"form.scantron.first_bubble_line.$counter"};
                   8335:     }
                   8336:     if ($symb) {
                   8337:         my %recorded;
                   8338:         my (%returnhash) = &Apache::lonnet::restore($symb,$cid,$domain,$username);
                   8339:         if ($returnhash{'version'}) {
                   8340:             my %lasthash=();
                   8341:             my $version;
                   8342:             for ($version=1;$version<=$returnhash{'version'};$version++) {
                   8343:                 foreach my $key (sort(split(/\:/,$returnhash{$version.':keys'}))) {
                   8344:                     $lasthash{$key}=$returnhash{$version.':'.$key};
                   8345:                 }
                   8346:             }
                   8347:             foreach my $key (keys(%lasthash)) {
                   8348:                 if ($key =~ /\.scantron$/) {
                   8349:                     my $value = &unescape($lasthash{$key});
                   8350:                     my ($part_id) = ($key =~ /^resource\.(.+)\.scantron$/);
                   8351:                     if ($value eq '') {
                   8352:                         for (my $i=0; $i<$expected{$part_id}; $i++) {
                   8353:                             for (my $j=0; $j<$scantron_config->{'length'}; $j++) {
                   8354:                                 $recorded{$part_id} .= $scantron_config->{'Qoff'};
                   8355:                             }
                   8356:                         }
                   8357:                     } else {
                   8358:                         my @tocheck;
                   8359:                         my @items = split(//,$value);
                   8360:                         if (($scantron_config->{'Qon'} eq 'letter') ||
                   8361:                             ($scantron_config->{'Qon'} eq 'number')) {
                   8362:                             if (@items < $expected{$part_id}) {
                   8363:                                 my $fragment = substr($scandata,$startpos{$part_id},$expected{$part_id});
                   8364:                                 my @singles = split(//,$fragment);
                   8365:                                 foreach my $pos (@singles) {
                   8366:                                     if ($pos eq ' ') {
                   8367:                                         push(@tocheck,$pos);
                   8368:                                     } else {
                   8369:                                         my $next = shift(@items);
                   8370:                                         push(@tocheck,$next);
                   8371:                                     }
                   8372:                                 }
                   8373:                             } else {
                   8374:                                 @tocheck = @items;
                   8375:                             }
                   8376:                             foreach my $letter (@tocheck) {
                   8377:                                 if ($scantron_config->{'Qon'} eq 'letter') {
                   8378:                                     if ($letter !~ /^[A-J]$/) {
                   8379:                                         $letter = $scantron_config->{'Qoff'};
                   8380:                                     }
                   8381:                                     $recorded{$part_id} .= $letter;
                   8382:                                 } elsif ($scantron_config->{'Qon'} eq 'number') {
                   8383:                                     my $digit;
                   8384:                                     if ($letter !~ /^[A-J]$/) {
                   8385:                                         $digit = $scantron_config->{'Qoff'};
                   8386:                                     } else {
                   8387:                                         $digit = $lettdig->{$letter};
                   8388:                                     }
                   8389:                                     $recorded{$part_id} .= $digit;
                   8390:                                 }
                   8391:                             }
                   8392:                         } else {
                   8393:                             @tocheck = @items;
                   8394:                             for (my $i=0; $i<$expected{$part_id}; $i++) {
                   8395:                                 my $curr_sub = shift(@tocheck);
                   8396:                                 my $digit;
                   8397:                                 if ($curr_sub =~ /^[A-J]$/) {
                   8398:                                     $digit = $lettdig->{$curr_sub}-1;
                   8399:                                 }
                   8400:                                 if ($curr_sub eq 'J') {
                   8401:                                     $digit += scalar($numletts);
                   8402:                                 }
                   8403:                                 for (my $j=0; $j<$scantron_config->{'Qlength'}; $j++) {
                   8404:                                     if ($j == $digit) {
                   8405:                                         $recorded{$part_id} .= $scantron_config->{'Qon'};
                   8406:                                     } else {
                   8407:                                         $recorded{$part_id} .= $scantron_config->{'Qoff'};
                   8408:                                     }
                   8409:                                 }
                   8410:                             }
                   8411:                         }
                   8412:                     }
                   8413:                 }
                   8414:             }
                   8415:         }
1.554     raeburn  8416:         foreach my $part_id (@{$partids}) {
1.542     raeburn  8417:             if ($recorded{$part_id} eq '') {
                   8418:                 for (my $i=0; $i<$expected{$part_id}; $i++) {
                   8419:                     for (my $j=0; $j<$scantron_config->{'Qlength'}; $j++) {
                   8420:                         $recorded{$part_id} .= $scantron_config->{'Qoff'};
                   8421:                     }
                   8422:                 }
                   8423:             }
                   8424:             $record .= $recorded{$part_id};
                   8425:         }
                   8426:     }
                   8427:     return ($counter,$record);
                   8428: }
                   8429: 
                   8430: sub letter_to_digits { 
                   8431:     my %lettdig = (
                   8432:                     A => 1,
                   8433:                     B => 2,
                   8434:                     C => 3,
                   8435:                     D => 4,
                   8436:                     E => 5,
                   8437:                     F => 6,
                   8438:                     G => 7,
                   8439:                     H => 8,
                   8440:                     I => 9,
                   8441:                     J => 0,
                   8442:                   );
                   8443:     return %lettdig;
                   8444: }
                   8445: 
1.423     albertel 8446: 
1.75      albertel 8447: #-------- end of section for handling grading scantron forms -------
                   8448: #
                   8449: #-------------------------------------------------------------------
                   8450: 
1.72      ng       8451: #-------------------------- Menu interface -------------------------
                   8452: #
                   8453: #--- Show a Grading Menu button - Calls the next routine ---
                   8454: sub show_grading_menu_form {
1.324     albertel 8455:     my ($symb)=@_;
1.125     ng       8456:     my $result.='<br /><form action="/adm/grades" method="post">'."\n".
1.418     albertel 8457: 	'<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.257     albertel 8458: 	'<input type="hidden" name="saveState"  value="'.$env{'form.saveState'}.'" />'."\n".
1.72      ng       8459: 	'<input type="hidden" name="command" value="gradingmenu" />'."\n".
1.478     albertel 8460: 	'<input type="submit" name="submit" value="'.&mt('Grading Menu').'" />'."\n".
1.72      ng       8461: 	'</form>'."\n";
                   8462:     return $result;
                   8463: }
                   8464: 
1.443     banghart 8465: sub grading_menu {
                   8466:     my ($request) = @_;
                   8467:     my ($symb)=&get_symb($request);
                   8468:     if (!$symb) {return '';}
                   8469: 
                   8470:     my %fields = ('symb'=>&Apache::lonenc::check_encrypt($symb),
1.598     www      8471:                   'command'=>'individual',
1.443     banghart 8472:                   'gradingMenu'=>1,
                   8473:                   'showgrading'=>"yes");
1.538     schulted 8474:     
1.598     www      8475:     my $url1a = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   8476: 
                   8477:     $fields{'command'}='ungraded';
                   8478:     my $url1b=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   8479: 
                   8480:     $fields{'command'}='table';
                   8481:     my $url1c=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   8482: 
                   8483:     $fields{'command'}='all_for_one';
                   8484:     my $url1d=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   8485: 
1.443     banghart 8486:     $fields{'command'} = 'csvform';
1.538     schulted 8487:     my $url2 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   8488:     
1.443     banghart 8489:     $fields{'command'} = 'processclicker';
1.538     schulted 8490:     my $url3 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   8491:     
1.443     banghart 8492:     $fields{'command'} = 'scantron_selectphase';
1.538     schulted 8493:     my $url4 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
1.602     www      8494: 
                   8495:     $fields{'command'} = 'initialverifyreceipt';
                   8496:     my $url5 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
1.538     schulted 8497:     
1.598     www      8498:     my @menu = ({	categorytitle=>'Hand Grading',
1.538     schulted 8499:             items =>[
1.598     www      8500:                         {	linktext => 'Select individual students to grade',
                   8501:                     		url => $url1a,
1.538     schulted 8502:                     		permission => 'F',
                   8503:                     		icon => 'edit-find-replace.png',
1.598     www      8504:                     		linktitle => 'Grade current resource for a selection of students.'
                   8505:                         }, 
                   8506:                         {       linktext => 'Grade ungraded submissions.',
                   8507:                                 url => $url1b,
                   8508:                                 permission => 'F',
                   8509:                                 icon => 'edit-find-replace.png',
                   8510:                                 linktitle => 'Grade all submissions that have not been graded yet.'
1.538     schulted 8511:                         },
1.598     www      8512: 
                   8513:                         {       linktext => 'Grading table',
                   8514:                                 url => $url1c,
                   8515:                                 permission => 'F',
                   8516:                                 icon => 'edit-find-replace.png',
                   8517:                                 linktitle => 'Grade current resource for all students.'
                   8518:                         },
1.600     www      8519:                         {       linktext => 'Grade complete page/sequence/folder for one student',
1.598     www      8520:                                 url => $url1d,
                   8521:                                 permission => 'F',
                   8522:                                 icon => 'edit-find-replace.png',
                   8523:                                 linktitle => 'Grade all resources in current page/sequence/folder for one student.'
                   8524:                         }]},
                   8525:                          { categorytitle=>'Automated Grading',
                   8526:                items =>[
                   8527: 
1.538     schulted 8528:                 	    {	linktext => 'Upload Scores',
                   8529:                     		url => $url2,
                   8530:                     		permission => 'F',
                   8531:                     		icon => 'uploadscores.png',
                   8532:                     		linktitle => 'Specify a file containing the class scores for current resource.'
                   8533:                 	    },
                   8534:                 	    {	linktext => 'Process Clicker',
                   8535:                     		url => $url3,
                   8536:                     		permission => 'F',
                   8537:                     		icon => 'addClickerInfoFile.png',
                   8538:                     		linktitle => 'Specify a file containing the clicker information for this resource.'
                   8539:                 	    },
1.587     raeburn  8540:                 	    {	linktext => 'Grade/Manage/Review Bubblesheets',
1.538     schulted 8541:                     		url => $url4,
                   8542:                     		permission => 'F',
                   8543:                     		icon => 'stat.png',
                   8544:                     		linktitle => 'Grade scantron exams, upload/download scantron data files, and review previously graded scantron exams.'
1.602     www      8545:                 	    },
                   8546:                             {   linktext => 'Verify Receipt No.',
                   8547:                                 url => $url5,
                   8548:                                 permission => 'F',
                   8549:                                 icon => 'edit-find-replace.png',
                   8550:                                 linktitle => 'Verify a system-generated receipt number for correct problem solution.'
                   8551:                             }
                   8552: 
1.538     schulted 8553:                     ]
                   8554:             });
                   8555: 
1.443     banghart 8556:     # Create the menu
                   8557:     my $Str;
1.445     banghart 8558:     $Str .= '<form method="post" action="" name="gradingMenu">';
                   8559:     $Str .= '<input type="hidden" name="command" value="" />'.
                   8560:     	'<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
                   8561: 	'<input type="hidden" name="gradingMenu" value="1" />'."\n".
                   8562: 	'<input type="hidden" name="showgrading" value="yes" />'."\n";
                   8563: 
1.602     www      8564:     $Str .= &Apache::lonhtmlcommon::generate_menu(@menu);
1.443     banghart 8565:     return $Str;    
                   8566: }
                   8567: 
1.598     www      8568: 
                   8569: sub ungraded {
                   8570:     my ($request)=@_;
                   8571:     &submit_options($request);
                   8572: }
                   8573: 
1.599     www      8574: sub submit_options_sequence {
                   8575:     my ($request) = @_;
                   8576:     my ($symb)=&get_symb($request);
                   8577:     if (!$symb) {return '';}
1.600     www      8578:     &commonJSfunctions($request);
                   8579:     my $result;
1.599     www      8580: 
1.600     www      8581:     $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
                   8582:         '<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
                   8583:         '<input type="hidden" name="gradingMenu" value="1" />'."\n".
                   8584:         '<input type="hidden" name="showgrading" value="yes" />'."\n";
                   8585: 
                   8586:     $result.='
                   8587: <h2>
                   8588:   '.&mt('Grade complete page/sequence/folder for one student').'
1.601     www      8589: </h2>'.
                   8590:             &selectfield(0).
                   8591:             '<input type="hidden" name="command" value="pickStudentPage" />
1.600     www      8592:             <div>
                   8593:               <input type="submit" value="'.&mt('Next').' &rarr;" />
                   8594:             </div>
                   8595:         </div>
                   8596:   </form>';
                   8597:     $result .= &show_grading_menu_form($symb);
                   8598:     return $result;
                   8599: }
                   8600: 
                   8601: sub submit_options_table {
                   8602:     my ($request) = @_;
                   8603:     my ($symb)=&get_symb($request);
                   8604:     if (!$symb) {return '';}
1.599     www      8605:     &commonJSfunctions($request);
                   8606:     my $result;
                   8607: 
                   8608:     $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
                   8609:         '<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
                   8610:         '<input type="hidden" name="gradingMenu" value="1" />'."\n".
                   8611:         '<input type="hidden" name="showgrading" value="yes" />'."\n";
                   8612: 
                   8613:     $result.='
                   8614: <h2>
1.600     www      8615:   '.&mt('Grading table').'
1.601     www      8616: </h2>'.
                   8617:             &selectfield(0).
                   8618:             '<input type="hidden" name="command" value="viewgrades" />
1.599     www      8619:             <div>
                   8620:               <input type="submit" value="'.&mt('Next').' &rarr;" />
                   8621:             </div>
                   8622:         </div>
                   8623:   </form>';
                   8624:     $result .= &show_grading_menu_form($symb);
                   8625:     return $result;
                   8626: }
1.443     banghart 8627: 
1.600     www      8628: 
                   8629: 
1.443     banghart 8630: #--- Displays the submissions first page -------
                   8631: sub submit_options {
1.72      ng       8632:     my ($request) = @_;
1.324     albertel 8633:     my ($symb)=&get_symb($request);
1.72      ng       8634:     if (!$symb) {return '';}
                   8635: 
1.118     ng       8636:     &commonJSfunctions($request);
1.473     albertel 8637:     my $result;
1.533     bisitz   8638: 
1.72      ng       8639:     $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
1.418     albertel 8640: 	'<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.124     ng       8641: 	'<input type="hidden" name="gradingMenu" value="1" />'."\n".
1.72      ng       8642: 	'<input type="hidden" name="showgrading" value="yes" />'."\n";
                   8643: 
1.472     albertel 8644:     $result.='
1.533     bisitz   8645: <h2>
1.600     www      8646:   '.&mt('Select individual students to grade').'
1.601     www      8647: </h2>'.&selectfield(1).'
                   8648:                 <input type="hidden" name="command" value="submission" /> 
                   8649: 	      <input type="submit" value="'.&mt('Next').' &rarr;" />
                   8650:             </div>
                   8651:           </div>
                   8652: 
                   8653: 
                   8654:   </form>';
                   8655:     $result .= &show_grading_menu_form($symb);
                   8656:     return $result;
                   8657: }
1.533     bisitz   8658: 
1.601     www      8659: sub selectfield {
                   8660:    my ($full)=@_;
                   8661:    my $result='<div class="LC_columnSection">
1.537     harmsja  8662:   
1.533     bisitz   8663:     <fieldset>
                   8664:       <legend>
                   8665:        '.&mt('Sections').'
                   8666:       </legend>
1.601     www      8667:       '.&Apache::lonstatistics::SectionSelect('section','multiple',5).'
1.533     bisitz   8668:     </fieldset>
1.537     harmsja  8669:   
1.533     bisitz   8670:     <fieldset>
                   8671:       <legend>
                   8672:         '.&mt('Groups').'
                   8673:       </legend>
                   8674:       '.&Apache::lonstatistics::GroupSelect('group','multiple',5).'
                   8675:     </fieldset>
1.537     harmsja  8676:   
1.533     bisitz   8677:     <fieldset>
                   8678:       <legend>
                   8679:         '.&mt('Access Status').'
                   8680:       </legend>
1.601     www      8681:       '.&Apache::lonhtmlcommon::StatusOptions(undef,undef,5,undef,'mult').'
                   8682:     </fieldset>';
                   8683:     if ($full) {
                   8684:        $result.='
1.533     bisitz   8685:     <fieldset>
                   8686:       <legend>
                   8687:         '.&mt('Submission Status').'
1.601     www      8688:       </legend>'.
                   8689:        &Apache::loncommon::select_form('all','submitonly',
                   8690:           (&Apache::lonlocal::texthash(
                   8691:              'yes'       => 'with submissions',
                   8692:              'queued'    => 'in grading queue',
                   8693:              'graded'    => 'with ungraded submissions',
                   8694:              'incorrect' => 'with incorrect submissions',
                   8695:              'all'       => 'with any status'),
                   8696:              'select_form_order' => ['yes','queued','graded','incorrect','all'])).
                   8697:    '</fieldset>';
                   8698:     }
                   8699:     $result.='</div><br />';
1.44      ng       8700:     return $result;
1.2       albertel 8701: }
                   8702: 
1.285     albertel 8703: sub reset_perm {
                   8704:     undef(%perm);
                   8705: }
                   8706: 
                   8707: sub init_perm {
                   8708:     &reset_perm();
1.300     albertel 8709:     foreach my $test_perm ('vgr','mgr','opa') {
                   8710: 
                   8711: 	my $scope = $env{'request.course.id'};
                   8712: 	if (!($perm{$test_perm}=&Apache::lonnet::allowed($test_perm,$scope))) {
                   8713: 
                   8714: 	    $scope .= '/'.$env{'request.course.sec'};
                   8715: 	    if ( $perm{$test_perm}=
                   8716: 		 &Apache::lonnet::allowed($test_perm,$scope)) {
                   8717: 		$perm{$test_perm.'_section'}=$env{'request.course.sec'};
                   8718: 	    } else {
                   8719: 		delete($perm{$test_perm});
                   8720: 	    }
1.285     albertel 8721: 	}
                   8722:     }
                   8723: }
                   8724: 
1.400     www      8725: sub gather_clicker_ids {
1.408     albertel 8726:     my %clicker_ids;
1.400     www      8727: 
                   8728:     my $classlist = &Apache::loncoursedata::get_classlist();
                   8729: 
                   8730:     # Set up a couple variables.
1.407     albertel 8731:     my $username_idx = &Apache::loncoursedata::CL_SNAME();
                   8732:     my $domain_idx   = &Apache::loncoursedata::CL_SDOM();
1.438     www      8733:     my $status_idx   = &Apache::loncoursedata::CL_STATUS();
1.400     www      8734: 
1.407     albertel 8735:     foreach my $student (keys(%$classlist)) {
1.438     www      8736:         if ($classlist->{$student}->[$status_idx] ne 'Active') { next; }
1.407     albertel 8737:         my $username = $classlist->{$student}->[$username_idx];
                   8738:         my $domain   = $classlist->{$student}->[$domain_idx];
1.400     www      8739:         my $clickers =
1.408     albertel 8740: 	    (&Apache::lonnet::userenvironment($domain,$username,'clickers'))[1];
1.400     www      8741:         foreach my $id (split(/\,/,$clickers)) {
1.414     www      8742:             $id=~s/^[\#0]+//;
1.421     www      8743:             $id=~s/[\-\:]//g;
1.407     albertel 8744:             if (exists($clicker_ids{$id})) {
1.408     albertel 8745: 		$clicker_ids{$id}.=','.$username.':'.$domain;
1.400     www      8746:             } else {
1.408     albertel 8747: 		$clicker_ids{$id}=$username.':'.$domain;
1.400     www      8748:             }
                   8749:         }
                   8750:     }
1.407     albertel 8751:     return %clicker_ids;
1.400     www      8752: }
                   8753: 
1.402     www      8754: sub gather_adv_clicker_ids {
1.408     albertel 8755:     my %clicker_ids;
1.402     www      8756:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
                   8757:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   8758:     my %coursepersonnel=&Apache::lonnet::get_course_adv_roles($cdom.'/'.$cnum);
1.409     albertel 8759:     foreach my $element (sort(keys(%coursepersonnel))) {
1.402     www      8760:         foreach my $person (split(/\,/,$coursepersonnel{$element})) {
                   8761:             my ($puname,$pudom)=split(/\:/,$person);
                   8762:             my $clickers =
1.408     albertel 8763: 		(&Apache::lonnet::userenvironment($pudom,$puname,'clickers'))[1];
1.405     www      8764:             foreach my $id (split(/\,/,$clickers)) {
1.414     www      8765: 		$id=~s/^[\#0]+//;
1.421     www      8766:                 $id=~s/[\-\:]//g;
1.408     albertel 8767: 		if (exists($clicker_ids{$id})) {
                   8768: 		    $clicker_ids{$id}.=','.$puname.':'.$pudom;
                   8769: 		} else {
                   8770: 		    $clicker_ids{$id}=$puname.':'.$pudom;
                   8771: 		}
1.405     www      8772:             }
1.402     www      8773:         }
                   8774:     }
1.407     albertel 8775:     return %clicker_ids;
1.402     www      8776: }
                   8777: 
1.413     www      8778: sub clicker_grading_parameters {
                   8779:     return ('gradingmechanism' => 'scalar',
                   8780:             'upfiletype' => 'scalar',
                   8781:             'specificid' => 'scalar',
                   8782:             'pcorrect' => 'scalar',
                   8783:             'pincorrect' => 'scalar');
                   8784: }
                   8785: 
1.400     www      8786: sub process_clicker {
                   8787:     my ($r)=@_;
                   8788:     my ($symb)=&get_symb($r);
                   8789:     if (!$symb) {return '';}
                   8790:     my $result=&checkforfile_js();
                   8791:     $result.='<br /><table width="100%" border="0"><tr><td bgcolor="#777777">'."\n";
                   8792:     $result.='<table width="100%" border="0"><tr bgcolor="#e6ffff"><td>'."\n";
1.538     schulted 8793:     $result.='&nbsp;<b>'.&mt('Specify a file containing the clicker information for this resource.').
                   8794:         '</b></td></tr>'."\n";
1.601     www      8795:     $result.='<tr bgcolor="#ffffe6"><td>'."\n";
1.413     www      8796: # Attempt to restore parameters from last session, set defaults if not present
                   8797:     my %Saveable_Parameters=&clicker_grading_parameters();
                   8798:     &Apache::loncommon::restore_course_settings('grades_clicker',
                   8799:                                                  \%Saveable_Parameters);
                   8800:     if (!$env{'form.pcorrect'}) { $env{'form.pcorrect'}=100; }
                   8801:     if (!$env{'form.pincorrect'}) { $env{'form.pincorrect'}=100; }
                   8802:     if (!$env{'form.gradingmechanism'}) { $env{'form.gradingmechanism'}='attendance'; }
                   8803:     if (!$env{'form.upfiletype'}) { $env{'form.upfiletype'}='iclicker'; }
                   8804: 
                   8805:     my %checked;
1.521     www      8806:     foreach my $gradingmechanism ('attendance','personnel','specific','given') {
1.413     www      8807:        if ($env{'form.gradingmechanism'} eq $gradingmechanism) {
1.569     bisitz   8808:           $checked{$gradingmechanism}=' checked="checked"';
1.413     www      8809:        }
                   8810:     }
                   8811: 
1.400     www      8812:     my $upload=&mt("Upload File");
                   8813:     my $type=&mt("Type");
1.402     www      8814:     my $attendance=&mt("Award points just for participation");
                   8815:     my $personnel=&mt("Correctness determined from response by course personnel");
1.414     www      8816:     my $specific=&mt("Correctness determined from response with clicker ID(s)"); 
1.521     www      8817:     my $given=&mt("Correctness determined from given list of answers").' '.
                   8818:               '<font size="-2"><tt>('.&mt("Provide comma-separated list. Use '*' for any answer correct, '-' for skip").')</tt></font>';
1.402     www      8819:     my $pcorrect=&mt("Percentage points for correct solution");
                   8820:     my $pincorrect=&mt("Percentage points for incorrect solution");
1.413     www      8821:     my $selectform=&Apache::loncommon::select_form($env{'form.upfiletype'},'upfiletype',
1.419     www      8822: 						   ('iclicker' => 'i>clicker',
                   8823:                                                     'interwrite' => 'interwrite PRS'));
1.418     albertel 8824:     $symb = &Apache::lonenc::check_encrypt($symb);
1.597     wenzelju 8825:     $result.= &Apache::lonhtmlcommon::scripttag(<<ENDUPFORM);
1.402     www      8826: function sanitycheck() {
                   8827: // Accept only integer percentages
                   8828:    document.forms.gradesupload.pcorrect.value=Math.round(document.forms.gradesupload.pcorrect.value);
                   8829:    document.forms.gradesupload.pincorrect.value=Math.round(document.forms.gradesupload.pincorrect.value);
                   8830: // Find out grading choice
                   8831:    for (i=0; i<document.forms.gradesupload.gradingmechanism.length; i++) {
                   8832:       if (document.forms.gradesupload.gradingmechanism[i].checked) {
                   8833:          gradingchoice=document.forms.gradesupload.gradingmechanism[i].value;
                   8834:       }
                   8835:    }
                   8836: // By default, new choice equals user selection
                   8837:    newgradingchoice=gradingchoice;
                   8838: // Not good to give more points for false answers than correct ones
                   8839:    if (Math.round(document.forms.gradesupload.pcorrect.value)<Math.round(document.forms.gradesupload.pincorrect.value)) {
                   8840:       document.forms.gradesupload.pcorrect.value=document.forms.gradesupload.pincorrect.value;
                   8841:    }
                   8842: // If new choice is attendance only, and old choice was correctness-based, restore defaults
                   8843:    if ((gradingchoice=='attendance') && (document.forms.gradesupload.waschecked.value!='attendance')) {
                   8844:       document.forms.gradesupload.pcorrect.value=100;
                   8845:       document.forms.gradesupload.pincorrect.value=100;
                   8846:    }
                   8847: // If the values are different, cannot be attendance only
                   8848:    if ((Math.round(document.forms.gradesupload.pcorrect.value)!=Math.round(document.forms.gradesupload.pincorrect.value)) &&
                   8849:        (gradingchoice=='attendance')) {
                   8850:        newgradingchoice='personnel';
                   8851:    }
                   8852: // Change grading choice to new one
                   8853:    for (i=0; i<document.forms.gradesupload.gradingmechanism.length; i++) {
                   8854:       if (document.forms.gradesupload.gradingmechanism[i].value==newgradingchoice) {
                   8855:          document.forms.gradesupload.gradingmechanism[i].checked=true;
                   8856:       } else {
                   8857:          document.forms.gradesupload.gradingmechanism[i].checked=false;
                   8858:       }
                   8859:    }
                   8860: // Remember the old state
                   8861:    document.forms.gradesupload.waschecked.value=newgradingchoice;
                   8862: }
1.597     wenzelju 8863: ENDUPFORM
                   8864:     $result.= <<ENDUPFORM;
1.400     www      8865: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
                   8866: <input type="hidden" name="symb" value="$symb" />
                   8867: <input type="hidden" name="command" value="processclickerfile" />
                   8868: <input type="hidden" name="saveState"  value="$env{'form.saveState'}" />
                   8869: <input type="file" name="upfile" size="50" />
                   8870: <br /><label>$type: $selectform</label>
1.589     bisitz   8871: <br /><label><input type="radio" name="gradingmechanism" value="attendance"$checked{'attendance'} onclick="sanitycheck()" />$attendance </label>
                   8872: <br /><label><input type="radio" name="gradingmechanism" value="personnel"$checked{'personnel'} onclick="sanitycheck()" />$personnel</label>
                   8873: <br /><label><input type="radio" name="gradingmechanism" value="specific"$checked{'specific'} onclick="sanitycheck()" />$specific </label>
1.414     www      8874: <input type="text" name="specificid" value="$env{'form.specificid'}" size="20" />
1.589     bisitz   8875: <br /><label><input type="radio" name="gradingmechanism" value="given"$checked{'given'} onclick="sanitycheck()" />$given </label>
1.521     www      8876: <br />&nbsp;&nbsp;&nbsp;
                   8877: <input type="text" name="givenanswer" size="50" />
1.413     www      8878: <input type="hidden" name="waschecked" value="$env{'form.gradingmechanism'}" />
1.589     bisitz   8879: <br /><label>$pcorrect: <input type="text" name="pcorrect" size="4" value="$env{'form.pcorrect'}" onchange="sanitycheck()" /></label>
                   8880: <br /><label>$pincorrect: <input type="text" name="pincorrect" size="4" value="$env{'form.pincorrect'}" onchange="sanitycheck()" /></label>
                   8881: <br /><input type="button" onclick="javascript:checkUpload(this.form);" value="$upload" />
1.597     wenzelju 8882: </form>'
1.400     www      8883: ENDUPFORM
                   8884:     $result.='</td></tr></table>'."\n".
                   8885:              '</td></tr></table><br /><br />'."\n";
                   8886:     $result.=&show_grading_menu_form($symb);
                   8887:     return $result;
                   8888: }
                   8889: 
                   8890: sub process_clicker_file {
                   8891:     my ($r)=@_;
                   8892:     my ($symb)=&get_symb($r);
                   8893:     if (!$symb) {return '';}
1.413     www      8894: 
                   8895:     my %Saveable_Parameters=&clicker_grading_parameters();
                   8896:     &Apache::loncommon::store_course_settings('grades_clicker',
                   8897:                                               \%Saveable_Parameters);
1.598     www      8898:     my $result='';
1.404     www      8899:     if (($env{'form.gradingmechanism'} eq 'specific') && ($env{'form.specificid'}!~/\w/)) {
1.408     albertel 8900: 	$result.='<span class="LC_error">'.&mt('You need to specify a clicker ID for the correct answer').'</span>';
                   8901: 	return $result.&show_grading_menu_form($symb);
1.404     www      8902:     }
1.522     www      8903:     if (($env{'form.gradingmechanism'} eq 'given') && ($env{'form.givenanswer'}!~/\S/)) {
1.521     www      8904:         $result.='<span class="LC_error">'.&mt('You need to specify the correct answer').'</span>';
                   8905:         return $result.&show_grading_menu_form($symb);
                   8906:     }
1.522     www      8907:     my $foundgiven=0;
1.521     www      8908:     if ($env{'form.gradingmechanism'} eq 'given') {
                   8909:         $env{'form.givenanswer'}=~s/^\s*//gs;
                   8910:         $env{'form.givenanswer'}=~s/\s*$//gs;
                   8911:         $env{'form.givenanswer'}=~s/[^a-zA-Z0-9\.\*\-]+/\,/g;
                   8912:         $env{'form.givenanswer'}=uc($env{'form.givenanswer'});
1.522     www      8913:         my @answers=split(/\,/,$env{'form.givenanswer'});
                   8914:         $foundgiven=$#answers+1;
1.521     www      8915:     }
1.407     albertel 8916:     my %clicker_ids=&gather_clicker_ids();
1.408     albertel 8917:     my %correct_ids;
1.404     www      8918:     if ($env{'form.gradingmechanism'} eq 'personnel') {
1.408     albertel 8919: 	%correct_ids=&gather_adv_clicker_ids();
1.404     www      8920:     }
                   8921:     if ($env{'form.gradingmechanism'} eq 'specific') {
1.414     www      8922: 	foreach my $correct_id (split(/[\s\,]/,$env{'form.specificid'})) {;
                   8923: 	   $correct_id=~tr/a-z/A-Z/;
                   8924: 	   $correct_id=~s/\s//gs;
                   8925: 	   $correct_id=~s/^[\#0]+//;
1.421     www      8926:            $correct_id=~s/[\-\:]//g;
1.414     www      8927:            if ($correct_id) {
                   8928: 	      $correct_ids{$correct_id}='specified';
                   8929:            }
                   8930:         }
1.400     www      8931:     }
1.404     www      8932:     if ($env{'form.gradingmechanism'} eq 'attendance') {
1.408     albertel 8933: 	$result.=&mt('Score based on attendance only');
1.521     www      8934:     } elsif ($env{'form.gradingmechanism'} eq 'given') {
1.522     www      8935:         $result.=&mt('Score based on [_1] ([_2] answers)','<tt>'.$env{'form.givenanswer'}.'</tt>',$foundgiven);
1.404     www      8936:     } else {
1.408     albertel 8937: 	my $number=0;
1.411     www      8938: 	$result.='<p><b>'.&mt('Correctness determined by the following IDs').'</b>';
1.408     albertel 8939: 	foreach my $id (sort(keys(%correct_ids))) {
1.411     www      8940: 	    $result.='<br /><tt>'.$id.'</tt> - ';
1.408     albertel 8941: 	    if ($correct_ids{$id} eq 'specified') {
                   8942: 		$result.=&mt('specified');
                   8943: 	    } else {
                   8944: 		my ($uname,$udom)=split(/\:/,$correct_ids{$id});
                   8945: 		$result.=&Apache::loncommon::plainname($uname,$udom);
                   8946: 	    }
                   8947: 	    $number++;
                   8948: 	}
1.411     www      8949:         $result.="</p>\n";
1.408     albertel 8950: 	if ($number==0) {
                   8951: 	    $result.='<span class="LC_error">'.&mt('No IDs found to determine correct answer').'</span>';
                   8952: 	    return $result.&show_grading_menu_form($symb);
                   8953: 	}
1.404     www      8954:     }
1.405     www      8955:     if (length($env{'form.upfile'}) < 2) {
1.407     albertel 8956:         $result.=&mt('[_1] Error: [_2] The file you attempted to upload, [_3] contained no information. Please check that you entered the correct filename.',
                   8957: 		     '<span class="LC_error">',
                   8958: 		     '</span>',
                   8959: 		     '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>');
1.405     www      8960:         return $result.&show_grading_menu_form($symb);
                   8961:     }
1.410     www      8962: 
                   8963: # Were able to get all the info needed, now analyze the file
                   8964: 
1.411     www      8965:     $result.=&Apache::loncommon::studentbrowser_javascript();
1.418     albertel 8966:     $symb = &Apache::lonenc::check_encrypt($symb);
1.410     www      8967:     my $heading=&mt('Scanning clicker file');
                   8968:     $result.=(<<ENDHEADER);
                   8969: <br /><table width="100%" border="0"><tr><td bgcolor="#777777">
                   8970: <table width="100%" border="0"><tr bgcolor="#e6ffff"><td>
                   8971: <b>$heading</b></td></tr><tr bgcolor=#ffffe6><td>
                   8972: <form method="post" action="/adm/grades" name="clickeranalysis">
                   8973: <input type="hidden" name="symb" value="$symb" />
                   8974: <input type="hidden" name="command" value="assignclickergrades" />
                   8975: <input type="hidden" name="saveState"  value="$env{'form.saveState'}" />
1.411     www      8976: <input type="hidden" name="gradingmechanism" value="$env{'form.gradingmechanism'}" />
                   8977: <input type="hidden" name="pcorrect" value="$env{'form.pcorrect'}" />
                   8978: <input type="hidden" name="pincorrect" value="$env{'form.pincorrect'}" />
1.410     www      8979: ENDHEADER
1.522     www      8980:     if ($env{'form.gradingmechanism'} eq 'given') {
                   8981:        $result.='<input type="hidden" name="correct:given" value="'.$env{'form.givenanswer'}.'" />';
                   8982:     } 
1.408     albertel 8983:     my %responses;
                   8984:     my @questiontitles;
1.405     www      8985:     my $errormsg='';
                   8986:     my $number=0;
                   8987:     if ($env{'form.upfiletype'} eq 'iclicker') {
1.408     albertel 8988: 	($errormsg,$number)=&iclicker_eval(\@questiontitles,\%responses);
1.406     www      8989:     }
1.419     www      8990:     if ($env{'form.upfiletype'} eq 'interwrite') {
                   8991:         ($errormsg,$number)=&interwrite_eval(\@questiontitles,\%responses);
                   8992:     }
1.411     www      8993:     $result.='<br />'.&mt('Found [_1] question(s)',$number).'<br />'.
                   8994:              '<input type="hidden" name="number" value="'.$number.'" />'.
                   8995:              &mt('Awarding [_1] percent for correct and [_2] percent for incorrect responses',
                   8996:                  $env{'form.pcorrect'},$env{'form.pincorrect'}).
                   8997:              '<br />';
1.522     www      8998:     if (($env{'form.gradingmechanism'} eq 'given') && ($number!=$foundgiven)) {
                   8999:        $result.='<span class="LC_error">'.&mt('Number of given answers does not agree with number of questions in file.').'</span>';
                   9000:        return $result.&show_grading_menu_form($symb);
                   9001:     } 
1.414     www      9002: # Remember Question Titles
                   9003: # FIXME: Possibly need delimiter other than ":"
                   9004:     for (my $i=0;$i<$number;$i++) {
                   9005:         $result.='<input type="hidden" name="question:'.$i.'" value="'.
                   9006:                  &HTML::Entities::encode($questiontitles[$i],'"&<>').'" />';
                   9007:     }
1.411     www      9008:     my $correct_count=0;
                   9009:     my $student_count=0;
                   9010:     my $unknown_count=0;
1.414     www      9011: # Match answers with usernames
                   9012: # FIXME: Possibly need delimiter other than ":"
1.409     albertel 9013:     foreach my $id (keys(%responses)) {
1.410     www      9014:        if ($correct_ids{$id}) {
1.414     www      9015:           $result.="\n".'<input type="hidden" name="correct:'.$correct_count.':'.$correct_ids{$id}.'" value="'.$responses{$id}.'" />';
1.411     www      9016:           $correct_count++;
1.410     www      9017:        } elsif ($clicker_ids{$id}) {
1.437     www      9018:           if ($clicker_ids{$id}=~/\,/) {
                   9019: # More than one user with the same clicker!
                   9020:              $result.="\n<hr />".&mt('Clicker registered more than once').": <tt>".$id."</tt><br />";
                   9021:              $result.="\n".'<input type="hidden" name="unknown:'.$id.'" value="'.$responses{$id}.'" />'.
                   9022:                            "<select name='multi".$id."'>";
                   9023:              foreach my $reguser (sort(split(/\,/,$clicker_ids{$id}))) {
                   9024:                  $result.="<option value='".$reguser."'>".&Apache::loncommon::plainname(split(/\:/,$reguser)).' ('.$reguser.')</option>';
                   9025:              }
                   9026:              $result.='</select>';
                   9027:              $unknown_count++;
                   9028:           } else {
                   9029: # Good: found one and only one user with the right clicker
                   9030:              $result.="\n".'<input type="hidden" name="student:'.$clicker_ids{$id}.'" value="'.$responses{$id}.'" />';
                   9031:              $student_count++;
                   9032:           }
1.410     www      9033:        } else {
1.411     www      9034:           $result.="\n<hr />".&mt('Unregistered Clicker')." <tt>".$id."</tt><br />";
                   9035:           $result.="\n".'<input type="hidden" name="unknown:'.$id.'" value="'.$responses{$id}.'" />'.
                   9036:                    "\n".&mt("Username").": <input type='text' name='uname".$id."' />&nbsp;".
                   9037:                    "\n".&mt("Domain").": ".
                   9038:                    &Apache::loncommon::select_dom_form($env{'course.'.$env{'request.course.id'}.'.domain'},'udom'.$id).'&nbsp;'.
                   9039:                    &Apache::loncommon::selectstudent_link('clickeranalysis','uname'.$id,'udom'.$id);
                   9040:           $unknown_count++;
1.410     www      9041:        }
1.405     www      9042:     }
1.412     www      9043:     $result.='<hr />'.
                   9044:              &mt('Found [_1] registered and [_2] unregistered clickers.',$student_count,$unknown_count);
1.521     www      9045:     if (($env{'form.gradingmechanism'} ne 'attendance') && ($env{'form.gradingmechanism'} ne 'given')) {
1.412     www      9046:        if ($correct_count==0) {
                   9047:           $errormsg.="Found no correct answers answers for grading!";
                   9048:        } elsif ($correct_count>1) {
1.414     www      9049:           $result.='<br /><span class="LC_warning">'.&mt("Found [_1] entries for grading!",$correct_count).'</span>';
1.412     www      9050:        }
                   9051:     }
1.428     www      9052:     if ($number<1) {
                   9053:        $errormsg.="Found no questions.";
                   9054:     }
1.412     www      9055:     if ($errormsg) {
                   9056:        $result.='<br /><span class="LC_error">'.&mt($errormsg).'</span>';
                   9057:     } else {
                   9058:        $result.='<br /><input type="submit" name="finalize" value="'.&mt('Finalize Grading').'" />';
                   9059:     }
                   9060:     $result.='</form></td></tr></table>'."\n".
1.410     www      9061:              '</td></tr></table><br /><br />'."\n";
1.404     www      9062:     return $result.&show_grading_menu_form($symb);
1.400     www      9063: }
                   9064: 
1.405     www      9065: sub iclicker_eval {
1.406     www      9066:     my ($questiontitles,$responses)=@_;
1.405     www      9067:     my $number=0;
                   9068:     my $errormsg='';
                   9069:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
1.410     www      9070:         my %components=&Apache::loncommon::record_sep($line);
                   9071:         my @entries=map {$components{$_}} (sort(keys(%components)));
1.408     albertel 9072: 	if ($entries[0] eq 'Question') {
                   9073: 	    for (my $i=3;$i<$#entries;$i+=6) {
                   9074: 		$$questiontitles[$number]=$entries[$i];
                   9075: 		$number++;
                   9076: 	    }
                   9077: 	}
                   9078: 	if ($entries[0]=~/^\#/) {
                   9079: 	    my $id=$entries[0];
                   9080: 	    my @idresponses;
                   9081: 	    $id=~s/^[\#0]+//;
                   9082: 	    for (my $i=0;$i<$number;$i++) {
                   9083: 		my $idx=3+$i*6;
                   9084: 		push(@idresponses,$entries[$idx]);
                   9085: 	    }
                   9086: 	    $$responses{$id}=join(',',@idresponses);
                   9087: 	}
1.405     www      9088:     }
                   9089:     return ($errormsg,$number);
                   9090: }
                   9091: 
1.419     www      9092: sub interwrite_eval {
                   9093:     my ($questiontitles,$responses)=@_;
                   9094:     my $number=0;
                   9095:     my $errormsg='';
1.420     www      9096:     my $skipline=1;
                   9097:     my $questionnumber=0;
                   9098:     my %idresponses=();
1.419     www      9099:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
                   9100:         my %components=&Apache::loncommon::record_sep($line);
                   9101:         my @entries=map {$components{$_}} (sort(keys(%components)));
1.420     www      9102:         if ($entries[1] eq 'Time') { $skipline=0; next; }
                   9103:         if ($entries[1] eq 'Response') { $skipline=1; }
                   9104:         next if $skipline;
                   9105:         if ($entries[0]!=$questionnumber) {
                   9106:            $questionnumber=$entries[0];
                   9107:            $$questiontitles[$number]=&mt('Question [_1]',$questionnumber);
                   9108:            $number++;
1.419     www      9109:         }
1.420     www      9110:         my $id=$entries[4];
                   9111:         $id=~s/^[\#0]+//;
1.421     www      9112:         $id=~s/^v\d*\://i;
                   9113:         $id=~s/[\-\:]//g;
1.420     www      9114:         $idresponses{$id}[$number]=$entries[6];
                   9115:     }
1.524     raeburn  9116:     foreach my $id (keys(%idresponses)) {
1.420     www      9117:        $$responses{$id}=join(',',@{$idresponses{$id}});
                   9118:        $$responses{$id}=~s/^\s*\,//;
1.419     www      9119:     }
                   9120:     return ($errormsg,$number);
                   9121: }
                   9122: 
1.414     www      9123: sub assign_clicker_grades {
                   9124:     my ($r)=@_;
                   9125:     my ($symb)=&get_symb($r);
                   9126:     if (!$symb) {return '';}
1.416     www      9127: # See which part we are saving to
1.582     raeburn  9128:     my $res_error;
                   9129:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
                   9130:     if ($res_error) {
                   9131:         return &navmap_errormsg();
                   9132:     }
1.416     www      9133: # FIXME: This should probably look for the first handgradeable part
                   9134:     my $part=$$partlist[0];
                   9135: # Start screen output
1.598     www      9136:     my $result='';
1.416     www      9137: 
1.414     www      9138:     my $heading=&mt('Assigning grades based on clicker file');
                   9139:     $result.=(<<ENDHEADER);
                   9140: <br /><table width="100%" border="0"><tr><td bgcolor="#777777">
                   9141: <table width="100%" border="0"><tr bgcolor="#e6ffff"><td>
                   9142: <b>$heading</b></td></tr><tr bgcolor=#ffffe6><td>
                   9143: ENDHEADER
                   9144: # Get correct result
                   9145: # FIXME: Possibly need delimiter other than ":"
                   9146:     my @correct=();
1.415     www      9147:     my $gradingmechanism=$env{'form.gradingmechanism'};
                   9148:     my $number=$env{'form.number'};
                   9149:     if ($gradingmechanism ne 'attendance') {
1.414     www      9150:        foreach my $key (keys(%env)) {
                   9151:           if ($key=~/^form\.correct\:/) {
                   9152:              my @input=split(/\,/,$env{$key});
                   9153:              for (my $i=0;$i<=$#input;$i++) {
                   9154:                  if (($correct[$i]) && ($input[$i]) &&
                   9155:                      ($correct[$i] ne $input[$i])) {
                   9156:                     $result.='<br /><span class="LC_warning">'.
                   9157:                              &mt('More than one correct result given for question "[_1]": [_2] versus [_3].',
                   9158:                                  $env{'form.question:'.$i},$correct[$i],$input[$i]).'</span>';
                   9159:                  } elsif ($input[$i]) {
                   9160:                     $correct[$i]=$input[$i];
                   9161:                  }
                   9162:              }
                   9163:           }
                   9164:        }
1.415     www      9165:        for (my $i=0;$i<$number;$i++) {
1.414     www      9166:           if (!$correct[$i]) {
                   9167:              $result.='<br /><span class="LC_error">'.
                   9168:                       &mt('No correct result given for question "[_1]"!',
                   9169:                           $env{'form.question:'.$i}).'</span>';
                   9170:           }
                   9171:        }
                   9172:        $result.='<br />'.&mt("Correct answer: [_1]",join(', ',map { ($_?$_:'-') } @correct));
                   9173:     }
                   9174: # Start grading
1.415     www      9175:     my $pcorrect=$env{'form.pcorrect'};
                   9176:     my $pincorrect=$env{'form.pincorrect'};
1.416     www      9177:     my $storecount=0;
1.415     www      9178:     foreach my $key (keys(%env)) {
1.420     www      9179:        my $user='';
1.415     www      9180:        if ($key=~/^form\.student\:(.*)$/) {
1.420     www      9181:           $user=$1;
                   9182:        }
                   9183:        if ($key=~/^form\.unknown\:(.*)$/) {
                   9184:           my $id=$1;
                   9185:           if (($env{'form.uname'.$id}) && ($env{'form.udom'.$id})) {
                   9186:              $user=$env{'form.uname'.$id}.':'.$env{'form.udom'.$id};
1.437     www      9187:           } elsif ($env{'form.multi'.$id}) {
                   9188:              $user=$env{'form.multi'.$id};
1.420     www      9189:           }
                   9190:        }
                   9191:        if ($user) { 
1.415     www      9192:           my @answer=split(/\,/,$env{$key});
                   9193:           my $sum=0;
1.522     www      9194:           my $realnumber=$number;
1.415     www      9195:           for (my $i=0;$i<$number;$i++) {
1.576     www      9196:              if  ($correct[$i] eq '-') {
                   9197:                 $realnumber--;
                   9198:              } elsif ($answer[$i]) {
1.415     www      9199:                 if ($gradingmechanism eq 'attendance') {
                   9200:                    $sum+=$pcorrect;
1.576     www      9201:                 } elsif ($correct[$i] eq '*') {
1.522     www      9202:                    $sum+=$pcorrect;
1.415     www      9203:                 } else {
                   9204:                    if ($answer[$i] eq $correct[$i]) {
                   9205:                       $sum+=$pcorrect;
                   9206:                    } else {
                   9207:                       $sum+=$pincorrect;
                   9208:                    }
                   9209:                 }
                   9210:              }
                   9211:           }
1.522     www      9212:           my $ave=$sum/(100*$realnumber);
1.416     www      9213: # Store
                   9214:           my ($username,$domain)=split(/\:/,$user);
                   9215:           my %grades=();
                   9216:           $grades{"resource.$part.solved"}='correct_by_override';
                   9217:           $grades{"resource.$part.awarded"}=$ave;
                   9218:           $grades{"resource.regrader"}="$env{'user.name'}:$env{'user.domain'}";
                   9219:           my $returncode=&Apache::lonnet::cstore(\%grades,$symb,
                   9220:                                                  $env{'request.course.id'},
                   9221:                                                  $domain,$username);
                   9222:           if ($returncode ne 'ok') {
                   9223:              $result.="<br /><span class=\"LC_error\">Failed to save student $username:$domain. Message when trying to save was ($returncode)</span>";
                   9224:           } else {
                   9225:              $storecount++;
                   9226:           }
1.415     www      9227:        }
                   9228:     }
                   9229: # We are done
1.549     hauer    9230:     $result.='<br />'.&mt('Successfully stored grades for [quant,_1,student].',$storecount).
1.416     www      9231:              '</td></tr></table>'."\n".
1.414     www      9232:              '</td></tr></table><br /><br />'."\n";
                   9233:     return $result.&show_grading_menu_form($symb);
                   9234: }
                   9235: 
1.582     raeburn  9236: sub navmap_errormsg {
                   9237:     return '<div class="LC_error">'.
                   9238:            &mt('An error occurred retrieving information about resources in the course.').'<br />'.
1.595     raeburn  9239:            &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  9240:            '</div>';
                   9241: }
1.607   ! droeschl 9242: sub startpage{
        !          9243:     my ($r,$crumbs) = @_;
        !          9244: 
        !          9245:     unshift(@$crumbs,  {href=>"/adm/grades",text=>"Grading"});
        !          9246:     $r->print(&Apache::loncommon::start_page('Grading',undef,
        !          9247:                                           {'bread_crumbs' => $crumbs}));
        !          9248: }
1.582     raeburn  9249: 
1.1       albertel 9250: sub handler {
1.41      ng       9251:     my $request=$_[0];
1.434     albertel 9252:     &reset_caches();
1.257     albertel 9253:     if ($env{'browser.mathml'}) {
1.141     www      9254: 	&Apache::loncommon::content_type($request,'text/xml');
1.41      ng       9255:     } else {
1.141     www      9256: 	&Apache::loncommon::content_type($request,'text/html');
1.41      ng       9257:     }
                   9258:     $request->send_http_header;
1.44      ng       9259:     return '' if $request->header_only;
1.41      ng       9260:     &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'});
1.324     albertel 9261:     my $symb=&get_symb($request,1);
1.160     albertel 9262:     my @commands=&Apache::loncommon::get_env_multiple('form.command');
                   9263:     my $command=$commands[0];
1.447     foxr     9264: 
1.160     albertel 9265:     if ($#commands > 0) {
                   9266: 	&Apache::lonnet::logthis("grades got multiple commands ".join(':',@commands));
                   9267:     }
1.607   ! droeschl 9268:                              
1.513     foxr     9269:     $ssi_error = 0;
1.324     albertel 9270:     if ($symb eq '' && $command eq '') {
1.601     www      9271: #
                   9272: # Not called from a resource
                   9273: #    
                   9274: 
1.41      ng       9275:     } else {
1.285     albertel 9276: 	&init_perm();
1.104     albertel 9277: 	if ($command eq 'submission' && $perm{'vgr'}) {
1.607   ! droeschl 9278:         &startpage($request, [{href=>"", text=>"Student Submissions"}]);
1.257     albertel 9279: 	    ($env{'form.student'} eq '' ? &listStudents($request) : &submission($request,0,0));
1.103     albertel 9280: 	} elsif ($command eq 'pickStudentPage' && $perm{'vgr'}) {
1.68      ng       9281: 	    &pickStudentPage($request);
1.103     albertel 9282: 	} elsif ($command eq 'displayPage' && $perm{'vgr'}) {
1.68      ng       9283: 	    &displayPage($request);
1.104     albertel 9284: 	} elsif ($command eq 'gradeByPage' && $perm{'mgr'}) {
1.71      ng       9285: 	    &updateGradeByPage($request);
1.104     albertel 9286: 	} elsif ($command eq 'processGroup' && $perm{'vgr'}) {
1.41      ng       9287: 	    &processGroup($request);
1.104     albertel 9288: 	} elsif ($command eq 'gradingmenu' && $perm{'vgr'}) {
1.607   ! droeschl 9289:         &startpage($request);
1.443     banghart 9290: 	    $request->print(&grading_menu($request));
1.598     www      9291: 	} elsif ($command eq 'individual' && $perm{'vgr'}) {
1.600     www      9292: 	    $request->print(&submit_options($request));
1.598     www      9293:         } elsif ($command eq 'ungraded' && $perm{'vgr'}) {
                   9294:             $request->print(&submit_options($request));
                   9295:         } elsif ($command eq 'table' && $perm{'vgr'}) {
1.600     www      9296:             $request->print(&submit_options_table($request));
1.598     www      9297:         } elsif ($command eq 'all_for_one' && $perm{'vgr'}) {
1.599     www      9298:             $request->print(&submit_options_sequence($request));
1.104     albertel 9299: 	} elsif ($command eq 'viewgrades' && $perm{'vgr'}) {
1.41      ng       9300: 	    $request->print(&viewgrades($request));
1.104     albertel 9301: 	} elsif ($command eq 'handgrade' && $perm{'mgr'}) {
1.41      ng       9302: 	    $request->print(&processHandGrade($request));
1.106     albertel 9303: 	} elsif ($command eq 'editgrades' && $perm{'mgr'}) {
1.41      ng       9304: 	    $request->print(&editgrades($request));
1.602     www      9305:         } elsif ($command eq 'initialverifyreceipt' && $perm{'vgr'}) {
                   9306:             $request->print(&initialverifyreceipt($request));
1.106     albertel 9307: 	} elsif ($command eq 'verify' && $perm{'vgr'}) {
1.41      ng       9308: 	    $request->print(&verifyreceipt($request));
1.400     www      9309:         } elsif ($command eq 'processclicker' && $perm{'mgr'}) {
                   9310:             $request->print(&process_clicker($request));
                   9311:         } elsif ($command eq 'processclickerfile' && $perm{'mgr'}) {
                   9312:             $request->print(&process_clicker_file($request));
1.414     www      9313:         } elsif ($command eq 'assignclickergrades' && $perm{'mgr'}) {
                   9314:             $request->print(&assign_clicker_grades($request));
1.106     albertel 9315: 	} elsif ($command eq 'csvform' && $perm{'mgr'}) {
1.72      ng       9316: 	    $request->print(&upcsvScores_form($request));
1.106     albertel 9317: 	} elsif ($command eq 'csvupload' && $perm{'mgr'}) {
1.41      ng       9318: 	    $request->print(&csvupload($request));
1.106     albertel 9319: 	} elsif ($command eq 'csvuploadmap' && $perm{'mgr'} ) {
1.41      ng       9320: 	    $request->print(&csvuploadmap($request));
1.246     albertel 9321: 	} elsif ($command eq 'csvuploadoptions' && $perm{'mgr'}) {
1.257     albertel 9322: 	    if ($env{'form.associate'} ne 'Reverse Association') {
1.246     albertel 9323: 		$request->print(&csvuploadoptions($request));
1.41      ng       9324: 	    } else {
1.257     albertel 9325: 		if ( $env{'form.upfile_associate'} ne 'reverse' ) {
                   9326: 		    $env{'form.upfile_associate'} = 'reverse';
1.41      ng       9327: 		} else {
1.257     albertel 9328: 		    $env{'form.upfile_associate'} = 'forward';
1.41      ng       9329: 		}
                   9330: 		$request->print(&csvuploadmap($request));
                   9331: 	    }
1.246     albertel 9332: 	} elsif ($command eq 'csvuploadassign' && $perm{'mgr'} ) {
                   9333: 	    $request->print(&csvuploadassign($request));
1.106     albertel 9334: 	} elsif ($command eq 'scantron_selectphase' && $perm{'mgr'}) {
1.75      albertel 9335: 	    $request->print(&scantron_selectphase($request));
1.203     albertel 9336:  	} elsif ($command eq 'scantron_warning' && $perm{'mgr'}) {
                   9337:  	    $request->print(&scantron_do_warning($request));
1.142     albertel 9338: 	} elsif ($command eq 'scantron_validate' && $perm{'mgr'}) {
                   9339: 	    $request->print(&scantron_validate_file($request));
1.106     albertel 9340: 	} elsif ($command eq 'scantron_process' && $perm{'mgr'}) {
1.82      albertel 9341: 	    $request->print(&scantron_process_students($request));
1.157     albertel 9342:  	} elsif ($command eq 'scantronupload' && 
1.257     albertel 9343:  		 (&Apache::lonnet::allowed('usc',$env{'request.role.domain'})||
                   9344: 		  &Apache::lonnet::allowed('usc',$env{'request.course.id'}))) {
1.162     albertel 9345:  	    $request->print(&scantron_upload_scantron_data($request)); 
1.157     albertel 9346:  	} elsif ($command eq 'scantronupload_save' &&
1.257     albertel 9347:  		 (&Apache::lonnet::allowed('usc',$env{'request.role.domain'})||
                   9348: 		  &Apache::lonnet::allowed('usc',$env{'request.course.id'}))) {
1.157     albertel 9349:  	    $request->print(&scantron_upload_scantron_data_save($request));
1.202     albertel 9350:  	} elsif ($command eq 'scantron_download' &&
1.257     albertel 9351: 		 &Apache::lonnet::allowed('usc',$env{'request.course.id'})) {
1.162     albertel 9352:  	    $request->print(&scantron_download_scantron_data($request));
1.523     raeburn  9353:         } elsif ($command eq 'checksubmissions' && $perm{'vgr'}) {
                   9354:             $request->print(&checkscantron_results($request));     
1.106     albertel 9355: 	} elsif ($command) {
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>