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

1.17      albertel    1: # The LearningOnline Network with CAPA
1.13      albertel    2: # The LON-CAPA Grading handler
1.17      albertel    3: #
1.603   ! www         4: # $Id: grades.pm,v 1.602 2010/03/25 19:56:33 www Exp $
1.17      albertel    5: #
                      6: # Copyright Michigan State University Board of Trustees
                      7: #
                      8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
                      9: #
                     10: # LON-CAPA is free software; you can redistribute it and/or modify
                     11: # it under the terms of the GNU General Public License as published by
                     12: # the Free Software Foundation; either version 2 of the License, or
                     13: # (at your option) any later version.
                     14: #
                     15: # LON-CAPA is distributed in the hope that it will be useful,
                     16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
                     17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
                     18: # GNU General Public License for more details.
                     19: #
                     20: # You should have received a copy of the GNU General Public License
                     21: # along with LON-CAPA; if not, write to the Free Software
                     22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
                     23: #
                     24: # /home/httpd/html/adm/gpl.txt
                     25: #
                     26: # http://www.lon-capa.org/
                     27: #
1.1       albertel   28: 
1.529     jms        29: 
                     30: 
1.1       albertel   31: package Apache::grades;
                     32: use strict;
                     33: use Apache::style;
                     34: use Apache::lonxml;
                     35: use Apache::lonnet;
1.3       albertel   36: use Apache::loncommon;
1.112     ng         37: use Apache::lonhtmlcommon;
1.68      ng         38: use Apache::lonnavmaps;
1.1       albertel   39: use Apache::lonhomework;
1.456     banghart   40: use Apache::lonpickcode;
1.55      matthew    41: use Apache::loncoursedata;
1.362     albertel   42: use Apache::lonmsg();
1.1       albertel   43: use Apache::Constants qw(:common);
1.167     sakharuk   44: use Apache::lonlocal;
1.386     raeburn    45: use Apache::lonenc;
1.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".
                    640: 	'<input type="hidden" name="probTitle" value="'.$env{'form.probTitle'}.'" />'."\n".
1.442     banghart  641: 	'<input type="hidden" name="Status"  value="'.$stu_status.'" />'."\n".
1.45      ng        642: 	'<input type="hidden" name="command" value="submission" />'."\n".
                    643: 	'<input type="hidden" name="student" value="" />'."\n".
                    644: 	'<input type="hidden" name="userdom" value="" />'."\n".
                    645: 	'</form>'."\n";
                    646:     return $jscript;
                    647: }
1.39      ng        648: 
1.447     foxr      649: 
                    650: 
1.315     bowersj2  651: # Given the score (as a number [0-1] and the weight) what is the final
                    652: # point value? This function will round to the nearest tenth, third,
                    653: # or quarter if one of those is within the tolerance of .00001.
1.316     albertel  654: sub compute_points {
1.315     bowersj2  655:     my ($score, $weight) = @_;
                    656:     
                    657:     my $tolerance = .00001;
                    658:     my $points = $score * $weight;
                    659: 
                    660:     # Check for nearness to 1/x.
                    661:     my $check_for_nearness = sub {
                    662:         my ($factor) = @_;
                    663:         my $num = ($points * $factor) + $tolerance;
                    664:         my $floored_num = floor($num);
1.316     albertel  665:         if ($num - $floored_num < 2 * $tolerance * $factor) {
1.315     bowersj2  666:             return $floored_num / $factor;
                    667:         }
                    668:         return $points;
                    669:     };
                    670: 
                    671:     $points = $check_for_nearness->(10);
                    672:     $points = $check_for_nearness->(3);
                    673:     $points = $check_for_nearness->(4);
                    674:     
                    675:     return $points;
                    676: }
                    677: 
1.44      ng        678: #------------------ End of general use routines --------------------
1.87      www       679: 
                    680: #
                    681: # Find most similar essay
                    682: #
                    683: 
                    684: sub most_similar {
1.426     albertel  685:     my ($uname,$udom,$uessay,$old_essays)=@_;
1.87      www       686: 
                    687: # ignore spaces and punctuation
                    688: 
                    689:     $uessay=~s/\W+/ /gs;
                    690: 
1.282     www       691: # ignore empty submissions (occuring when only files are sent)
                    692: 
1.598     www       693:     unless ($uessay=~/\w+/s) { return ''; }
1.282     www       694: 
1.87      www       695: # these will be returned. Do not care if not at least 50 percent similar
1.88      www       696:     my $limit=0.6;
1.87      www       697:     my $sname='';
                    698:     my $sdom='';
                    699:     my $scrsid='';
                    700:     my $sessay='';
                    701: # go through all essays ...
1.426     albertel  702:     foreach my $tkey (keys(%$old_essays)) {
                    703: 	my ($tname,$tdom,$tcrsid)=map {&unescape($_)} (split(/\./,$tkey));
1.87      www       704: # ... except the same student
1.426     albertel  705:         next if (($tname eq $uname) && ($tdom eq $udom));
                    706: 	my $tessay=$old_essays->{$tkey};
                    707: 	$tessay=~s/\W+/ /gs;
1.87      www       708: # String similarity gives up if not even limit
1.426     albertel  709: 	my $tsimilar=&String::Similarity::similarity($uessay,$tessay,$limit);
1.87      www       710: # Found one
1.426     albertel  711: 	if ($tsimilar>$limit) {
                    712: 	    $limit=$tsimilar;
                    713: 	    $sname=$tname;
                    714: 	    $sdom=$tdom;
                    715: 	    $scrsid=$tcrsid;
                    716: 	    $sessay=$old_essays->{$tkey};
                    717: 	}
1.87      www       718:     }
1.88      www       719:     if ($limit>0.6) {
1.87      www       720:        return ($sname,$sdom,$scrsid,$sessay,$limit);
                    721:     } else {
                    722:        return ('','','','',0);
                    723:     }
                    724: }
                    725: 
1.44      ng        726: #-------------------------------------------------------------------
                    727: 
                    728: #------------------------------------ Receipt Verification Routines
1.45      ng        729: #
1.602     www       730: 
                    731: sub initialverifyreceipt {
                    732:    my $request = shift;
                    733:    &commonJSfunctions($request);
1.603   ! www       734:    my ($symb)   = &get_symb($request);
        !           735:    return '<form name="gradingMenu"><input type="submit" value="'.&mt('Verify Receipt No.').'" />'.
1.602     www       736:         &Apache::lonnet::recprefix($env{'request.course.id'}).
                    737:         '-<input type="text" name="receipt" size="4" />'.
1.603   ! www       738:         '<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
        !           739:         '<input type="hidden" name="command" value="verify" />'.
        !           740:         "</form>\n";
1.602     www       741: }
                    742: 
1.44      ng        743: #--- Check whether a receipt number is valid.---
                    744: sub verifyreceipt {
                    745:     my $request  = shift;
                    746: 
1.257     albertel  747:     my $courseid = $env{'request.course.id'};
1.184     www       748:     my $receipt  = &Apache::lonnet::recprefix($courseid).'-'.
1.257     albertel  749: 	$env{'form.receipt'};
1.44      ng        750:     $receipt     =~ s/[^\-\d]//g;
1.378     albertel  751:     my ($symb)   = &get_symb($request);
1.44      ng        752: 
1.487     albertel  753:     my $title.=
                    754: 	'<h3><span class="LC_info">'.
1.584     bisitz    755: 	&mt('Verifying Receipt No. [_1]',$receipt).
1.487     albertel  756: 	'</span></h3>'."\n".
                    757: 	'<h4>'.&mt('<b>Resource: </b>[_1]',$env{'form.probTitle'}).
                    758: 	'</h4>'."\n";
1.44      ng        759: 
                    760:     my ($string,$contents,$matches) = ('','',0);
1.56      matthew   761:     my (undef,undef,$fullname) = &getclasslist('all','0');
1.177     albertel  762:     
                    763:     my $receiptparts=0;
1.390     albertel  764:     if ($env{"course.$courseid.receiptalg"} eq 'receipt2' ||
                    765: 	$env{"course.$courseid.receiptalg"} eq 'receipt3') { $receiptparts=1; }
1.177     albertel  766:     my $parts=['0'];
1.582     raeburn   767:     if ($receiptparts) {
                    768:         my $res_error; 
                    769:         ($parts)=&response_type($symb,\$res_error);
                    770:         if ($res_error) {
                    771:             return &navmap_errormsg();
                    772:         } 
                    773:     }
1.486     albertel  774:     
                    775:     my $header = 
                    776: 	&Apache::loncommon::start_data_table().
                    777: 	&Apache::loncommon::start_data_table_header_row().
1.487     albertel  778: 	'<th>&nbsp;'.&mt('Fullname').'&nbsp;</th>'."\n".
                    779: 	'<th>&nbsp;'.&mt('Username').'&nbsp;</th>'."\n".
                    780: 	'<th>&nbsp;'.&mt('Domain').'&nbsp;</th>';
1.486     albertel  781:     if ($receiptparts) {
1.487     albertel  782: 	$header.='<th>&nbsp;'.&mt('Problem Part').'&nbsp;</th>';
1.486     albertel  783:     }
                    784:     $header.=
                    785: 	&Apache::loncommon::end_data_table_header_row();
                    786: 
1.294     albertel  787:     foreach (sort 
                    788: 	     {
                    789: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                    790: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                    791: 		 }
                    792: 		 return $a cmp $b;
                    793: 	     } (keys(%$fullname))) {
1.44      ng        794: 	my ($uname,$udom)=split(/\:/);
1.177     albertel  795: 	foreach my $part (@$parts) {
                    796: 	    if ($receipt eq &Apache::lonnet::ireceipt($uname,$udom,$courseid,$symb,$part)) {
1.486     albertel  797: 		$contents.=
                    798: 		    &Apache::loncommon::start_data_table_row().
                    799: 		    '<td>&nbsp;'."\n".
1.177     albertel  800: 		    '<a href="javascript:viewOneStudent(\''.$uname.'\',\''.$udom.
1.417     albertel  801: 		    '\');" target="_self">'.$$fullname{$_}.'</a>&nbsp;</td>'."\n".
1.177     albertel  802: 		    '<td>&nbsp;'.$uname.'&nbsp;</td>'.
                    803: 		    '<td>&nbsp;'.$udom.'&nbsp;</td>';
                    804: 		if ($receiptparts) {
                    805: 		    $contents.='<td>&nbsp;'.$part.'&nbsp;</td>';
                    806: 		}
1.486     albertel  807: 		$contents.= 
                    808: 		    &Apache::loncommon::end_data_table_row()."\n";
1.177     albertel  809: 		
                    810: 		$matches++;
                    811: 	    }
1.44      ng        812: 	}
                    813:     }
                    814:     if ($matches == 0) {
1.584     bisitz    815:         $string = $title
                    816:                  .'<p class="LC_warning">'
                    817:                  .&mt('No match found for the above receipt number.')
                    818:                  .'</p>';
1.44      ng        819:     } else {
1.324     albertel  820: 	$string = &jscriptNform($symb).$title.
1.487     albertel  821: 	    '<p>'.
1.584     bisitz    822: 	    &mt('The above receipt number matches the following [quant,_1,student].',$matches).
1.487     albertel  823: 	    '</p>'.
1.486     albertel  824: 	    $header.
                    825: 	    $contents.
                    826: 	    &Apache::loncommon::end_data_table()."\n";
1.44      ng        827:     }
1.324     albertel  828:     return $string.&show_grading_menu_form($symb);
1.44      ng        829: }
                    830: 
                    831: #--- This is called by a number of programs.
                    832: #--- Called from the Grading Menu - View/Grade an individual student
                    833: #--- Also called directly when one clicks on the subm button 
                    834: #    on the problem page.
1.30      ng        835: sub listStudents {
1.41      ng        836:     my ($request) = shift;
1.49      albertel  837: 
1.324     albertel  838:     my ($symb) = &get_symb($request);
1.257     albertel  839:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
                    840:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
                    841:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
1.449     banghart  842:     my $getgroup  = $env{'form.group'} eq '' ? 'all' : $env{'form.group'};
1.257     albertel  843:     my $submitonly= $env{'form.submitonly'} eq '' ? 'all' : $env{'form.submitonly'};
1.548     bisitz    844:     my $viewgrade = $env{'form.showgrading'} eq 'yes' ? 'View/Grade/Regrade' : 'View';
1.257     albertel  845:     $env{'form.probTitle'} = $env{'form.probTitle'} eq '' ? 
                    846: 	&Apache::lonnet::gettitle($symb) : $env{'form.probTitle'};
1.49      albertel  847: 
1.548     bisitz    848:     my $result='<h3><span class="LC_info">&nbsp;'
                    849: 	.&mt("$viewgrade Submissions for a Student or a Group of Students")
1.485     albertel  850: 	.'</span></h3>';
1.118     ng        851: 
1.598     www       852:     my ($partlist,$handgrade,$responseType) = &response_type($symb
                    853: #,$res_error
                    854:     );
1.49      albertel  855: 
1.559     raeburn   856:     my %lt = &Apache::lonlocal::texthash (
                    857: 		'multiple' => 'Please select a student or group of students before clicking on the Next button.',
                    858: 		'single'   => 'Please select the student before clicking on the Next button.',
                    859: 	     );
1.597     wenzelju  860:     $request->print(&Apache::lonhtmlcommon::scripttag(<<LISTJAVASCRIPT));
1.110     ng        861:     function checkSelect(checkBox) {
                    862: 	var ctr=0;
                    863: 	var sense="";
                    864: 	if (checkBox.length > 1) {
                    865: 	    for (var i=0; i<checkBox.length; i++) {
                    866: 		if (checkBox[i].checked) {
                    867: 		    ctr++;
                    868: 		}
                    869: 	    }
1.485     albertel  870: 	    sense = '$lt{'multiple'}';
1.110     ng        871: 	} else {
                    872: 	    if (checkBox.checked) {
                    873: 		ctr = 1;
                    874: 	    }
1.485     albertel  875: 	    sense = '$lt{'single'}';
1.110     ng        876: 	}
                    877: 	if (ctr == 0) {
1.485     albertel  878: 	    alert(sense);
1.110     ng        879: 	    return false;
                    880: 	}
                    881: 	document.gradesub.submit();
                    882:     }
                    883: 
                    884:     function reLoadList(formname) {
1.112     ng        885: 	if (formname.saveStatusOld.value == pullDownSelection(formname.Status)) {return;}
1.110     ng        886: 	formname.command.value = 'submission';
                    887: 	formname.submit();
                    888:     }
1.45      ng        889: LISTJAVASCRIPT
                    890: 
1.118     ng        891:     &commonJSfunctions($request);
1.41      ng        892:     $request->print($result);
1.39      ng        893: 
1.401     albertel  894:     my $checkhdgrade = ($env{'form.handgrade'} eq 'yes' && scalar(@$partlist) > 1 ) ? 'checked="checked"' : '';
                    895:     my $checklastsub = $checkhdgrade eq '' ? 'checked="checked"' : '';
1.154     albertel  896:     my $gradeTable='<form action="/adm/grades" method="post" name="gradesub">'.
1.598     www       897: 	"\n";
1.485     albertel  898: 	
1.561     bisitz    899:     $gradeTable .= &Apache::lonhtmlcommon::start_pick_box();
                    900:     $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('View Problem Text'))
                    901:                   .'<label><input type="radio" name="vProb" value="no" checked="checked" /> '.&mt('no').' </label>'."\n"
                    902:                   .'<label><input type="radio" name="vProb" value="yes" /> '.&mt('one student').' </label>'."\n"
                    903:                   .'<label><input type="radio" name="vProb" value="all" /> '.&mt('all students').' </label><br />'."\n"
                    904:                   .&Apache::lonhtmlcommon::row_closure();
                    905:     $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('View Answer'))
                    906:                   .'<label><input type="radio" name="vAns" value="no"  /> '.&mt('no').' </label>'."\n"
                    907:                   .'<label><input type="radio" name="vAns" value="yes" /> '.&mt('one student').' </label>'."\n"
                    908:                   .'<label><input type="radio" name="vAns" value="all" checked="checked" /> '.&mt('all students').' </label><br />'."\n"
                    909:                   .&Apache::lonhtmlcommon::row_closure();
1.485     albertel  910: 
                    911:     my $submission_options;
1.257     albertel  912:     if ($env{'form.handgrade'} eq 'yes' && scalar(@$partlist) > 1) {
1.485     albertel  913: 	$submission_options.=
                    914: 	    '<label><input type="radio" name="lastSub" value="hdgrade" '.$checkhdgrade.' /> '.&mt('essay part only').' </label>'."\n";
1.49      albertel  915:     }
1.442     banghart  916:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
                    917:     my $saveStatus = $stu_status eq '' ? 'Active' : $stu_status;
1.257     albertel  918:     $env{'form.Status'} = $saveStatus;
1.485     albertel  919:     $submission_options.=
1.592     bisitz    920:         '<span class="LC_nobreak">'.
                    921:         '<label><input type="radio" name="lastSub" value="lastonly" '.$checklastsub.' /> '.
                    922:         &mt('last submission only').' </label></span>'."\n".
                    923:         '<span class="LC_nobreak">'.
                    924:         '<label><input type="radio" name="lastSub" value="last" /> '.
                    925:         &mt('last submission &amp; parts info').' </label></span>'."\n".
                    926:         '<span class="LC_nobreak">'.
                    927:         '<label><input type="radio" name="lastSub" value="datesub" /> '.
                    928:         &mt('by dates and submissions').'</label></span>'."\n".
                    929:         '<span class="LC_nobreak">'.
                    930:         '<label><input type="radio" name="lastSub" value="all" /> '.
                    931:         &mt('all details').'</label></span>';
1.561     bisitz    932:     $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('Submissions'))
                    933:                   .$submission_options
                    934:                   .&Apache::lonhtmlcommon::row_closure();
                    935: 
                    936:     $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('Grading Increments'))
                    937:                   .'<select name="increment">'
                    938:                   .'<option value="1">'.&mt('Whole Points').'</option>'
                    939:                   .'<option value=".5">'.&mt('Half Points').'</option>'
                    940:                   .'<option value=".25">'.&mt('Quarter Points').'</option>'
                    941:                   .'<option value=".1">'.&mt('Tenths of a Point').'</option>'
                    942:                   .'</select>'
                    943:                   .&Apache::lonhtmlcommon::row_closure();
1.485     albertel  944: 
                    945:     $gradeTable .= 
1.432     banghart  946:         &build_section_inputs().
1.45      ng        947: 	'<input type="hidden" name="submitonly"  value="'.$submitonly.'" />'."\n".
1.257     albertel  948: 	'<input type="hidden" name="handgrade"   value="'.$env{'form.handgrade'}.'" /><br />'."\n".
                    949: 	'<input type="hidden" name="showgrading" value="'.$env{'form.showgrading'}.'" /><br />'."\n".
                    950: 	'<input type="hidden" name="saveState"   value="'.$env{'form.saveState'}.'" />'."\n".
                    951: 	'<input type="hidden" name="probTitle"   value="'.$env{'form.probTitle'}.'" />'."\n".
1.418     albertel  952: 	'<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.110     ng        953: 	'<input type="hidden" name="saveStatusOld" value="'.$saveStatus.'" />'."\n";
                    954: 
1.257     albertel  955:     if (exists($env{'form.gradingMenu'}) && exists($env{'form.Status'})) {
1.561     bisitz    956: 	$gradeTable .= '<input type="hidden" name="Status" value="'.$stu_status.'" />'."\n";
1.124     ng        957:     } else {
1.561     bisitz    958:         $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('Student Status'))
                    959:                       .&Apache::lonhtmlcommon::StatusOptions(
                    960:                            $saveStatus,undef,1,'javascript:reLoadList(this.form);')
                    961:                       .&Apache::lonhtmlcommon::row_closure();
1.124     ng        962:     }
1.112     ng        963: 
1.561     bisitz    964:     $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('Check For Plagiarism'))
                    965:                   .'<input type="checkbox" name="checkPlag" checked="checked" />'
                    966:                   .&Apache::lonhtmlcommon::row_closure(1)
                    967:                   .&Apache::lonhtmlcommon::end_pick_box();
                    968: 
                    969:     $gradeTable .= '<p>'
                    970:                   .&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"
                    971:                   .'<input type="hidden" name="command" value="processGroup" />'
                    972:                   .'</p>';
1.249     albertel  973: 
                    974: # checkall buttons
                    975:     $gradeTable.=&check_script('gradesub', 'stuinfo');
1.110     ng        976:     $gradeTable.='<input type="button" '."\n".
1.589     bisitz    977:         'onclick="javascript:checkSelect(this.form.stuinfo);" '."\n".
                    978:         'value="'.&mt('Next').' &rarr;" /> <br />'."\n";
1.249     albertel  979:     $gradeTable.=&check_buttons();
1.450     banghart  980:     my ($classlist, undef, $fullname) = &getclasslist($getsec,'1',$getgroup);
1.474     albertel  981:     $gradeTable.= &Apache::loncommon::start_data_table().
                    982: 	&Apache::loncommon::start_data_table_header_row();
1.110     ng        983:     my $loop = 0;
                    984:     while ($loop < 2) {
1.485     albertel  985: 	$gradeTable.='<th>'.&mt('No.').'</th><th>'.&mt('Select').'</th>'.
                    986: 	    '<th>'.&nameUserString('header').'&nbsp;'.&mt('Section/Group').'</th>';
1.301     albertel  987: 	if ($env{'form.showgrading'} eq 'yes' 
                    988: 	    && $submitonly ne 'queued'
                    989: 	    && $submitonly ne 'all') {
1.485     albertel  990: 	    foreach my $part (sort(@$partlist)) {
                    991: 		my $display_part=
                    992: 		    &get_display_part((split(/_/,$part))[0],$symb);
                    993: 		$gradeTable.=
                    994: 		    '<th>'.&mt('Part: [_1] Status',$display_part).'</th>';
1.110     ng        995: 	    }
1.301     albertel  996: 	} elsif ($submitonly eq 'queued') {
1.474     albertel  997: 	    $gradeTable.='<th>'.&mt('Queue Status').'&nbsp;</th>';
1.110     ng        998: 	}
                    999: 	$loop++;
1.126     ng       1000: #	$gradeTable.='<td></td>' if ($loop%2 ==1);
1.41      ng       1001:     }
1.474     albertel 1002:     $gradeTable.=&Apache::loncommon::end_data_table_header_row()."\n";
1.41      ng       1003: 
1.45      ng       1004:     my $ctr = 0;
1.294     albertel 1005:     foreach my $student (sort 
                   1006: 			 {
                   1007: 			     if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                   1008: 				 return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                   1009: 			     }
                   1010: 			     return $a cmp $b;
                   1011: 			 }
                   1012: 			 (keys(%$fullname))) {
1.41      ng       1013: 	my ($uname,$udom) = split(/:/,$student);
1.301     albertel 1014: 
1.110     ng       1015: 	my %status = ();
1.301     albertel 1016: 
                   1017: 	if ($submitonly eq 'queued') {
                   1018: 	    my %queue_status = 
                   1019: 		&Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
                   1020: 							$udom,$uname);
                   1021: 	    next if (!defined($queue_status{'gradingqueue'}));
                   1022: 	    $status{'gradingqueue'} = $queue_status{'gradingqueue'};
                   1023: 	}
                   1024: 
                   1025: 	if ($env{'form.showgrading'} eq 'yes' 
                   1026: 	    && $submitonly ne 'queued'
                   1027: 	    && $submitonly ne 'all') {
1.324     albertel 1028: 	    (%status) =&student_gradeStatus($symb,$udom,$uname,$partlist);
1.145     albertel 1029: 	    my $submitted = 0;
1.164     albertel 1030: 	    my $graded = 0;
1.248     albertel 1031: 	    my $incorrect = 0;
1.110     ng       1032: 	    foreach (keys(%status)) {
1.145     albertel 1033: 		$submitted = 1 if ($status{$_} ne 'nothing');
1.248     albertel 1034: 		$graded = 1 if ($status{$_} =~ /^ungraded/);
                   1035: 		$incorrect = 1 if ($status{$_} =~ /^incorrect/);
                   1036: 		
1.110     ng       1037: 		my ($foo,$partid,$foo1) = split(/\./,$_);
                   1038: 		if ($status{'resource.'.$partid.'.submitted_by'} ne '') {
1.145     albertel 1039: 		    $submitted = 0;
1.150     albertel 1040: 		    my ($part)=split(/\./,$partid);
1.110     ng       1041: 		    $gradeTable.='<input type="hidden" name="'.
1.150     albertel 1042: 			$student.':'.$part.':submitted_by" value="'.
1.110     ng       1043: 			$status{'resource.'.$partid.'.submitted_by'}.'" />';
                   1044: 		}
1.41      ng       1045: 	    }
1.248     albertel 1046: 	    
1.156     albertel 1047: 	    next if (!$submitted && ($submitonly eq 'yes' ||
                   1048: 				     $submitonly eq 'incorrect' ||
                   1049: 				     $submitonly eq 'graded'));
1.248     albertel 1050: 	    next if (!$graded && ($submitonly eq 'graded'));
                   1051: 	    next if (!$incorrect && $submitonly eq 'incorrect');
1.41      ng       1052: 	}
1.34      ng       1053: 
1.45      ng       1054: 	$ctr++;
1.249     albertel 1055: 	my $section = $classlist->{$student}->[&Apache::loncoursedata::CL_SECTION()];
1.452     banghart 1056:         my $group = $classlist->{$student}->[&Apache::loncoursedata::CL_GROUP()];
1.104     albertel 1057: 	if ( $perm{'vgr'} eq 'F' ) {
1.474     albertel 1058: 	    if ($ctr%2 ==1) {
                   1059: 		$gradeTable.= &Apache::loncommon::start_data_table_row();
                   1060: 	    }
1.126     ng       1061: 	    $gradeTable.='<td align="right">'.$ctr.'&nbsp;</td>'.
1.563     bisitz   1062:                '<td align="center"><label><input type="checkbox" name="stuinfo" value="'.
1.249     albertel 1063:                $student.':'.$$fullname{$student}.':::SECTION'.$section.
                   1064: 	       ')&nbsp;" />&nbsp;&nbsp;</label></td>'."\n".'<td>'.
                   1065: 	       &nameUserString(undef,$$fullname{$student},$uname,$udom).
1.474     albertel 1066: 	       '&nbsp;'.$section.($group ne '' ?'/'.$group:'').'</td>'."\n";
1.110     ng       1067: 
1.257     albertel 1068: 	    if ($env{'form.showgrading'} eq 'yes' && $submitonly ne 'all') {
1.524     raeburn  1069: 		foreach (sort(keys(%status))) {
1.485     albertel 1070: 		    next if ($_ =~ /^resource.*?submitted_by$/);
                   1071: 		    $gradeTable.='<td align="center">&nbsp;'.&mt($status{$_}).'&nbsp;</td>'."\n";
1.110     ng       1072: 		}
1.41      ng       1073: 	    }
1.126     ng       1074: #	    $gradeTable.='<td></td>' if ($ctr%2 ==1);
1.474     albertel 1075: 	    if ($ctr%2 ==0) {
                   1076: 		$gradeTable.=&Apache::loncommon::end_data_table_row()."\n";
                   1077: 	    }
1.41      ng       1078: 	}
                   1079:     }
1.110     ng       1080:     if ($ctr%2 ==1) {
1.126     ng       1081: 	$gradeTable.='<td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td>';
1.301     albertel 1082: 	    if ($env{'form.showgrading'} eq 'yes' 
                   1083: 		&& $submitonly ne 'queued'
                   1084: 		&& $submitonly ne 'all') {
1.110     ng       1085: 		foreach (@$partlist) {
                   1086: 		    $gradeTable.='<td>&nbsp;</td>';
                   1087: 		}
1.301     albertel 1088: 	    } elsif ($submitonly eq 'queued') {
                   1089: 		$gradeTable.='<td>&nbsp;</td>';
1.110     ng       1090: 	    }
1.474     albertel 1091: 	$gradeTable.=&Apache::loncommon::end_data_table_row();
1.110     ng       1092:     }
                   1093: 
1.474     albertel 1094:     $gradeTable.=&Apache::loncommon::end_data_table()."\n".
1.589     bisitz   1095:         '<input type="button" '.
                   1096:         'onclick="javascript:checkSelect(this.form.stuinfo);" '.
                   1097:         'value="'.&mt('Next').' &rarr;" /></form>'."\n";
1.45      ng       1098:     if ($ctr == 0) {
1.96      albertel 1099: 	my $num_students=(scalar(keys(%$fullname)));
                   1100: 	if ($num_students eq 0) {
1.485     albertel 1101: 	    $gradeTable='<br />&nbsp;<span class="LC_warning">'.&mt('There are no students currently enrolled.').'</span>';
1.96      albertel 1102: 	} else {
1.171     albertel 1103: 	    my $submissions='submissions';
                   1104: 	    if ($submitonly eq 'incorrect') { $submissions = 'incorrect submissions'; }
                   1105: 	    if ($submitonly eq 'graded'   ) { $submissions = 'ungraded submissions'; }
1.301     albertel 1106: 	    if ($submitonly eq 'queued'   ) { $submissions = 'queued submissions'; }
1.398     albertel 1107: 	    $gradeTable='<br />&nbsp;<span class="LC_warning">'.
1.485     albertel 1108: 		&mt('No '.$submissions.' found for this resource for any students. ([_1] students checked for '.$submissions.')',
                   1109: 		    $num_students).
                   1110: 		'</span><br />';
1.96      albertel 1111: 	}
1.46      ng       1112:     } elsif ($ctr == 1) {
1.474     albertel 1113: 	$gradeTable =~ s/type="checkbox"/type="checkbox" checked="checked"/;
1.45      ng       1114:     }
1.324     albertel 1115:     $gradeTable.=&show_grading_menu_form($symb);
1.45      ng       1116:     $request->print($gradeTable);
1.44      ng       1117:     return '';
1.10      ng       1118: }
                   1119: 
1.44      ng       1120: #---- Called from the listStudents routine
1.249     albertel 1121: 
                   1122: sub check_script {
                   1123:     my ($form, $type)=@_;
1.597     wenzelju 1124:     my $chkallscript= &Apache::lonhtmlcommon::scripttag('
1.249     albertel 1125:     function checkall() {
                   1126:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
                   1127:             ele = document.forms.'.$form.'.elements[i];
                   1128:             if (ele.name == "'.$type.'") {
                   1129:             document.forms.'.$form.'.elements[i].checked=true;
                   1130:                                        }
                   1131:         }
                   1132:     }
                   1133: 
                   1134:     function checksec() {
                   1135:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
                   1136:             ele = document.forms.'.$form.'.elements[i];
                   1137:            string = document.forms.'.$form.'.chksec.value;
                   1138:            if
                   1139:           (ele.value.indexOf(":::SECTION"+string)>0) {
                   1140:               document.forms.'.$form.'.elements[i].checked=true;
                   1141:             }
                   1142:         }
                   1143:     }
                   1144: 
                   1145: 
                   1146:     function uncheckall() {
                   1147:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
                   1148:             ele = document.forms.'.$form.'.elements[i];
                   1149:             if (ele.name == "'.$type.'") {
                   1150:             document.forms.'.$form.'.elements[i].checked=false;
                   1151:                                        }
                   1152:         }
                   1153:     }
                   1154: 
1.597     wenzelju 1155: '."\n");
1.249     albertel 1156:     return $chkallscript;
                   1157: }
                   1158: 
                   1159: sub check_buttons {
1.485     albertel 1160:     my $buttons.='<input type="button" onclick="checkall()" value="'.&mt('Check All').'" />';
                   1161:     $buttons.='<input type="button" onclick="uncheckall()" value="'.&mt('Uncheck All').'" />&nbsp;';
                   1162:     $buttons.='<input type="button" onclick="checksec()" value="'.&mt('Check Section/Group').'" />';
1.249     albertel 1163:     $buttons.='<input type="text" size="5" name="chksec" />&nbsp;';
                   1164:     return $buttons;
                   1165: }
                   1166: 
1.44      ng       1167: #     Displays the submissions for one student or a group of students
1.34      ng       1168: sub processGroup {
1.41      ng       1169:     my ($request)  = shift;
                   1170:     my $ctr        = 0;
1.155     albertel 1171:     my @stuchecked = &Apache::loncommon::get_env_multiple('form.stuinfo');
1.41      ng       1172:     my $total      = scalar(@stuchecked)-1;
1.45      ng       1173: 
1.396     banghart 1174:     foreach my $student (@stuchecked) {
                   1175: 	my ($uname,$udom,$fullname) = split(/:/,$student);
1.257     albertel 1176: 	$env{'form.student'}        = $uname;
                   1177: 	$env{'form.userdom'}        = $udom;
                   1178: 	$env{'form.fullname'}       = $fullname;
1.41      ng       1179: 	&submission($request,$ctr,$total);
                   1180: 	$ctr++;
                   1181:     }
                   1182:     return '';
1.35      ng       1183: }
1.34      ng       1184: 
1.44      ng       1185: #------------------------------------------------------------------------------------
                   1186: #
                   1187: #-------------------------- Next few routines handles grading by student, essentially
                   1188: #                           handles essay response type problem/part
                   1189: #
                   1190: #--- Javascript to handle the submission page functionality ---
                   1191: sub sub_page_js {
                   1192:     my $request = shift;
1.539     riegler  1193: 	    my $alertmsg = &mt('A number equal or greater than 0 is expected. Entered value = ');
1.597     wenzelju 1194:     $request->print(&Apache::lonhtmlcommon::scripttag(<<SUBJAVASCRIPT));
1.71      ng       1195:     function updateRadio(formname,id,weight) {
1.125     ng       1196: 	var gradeBox = formname["GD_BOX"+id];
                   1197: 	var radioButton = formname["RADVAL"+id];
                   1198: 	var oldpts = formname["oldpts"+id].value;
1.72      ng       1199: 	var pts = checkSolved(formname,id) == 'update' ? gradeBox.value : oldpts;
1.71      ng       1200: 	gradeBox.value = pts;
                   1201: 	var resetbox = false;
                   1202: 	if (isNaN(pts) || pts < 0) {
1.539     riegler  1203: 	    alert("$alertmsg"+pts);
1.71      ng       1204: 	    for (var i=0; i<radioButton.length; i++) {
                   1205: 		if (radioButton[i].checked) {
                   1206: 		    gradeBox.value = i;
                   1207: 		    resetbox = true;
                   1208: 		}
                   1209: 	    }
                   1210: 	    if (!resetbox) {
                   1211: 		formtextbox.value = "";
                   1212: 	    }
                   1213: 	    return;
1.44      ng       1214: 	}
1.71      ng       1215: 
                   1216: 	if (pts > weight) {
                   1217: 	    var resp = confirm("You entered a value ("+pts+
                   1218: 			       ") greater than the weight for the part. Accept?");
                   1219: 	    if (resp == false) {
1.125     ng       1220: 		gradeBox.value = oldpts;
1.71      ng       1221: 		return;
                   1222: 	    }
1.44      ng       1223: 	}
1.13      albertel 1224: 
1.71      ng       1225: 	for (var i=0; i<radioButton.length; i++) {
                   1226: 	    radioButton[i].checked=false;
                   1227: 	    if (pts == i && pts != "") {
                   1228: 		radioButton[i].checked=true;
                   1229: 	    }
                   1230: 	}
                   1231: 	updateSelect(formname,id);
1.125     ng       1232: 	formname["stores"+id].value = "0";
1.41      ng       1233:     }
1.5       albertel 1234: 
1.72      ng       1235:     function writeBox(formname,id,pts) {
1.125     ng       1236: 	var gradeBox = formname["GD_BOX"+id];
1.71      ng       1237: 	if (checkSolved(formname,id) == 'update') {
                   1238: 	    gradeBox.value = pts;
                   1239: 	} else {
1.125     ng       1240: 	    var oldpts = formname["oldpts"+id].value;
1.72      ng       1241: 	    gradeBox.value = oldpts;
1.125     ng       1242: 	    var radioButton = formname["RADVAL"+id];
1.71      ng       1243: 	    for (var i=0; i<radioButton.length; i++) {
                   1244: 		radioButton[i].checked=false;
1.72      ng       1245: 		if (i == oldpts) {
1.71      ng       1246: 		    radioButton[i].checked=true;
                   1247: 		}
                   1248: 	    }
1.41      ng       1249: 	}
1.125     ng       1250: 	formname["stores"+id].value = "0";
1.71      ng       1251: 	updateSelect(formname,id);
                   1252: 	return;
1.41      ng       1253:     }
1.44      ng       1254: 
1.71      ng       1255:     function clearRadBox(formname,id) {
                   1256: 	if (checkSolved(formname,id) == 'noupdate') {
                   1257: 	    updateSelect(formname,id);
                   1258: 	    return;
                   1259: 	}
1.125     ng       1260: 	gradeSelect = formname["GD_SEL"+id];
1.71      ng       1261: 	for (var i=0; i<gradeSelect.length; i++) {
                   1262: 	    if (gradeSelect[i].selected) {
                   1263: 		var selectx=i;
                   1264: 	    }
                   1265: 	}
1.125     ng       1266: 	var stores = formname["stores"+id];
1.71      ng       1267: 	if (selectx == stores.value) { return };
1.125     ng       1268: 	var gradeBox = formname["GD_BOX"+id];
1.71      ng       1269: 	gradeBox.value = "";
1.125     ng       1270: 	var radioButton = formname["RADVAL"+id];
1.71      ng       1271: 	for (var i=0; i<radioButton.length; i++) {
                   1272: 	    radioButton[i].checked=false;
                   1273: 	}
                   1274: 	stores.value = selectx;
                   1275:     }
1.5       albertel 1276: 
1.71      ng       1277:     function checkSolved(formname,id) {
1.125     ng       1278: 	if (formname["solved"+id].value == "correct_by_student" && formname.overRideScore.value == 'no') {
1.118     ng       1279: 	    var reply = confirm("This problem has been graded correct by the computer. Do you want to change the score?");
                   1280: 	    if (!reply) {return "noupdate";}
1.120     ng       1281: 	    formname.overRideScore.value = 'yes';
1.41      ng       1282: 	}
1.71      ng       1283: 	return "update";
1.13      albertel 1284:     }
1.71      ng       1285: 
                   1286:     function updateSelect(formname,id) {
1.125     ng       1287: 	formname["GD_SEL"+id][0].selected = true;
1.71      ng       1288: 	return;
1.41      ng       1289:     }
1.33      ng       1290: 
1.121     ng       1291: //=========== Check that a point is assigned for all the parts  ============
1.71      ng       1292:     function checksubmit(formname,val,total,parttot) {
1.121     ng       1293: 	formname.gradeOpt.value = val;
1.71      ng       1294: 	if (val == "Save & Next") {
                   1295: 	    for (i=0;i<=total;i++) {
                   1296: 		for (j=0;j<parttot;j++) {
1.125     ng       1297: 		    var partid = formname["partid"+i+"_"+j].value;
1.127     ng       1298: 		    if (formname["GD_SEL"+i+"_"+partid][0].selected) {
1.125     ng       1299: 			var points = formname["GD_BOX"+i+"_"+partid].value;
1.71      ng       1300: 			if (points == "") {
1.125     ng       1301: 			    var name = formname["name"+i].value;
1.129     ng       1302: 			    var studentID = (name != '' ? name : formname["unamedom"+i].value);
                   1303: 			    var resp = confirm("You did not assign a score for "+studentID+
                   1304: 					       ", part "+partid+". Continue?");
1.71      ng       1305: 			    if (resp == false) {
1.125     ng       1306: 				formname["GD_BOX"+i+"_"+partid].focus();
1.71      ng       1307: 				return false;
                   1308: 			    }
                   1309: 			}
                   1310: 		    }
                   1311: 		    
                   1312: 		}
                   1313: 	    }
                   1314: 	    
                   1315: 	}
1.121     ng       1316: 	if (val == "Grade Student") {
                   1317: 	    formname.showgrading.value = "yes";
                   1318: 	    if (formname.Status.value == "") {
                   1319: 		formname.Status.value = "Active";
                   1320: 	    }
                   1321: 	    formname.studentNo.value = total;
                   1322: 	}
1.120     ng       1323: 	formname.submit();
                   1324:     }
                   1325: 
1.71      ng       1326: //======= Check that a score is assigned for all the problems (page/sequence grading only) =========
                   1327:     function checkSubmitPage(formname,total) {
                   1328: 	noscore = new Array(100);
                   1329: 	var ptr = 0;
                   1330: 	for (i=1;i<total;i++) {
1.125     ng       1331: 	    var partid = formname["q_"+i].value;
1.127     ng       1332: 	    if (formname["GD_SEL"+i+"_"+partid][0].selected) {
1.125     ng       1333: 		var points = formname["GD_BOX"+i+"_"+partid].value;
                   1334: 		var status = formname["solved"+i+"_"+partid].value;
1.71      ng       1335: 		if (points == "" && status != "correct_by_student") {
                   1336: 		    noscore[ptr] = i;
                   1337: 		    ptr++;
                   1338: 		}
                   1339: 	    }
                   1340: 	}
                   1341: 	if (ptr != 0) {
                   1342: 	    var sense = ptr == 1 ? ": " : "s: ";
                   1343: 	    var prolist = "";
                   1344: 	    if (ptr == 1) {
                   1345: 		prolist = noscore[0];
                   1346: 	    } else {
                   1347: 		var i = 0;
                   1348: 		while (i < ptr-1) {
                   1349: 		    prolist += noscore[i]+", ";
                   1350: 		    i++;
                   1351: 		}
                   1352: 		prolist += "and "+noscore[i];
                   1353: 	    }
                   1354: 	    var resp = confirm("You did not assign any score for the following problem"+sense+prolist+". Continue?");
                   1355: 	    if (resp == false) {
                   1356: 		return false;
                   1357: 	    }
                   1358: 	}
1.45      ng       1359: 
1.71      ng       1360: 	formname.submit();
                   1361:     }
                   1362: SUBJAVASCRIPT
                   1363: }
1.45      ng       1364: 
1.71      ng       1365: #--- javascript for essay type problem --
                   1366: sub sub_page_kw_js {
                   1367:     my $request = shift;
1.80      ng       1368:     my $iconpath = $request->dir_config('lonIconsURL');
1.118     ng       1369:     &commonJSfunctions($request);
1.350     albertel 1370: 
1.597     wenzelju 1371:     my $inner_js_msg_central= &Apache::lonhtmlcommon::scripttag(<<INNERJS);
1.350     albertel 1372:     function checkInput() {
                   1373:       opener.document.SCORE.msgsub.value = opener.checkEntities(document.msgcenter.msgsub.value);
                   1374:       var nmsg   = opener.document.SCORE.savemsgN.value;
                   1375:       var usrctr = document.msgcenter.usrctr.value;
                   1376:       var newval = opener.document.SCORE["newmsg"+usrctr];
                   1377:       newval.value = opener.checkEntities(document.msgcenter.newmsg.value);
                   1378: 
                   1379:       var msgchk = "";
                   1380:       if (document.msgcenter.subchk.checked) {
                   1381:          msgchk = "msgsub,";
                   1382:       }
                   1383:       var includemsg = 0;
                   1384:       for (var i=1; i<=nmsg; i++) {
                   1385:           var opnmsg = opener.document.SCORE["savemsg"+i];
                   1386:           var frmmsg = document.msgcenter["msg"+i];
                   1387:           opnmsg.value = opener.checkEntities(frmmsg.value);
                   1388:           var showflg = opener.document.SCORE["shownOnce"+i];
                   1389:           showflg.value = "1";
                   1390:           var chkbox = document.msgcenter["msgn"+i];
                   1391:           if (chkbox.checked) {
                   1392:              msgchk += "savemsg"+i+",";
                   1393:              includemsg = 1;
                   1394:           }
                   1395:       }
                   1396:       if (document.msgcenter.newmsgchk.checked) {
                   1397:          msgchk += "newmsg"+usrctr;
                   1398:          includemsg = 1;
                   1399:       }
                   1400:       imgformname = opener.document.SCORE["mailicon"+usrctr];
                   1401:       imgformname.src = "$iconpath/"+((includemsg) ? "mailto.gif" : "mailbkgrd.gif");
                   1402:       var includemsg = opener.document.SCORE["includemsg"+usrctr];
                   1403:       includemsg.value = msgchk;
                   1404: 
                   1405:       self.close()
                   1406: 
                   1407:     }
                   1408: INNERJS
                   1409: 
1.597     wenzelju 1410:     my $inner_js_highlight_central= &Apache::lonhtmlcommon::scripttag(<<INNERJS);
1.351     albertel 1411:     function updateChoice(flag) {
                   1412:       opener.document.SCORE.kwclr.value = opener.radioSelection(document.hlCenter.kwdclr);
                   1413:       opener.document.SCORE.kwsize.value = opener.radioSelection(document.hlCenter.kwdsize);
                   1414:       opener.document.SCORE.kwstyle.value = opener.radioSelection(document.hlCenter.kwdstyle);
                   1415:       opener.document.SCORE.refresh.value = "on";
                   1416:       if (opener.document.SCORE.keywords.value!=""){
                   1417:          opener.document.SCORE.submit();
                   1418:       }
                   1419:       self.close()
                   1420:     }
                   1421: INNERJS
                   1422: 
                   1423:     my $start_page_msg_central = 
                   1424:         &Apache::loncommon::start_page('Message Central',$inner_js_msg_central,
                   1425: 				       {'js_ready'  => 1,
                   1426: 					'only_body' => 1,
                   1427: 					'bgcolor'   =>'#FFFFFF',});
                   1428:     my $end_page_msg_central = 
                   1429: 	&Apache::loncommon::end_page({'js_ready' => 1});
                   1430: 
                   1431: 
                   1432:     my $start_page_highlight_central = 
                   1433:         &Apache::loncommon::start_page('Highlight Central',
                   1434: 				       $inner_js_highlight_central,
1.350     albertel 1435: 				       {'js_ready'  => 1,
                   1436: 					'only_body' => 1,
                   1437: 					'bgcolor'   =>'#FFFFFF',});
1.351     albertel 1438:     my $end_page_highlight_central = 
1.350     albertel 1439: 	&Apache::loncommon::end_page({'js_ready' => 1});
                   1440: 
1.219     www      1441:     my $docopen=&Apache::lonhtmlcommon::javascript_docopen();
1.236     albertel 1442:     $docopen=~s/^document\.//;
1.539     riegler  1443:     my $alertmsg = &mt('Please select a word or group of words from document and then click this link.');
1.597     wenzelju 1444:     $request->print(&Apache::lonhtmlcommon::scripttag(<<SUBJAVASCRIPT));
1.45      ng       1445: 
1.44      ng       1446: //===================== Show list of keywords ====================
1.122     ng       1447:   function keywords(formname) {
                   1448:     var nret = prompt("Keywords list, separated by a space. Add/delete to list if desired.",formname.keywords.value);
1.44      ng       1449:     if (nret==null) return;
1.122     ng       1450:     formname.keywords.value = nret;
1.44      ng       1451: 
1.122     ng       1452:     if (formname.keywords.value != "") {
1.128     ng       1453: 	formname.refresh.value = "on";
1.122     ng       1454: 	formname.submit();
1.44      ng       1455:     }
                   1456:     return;
                   1457:   }
                   1458: 
                   1459: //===================== Script to view submitted by ==================
                   1460:   function viewSubmitter(submitter) {
                   1461:     document.SCORE.refresh.value = "on";
                   1462:     document.SCORE.NCT.value = "1";
                   1463:     document.SCORE.unamedom0.value = submitter;
                   1464:     document.SCORE.submit();
                   1465:     return;
                   1466:   }
                   1467: 
                   1468: //===================== Script to add keyword(s) ==================
                   1469:   function getSel() {
                   1470:     if (document.getSelection) txt = document.getSelection();
                   1471:     else if (document.selection) txt = document.selection.createRange().text;
                   1472:     else return;
                   1473:     var cleantxt = txt.replace(new RegExp('([\\f\\n\\r\\t\\v ])+', 'g')," ");
                   1474:     if (cleantxt=="") {
1.539     riegler  1475: 	alert("$alertmsg");
1.44      ng       1476: 	return;
                   1477:     }
                   1478:     var nret = prompt("Add selection to keyword list? Edit if desired.",cleantxt);
                   1479:     if (nret==null) return;
1.127     ng       1480:     document.SCORE.keywords.value = document.SCORE.keywords.value+" "+nret;
1.44      ng       1481:     if (document.SCORE.keywords.value != "") {
1.127     ng       1482: 	document.SCORE.refresh.value = "on";
1.44      ng       1483: 	document.SCORE.submit();
                   1484:     }
                   1485:     return;
                   1486:   }
                   1487: 
                   1488: //====================== Script for composing message ==============
1.80      ng       1489:    // preload images
                   1490:    img1 = new Image();
                   1491:    img1.src = "$iconpath/mailbkgrd.gif";
                   1492:    img2 = new Image();
                   1493:    img2.src = "$iconpath/mailto.gif";
                   1494: 
1.44      ng       1495:   function msgCenter(msgform,usrctr,fullname) {
                   1496:     var Nmsg  = msgform.savemsgN.value;
                   1497:     savedMsgHeader(Nmsg,usrctr,fullname);
                   1498:     var subject = msgform.msgsub.value;
1.127     ng       1499:     var msgchk = document.SCORE["includemsg"+usrctr].value;
1.44      ng       1500:     re = /msgsub/;
                   1501:     var shwsel = "";
                   1502:     if (re.test(msgchk)) { shwsel = "checked" }
1.123     ng       1503:     subject = (document.SCORE.shownSub.value == 0 ? checkEntities(subject) : subject);
                   1504:     displaySubject(checkEntities(subject),shwsel);
1.44      ng       1505:     for (var i=1; i<=Nmsg; i++) {
1.123     ng       1506: 	var testmsg = "savemsg"+i+",";
                   1507: 	re = new RegExp(testmsg,"g");
1.44      ng       1508: 	shwsel = "";
                   1509: 	if (re.test(msgchk)) { shwsel = "checked" }
1.125     ng       1510: 	var message = document.SCORE["savemsg"+i].value;
1.126     ng       1511: 	message = (document.SCORE["shownOnce"+i].value == 0 ? checkEntities(message) : message);
1.123     ng       1512: 	displaySavedMsg(i,message,shwsel); //I do not get it. w/o checkEntities on saved messages,
                   1513: 	                                   //any &lt; is already converted to <, etc. However, only once!!
1.44      ng       1514:     }
1.125     ng       1515:     newmsg = document.SCORE["newmsg"+usrctr].value;
1.44      ng       1516:     shwsel = "";
                   1517:     re = /newmsg/;
                   1518:     if (re.test(msgchk)) { shwsel = "checked" }
                   1519:     newMsg(newmsg,shwsel);
                   1520:     msgTail(); 
                   1521:     return;
                   1522:   }
                   1523: 
1.123     ng       1524:   function checkEntities(strx) {
                   1525:     if (strx.length == 0) return strx;
                   1526:     var orgStr = ["&", "<", ">", '"']; 
                   1527:     var newStr = ["&amp;", "&lt;", "&gt;", "&quot;"];
                   1528:     var counter = 0;
                   1529:     while (counter < 4) {
                   1530: 	strx = strReplace(strx,orgStr[counter],newStr[counter]);
                   1531: 	counter++;
                   1532:     }
                   1533:     return strx;
                   1534:   }
                   1535: 
                   1536:   function strReplace(strx, orgStr, newStr) {
                   1537:     return strx.split(orgStr).join(newStr);
                   1538:   }
                   1539: 
1.44      ng       1540:   function savedMsgHeader(Nmsg,usrctr,fullname) {
1.76      ng       1541:     var height = 70*Nmsg+250;
1.44      ng       1542:     var scrollbar = "no";
                   1543:     if (height > 600) {
                   1544: 	height = 600;
                   1545: 	scrollbar = "yes";
                   1546:     }
1.118     ng       1547:     var xpos = (screen.width-600)/2;
                   1548:     xpos = (xpos < 0) ? '0' : xpos;
                   1549:     var ypos = (screen.height-height)/2-30;
                   1550:     ypos = (ypos < 0) ? '0' : ypos;
                   1551: 
1.206     albertel 1552:     pWin = window.open('', 'MessageCenter', 'resizable=yes,toolbar=no,location=no,scrollbars='+scrollbar+',screenx='+xpos+',screeny='+ypos+',width=600,height='+height);
1.76      ng       1553:     pWin.focus();
                   1554:     pDoc = pWin.document;
1.219     www      1555:     pDoc.$docopen;
1.351     albertel 1556:     pDoc.write('$start_page_msg_central');
1.76      ng       1557: 
                   1558:     pDoc.write("<form action=\\"inactive\\" name=\\"msgcenter\\">");
                   1559:     pDoc.write("<input value=\\""+usrctr+"\\" name=\\"usrctr\\" type=\\"hidden\\">");
1.465     albertel 1560:     pDoc.write("<h3><span class=\\"LC_info\\">&nbsp;Compose Message for \"+fullname+\"<\\/span><\\/h3><br /><br />");
1.76      ng       1561: 
1.564     bisitz   1562:     pDoc.write('<table border="0" width="100%"><tr><td bgcolor="#777777">');
                   1563:     pDoc.write('<table border="0" width="100%"><tr bgcolor="#DDFFFF">');
1.465     albertel 1564:     pDoc.write("<td><b>Type<\\/b><\\/td><td><b>Include<\\/b><\\/td><td><b>Message<\\/td><\\/tr>");
1.44      ng       1565: }
                   1566:     function displaySubject(msg,shwsel) {
1.76      ng       1567:     pDoc = pWin.document;
                   1568:     pDoc.write("<tr bgcolor=\\"#ffffdd\\">");
1.465     albertel 1569:     pDoc.write("<td>Subject<\\/td>");
                   1570:     pDoc.write("<td align=\\"center\\"><input name=\\"subchk\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
                   1571:     pDoc.write("<td><input name=\\"msgsub\\" type=\\"text\\" value=\\""+msg+"\\"size=\\"60\\" maxlength=\\"80\\"><\\/td><\\/tr>");
1.44      ng       1572: }
                   1573: 
1.72      ng       1574:   function displaySavedMsg(ctr,msg,shwsel) {
1.76      ng       1575:     pDoc = pWin.document;
                   1576:     pDoc.write("<tr bgcolor=\\"#ffffdd\\">");
1.465     albertel 1577:     pDoc.write("<td align=\\"center\\">"+ctr+"<\\/td>");
                   1578:     pDoc.write("<td align=\\"center\\"><input name=\\"msgn"+ctr+"\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
                   1579:     pDoc.write("<td><textarea name=\\"msg"+ctr+"\\" cols=\\"60\\" rows=\\"3\\">"+msg+"<\\/textarea><\\/td><\\/tr>");
1.44      ng       1580: }
                   1581: 
                   1582:   function newMsg(newmsg,shwsel) {
1.76      ng       1583:     pDoc = pWin.document;
                   1584:     pDoc.write("<tr bgcolor=\\"#ffffdd\\">");
1.465     albertel 1585:     pDoc.write("<td align=\\"center\\">New<\\/td>");
                   1586:     pDoc.write("<td align=\\"center\\"><input name=\\"newmsgchk\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
                   1587:     pDoc.write("<td><textarea name=\\"newmsg\\" cols=\\"60\\" rows=\\"3\\" onchange=\\"javascript:this.form.newmsgchk.checked=true\\" >"+newmsg+"<\\/textarea><\\/td><\\/tr>");
1.44      ng       1588: }
                   1589: 
                   1590:   function msgTail() {
1.76      ng       1591:     pDoc = pWin.document;
1.465     albertel 1592:     pDoc.write("<\\/table>");
                   1593:     pDoc.write("<\\/td><\\/tr><\\/table>&nbsp;");
1.589     bisitz   1594:     pDoc.write("<input type=\\"button\\" value=\\"Save\\" onclick=\\"javascript:checkInput()\\">&nbsp;&nbsp;");
                   1595:     pDoc.write("<input type=\\"button\\" value=\\"Cancel\\" onclick=\\"self.close()\\"><br /><br />");
1.465     albertel 1596:     pDoc.write("<\\/form>");
1.351     albertel 1597:     pDoc.write('$end_page_msg_central');
1.128     ng       1598:     pDoc.close();
1.44      ng       1599: }
                   1600: 
                   1601: //====================== Script for keyword highlight options ==============
                   1602:   function kwhighlight() {
                   1603:     var kwclr    = document.SCORE.kwclr.value;
                   1604:     var kwsize   = document.SCORE.kwsize.value;
                   1605:     var kwstyle  = document.SCORE.kwstyle.value;
                   1606:     var redsel = "";
                   1607:     var grnsel = "";
                   1608:     var blusel = "";
                   1609:     if (kwclr=="red")   {var redsel="checked"};
                   1610:     if (kwclr=="green") {var grnsel="checked"};
                   1611:     if (kwclr=="blue")  {var blusel="checked"};
                   1612:     var sznsel = "";
                   1613:     var sz1sel = "";
                   1614:     var sz2sel = "";
                   1615:     if (kwsize=="0")  {var sznsel="checked"};
                   1616:     if (kwsize=="+1") {var sz1sel="checked"};
                   1617:     if (kwsize=="+2") {var sz2sel="checked"};
                   1618:     var synsel = "";
                   1619:     var syisel = "";
                   1620:     var sybsel = "";
                   1621:     if (kwstyle=="")    {var synsel="checked"};
                   1622:     if (kwstyle=="<i>") {var syisel="checked"};
                   1623:     if (kwstyle=="<b>") {var sybsel="checked"};
                   1624:     highlightCentral();
                   1625:     highlightbody('red','red',redsel,'0','normal',sznsel,'','normal',synsel);
                   1626:     highlightbody('green','green',grnsel,'+1','+1',sz1sel,'<i>','italic',syisel);
                   1627:     highlightbody('blue','blue',blusel,'+2','+2',sz2sel,'<b>','bold',sybsel);
                   1628:     highlightend();
                   1629:     return;
                   1630:   }
                   1631: 
                   1632:   function highlightCentral() {
1.76      ng       1633: //    if (window.hwdWin) window.hwdWin.close();
1.118     ng       1634:     var xpos = (screen.width-400)/2;
                   1635:     xpos = (xpos < 0) ? '0' : xpos;
                   1636:     var ypos = (screen.height-330)/2-30;
                   1637:     ypos = (ypos < 0) ? '0' : ypos;
                   1638: 
1.206     albertel 1639:     hwdWin = window.open('', 'KeywordHighlightCentral', 'resizeable=yes,toolbar=no,location=no,scrollbars=no,width=400,height=300,screenx='+xpos+',screeny='+ypos);
1.76      ng       1640:     hwdWin.focus();
                   1641:     var hDoc = hwdWin.document;
1.219     www      1642:     hDoc.$docopen;
1.351     albertel 1643:     hDoc.write('$start_page_highlight_central');
1.76      ng       1644:     hDoc.write("<form action=\\"inactive\\" name=\\"hlCenter\\">");
1.465     albertel 1645:     hDoc.write("<h3><span class=\\"LC_info\\">&nbsp;Keyword Highlight Options<\\/span><\\/h3><br /><br />");
1.76      ng       1646: 
1.564     bisitz   1647:     hDoc.write('<table border="0" width="100%"><tr><td bgcolor="#777777">');
                   1648:     hDoc.write('<table border="0" width="100%"><tr bgcolor="#DDFFFF">');
1.465     albertel 1649:     hDoc.write("<td><b>Text Color<\\/b><\\/td><td><b>Font Size<\\/b><\\/td><td><b>Font Style<\\/td><\\/tr>");
1.44      ng       1650:   }
                   1651: 
                   1652:   function highlightbody(clrval,clrtxt,clrsel,szval,sztxt,szsel,syval,sytxt,sysel) { 
1.76      ng       1653:     var hDoc = hwdWin.document;
                   1654:     hDoc.write("<tr bgcolor=\\"#ffffdd\\">");
                   1655:     hDoc.write("<td align=\\"left\\">");
1.465     albertel 1656:     hDoc.write("<input name=\\"kwdclr\\" type=\\"radio\\" value=\\""+clrval+"\\" "+clrsel+">&nbsp;"+clrtxt+"<\\/td>");
1.76      ng       1657:     hDoc.write("<td align=\\"left\\">");
1.465     albertel 1658:     hDoc.write("<input name=\\"kwdsize\\" type=\\"radio\\" value=\\""+szval+"\\" "+szsel+">&nbsp;"+sztxt+"<\\/td>");
1.76      ng       1659:     hDoc.write("<td align=\\"left\\">");
1.465     albertel 1660:     hDoc.write("<input name=\\"kwdstyle\\" type=\\"radio\\" value=\\""+syval+"\\" "+sysel+">&nbsp;"+sytxt+"<\\/td>");
                   1661:     hDoc.write("<\\/tr>");
1.44      ng       1662:   }
                   1663: 
                   1664:   function highlightend() { 
1.76      ng       1665:     var hDoc = hwdWin.document;
1.465     albertel 1666:     hDoc.write("<\\/table>");
                   1667:     hDoc.write("<\\/td><\\/tr><\\/table>&nbsp;");
1.589     bisitz   1668:     hDoc.write("<input type=\\"button\\" value=\\"Save\\" onclick=\\"javascript:updateChoice(1)\\">&nbsp;&nbsp;");
                   1669:     hDoc.write("<input type=\\"button\\" value=\\"Cancel\\" onclick=\\"self.close()\\"><br /><br />");
1.465     albertel 1670:     hDoc.write("<\\/form>");
1.351     albertel 1671:     hDoc.write('$end_page_highlight_central');
1.128     ng       1672:     hDoc.close();
1.44      ng       1673:   }
                   1674: 
                   1675: SUBJAVASCRIPT
                   1676: }
                   1677: 
1.349     albertel 1678: sub get_increment {
1.348     bowersj2 1679:     my $increment = $env{'form.increment'};
                   1680:     if ($increment != 1 && $increment != .5 && $increment != .25 &&
                   1681:         $increment != .1) {
                   1682:         $increment = 1;
                   1683:     }
                   1684:     return $increment;
                   1685: }
                   1686: 
1.585     bisitz   1687: sub gradeBox_start {
                   1688:     return (
                   1689:         &Apache::loncommon::start_data_table()
                   1690:        .&Apache::loncommon::start_data_table_header_row()
                   1691:        .'<th>'.&mt('Part').'</th>'
                   1692:        .'<th>'.&mt('Points').'</th>'
                   1693:        .'<th>&nbsp;</th>'
                   1694:        .'<th>'.&mt('Assign Grade').'</th>'
                   1695:        .'<th>'.&mt('Weight').'</th>'
                   1696:        .'<th>'.&mt('Grade Status').'</th>'
                   1697:        .&Apache::loncommon::end_data_table_header_row()
                   1698:     );
                   1699: }
                   1700: 
                   1701: sub gradeBox_end {
                   1702:     return (
                   1703:         &Apache::loncommon::end_data_table()
                   1704:     );
                   1705: }
1.71      ng       1706: #--- displays the grading box, used in essay type problem and grading by page/sequence
                   1707: sub gradeBox {
1.322     albertel 1708:     my ($request,$symb,$uname,$udom,$counter,$partid,$record) = @_;
1.381     albertel 1709:     my $checkIcon = '<img alt="'.&mt('Check Mark').
1.485     albertel 1710: 	'" src="'.&Apache::loncommon::lonhttpdurl($request->dir_config('lonIconsURL').'/check.gif').'" height="16" border="0" />';
1.71      ng       1711:     my $wgt    = &Apache::lonnet::EXT('resource.'.$partid.'.weight',$symb,$udom,$uname);
1.466     albertel 1712:     my $wgtmsg = ($wgt > 0) ? &mt('(problem weight)') 
                   1713:                            : '<span class="LC_info">'.&mt('problem weight assigned by computer').'</span>';
1.71      ng       1714:     $wgt       = ($wgt > 0 ? $wgt : '1');
                   1715:     my $score  = ($$record{'resource.'.$partid.'.awarded'} eq '' ?
1.320     albertel 1716: 		  '' : &compute_points($$record{'resource.'.$partid.'.awarded'},$wgt));
1.71      ng       1717:     my $result='<input type="hidden" name="WGT'.$counter.'_'.$partid.'" value="'.$wgt.'" />'."\n";
1.466     albertel 1718:     my $display_part= &get_display_part($partid,$symb);
1.270     albertel 1719:     my %last_resets = &get_last_resets($symb,$env{'request.course.id'},
                   1720: 				       [$partid]);
                   1721:     my $aggtries = $$record{'resource.'.$partid.'.tries'};
1.269     raeburn  1722:     if ($last_resets{$partid}) {
                   1723:         $aggtries = &get_num_tries($record,$last_resets{$partid},$partid);
                   1724:     }
1.585     bisitz   1725:     $result.=&Apache::loncommon::start_data_table_row();
1.71      ng       1726:     my $ctr = 0;
1.348     bowersj2 1727:     my $thisweight = 0;
1.349     albertel 1728:     my $increment = &get_increment();
1.485     albertel 1729: 
                   1730:     my $radio.='<table border="0"><tr>'."\n";  # display radio buttons in a nice table 10 across
1.348     bowersj2 1731:     while ($thisweight<=$wgt) {
1.532     bisitz   1732: 	$radio.= '<td><span class="LC_nobreak"><label><input type="radio" name="RADVAL'.$counter.'_'.$partid.'" '.
1.589     bisitz   1733:         'onclick="javascript:writeBox(this.form,\''.$counter.'_'.$partid.'\','.
1.348     bowersj2 1734: 	    $thisweight.')" value="'.$thisweight.'" '.
1.401     albertel 1735: 	    ($score eq $thisweight ? 'checked="checked"':'').' /> '.$thisweight."</label></span></td>\n";
1.485     albertel 1736: 	$radio.=(($ctr+1)%10 == 0 ? '</tr><tr>' : '');
1.348     bowersj2 1737:         $thisweight += $increment;
1.71      ng       1738: 	$ctr++;
                   1739:     }
1.485     albertel 1740:     $radio.='</tr></table>';
                   1741: 
                   1742:     my $line.='<input type="text" name="GD_BOX'.$counter.'_'.$partid.'"'.
1.71      ng       1743: 	($score ne ''? ' value = "'.$score.'"':'').' size="4" '.
1.589     bisitz   1744: 	'onchange="javascript:updateRadio(this.form,\''.$counter.'_'.$partid.'\','.
1.71      ng       1745: 	$wgt.')" /></td>'."\n";
1.485     albertel 1746:     $line.='<td>/'.$wgt.' '.$wgtmsg.
1.71      ng       1747: 	($$record{'resource.'.$partid.'.solved'} eq 'correct_by_student' ? '&nbsp;'.$checkIcon : '').
1.585     bisitz   1748: 	' </td>'."\n";
                   1749:     $line.='<td><select name="GD_SEL'.$counter.'_'.$partid.'" '.
1.589     bisitz   1750: 	'onchange="javascript:clearRadBox(this.form,\''.$counter.'_'.$partid.'\')" >'."\n";
1.71      ng       1751:     if ($$record{'resource.'.$partid.'.solved'} eq 'excused') {
1.485     albertel 1752: 	$line.='<option></option>'.
                   1753: 	    '<option value="excused" selected="selected">'.&mt('excused').'</option>';
1.71      ng       1754:     } else {
1.485     albertel 1755: 	$line.='<option selected="selected"></option>'.
                   1756: 	    '<option value="excused" >'.&mt('excused').'</option>';
1.71      ng       1757:     }
1.485     albertel 1758:     $line.='<option value="reset status">'.&mt('reset status').'</option></select>'."\n";
                   1759: 
                   1760: 
1.540     riegler  1761: 	#&mt('<td><b>Part:</b></td><td>[_1]</td><td><b>Points:</b></td><td>[_2]</td><td>or</td><td>[_3]</td>',$display_part,$radio,$line);
1.485     albertel 1762:     $result .= 
1.585     bisitz   1763: 	    '<td>'.$display_part.'</td><td>'.$radio.'</td><td>'.&mt('or').'</td><td>'.$line.'</td>';
                   1764:     $result.=&Apache::loncommon::end_data_table_row();
1.71      ng       1765:     $result.='<input type="hidden" name="stores'.$counter.'_'.$partid.'" value="" />'."\n".
                   1766: 	'<input type="hidden" name="oldpts'.$counter.'_'.$partid.'" value="'.$score.'" />'."\n".
                   1767: 	'<input type="hidden" name="solved'.$counter.'_'.$partid.'" value="'.
1.269     raeburn  1768: 	$$record{'resource.'.$partid.'.solved'}.'" />'."\n".
                   1769:         '<input type="hidden" name="totaltries'.$counter.'_'.$partid.'" value="'.
                   1770:         $$record{'resource.'.$partid.'.tries'}.'" />'."\n".
                   1771:         '<input type="hidden" name="aggtries'.$counter.'_'.$partid.'" value="'.
                   1772:         $aggtries.'" />'."\n";
1.582     raeburn  1773:     my $res_error;
                   1774:     $result.=&handback_box($symb,$uname,$udom,$counter,$partid,$record,\$res_error);
                   1775:     if ($res_error) {
                   1776:         return &navmap_errormsg();
                   1777:     }
1.318     banghart 1778:     return $result;
                   1779: }
1.322     albertel 1780: 
                   1781: sub handback_box {
1.582     raeburn  1782:     my ($symb,$uname,$udom,$counter,$partid,$record,$res_error) = @_;
                   1783:     my ($partlist,$handgrade,$responseType) = &response_type($symb,$res_error);
1.323     banghart 1784:     my (@respids);
1.375     albertel 1785:      my @part_response_id = &flatten_responseType($responseType);
                   1786:     foreach my $part_response_id (@part_response_id) {
                   1787:     	my ($part,$resp) = @{ $part_response_id };
1.323     banghart 1788:         if ($part eq $partid) {
1.375     albertel 1789:             push(@respids,$resp);
1.323     banghart 1790:         }
                   1791:     }
1.318     banghart 1792:     my $result;
1.323     banghart 1793:     foreach my $respid (@respids) {
1.322     albertel 1794: 	my $prefix = $counter.'_'.$partid.'_'.$respid.'_';
                   1795: 	my $files=&get_submitted_files($udom,$uname,$partid,$respid,$record);
                   1796: 	next if (!@$files);
                   1797: 	my $file_counter = 1;
1.313     banghart 1798: 	foreach my $file (@$files) {
1.368     banghart 1799: 	    if ($file =~ /\/portfolio\//) {
                   1800:     	        my ($file_path, $file_disp) = ($file =~ m|(.+/)(.+)$|);
                   1801:     	        my ($name,$version,$ext) = &file_name_version_ext($file_disp);
                   1802:     	        $file_disp = "$name.$ext";
                   1803:     	        $file = $file_path.$file_disp;
                   1804:     	        $result.=&mt('Return commented version of [_1] to student.',
                   1805:     			 '<span class="LC_filename">'.$file_disp.'</span>');
                   1806:     	        $result.='<input type="file"   name="'.$prefix.'returndoc'.$file_counter.'" />'."\n";
                   1807:     	        $result.='<input type="hidden" name="'.$prefix.'origdoc'.$file_counter.'" value="'.$file.'" /><br />';
1.485     albertel 1808:     	        $result.='('.&mt('File will be uploaded when you click on Save &amp; Next below.').')<br />';
1.368     banghart 1809:     	        $file_counter++;
                   1810: 	    }
1.322     albertel 1811: 	}
1.313     banghart 1812:     }
1.318     banghart 1813:     return $result;    
1.71      ng       1814: }
1.44      ng       1815: 
1.58      albertel 1816: sub show_problem {
1.382     albertel 1817:     my ($request,$symb,$uname,$udom,$removeform,$viewon,$mode,$form) = @_;
1.144     albertel 1818:     my $rendered;
1.382     albertel 1819:     my %form = ((ref($form) eq 'HASH')? %{$form} : ());
1.329     albertel 1820:     &Apache::lonxml::remember_problem_counter();
1.144     albertel 1821:     if ($mode eq 'both' or $mode eq 'text') {
                   1822: 	$rendered=&Apache::loncommon::get_student_view($symb,$uname,$udom,
1.382     albertel 1823: 						       $env{'request.course.id'},
                   1824: 						       undef,\%form);
1.144     albertel 1825:     }
1.58      albertel 1826:     if ($removeform) {
                   1827: 	$rendered=~s|<form(.*?)>||g;
                   1828: 	$rendered=~s|</form>||g;
1.374     albertel 1829: 	$rendered=~s|(<input[^>]*name\s*=\s*"?)(\w+)("?)|$1would_have_been_$2$3|g;
1.58      albertel 1830:     }
1.144     albertel 1831:     my $companswer;
                   1832:     if ($mode eq 'both' or $mode eq 'answer') {
1.329     albertel 1833: 	&Apache::lonxml::restore_problem_counter();
1.382     albertel 1834: 	$companswer=
                   1835: 	    &Apache::loncommon::get_student_answers($symb,$uname,$udom,
                   1836: 						    $env{'request.course.id'},
                   1837: 						    %form);
1.144     albertel 1838:     }
1.58      albertel 1839:     if ($removeform) {
                   1840: 	$companswer=~s|<form(.*?)>||g;
                   1841: 	$companswer=~s|</form>||g;
1.144     albertel 1842: 	$companswer=~s|name="submit"|name="would_have_been_submit"|g;
1.58      albertel 1843:     }
1.468     albertel 1844:     $rendered=
1.588     bisitz   1845:         '<div class="LC_Box">'
                   1846:        .'<h3 class="LC_hcell">'.&mt('View of the problem').'</h3>'
                   1847:        .$rendered
                   1848:        .'</div>';
1.468     albertel 1849:     $companswer=
1.588     bisitz   1850:         '<div class="LC_Box">'
                   1851:        .'<h3 class="LC_hcell">'.&mt('Correct answer').'</h3>'
                   1852:        .$companswer
                   1853:        .'</div>';
1.468     albertel 1854:     my $result;
1.144     albertel 1855:     if ($mode eq 'both') {
1.588     bisitz   1856:         $result=$rendered.$companswer;
1.144     albertel 1857:     } elsif ($mode eq 'text') {
1.588     bisitz   1858:         $result=$rendered;
1.144     albertel 1859:     } elsif ($mode eq 'answer') {
1.588     bisitz   1860:         $result=$companswer;
1.144     albertel 1861:     }
1.71      ng       1862:     return $result;
1.58      albertel 1863: }
1.397     albertel 1864: 
1.396     banghart 1865: sub files_exist {
                   1866:     my ($r, $symb) = @_;
                   1867:     my @students = &Apache::loncommon::get_env_multiple('form.stuinfo');
1.397     albertel 1868: 
1.396     banghart 1869:     foreach my $student (@students) {
                   1870:         my ($uname,$udom,$fullname) = split(/:/,$student);
1.397     albertel 1871:         my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},
                   1872: 					      $udom,$uname);
1.396     banghart 1873:         my ($string,$timestamp)= &get_last_submission(\%record);
1.397     albertel 1874:         foreach my $submission (@$string) {
                   1875:             my ($partid,$respid) =
                   1876: 		($submission =~ /^resource\.([^\.]*)\.([^\.]*)\.submission/);
                   1877:             my $files=&get_submitted_files($udom,$uname,$partid,$respid,
                   1878: 					   \%record);
                   1879:             return 1 if (@$files);
1.396     banghart 1880:         }
                   1881:     }
1.397     albertel 1882:     return 0;
1.396     banghart 1883: }
1.397     albertel 1884: 
1.394     banghart 1885: sub download_all_link {
                   1886:     my ($r,$symb) = @_;
1.395     albertel 1887:     my $all_students = 
                   1888: 	join("\n", &Apache::loncommon::get_env_multiple('form.stuinfo'));
                   1889: 
                   1890:     my $parts =
                   1891: 	join("\n",&Apache::loncommon::get_env_multiple('form.vPart'));
                   1892: 
1.394     banghart 1893:     my $identifier = &Apache::loncommon::get_cgi_id();
1.514     raeburn  1894:     &Apache::lonnet::appenv({'cgi.'.$identifier.'.students' => $all_students,
                   1895:                              'cgi.'.$identifier.'.symb' => $symb,
                   1896:                              'cgi.'.$identifier.'.parts' => $parts,});
1.395     albertel 1897:     $r->print('<a href="/cgi-bin/multidownload.pl?'.$identifier.'">'.
                   1898: 	      &mt('Download All Submitted Documents').'</a>');
1.394     banghart 1899:     return
                   1900: }
1.395     albertel 1901: 
1.432     banghart 1902: sub build_section_inputs {
                   1903:     my $section_inputs;
                   1904:     if ($env{'form.section'} eq '') {
                   1905:         $section_inputs .= '<input type="hidden" name="section" value="all" />'."\n";
                   1906:     } else {
                   1907:         my @sections = &Apache::loncommon::get_env_multiple('form.section');
1.434     albertel 1908:         foreach my $section (@sections) {
1.432     banghart 1909:             $section_inputs .= '<input type="hidden" name="section" value="'.$section.'" />'."\n";
                   1910:         }
                   1911:     }
                   1912:     return $section_inputs;
                   1913: }
                   1914: 
1.44      ng       1915: # --------------------------- show submissions of a student, option to grade 
                   1916: sub submission {
                   1917:     my ($request,$counter,$total) = @_;
1.257     albertel 1918:     my ($uname,$udom)     = ($env{'form.student'},$env{'form.userdom'});
                   1919:     $udom = ($udom eq '' ? $env{'user.domain'} : $udom); #has form.userdom changed for a student?
                   1920:     my $usec = &Apache::lonnet::getsection($udom,$uname,$env{'request.course.id'});
                   1921:     $env{'form.fullname'} = &Apache::loncommon::plainname($uname,$udom,'lastname') if $env{'form.fullname'} eq '';
1.324     albertel 1922:     my $symb = &get_symb($request); 
                   1923:     if ($symb eq '') { $request->print("Unable to handle ambiguous references:."); return ''; }
1.104     albertel 1924: 
                   1925:     if (!&canview($usec)) {
1.398     albertel 1926: 	$request->print('<span class="LC_warning">Unable to view requested student.('.
                   1927: 			$uname.':'.$udom.' in section '.$usec.' in course id '.
                   1928: 			$env{'request.course.id'}.')</span>');
1.324     albertel 1929: 	$request->print(&show_grading_menu_form($symb));
1.104     albertel 1930: 	return;
                   1931:     }
                   1932: 
1.257     albertel 1933:     if (!$env{'form.lastSub'}) { $env{'form.lastSub'} = 'datesub'; }
                   1934:     if (!$env{'form.vProb'}) { $env{'form.vProb'} = 'yes'; }
                   1935:     if (!$env{'form.vAns'}) { $env{'form.vAns'} = 'yes'; }
                   1936:     my $last = ($env{'form.lastSub'} eq 'last' ? 'last' : '');
1.381     albertel 1937:     my $checkIcon = '<img alt="'.&mt('Check Mark').
                   1938: 	'" src="'.$request->dir_config('lonIconsURL').
1.122     ng       1939: 	'/check.gif" height="16" border="0" />';
1.41      ng       1940: 
1.426     albertel 1941:     my %old_essays;
1.41      ng       1942:     # header info
                   1943:     if ($counter == 0) {
                   1944: 	&sub_page_js($request);
1.257     albertel 1945: 	&sub_page_kw_js($request) if ($env{'form.handgrade'} eq 'yes');
                   1946: 	$env{'form.probTitle'} = $env{'form.probTitle'} eq '' ? 
                   1947: 	    &Apache::lonnet::gettitle($symb) : $env{'form.probTitle'};
1.397     albertel 1948: 	if ($env{'form.handgrade'} eq 'yes' && &files_exist($request, $symb)) {
1.396     banghart 1949: 	    &download_all_link($request, $symb);
                   1950: 	}
1.485     albertel 1951: 	$request->print('<h3>&nbsp;<span class="LC_info">'.&mt('Submission Record').'</span></h3>'."\n".
                   1952: 			'<h4>&nbsp;'.&mt('<b>Resource: </b> [_1]',$env{'form.probTitle'}).'</h4>'."\n");
1.118     ng       1953: 
1.44      ng       1954: 	# option to display problem, only once else it cause problems 
                   1955:         # with the form later since the problem has a form.
1.257     albertel 1956: 	if ($env{'form.vProb'} eq 'yes' or $env{'form.vAns'} eq 'yes') {
1.144     albertel 1957: 	    my $mode;
1.257     albertel 1958: 	    if ($env{'form.vProb'} eq 'yes' && $env{'form.vAns'} eq 'yes') {
1.144     albertel 1959: 		$mode='both';
1.257     albertel 1960: 	    } elsif ($env{'form.vProb'} eq 'yes') {
1.144     albertel 1961: 		$mode='text';
1.257     albertel 1962: 	    } elsif ($env{'form.vAns'} eq 'yes') {
1.144     albertel 1963: 		$mode='answer';
                   1964: 	    }
1.329     albertel 1965: 	    &Apache::lonxml::clear_problem_counter();
1.144     albertel 1966: 	    $request->print(&show_problem($request,$symb,$uname,$udom,0,1,$mode));
1.41      ng       1967: 	}
1.441     www      1968: 
1.44      ng       1969: 	# kwclr is the only variable that is guaranteed to be non blank 
                   1970:         # if this subroutine has been called once.
1.41      ng       1971: 	my %keyhash = ();
1.257     albertel 1972: 	if ($env{'form.kwclr'} eq '' && $env{'form.handgrade'} eq 'yes') {
1.41      ng       1973: 	    %keyhash = &Apache::lonnet::dump('nohist_handgrade',
1.257     albertel 1974: 					     $env{'course.'.$env{'request.course.id'}.'.domain'},
                   1975: 					     $env{'course.'.$env{'request.course.id'}.'.num'});
1.41      ng       1976: 
1.257     albertel 1977: 	    my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
                   1978: 	    $env{'form.keywords'} = $keyhash{$symb.'_keywords'} ne '' ? $keyhash{$symb.'_keywords'} : '';
                   1979: 	    $env{'form.kwclr'}    = $keyhash{$loginuser.'_kwclr'} ne '' ? $keyhash{$loginuser.'_kwclr'} : 'red';
                   1980: 	    $env{'form.kwsize'}   = $keyhash{$loginuser.'_kwsize'} ne '' ? $keyhash{$loginuser.'_kwsize'} : '0';
                   1981: 	    $env{'form.kwstyle'}  = $keyhash{$loginuser.'_kwstyle'} ne '' ? $keyhash{$loginuser.'_kwstyle'} : '';
                   1982: 	    $env{'form.msgsub'}   = $keyhash{$symb.'_subject'} ne '' ? 
                   1983: 		$keyhash{$symb.'_subject'} : $env{'form.probTitle'};
                   1984: 	    $env{'form.savemsgN'} = $keyhash{$symb.'_savemsgN'} ne '' ? $keyhash{$symb.'_savemsgN'} : '0';
1.41      ng       1985: 	}
1.257     albertel 1986: 	my $overRideScore = $env{'form.overRideScore'} eq '' ? 'no' : $env{'form.overRideScore'};
1.442     banghart 1987: 	my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
1.303     banghart 1988: 	$request->print('<form action="/adm/grades" method="post" name="SCORE" enctype="multipart/form-data">'."\n".
1.41      ng       1989: 			'<input type="hidden" name="command"    value="handgrade" />'."\n".
1.257     albertel 1990: 			'<input type="hidden" name="saveState"  value="'.$env{'form.saveState'}.'" />'."\n".
1.442     banghart 1991: 			'<input type="hidden" name="Status"     value="'.$stu_status.'" />'."\n".
1.120     ng       1992: 			'<input type="hidden" name="overRideScore" value="'.$overRideScore.'" />'."\n".
1.257     albertel 1993: 			'<input type="hidden" name="probTitle"  value="'.$env{'form.probTitle'}.'" />'."\n".
1.41      ng       1994: 			'<input type="hidden" name="refresh"    value="off" />'."\n".
1.120     ng       1995: 			'<input type="hidden" name="studentNo"  value="" />'."\n".
                   1996: 			'<input type="hidden" name="gradeOpt"   value="" />'."\n".
1.418     albertel 1997: 			'<input type="hidden" name="symb"       value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.257     albertel 1998: 			'<input type="hidden" name="showgrading" value="'.$env{'form.showgrading'}.'" />'."\n".
                   1999: 			'<input type="hidden" name="vProb"      value="'.$env{'form.vProb'}.'" />'."\n".
                   2000: 			'<input type="hidden" name="vAns"       value="'.$env{'form.vAns'}.'" />'."\n".
                   2001: 			'<input type="hidden" name="lastSub"    value="'.$env{'form.lastSub'}.'" />'."\n".
1.432     banghart 2002: 			&build_section_inputs().
1.326     albertel 2003: 			'<input type="hidden" name="submitonly" value="'.$env{'form.submitonly'}.'" />'."\n".
                   2004: 			'<input type="hidden" name="handgrade"  value="'.$env{'form.handgrade'}.'" />'."\n".
1.41      ng       2005: 			'<input type="hidden" name="NCT"'.
1.257     albertel 2006: 			' value="'.($env{'form.NTSTU'} ne '' ? $env{'form.NTSTU'} : $total+1).'" />'."\n");
                   2007: 	if ($env{'form.handgrade'} eq 'yes') {
                   2008: 	    $request->print('<input type="hidden" name="keywords" value="'.$env{'form.keywords'}.'" />'."\n".
                   2009: 			    '<input type="hidden" name="kwclr"    value="'.$env{'form.kwclr'}.'" />'."\n".
                   2010: 			    '<input type="hidden" name="kwsize"   value="'.$env{'form.kwsize'}.'" />'."\n".
                   2011: 			    '<input type="hidden" name="kwstyle"  value="'.$env{'form.kwstyle'}.'" />'."\n".
                   2012: 			    '<input type="hidden" name="msgsub"   value="'.$env{'form.msgsub'}.'" />'."\n".
1.123     ng       2013: 			    '<input type="hidden" name="shownSub" value="0" />'."\n".
1.257     albertel 2014: 			    '<input type="hidden" name="savemsgN" value="'.$env{'form.savemsgN'}.'" />'."\n");
1.154     albertel 2015: 	    foreach my $partid (&Apache::loncommon::get_env_multiple('form.vPart')) {
                   2016: 		$request->print('<input type="hidden" name="vPart" value="'.$partid.'" />'."\n");
                   2017: 	    }
1.123     ng       2018: 	}
1.41      ng       2019: 	
                   2020: 	my ($cts,$prnmsg) = (1,'');
1.257     albertel 2021: 	while ($cts <= $env{'form.savemsgN'}) {
1.41      ng       2022: 	    $prnmsg.='<input type="hidden" name="savemsg'.$cts.'" value="'.
1.123     ng       2023: 		(!exists($keyhash{$symb.'_savemsg'.$cts}) ? 
1.257     albertel 2024: 		 &Apache::lonfeedback::clear_out_html($env{'form.savemsg'.$cts}) :
1.80      ng       2025: 		 &Apache::lonfeedback::clear_out_html($keyhash{$symb.'_savemsg'.$cts})).
1.123     ng       2026: 		'" />'."\n".
                   2027: 		'<input type="hidden" name="shownOnce'.$cts.'" value="0" />'."\n";
1.41      ng       2028: 	    $cts++;
                   2029: 	}
                   2030: 	$request->print($prnmsg);
1.32      ng       2031: 
1.257     albertel 2032: 	if ($env{'form.handgrade'} eq 'yes' && $env{'form.showgrading'} eq 'yes') {
1.88      www      2033: #
                   2034: # Print out the keyword options line
                   2035: #
1.41      ng       2036: 	    $request->print(<<KEYWORDS);
1.38      ng       2037: &nbsp;<b>Keyword Options:</b>&nbsp;
1.417     albertel 2038: <a href="javascript:keywords(document.SCORE);" target="_self">List</a>&nbsp; &nbsp;
1.589     bisitz   2039: <a href="#" onmousedown="javascript:getSel(); return false"
1.38      ng       2040:  CLASS="page">Paste Selection to List</a>&nbsp; &nbsp;
1.417     albertel 2041: <a href="javascript:kwhighlight();" target="_self">Highlight Attribute</a><br /><br />
1.38      ng       2042: KEYWORDS
1.88      www      2043: #
                   2044: # Load the other essays for similarity check
                   2045: #
1.324     albertel 2046:             my (undef,undef,$essayurl) = &Apache::lonnet::decode_symb($symb);
1.384     albertel 2047: 	    my ($adom,$aname,$apath)=($essayurl=~/^($LONCAPA::domain_re)\/($LONCAPA::username_re)\/(.*)$/);
1.359     www      2048: 	    $apath=&escape($apath);
1.88      www      2049: 	    $apath=~s/\W/\_/gs;
1.426     albertel 2050: 	    %old_essays=&Apache::lonnet::dump('nohist_essay_'.$apath,$adom,$aname);
1.41      ng       2051:         }
                   2052:     }
1.44      ng       2053: 
1.441     www      2054: # This is where output for one specific student would start
1.592     bisitz   2055:     my $add_class = ($counter%2) ? ' LC_grade_show_user_odd_row' : '';
                   2056:     $request->print(
                   2057:         "\n\n"
                   2058:        .'<div class="LC_grade_show_user'.$add_class.'">'
                   2059:        .'<h2>'.&nameUserString(undef,$env{'form.fullname'},$uname,$udom).'</h2>'
                   2060:        ."\n"
                   2061:     );
1.441     www      2062: 
1.592     bisitz   2063:     # Show additional functions if allowed
                   2064:     if ($perm{'vgr'}) {
                   2065:         $request->print(
                   2066:             &Apache::loncommon::track_student_link(
                   2067:                 &mt('View recent activity'),
                   2068:                 $uname,$udom,'check')
                   2069:            .' '
                   2070:         );
                   2071:     }
                   2072:     if ($perm{'opa'}) {
                   2073:         $request->print(
                   2074:             &Apache::loncommon::pprmlink(
                   2075:                 &mt('Set/Change parameters'),
                   2076:                 $uname,$udom,$symb,'check'));
                   2077:     }
                   2078: 
                   2079:     # Show Problem
1.257     albertel 2080:     if ($env{'form.vProb'} eq 'all' or $env{'form.vAns'} eq 'all') {
1.144     albertel 2081: 	my $mode;
1.257     albertel 2082: 	if ($env{'form.vProb'} eq 'all' && $env{'form.vAns'} eq 'all') {
1.144     albertel 2083: 	    $mode='both';
1.257     albertel 2084: 	} elsif ($env{'form.vProb'} eq 'all' ) {
1.144     albertel 2085: 	    $mode='text';
1.257     albertel 2086: 	} elsif ($env{'form.vAns'} eq 'all') {
1.144     albertel 2087: 	    $mode='answer';
                   2088: 	}
1.329     albertel 2089: 	&Apache::lonxml::clear_problem_counter();
1.475     albertel 2090: 	$request->print(&show_problem($request,$symb,$uname,$udom,1,1,$mode,{'request.prefix' => 'ctr'.$counter}));
1.58      albertel 2091:     }
1.144     albertel 2092: 
1.257     albertel 2093:     my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
1.582     raeburn  2094:     my $res_error;
                   2095:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
                   2096:     if ($res_error) {
                   2097:         $request->print(&navmap_errormsg());
                   2098:         return;
                   2099:     }
1.41      ng       2100: 
1.44      ng       2101:     # Display student info
1.41      ng       2102:     $request->print(($counter == 0 ? '' : '<br />'));
1.590     bisitz   2103: 
                   2104:     my $result='<div class="LC_Box">'
                   2105:               .'<h3 class="LC_hcell">'.&mt('Submissions').'</h3>';
1.45      ng       2106:     $result.='<input type="hidden" name="name'.$counter.
1.588     bisitz   2107:              '" value="'.$env{'form.fullname'}.'" />'."\n";
1.469     albertel 2108:     if ($env{'form.handgrade'} eq 'no') {
1.588     bisitz   2109:         $result.='<p class="LC_info">'
                   2110:                 .&mt('Part(s) graded correct by the computer is marked with a [_1] symbol.',$checkIcon)
                   2111:                 ."</p>\n";
1.469     albertel 2112:     }
                   2113: 
1.118     ng       2114:     # If any part of the problem is an essay-response (handgraded), then check for collaborators
1.464     albertel 2115:     my $fullname;
                   2116:     my $col_fullnames = [];
1.257     albertel 2117:     if ($env{'form.handgrade'} eq 'yes') {
1.464     albertel 2118: 	(my $sub_result,$fullname,$col_fullnames)=
                   2119: 	    &check_collaborators($symb,$uname,$udom,\%record,$handgrade,
                   2120: 				 $counter);
                   2121: 	$result.=$sub_result;
1.41      ng       2122:     }
1.44      ng       2123:     $request->print($result."\n");
1.588     bisitz   2124: 
1.44      ng       2125:     # print student answer/submission
1.588     bisitz   2126:     # Options are (1) Handgraded submission only
1.44      ng       2127:     #             (2) Last submission, includes submission that is not handgraded 
                   2128:     #                  (for multi-response type part)
                   2129:     #             (3) Last submission plus the parts info
                   2130:     #             (4) The whole record for this student
1.257     albertel 2131:     if ($env{'form.lastSub'} =~ /^(lastonly|hdgrade)$/) {
1.151     albertel 2132: 	my ($string,$timestamp)= &get_last_submission(\%record);
1.468     albertel 2133: 	
                   2134: 	my $lastsubonly;
                   2135: 
1.588     bisitz   2136:         if ($$timestamp eq '') {
                   2137:             $lastsubonly.='<div class="LC_grade_submissions_body">'.$$string[0].'</div>'; 
                   2138:         } else {
1.592     bisitz   2139:             $lastsubonly =
                   2140:                 '<div class="LC_grade_submissions_body">'
                   2141:                .'<b>'.&mt('Date Submitted:').'</b> '.$$timestamp."\n";
1.468     albertel 2142: 
1.151     albertel 2143: 	    my %seenparts;
1.375     albertel 2144: 	    my @part_response_id = &flatten_responseType($responseType);
                   2145: 	    foreach my $part (@part_response_id) {
1.393     albertel 2146: 		next if ($env{'form.lastSub'} eq 'hdgrade' 
                   2147: 			 && $$handgrade{$$part[0].'_'.$$part[1]} ne 'yes');
                   2148: 
1.375     albertel 2149: 		my ($partid,$respid) = @{ $part };
1.324     albertel 2150: 		my $display_part=&get_display_part($partid,$symb);
1.257     albertel 2151: 		if ($env{"form.$uname:$udom:$partid:submitted_by"}) {
1.151     albertel 2152: 		    if (exists($seenparts{$partid})) { next; }
                   2153: 		    $seenparts{$partid}=1;
1.207     albertel 2154: 		    my $submitby='<b>Part:</b> '.$display_part.
                   2155: 			' <b>Collaborative submission by:</b> '.
1.151     albertel 2156: 			'<a href="javascript:viewSubmitter(\''.
1.257     albertel 2157: 			$env{"form.$uname:$udom:$partid:submitted_by"}.
1.417     albertel 2158: 			'\');" target="_self">'.
1.257     albertel 2159: 			$$fullname{$env{"form.$uname:$udom:$partid:submitted_by"}}.'</a><br />';
1.151     albertel 2160: 		    $request->print($submitby);
                   2161: 		    next;
                   2162: 		}
                   2163: 		my $responsetype = $responseType->{$partid}->{$respid};
                   2164: 		if (!exists($record{"resource.$partid.$respid.submission"})) {
1.577     bisitz   2165:                     $lastsubonly.="\n".'<div class="LC_grade_submission_part">'.
                   2166:                         '<b>'.&mt('Part: [_1]',$display_part).'</b>'.
                   2167:                         ' <span class="LC_internal_info">'.
1.597     wenzelju 2168:                         '('.&mt('Part ID: [_1]',$respid).')'.
1.577     bisitz   2169:                         '</span>&nbsp; &nbsp;'.
1.539     riegler  2170: 			'<span class="LC_warning">'.&mt('Nothing submitted - no attempts.').'</span><br /><br /></div>';
1.151     albertel 2171: 		    next;
                   2172: 		}
1.468     albertel 2173: 		foreach my $submission (@$string) {
                   2174: 		    my ($partid,$respid) = ($submission =~ /^resource\.([^\.]*)\.([^\.]*)\.submission/);
1.375     albertel 2175: 		    if (join('_',@{$part}) ne ($partid.'_'.$respid)) { next; }
1.596     raeburn  2176: 		    my ($ressub,$hide,$subval) = split(/:/,$submission,3);
1.151     albertel 2177: 		    # Similarity check
                   2178: 		    my $similar='';
1.257     albertel 2179: 		    if($env{'form.checkPlag'}){
1.151     albertel 2180: 			my ($oname,$odom,$ocrsid,$oessay,$osim)=
1.426     albertel 2181: 			    &most_similar($uname,$udom,$subval,\%old_essays);
1.151     albertel 2182: 			if ($osim) {
                   2183: 			    $osim=int($osim*100.0);
1.426     albertel 2184: 			    my %old_course_desc = 
                   2185: 				&Apache::lonnet::coursedescription($ocrsid,
                   2186: 								   {'one_time' => 1});
                   2187: 
1.596     raeburn  2188:                             if ($hide) {
                   2189:                                 $similar='<hr /><span class="LC_warning">'.&mt("Essay was found to be similar to another essay submitted for this assignment.").'<br />'.
                   2190:                                          &mt('As the current submission is for an anonymous survey, no other details are available.').'</span><hr />';
                   2191:                             } else {
                   2192: 			        $similar="<hr /><h3><span class=\"LC_warning\">".
                   2193: 				    &mt('Essay is [_1]% similar to an essay by [_2] in course [_3] (course id [_4]:[_5])',
                   2194: 				        $osim,
                   2195: 				        &Apache::loncommon::plainname($oname,$odom).' ('.$oname.':'.$odom.')',
                   2196: 				        $old_course_desc{'description'},
                   2197: 				        $old_course_desc{'num'},
                   2198: 				        $old_course_desc{'domain'}).
                   2199: 				    '</span></h3><blockquote><i>'.
                   2200: 				    &keywords_highlight($oessay).
                   2201: 				    '</i></blockquote><hr />';
                   2202:                             }
1.151     albertel 2203: 			}
1.150     albertel 2204: 		    }
1.151     albertel 2205: 		    my $order=&get_order($partid,$respid,$symb,$uname,$udom);
1.257     albertel 2206: 		    if ($env{'form.lastSub'} eq 'lastonly' || 
                   2207: 			($env{'form.lastSub'} eq 'hdgrade' && 
1.377     albertel 2208: 			 $$handgrade{$$part[0].'_'.$$part[1]} eq 'yes')) {
1.324     albertel 2209: 			my $display_part=&get_display_part($partid,$symb);
1.577     bisitz   2210:                         $lastsubonly.='<div class="LC_grade_submission_part">'.
                   2211:                             '<b>'.&mt('Part: [_1]',$display_part).'</b>'.
                   2212:                             ' <span class="LC_internal_info">'.
                   2213:                             '('.&mt('Part ID: [_1]',$respid).')'.
1.597     wenzelju 2214:                             '</span>&nbsp; &nbsp;';
1.313     banghart 2215: 			my $files=&get_submitted_files($udom,$uname,$partid,$respid,\%record);
                   2216: 			if (@$files) {
1.596     raeburn  2217:                             if ($hide) {
                   2218:                                 $lastsubonly.='<br />'.&mt('[quant,_1,file] uploaded to this anonymous survey',scalar(@{$files}));
                   2219:                             } else {
                   2220:                                 $lastsubonly.='<br /><span class="LC_warning">'.&mt('Like all files provided by users, this file may contain viruses').'</span><br />';
                   2221:                                 foreach my $file (@$files) {
                   2222:                                     &Apache::lonnet::allowuploaded('/adm/grades',$file);
                   2223:                                     $lastsubonly.='<br /><a href="'.$file.'?rawmode=1" target="lonGRDs"><img src="'.&Apache::loncommon::icon($file).'" border="0" /> '.$file.'</a>';
                   2224:                                 }
                   2225:                             }
1.236     albertel 2226: 			    $lastsubonly.='<br />';
1.41      ng       2227: 			}
1.596     raeburn  2228:                         if ($hide) {
                   2229:                             $lastsubonly.='<b>'.&mt('Anonymous Survey').'</b>'; 
                   2230:                         } else {
                   2231: 			    $lastsubonly.='<b>'.&mt('Submitted Answer:').' </b>'.
                   2232: 			        &cleanRecord($subval,$responsetype,$symb,$partid,
                   2233: 					     $respid,\%record,$order,undef,$uname,$udom);
                   2234:                         }
1.151     albertel 2235: 			if ($similar) {$lastsubonly.="<br /><br />$similar\n";}
1.468     albertel 2236: 			$lastsubonly.='</div>';
1.41      ng       2237: 		    }
                   2238: 		}
                   2239: 	    }
1.588     bisitz   2240: 	    $lastsubonly.='</div>'."\n"; # End: LC_grade_submissions_body
1.151     albertel 2241: 	}
                   2242: 	$request->print($lastsubonly);
1.468     albertel 2243:    } elsif ($env{'form.lastSub'} eq 'datesub') {
1.598     www      2244: #	my (undef,$responseType,undef,$parts) = &showResourceInfo($symb);
                   2245:     my ($parts,$handgrade,$responseType) = &response_type($symb);
                   2246: 
1.148     albertel 2247: 	$request->print(&displaySubByDates($symb,\%record,$parts,$responseType,$checkIcon,$uname,$udom));
1.257     albertel 2248:     } elsif ($env{'form.lastSub'} =~ /^(last|all)$/) {
1.41      ng       2249: 	$request->print(&Apache::loncommon::get_previous_attempt($symb,$uname,$udom,
1.257     albertel 2250: 								 $env{'request.course.id'},
1.44      ng       2251: 								 $last,'.submission',
                   2252: 								 'Apache::grades::keywords_highlight'));
1.41      ng       2253:     }
1.120     ng       2254: 
1.121     ng       2255:     $request->print('<input type="hidden" name="unamedom'.$counter.'" value="'.$uname.':'
                   2256: 	.$udom.'" />'."\n");
1.44      ng       2257:     # return if view submission with no grading option
1.257     albertel 2258:     if ($env{'form.showgrading'} eq '' || (!&canmodify($usec))) {
1.120     ng       2259: 	my $toGrade.='<input type="button" value="Grade Student" '.
1.589     bisitz   2260: 	    'onclick="javascript:checksubmit(this.form,\'Grade Student\',\''
1.417     albertel 2261: 	    .$counter.'\');" target="_self" /> &nbsp;'."\n" if (&canmodify($usec));
1.468     albertel 2262: 	$toGrade.='</div>'."\n";
1.257     albertel 2263: 	if (($env{'form.command'} eq 'submission') || 
                   2264: 	    ($env{'form.command'} eq 'processGroup' && $counter == $total)) {
1.324     albertel 2265: 	    $toGrade.='</form>'.&show_grading_menu_form($symb); 
1.169     albertel 2266: 	}
1.180     albertel 2267: 	$request->print($toGrade);
1.41      ng       2268: 	return;
1.180     albertel 2269:     } else {
1.468     albertel 2270: 	$request->print('</div>'."\n");
1.41      ng       2271:     }
1.33      ng       2272: 
1.121     ng       2273:     # essay grading message center
1.257     albertel 2274:     if ($env{'form.handgrade'} eq 'yes') {
1.468     albertel 2275: 	my $result='<div class="LC_grade_message_center">';
                   2276:     
                   2277: 	$result.='<div class="LC_grade_message_center_header">'.
                   2278: 	    &mt('Send Message').'</div><div class="LC_grade_message_center_body">';
1.257     albertel 2279: 	my ($lastname,$givenn) = split(/,/,$env{'form.fullname'});
1.118     ng       2280: 	my $msgfor = $givenn.' '.$lastname;
1.464     albertel 2281: 	if (scalar(@$col_fullnames) > 0) {
                   2282: 	    my $lastone = pop(@$col_fullnames);
                   2283: 	    $msgfor .= ', '.(join ', ',@$col_fullnames).' and '.$lastone.'.';
1.118     ng       2284: 	}
                   2285: 	$msgfor =~ s/\'/\\'/g; #' stupid emacs - no! javascript
1.468     albertel 2286: 	$result.='<input type="hidden" name="includemsg'.$counter.'" value="" />'."\n".
1.121     ng       2287: 	    '<input type="hidden" name="newmsg'.$counter.'" value="" />'."\n";
                   2288: 	$result.='&nbsp;<a href="javascript:msgCenter(document.SCORE,'.$counter.
1.417     albertel 2289: 	    ',\''.$msgfor.'\');" target="_self">'.
1.464     albertel 2290: 	    &mt('Compose message to student').(scalar(@$col_fullnames) >= 1 ? 's' : '').'</a><label> ('.
1.350     albertel 2291: 	    &mt('incl. grades').' <input type="checkbox" name="withgrades'.$counter.'" /></label>)'.
1.118     ng       2292: 	    '<img src="'.$request->dir_config('lonIconsURL').
                   2293: 	    '/mailbkgrd.gif" width="14" height="10" name="mailicon'.$counter.'" />'."\n".
1.298     www      2294: 	    '<br />&nbsp;('.
1.468     albertel 2295: 	    &mt('Message will be sent when you click on Save &amp; Next below.').")\n";
                   2296: 	$result.='</div></div>';
1.121     ng       2297: 	$request->print($result);
1.118     ng       2298:     }
1.41      ng       2299: 
                   2300:     my %seen = ();
                   2301:     my @partlist;
1.129     ng       2302:     my @gradePartRespid;
1.375     albertel 2303:     my @part_response_id = &flatten_responseType($responseType);
1.585     bisitz   2304:     $request->print(
1.588     bisitz   2305:         '<div class="LC_Box">'
                   2306:        .'<h3 class="LC_hcell">'.&mt('Assign Grades').'</h3>'
1.585     bisitz   2307:     );
1.592     bisitz   2308:     $request->print(&gradeBox_start());
1.375     albertel 2309:     foreach my $part_response_id (@part_response_id) {
                   2310:     	my ($partid,$respid) = @{ $part_response_id };
                   2311: 	my $part_resp = join('_',@{ $part_response_id });
1.322     albertel 2312: 	next if ($seen{$partid} > 0);
1.41      ng       2313: 	$seen{$partid}++;
1.393     albertel 2314: 	next if ($$handgrade{$part_resp} ne 'yes' 
                   2315: 		 && $env{'form.lastSub'} eq 'hdgrade');
1.524     raeburn  2316: 	push(@partlist,$partid);
                   2317: 	push(@gradePartRespid,$partid.'.'.$respid);
1.322     albertel 2318: 	$request->print(&gradeBox($request,$symb,$uname,$udom,$counter,$partid,\%record));
1.41      ng       2319:     }
1.585     bisitz   2320:     $request->print(&gradeBox_end()); # </div>
                   2321:     $request->print('</div>');
1.468     albertel 2322: 
                   2323:     $request->print('<div class="LC_grade_info_links">');
                   2324:     $request->print('</div>');
                   2325: 
1.45      ng       2326:     $result='<input type="hidden" name="partlist'.$counter.
                   2327: 	'" value="'.(join ":",@partlist).'" />'."\n";
1.129     ng       2328:     $result.='<input type="hidden" name="gradePartRespid'.
                   2329: 	'" value="'.(join ":",@gradePartRespid).'" />'."\n" if ($counter == 0);
1.45      ng       2330:     my $ctr = 0;
                   2331:     while ($ctr < scalar(@partlist)) {
                   2332: 	$result.='<input type="hidden" name="partid'.$counter.'_'.$ctr.'" value="'.
                   2333: 	    $partlist[$ctr].'" />'."\n";
                   2334: 	$ctr++;
                   2335:     }
1.468     albertel 2336:     $request->print($result.''."\n");
1.41      ng       2337: 
1.441     www      2338: # Done with printing info for one student
                   2339: 
1.468     albertel 2340:     $request->print('</div>');#LC_grade_show_user
1.441     www      2341: 
                   2342: 
1.41      ng       2343:     # print end of form
                   2344:     if ($counter == $total) {
1.592     bisitz   2345:         my $endform='<br /><hr /><table border="0"><tr><td>'."\n";
1.485     albertel 2346: 	$endform.='<input type="button" value="'.&mt('Save &amp; Next').'" '.
1.589     bisitz   2347: 	    'onclick="javascript:checksubmit(this.form,\'Save & Next\','.
1.417     albertel 2348: 	    $total.','.scalar(@partlist).');" target="_self" /> &nbsp;'."\n";
1.119     ng       2349: 	my $ntstu ='<select name="NTSTU">'.
                   2350: 	    '<option>1</option><option>2</option>'.
                   2351: 	    '<option>3</option><option>5</option>'.
                   2352: 	    '<option>7</option><option>10</option></select>'."\n";
1.257     albertel 2353: 	my $nsel = ($env{'form.NTSTU'} ne '' ? $env{'form.NTSTU'} : '1');
1.401     albertel 2354: 	$ntstu =~ s/<option>$nsel</<option selected="selected">$nsel</;
1.578     raeburn  2355:         $endform.=&mt('[_1]student(s)',$ntstu);
1.485     albertel 2356: 	$endform.='&nbsp;&nbsp;<input type="button" value="'.&mt('Previous').'" '.
1.589     bisitz   2357: 	    'onclick="javascript:checksubmit(this.form,\'Previous\');" target="_self" /> &nbsp;'."\n".
1.485     albertel 2358: 	    '<input type="button" value="'.&mt('Next').'" '.
1.589     bisitz   2359: 	    'onclick="javascript:checksubmit(this.form,\'Next\');" target="_self" /> &nbsp;';
1.592     bisitz   2360:         $endform.='<span class="LC_warning">'.
                   2361:                   &mt('(Next and Previous (student) do not save the scores.)').
                   2362:                   '</span>'."\n" ;
1.349     albertel 2363:         $endform.="<input type='hidden' value='".&get_increment().
1.348     bowersj2 2364:             "' name='increment' />";
1.485     albertel 2365: 	$endform.='</td></tr></table></form>';
1.324     albertel 2366: 	$endform.=&show_grading_menu_form($symb);
1.41      ng       2367: 	$request->print($endform);
                   2368:     }
                   2369:     return '';
1.38      ng       2370: }
                   2371: 
1.464     albertel 2372: sub check_collaborators {
                   2373:     my ($symb,$uname,$udom,$record,$handgrade,$counter) = @_;
                   2374:     my ($result,@col_fullnames);
                   2375:     my ($classlist,undef,$fullname) = &getclasslist('all','0');
                   2376:     foreach my $part (keys(%$handgrade)) {
                   2377: 	my $ncol = &Apache::lonnet::EXT('resource.'.$part.
                   2378: 					'.maxcollaborators',
                   2379: 					$symb,$udom,$uname);
                   2380: 	next if ($ncol <= 0);
                   2381: 	$part =~ s/\_/\./g;
                   2382: 	next if ($record->{'resource.'.$part.'.collaborators'} eq '');
                   2383: 	my (@good_collaborators, @bad_collaborators);
                   2384: 	foreach my $possible_collaborator
                   2385: 	    (split(/,?\s+/,$record->{'resource.'.$part.'.collaborators'})) { 
                   2386: 	    $possible_collaborator =~ s/[\$\^\(\)]//g;
                   2387: 	    next if ($possible_collaborator eq '');
                   2388: 	    my ($co_name,$co_dom) = split(/\@|:/,$possible_collaborator);
                   2389: 	    $co_dom = $udom if (! defined($co_dom) || $co_dom =~ /^domain$/i);
                   2390: 	    next if ($co_name eq $uname && $co_dom eq $udom);
                   2391: 	    # Doing this grep allows 'fuzzy' specification
                   2392: 	    my @matches = grep(/^\Q$co_name\E:\Q$co_dom\E$/i, 
                   2393: 			       keys(%$classlist));
                   2394: 	    if (! scalar(@matches)) {
                   2395: 		push(@bad_collaborators, $possible_collaborator);
                   2396: 	    } else {
                   2397: 		push(@good_collaborators, @matches);
                   2398: 	    }
                   2399: 	}
                   2400: 	if (scalar(@good_collaborators) != 0) {
1.466     albertel 2401: 	    $result.='<br />'.&mt('Collaborators: ');
1.464     albertel 2402: 	    foreach my $name (@good_collaborators) {
                   2403: 		my ($lastname,$givenn) = split(/,/,$$fullname{$name});
                   2404: 		push(@col_fullnames, $givenn.' '.$lastname);
                   2405: 		$result.=$fullname->{$name}.'&nbsp; &nbsp; &nbsp;';
                   2406: 	    }
                   2407: 	    $result.='<br />'."\n";
1.466     albertel 2408: 	    my ($part)=split(/\./,$part);
1.464     albertel 2409: 	    $result.='<input type="hidden" name="collaborator'.$counter.
                   2410: 		'" value="'.$part.':'.(join ':',@good_collaborators).'" />'.
                   2411: 		"\n";
                   2412: 	}
                   2413: 	if (scalar(@bad_collaborators) > 0) {
1.466     albertel 2414: 	    $result.='<div class="LC_warning">';
1.464     albertel 2415: 	    $result.=&mt('This student has submitted [quant,_1,invalid collaborator]: [_2]',scalar(@bad_collaborators),join(', ',@bad_collaborators));
                   2416: 	    $result .= '</div>';
                   2417: 	}         
                   2418: 	if (scalar(@bad_collaborators > $ncol)) {
1.466     albertel 2419: 	    $result .= '<div class="LC_warning">';
1.464     albertel 2420: 	    $result .= &mt('This student has submitted too many '.
                   2421: 		'collaborators.  Maximum is [_1].',$ncol);
                   2422: 	    $result .= '</div>';
                   2423: 	}
                   2424:     }
                   2425:     return ($result,$fullname,\@col_fullnames);
                   2426: }
                   2427: 
1.44      ng       2428: #--- Retrieve the last submission for all the parts
1.38      ng       2429: sub get_last_submission {
1.119     ng       2430:     my ($returnhash)=@_;
1.596     raeburn  2431:     my (@string,$timestamp,%lasthidden);
1.119     ng       2432:     if ($$returnhash{'version'}) {
1.46      ng       2433: 	my %lasthash=();
                   2434: 	my ($version);
1.119     ng       2435: 	for ($version=1;$version<=$$returnhash{'version'};$version++) {
1.397     albertel 2436: 	    foreach my $key (sort(split(/\:/,
                   2437: 					$$returnhash{$version.':keys'}))) {
                   2438: 		$lasthash{$key}=$$returnhash{$version.':'.$key};
                   2439: 		$timestamp = 
1.545     raeburn  2440: 		    &Apache::lonlocal::locallocaltime($$returnhash{$version.':timestamp'});
1.46      ng       2441: 	    }
                   2442: 	}
1.596     raeburn  2443:         my %typeparts;
                   2444:         my $showsurv = 
                   2445:             &Apache::lonnet::allowed('vas',$env{'request.course.id'});
                   2446:         foreach my $key (sort(keys(%lasthash))) {
                   2447:             if ($key =~ /\.type$/) {
                   2448:                 if (($lasthash{$key} eq 'anonsurvey') || 
                   2449:                     ($lasthash{$key} eq 'anonsurveycred')) {
                   2450:                     my ($ign,@parts) = split(/\./,$key);
                   2451:                     pop(@parts);
                   2452:                     unless ($showsurv) {
                   2453:                         my $id = join(',',@parts);
                   2454:                         $typeparts{$ign.'.'.$id} = $lasthash{$key};
                   2455:                     }
                   2456:                     delete($lasthash{$key});
                   2457:                 }
                   2458:             }
                   2459:         }
                   2460:         my @hidden = keys(%typeparts);
1.397     albertel 2461: 	foreach my $key (keys(%lasthash)) {
                   2462: 	    next if ($key !~ /\.submission$/);
1.596     raeburn  2463:             my $hide;
                   2464:             if (@hidden) {
                   2465:                 foreach my $id (@hidden) {
                   2466:                     if ($key =~ /^\Q$id\E/) {
                   2467:                         $hide = 1;
                   2468:                         last;
                   2469:                     }
                   2470:                 }
                   2471:             }
1.397     albertel 2472: 	    my ($partid,$foo) = split(/submission$/,$key);
                   2473: 	    my $draft  = $lasthash{$partid.'awarddetail'} eq 'DRAFT' ?
1.398     albertel 2474: 		'<span class="LC_warning">Draft Copy</span> ' : '';
1.596     raeburn  2475: 	    push(@string, join(':', $key, $hide, $draft.$lasthash{$key}));
1.41      ng       2476: 	}
                   2477:     }
1.397     albertel 2478:     if (!@string) {
                   2479: 	$string[0] =
1.539     riegler  2480: 	    '<span class="LC_warning">'.&mt('Nothing submitted - no attempts.').'</span>';
1.397     albertel 2481:     }
                   2482:     return (\@string,\$timestamp);
1.38      ng       2483: }
1.35      ng       2484: 
1.44      ng       2485: #--- High light keywords, with style choosen by user.
1.38      ng       2486: sub keywords_highlight {
1.44      ng       2487:     my $string    = shift;
1.257     albertel 2488:     my $size      = $env{'form.kwsize'} eq '0' ? '' : 'size='.$env{'form.kwsize'};
                   2489:     my $styleon   = $env{'form.kwstyle'} eq ''  ? '' : $env{'form.kwstyle'};
1.41      ng       2490:     (my $styleoff = $styleon) =~ s/\</\<\//;
1.257     albertel 2491:     my @keylist   = split(/[,\s+]/,$env{'form.keywords'});
1.398     albertel 2492:     foreach my $keyword (@keylist) {
                   2493: 	$string =~ s/\b\Q$keyword\E(\b|\.)/<font color\=$env{'form.kwclr'} $size\>$styleon$keyword$styleoff<\/font>/gi;
1.41      ng       2494:     }
                   2495:     return $string;
1.38      ng       2496: }
1.36      ng       2497: 
1.44      ng       2498: #--- Called from submission routine
1.38      ng       2499: sub processHandGrade {
1.41      ng       2500:     my ($request) = shift;
1.324     albertel 2501:     my $symb   = &get_symb($request);
                   2502:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
1.257     albertel 2503:     my $button = $env{'form.gradeOpt'};
                   2504:     my $ngrade = $env{'form.NCT'};
                   2505:     my $ntstu  = $env{'form.NTSTU'};
1.301     albertel 2506:     my $cdom   = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   2507:     my $cnum   = $env{'course.'.$env{'request.course.id'}.'.num'};
                   2508: 
1.44      ng       2509:     if ($button eq 'Save & Next') {
                   2510: 	my $ctr = 0;
                   2511: 	while ($ctr < $ngrade) {
1.257     albertel 2512: 	    my ($uname,$udom) = split(/:/,$env{'form.unamedom'.$ctr});
1.324     albertel 2513: 	    my ($errorflag,$pts,$wgt) = &saveHandGrade($request,$symb,$uname,$udom,$ctr);
1.71      ng       2514: 	    if ($errorflag eq 'no_score') {
                   2515: 		$ctr++;
                   2516: 		next;
                   2517: 	    }
1.104     albertel 2518: 	    if ($errorflag eq 'not_allowed') {
1.398     albertel 2519: 		$request->print("<span class=\"LC_warning\">Not allowed to modify grades for $uname:$udom</span>");
1.104     albertel 2520: 		$ctr++;
                   2521: 		next;
                   2522: 	    }
1.257     albertel 2523: 	    my $includemsg = $env{'form.includemsg'.$ctr};
1.44      ng       2524: 	    my ($subject,$message,$msgstatus) = ('','','');
1.418     albertel 2525: 	    my $restitle = &Apache::lonnet::gettitle($symb);
                   2526:             my ($feedurl,$showsymb) =
                   2527: 		&get_feedurl_and_symb($symb,$uname,$udom);
                   2528: 	    my $messagetail;
1.62      albertel 2529: 	    if ($includemsg =~ /savemsg|newmsg\Q$ctr\E/) {
1.298     www      2530: 		$subject = $env{'form.msgsub'} if ($includemsg =~ /msgsub/);
1.295     www      2531: 		unless ($subject=~/\w/) { $subject=&mt('Grading Feedback'); }
1.386     raeburn  2532: 		$subject.=' ['.$restitle.']';
1.44      ng       2533: 		my (@msgnum) = split(/,/,$includemsg);
                   2534: 		foreach (@msgnum) {
1.257     albertel 2535: 		    $message.=$env{'form.'.$_} if ($_ =~ /savemsg|newmsg/ && $_ ne '');
1.44      ng       2536: 		}
1.80      ng       2537: 		$message =&Apache::lonfeedback::clear_out_html($message);
1.298     www      2538: 		if ($env{'form.withgrades'.$ctr}) {
                   2539: 		    $message.="\n\nPoint".($pts > 1 ? 's':'').' awarded = '.$pts.' out of '.$wgt;
1.386     raeburn  2540: 		    $messagetail = " for <a href=\"".
1.418     albertel 2541: 		                   $feedurl."?symb=$showsymb\">$env{'form.probTitle'}</a>";
1.386     raeburn  2542: 		}
                   2543: 		$msgstatus = 
                   2544:                     &Apache::lonmsg::user_normal_msg($uname,$udom,$subject,
                   2545: 						     $message.$messagetail,
1.418     albertel 2546:                                                      undef,$feedurl,undef,
1.386     raeburn  2547:                                                      undef,undef,$showsymb,
                   2548:                                                      $restitle);
1.574     bisitz   2549: 		$request->print('<br />'.&mt('Sending message to [_1]',$uname.':'.$udom).': '.
1.296     www      2550: 				$msgstatus);
1.44      ng       2551: 	    }
1.257     albertel 2552: 	    if ($env{'form.collaborator'.$ctr}) {
1.155     albertel 2553: 		my @collabstrs=&Apache::loncommon::get_env_multiple("form.collaborator$ctr");
1.150     albertel 2554: 		foreach my $collabstr (@collabstrs) {
                   2555: 		    my ($part,@collaborators) = split(/:/,$collabstr);
1.310     banghart 2556: 		    foreach my $collaborator (@collaborators) {
1.150     albertel 2557: 			my ($errorflag,$pts,$wgt) = 
1.324     albertel 2558: 			    &saveHandGrade($request,$symb,$collaborator,$udom,$ctr,
1.257     albertel 2559: 					   $env{'form.unamedom'.$ctr},$part);
1.150     albertel 2560: 			if ($errorflag eq 'not_allowed') {
1.362     albertel 2561: 			    $request->print("<span class=\"LC_error\">".&mt('Not allowed to modify grades for [_1]',"$collaborator:$udom")."</span>");
1.150     albertel 2562: 			    next;
1.418     albertel 2563: 			} elsif ($message ne '') {
                   2564: 			    my ($baseurl,$showsymb) = 
                   2565: 				&get_feedurl_and_symb($symb,$collaborator,
                   2566: 						      $udom);
                   2567: 			    if ($env{'form.withgrades'.$ctr}) {
                   2568: 				$messagetail = " for <a href=\"".
1.386     raeburn  2569:                                     $baseurl."?symb=$showsymb\">$env{'form.probTitle'}</a>";
1.150     albertel 2570: 			    }
1.418     albertel 2571: 			    $msgstatus = 
                   2572: 				&Apache::lonmsg::user_normal_msg($collaborator,$udom,$subject,$message.$messagetail,undef,$baseurl,undef,undef,undef,$showsymb,$restitle);
1.104     albertel 2573: 			}
1.44      ng       2574: 		    }
                   2575: 		}
                   2576: 	    }
                   2577: 	    $ctr++;
                   2578: 	}
                   2579:     }
                   2580: 
1.257     albertel 2581:     if ($env{'form.handgrade'} eq 'yes') {
1.119     ng       2582: 	# Keywords sorted in alphabatical order
1.257     albertel 2583: 	my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
1.119     ng       2584: 	my %keyhash = ();
1.257     albertel 2585: 	$env{'form.keywords'}           =~ s/,\s{0,}|\s+/ /g;
                   2586: 	$env{'form.keywords'}           =~ s/^\s+|\s+$//;
                   2587: 	my (@keywords) = sort(split(/\s+/,$env{'form.keywords'}));
                   2588: 	$env{'form.keywords'} = join(' ',@keywords);
                   2589: 	$keyhash{$symb.'_keywords'}     = $env{'form.keywords'};
                   2590: 	$keyhash{$symb.'_subject'}      = $env{'form.msgsub'};
                   2591: 	$keyhash{$loginuser.'_kwclr'}   = $env{'form.kwclr'};
                   2592: 	$keyhash{$loginuser.'_kwsize'}  = $env{'form.kwsize'};
                   2593: 	$keyhash{$loginuser.'_kwstyle'} = $env{'form.kwstyle'};
1.119     ng       2594: 
                   2595: 	# message center - Order of message gets changed. Blank line is eliminated.
1.257     albertel 2596: 	# New messages are saved in env for the next student.
1.119     ng       2597: 	# All messages are saved in nohist_handgrade.db
                   2598: 	my ($ctr,$idx) = (1,1);
1.257     albertel 2599: 	while ($ctr <= $env{'form.savemsgN'}) {
                   2600: 	    if ($env{'form.savemsg'.$ctr} ne '') {
                   2601: 		$keyhash{$symb.'_savemsg'.$idx} = $env{'form.savemsg'.$ctr};
1.119     ng       2602: 		$idx++;
                   2603: 	    }
                   2604: 	    $ctr++;
1.41      ng       2605: 	}
1.119     ng       2606: 	$ctr = 0;
                   2607: 	while ($ctr < $ngrade) {
1.257     albertel 2608: 	    if ($env{'form.newmsg'.$ctr} ne '') {
                   2609: 		$keyhash{$symb.'_savemsg'.$idx} = $env{'form.newmsg'.$ctr};
                   2610: 		$env{'form.savemsg'.$idx} = $env{'form.newmsg'.$ctr};
1.119     ng       2611: 		$idx++;
                   2612: 	    }
                   2613: 	    $ctr++;
1.41      ng       2614: 	}
1.257     albertel 2615: 	$env{'form.savemsgN'} = --$idx;
                   2616: 	$keyhash{$symb.'_savemsgN'} = $env{'form.savemsgN'};
1.119     ng       2617: 	my $putresult = &Apache::lonnet::put
1.301     albertel 2618: 	    ('nohist_handgrade',\%keyhash,$cdom,$cnum);
1.41      ng       2619:     }
1.44      ng       2620:     # Called by Save & Refresh from Highlight Attribute Window
1.257     albertel 2621:     my (undef,undef,$fullname) = &getclasslist($env{'form.section'},'1');
                   2622:     if ($env{'form.refresh'} eq 'on') {
1.86      ng       2623: 	my ($ctr,$total) = (0,0);
                   2624: 	while ($ctr < $ngrade) {
1.257     albertel 2625: 	    $total++ if  $env{'form.unamedom'.$ctr} ne '';
1.86      ng       2626: 	    $ctr++;
                   2627: 	}
1.257     albertel 2628: 	$env{'form.NTSTU'}=$ngrade;
1.86      ng       2629: 	$ctr = 0;
                   2630: 	while ($ctr < $total) {
1.257     albertel 2631: 	    my $processUser = $env{'form.unamedom'.$ctr};
                   2632: 	    ($env{'form.student'},$env{'form.userdom'}) = split(/:/,$processUser);
                   2633: 	    $env{'form.fullname'} = $$fullname{$processUser};
1.86      ng       2634: 	    &submission($request,$ctr,$total-1);
1.41      ng       2635: 	    $ctr++;
                   2636: 	}
                   2637: 	return '';
                   2638:     }
1.36      ng       2639: 
1.121     ng       2640: # Go directly to grade student - from submission or link from chart page
1.120     ng       2641:     if ($button eq 'Grade Student') {
1.598     www      2642: #	(undef,undef,$env{'form.handgrade'},undef,undef) = &showResourceInfo($symb);
1.257     albertel 2643: 	my $processUser = $env{'form.unamedom'.$env{'form.studentNo'}};
                   2644: 	($env{'form.student'},$env{'form.userdom'}) = split(/:/,$processUser);
                   2645: 	$env{'form.fullname'} = $$fullname{$processUser};
1.120     ng       2646: 	&submission($request,0,0);
                   2647: 	return '';
                   2648:     }
                   2649: 
1.44      ng       2650:     # Get the next/previous one or group of students
1.257     albertel 2651:     my $firststu = $env{'form.unamedom0'};
                   2652:     my $laststu = $env{'form.unamedom'.($ngrade-1)};
1.119     ng       2653:     my $ctr = 2;
1.41      ng       2654:     while ($laststu eq '') {
1.257     albertel 2655: 	$laststu  = $env{'form.unamedom'.($ngrade-$ctr)};
1.41      ng       2656: 	$ctr++;
                   2657: 	$laststu = $firststu if ($ctr > $ngrade);
                   2658:     }
1.44      ng       2659: 
1.41      ng       2660:     my (@parsedlist,@nextlist);
                   2661:     my ($nextflg) = 0;
1.524     raeburn  2662:     foreach my $item (sort 
1.294     albertel 2663: 	     {
                   2664: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                   2665: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                   2666: 		 }
                   2667: 		 return $a cmp $b;
                   2668: 	     } (keys(%$fullname))) {
1.41      ng       2669: 	if ($nextflg == 1 && $button =~ /Next$/) {
1.524     raeburn  2670: 	    push(@parsedlist,$item);
1.41      ng       2671: 	}
1.524     raeburn  2672: 	$nextflg = 1 if ($item eq $laststu);
1.41      ng       2673: 	if ($button eq 'Previous') {
1.524     raeburn  2674: 	    last if ($item eq $firststu);
                   2675: 	    push(@parsedlist,$item);
1.41      ng       2676: 	}
                   2677:     }
                   2678:     $ctr = 0;
                   2679:     @parsedlist = reverse @parsedlist if ($button eq 'Previous');
1.582     raeburn  2680:     my $res_error;
                   2681:     my ($partlist) = &response_type($symb,\$res_error);
                   2682:     if ($res_error) {
                   2683:         $request->print(&navmap_errormsg());
                   2684:         return;
                   2685:     }
1.41      ng       2686:     foreach my $student (@parsedlist) {
1.257     albertel 2687: 	my $submitonly=$env{'form.submitonly'};
1.41      ng       2688: 	my ($uname,$udom) = split(/:/,$student);
1.301     albertel 2689: 	
                   2690: 	if ($submitonly eq 'queued') {
                   2691: 	    my %queue_status = 
                   2692: 		&Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
                   2693: 							$udom,$uname);
                   2694: 	    next if (!defined($queue_status{'gradingqueue'}));
                   2695: 	}
                   2696: 
1.156     albertel 2697: 	if ($submitonly =~ /^(yes|graded|incorrect)$/) {
1.257     albertel 2698: #	    my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
1.324     albertel 2699: 	    my %status=&student_gradeStatus($symb,$udom,$uname,$partlist);
1.145     albertel 2700: 	    my $submitted = 0;
1.248     albertel 2701: 	    my $ungraded = 0;
                   2702: 	    my $incorrect = 0;
1.524     raeburn  2703: 	    foreach my $item (keys(%status)) {
                   2704: 		$submitted = 1 if ($status{$item} ne 'nothing');
                   2705: 		$ungraded = 1 if ($status{$item} =~ /^ungraded/);
                   2706: 		$incorrect = 1 if ($status{$item} =~ /^incorrect/);
                   2707: 		my ($foo,$partid,$foo1) = split(/\./,$item);
1.145     albertel 2708: 		if ($status{'resource.'.$partid.'.submitted_by'} ne '') {
                   2709: 		    $submitted = 0;
                   2710: 		}
1.41      ng       2711: 	    }
1.156     albertel 2712: 	    next if (!$submitted && ($submitonly eq 'yes' ||
                   2713: 				     $submitonly eq 'incorrect' ||
                   2714: 				     $submitonly eq 'graded'));
1.248     albertel 2715: 	    next if (!$ungraded && ($submitonly eq 'graded'));
                   2716: 	    next if (!$incorrect && $submitonly eq 'incorrect');
1.41      ng       2717: 	}
1.524     raeburn  2718: 	push(@nextlist,$student) if ($ctr < $ntstu);
1.129     ng       2719: 	last if ($ctr == $ntstu);
1.41      ng       2720: 	$ctr++;
                   2721:     }
1.36      ng       2722: 
1.41      ng       2723:     $ctr = 0;
                   2724:     my $total = scalar(@nextlist)-1;
1.39      ng       2725: 
1.524     raeburn  2726:     foreach (sort(@nextlist)) {
1.41      ng       2727: 	my ($uname,$udom,$submitter) = split(/:/);
1.257     albertel 2728: 	$env{'form.student'}  = $uname;
                   2729: 	$env{'form.userdom'}  = $udom;
                   2730: 	$env{'form.fullname'} = $$fullname{$_};
1.41      ng       2731: 	&submission($request,$ctr,$total);
                   2732: 	$ctr++;
                   2733:     }
                   2734:     if ($total < 0) {
1.485     albertel 2735: 	my $the_end = '<h3><span class="LC_info">'.&mt('LON-CAPA User Message').'</span></h3><br />'."\n";
                   2736: 	$the_end.=&mt('<b>Message: </b> No more students for this section or class.').'<br /><br />'."\n";
                   2737: 	$the_end.=&mt('Click on the button below to return to the grading menu.').'<br /><br />'."\n";
1.324     albertel 2738: 	$the_end.=&show_grading_menu_form($symb);
1.41      ng       2739: 	$request->print($the_end);
                   2740:     }
                   2741:     return '';
1.38      ng       2742: }
1.36      ng       2743: 
1.44      ng       2744: #---- Save the score and award for each student, if changed
1.38      ng       2745: sub saveHandGrade {
1.324     albertel 2746:     my ($request,$symb,$stuname,$domain,$newflg,$submitter,$part) = @_;
1.342     banghart 2747:     my @version_parts;
1.104     albertel 2748:     my $usec = &Apache::lonnet::getsection($domain,$stuname,
1.257     albertel 2749: 					   $env{'request.course.id'});
1.104     albertel 2750:     if (!&canmodify($usec)) { return('not_allowed'); }
1.337     banghart 2751:     my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$domain,$stuname);
1.251     banghart 2752:     my @parts_graded;
1.77      ng       2753:     my %newrecord  = ();
                   2754:     my ($pts,$wgt) = ('','');
1.269     raeburn  2755:     my %aggregate = ();
                   2756:     my $aggregateflag = 0;
1.301     albertel 2757:     my @parts = split(/:/,$env{'form.partlist'.$newflg});
                   2758:     foreach my $new_part (@parts) {
1.337     banghart 2759: 	#collaborator ($submi may vary for different parts
1.259     banghart 2760: 	if ($submitter && $new_part ne $part) { next; }
                   2761: 	my $dropMenu = $env{'form.GD_SEL'.$newflg.'_'.$new_part};
1.125     ng       2762: 	if ($dropMenu eq 'excused') {
1.259     banghart 2763: 	    if ($record{'resource.'.$new_part.'.solved'} ne 'excused') {
                   2764: 		$newrecord{'resource.'.$new_part.'.solved'} = 'excused';
                   2765: 		if (exists($record{'resource.'.$new_part.'.awarded'})) {
                   2766: 		    $newrecord{'resource.'.$new_part.'.awarded'} = '';
1.58      albertel 2767: 		}
1.364     banghart 2768: 	        $newrecord{'resource.'.$new_part.'.regrader'}="$env{'user.name'}:$env{'user.domain'}";
1.58      albertel 2769: 	    }
1.125     ng       2770: 	} elsif ($dropMenu eq 'reset status'
1.259     banghart 2771: 		 && exists($record{'resource.'.$new_part.'.solved'})) { #don't bother if no old records -> no attempts
1.524     raeburn  2772: 	    foreach my $key (keys(%record)) {
1.259     banghart 2773: 		if ($key=~/^resource\.\Q$new_part\E\./) { $newrecord{$key} = ''; }
1.197     albertel 2774: 	    }
1.259     banghart 2775: 	    $newrecord{'resource.'.$new_part.'.regrader'}=
1.257     albertel 2776: 		"$env{'user.name'}:$env{'user.domain'}";
1.270     albertel 2777:             my $totaltries = $record{'resource.'.$part.'.tries'};
                   2778: 
                   2779:             my %last_resets = &get_last_resets($symb,$env{'request.course.id'},
                   2780: 					       [$new_part]);
                   2781:             my $aggtries =$totaltries;
1.269     raeburn  2782:             if ($last_resets{$new_part}) {
1.270     albertel 2783:                 $aggtries = &get_num_tries(\%record,$last_resets{$new_part},
                   2784: 					   $new_part);
1.269     raeburn  2785:             }
1.270     albertel 2786: 
                   2787:             my $solvedstatus = $record{'resource.'.$new_part.'.solved'};
1.269     raeburn  2788:             if ($aggtries > 0) {
1.327     albertel 2789:                 &decrement_aggs($symb,$new_part,\%aggregate,$aggtries,$totaltries,$solvedstatus);
1.269     raeburn  2790:                 $aggregateflag = 1;
                   2791:             }
1.125     ng       2792: 	} elsif ($dropMenu eq '') {
1.259     banghart 2793: 	    $pts = ($env{'form.GD_BOX'.$newflg.'_'.$new_part} ne '' ? 
                   2794: 		    $env{'form.GD_BOX'.$newflg.'_'.$new_part} : 
                   2795: 		    $env{'form.RADVAL'.$newflg.'_'.$new_part});
                   2796: 	    if ($pts eq '' && $env{'form.GD_SEL'.$newflg.'_'.$new_part} eq '') {
1.153     albertel 2797: 		next;
                   2798: 	    }
1.259     banghart 2799: 	    $wgt = $env{'form.WGT'.$newflg.'_'.$new_part} eq '' ? 1 : 
                   2800: 		$env{'form.WGT'.$newflg.'_'.$new_part};
1.41      ng       2801: 	    my $partial= $pts/$wgt;
1.259     banghart 2802: 	    if ($partial eq $record{'resource.'.$new_part.'.awarded'}) {
1.153     albertel 2803: 		#do not update score for part if not changed.
1.346     banghart 2804:                 &handback_files($request,$symb,$stuname,$domain,$newflg,$new_part,\%newrecord);
1.153     albertel 2805: 		next;
1.251     banghart 2806: 	    } else {
1.524     raeburn  2807: 	        push(@parts_graded,$new_part);
1.153     albertel 2808: 	    }
1.259     banghart 2809: 	    if ($record{'resource.'.$new_part.'.awarded'} ne $partial) {
                   2810: 		$newrecord{'resource.'.$new_part.'.awarded'}  = $partial;
1.153     albertel 2811: 	    }
1.259     banghart 2812: 	    my $reckey = 'resource.'.$new_part.'.solved';
1.41      ng       2813: 	    if ($partial == 0) {
1.153     albertel 2814: 		if ($record{$reckey} ne 'incorrect_by_override') {
                   2815: 		    $newrecord{$reckey} = 'incorrect_by_override';
                   2816: 		}
1.41      ng       2817: 	    } else {
1.153     albertel 2818: 		if ($record{$reckey} ne 'correct_by_override') {
                   2819: 		    $newrecord{$reckey} = 'correct_by_override';
                   2820: 		}
                   2821: 	    }	    
                   2822: 	    if ($submitter && 
1.259     banghart 2823: 		($record{'resource.'.$new_part.'.submitted_by'} ne $submitter)) {
                   2824: 		$newrecord{'resource.'.$new_part.'.submitted_by'} = $submitter;
1.41      ng       2825: 	    }
1.259     banghart 2826: 	    $newrecord{'resource.'.$new_part.'.regrader'}=
1.257     albertel 2827: 		"$env{'user.name'}:$env{'user.domain'}";
1.41      ng       2828: 	}
1.259     banghart 2829: 	# unless problem has been graded, set flag to version the submitted files
1.305     banghart 2830: 	unless ($record{'resource.'.$new_part.'.solved'} =~ /^correct_/  || 
                   2831: 	        $record{'resource.'.$new_part.'.solved'} eq 'incorrect_by_override' ||
                   2832: 	        $dropMenu eq 'reset status')
                   2833: 	   {
1.524     raeburn  2834: 	    push(@version_parts,$new_part);
1.259     banghart 2835: 	}
1.41      ng       2836:     }
1.301     albertel 2837:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   2838:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   2839: 
1.344     albertel 2840:     if (%newrecord) {
                   2841:         if (@version_parts) {
1.364     banghart 2842:             my @changed_keys = &version_portfiles(\%record, \@parts_graded, 
                   2843:                                 $env{'request.course.id'}, $symb, $domain, $stuname, \@version_parts);
1.344     albertel 2844: 	    @newrecord{@changed_keys} = @record{@changed_keys};
1.367     albertel 2845: 	    foreach my $new_part (@version_parts) {
                   2846: 		&handback_files($request,$symb,$stuname,$domain,$newflg,
                   2847: 				$new_part,\%newrecord);
                   2848: 	    }
1.259     banghart 2849:         }
1.44      ng       2850: 	&Apache::lonnet::cstore(\%newrecord,$symb,
1.257     albertel 2851: 				$env{'request.course.id'},$domain,$stuname);
1.380     albertel 2852: 	&check_and_remove_from_queue(\@parts,\%record,\%newrecord,$symb,
                   2853: 				     $cdom,$cnum,$domain,$stuname);
1.41      ng       2854:     }
1.269     raeburn  2855:     if ($aggregateflag) {
                   2856:         &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
1.301     albertel 2857: 			      $cdom,$cnum);
1.269     raeburn  2858:     }
1.301     albertel 2859:     return ('',$pts,$wgt);
1.36      ng       2860: }
1.322     albertel 2861: 
1.380     albertel 2862: sub check_and_remove_from_queue {
                   2863:     my ($parts,$record,$newrecord,$symb,$cdom,$cnum,$domain,$stuname) = @_;
                   2864:     my @ungraded_parts;
                   2865:     foreach my $part (@{$parts}) {
                   2866: 	if (    $record->{   'resource.'.$part.'.awarded'} eq ''
                   2867: 	     && $record->{   'resource.'.$part.'.solved' } ne 'excused'
                   2868: 	     && $newrecord->{'resource.'.$part.'.awarded'} eq ''
                   2869: 	     && $newrecord->{'resource.'.$part.'.solved' } ne 'excused'
                   2870: 		) {
                   2871: 	    push(@ungraded_parts, $part);
                   2872: 	}
                   2873:     }
                   2874:     if ( !@ungraded_parts ) {
                   2875: 	&Apache::bridgetask::remove_from_queue('gradingqueue',$symb,$cdom,
                   2876: 					       $cnum,$domain,$stuname);
                   2877:     }
                   2878: }
                   2879: 
1.337     banghart 2880: sub handback_files {
                   2881:     my ($request,$symb,$stuname,$domain,$newflg,$new_part,$newrecord) = @_;
1.517     raeburn  2882:     my $portfolio_root = '/userfiles/portfolio';
1.582     raeburn  2883:     my $res_error;
                   2884:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
                   2885:     if ($res_error) {
                   2886:         $request->print('<br />'.&navmap_errormsg().'<br />');
                   2887:         return;
                   2888:     }
1.375     albertel 2889:     my @part_response_id = &flatten_responseType($responseType);
                   2890:     foreach my $part_response_id (@part_response_id) {
                   2891:     	my ($part_id,$resp_id) = @{ $part_response_id };
                   2892: 	my $part_resp = join('_',@{ $part_response_id });
1.337     banghart 2893:             if (($env{'form.'.$newflg.'_'.$part_resp.'_returndoc1'}) && ($new_part == $part_id)) {
                   2894:                 # if multiple files are uploaded names will be 'returndoc2','returndoc3'
                   2895:                 my $file_counter = 1;
1.367     albertel 2896: 		my $file_msg;
1.337     banghart 2897:                 while ($env{'form.'.$newflg.'_'.$part_resp.'_returndoc'.$file_counter}) {
                   2898:                     my $fname=$env{'form.'.$newflg.'_'.$part_resp.'_returndoc'.$file_counter.'.filename'};
1.338     banghart 2899:                     my ($directory,$answer_file) = 
                   2900:                         ($env{'form.'.$newflg.'_'.$part_resp.'_origdoc'.$file_counter} =~ /^(.*?)([^\/]*)$/);
                   2901:                     my ($answer_name,$answer_ver,$answer_ext) =
                   2902: 		        &file_name_version_ext($answer_file);
1.355     banghart 2903: 		    my ($portfolio_path) = ($directory =~ /^.+$stuname\/portfolio(.*)/);
1.517     raeburn  2904:                     my $getpropath = 1;
                   2905: 		    my @dir_list = &Apache::lonnet::dirlist($portfolio_root.$portfolio_path,$domain,$stuname,$getpropath);
1.338     banghart 2906: 		    my $version = &get_next_version($answer_name, $answer_ext, \@dir_list);
1.355     banghart 2907:                     # fix file name
                   2908:                     my ($save_file_name) = (($directory.$answer_name.".$version.".$answer_ext) =~ /^.+\/${stuname}\/(.*)/);
                   2909:                     my $result=&Apache::lonnet::finishuserfileupload($stuname,$domain,
                   2910:             	                                $newflg.'_'.$part_resp.'_returndoc'.$file_counter,
                   2911:             	                                $save_file_name);
1.337     banghart 2912:                     if ($result !~ m|^/uploaded/|) {
1.536     raeburn  2913:                         $request->print('<br /><span class="LC_error">'.
                   2914:                             &mt('An error occurred ([_1]) while trying to upload [_2].',
                   2915:                                 $result,$newflg.'_'.$part_resp.'_returndoc'.$file_counter).
                   2916:                                         '</span>');
1.356     banghart 2917:                     } else {
1.360     banghart 2918:                         # mark the file as read only
                   2919:                         my @files = ($save_file_name);
1.372     albertel 2920:                         my @what = ($symb,$env{'request.course.id'},'handback');
1.360     banghart 2921:                         &Apache::lonnet::mark_as_readonly($domain,$stuname,\@files,\@what);
1.367     albertel 2922: 			if (exists($$newrecord{"resource.$new_part.$resp_id.handback"})) {
                   2923: 			    $$newrecord{"resource.$new_part.$resp_id.handback"}.=',';
                   2924: 			}
                   2925:                         $$newrecord{"resource.$new_part.$resp_id.handback"} .= $save_file_name;
                   2926: 			$file_msg.= "\n".'<br /><span class="LC_filename"><a href="/uploaded/'."$domain/$stuname/".$save_file_name.'">'.$save_file_name."</a></span><br />";
                   2927: 
1.337     banghart 2928:                     }
                   2929:                     $request->print("<br />".$fname." will be the uploaded file name");
1.354     albertel 2930:                     $request->print(" ".$env{'form.'.$newflg.'_'.$part_resp.'_origdoc'.$file_counter});
1.337     banghart 2931:                     $file_counter++;
                   2932:                 }
1.367     albertel 2933: 		my $subject = "File Handed Back by Instructor ";
                   2934: 		my $message = "A file has been returned that was originally submitted in reponse to: <br />";
                   2935: 		$message .= "<strong>".&Apache::lonnet::gettitle($symb)."</strong><br />";
                   2936: 		$message .= ' The returned file(s) are named: '. $file_msg;
                   2937: 		$message .= " and can be found in your portfolio space.";
1.418     albertel 2938: 		my ($feedurl,$showsymb) = 
                   2939: 		    &get_feedurl_and_symb($symb,$domain,$stuname);
1.386     raeburn  2940:                 my $restitle = &Apache::lonnet::gettitle($symb);
                   2941: 		my $msgstatus = 
                   2942:                    &Apache::lonmsg::user_normal_msg($stuname,$domain,$subject.
                   2943: 			 ' (File Returned) ['.$restitle.']',$message,undef,
1.418     albertel 2944:                          $feedurl,undef,undef,undef,$showsymb,$restitle);
1.337     banghart 2945:             }
                   2946:         }
1.338     banghart 2947:     return;
1.337     banghart 2948: }
                   2949: 
1.418     albertel 2950: sub get_feedurl_and_symb {
                   2951:     my ($symb,$uname,$udom) = @_;
                   2952:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
                   2953:     $url = &Apache::lonnet::clutter($url);
                   2954:     my $encrypturl=&Apache::lonnet::EXT('resource.0.encrypturl',
                   2955: 					$symb,$udom,$uname);
                   2956:     if ($encrypturl =~ /^yes$/i) {
                   2957: 	&Apache::lonenc::encrypted(\$url,1);
                   2958: 	&Apache::lonenc::encrypted(\$symb,1);
                   2959:     }
                   2960:     return ($url,$symb);
                   2961: }
                   2962: 
1.313     banghart 2963: sub get_submitted_files {
                   2964:     my ($udom,$uname,$partid,$respid,$record) = @_;
                   2965:     my @files;
                   2966:     if ($$record{"resource.$partid.$respid.portfiles"}) {
                   2967:         my $file_url = '/uploaded/'.$udom.'/'.$uname.'/portfolio';
                   2968:         foreach my $file (split(',',$$record{"resource.$partid.$respid.portfiles"})) {
                   2969:     	    push(@files,$file_url.$file);
                   2970:         }
                   2971:     }
                   2972:     if ($$record{"resource.$partid.$respid.uploadedurl"}) {
                   2973:         push(@files,$$record{"resource.$partid.$respid.uploadedurl"});
                   2974:     }
                   2975:     return (\@files);
                   2976: }
1.322     albertel 2977: 
1.269     raeburn  2978: # ----------- Provides number of tries since last reset.
                   2979: sub get_num_tries {
                   2980:     my ($record,$last_reset,$part) = @_;
                   2981:     my $timestamp = '';
                   2982:     my $num_tries = 0;
                   2983:     if ($$record{'version'}) {
                   2984:         for (my $version=$$record{'version'};$version>=1;$version--) {
                   2985:             if (exists($$record{$version.':resource.'.$part.'.solved'})) {
                   2986:                 $timestamp = $$record{$version.':timestamp'};
                   2987:                 if ($timestamp > $last_reset) {
                   2988:                     $num_tries ++;
                   2989:                 } else {
                   2990:                     last;
                   2991:                 }
                   2992:             }
                   2993:         }
                   2994:     }
                   2995:     return $num_tries;
                   2996: }
                   2997: 
                   2998: # ----------- Determine decrements required in aggregate totals 
                   2999: sub decrement_aggs {
                   3000:     my ($symb,$part,$aggregate,$aggtries,$totaltries,$solvedstatus) = @_;
                   3001:     my %decrement = (
                   3002:                         attempts => 0,
                   3003:                         users => 0,
                   3004:                         correct => 0
                   3005:                     );
                   3006:     $decrement{'attempts'} = $aggtries;
                   3007:     if ($solvedstatus =~ /^correct/) {
                   3008:         $decrement{'correct'} = 1;
                   3009:     }
                   3010:     if ($aggtries == $totaltries) {
                   3011:         $decrement{'users'} = 1;
                   3012:     }
1.524     raeburn  3013:     foreach my $type (keys(%decrement)) {
1.269     raeburn  3014:         $$aggregate{$symb."\0".$part."\0".$type} = -$decrement{$type};
                   3015:     }
                   3016:     return;
                   3017: }
                   3018: 
                   3019: # ----------- Determine timestamps for last reset of aggregate totals for parts  
                   3020: sub get_last_resets {
1.270     albertel 3021:     my ($symb,$courseid,$partids) =@_;
                   3022:     my %last_resets;
1.269     raeburn  3023:     my $cdom = $env{'course.'.$courseid.'.domain'};
                   3024:     my $cname = $env{'course.'.$courseid.'.num'};
1.271     albertel 3025:     my @keys;
                   3026:     foreach my $part (@{$partids}) {
                   3027: 	push(@keys,"$symb\0$part\0resettime");
                   3028:     }
                   3029:     my %results=&Apache::lonnet::get('nohist_resourcetracker',\@keys,
                   3030: 				     $cdom,$cname);
                   3031:     foreach my $part (@{$partids}) {
                   3032: 	$last_resets{$part}=$results{"$symb\0$part\0resettime"};
1.269     raeburn  3033:     }
1.270     albertel 3034:     return %last_resets;
1.269     raeburn  3035: }
                   3036: 
1.251     banghart 3037: # ----------- Handles creating versions for portfolio files as answers
                   3038: sub version_portfiles {
1.343     banghart 3039:     my ($record, $parts_graded, $courseid, $symb, $domain, $stu_name, $v_flag) = @_;
1.263     banghart 3040:     my $version_parts = join('|',@$v_flag);
1.343     banghart 3041:     my @returned_keys;
1.255     banghart 3042:     my $parts = join('|', @$parts_graded);
1.517     raeburn  3043:     my $portfolio_root = '/userfiles/portfolio';
1.277     albertel 3044:     foreach my $key (keys(%$record)) {
1.259     banghart 3045:         my $new_portfiles;
1.263     banghart 3046:         if ($key =~ /^resource\.($version_parts)\./ && $key =~ /\.portfiles$/ ) {
1.342     banghart 3047:             my @versioned_portfiles;
1.367     albertel 3048:             my @portfiles = split(/\s*,\s*/,$$record{$key});
1.252     banghart 3049:             foreach my $file (@portfiles) {
1.306     banghart 3050:                 &Apache::lonnet::unmark_as_readonly($domain,$stu_name,[$symb,$env{'request.course.id'}],$file);
1.304     albertel 3051:                 my ($directory,$answer_file) =($file =~ /^(.*?)([^\/]*)$/);
                   3052: 		my ($answer_name,$answer_ver,$answer_ext) =
                   3053: 		    &file_name_version_ext($answer_file);
1.517     raeburn  3054:                 my $getpropath = 1;    
                   3055:                 my @dir_list = &Apache::lonnet::dirlist($portfolio_root.$directory,$domain,$stu_name,$getpropath);
1.342     banghart 3056:                 my $version = &get_next_version($answer_name, $answer_ext, \@dir_list);
1.306     banghart 3057:                 my $new_answer = &version_selected_portfile($domain, $stu_name, $directory, $answer_file, $version);
                   3058:                 if ($new_answer ne 'problem getting file') {
1.342     banghart 3059:                     push(@versioned_portfiles, $directory.$new_answer);
1.306     banghart 3060:                     &Apache::lonnet::mark_as_readonly($domain,$stu_name,
1.367     albertel 3061:                         [$directory.$new_answer],
1.306     banghart 3062:                         [$symb,$env{'request.course.id'},'graded']);
1.259     banghart 3063:                 }
1.252     banghart 3064:             }
1.343     banghart 3065:             $$record{$key} = join(',',@versioned_portfiles);
                   3066:             push(@returned_keys,$key);
1.251     banghart 3067:         }
                   3068:     } 
1.343     banghart 3069:     return (@returned_keys);   
1.305     banghart 3070: }
                   3071: 
1.307     banghart 3072: sub get_next_version {
1.341     banghart 3073:     my ($answer_name, $answer_ext, $dir_list) = @_;
1.307     banghart 3074:     my $version;
                   3075:     foreach my $row (@$dir_list) {
                   3076:         my ($file) = split(/\&/,$row,2);
                   3077:         my ($file_name,$file_version,$file_ext) =
                   3078: 	    &file_name_version_ext($file);
                   3079:         if (($file_name eq $answer_name) && 
                   3080: 	    ($file_ext eq $answer_ext)) {
                   3081:                 # gets here if filename and extension match, regardless of version
                   3082:                 if ($file_version ne '') {
                   3083:                 # a versioned file is found  so save it for later
                   3084:                 if ($file_version > $version) {
                   3085: 		    $version = $file_version;
                   3086: 	        }
                   3087:             }
                   3088:         }
                   3089:     } 
                   3090:     $version ++;
                   3091:     return($version);
                   3092: }
                   3093: 
1.305     banghart 3094: sub version_selected_portfile {
1.306     banghart 3095:     my ($domain,$stu_name,$directory,$file_name,$version) = @_;
                   3096:     my ($answer_name,$answer_ver,$answer_ext) =
                   3097:         &file_name_version_ext($file_name);
                   3098:     my $new_answer;
                   3099:     $env{'form.copy'} = &Apache::lonnet::getfile("/uploaded/$domain/$stu_name/portfolio$directory$file_name");
                   3100:     if($env{'form.copy'} eq '-1') {
                   3101:         $new_answer = 'problem getting file';
                   3102:     } else {
                   3103:         $new_answer = $answer_name.'.'.$version.'.'.$answer_ext;
                   3104:         my $copy_result = &Apache::lonnet::finishuserfileupload(
                   3105:                             $stu_name,$domain,'copy',
                   3106: 		        '/portfolio'.$directory.$new_answer);
                   3107:     }    
                   3108:     return ($new_answer);
1.251     banghart 3109: }
                   3110: 
1.304     albertel 3111: sub file_name_version_ext {
                   3112:     my ($file)=@_;
                   3113:     my @file_parts = split(/\./, $file);
                   3114:     my ($name,$version,$ext);
                   3115:     if (@file_parts > 1) {
                   3116: 	$ext=pop(@file_parts);
                   3117: 	if (@file_parts > 1 && $file_parts[-1] =~ /^\d+$/) {
                   3118: 	    $version=pop(@file_parts);
                   3119: 	}
                   3120: 	$name=join('.',@file_parts);
                   3121:     } else {
                   3122: 	$name=join('.',@file_parts);
                   3123:     }
                   3124:     return($name,$version,$ext);
                   3125: }
                   3126: 
1.44      ng       3127: #--------------------------------------------------------------------------------------
                   3128: #
                   3129: #-------------------------- Next few routines handles grading by section or whole class
                   3130: #
                   3131: #--- Javascript to handle grading by section or whole class
1.42      ng       3132: sub viewgrades_js {
                   3133:     my ($request) = shift;
                   3134: 
1.539     riegler  3135:     my $alertmsg = &mt('A number equal or greater than 0 is expected. Entered value = ');
1.597     wenzelju 3136:     $request->print(&Apache::lonhtmlcommon::scripttag(<<VIEWJAVASCRIPT));
1.45      ng       3137:    function writePoint(partid,weight,point) {
1.125     ng       3138: 	var radioButton = document.classgrade["RADVAL_"+partid];
                   3139: 	var textbox = document.classgrade["TEXTVAL_"+partid];
1.42      ng       3140: 	if (point == "textval") {
1.125     ng       3141: 	    point = document.classgrade["TEXTVAL_"+partid].value;
1.109     matthew  3142: 	    if (isNaN(point) || parseFloat(point) < 0) {
1.539     riegler  3143: 		alert("$alertmsg"+parseFloat(point));
1.42      ng       3144: 		var resetbox = false;
                   3145: 		for (var i=0; i<radioButton.length; i++) {
                   3146: 		    if (radioButton[i].checked) {
                   3147: 			textbox.value = i;
                   3148: 			resetbox = true;
                   3149: 		    }
                   3150: 		}
                   3151: 		if (!resetbox) {
                   3152: 		    textbox.value = "";
                   3153: 		}
                   3154: 		return;
                   3155: 	    }
1.109     matthew  3156: 	    if (parseFloat(point) > parseFloat(weight)) {
                   3157: 		var resp = confirm("You entered a value ("+parseFloat(point)+
1.44      ng       3158: 				   ") greater than the weight for the part. Accept?");
                   3159: 		if (resp == false) {
                   3160: 		    textbox.value = "";
                   3161: 		    return;
                   3162: 		}
                   3163: 	    }
1.42      ng       3164: 	    for (var i=0; i<radioButton.length; i++) {
                   3165: 		radioButton[i].checked=false;
1.109     matthew  3166: 		if (parseFloat(point) == i) {
1.42      ng       3167: 		    radioButton[i].checked=true;
                   3168: 		}
                   3169: 	    }
1.41      ng       3170: 
1.42      ng       3171: 	} else {
1.125     ng       3172: 	    textbox.value = parseFloat(point);
1.42      ng       3173: 	}
1.41      ng       3174: 	for (i=0;i<document.classgrade.total.value;i++) {
1.125     ng       3175: 	    var user = document.classgrade["ctr"+i].value;
1.289     albertel 3176: 	    user = user.replace(new RegExp(':', 'g'),"_");
1.125     ng       3177: 	    var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
                   3178: 	    var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
                   3179: 	    var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
1.42      ng       3180: 	    if (saveval != "correct") {
                   3181: 		scorename.value = point;
1.43      ng       3182: 		if (selname[0].selected != true) {
                   3183: 		    selname[0].selected = true;
                   3184: 		}
1.42      ng       3185: 	    }
                   3186: 	}
1.125     ng       3187: 	document.classgrade["SELVAL_"+partid][0].selected = true;
1.42      ng       3188:     }
                   3189: 
                   3190:     function writeRadText(partid,weight) {
1.125     ng       3191: 	var selval   = document.classgrade["SELVAL_"+partid];
                   3192: 	var radioButton = document.classgrade["RADVAL_"+partid];
1.265     www      3193:         var override = document.classgrade["FORCE_"+partid].checked;
1.125     ng       3194: 	var textbox = document.classgrade["TEXTVAL_"+partid];
                   3195: 	if (selval[1].selected || selval[2].selected) {
1.42      ng       3196: 	    for (var i=0; i<radioButton.length; i++) {
                   3197: 		radioButton[i].checked=false;
                   3198: 
                   3199: 	    }
                   3200: 	    textbox.value = "";
                   3201: 
                   3202: 	    for (i=0;i<document.classgrade.total.value;i++) {
1.125     ng       3203: 		var user = document.classgrade["ctr"+i].value;
1.289     albertel 3204: 		user = user.replace(new RegExp(':', 'g'),"_");
1.125     ng       3205: 		var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
                   3206: 		var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
                   3207: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
1.265     www      3208: 		if ((saveval != "correct") || override) {
1.42      ng       3209: 		    scorename.value = "";
1.125     ng       3210: 		    if (selval[1].selected) {
                   3211: 			selname[1].selected = true;
                   3212: 		    } else {
                   3213: 			selname[2].selected = true;
                   3214: 			if (Number(document.classgrade["GD_"+user+"_"+partid+"_tries"].value)) 
                   3215: 			{document.classgrade["GD_"+user+"_"+partid+"_tries"].value = '0';}
                   3216: 		    }
1.42      ng       3217: 		}
                   3218: 	    }
1.43      ng       3219: 	} else {
                   3220: 	    for (i=0;i<document.classgrade.total.value;i++) {
1.125     ng       3221: 		var user = document.classgrade["ctr"+i].value;
1.289     albertel 3222: 		user = user.replace(new RegExp(':', 'g'),"_");
1.125     ng       3223: 		var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
                   3224: 		var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
                   3225: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
1.265     www      3226: 		if ((saveval != "correct") || override) {
1.125     ng       3227: 		    scorename.value = document.classgrade["GD_"+user+"_"+partid+"_awarded_s"].value;
1.43      ng       3228: 		    selname[0].selected = true;
                   3229: 		}
                   3230: 	    }
                   3231: 	}	    
1.42      ng       3232:     }
                   3233: 
                   3234:     function changeSelect(partid,user) {
1.125     ng       3235: 	var selval = document.classgrade["GD_"+user+'_'+partid+"_solved"];
                   3236: 	var textbox = document.classgrade["GD_"+user+'_'+partid+"_awarded"];
1.44      ng       3237: 	var point  = textbox.value;
1.125     ng       3238: 	var weight = document.classgrade["weight_"+partid].value;
1.44      ng       3239: 
1.109     matthew  3240: 	if (isNaN(point) || parseFloat(point) < 0) {
1.539     riegler  3241: 	    alert("$alertmsg"+parseFloat(point));
1.44      ng       3242: 	    textbox.value = "";
                   3243: 	    return;
                   3244: 	}
1.109     matthew  3245: 	if (parseFloat(point) > parseFloat(weight)) {
                   3246: 	    var resp = confirm("You entered a value ("+parseFloat(point)+
1.44      ng       3247: 			       ") greater than the weight of the part. Accept?");
                   3248: 	    if (resp == false) {
                   3249: 		textbox.value = "";
                   3250: 		return;
                   3251: 	    }
                   3252: 	}
1.42      ng       3253: 	selval[0].selected = true;
                   3254:     }
                   3255: 
                   3256:     function changeOneScore(partid,user) {
1.125     ng       3257: 	var selval = document.classgrade["GD_"+user+'_'+partid+"_solved"];
                   3258: 	if (selval[1].selected || selval[2].selected) {
                   3259: 	    document.classgrade["GD_"+user+'_'+partid+"_awarded"].value = "";
                   3260: 	    if (selval[2].selected) {
                   3261: 		document.classgrade["GD_"+user+'_'+partid+"_tries"].value = "0";
                   3262: 	    }
1.269     raeburn  3263:         }
1.42      ng       3264:     }
                   3265: 
                   3266:     function resetEntry(numpart) {
                   3267: 	for (ctpart=0;ctpart<numpart;ctpart++) {
1.125     ng       3268: 	    var partid = document.classgrade["partid_"+ctpart].value;
                   3269: 	    var radioButton = document.classgrade["RADVAL_"+partid];
                   3270: 	    var textbox = document.classgrade["TEXTVAL_"+partid];
                   3271: 	    var selval  = document.classgrade["SELVAL_"+partid];
1.42      ng       3272: 	    for (var i=0; i<radioButton.length; i++) {
                   3273: 		radioButton[i].checked=false;
                   3274: 
                   3275: 	    }
                   3276: 	    textbox.value = "";
                   3277: 	    selval[0].selected = true;
                   3278: 
                   3279: 	    for (i=0;i<document.classgrade.total.value;i++) {
1.125     ng       3280: 		var user = document.classgrade["ctr"+i].value;
1.289     albertel 3281: 		user = user.replace(new RegExp(':', 'g'),"_");
1.125     ng       3282: 		var resetscore = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
                   3283: 		resetscore.value = document.classgrade["GD_"+user+"_"+partid+"_awarded_s"].value;
                   3284: 		var resettries = document.classgrade["GD_"+user+"_"+partid+"_tries"];
                   3285: 		resettries.value = document.classgrade["GD_"+user+"_"+partid+"_tries_s"].value;
                   3286: 		var saveselval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
                   3287: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
1.42      ng       3288: 		if (saveselval == "excused") {
1.43      ng       3289: 		    if (selname[1].selected == false) { selname[1].selected = true;}
1.42      ng       3290: 		} else {
1.43      ng       3291: 		    if (selname[0].selected == false) {selname[0].selected = true};
1.42      ng       3292: 		}
                   3293: 	    }
1.41      ng       3294: 	}
1.42      ng       3295:     }
                   3296: 
1.41      ng       3297: VIEWJAVASCRIPT
1.42      ng       3298: }
                   3299: 
1.44      ng       3300: #--- show scores for a section or whole class w/ option to change/update a score
1.42      ng       3301: sub viewgrades {
                   3302:     my ($request) = shift;
                   3303:     &viewgrades_js($request);
1.41      ng       3304: 
1.324     albertel 3305:     my ($symb) = &get_symb($request);
1.168     albertel 3306:     #need to make sure we have the correct data for later EXT calls, 
                   3307:     #thus invalidate the cache
                   3308:     &Apache::lonnet::devalidatecourseresdata(
1.257     albertel 3309:                  $env{'course.'.$env{'request.course.id'}.'.num'},
                   3310:                  $env{'course.'.$env{'request.course.id'}.'.domain'});
1.168     albertel 3311:     &Apache::lonnet::clear_EXT_cache_status();
                   3312: 
1.398     albertel 3313:     my $result='<h3><span class="LC_info">'.&mt('Manual Grading').'</span></h3>';
1.485     albertel 3314:     $result.='<h4>'.&mt('<b>Current Resource: </b>[_1]',$env{'form.probTitle'}).'</h4>'."\n";
1.41      ng       3315: 
                   3316:     #view individual student submission form - called using Javascript viewOneStudent
1.324     albertel 3317:     $result.=&jscriptNform($symb);
1.41      ng       3318: 
1.44      ng       3319:     #beginning of class grading form
1.442     banghart 3320:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
1.41      ng       3321:     $result.= '<form action="/adm/grades" method="post" name="classgrade">'."\n".
1.418     albertel 3322: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.38      ng       3323: 	'<input type="hidden" name="command" value="editgrades" />'."\n".
1.432     banghart 3324: 	&build_section_inputs().
1.257     albertel 3325: 	'<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n".
1.442     banghart 3326: 	'<input type="hidden" name="Status" value="'.$env{'stu_status'}.'" />'."\n".
1.257     albertel 3327: 	'<input type="hidden" name="probTitle" value="'.$env{'form.probTitle'}.'" />'."\n";
1.72      ng       3328: 
1.560     raeburn  3329:     my ($common_header,$specific_header);
1.257     albertel 3330:     if ($env{'form.section'} eq 'all') {
1.560     raeburn  3331: 	$common_header = &mt('Assign Common Grade to Class');
                   3332:         $specific_header = &mt('Assign Grade to Specific Students in Class');
1.257     albertel 3333:     } elsif ($env{'form.section'} eq 'none') {
1.560     raeburn  3334:         $common_header = &mt('Assign Common Grade to Students in no Section');
                   3335: 	$specific_header = &mt('Assign Grade to Specific Students in no Section');
1.52      albertel 3336:     } else {
1.560     raeburn  3337:         my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
                   3338:         $common_header = &mt('Assign Common Grade to Students in Section(s) [_1]',$section_display);
                   3339: 	$specific_header = &mt('Assign Grade to Specific Students in Section(s) [_1]',$section_display);
1.52      albertel 3340:     }
1.560     raeburn  3341:     $result.= '<h3>'.$common_header.'</h3>'.&Apache::loncommon::start_data_table();
1.44      ng       3342:     #radio buttons/text box for assigning points for a section or class.
                   3343:     #handles different parts of a problem
1.582     raeburn  3344:     my $res_error;
                   3345:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
                   3346:     if ($res_error) {
                   3347:         return &navmap_errormsg();
                   3348:     }
1.42      ng       3349:     my %weight = ();
                   3350:     my $ctsparts = 0;
1.45      ng       3351:     my %seen = ();
1.375     albertel 3352:     my @part_response_id = &flatten_responseType($responseType);
                   3353:     foreach my $part_response_id (@part_response_id) {
                   3354:     	my ($partid,$respid) = @{ $part_response_id };
                   3355: 	my $part_resp = join('_',@{ $part_response_id });
1.45      ng       3356: 	next if $seen{$partid};
                   3357: 	$seen{$partid}++;
1.375     albertel 3358: 	my $handgrade=$$handgrade{$part_resp};
1.42      ng       3359: 	my $wgt = &Apache::lonnet::EXT('resource.'.$partid.'.weight',$symb);
                   3360: 	$weight{$partid} = $wgt eq '' ? '1' : $wgt;
                   3361: 
1.324     albertel 3362: 	my $display_part=&get_display_part($partid,$symb);
1.485     albertel 3363: 	my $radio.='<table border="0"><tr>';  
1.41      ng       3364: 	my $ctr = 0;
1.42      ng       3365: 	while ($ctr<=$weight{$partid}) { # display radio buttons in a nice table 10 across
1.485     albertel 3366: 	    $radio.= '<td><label><input type="radio" name="RADVAL_'.$partid.'" '.
1.54      albertel 3367: 		'onclick="javascript:writePoint(\''.$partid.'\','.$weight{$partid}.
1.288     albertel 3368: 		','.$ctr.')" />'.$ctr."</label></td>\n";
1.41      ng       3369: 	    $result.=(($ctr+1)%10 == 0 ? '</tr><tr>' : '');
                   3370: 	    $ctr++;
                   3371: 	}
1.485     albertel 3372: 	$radio.='</tr></table>';
                   3373: 	my $line = '<input type="text" name="TEXTVAL_'.
1.589     bisitz   3374: 	    $partid.'" size="4" '.'onchange="javascript:writePoint(\''.
1.54      albertel 3375: 		$partid.'\','.$weight{$partid}.',\'textval\')" /> /'.
1.539     riegler  3376: 	    $weight{$partid}.' '.&mt('(problem weight)').'</td>'."\n";
                   3377: 	$line.= '<td><b>'.&mt('Grade Status').':</b><select name="SELVAL_'.$partid.'"'.
1.589     bisitz   3378: 	    'onchange="javascript:writeRadText(\''.$partid.'\','.
1.59      albertel 3379: 		$weight{$partid}.')"> '.
1.401     albertel 3380: 	    '<option selected="selected"> </option>'.
1.485     albertel 3381: 	    '<option value="excused">'.&mt('excused').'</option>'.
                   3382: 	    '<option value="reset status">'.&mt('reset status').'</option>'.
                   3383: 	    '</select></td>'.
                   3384:             '<td><label><input type="checkbox" name="FORCE_'.$partid.'" />'.&mt('Override "Correct"').'</label>';
                   3385: 	$line.='<input type="hidden" name="partid_'.
                   3386: 	    $ctsparts.'" value="'.$partid.'" />'."\n";
                   3387: 	$line.='<input type="hidden" name="weight_'.
                   3388: 	    $partid.'" value="'.$weight{$partid}.'" />'."\n";
                   3389: 
                   3390: 	$result.=
                   3391: 	    &Apache::loncommon::start_data_table_row()."\n".
1.577     bisitz   3392: 	    '<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 3393: 	    &Apache::loncommon::end_data_table_row()."\n";
1.42      ng       3394: 	$ctsparts++;
1.41      ng       3395:     }
1.474     albertel 3396:     $result.=&Apache::loncommon::end_data_table()."\n".
1.52      albertel 3397: 	'<input type="hidden" name="totalparts" value="'.$ctsparts.'" />';
1.485     albertel 3398:     $result.='<input type="button" value="'.&mt('Revert to Default').'" '.
1.589     bisitz   3399: 	'onclick="javascript:resetEntry('.$ctsparts.');" />';
1.41      ng       3400: 
1.44      ng       3401:     #table listing all the students in a section/class
                   3402:     #header of table
1.560     raeburn  3403:     $result.= '<h3>'.$specific_header.'</h3>'.
                   3404:               &Apache::loncommon::start_data_table().
                   3405: 	      &Apache::loncommon::start_data_table_header_row().
                   3406: 	      '<th>'.&mt('No.').'</th>'.
                   3407: 	      '<th>'.&nameUserString('header')."</th>\n";
1.582     raeburn  3408:     my $partserror;
                   3409:     my (@parts) = sort(&getpartlist($symb,\$partserror));
                   3410:     if ($partserror) {
                   3411:         return &navmap_errormsg();
                   3412:     }
1.324     albertel 3413:     my (undef,undef,$url)=&Apache::lonnet::decode_symb($symb);
1.269     raeburn  3414:     my @partids = ();
1.41      ng       3415:     foreach my $part (@parts) {
                   3416: 	my $display=&Apache::lonnet::metadata($url,$part.'.display');
1.539     riegler  3417:         my $narrowtext = &mt('Tries');
                   3418: 	$display =~ s|^Number of Attempts|$narrowtext <br />|; # makes the column narrower
1.41      ng       3419: 	if  (!$display) { $display = &Apache::lonnet::metadata($url,$part.'.name'); }
1.207     albertel 3420: 	my ($partid) = &split_part_type($part);
1.524     raeburn  3421:         push(@partids,$partid);
1.324     albertel 3422: 	my $display_part=&get_display_part($partid,$symb);
1.41      ng       3423: 	if ($display =~ /^Partial Credit Factor/) {
1.485     albertel 3424: 	    $result.='<th>'.
                   3425: 		&mt('Score Part: [_1]<br /> (weight = [_2])',
                   3426: 		    $display_part,$weight{$partid}).'</th>'."\n";
1.41      ng       3427: 	    next;
1.485     albertel 3428: 	    
1.207     albertel 3429: 	} else {
1.485     albertel 3430: 	    if ($display =~ /Problem Status/) {
                   3431: 		my $grade_status_mt = &mt('Grade Status');
                   3432: 		$display =~ s{Problem Status}{$grade_status_mt<br />};
                   3433: 	    }
                   3434: 	    my $part_mt = &mt('Part:');
                   3435: 	    $display =~s{\[Part: \Q$partid\E\]}{$part_mt $display_part};
1.41      ng       3436: 	}
1.485     albertel 3437: 
1.474     albertel 3438: 	$result.='<th>'.$display.'</th>'."\n";
1.41      ng       3439:     }
1.474     albertel 3440:     $result.=&Apache::loncommon::end_data_table_header_row();
1.44      ng       3441: 
1.270     albertel 3442:     my %last_resets = 
                   3443: 	&get_last_resets($symb,$env{'request.course.id'},\@partids);
1.269     raeburn  3444: 
1.41      ng       3445:     #get info for each student
1.44      ng       3446:     #list all the students - with points and grade status
1.257     albertel 3447:     my (undef,undef,$fullname) = &getclasslist($env{'form.section'},'1');
1.41      ng       3448:     my $ctr = 0;
1.294     albertel 3449:     foreach (sort 
                   3450: 	     {
                   3451: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                   3452: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                   3453: 		 }
                   3454: 		 return $a cmp $b;
                   3455: 	     } (keys(%$fullname))) {
1.126     ng       3456: 	$ctr++;
1.324     albertel 3457: 	$result.=&viewstudentgrade($symb,$env{'request.course.id'},
1.269     raeburn  3458: 				   $_,$$fullname{$_},\@parts,\%weight,$ctr,\%last_resets);
1.41      ng       3459:     }
1.474     albertel 3460:     $result.=&Apache::loncommon::end_data_table();
1.41      ng       3461:     $result.='<input type="hidden" name="total" value="'.$ctr.'" />'."\n";
1.485     albertel 3462:     $result.='<input type="button" value="'.&mt('Save').'" '.
1.589     bisitz   3463: 	'onclick="javascript:submit();" target="_self" /></form>'."\n";
1.96      albertel 3464:     if (scalar(%$fullname) eq 0) {
                   3465: 	my $colspan=3+scalar(@parts);
1.433     banghart 3466: 	my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
1.442     banghart 3467:         my $stu_status = join(' or ',&Apache::loncommon::get_env_multiple('form.Status'));
1.433     banghart 3468: 	$result='<span class="LC_warning">'.
1.485     albertel 3469: 	    &mt('There are no students in section(s) [_1] with enrollment status [_2] to modify or grade.',
1.442     banghart 3470: 	        $section_display, $stu_status).
1.433     banghart 3471: 	    '</span>';
1.96      albertel 3472:     }
1.324     albertel 3473:     $result.=&show_grading_menu_form($symb);
1.41      ng       3474:     return $result;
                   3475: }
                   3476: 
1.44      ng       3477: #--- call by previous routine to display each student
1.41      ng       3478: sub viewstudentgrade {
1.324     albertel 3479:     my ($symb,$courseid,$student,$fullname,$parts,$weight,$ctr,$last_resets) = @_;
1.44      ng       3480:     my ($uname,$udom) = split(/:/,$student);
                   3481:     my %record=&Apache::lonnet::restore($symb,$courseid,$udom,$uname);
1.269     raeburn  3482:     my %aggregates = (); 
1.474     albertel 3483:     my $result=&Apache::loncommon::start_data_table_row().'<td align="right">'.
1.233     albertel 3484: 	'<input type="hidden" name="ctr'.($ctr-1).'" value="'.$student.'" />'.
                   3485: 	"\n".$ctr.'&nbsp;</td><td>&nbsp;'.
1.44      ng       3486: 	'<a href="javascript:viewOneStudent(\''.$uname.'\',\''.$udom.
1.417     albertel 3487: 	'\');" target="_self">'.$fullname.'</a> '.
1.398     albertel 3488: 	'<span class="LC_internal_info">('.$uname.($env{'user.domain'} eq $udom ? '' : ':'.$udom).')</span></td>'."\n";
1.281     albertel 3489:     $student=~s/:/_/; # colon doen't work in javascript for names
1.63      albertel 3490:     foreach my $apart (@$parts) {
                   3491: 	my ($part,$type) = &split_part_type($apart);
1.41      ng       3492: 	my $score=$record{"resource.$part.$type"};
1.276     albertel 3493:         $result.='<td align="center">';
1.269     raeburn  3494:         my ($aggtries,$totaltries);
                   3495:         unless (exists($aggregates{$part})) {
1.270     albertel 3496: 	    $totaltries = $record{'resource.'.$part.'.tries'};
                   3497: 
                   3498: 	    $aggtries = $totaltries;
1.269     raeburn  3499:             if ($$last_resets{$part}) {  
1.270     albertel 3500:                 $aggtries = &get_num_tries(\%record,$$last_resets{$part},
                   3501: 					   $part);
                   3502:             }
1.269     raeburn  3503:             $result.='<input type="hidden" name="'.
                   3504:                 'GD_'.$student.'_'.$part.'_aggtries" value="'.$aggtries.'" />'."\n";
                   3505:             $result.='<input type="hidden" name="'.
                   3506:                 'GD_'.$student.'_'.$part.'_totaltries" value="'.$totaltries.'" />'."\n";
                   3507:             $aggregates{$part} = 1;
                   3508:         }
1.41      ng       3509: 	if ($type eq 'awarded') {
1.320     albertel 3510: 	    my $pts = $score eq '' ? '' : &compute_points($score,$$weight{$part});
1.42      ng       3511: 	    $result.='<input type="hidden" name="'.
1.89      albertel 3512: 		'GD_'.$student.'_'.$part.'_awarded_s" value="'.$pts.'" />'."\n";
1.233     albertel 3513: 	    $result.='<input type="text" name="'.
1.89      albertel 3514: 		'GD_'.$student.'_'.$part.'_awarded" '.
1.589     bisitz   3515:                 'onchange="javascript:changeSelect(\''.$part.'\',\''.$student.
1.44      ng       3516: 		'\')" value="'.$pts.'" size="4" /></td>'."\n";
1.41      ng       3517: 	} elsif ($type eq 'solved') {
                   3518: 	    my ($status,$foo)=split(/_/,$score,2);
                   3519: 	    $status = 'nothing' if ($status eq '');
1.89      albertel 3520: 	    $result.='<input type="hidden" name="'.'GD_'.$student.'_'.
1.54      albertel 3521: 		$part.'_solved_s" value="'.$status.'" />'."\n";
1.233     albertel 3522: 	    $result.='&nbsp;<select name="'.
1.89      albertel 3523: 		'GD_'.$student.'_'.$part.'_solved" '.
1.589     bisitz   3524:                 'onchange="javascript:changeOneScore(\''.$part.'\',\''.$student.'\')" >'."\n";
1.485     albertel 3525: 	    $result.= (($status eq 'excused') ? '<option> </option><option selected="selected" value="excused">'.&mt('excused').'</option>' 
                   3526: 		: '<option selected="selected"> </option><option value="excused">'.&mt('excused').'</option>')."\n";
                   3527: 	    $result.='<option value="reset status">'.&mt('reset status').'</option>';
1.126     ng       3528: 	    $result.="</select>&nbsp;</td>\n";
1.122     ng       3529: 	} else {
                   3530: 	    $result.='<input type="hidden" name="'.
                   3531: 		'GD_'.$student.'_'.$part.'_'.$type.'_s" value="'.$score.'" />'.
                   3532: 		    "\n";
1.233     albertel 3533: 	    $result.='<input type="text" name="'.
1.122     ng       3534: 		'GD_'.$student.'_'.$part.'_'.$type.'" '.
                   3535: 		'value="'.$score.'" size="4" /></td>'."\n";
1.41      ng       3536: 	}
                   3537:     }
1.474     albertel 3538:     $result.=&Apache::loncommon::end_data_table_row();
1.41      ng       3539:     return $result;
1.38      ng       3540: }
                   3541: 
1.44      ng       3542: #--- change scores for all the students in a section/class
                   3543: #    record does not get update if unchanged
1.38      ng       3544: sub editgrades {
1.41      ng       3545:     my ($request) = @_;
                   3546: 
1.324     albertel 3547:     my $symb=&get_symb($request);
1.433     banghart 3548:     my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
1.477     albertel 3549:     my $title='<h2>'.&mt('Current Grade Status').'</h2>';
                   3550:     $title.='<h4>'.&mt('<b>Current Resource: </b>[_1]',$env{'form.probTitle'}).'</h4>'."\n";
1.433     banghart 3551:     $title.='<h4>'.&mt('<b>Section: </b>[_1]',$section_display).'</h4>'."\n";
1.126     ng       3552: 
1.477     albertel 3553:     my $result= &Apache::loncommon::start_data_table().
                   3554: 	&Apache::loncommon::start_data_table_header_row().
                   3555: 	'<th rowspan="2" valign="middle">'.&mt('No.').'</th>'.
                   3556: 	'<th rowspan="2" valign="middle">'.&nameUserString('header')."</th>\n";
1.43      ng       3557:     my %scoreptr = (
                   3558: 		    'correct'  =>'correct_by_override',
                   3559: 		    'incorrect'=>'incorrect_by_override',
                   3560: 		    'excused'  =>'excused',
                   3561: 		    'ungraded' =>'ungraded_attempted',
1.596     raeburn  3562:                     'credited' =>'credit_attempted',
1.43      ng       3563: 		    'nothing'  => '',
                   3564: 		    );
1.257     albertel 3565:     my ($classlist,undef,$fullname) = &getclasslist($env{'form.section'},'0');
1.34      ng       3566: 
1.44      ng       3567:     my (@partid);
                   3568:     my %weight = ();
1.54      albertel 3569:     my %columns = ();
1.44      ng       3570:     my ($i,$ctr,$count,$rec_update) = (0,0,0,0);
1.54      albertel 3571: 
1.582     raeburn  3572:     my $partserror;
                   3573:     my (@parts) = sort(&getpartlist($symb,\$partserror));
                   3574:     if ($partserror) {
                   3575:         return &navmap_errormsg();
                   3576:     }
1.54      albertel 3577:     my $header;
1.257     albertel 3578:     while ($ctr < $env{'form.totalparts'}) {
                   3579: 	my $partid = $env{'form.partid_'.$ctr};
1.524     raeburn  3580: 	push(@partid,$partid);
1.257     albertel 3581: 	$weight{$partid} = $env{'form.weight_'.$partid};
1.44      ng       3582: 	$ctr++;
1.54      albertel 3583:     }
1.324     albertel 3584:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
1.54      albertel 3585:     foreach my $partid (@partid) {
1.478     albertel 3586: 	$header .= '<th align="center">'.&mt('Old Score').'</th>'.
                   3587: 	    '<th align="center">'.&mt('New Score').'</th>';
1.54      albertel 3588: 	$columns{$partid}=2;
                   3589: 	foreach my $stores (@parts) {
                   3590: 	    my ($part,$type) = &split_part_type($stores);
                   3591: 	    if ($part !~ m/^\Q$partid\E/) { next;}
                   3592: 	    if ($type eq 'awarded' || $type eq 'solved') { next; }
                   3593: 	    my $display=&Apache::lonnet::metadata($url,$stores.'.display');
1.551     raeburn  3594: 	    $display =~ s/\[Part: \Q$part\E\]//;
1.539     riegler  3595:             my $narrowtext = &mt('Tries');
                   3596: 	    $display =~ s/Number of Attempts/$narrowtext/;
                   3597: 	    $header .= '<th align="center">'.&mt('Old').' '.$display.'</th>'.
                   3598: 		'<th align="center">'.&mt('New').' '.$display.'</th>';
1.54      albertel 3599: 	    $columns{$partid}+=2;
                   3600: 	}
                   3601:     }
                   3602:     foreach my $partid (@partid) {
1.324     albertel 3603: 	my $display_part=&get_display_part($partid,$symb);
1.478     albertel 3604: 	$result .= '<th colspan="'.$columns{$partid}.'" align="center">'.
                   3605: 	    &mt('Part: [_1] (Weight = [_2])',$display_part,$weight{$partid}).
                   3606: 	    '</th>';
1.54      albertel 3607: 
1.44      ng       3608:     }
1.477     albertel 3609:     $result .= &Apache::loncommon::end_data_table_header_row().
                   3610: 	&Apache::loncommon::start_data_table_header_row().
                   3611: 	$header.
                   3612: 	&Apache::loncommon::end_data_table_header_row();
                   3613:     my @noupdate;
1.126     ng       3614:     my ($updateCtr,$noupdateCtr) = (1,1);
1.257     albertel 3615:     for ($i=0; $i<$env{'form.total'}; $i++) {
1.93      albertel 3616: 	my $line;
1.257     albertel 3617: 	my $user = $env{'form.ctr'.$i};
1.281     albertel 3618: 	my ($uname,$udom)=split(/:/,$user);
1.44      ng       3619: 	my %newrecord;
                   3620: 	my $updateflag = 0;
1.281     albertel 3621: 	$line .= '<td>'.&nameUserString(undef,$$fullname{$user},$uname,$udom).'</td>';
1.108     albertel 3622: 	my $usec=$classlist->{"$uname:$udom"}[5];
1.105     albertel 3623: 	if (!&canmodify($usec)) {
1.126     ng       3624: 	    my $numcols=scalar(@partid)*4+2;
1.477     albertel 3625: 	    push(@noupdate,
1.478     albertel 3626: 		 $line."<td colspan=\"$numcols\"><span class=\"LC_warning\">".
                   3627: 		 &mt('Not allowed to modify student')."</span></td></tr>");
1.105     albertel 3628: 	    next;
                   3629: 	}
1.269     raeburn  3630:         my %aggregate = ();
                   3631:         my $aggregateflag = 0;
1.281     albertel 3632: 	$user=~s/:/_/; # colon doen't work in javascript for names
1.44      ng       3633: 	foreach (@partid) {
1.257     albertel 3634: 	    my $old_aw    = $env{'form.GD_'.$user.'_'.$_.'_awarded_s'};
1.54      albertel 3635: 	    my $old_part_pcr = $old_aw/($weight{$_} ne '0' ? $weight{$_}:1);
                   3636: 	    my $old_part  = $old_aw eq '' ? '' : $old_part_pcr;
1.257     albertel 3637: 	    my $old_score = $scoreptr{$env{'form.GD_'.$user.'_'.$_.'_solved_s'}};
                   3638: 	    my $awarded   = $env{'form.GD_'.$user.'_'.$_.'_awarded'};
1.54      albertel 3639: 	    my $pcr       = $awarded/($weight{$_} ne '0' ? $weight{$_} : 1);
                   3640: 	    my $partial   = $awarded eq '' ? '' : $pcr;
1.44      ng       3641: 	    my $score;
                   3642: 	    if ($partial eq '') {
1.257     albertel 3643: 		$score = $scoreptr{$env{'form.GD_'.$user.'_'.$_.'_solved_s'}};
1.44      ng       3644: 	    } elsif ($partial > 0) {
                   3645: 		$score = 'correct_by_override';
                   3646: 	    } elsif ($partial == 0) {
                   3647: 		$score = 'incorrect_by_override';
                   3648: 	    }
1.257     albertel 3649: 	    my $dropMenu = $env{'form.GD_'.$user.'_'.$_.'_solved'};
1.125     ng       3650: 	    $score = 'excused' if (($dropMenu eq 'excused') && ($score ne 'excused'));
                   3651: 
1.292     albertel 3652: 	    $newrecord{'resource.'.$_.'.regrader'}=
                   3653: 		"$env{'user.name'}:$env{'user.domain'}";
1.125     ng       3654: 	    if ($dropMenu eq 'reset status' &&
                   3655: 		$old_score ne '') { # ignore if no previous attempts => nothing to reset
1.299     albertel 3656: 		$newrecord{'resource.'.$_.'.tries'} = '';
1.125     ng       3657: 		$newrecord{'resource.'.$_.'.solved'} = '';
                   3658: 		$newrecord{'resource.'.$_.'.award'} = '';
1.299     albertel 3659: 		$newrecord{'resource.'.$_.'.awarded'} = '';
1.125     ng       3660: 		$updateflag = 1;
1.269     raeburn  3661:                 if ($env{'form.GD_'.$user.'_'.$_.'_aggtries'} > 0) {
                   3662:                     my $aggtries = $env{'form.GD_'.$user.'_'.$_.'_aggtries'};
                   3663:                     my $totaltries = $env{'form.GD_'.$user.'_'.$_.'_totaltries'};
                   3664:                     my $solvedstatus = $env{'form.GD_'.$user.'_'.$_.'_solved_s'};
                   3665:                     &decrement_aggs($symb,$_,\%aggregate,$aggtries,$totaltries,$solvedstatus);
                   3666:                     $aggregateflag = 1;
                   3667:                 }
1.139     albertel 3668: 	    } elsif (!($old_part eq $partial && $old_score eq $score)) {
                   3669: 		$updateflag = 1;
                   3670: 		$newrecord{'resource.'.$_.'.awarded'}  = $partial if $partial ne '';
                   3671: 		$newrecord{'resource.'.$_.'.solved'}   = $score;
                   3672: 		$rec_update++;
1.125     ng       3673: 	    }
                   3674: 
1.93      albertel 3675: 	    $line .= '<td align="center">'.$old_aw.'&nbsp;</td>'.
1.44      ng       3676: 		'<td align="center">'.$awarded.
                   3677: 		($score eq 'excused' ? $score : '').'&nbsp;</td>';
1.5       albertel 3678: 
1.54      albertel 3679: 
                   3680: 	    my $partid=$_;
                   3681: 	    foreach my $stores (@parts) {
                   3682: 		my ($part,$type) = &split_part_type($stores);
                   3683: 		if ($part !~ m/^\Q$partid\E/) { next;}
                   3684: 		if ($type eq 'awarded' || $type eq 'solved') { next; }
1.257     albertel 3685: 		my $old_aw    = $env{'form.GD_'.$user.'_'.$part.'_'.$type.'_s'};
                   3686: 		my $awarded   = $env{'form.GD_'.$user.'_'.$part.'_'.$type};
1.54      albertel 3687: 		if ($awarded ne '' && $awarded ne $old_aw) {
                   3688: 		    $newrecord{'resource.'.$part.'.'.$type}= $awarded;
1.257     albertel 3689: 		    $newrecord{'resource.'.$part.'.regrader'}="$env{'user.name'}:$env{'user.domain'}";
1.54      albertel 3690: 		    $updateflag=1;
                   3691: 		}
1.93      albertel 3692: 		$line .= '<td align="center">'.$old_aw.'&nbsp;</td>'.
1.54      albertel 3693: 		    '<td align="center">'.$awarded.'&nbsp;</td>';
                   3694: 	    }
1.44      ng       3695: 	}
1.477     albertel 3696: 	$line.="\n";
1.301     albertel 3697: 
                   3698: 	my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   3699: 	my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   3700: 
1.44      ng       3701: 	if ($updateflag) {
                   3702: 	    $count++;
1.257     albertel 3703: 	    &Apache::lonnet::cstore(\%newrecord,$symb,$env{'request.course.id'},
1.89      albertel 3704: 				    $udom,$uname);
1.301     albertel 3705: 
                   3706: 	    if (&Apache::bridgetask::in_queue('gradingqueue',$symb,$cdom,
                   3707: 					      $cnum,$udom,$uname)) {
                   3708: 		# need to figure out if should be in queue.
                   3709: 		my %record =  
                   3710: 		    &Apache::lonnet::restore($symb,$env{'request.course.id'},
                   3711: 					     $udom,$uname);
                   3712: 		my $all_graded = 1;
                   3713: 		my $none_graded = 1;
                   3714: 		foreach my $part (@parts) {
                   3715: 		    if ( $record{'resource.'.$part.'.awarded'} eq '' ) {
                   3716: 			$all_graded = 0;
                   3717: 		    } else {
                   3718: 			$none_graded = 0;
                   3719: 		    }
                   3720: 		}
                   3721: 
                   3722: 		if ($all_graded || $none_graded) {
                   3723: 		    &Apache::bridgetask::remove_from_queue('gradingqueue',
                   3724: 							   $symb,$cdom,$cnum,
                   3725: 							   $udom,$uname);
                   3726: 		}
                   3727: 	    }
                   3728: 
1.477     albertel 3729: 	    $result.=&Apache::loncommon::start_data_table_row().
                   3730: 		'<td align="right">&nbsp;'.$updateCtr.'&nbsp;</td>'.$line.
                   3731: 		&Apache::loncommon::end_data_table_row();
1.126     ng       3732: 	    $updateCtr++;
1.93      albertel 3733: 	} else {
1.477     albertel 3734: 	    push(@noupdate,
                   3735: 		 '<td align="right">&nbsp;'.$noupdateCtr.'&nbsp;</td>'.$line);
1.126     ng       3736: 	    $noupdateCtr++;
1.44      ng       3737: 	}
1.269     raeburn  3738:         if ($aggregateflag) {
                   3739:             &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
1.301     albertel 3740: 				  $cdom,$cnum);
1.269     raeburn  3741:         }
1.93      albertel 3742:     }
1.477     albertel 3743:     if (@noupdate) {
1.126     ng       3744: #	my $numcols=(scalar(@partid)*(scalar(@parts)-1)*2)+3;
                   3745: 	my $numcols=scalar(@partid)*4+2;
1.477     albertel 3746: 	$result .= &Apache::loncommon::start_data_table_row('LC_empty_row').
1.478     albertel 3747: 	    '<td align="center" colspan="'.$numcols.'">'.
                   3748: 	    &mt('No Changes Occurred For the Students Below').
                   3749: 	    '</td>'.
1.477     albertel 3750: 	    &Apache::loncommon::end_data_table_row();
                   3751: 	foreach my $line (@noupdate) {
                   3752: 	    $result.=
                   3753: 		&Apache::loncommon::start_data_table_row().
                   3754: 		$line.
                   3755: 		&Apache::loncommon::end_data_table_row();
                   3756: 	}
1.44      ng       3757:     }
1.477     albertel 3758:     $result .= &Apache::loncommon::end_data_table().
                   3759: 	&show_grading_menu_form($symb);
1.478     albertel 3760:     my $msg = '<p><b>'.
                   3761: 	&mt('Number of records updated = [_1] for [quant,_2,student].',
                   3762: 	    $rec_update,$count).'</b><br />'.
                   3763: 	'<b>'.&mt('Total number of students = [_1]',$env{'form.total'}).
                   3764: 	'</b></p>';
1.44      ng       3765:     return $title.$msg.$result;
1.5       albertel 3766: }
1.54      albertel 3767: 
                   3768: sub split_part_type {
                   3769:     my ($partstr) = @_;
                   3770:     my ($temp,@allparts)=split(/_/,$partstr);
                   3771:     my $type=pop(@allparts);
1.439     albertel 3772:     my $part=join('_',@allparts);
1.54      albertel 3773:     return ($part,$type);
                   3774: }
                   3775: 
1.44      ng       3776: #------------- end of section for handling grading by section/class ---------
                   3777: #
                   3778: #----------------------------------------------------------------------------
                   3779: 
1.5       albertel 3780: 
1.44      ng       3781: #----------------------------------------------------------------------------
                   3782: #
                   3783: #-------------------------- Next few routines handles grading by csv upload
                   3784: #
                   3785: #--- Javascript to handle csv upload
1.27      albertel 3786: sub csvupload_javascript_reverse_associate {
1.573     bisitz   3787:     my $error1=&mt('You need to specify the username or the student/employee ID');
1.246     albertel 3788:     my $error2=&mt('You need to specify at least one grading field');
1.27      albertel 3789:   return(<<ENDPICK);
                   3790:   function verify(vf) {
                   3791:     var foundsomething=0;
                   3792:     var founduname=0;
1.243     albertel 3793:     var foundID=0;
1.27      albertel 3794:     for (i=0;i<=vf.nfields.value;i++) {
                   3795:       tw=eval('vf.f'+i+'.selectedIndex');
1.243     albertel 3796:       if (i==0 && tw!=0) { foundID=1; }
                   3797:       if (i==1 && tw!=0) { founduname=1; }
                   3798:       if (i!=0 && i!=1 && i!=2 && tw!=0) { foundsomething=1; }
1.27      albertel 3799:     }
1.246     albertel 3800:     if (founduname==0 && foundID==0) {
                   3801: 	alert('$error1');
                   3802: 	return;
1.27      albertel 3803:     }
                   3804:     if (foundsomething==0) {
1.246     albertel 3805: 	alert('$error2');
                   3806: 	return;
1.27      albertel 3807:     }
                   3808:     vf.submit();
                   3809:   }
                   3810:   function flip(vf,tf) {
                   3811:     var nw=eval('vf.f'+tf+'.selectedIndex');
                   3812:     var i;
                   3813:     for (i=0;i<=vf.nfields.value;i++) {
                   3814:       //can not pick the same destination field for both name and domain
                   3815:       if (((i ==0)||(i ==1)) && 
                   3816:           ((tf==0)||(tf==1)) && 
                   3817:           (i!=tf) &&
                   3818:           (eval('vf.f'+i+'.selectedIndex')==nw)) {
                   3819:         eval('vf.f'+i+'.selectedIndex=0;')
                   3820:       }
                   3821:     }
                   3822:   }
                   3823: ENDPICK
                   3824: }
                   3825: 
                   3826: sub csvupload_javascript_forward_associate {
1.573     bisitz   3827:     my $error1=&mt('You need to specify the username or the student/employee ID');
1.246     albertel 3828:     my $error2=&mt('You need to specify at least one grading field');
1.27      albertel 3829:   return(<<ENDPICK);
                   3830:   function verify(vf) {
                   3831:     var foundsomething=0;
                   3832:     var founduname=0;
1.243     albertel 3833:     var foundID=0;
1.27      albertel 3834:     for (i=0;i<=vf.nfields.value;i++) {
                   3835:       tw=eval('vf.f'+i+'.selectedIndex');
1.243     albertel 3836:       if (tw==1) { foundID=1; }
                   3837:       if (tw==2) { founduname=1; }
                   3838:       if (tw>3) { foundsomething=1; }
1.27      albertel 3839:     }
1.246     albertel 3840:     if (founduname==0 && foundID==0) {
                   3841: 	alert('$error1');
                   3842: 	return;
1.27      albertel 3843:     }
                   3844:     if (foundsomething==0) {
1.246     albertel 3845: 	alert('$error2');
                   3846: 	return;
1.27      albertel 3847:     }
                   3848:     vf.submit();
                   3849:   }
                   3850:   function flip(vf,tf) {
                   3851:     var nw=eval('vf.f'+tf+'.selectedIndex');
                   3852:     var i;
                   3853:     //can not pick the same destination field twice
                   3854:     for (i=0;i<=vf.nfields.value;i++) {
                   3855:       if ((i!=tf) && (eval('vf.f'+i+'.selectedIndex')==nw)) {
                   3856:         eval('vf.f'+i+'.selectedIndex=0;')
                   3857:       }
                   3858:     }
                   3859:   }
                   3860: ENDPICK
                   3861: }
                   3862: 
1.26      albertel 3863: sub csvuploadmap_header {
1.324     albertel 3864:     my ($request,$symb,$datatoken,$distotal)= @_;
1.41      ng       3865:     my $javascript;
1.257     albertel 3866:     if ($env{'form.upfile_associate'} eq 'reverse') {
1.41      ng       3867: 	$javascript=&csvupload_javascript_reverse_associate();
                   3868:     } else {
                   3869: 	$javascript=&csvupload_javascript_forward_associate();
                   3870:     }
1.45      ng       3871: 
1.598     www      3872: #    my ($result) = &showResourceInfo($symb,$env{'form.probTitle'});
                   3873:     my $result='';
1.257     albertel 3874:     my $checked=(($env{'form.noFirstLine'})?' checked="checked"':'');
1.245     albertel 3875:     my $ignore=&mt('Ignore First Line');
1.418     albertel 3876:     $symb = &Apache::lonenc::check_encrypt($symb);
1.41      ng       3877:     $request->print(<<ENDPICK);
1.26      albertel 3878: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
1.398     albertel 3879: <h3><span class="LC_info">Uploading Class Grades</span></h3>
1.45      ng       3880: $result
1.326     albertel 3881: <hr />
1.26      albertel 3882: <h3>Identify fields</h3>
                   3883: Total number of records found in file: $distotal <hr />
                   3884: Enter as many fields as you can. The system will inform you and bring you back
                   3885: to this page if the data selected is insufficient to run your class.<hr />
1.589     bisitz   3886: <input type="button" value="Reverse Association" onclick="javascript:this.form.associate.value='Reverse Association';submit(this.form);" />
1.245     albertel 3887: <label><input type="checkbox" name="noFirstLine" $checked />$ignore</label>
1.26      albertel 3888: <input type="hidden" name="associate"  value="" />
                   3889: <input type="hidden" name="phase"      value="three" />
                   3890: <input type="hidden" name="datatoken"  value="$datatoken" />
1.257     albertel 3891: <input type="hidden" name="fileupload" value="$env{'form.fileupload'}" />
                   3892: <input type="hidden" name="upfiletype" value="$env{'form.upfiletype'}" />
1.26      albertel 3893: <input type="hidden" name="upfile_associate" 
1.257     albertel 3894:                                        value="$env{'form.upfile_associate'}" />
1.26      albertel 3895: <input type="hidden" name="symb"       value="$symb" />
1.257     albertel 3896: <input type="hidden" name="saveState"  value="$env{'form.saveState'}" />
                   3897: <input type="hidden" name="probTitle"  value="$env{'form.probTitle'}" />
1.246     albertel 3898: <input type="hidden" name="command"    value="csvuploadoptions" />
1.26      albertel 3899: <hr />
                   3900: ENDPICK
1.597     wenzelju 3901:     $request->print(&Apache::lonhtmlcommon::scripttag($javascript));
1.118     ng       3902:     return '';
1.26      albertel 3903: 
                   3904: }
                   3905: 
                   3906: sub csvupload_fields {
1.582     raeburn  3907:     my ($symb,$errorref) = @_;
                   3908:     my (@parts) = &getpartlist($symb,$errorref);
                   3909:     if (ref($errorref)) {
                   3910:         if ($$errorref) {
                   3911:             return;
                   3912:         }
                   3913:     }
                   3914: 
1.556     weissno  3915:     my @fields=(['ID','Student/Employee ID'],
1.243     albertel 3916: 		['username','Student Username'],
                   3917: 		['domain','Student Domain']);
1.324     albertel 3918:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
1.41      ng       3919:     foreach my $part (sort(@parts)) {
                   3920: 	my @datum;
                   3921: 	my $display=&Apache::lonnet::metadata($url,$part.'.display');
                   3922: 	my $name=$part;
                   3923: 	if  (!$display) { $display = $name; }
                   3924: 	@datum=($name,$display);
1.244     albertel 3925: 	if ($name=~/^stores_(.*)_awarded/) {
                   3926: 	    push(@fields,['stores_'.$1.'_points',"Points [Part: $1]"]);
                   3927: 	}
1.41      ng       3928: 	push(@fields,\@datum);
                   3929:     }
                   3930:     return (@fields);
1.26      albertel 3931: }
                   3932: 
                   3933: sub csvuploadmap_footer {
1.41      ng       3934:     my ($request,$i,$keyfields) =@_;
                   3935:     $request->print(<<ENDPICK);
1.26      albertel 3936: </table>
                   3937: <input type="hidden" name="nfields" value="$i" />
                   3938: <input type="hidden" name="keyfields" value="$keyfields" />
1.589     bisitz   3939: <input type="button" onclick="javascript:verify(this.form)" value="Assign Grades" /><br />
1.26      albertel 3940: </form>
                   3941: ENDPICK
                   3942: }
                   3943: 
1.283     albertel 3944: sub checkforfile_js {
1.539     riegler  3945:     my $alertmsg = &mt('Please use the browse button to select a file from your local directory.');
1.597     wenzelju 3946:     my $result = &Apache::lonhtmlcommon::scripttag(<<CSVFORMJS);
1.86      ng       3947:     function checkUpload(formname) {
                   3948: 	if (formname.upfile.value == "") {
1.539     riegler  3949: 	    alert("$alertmsg");
1.86      ng       3950: 	    return false;
                   3951: 	}
                   3952: 	formname.submit();
                   3953:     }
                   3954: CSVFORMJS
1.283     albertel 3955:     return $result;
                   3956: }
                   3957: 
                   3958: sub upcsvScores_form {
                   3959:     my ($request) = shift;
1.324     albertel 3960:     my ($symb)=&get_symb($request);
1.283     albertel 3961:     if (!$symb) {return '';}
                   3962:     my $result=&checkforfile_js();
1.257     albertel 3963:     $env{'form.probTitle'} = &Apache::lonnet::gettitle($symb);
1.598     www      3964: #    my ($table) = &showResourceInfo($symb,$env{'form.probTitle'});
                   3965: #    $result.=$table;
1.326     albertel 3966:     $result.='<br /><table width="100%" border="0"><tr><td bgcolor="#777777">'."\n";
                   3967:     $result.='<table width="100%" border="0"><tr bgcolor="#e6ffff"><td>'."\n";
1.538     schulted 3968:     $result.='&nbsp;<b>'.&mt('Specify a file containing the class scores for current resource.').
                   3969: 	'</b></td></tr>'."\n";
1.86      ng       3970:     $result.='<tr bgcolor=#ffffe6><td>'."\n";
1.370     www      3971:     my $upload=&mt("Upload Scores");
1.86      ng       3972:     my $upfile_select=&Apache::loncommon::upfile_select_html();
1.245     albertel 3973:     my $ignore=&mt('Ignore First Line');
1.418     albertel 3974:     $symb = &Apache::lonenc::check_encrypt($symb);
1.86      ng       3975:     $result.=<<ENDUPFORM;
1.106     albertel 3976: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
1.86      ng       3977: <input type="hidden" name="symb" value="$symb" />
                   3978: <input type="hidden" name="command" value="csvuploadmap" />
1.257     albertel 3979: <input type="hidden" name="probTitle" value="$env{'form.probTitle'}" />
                   3980: <input type="hidden" name="saveState"  value="$env{'form.saveState'}" />
1.86      ng       3981: $upfile_select
1.589     bisitz   3982: <br /><input type="button" onclick="javascript:checkUpload(this.form);" value="$upload" />
1.283     albertel 3983: <label><input type="checkbox" name="noFirstLine" />$ignore</label>
1.86      ng       3984: </form>
                   3985: ENDUPFORM
1.370     www      3986:     $result.=&Apache::loncommon::help_open_topic("Course_Convert_To_CSV",
                   3987:                            &mt("How do I create a CSV file from a spreadsheet"))
                   3988:     .'</td></tr></table>'."\n";
1.86      ng       3989:     $result.='</td></tr></table><br /><br />'."\n";
1.324     albertel 3990:     $result.=&show_grading_menu_form($symb);
1.86      ng       3991:     return $result;
                   3992: }
                   3993: 
                   3994: 
1.26      albertel 3995: sub csvuploadmap {
1.41      ng       3996:     my ($request)= @_;
1.324     albertel 3997:     my ($symb)=&get_symb($request);
1.41      ng       3998:     if (!$symb) {return '';}
1.72      ng       3999: 
1.41      ng       4000:     my $datatoken;
1.257     albertel 4001:     if (!$env{'form.datatoken'}) {
1.41      ng       4002: 	$datatoken=&Apache::loncommon::upfile_store($request);
1.26      albertel 4003:     } else {
1.257     albertel 4004: 	$datatoken=$env{'form.datatoken'};
1.41      ng       4005: 	&Apache::loncommon::load_tmp_file($request);
1.26      albertel 4006:     }
1.41      ng       4007:     my @records=&Apache::loncommon::upfile_record_sep();
1.257     albertel 4008:     if ($env{'form.noFirstLine'}) { shift(@records); }
1.324     albertel 4009:     &csvuploadmap_header($request,$symb,$datatoken,$#records+1);
1.41      ng       4010:     my ($i,$keyfields);
                   4011:     if (@records) {
1.582     raeburn  4012:         my $fieldserror;
                   4013: 	my @fields=&csvupload_fields($symb,\$fieldserror);
                   4014:         if ($fieldserror) {
                   4015:             $request->print(&navmap_errormsg());
                   4016:             return;
                   4017:         }
1.257     albertel 4018: 	if ($env{'form.upfile_associate'} eq 'reverse') {	
1.41      ng       4019: 	    &Apache::loncommon::csv_print_samples($request,\@records);
                   4020: 	    $i=&Apache::loncommon::csv_print_select_table($request,\@records,
                   4021: 							  \@fields);
                   4022: 	    foreach (@fields) { $keyfields.=$_->[0].','; }
                   4023: 	    chop($keyfields);
                   4024: 	} else {
                   4025: 	    unshift(@fields,['none','']);
                   4026: 	    $i=&Apache::loncommon::csv_samples_select_table($request,\@records,
                   4027: 							    \@fields);
1.311     banghart 4028:             foreach my $rec (@records) {
                   4029:                 my %temp = &Apache::loncommon::record_sep($rec);
                   4030:                 if (%temp) {
                   4031:                     $keyfields=join(',',sort(keys(%temp)));
                   4032:                     last;
                   4033:                 }
                   4034:             }
1.41      ng       4035: 	}
                   4036:     }
                   4037:     &csvuploadmap_footer($request,$i,$keyfields);
1.324     albertel 4038:     $request->print(&show_grading_menu_form($symb));
1.72      ng       4039: 
1.41      ng       4040:     return '';
1.27      albertel 4041: }
                   4042: 
1.246     albertel 4043: sub csvuploadoptions {
1.41      ng       4044:     my ($request)= @_;
1.324     albertel 4045:     my ($symb)=&get_symb($request);
1.257     albertel 4046:     my $checked=(($env{'form.noFirstLine'})?'1':'0');
1.246     albertel 4047:     my $ignore=&mt('Ignore First Line');
                   4048:     $request->print(<<ENDPICK);
                   4049: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
1.398     albertel 4050: <h3><span class="LC_info">Uploading Class Grade Options</span></h3>
1.246     albertel 4051: <input type="hidden" name="command"    value="csvuploadassign" />
1.302     albertel 4052: <!--
1.246     albertel 4053: <p>
                   4054: <label>
                   4055:    <input type="checkbox" name="show_full_results" />
                   4056:    Show a table of all changes
                   4057: </label>
                   4058: </p>
1.302     albertel 4059: -->
1.246     albertel 4060: <p>
                   4061: <label>
                   4062:    <input type="checkbox" name="overwite_scores" checked="checked" />
                   4063:    Overwrite any existing score
                   4064: </label>
                   4065: </p>
                   4066: ENDPICK
                   4067:     my %fields=&get_fields();
                   4068:     if (!defined($fields{'domain'})) {
1.257     albertel 4069: 	my $domform = &Apache::loncommon::select_dom_form($env{'request.role.domain'},'default_domain');
1.246     albertel 4070: 	$request->print("\n<p> Users are in domain: ".$domform."</p>\n");
                   4071:     }
1.257     albertel 4072:     foreach my $key (sort(keys(%env))) {
1.246     albertel 4073: 	if ($key !~ /^form\.(.*)$/) { next; }
                   4074: 	my $cleankey=$1;
                   4075: 	if ($cleankey eq 'command') { next; }
                   4076: 	$request->print('<input type="hidden" name="'.$cleankey.
1.257     albertel 4077: 			'"  value="'.$env{$key}.'" />'."\n");
1.246     albertel 4078:     }
                   4079:     # FIXME do a check for any duplicated user ids...
                   4080:     # FIXME do a check for any invalid user ids?...
1.290     albertel 4081:     $request->print('<input type="submit" value="Assign Grades" /><br />
                   4082: <hr /></form>'."\n");
1.324     albertel 4083:     $request->print(&show_grading_menu_form($symb));
1.246     albertel 4084:     return '';
                   4085: }
                   4086: 
                   4087: sub get_fields {
                   4088:     my %fields;
1.257     albertel 4089:     my @keyfields = split(/\,/,$env{'form.keyfields'});
                   4090:     for (my $i=0; $i<=$env{'form.nfields'}; $i++) {
                   4091: 	if ($env{'form.upfile_associate'} eq 'reverse') {
                   4092: 	    if ($env{'form.f'.$i} ne 'none') {
                   4093: 		$fields{$keyfields[$i]}=$env{'form.f'.$i};
1.41      ng       4094: 	    }
                   4095: 	} else {
1.257     albertel 4096: 	    if ($env{'form.f'.$i} ne 'none') {
                   4097: 		$fields{$env{'form.f'.$i}}=$keyfields[$i];
1.41      ng       4098: 	    }
                   4099: 	}
1.27      albertel 4100:     }
1.246     albertel 4101:     return %fields;
                   4102: }
                   4103: 
                   4104: sub csvuploadassign {
                   4105:     my ($request)= @_;
1.324     albertel 4106:     my ($symb)=&get_symb($request);
1.246     albertel 4107:     if (!$symb) {return '';}
1.345     bowersj2 4108:     my $error_msg = '';
1.246     albertel 4109:     &Apache::loncommon::load_tmp_file($request);
                   4110:     my @gradedata = &Apache::loncommon::upfile_record_sep();
1.257     albertel 4111:     if ($env{'form.noFirstLine'}) { shift(@gradedata); }
1.246     albertel 4112:     my %fields=&get_fields();
1.41      ng       4113:     $request->print('<h3>Assigning Grades</h3>');
1.257     albertel 4114:     my $courseid=$env{'request.course.id'};
1.97      albertel 4115:     my ($classlist) = &getclasslist('all',0);
1.106     albertel 4116:     my @notallowed;
1.41      ng       4117:     my @skipped;
                   4118:     my $countdone=0;
                   4119:     foreach my $grade (@gradedata) {
                   4120: 	my %entries=&Apache::loncommon::record_sep($grade);
1.246     albertel 4121: 	my $domain;
                   4122: 	if ($entries{$fields{'domain'}}) {
                   4123: 	    $domain=$entries{$fields{'domain'}};
                   4124: 	} else {
1.257     albertel 4125: 	    $domain=$env{'form.default_domain'};
1.246     albertel 4126: 	}
1.243     albertel 4127: 	$domain=~s/\s//g;
1.41      ng       4128: 	my $username=$entries{$fields{'username'}};
1.160     albertel 4129: 	$username=~s/\s//g;
1.243     albertel 4130: 	if (!$username) {
                   4131: 	    my $id=$entries{$fields{'ID'}};
1.247     albertel 4132: 	    $id=~s/\s//g;
1.243     albertel 4133: 	    my %ids=&Apache::lonnet::idget($domain,$id);
                   4134: 	    $username=$ids{$id};
                   4135: 	}
1.41      ng       4136: 	if (!exists($$classlist{"$username:$domain"})) {
1.247     albertel 4137: 	    my $id=$entries{$fields{'ID'}};
                   4138: 	    $id=~s/\s//g;
                   4139: 	    if ($id) {
                   4140: 		push(@skipped,"$id:$domain");
                   4141: 	    } else {
                   4142: 		push(@skipped,"$username:$domain");
                   4143: 	    }
1.41      ng       4144: 	    next;
                   4145: 	}
1.108     albertel 4146: 	my $usec=$classlist->{"$username:$domain"}[5];
1.106     albertel 4147: 	if (!&canmodify($usec)) {
                   4148: 	    push(@notallowed,"$username:$domain");
                   4149: 	    next;
                   4150: 	}
1.244     albertel 4151: 	my %points;
1.41      ng       4152: 	my %grades;
                   4153: 	foreach my $dest (keys(%fields)) {
1.244     albertel 4154: 	    if ($dest eq 'ID' || $dest eq 'username' ||
                   4155: 		$dest eq 'domain') { next; }
                   4156: 	    if ($entries{$fields{$dest}} =~ /^\s*$/) { next; }
                   4157: 	    if ($dest=~/stores_(.*)_points/) {
                   4158: 		my $part=$1;
                   4159: 		my $wgt =&Apache::lonnet::EXT('resource.'.$part.'.weight',
                   4160: 					      $symb,$domain,$username);
1.345     bowersj2 4161:                 if ($wgt) {
                   4162:                     $entries{$fields{$dest}}=~s/\s//g;
                   4163:                     my $pcr=$entries{$fields{$dest}} / $wgt;
1.463     albertel 4164:                     my $award=($pcr == 0) ? 'incorrect_by_override'
                   4165:                                           : 'correct_by_override';
1.345     bowersj2 4166:                     $grades{"resource.$part.awarded"}=$pcr;
                   4167:                     $grades{"resource.$part.solved"}=$award;
                   4168:                     $points{$part}=1;
                   4169:                 } else {
                   4170:                     $error_msg = "<br />" .
                   4171:                         &mt("Some point values were assigned"
                   4172:                             ." for problems with a weight "
                   4173:                             ."of zero. These values were "
                   4174:                             ."ignored.");
                   4175:                 }
1.244     albertel 4176: 	    } else {
                   4177: 		if ($dest=~/stores_(.*)_awarded/) { if ($points{$1}) {next;} }
                   4178: 		if ($dest=~/stores_(.*)_solved/)  { if ($points{$1}) {next;} }
                   4179: 		my $store_key=$dest;
                   4180: 		$store_key=~s/^stores/resource/;
                   4181: 		$store_key=~s/_/\./g;
                   4182: 		$grades{$store_key}=$entries{$fields{$dest}};
                   4183: 	    }
1.41      ng       4184: 	}
1.508     www      4185: 	if (! %grades) { 
                   4186:            push(@skipped,&mt("[_1]: no data to save","$username:$domain")); 
                   4187:         } else {
                   4188: 	   $grades{"resource.regrader"}="$env{'user.name'}:$env{'user.domain'}";
                   4189: 	   my $result=&Apache::lonnet::cstore(\%grades,$symb,
1.302     albertel 4190: 					   $env{'request.course.id'},
                   4191: 					   $domain,$username);
1.508     www      4192: 	   if ($result eq 'ok') {
                   4193: 	      $request->print('.');
                   4194: 	   } else {
                   4195: 	      $request->print("<p><span class=\"LC_error\">".
                   4196:                               &mt("Failed to save data for student [_1]. Message when trying to save was: [_2]",
                   4197:                                   "$username:$domain",$result)."</span></p>");
                   4198: 	   }
                   4199: 	   $request->rflush();
                   4200: 	   $countdone++;
                   4201:         }
1.41      ng       4202:     }
1.570     www      4203:     $request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt("Saved scores for [quant,_1,student]",$countdone),$countdone==0));
1.41      ng       4204:     if (@skipped) {
1.571     www      4205: 	$request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt('No scores stored for the following username(s):'),1).'<br />');
                   4206:         $request->print(join(', ',@skipped));
1.106     albertel 4207:     }
                   4208:     if (@notallowed) {
1.571     www      4209: 	$request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt('Modification of scores not allowed for the following username(s):'),1).'<br />');
                   4210: 	$request->print(join(', ',@notallowed));
1.41      ng       4211:     }
1.106     albertel 4212:     $request->print("<br />\n");
1.324     albertel 4213:     $request->print(&show_grading_menu_form($symb));
1.345     bowersj2 4214:     return $error_msg;
1.26      albertel 4215: }
1.44      ng       4216: #------------- end of section for handling csv file upload ---------
                   4217: #
                   4218: #-------------------------------------------------------------------
                   4219: #
1.122     ng       4220: #-------------- Next few routines handle grading by page/sequence
1.72      ng       4221: #
                   4222: #--- Select a page/sequence and a student to grade
1.68      ng       4223: sub pickStudentPage {
                   4224:     my ($request) = shift;
                   4225: 
1.539     riegler  4226:     my $alertmsg = &mt('Please select the student you wish to grade.');
1.597     wenzelju 4227:     $request->print(&Apache::lonhtmlcommon::scripttag(<<LISTJAVASCRIPT));
1.68      ng       4228: 
                   4229: function checkPickOne(formname) {
1.76      ng       4230:     if (radioSelection(formname.student) == null) {
1.539     riegler  4231: 	alert("$alertmsg");
1.68      ng       4232: 	return;
                   4233:     }
1.125     ng       4234:     ptr = pullDownSelection(formname.selectpage);
                   4235:     formname.page.value = formname["page"+ptr].value;
                   4236:     formname.title.value = formname["title"+ptr].value;
1.68      ng       4237:     formname.submit();
                   4238: }
                   4239: 
                   4240: LISTJAVASCRIPT
1.118     ng       4241:     &commonJSfunctions($request);
1.324     albertel 4242:     my ($symb) = &get_symb($request);
1.257     albertel 4243:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
                   4244:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
                   4245:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
1.68      ng       4246: 
1.398     albertel 4247:     my $result='<h3><span class="LC_info">&nbsp;'.
1.485     albertel 4248: 	&mt('Manual Grading by Page or Sequence').'</span></h3>';
1.68      ng       4249: 
1.80      ng       4250:     $result.='<form action="/adm/grades" method="post" name="displayPage">'."\n";
1.582     raeburn  4251:     my $map_error;
                   4252:     my ($titles,$symbx) = &getSymbMap($map_error);
                   4253:     if ($map_error) {
                   4254:         $request->print(&navmap_errormsg());
                   4255:         return; 
                   4256:     }
1.137     albertel 4257:     my ($curpage) =&Apache::lonnet::decode_symb($symb); 
                   4258: #    my ($curpage,$mapId) =&Apache::lonnet::decode_symb($symb); 
                   4259: #    my $type=($curpage =~ /\.(page|sequence)/);
1.485     albertel 4260:     my $select = '<select name="selectpage">'."\n";
1.70      ng       4261:     my $ctr=0;
1.68      ng       4262:     foreach (@$titles) {
                   4263: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
1.485     albertel 4264: 	$select.='<option value="'.$ctr.'" '.
1.401     albertel 4265: 	    ($$symbx{$_} =~ /$curpage$/ ? 'selected="selected"' : '').
1.71      ng       4266: 	    '>'.$showtitle.'</option>'."\n";
1.70      ng       4267: 	$ctr++;
1.68      ng       4268:     }
1.485     albertel 4269:     $select.= '</select>';
1.539     riegler  4270:     $result.='&nbsp;<b>'.&mt('Problems from').':</b> '.$select."<br />\n";
1.485     albertel 4271: 
1.70      ng       4272:     $ctr=0;
                   4273:     foreach (@$titles) {
                   4274: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
                   4275: 	$result.='<input type="hidden" name="page'.$ctr.'" value="'.$$symbx{$_}.'" />'."\n";
                   4276: 	$result.='<input type="hidden" name="title'.$ctr.'" value="'.$showtitle.'" />'."\n";
                   4277: 	$ctr++;
                   4278:     }
1.72      ng       4279:     $result.='<input type="hidden" name="page" />'."\n".
                   4280: 	'<input type="hidden" name="title" />'."\n";
1.68      ng       4281: 
1.485     albertel 4282:     my $options =
                   4283: 	'<label><input type="radio" name="vProb" value="no" checked="checked" /> '.&mt('no').' </label>'."\n".
                   4284: 	'<label><input type="radio" name="vProb" value="yes" /> '.&mt('yes').' </label>'."<br />\n";
1.539     riegler  4285:     $result.='&nbsp;<b>'.&mt('View Problem Text').': </b>'.$options;
1.485     albertel 4286: 
                   4287:     $options =
                   4288: 	'<label><input type="radio" name="lastSub" value="none" /> '.&mt('none').' </label>'."\n".
                   4289: 	'<label><input type="radio" name="lastSub" value="datesub" checked="checked" /> '.&mt('by dates and submissions').'</label>'."\n".
                   4290: 	'<label><input type="radio" name="lastSub" value="all" /> '.&mt('all details').' </label>'."\n";
1.539     riegler  4291:     $result.='&nbsp;<b>'.&mt('Submissions').': </b>'.$options;
1.432     banghart 4292:     
                   4293:     $result.=&build_section_inputs();
1.442     banghart 4294:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
                   4295:     $result.='<input type="hidden" name="Status"  value="'.$stu_status.'" />'."\n".
1.72      ng       4296: 	'<input type="hidden" name="command" value="displayPage" />'."\n".
1.418     albertel 4297: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.257     albertel 4298: 	'<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."<br />\n";
1.72      ng       4299: 
1.539     riegler  4300:     $result.='&nbsp;<b>'.&mt('Use CODE').': </b> <input type="text" name="CODE" value="" /> <br />'."\n";
1.382     albertel 4301: 
1.80      ng       4302:     $result.='&nbsp;<input type="button" '.
1.589     bisitz   4303:              'onclick="javascript:checkPickOne(this.form);" value="'.&mt('Next').' &rarr;" /><br />'."\n";
1.72      ng       4304: 
1.68      ng       4305:     $request->print($result);
                   4306: 
1.485     albertel 4307:     my $studentTable.='&nbsp;<b>'.&mt('Select a student you wish to grade and then click on the Next button.').'</b><br />'.
1.484     albertel 4308: 	&Apache::loncommon::start_data_table().
                   4309: 	&Apache::loncommon::start_data_table_header_row().
1.485     albertel 4310: 	'<th align="right">&nbsp;'.&mt('No.').'</th>'.
1.484     albertel 4311: 	'<th>'.&nameUserString('header').'</th>'.
1.485     albertel 4312: 	'<th align="right">&nbsp;'.&mt('No.').'</th>'.
1.484     albertel 4313: 	'<th>'.&nameUserString('header').'</th>'.
                   4314: 	&Apache::loncommon::end_data_table_header_row();
1.68      ng       4315:  
1.76      ng       4316:     my (undef,undef,$fullname) = &getclasslist($getsec,'1');
1.68      ng       4317:     my $ptr = 1;
1.294     albertel 4318:     foreach my $student (sort 
                   4319: 			 {
                   4320: 			     if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                   4321: 				 return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                   4322: 			     }
                   4323: 			     return $a cmp $b;
                   4324: 			 } (keys(%$fullname))) {
1.68      ng       4325: 	my ($uname,$udom) = split(/:/,$student);
1.484     albertel 4326: 	$studentTable.=($ptr%2==1 ? &Apache::loncommon::start_data_table_row()
                   4327:                                   : '</td>');
1.126     ng       4328: 	$studentTable.='<td align="right">'.$ptr.'&nbsp;</td>';
1.288     albertel 4329: 	$studentTable.='<td>&nbsp;<label><input type="radio" name="student" value="'.$student.'" /> '
                   4330: 	    .&nameUserString(undef,$$fullname{$student},$uname,$udom)."</label>\n";
1.484     albertel 4331: 	$studentTable.=
                   4332: 	    ($ptr%2 == 0 ? '</td>'.&Apache::loncommon::end_data_table_row() 
                   4333:                          : '');
1.68      ng       4334: 	$ptr++;
                   4335:     }
1.484     albertel 4336:     if ($ptr%2 == 0) {
                   4337: 	$studentTable.='</td><td>&nbsp;</td><td>&nbsp;</td>'.
                   4338: 	    &Apache::loncommon::end_data_table_row();
                   4339:     }
                   4340:     $studentTable.=&Apache::loncommon::end_data_table()."\n";
1.126     ng       4341:     $studentTable.='<input type="button" '.
1.589     bisitz   4342:                    'onclick="javascript:checkPickOne(this.form);" value="'.&mt('Next').' &rarr;" /></form>'."\n";
1.68      ng       4343: 
1.324     albertel 4344:     $studentTable.=&show_grading_menu_form($symb);
1.68      ng       4345:     $request->print($studentTable);
                   4346: 
                   4347:     return '';
                   4348: }
                   4349: 
                   4350: sub getSymbMap {
1.582     raeburn  4351:     my ($map_error) = @_;
1.132     bowersj2 4352:     my $navmap = Apache::lonnavmaps::navmap->new();
1.582     raeburn  4353:     unless (ref($navmap)) {
                   4354:         if (ref($map_error)) {
                   4355:             $$map_error = 'navmap';
                   4356:         }
                   4357:         return;
                   4358:     }
1.68      ng       4359:     my %symbx = ();
                   4360:     my @titles = ();
1.117     bowersj2 4361:     my $minder = 0;
                   4362: 
                   4363:     # Gather every sequence that has problems.
1.240     albertel 4364:     my @sequences = $navmap->retrieveResources(undef, sub { shift->is_map(); },
                   4365: 					       1,0,1);
1.117     bowersj2 4366:     for my $sequence ($navmap->getById('0.0'), @sequences) {
1.241     albertel 4367: 	if ($navmap->hasResource($sequence, sub { shift->is_problem(); }, 0) ) {
1.381     albertel 4368: 	    my $title = $minder.'.'.
                   4369: 		&HTML::Entities::encode($sequence->compTitle(),'"\'&');
                   4370: 	    push(@titles, $title); # minder in case two titles are identical
                   4371: 	    $symbx{$title} = &HTML::Entities::encode($sequence->symb(),'"\'&');
1.117     bowersj2 4372: 	    $minder++;
1.241     albertel 4373: 	}
1.68      ng       4374:     }
                   4375:     return \@titles,\%symbx;
                   4376: }
                   4377: 
1.72      ng       4378: #
                   4379: #--- Displays a page/sequence w/wo problems, w/wo submissions
1.68      ng       4380: sub displayPage {
                   4381:     my ($request) = shift;
                   4382: 
1.324     albertel 4383:     my ($symb) = &get_symb($request);
1.257     albertel 4384:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
                   4385:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
                   4386:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
                   4387:     my $pageTitle = $env{'form.page'};
1.103     albertel 4388:     my ($classlist,undef,$fullname) = &getclasslist($getsec,'1');
1.257     albertel 4389:     my ($uname,$udom) = split(/:/,$env{'form.student'});
                   4390:     my $usec=$classlist->{$env{'form.student'}}[5];
1.168     albertel 4391: 
                   4392:     #need to make sure we have the correct data for later EXT calls, 
                   4393:     #thus invalidate the cache
                   4394:     &Apache::lonnet::devalidatecourseresdata(
1.257     albertel 4395:                  $env{'course.'.$env{'request.course.id'}.'.num'},
                   4396:                  $env{'course.'.$env{'request.course.id'}.'.domain'});
1.168     albertel 4397:     &Apache::lonnet::clear_EXT_cache_status();
                   4398: 
1.103     albertel 4399:     if (!&canview($usec)) {
1.485     albertel 4400: 	$request->print('<span class="LC_warning">'.&mt('Unable to view requested student. ([_1])',$env{'form.student'}).'</span>');
1.324     albertel 4401: 	$request->print(&show_grading_menu_form($symb));
1.103     albertel 4402: 	return;
                   4403:     }
1.398     albertel 4404:     my $result='<h3><span class="LC_info">&nbsp;'.$env{'form.title'}.'</span></h3>';
1.485     albertel 4405:     $result.='<h3>&nbsp;'.&mt('Student: [_1]',&nameUserString(undef,$$fullname{$env{'form.student'}},$uname,$udom)).
1.129     ng       4406: 	'</h3>'."\n";
1.500     albertel 4407:     $env{'form.CODE'} = uc($env{'form.CODE'});
1.501     foxr     4408:     if (&Apache::lonnet::validCODE(uc($env{'form.CODE'}))) {
1.485     albertel 4409: 	$result.='<h3>&nbsp;'.&mt('CODE: [_1]',$env{'form.CODE'}).'</h3>'."\n";
1.382     albertel 4410:     } else {
                   4411: 	delete($env{'form.CODE'});
                   4412:     }
1.71      ng       4413:     &sub_page_js($request);
                   4414:     $request->print($result);
                   4415: 
1.132     bowersj2 4416:     my $navmap = Apache::lonnavmaps::navmap->new();
1.582     raeburn  4417:     unless (ref($navmap)) {
                   4418:         $request->print(&navmap_errormsg());
                   4419:         $request->print(&show_grading_menu_form($symb));
                   4420:         return;
                   4421:     }
1.257     albertel 4422:     my ($mapUrl, $id, $resUrl)=&Apache::lonnet::decode_symb($env{'form.page'});
1.68      ng       4423:     my $map = $navmap->getResourceByUrl($resUrl); # add to navmaps
1.288     albertel 4424:     if (!$map) {
1.485     albertel 4425: 	$request->print('<span class="LC_warning">'.&mt('Unable to view requested sequence. ([_1])',$resUrl).'</span>');
1.324     albertel 4426: 	$request->print(&show_grading_menu_form($symb));
1.288     albertel 4427: 	return; 
                   4428:     }
1.68      ng       4429:     my $iterator = $navmap->getIterator($map->map_start(),
                   4430: 					$map->map_finish());
                   4431: 
1.71      ng       4432:     my $studentTable='<form action="/adm/grades" method="post" name="gradePage">'."\n".
1.72      ng       4433: 	'<input type="hidden" name="command" value="gradeByPage" />'."\n".
1.257     albertel 4434: 	'<input type="hidden" name="fullname" value="'.$$fullname{$env{'form.student'}}.'" />'."\n".
                   4435: 	'<input type="hidden" name="student" value="'.$env{'form.student'}.'" />'."\n".
1.72      ng       4436: 	'<input type="hidden" name="page"    value="'.$pageTitle.'" />'."\n".
1.257     albertel 4437: 	'<input type="hidden" name="title"   value="'.$env{'form.title'}.'" />'."\n".
1.418     albertel 4438: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.125     ng       4439: 	'<input type="hidden" name="overRideScore" value="no" />'."\n".
1.257     albertel 4440: 	'<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n";
1.71      ng       4441: 
1.382     albertel 4442:     if (defined($env{'form.CODE'})) {
                   4443: 	$studentTable.=
                   4444: 	    '<input type="hidden" name="CODE" value="'.$env{'form.CODE'}.'" />'."\n";
                   4445:     }
1.381     albertel 4446:     my $checkIcon = '<img alt="'.&mt('Check Mark').
1.485     albertel 4447: 	'" src="'.&Apache::loncommon::lonhttpdurl($request->dir_config('lonIconsURL').'/check.gif').'" height="16" border="0" />';
1.71      ng       4448: 
1.594     bisitz   4449:     $studentTable.='&nbsp;<span class="LC_info">'.
                   4450:         &mt('Problems graded correct by the computer are marked with a [_1] symbol.',$checkIcon).
                   4451:         '</span>'."\n".
1.484     albertel 4452: 	&Apache::loncommon::start_data_table().
                   4453: 	&Apache::loncommon::start_data_table_header_row().
                   4454: 	'<th align="center">&nbsp;Prob.&nbsp;</th>'.
1.485     albertel 4455: 	'<th>&nbsp;'.($env{'form.vProb'} eq 'no' ? &mt('Title') : &mt('Problem Text')).'/'.&mt('Grade').'</th>'.
1.484     albertel 4456: 	&Apache::loncommon::end_data_table_header_row();
1.71      ng       4457: 
1.329     albertel 4458:     &Apache::lonxml::clear_problem_counter();
1.196     albertel 4459:     my ($depth,$question,$prob) = (1,1,1);
1.68      ng       4460:     $iterator->next(); # skip the first BEGIN_MAP
                   4461:     my $curRes = $iterator->next(); # for "current resource"
1.101     albertel 4462:     while ($depth > 0) {
1.68      ng       4463:         if($curRes == $iterator->BEGIN_MAP) { $depth++; }
1.100     bowersj2 4464:         if($curRes == $iterator->END_MAP) { $depth--; }
1.68      ng       4465: 
1.385     albertel 4466:         if (ref($curRes) && $curRes->is_problem()) {
1.91      albertel 4467: 	    my $parts = $curRes->parts();
1.68      ng       4468:             my $title = $curRes->compTitle();
1.71      ng       4469: 	    my $symbx = $curRes->symb();
1.484     albertel 4470: 	    $studentTable.=
                   4471: 		&Apache::loncommon::start_data_table_row().
                   4472: 		'<td align="center" valign="top" >'.$prob.
1.485     albertel 4473: 		(scalar(@{$parts}) == 1 ? '' 
                   4474: 		                        : '<br />('.&mt('[_1]&nbsp;parts)',
                   4475: 							scalar(@{$parts}))
                   4476: 		 ).
                   4477: 		 '</td>';
1.71      ng       4478: 	    $studentTable.='<td valign="top">';
1.382     albertel 4479: 	    my %form = ('CODE' => $env{'form.CODE'},);
1.257     albertel 4480: 	    if ($env{'form.vProb'} eq 'yes' ) {
1.144     albertel 4481: 		$studentTable.=&show_problem($request,$symbx,$uname,$udom,1,
1.383     albertel 4482: 					     undef,'both',\%form);
1.71      ng       4483: 	    } else {
1.382     albertel 4484: 		my $companswer = &Apache::loncommon::get_student_answers($symbx,$uname,$udom,$env{'request.course.id'},%form);
1.80      ng       4485: 		$companswer =~ s|<form(.*?)>||g;
                   4486: 		$companswer =~ s|</form>||g;
1.71      ng       4487: #		while ($companswer =~ /(<a href\=\"javascript:newWindow.*?Script Vars<\/a>)/s) { #<a href="javascript:newWindow</a>
1.116     ng       4488: #		    $companswer =~ s/$1/ /ms;
1.326     albertel 4489: #		    $request->print('match='.$1."<br />\n");
1.71      ng       4490: #		}
1.116     ng       4491: #		$companswer =~ s|<table border=\"1\">|<table border=\"0\">|g;
1.539     riegler  4492: 		$studentTable.='&nbsp;<b>'.$title.'</b>&nbsp;<br />&nbsp;<b>'.&mt('Correct answer').':</b><br />'.$companswer;
1.71      ng       4493: 	    }
                   4494: 
1.257     albertel 4495: 	    my %record = &Apache::lonnet::restore($symbx,$env{'request.course.id'},$udom,$uname);
1.125     ng       4496: 
1.257     albertel 4497: 	    if ($env{'form.lastSub'} eq 'datesub') {
1.71      ng       4498: 		if ($record{'version'} eq '') {
1.485     albertel 4499: 		    $studentTable.='<br />&nbsp;<span class="LC_warning">'.&mt('No recorded submission for this problem.').'</span><br />';
1.71      ng       4500: 		} else {
1.116     ng       4501: 		    my %responseType = ();
                   4502: 		    foreach my $partid (@{$parts}) {
1.147     albertel 4503: 			my @responseIds =$curRes->responseIds($partid);
                   4504: 			my @responseType =$curRes->responseType($partid);
                   4505: 			my %responseIds;
                   4506: 			for (my $i=0;$i<=$#responseIds;$i++) {
                   4507: 			    $responseIds{$responseIds[$i]}=$responseType[$i];
                   4508: 			}
                   4509: 			$responseType{$partid} = \%responseIds;
1.116     ng       4510: 		    }
1.148     albertel 4511: 		    $studentTable.= &displaySubByDates($symbx,\%record,$parts,\%responseType,$checkIcon,$uname,$udom);
1.147     albertel 4512: 
1.71      ng       4513: 		}
1.257     albertel 4514: 	    } elsif ($env{'form.lastSub'} eq 'all') {
                   4515: 		my $last = ($env{'form.lastSub'} eq 'last' ? 'last' : '');
1.71      ng       4516: 		$studentTable.=&Apache::loncommon::get_previous_attempt($symbx,$uname,$udom,
1.257     albertel 4517: 									$env{'request.course.id'},
1.71      ng       4518: 									'','.submission');
                   4519:  
                   4520: 	    }
1.103     albertel 4521: 	    if (&canmodify($usec)) {
1.585     bisitz   4522:             $studentTable.=&gradeBox_start();
1.103     albertel 4523: 		foreach my $partid (@{$parts}) {
                   4524: 		    $studentTable.=&gradeBox($request,$symbx,$uname,$udom,$question,$partid,\%record);
                   4525: 		    $studentTable.='<input type="hidden" name="q_'.$question.'" value="'.$partid.'" />'."\n";
                   4526: 		    $question++;
                   4527: 		}
1.585     bisitz   4528:             $studentTable.=&gradeBox_end();
1.196     albertel 4529: 		$prob++;
1.71      ng       4530: 	    }
                   4531: 	    $studentTable.='</td></tr>';
1.68      ng       4532: 
1.103     albertel 4533: 	}
1.68      ng       4534:         $curRes = $iterator->next();
                   4535:     }
                   4536: 
1.589     bisitz   4537:     $studentTable.=
                   4538:         '</table>'."\n".
                   4539:         '<input type="button" value="'.&mt('Save').'" '.
                   4540:         'onclick="javascript:checkSubmitPage(this.form,'.$question.');" />'.
                   4541:         '</form>'."\n";
1.324     albertel 4542:     $studentTable.=&show_grading_menu_form($symb);
1.71      ng       4543:     $request->print($studentTable);
                   4544: 
                   4545:     return '';
1.119     ng       4546: }
                   4547: 
                   4548: sub displaySubByDates {
1.148     albertel 4549:     my ($symb,$record,$parts,$responseType,$checkIcon,$uname,$udom) = @_;
1.224     albertel 4550:     my $isCODE=0;
1.335     albertel 4551:     my $isTask = ($symb =~/\.task$/);
1.224     albertel 4552:     if (exists($record->{'resource.CODE'})) { $isCODE=1; }
1.467     albertel 4553:     my $studentTable=&Apache::loncommon::start_data_table().
                   4554: 	&Apache::loncommon::start_data_table_header_row().
                   4555: 	'<th>'.&mt('Date/Time').'</th>'.
                   4556: 	($isCODE?'<th>'.&mt('CODE').'</th>':'').
                   4557: 	'<th>'.&mt('Submission').'</th>'.
                   4558: 	'<th>'.&mt('Status').'</th>'.
                   4559: 	&Apache::loncommon::end_data_table_header_row();
1.119     ng       4560:     my ($version);
                   4561:     my %mark;
1.148     albertel 4562:     my %orders;
1.119     ng       4563:     $mark{'correct_by_student'} = $checkIcon;
1.147     albertel 4564:     if (!exists($$record{'1:timestamp'})) {
1.539     riegler  4565: 	return '<br />&nbsp;<span class="LC_warning">'.&mt('Nothing submitted - no attempts.').'</span><br />';
1.147     albertel 4566:     }
1.335     albertel 4567: 
                   4568:     my $interaction;
1.525     raeburn  4569:     my $no_increment = 1;
1.119     ng       4570:     for ($version=1;$version<=$$record{'version'};$version++) {
1.467     albertel 4571: 	my $timestamp = 
                   4572: 	    &Apache::lonlocal::locallocaltime($$record{$version.':timestamp'});
1.335     albertel 4573: 	if (exists($$record{$version.':resource.0.version'})) {
                   4574: 	    $interaction = $$record{$version.':resource.0.version'};
                   4575: 	}
                   4576: 
                   4577: 	my $where = ($isTask ? "$version:resource.$interaction"
                   4578: 		             : "$version:resource");
1.467     albertel 4579: 	$studentTable.=&Apache::loncommon::start_data_table_row().
                   4580: 	    '<td>'.$timestamp.'</td>';
1.224     albertel 4581: 	if ($isCODE) {
                   4582: 	    $studentTable.='<td>'.$record->{$version.':resource.CODE'}.'</td>';
                   4583: 	}
1.119     ng       4584: 	my @versionKeys = split(/\:/,$$record{$version.':keys'});
                   4585: 	my @displaySub = ();
                   4586: 	foreach my $partid (@{$parts}) {
1.596     raeburn  4587:             my $hidden;
                   4588:             if (($$record{$version.':resource.'.$partid.'.type'} eq 'anonsurvey') ||
                   4589:                 ($$record{$version.':resource.'.$partid.'.type'} eq 'anonsurveycred')) {
                   4590:                 $hidden = 1;
                   4591:             }
1.335     albertel 4592: 	    my @matchKey = ($isTask ? sort(grep /^resource\.\d+\.\Q$partid\E\.award$/,@versionKeys)
                   4593: 			            : sort(grep /^resource\.\Q$partid\E\..*?\.submission$/,@versionKeys));
                   4594: 	    
1.122     ng       4595: #	    next if ($$record{"$version:resource.$partid.solved"} eq '');
1.324     albertel 4596: 	    my $display_part=&get_display_part($partid,$symb);
1.147     albertel 4597: 	    foreach my $matchKey (@matchKey) {
1.198     albertel 4598: 		if (exists($$record{$version.':'.$matchKey}) &&
                   4599: 		    $$record{$version.':'.$matchKey} ne '') {
1.596     raeburn  4600:                     
1.335     albertel 4601: 		    my ($responseId)= ($isTask ? ($matchKey=~ /^resource\.(.*?)\.\Q$partid\E\.award$/)
                   4602: 				               : ($matchKey=~ /^resource\.\Q$partid\E\.(.*?)\.submission$/));
1.577     bisitz   4603:                     $displaySub[0].='<span class="LC_nobreak"';
                   4604:                     $displaySub[0].='<b>'.&mt('Part: [_1]',$display_part).'</b>'
                   4605:                                    .' <span class="LC_internal_info">'
                   4606:                                    .'('.&mt('Part ID: [_1]',$responseId).')'
                   4607:                                    .'</span>'
                   4608:                                    .' <b>';
1.596     raeburn  4609:                     if ($hidden) {
                   4610:                         $displaySub[0].= &mt('Anonymous Survey').'</b>';
                   4611:                     } else {
                   4612: 		        if ($$record{"$where.$partid.tries"} eq '') {
                   4613: 			    $displaySub[0].=&mt('Trial not counted');
                   4614: 		        } else {
                   4615: 			    $displaySub[0].=&mt('Trial: [_1]',
1.467     albertel 4616: 					    $$record{"$where.$partid.tries"});
1.596     raeburn  4617: 		        }
                   4618: 		        my $responseType=($isTask ? 'Task'
1.335     albertel 4619:                                               : $responseType->{$partid}->{$responseId});
1.596     raeburn  4620: 		        if (!exists($orders{$partid})) { $orders{$partid}={}; }
                   4621: 		        if (!exists($orders{$partid}->{$responseId})) {
                   4622: 			    $orders{$partid}->{$responseId}=
                   4623: 			        &get_order($partid,$responseId,$symb,$uname,$udom,
                   4624:                                            $no_increment);
                   4625: 		        }
                   4626: 		        $displaySub[0].='</b></span>'; # /nobreak
                   4627: 		        $displaySub[0].='&nbsp; '.
                   4628: 			    &cleanRecord($$record{$version.':'.$matchKey},$responseType,$symb,$partid,$responseId,$record,$orders{$partid}->{$responseId},"$version:",$uname,$udom).'<br />';
                   4629:                     }
1.147     albertel 4630: 		}
                   4631: 	    }
1.335     albertel 4632: 	    if (exists($$record{"$where.$partid.checkedin"})) {
1.485     albertel 4633: 		$displaySub[1].=&mt('Checked in by [_1] into slot [_2]',
                   4634: 				    $$record{"$where.$partid.checkedin"},
                   4635: 				    $$record{"$where.$partid.checkedin.slot"}).
                   4636: 					'<br />';
1.335     albertel 4637: 	    }
                   4638: 	    if (exists $$record{"$where.$partid.award"}) {
1.485     albertel 4639: 		$displaySub[1].='<b>'.&mt('Part:').'</b>&nbsp;'.$display_part.' &nbsp;'.
1.335     albertel 4640: 		    lc($$record{"$where.$partid.award"}).' '.
                   4641: 		    $mark{$$record{"$where.$partid.solved"}}.
1.147     albertel 4642: 		    '<br />';
                   4643: 	    }
1.335     albertel 4644: 	    if (exists $$record{"$where.$partid.regrader"}) {
                   4645: 		$displaySub[2].=$$record{"$where.$partid.regrader"}.
                   4646: 		    ' (<b>'.&mt('Part').':</b> '.$display_part.')';
                   4647: 	    } elsif ($$record{"$version:resource.$partid.regrader"} =~ /\S/) {
                   4648: 		$displaySub[2].=
                   4649: 		    $$record{"$version:resource.$partid.regrader"}.
1.207     albertel 4650: 		    ' (<b>'.&mt('Part').':</b> '.$display_part.')';
1.147     albertel 4651: 	    }
                   4652: 	}
                   4653: 	# needed because old essay regrader has not parts info
                   4654: 	if (exists $$record{"$version:resource.regrader"}) {
                   4655: 	    $displaySub[2].=$$record{"$version:resource.regrader"};
                   4656: 	}
                   4657: 	$studentTable.='<td>'.$displaySub[0].'&nbsp;</td><td>'.$displaySub[1];
                   4658: 	if ($displaySub[2]) {
1.467     albertel 4659: 	    $studentTable.=&mt('Manually graded by [_1]',$displaySub[2]);
1.147     albertel 4660: 	}
1.467     albertel 4661: 	$studentTable.='&nbsp;</td>'.
                   4662: 	    &Apache::loncommon::end_data_table_row();
1.119     ng       4663:     }
1.467     albertel 4664:     $studentTable.=&Apache::loncommon::end_data_table();
1.119     ng       4665:     return $studentTable;
1.71      ng       4666: }
                   4667: 
                   4668: sub updateGradeByPage {
                   4669:     my ($request) = shift;
                   4670: 
1.257     albertel 4671:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
                   4672:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
                   4673:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
                   4674:     my $pageTitle = $env{'form.page'};
1.103     albertel 4675:     my ($classlist,undef,$fullname) = &getclasslist($getsec,'1');
1.257     albertel 4676:     my ($uname,$udom) = split(/:/,$env{'form.student'});
                   4677:     my $usec=$classlist->{$env{'form.student'}}[5];
1.103     albertel 4678:     if (!&canmodify($usec)) {
1.526     raeburn  4679: 	$request->print('<span class="LC_warning">'.&mt('Unable to modify requested student ([_1])',$env{'form.student'}).'</span>');
1.324     albertel 4680: 	$request->print(&show_grading_menu_form($env{'form.symb'}));
1.103     albertel 4681: 	return;
                   4682:     }
1.398     albertel 4683:     my $result='<h3><span class="LC_info">&nbsp;'.$env{'form.title'}.'</span></h3>';
1.526     raeburn  4684:     $result.='<h3>&nbsp;'.&mt('Student: ').&nameUserString(undef,$env{'form.fullname'},$uname,$udom).
1.129     ng       4685: 	'</h3>'."\n";
1.70      ng       4686: 
1.68      ng       4687:     $request->print($result);
                   4688: 
1.582     raeburn  4689: 
1.132     bowersj2 4690:     my $navmap = Apache::lonnavmaps::navmap->new();
1.582     raeburn  4691:     unless (ref($navmap)) {
                   4692:         $request->print(&navmap_errormsg());
                   4693:         return;
                   4694:     }
1.257     albertel 4695:     my ($mapUrl, $id, $resUrl) = &Apache::lonnet::decode_symb( $env{'form.page'});
1.71      ng       4696:     my $map = $navmap->getResourceByUrl($resUrl); # add to navmaps
1.288     albertel 4697:     if (!$map) {
1.527     raeburn  4698: 	$request->print('<span class="LC_warning">'.&mt('Unable to grade requested sequence ([_1]).',$resUrl).'</span>');
1.324     albertel 4699: 	my ($symb)=&get_symb($request);
                   4700: 	$request->print(&show_grading_menu_form($symb));
1.288     albertel 4701: 	return; 
                   4702:     }
1.71      ng       4703:     my $iterator = $navmap->getIterator($map->map_start(),
                   4704: 					$map->map_finish());
1.70      ng       4705: 
1.484     albertel 4706:     my $studentTable=
                   4707: 	&Apache::loncommon::start_data_table().
                   4708: 	&Apache::loncommon::start_data_table_header_row().
1.485     albertel 4709: 	'<th align="center">&nbsp;'.&mt('Prob.').'&nbsp;</th>'.
                   4710: 	'<th>&nbsp;'.&mt('Title').'&nbsp;</th>'.
                   4711: 	'<th>&nbsp;'.&mt('Previous Score').'&nbsp;</th>'.
                   4712: 	'<th>&nbsp;'.&mt('New Score').'&nbsp;</th>'.
1.484     albertel 4713: 	&Apache::loncommon::end_data_table_header_row();
1.71      ng       4714: 
                   4715:     $iterator->next(); # skip the first BEGIN_MAP
                   4716:     my $curRes = $iterator->next(); # for "current resource"
1.196     albertel 4717:     my ($depth,$question,$prob,$changeflag)= (1,1,1,0);
1.101     albertel 4718:     while ($depth > 0) {
1.71      ng       4719:         if($curRes == $iterator->BEGIN_MAP) { $depth++; }
1.100     bowersj2 4720:         if($curRes == $iterator->END_MAP) { $depth--; }
1.71      ng       4721: 
1.385     albertel 4722:         if (ref($curRes) && $curRes->is_problem()) {
1.91      albertel 4723: 	    my $parts = $curRes->parts();
1.71      ng       4724:             my $title = $curRes->compTitle();
                   4725: 	    my $symbx = $curRes->symb();
1.484     albertel 4726: 	    $studentTable.=
                   4727: 		&Apache::loncommon::start_data_table_row().
                   4728: 		'<td align="center" valign="top" >'.$prob.
1.485     albertel 4729: 		(scalar(@{$parts}) == 1 ? '' 
1.526     raeburn  4730:                                         : '<br />('.&mt('[quant,_1,&nbsp;part]',scalar(@{$parts}))
                   4731: 		.')').'</td>';
1.71      ng       4732: 	    $studentTable.='<td valign="top">&nbsp;<b>'.$title.'</b>&nbsp;</td>';
                   4733: 
                   4734: 	    my %newrecord=();
                   4735: 	    my @displayPts=();
1.269     raeburn  4736:             my %aggregate = ();
                   4737:             my $aggregateflag = 0;
1.71      ng       4738: 	    foreach my $partid (@{$parts}) {
1.257     albertel 4739: 		my $newpts = $env{'form.GD_BOX'.$question.'_'.$partid};
                   4740: 		my $oldpts = $env{'form.oldpts'.$question.'_'.$partid};
1.71      ng       4741: 
1.257     albertel 4742: 		my $wgt = $env{'form.WGT'.$question.'_'.$partid} != 0 ? 
                   4743: 		    $env{'form.WGT'.$question.'_'.$partid} : 1;
1.71      ng       4744: 		my $partial = $newpts/$wgt;
                   4745: 		my $score;
                   4746: 		if ($partial > 0) {
                   4747: 		    $score = 'correct_by_override';
1.125     ng       4748: 		} elsif ($newpts ne '') { #empty is taken as 0
1.71      ng       4749: 		    $score = 'incorrect_by_override';
                   4750: 		}
1.257     albertel 4751: 		my $dropMenu = $env{'form.GD_SEL'.$question.'_'.$partid};
1.125     ng       4752: 		if ($dropMenu eq 'excused') {
1.71      ng       4753: 		    $partial = '';
                   4754: 		    $score = 'excused';
1.125     ng       4755: 		} elsif ($dropMenu eq 'reset status'
1.257     albertel 4756: 			 && $env{'form.solved'.$question.'_'.$partid} ne '') { #update only if previous record exists
1.125     ng       4757: 		    $newrecord{'resource.'.$partid.'.tries'} = 0;
                   4758: 		    $newrecord{'resource.'.$partid.'.solved'} = '';
                   4759: 		    $newrecord{'resource.'.$partid.'.award'} = '';
                   4760: 		    $newrecord{'resource.'.$partid.'.awarded'} = 0;
1.257     albertel 4761: 		    $newrecord{'resource.'.$partid.'.regrader'} = "$env{'user.name'}:$env{'user.domain'}";
1.125     ng       4762: 		    $changeflag++;
                   4763: 		    $newpts = '';
1.269     raeburn  4764:                     
                   4765:                     my $aggtries =  $env{'form.aggtries'.$question.'_'.$partid};
                   4766:                     my $totaltries = $env{'form.totaltries'.$question.'_'.$partid};
                   4767:                     my $solvedstatus = $env{'form.solved'.$question.'_'.$partid};
                   4768:                     if ($aggtries > 0) {
                   4769:                         &decrement_aggs($symbx,$partid,\%aggregate,$aggtries,$totaltries,$solvedstatus);
                   4770:                         $aggregateflag = 1;
                   4771:                     }
1.71      ng       4772: 		}
1.324     albertel 4773: 		my $display_part=&get_display_part($partid,$curRes->symb());
1.257     albertel 4774: 		my $oldstatus = $env{'form.solved'.$question.'_'.$partid};
1.526     raeburn  4775: 		$displayPts[0].='&nbsp;<b>'.&mt('Part').':</b> '.$display_part.' = '.
1.71      ng       4776: 		    (($oldstatus eq 'excused') ? 'excused' : $oldpts).
1.326     albertel 4777: 		    '&nbsp;<br />';
1.526     raeburn  4778: 		$displayPts[1].='&nbsp;<b>'.&mt('Part').':</b> '.$display_part.' = '.
1.125     ng       4779: 		     (($score eq 'excused') ? 'excused' : $newpts).
1.326     albertel 4780: 		    '&nbsp;<br />';
1.71      ng       4781: 		$question++;
1.380     albertel 4782: 		next if ($dropMenu eq 'reset status' || ($newpts eq $oldpts && $score ne 'excused'));
1.125     ng       4783: 
1.71      ng       4784: 		$newrecord{'resource.'.$partid.'.awarded'}  = $partial if $partial ne '';
1.125     ng       4785: 		$newrecord{'resource.'.$partid.'.solved'}   = $score if $score ne '';
1.257     albertel 4786: 		$newrecord{'resource.'.$partid.'.regrader'} = "$env{'user.name'}:$env{'user.domain'}"
1.125     ng       4787: 		    if (scalar(keys(%newrecord)) > 0);
1.71      ng       4788: 
                   4789: 		$changeflag++;
                   4790: 	    }
                   4791: 	    if (scalar(keys(%newrecord)) > 0) {
1.382     albertel 4792: 		my %record = 
                   4793: 		    &Apache::lonnet::restore($symbx,$env{'request.course.id'},
                   4794: 					     $udom,$uname);
                   4795: 
                   4796: 		if (&Apache::lonnet::validCODE($env{'form.CODE'})) {
                   4797: 		    $newrecord{'resource.CODE'} = $env{'form.CODE'};
                   4798: 		} elsif (&Apache::lonnet::validCODE($record{'resource.CODE'})) {
                   4799: 		    $newrecord{'resource.CODE'} = '';
                   4800: 		}
1.257     albertel 4801: 		&Apache::lonnet::cstore(\%newrecord,$symbx,$env{'request.course.id'},
1.71      ng       4802: 					$udom,$uname);
1.382     albertel 4803: 		%record = &Apache::lonnet::restore($symbx,
                   4804: 						   $env{'request.course.id'},
                   4805: 						   $udom,$uname);
1.380     albertel 4806: 		&check_and_remove_from_queue($parts,\%record,undef,$symbx,
                   4807: 					     $cdom,$cnum,$udom,$uname);
1.71      ng       4808: 	    }
1.380     albertel 4809: 	    
1.269     raeburn  4810:             if ($aggregateflag) {
                   4811:                 &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
                   4812:                       $env{'course.'.$env{'request.course.id'}.'.domain'},
                   4813:                       $env{'course.'.$env{'request.course.id'}.'.num'});
                   4814:             }
1.125     ng       4815: 
1.71      ng       4816: 	    $studentTable.='<td valign="top">'.$displayPts[0].'</td>'.
                   4817: 		'<td valign="top">'.$displayPts[1].'</td>'.
1.484     albertel 4818: 		&Apache::loncommon::end_data_table_row();
1.68      ng       4819: 
1.196     albertel 4820: 	    $prob++;
1.68      ng       4821: 	}
1.71      ng       4822:         $curRes = $iterator->next();
1.68      ng       4823:     }
1.98      albertel 4824: 
1.484     albertel 4825:     $studentTable.=&Apache::loncommon::end_data_table();
1.324     albertel 4826:     $studentTable.=&show_grading_menu_form($env{'form.symb'});
1.526     raeburn  4827:     my $grademsg=($changeflag == 0 ? &mt('No score was changed or updated.') :
                   4828: 		  &mt('The scores were changed for [quant,_1,problem].',
                   4829: 		  $changeflag));
1.76      ng       4830:     $request->print($grademsg.$studentTable);
1.68      ng       4831: 
1.70      ng       4832:     return '';
                   4833: }
                   4834: 
1.72      ng       4835: #-------- end of section for handling grading by page/sequence ---------
                   4836: #
                   4837: #-------------------------------------------------------------------
                   4838: 
1.581     www      4839: #-------------------- Bubblesheet (Scantron) Grading -------------------
1.75      albertel 4840: #
                   4841: #------ start of section for handling grading by page/sequence ---------
                   4842: 
1.423     albertel 4843: =pod
                   4844: 
                   4845: =head1 Bubble sheet grading routines
                   4846: 
1.424     albertel 4847:   For this documentation:
                   4848: 
                   4849:    'scanline' refers to the full line of characters
                   4850:    from the file that we are parsing that represents one entire sheet
                   4851: 
                   4852:    'bubble line' refers to the data
                   4853:    representing the line of bubbles that are on the physical bubble sheet
                   4854: 
                   4855: 
                   4856: The overall process is that a scanned in bubble sheet data is uploaded
                   4857: into a course. When a user wants to grade, they select a
                   4858: sequence/folder of resources, a file of bubble sheet info, and pick
                   4859: one of the predefined configurations for what each scanline looks
                   4860: like.
                   4861: 
                   4862: Next each scanline is checked for any errors of either 'missing
1.435     foxr     4863: bubbles' (it's an error because it may have been mis-scanned
1.424     albertel 4864: because too light bubbling), 'double bubble' (each bubble line should
                   4865: have no more that one letter picked), invalid or duplicated CODE,
1.556     weissno  4866: invalid student/employee ID
1.424     albertel 4867: 
                   4868: If the CODE option is used that determines the randomization of the
1.556     weissno  4869: homework problems, either way the student/employee ID is looked up into a
1.424     albertel 4870: username:domain.
                   4871: 
                   4872: During the validation phase the instructor can choose to skip scanlines. 
                   4873: 
1.435     foxr     4874: After the validation phase, there are now 3 bubble sheet files
1.424     albertel 4875: 
                   4876:   scantron_original_filename (unmodified original file)
                   4877:   scantron_corrected_filename (file where the corrected information has replaced the original information)
                   4878:   scantron_skipped_filename (contains the exact text of scanlines that where skipped)
                   4879: 
                   4880: Also there is a separate hash nohist_scantrondata that contains extra
                   4881: correction information that isn't representable in the bubble sheet
                   4882: file (see &scantron_getfile() for more information)
                   4883: 
                   4884: After all scanlines are either valid, marked as valid or skipped, then
                   4885: foreach line foreach problem in the picked sequence, an ssi request is
                   4886: made that simulates a user submitting their selected letter(s) against
                   4887: the homework problem.
1.423     albertel 4888: 
                   4889: =over 4
                   4890: 
                   4891: 
                   4892: 
                   4893: =item defaultFormData
                   4894: 
                   4895:   Returns html hidden inputs used to hold context/default values.
                   4896: 
                   4897:  Arguments:
                   4898:   $symb - $symb of the current resource 
                   4899: 
                   4900: =cut
1.422     foxr     4901: 
1.81      albertel 4902: sub defaultFormData {
1.324     albertel 4903:     my ($symb)=@_;
1.447     foxr     4904:     return '<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.257     albertel 4905:      '<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n".
                   4906:      '<input type="hidden" name="probTitle" value="'.$env{'form.probTitle'}.'" />'."\n";
1.81      albertel 4907: }
                   4908: 
1.447     foxr     4909: 
1.423     albertel 4910: =pod 
                   4911: 
                   4912: =item getSequenceDropDown
                   4913: 
                   4914:    Return html dropdown of possible sequences to grade
                   4915:  
                   4916:  Arguments:
1.582     raeburn  4917:    $symb - $symb of the current resource
                   4918:    $map_error - ref to scalar which will container error if
                   4919:                 $navmap object is unavailable in &getSymbMap().
1.423     albertel 4920: 
                   4921: =cut
1.422     foxr     4922: 
1.75      albertel 4923: sub getSequenceDropDown {
1.582     raeburn  4924:     my ($symb,$map_error)=@_;
1.75      albertel 4925:     my $result='<select name="selectpage">'."\n";
1.582     raeburn  4926:     my ($titles,$symbx) = &getSymbMap($map_error);
                   4927:     if (ref($map_error)) {
                   4928:         return if ($$map_error);
                   4929:     }
1.137     albertel 4930:     my ($curpage)=&Apache::lonnet::decode_symb($symb); 
1.75      albertel 4931:     my $ctr=0;
                   4932:     foreach (@$titles) {
                   4933: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
                   4934: 	$result.='<option value="'.$$symbx{$_}.'" '.
1.401     albertel 4935: 	    ($$symbx{$_} =~ /$curpage$/ ? 'selected="selected"' : '').
1.75      albertel 4936: 	    '>'.$showtitle.'</option>'."\n";
                   4937: 	$ctr++;
                   4938:     }
                   4939:     $result.= '</select>';
                   4940:     return $result;
                   4941: }
                   4942: 
1.495     albertel 4943: my %bubble_lines_per_response;     # no. bubble lines for each response.
1.554     raeburn  4944:                                    # key is zero-based index - 0, 1, 2 ...
1.495     albertel 4945: 
                   4946: my %first_bubble_line;             # First bubble line no. for each bubble.
                   4947: 
1.509     raeburn  4948: my %subdivided_bubble_lines;       # no. bubble lines for optionresponse, 
                   4949:                                    # matchresponse or rankresponse, where 
                   4950:                                    # an individual response can have multiple 
                   4951:                                    # lines
1.503     raeburn  4952: 
                   4953: my %responsetype_per_response;     # responsetype for each response
                   4954: 
1.495     albertel 4955: # Save and restore the bubble lines array to the form env.
                   4956: 
                   4957: 
                   4958: sub save_bubble_lines {
                   4959:     foreach my $line (keys(%bubble_lines_per_response)) {
                   4960: 	$env{"form.scantron.bubblelines.$line"}  = $bubble_lines_per_response{$line};
                   4961: 	$env{"form.scantron.first_bubble_line.$line"} =
                   4962: 	    $first_bubble_line{$line};
1.503     raeburn  4963:         $env{"form.scantron.sub_bubblelines.$line"} = 
                   4964:             $subdivided_bubble_lines{$line};
                   4965:         $env{"form.scantron.responsetype.$line"} =
                   4966:             $responsetype_per_response{$line};
1.495     albertel 4967:     }
                   4968: }
                   4969: 
                   4970: 
                   4971: sub restore_bubble_lines {
                   4972:     my $line = 0;
                   4973:     %bubble_lines_per_response = ();
                   4974:     while ($env{"form.scantron.bubblelines.$line"}) {
                   4975: 	my $value = $env{"form.scantron.bubblelines.$line"};
                   4976: 	$bubble_lines_per_response{$line} = $value;
                   4977: 	$first_bubble_line{$line}  =
                   4978: 	    $env{"form.scantron.first_bubble_line.$line"};
1.503     raeburn  4979:         $subdivided_bubble_lines{$line} =
                   4980:             $env{"form.scantron.sub_bubblelines.$line"};
                   4981:         $responsetype_per_response{$line} =
                   4982:             $env{"form.scantron.responsetype.$line"};
1.495     albertel 4983: 	$line++;
                   4984:     }
                   4985: }
                   4986: 
                   4987: #  Given the parsed scanline, get the response for 
                   4988: #  'answer' number n:
                   4989: 
                   4990: sub get_response_bubbles {
                   4991:     my ($parsed_line, $response)  = @_;
                   4992: 
                   4993:     my $bubble_line = $first_bubble_line{$response-1} +1;
                   4994:     my $bubble_lines= $bubble_lines_per_response{$response-1};
                   4995:     
                   4996:     my $selected = "";
                   4997: 
                   4998:     for (my $bline = 0; $bline < $bubble_lines; $bline++) {
                   4999: 	$selected .= $$parsed_line{"scantron.$bubble_line.answer"}.":";
                   5000: 	$bubble_line++;
                   5001:     }
                   5002:     return $selected;
                   5003: }
1.423     albertel 5004: 
                   5005: =pod 
                   5006: 
                   5007: =item scantron_filenames
                   5008: 
                   5009:    Returns a list of the scantron files in the current course 
                   5010: 
                   5011: =cut
1.422     foxr     5012: 
1.202     albertel 5013: sub scantron_filenames {
1.257     albertel 5014:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   5015:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
1.517     raeburn  5016:     my $getpropath = 1;
1.157     albertel 5017:     my @files=&Apache::lonnet::dirlist('userfiles',$cdom,$cname,
1.517     raeburn  5018:                                        $getpropath);
1.202     albertel 5019:     my @possiblenames;
1.201     albertel 5020:     foreach my $filename (sort(@files)) {
1.157     albertel 5021: 	($filename)=split(/&/,$filename);
                   5022: 	if ($filename!~/^scantron_orig_/) { next ; }
                   5023: 	$filename=~s/^scantron_orig_//;
1.202     albertel 5024: 	push(@possiblenames,$filename);
                   5025:     }
                   5026:     return @possiblenames;
                   5027: }
                   5028: 
1.423     albertel 5029: =pod 
                   5030: 
                   5031: =item scantron_uploads
                   5032: 
                   5033:    Returns  html drop-down list of scantron files in current course.
                   5034: 
                   5035:  Arguments:
                   5036:    $file2grade - filename to set as selected in the dropdown
                   5037: 
                   5038: =cut
1.422     foxr     5039: 
1.202     albertel 5040: sub scantron_uploads {
1.209     ng       5041:     my ($file2grade) = @_;
1.202     albertel 5042:     my $result=	'<select name="scantron_selectfile">';
                   5043:     $result.="<option></option>";
                   5044:     foreach my $filename (sort(&scantron_filenames())) {
1.401     albertel 5045: 	$result.="<option".($filename eq $file2grade ? ' selected="selected"':'').">$filename</option>\n";
1.81      albertel 5046:     }
                   5047:     $result.="</select>";
                   5048:     return $result;
                   5049: }
                   5050: 
1.423     albertel 5051: =pod 
                   5052: 
                   5053: =item scantron_scantab
                   5054: 
                   5055:   Returns html drop down of the scantron formats in the scantronformat.tab
                   5056:   file.
                   5057: 
                   5058: =cut
1.422     foxr     5059: 
1.82      albertel 5060: sub scantron_scantab {
                   5061:     my $result='<select name="scantron_format">'."\n";
1.191     albertel 5062:     $result.='<option></option>'."\n";
1.518     raeburn  5063:     my @lines = &get_scantronformat_file();
                   5064:     if (@lines > 0) {
                   5065:         foreach my $line (@lines) {
                   5066:             next if (($line =~ /^\#/) || ($line eq ''));
                   5067: 	    my ($name,$descrip)=split(/:/,$line);
                   5068: 	    $result.='<option value="'.$name.'">'.$descrip.'</option>'."\n";
                   5069:         }
1.82      albertel 5070:     }
                   5071:     $result.='</select>'."\n";
1.518     raeburn  5072:     return $result;
                   5073: }
                   5074: 
                   5075: =pod
                   5076: 
                   5077: =item get_scantronformat_file
                   5078: 
                   5079:   Returns an array containing lines from the scantron format file for
                   5080:   the domain of the course.
                   5081: 
                   5082:   If a url for a custom.tab file is listed in domain's configuration.db, 
                   5083:   lines are from this file.
                   5084: 
                   5085:   Otherwise, if a default.tab has been published in RES space by the 
                   5086:   domainconfig user, lines are from this file.
                   5087: 
                   5088:   Otherwise, fall back to getting lines from the legacy file on the
1.519     raeburn  5089:   local server:  /home/httpd/lonTabs/default_scantronformat.tab    
1.82      albertel 5090: 
1.518     raeburn  5091: =cut
                   5092: 
                   5093: sub get_scantronformat_file {
                   5094:     my $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
                   5095:     my %domconfig = &Apache::lonnet::get_dom('configuration',['scantron'],$cdom);
                   5096:     my $gottab = 0;
                   5097:     my @lines;
                   5098:     if (ref($domconfig{'scantron'}) eq 'HASH') {
                   5099:         if ($domconfig{'scantron'}{'scantronformat'} ne '') {
                   5100:             my $formatfile = &Apache::lonnet::getfile($Apache::lonnet::perlvar{'lonDocRoot'}.$domconfig{'scantron'}{'scantronformat'});
                   5101:             if ($formatfile ne '-1') {
                   5102:                 @lines = split("\n",$formatfile,-1);
                   5103:                 $gottab = 1;
                   5104:             }
                   5105:         }
                   5106:     }
                   5107:     if (!$gottab) {
                   5108:         my $confname = $cdom.'-domainconfig';
                   5109:         my $default = $Apache::lonnet::perlvar{'lonDocRoot'}.'/res/'.$cdom.'/'.$confname.'/default.tab';
                   5110:         my $formatfile =  &Apache::lonnet::getfile($default);
                   5111:         if ($formatfile ne '-1') {
                   5112:             @lines = split("\n",$formatfile,-1);
                   5113:             $gottab = 1;
                   5114:         }
                   5115:     }
                   5116:     if (!$gottab) {
1.519     raeburn  5117:         my @domains = &Apache::lonnet::current_machine_domains();
                   5118:         if (grep(/^\Q$cdom\E$/,@domains)) {
                   5119:             my $fh=Apache::File->new($Apache::lonnet::perlvar{'lonTabDir'}.'/scantronformat.tab');
                   5120:             @lines = <$fh>;
                   5121:             close($fh);
                   5122:         } else {
                   5123:             my $fh=Apache::File->new($Apache::lonnet::perlvar{'lonTabDir'}.'/default_scantronformat.tab');
                   5124:             @lines = <$fh>;
                   5125:             close($fh);
                   5126:         }
1.518     raeburn  5127:     }
                   5128:     return @lines;
1.82      albertel 5129: }
                   5130: 
1.423     albertel 5131: =pod 
                   5132: 
                   5133: =item scantron_CODElist
                   5134: 
                   5135:   Returns html drop down of the saved CODE lists from current course,
                   5136:   generated from earlier printings.
                   5137: 
                   5138: =cut
1.422     foxr     5139: 
1.186     albertel 5140: sub scantron_CODElist {
1.257     albertel 5141:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   5142:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
1.186     albertel 5143:     my @names=&Apache::lonnet::getkeys('CODEs',$cdom,$cnum);
                   5144:     my $namechoice='<option></option>';
1.225     albertel 5145:     foreach my $name (sort {uc($a) cmp uc($b)} @names) {
1.191     albertel 5146: 	if ($name =~ /^error: 2 /) { next; }
1.278     albertel 5147: 	if ($name =~ /^type\0/) { next; }
1.186     albertel 5148: 	$namechoice.='<option value="'.$name.'">'.$name.'</option>';
                   5149:     }
                   5150:     $namechoice='<select name="scantron_CODElist">'.$namechoice.'</select>';
                   5151:     return $namechoice;
                   5152: }
                   5153: 
1.423     albertel 5154: =pod 
                   5155: 
                   5156: =item scantron_CODEunique
                   5157: 
                   5158:   Returns the html for "Each CODE to be used once" radio.
                   5159: 
                   5160: =cut
1.422     foxr     5161: 
1.186     albertel 5162: sub scantron_CODEunique {
1.532     bisitz   5163:     my $result='<span class="LC_nobreak">
1.272     albertel 5164:                  <label><input type="radio" name="scantron_CODEunique"
1.423     albertel 5165:                         value="yes" checked="checked" />'.&mt('Yes').' </label>
1.381     albertel 5166:                 </span>
1.532     bisitz   5167:                 <span class="LC_nobreak">
1.272     albertel 5168:                  <label><input type="radio" name="scantron_CODEunique"
1.423     albertel 5169:                         value="no" />'.&mt('No').' </label>
1.381     albertel 5170:                 </span>';
1.186     albertel 5171:     return $result;
                   5172: }
1.423     albertel 5173: 
                   5174: =pod 
                   5175: 
                   5176: =item scantron_selectphase
                   5177: 
                   5178:   Generates the initial screen to start the bubble sheet process.
                   5179:   Allows for - starting a grading run.
1.424     albertel 5180:              - downloading existing scan data (original, corrected
1.423     albertel 5181:                                                 or skipped info)
                   5182: 
                   5183:              - uploading new scan data
                   5184: 
                   5185:  Arguments:
                   5186:   $r          - The Apache request object
                   5187:   $file2grade - name of the file that contain the scanned data to score
                   5188: 
                   5189: =cut
1.186     albertel 5190: 
1.75      albertel 5191: sub scantron_selectphase {
1.209     ng       5192:     my ($r,$file2grade) = @_;
1.324     albertel 5193:     my ($symb)=&get_symb($r);
1.75      albertel 5194:     if (!$symb) {return '';}
1.582     raeburn  5195:     my $map_error;
                   5196:     my $sequence_selector=&getSequenceDropDown($symb,\$map_error);
                   5197:     if ($map_error) {
                   5198:         $r->print('<br />'.&navmap_errormsg().'<br />');
                   5199:         return;
                   5200:     }
1.324     albertel 5201:     my $default_form_data=&defaultFormData($symb);
                   5202:     my $grading_menu_button=&show_grading_menu_form($symb);
1.209     ng       5203:     my $file_selector=&scantron_uploads($file2grade);
1.82      albertel 5204:     my $format_selector=&scantron_scantab();
1.186     albertel 5205:     my $CODE_selector=&scantron_CODElist();
                   5206:     my $CODE_unique=&scantron_CODEunique();
1.75      albertel 5207:     my $result;
1.422     foxr     5208: 
1.513     foxr     5209:     $ssi_error = 0;
                   5210: 
1.422     foxr     5211:     # Chunk of form to prompt for a file to grade and how:
                   5212: 
1.489     albertel 5213:     $result.= '
                   5214:     <br />
                   5215:     <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantron_process">
                   5216:     <input type="hidden" name="command" value="scantron_warning" />
                   5217:     '.$default_form_data.'
                   5218:     '.&Apache::loncommon::start_data_table('LC_scantron_action').'
                   5219:        '.&Apache::loncommon::start_data_table_header_row().'
                   5220:             <th colspan="2">
1.492     albertel 5221:               &nbsp;'.&mt('Specify file and which Folder/Sequence to grade').'
1.489     albertel 5222:             </th>
                   5223:        '.&Apache::loncommon::end_data_table_header_row().'
                   5224:        '.&Apache::loncommon::start_data_table_row().'
1.492     albertel 5225:             <td> '.&mt('Sequence to grade:').' </td><td> '.$sequence_selector.' </td>
1.489     albertel 5226:        '.&Apache::loncommon::end_data_table_row().'
                   5227:        '.&Apache::loncommon::start_data_table_row().'
1.572     www      5228:             <td> '.&mt('Filename of bubblesheet data file:').' </td><td> '.$file_selector.' </td>
1.489     albertel 5229:        '.&Apache::loncommon::end_data_table_row().'
                   5230:        '.&Apache::loncommon::start_data_table_row().'
1.572     www      5231:             <td> '.&mt('Format of bubblesheet data file:').' </td><td> '.$format_selector.' </td>
1.489     albertel 5232:        '.&Apache::loncommon::end_data_table_row().'
                   5233:        '.&Apache::loncommon::start_data_table_row().'
1.492     albertel 5234:             <td> '.&mt('Saved CODEs to validate against:').' </td><td> '.$CODE_selector.' </td>
1.489     albertel 5235:        '.&Apache::loncommon::end_data_table_row().'
                   5236:        '.&Apache::loncommon::start_data_table_row().'
1.492     albertel 5237:             <td> '.&mt('Each CODE is only to be used once:').'</td><td> '.$CODE_unique.' </td>
1.489     albertel 5238:        '.&Apache::loncommon::end_data_table_row().'
                   5239:        '.&Apache::loncommon::start_data_table_row().'
1.492     albertel 5240: 	    <td> '.&mt('Options:').' </td>
1.187     albertel 5241:             <td>
1.492     albertel 5242: 	       <label><input type="checkbox" name="scantron_options_redo" value="redo_skipped"/> '.&mt('Do only previously skipped records').'</label> <br />
                   5243:                <label><input type="checkbox" name="scantron_options_ignore" value="ignore_corrections"/> '.&mt('Remove all existing corrections').'</label> <br />
                   5244:                <label><input type="checkbox" name="scantron_options_hidden" value="ignore_hidden"/> '.&mt('Skip hidden resources when grading').'</label>
1.187     albertel 5245: 	    </td>
1.489     albertel 5246:        '.&Apache::loncommon::end_data_table_row().'
                   5247:        '.&Apache::loncommon::start_data_table_row().'
1.174     albertel 5248:             <td colspan="2">
1.572     www      5249:               <input type="submit" value="'.&mt('Grading: Validate Bubblesheet Records').'" />
1.162     albertel 5250:             </td>
1.489     albertel 5251:        '.&Apache::loncommon::end_data_table_row().'
                   5252:     '.&Apache::loncommon::end_data_table().'
                   5253:     </form>
                   5254: ';
1.162     albertel 5255:    
                   5256:     $r->print($result);
                   5257: 
1.257     albertel 5258:     if (&Apache::lonnet::allowed('usc',$env{'request.role.domain'}) ||
                   5259:         &Apache::lonnet::allowed('usc',$env{'request.course.id'})) {
1.162     albertel 5260: 
1.422     foxr     5261: 	# Chunk of form to prompt for a scantron file upload.
                   5262: 
1.489     albertel 5263:         $r->print('
                   5264:     <br />
                   5265:     '.&Apache::loncommon::start_data_table('LC_scantron_action').'
                   5266:        '.&Apache::loncommon::start_data_table_header_row().'
                   5267:             <th>
1.572     www      5268:               &nbsp;'.&mt('Specify a bubblesheet data file to upload.').'
1.489     albertel 5269:             </th>
                   5270:        '.&Apache::loncommon::end_data_table_header_row().'
                   5271:        '.&Apache::loncommon::start_data_table_row().'
1.162     albertel 5272:             <td>
1.489     albertel 5273: ');
1.324     albertel 5274:     my $default_form_data=&defaultFormData(&get_symb($r,1));
1.257     albertel 5275:     my $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
                   5276:     my $cnum= $env{'course.'.$env{'request.course.id'}.'.num'};
1.597     wenzelju 5277:     $r->print(&Apache::lonhtmlcommon::scripttag('
1.174     albertel 5278:     function checkUpload(formname) {
                   5279: 	if (formname.upfile.value == "") {
1.492     albertel 5280: 	    alert("'.&mt('Please use the browse button to select a file from your local directory.').'");
1.174     albertel 5281: 	    return false;
                   5282: 	}
                   5283: 	formname.submit();
1.597     wenzelju 5284:     }'));
                   5285:     $r->print('
1.492     albertel 5286:               <form enctype="multipart/form-data" action="/adm/grades" name="rules" method="post">
                   5287:                 '.$default_form_data.'
                   5288:                 <input name="courseid" type="hidden" value="'.$cnum.'" />
                   5289:                 <input name="domainid" type="hidden" value="'.$cdom.'" />
                   5290:                 <input name="command" value="scantronupload_save" type="hidden" />
                   5291:                 '.&mt('File to upload: [_1]','<input type="file" name="upfile" size="50" />').'
1.174     albertel 5292:                 <br />
1.589     bisitz   5293:                 <input type="button" onclick="javascript:checkUpload(this.form);" value="'.&mt('Upload Bubblesheet Data').'" />
1.174     albertel 5294:               </form>
1.492     albertel 5295: ');
1.162     albertel 5296: 
1.489     albertel 5297:         $r->print('
1.162     albertel 5298:             </td>
1.489     albertel 5299:        '.&Apache::loncommon::end_data_table_row().'
                   5300:        '.&Apache::loncommon::end_data_table().'
                   5301: ');
1.162     albertel 5302:     }
1.422     foxr     5303: 
                   5304:     # Chunk of the form that prompts to view a scoring office file,
                   5305:     # corrected file, skipped records in a file.
                   5306: 
1.489     albertel 5307:     $r->print('
                   5308:    <br />
                   5309:    <form action="/adm/grades" name="scantron_download">
                   5310:      '.$default_form_data.'
                   5311:      <input type="hidden" name="command" value="scantron_download" />
                   5312:      '.&Apache::loncommon::start_data_table('LC_scantron_action').'
                   5313:        '.&Apache::loncommon::start_data_table_header_row().'
                   5314:               <th>
1.492     albertel 5315:                 &nbsp;'.&mt('Download a scoring office file').'
1.489     albertel 5316:               </th>
                   5317:        '.&Apache::loncommon::end_data_table_header_row().'
                   5318:        '.&Apache::loncommon::start_data_table_row().'
1.492     albertel 5319:               <td> '.&mt('Filename of scoring office file: [_1]',$file_selector).' 
1.489     albertel 5320:                 <br />
1.492     albertel 5321:                 <input type="submit" value="'.&mt('Download: Show List of Associated Files').'" />
1.489     albertel 5322:        '.&Apache::loncommon::end_data_table_row().'
                   5323:      '.&Apache::loncommon::end_data_table().'
                   5324:    </form>
                   5325:    <br />
                   5326: ');
1.162     albertel 5327: 
1.457     banghart 5328:     &Apache::lonpickcode::code_list($r,2);
1.523     raeburn  5329: 
1.528     raeburn  5330:     $r->print('<br /><form method="post" name="checkscantron">'.
1.523     raeburn  5331:              $default_form_data."\n".
                   5332:              &Apache::loncommon::start_data_table('LC_scantron_action')."\n".
                   5333:              &Apache::loncommon::start_data_table_header_row()."\n".
                   5334:              '<th colspan="2">
1.572     www      5335:               &nbsp;'.&mt('Review bubblesheet data and submissions for a previously graded folder/sequence')."\n".
1.523     raeburn  5336:              '</th>'."\n".
                   5337:               &Apache::loncommon::end_data_table_header_row()."\n".
                   5338:               &Apache::loncommon::start_data_table_row()."\n".
                   5339:               '<td> '.&mt('Graded folder/sequence:').' </td>'."\n".
                   5340:               '<td> '.$sequence_selector.' </td>'.
                   5341:               &Apache::loncommon::end_data_table_row()."\n".
                   5342:               &Apache::loncommon::start_data_table_row()."\n".
                   5343:               '<td> '.&mt('Filename of scoring office file:').' </td>'."\n".
                   5344:               '<td> '.$file_selector.' </td>'."\n".
                   5345:               &Apache::loncommon::end_data_table_row()."\n".
                   5346:               &Apache::loncommon::start_data_table_row()."\n".
                   5347:               '<td> '.&mt('Format of data file:').' </td>'."\n".
                   5348:               '<td> '.$format_selector.' </td>'."\n".
                   5349:               &Apache::loncommon::end_data_table_row()."\n".
                   5350:               &Apache::loncommon::start_data_table_row()."\n".
1.557     raeburn  5351:               '<td> '.&mt('Options').' </td>'."\n".
                   5352:               '<td> <label><input type="checkbox" name="scantron_options_hidden" value="ignore_hidden"/> '.&mt('Skip hidden resources').'</label></td>'.
                   5353:               &Apache::loncommon::end_data_table_row()."\n".
                   5354:               &Apache::loncommon::start_data_table_row()."\n".
1.523     raeburn  5355:               '<td colspan="2">'."\n".
                   5356:               '<input type="hidden" name="command" value="checksubmissions" />'."\n".
1.575     www      5357:               '<input type="submit" value="'.&mt('Review Bubblesheet Data and Submission Records').'" />'."\n".
1.523     raeburn  5358:               '</td>'."\n".
                   5359:               &Apache::loncommon::end_data_table_row()."\n".
                   5360:               &Apache::loncommon::end_data_table()."\n".
                   5361:               '</form><br />');
1.457     banghart 5362:     $r->print($grading_menu_button);
1.523     raeburn  5363:     return;
1.75      albertel 5364: }
                   5365: 
1.423     albertel 5366: =pod
                   5367: 
                   5368: =item get_scantron_config
                   5369: 
                   5370:    Parse and return the scantron configuration line selected as a
                   5371:    hash of configuration file fields.
                   5372: 
                   5373:  Arguments:
                   5374:     which - the name of the configuration to parse from the file.
                   5375: 
                   5376: 
                   5377:  Returns:
                   5378:             If the named configuration is not in the file, an empty
                   5379:             hash is returned.
                   5380:     a hash with the fields
                   5381:       name         - internal name for the this configuration setup
                   5382:       description  - text to display to operator that describes this config
                   5383:       CODElocation - if 0 or the string 'none'
                   5384:                           - no CODE exists for this config
                   5385:                      if -1 || the string 'letter'
                   5386:                           - a CODE exists for this config and is
                   5387:                             a string of letters
                   5388:                      Unsupported value (but planned for future support)
                   5389:                           if a positive integer
                   5390:                                - The CODE exists as the first n items from
                   5391:                                  the question section of the form
                   5392:                           if the string 'number'
                   5393:                                - The CODE exists for this config and is
                   5394:                                  a string of numbers
                   5395:       CODEstart   - (only matter if a CODE exists) column in the line where
                   5396:                      the CODE starts
                   5397:       CODElength  - length of the CODE
1.573     bisitz   5398:       IDstart     - column where the student/employee ID starts
1.556     weissno  5399:       IDlength    - length of the student/employee ID info
1.423     albertel 5400:       Qstart      - column where the information from the bubbled
                   5401:                     'questions' start
                   5402:       Qlength     - number of columns comprising a single bubble line from
                   5403:                     the sheet. (usually either 1 or 10)
1.424     albertel 5404:       Qon         - either a single character representing the character used
1.423     albertel 5405:                     to signal a bubble was chosen in the positional setup, or
                   5406:                     the string 'letter' if the letter of the chosen bubble is
                   5407:                     in the final, or 'number' if a number representing the
                   5408:                     chosen bubble is in the file (1->A 0->J)
1.424     albertel 5409:       Qoff        - the character used to represent that a bubble was
                   5410:                     left blank
1.423     albertel 5411:       PaperID     - if the scanning process generates a unique number for each
                   5412:                     sheet scanned the column that this ID number starts in
                   5413:       PaperIDlength - number of columns that comprise the unique ID number
                   5414:                       for the sheet of paper
1.424     albertel 5415:       FirstName   - column that the first name starts in
1.423     albertel 5416:       FirstNameLength - number of columns that the first name spans
                   5417:  
                   5418:       LastName    - column that the last name starts in
                   5419:       LastNameLength - number of columns that the last name spans
                   5420: 
                   5421: =cut
1.422     foxr     5422: 
1.82      albertel 5423: sub get_scantron_config {
                   5424:     my ($which) = @_;
1.518     raeburn  5425:     my @lines = &get_scantronformat_file();
1.82      albertel 5426:     my %config;
1.157     albertel 5427:     #FIXME probably should move to XML it has already gotten a bit much now
1.518     raeburn  5428:     foreach my $line (@lines) {
1.82      albertel 5429: 	my ($name,$descrip)=split(/:/,$line);
                   5430: 	if ($name ne $which ) { next; }
                   5431: 	chomp($line);
                   5432: 	my @config=split(/:/,$line);
                   5433: 	$config{'name'}=$config[0];
                   5434: 	$config{'description'}=$config[1];
                   5435: 	$config{'CODElocation'}=$config[2];
                   5436: 	$config{'CODEstart'}=$config[3];
                   5437: 	$config{'CODElength'}=$config[4];
                   5438: 	$config{'IDstart'}=$config[5];
                   5439: 	$config{'IDlength'}=$config[6];
                   5440: 	$config{'Qstart'}=$config[7];
1.497     foxr     5441:  	$config{'Qlength'}=$config[8];
1.82      albertel 5442: 	$config{'Qoff'}=$config[9];
                   5443: 	$config{'Qon'}=$config[10];
1.157     albertel 5444: 	$config{'PaperID'}=$config[11];
                   5445: 	$config{'PaperIDlength'}=$config[12];
                   5446: 	$config{'FirstName'}=$config[13];
                   5447: 	$config{'FirstNamelength'}=$config[14];
                   5448: 	$config{'LastName'}=$config[15];
                   5449: 	$config{'LastNamelength'}=$config[16];
1.82      albertel 5450: 	last;
                   5451:     }
                   5452:     return %config;
                   5453: }
                   5454: 
1.423     albertel 5455: =pod 
                   5456: 
                   5457: =item username_to_idmap
                   5458: 
1.556     weissno  5459:     creates a hash keyed by student/employee ID with values of the corresponding
1.423     albertel 5460:     student username:domain.
                   5461: 
                   5462:   Arguments:
                   5463: 
                   5464:     $classlist - reference to the class list hash. This is a hash
                   5465:                  keyed by student name:domain  whose elements are references
1.424     albertel 5466:                  to arrays containing various chunks of information
1.423     albertel 5467:                  about the student. (See loncoursedata for more info).
                   5468: 
                   5469:   Returns
                   5470:     %idmap - the constructed hash
                   5471: 
                   5472: =cut
                   5473: 
1.82      albertel 5474: sub username_to_idmap {
                   5475:     my ($classlist)= @_;
                   5476:     my %idmap;
                   5477:     foreach my $student (keys(%$classlist)) {
                   5478: 	$idmap{$classlist->{$student}->[&Apache::loncoursedata::CL_ID]}=
                   5479: 	    $student;
                   5480:     }
                   5481:     return %idmap;
                   5482: }
1.423     albertel 5483: 
                   5484: =pod
                   5485: 
1.424     albertel 5486: =item scantron_fixup_scanline
1.423     albertel 5487: 
                   5488:    Process a requested correction to a scanline.
                   5489: 
                   5490:   Arguments:
                   5491:     $scantron_config   - hash from &get_scantron_config()
                   5492:     $scan_data         - hash of correction information 
                   5493:                           (see &scantron_getfile())
                   5494:     $line              - existing scanline
                   5495:     $whichline         - line number of the passed in scanline
                   5496:     $field             - type of change to process 
                   5497:                          (either 
1.573     bisitz   5498:                           'ID'     -> correct the student/employee ID
1.423     albertel 5499:                           'CODE'   -> correct the CODE
                   5500:                           'answer' -> fixup the submitted answers)
                   5501:     
                   5502:    $args               - hash of additional info,
                   5503:                           - 'ID' 
                   5504:                                'newid' -> studentID to use in replacement
1.424     albertel 5505:                                           of existing one
1.423     albertel 5506:                           - 'CODE' 
                   5507:                                'CODE_ignore_dup' - set to true if duplicates
                   5508:                                                    should be ignored.
                   5509: 	                       'CODE' - is new code or 'use_unfound'
1.424     albertel 5510:                                         if the existing unfound code should
1.423     albertel 5511:                                         be used as is
                   5512:                           - 'answer'
                   5513:                                'response' - new answer or 'none' if blank
                   5514:                                'question' - the bubble line to change
1.503     raeburn  5515:                                'questionnum' - the question identifier,
                   5516:                                                may include subquestion. 
1.423     albertel 5517: 
                   5518:   Returns:
                   5519:     $line - the modified scanline
                   5520: 
                   5521:   Side effects: 
                   5522:     $scan_data - may be updated
                   5523: 
                   5524: =cut
                   5525: 
1.82      albertel 5526: 
1.157     albertel 5527: sub scantron_fixup_scanline {
                   5528:     my ($scantron_config,$scan_data,$line,$whichline,$field,$args)=@_;
                   5529:     if ($field eq 'ID') {
                   5530: 	if (length($args->{'newid'}) > $$scantron_config{'IDlength'}) {
1.186     albertel 5531: 	    return ($line,1,'New value too large');
1.157     albertel 5532: 	}
                   5533: 	if (length($args->{'newid'}) < $$scantron_config{'IDlength'}) {
                   5534: 	    $args->{'newid'}=sprintf('%-'.$$scantron_config{'IDlength'}.'s',
                   5535: 				     $args->{'newid'});
                   5536: 	}
                   5537: 	substr($line,$$scantron_config{'IDstart'}-1,
                   5538: 	       $$scantron_config{'IDlength'})=$args->{'newid'};
                   5539: 	if ($args->{'newid'}=~/^\s*$/) {
                   5540: 	    &scan_data($scan_data,"$whichline.user",
                   5541: 		       $args->{'username'}.':'.$args->{'domain'});
                   5542: 	}
1.186     albertel 5543:     } elsif ($field eq 'CODE') {
1.192     albertel 5544: 	if ($args->{'CODE_ignore_dup'}) {
                   5545: 	    &scan_data($scan_data,"$whichline.CODE_ignore_dup",'1');
                   5546: 	}
                   5547: 	&scan_data($scan_data,"$whichline.useCODE",'1');
                   5548: 	if ($args->{'CODE'} ne 'use_unfound') {
1.191     albertel 5549: 	    if (length($args->{'CODE'}) > $$scantron_config{'CODElength'}) {
                   5550: 		return ($line,1,'New CODE value too large');
                   5551: 	    }
                   5552: 	    if (length($args->{'CODE'}) < $$scantron_config{'CODElength'}) {
                   5553: 		$args->{'CODE'}=sprintf('%-'.$$scantron_config{'CODElength'}.'s',$args->{'CODE'});
                   5554: 	    }
                   5555: 	    substr($line,$$scantron_config{'CODEstart'}-1,
                   5556: 		   $$scantron_config{'CODElength'})=$args->{'CODE'};
1.186     albertel 5557: 	}
1.157     albertel 5558:     } elsif ($field eq 'answer') {
1.497     foxr     5559: 	my $length=$scantron_config->{'Qlength'};
1.157     albertel 5560: 	my $off=$scantron_config->{'Qoff'};
                   5561: 	my $on=$scantron_config->{'Qon'};
1.497     foxr     5562: 	my $answer=${off}x$length;
                   5563: 	if ($args->{'response'} eq 'none') {
                   5564: 	    &scan_data($scan_data,
1.503     raeburn  5565: 		       "$whichline.no_bubble.".$args->{'questionnum'},'1');
1.497     foxr     5566: 	} else {
                   5567: 	    if ($on eq 'letter') {
                   5568: 		my @alphabet=('A'..'Z');
                   5569: 		$answer=$alphabet[$args->{'response'}];
                   5570: 	    } elsif ($on eq 'number') {
                   5571: 		$answer=$args->{'response'}+1;
                   5572: 		if ($answer == 10) { $answer = '0'; }
1.274     albertel 5573: 	    } else {
1.497     foxr     5574: 		substr($answer,$args->{'response'},1)=$on;
1.274     albertel 5575: 	    }
1.497     foxr     5576: 	    &scan_data($scan_data,
1.503     raeburn  5577: 		       "$whichline.no_bubble.".$args->{'questionnum'},undef,'1');
1.157     albertel 5578: 	}
1.497     foxr     5579: 	my $where=$length*($args->{'question'}-1)+$scantron_config->{'Qstart'};
                   5580: 	substr($line,$where-1,$length)=$answer;
1.157     albertel 5581:     }
                   5582:     return $line;
                   5583: }
1.423     albertel 5584: 
                   5585: =pod
                   5586: 
                   5587: =item scan_data
                   5588: 
                   5589:     Edit or look up  an item in the scan_data hash.
                   5590: 
                   5591:   Arguments:
                   5592:     $scan_data  - The hash (see scantron_getfile)
                   5593:     $key        - shorthand of the key to edit (actual key is
1.424     albertel 5594:                   scantronfilename_key).
1.423     albertel 5595:     $data        - New value of the hash entry.
                   5596:     $delete      - If true, the entry is removed from the hash.
                   5597: 
                   5598:   Returns:
                   5599:     The new value of the hash table field (undefined if deleted).
                   5600: 
                   5601: =cut
                   5602: 
                   5603: 
1.157     albertel 5604: sub scan_data {
                   5605:     my ($scan_data,$key,$value,$delete)=@_;
1.257     albertel 5606:     my $filename=$env{'form.scantron_selectfile'};
1.157     albertel 5607:     if (defined($value)) {
                   5608: 	$scan_data->{$filename.'_'.$key} = $value;
                   5609:     }
                   5610:     if ($delete) { delete($scan_data->{$filename.'_'.$key}); }
                   5611:     return $scan_data->{$filename.'_'.$key};
                   5612: }
1.423     albertel 5613: 
1.495     albertel 5614: # ----- These first few routines are general use routines.----
                   5615: 
                   5616: # Return the number of occurences of a pattern in a string.
                   5617: 
                   5618: sub occurence_count {
                   5619:     my ($string, $pattern) = @_;
                   5620: 
                   5621:     my @matches = ($string =~ /$pattern/g);
                   5622: 
                   5623:     return scalar(@matches);
                   5624: }
                   5625: 
                   5626: 
                   5627: # Take a string known to have digits and convert all the
                   5628: # digits into letters in the range J,A..I.
                   5629: 
                   5630: sub digits_to_letters {
                   5631:     my ($input) = @_;
                   5632: 
                   5633:     my @alphabet = ('J', 'A'..'I');
                   5634: 
                   5635:     my @input    = split(//, $input);
                   5636:     my $output ='';
                   5637:     for (my $i = 0; $i < scalar(@input); $i++) {
                   5638: 	if ($input[$i] =~ /\d/) {
                   5639: 	    $output .= $alphabet[$input[$i]];
                   5640: 	} else {
                   5641: 	    $output .= $input[$i];
                   5642: 	}
                   5643:     }
                   5644:     return $output;
                   5645: }
                   5646: 
1.423     albertel 5647: =pod 
                   5648: 
                   5649: =item scantron_parse_scanline
                   5650: 
                   5651:   Decodes a scanline from the selected scantron file
                   5652: 
                   5653:  Arguments:
                   5654:     line             - The text of the scantron file line to process
                   5655:     whichline        - Line number
                   5656:     scantron_config  - Hash describing the format of the scantron lines.
                   5657:     scan_data        - Hash of extra information about the scanline
                   5658:                        (see scantron_getfile for more information)
                   5659:     just_header      - True if should not process question answers but only
                   5660:                        the stuff to the left of the answers.
                   5661:  Returns:
                   5662:    Hash containing the result of parsing the scanline
                   5663: 
                   5664:    Keys are all proceeded by the string 'scantron.'
                   5665: 
                   5666:        CODE    - the CODE in use for this scanline
                   5667:        useCODE - 1 if the CODE is invalid but it usage has been forced
                   5668:                  by the operator
                   5669:        CODE_ignore_dup - 1 if the CODE is a duplicated use when unique
                   5670:                             CODEs were selected, but the usage has been
                   5671:                             forced by the operator
1.556     weissno  5672:        ID  - student/employee ID
1.423     albertel 5673:        PaperID - if used, the ID number printed on the sheet when the 
                   5674:                  paper was scanned
                   5675:        FirstName - first name from the sheet
                   5676:        LastName  - last name from the sheet
                   5677: 
                   5678:      if just_header was not true these key may also exist
                   5679: 
1.447     foxr     5680:        missingerror - a list of bubble ranges that are considered to be answers
                   5681:                       to a single question that don't have any bubbles filled in.
                   5682:                       Of the form questionnumber:firstbubblenumber:count.
                   5683:        doubleerror  - a list of bubble ranges that are considered to be answers
                   5684:                       to a single question that have more than one bubble filled in.
                   5685:                       Of the form questionnumber::firstbubblenumber:count
                   5686:    
                   5687:                 In the above, count is the number of bubble responses in the
                   5688:                 input line needed to represent the possible answers to the question.
                   5689:                 e.g. a radioresponse with 15 choices in an answer sheet with 10 choices
                   5690:                 per line would have count = 2.
                   5691: 
1.423     albertel 5692:        maxquest     - the number of the last bubble line that was parsed
                   5693: 
                   5694:        (<number> starts at 1)
                   5695:        <number>.answer - zero or more letters representing the selected
                   5696:                          letters from the scanline for the bubble line 
                   5697:                          <number>.
                   5698:                          if blank there was either no bubble or there where
                   5699:                          multiple bubbles, (consult the keys missingerror and
                   5700:                          doubleerror if this is an error condition)
                   5701: 
                   5702: =cut
                   5703: 
1.82      albertel 5704: sub scantron_parse_scanline {
1.423     albertel 5705:     my ($line,$whichline,$scantron_config,$scan_data,$just_header)=@_;
1.470     foxr     5706: 
1.82      albertel 5707:     my %record;
1.550     raeburn  5708:     my $lastpos = $env{'form.scantron_maxbubble'}*$$scantron_config{'Qlength'};
                   5709:     my $questions=substr($line,$$scantron_config{'Qstart'}-1,$lastpos);  # Answers
1.422     foxr     5710:     my $data=substr($line,0,$$scantron_config{'Qstart'}-1);     # earlier stuff
1.278     albertel 5711:     if (!($$scantron_config{'CODElocation'} eq 0 ||
                   5712: 	  $$scantron_config{'CODElocation'} eq 'none')) {
                   5713: 	if ($$scantron_config{'CODElocation'} < 0 ||
                   5714: 	    $$scantron_config{'CODElocation'} eq 'letter' ||
                   5715: 	    $$scantron_config{'CODElocation'} eq 'number') {
1.191     albertel 5716: 	    $record{'scantron.CODE'}=substr($data,
                   5717: 					    $$scantron_config{'CODEstart'}-1,
1.83      albertel 5718: 					    $$scantron_config{'CODElength'});
1.191     albertel 5719: 	    if (&scan_data($scan_data,"$whichline.useCODE")) {
                   5720: 		$record{'scantron.useCODE'}=1;
                   5721: 	    }
1.192     albertel 5722: 	    if (&scan_data($scan_data,"$whichline.CODE_ignore_dup")) {
                   5723: 		$record{'scantron.CODE_ignore_dup'}=1;
                   5724: 	    }
1.82      albertel 5725: 	} else {
                   5726: 	    #FIXME interpret first N questions
                   5727: 	}
                   5728:     }
1.83      albertel 5729:     $record{'scantron.ID'}=substr($data,$$scantron_config{'IDstart'}-1,
                   5730: 				  $$scantron_config{'IDlength'});
1.157     albertel 5731:     $record{'scantron.PaperID'}=
                   5732: 	substr($data,$$scantron_config{'PaperID'}-1,
                   5733: 	       $$scantron_config{'PaperIDlength'});
                   5734:     $record{'scantron.FirstName'}=
                   5735: 	substr($data,$$scantron_config{'FirstName'}-1,
                   5736: 	       $$scantron_config{'FirstNamelength'});
                   5737:     $record{'scantron.LastName'}=
                   5738: 	substr($data,$$scantron_config{'LastName'}-1,
                   5739: 	       $$scantron_config{'LastNamelength'});
1.423     albertel 5740:     if ($just_header) { return \%record; }
1.194     albertel 5741: 
1.82      albertel 5742:     my @alphabet=('A'..'Z');
                   5743:     my $questnum=0;
1.447     foxr     5744:     my $ansnum  =1;		# Multiple 'answer lines'/question.
                   5745: 
1.470     foxr     5746:     chomp($questions);		# Get rid of any trailing \n.
                   5747:     $questions =~ s/\r$//;      # Get rid of trailing \r too (MAC or Win uploads).
                   5748:     while (length($questions)) {
1.447     foxr     5749: 	my $answers_needed = $bubble_lines_per_response{$questnum};
1.503     raeburn  5750:         my $answer_length  = ($$scantron_config{'Qlength'} * $answers_needed)
                   5751:                              || 1;
                   5752:         $questnum++;
                   5753:         my $quest_id = $questnum;
                   5754:         my $currentquest = substr($questions,0,$answer_length);
                   5755:         $questions       = substr($questions,$answer_length);
                   5756:         if (length($currentquest) < $answer_length) { next; }
                   5757: 
                   5758:         if ($subdivided_bubble_lines{$questnum-1} =~ /,/) {
                   5759:             my $subquestnum = 1;
                   5760:             my $subquestions = $currentquest;
                   5761:             my @subanswers_needed = 
                   5762:                 split(/,/,$subdivided_bubble_lines{$questnum-1});  
                   5763:             foreach my $subans (@subanswers_needed) {
                   5764:                 my $subans_length =
                   5765:                     ($$scantron_config{'Qlength'} * $subans)  || 1;
                   5766:                 my $currsubquest = substr($subquestions,0,$subans_length);
                   5767:                 $subquestions   = substr($subquestions,$subans_length);
                   5768:                 $quest_id = "$questnum.$subquestnum";
                   5769:                 if (($$scantron_config{'Qon'} eq 'letter') ||
                   5770:                     ($$scantron_config{'Qon'} eq 'number')) {
                   5771:                     $ansnum = &scantron_validator_lettnum($ansnum, 
                   5772:                         $questnum,$quest_id,$subans,$currsubquest,$whichline,
                   5773:                         \@alphabet,\%record,$scantron_config,$scan_data);
                   5774:                 } else {
                   5775:                     $ansnum = &scantron_validator_positional($ansnum,
                   5776:                         $questnum,$quest_id,$subans,$currsubquest,$whichline,                        \@alphabet,\%record,$scantron_config,$scan_data);
                   5777:                 }
                   5778:                 $subquestnum ++;
                   5779:             }
                   5780:         } else {
                   5781:             if (($$scantron_config{'Qon'} eq 'letter') ||
                   5782:                 ($$scantron_config{'Qon'} eq 'number')) {
                   5783:                 $ansnum = &scantron_validator_lettnum($ansnum,$questnum,
                   5784:                     $quest_id,$answers_needed,$currentquest,$whichline,
                   5785:                     \@alphabet,\%record,$scantron_config,$scan_data);
                   5786:             } else {
                   5787:                 $ansnum = &scantron_validator_positional($ansnum,$questnum,
                   5788:                     $quest_id,$answers_needed,$currentquest,$whichline,
                   5789:                     \@alphabet,\%record,$scantron_config,$scan_data);
                   5790:             }
                   5791:         }
                   5792:     }
                   5793:     $record{'scantron.maxquest'}=$questnum;
                   5794:     return \%record;
                   5795: }
1.447     foxr     5796: 
1.503     raeburn  5797: sub scantron_validator_lettnum {
                   5798:     my ($ansnum,$questnum,$quest_id,$answers_needed,$currquest,$whichline,
                   5799:         $alphabet,$record,$scantron_config,$scan_data) = @_;
                   5800: 
                   5801:     # Qon 'letter' implies for each slot in currquest we have:
                   5802:     #    ? or * for doubles, a letter in A-Z for a bubble, and
                   5803:     #    about anything else (esp. a value of Qoff) for missing
                   5804:     #    bubbles.
                   5805:     #
                   5806:     # Qon 'number' implies each slot gives a digit that indexes the
                   5807:     #    bubbles filled, or Qoff, or a non-number for unbubbled lines,
                   5808:     #    and * or ? for double bubbles on a single line.
                   5809:     #
1.447     foxr     5810: 
1.503     raeburn  5811:     my $matchon;
                   5812:     if ($$scantron_config{'Qon'} eq 'letter') {
                   5813:         $matchon = '[A-Z]';
                   5814:     } elsif ($$scantron_config{'Qon'} eq 'number') {
                   5815:         $matchon = '\d';
                   5816:     }
                   5817:     my $occurrences = 0;
                   5818:     if (($responsetype_per_response{$questnum-1} eq 'essayresponse') ||
                   5819:         ($responsetype_per_response{$questnum-1} eq 'formularesponse') ||
1.510     raeburn  5820:         ($responsetype_per_response{$questnum-1} eq 'stringresponse') ||
                   5821:         ($responsetype_per_response{$questnum-1} eq 'imageresponse') ||
                   5822:         ($responsetype_per_response{$questnum-1} eq 'reactionresponse') ||
                   5823:         ($responsetype_per_response{$questnum-1} eq 'organicresponse')) {
1.503     raeburn  5824:         my @singlelines = split('',$currquest);
                   5825:         foreach my $entry (@singlelines) {
                   5826:             $occurrences = &occurence_count($entry,$matchon);
                   5827:             if ($occurrences > 1) {
                   5828:                 last;
                   5829:             }
                   5830:         } 
                   5831:     } else {
                   5832:         $occurrences = &occurence_count($currquest,$matchon); 
                   5833:     }
                   5834:     if (($currquest =~ /\?/ || $currquest =~ /\*/) || ($occurrences > 1)) {
                   5835:         push(@{$record->{'scantron.doubleerror'}},$quest_id);
                   5836:         for (my $ans=0; $ans<$answers_needed; $ans++) {
                   5837:             my $bubble = substr($currquest,$ans,1);
                   5838:             if ($bubble =~ /$matchon/ ) {
                   5839:                 if ($$scantron_config{'Qon'} eq 'number') {
                   5840:                     if ($bubble == 0) {
                   5841:                         $bubble = 10; 
                   5842:                     }
                   5843:                     $record->{"scantron.$ansnum.answer"} = 
                   5844:                         $alphabet->[$bubble-1];
                   5845:                 } else {
                   5846:                     $record->{"scantron.$ansnum.answer"} = $bubble;
                   5847:                 }
                   5848:             } else {
                   5849:                 $record->{"scantron.$ansnum.answer"}='';
                   5850:             }
                   5851:             $ansnum++;
                   5852:         }
                   5853:     } elsif (!defined($currquest)
                   5854:             || (&occurence_count($currquest, $$scantron_config{'Qoff'}) == length($currquest))
                   5855:             || (&occurence_count($currquest,$matchon) == 0)) {
                   5856:         for (my $ans=0; $ans<$answers_needed; $ans++ ) {
                   5857:             $record->{"scantron.$ansnum.answer"}='';
                   5858:             $ansnum++;
                   5859:         }
                   5860:         if (!&scan_data($scan_data,"$whichline.no_bubble.$quest_id")) {
                   5861:             push(@{$record->{'scantron.missingerror'}},$quest_id);
                   5862:         }
                   5863:     } else {
                   5864:         if ($$scantron_config{'Qon'} eq 'number') {
                   5865:             $currquest = &digits_to_letters($currquest);            
                   5866:         }
                   5867:         for (my $ans=0; $ans<$answers_needed; $ans++) {
                   5868:             my $bubble = substr($currquest,$ans,1);
                   5869:             $record->{"scantron.$ansnum.answer"} = $bubble;
                   5870:             $ansnum++;
                   5871:         }
                   5872:     }
                   5873:     return $ansnum;
                   5874: }
1.447     foxr     5875: 
1.503     raeburn  5876: sub scantron_validator_positional {
                   5877:     my ($ansnum,$questnum,$quest_id,$answers_needed,$currquest,
                   5878:         $whichline,$alphabet,$record,$scantron_config,$scan_data) = @_;
1.447     foxr     5879: 
1.503     raeburn  5880:     # Otherwise there's a positional notation;
                   5881:     # each bubble line requires Qlength items, and there are filled in
                   5882:     # bubbles for each case where there 'Qon' characters.
                   5883:     #
1.447     foxr     5884: 
1.503     raeburn  5885:     my @array=split($$scantron_config{'Qon'},$currquest,-1);
1.447     foxr     5886: 
1.503     raeburn  5887:     # If the split only gives us one element.. the full length of the
                   5888:     # answer string, no bubbles are filled in:
1.447     foxr     5889: 
1.507     raeburn  5890:     if ($answers_needed eq '') {
                   5891:         return;
                   5892:     }
                   5893: 
1.503     raeburn  5894:     if (length($array[0]) eq $$scantron_config{'Qlength'}*$answers_needed) {
                   5895:         for (my $ans=0; $ans<$answers_needed; $ans++ ) {
                   5896:             $record->{"scantron.$ansnum.answer"}='';
                   5897:             $ansnum++;
                   5898:         }
                   5899:         if (!&scan_data($scan_data,"$whichline.no_bubble.$quest_id")) {
                   5900:             push(@{$record->{"scantron.missingerror"}},$quest_id);
                   5901:         }
                   5902:     } elsif (scalar(@array) == 2) {
                   5903:         my $location = length($array[0]);
                   5904:         my $line_num = int($location / $$scantron_config{'Qlength'});
                   5905:         my $bubble   = $alphabet->[$location % $$scantron_config{'Qlength'}];
                   5906:         for (my $ans=0; $ans<$answers_needed; $ans++) {
                   5907:             if ($ans eq $line_num) {
                   5908:                 $record->{"scantron.$ansnum.answer"} = $bubble;
                   5909:             } else {
                   5910:                 $record->{"scantron.$ansnum.answer"} = ' ';
                   5911:             }
                   5912:             $ansnum++;
                   5913:          }
                   5914:     } else {
                   5915:         #  If there's more than one instance of a bubble character
                   5916:         #  That's a double bubble; with positional notation we can
                   5917:         #  record all the bubbles filled in as well as the
                   5918:         #  fact this response consists of multiple bubbles.
                   5919:         #
                   5920:         if (($responsetype_per_response{$questnum-1} eq 'essayresponse') ||
                   5921:             ($responsetype_per_response{$questnum-1} eq 'formularesponse') ||
1.510     raeburn  5922:             ($responsetype_per_response{$questnum-1} eq 'stringresponse') ||
                   5923:             ($responsetype_per_response{$questnum-1} eq 'imageresponse') ||
                   5924:             ($responsetype_per_response{$questnum-1} eq 'reactionresponse') ||
                   5925:             ($responsetype_per_response{$questnum-1} eq 'organicresponse')) {
1.503     raeburn  5926:             my $doubleerror = 0;
                   5927:             while (($currquest >= $$scantron_config{'Qlength'}) && 
                   5928:                    (!$doubleerror)) {
                   5929:                my $currline = substr($currquest,0,$$scantron_config{'Qlength'});
                   5930:                $currquest = substr($currquest,$$scantron_config{'Qlength'});
                   5931:                my @currarray = split($$scantron_config{'Qon'},$currline,-1);
                   5932:                if (length(@currarray) > 2) {
                   5933:                    $doubleerror = 1;
                   5934:                } 
                   5935:             }
                   5936:             if ($doubleerror) {
                   5937:                 push(@{$record->{'scantron.doubleerror'}},$quest_id);
                   5938:             }
                   5939:         } else {
                   5940:             push(@{$record->{'scantron.doubleerror'}},$quest_id);
                   5941:         }
                   5942:         my $item = $ansnum;
                   5943:         for (my $ans=0; $ans<$answers_needed; $ans++) {
                   5944:             $record->{"scantron.$item.answer"} = '';
                   5945:             $item ++;
                   5946:         }
1.447     foxr     5947: 
1.503     raeburn  5948:         my @ans=@array;
                   5949:         my $i=0;
                   5950:         my $increment = 0;
                   5951:         while ($#ans) {
                   5952:             $i+=length($ans[0]) + $increment;
                   5953:             my $line   = int($i/$$scantron_config{'Qlength'} + $ansnum);
                   5954:             my $bubble = $i%$$scantron_config{'Qlength'};
                   5955:             $record->{"scantron.$line.answer"}.=$alphabet->[$bubble];
                   5956:             shift(@ans);
                   5957:             $increment = 1;
                   5958:         }
                   5959:         $ansnum += $answers_needed;
1.82      albertel 5960:     }
1.503     raeburn  5961:     return $ansnum;
1.82      albertel 5962: }
                   5963: 
1.423     albertel 5964: =pod
                   5965: 
                   5966: =item scantron_add_delay
                   5967: 
                   5968:    Adds an error message that occurred during the grading phase to a
                   5969:    queue of messages to be shown after grading pass is complete
                   5970: 
                   5971:  Arguments:
1.424     albertel 5972:    $delayqueue  - arrary ref of hash ref of error messages
1.423     albertel 5973:    $scanline    - the scanline that caused the error
                   5974:    $errormesage - the error message
                   5975:    $errorcode   - a numeric code for the error
                   5976: 
                   5977:  Side Effects:
1.424     albertel 5978:    updates the $delayqueue to have a new hash ref of the error
1.423     albertel 5979: 
                   5980: =cut
                   5981: 
1.82      albertel 5982: sub scantron_add_delay {
1.140     albertel 5983:     my ($delayqueue,$scanline,$errormessage,$errorcode)=@_;
                   5984:     push(@$delayqueue,
                   5985: 	 {'line' => $scanline, 'emsg' => $errormessage,
                   5986: 	  'ecode' => $errorcode }
                   5987: 	 );
1.82      albertel 5988: }
                   5989: 
1.423     albertel 5990: =pod
                   5991: 
                   5992: =item scantron_find_student
                   5993: 
1.424     albertel 5994:    Finds the username for the current scanline
                   5995: 
                   5996:   Arguments:
                   5997:    $scantron_record - hash result from scantron_parse_scanline
                   5998:    $scan_data       - hash of correction information 
                   5999:                       (see &scantron_getfile() form more information)
                   6000:    $idmap           - hash from &username_to_idmap()
                   6001:    $line            - number of current scanline
                   6002:  
                   6003:   Returns:
                   6004:    Either 'username:domain' or undef if unknown
                   6005: 
1.423     albertel 6006: =cut
                   6007: 
1.82      albertel 6008: sub scantron_find_student {
1.157     albertel 6009:     my ($scantron_record,$scan_data,$idmap,$line)=@_;
1.83      albertel 6010:     my $scanID=$$scantron_record{'scantron.ID'};
1.157     albertel 6011:     if ($scanID =~ /^\s*$/) {
                   6012:  	return &scan_data($scan_data,"$line.user");
                   6013:     }
1.83      albertel 6014:     foreach my $id (keys(%$idmap)) {
1.157     albertel 6015:  	if (lc($id) eq lc($scanID)) {
                   6016:  	    return $$idmap{$id};
                   6017:  	}
1.83      albertel 6018:     }
                   6019:     return undef;
                   6020: }
                   6021: 
1.423     albertel 6022: =pod
                   6023: 
                   6024: =item scantron_filter
                   6025: 
1.424     albertel 6026:    Filter sub for lonnavmaps, filters out hidden resources if ignore
                   6027:    hidden resources was selected
                   6028: 
1.423     albertel 6029: =cut
                   6030: 
1.83      albertel 6031: sub scantron_filter {
                   6032:     my ($curres)=@_;
1.331     albertel 6033: 
                   6034:     if (ref($curres) && $curres->is_problem()) {
                   6035: 	# if the user has asked to not have either hidden
                   6036: 	# or 'randomout' controlled resources to be graded
                   6037: 	# don't include them
                   6038: 	if ($env{'form.scantron_options_hidden'} eq 'ignore_hidden'
                   6039: 	    && $curres->randomout) {
                   6040: 	    return 0;
                   6041: 	}
1.83      albertel 6042: 	return 1;
                   6043:     }
                   6044:     return 0;
1.82      albertel 6045: }
                   6046: 
1.423     albertel 6047: =pod
                   6048: 
                   6049: =item scantron_process_corrections
                   6050: 
1.424     albertel 6051:    Gets correction information out of submitted form data and corrects
                   6052:    the scanline
                   6053: 
1.423     albertel 6054: =cut
                   6055: 
1.157     albertel 6056: sub scantron_process_corrections {
                   6057:     my ($r) = @_;
1.257     albertel 6058:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.157     albertel 6059:     my ($scanlines,$scan_data)=&scantron_getfile();
                   6060:     my $classlist=&Apache::loncoursedata::get_classlist();
1.257     albertel 6061:     my $which=$env{'form.scantron_line'};
1.200     albertel 6062:     my $line=&scantron_get_line($scanlines,$scan_data,$which);
1.157     albertel 6063:     my ($skip,$err,$errmsg);
1.257     albertel 6064:     if ($env{'form.scantron_skip_record'}) {
1.157     albertel 6065: 	$skip=1;
1.257     albertel 6066:     } elsif ($env{'form.scantron_corrections'} =~ /^(duplicate|incorrect)ID$/) {
                   6067: 	my $newstudent=$env{'form.scantron_username'}.':'.
                   6068: 	    $env{'form.scantron_domain'};
1.157     albertel 6069: 	my $newid=$classlist->{$newstudent}->[&Apache::loncoursedata::CL_ID];
                   6070: 	($line,$err,$errmsg)=
                   6071: 	    &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,$which,
                   6072: 				     'ID',{'newid'=>$newid,
1.257     albertel 6073: 				    'username'=>$env{'form.scantron_username'},
                   6074: 				    'domain'=>$env{'form.scantron_domain'}});
                   6075:     } elsif ($env{'form.scantron_corrections'} =~ /^(duplicate|incorrect)CODE$/) {
                   6076: 	my $resolution=$env{'form.scantron_CODE_resolution'};
1.190     albertel 6077: 	my $newCODE;
1.192     albertel 6078: 	my %args;
1.190     albertel 6079: 	if      ($resolution eq 'use_unfound') {
1.191     albertel 6080: 	    $newCODE='use_unfound';
1.190     albertel 6081: 	} elsif ($resolution eq 'use_found') {
1.257     albertel 6082: 	    $newCODE=$env{'form.scantron_CODE_selectedvalue'};
1.190     albertel 6083: 	} elsif ($resolution eq 'use_typed') {
1.257     albertel 6084: 	    $newCODE=$env{'form.scantron_CODE_newvalue'};
1.194     albertel 6085: 	} elsif ($resolution =~ /^use_closest_(\d+)/) {
1.257     albertel 6086: 	    $newCODE=$env{"form.scantron_CODE_closest_$1"};
1.190     albertel 6087: 	}
1.257     albertel 6088: 	if ($env{'form.scantron_corrections'} eq 'duplicateCODE') {
1.192     albertel 6089: 	    $args{'CODE_ignore_dup'}=1;
                   6090: 	}
                   6091: 	$args{'CODE'}=$newCODE;
1.186     albertel 6092: 	($line,$err,$errmsg)=
                   6093: 	    &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,$which,
1.192     albertel 6094: 				     'CODE',\%args);
1.257     albertel 6095:     } elsif ($env{'form.scantron_corrections'} =~ /^(missing|double)bubble$/) {
                   6096: 	foreach my $question (split(',',$env{'form.scantron_questions'})) {
1.157     albertel 6097: 	    ($line,$err,$errmsg)=
                   6098: 		&scantron_fixup_scanline(\%scantron_config,$scan_data,$line,
                   6099: 					 $which,'answer',
                   6100: 					 { 'question'=>$question,
1.503     raeburn  6101: 		      		   'response'=>$env{"form.scantron_correct_Q_$question"},
                   6102:                                    'questionnum'=>$env{"form.scantron_questionnum_Q_$question"}});
1.157     albertel 6103: 	    if ($err) { last; }
                   6104: 	}
                   6105:     }
                   6106:     if ($err) {
1.398     albertel 6107: 	$r->print("<span class=\"LC_warning\">Unable to accept last correction, an error occurred :$errmsg:</span>");
1.157     albertel 6108:     } else {
1.200     albertel 6109: 	&scantron_put_line($scanlines,$scan_data,$which,$line,$skip);
1.157     albertel 6110: 	&scantron_putfile($scanlines,$scan_data);
                   6111:     }
                   6112: }
                   6113: 
1.423     albertel 6114: =pod
                   6115: 
                   6116: =item reset_skipping_status
                   6117: 
1.424     albertel 6118:    Forgets the current set of remember skipped scanlines (and thus
                   6119:    reverts back to considering all lines in the
                   6120:    scantron_skipped_<filename> file)
                   6121: 
1.423     albertel 6122: =cut
                   6123: 
1.200     albertel 6124: sub reset_skipping_status {
                   6125:     my ($scanlines,$scan_data)=&scantron_getfile();
                   6126:     &scan_data($scan_data,'remember_skipping',undef,1);
                   6127:     &scantron_putfile(undef,$scan_data);
                   6128: }
                   6129: 
1.423     albertel 6130: =pod
                   6131: 
                   6132: =item start_skipping
                   6133: 
1.424     albertel 6134:    Marks a scanline to be skipped. 
                   6135: 
1.423     albertel 6136: =cut
                   6137: 
1.376     albertel 6138: sub start_skipping {
1.200     albertel 6139:     my ($scan_data,$i)=@_;
                   6140:     my %remembered=split(':',&scan_data($scan_data,'remember_skipping'));
1.376     albertel 6141:     if ($env{'form.scantron_options_redo'} =~ /^redo_/) {
                   6142: 	$remembered{$i}=2;
                   6143:     } else {
                   6144: 	$remembered{$i}=1;
                   6145:     }
1.200     albertel 6146:     &scan_data($scan_data,'remember_skipping',join(':',%remembered));
                   6147: }
                   6148: 
1.423     albertel 6149: =pod
                   6150: 
                   6151: =item should_be_skipped
                   6152: 
1.424     albertel 6153:    Checks whether a scanline should be skipped.
                   6154: 
1.423     albertel 6155: =cut
                   6156: 
1.200     albertel 6157: sub should_be_skipped {
1.376     albertel 6158:     my ($scanlines,$scan_data,$i)=@_;
1.257     albertel 6159:     if ($env{'form.scantron_options_redo'} !~ /^redo_/) {
1.200     albertel 6160: 	# not redoing old skips
1.376     albertel 6161: 	if ($scanlines->{'skipped'}[$i]) { return 1; }
1.200     albertel 6162: 	return 0;
                   6163:     }
                   6164:     my %remembered=split(':',&scan_data($scan_data,'remember_skipping'));
1.376     albertel 6165: 
                   6166:     if (exists($remembered{$i}) && $remembered{$i} != 2 ) {
                   6167: 	return 0;
                   6168:     }
1.200     albertel 6169:     return 1;
                   6170: }
                   6171: 
1.423     albertel 6172: =pod
                   6173: 
                   6174: =item remember_current_skipped
                   6175: 
1.424     albertel 6176:    Discovers what scanlines are in the scantron_skipped_<filename>
                   6177:    file and remembers them into scan_data for later use.
                   6178: 
1.423     albertel 6179: =cut
                   6180: 
1.200     albertel 6181: sub remember_current_skipped {
                   6182:     my ($scanlines,$scan_data)=&scantron_getfile();
                   6183:     my %to_remember;
                   6184:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
                   6185: 	if ($scanlines->{'skipped'}[$i]) {
                   6186: 	    $to_remember{$i}=1;
                   6187: 	}
                   6188:     }
1.376     albertel 6189: 
1.200     albertel 6190:     &scan_data($scan_data,'remember_skipping',join(':',%to_remember));
                   6191:     &scantron_putfile(undef,$scan_data);
                   6192: }
                   6193: 
1.423     albertel 6194: =pod
                   6195: 
                   6196: =item check_for_error
                   6197: 
1.424     albertel 6198:     Checks if there was an error when attempting to remove a specific
                   6199:     scantron_.. bubble sheet data file. Prints out an error if
                   6200:     something went wrong.
                   6201: 
1.423     albertel 6202: =cut
                   6203: 
1.200     albertel 6204: sub check_for_error {
                   6205:     my ($r,$result)=@_;
                   6206:     if ($result ne 'ok' && $result ne 'not_found' ) {
1.492     albertel 6207: 	$r->print(&mt("An error occurred ([_1]) when trying to remove the existing corrections.",$result));
1.200     albertel 6208:     }
                   6209: }
1.157     albertel 6210: 
1.423     albertel 6211: =pod
                   6212: 
                   6213: =item scantron_warning_screen
                   6214: 
1.424     albertel 6215:    Interstitial screen to make sure the operator has selected the
                   6216:    correct options before we start the validation phase.
                   6217: 
1.423     albertel 6218: =cut
                   6219: 
1.203     albertel 6220: sub scantron_warning_screen {
                   6221:     my ($button_text)=@_;
1.257     albertel 6222:     my $title=&Apache::lonnet::gettitle($env{'form.selectpage'});
1.284     albertel 6223:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.373     albertel 6224:     my $CODElist;
1.284     albertel 6225:     if ($scantron_config{'CODElocation'} &&
                   6226: 	$scantron_config{'CODEstart'} &&
                   6227: 	$scantron_config{'CODElength'}) {
                   6228: 	$CODElist=$env{'form.scantron_CODElist'};
1.398     albertel 6229: 	if ($env{'form.scantron_CODElist'} eq '') { $CODElist='<span class="LC_warning">None</span>'; }
1.284     albertel 6230: 	$CODElist=
1.492     albertel 6231: 	    '<tr><td><b>'.&mt('List of CODES to validate against:').'</b></td><td><tt>'.
1.373     albertel 6232: 	    $env{'form.scantron_CODElist'}.'</tt></td></tr>';
1.284     albertel 6233:     }
1.492     albertel 6234:     return ('
1.203     albertel 6235: <p>
1.492     albertel 6236: <span class="LC_warning">
                   6237: '.&mt('Please double check the information below before clicking on \'[_1]\'',&mt($button_text)).'</span>
1.203     albertel 6238: </p>
                   6239: <table>
1.492     albertel 6240: <tr><td><b>'.&mt('Sequence to be Graded:').'</b></td><td>'.$title.'</td></tr>
                   6241: <tr><td><b>'.&mt('Data File that will be used:').'</b></td><td><tt>'.$env{'form.scantron_selectfile'}.'</tt></td></tr>
                   6242: '.$CODElist.'
1.203     albertel 6243: </table>
                   6244: <br />
1.492     albertel 6245: <p> '.&mt('If this information is correct, please click on \'[_1]\'.',&mt($button_text)).'</p>
                   6246: <p> '.&mt('If something is incorrect, please click the \'Grading Menu\' button to start over.').'</p>
1.203     albertel 6247: 
                   6248: <br />
1.492     albertel 6249: ');
1.203     albertel 6250: }
                   6251: 
1.423     albertel 6252: =pod
                   6253: 
                   6254: =item scantron_do_warning
                   6255: 
1.424     albertel 6256:    Check if the operator has picked something for all required
                   6257:    fields. Error out if something is missing.
                   6258: 
1.423     albertel 6259: =cut
                   6260: 
1.203     albertel 6261: sub scantron_do_warning {
                   6262:     my ($r)=@_;
1.324     albertel 6263:     my ($symb)=&get_symb($r);
1.203     albertel 6264:     if (!$symb) {return '';}
1.324     albertel 6265:     my $default_form_data=&defaultFormData($symb);
1.203     albertel 6266:     $r->print(&scantron_form_start().$default_form_data);
1.257     albertel 6267:     if ( $env{'form.selectpage'} eq '' ||
                   6268: 	 $env{'form.scantron_selectfile'} eq '' ||
                   6269: 	 $env{'form.scantron_format'} eq '' ) {
1.492     albertel 6270: 	$r->print("<p>".&mt('You have forgetten to specify some information. Please go Back and try again.')."</p>");
1.257     albertel 6271: 	if ( $env{'form.selectpage'} eq '') {
1.492     albertel 6272: 	    $r->print('<p><span class="LC_error">'.&mt('You have not selected a Sequence to grade').'</span></p>');
1.237     albertel 6273: 	} 
1.257     albertel 6274: 	if ( $env{'form.scantron_selectfile'} eq '') {
1.492     albertel 6275: 	    $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 6276: 	} 
1.257     albertel 6277: 	if ( $env{'form.scantron_format'} eq '') {
1.492     albertel 6278: 	    $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 6279: 	} 
                   6280:     } else {
1.265     www      6281: 	my $warning=&scantron_warning_screen('Grading: Validate Records');
1.492     albertel 6282: 	$r->print('
                   6283: '.$warning.'
                   6284: <input type="submit" name="submit" value="'.&mt('Grading: Validate Records').'" />
1.203     albertel 6285: <input type="hidden" name="command" value="scantron_validate" />
1.492     albertel 6286: ');
1.237     albertel 6287:     }
1.352     albertel 6288:     $r->print("</form><br />".&show_grading_menu_form($symb));
1.203     albertel 6289:     return '';
                   6290: }
                   6291: 
1.423     albertel 6292: =pod
                   6293: 
                   6294: =item scantron_form_start
                   6295: 
1.424     albertel 6296:     html hidden input for remembering all selected grading options
                   6297: 
1.423     albertel 6298: =cut
                   6299: 
1.203     albertel 6300: sub scantron_form_start {
                   6301:     my ($max_bubble)=@_;
                   6302:     my $result= <<SCANTRONFORM;
                   6303: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantronupload">
1.257     albertel 6304:   <input type="hidden" name="selectpage" value="$env{'form.selectpage'}" />
                   6305:   <input type="hidden" name="scantron_format" value="$env{'form.scantron_format'}" />
                   6306:   <input type="hidden" name="scantron_selectfile" value="$env{'form.scantron_selectfile'}" />
1.218     albertel 6307:   <input type="hidden" name="scantron_maxbubble" value="$max_bubble" />
1.257     albertel 6308:   <input type="hidden" name="scantron_CODElist" value="$env{'form.scantron_CODElist'}" />
                   6309:   <input type="hidden" name="scantron_CODEunique" value="$env{'form.scantron_CODEunique'}" />
                   6310:   <input type="hidden" name="scantron_options_redo" value="$env{'form.scantron_options_redo'}" />
                   6311:   <input type="hidden" name="scantron_options_ignore" value="$env{'form.scantron_options_ignore'}" />
1.331     albertel 6312:   <input type="hidden" name="scantron_options_hidden" value="$env{'form.scantron_options_hidden'}" />
1.203     albertel 6313: SCANTRONFORM
1.447     foxr     6314: 
                   6315:   my $line = 0;
                   6316:     while (defined($env{"form.scantron.bubblelines.$line"})) {
                   6317:        my $chunk =
                   6318: 	   '<input type="hidden" name="scantron.bubblelines.'.$line.'" value="'.$env{"form.scantron.bubblelines.$line"}.'" />'."\n";
1.448     foxr     6319:        $chunk .=
                   6320: 	   '<input type="hidden" name="scantron.first_bubble_line.'.$line.'" value="'.$env{"form.scantron.first_bubble_line.$line"}.'" />'."\n";
1.503     raeburn  6321:        $chunk .= 
                   6322:            '<input type="hidden" name="scantron.sub_bubblelines.'.$line.'" value="'.$env{"form.scantron.sub_bubblelines.$line"}.'" />'."\n";
1.504     raeburn  6323:        $chunk .=
                   6324:            '<input type="hidden" name="scantron.responsetype.'.$line.'" value="'.$env{"form.scantron.responsetype.$line"}.'" />'."\n";
1.447     foxr     6325:        $result .= $chunk;
                   6326:        $line++;
                   6327:    }
1.203     albertel 6328:     return $result;
                   6329: }
                   6330: 
1.423     albertel 6331: =pod
                   6332: 
                   6333: =item scantron_validate_file
                   6334: 
1.424     albertel 6335:     Dispatch routine for doing validation of a bubble sheet data file.
                   6336: 
                   6337:     Also processes any necessary information resets that need to
                   6338:     occur before validation begins (ignore previous corrections,
                   6339:     restarting the skipped records processing)
                   6340: 
1.423     albertel 6341: =cut
                   6342: 
1.157     albertel 6343: sub scantron_validate_file {
                   6344:     my ($r) = @_;
1.324     albertel 6345:     my ($symb)=&get_symb($r);
1.157     albertel 6346:     if (!$symb) {return '';}
1.324     albertel 6347:     my $default_form_data=&defaultFormData($symb);
1.200     albertel 6348:     
                   6349:     # do the detection of only doing skipped records first befroe we delete
1.424     albertel 6350:     # them when doing the corrections reset
1.257     albertel 6351:     if ($env{'form.scantron_options_redo'} ne 'redo_skipped_ready') {
1.200     albertel 6352: 	&reset_skipping_status();
                   6353:     }
1.257     albertel 6354:     if ($env{'form.scantron_options_redo'} eq 'redo_skipped') {
1.200     albertel 6355: 	&remember_current_skipped();
1.257     albertel 6356: 	$env{'form.scantron_options_redo'}='redo_skipped_ready';
1.200     albertel 6357:     }
                   6358: 
1.257     albertel 6359:     if ($env{'form.scantron_options_ignore'} eq 'ignore_corrections') {
1.200     albertel 6360: 	&check_for_error($r,&scantron_remove_file('corrected'));
                   6361: 	&check_for_error($r,&scantron_remove_file('skipped'));
                   6362: 	&check_for_error($r,&scantron_remove_scan_data());
1.257     albertel 6363: 	$env{'form.scantron_options_ignore'}='done';
1.192     albertel 6364:     }
1.200     albertel 6365: 
1.257     albertel 6366:     if ($env{'form.scantron_corrections'}) {
1.157     albertel 6367: 	&scantron_process_corrections($r);
                   6368:     }
1.503     raeburn  6369:     $r->print('<p>'.&mt('Gathering necessary information.').'</p>');$r->rflush();
1.157     albertel 6370:     #get the student pick code ready
                   6371:     $r->print(&Apache::loncommon::studentbrowser_javascript());
1.582     raeburn  6372:     my $nav_error;
                   6373:     my $max_bubble=&scantron_get_maxbubble(\$nav_error);
                   6374:     if ($nav_error) {
                   6375:         $r->print(&navmap_errormsg());
                   6376:         return '';
                   6377:     }
1.203     albertel 6378:     my $result=&scantron_form_start($max_bubble).$default_form_data;
1.157     albertel 6379:     $r->print($result);
                   6380:     
1.334     albertel 6381:     my @validate_phases=( 'sequence',
                   6382: 			  'ID',
1.157     albertel 6383: 			  'CODE',
                   6384: 			  'doublebubble',
                   6385: 			  'missingbubbles');
1.257     albertel 6386:     if (!$env{'form.validatepass'}) {
                   6387: 	$env{'form.validatepass'} = 0;
1.157     albertel 6388:     }
1.257     albertel 6389:     my $currentphase=$env{'form.validatepass'};
1.157     albertel 6390: 
1.448     foxr     6391: 
1.157     albertel 6392:     my $stop=0;
                   6393:     while (!$stop && $currentphase < scalar(@validate_phases)) {
1.503     raeburn  6394: 	$r->print(&mt('Validating '.$validate_phases[$currentphase]).'<br />');
1.157     albertel 6395: 	$r->rflush();
                   6396: 	my $which="scantron_validate_".$validate_phases[$currentphase];
                   6397: 	{
                   6398: 	    no strict 'refs';
                   6399: 	    ($stop,$currentphase)=&$which($r,$currentphase);
                   6400: 	}
                   6401:     }
                   6402:     if (!$stop) {
1.203     albertel 6403: 	my $warning=&scantron_warning_screen('Start Grading');
1.542     raeburn  6404: 	$r->print(&mt('Validation process complete.').'<br />'.
                   6405:                   $warning.
                   6406:                   &mt('Perform verification for each student after storage of submissions?').
                   6407:                   '&nbsp;<span class="LC_nobreak"><label>'.
                   6408:                   '<input type="radio" name="verifyrecord" value="1" />'.&mt('Yes').'</label>'.
                   6409:                   ('&nbsp;'x3).'<label>'.
                   6410:                   '<input type="radio" name="verifyrecord" value="0" checked="checked" />'.&mt('No').
                   6411:                   '</label></span><br />'.
                   6412:                   &mt('Grading will take longer if you use verification.').'<br />'.
1.572     www      6413:                   &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  6414:                   '<input type="submit" name="submit" value="'.&mt('Start Grading').'" />'.
                   6415:                   '<input type="hidden" name="command" value="scantron_process" />'."\n");
1.157     albertel 6416:     } else {
                   6417: 	$r->print('<input type="hidden" name="command" value="scantron_validate" />');
                   6418: 	$r->print("<input type='hidden' name='validatepass' value='".$currentphase."' />");
                   6419:     }
                   6420:     if ($stop) {
1.334     albertel 6421: 	if ($validate_phases[$currentphase] eq 'sequence') {
1.539     riegler  6422: 	    $r->print('<input type="submit" name="submit" value="'.&mt('Ignore').' &rarr; " />');
1.492     albertel 6423: 	    $r->print(' '.&mt('this error').' <br />');
1.334     albertel 6424: 
1.492     albertel 6425: 	    $r->print(" <p>".&mt("Or click the 'Grading Menu' button to start over.")."</p>");
1.334     albertel 6426: 	} else {
1.503     raeburn  6427:             if ($validate_phases[$currentphase] eq 'doublebubble' || $validate_phases[$currentphase] eq 'missingbubbles') {
1.539     riegler  6428: 	        $r->print('<input type="button" name="submitbutton" value="'.&mt('Continue').' &rarr;" onclick="javascript:verify_bubble_radio(this.form)" />');
1.503     raeburn  6429:             } else {
1.539     riegler  6430:                 $r->print('<input type="submit" name="submit" value="'.&mt('Continue').' &rarr;" />');
1.503     raeburn  6431:             }
1.492     albertel 6432: 	    $r->print(' '.&mt('using corrected info').' <br />');
                   6433: 	    $r->print("<input type='submit' value='".&mt("Skip")."' name='scantron_skip_record' />");
                   6434: 	    $r->print(" ".&mt("this scanline saving it for later."));
1.334     albertel 6435: 	}
1.157     albertel 6436:     }
1.352     albertel 6437:     $r->print(" </form><br />".&show_grading_menu_form($symb));
1.157     albertel 6438:     return '';
                   6439: }
                   6440: 
1.423     albertel 6441: 
                   6442: =pod
                   6443: 
                   6444: =item scantron_remove_file
                   6445: 
1.424     albertel 6446:    Removes the requested bubble sheet data file, makes sure that
                   6447:    scantron_original_<filename> is never removed
                   6448: 
                   6449: 
1.423     albertel 6450: =cut
                   6451: 
1.200     albertel 6452: sub scantron_remove_file {
1.192     albertel 6453:     my ($which)=@_;
1.257     albertel 6454:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   6455:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.192     albertel 6456:     my $file='scantron_';
1.200     albertel 6457:     if ($which eq 'corrected' || $which eq 'skipped') {
                   6458: 	$file.=$which.'_';
1.192     albertel 6459:     } else {
                   6460: 	return 'refused';
                   6461:     }
1.257     albertel 6462:     $file.=$env{'form.scantron_selectfile'};
1.200     albertel 6463:     return &Apache::lonnet::removeuserfile($cname,$cdom,$file);
                   6464: }
                   6465: 
1.423     albertel 6466: 
                   6467: =pod
                   6468: 
                   6469: =item scantron_remove_scan_data
                   6470: 
1.424     albertel 6471:    Removes all scan_data correction for the requested bubble sheet
                   6472:    data file.  (In the case that both the are doing skipped records we need
                   6473:    to remember the old skipped lines for the time being so that element
                   6474:    persists for a while.)
                   6475: 
1.423     albertel 6476: =cut
                   6477: 
1.200     albertel 6478: sub scantron_remove_scan_data {
1.257     albertel 6479:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   6480:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.192     albertel 6481:     my @keys=&Apache::lonnet::getkeys('nohist_scantrondata',$cdom,$cname);
                   6482:     my @todelete;
1.257     albertel 6483:     my $filename=$env{'form.scantron_selectfile'};
1.192     albertel 6484:     foreach my $key (@keys) {
                   6485: 	if ($key=~/^\Q$filename\E_/) {
1.257     albertel 6486: 	    if ($env{'form.scantron_options_redo'} eq 'redo_skipped_ready' &&
1.200     albertel 6487: 		$key=~/remember_skipping/) {
                   6488: 		next;
                   6489: 	    }
1.192     albertel 6490: 	    push(@todelete,$key);
                   6491: 	}
                   6492:     }
1.200     albertel 6493:     my $result;
1.192     albertel 6494:     if (@todelete) {
1.491     albertel 6495: 	$result = &Apache::lonnet::del('nohist_scantrondata',
                   6496: 				       \@todelete,$cdom,$cname);
                   6497:     } else {
                   6498: 	$result = 'ok';
1.192     albertel 6499:     }
                   6500:     return $result;
                   6501: }
                   6502: 
1.423     albertel 6503: 
                   6504: =pod
                   6505: 
                   6506: =item scantron_getfile
                   6507: 
1.424     albertel 6508:     Fetches the requested bubble sheet data file (all 3 versions), and
                   6509:     the scan_data hash
                   6510:   
                   6511:   Arguments:
                   6512:     None
                   6513: 
                   6514:   Returns:
                   6515:     2 hash references
                   6516: 
                   6517:      - first one has 
                   6518:          orig      -
                   6519:          corrected -
                   6520:          skipped   -  each of which points to an array ref of the specified
                   6521:                       file broken up into individual lines
                   6522:          count     - number of scanlines
                   6523:  
                   6524:      - second is the scan_data hash possible keys are
1.425     albertel 6525:        ($number refers to scanline numbered $number and thus the key affects
                   6526:         only that scanline
                   6527:         $bubline refers to the specific bubble line element and the aspects
                   6528:         refers to that specific bubble line element)
                   6529: 
                   6530:        $number.user - username:domain to use
                   6531:        $number.CODE_ignore_dup 
                   6532:                     - ignore the duplicate CODE error 
                   6533:        $number.useCODE
                   6534:                     - use the CODE in the scanline as is
                   6535:        $number.no_bubble.$bubline
                   6536:                     - it is valid that there is no bubbled in bubble
                   6537:                       at $number $bubline
                   6538:        remember_skipping
                   6539:                     - a frozen hash containing keys of $number and values
                   6540:                       of either 
                   6541:                         1 - we are on a 'do skipped records pass' and plan
                   6542:                             on processing this line
                   6543:                         2 - we are on a 'do skipped records pass' and this
                   6544:                             scanline has been marked to skip yet again
1.424     albertel 6545: 
1.423     albertel 6546: =cut
                   6547: 
1.157     albertel 6548: sub scantron_getfile {
1.200     albertel 6549:     #FIXME really would prefer a scantron directory
1.257     albertel 6550:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   6551:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.157     albertel 6552:     my $lines;
                   6553:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
1.257     albertel 6554: 		       'scantron_orig_'.$env{'form.scantron_selectfile'});
1.157     albertel 6555:     my %scanlines;
                   6556:     $scanlines{'orig'}=[(split("\n",$lines,-1))];
                   6557:     my $temp=$scanlines{'orig'};
                   6558:     $scanlines{'count'}=$#$temp;
                   6559: 
                   6560:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
1.257     albertel 6561: 		       'scantron_corrected_'.$env{'form.scantron_selectfile'});
1.157     albertel 6562:     if ($lines eq '-1') {
                   6563: 	$scanlines{'corrected'}=[];
                   6564:     } else {
                   6565: 	$scanlines{'corrected'}=[(split("\n",$lines,-1))];
                   6566:     }
                   6567:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
1.257     albertel 6568: 		       'scantron_skipped_'.$env{'form.scantron_selectfile'});
1.157     albertel 6569:     if ($lines eq '-1') {
                   6570: 	$scanlines{'skipped'}=[];
                   6571:     } else {
                   6572: 	$scanlines{'skipped'}=[(split("\n",$lines,-1))];
                   6573:     }
1.175     albertel 6574:     my @tmp=&Apache::lonnet::dump('nohist_scantrondata',$cdom,$cname);
1.157     albertel 6575:     if ($tmp[0] =~ /^(error:|no_such_host)/) { @tmp=(); }
                   6576:     my %scan_data = @tmp;
                   6577:     return (\%scanlines,\%scan_data);
                   6578: }
                   6579: 
1.423     albertel 6580: =pod
                   6581: 
                   6582: =item lonnet_putfile
                   6583: 
1.424     albertel 6584:    Wrapper routine to call &Apache::lonnet::finishuserfileupload
                   6585: 
                   6586:  Arguments:
                   6587:    $contents - data to store
                   6588:    $filename - filename to store $contents into
                   6589: 
                   6590:  Returns:
                   6591:    result value from &Apache::lonnet::finishuserfileupload
                   6592: 
1.423     albertel 6593: =cut
                   6594: 
1.157     albertel 6595: sub lonnet_putfile {
                   6596:     my ($contents,$filename)=@_;
1.257     albertel 6597:     my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   6598:     my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   6599:     $env{'form.sillywaytopassafilearound'}=$contents;
1.275     albertel 6600:     &Apache::lonnet::finishuserfileupload($docuname,$docudom,'sillywaytopassafilearound',$filename);
1.157     albertel 6601: 
                   6602: }
                   6603: 
1.423     albertel 6604: =pod
                   6605: 
                   6606: =item scantron_putfile
                   6607: 
1.424     albertel 6608:     Stores the current version of the bubble sheet data files, and the
                   6609:     scan_data hash. (Does not modify the original version only the
                   6610:     corrected and skipped versions.
                   6611: 
                   6612:  Arguments:
                   6613:     $scanlines - hash ref that looks like the first return value from
                   6614:                  &scantron_getfile()
                   6615:     $scan_data - hash ref that looks like the second return value from
                   6616:                  &scantron_getfile()
                   6617: 
1.423     albertel 6618: =cut
                   6619: 
1.157     albertel 6620: sub scantron_putfile {
                   6621:     my ($scanlines,$scan_data) = @_;
1.200     albertel 6622:     #FIXME really would prefer a scantron directory
1.257     albertel 6623:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   6624:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.200     albertel 6625:     if ($scanlines) {
                   6626: 	my $prefix='scantron_';
1.157     albertel 6627: # no need to update orig, shouldn't change
                   6628: #   &lonnet_putfile(join("\n",@{$scanlines->{'orig'}}),$prefix.'orig_'.
1.257     albertel 6629: #		    $env{'form.scantron_selectfile'});
1.200     albertel 6630: 	&lonnet_putfile(join("\n",@{$scanlines->{'corrected'}}),
                   6631: 			$prefix.'corrected_'.
1.257     albertel 6632: 			$env{'form.scantron_selectfile'});
1.200     albertel 6633: 	&lonnet_putfile(join("\n",@{$scanlines->{'skipped'}}),
                   6634: 			$prefix.'skipped_'.
1.257     albertel 6635: 			$env{'form.scantron_selectfile'});
1.200     albertel 6636:     }
1.175     albertel 6637:     &Apache::lonnet::put('nohist_scantrondata',$scan_data,$cdom,$cname);
1.157     albertel 6638: }
                   6639: 
1.423     albertel 6640: =pod
                   6641: 
                   6642: =item scantron_get_line
                   6643: 
1.424     albertel 6644:    Returns the correct version of the scanline
                   6645: 
                   6646:  Arguments:
                   6647:     $scanlines - hash ref that looks like the first return value from
                   6648:                  &scantron_getfile()
                   6649:     $scan_data - hash ref that looks like the second return value from
                   6650:                  &scantron_getfile()
                   6651:     $i         - number of the requested line (starts at 0)
                   6652: 
                   6653:  Returns:
                   6654:    A scanline, (either the original or the corrected one if it
                   6655:    exists), or undef if the requested scanline should be
                   6656:    skipped. (Either because it's an skipped scanline, or it's an
                   6657:    unskipped scanline and we are not doing a 'do skipped scanlines'
                   6658:    pass.
                   6659: 
1.423     albertel 6660: =cut
                   6661: 
1.157     albertel 6662: sub scantron_get_line {
1.200     albertel 6663:     my ($scanlines,$scan_data,$i)=@_;
1.376     albertel 6664:     if (&should_be_skipped($scanlines,$scan_data,$i)) { return undef; }
                   6665:     #if ($scanlines->{'skipped'}[$i]) { return undef; }
1.157     albertel 6666:     if ($scanlines->{'corrected'}[$i]) {return $scanlines->{'corrected'}[$i];}
                   6667:     return $scanlines->{'orig'}[$i]; 
                   6668: }
                   6669: 
1.423     albertel 6670: =pod
                   6671: 
                   6672: =item scantron_todo_count
                   6673: 
1.424     albertel 6674:     Counts the number of scanlines that need processing.
                   6675: 
                   6676:  Arguments:
                   6677:     $scanlines - hash ref that looks like the first return value from
                   6678:                  &scantron_getfile()
                   6679:     $scan_data - hash ref that looks like the second return value from
                   6680:                  &scantron_getfile()
                   6681: 
                   6682:  Returns:
                   6683:     $count - number of scanlines to process
                   6684: 
1.423     albertel 6685: =cut
                   6686: 
1.200     albertel 6687: sub get_todo_count {
                   6688:     my ($scanlines,$scan_data)=@_;
                   6689:     my $count=0;
                   6690:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
                   6691: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
                   6692: 	if ($line=~/^[\s\cz]*$/) { next; }
                   6693: 	$count++;
                   6694:     }
                   6695:     return $count;
                   6696: }
                   6697: 
1.423     albertel 6698: =pod
                   6699: 
                   6700: =item scantron_put_line
                   6701: 
1.424     albertel 6702:     Updates the 'corrected' or 'skipped' versions of the bubble sheet
                   6703:     data file.
                   6704: 
                   6705:  Arguments:
                   6706:     $scanlines - hash ref that looks like the first return value from
                   6707:                  &scantron_getfile()
                   6708:     $scan_data - hash ref that looks like the second return value from
                   6709:                  &scantron_getfile()
                   6710:     $i         - line number to update
                   6711:     $newline   - contents of the updated scanline
                   6712:     $skip      - if true make the line for skipping and update the
                   6713:                  'skipped' file
                   6714: 
1.423     albertel 6715: =cut
                   6716: 
1.157     albertel 6717: sub scantron_put_line {
1.200     albertel 6718:     my ($scanlines,$scan_data,$i,$newline,$skip)=@_;
1.157     albertel 6719:     if ($skip) {
                   6720: 	$scanlines->{'skipped'}[$i]=$newline;
1.376     albertel 6721: 	&start_skipping($scan_data,$i);
1.157     albertel 6722: 	return;
                   6723:     }
                   6724:     $scanlines->{'corrected'}[$i]=$newline;
                   6725: }
                   6726: 
1.423     albertel 6727: =pod
                   6728: 
                   6729: =item scantron_clear_skip
                   6730: 
1.424     albertel 6731:    Remove a line from the 'skipped' file
                   6732: 
                   6733:  Arguments:
                   6734:     $scanlines - hash ref that looks like the first return value from
                   6735:                  &scantron_getfile()
                   6736:     $scan_data - hash ref that looks like the second return value from
                   6737:                  &scantron_getfile()
                   6738:     $i         - line number to update
                   6739: 
1.423     albertel 6740: =cut
                   6741: 
1.376     albertel 6742: sub scantron_clear_skip {
                   6743:     my ($scanlines,$scan_data,$i)=@_;
                   6744:     if (exists($scanlines->{'skipped'}[$i])) {
                   6745: 	undef($scanlines->{'skipped'}[$i]);
                   6746: 	return 1;
                   6747:     }
                   6748:     return 0;
                   6749: }
                   6750: 
1.423     albertel 6751: =pod
                   6752: 
                   6753: =item scantron_filter_not_exam
                   6754: 
1.424     albertel 6755:    Filter routine used by &Apache::lonnavmaps::retrieveResources(), to
                   6756:    filter out resources that are not marked as 'exam' mode
                   6757: 
1.423     albertel 6758: =cut
                   6759: 
1.334     albertel 6760: sub scantron_filter_not_exam {
                   6761:     my ($curres)=@_;
                   6762:     
                   6763:     if (ref($curres) && $curres->is_problem() && !$curres->is_exam()) {
                   6764: 	# if the user has asked to not have either hidden
                   6765: 	# or 'randomout' controlled resources to be graded
                   6766: 	# don't include them
                   6767: 	if ($env{'form.scantron_options_hidden'} eq 'ignore_hidden'
                   6768: 	    && $curres->randomout) {
                   6769: 	    return 0;
                   6770: 	}
                   6771: 	return 1;
                   6772:     }
                   6773:     return 0;
                   6774: }
                   6775: 
1.423     albertel 6776: =pod
                   6777: 
                   6778: =item scantron_validate_sequence
                   6779: 
1.424     albertel 6780:     Validates the selected sequence, checking for resource that are
                   6781:     not set to exam mode.
                   6782: 
1.423     albertel 6783: =cut
                   6784: 
1.334     albertel 6785: sub scantron_validate_sequence {
                   6786:     my ($r,$currentphase) = @_;
                   6787: 
                   6788:     my $navmap=Apache::lonnavmaps::navmap->new();
1.582     raeburn  6789:     unless (ref($navmap)) {
                   6790:         $r->print(&navmap_errormsg());
                   6791:         return (1,$currentphase);
                   6792:     }
1.334     albertel 6793:     my (undef,undef,$sequence)=
                   6794: 	&Apache::lonnet::decode_symb($env{'form.selectpage'});
                   6795: 
                   6796:     my $map=$navmap->getResourceByUrl($sequence);
                   6797: 
                   6798:     $r->print('<input type="hidden" name="validate_sequence_exam"
                   6799:                                     value="ignore" />');
                   6800:     if ($env{'form.validate_sequence_exam'} ne 'ignore') {
                   6801: 	my @resources=
                   6802: 	    $navmap->retrieveResources($map,\&scantron_filter_not_exam,1,0);
                   6803: 	if (@resources) {
1.357     banghart 6804: 	    $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 6805: 	    return (1,$currentphase);
                   6806: 	}
                   6807:     }
                   6808: 
                   6809:     return (0,$currentphase+1);
                   6810: }
                   6811: 
1.423     albertel 6812: 
                   6813: 
1.157     albertel 6814: sub scantron_validate_ID {
                   6815:     my ($r,$currentphase) = @_;
                   6816:     
                   6817:     #get student info
                   6818:     my $classlist=&Apache::loncoursedata::get_classlist();
                   6819:     my %idmap=&username_to_idmap($classlist);
                   6820: 
                   6821:     #get scantron line setup
1.257     albertel 6822:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.157     albertel 6823:     my ($scanlines,$scan_data)=&scantron_getfile();
1.582     raeburn  6824: 
                   6825:     my $nav_error;
                   6826:     &scantron_get_maxbubble(\$nav_error); # parse needs the bubble_lines.. array.
                   6827:     if ($nav_error) {
                   6828:         $r->print(&navmap_errormsg());
                   6829:         return(1,$currentphase);
                   6830:     }
1.157     albertel 6831: 
                   6832:     my %found=('ids'=>{},'usernames'=>{});
                   6833:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
1.200     albertel 6834: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.157     albertel 6835: 	if ($line=~/^[\s\cz]*$/) { next; }
                   6836: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
                   6837: 						 $scan_data);
                   6838: 	my $id=$$scan_record{'scantron.ID'};
                   6839: 	my $found;
                   6840: 	foreach my $checkid (keys(%idmap)) {
                   6841: 	    if (lc($checkid) eq lc($id)) { $found=$checkid;last; }
                   6842: 	}
                   6843: 	if ($found) {
                   6844: 	    my $username=$idmap{$found};
                   6845: 	    if ($found{'ids'}{$found}) {
                   6846: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
                   6847: 					 $line,'duplicateID',$found);
1.194     albertel 6848: 		return(1,$currentphase);
1.157     albertel 6849: 	    } elsif ($found{'usernames'}{$username}) {
                   6850: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
                   6851: 					 $line,'duplicateID',$username);
1.194     albertel 6852: 		return(1,$currentphase);
1.157     albertel 6853: 	    }
1.186     albertel 6854: 	    #FIXME store away line we previously saw the ID on to use above
1.157     albertel 6855: 	    $found{'ids'}{$found}++;
                   6856: 	    $found{'usernames'}{$username}++;
                   6857: 	} else {
                   6858: 	    if ($id =~ /^\s*$/) {
1.158     albertel 6859: 		my $username=&scan_data($scan_data,"$i.user");
1.157     albertel 6860: 		if (defined($username) && $found{'usernames'}{$username}) {
                   6861: 		    &scantron_get_correction($r,$i,$scan_record,
                   6862: 					     \%scantron_config,
                   6863: 					     $line,'duplicateID',$username);
1.194     albertel 6864: 		    return(1,$currentphase);
1.157     albertel 6865: 		} elsif (!defined($username)) {
                   6866: 		    &scantron_get_correction($r,$i,$scan_record,
                   6867: 					     \%scantron_config,
                   6868: 					     $line,'incorrectID');
1.194     albertel 6869: 		    return(1,$currentphase);
1.157     albertel 6870: 		}
                   6871: 		$found{'usernames'}{$username}++;
                   6872: 	    } else {
                   6873: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
                   6874: 					 $line,'incorrectID');
1.194     albertel 6875: 		return(1,$currentphase);
1.157     albertel 6876: 	    }
                   6877: 	}
                   6878:     }
                   6879: 
                   6880:     return (0,$currentphase+1);
                   6881: }
                   6882: 
1.423     albertel 6883: 
1.157     albertel 6884: sub scantron_get_correction {
                   6885:     my ($r,$i,$scan_record,$scan_config,$line,$error,$arg)=@_;
1.454     banghart 6886: #FIXME in the case of a duplicated ID the previous line, probably need
1.157     albertel 6887: #to show both the current line and the previous one and allow skipping
                   6888: #the previous one or the current one
                   6889: 
1.333     albertel 6890:     if ( $$scan_record{'scantron.PaperID'} =~ /\S/) {
1.492     albertel 6891: 	$r->print("<p>".&mt("<b>An error was detected ($error)</b>".
                   6892: 			    " for PaperID <tt>[_1]</tt>",
                   6893: 			    $$scan_record{'scantron.PaperID'})."</p> \n");
1.157     albertel 6894:     } else {
1.492     albertel 6895: 	$r->print("<p>".&mt("<b>An error was detected ($error)</b>".
                   6896: 			    " in scanline [_1] <pre>[_2]</pre>",
                   6897: 			    $i,$line)."</p> \n");
                   6898:     }
                   6899:     my $message="<p>".&mt("The ID on the form is  <tt>[_1]</tt><br />".
                   6900: 			  "The name on the paper is [_2],[_3]",
                   6901: 			  $$scan_record{'scantron.ID'},
                   6902: 			  $$scan_record{'scantron.LastName'},
                   6903: 			  $$scan_record{'scantron.FirstName'})."</p>";
1.242     albertel 6904: 
1.157     albertel 6905:     $r->print('<input type="hidden" name="scantron_corrections" value="'.$error.'" />'."\n");
                   6906:     $r->print('<input type="hidden" name="scantron_line" value="'.$i.'" />'."\n");
1.503     raeburn  6907:                            # Array populated for doublebubble or
                   6908:     my @lines_to_correct;  # missingbubble errors to build javascript
                   6909:                            # to validate radio button checking   
                   6910: 
1.157     albertel 6911:     if ($error =~ /ID$/) {
1.186     albertel 6912: 	if ($error eq 'incorrectID') {
1.492     albertel 6913: 	    $r->print("<p>".&mt("The encoded ID is not in the classlist").
                   6914: 		      "</p>\n");
1.157     albertel 6915: 	} elsif ($error eq 'duplicateID') {
1.492     albertel 6916: 	    $r->print("<p>".&mt("The encoded ID has also been used by a previous paper [_1]",$arg)."</p>\n");
1.157     albertel 6917: 	}
1.242     albertel 6918: 	$r->print($message);
1.492     albertel 6919: 	$r->print("<p>".&mt("How should I handle this?")." <br /> \n");
1.157     albertel 6920: 	$r->print("\n<ul><li> ");
                   6921: 	#FIXME it would be nice if this sent back the user ID and
                   6922: 	#could do partial userID matches
                   6923: 	$r->print(&Apache::loncommon::selectstudent_link('scantronupload',
                   6924: 				       'scantron_username','scantron_domain'));
                   6925: 	$r->print(": <input type='text' name='scantron_username' value='' />");
                   6926: 	$r->print("\n@".
1.257     albertel 6927: 		 &Apache::loncommon::select_dom_form($env{'request.role.domain'},'scantron_domain'));
1.157     albertel 6928: 
                   6929: 	$r->print('</li>');
1.186     albertel 6930:     } elsif ($error =~ /CODE$/) {
                   6931: 	if ($error eq 'incorrectCODE') {
1.492     albertel 6932: 	    $r->print("<p>".&mt("The encoded CODE is not in the list of possible CODEs.")."</p>\n");
1.186     albertel 6933: 	} elsif ($error eq 'duplicateCODE') {
1.492     albertel 6934: 	    $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 6935: 	}
1.492     albertel 6936: 	$r->print("<p>".&mt("The CODE on the form is  <tt>'[_1]'</tt>",
                   6937: 			    $$scan_record{'scantron.CODE'})."<br />\n");
1.242     albertel 6938: 	$r->print($message);
1.492     albertel 6939: 	$r->print("<p>".&mt("How should I handle this?")." <br /> \n");
1.187     albertel 6940: 	$r->print("\n<br /> ");
1.194     albertel 6941: 	my $i=0;
1.273     albertel 6942: 	if ($error eq 'incorrectCODE' 
                   6943: 	    && $$scan_record{'scantron.CODE'}=~/\S/ ) {
1.194     albertel 6944: 	    my ($max,$closest)=&scantron_get_closely_matching_CODEs($arg,$$scan_record{'scantron.CODE'});
1.278     albertel 6945: 	    if ($closest > 0) {
                   6946: 		foreach my $testcode (@{$closest}) {
                   6947: 		    my $checked='';
1.569     bisitz   6948: 		    if (!$i) { $checked=' checked="checked"'; }
1.492     albertel 6949: 		    $r->print("
                   6950:    <label>
1.569     bisitz   6951:        <input type='radio' name='scantron_CODE_resolution' value='use_closest_$i'$checked />
1.492     albertel 6952:        ".&mt("Use the similar CODE [_1] instead.",
                   6953: 	    "<b><tt>".$testcode."</tt></b>")."
                   6954:     </label>
                   6955:     <input type='hidden' name='scantron_CODE_closest_$i' value='$testcode' />");
1.278     albertel 6956: 		    $r->print("\n<br />");
                   6957: 		    $i++;
                   6958: 		}
1.194     albertel 6959: 	    }
                   6960: 	}
1.273     albertel 6961: 	if ($$scan_record{'scantron.CODE'}=~/\S/ ) {
1.569     bisitz   6962: 	    my $checked; if (!$i) { $checked=' checked="checked"'; }
1.492     albertel 6963: 	    $r->print("
                   6964:     <label>
1.569     bisitz   6965:         <input type='radio' name='scantron_CODE_resolution' value='use_unfound'$checked />
1.492     albertel 6966:        ".&mt("Use the CODE [_1] that is was on the paper, ignoring the error.",
                   6967: 	     "<b><tt>".$$scan_record{'scantron.CODE'}."</tt></b>")."
                   6968:     </label>");
1.273     albertel 6969: 	    $r->print("\n<br />");
                   6970: 	}
1.194     albertel 6971: 
1.597     wenzelju 6972: 	$r->print(&Apache::lonhtmlcommon::scripttag(<<ENDSCRIPT));
1.188     albertel 6973: function change_radio(field) {
1.190     albertel 6974:     var slct=document.scantronupload.scantron_CODE_resolution;
1.188     albertel 6975:     var i;
                   6976:     for (i=0;i<slct.length;i++) {
                   6977:         if (slct[i].value==field) { slct[i].checked=true; }
                   6978:     }
                   6979: }
                   6980: ENDSCRIPT
1.187     albertel 6981: 	my $href="/adm/pickcode?".
1.359     www      6982: 	   "form=".&escape("scantronupload").
                   6983: 	   "&scantron_format=".&escape($env{'form.scantron_format'}).
                   6984: 	   "&scantron_CODElist=".&escape($env{'form.scantron_CODElist'}).
                   6985: 	   "&curCODE=".&escape($$scan_record{'scantron.CODE'}).
                   6986: 	   "&scantron_selectfile=".&escape($env{'form.scantron_selectfile'});
1.332     albertel 6987: 	if ($env{'form.scantron_CODElist'} =~ /\S/) { 
1.492     albertel 6988: 	    $r->print("
                   6989:     <label>
                   6990:        <input type='radio' name='scantron_CODE_resolution' value='use_found' />
                   6991:        ".&mt("[_1]Select[_2] a CODE from the list of all CODEs and use it.",
                   6992: 	     "<a target='_blank' href='$href'>","</a>")."
                   6993:     </label> 
1.558     bisitz   6994:     ".&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 6995: 	    $r->print("\n<br />");
                   6996: 	}
1.492     albertel 6997: 	$r->print("
                   6998:     <label>
                   6999:        <input type='radio' name='scantron_CODE_resolution' value='use_typed' />
                   7000:        ".&mt("Use [_1] as the CODE.",
                   7001: 	     "</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 7002: 	$r->print("\n<br /><br />");
1.157     albertel 7003:     } elsif ($error eq 'doublebubble') {
1.503     raeburn  7004: 	$r->print("<p>".&mt("There have been multiple bubbles scanned for some question(s)")."</p>\n");
1.497     foxr     7005: 
                   7006: 	# The form field scantron_questions is acutally a list of line numbers.
                   7007: 	# represented by this form so:
                   7008: 
                   7009: 	my $line_list = &questions_to_line_list($arg);
                   7010: 
1.157     albertel 7011: 	$r->print('<input type="hidden" name="scantron_questions" value="'.
1.497     foxr     7012: 		  $line_list.'" />');
1.242     albertel 7013: 	$r->print($message);
1.492     albertel 7014: 	$r->print("<p>".&mt("Please indicate which bubble should be used for grading")."</p>");
1.157     albertel 7015: 	foreach my $question (@{$arg}) {
1.503     raeburn  7016: 	    my @linenums = &prompt_for_corrections($r,$question,$scan_config,
                   7017:                                                    $scan_record, $error);
1.524     raeburn  7018:             push(@lines_to_correct,@linenums);
1.157     albertel 7019: 	}
1.503     raeburn  7020:         $r->print(&verify_bubbles_checked(@lines_to_correct));
1.157     albertel 7021:     } elsif ($error eq 'missingbubble') {
1.492     albertel 7022: 	$r->print("<p>".&mt("There have been <b>no</b> bubbles scanned for some question(s)")."</p>\n");
1.242     albertel 7023: 	$r->print($message);
1.492     albertel 7024: 	$r->print("<p>".&mt("Please indicate which bubble should be used for grading.")."</p>");
1.503     raeburn  7025: 	$r->print(&mt("Some questions have no scanned bubbles.")."\n");
1.497     foxr     7026: 
1.503     raeburn  7027: 	# The form field scantron_questions is actually a list of line numbers not
1.497     foxr     7028: 	# a list of question numbers. Therefore:
                   7029: 	#
                   7030: 	
                   7031: 	my $line_list = &questions_to_line_list($arg);
                   7032: 
1.157     albertel 7033: 	$r->print('<input type="hidden" name="scantron_questions" value="'.
1.497     foxr     7034: 		  $line_list.'" />');
1.157     albertel 7035: 	foreach my $question (@{$arg}) {
1.503     raeburn  7036: 	    my @linenums = &prompt_for_corrections($r,$question,$scan_config,
                   7037:                                                    $scan_record, $error);
1.524     raeburn  7038:             push(@lines_to_correct,@linenums);
1.157     albertel 7039: 	}
1.503     raeburn  7040:         $r->print(&verify_bubbles_checked(@lines_to_correct));
1.157     albertel 7041:     } else {
                   7042: 	$r->print("\n<ul>");
                   7043:     }
                   7044:     $r->print("\n</li></ul>");
1.497     foxr     7045: }
                   7046: 
1.503     raeburn  7047: sub verify_bubbles_checked {
                   7048:     my (@ansnums) = @_;
                   7049:     my $ansnumstr = join('","',@ansnums);
                   7050:     my $warning = &mt("A bubble or 'No bubble' selection has not been made for one or more lines.");
1.597     wenzelju 7051:     my $output = &Apache::lonhtmlcommon::scripttag((<<ENDSCRIPT));
1.503     raeburn  7052: function verify_bubble_radio(form) {
                   7053:     var ansnumArray = new Array ("$ansnumstr");
                   7054:     var need_bubble_count = 0;
                   7055:     for (var i=0; i<ansnumArray.length; i++) {
                   7056:         if (form.elements["scantron_correct_Q_"+ansnumArray[i]].length > 1) {
                   7057:             var bubble_picked = 0; 
                   7058:             for (var j=0; j<form.elements["scantron_correct_Q_"+ansnumArray[i]].length; j++) {
                   7059:                 if (form.elements["scantron_correct_Q_"+ansnumArray[i]][j].checked == true) {
                   7060:                     bubble_picked = 1;
                   7061:                 }
                   7062:             }
                   7063:             if (bubble_picked == 0) {
                   7064:                 need_bubble_count ++;
                   7065:             }
                   7066:         }
                   7067:     }
                   7068:     if (need_bubble_count) {
                   7069:         alert("$warning");
                   7070:         return;
                   7071:     }
                   7072:     form.submit(); 
                   7073: }
                   7074: ENDSCRIPT
                   7075:     return $output;
                   7076: }
                   7077: 
1.497     foxr     7078: =pod
                   7079: 
                   7080: =item  questions_to_line_list
1.157     albertel 7081: 
1.497     foxr     7082: Converts a list of questions into a string of comma separated
                   7083: line numbers in the answer sheet used by the questions.  This is
                   7084: used to fill in the scantron_questions form field.
                   7085: 
                   7086:   Arguments:
                   7087:      questions    - Reference to an array of questions.
                   7088: 
                   7089: =cut
                   7090: 
                   7091: 
                   7092: sub questions_to_line_list {
                   7093:     my ($questions) = @_;
                   7094:     my @lines;
                   7095: 
1.503     raeburn  7096:     foreach my $item (@{$questions}) {
                   7097:         my $question = $item;
                   7098:         my ($first,$count,$last);
                   7099:         if ($item =~ /^(\d+)\.(\d+)$/) {
                   7100:             $question = $1;
                   7101:             my $subquestion = $2;
                   7102:             $first = $first_bubble_line{$question-1} + 1;
                   7103:             my @subans = split(/,/,$subdivided_bubble_lines{$question-1});
                   7104:             my $subcount = 1;
                   7105:             while ($subcount<$subquestion) {
                   7106:                 $first += $subans[$subcount-1];
                   7107:                 $subcount ++;
                   7108:             }
                   7109:             $count = $subans[$subquestion-1];
                   7110:         } else {
                   7111: 	    $first   = $first_bubble_line{$question-1} + 1;
                   7112: 	    $count   = $bubble_lines_per_response{$question-1};
                   7113:         }
1.506     raeburn  7114:         $last = $first+$count-1;
1.503     raeburn  7115:         push(@lines, ($first..$last));
1.497     foxr     7116:     }
                   7117:     return join(',', @lines);
                   7118: }
                   7119: 
                   7120: =pod 
                   7121: 
                   7122: =item prompt_for_corrections
                   7123: 
                   7124: Prompts for a potentially multiline correction to the
                   7125: user's bubbling (factors out common code from scantron_get_correction
                   7126: for multi and missing bubble cases).
                   7127: 
                   7128:  Arguments:
                   7129:    $r           - Apache request object.
                   7130:    $question    - The question number to prompt for.
                   7131:    $scan_config - The scantron file configuration hash.
                   7132:    $scan_record - Reference to the hash that has the the parsed scanlines.
1.503     raeburn  7133:    $error       - Type of error
1.497     foxr     7134: 
                   7135:  Implicit inputs:
                   7136:    %bubble_lines_per_response   - Starting line numbers for each question.
                   7137:                                   Numbered from 0 (but question numbers are from
                   7138:                                   1.
                   7139:    %first_bubble_line           - Starting bubble line for each question.
1.509     raeburn  7140:    %subdivided_bubble_lines     - optionresponse, matchresponse and rankresponse 
                   7141:                                   type problems render as separate sub-questions, 
1.503     raeburn  7142:                                   in exam mode. This hash contains a 
                   7143:                                   comma-separated list of the lines per 
                   7144:                                   sub-question.
1.510     raeburn  7145:    %responsetype_per_response   - essayresponse, formularesponse,
                   7146:                                   stringresponse, imageresponse, reactionresponse,
                   7147:                                   and organicresponse type problem parts can have
1.503     raeburn  7148:                                   multiple lines per response if the weight
                   7149:                                   assigned exceeds 10.  In this case, only
                   7150:                                   one bubble per line is permitted, but more 
                   7151:                                   than one line might contain bubbles, e.g.
                   7152:                                   bubbling of: line 1 - J, line 2 - J, 
                   7153:                                   line 3 - B would assign 22 points.  
1.497     foxr     7154: 
                   7155: =cut
                   7156: 
                   7157: sub prompt_for_corrections {
1.503     raeburn  7158:     my ($r, $question, $scan_config, $scan_record, $error) = @_;
                   7159:     my ($current_line,$lines);
                   7160:     my @linenums;
                   7161:     my $questionnum = $question;
                   7162:     if ($question =~ /^(\d+)\.(\d+)$/) {
                   7163:         $question = $1;
                   7164:         $current_line = $first_bubble_line{$question-1} + 1 ;
                   7165:         my $subquestion = $2;
                   7166:         my @subans = split(/,/,$subdivided_bubble_lines{$question-1});
                   7167:         my $subcount = 1;
                   7168:         while ($subcount<$subquestion) {
                   7169:             $current_line += $subans[$subcount-1];
                   7170:             $subcount ++;
                   7171:         }
                   7172:         $lines = $subans[$subquestion-1];
                   7173:     } else {
                   7174:         $current_line = $first_bubble_line{$question-1} + 1 ;
                   7175:         $lines        = $bubble_lines_per_response{$question-1};
                   7176:     }
1.497     foxr     7177:     if ($lines > 1) {
1.503     raeburn  7178:         $r->print(&mt('The group of bubble lines below responds to a single question.').'<br />');
                   7179:         if (($responsetype_per_response{$question-1} eq 'essayresponse') ||
                   7180:             ($responsetype_per_response{$question-1} eq 'formularesponse') ||
1.510     raeburn  7181:             ($responsetype_per_response{$question-1} eq 'stringresponse') ||
                   7182:             ($responsetype_per_response{$question-1} eq 'imageresponse') ||
                   7183:             ($responsetype_per_response{$question-1} eq 'reactionresponse') ||
                   7184:             ($responsetype_per_response{$question-1} eq 'organicresponse')) {
1.572     www      7185:             $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  7186:         } else {
                   7187:             $r->print(&mt("Select at most one bubble in a single line and select 'No Bubble' in all the other lines. ")."<br />");
                   7188:         }
1.497     foxr     7189:     }
                   7190:     for (my $i =0; $i < $lines; $i++) {
1.503     raeburn  7191:         my $selected = $$scan_record{"scantron.$current_line.answer"};
                   7192: 	&scantron_bubble_selector($r,$scan_config,$current_line, 
                   7193: 	        		  $questionnum,$error,split('', $selected));
1.524     raeburn  7194:         push(@linenums,$current_line);
1.497     foxr     7195: 	$current_line++;
                   7196:     }
                   7197:     if ($lines > 1) {
                   7198: 	$r->print("<hr /><br />");
                   7199:     }
1.503     raeburn  7200:     return @linenums;
1.157     albertel 7201: }
1.423     albertel 7202: 
                   7203: =pod
                   7204: 
                   7205: =item scantron_bubble_selector
                   7206:   
                   7207:    Generates the html radiobuttons to correct a single bubble line
1.424     albertel 7208:    possibly showing the existing the selected bubbles if known
1.423     albertel 7209: 
                   7210:  Arguments:
                   7211:     $r           - Apache request object
                   7212:     $scan_config - hash from &get_scantron_config()
1.497     foxr     7213:     $line        - Number of the line being displayed.
1.503     raeburn  7214:     $questionnum - Question number (may include subquestion)
                   7215:     $error       - Type of error.
1.497     foxr     7216:     @selected    - Array of bubbles picked on this line.
1.423     albertel 7217: 
                   7218: =cut
                   7219: 
1.157     albertel 7220: sub scantron_bubble_selector {
1.503     raeburn  7221:     my ($r,$scan_config,$line,$questionnum,$error,@selected)=@_;
1.157     albertel 7222:     my $max=$$scan_config{'Qlength'};
1.274     albertel 7223: 
                   7224:     my $scmode=$$scan_config{'Qon'};
                   7225:     if ($scmode eq 'number' || $scmode eq 'letter') { $max=10; }	     
                   7226: 
1.157     albertel 7227:     my @alphabet=('A'..'Z');
1.503     raeburn  7228:     $r->print(&Apache::loncommon::start_data_table().
                   7229:               &Apache::loncommon::start_data_table_row());
                   7230:     $r->print('<td rowspan="2" class="LC_leftcol_header">'.$line.'</td>');
1.497     foxr     7231:     for (my $i=0;$i<$max+1;$i++) {
                   7232: 	$r->print("\n".'<td align="center">');
                   7233: 	if ($selected[0] eq $alphabet[$i]) { $r->print('X'); shift(@selected) }
                   7234: 	else { $r->print('&nbsp;'); }
                   7235: 	$r->print('</td>');
                   7236:     }
1.503     raeburn  7237:     $r->print(&Apache::loncommon::end_data_table_row().
                   7238:               &Apache::loncommon::start_data_table_row());
1.497     foxr     7239:     for (my $i=0;$i<$max;$i++) {
                   7240: 	$r->print("\n".
                   7241: 		  '<td><label><input type="radio" name="scantron_correct_Q_'.
                   7242: 		  $line.'" value="'.$i.'" />'.$alphabet[$i]."</label></td>");
                   7243:     }
1.503     raeburn  7244:     my $nobub_checked = ' ';
                   7245:     if ($error eq 'missingbubble') {
                   7246:         $nobub_checked = ' checked = "checked" ';
                   7247:     }
                   7248:     $r->print("\n".'<td><label><input type="radio" name="scantron_correct_Q_'.
                   7249: 	      $line.'" value="none"'.$nobub_checked.'/>'.&mt('No bubble').
                   7250:               '</label>'."\n".'<input type="hidden" name="scantron_questionnum_Q_'.
                   7251:               $line.'" value="'.$questionnum.'" /></td>');
                   7252:     $r->print(&Apache::loncommon::end_data_table_row().
                   7253:               &Apache::loncommon::end_data_table());
1.157     albertel 7254: }
                   7255: 
1.423     albertel 7256: =pod
                   7257: 
                   7258: =item num_matches
                   7259: 
1.424     albertel 7260:    Counts the number of characters that are the same between the two arguments.
                   7261: 
                   7262:  Arguments:
                   7263:    $orig - CODE from the scanline
                   7264:    $code - CODE to match against
                   7265: 
                   7266:  Returns:
                   7267:    $count - integer count of the number of same characters between the
                   7268:             two arguments
                   7269: 
1.423     albertel 7270: =cut
                   7271: 
1.194     albertel 7272: sub num_matches {
                   7273:     my ($orig,$code) = @_;
                   7274:     my @code=split(//,$code);
                   7275:     my @orig=split(//,$orig);
                   7276:     my $same=0;
                   7277:     for (my $i=0;$i<scalar(@code);$i++) {
                   7278: 	if ($code[$i] eq $orig[$i]) { $same++; }
                   7279:     }
                   7280:     return $same;
                   7281: }
                   7282: 
1.423     albertel 7283: =pod
                   7284: 
                   7285: =item scantron_get_closely_matching_CODEs
                   7286: 
1.424     albertel 7287:    Cycles through all CODEs and finds the set that has the greatest
                   7288:    number of same characters as the provided CODE
                   7289: 
                   7290:  Arguments:
                   7291:    $allcodes - hash ref returned by &get_codes()
                   7292:    $CODE     - CODE from the current scanline
                   7293: 
                   7294:  Returns:
                   7295:    2 element list
                   7296:     - first elements is number of how closely matching the best fit is 
                   7297:       (5 means best set has 5 matching characters)
                   7298:     - second element is an arrary ref containing the set of valid CODEs
                   7299:       that best fit the passed in CODE
                   7300: 
1.423     albertel 7301: =cut
                   7302: 
1.194     albertel 7303: sub scantron_get_closely_matching_CODEs {
                   7304:     my ($allcodes,$CODE)=@_;
                   7305:     my @CODEs;
                   7306:     foreach my $testcode (sort(keys(%{$allcodes}))) {
                   7307: 	push(@{$CODEs[&num_matches($CODE,$testcode)]},$testcode);
                   7308:     }
                   7309: 
                   7310:     return ($#CODEs,$CODEs[-1]);
                   7311: }
                   7312: 
1.423     albertel 7313: =pod
                   7314: 
                   7315: =item get_codes
                   7316: 
1.424     albertel 7317:    Builds a hash which has keys of all of the valid CODEs from the selected
                   7318:    set of remembered CODEs.
                   7319: 
                   7320:  Arguments:
                   7321:   $old_name - name of the set of remembered CODEs
                   7322:   $cdom     - domain of the course
                   7323:   $cnum     - internal course name
                   7324: 
                   7325:  Returns:
                   7326:   %allcodes - keys are the valid CODEs, values are all 1
                   7327: 
1.423     albertel 7328: =cut
                   7329: 
1.194     albertel 7330: sub get_codes {
1.280     foxr     7331:     my ($old_name, $cdom, $cnum) = @_;
                   7332:     if (!$old_name) {
                   7333: 	$old_name=$env{'form.scantron_CODElist'};
                   7334:     }
                   7335:     if (!$cdom) {
                   7336: 	$cdom =$env{'course.'.$env{'request.course.id'}.'.domain'};
                   7337:     }
                   7338:     if (!$cnum) {
                   7339: 	$cnum =$env{'course.'.$env{'request.course.id'}.'.num'};
                   7340:     }
1.278     albertel 7341:     my %result=&Apache::lonnet::get('CODEs',[$old_name,"type\0$old_name"],
                   7342: 				    $cdom,$cnum);
                   7343:     my %allcodes;
                   7344:     if ($result{"type\0$old_name"} eq 'number') {
                   7345: 	%allcodes=map {($_,1)} split(',',$result{$old_name});
                   7346:     } else {
                   7347: 	%allcodes=map {(&Apache::lonprintout::num_to_letters($_),1)} split(',',$result{$old_name});
                   7348:     }
1.194     albertel 7349:     return %allcodes;
                   7350: }
                   7351: 
1.423     albertel 7352: =pod
                   7353: 
                   7354: =item scantron_validate_CODE
                   7355: 
1.424     albertel 7356:    Validates all scanlines in the selected file to not have any
                   7357:    invalid or underspecified CODEs and that none of the codes are
                   7358:    duplicated if this was requested.
                   7359: 
1.423     albertel 7360: =cut
                   7361: 
1.157     albertel 7362: sub scantron_validate_CODE {
                   7363:     my ($r,$currentphase) = @_;
1.257     albertel 7364:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.186     albertel 7365:     if ($scantron_config{'CODElocation'} &&
                   7366: 	$scantron_config{'CODEstart'} &&
                   7367: 	$scantron_config{'CODElength'}) {
1.257     albertel 7368: 	if (!defined($env{'form.scantron_CODElist'})) {
1.186     albertel 7369: 	    &FIXME_blow_up()
                   7370: 	}
                   7371:     } else {
                   7372: 	return (0,$currentphase+1);
                   7373:     }
                   7374:     
                   7375:     my %usedCODEs;
                   7376: 
1.194     albertel 7377:     my %allcodes=&get_codes();
1.186     albertel 7378: 
1.582     raeburn  7379:     my $nav_error;
                   7380:     &scantron_get_maxbubble(\$nav_error); # parse needs the lines per response array.
                   7381:     if ($nav_error) {
                   7382:         $r->print(&navmap_errormsg());
                   7383:         return(1,$currentphase);
                   7384:     }
1.447     foxr     7385: 
1.186     albertel 7386:     my ($scanlines,$scan_data)=&scantron_getfile();
                   7387:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
1.200     albertel 7388: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.186     albertel 7389: 	if ($line=~/^[\s\cz]*$/) { next; }
                   7390: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
                   7391: 						 $scan_data);
                   7392: 	my $CODE=$$scan_record{'scantron.CODE'};
                   7393: 	my $error=0;
1.224     albertel 7394: 	if (!&Apache::lonnet::validCODE($CODE)) {
                   7395: 	    &scantron_get_correction($r,$i,$scan_record,
                   7396: 				     \%scantron_config,
                   7397: 				     $line,'incorrectCODE',\%allcodes);
                   7398: 	    return(1,$currentphase);
                   7399: 	}
1.221     albertel 7400: 	if (%allcodes && !exists($allcodes{$CODE}) 
                   7401: 	    && !$$scan_record{'scantron.useCODE'}) {
1.186     albertel 7402: 	    &scantron_get_correction($r,$i,$scan_record,
                   7403: 				     \%scantron_config,
1.194     albertel 7404: 				     $line,'incorrectCODE',\%allcodes);
                   7405: 	    return(1,$currentphase);
1.186     albertel 7406: 	}
1.214     albertel 7407: 	if (exists($usedCODEs{$CODE}) 
1.257     albertel 7408: 	    && $env{'form.scantron_CODEunique'} eq 'yes'
1.192     albertel 7409: 	    && !$$scan_record{'scantron.CODE_ignore_dup'}) {
1.186     albertel 7410: 	    &scantron_get_correction($r,$i,$scan_record,
                   7411: 				     \%scantron_config,
1.194     albertel 7412: 				     $line,'duplicateCODE',$usedCODEs{$CODE});
                   7413: 	    return(1,$currentphase);
1.186     albertel 7414: 	}
1.524     raeburn  7415: 	push(@{$usedCODEs{$CODE}},$$scan_record{'scantron.PaperID'});
1.186     albertel 7416:     }
1.157     albertel 7417:     return (0,$currentphase+1);
                   7418: }
                   7419: 
1.423     albertel 7420: =pod
                   7421: 
                   7422: =item scantron_validate_doublebubble
                   7423: 
1.424     albertel 7424:    Validates all scanlines in the selected file to not have any
                   7425:    bubble lines with multiple bubbles marked.
                   7426: 
1.423     albertel 7427: =cut
                   7428: 
1.157     albertel 7429: sub scantron_validate_doublebubble {
                   7430:     my ($r,$currentphase) = @_;
                   7431:     #get student info
                   7432:     my $classlist=&Apache::loncoursedata::get_classlist();
                   7433:     my %idmap=&username_to_idmap($classlist);
                   7434: 
                   7435:     #get scantron line setup
1.257     albertel 7436:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.157     albertel 7437:     my ($scanlines,$scan_data)=&scantron_getfile();
1.583     raeburn  7438:     my $nav_error;
                   7439:     &scantron_get_maxbubble(\$nav_error); # parse needs the bubble line array.
                   7440:     if ($nav_error) {
                   7441:         $r->print(&navmap_errormsg());
                   7442:         return(1,$currentphase);
                   7443:     }
1.447     foxr     7444: 
1.157     albertel 7445:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
1.200     albertel 7446: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.157     albertel 7447: 	if ($line=~/^[\s\cz]*$/) { next; }
                   7448: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
                   7449: 						 $scan_data);
                   7450: 	if (!defined($$scan_record{'scantron.doubleerror'})) { next; }
                   7451: 	&scantron_get_correction($r,$i,$scan_record,\%scantron_config,$line,
                   7452: 				 'doublebubble',
                   7453: 				 $$scan_record{'scantron.doubleerror'});
                   7454:     	return (1,$currentphase);
                   7455:     }
                   7456:     return (0,$currentphase+1);
                   7457: }
                   7458: 
1.423     albertel 7459: 
1.503     raeburn  7460: sub scantron_get_maxbubble {
1.582     raeburn  7461:     my ($nav_error) = @_;
1.257     albertel 7462:     if (defined($env{'form.scantron_maxbubble'}) &&
                   7463: 	$env{'form.scantron_maxbubble'}) {
1.447     foxr     7464: 	&restore_bubble_lines();
1.257     albertel 7465: 	return $env{'form.scantron_maxbubble'};
1.191     albertel 7466:     }
1.330     albertel 7467: 
1.447     foxr     7468:     my (undef, undef, $sequence) =
1.257     albertel 7469: 	&Apache::lonnet::decode_symb($env{'form.selectpage'});
1.330     albertel 7470: 
1.447     foxr     7471:     my $navmap=Apache::lonnavmaps::navmap->new();
1.582     raeburn  7472:     unless (ref($navmap)) {
                   7473:         if (ref($nav_error)) {
                   7474:             $$nav_error = 1;
                   7475:         }
1.591     raeburn  7476:         return;
1.582     raeburn  7477:     }
1.191     albertel 7478:     my $map=$navmap->getResourceByUrl($sequence);
                   7479:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
1.330     albertel 7480: 
                   7481:     &Apache::lonxml::clear_problem_counter();
                   7482: 
1.557     raeburn  7483:     my $uname       = $env{'user.name'};
                   7484:     my $udom        = $env{'user.domain'};
1.435     foxr     7485:     my $cid         = $env{'request.course.id'};
                   7486:     my $total_lines = 0;
                   7487:     %bubble_lines_per_response = ();
1.447     foxr     7488:     %first_bubble_line         = ();
1.503     raeburn  7489:     %subdivided_bubble_lines   = ();
                   7490:     %responsetype_per_response = ();
1.554     raeburn  7491: 
1.447     foxr     7492:     my $response_number = 0;
                   7493:     my $bubble_line     = 0;
1.191     albertel 7494:     foreach my $resource (@resources) {
1.542     raeburn  7495:         my ($analysis,$parts) = &scantron_partids_tograde($resource,$cid,$uname,$udom);
                   7496:         if ((ref($analysis) eq 'HASH') && (ref($parts) eq 'ARRAY')) {
                   7497: 	    foreach my $part_id (@{$parts}) {
                   7498:                 my $lines;
                   7499: 
                   7500: 	        # TODO - make this a persistent hash not an array.
                   7501: 
                   7502:                 # optionresponse, matchresponse and rankresponse type items 
                   7503:                 # render as separate sub-questions in exam mode.
                   7504:                 if (($analysis->{$part_id.'.type'} eq 'optionresponse') ||
                   7505:                     ($analysis->{$part_id.'.type'} eq 'matchresponse') ||
                   7506:                     ($analysis->{$part_id.'.type'} eq 'rankresponse')) {
                   7507:                     my ($numbub,$numshown);
                   7508:                     if ($analysis->{$part_id.'.type'} eq 'optionresponse') {
                   7509:                         if (ref($analysis->{$part_id.'.options'}) eq 'ARRAY') {
                   7510:                             $numbub = scalar(@{$analysis->{$part_id.'.options'}});
                   7511:                         }
                   7512:                     } elsif ($analysis->{$part_id.'.type'} eq 'matchresponse') {
                   7513:                         if (ref($analysis->{$part_id.'.items'}) eq 'ARRAY') {
                   7514:                             $numbub = scalar(@{$analysis->{$part_id.'.items'}});
                   7515:                         }
                   7516:                     } elsif ($analysis->{$part_id.'.type'} eq 'rankresponse') {
                   7517:                         if (ref($analysis->{$part_id.'.foils'}) eq 'ARRAY') {
                   7518:                             $numbub = scalar(@{$analysis->{$part_id.'.foils'}});
                   7519:                         }
                   7520:                     }
                   7521:                     if (ref($analysis->{$part_id.'.shown'}) eq 'ARRAY') {
                   7522:                         $numshown = scalar(@{$analysis->{$part_id.'.shown'}});
                   7523:                     }
                   7524:                     my $bubbles_per_line = 10;
                   7525:                     my $inner_bubble_lines = int($numbub/$bubbles_per_line);
                   7526:                     if (($numbub % $bubbles_per_line) != 0) {
                   7527:                         $inner_bubble_lines++;
                   7528:                     }
                   7529:                     for (my $i=0; $i<$numshown; $i++) {
                   7530:                         $subdivided_bubble_lines{$response_number} .= 
                   7531:                             $inner_bubble_lines.',';
                   7532:                     }
                   7533:                     $subdivided_bubble_lines{$response_number} =~ s/,$//;
                   7534:                     $lines = $numshown * $inner_bubble_lines;
                   7535:                 } else {
                   7536:                     $lines = $analysis->{"$part_id.bubble_lines"};
                   7537:                 } 
                   7538: 
                   7539:                 $first_bubble_line{$response_number} = $bubble_line;
                   7540: 	        $bubble_lines_per_response{$response_number} = $lines;
                   7541:                 $responsetype_per_response{$response_number} = 
                   7542:                     $analysis->{$part_id.'.type'};
                   7543: 	        $response_number++;
                   7544: 
                   7545: 	        $bubble_line +=  $lines;
                   7546: 	        $total_lines +=  $lines;
                   7547: 	    }
                   7548:         }
                   7549:     }
1.552     raeburn  7550:     &Apache::lonnet::delenv('scantron.');
1.542     raeburn  7551: 
                   7552:     &save_bubble_lines();
                   7553:     $env{'form.scantron_maxbubble'} =
                   7554: 	$total_lines;
                   7555:     return $env{'form.scantron_maxbubble'};
                   7556: }
1.523     raeburn  7557: 
1.157     albertel 7558: sub scantron_validate_missingbubbles {
                   7559:     my ($r,$currentphase) = @_;
                   7560:     #get student info
                   7561:     my $classlist=&Apache::loncoursedata::get_classlist();
                   7562:     my %idmap=&username_to_idmap($classlist);
                   7563: 
                   7564:     #get scantron line setup
1.257     albertel 7565:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.157     albertel 7566:     my ($scanlines,$scan_data)=&scantron_getfile();
1.582     raeburn  7567:     my $nav_error;
                   7568:     my $max_bubble=&scantron_get_maxbubble(\$nav_error);
                   7569:     if ($nav_error) {
                   7570:         return(1,$currentphase);
                   7571:     }
1.157     albertel 7572:     if (!$max_bubble) { $max_bubble=2**31; }
                   7573:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
1.200     albertel 7574: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.157     albertel 7575: 	if ($line=~/^[\s\cz]*$/) { next; }
                   7576: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
                   7577: 						 $scan_data);
                   7578: 	if (!defined($$scan_record{'scantron.missingerror'})) { next; }
                   7579: 	my @to_correct;
1.470     foxr     7580: 	
                   7581: 	# Probably here's where the error is...
                   7582: 
1.157     albertel 7583: 	foreach my $missing (@{$$scan_record{'scantron.missingerror'}}) {
1.505     raeburn  7584:             my $lastbubble;
                   7585:             if ($missing =~ /^(\d+)\.(\d+)$/) {
                   7586:                my $question = $1;
                   7587:                my $subquestion = $2;
                   7588:                if (!defined($first_bubble_line{$question -1})) { next; }
                   7589:                my $first = $first_bubble_line{$question-1};
                   7590:                my @subans = split(/,/,$subdivided_bubble_lines{$question-1});
                   7591:                my $subcount = 1;
                   7592:                while ($subcount<$subquestion) {
                   7593:                    $first += $subans[$subcount-1];
                   7594:                    $subcount ++;
                   7595:                }
                   7596:                my $count = $subans[$subquestion-1];
                   7597:                $lastbubble = $first + $count;
                   7598:             } else {
                   7599:                 if (!defined($first_bubble_line{$missing - 1})) { next; }
                   7600:                 $lastbubble = $first_bubble_line{$missing - 1} + $bubble_lines_per_response{$missing - 1};
                   7601:             }
                   7602:             if ($lastbubble > $max_bubble) { next; }
1.157     albertel 7603: 	    push(@to_correct,$missing);
                   7604: 	}
                   7605: 	if (@to_correct) {
                   7606: 	    &scantron_get_correction($r,$i,$scan_record,\%scantron_config,
                   7607: 				     $line,'missingbubble',\@to_correct);
                   7608: 	    return (1,$currentphase);
                   7609: 	}
                   7610: 
                   7611:     }
                   7612:     return (0,$currentphase+1);
                   7613: }
                   7614: 
1.423     albertel 7615: 
1.82      albertel 7616: sub scantron_process_students {
1.75      albertel 7617:     my ($r) = @_;
1.513     foxr     7618: 
1.257     albertel 7619:     my (undef,undef,$sequence)=&Apache::lonnet::decode_symb($env{'form.selectpage'});
1.324     albertel 7620:     my ($symb)=&get_symb($r);
1.513     foxr     7621:     if (!$symb) {
                   7622: 	return '';
                   7623:     }
1.324     albertel 7624:     my $default_form_data=&defaultFormData($symb);
1.82      albertel 7625: 
1.257     albertel 7626:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.157     albertel 7627:     my ($scanlines,$scan_data)=&scantron_getfile();
1.82      albertel 7628:     my $classlist=&Apache::loncoursedata::get_classlist();
                   7629:     my %idmap=&username_to_idmap($classlist);
1.132     bowersj2 7630:     my $navmap=Apache::lonnavmaps::navmap->new();
1.582     raeburn  7631:     unless (ref($navmap)) {
                   7632:         $r->print(&navmap_errormsg());
                   7633:         return '';
                   7634:     }  
1.83      albertel 7635:     my $map=$navmap->getResourceByUrl($sequence);
                   7636:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
1.557     raeburn  7637:     my (%grader_partids_by_symb,%grader_randomlists_by_symb);
                   7638:     &graders_resources_pass(\@resources,\%grader_partids_by_symb,
                   7639:                             \%grader_randomlists_by_symb);
1.586     raeburn  7640:     my $resource_error;
1.557     raeburn  7641:     foreach my $resource (@resources) {
1.586     raeburn  7642:         my $ressymb;
                   7643:         if (ref($resource)) {
                   7644:             $ressymb = $resource->symb();
                   7645:         } else {
                   7646:             $resource_error = 1;
                   7647:             last;
                   7648:         }
1.557     raeburn  7649:         my ($analysis,$parts) =
                   7650:             &scantron_partids_tograde($resource,$env{'request.course.id'},
                   7651:                                       $env{'user.name'},$env{'user.domain'},1);
                   7652:         $grader_partids_by_symb{$ressymb} = $parts;
                   7653:         if (ref($analysis) eq 'HASH') {
                   7654:             if (ref($analysis->{'parts_withrandomlist'}) eq 'ARRAY') {
                   7655:                 $grader_randomlists_by_symb{$ressymb} = 
                   7656:                     $analysis->{'parts_withrandomlist'};
                   7657:             }
                   7658:         }
                   7659:     }
1.586     raeburn  7660:     if ($resource_error) {
                   7661:         $r->print(&navmap_errormsg());
                   7662:         return '';
                   7663:     }
1.557     raeburn  7664: 
1.554     raeburn  7665:     my ($uname,$udom);
1.82      albertel 7666:     my $result= <<SCANTRONFORM;
1.81      albertel 7667: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantronupload">
                   7668:   <input type="hidden" name="command" value="scantron_configphase" />
                   7669:   $default_form_data
                   7670: SCANTRONFORM
1.82      albertel 7671:     $r->print($result);
                   7672: 
                   7673:     my @delayqueue;
1.542     raeburn  7674:     my (%completedstudents,%scandata);
1.140     albertel 7675:     
1.520     www      7676:     my $lock=&Apache::lonnet::set_lock(&mt('Grading bubblesheet exam'));
1.200     albertel 7677:     my $count=&get_todo_count($scanlines,$scan_data);
1.575     www      7678:     my %prog_state=&Apache::lonhtmlcommon::Create_PrgWin($r,'Bubblesheet Status',
                   7679:  				    'Bubblesheet Progress',$count,
1.195     albertel 7680: 				    'inline',undef,'scantronupload');
1.140     albertel 7681:     &Apache::lonhtmlcommon::Update_PrgWin($r,\%prog_state,
                   7682: 					  'Processing first student');
1.542     raeburn  7683:     $r->print('<br />');
1.140     albertel 7684:     my $start=&Time::HiRes::time();
1.158     albertel 7685:     my $i=-1;
1.542     raeburn  7686:     my $started;
1.447     foxr     7687: 
1.582     raeburn  7688:     my $nav_error;
                   7689:     &scantron_get_maxbubble(\$nav_error); # Need the bubble lines array to parse.
                   7690:     if ($nav_error) {
                   7691:         $r->print(&navmap_errormsg());
                   7692:         return '';
                   7693:     }
                   7694: 
1.513     foxr     7695:     # If an ssi failed in scantron_get_maxbubble, put an error message out to
                   7696:     # the user and return.
                   7697: 
                   7698:     if ($ssi_error) {
                   7699: 	$r->print("</form>");
                   7700: 	&ssi_print_error($r);
                   7701: 	$r->print(&show_grading_menu_form($symb));
1.520     www      7702:         &Apache::lonnet::remove_lock($lock);
1.513     foxr     7703: 	return '';		# Dunno why the other returns return '' rather than just returning.
                   7704:     }
1.447     foxr     7705: 
1.542     raeburn  7706:     my %lettdig = &letter_to_digits();
                   7707:     my $numletts = scalar(keys(%lettdig));
                   7708: 
1.157     albertel 7709:     while ($i<$scanlines->{'count'}) {
                   7710:  	($uname,$udom)=('','');
                   7711:  	$i++;
1.200     albertel 7712:  	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.157     albertel 7713:  	if ($line=~/^[\s\cz]*$/) { next; }
1.200     albertel 7714: 	if ($started) {
                   7715: 	    &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state,
                   7716: 						     'last student');
                   7717: 	}
                   7718: 	$started=1;
1.157     albertel 7719:  	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
                   7720:  						 $scan_data);
                   7721:  	unless ($uname=&scantron_find_student($scan_record,$scan_data,
                   7722:  					      \%idmap,$i)) {
                   7723:   	    &scantron_add_delay(\@delayqueue,$line,
                   7724:  				'Unable to find a student that matches',1);
                   7725:  	    next;
                   7726:   	}
                   7727:  	if (exists $completedstudents{$uname}) {
                   7728:  	    &scantron_add_delay(\@delayqueue,$line,
                   7729:  				'Student '.$uname.' has multiple sheets',2);
                   7730:  	    next;
                   7731:  	}
                   7732:   	($uname,$udom)=split(/:/,$uname);
1.330     albertel 7733: 
1.586     raeburn  7734:         my (%partids_by_symb,$res_error);
1.554     raeburn  7735:         foreach my $resource (@resources) {
1.586     raeburn  7736:             my $ressymb;
                   7737:             if (ref($resource)) {
                   7738:                 $ressymb = $resource->symb();
                   7739:             } else {
                   7740:                 $res_error = 1;
                   7741:                 last;
                   7742:             }
1.557     raeburn  7743:             if ((exists($grader_randomlists_by_symb{$ressymb})) ||
                   7744:                 (ref($grader_partids_by_symb{$ressymb}) ne 'ARRAY')) {
                   7745:                 my ($analysis,$parts) =
                   7746:                     &scantron_partids_tograde($resource,$env{'request.course.id'},$uname,$udom);
                   7747:                 $partids_by_symb{$ressymb} = $parts;
                   7748:             } else {
                   7749:                 $partids_by_symb{$ressymb} = $grader_partids_by_symb{$ressymb};
                   7750:             }
1.554     raeburn  7751:         }
                   7752: 
1.586     raeburn  7753:         if ($res_error) {
                   7754:             &scantron_add_delay(\@delayqueue,$line,
                   7755:                                 'An error occurred while grading student '.$uname,2);
                   7756:             next;
                   7757:         }
                   7758: 
1.330     albertel 7759: 	&Apache::lonxml::clear_problem_counter();
1.514     raeburn  7760:   	&Apache::lonnet::appenv($scan_record);
1.376     albertel 7761: 
                   7762: 	if (&scantron_clear_skip($scanlines,$scan_data,$i)) {
                   7763: 	    &scantron_putfile($scanlines,$scan_data);
                   7764: 	}
1.161     albertel 7765: 	
1.542     raeburn  7766:         my $scancode;
                   7767:         if ((exists($scan_record->{'scantron.CODE'})) &&
                   7768:             (&Apache::lonnet::validCODE($scan_record->{'scantron.CODE'}))) {
                   7769:             $scancode = $scan_record->{'scantron.CODE'};
                   7770:         } else {
                   7771:             $scancode = '';
                   7772:         }
                   7773: 
                   7774:         if (&grade_student_bubbles($r,$uname,$udom,$scan_record,$scancode,
1.554     raeburn  7775:                                    \@resources,\%partids_by_symb) eq 'ssi_error') {
1.542     raeburn  7776:             $ssi_error = 0; # So end of handler error message does not trigger.
                   7777:             $r->print("</form>");
                   7778:             &ssi_print_error($r);
                   7779:             $r->print(&show_grading_menu_form($symb));
                   7780:             &Apache::lonnet::remove_lock($lock);
                   7781:             return '';      # Why return ''?  Beats me.
                   7782:         }
1.513     foxr     7783: 
1.140     albertel 7784: 	$completedstudents{$uname}={'line'=>$line};
1.542     raeburn  7785:         if ($env{'form.verifyrecord'}) {
                   7786:             my $lastpos = $env{'form.scantron_maxbubble'}*$scantron_config{'Qlength'};
                   7787:             my $studentdata = substr($line,$scantron_config{'Qstart'}-1,$lastpos);
                   7788:             chomp($studentdata);
                   7789:             $studentdata =~ s/\r$//;
                   7790:             my $studentrecord = '';
                   7791:             my $counter = -1;
                   7792:             foreach my $resource (@resources) {
1.554     raeburn  7793:                 my $ressymb = $resource->symb();
1.542     raeburn  7794:                 ($counter,my $recording) =
                   7795:                     &verify_scantron_grading($resource,$udom,$uname,$env{'request.course.id'},
1.554     raeburn  7796:                                              $counter,$studentdata,$partids_by_symb{$ressymb},
1.542     raeburn  7797:                                              \%scantron_config,\%lettdig,$numletts);
                   7798:                 $studentrecord .= $recording;
                   7799:             }
                   7800:             if ($studentrecord ne $studentdata) {
1.554     raeburn  7801:                 &Apache::lonxml::clear_problem_counter();
                   7802:                 if (&grade_student_bubbles($r,$uname,$udom,$scan_record,$scancode,
                   7803:                                            \@resources,\%partids_by_symb) eq 'ssi_error') {
                   7804:                     $ssi_error = 0; # So end of handler error message does not trigger.
                   7805:                     $r->print("</form>");
                   7806:                     &ssi_print_error($r);
                   7807:                     $r->print(&show_grading_menu_form($symb));
                   7808:                     &Apache::lonnet::remove_lock($lock);
                   7809:                     delete($completedstudents{$uname});
                   7810:                     return '';
                   7811:                 }
1.542     raeburn  7812:                 $counter = -1;
                   7813:                 $studentrecord = '';
                   7814:                 foreach my $resource (@resources) {
1.554     raeburn  7815:                     my $ressymb = $resource->symb();
1.542     raeburn  7816:                     ($counter,my $recording) =
                   7817:                         &verify_scantron_grading($resource,$udom,$uname,$env{'request.course.id'},
1.554     raeburn  7818:                                                  $counter,$studentdata,$partids_by_symb{$ressymb},
1.542     raeburn  7819:                                                  \%scantron_config,\%lettdig,$numletts);
                   7820:                     $studentrecord .= $recording;
                   7821:                 }
                   7822:                 if ($studentrecord ne $studentdata) {
                   7823:                     $r->print('<p><span class="LC_error">');
                   7824:                     if ($scancode eq '') {
                   7825:                         $r->print(&mt('Mismatch grading bubble sheet for user: [_1] with ID: [_2].',
                   7826:                                   $uname.':'.$udom,$scan_record->{'scantron.ID'}));
                   7827:                     } else {
                   7828:                         $r->print(&mt('Mismatch grading bubble sheet for user: [_1] with ID: [_2] and CODE: [_3].',
                   7829:                                   $uname.':'.$udom,$scan_record->{'scantron.ID'},$scancode));
                   7830:                     }
                   7831:                     $r->print('</span><br />'.&Apache::loncommon::start_data_table()."\n".
                   7832:                               &Apache::loncommon::start_data_table_header_row()."\n".
                   7833:                               '<th>'.&mt('Source').'</th><th>'.&mt('Bubbled responses').'</th>'.
                   7834:                               &Apache::loncommon::end_data_table_header_row()."\n".
                   7835:                               &Apache::loncommon::start_data_table_row().
                   7836:                               '<td>'.&mt('Bubble Sheet').'</td>'.
                   7837:                               '<td><span class="LC_nobreak">'.$studentdata.'</span></td>'.
                   7838:                               &Apache::loncommon::end_data_table_row().
                   7839:                               &Apache::loncommon::start_data_table_row().
                   7840:                               '<td>Stored submissions</td>'.
                   7841:                               '<td><span class="LC_nobreak">'.$studentrecord.'</span></td>'."\n".
                   7842:                               &Apache::loncommon::end_data_table_row().
                   7843:                               &Apache::loncommon::end_data_table().'</p>');
                   7844:                 } else {
                   7845:                     $r->print('<br /><span class="LC_warning">'.
                   7846:                              &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 />'.
                   7847:                              &mt("As a consequence, this user's submission history records two tries.").
                   7848:                                  '</span><br />');
                   7849:                 }
                   7850:             }
                   7851:         }
1.543     raeburn  7852:         if (&Apache::loncommon::connection_aborted($r)) { last; }
1.140     albertel 7853:     } continue {
1.330     albertel 7854: 	&Apache::lonxml::clear_problem_counter();
1.552     raeburn  7855: 	&Apache::lonnet::delenv('scantron.');
1.82      albertel 7856:     }
1.140     albertel 7857:     &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
1.520     www      7858:     &Apache::lonnet::remove_lock($lock);
1.172     albertel 7859: #    my $lasttime = &Time::HiRes::time()-$start;
                   7860: #    $r->print("<p>took $lasttime</p>");
1.140     albertel 7861: 
1.200     albertel 7862:     $r->print("</form>");
1.324     albertel 7863:     $r->print(&show_grading_menu_form($symb));
1.157     albertel 7864:     return '';
1.75      albertel 7865: }
1.157     albertel 7866: 
1.557     raeburn  7867: sub graders_resources_pass {
                   7868:     my ($resources,$grader_partids_by_symb,$grader_randomlists_by_symb) = @_;
                   7869:     if ((ref($resources) eq 'ARRAY') && (ref($grader_partids_by_symb)) && 
                   7870:         (ref($grader_randomlists_by_symb) eq 'HASH')) {
                   7871:         foreach my $resource (@{$resources}) {
                   7872:             my $ressymb = $resource->symb();
                   7873:             my ($analysis,$parts) =
                   7874:                 &scantron_partids_tograde($resource,$env{'request.course.id'},
                   7875:                                           $env{'user.name'},$env{'user.domain'},1);
                   7876:             $grader_partids_by_symb->{$ressymb} = $parts;
                   7877:             if (ref($analysis) eq 'HASH') {
                   7878:                 if (ref($analysis->{'parts_withrandomlist'}) eq 'ARRAY') {
                   7879:                     $grader_randomlists_by_symb->{$ressymb} =
                   7880:                         $analysis->{'parts_withrandomlist'};
                   7881:                 }
                   7882:             }
                   7883:         }
                   7884:     }
                   7885:     return;
                   7886: }
                   7887: 
1.542     raeburn  7888: sub grade_student_bubbles {
1.554     raeburn  7889:     my ($r,$uname,$udom,$scan_record,$scancode,$resources,$parts) = @_;
                   7890:     if (ref($resources) eq 'ARRAY') {
                   7891:         my $count = 0;
                   7892:         foreach my $resource (@{$resources}) {
                   7893:             my $ressymb = $resource->symb();
                   7894:             my %form = ('submitted'      => 'scantron',
                   7895:                         'grade_target'   => 'grade',
                   7896:                         'grade_username' => $uname,
                   7897:                         'grade_domain'   => $udom,
                   7898:                         'grade_courseid' => $env{'request.course.id'},
                   7899:                         'grade_symb'     => $ressymb,
                   7900:                         'CODE'           => $scancode
                   7901:                        );
                   7902:             if (ref($parts) eq 'HASH') {
                   7903:                 if (ref($parts->{$ressymb}) eq 'ARRAY') {
                   7904:                     foreach my $part (@{$parts->{$ressymb}}) {
                   7905:                         $form{'scantron_questnum_start.'.$part} =
                   7906:                             1+$env{'form.scantron.first_bubble_line.'.$count};
                   7907:                         $count++;
                   7908:                     }
                   7909:                 }
                   7910:             }
                   7911:             my $result=&ssi_with_retries($resource->src(),$ssi_retries,%form);
                   7912:             return 'ssi_error' if ($ssi_error);
                   7913:             last if (&Apache::loncommon::connection_aborted($r));
                   7914:         }
1.542     raeburn  7915:     }
                   7916:     return;
                   7917: }
                   7918: 
1.157     albertel 7919: sub scantron_upload_scantron_data {
                   7920:     my ($r)=@_;
1.565     raeburn  7921:     my $dom = $env{'request.role.domain'};
                   7922:     my $domdesc = &Apache::lonnet::domain($dom,'description');
                   7923:     $r->print(&Apache::loncommon::coursebrowser_javascript($dom));
1.157     albertel 7924:     my $select_link=&Apache::loncommon::selectcourse_link('rules','courseid',
1.181     albertel 7925: 							  'domainid',
1.565     raeburn  7926: 							  'coursename',$dom);
                   7927:     my $syllabuslink = '<a href="javascript:ToSyllabus();">'.&mt('Syllabus').'</a>'.
                   7928:                        ('&nbsp'x2).&mt('(shows course personnel)'); 
1.324     albertel 7929:     my $default_form_data=&defaultFormData(&get_symb($r,1));
1.579     raeburn  7930:     my $nofile_alert = &mt('Please use the browse button to select a file from your local directory.');
                   7931:     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 7932:     $r->print(&Apache::lonhtmlcommon::scripttag('
1.157     albertel 7933:     function checkUpload(formname) {
                   7934: 	if (formname.upfile.value == "") {
1.579     raeburn  7935: 	    alert("'.$nofile_alert.'");
1.157     albertel 7936: 	    return false;
                   7937: 	}
1.565     raeburn  7938:         if (formname.courseid.value == "") {
1.579     raeburn  7939:             alert("'.$nocourseid_alert.'");
1.565     raeburn  7940:             return false;
                   7941:         }
1.157     albertel 7942: 	formname.submit();
                   7943:     }
1.565     raeburn  7944: 
                   7945:     function ToSyllabus() {
                   7946:         var cdom = '."'$dom'".';
                   7947:         var cnum = document.rules.courseid.value;
                   7948:         if (cdom == "" || cdom == null) {
                   7949:             return;
                   7950:         }
                   7951:         if (cnum == "" || cnum == null) {
                   7952:            return;
                   7953:         }
                   7954:         syllwin=window.open("/public/"+cdom+"/"+cnum+"/syllabus","LONCAPASyllabus",
                   7955:                             "height=350,width=350,scrollbars=yes,menubar=no");
                   7956:         return;
                   7957:     }
                   7958: 
1.597     wenzelju 7959: '));
                   7960:     $r->print('
1.566     raeburn  7961: <h3>'.&mt('Send scanned bubblesheet data to a course').'</h3>
                   7962: 
1.492     albertel 7963: <form enctype="multipart/form-data" action="/adm/grades" name="rules" method="post">
1.565     raeburn  7964: '.$default_form_data.
                   7965:   &Apache::lonhtmlcommon::start_pick_box().
                   7966:   &Apache::lonhtmlcommon::row_title(&mt('Course ID')).
                   7967:   '<input name="courseid" type="text" size="30" />'.$select_link.
                   7968:   &Apache::lonhtmlcommon::row_closure().
                   7969:   &Apache::lonhtmlcommon::row_title(&mt('Course Name')).
                   7970:   '<input name="coursename" type="text" size="30" />'.$syllabuslink.
                   7971:   &Apache::lonhtmlcommon::row_closure().
                   7972:   &Apache::lonhtmlcommon::row_title(&mt('Domain')).
                   7973:   '<input name="domainid" type="hidden" />'.$domdesc.
                   7974:   &Apache::lonhtmlcommon::row_closure().
                   7975:   &Apache::lonhtmlcommon::row_title(&mt('File to upload')).
                   7976:   '<input type="file" name="upfile" size="50" />'.
                   7977:   &Apache::lonhtmlcommon::row_closure(1).
                   7978:   &Apache::lonhtmlcommon::end_pick_box().'<br />
                   7979: 
1.492     albertel 7980: <input name="command" value="scantronupload_save" type="hidden" />
1.589     bisitz   7981: <input type="button" onclick="javascript:checkUpload(this.form);" value="'.&mt('Upload Bubblesheet Data').'" />
1.157     albertel 7982: </form>
1.492     albertel 7983: ');
1.157     albertel 7984:     return '';
                   7985: }
                   7986: 
1.423     albertel 7987: 
1.157     albertel 7988: sub scantron_upload_scantron_data_save {
                   7989:     my($r)=@_;
1.324     albertel 7990:     my ($symb)=&get_symb($r,1);
1.182     albertel 7991:     my $doanotherupload=
                   7992: 	'<br /><form action="/adm/grades" method="post">'."\n".
                   7993: 	'<input type="hidden" name="command" value="scantronupload" />'."\n".
1.492     albertel 7994: 	'<input type="submit" name="submit" value="'.&mt('Do Another Upload').'" />'."\n".
1.182     albertel 7995: 	'</form>'."\n";
1.257     albertel 7996:     if (!&Apache::lonnet::allowed('usc',$env{'form.domainid'}) &&
1.162     albertel 7997: 	!&Apache::lonnet::allowed('usc',
1.257     albertel 7998: 			    $env{'form.domainid'}.'_'.$env{'form.courseid'})) {
1.575     www      7999: 	$r->print(&mt("You are not allowed to upload bubblesheet data to the requested course.")."<br />");
1.182     albertel 8000: 	if ($symb) {
1.324     albertel 8001: 	    $r->print(&show_grading_menu_form($symb));
1.182     albertel 8002: 	} else {
                   8003: 	    $r->print($doanotherupload);
                   8004: 	}
1.162     albertel 8005: 	return '';
                   8006:     }
1.257     albertel 8007:     my %coursedata=&Apache::lonnet::coursedescription($env{'form.domainid'}.'_'.$env{'form.courseid'});
1.568     raeburn  8008:     my $uploadedfile;
1.567     raeburn  8009:     $r->print('<h3>'.&mt("Uploading file to [_1]",$coursedata{'description'}).'</h3>');
1.257     albertel 8010:     if (length($env{'form.upfile'}) < 2) {
1.568     raeburn  8011:         $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 8012:     } else {
1.568     raeburn  8013:         my $result = 
                   8014:             &Apache::lonnet::userfileupload('upfile','','scantron','','','',
                   8015:                                             $env{'form.courseid'},$env{'form.domainid'});
                   8016: 	if ($result =~ m{^/uploaded/}) {
1.567     raeburn  8017: 	    $r->print(&mt('[_1]Success:[_2] Successfully uploaded [_3] bytes of data into location: [_4]',
                   8018:                           '<span class="LC_success">','</span>',(length($env{'form.upfile'})-1),
                   8019: 			  '<span class="LC_filename">'.$result.'</span>'));
1.568     raeburn  8020:             ($uploadedfile) = ($result =~ m{/([^/]+)$});
1.567     raeburn  8021:             $r->print(&validate_uploaded_scantron_file($env{'form.domainid'},
1.568     raeburn  8022:                                                        $env{'form.courseid'},$uploadedfile));
1.210     albertel 8023: 	} else {
1.567     raeburn  8024: 	    $r->print(&mt('[_1]Error:[_2] An error ([_3]) occurred when attempting to upload the file, [_4]',
                   8025:                           '<span class="LC_error">','</span>',$result,
1.568     raeburn  8026: 			  '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>'));
1.183     albertel 8027: 	}
                   8028:     }
1.174     albertel 8029:     if ($symb) {
1.209     ng       8030: 	$r->print(&scantron_selectphase($r,$uploadedfile));
1.174     albertel 8031:     } else {
1.182     albertel 8032: 	$r->print($doanotherupload);
1.174     albertel 8033:     }
1.157     albertel 8034:     return '';
                   8035: }
                   8036: 
1.567     raeburn  8037: sub validate_uploaded_scantron_file {
                   8038:     my ($cdom,$cname,$fname) = @_;
                   8039:     my $scanlines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.$fname);
                   8040:     my @lines;
                   8041:     if ($scanlines ne '-1') {
                   8042:         @lines=split("\n",$scanlines,-1);
                   8043:     }
                   8044:     my $output;
                   8045:     if (@lines) {
                   8046:         my (%counts,$max_match_format);
                   8047:         my ($max_match_count,$max_match_pct) = (0,0);
                   8048:         my $classlist = &Apache::loncoursedata::get_classlist($cdom,$cname);
                   8049:         my %idmap = &username_to_idmap($classlist);
                   8050:         foreach my $key (keys(%idmap)) {
                   8051:             my $lckey = lc($key);
                   8052:             $idmap{$lckey} = $idmap{$key};
                   8053:         }
                   8054:         my %unique_formats;
                   8055:         my @formatlines = &get_scantronformat_file();
                   8056:         foreach my $line (@formatlines) {
                   8057:             chomp($line);
                   8058:             my @config = split(/:/,$line);
                   8059:             my $idstart = $config[5];
                   8060:             my $idlength = $config[6];
                   8061:             if (($idstart ne '') && ($idlength > 0)) {
                   8062:                 if (ref($unique_formats{$idstart.':'.$idlength}) eq 'ARRAY') {
                   8063:                     push(@{$unique_formats{$idstart.':'.$idlength}},$config[0].':'.$config[1]); 
                   8064:                 } else {
                   8065:                     $unique_formats{$idstart.':'.$idlength} = [$config[0].':'.$config[1]];
                   8066:                 }
                   8067:             }
                   8068:         }
                   8069:         foreach my $key (keys(%unique_formats)) {
                   8070:             my ($idstart,$idlength) = split(':',$key);
                   8071:             %{$counts{$key}} = (
                   8072:                                'found'   => 0,
                   8073:                                'total'   => 0,
                   8074:                               );
                   8075:             foreach my $line (@lines) {
                   8076:                 next if ($line =~ /^#/);
                   8077:                 next if ($line =~ /^[\s\cz]*$/);
                   8078:                 my $id = substr($line,$idstart-1,$idlength);
                   8079:                 $id = lc($id);
                   8080:                 if (exists($idmap{$id})) {
                   8081:                     $counts{$key}{'found'} ++;
                   8082:                 }
                   8083:                 $counts{$key}{'total'} ++;
                   8084:             }
                   8085:             if ($counts{$key}{'total'}) {
                   8086:                 my $percent_match = (100*$counts{$key}{'found'})/($counts{$key}{'total'});
                   8087:                 if (($max_match_format eq '') || ($percent_match > $max_match_pct)) {
                   8088:                     $max_match_pct = $percent_match;
                   8089:                     $max_match_format = $key;
                   8090:                     $max_match_count = $counts{$key}{'total'};
                   8091:                 }
                   8092:             }
                   8093:         }
                   8094:         if (ref($unique_formats{$max_match_format}) eq 'ARRAY') {
                   8095:             my $format_descs;
                   8096:             my $numwithformat = @{$unique_formats{$max_match_format}};
                   8097:             for (my $i=0; $i<$numwithformat; $i++) {
                   8098:                 my ($name,$desc) = split(':',$unique_formats{$max_match_format}[$i]);
                   8099:                 if ($i<$numwithformat-2) {
                   8100:                     $format_descs .= '"<i>'.$desc.'</i>", ';
                   8101:                 } elsif ($i==$numwithformat-2) {
                   8102:                     $format_descs .= '"<i>'.$desc.'</i>" '.&mt('and').' ';
                   8103:                 } elsif ($i==$numwithformat-1) {
                   8104:                     $format_descs .= '"<i>'.$desc.'</i>"';
                   8105:                 }
                   8106:             }
                   8107:             my $showpct = sprintf("%.0f",$max_match_pct).'%';
                   8108:             $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).
                   8109:                        '<br />'.&mt('A low percentage of matches results from one of the following:').'<ul>'.
                   8110:                        '<li>'.&mt('The file was uploaded to the wrong course').'</li>'.
                   8111:                        '<li>'.&mt('The data are not in the format expected for the domain: [_1]',
                   8112:                                   '<i>'.$cdom.'</i>').'</li>'.
                   8113:                        '<li>'.&mt('Students did not bubble their IDs, or mis-bubbled them').'</li>'.
                   8114:                        '<li>'.&mt('The course roster is not up to date').'</li>'.
                   8115:                        '</ul>';
                   8116:         }
                   8117:     } else {
                   8118:         $output = '<span class="LC_warning">'.&mt('Uploaded file contained no data').'</span>';
                   8119:     }
                   8120:     return $output;
                   8121: }
                   8122: 
1.202     albertel 8123: sub valid_file {
                   8124:     my ($requested_file)=@_;
                   8125:     foreach my $filename (sort(&scantron_filenames())) {
                   8126: 	if ($requested_file eq $filename) { return 1; }
                   8127:     }
                   8128:     return 0;
                   8129: }
                   8130: 
                   8131: sub scantron_download_scantron_data {
                   8132:     my ($r)=@_;
1.324     albertel 8133:     my $default_form_data=&defaultFormData(&get_symb($r,1));
1.257     albertel 8134:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   8135:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   8136:     my $file=$env{'form.scantron_selectfile'};
1.202     albertel 8137:     if (! &valid_file($file)) {
1.492     albertel 8138: 	$r->print('
1.202     albertel 8139: 	<p>
1.492     albertel 8140: 	    '.&mt('The requested file name was invalid.').'
1.202     albertel 8141:         </p>
1.492     albertel 8142: ');
1.324     albertel 8143: 	$r->print(&show_grading_menu_form(&get_symb($r,1)));
1.202     albertel 8144: 	return;
                   8145:     }
                   8146:     my $orig='/uploaded/'.$cdom.'/'.$cname.'/scantron_orig_'.$file;
                   8147:     my $corrected='/uploaded/'.$cdom.'/'.$cname.'/scantron_corrected_'.$file;
                   8148:     my $skipped='/uploaded/'.$cdom.'/'.$cname.'/scantron_skipped_'.$file;
                   8149:     &Apache::lonnet::allowuploaded('/adm/grades',$orig);
                   8150:     &Apache::lonnet::allowuploaded('/adm/grades',$corrected);
                   8151:     &Apache::lonnet::allowuploaded('/adm/grades',$skipped);
1.492     albertel 8152:     $r->print('
1.202     albertel 8153:     <p>
1.492     albertel 8154: 	'.&mt('[_1]Original[_2] file as uploaded by the scantron office.',
                   8155: 	      '<a href="'.$orig.'">','</a>').'
1.202     albertel 8156:     </p>
                   8157:     <p>
1.492     albertel 8158: 	'.&mt('[_1]Corrections[_2], a file of corrected records that were used in grading.',
                   8159: 	      '<a href="'.$corrected.'">','</a>').'
1.202     albertel 8160:     </p>
                   8161:     <p>
1.492     albertel 8162: 	'.&mt('[_1]Skipped[_2], a file of records that were skipped.',
                   8163: 	      '<a href="'.$skipped.'">','</a>').'
1.202     albertel 8164:     </p>
1.492     albertel 8165: ');
1.324     albertel 8166:     $r->print(&show_grading_menu_form(&get_symb($r,1)));
1.202     albertel 8167:     return '';
                   8168: }
1.157     albertel 8169: 
1.523     raeburn  8170: sub checkscantron_results {
                   8171:     my ($r) = @_;
                   8172:     my ($symb)=&get_symb($r);
                   8173:     if (!$symb) {return '';}
                   8174:     my $grading_menu_button=&show_grading_menu_form($symb);
                   8175:     my $cid = $env{'request.course.id'};
1.542     raeburn  8176:     my %lettdig = &letter_to_digits();
1.523     raeburn  8177:     my $numletts = scalar(keys(%lettdig));
                   8178:     my $cnum = $env{'course.'.$cid.'.num'};
                   8179:     my $cdom = $env{'course.'.$cid.'.domain'};
                   8180:     my (undef, undef, $sequence) = &Apache::lonnet::decode_symb($env{'form.selectpage'});
                   8181:     my %record;
                   8182:     my %scantron_config =
                   8183:         &Apache::grades::get_scantron_config($env{'form.scantron_format'});
                   8184:     my ($scanlines,$scan_data)=&Apache::grades::scantron_getfile();
                   8185:     my $classlist=&Apache::loncoursedata::get_classlist();
                   8186:     my %idmap=&Apache::grades::username_to_idmap($classlist);
                   8187:     my $navmap=Apache::lonnavmaps::navmap->new();
1.582     raeburn  8188:     unless (ref($navmap)) {
                   8189:         $r->print(&navmap_errormsg());
                   8190:         return '';
                   8191:     }
1.523     raeburn  8192:     my $map=$navmap->getResourceByUrl($sequence);
1.557     raeburn  8193:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
                   8194:     my (%grader_partids_by_symb,%grader_randomlists_by_symb);
                   8195:     &graders_resources_pass(\@resources,\%grader_partids_by_symb,                             \%grader_randomlists_by_symb);
                   8196: 
1.554     raeburn  8197:     my ($uname,$udom);
1.523     raeburn  8198:     my (%scandata,%lastname,%bylast);
                   8199:     $r->print('
                   8200: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="checkscantron">'."\n");
                   8201: 
                   8202:     my @delayqueue;
                   8203:     my %completedstudents;
                   8204: 
                   8205:     my $count=&Apache::grades::get_todo_count($scanlines,$scan_data);
1.581     www      8206:     my %prog_state=&Apache::lonhtmlcommon::Create_PrgWin($r,'Bubblesheet/Submissions Comparison Status',
                   8207:                                     'Progress of Bubblesheet Data/Submission Records Comparison',$count,
1.523     raeburn  8208:                                     'inline',undef,'checkscantron');
1.546     raeburn  8209:     my ($username,$domain,$started);
1.582     raeburn  8210:     my $nav_error;
                   8211:     &scantron_get_maxbubble(\$nav_error); # Need the bubble lines array to parse.
                   8212:     if ($nav_error) {
                   8213:         $r->print(&navmap_errormsg());
                   8214:         return '';
                   8215:     }
1.523     raeburn  8216: 
                   8217:     &Apache::lonhtmlcommon::Update_PrgWin($r,\%prog_state,
                   8218:                                           'Processing first student');
                   8219:     my $start=&Time::HiRes::time();
                   8220:     my $i=-1;
                   8221: 
                   8222:     while ($i<$scanlines->{'count'}) {
                   8223:         ($username,$domain,$uname)=('','','');
                   8224:         $i++;
                   8225:         my $line=&Apache::grades::scantron_get_line($scanlines,$scan_data,$i);
                   8226:         if ($line=~/^[\s\cz]*$/) { next; }
                   8227:         if ($started) {
                   8228:             &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state,
                   8229:                                                      'last student');
                   8230:         }
                   8231:         $started=1;
                   8232:         my $scan_record=
                   8233:             &Apache::grades::scantron_parse_scanline($line,$i,\%scantron_config,
                   8234:                                                      $scan_data);
                   8235:         unless ($uname=&Apache::grades::scantron_find_student($scan_record,$scan_data,
                   8236:                                                               \%idmap,$i)) {
                   8237:             &Apache::grades::scantron_add_delay(\@delayqueue,$line,
                   8238:                                 'Unable to find a student that matches',1);
                   8239:             next;
                   8240:         }
                   8241:         if (exists $completedstudents{$uname}) {
                   8242:             &Apache::grades::scantron_add_delay(\@delayqueue,$line,
                   8243:                                 'Student '.$uname.' has multiple sheets',2);
                   8244:             next;
                   8245:         }
                   8246:         my $pid = $scan_record->{'scantron.ID'};
                   8247:         $lastname{$pid} = $scan_record->{'scantron.LastName'};
                   8248:         push(@{$bylast{$lastname{$pid}}},$pid);
                   8249:         my $lastpos = $env{'form.scantron_maxbubble'}*$scantron_config{'Qlength'};
                   8250:         $scandata{$pid} = substr($line,$scantron_config{'Qstart'}-1,$lastpos);
                   8251:         chomp($scandata{$pid});
                   8252:         $scandata{$pid} =~ s/\r$//;
                   8253:         ($username,$domain)=split(/:/,$uname);
                   8254:         my $counter = -1;
                   8255:         foreach my $resource (@resources) {
1.557     raeburn  8256:             my $parts;
1.554     raeburn  8257:             my $ressymb = $resource->symb();
1.557     raeburn  8258:             if ((exists($grader_randomlists_by_symb{$ressymb})) ||
                   8259:                 (ref($grader_partids_by_symb{$ressymb}) ne 'ARRAY')) {
                   8260:                 (my $analysis,$parts) =
                   8261:                     &scantron_partids_tograde($resource,$env{'request.course.id'},$username,$domain);
                   8262:             } else {
                   8263:                 $parts = $grader_partids_by_symb{$ressymb};
                   8264:             }
1.542     raeburn  8265:             ($counter,my $recording) =
                   8266:                 &verify_scantron_grading($resource,$domain,$username,$cid,$counter,
1.554     raeburn  8267:                                          $scandata{$pid},$parts,
1.542     raeburn  8268:                                          \%scantron_config,\%lettdig,$numletts);
                   8269:             $record{$pid} .= $recording;
1.523     raeburn  8270:         }
                   8271:     }
                   8272:     &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
                   8273:     $r->print('<br />');
                   8274:     my ($okstudents,$badstudents,$numstudents,$passed,$failed);
                   8275:     $passed = 0;
                   8276:     $failed = 0;
                   8277:     $numstudents = 0;
                   8278:     foreach my $last (sort(keys(%bylast))) {
                   8279:         if (ref($bylast{$last}) eq 'ARRAY') {
                   8280:             foreach my $pid (sort(@{$bylast{$last}})) {
                   8281:                 my $showscandata = $scandata{$pid};
                   8282:                 my $showrecord = $record{$pid};
                   8283:                 $showscandata =~ s/\s/&nbsp;/g;
                   8284:                 $showrecord =~ s/\s/&nbsp;/g;
                   8285:                 if ($scandata{$pid} eq $record{$pid}) {
                   8286:                     my $css_class = ($passed % 2)?'LC_odd_row':'LC_even_row';
                   8287:                     $okstudents .= '<tr class="'.$css_class.'">'.
1.581     www      8288: '<td>'.&mt('Bubblesheet').'</td><td>'.$showscandata.'</td><td rowspan="2">'.$last.'</td><td rowspan="2">'.$pid.'</td>'."\n".
1.523     raeburn  8289: '</tr>'."\n".
                   8290: '<tr class="'.$css_class.'">'."\n".
                   8291: '<td>Submissions</td><td>'.$showrecord.'</td></tr>'."\n";
                   8292:                     $passed ++;
                   8293:                 } else {
                   8294:                     my $css_class = ($failed % 2)?'LC_odd_row':'LC_even_row';
1.581     www      8295:                     $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  8296: '</tr>'."\n".
                   8297: '<tr class="'.$css_class.'">'."\n".
                   8298: '<td>Submissions</td><td><span class="LC_nobreak">'.$record{$pid}.'</span></td>'."\n".
                   8299: '</tr>'."\n";
                   8300:                     $failed ++;
                   8301:                 }
                   8302:                 $numstudents ++;
                   8303:             }
                   8304:         }
                   8305:     }
1.572     www      8306:     $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  8307:     $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>');
                   8308:     if ($passed) {
1.572     www      8309:         $r->print(&mt('Students with exact correspondence between bubblesheet data and submissions are as follows:').'<br /><br />');
1.523     raeburn  8310:         $r->print(&Apache::loncommon::start_data_table()."\n".
                   8311:                  &Apache::loncommon::start_data_table_header_row()."\n".
                   8312:                  '<th>'.&mt('Source').'</th><th>'.&mt('Bubble records').'</th><th>'.&mt('Name').'</th><th>'.&mt('ID').'</th>'.
                   8313:                  &Apache::loncommon::end_data_table_header_row()."\n".
                   8314:                  $okstudents."\n".
                   8315:                  &Apache::loncommon::end_data_table().'<br />');
                   8316:     }
                   8317:     if ($failed) {
1.572     www      8318:         $r->print(&mt('Students with differences between bubblesheet data and submissions are as follows:').'<br /><br />');
1.523     raeburn  8319:         $r->print(&Apache::loncommon::start_data_table()."\n".
                   8320:                  &Apache::loncommon::start_data_table_header_row()."\n".
                   8321:                  '<th>'.&mt('Source').'</th><th>'.&mt('Bubble records').'</th><th>'.&mt('Name').'</th><th>'.&mt('ID').'</th>'.
                   8322:                  &Apache::loncommon::end_data_table_header_row()."\n".
                   8323:                  $badstudents."\n".
                   8324:                  &Apache::loncommon::end_data_table()).'<br />'.
1.572     www      8325:                  &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  8326:     }
                   8327:     $r->print('</form><br />'.$grading_menu_button);
                   8328:     return;
                   8329: }
                   8330: 
1.542     raeburn  8331: sub verify_scantron_grading {
1.554     raeburn  8332:     my ($resource,$domain,$username,$cid,$counter,$scandata,$partids,
1.542     raeburn  8333:         $scantron_config,$lettdig,$numletts) = @_;
                   8334:     my ($record,%expected,%startpos);
                   8335:     return ($counter,$record) if (!ref($resource));
                   8336:     return ($counter,$record) if (!$resource->is_problem());
                   8337:     my $symb = $resource->symb();
1.554     raeburn  8338:     return ($counter,$record) if (ref($partids) ne 'ARRAY');
                   8339:     foreach my $part_id (@{$partids}) {
1.542     raeburn  8340:         $counter ++;
                   8341:         $expected{$part_id} = 0;
                   8342:         if ($env{"form.scantron.sub_bubblelines.$counter"}) {
                   8343:             my @sub_lines = split(/,/,$env{"form.scantron.sub_bubblelines.$counter"});
                   8344:             foreach my $item (@sub_lines) {
                   8345:                 $expected{$part_id} += $item;
                   8346:             }
                   8347:         } else {
                   8348:             $expected{$part_id} = $env{"form.scantron.bubblelines.$counter"};
                   8349:         }
                   8350:         $startpos{$part_id} = $env{"form.scantron.first_bubble_line.$counter"};
                   8351:     }
                   8352:     if ($symb) {
                   8353:         my %recorded;
                   8354:         my (%returnhash) = &Apache::lonnet::restore($symb,$cid,$domain,$username);
                   8355:         if ($returnhash{'version'}) {
                   8356:             my %lasthash=();
                   8357:             my $version;
                   8358:             for ($version=1;$version<=$returnhash{'version'};$version++) {
                   8359:                 foreach my $key (sort(split(/\:/,$returnhash{$version.':keys'}))) {
                   8360:                     $lasthash{$key}=$returnhash{$version.':'.$key};
                   8361:                 }
                   8362:             }
                   8363:             foreach my $key (keys(%lasthash)) {
                   8364:                 if ($key =~ /\.scantron$/) {
                   8365:                     my $value = &unescape($lasthash{$key});
                   8366:                     my ($part_id) = ($key =~ /^resource\.(.+)\.scantron$/);
                   8367:                     if ($value eq '') {
                   8368:                         for (my $i=0; $i<$expected{$part_id}; $i++) {
                   8369:                             for (my $j=0; $j<$scantron_config->{'length'}; $j++) {
                   8370:                                 $recorded{$part_id} .= $scantron_config->{'Qoff'};
                   8371:                             }
                   8372:                         }
                   8373:                     } else {
                   8374:                         my @tocheck;
                   8375:                         my @items = split(//,$value);
                   8376:                         if (($scantron_config->{'Qon'} eq 'letter') ||
                   8377:                             ($scantron_config->{'Qon'} eq 'number')) {
                   8378:                             if (@items < $expected{$part_id}) {
                   8379:                                 my $fragment = substr($scandata,$startpos{$part_id},$expected{$part_id});
                   8380:                                 my @singles = split(//,$fragment);
                   8381:                                 foreach my $pos (@singles) {
                   8382:                                     if ($pos eq ' ') {
                   8383:                                         push(@tocheck,$pos);
                   8384:                                     } else {
                   8385:                                         my $next = shift(@items);
                   8386:                                         push(@tocheck,$next);
                   8387:                                     }
                   8388:                                 }
                   8389:                             } else {
                   8390:                                 @tocheck = @items;
                   8391:                             }
                   8392:                             foreach my $letter (@tocheck) {
                   8393:                                 if ($scantron_config->{'Qon'} eq 'letter') {
                   8394:                                     if ($letter !~ /^[A-J]$/) {
                   8395:                                         $letter = $scantron_config->{'Qoff'};
                   8396:                                     }
                   8397:                                     $recorded{$part_id} .= $letter;
                   8398:                                 } elsif ($scantron_config->{'Qon'} eq 'number') {
                   8399:                                     my $digit;
                   8400:                                     if ($letter !~ /^[A-J]$/) {
                   8401:                                         $digit = $scantron_config->{'Qoff'};
                   8402:                                     } else {
                   8403:                                         $digit = $lettdig->{$letter};
                   8404:                                     }
                   8405:                                     $recorded{$part_id} .= $digit;
                   8406:                                 }
                   8407:                             }
                   8408:                         } else {
                   8409:                             @tocheck = @items;
                   8410:                             for (my $i=0; $i<$expected{$part_id}; $i++) {
                   8411:                                 my $curr_sub = shift(@tocheck);
                   8412:                                 my $digit;
                   8413:                                 if ($curr_sub =~ /^[A-J]$/) {
                   8414:                                     $digit = $lettdig->{$curr_sub}-1;
                   8415:                                 }
                   8416:                                 if ($curr_sub eq 'J') {
                   8417:                                     $digit += scalar($numletts);
                   8418:                                 }
                   8419:                                 for (my $j=0; $j<$scantron_config->{'Qlength'}; $j++) {
                   8420:                                     if ($j == $digit) {
                   8421:                                         $recorded{$part_id} .= $scantron_config->{'Qon'};
                   8422:                                     } else {
                   8423:                                         $recorded{$part_id} .= $scantron_config->{'Qoff'};
                   8424:                                     }
                   8425:                                 }
                   8426:                             }
                   8427:                         }
                   8428:                     }
                   8429:                 }
                   8430:             }
                   8431:         }
1.554     raeburn  8432:         foreach my $part_id (@{$partids}) {
1.542     raeburn  8433:             if ($recorded{$part_id} eq '') {
                   8434:                 for (my $i=0; $i<$expected{$part_id}; $i++) {
                   8435:                     for (my $j=0; $j<$scantron_config->{'Qlength'}; $j++) {
                   8436:                         $recorded{$part_id} .= $scantron_config->{'Qoff'};
                   8437:                     }
                   8438:                 }
                   8439:             }
                   8440:             $record .= $recorded{$part_id};
                   8441:         }
                   8442:     }
                   8443:     return ($counter,$record);
                   8444: }
                   8445: 
                   8446: sub letter_to_digits { 
                   8447:     my %lettdig = (
                   8448:                     A => 1,
                   8449:                     B => 2,
                   8450:                     C => 3,
                   8451:                     D => 4,
                   8452:                     E => 5,
                   8453:                     F => 6,
                   8454:                     G => 7,
                   8455:                     H => 8,
                   8456:                     I => 9,
                   8457:                     J => 0,
                   8458:                   );
                   8459:     return %lettdig;
                   8460: }
                   8461: 
1.423     albertel 8462: 
1.75      albertel 8463: #-------- end of section for handling grading scantron forms -------
                   8464: #
                   8465: #-------------------------------------------------------------------
                   8466: 
1.72      ng       8467: #-------------------------- Menu interface -------------------------
                   8468: #
                   8469: #--- Show a Grading Menu button - Calls the next routine ---
                   8470: sub show_grading_menu_form {
1.324     albertel 8471:     my ($symb)=@_;
1.125     ng       8472:     my $result.='<br /><form action="/adm/grades" method="post">'."\n".
1.418     albertel 8473: 	'<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.257     albertel 8474: 	'<input type="hidden" name="saveState"  value="'.$env{'form.saveState'}.'" />'."\n".
1.72      ng       8475: 	'<input type="hidden" name="command" value="gradingmenu" />'."\n".
1.478     albertel 8476: 	'<input type="submit" name="submit" value="'.&mt('Grading Menu').'" />'."\n".
1.72      ng       8477: 	'</form>'."\n";
                   8478:     return $result;
                   8479: }
                   8480: 
1.443     banghart 8481: sub grading_menu {
                   8482:     my ($request) = @_;
                   8483:     my ($symb)=&get_symb($request);
                   8484:     if (!$symb) {return '';}
                   8485:     my $probTitle = &Apache::lonnet::gettitle($symb);
                   8486: 
                   8487:     my %fields = ('symb'=>&Apache::lonenc::check_encrypt($symb),
                   8488:                   'probTitle'=>$probTitle,
1.598     www      8489:                   'command'=>'individual',
1.443     banghart 8490:                   'gradingMenu'=>1,
                   8491:                   'showgrading'=>"yes");
1.538     schulted 8492:     
1.598     www      8493:     my $url1a = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   8494: 
                   8495:     $fields{'command'}='ungraded';
                   8496:     my $url1b=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   8497: 
                   8498:     $fields{'command'}='table';
                   8499:     my $url1c=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   8500: 
                   8501:     $fields{'command'}='all_for_one';
                   8502:     my $url1d=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   8503: 
1.443     banghart 8504:     $fields{'command'} = 'csvform';
1.538     schulted 8505:     my $url2 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   8506:     
1.443     banghart 8507:     $fields{'command'} = 'processclicker';
1.538     schulted 8508:     my $url3 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   8509:     
1.443     banghart 8510:     $fields{'command'} = 'scantron_selectphase';
1.538     schulted 8511:     my $url4 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
1.602     www      8512: 
                   8513:     $fields{'command'} = 'initialverifyreceipt';
                   8514:     my $url5 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
1.538     schulted 8515:     
1.598     www      8516:     my @menu = ({	categorytitle=>'Hand Grading',
1.538     schulted 8517:             items =>[
1.598     www      8518:                         {	linktext => 'Select individual students to grade',
                   8519:                     		url => $url1a,
1.538     schulted 8520:                     		permission => 'F',
                   8521:                     		icon => 'edit-find-replace.png',
1.598     www      8522:                     		linktitle => 'Grade current resource for a selection of students.'
                   8523:                         }, 
                   8524:                         {       linktext => 'Grade ungraded submissions.',
                   8525:                                 url => $url1b,
                   8526:                                 permission => 'F',
                   8527:                                 icon => 'edit-find-replace.png',
                   8528:                                 linktitle => 'Grade all submissions that have not been graded yet.'
1.538     schulted 8529:                         },
1.598     www      8530: 
                   8531:                         {       linktext => 'Grading table',
                   8532:                                 url => $url1c,
                   8533:                                 permission => 'F',
                   8534:                                 icon => 'edit-find-replace.png',
                   8535:                                 linktitle => 'Grade current resource for all students.'
                   8536:                         },
1.600     www      8537:                         {       linktext => 'Grade complete page/sequence/folder for one student',
1.598     www      8538:                                 url => $url1d,
                   8539:                                 permission => 'F',
                   8540:                                 icon => 'edit-find-replace.png',
                   8541:                                 linktitle => 'Grade all resources in current page/sequence/folder for one student.'
                   8542:                         }]},
                   8543:                          { categorytitle=>'Automated Grading',
                   8544:                items =>[
                   8545: 
1.538     schulted 8546:                 	    {	linktext => 'Upload Scores',
                   8547:                     		url => $url2,
                   8548:                     		permission => 'F',
                   8549:                     		icon => 'uploadscores.png',
                   8550:                     		linktitle => 'Specify a file containing the class scores for current resource.'
                   8551:                 	    },
                   8552:                 	    {	linktext => 'Process Clicker',
                   8553:                     		url => $url3,
                   8554:                     		permission => 'F',
                   8555:                     		icon => 'addClickerInfoFile.png',
                   8556:                     		linktitle => 'Specify a file containing the clicker information for this resource.'
                   8557:                 	    },
1.587     raeburn  8558:                 	    {	linktext => 'Grade/Manage/Review Bubblesheets',
1.538     schulted 8559:                     		url => $url4,
                   8560:                     		permission => 'F',
                   8561:                     		icon => 'stat.png',
                   8562:                     		linktitle => 'Grade scantron exams, upload/download scantron data files, and review previously graded scantron exams.'
1.602     www      8563:                 	    },
                   8564:                             {   linktext => 'Verify Receipt No.',
                   8565:                                 url => $url5,
                   8566:                                 permission => 'F',
                   8567:                                 icon => 'edit-find-replace.png',
                   8568:                                 linktitle => 'Verify a system-generated receipt number for correct problem solution.'
                   8569:                             }
                   8570: 
1.538     schulted 8571:                     ]
                   8572:             });
                   8573: 
1.443     banghart 8574:     # Create the menu
                   8575:     my $Str;
1.445     banghart 8576:     $Str .= '<form method="post" action="" name="gradingMenu">';
                   8577:     $Str .= '<input type="hidden" name="command" value="" />'.
                   8578:     	'<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.476     albertel 8579: 	'<input type="hidden" name="probTitle"   value="'.$probTitle.'" />'."\n".
1.445     banghart 8580: 	'<input type="hidden" name="gradingMenu" value="1" />'."\n".
                   8581: 	'<input type="hidden" name="showgrading" value="yes" />'."\n";
                   8582: 
1.602     www      8583:     $Str .= &Apache::lonhtmlcommon::generate_menu(@menu);
1.443     banghart 8584:     return $Str;    
                   8585: }
                   8586: 
1.598     www      8587: 
                   8588: sub ungraded {
                   8589:     my ($request)=@_;
                   8590:     &submit_options($request);
                   8591: }
                   8592: 
1.599     www      8593: sub submit_options_sequence {
                   8594:     my ($request) = @_;
                   8595:     my ($symb)=&get_symb($request);
                   8596:     if (!$symb) {return '';}
1.600     www      8597:     &commonJSfunctions($request);
                   8598:     my $result;
1.599     www      8599: 
1.600     www      8600:     $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
                   8601:         '<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
                   8602:         '<input type="hidden" name="gradingMenu" value="1" />'."\n".
                   8603:         '<input type="hidden" name="showgrading" value="yes" />'."\n";
                   8604: 
                   8605:     $result.='
                   8606: <h2>
                   8607:   '.&mt('Grade complete page/sequence/folder for one student').'
1.601     www      8608: </h2>'.
                   8609:             &selectfield(0).
                   8610:             '<input type="hidden" name="command" value="pickStudentPage" />
1.600     www      8611:             <div>
                   8612:               <input type="submit" value="'.&mt('Next').' &rarr;" />
                   8613:             </div>
                   8614:         </div>
                   8615:   </form>';
                   8616:     $result .= &show_grading_menu_form($symb);
                   8617:     return $result;
                   8618: }
                   8619: 
                   8620: sub submit_options_table {
                   8621:     my ($request) = @_;
                   8622:     my ($symb)=&get_symb($request);
                   8623:     if (!$symb) {return '';}
1.599     www      8624:     &commonJSfunctions($request);
                   8625:     my $result;
                   8626: 
                   8627:     $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
                   8628:         '<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
                   8629:         '<input type="hidden" name="gradingMenu" value="1" />'."\n".
                   8630:         '<input type="hidden" name="showgrading" value="yes" />'."\n";
                   8631: 
                   8632:     $result.='
                   8633: <h2>
1.600     www      8634:   '.&mt('Grading table').'
1.601     www      8635: </h2>'.
                   8636:             &selectfield(0).
                   8637:             '<input type="hidden" name="command" value="viewgrades" />
1.599     www      8638:             <div>
                   8639:               <input type="submit" value="'.&mt('Next').' &rarr;" />
                   8640:             </div>
                   8641:         </div>
                   8642:   </form>';
                   8643:     $result .= &show_grading_menu_form($symb);
                   8644:     return $result;
                   8645: }
1.443     banghart 8646: 
1.600     www      8647: 
                   8648: 
1.443     banghart 8649: #--- Displays the submissions first page -------
                   8650: sub submit_options {
1.72      ng       8651:     my ($request) = @_;
1.324     albertel 8652:     my ($symb)=&get_symb($request);
1.72      ng       8653:     if (!$symb) {return '';}
1.76      ng       8654:     my $probTitle = &Apache::lonnet::gettitle($symb);
1.72      ng       8655: 
1.118     ng       8656:     &commonJSfunctions($request);
1.473     albertel 8657:     my $result;
1.533     bisitz   8658: 
1.72      ng       8659:     $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
1.418     albertel 8660: 	'<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.72      ng       8661: 	'<input type="hidden" name="probTitle"   value="'.$probTitle.'" />'."\n".
1.124     ng       8662: 	'<input type="hidden" name="gradingMenu" value="1" />'."\n".
1.72      ng       8663: 	'<input type="hidden" name="showgrading" value="yes" />'."\n";
                   8664: 
1.472     albertel 8665:     $result.='
1.533     bisitz   8666: <h2>
1.600     www      8667:   '.&mt('Select individual students to grade').'
1.601     www      8668: </h2>'.&selectfield(1).'
                   8669:                 <input type="hidden" name="command" value="submission" /> 
                   8670: 	      <input type="submit" value="'.&mt('Next').' &rarr;" />
                   8671:             </div>
                   8672:           </div>
                   8673: 
                   8674: 
                   8675:   </form>';
                   8676:     $result .= &show_grading_menu_form($symb);
                   8677:     return $result;
                   8678: }
1.533     bisitz   8679: 
1.601     www      8680: sub selectfield {
                   8681:    my ($full)=@_;
                   8682:    my $result='<div class="LC_columnSection">
1.537     harmsja  8683:   
1.533     bisitz   8684:     <fieldset>
                   8685:       <legend>
                   8686:        '.&mt('Sections').'
                   8687:       </legend>
1.601     www      8688:       '.&Apache::lonstatistics::SectionSelect('section','multiple',5).'
1.533     bisitz   8689:     </fieldset>
1.537     harmsja  8690:   
1.533     bisitz   8691:     <fieldset>
                   8692:       <legend>
                   8693:         '.&mt('Groups').'
                   8694:       </legend>
                   8695:       '.&Apache::lonstatistics::GroupSelect('group','multiple',5).'
                   8696:     </fieldset>
1.537     harmsja  8697:   
1.533     bisitz   8698:     <fieldset>
                   8699:       <legend>
                   8700:         '.&mt('Access Status').'
                   8701:       </legend>
1.601     www      8702:       '.&Apache::lonhtmlcommon::StatusOptions(undef,undef,5,undef,'mult').'
                   8703:     </fieldset>';
                   8704:     if ($full) {
                   8705:        $result.='
1.533     bisitz   8706:     <fieldset>
                   8707:       <legend>
                   8708:         '.&mt('Submission Status').'
1.601     www      8709:       </legend>'.
                   8710:        &Apache::loncommon::select_form('all','submitonly',
                   8711:           (&Apache::lonlocal::texthash(
                   8712:              'yes'       => 'with submissions',
                   8713:              'queued'    => 'in grading queue',
                   8714:              'graded'    => 'with ungraded submissions',
                   8715:              'incorrect' => 'with incorrect submissions',
                   8716:              'all'       => 'with any status'),
                   8717:              'select_form_order' => ['yes','queued','graded','incorrect','all'])).
                   8718:    '</fieldset>';
                   8719:     }
                   8720:     $result.='</div><br />';
1.44      ng       8721:     return $result;
1.2       albertel 8722: }
                   8723: 
1.285     albertel 8724: sub reset_perm {
                   8725:     undef(%perm);
                   8726: }
                   8727: 
                   8728: sub init_perm {
                   8729:     &reset_perm();
1.300     albertel 8730:     foreach my $test_perm ('vgr','mgr','opa') {
                   8731: 
                   8732: 	my $scope = $env{'request.course.id'};
                   8733: 	if (!($perm{$test_perm}=&Apache::lonnet::allowed($test_perm,$scope))) {
                   8734: 
                   8735: 	    $scope .= '/'.$env{'request.course.sec'};
                   8736: 	    if ( $perm{$test_perm}=
                   8737: 		 &Apache::lonnet::allowed($test_perm,$scope)) {
                   8738: 		$perm{$test_perm.'_section'}=$env{'request.course.sec'};
                   8739: 	    } else {
                   8740: 		delete($perm{$test_perm});
                   8741: 	    }
1.285     albertel 8742: 	}
                   8743:     }
                   8744: }
                   8745: 
1.400     www      8746: sub gather_clicker_ids {
1.408     albertel 8747:     my %clicker_ids;
1.400     www      8748: 
                   8749:     my $classlist = &Apache::loncoursedata::get_classlist();
                   8750: 
                   8751:     # Set up a couple variables.
1.407     albertel 8752:     my $username_idx = &Apache::loncoursedata::CL_SNAME();
                   8753:     my $domain_idx   = &Apache::loncoursedata::CL_SDOM();
1.438     www      8754:     my $status_idx   = &Apache::loncoursedata::CL_STATUS();
1.400     www      8755: 
1.407     albertel 8756:     foreach my $student (keys(%$classlist)) {
1.438     www      8757:         if ($classlist->{$student}->[$status_idx] ne 'Active') { next; }
1.407     albertel 8758:         my $username = $classlist->{$student}->[$username_idx];
                   8759:         my $domain   = $classlist->{$student}->[$domain_idx];
1.400     www      8760:         my $clickers =
1.408     albertel 8761: 	    (&Apache::lonnet::userenvironment($domain,$username,'clickers'))[1];
1.400     www      8762:         foreach my $id (split(/\,/,$clickers)) {
1.414     www      8763:             $id=~s/^[\#0]+//;
1.421     www      8764:             $id=~s/[\-\:]//g;
1.407     albertel 8765:             if (exists($clicker_ids{$id})) {
1.408     albertel 8766: 		$clicker_ids{$id}.=','.$username.':'.$domain;
1.400     www      8767:             } else {
1.408     albertel 8768: 		$clicker_ids{$id}=$username.':'.$domain;
1.400     www      8769:             }
                   8770:         }
                   8771:     }
1.407     albertel 8772:     return %clicker_ids;
1.400     www      8773: }
                   8774: 
1.402     www      8775: sub gather_adv_clicker_ids {
1.408     albertel 8776:     my %clicker_ids;
1.402     www      8777:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
                   8778:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   8779:     my %coursepersonnel=&Apache::lonnet::get_course_adv_roles($cdom.'/'.$cnum);
1.409     albertel 8780:     foreach my $element (sort(keys(%coursepersonnel))) {
1.402     www      8781:         foreach my $person (split(/\,/,$coursepersonnel{$element})) {
                   8782:             my ($puname,$pudom)=split(/\:/,$person);
                   8783:             my $clickers =
1.408     albertel 8784: 		(&Apache::lonnet::userenvironment($pudom,$puname,'clickers'))[1];
1.405     www      8785:             foreach my $id (split(/\,/,$clickers)) {
1.414     www      8786: 		$id=~s/^[\#0]+//;
1.421     www      8787:                 $id=~s/[\-\:]//g;
1.408     albertel 8788: 		if (exists($clicker_ids{$id})) {
                   8789: 		    $clicker_ids{$id}.=','.$puname.':'.$pudom;
                   8790: 		} else {
                   8791: 		    $clicker_ids{$id}=$puname.':'.$pudom;
                   8792: 		}
1.405     www      8793:             }
1.402     www      8794:         }
                   8795:     }
1.407     albertel 8796:     return %clicker_ids;
1.402     www      8797: }
                   8798: 
1.413     www      8799: sub clicker_grading_parameters {
                   8800:     return ('gradingmechanism' => 'scalar',
                   8801:             'upfiletype' => 'scalar',
                   8802:             'specificid' => 'scalar',
                   8803:             'pcorrect' => 'scalar',
                   8804:             'pincorrect' => 'scalar');
                   8805: }
                   8806: 
1.400     www      8807: sub process_clicker {
                   8808:     my ($r)=@_;
                   8809:     my ($symb)=&get_symb($r);
                   8810:     if (!$symb) {return '';}
                   8811:     my $result=&checkforfile_js();
                   8812:     $env{'form.probTitle'} = &Apache::lonnet::gettitle($symb);
                   8813:     $result.='<br /><table width="100%" border="0"><tr><td bgcolor="#777777">'."\n";
                   8814:     $result.='<table width="100%" border="0"><tr bgcolor="#e6ffff"><td>'."\n";
1.538     schulted 8815:     $result.='&nbsp;<b>'.&mt('Specify a file containing the clicker information for this resource.').
                   8816:         '</b></td></tr>'."\n";
1.601     www      8817:     $result.='<tr bgcolor="#ffffe6"><td>'."\n";
1.413     www      8818: # Attempt to restore parameters from last session, set defaults if not present
                   8819:     my %Saveable_Parameters=&clicker_grading_parameters();
                   8820:     &Apache::loncommon::restore_course_settings('grades_clicker',
                   8821:                                                  \%Saveable_Parameters);
                   8822:     if (!$env{'form.pcorrect'}) { $env{'form.pcorrect'}=100; }
                   8823:     if (!$env{'form.pincorrect'}) { $env{'form.pincorrect'}=100; }
                   8824:     if (!$env{'form.gradingmechanism'}) { $env{'form.gradingmechanism'}='attendance'; }
                   8825:     if (!$env{'form.upfiletype'}) { $env{'form.upfiletype'}='iclicker'; }
                   8826: 
                   8827:     my %checked;
1.521     www      8828:     foreach my $gradingmechanism ('attendance','personnel','specific','given') {
1.413     www      8829:        if ($env{'form.gradingmechanism'} eq $gradingmechanism) {
1.569     bisitz   8830:           $checked{$gradingmechanism}=' checked="checked"';
1.413     www      8831:        }
                   8832:     }
                   8833: 
1.400     www      8834:     my $upload=&mt("Upload File");
                   8835:     my $type=&mt("Type");
1.402     www      8836:     my $attendance=&mt("Award points just for participation");
                   8837:     my $personnel=&mt("Correctness determined from response by course personnel");
1.414     www      8838:     my $specific=&mt("Correctness determined from response with clicker ID(s)"); 
1.521     www      8839:     my $given=&mt("Correctness determined from given list of answers").' '.
                   8840:               '<font size="-2"><tt>('.&mt("Provide comma-separated list. Use '*' for any answer correct, '-' for skip").')</tt></font>';
1.402     www      8841:     my $pcorrect=&mt("Percentage points for correct solution");
                   8842:     my $pincorrect=&mt("Percentage points for incorrect solution");
1.413     www      8843:     my $selectform=&Apache::loncommon::select_form($env{'form.upfiletype'},'upfiletype',
1.419     www      8844: 						   ('iclicker' => 'i>clicker',
                   8845:                                                     'interwrite' => 'interwrite PRS'));
1.418     albertel 8846:     $symb = &Apache::lonenc::check_encrypt($symb);
1.597     wenzelju 8847:     $result.= &Apache::lonhtmlcommon::scripttag(<<ENDUPFORM);
1.402     www      8848: function sanitycheck() {
                   8849: // Accept only integer percentages
                   8850:    document.forms.gradesupload.pcorrect.value=Math.round(document.forms.gradesupload.pcorrect.value);
                   8851:    document.forms.gradesupload.pincorrect.value=Math.round(document.forms.gradesupload.pincorrect.value);
                   8852: // Find out grading choice
                   8853:    for (i=0; i<document.forms.gradesupload.gradingmechanism.length; i++) {
                   8854:       if (document.forms.gradesupload.gradingmechanism[i].checked) {
                   8855:          gradingchoice=document.forms.gradesupload.gradingmechanism[i].value;
                   8856:       }
                   8857:    }
                   8858: // By default, new choice equals user selection
                   8859:    newgradingchoice=gradingchoice;
                   8860: // Not good to give more points for false answers than correct ones
                   8861:    if (Math.round(document.forms.gradesupload.pcorrect.value)<Math.round(document.forms.gradesupload.pincorrect.value)) {
                   8862:       document.forms.gradesupload.pcorrect.value=document.forms.gradesupload.pincorrect.value;
                   8863:    }
                   8864: // If new choice is attendance only, and old choice was correctness-based, restore defaults
                   8865:    if ((gradingchoice=='attendance') && (document.forms.gradesupload.waschecked.value!='attendance')) {
                   8866:       document.forms.gradesupload.pcorrect.value=100;
                   8867:       document.forms.gradesupload.pincorrect.value=100;
                   8868:    }
                   8869: // If the values are different, cannot be attendance only
                   8870:    if ((Math.round(document.forms.gradesupload.pcorrect.value)!=Math.round(document.forms.gradesupload.pincorrect.value)) &&
                   8871:        (gradingchoice=='attendance')) {
                   8872:        newgradingchoice='personnel';
                   8873:    }
                   8874: // Change grading choice to new one
                   8875:    for (i=0; i<document.forms.gradesupload.gradingmechanism.length; i++) {
                   8876:       if (document.forms.gradesupload.gradingmechanism[i].value==newgradingchoice) {
                   8877:          document.forms.gradesupload.gradingmechanism[i].checked=true;
                   8878:       } else {
                   8879:          document.forms.gradesupload.gradingmechanism[i].checked=false;
                   8880:       }
                   8881:    }
                   8882: // Remember the old state
                   8883:    document.forms.gradesupload.waschecked.value=newgradingchoice;
                   8884: }
1.597     wenzelju 8885: ENDUPFORM
                   8886:     $result.= <<ENDUPFORM;
1.400     www      8887: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
                   8888: <input type="hidden" name="symb" value="$symb" />
                   8889: <input type="hidden" name="command" value="processclickerfile" />
                   8890: <input type="hidden" name="probTitle" value="$env{'form.probTitle'}" />
                   8891: <input type="hidden" name="saveState"  value="$env{'form.saveState'}" />
                   8892: <input type="file" name="upfile" size="50" />
                   8893: <br /><label>$type: $selectform</label>
1.589     bisitz   8894: <br /><label><input type="radio" name="gradingmechanism" value="attendance"$checked{'attendance'} onclick="sanitycheck()" />$attendance </label>
                   8895: <br /><label><input type="radio" name="gradingmechanism" value="personnel"$checked{'personnel'} onclick="sanitycheck()" />$personnel</label>
                   8896: <br /><label><input type="radio" name="gradingmechanism" value="specific"$checked{'specific'} onclick="sanitycheck()" />$specific </label>
1.414     www      8897: <input type="text" name="specificid" value="$env{'form.specificid'}" size="20" />
1.589     bisitz   8898: <br /><label><input type="radio" name="gradingmechanism" value="given"$checked{'given'} onclick="sanitycheck()" />$given </label>
1.521     www      8899: <br />&nbsp;&nbsp;&nbsp;
                   8900: <input type="text" name="givenanswer" size="50" />
1.413     www      8901: <input type="hidden" name="waschecked" value="$env{'form.gradingmechanism'}" />
1.589     bisitz   8902: <br /><label>$pcorrect: <input type="text" name="pcorrect" size="4" value="$env{'form.pcorrect'}" onchange="sanitycheck()" /></label>
                   8903: <br /><label>$pincorrect: <input type="text" name="pincorrect" size="4" value="$env{'form.pincorrect'}" onchange="sanitycheck()" /></label>
                   8904: <br /><input type="button" onclick="javascript:checkUpload(this.form);" value="$upload" />
1.597     wenzelju 8905: </form>'
1.400     www      8906: ENDUPFORM
                   8907:     $result.='</td></tr></table>'."\n".
                   8908:              '</td></tr></table><br /><br />'."\n";
                   8909:     $result.=&show_grading_menu_form($symb);
                   8910:     return $result;
                   8911: }
                   8912: 
                   8913: sub process_clicker_file {
                   8914:     my ($r)=@_;
                   8915:     my ($symb)=&get_symb($r);
                   8916:     if (!$symb) {return '';}
1.413     www      8917: 
                   8918:     my %Saveable_Parameters=&clicker_grading_parameters();
                   8919:     &Apache::loncommon::store_course_settings('grades_clicker',
                   8920:                                               \%Saveable_Parameters);
1.598     www      8921:     my $result='';
                   8922: #    my ($result) = &showResourceInfo($symb,$env{'form.probTitle'});
1.404     www      8923:     if (($env{'form.gradingmechanism'} eq 'specific') && ($env{'form.specificid'}!~/\w/)) {
1.408     albertel 8924: 	$result.='<span class="LC_error">'.&mt('You need to specify a clicker ID for the correct answer').'</span>';
                   8925: 	return $result.&show_grading_menu_form($symb);
1.404     www      8926:     }
1.522     www      8927:     if (($env{'form.gradingmechanism'} eq 'given') && ($env{'form.givenanswer'}!~/\S/)) {
1.521     www      8928:         $result.='<span class="LC_error">'.&mt('You need to specify the correct answer').'</span>';
                   8929:         return $result.&show_grading_menu_form($symb);
                   8930:     }
1.522     www      8931:     my $foundgiven=0;
1.521     www      8932:     if ($env{'form.gradingmechanism'} eq 'given') {
                   8933:         $env{'form.givenanswer'}=~s/^\s*//gs;
                   8934:         $env{'form.givenanswer'}=~s/\s*$//gs;
                   8935:         $env{'form.givenanswer'}=~s/[^a-zA-Z0-9\.\*\-]+/\,/g;
                   8936:         $env{'form.givenanswer'}=uc($env{'form.givenanswer'});
1.522     www      8937:         my @answers=split(/\,/,$env{'form.givenanswer'});
                   8938:         $foundgiven=$#answers+1;
1.521     www      8939:     }
1.407     albertel 8940:     my %clicker_ids=&gather_clicker_ids();
1.408     albertel 8941:     my %correct_ids;
1.404     www      8942:     if ($env{'form.gradingmechanism'} eq 'personnel') {
1.408     albertel 8943: 	%correct_ids=&gather_adv_clicker_ids();
1.404     www      8944:     }
                   8945:     if ($env{'form.gradingmechanism'} eq 'specific') {
1.414     www      8946: 	foreach my $correct_id (split(/[\s\,]/,$env{'form.specificid'})) {;
                   8947: 	   $correct_id=~tr/a-z/A-Z/;
                   8948: 	   $correct_id=~s/\s//gs;
                   8949: 	   $correct_id=~s/^[\#0]+//;
1.421     www      8950:            $correct_id=~s/[\-\:]//g;
1.414     www      8951:            if ($correct_id) {
                   8952: 	      $correct_ids{$correct_id}='specified';
                   8953:            }
                   8954:         }
1.400     www      8955:     }
1.404     www      8956:     if ($env{'form.gradingmechanism'} eq 'attendance') {
1.408     albertel 8957: 	$result.=&mt('Score based on attendance only');
1.521     www      8958:     } elsif ($env{'form.gradingmechanism'} eq 'given') {
1.522     www      8959:         $result.=&mt('Score based on [_1] ([_2] answers)','<tt>'.$env{'form.givenanswer'}.'</tt>',$foundgiven);
1.404     www      8960:     } else {
1.408     albertel 8961: 	my $number=0;
1.411     www      8962: 	$result.='<p><b>'.&mt('Correctness determined by the following IDs').'</b>';
1.408     albertel 8963: 	foreach my $id (sort(keys(%correct_ids))) {
1.411     www      8964: 	    $result.='<br /><tt>'.$id.'</tt> - ';
1.408     albertel 8965: 	    if ($correct_ids{$id} eq 'specified') {
                   8966: 		$result.=&mt('specified');
                   8967: 	    } else {
                   8968: 		my ($uname,$udom)=split(/\:/,$correct_ids{$id});
                   8969: 		$result.=&Apache::loncommon::plainname($uname,$udom);
                   8970: 	    }
                   8971: 	    $number++;
                   8972: 	}
1.411     www      8973:         $result.="</p>\n";
1.408     albertel 8974: 	if ($number==0) {
                   8975: 	    $result.='<span class="LC_error">'.&mt('No IDs found to determine correct answer').'</span>';
                   8976: 	    return $result.&show_grading_menu_form($symb);
                   8977: 	}
1.404     www      8978:     }
1.405     www      8979:     if (length($env{'form.upfile'}) < 2) {
1.407     albertel 8980:         $result.=&mt('[_1] Error: [_2] The file you attempted to upload, [_3] contained no information. Please check that you entered the correct filename.',
                   8981: 		     '<span class="LC_error">',
                   8982: 		     '</span>',
                   8983: 		     '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>');
1.405     www      8984:         return $result.&show_grading_menu_form($symb);
                   8985:     }
1.410     www      8986: 
                   8987: # Were able to get all the info needed, now analyze the file
                   8988: 
1.411     www      8989:     $result.=&Apache::loncommon::studentbrowser_javascript();
1.418     albertel 8990:     $symb = &Apache::lonenc::check_encrypt($symb);
1.410     www      8991:     my $heading=&mt('Scanning clicker file');
                   8992:     $result.=(<<ENDHEADER);
                   8993: <br /><table width="100%" border="0"><tr><td bgcolor="#777777">
                   8994: <table width="100%" border="0"><tr bgcolor="#e6ffff"><td>
                   8995: <b>$heading</b></td></tr><tr bgcolor=#ffffe6><td>
                   8996: <form method="post" action="/adm/grades" name="clickeranalysis">
                   8997: <input type="hidden" name="symb" value="$symb" />
                   8998: <input type="hidden" name="command" value="assignclickergrades" />
                   8999: <input type="hidden" name="probTitle" value="$env{'form.probTitle'}" />
                   9000: <input type="hidden" name="saveState"  value="$env{'form.saveState'}" />
1.411     www      9001: <input type="hidden" name="gradingmechanism" value="$env{'form.gradingmechanism'}" />
                   9002: <input type="hidden" name="pcorrect" value="$env{'form.pcorrect'}" />
                   9003: <input type="hidden" name="pincorrect" value="$env{'form.pincorrect'}" />
1.410     www      9004: ENDHEADER
1.522     www      9005:     if ($env{'form.gradingmechanism'} eq 'given') {
                   9006:        $result.='<input type="hidden" name="correct:given" value="'.$env{'form.givenanswer'}.'" />';
                   9007:     } 
1.408     albertel 9008:     my %responses;
                   9009:     my @questiontitles;
1.405     www      9010:     my $errormsg='';
                   9011:     my $number=0;
                   9012:     if ($env{'form.upfiletype'} eq 'iclicker') {
1.408     albertel 9013: 	($errormsg,$number)=&iclicker_eval(\@questiontitles,\%responses);
1.406     www      9014:     }
1.419     www      9015:     if ($env{'form.upfiletype'} eq 'interwrite') {
                   9016:         ($errormsg,$number)=&interwrite_eval(\@questiontitles,\%responses);
                   9017:     }
1.411     www      9018:     $result.='<br />'.&mt('Found [_1] question(s)',$number).'<br />'.
                   9019:              '<input type="hidden" name="number" value="'.$number.'" />'.
                   9020:              &mt('Awarding [_1] percent for correct and [_2] percent for incorrect responses',
                   9021:                  $env{'form.pcorrect'},$env{'form.pincorrect'}).
                   9022:              '<br />';
1.522     www      9023:     if (($env{'form.gradingmechanism'} eq 'given') && ($number!=$foundgiven)) {
                   9024:        $result.='<span class="LC_error">'.&mt('Number of given answers does not agree with number of questions in file.').'</span>';
                   9025:        return $result.&show_grading_menu_form($symb);
                   9026:     } 
1.414     www      9027: # Remember Question Titles
                   9028: # FIXME: Possibly need delimiter other than ":"
                   9029:     for (my $i=0;$i<$number;$i++) {
                   9030:         $result.='<input type="hidden" name="question:'.$i.'" value="'.
                   9031:                  &HTML::Entities::encode($questiontitles[$i],'"&<>').'" />';
                   9032:     }
1.411     www      9033:     my $correct_count=0;
                   9034:     my $student_count=0;
                   9035:     my $unknown_count=0;
1.414     www      9036: # Match answers with usernames
                   9037: # FIXME: Possibly need delimiter other than ":"
1.409     albertel 9038:     foreach my $id (keys(%responses)) {
1.410     www      9039:        if ($correct_ids{$id}) {
1.414     www      9040:           $result.="\n".'<input type="hidden" name="correct:'.$correct_count.':'.$correct_ids{$id}.'" value="'.$responses{$id}.'" />';
1.411     www      9041:           $correct_count++;
1.410     www      9042:        } elsif ($clicker_ids{$id}) {
1.437     www      9043:           if ($clicker_ids{$id}=~/\,/) {
                   9044: # More than one user with the same clicker!
                   9045:              $result.="\n<hr />".&mt('Clicker registered more than once').": <tt>".$id."</tt><br />";
                   9046:              $result.="\n".'<input type="hidden" name="unknown:'.$id.'" value="'.$responses{$id}.'" />'.
                   9047:                            "<select name='multi".$id."'>";
                   9048:              foreach my $reguser (sort(split(/\,/,$clicker_ids{$id}))) {
                   9049:                  $result.="<option value='".$reguser."'>".&Apache::loncommon::plainname(split(/\:/,$reguser)).' ('.$reguser.')</option>';
                   9050:              }
                   9051:              $result.='</select>';
                   9052:              $unknown_count++;
                   9053:           } else {
                   9054: # Good: found one and only one user with the right clicker
                   9055:              $result.="\n".'<input type="hidden" name="student:'.$clicker_ids{$id}.'" value="'.$responses{$id}.'" />';
                   9056:              $student_count++;
                   9057:           }
1.410     www      9058:        } else {
1.411     www      9059:           $result.="\n<hr />".&mt('Unregistered Clicker')." <tt>".$id."</tt><br />";
                   9060:           $result.="\n".'<input type="hidden" name="unknown:'.$id.'" value="'.$responses{$id}.'" />'.
                   9061:                    "\n".&mt("Username").": <input type='text' name='uname".$id."' />&nbsp;".
                   9062:                    "\n".&mt("Domain").": ".
                   9063:                    &Apache::loncommon::select_dom_form($env{'course.'.$env{'request.course.id'}.'.domain'},'udom'.$id).'&nbsp;'.
                   9064:                    &Apache::loncommon::selectstudent_link('clickeranalysis','uname'.$id,'udom'.$id);
                   9065:           $unknown_count++;
1.410     www      9066:        }
1.405     www      9067:     }
1.412     www      9068:     $result.='<hr />'.
                   9069:              &mt('Found [_1] registered and [_2] unregistered clickers.',$student_count,$unknown_count);
1.521     www      9070:     if (($env{'form.gradingmechanism'} ne 'attendance') && ($env{'form.gradingmechanism'} ne 'given')) {
1.412     www      9071:        if ($correct_count==0) {
                   9072:           $errormsg.="Found no correct answers answers for grading!";
                   9073:        } elsif ($correct_count>1) {
1.414     www      9074:           $result.='<br /><span class="LC_warning">'.&mt("Found [_1] entries for grading!",$correct_count).'</span>';
1.412     www      9075:        }
                   9076:     }
1.428     www      9077:     if ($number<1) {
                   9078:        $errormsg.="Found no questions.";
                   9079:     }
1.412     www      9080:     if ($errormsg) {
                   9081:        $result.='<br /><span class="LC_error">'.&mt($errormsg).'</span>';
                   9082:     } else {
                   9083:        $result.='<br /><input type="submit" name="finalize" value="'.&mt('Finalize Grading').'" />';
                   9084:     }
                   9085:     $result.='</form></td></tr></table>'."\n".
1.410     www      9086:              '</td></tr></table><br /><br />'."\n";
1.404     www      9087:     return $result.&show_grading_menu_form($symb);
1.400     www      9088: }
                   9089: 
1.405     www      9090: sub iclicker_eval {
1.406     www      9091:     my ($questiontitles,$responses)=@_;
1.405     www      9092:     my $number=0;
                   9093:     my $errormsg='';
                   9094:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
1.410     www      9095:         my %components=&Apache::loncommon::record_sep($line);
                   9096:         my @entries=map {$components{$_}} (sort(keys(%components)));
1.408     albertel 9097: 	if ($entries[0] eq 'Question') {
                   9098: 	    for (my $i=3;$i<$#entries;$i+=6) {
                   9099: 		$$questiontitles[$number]=$entries[$i];
                   9100: 		$number++;
                   9101: 	    }
                   9102: 	}
                   9103: 	if ($entries[0]=~/^\#/) {
                   9104: 	    my $id=$entries[0];
                   9105: 	    my @idresponses;
                   9106: 	    $id=~s/^[\#0]+//;
                   9107: 	    for (my $i=0;$i<$number;$i++) {
                   9108: 		my $idx=3+$i*6;
                   9109: 		push(@idresponses,$entries[$idx]);
                   9110: 	    }
                   9111: 	    $$responses{$id}=join(',',@idresponses);
                   9112: 	}
1.405     www      9113:     }
                   9114:     return ($errormsg,$number);
                   9115: }
                   9116: 
1.419     www      9117: sub interwrite_eval {
                   9118:     my ($questiontitles,$responses)=@_;
                   9119:     my $number=0;
                   9120:     my $errormsg='';
1.420     www      9121:     my $skipline=1;
                   9122:     my $questionnumber=0;
                   9123:     my %idresponses=();
1.419     www      9124:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
                   9125:         my %components=&Apache::loncommon::record_sep($line);
                   9126:         my @entries=map {$components{$_}} (sort(keys(%components)));
1.420     www      9127:         if ($entries[1] eq 'Time') { $skipline=0; next; }
                   9128:         if ($entries[1] eq 'Response') { $skipline=1; }
                   9129:         next if $skipline;
                   9130:         if ($entries[0]!=$questionnumber) {
                   9131:            $questionnumber=$entries[0];
                   9132:            $$questiontitles[$number]=&mt('Question [_1]',$questionnumber);
                   9133:            $number++;
1.419     www      9134:         }
1.420     www      9135:         my $id=$entries[4];
                   9136:         $id=~s/^[\#0]+//;
1.421     www      9137:         $id=~s/^v\d*\://i;
                   9138:         $id=~s/[\-\:]//g;
1.420     www      9139:         $idresponses{$id}[$number]=$entries[6];
                   9140:     }
1.524     raeburn  9141:     foreach my $id (keys(%idresponses)) {
1.420     www      9142:        $$responses{$id}=join(',',@{$idresponses{$id}});
                   9143:        $$responses{$id}=~s/^\s*\,//;
1.419     www      9144:     }
                   9145:     return ($errormsg,$number);
                   9146: }
                   9147: 
1.414     www      9148: sub assign_clicker_grades {
                   9149:     my ($r)=@_;
                   9150:     my ($symb)=&get_symb($r);
                   9151:     if (!$symb) {return '';}
1.416     www      9152: # See which part we are saving to
1.582     raeburn  9153:     my $res_error;
                   9154:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
                   9155:     if ($res_error) {
                   9156:         return &navmap_errormsg();
                   9157:     }
1.416     www      9158: # FIXME: This should probably look for the first handgradeable part
                   9159:     my $part=$$partlist[0];
                   9160: # Start screen output
1.598     www      9161:     my $result='';
                   9162: #    my ($result) = &showResourceInfo($symb,$env{'form.probTitle'});
1.416     www      9163: 
1.414     www      9164:     my $heading=&mt('Assigning grades based on clicker file');
                   9165:     $result.=(<<ENDHEADER);
                   9166: <br /><table width="100%" border="0"><tr><td bgcolor="#777777">
                   9167: <table width="100%" border="0"><tr bgcolor="#e6ffff"><td>
                   9168: <b>$heading</b></td></tr><tr bgcolor=#ffffe6><td>
                   9169: ENDHEADER
                   9170: # Get correct result
                   9171: # FIXME: Possibly need delimiter other than ":"
                   9172:     my @correct=();
1.415     www      9173:     my $gradingmechanism=$env{'form.gradingmechanism'};
                   9174:     my $number=$env{'form.number'};
                   9175:     if ($gradingmechanism ne 'attendance') {
1.414     www      9176:        foreach my $key (keys(%env)) {
                   9177:           if ($key=~/^form\.correct\:/) {
                   9178:              my @input=split(/\,/,$env{$key});
                   9179:              for (my $i=0;$i<=$#input;$i++) {
                   9180:                  if (($correct[$i]) && ($input[$i]) &&
                   9181:                      ($correct[$i] ne $input[$i])) {
                   9182:                     $result.='<br /><span class="LC_warning">'.
                   9183:                              &mt('More than one correct result given for question "[_1]": [_2] versus [_3].',
                   9184:                                  $env{'form.question:'.$i},$correct[$i],$input[$i]).'</span>';
                   9185:                  } elsif ($input[$i]) {
                   9186:                     $correct[$i]=$input[$i];
                   9187:                  }
                   9188:              }
                   9189:           }
                   9190:        }
1.415     www      9191:        for (my $i=0;$i<$number;$i++) {
1.414     www      9192:           if (!$correct[$i]) {
                   9193:              $result.='<br /><span class="LC_error">'.
                   9194:                       &mt('No correct result given for question "[_1]"!',
                   9195:                           $env{'form.question:'.$i}).'</span>';
                   9196:           }
                   9197:        }
                   9198:        $result.='<br />'.&mt("Correct answer: [_1]",join(', ',map { ($_?$_:'-') } @correct));
                   9199:     }
                   9200: # Start grading
1.415     www      9201:     my $pcorrect=$env{'form.pcorrect'};
                   9202:     my $pincorrect=$env{'form.pincorrect'};
1.416     www      9203:     my $storecount=0;
1.415     www      9204:     foreach my $key (keys(%env)) {
1.420     www      9205:        my $user='';
1.415     www      9206:        if ($key=~/^form\.student\:(.*)$/) {
1.420     www      9207:           $user=$1;
                   9208:        }
                   9209:        if ($key=~/^form\.unknown\:(.*)$/) {
                   9210:           my $id=$1;
                   9211:           if (($env{'form.uname'.$id}) && ($env{'form.udom'.$id})) {
                   9212:              $user=$env{'form.uname'.$id}.':'.$env{'form.udom'.$id};
1.437     www      9213:           } elsif ($env{'form.multi'.$id}) {
                   9214:              $user=$env{'form.multi'.$id};
1.420     www      9215:           }
                   9216:        }
                   9217:        if ($user) { 
1.415     www      9218:           my @answer=split(/\,/,$env{$key});
                   9219:           my $sum=0;
1.522     www      9220:           my $realnumber=$number;
1.415     www      9221:           for (my $i=0;$i<$number;$i++) {
1.576     www      9222:              if  ($correct[$i] eq '-') {
                   9223:                 $realnumber--;
                   9224:              } elsif ($answer[$i]) {
1.415     www      9225:                 if ($gradingmechanism eq 'attendance') {
                   9226:                    $sum+=$pcorrect;
1.576     www      9227:                 } elsif ($correct[$i] eq '*') {
1.522     www      9228:                    $sum+=$pcorrect;
1.415     www      9229:                 } else {
                   9230:                    if ($answer[$i] eq $correct[$i]) {
                   9231:                       $sum+=$pcorrect;
                   9232:                    } else {
                   9233:                       $sum+=$pincorrect;
                   9234:                    }
                   9235:                 }
                   9236:              }
                   9237:           }
1.522     www      9238:           my $ave=$sum/(100*$realnumber);
1.416     www      9239: # Store
                   9240:           my ($username,$domain)=split(/\:/,$user);
                   9241:           my %grades=();
                   9242:           $grades{"resource.$part.solved"}='correct_by_override';
                   9243:           $grades{"resource.$part.awarded"}=$ave;
                   9244:           $grades{"resource.regrader"}="$env{'user.name'}:$env{'user.domain'}";
                   9245:           my $returncode=&Apache::lonnet::cstore(\%grades,$symb,
                   9246:                                                  $env{'request.course.id'},
                   9247:                                                  $domain,$username);
                   9248:           if ($returncode ne 'ok') {
                   9249:              $result.="<br /><span class=\"LC_error\">Failed to save student $username:$domain. Message when trying to save was ($returncode)</span>";
                   9250:           } else {
                   9251:              $storecount++;
                   9252:           }
1.415     www      9253:        }
                   9254:     }
                   9255: # We are done
1.549     hauer    9256:     $result.='<br />'.&mt('Successfully stored grades for [quant,_1,student].',$storecount).
1.416     www      9257:              '</td></tr></table>'."\n".
1.414     www      9258:              '</td></tr></table><br /><br />'."\n";
                   9259:     return $result.&show_grading_menu_form($symb);
                   9260: }
                   9261: 
1.582     raeburn  9262: sub navmap_errormsg {
                   9263:     return '<div class="LC_error">'.
                   9264:            &mt('An error occurred retrieving information about resources in the course.').'<br />'.
1.595     raeburn  9265:            &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  9266:            '</div>';
                   9267: }
                   9268: 
1.1       albertel 9269: sub handler {
1.41      ng       9270:     my $request=$_[0];
1.434     albertel 9271:     &reset_caches();
1.257     albertel 9272:     if ($env{'browser.mathml'}) {
1.141     www      9273: 	&Apache::loncommon::content_type($request,'text/xml');
1.41      ng       9274:     } else {
1.141     www      9275: 	&Apache::loncommon::content_type($request,'text/html');
1.41      ng       9276:     }
                   9277:     $request->send_http_header;
1.44      ng       9278:     return '' if $request->header_only;
1.41      ng       9279:     &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'});
1.324     albertel 9280:     my $symb=&get_symb($request,1);
1.160     albertel 9281:     my @commands=&Apache::loncommon::get_env_multiple('form.command');
                   9282:     my $command=$commands[0];
1.447     foxr     9283: 
1.160     albertel 9284:     if ($#commands > 0) {
                   9285: 	&Apache::lonnet::logthis("grades got multiple commands ".join(':',@commands));
                   9286:     }
1.447     foxr     9287: 
1.513     foxr     9288:     $ssi_error = 0;
1.535     raeburn  9289:     my $brcrum = [{href=>"/adm/grades",text=>"Grading"}];
                   9290:     $request->print(&Apache::loncommon::start_page('Grading',undef,
                   9291:                                           {'bread_crumbs' => $brcrum}));
1.324     albertel 9292:     if ($symb eq '' && $command eq '') {
1.601     www      9293: #
                   9294: # Not called from a resource
                   9295: #    
                   9296: 
1.41      ng       9297:     } else {
1.285     albertel 9298: 	&init_perm();
1.104     albertel 9299: 	if ($command eq 'submission' && $perm{'vgr'}) {
1.257     albertel 9300: 	    ($env{'form.student'} eq '' ? &listStudents($request) : &submission($request,0,0));
1.103     albertel 9301: 	} elsif ($command eq 'pickStudentPage' && $perm{'vgr'}) {
1.68      ng       9302: 	    &pickStudentPage($request);
1.103     albertel 9303: 	} elsif ($command eq 'displayPage' && $perm{'vgr'}) {
1.68      ng       9304: 	    &displayPage($request);
1.104     albertel 9305: 	} elsif ($command eq 'gradeByPage' && $perm{'mgr'}) {
1.71      ng       9306: 	    &updateGradeByPage($request);
1.104     albertel 9307: 	} elsif ($command eq 'processGroup' && $perm{'vgr'}) {
1.41      ng       9308: 	    &processGroup($request);
1.104     albertel 9309: 	} elsif ($command eq 'gradingmenu' && $perm{'vgr'}) {
1.443     banghart 9310: 	    $request->print(&grading_menu($request));
1.598     www      9311: 	} elsif ($command eq 'individual' && $perm{'vgr'}) {
1.600     www      9312: 	    $request->print(&submit_options($request));
1.598     www      9313:         } elsif ($command eq 'ungraded' && $perm{'vgr'}) {
                   9314:             $request->print(&submit_options($request));
                   9315:         } elsif ($command eq 'table' && $perm{'vgr'}) {
1.600     www      9316:             $request->print(&submit_options_table($request));
1.598     www      9317:         } elsif ($command eq 'all_for_one' && $perm{'vgr'}) {
1.599     www      9318:             $request->print(&submit_options_sequence($request));
1.104     albertel 9319: 	} elsif ($command eq 'viewgrades' && $perm{'vgr'}) {
1.41      ng       9320: 	    $request->print(&viewgrades($request));
1.104     albertel 9321: 	} elsif ($command eq 'handgrade' && $perm{'mgr'}) {
1.41      ng       9322: 	    $request->print(&processHandGrade($request));
1.106     albertel 9323: 	} elsif ($command eq 'editgrades' && $perm{'mgr'}) {
1.41      ng       9324: 	    $request->print(&editgrades($request));
1.602     www      9325:         } elsif ($command eq 'initialverifyreceipt' && $perm{'vgr'}) {
                   9326:             $request->print(&initialverifyreceipt($request));
1.106     albertel 9327: 	} elsif ($command eq 'verify' && $perm{'vgr'}) {
1.41      ng       9328: 	    $request->print(&verifyreceipt($request));
1.400     www      9329:         } elsif ($command eq 'processclicker' && $perm{'mgr'}) {
                   9330:             $request->print(&process_clicker($request));
                   9331:         } elsif ($command eq 'processclickerfile' && $perm{'mgr'}) {
                   9332:             $request->print(&process_clicker_file($request));
1.414     www      9333:         } elsif ($command eq 'assignclickergrades' && $perm{'mgr'}) {
                   9334:             $request->print(&assign_clicker_grades($request));
1.106     albertel 9335: 	} elsif ($command eq 'csvform' && $perm{'mgr'}) {
1.72      ng       9336: 	    $request->print(&upcsvScores_form($request));
1.106     albertel 9337: 	} elsif ($command eq 'csvupload' && $perm{'mgr'}) {
1.41      ng       9338: 	    $request->print(&csvupload($request));
1.106     albertel 9339: 	} elsif ($command eq 'csvuploadmap' && $perm{'mgr'} ) {
1.41      ng       9340: 	    $request->print(&csvuploadmap($request));
1.246     albertel 9341: 	} elsif ($command eq 'csvuploadoptions' && $perm{'mgr'}) {
1.257     albertel 9342: 	    if ($env{'form.associate'} ne 'Reverse Association') {
1.246     albertel 9343: 		$request->print(&csvuploadoptions($request));
1.41      ng       9344: 	    } else {
1.257     albertel 9345: 		if ( $env{'form.upfile_associate'} ne 'reverse' ) {
                   9346: 		    $env{'form.upfile_associate'} = 'reverse';
1.41      ng       9347: 		} else {
1.257     albertel 9348: 		    $env{'form.upfile_associate'} = 'forward';
1.41      ng       9349: 		}
                   9350: 		$request->print(&csvuploadmap($request));
                   9351: 	    }
1.246     albertel 9352: 	} elsif ($command eq 'csvuploadassign' && $perm{'mgr'} ) {
                   9353: 	    $request->print(&csvuploadassign($request));
1.106     albertel 9354: 	} elsif ($command eq 'scantron_selectphase' && $perm{'mgr'}) {
1.75      albertel 9355: 	    $request->print(&scantron_selectphase($request));
1.203     albertel 9356:  	} elsif ($command eq 'scantron_warning' && $perm{'mgr'}) {
                   9357:  	    $request->print(&scantron_do_warning($request));
1.142     albertel 9358: 	} elsif ($command eq 'scantron_validate' && $perm{'mgr'}) {
                   9359: 	    $request->print(&scantron_validate_file($request));
1.106     albertel 9360: 	} elsif ($command eq 'scantron_process' && $perm{'mgr'}) {
1.82      albertel 9361: 	    $request->print(&scantron_process_students($request));
1.157     albertel 9362:  	} elsif ($command eq 'scantronupload' && 
1.257     albertel 9363:  		 (&Apache::lonnet::allowed('usc',$env{'request.role.domain'})||
                   9364: 		  &Apache::lonnet::allowed('usc',$env{'request.course.id'}))) {
1.162     albertel 9365:  	    $request->print(&scantron_upload_scantron_data($request)); 
1.157     albertel 9366:  	} elsif ($command eq 'scantronupload_save' &&
1.257     albertel 9367:  		 (&Apache::lonnet::allowed('usc',$env{'request.role.domain'})||
                   9368: 		  &Apache::lonnet::allowed('usc',$env{'request.course.id'}))) {
1.157     albertel 9369:  	    $request->print(&scantron_upload_scantron_data_save($request));
1.202     albertel 9370:  	} elsif ($command eq 'scantron_download' &&
1.257     albertel 9371: 		 &Apache::lonnet::allowed('usc',$env{'request.course.id'})) {
1.162     albertel 9372:  	    $request->print(&scantron_download_scantron_data($request));
1.523     raeburn  9373:         } elsif ($command eq 'checksubmissions' && $perm{'vgr'}) {
                   9374:             $request->print(&checkscantron_results($request));     
1.106     albertel 9375: 	} elsif ($command) {
1.562     bisitz   9376: 	    $request->print('<p class="LC_error">'.&mt('Access Denied ([_1])',$command).'</p>');
1.26      albertel 9377: 	}
1.2       albertel 9378:     }
1.513     foxr     9379:     if ($ssi_error) {
                   9380: 	&ssi_print_error($request);
                   9381:     }
1.353     albertel 9382:     $request->print(&Apache::loncommon::end_page());
1.434     albertel 9383:     &reset_caches();
1.44      ng       9384:     return '';
                   9385: }
                   9386: 
1.1       albertel 9387: 1;
                   9388: 
1.13      albertel 9389: __END__;
1.531     jms      9390: 
                   9391: 
                   9392: =head1 NAME
                   9393: 
                   9394: Apache::grades
                   9395: 
                   9396: =head1 SYNOPSIS
                   9397: 
                   9398: Handles the viewing of grades.
                   9399: 
                   9400: This is part of the LearningOnline Network with CAPA project
                   9401: described at http://www.lon-capa.org.
                   9402: 
                   9403: =head1 OVERVIEW
                   9404: 
                   9405: Do an ssi with retries:
                   9406: While I'd love to factor out this with the vesrion in lonprintout,
                   9407: 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
                   9408: I'm not quite ready to invent (e.g. an ssi_with_retry object).
                   9409: 
                   9410: At least the logic that drives this has been pulled out into loncommon.
                   9411: 
                   9412: 
                   9413: 
                   9414: ssi_with_retries - Does the server side include of a resource.
                   9415:                      if the ssi call returns an error we'll retry it up to
                   9416:                      the number of times requested by the caller.
                   9417:                      If we still have a proble, no text is appended to the
                   9418:                      output and we set some global variables.
                   9419:                      to indicate to the caller an SSI error occurred.  
                   9420:                      All of this is supposed to deal with the issues described
                   9421:                      in LonCAPA BZ 5631 see:
                   9422:                      http://bugs.lon-capa.org/show_bug.cgi?id=5631
                   9423:                      by informing the user that this happened.
                   9424: 
                   9425: Parameters:
                   9426:   resource   - The resource to include.  This is passed directly, without
                   9427:                interpretation to lonnet::ssi.
                   9428:   form       - The form hash parameters that guide the interpretation of the resource
                   9429:                
                   9430:   retries    - Number of retries allowed before giving up completely.
                   9431: Returns:
                   9432:   On success, returns the rendered resource identified by the resource parameter.
                   9433: Side Effects:
                   9434:   The following global variables can be set:
                   9435:    ssi_error                - If an unrecoverable error occurred this becomes true.
                   9436:                               It is up to the caller to initialize this to false
                   9437:                               if desired.
                   9438:    ssi_error_resource  - If an unrecoverable error occurred, this is the value
                   9439:                               of the resource that could not be rendered by the ssi
                   9440:                               call.
                   9441:    ssi_error_message   - The error string fetched from the ssi response
                   9442:                               in the event of an error.
                   9443: 
                   9444: 
                   9445: =head1 HANDLER SUBROUTINE
                   9446: 
                   9447: ssi_with_retries()
                   9448: 
                   9449: =head1 SUBROUTINES
                   9450: 
                   9451: =over
                   9452: 
                   9453: =item scantron_get_correction() : 
                   9454: 
                   9455:    Builds the interface screen to interact with the operator to fix a
                   9456:    specific error condition in a specific scanline
                   9457: 
                   9458:  Arguments:
                   9459:     $r           - Apache request object
                   9460:     $i           - number of the current scanline
                   9461:     $scan_record - hash ref as returned from &scantron_parse_scanline()
                   9462:     $scan_config - hash ref as returned from &get_scantron_config()
                   9463:     $line        - full contents of the current scanline
                   9464:     $error       - error condition, valid values are
                   9465:                    'incorrectCODE', 'duplicateCODE',
                   9466:                    'doublebubble', 'missingbubble',
                   9467:                    'duplicateID', 'incorrectID'
                   9468:     $arg         - extra information needed
                   9469:        For errors:
                   9470:          - duplicateID   - paper number that this studentID was seen before on
                   9471:          - duplicateCODE - array ref of the paper numbers this CODE was
                   9472:                            seen on before
                   9473:          - incorrectCODE - current incorrect CODE 
                   9474:          - doublebubble  - array ref of the bubble lines that have double
                   9475:                            bubble errors
                   9476:          - missingbubble - array ref of the bubble lines that have missing
                   9477:                            bubble errors
                   9478: 
                   9479: =item  scantron_get_maxbubble() : 
                   9480: 
1.582     raeburn  9481:    Arguments:
                   9482:        $nav_error  - Reference to scalar which is a flag to indicate a
                   9483:                       failure to retrieve a navmap object.
                   9484:        if $nav_error is set to 1 by scantron_get_maxbubble(), the 
                   9485:        calling routine should trap the error condition and display the warning
                   9486:        found in &navmap_errormsg().
                   9487: 
1.531     jms      9488:    Returns the maximum number of bubble lines that are expected to
                   9489:    occur. Does this by walking the selected sequence rendering the
                   9490:    resource and then checking &Apache::lonxml::get_problem_counter()
                   9491:    for what the current value of the problem counter is.
                   9492: 
                   9493:    Caches the results to $env{'form.scantron_maxbubble'},
                   9494:    $env{'form.scantron.bubble_lines.n'}, 
                   9495:    $env{'form.scantron.first_bubble_line.n'} and
                   9496:    $env{"form.scantron.sub_bubblelines.n"}
                   9497:    which are the total number of bubble, lines, the number of bubble
                   9498:    lines for response n and number of the first bubble line for response n,
                   9499:    and a comma separated list of numbers of bubble lines for sub-questions
                   9500:    (for optionresponse, matchresponse, and rankresponse items), for response n.  
                   9501: 
                   9502: 
                   9503: =item  scantron_validate_missingbubbles() : 
                   9504: 
                   9505:    Validates all scanlines in the selected file to not have any
                   9506:     answers that don't have bubbles that have not been verified
                   9507:     to be bubble free.
                   9508: 
                   9509: =item  scantron_process_students() : 
                   9510: 
                   9511:    Routine that does the actual grading of the bubble sheet information.
                   9512: 
                   9513:    The parsed scanline hash is added to %env 
                   9514: 
                   9515:    Then foreach unskipped scanline it does an &Apache::lonnet::ssi()
                   9516:    foreach resource , with the form data of
                   9517: 
                   9518: 	'submitted'     =>'scantron' 
                   9519: 	'grade_target'  =>'grade',
                   9520: 	'grade_username'=> username of student
                   9521: 	'grade_domain'  => domain of student
                   9522: 	'grade_courseid'=> of course
                   9523: 	'grade_symb'    => symb of resource to grade
                   9524: 
                   9525:     This triggers a grading pass. The problem grading code takes care
                   9526:     of converting the bubbled letter information (now in %env) into a
                   9527:     valid submission.
                   9528: 
                   9529: =item  scantron_upload_scantron_data() :
                   9530: 
                   9531:     Creates the screen for adding a new bubble sheet data file to a course.
                   9532: 
                   9533: =item  scantron_upload_scantron_data_save() : 
                   9534: 
                   9535:    Adds a provided bubble information data file to the course if user
                   9536:    has the correct privileges to do so. 
                   9537: 
                   9538: =item  valid_file() :
                   9539: 
                   9540:    Validates that the requested bubble data file exists in the course.
                   9541: 
                   9542: =item  scantron_download_scantron_data() : 
                   9543: 
                   9544:    Shows a list of the three internal files (original, corrected,
                   9545:    skipped) for a specific bubble sheet data file that exists in the
                   9546:    course.
                   9547: 
                   9548: =item  scantron_validate_ID() : 
                   9549: 
                   9550:    Validates all scanlines in the selected file to not have any
1.556     weissno  9551:    invalid or underspecified student/employee IDs
1.531     jms      9552: 
1.582     raeburn  9553: =item navmap_errormsg() :
                   9554: 
                   9555:    Returns HTML mark-up inside a <div></div> with a link to re-initialize the course.
                   9556:    Should be called whenever the request to instantiate a navmap object fails.  
                   9557: 
1.531     jms      9558: =back
                   9559: 
                   9560: =cut

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