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

1.17      albertel    1: # The LearningOnline Network with CAPA
1.13      albertel    2: # The LON-CAPA Grading handler
1.17      albertel    3: #
1.602   ! www         4: # $Id: grades.pm,v 1.601 2010/03/21 18:31:45 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);
        !           734:    $request->print('<form name="gradingMenu"><input type="submit" value="'.&mt('Verify Receipt No.').'" />'.
        !           735:         &Apache::lonnet::recprefix($env{'request.course.id'}).
        !           736:         '-<input type="text" name="receipt" size="4" />'.
        !           737:         "</form>\n");
        !           738: }
        !           739: 
1.44      ng        740: #--- Check whether a receipt number is valid.---
                    741: sub verifyreceipt {
                    742:     my $request  = shift;
                    743: 
1.257     albertel  744:     my $courseid = $env{'request.course.id'};
1.184     www       745:     my $receipt  = &Apache::lonnet::recprefix($courseid).'-'.
1.257     albertel  746: 	$env{'form.receipt'};
1.44      ng        747:     $receipt     =~ s/[^\-\d]//g;
1.378     albertel  748:     my ($symb)   = &get_symb($request);
1.44      ng        749: 
1.487     albertel  750:     my $title.=
                    751: 	'<h3><span class="LC_info">'.
1.584     bisitz    752: 	&mt('Verifying Receipt No. [_1]',$receipt).
1.487     albertel  753: 	'</span></h3>'."\n".
                    754: 	'<h4>'.&mt('<b>Resource: </b>[_1]',$env{'form.probTitle'}).
                    755: 	'</h4>'."\n";
1.44      ng        756: 
                    757:     my ($string,$contents,$matches) = ('','',0);
1.56      matthew   758:     my (undef,undef,$fullname) = &getclasslist('all','0');
1.177     albertel  759:     
                    760:     my $receiptparts=0;
1.390     albertel  761:     if ($env{"course.$courseid.receiptalg"} eq 'receipt2' ||
                    762: 	$env{"course.$courseid.receiptalg"} eq 'receipt3') { $receiptparts=1; }
1.177     albertel  763:     my $parts=['0'];
1.582     raeburn   764:     if ($receiptparts) {
                    765:         my $res_error; 
                    766:         ($parts)=&response_type($symb,\$res_error);
                    767:         if ($res_error) {
                    768:             return &navmap_errormsg();
                    769:         } 
                    770:     }
1.486     albertel  771:     
                    772:     my $header = 
                    773: 	&Apache::loncommon::start_data_table().
                    774: 	&Apache::loncommon::start_data_table_header_row().
1.487     albertel  775: 	'<th>&nbsp;'.&mt('Fullname').'&nbsp;</th>'."\n".
                    776: 	'<th>&nbsp;'.&mt('Username').'&nbsp;</th>'."\n".
                    777: 	'<th>&nbsp;'.&mt('Domain').'&nbsp;</th>';
1.486     albertel  778:     if ($receiptparts) {
1.487     albertel  779: 	$header.='<th>&nbsp;'.&mt('Problem Part').'&nbsp;</th>';
1.486     albertel  780:     }
                    781:     $header.=
                    782: 	&Apache::loncommon::end_data_table_header_row();
                    783: 
1.294     albertel  784:     foreach (sort 
                    785: 	     {
                    786: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                    787: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                    788: 		 }
                    789: 		 return $a cmp $b;
                    790: 	     } (keys(%$fullname))) {
1.44      ng        791: 	my ($uname,$udom)=split(/\:/);
1.177     albertel  792: 	foreach my $part (@$parts) {
                    793: 	    if ($receipt eq &Apache::lonnet::ireceipt($uname,$udom,$courseid,$symb,$part)) {
1.486     albertel  794: 		$contents.=
                    795: 		    &Apache::loncommon::start_data_table_row().
                    796: 		    '<td>&nbsp;'."\n".
1.177     albertel  797: 		    '<a href="javascript:viewOneStudent(\''.$uname.'\',\''.$udom.
1.417     albertel  798: 		    '\');" target="_self">'.$$fullname{$_}.'</a>&nbsp;</td>'."\n".
1.177     albertel  799: 		    '<td>&nbsp;'.$uname.'&nbsp;</td>'.
                    800: 		    '<td>&nbsp;'.$udom.'&nbsp;</td>';
                    801: 		if ($receiptparts) {
                    802: 		    $contents.='<td>&nbsp;'.$part.'&nbsp;</td>';
                    803: 		}
1.486     albertel  804: 		$contents.= 
                    805: 		    &Apache::loncommon::end_data_table_row()."\n";
1.177     albertel  806: 		
                    807: 		$matches++;
                    808: 	    }
1.44      ng        809: 	}
                    810:     }
                    811:     if ($matches == 0) {
1.584     bisitz    812:         $string = $title
                    813:                  .'<p class="LC_warning">'
                    814:                  .&mt('No match found for the above receipt number.')
                    815:                  .'</p>';
1.44      ng        816:     } else {
1.324     albertel  817: 	$string = &jscriptNform($symb).$title.
1.487     albertel  818: 	    '<p>'.
1.584     bisitz    819: 	    &mt('The above receipt number matches the following [quant,_1,student].',$matches).
1.487     albertel  820: 	    '</p>'.
1.486     albertel  821: 	    $header.
                    822: 	    $contents.
                    823: 	    &Apache::loncommon::end_data_table()."\n";
1.44      ng        824:     }
1.324     albertel  825:     return $string.&show_grading_menu_form($symb);
1.44      ng        826: }
                    827: 
                    828: #--- This is called by a number of programs.
                    829: #--- Called from the Grading Menu - View/Grade an individual student
                    830: #--- Also called directly when one clicks on the subm button 
                    831: #    on the problem page.
1.30      ng        832: sub listStudents {
1.41      ng        833:     my ($request) = shift;
1.49      albertel  834: 
1.324     albertel  835:     my ($symb) = &get_symb($request);
1.257     albertel  836:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
                    837:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
                    838:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
1.449     banghart  839:     my $getgroup  = $env{'form.group'} eq '' ? 'all' : $env{'form.group'};
1.257     albertel  840:     my $submitonly= $env{'form.submitonly'} eq '' ? 'all' : $env{'form.submitonly'};
1.548     bisitz    841:     my $viewgrade = $env{'form.showgrading'} eq 'yes' ? 'View/Grade/Regrade' : 'View';
1.257     albertel  842:     $env{'form.probTitle'} = $env{'form.probTitle'} eq '' ? 
                    843: 	&Apache::lonnet::gettitle($symb) : $env{'form.probTitle'};
1.49      albertel  844: 
1.548     bisitz    845:     my $result='<h3><span class="LC_info">&nbsp;'
                    846: 	.&mt("$viewgrade Submissions for a Student or a Group of Students")
1.485     albertel  847: 	.'</span></h3>';
1.118     ng        848: 
1.598     www       849:     my ($partlist,$handgrade,$responseType) = &response_type($symb
                    850: #,$res_error
                    851:     );
1.49      albertel  852: 
1.559     raeburn   853:     my %lt = &Apache::lonlocal::texthash (
                    854: 		'multiple' => 'Please select a student or group of students before clicking on the Next button.',
                    855: 		'single'   => 'Please select the student before clicking on the Next button.',
                    856: 	     );
1.597     wenzelju  857:     $request->print(&Apache::lonhtmlcommon::scripttag(<<LISTJAVASCRIPT));
1.110     ng        858:     function checkSelect(checkBox) {
                    859: 	var ctr=0;
                    860: 	var sense="";
                    861: 	if (checkBox.length > 1) {
                    862: 	    for (var i=0; i<checkBox.length; i++) {
                    863: 		if (checkBox[i].checked) {
                    864: 		    ctr++;
                    865: 		}
                    866: 	    }
1.485     albertel  867: 	    sense = '$lt{'multiple'}';
1.110     ng        868: 	} else {
                    869: 	    if (checkBox.checked) {
                    870: 		ctr = 1;
                    871: 	    }
1.485     albertel  872: 	    sense = '$lt{'single'}';
1.110     ng        873: 	}
                    874: 	if (ctr == 0) {
1.485     albertel  875: 	    alert(sense);
1.110     ng        876: 	    return false;
                    877: 	}
                    878: 	document.gradesub.submit();
                    879:     }
                    880: 
                    881:     function reLoadList(formname) {
1.112     ng        882: 	if (formname.saveStatusOld.value == pullDownSelection(formname.Status)) {return;}
1.110     ng        883: 	formname.command.value = 'submission';
                    884: 	formname.submit();
                    885:     }
1.45      ng        886: LISTJAVASCRIPT
                    887: 
1.118     ng        888:     &commonJSfunctions($request);
1.41      ng        889:     $request->print($result);
1.39      ng        890: 
1.401     albertel  891:     my $checkhdgrade = ($env{'form.handgrade'} eq 'yes' && scalar(@$partlist) > 1 ) ? 'checked="checked"' : '';
                    892:     my $checklastsub = $checkhdgrade eq '' ? 'checked="checked"' : '';
1.154     albertel  893:     my $gradeTable='<form action="/adm/grades" method="post" name="gradesub">'.
1.598     www       894: 	"\n";
1.485     albertel  895: 	
1.561     bisitz    896:     $gradeTable .= &Apache::lonhtmlcommon::start_pick_box();
                    897:     $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('View Problem Text'))
                    898:                   .'<label><input type="radio" name="vProb" value="no" checked="checked" /> '.&mt('no').' </label>'."\n"
                    899:                   .'<label><input type="radio" name="vProb" value="yes" /> '.&mt('one student').' </label>'."\n"
                    900:                   .'<label><input type="radio" name="vProb" value="all" /> '.&mt('all students').' </label><br />'."\n"
                    901:                   .&Apache::lonhtmlcommon::row_closure();
                    902:     $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('View Answer'))
                    903:                   .'<label><input type="radio" name="vAns" value="no"  /> '.&mt('no').' </label>'."\n"
                    904:                   .'<label><input type="radio" name="vAns" value="yes" /> '.&mt('one student').' </label>'."\n"
                    905:                   .'<label><input type="radio" name="vAns" value="all" checked="checked" /> '.&mt('all students').' </label><br />'."\n"
                    906:                   .&Apache::lonhtmlcommon::row_closure();
1.485     albertel  907: 
                    908:     my $submission_options;
1.257     albertel  909:     if ($env{'form.handgrade'} eq 'yes' && scalar(@$partlist) > 1) {
1.485     albertel  910: 	$submission_options.=
                    911: 	    '<label><input type="radio" name="lastSub" value="hdgrade" '.$checkhdgrade.' /> '.&mt('essay part only').' </label>'."\n";
1.49      albertel  912:     }
1.442     banghart  913:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
                    914:     my $saveStatus = $stu_status eq '' ? 'Active' : $stu_status;
1.257     albertel  915:     $env{'form.Status'} = $saveStatus;
1.485     albertel  916:     $submission_options.=
1.592     bisitz    917:         '<span class="LC_nobreak">'.
                    918:         '<label><input type="radio" name="lastSub" value="lastonly" '.$checklastsub.' /> '.
                    919:         &mt('last submission only').' </label></span>'."\n".
                    920:         '<span class="LC_nobreak">'.
                    921:         '<label><input type="radio" name="lastSub" value="last" /> '.
                    922:         &mt('last submission &amp; parts info').' </label></span>'."\n".
                    923:         '<span class="LC_nobreak">'.
                    924:         '<label><input type="radio" name="lastSub" value="datesub" /> '.
                    925:         &mt('by dates and submissions').'</label></span>'."\n".
                    926:         '<span class="LC_nobreak">'.
                    927:         '<label><input type="radio" name="lastSub" value="all" /> '.
                    928:         &mt('all details').'</label></span>';
1.561     bisitz    929:     $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('Submissions'))
                    930:                   .$submission_options
                    931:                   .&Apache::lonhtmlcommon::row_closure();
                    932: 
                    933:     $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('Grading Increments'))
                    934:                   .'<select name="increment">'
                    935:                   .'<option value="1">'.&mt('Whole Points').'</option>'
                    936:                   .'<option value=".5">'.&mt('Half Points').'</option>'
                    937:                   .'<option value=".25">'.&mt('Quarter Points').'</option>'
                    938:                   .'<option value=".1">'.&mt('Tenths of a Point').'</option>'
                    939:                   .'</select>'
                    940:                   .&Apache::lonhtmlcommon::row_closure();
1.485     albertel  941: 
                    942:     $gradeTable .= 
1.432     banghart  943:         &build_section_inputs().
1.45      ng        944: 	'<input type="hidden" name="submitonly"  value="'.$submitonly.'" />'."\n".
1.257     albertel  945: 	'<input type="hidden" name="handgrade"   value="'.$env{'form.handgrade'}.'" /><br />'."\n".
                    946: 	'<input type="hidden" name="showgrading" value="'.$env{'form.showgrading'}.'" /><br />'."\n".
                    947: 	'<input type="hidden" name="saveState"   value="'.$env{'form.saveState'}.'" />'."\n".
                    948: 	'<input type="hidden" name="probTitle"   value="'.$env{'form.probTitle'}.'" />'."\n".
1.418     albertel  949: 	'<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.110     ng        950: 	'<input type="hidden" name="saveStatusOld" value="'.$saveStatus.'" />'."\n";
                    951: 
1.257     albertel  952:     if (exists($env{'form.gradingMenu'}) && exists($env{'form.Status'})) {
1.561     bisitz    953: 	$gradeTable .= '<input type="hidden" name="Status" value="'.$stu_status.'" />'."\n";
1.124     ng        954:     } else {
1.561     bisitz    955:         $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('Student Status'))
                    956:                       .&Apache::lonhtmlcommon::StatusOptions(
                    957:                            $saveStatus,undef,1,'javascript:reLoadList(this.form);')
                    958:                       .&Apache::lonhtmlcommon::row_closure();
1.124     ng        959:     }
1.112     ng        960: 
1.561     bisitz    961:     $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('Check For Plagiarism'))
                    962:                   .'<input type="checkbox" name="checkPlag" checked="checked" />'
                    963:                   .&Apache::lonhtmlcommon::row_closure(1)
                    964:                   .&Apache::lonhtmlcommon::end_pick_box();
                    965: 
                    966:     $gradeTable .= '<p>'
                    967:                   .&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"
                    968:                   .'<input type="hidden" name="command" value="processGroup" />'
                    969:                   .'</p>';
1.249     albertel  970: 
                    971: # checkall buttons
                    972:     $gradeTable.=&check_script('gradesub', 'stuinfo');
1.110     ng        973:     $gradeTable.='<input type="button" '."\n".
1.589     bisitz    974:         'onclick="javascript:checkSelect(this.form.stuinfo);" '."\n".
                    975:         'value="'.&mt('Next').' &rarr;" /> <br />'."\n";
1.249     albertel  976:     $gradeTable.=&check_buttons();
1.450     banghart  977:     my ($classlist, undef, $fullname) = &getclasslist($getsec,'1',$getgroup);
1.474     albertel  978:     $gradeTable.= &Apache::loncommon::start_data_table().
                    979: 	&Apache::loncommon::start_data_table_header_row();
1.110     ng        980:     my $loop = 0;
                    981:     while ($loop < 2) {
1.485     albertel  982: 	$gradeTable.='<th>'.&mt('No.').'</th><th>'.&mt('Select').'</th>'.
                    983: 	    '<th>'.&nameUserString('header').'&nbsp;'.&mt('Section/Group').'</th>';
1.301     albertel  984: 	if ($env{'form.showgrading'} eq 'yes' 
                    985: 	    && $submitonly ne 'queued'
                    986: 	    && $submitonly ne 'all') {
1.485     albertel  987: 	    foreach my $part (sort(@$partlist)) {
                    988: 		my $display_part=
                    989: 		    &get_display_part((split(/_/,$part))[0],$symb);
                    990: 		$gradeTable.=
                    991: 		    '<th>'.&mt('Part: [_1] Status',$display_part).'</th>';
1.110     ng        992: 	    }
1.301     albertel  993: 	} elsif ($submitonly eq 'queued') {
1.474     albertel  994: 	    $gradeTable.='<th>'.&mt('Queue Status').'&nbsp;</th>';
1.110     ng        995: 	}
                    996: 	$loop++;
1.126     ng        997: #	$gradeTable.='<td></td>' if ($loop%2 ==1);
1.41      ng        998:     }
1.474     albertel  999:     $gradeTable.=&Apache::loncommon::end_data_table_header_row()."\n";
1.41      ng       1000: 
1.45      ng       1001:     my $ctr = 0;
1.294     albertel 1002:     foreach my $student (sort 
                   1003: 			 {
                   1004: 			     if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                   1005: 				 return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                   1006: 			     }
                   1007: 			     return $a cmp $b;
                   1008: 			 }
                   1009: 			 (keys(%$fullname))) {
1.41      ng       1010: 	my ($uname,$udom) = split(/:/,$student);
1.301     albertel 1011: 
1.110     ng       1012: 	my %status = ();
1.301     albertel 1013: 
                   1014: 	if ($submitonly eq 'queued') {
                   1015: 	    my %queue_status = 
                   1016: 		&Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
                   1017: 							$udom,$uname);
                   1018: 	    next if (!defined($queue_status{'gradingqueue'}));
                   1019: 	    $status{'gradingqueue'} = $queue_status{'gradingqueue'};
                   1020: 	}
                   1021: 
                   1022: 	if ($env{'form.showgrading'} eq 'yes' 
                   1023: 	    && $submitonly ne 'queued'
                   1024: 	    && $submitonly ne 'all') {
1.324     albertel 1025: 	    (%status) =&student_gradeStatus($symb,$udom,$uname,$partlist);
1.145     albertel 1026: 	    my $submitted = 0;
1.164     albertel 1027: 	    my $graded = 0;
1.248     albertel 1028: 	    my $incorrect = 0;
1.110     ng       1029: 	    foreach (keys(%status)) {
1.145     albertel 1030: 		$submitted = 1 if ($status{$_} ne 'nothing');
1.248     albertel 1031: 		$graded = 1 if ($status{$_} =~ /^ungraded/);
                   1032: 		$incorrect = 1 if ($status{$_} =~ /^incorrect/);
                   1033: 		
1.110     ng       1034: 		my ($foo,$partid,$foo1) = split(/\./,$_);
                   1035: 		if ($status{'resource.'.$partid.'.submitted_by'} ne '') {
1.145     albertel 1036: 		    $submitted = 0;
1.150     albertel 1037: 		    my ($part)=split(/\./,$partid);
1.110     ng       1038: 		    $gradeTable.='<input type="hidden" name="'.
1.150     albertel 1039: 			$student.':'.$part.':submitted_by" value="'.
1.110     ng       1040: 			$status{'resource.'.$partid.'.submitted_by'}.'" />';
                   1041: 		}
1.41      ng       1042: 	    }
1.248     albertel 1043: 	    
1.156     albertel 1044: 	    next if (!$submitted && ($submitonly eq 'yes' ||
                   1045: 				     $submitonly eq 'incorrect' ||
                   1046: 				     $submitonly eq 'graded'));
1.248     albertel 1047: 	    next if (!$graded && ($submitonly eq 'graded'));
                   1048: 	    next if (!$incorrect && $submitonly eq 'incorrect');
1.41      ng       1049: 	}
1.34      ng       1050: 
1.45      ng       1051: 	$ctr++;
1.249     albertel 1052: 	my $section = $classlist->{$student}->[&Apache::loncoursedata::CL_SECTION()];
1.452     banghart 1053:         my $group = $classlist->{$student}->[&Apache::loncoursedata::CL_GROUP()];
1.104     albertel 1054: 	if ( $perm{'vgr'} eq 'F' ) {
1.474     albertel 1055: 	    if ($ctr%2 ==1) {
                   1056: 		$gradeTable.= &Apache::loncommon::start_data_table_row();
                   1057: 	    }
1.126     ng       1058: 	    $gradeTable.='<td align="right">'.$ctr.'&nbsp;</td>'.
1.563     bisitz   1059:                '<td align="center"><label><input type="checkbox" name="stuinfo" value="'.
1.249     albertel 1060:                $student.':'.$$fullname{$student}.':::SECTION'.$section.
                   1061: 	       ')&nbsp;" />&nbsp;&nbsp;</label></td>'."\n".'<td>'.
                   1062: 	       &nameUserString(undef,$$fullname{$student},$uname,$udom).
1.474     albertel 1063: 	       '&nbsp;'.$section.($group ne '' ?'/'.$group:'').'</td>'."\n";
1.110     ng       1064: 
1.257     albertel 1065: 	    if ($env{'form.showgrading'} eq 'yes' && $submitonly ne 'all') {
1.524     raeburn  1066: 		foreach (sort(keys(%status))) {
1.485     albertel 1067: 		    next if ($_ =~ /^resource.*?submitted_by$/);
                   1068: 		    $gradeTable.='<td align="center">&nbsp;'.&mt($status{$_}).'&nbsp;</td>'."\n";
1.110     ng       1069: 		}
1.41      ng       1070: 	    }
1.126     ng       1071: #	    $gradeTable.='<td></td>' if ($ctr%2 ==1);
1.474     albertel 1072: 	    if ($ctr%2 ==0) {
                   1073: 		$gradeTable.=&Apache::loncommon::end_data_table_row()."\n";
                   1074: 	    }
1.41      ng       1075: 	}
                   1076:     }
1.110     ng       1077:     if ($ctr%2 ==1) {
1.126     ng       1078: 	$gradeTable.='<td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td>';
1.301     albertel 1079: 	    if ($env{'form.showgrading'} eq 'yes' 
                   1080: 		&& $submitonly ne 'queued'
                   1081: 		&& $submitonly ne 'all') {
1.110     ng       1082: 		foreach (@$partlist) {
                   1083: 		    $gradeTable.='<td>&nbsp;</td>';
                   1084: 		}
1.301     albertel 1085: 	    } elsif ($submitonly eq 'queued') {
                   1086: 		$gradeTable.='<td>&nbsp;</td>';
1.110     ng       1087: 	    }
1.474     albertel 1088: 	$gradeTable.=&Apache::loncommon::end_data_table_row();
1.110     ng       1089:     }
                   1090: 
1.474     albertel 1091:     $gradeTable.=&Apache::loncommon::end_data_table()."\n".
1.589     bisitz   1092:         '<input type="button" '.
                   1093:         'onclick="javascript:checkSelect(this.form.stuinfo);" '.
                   1094:         'value="'.&mt('Next').' &rarr;" /></form>'."\n";
1.45      ng       1095:     if ($ctr == 0) {
1.96      albertel 1096: 	my $num_students=(scalar(keys(%$fullname)));
                   1097: 	if ($num_students eq 0) {
1.485     albertel 1098: 	    $gradeTable='<br />&nbsp;<span class="LC_warning">'.&mt('There are no students currently enrolled.').'</span>';
1.96      albertel 1099: 	} else {
1.171     albertel 1100: 	    my $submissions='submissions';
                   1101: 	    if ($submitonly eq 'incorrect') { $submissions = 'incorrect submissions'; }
                   1102: 	    if ($submitonly eq 'graded'   ) { $submissions = 'ungraded submissions'; }
1.301     albertel 1103: 	    if ($submitonly eq 'queued'   ) { $submissions = 'queued submissions'; }
1.398     albertel 1104: 	    $gradeTable='<br />&nbsp;<span class="LC_warning">'.
1.485     albertel 1105: 		&mt('No '.$submissions.' found for this resource for any students. ([_1] students checked for '.$submissions.')',
                   1106: 		    $num_students).
                   1107: 		'</span><br />';
1.96      albertel 1108: 	}
1.46      ng       1109:     } elsif ($ctr == 1) {
1.474     albertel 1110: 	$gradeTable =~ s/type="checkbox"/type="checkbox" checked="checked"/;
1.45      ng       1111:     }
1.324     albertel 1112:     $gradeTable.=&show_grading_menu_form($symb);
1.45      ng       1113:     $request->print($gradeTable);
1.44      ng       1114:     return '';
1.10      ng       1115: }
                   1116: 
1.44      ng       1117: #---- Called from the listStudents routine
1.249     albertel 1118: 
                   1119: sub check_script {
                   1120:     my ($form, $type)=@_;
1.597     wenzelju 1121:     my $chkallscript= &Apache::lonhtmlcommon::scripttag('
1.249     albertel 1122:     function checkall() {
                   1123:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
                   1124:             ele = document.forms.'.$form.'.elements[i];
                   1125:             if (ele.name == "'.$type.'") {
                   1126:             document.forms.'.$form.'.elements[i].checked=true;
                   1127:                                        }
                   1128:         }
                   1129:     }
                   1130: 
                   1131:     function checksec() {
                   1132:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
                   1133:             ele = document.forms.'.$form.'.elements[i];
                   1134:            string = document.forms.'.$form.'.chksec.value;
                   1135:            if
                   1136:           (ele.value.indexOf(":::SECTION"+string)>0) {
                   1137:               document.forms.'.$form.'.elements[i].checked=true;
                   1138:             }
                   1139:         }
                   1140:     }
                   1141: 
                   1142: 
                   1143:     function uncheckall() {
                   1144:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
                   1145:             ele = document.forms.'.$form.'.elements[i];
                   1146:             if (ele.name == "'.$type.'") {
                   1147:             document.forms.'.$form.'.elements[i].checked=false;
                   1148:                                        }
                   1149:         }
                   1150:     }
                   1151: 
1.597     wenzelju 1152: '."\n");
1.249     albertel 1153:     return $chkallscript;
                   1154: }
                   1155: 
                   1156: sub check_buttons {
1.485     albertel 1157:     my $buttons.='<input type="button" onclick="checkall()" value="'.&mt('Check All').'" />';
                   1158:     $buttons.='<input type="button" onclick="uncheckall()" value="'.&mt('Uncheck All').'" />&nbsp;';
                   1159:     $buttons.='<input type="button" onclick="checksec()" value="'.&mt('Check Section/Group').'" />';
1.249     albertel 1160:     $buttons.='<input type="text" size="5" name="chksec" />&nbsp;';
                   1161:     return $buttons;
                   1162: }
                   1163: 
1.44      ng       1164: #     Displays the submissions for one student or a group of students
1.34      ng       1165: sub processGroup {
1.41      ng       1166:     my ($request)  = shift;
                   1167:     my $ctr        = 0;
1.155     albertel 1168:     my @stuchecked = &Apache::loncommon::get_env_multiple('form.stuinfo');
1.41      ng       1169:     my $total      = scalar(@stuchecked)-1;
1.45      ng       1170: 
1.396     banghart 1171:     foreach my $student (@stuchecked) {
                   1172: 	my ($uname,$udom,$fullname) = split(/:/,$student);
1.257     albertel 1173: 	$env{'form.student'}        = $uname;
                   1174: 	$env{'form.userdom'}        = $udom;
                   1175: 	$env{'form.fullname'}       = $fullname;
1.41      ng       1176: 	&submission($request,$ctr,$total);
                   1177: 	$ctr++;
                   1178:     }
                   1179:     return '';
1.35      ng       1180: }
1.34      ng       1181: 
1.44      ng       1182: #------------------------------------------------------------------------------------
                   1183: #
                   1184: #-------------------------- Next few routines handles grading by student, essentially
                   1185: #                           handles essay response type problem/part
                   1186: #
                   1187: #--- Javascript to handle the submission page functionality ---
                   1188: sub sub_page_js {
                   1189:     my $request = shift;
1.539     riegler  1190: 	    my $alertmsg = &mt('A number equal or greater than 0 is expected. Entered value = ');
1.597     wenzelju 1191:     $request->print(&Apache::lonhtmlcommon::scripttag(<<SUBJAVASCRIPT));
1.71      ng       1192:     function updateRadio(formname,id,weight) {
1.125     ng       1193: 	var gradeBox = formname["GD_BOX"+id];
                   1194: 	var radioButton = formname["RADVAL"+id];
                   1195: 	var oldpts = formname["oldpts"+id].value;
1.72      ng       1196: 	var pts = checkSolved(formname,id) == 'update' ? gradeBox.value : oldpts;
1.71      ng       1197: 	gradeBox.value = pts;
                   1198: 	var resetbox = false;
                   1199: 	if (isNaN(pts) || pts < 0) {
1.539     riegler  1200: 	    alert("$alertmsg"+pts);
1.71      ng       1201: 	    for (var i=0; i<radioButton.length; i++) {
                   1202: 		if (radioButton[i].checked) {
                   1203: 		    gradeBox.value = i;
                   1204: 		    resetbox = true;
                   1205: 		}
                   1206: 	    }
                   1207: 	    if (!resetbox) {
                   1208: 		formtextbox.value = "";
                   1209: 	    }
                   1210: 	    return;
1.44      ng       1211: 	}
1.71      ng       1212: 
                   1213: 	if (pts > weight) {
                   1214: 	    var resp = confirm("You entered a value ("+pts+
                   1215: 			       ") greater than the weight for the part. Accept?");
                   1216: 	    if (resp == false) {
1.125     ng       1217: 		gradeBox.value = oldpts;
1.71      ng       1218: 		return;
                   1219: 	    }
1.44      ng       1220: 	}
1.13      albertel 1221: 
1.71      ng       1222: 	for (var i=0; i<radioButton.length; i++) {
                   1223: 	    radioButton[i].checked=false;
                   1224: 	    if (pts == i && pts != "") {
                   1225: 		radioButton[i].checked=true;
                   1226: 	    }
                   1227: 	}
                   1228: 	updateSelect(formname,id);
1.125     ng       1229: 	formname["stores"+id].value = "0";
1.41      ng       1230:     }
1.5       albertel 1231: 
1.72      ng       1232:     function writeBox(formname,id,pts) {
1.125     ng       1233: 	var gradeBox = formname["GD_BOX"+id];
1.71      ng       1234: 	if (checkSolved(formname,id) == 'update') {
                   1235: 	    gradeBox.value = pts;
                   1236: 	} else {
1.125     ng       1237: 	    var oldpts = formname["oldpts"+id].value;
1.72      ng       1238: 	    gradeBox.value = oldpts;
1.125     ng       1239: 	    var radioButton = formname["RADVAL"+id];
1.71      ng       1240: 	    for (var i=0; i<radioButton.length; i++) {
                   1241: 		radioButton[i].checked=false;
1.72      ng       1242: 		if (i == oldpts) {
1.71      ng       1243: 		    radioButton[i].checked=true;
                   1244: 		}
                   1245: 	    }
1.41      ng       1246: 	}
1.125     ng       1247: 	formname["stores"+id].value = "0";
1.71      ng       1248: 	updateSelect(formname,id);
                   1249: 	return;
1.41      ng       1250:     }
1.44      ng       1251: 
1.71      ng       1252:     function clearRadBox(formname,id) {
                   1253: 	if (checkSolved(formname,id) == 'noupdate') {
                   1254: 	    updateSelect(formname,id);
                   1255: 	    return;
                   1256: 	}
1.125     ng       1257: 	gradeSelect = formname["GD_SEL"+id];
1.71      ng       1258: 	for (var i=0; i<gradeSelect.length; i++) {
                   1259: 	    if (gradeSelect[i].selected) {
                   1260: 		var selectx=i;
                   1261: 	    }
                   1262: 	}
1.125     ng       1263: 	var stores = formname["stores"+id];
1.71      ng       1264: 	if (selectx == stores.value) { return };
1.125     ng       1265: 	var gradeBox = formname["GD_BOX"+id];
1.71      ng       1266: 	gradeBox.value = "";
1.125     ng       1267: 	var radioButton = formname["RADVAL"+id];
1.71      ng       1268: 	for (var i=0; i<radioButton.length; i++) {
                   1269: 	    radioButton[i].checked=false;
                   1270: 	}
                   1271: 	stores.value = selectx;
                   1272:     }
1.5       albertel 1273: 
1.71      ng       1274:     function checkSolved(formname,id) {
1.125     ng       1275: 	if (formname["solved"+id].value == "correct_by_student" && formname.overRideScore.value == 'no') {
1.118     ng       1276: 	    var reply = confirm("This problem has been graded correct by the computer. Do you want to change the score?");
                   1277: 	    if (!reply) {return "noupdate";}
1.120     ng       1278: 	    formname.overRideScore.value = 'yes';
1.41      ng       1279: 	}
1.71      ng       1280: 	return "update";
1.13      albertel 1281:     }
1.71      ng       1282: 
                   1283:     function updateSelect(formname,id) {
1.125     ng       1284: 	formname["GD_SEL"+id][0].selected = true;
1.71      ng       1285: 	return;
1.41      ng       1286:     }
1.33      ng       1287: 
1.121     ng       1288: //=========== Check that a point is assigned for all the parts  ============
1.71      ng       1289:     function checksubmit(formname,val,total,parttot) {
1.121     ng       1290: 	formname.gradeOpt.value = val;
1.71      ng       1291: 	if (val == "Save & Next") {
                   1292: 	    for (i=0;i<=total;i++) {
                   1293: 		for (j=0;j<parttot;j++) {
1.125     ng       1294: 		    var partid = formname["partid"+i+"_"+j].value;
1.127     ng       1295: 		    if (formname["GD_SEL"+i+"_"+partid][0].selected) {
1.125     ng       1296: 			var points = formname["GD_BOX"+i+"_"+partid].value;
1.71      ng       1297: 			if (points == "") {
1.125     ng       1298: 			    var name = formname["name"+i].value;
1.129     ng       1299: 			    var studentID = (name != '' ? name : formname["unamedom"+i].value);
                   1300: 			    var resp = confirm("You did not assign a score for "+studentID+
                   1301: 					       ", part "+partid+". Continue?");
1.71      ng       1302: 			    if (resp == false) {
1.125     ng       1303: 				formname["GD_BOX"+i+"_"+partid].focus();
1.71      ng       1304: 				return false;
                   1305: 			    }
                   1306: 			}
                   1307: 		    }
                   1308: 		    
                   1309: 		}
                   1310: 	    }
                   1311: 	    
                   1312: 	}
1.121     ng       1313: 	if (val == "Grade Student") {
                   1314: 	    formname.showgrading.value = "yes";
                   1315: 	    if (formname.Status.value == "") {
                   1316: 		formname.Status.value = "Active";
                   1317: 	    }
                   1318: 	    formname.studentNo.value = total;
                   1319: 	}
1.120     ng       1320: 	formname.submit();
                   1321:     }
                   1322: 
1.71      ng       1323: //======= Check that a score is assigned for all the problems (page/sequence grading only) =========
                   1324:     function checkSubmitPage(formname,total) {
                   1325: 	noscore = new Array(100);
                   1326: 	var ptr = 0;
                   1327: 	for (i=1;i<total;i++) {
1.125     ng       1328: 	    var partid = formname["q_"+i].value;
1.127     ng       1329: 	    if (formname["GD_SEL"+i+"_"+partid][0].selected) {
1.125     ng       1330: 		var points = formname["GD_BOX"+i+"_"+partid].value;
                   1331: 		var status = formname["solved"+i+"_"+partid].value;
1.71      ng       1332: 		if (points == "" && status != "correct_by_student") {
                   1333: 		    noscore[ptr] = i;
                   1334: 		    ptr++;
                   1335: 		}
                   1336: 	    }
                   1337: 	}
                   1338: 	if (ptr != 0) {
                   1339: 	    var sense = ptr == 1 ? ": " : "s: ";
                   1340: 	    var prolist = "";
                   1341: 	    if (ptr == 1) {
                   1342: 		prolist = noscore[0];
                   1343: 	    } else {
                   1344: 		var i = 0;
                   1345: 		while (i < ptr-1) {
                   1346: 		    prolist += noscore[i]+", ";
                   1347: 		    i++;
                   1348: 		}
                   1349: 		prolist += "and "+noscore[i];
                   1350: 	    }
                   1351: 	    var resp = confirm("You did not assign any score for the following problem"+sense+prolist+". Continue?");
                   1352: 	    if (resp == false) {
                   1353: 		return false;
                   1354: 	    }
                   1355: 	}
1.45      ng       1356: 
1.71      ng       1357: 	formname.submit();
                   1358:     }
                   1359: SUBJAVASCRIPT
                   1360: }
1.45      ng       1361: 
1.71      ng       1362: #--- javascript for essay type problem --
                   1363: sub sub_page_kw_js {
                   1364:     my $request = shift;
1.80      ng       1365:     my $iconpath = $request->dir_config('lonIconsURL');
1.118     ng       1366:     &commonJSfunctions($request);
1.350     albertel 1367: 
1.597     wenzelju 1368:     my $inner_js_msg_central= &Apache::lonhtmlcommon::scripttag(<<INNERJS);
1.350     albertel 1369:     function checkInput() {
                   1370:       opener.document.SCORE.msgsub.value = opener.checkEntities(document.msgcenter.msgsub.value);
                   1371:       var nmsg   = opener.document.SCORE.savemsgN.value;
                   1372:       var usrctr = document.msgcenter.usrctr.value;
                   1373:       var newval = opener.document.SCORE["newmsg"+usrctr];
                   1374:       newval.value = opener.checkEntities(document.msgcenter.newmsg.value);
                   1375: 
                   1376:       var msgchk = "";
                   1377:       if (document.msgcenter.subchk.checked) {
                   1378:          msgchk = "msgsub,";
                   1379:       }
                   1380:       var includemsg = 0;
                   1381:       for (var i=1; i<=nmsg; i++) {
                   1382:           var opnmsg = opener.document.SCORE["savemsg"+i];
                   1383:           var frmmsg = document.msgcenter["msg"+i];
                   1384:           opnmsg.value = opener.checkEntities(frmmsg.value);
                   1385:           var showflg = opener.document.SCORE["shownOnce"+i];
                   1386:           showflg.value = "1";
                   1387:           var chkbox = document.msgcenter["msgn"+i];
                   1388:           if (chkbox.checked) {
                   1389:              msgchk += "savemsg"+i+",";
                   1390:              includemsg = 1;
                   1391:           }
                   1392:       }
                   1393:       if (document.msgcenter.newmsgchk.checked) {
                   1394:          msgchk += "newmsg"+usrctr;
                   1395:          includemsg = 1;
                   1396:       }
                   1397:       imgformname = opener.document.SCORE["mailicon"+usrctr];
                   1398:       imgformname.src = "$iconpath/"+((includemsg) ? "mailto.gif" : "mailbkgrd.gif");
                   1399:       var includemsg = opener.document.SCORE["includemsg"+usrctr];
                   1400:       includemsg.value = msgchk;
                   1401: 
                   1402:       self.close()
                   1403: 
                   1404:     }
                   1405: INNERJS
                   1406: 
1.597     wenzelju 1407:     my $inner_js_highlight_central= &Apache::lonhtmlcommon::scripttag(<<INNERJS);
1.351     albertel 1408:     function updateChoice(flag) {
                   1409:       opener.document.SCORE.kwclr.value = opener.radioSelection(document.hlCenter.kwdclr);
                   1410:       opener.document.SCORE.kwsize.value = opener.radioSelection(document.hlCenter.kwdsize);
                   1411:       opener.document.SCORE.kwstyle.value = opener.radioSelection(document.hlCenter.kwdstyle);
                   1412:       opener.document.SCORE.refresh.value = "on";
                   1413:       if (opener.document.SCORE.keywords.value!=""){
                   1414:          opener.document.SCORE.submit();
                   1415:       }
                   1416:       self.close()
                   1417:     }
                   1418: INNERJS
                   1419: 
                   1420:     my $start_page_msg_central = 
                   1421:         &Apache::loncommon::start_page('Message Central',$inner_js_msg_central,
                   1422: 				       {'js_ready'  => 1,
                   1423: 					'only_body' => 1,
                   1424: 					'bgcolor'   =>'#FFFFFF',});
                   1425:     my $end_page_msg_central = 
                   1426: 	&Apache::loncommon::end_page({'js_ready' => 1});
                   1427: 
                   1428: 
                   1429:     my $start_page_highlight_central = 
                   1430:         &Apache::loncommon::start_page('Highlight Central',
                   1431: 				       $inner_js_highlight_central,
1.350     albertel 1432: 				       {'js_ready'  => 1,
                   1433: 					'only_body' => 1,
                   1434: 					'bgcolor'   =>'#FFFFFF',});
1.351     albertel 1435:     my $end_page_highlight_central = 
1.350     albertel 1436: 	&Apache::loncommon::end_page({'js_ready' => 1});
                   1437: 
1.219     www      1438:     my $docopen=&Apache::lonhtmlcommon::javascript_docopen();
1.236     albertel 1439:     $docopen=~s/^document\.//;
1.539     riegler  1440:     my $alertmsg = &mt('Please select a word or group of words from document and then click this link.');
1.597     wenzelju 1441:     $request->print(&Apache::lonhtmlcommon::scripttag(<<SUBJAVASCRIPT));
1.45      ng       1442: 
1.44      ng       1443: //===================== Show list of keywords ====================
1.122     ng       1444:   function keywords(formname) {
                   1445:     var nret = prompt("Keywords list, separated by a space. Add/delete to list if desired.",formname.keywords.value);
1.44      ng       1446:     if (nret==null) return;
1.122     ng       1447:     formname.keywords.value = nret;
1.44      ng       1448: 
1.122     ng       1449:     if (formname.keywords.value != "") {
1.128     ng       1450: 	formname.refresh.value = "on";
1.122     ng       1451: 	formname.submit();
1.44      ng       1452:     }
                   1453:     return;
                   1454:   }
                   1455: 
                   1456: //===================== Script to view submitted by ==================
                   1457:   function viewSubmitter(submitter) {
                   1458:     document.SCORE.refresh.value = "on";
                   1459:     document.SCORE.NCT.value = "1";
                   1460:     document.SCORE.unamedom0.value = submitter;
                   1461:     document.SCORE.submit();
                   1462:     return;
                   1463:   }
                   1464: 
                   1465: //===================== Script to add keyword(s) ==================
                   1466:   function getSel() {
                   1467:     if (document.getSelection) txt = document.getSelection();
                   1468:     else if (document.selection) txt = document.selection.createRange().text;
                   1469:     else return;
                   1470:     var cleantxt = txt.replace(new RegExp('([\\f\\n\\r\\t\\v ])+', 'g')," ");
                   1471:     if (cleantxt=="") {
1.539     riegler  1472: 	alert("$alertmsg");
1.44      ng       1473: 	return;
                   1474:     }
                   1475:     var nret = prompt("Add selection to keyword list? Edit if desired.",cleantxt);
                   1476:     if (nret==null) return;
1.127     ng       1477:     document.SCORE.keywords.value = document.SCORE.keywords.value+" "+nret;
1.44      ng       1478:     if (document.SCORE.keywords.value != "") {
1.127     ng       1479: 	document.SCORE.refresh.value = "on";
1.44      ng       1480: 	document.SCORE.submit();
                   1481:     }
                   1482:     return;
                   1483:   }
                   1484: 
                   1485: //====================== Script for composing message ==============
1.80      ng       1486:    // preload images
                   1487:    img1 = new Image();
                   1488:    img1.src = "$iconpath/mailbkgrd.gif";
                   1489:    img2 = new Image();
                   1490:    img2.src = "$iconpath/mailto.gif";
                   1491: 
1.44      ng       1492:   function msgCenter(msgform,usrctr,fullname) {
                   1493:     var Nmsg  = msgform.savemsgN.value;
                   1494:     savedMsgHeader(Nmsg,usrctr,fullname);
                   1495:     var subject = msgform.msgsub.value;
1.127     ng       1496:     var msgchk = document.SCORE["includemsg"+usrctr].value;
1.44      ng       1497:     re = /msgsub/;
                   1498:     var shwsel = "";
                   1499:     if (re.test(msgchk)) { shwsel = "checked" }
1.123     ng       1500:     subject = (document.SCORE.shownSub.value == 0 ? checkEntities(subject) : subject);
                   1501:     displaySubject(checkEntities(subject),shwsel);
1.44      ng       1502:     for (var i=1; i<=Nmsg; i++) {
1.123     ng       1503: 	var testmsg = "savemsg"+i+",";
                   1504: 	re = new RegExp(testmsg,"g");
1.44      ng       1505: 	shwsel = "";
                   1506: 	if (re.test(msgchk)) { shwsel = "checked" }
1.125     ng       1507: 	var message = document.SCORE["savemsg"+i].value;
1.126     ng       1508: 	message = (document.SCORE["shownOnce"+i].value == 0 ? checkEntities(message) : message);
1.123     ng       1509: 	displaySavedMsg(i,message,shwsel); //I do not get it. w/o checkEntities on saved messages,
                   1510: 	                                   //any &lt; is already converted to <, etc. However, only once!!
1.44      ng       1511:     }
1.125     ng       1512:     newmsg = document.SCORE["newmsg"+usrctr].value;
1.44      ng       1513:     shwsel = "";
                   1514:     re = /newmsg/;
                   1515:     if (re.test(msgchk)) { shwsel = "checked" }
                   1516:     newMsg(newmsg,shwsel);
                   1517:     msgTail(); 
                   1518:     return;
                   1519:   }
                   1520: 
1.123     ng       1521:   function checkEntities(strx) {
                   1522:     if (strx.length == 0) return strx;
                   1523:     var orgStr = ["&", "<", ">", '"']; 
                   1524:     var newStr = ["&amp;", "&lt;", "&gt;", "&quot;"];
                   1525:     var counter = 0;
                   1526:     while (counter < 4) {
                   1527: 	strx = strReplace(strx,orgStr[counter],newStr[counter]);
                   1528: 	counter++;
                   1529:     }
                   1530:     return strx;
                   1531:   }
                   1532: 
                   1533:   function strReplace(strx, orgStr, newStr) {
                   1534:     return strx.split(orgStr).join(newStr);
                   1535:   }
                   1536: 
1.44      ng       1537:   function savedMsgHeader(Nmsg,usrctr,fullname) {
1.76      ng       1538:     var height = 70*Nmsg+250;
1.44      ng       1539:     var scrollbar = "no";
                   1540:     if (height > 600) {
                   1541: 	height = 600;
                   1542: 	scrollbar = "yes";
                   1543:     }
1.118     ng       1544:     var xpos = (screen.width-600)/2;
                   1545:     xpos = (xpos < 0) ? '0' : xpos;
                   1546:     var ypos = (screen.height-height)/2-30;
                   1547:     ypos = (ypos < 0) ? '0' : ypos;
                   1548: 
1.206     albertel 1549:     pWin = window.open('', 'MessageCenter', 'resizable=yes,toolbar=no,location=no,scrollbars='+scrollbar+',screenx='+xpos+',screeny='+ypos+',width=600,height='+height);
1.76      ng       1550:     pWin.focus();
                   1551:     pDoc = pWin.document;
1.219     www      1552:     pDoc.$docopen;
1.351     albertel 1553:     pDoc.write('$start_page_msg_central');
1.76      ng       1554: 
                   1555:     pDoc.write("<form action=\\"inactive\\" name=\\"msgcenter\\">");
                   1556:     pDoc.write("<input value=\\""+usrctr+"\\" name=\\"usrctr\\" type=\\"hidden\\">");
1.465     albertel 1557:     pDoc.write("<h3><span class=\\"LC_info\\">&nbsp;Compose Message for \"+fullname+\"<\\/span><\\/h3><br /><br />");
1.76      ng       1558: 
1.564     bisitz   1559:     pDoc.write('<table border="0" width="100%"><tr><td bgcolor="#777777">');
                   1560:     pDoc.write('<table border="0" width="100%"><tr bgcolor="#DDFFFF">');
1.465     albertel 1561:     pDoc.write("<td><b>Type<\\/b><\\/td><td><b>Include<\\/b><\\/td><td><b>Message<\\/td><\\/tr>");
1.44      ng       1562: }
                   1563:     function displaySubject(msg,shwsel) {
1.76      ng       1564:     pDoc = pWin.document;
                   1565:     pDoc.write("<tr bgcolor=\\"#ffffdd\\">");
1.465     albertel 1566:     pDoc.write("<td>Subject<\\/td>");
                   1567:     pDoc.write("<td align=\\"center\\"><input name=\\"subchk\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
                   1568:     pDoc.write("<td><input name=\\"msgsub\\" type=\\"text\\" value=\\""+msg+"\\"size=\\"60\\" maxlength=\\"80\\"><\\/td><\\/tr>");
1.44      ng       1569: }
                   1570: 
1.72      ng       1571:   function displaySavedMsg(ctr,msg,shwsel) {
1.76      ng       1572:     pDoc = pWin.document;
                   1573:     pDoc.write("<tr bgcolor=\\"#ffffdd\\">");
1.465     albertel 1574:     pDoc.write("<td align=\\"center\\">"+ctr+"<\\/td>");
                   1575:     pDoc.write("<td align=\\"center\\"><input name=\\"msgn"+ctr+"\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
                   1576:     pDoc.write("<td><textarea name=\\"msg"+ctr+"\\" cols=\\"60\\" rows=\\"3\\">"+msg+"<\\/textarea><\\/td><\\/tr>");
1.44      ng       1577: }
                   1578: 
                   1579:   function newMsg(newmsg,shwsel) {
1.76      ng       1580:     pDoc = pWin.document;
                   1581:     pDoc.write("<tr bgcolor=\\"#ffffdd\\">");
1.465     albertel 1582:     pDoc.write("<td align=\\"center\\">New<\\/td>");
                   1583:     pDoc.write("<td align=\\"center\\"><input name=\\"newmsgchk\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
                   1584:     pDoc.write("<td><textarea name=\\"newmsg\\" cols=\\"60\\" rows=\\"3\\" onchange=\\"javascript:this.form.newmsgchk.checked=true\\" >"+newmsg+"<\\/textarea><\\/td><\\/tr>");
1.44      ng       1585: }
                   1586: 
                   1587:   function msgTail() {
1.76      ng       1588:     pDoc = pWin.document;
1.465     albertel 1589:     pDoc.write("<\\/table>");
                   1590:     pDoc.write("<\\/td><\\/tr><\\/table>&nbsp;");
1.589     bisitz   1591:     pDoc.write("<input type=\\"button\\" value=\\"Save\\" onclick=\\"javascript:checkInput()\\">&nbsp;&nbsp;");
                   1592:     pDoc.write("<input type=\\"button\\" value=\\"Cancel\\" onclick=\\"self.close()\\"><br /><br />");
1.465     albertel 1593:     pDoc.write("<\\/form>");
1.351     albertel 1594:     pDoc.write('$end_page_msg_central');
1.128     ng       1595:     pDoc.close();
1.44      ng       1596: }
                   1597: 
                   1598: //====================== Script for keyword highlight options ==============
                   1599:   function kwhighlight() {
                   1600:     var kwclr    = document.SCORE.kwclr.value;
                   1601:     var kwsize   = document.SCORE.kwsize.value;
                   1602:     var kwstyle  = document.SCORE.kwstyle.value;
                   1603:     var redsel = "";
                   1604:     var grnsel = "";
                   1605:     var blusel = "";
                   1606:     if (kwclr=="red")   {var redsel="checked"};
                   1607:     if (kwclr=="green") {var grnsel="checked"};
                   1608:     if (kwclr=="blue")  {var blusel="checked"};
                   1609:     var sznsel = "";
                   1610:     var sz1sel = "";
                   1611:     var sz2sel = "";
                   1612:     if (kwsize=="0")  {var sznsel="checked"};
                   1613:     if (kwsize=="+1") {var sz1sel="checked"};
                   1614:     if (kwsize=="+2") {var sz2sel="checked"};
                   1615:     var synsel = "";
                   1616:     var syisel = "";
                   1617:     var sybsel = "";
                   1618:     if (kwstyle=="")    {var synsel="checked"};
                   1619:     if (kwstyle=="<i>") {var syisel="checked"};
                   1620:     if (kwstyle=="<b>") {var sybsel="checked"};
                   1621:     highlightCentral();
                   1622:     highlightbody('red','red',redsel,'0','normal',sznsel,'','normal',synsel);
                   1623:     highlightbody('green','green',grnsel,'+1','+1',sz1sel,'<i>','italic',syisel);
                   1624:     highlightbody('blue','blue',blusel,'+2','+2',sz2sel,'<b>','bold',sybsel);
                   1625:     highlightend();
                   1626:     return;
                   1627:   }
                   1628: 
                   1629:   function highlightCentral() {
1.76      ng       1630: //    if (window.hwdWin) window.hwdWin.close();
1.118     ng       1631:     var xpos = (screen.width-400)/2;
                   1632:     xpos = (xpos < 0) ? '0' : xpos;
                   1633:     var ypos = (screen.height-330)/2-30;
                   1634:     ypos = (ypos < 0) ? '0' : ypos;
                   1635: 
1.206     albertel 1636:     hwdWin = window.open('', 'KeywordHighlightCentral', 'resizeable=yes,toolbar=no,location=no,scrollbars=no,width=400,height=300,screenx='+xpos+',screeny='+ypos);
1.76      ng       1637:     hwdWin.focus();
                   1638:     var hDoc = hwdWin.document;
1.219     www      1639:     hDoc.$docopen;
1.351     albertel 1640:     hDoc.write('$start_page_highlight_central');
1.76      ng       1641:     hDoc.write("<form action=\\"inactive\\" name=\\"hlCenter\\">");
1.465     albertel 1642:     hDoc.write("<h3><span class=\\"LC_info\\">&nbsp;Keyword Highlight Options<\\/span><\\/h3><br /><br />");
1.76      ng       1643: 
1.564     bisitz   1644:     hDoc.write('<table border="0" width="100%"><tr><td bgcolor="#777777">');
                   1645:     hDoc.write('<table border="0" width="100%"><tr bgcolor="#DDFFFF">');
1.465     albertel 1646:     hDoc.write("<td><b>Text Color<\\/b><\\/td><td><b>Font Size<\\/b><\\/td><td><b>Font Style<\\/td><\\/tr>");
1.44      ng       1647:   }
                   1648: 
                   1649:   function highlightbody(clrval,clrtxt,clrsel,szval,sztxt,szsel,syval,sytxt,sysel) { 
1.76      ng       1650:     var hDoc = hwdWin.document;
                   1651:     hDoc.write("<tr bgcolor=\\"#ffffdd\\">");
                   1652:     hDoc.write("<td align=\\"left\\">");
1.465     albertel 1653:     hDoc.write("<input name=\\"kwdclr\\" type=\\"radio\\" value=\\""+clrval+"\\" "+clrsel+">&nbsp;"+clrtxt+"<\\/td>");
1.76      ng       1654:     hDoc.write("<td align=\\"left\\">");
1.465     albertel 1655:     hDoc.write("<input name=\\"kwdsize\\" type=\\"radio\\" value=\\""+szval+"\\" "+szsel+">&nbsp;"+sztxt+"<\\/td>");
1.76      ng       1656:     hDoc.write("<td align=\\"left\\">");
1.465     albertel 1657:     hDoc.write("<input name=\\"kwdstyle\\" type=\\"radio\\" value=\\""+syval+"\\" "+sysel+">&nbsp;"+sytxt+"<\\/td>");
                   1658:     hDoc.write("<\\/tr>");
1.44      ng       1659:   }
                   1660: 
                   1661:   function highlightend() { 
1.76      ng       1662:     var hDoc = hwdWin.document;
1.465     albertel 1663:     hDoc.write("<\\/table>");
                   1664:     hDoc.write("<\\/td><\\/tr><\\/table>&nbsp;");
1.589     bisitz   1665:     hDoc.write("<input type=\\"button\\" value=\\"Save\\" onclick=\\"javascript:updateChoice(1)\\">&nbsp;&nbsp;");
                   1666:     hDoc.write("<input type=\\"button\\" value=\\"Cancel\\" onclick=\\"self.close()\\"><br /><br />");
1.465     albertel 1667:     hDoc.write("<\\/form>");
1.351     albertel 1668:     hDoc.write('$end_page_highlight_central');
1.128     ng       1669:     hDoc.close();
1.44      ng       1670:   }
                   1671: 
                   1672: SUBJAVASCRIPT
                   1673: }
                   1674: 
1.349     albertel 1675: sub get_increment {
1.348     bowersj2 1676:     my $increment = $env{'form.increment'};
                   1677:     if ($increment != 1 && $increment != .5 && $increment != .25 &&
                   1678:         $increment != .1) {
                   1679:         $increment = 1;
                   1680:     }
                   1681:     return $increment;
                   1682: }
                   1683: 
1.585     bisitz   1684: sub gradeBox_start {
                   1685:     return (
                   1686:         &Apache::loncommon::start_data_table()
                   1687:        .&Apache::loncommon::start_data_table_header_row()
                   1688:        .'<th>'.&mt('Part').'</th>'
                   1689:        .'<th>'.&mt('Points').'</th>'
                   1690:        .'<th>&nbsp;</th>'
                   1691:        .'<th>'.&mt('Assign Grade').'</th>'
                   1692:        .'<th>'.&mt('Weight').'</th>'
                   1693:        .'<th>'.&mt('Grade Status').'</th>'
                   1694:        .&Apache::loncommon::end_data_table_header_row()
                   1695:     );
                   1696: }
                   1697: 
                   1698: sub gradeBox_end {
                   1699:     return (
                   1700:         &Apache::loncommon::end_data_table()
                   1701:     );
                   1702: }
1.71      ng       1703: #--- displays the grading box, used in essay type problem and grading by page/sequence
                   1704: sub gradeBox {
1.322     albertel 1705:     my ($request,$symb,$uname,$udom,$counter,$partid,$record) = @_;
1.381     albertel 1706:     my $checkIcon = '<img alt="'.&mt('Check Mark').
1.485     albertel 1707: 	'" src="'.&Apache::loncommon::lonhttpdurl($request->dir_config('lonIconsURL').'/check.gif').'" height="16" border="0" />';
1.71      ng       1708:     my $wgt    = &Apache::lonnet::EXT('resource.'.$partid.'.weight',$symb,$udom,$uname);
1.466     albertel 1709:     my $wgtmsg = ($wgt > 0) ? &mt('(problem weight)') 
                   1710:                            : '<span class="LC_info">'.&mt('problem weight assigned by computer').'</span>';
1.71      ng       1711:     $wgt       = ($wgt > 0 ? $wgt : '1');
                   1712:     my $score  = ($$record{'resource.'.$partid.'.awarded'} eq '' ?
1.320     albertel 1713: 		  '' : &compute_points($$record{'resource.'.$partid.'.awarded'},$wgt));
1.71      ng       1714:     my $result='<input type="hidden" name="WGT'.$counter.'_'.$partid.'" value="'.$wgt.'" />'."\n";
1.466     albertel 1715:     my $display_part= &get_display_part($partid,$symb);
1.270     albertel 1716:     my %last_resets = &get_last_resets($symb,$env{'request.course.id'},
                   1717: 				       [$partid]);
                   1718:     my $aggtries = $$record{'resource.'.$partid.'.tries'};
1.269     raeburn  1719:     if ($last_resets{$partid}) {
                   1720:         $aggtries = &get_num_tries($record,$last_resets{$partid},$partid);
                   1721:     }
1.585     bisitz   1722:     $result.=&Apache::loncommon::start_data_table_row();
1.71      ng       1723:     my $ctr = 0;
1.348     bowersj2 1724:     my $thisweight = 0;
1.349     albertel 1725:     my $increment = &get_increment();
1.485     albertel 1726: 
                   1727:     my $radio.='<table border="0"><tr>'."\n";  # display radio buttons in a nice table 10 across
1.348     bowersj2 1728:     while ($thisweight<=$wgt) {
1.532     bisitz   1729: 	$radio.= '<td><span class="LC_nobreak"><label><input type="radio" name="RADVAL'.$counter.'_'.$partid.'" '.
1.589     bisitz   1730:         'onclick="javascript:writeBox(this.form,\''.$counter.'_'.$partid.'\','.
1.348     bowersj2 1731: 	    $thisweight.')" value="'.$thisweight.'" '.
1.401     albertel 1732: 	    ($score eq $thisweight ? 'checked="checked"':'').' /> '.$thisweight."</label></span></td>\n";
1.485     albertel 1733: 	$radio.=(($ctr+1)%10 == 0 ? '</tr><tr>' : '');
1.348     bowersj2 1734:         $thisweight += $increment;
1.71      ng       1735: 	$ctr++;
                   1736:     }
1.485     albertel 1737:     $radio.='</tr></table>';
                   1738: 
                   1739:     my $line.='<input type="text" name="GD_BOX'.$counter.'_'.$partid.'"'.
1.71      ng       1740: 	($score ne ''? ' value = "'.$score.'"':'').' size="4" '.
1.589     bisitz   1741: 	'onchange="javascript:updateRadio(this.form,\''.$counter.'_'.$partid.'\','.
1.71      ng       1742: 	$wgt.')" /></td>'."\n";
1.485     albertel 1743:     $line.='<td>/'.$wgt.' '.$wgtmsg.
1.71      ng       1744: 	($$record{'resource.'.$partid.'.solved'} eq 'correct_by_student' ? '&nbsp;'.$checkIcon : '').
1.585     bisitz   1745: 	' </td>'."\n";
                   1746:     $line.='<td><select name="GD_SEL'.$counter.'_'.$partid.'" '.
1.589     bisitz   1747: 	'onchange="javascript:clearRadBox(this.form,\''.$counter.'_'.$partid.'\')" >'."\n";
1.71      ng       1748:     if ($$record{'resource.'.$partid.'.solved'} eq 'excused') {
1.485     albertel 1749: 	$line.='<option></option>'.
                   1750: 	    '<option value="excused" selected="selected">'.&mt('excused').'</option>';
1.71      ng       1751:     } else {
1.485     albertel 1752: 	$line.='<option selected="selected"></option>'.
                   1753: 	    '<option value="excused" >'.&mt('excused').'</option>';
1.71      ng       1754:     }
1.485     albertel 1755:     $line.='<option value="reset status">'.&mt('reset status').'</option></select>'."\n";
                   1756: 
                   1757: 
1.540     riegler  1758: 	#&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 1759:     $result .= 
1.585     bisitz   1760: 	    '<td>'.$display_part.'</td><td>'.$radio.'</td><td>'.&mt('or').'</td><td>'.$line.'</td>';
                   1761:     $result.=&Apache::loncommon::end_data_table_row();
1.71      ng       1762:     $result.='<input type="hidden" name="stores'.$counter.'_'.$partid.'" value="" />'."\n".
                   1763: 	'<input type="hidden" name="oldpts'.$counter.'_'.$partid.'" value="'.$score.'" />'."\n".
                   1764: 	'<input type="hidden" name="solved'.$counter.'_'.$partid.'" value="'.
1.269     raeburn  1765: 	$$record{'resource.'.$partid.'.solved'}.'" />'."\n".
                   1766:         '<input type="hidden" name="totaltries'.$counter.'_'.$partid.'" value="'.
                   1767:         $$record{'resource.'.$partid.'.tries'}.'" />'."\n".
                   1768:         '<input type="hidden" name="aggtries'.$counter.'_'.$partid.'" value="'.
                   1769:         $aggtries.'" />'."\n";
1.582     raeburn  1770:     my $res_error;
                   1771:     $result.=&handback_box($symb,$uname,$udom,$counter,$partid,$record,\$res_error);
                   1772:     if ($res_error) {
                   1773:         return &navmap_errormsg();
                   1774:     }
1.318     banghart 1775:     return $result;
                   1776: }
1.322     albertel 1777: 
                   1778: sub handback_box {
1.582     raeburn  1779:     my ($symb,$uname,$udom,$counter,$partid,$record,$res_error) = @_;
                   1780:     my ($partlist,$handgrade,$responseType) = &response_type($symb,$res_error);
1.323     banghart 1781:     my (@respids);
1.375     albertel 1782:      my @part_response_id = &flatten_responseType($responseType);
                   1783:     foreach my $part_response_id (@part_response_id) {
                   1784:     	my ($part,$resp) = @{ $part_response_id };
1.323     banghart 1785:         if ($part eq $partid) {
1.375     albertel 1786:             push(@respids,$resp);
1.323     banghart 1787:         }
                   1788:     }
1.318     banghart 1789:     my $result;
1.323     banghart 1790:     foreach my $respid (@respids) {
1.322     albertel 1791: 	my $prefix = $counter.'_'.$partid.'_'.$respid.'_';
                   1792: 	my $files=&get_submitted_files($udom,$uname,$partid,$respid,$record);
                   1793: 	next if (!@$files);
                   1794: 	my $file_counter = 1;
1.313     banghart 1795: 	foreach my $file (@$files) {
1.368     banghart 1796: 	    if ($file =~ /\/portfolio\//) {
                   1797:     	        my ($file_path, $file_disp) = ($file =~ m|(.+/)(.+)$|);
                   1798:     	        my ($name,$version,$ext) = &file_name_version_ext($file_disp);
                   1799:     	        $file_disp = "$name.$ext";
                   1800:     	        $file = $file_path.$file_disp;
                   1801:     	        $result.=&mt('Return commented version of [_1] to student.',
                   1802:     			 '<span class="LC_filename">'.$file_disp.'</span>');
                   1803:     	        $result.='<input type="file"   name="'.$prefix.'returndoc'.$file_counter.'" />'."\n";
                   1804:     	        $result.='<input type="hidden" name="'.$prefix.'origdoc'.$file_counter.'" value="'.$file.'" /><br />';
1.485     albertel 1805:     	        $result.='('.&mt('File will be uploaded when you click on Save &amp; Next below.').')<br />';
1.368     banghart 1806:     	        $file_counter++;
                   1807: 	    }
1.322     albertel 1808: 	}
1.313     banghart 1809:     }
1.318     banghart 1810:     return $result;    
1.71      ng       1811: }
1.44      ng       1812: 
1.58      albertel 1813: sub show_problem {
1.382     albertel 1814:     my ($request,$symb,$uname,$udom,$removeform,$viewon,$mode,$form) = @_;
1.144     albertel 1815:     my $rendered;
1.382     albertel 1816:     my %form = ((ref($form) eq 'HASH')? %{$form} : ());
1.329     albertel 1817:     &Apache::lonxml::remember_problem_counter();
1.144     albertel 1818:     if ($mode eq 'both' or $mode eq 'text') {
                   1819: 	$rendered=&Apache::loncommon::get_student_view($symb,$uname,$udom,
1.382     albertel 1820: 						       $env{'request.course.id'},
                   1821: 						       undef,\%form);
1.144     albertel 1822:     }
1.58      albertel 1823:     if ($removeform) {
                   1824: 	$rendered=~s|<form(.*?)>||g;
                   1825: 	$rendered=~s|</form>||g;
1.374     albertel 1826: 	$rendered=~s|(<input[^>]*name\s*=\s*"?)(\w+)("?)|$1would_have_been_$2$3|g;
1.58      albertel 1827:     }
1.144     albertel 1828:     my $companswer;
                   1829:     if ($mode eq 'both' or $mode eq 'answer') {
1.329     albertel 1830: 	&Apache::lonxml::restore_problem_counter();
1.382     albertel 1831: 	$companswer=
                   1832: 	    &Apache::loncommon::get_student_answers($symb,$uname,$udom,
                   1833: 						    $env{'request.course.id'},
                   1834: 						    %form);
1.144     albertel 1835:     }
1.58      albertel 1836:     if ($removeform) {
                   1837: 	$companswer=~s|<form(.*?)>||g;
                   1838: 	$companswer=~s|</form>||g;
1.144     albertel 1839: 	$companswer=~s|name="submit"|name="would_have_been_submit"|g;
1.58      albertel 1840:     }
1.468     albertel 1841:     $rendered=
1.588     bisitz   1842:         '<div class="LC_Box">'
                   1843:        .'<h3 class="LC_hcell">'.&mt('View of the problem').'</h3>'
                   1844:        .$rendered
                   1845:        .'</div>';
1.468     albertel 1846:     $companswer=
1.588     bisitz   1847:         '<div class="LC_Box">'
                   1848:        .'<h3 class="LC_hcell">'.&mt('Correct answer').'</h3>'
                   1849:        .$companswer
                   1850:        .'</div>';
1.468     albertel 1851:     my $result;
1.144     albertel 1852:     if ($mode eq 'both') {
1.588     bisitz   1853:         $result=$rendered.$companswer;
1.144     albertel 1854:     } elsif ($mode eq 'text') {
1.588     bisitz   1855:         $result=$rendered;
1.144     albertel 1856:     } elsif ($mode eq 'answer') {
1.588     bisitz   1857:         $result=$companswer;
1.144     albertel 1858:     }
1.71      ng       1859:     return $result;
1.58      albertel 1860: }
1.397     albertel 1861: 
1.396     banghart 1862: sub files_exist {
                   1863:     my ($r, $symb) = @_;
                   1864:     my @students = &Apache::loncommon::get_env_multiple('form.stuinfo');
1.397     albertel 1865: 
1.396     banghart 1866:     foreach my $student (@students) {
                   1867:         my ($uname,$udom,$fullname) = split(/:/,$student);
1.397     albertel 1868:         my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},
                   1869: 					      $udom,$uname);
1.396     banghart 1870:         my ($string,$timestamp)= &get_last_submission(\%record);
1.397     albertel 1871:         foreach my $submission (@$string) {
                   1872:             my ($partid,$respid) =
                   1873: 		($submission =~ /^resource\.([^\.]*)\.([^\.]*)\.submission/);
                   1874:             my $files=&get_submitted_files($udom,$uname,$partid,$respid,
                   1875: 					   \%record);
                   1876:             return 1 if (@$files);
1.396     banghart 1877:         }
                   1878:     }
1.397     albertel 1879:     return 0;
1.396     banghart 1880: }
1.397     albertel 1881: 
1.394     banghart 1882: sub download_all_link {
                   1883:     my ($r,$symb) = @_;
1.395     albertel 1884:     my $all_students = 
                   1885: 	join("\n", &Apache::loncommon::get_env_multiple('form.stuinfo'));
                   1886: 
                   1887:     my $parts =
                   1888: 	join("\n",&Apache::loncommon::get_env_multiple('form.vPart'));
                   1889: 
1.394     banghart 1890:     my $identifier = &Apache::loncommon::get_cgi_id();
1.514     raeburn  1891:     &Apache::lonnet::appenv({'cgi.'.$identifier.'.students' => $all_students,
                   1892:                              'cgi.'.$identifier.'.symb' => $symb,
                   1893:                              'cgi.'.$identifier.'.parts' => $parts,});
1.395     albertel 1894:     $r->print('<a href="/cgi-bin/multidownload.pl?'.$identifier.'">'.
                   1895: 	      &mt('Download All Submitted Documents').'</a>');
1.394     banghart 1896:     return
                   1897: }
1.395     albertel 1898: 
1.432     banghart 1899: sub build_section_inputs {
                   1900:     my $section_inputs;
                   1901:     if ($env{'form.section'} eq '') {
                   1902:         $section_inputs .= '<input type="hidden" name="section" value="all" />'."\n";
                   1903:     } else {
                   1904:         my @sections = &Apache::loncommon::get_env_multiple('form.section');
1.434     albertel 1905:         foreach my $section (@sections) {
1.432     banghart 1906:             $section_inputs .= '<input type="hidden" name="section" value="'.$section.'" />'."\n";
                   1907:         }
                   1908:     }
                   1909:     return $section_inputs;
                   1910: }
                   1911: 
1.44      ng       1912: # --------------------------- show submissions of a student, option to grade 
                   1913: sub submission {
                   1914:     my ($request,$counter,$total) = @_;
1.257     albertel 1915:     my ($uname,$udom)     = ($env{'form.student'},$env{'form.userdom'});
                   1916:     $udom = ($udom eq '' ? $env{'user.domain'} : $udom); #has form.userdom changed for a student?
                   1917:     my $usec = &Apache::lonnet::getsection($udom,$uname,$env{'request.course.id'});
                   1918:     $env{'form.fullname'} = &Apache::loncommon::plainname($uname,$udom,'lastname') if $env{'form.fullname'} eq '';
1.324     albertel 1919:     my $symb = &get_symb($request); 
                   1920:     if ($symb eq '') { $request->print("Unable to handle ambiguous references:."); return ''; }
1.104     albertel 1921: 
                   1922:     if (!&canview($usec)) {
1.398     albertel 1923: 	$request->print('<span class="LC_warning">Unable to view requested student.('.
                   1924: 			$uname.':'.$udom.' in section '.$usec.' in course id '.
                   1925: 			$env{'request.course.id'}.')</span>');
1.324     albertel 1926: 	$request->print(&show_grading_menu_form($symb));
1.104     albertel 1927: 	return;
                   1928:     }
                   1929: 
1.257     albertel 1930:     if (!$env{'form.lastSub'}) { $env{'form.lastSub'} = 'datesub'; }
                   1931:     if (!$env{'form.vProb'}) { $env{'form.vProb'} = 'yes'; }
                   1932:     if (!$env{'form.vAns'}) { $env{'form.vAns'} = 'yes'; }
                   1933:     my $last = ($env{'form.lastSub'} eq 'last' ? 'last' : '');
1.381     albertel 1934:     my $checkIcon = '<img alt="'.&mt('Check Mark').
                   1935: 	'" src="'.$request->dir_config('lonIconsURL').
1.122     ng       1936: 	'/check.gif" height="16" border="0" />';
1.41      ng       1937: 
1.426     albertel 1938:     my %old_essays;
1.41      ng       1939:     # header info
                   1940:     if ($counter == 0) {
                   1941: 	&sub_page_js($request);
1.257     albertel 1942: 	&sub_page_kw_js($request) if ($env{'form.handgrade'} eq 'yes');
                   1943: 	$env{'form.probTitle'} = $env{'form.probTitle'} eq '' ? 
                   1944: 	    &Apache::lonnet::gettitle($symb) : $env{'form.probTitle'};
1.397     albertel 1945: 	if ($env{'form.handgrade'} eq 'yes' && &files_exist($request, $symb)) {
1.396     banghart 1946: 	    &download_all_link($request, $symb);
                   1947: 	}
1.485     albertel 1948: 	$request->print('<h3>&nbsp;<span class="LC_info">'.&mt('Submission Record').'</span></h3>'."\n".
                   1949: 			'<h4>&nbsp;'.&mt('<b>Resource: </b> [_1]',$env{'form.probTitle'}).'</h4>'."\n");
1.118     ng       1950: 
1.44      ng       1951: 	# option to display problem, only once else it cause problems 
                   1952:         # with the form later since the problem has a form.
1.257     albertel 1953: 	if ($env{'form.vProb'} eq 'yes' or $env{'form.vAns'} eq 'yes') {
1.144     albertel 1954: 	    my $mode;
1.257     albertel 1955: 	    if ($env{'form.vProb'} eq 'yes' && $env{'form.vAns'} eq 'yes') {
1.144     albertel 1956: 		$mode='both';
1.257     albertel 1957: 	    } elsif ($env{'form.vProb'} eq 'yes') {
1.144     albertel 1958: 		$mode='text';
1.257     albertel 1959: 	    } elsif ($env{'form.vAns'} eq 'yes') {
1.144     albertel 1960: 		$mode='answer';
                   1961: 	    }
1.329     albertel 1962: 	    &Apache::lonxml::clear_problem_counter();
1.144     albertel 1963: 	    $request->print(&show_problem($request,$symb,$uname,$udom,0,1,$mode));
1.41      ng       1964: 	}
1.441     www      1965: 
1.44      ng       1966: 	# kwclr is the only variable that is guaranteed to be non blank 
                   1967:         # if this subroutine has been called once.
1.41      ng       1968: 	my %keyhash = ();
1.257     albertel 1969: 	if ($env{'form.kwclr'} eq '' && $env{'form.handgrade'} eq 'yes') {
1.41      ng       1970: 	    %keyhash = &Apache::lonnet::dump('nohist_handgrade',
1.257     albertel 1971: 					     $env{'course.'.$env{'request.course.id'}.'.domain'},
                   1972: 					     $env{'course.'.$env{'request.course.id'}.'.num'});
1.41      ng       1973: 
1.257     albertel 1974: 	    my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
                   1975: 	    $env{'form.keywords'} = $keyhash{$symb.'_keywords'} ne '' ? $keyhash{$symb.'_keywords'} : '';
                   1976: 	    $env{'form.kwclr'}    = $keyhash{$loginuser.'_kwclr'} ne '' ? $keyhash{$loginuser.'_kwclr'} : 'red';
                   1977: 	    $env{'form.kwsize'}   = $keyhash{$loginuser.'_kwsize'} ne '' ? $keyhash{$loginuser.'_kwsize'} : '0';
                   1978: 	    $env{'form.kwstyle'}  = $keyhash{$loginuser.'_kwstyle'} ne '' ? $keyhash{$loginuser.'_kwstyle'} : '';
                   1979: 	    $env{'form.msgsub'}   = $keyhash{$symb.'_subject'} ne '' ? 
                   1980: 		$keyhash{$symb.'_subject'} : $env{'form.probTitle'};
                   1981: 	    $env{'form.savemsgN'} = $keyhash{$symb.'_savemsgN'} ne '' ? $keyhash{$symb.'_savemsgN'} : '0';
1.41      ng       1982: 	}
1.257     albertel 1983: 	my $overRideScore = $env{'form.overRideScore'} eq '' ? 'no' : $env{'form.overRideScore'};
1.442     banghart 1984: 	my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
1.303     banghart 1985: 	$request->print('<form action="/adm/grades" method="post" name="SCORE" enctype="multipart/form-data">'."\n".
1.41      ng       1986: 			'<input type="hidden" name="command"    value="handgrade" />'."\n".
1.257     albertel 1987: 			'<input type="hidden" name="saveState"  value="'.$env{'form.saveState'}.'" />'."\n".
1.442     banghart 1988: 			'<input type="hidden" name="Status"     value="'.$stu_status.'" />'."\n".
1.120     ng       1989: 			'<input type="hidden" name="overRideScore" value="'.$overRideScore.'" />'."\n".
1.257     albertel 1990: 			'<input type="hidden" name="probTitle"  value="'.$env{'form.probTitle'}.'" />'."\n".
1.41      ng       1991: 			'<input type="hidden" name="refresh"    value="off" />'."\n".
1.120     ng       1992: 			'<input type="hidden" name="studentNo"  value="" />'."\n".
                   1993: 			'<input type="hidden" name="gradeOpt"   value="" />'."\n".
1.418     albertel 1994: 			'<input type="hidden" name="symb"       value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.257     albertel 1995: 			'<input type="hidden" name="showgrading" value="'.$env{'form.showgrading'}.'" />'."\n".
                   1996: 			'<input type="hidden" name="vProb"      value="'.$env{'form.vProb'}.'" />'."\n".
                   1997: 			'<input type="hidden" name="vAns"       value="'.$env{'form.vAns'}.'" />'."\n".
                   1998: 			'<input type="hidden" name="lastSub"    value="'.$env{'form.lastSub'}.'" />'."\n".
1.432     banghart 1999: 			&build_section_inputs().
1.326     albertel 2000: 			'<input type="hidden" name="submitonly" value="'.$env{'form.submitonly'}.'" />'."\n".
                   2001: 			'<input type="hidden" name="handgrade"  value="'.$env{'form.handgrade'}.'" />'."\n".
1.41      ng       2002: 			'<input type="hidden" name="NCT"'.
1.257     albertel 2003: 			' value="'.($env{'form.NTSTU'} ne '' ? $env{'form.NTSTU'} : $total+1).'" />'."\n");
                   2004: 	if ($env{'form.handgrade'} eq 'yes') {
                   2005: 	    $request->print('<input type="hidden" name="keywords" value="'.$env{'form.keywords'}.'" />'."\n".
                   2006: 			    '<input type="hidden" name="kwclr"    value="'.$env{'form.kwclr'}.'" />'."\n".
                   2007: 			    '<input type="hidden" name="kwsize"   value="'.$env{'form.kwsize'}.'" />'."\n".
                   2008: 			    '<input type="hidden" name="kwstyle"  value="'.$env{'form.kwstyle'}.'" />'."\n".
                   2009: 			    '<input type="hidden" name="msgsub"   value="'.$env{'form.msgsub'}.'" />'."\n".
1.123     ng       2010: 			    '<input type="hidden" name="shownSub" value="0" />'."\n".
1.257     albertel 2011: 			    '<input type="hidden" name="savemsgN" value="'.$env{'form.savemsgN'}.'" />'."\n");
1.154     albertel 2012: 	    foreach my $partid (&Apache::loncommon::get_env_multiple('form.vPart')) {
                   2013: 		$request->print('<input type="hidden" name="vPart" value="'.$partid.'" />'."\n");
                   2014: 	    }
1.123     ng       2015: 	}
1.41      ng       2016: 	
                   2017: 	my ($cts,$prnmsg) = (1,'');
1.257     albertel 2018: 	while ($cts <= $env{'form.savemsgN'}) {
1.41      ng       2019: 	    $prnmsg.='<input type="hidden" name="savemsg'.$cts.'" value="'.
1.123     ng       2020: 		(!exists($keyhash{$symb.'_savemsg'.$cts}) ? 
1.257     albertel 2021: 		 &Apache::lonfeedback::clear_out_html($env{'form.savemsg'.$cts}) :
1.80      ng       2022: 		 &Apache::lonfeedback::clear_out_html($keyhash{$symb.'_savemsg'.$cts})).
1.123     ng       2023: 		'" />'."\n".
                   2024: 		'<input type="hidden" name="shownOnce'.$cts.'" value="0" />'."\n";
1.41      ng       2025: 	    $cts++;
                   2026: 	}
                   2027: 	$request->print($prnmsg);
1.32      ng       2028: 
1.257     albertel 2029: 	if ($env{'form.handgrade'} eq 'yes' && $env{'form.showgrading'} eq 'yes') {
1.88      www      2030: #
                   2031: # Print out the keyword options line
                   2032: #
1.41      ng       2033: 	    $request->print(<<KEYWORDS);
1.38      ng       2034: &nbsp;<b>Keyword Options:</b>&nbsp;
1.417     albertel 2035: <a href="javascript:keywords(document.SCORE);" target="_self">List</a>&nbsp; &nbsp;
1.589     bisitz   2036: <a href="#" onmousedown="javascript:getSel(); return false"
1.38      ng       2037:  CLASS="page">Paste Selection to List</a>&nbsp; &nbsp;
1.417     albertel 2038: <a href="javascript:kwhighlight();" target="_self">Highlight Attribute</a><br /><br />
1.38      ng       2039: KEYWORDS
1.88      www      2040: #
                   2041: # Load the other essays for similarity check
                   2042: #
1.324     albertel 2043:             my (undef,undef,$essayurl) = &Apache::lonnet::decode_symb($symb);
1.384     albertel 2044: 	    my ($adom,$aname,$apath)=($essayurl=~/^($LONCAPA::domain_re)\/($LONCAPA::username_re)\/(.*)$/);
1.359     www      2045: 	    $apath=&escape($apath);
1.88      www      2046: 	    $apath=~s/\W/\_/gs;
1.426     albertel 2047: 	    %old_essays=&Apache::lonnet::dump('nohist_essay_'.$apath,$adom,$aname);
1.41      ng       2048:         }
                   2049:     }
1.44      ng       2050: 
1.441     www      2051: # This is where output for one specific student would start
1.592     bisitz   2052:     my $add_class = ($counter%2) ? ' LC_grade_show_user_odd_row' : '';
                   2053:     $request->print(
                   2054:         "\n\n"
                   2055:        .'<div class="LC_grade_show_user'.$add_class.'">'
                   2056:        .'<h2>'.&nameUserString(undef,$env{'form.fullname'},$uname,$udom).'</h2>'
                   2057:        ."\n"
                   2058:     );
1.441     www      2059: 
1.592     bisitz   2060:     # Show additional functions if allowed
                   2061:     if ($perm{'vgr'}) {
                   2062:         $request->print(
                   2063:             &Apache::loncommon::track_student_link(
                   2064:                 &mt('View recent activity'),
                   2065:                 $uname,$udom,'check')
                   2066:            .' '
                   2067:         );
                   2068:     }
                   2069:     if ($perm{'opa'}) {
                   2070:         $request->print(
                   2071:             &Apache::loncommon::pprmlink(
                   2072:                 &mt('Set/Change parameters'),
                   2073:                 $uname,$udom,$symb,'check'));
                   2074:     }
                   2075: 
                   2076:     # Show Problem
1.257     albertel 2077:     if ($env{'form.vProb'} eq 'all' or $env{'form.vAns'} eq 'all') {
1.144     albertel 2078: 	my $mode;
1.257     albertel 2079: 	if ($env{'form.vProb'} eq 'all' && $env{'form.vAns'} eq 'all') {
1.144     albertel 2080: 	    $mode='both';
1.257     albertel 2081: 	} elsif ($env{'form.vProb'} eq 'all' ) {
1.144     albertel 2082: 	    $mode='text';
1.257     albertel 2083: 	} elsif ($env{'form.vAns'} eq 'all') {
1.144     albertel 2084: 	    $mode='answer';
                   2085: 	}
1.329     albertel 2086: 	&Apache::lonxml::clear_problem_counter();
1.475     albertel 2087: 	$request->print(&show_problem($request,$symb,$uname,$udom,1,1,$mode,{'request.prefix' => 'ctr'.$counter}));
1.58      albertel 2088:     }
1.144     albertel 2089: 
1.257     albertel 2090:     my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
1.582     raeburn  2091:     my $res_error;
                   2092:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
                   2093:     if ($res_error) {
                   2094:         $request->print(&navmap_errormsg());
                   2095:         return;
                   2096:     }
1.41      ng       2097: 
1.44      ng       2098:     # Display student info
1.41      ng       2099:     $request->print(($counter == 0 ? '' : '<br />'));
1.590     bisitz   2100: 
                   2101:     my $result='<div class="LC_Box">'
                   2102:               .'<h3 class="LC_hcell">'.&mt('Submissions').'</h3>';
1.45      ng       2103:     $result.='<input type="hidden" name="name'.$counter.
1.588     bisitz   2104:              '" value="'.$env{'form.fullname'}.'" />'."\n";
1.469     albertel 2105:     if ($env{'form.handgrade'} eq 'no') {
1.588     bisitz   2106:         $result.='<p class="LC_info">'
                   2107:                 .&mt('Part(s) graded correct by the computer is marked with a [_1] symbol.',$checkIcon)
                   2108:                 ."</p>\n";
1.469     albertel 2109:     }
                   2110: 
1.118     ng       2111:     # If any part of the problem is an essay-response (handgraded), then check for collaborators
1.464     albertel 2112:     my $fullname;
                   2113:     my $col_fullnames = [];
1.257     albertel 2114:     if ($env{'form.handgrade'} eq 'yes') {
1.464     albertel 2115: 	(my $sub_result,$fullname,$col_fullnames)=
                   2116: 	    &check_collaborators($symb,$uname,$udom,\%record,$handgrade,
                   2117: 				 $counter);
                   2118: 	$result.=$sub_result;
1.41      ng       2119:     }
1.44      ng       2120:     $request->print($result."\n");
1.588     bisitz   2121: 
1.44      ng       2122:     # print student answer/submission
1.588     bisitz   2123:     # Options are (1) Handgraded submission only
1.44      ng       2124:     #             (2) Last submission, includes submission that is not handgraded 
                   2125:     #                  (for multi-response type part)
                   2126:     #             (3) Last submission plus the parts info
                   2127:     #             (4) The whole record for this student
1.257     albertel 2128:     if ($env{'form.lastSub'} =~ /^(lastonly|hdgrade)$/) {
1.151     albertel 2129: 	my ($string,$timestamp)= &get_last_submission(\%record);
1.468     albertel 2130: 	
                   2131: 	my $lastsubonly;
                   2132: 
1.588     bisitz   2133:         if ($$timestamp eq '') {
                   2134:             $lastsubonly.='<div class="LC_grade_submissions_body">'.$$string[0].'</div>'; 
                   2135:         } else {
1.592     bisitz   2136:             $lastsubonly =
                   2137:                 '<div class="LC_grade_submissions_body">'
                   2138:                .'<b>'.&mt('Date Submitted:').'</b> '.$$timestamp."\n";
1.468     albertel 2139: 
1.151     albertel 2140: 	    my %seenparts;
1.375     albertel 2141: 	    my @part_response_id = &flatten_responseType($responseType);
                   2142: 	    foreach my $part (@part_response_id) {
1.393     albertel 2143: 		next if ($env{'form.lastSub'} eq 'hdgrade' 
                   2144: 			 && $$handgrade{$$part[0].'_'.$$part[1]} ne 'yes');
                   2145: 
1.375     albertel 2146: 		my ($partid,$respid) = @{ $part };
1.324     albertel 2147: 		my $display_part=&get_display_part($partid,$symb);
1.257     albertel 2148: 		if ($env{"form.$uname:$udom:$partid:submitted_by"}) {
1.151     albertel 2149: 		    if (exists($seenparts{$partid})) { next; }
                   2150: 		    $seenparts{$partid}=1;
1.207     albertel 2151: 		    my $submitby='<b>Part:</b> '.$display_part.
                   2152: 			' <b>Collaborative submission by:</b> '.
1.151     albertel 2153: 			'<a href="javascript:viewSubmitter(\''.
1.257     albertel 2154: 			$env{"form.$uname:$udom:$partid:submitted_by"}.
1.417     albertel 2155: 			'\');" target="_self">'.
1.257     albertel 2156: 			$$fullname{$env{"form.$uname:$udom:$partid:submitted_by"}}.'</a><br />';
1.151     albertel 2157: 		    $request->print($submitby);
                   2158: 		    next;
                   2159: 		}
                   2160: 		my $responsetype = $responseType->{$partid}->{$respid};
                   2161: 		if (!exists($record{"resource.$partid.$respid.submission"})) {
1.577     bisitz   2162:                     $lastsubonly.="\n".'<div class="LC_grade_submission_part">'.
                   2163:                         '<b>'.&mt('Part: [_1]',$display_part).'</b>'.
                   2164:                         ' <span class="LC_internal_info">'.
1.597     wenzelju 2165:                         '('.&mt('Part ID: [_1]',$respid).')'.
1.577     bisitz   2166:                         '</span>&nbsp; &nbsp;'.
1.539     riegler  2167: 			'<span class="LC_warning">'.&mt('Nothing submitted - no attempts.').'</span><br /><br /></div>';
1.151     albertel 2168: 		    next;
                   2169: 		}
1.468     albertel 2170: 		foreach my $submission (@$string) {
                   2171: 		    my ($partid,$respid) = ($submission =~ /^resource\.([^\.]*)\.([^\.]*)\.submission/);
1.375     albertel 2172: 		    if (join('_',@{$part}) ne ($partid.'_'.$respid)) { next; }
1.596     raeburn  2173: 		    my ($ressub,$hide,$subval) = split(/:/,$submission,3);
1.151     albertel 2174: 		    # Similarity check
                   2175: 		    my $similar='';
1.257     albertel 2176: 		    if($env{'form.checkPlag'}){
1.151     albertel 2177: 			my ($oname,$odom,$ocrsid,$oessay,$osim)=
1.426     albertel 2178: 			    &most_similar($uname,$udom,$subval,\%old_essays);
1.151     albertel 2179: 			if ($osim) {
                   2180: 			    $osim=int($osim*100.0);
1.426     albertel 2181: 			    my %old_course_desc = 
                   2182: 				&Apache::lonnet::coursedescription($ocrsid,
                   2183: 								   {'one_time' => 1});
                   2184: 
1.596     raeburn  2185:                             if ($hide) {
                   2186:                                 $similar='<hr /><span class="LC_warning">'.&mt("Essay was found to be similar to another essay submitted for this assignment.").'<br />'.
                   2187:                                          &mt('As the current submission is for an anonymous survey, no other details are available.').'</span><hr />';
                   2188:                             } else {
                   2189: 			        $similar="<hr /><h3><span class=\"LC_warning\">".
                   2190: 				    &mt('Essay is [_1]% similar to an essay by [_2] in course [_3] (course id [_4]:[_5])',
                   2191: 				        $osim,
                   2192: 				        &Apache::loncommon::plainname($oname,$odom).' ('.$oname.':'.$odom.')',
                   2193: 				        $old_course_desc{'description'},
                   2194: 				        $old_course_desc{'num'},
                   2195: 				        $old_course_desc{'domain'}).
                   2196: 				    '</span></h3><blockquote><i>'.
                   2197: 				    &keywords_highlight($oessay).
                   2198: 				    '</i></blockquote><hr />';
                   2199:                             }
1.151     albertel 2200: 			}
1.150     albertel 2201: 		    }
1.151     albertel 2202: 		    my $order=&get_order($partid,$respid,$symb,$uname,$udom);
1.257     albertel 2203: 		    if ($env{'form.lastSub'} eq 'lastonly' || 
                   2204: 			($env{'form.lastSub'} eq 'hdgrade' && 
1.377     albertel 2205: 			 $$handgrade{$$part[0].'_'.$$part[1]} eq 'yes')) {
1.324     albertel 2206: 			my $display_part=&get_display_part($partid,$symb);
1.577     bisitz   2207:                         $lastsubonly.='<div class="LC_grade_submission_part">'.
                   2208:                             '<b>'.&mt('Part: [_1]',$display_part).'</b>'.
                   2209:                             ' <span class="LC_internal_info">'.
                   2210:                             '('.&mt('Part ID: [_1]',$respid).')'.
1.597     wenzelju 2211:                             '</span>&nbsp; &nbsp;';
1.313     banghart 2212: 			my $files=&get_submitted_files($udom,$uname,$partid,$respid,\%record);
                   2213: 			if (@$files) {
1.596     raeburn  2214:                             if ($hide) {
                   2215:                                 $lastsubonly.='<br />'.&mt('[quant,_1,file] uploaded to this anonymous survey',scalar(@{$files}));
                   2216:                             } else {
                   2217:                                 $lastsubonly.='<br /><span class="LC_warning">'.&mt('Like all files provided by users, this file may contain viruses').'</span><br />';
                   2218:                                 foreach my $file (@$files) {
                   2219:                                     &Apache::lonnet::allowuploaded('/adm/grades',$file);
                   2220:                                     $lastsubonly.='<br /><a href="'.$file.'?rawmode=1" target="lonGRDs"><img src="'.&Apache::loncommon::icon($file).'" border="0" /> '.$file.'</a>';
                   2221:                                 }
                   2222:                             }
1.236     albertel 2223: 			    $lastsubonly.='<br />';
1.41      ng       2224: 			}
1.596     raeburn  2225:                         if ($hide) {
                   2226:                             $lastsubonly.='<b>'.&mt('Anonymous Survey').'</b>'; 
                   2227:                         } else {
                   2228: 			    $lastsubonly.='<b>'.&mt('Submitted Answer:').' </b>'.
                   2229: 			        &cleanRecord($subval,$responsetype,$symb,$partid,
                   2230: 					     $respid,\%record,$order,undef,$uname,$udom);
                   2231:                         }
1.151     albertel 2232: 			if ($similar) {$lastsubonly.="<br /><br />$similar\n";}
1.468     albertel 2233: 			$lastsubonly.='</div>';
1.41      ng       2234: 		    }
                   2235: 		}
                   2236: 	    }
1.588     bisitz   2237: 	    $lastsubonly.='</div>'."\n"; # End: LC_grade_submissions_body
1.151     albertel 2238: 	}
                   2239: 	$request->print($lastsubonly);
1.468     albertel 2240:    } elsif ($env{'form.lastSub'} eq 'datesub') {
1.598     www      2241: #	my (undef,$responseType,undef,$parts) = &showResourceInfo($symb);
                   2242:     my ($parts,$handgrade,$responseType) = &response_type($symb);
                   2243: 
1.148     albertel 2244: 	$request->print(&displaySubByDates($symb,\%record,$parts,$responseType,$checkIcon,$uname,$udom));
1.257     albertel 2245:     } elsif ($env{'form.lastSub'} =~ /^(last|all)$/) {
1.41      ng       2246: 	$request->print(&Apache::loncommon::get_previous_attempt($symb,$uname,$udom,
1.257     albertel 2247: 								 $env{'request.course.id'},
1.44      ng       2248: 								 $last,'.submission',
                   2249: 								 'Apache::grades::keywords_highlight'));
1.41      ng       2250:     }
1.120     ng       2251: 
1.121     ng       2252:     $request->print('<input type="hidden" name="unamedom'.$counter.'" value="'.$uname.':'
                   2253: 	.$udom.'" />'."\n");
1.44      ng       2254:     # return if view submission with no grading option
1.257     albertel 2255:     if ($env{'form.showgrading'} eq '' || (!&canmodify($usec))) {
1.120     ng       2256: 	my $toGrade.='<input type="button" value="Grade Student" '.
1.589     bisitz   2257: 	    'onclick="javascript:checksubmit(this.form,\'Grade Student\',\''
1.417     albertel 2258: 	    .$counter.'\');" target="_self" /> &nbsp;'."\n" if (&canmodify($usec));
1.468     albertel 2259: 	$toGrade.='</div>'."\n";
1.257     albertel 2260: 	if (($env{'form.command'} eq 'submission') || 
                   2261: 	    ($env{'form.command'} eq 'processGroup' && $counter == $total)) {
1.324     albertel 2262: 	    $toGrade.='</form>'.&show_grading_menu_form($symb); 
1.169     albertel 2263: 	}
1.180     albertel 2264: 	$request->print($toGrade);
1.41      ng       2265: 	return;
1.180     albertel 2266:     } else {
1.468     albertel 2267: 	$request->print('</div>'."\n");
1.41      ng       2268:     }
1.33      ng       2269: 
1.121     ng       2270:     # essay grading message center
1.257     albertel 2271:     if ($env{'form.handgrade'} eq 'yes') {
1.468     albertel 2272: 	my $result='<div class="LC_grade_message_center">';
                   2273:     
                   2274: 	$result.='<div class="LC_grade_message_center_header">'.
                   2275: 	    &mt('Send Message').'</div><div class="LC_grade_message_center_body">';
1.257     albertel 2276: 	my ($lastname,$givenn) = split(/,/,$env{'form.fullname'});
1.118     ng       2277: 	my $msgfor = $givenn.' '.$lastname;
1.464     albertel 2278: 	if (scalar(@$col_fullnames) > 0) {
                   2279: 	    my $lastone = pop(@$col_fullnames);
                   2280: 	    $msgfor .= ', '.(join ', ',@$col_fullnames).' and '.$lastone.'.';
1.118     ng       2281: 	}
                   2282: 	$msgfor =~ s/\'/\\'/g; #' stupid emacs - no! javascript
1.468     albertel 2283: 	$result.='<input type="hidden" name="includemsg'.$counter.'" value="" />'."\n".
1.121     ng       2284: 	    '<input type="hidden" name="newmsg'.$counter.'" value="" />'."\n";
                   2285: 	$result.='&nbsp;<a href="javascript:msgCenter(document.SCORE,'.$counter.
1.417     albertel 2286: 	    ',\''.$msgfor.'\');" target="_self">'.
1.464     albertel 2287: 	    &mt('Compose message to student').(scalar(@$col_fullnames) >= 1 ? 's' : '').'</a><label> ('.
1.350     albertel 2288: 	    &mt('incl. grades').' <input type="checkbox" name="withgrades'.$counter.'" /></label>)'.
1.118     ng       2289: 	    '<img src="'.$request->dir_config('lonIconsURL').
                   2290: 	    '/mailbkgrd.gif" width="14" height="10" name="mailicon'.$counter.'" />'."\n".
1.298     www      2291: 	    '<br />&nbsp;('.
1.468     albertel 2292: 	    &mt('Message will be sent when you click on Save &amp; Next below.').")\n";
                   2293: 	$result.='</div></div>';
1.121     ng       2294: 	$request->print($result);
1.118     ng       2295:     }
1.41      ng       2296: 
                   2297:     my %seen = ();
                   2298:     my @partlist;
1.129     ng       2299:     my @gradePartRespid;
1.375     albertel 2300:     my @part_response_id = &flatten_responseType($responseType);
1.585     bisitz   2301:     $request->print(
1.588     bisitz   2302:         '<div class="LC_Box">'
                   2303:        .'<h3 class="LC_hcell">'.&mt('Assign Grades').'</h3>'
1.585     bisitz   2304:     );
1.592     bisitz   2305:     $request->print(&gradeBox_start());
1.375     albertel 2306:     foreach my $part_response_id (@part_response_id) {
                   2307:     	my ($partid,$respid) = @{ $part_response_id };
                   2308: 	my $part_resp = join('_',@{ $part_response_id });
1.322     albertel 2309: 	next if ($seen{$partid} > 0);
1.41      ng       2310: 	$seen{$partid}++;
1.393     albertel 2311: 	next if ($$handgrade{$part_resp} ne 'yes' 
                   2312: 		 && $env{'form.lastSub'} eq 'hdgrade');
1.524     raeburn  2313: 	push(@partlist,$partid);
                   2314: 	push(@gradePartRespid,$partid.'.'.$respid);
1.322     albertel 2315: 	$request->print(&gradeBox($request,$symb,$uname,$udom,$counter,$partid,\%record));
1.41      ng       2316:     }
1.585     bisitz   2317:     $request->print(&gradeBox_end()); # </div>
                   2318:     $request->print('</div>');
1.468     albertel 2319: 
                   2320:     $request->print('<div class="LC_grade_info_links">');
                   2321:     $request->print('</div>');
                   2322: 
1.45      ng       2323:     $result='<input type="hidden" name="partlist'.$counter.
                   2324: 	'" value="'.(join ":",@partlist).'" />'."\n";
1.129     ng       2325:     $result.='<input type="hidden" name="gradePartRespid'.
                   2326: 	'" value="'.(join ":",@gradePartRespid).'" />'."\n" if ($counter == 0);
1.45      ng       2327:     my $ctr = 0;
                   2328:     while ($ctr < scalar(@partlist)) {
                   2329: 	$result.='<input type="hidden" name="partid'.$counter.'_'.$ctr.'" value="'.
                   2330: 	    $partlist[$ctr].'" />'."\n";
                   2331: 	$ctr++;
                   2332:     }
1.468     albertel 2333:     $request->print($result.''."\n");
1.41      ng       2334: 
1.441     www      2335: # Done with printing info for one student
                   2336: 
1.468     albertel 2337:     $request->print('</div>');#LC_grade_show_user
1.441     www      2338: 
                   2339: 
1.41      ng       2340:     # print end of form
                   2341:     if ($counter == $total) {
1.592     bisitz   2342:         my $endform='<br /><hr /><table border="0"><tr><td>'."\n";
1.485     albertel 2343: 	$endform.='<input type="button" value="'.&mt('Save &amp; Next').'" '.
1.589     bisitz   2344: 	    'onclick="javascript:checksubmit(this.form,\'Save & Next\','.
1.417     albertel 2345: 	    $total.','.scalar(@partlist).');" target="_self" /> &nbsp;'."\n";
1.119     ng       2346: 	my $ntstu ='<select name="NTSTU">'.
                   2347: 	    '<option>1</option><option>2</option>'.
                   2348: 	    '<option>3</option><option>5</option>'.
                   2349: 	    '<option>7</option><option>10</option></select>'."\n";
1.257     albertel 2350: 	my $nsel = ($env{'form.NTSTU'} ne '' ? $env{'form.NTSTU'} : '1');
1.401     albertel 2351: 	$ntstu =~ s/<option>$nsel</<option selected="selected">$nsel</;
1.578     raeburn  2352:         $endform.=&mt('[_1]student(s)',$ntstu);
1.485     albertel 2353: 	$endform.='&nbsp;&nbsp;<input type="button" value="'.&mt('Previous').'" '.
1.589     bisitz   2354: 	    'onclick="javascript:checksubmit(this.form,\'Previous\');" target="_self" /> &nbsp;'."\n".
1.485     albertel 2355: 	    '<input type="button" value="'.&mt('Next').'" '.
1.589     bisitz   2356: 	    'onclick="javascript:checksubmit(this.form,\'Next\');" target="_self" /> &nbsp;';
1.592     bisitz   2357:         $endform.='<span class="LC_warning">'.
                   2358:                   &mt('(Next and Previous (student) do not save the scores.)').
                   2359:                   '</span>'."\n" ;
1.349     albertel 2360:         $endform.="<input type='hidden' value='".&get_increment().
1.348     bowersj2 2361:             "' name='increment' />";
1.485     albertel 2362: 	$endform.='</td></tr></table></form>';
1.324     albertel 2363: 	$endform.=&show_grading_menu_form($symb);
1.41      ng       2364: 	$request->print($endform);
                   2365:     }
                   2366:     return '';
1.38      ng       2367: }
                   2368: 
1.464     albertel 2369: sub check_collaborators {
                   2370:     my ($symb,$uname,$udom,$record,$handgrade,$counter) = @_;
                   2371:     my ($result,@col_fullnames);
                   2372:     my ($classlist,undef,$fullname) = &getclasslist('all','0');
                   2373:     foreach my $part (keys(%$handgrade)) {
                   2374: 	my $ncol = &Apache::lonnet::EXT('resource.'.$part.
                   2375: 					'.maxcollaborators',
                   2376: 					$symb,$udom,$uname);
                   2377: 	next if ($ncol <= 0);
                   2378: 	$part =~ s/\_/\./g;
                   2379: 	next if ($record->{'resource.'.$part.'.collaborators'} eq '');
                   2380: 	my (@good_collaborators, @bad_collaborators);
                   2381: 	foreach my $possible_collaborator
                   2382: 	    (split(/,?\s+/,$record->{'resource.'.$part.'.collaborators'})) { 
                   2383: 	    $possible_collaborator =~ s/[\$\^\(\)]//g;
                   2384: 	    next if ($possible_collaborator eq '');
                   2385: 	    my ($co_name,$co_dom) = split(/\@|:/,$possible_collaborator);
                   2386: 	    $co_dom = $udom if (! defined($co_dom) || $co_dom =~ /^domain$/i);
                   2387: 	    next if ($co_name eq $uname && $co_dom eq $udom);
                   2388: 	    # Doing this grep allows 'fuzzy' specification
                   2389: 	    my @matches = grep(/^\Q$co_name\E:\Q$co_dom\E$/i, 
                   2390: 			       keys(%$classlist));
                   2391: 	    if (! scalar(@matches)) {
                   2392: 		push(@bad_collaborators, $possible_collaborator);
                   2393: 	    } else {
                   2394: 		push(@good_collaborators, @matches);
                   2395: 	    }
                   2396: 	}
                   2397: 	if (scalar(@good_collaborators) != 0) {
1.466     albertel 2398: 	    $result.='<br />'.&mt('Collaborators: ');
1.464     albertel 2399: 	    foreach my $name (@good_collaborators) {
                   2400: 		my ($lastname,$givenn) = split(/,/,$$fullname{$name});
                   2401: 		push(@col_fullnames, $givenn.' '.$lastname);
                   2402: 		$result.=$fullname->{$name}.'&nbsp; &nbsp; &nbsp;';
                   2403: 	    }
                   2404: 	    $result.='<br />'."\n";
1.466     albertel 2405: 	    my ($part)=split(/\./,$part);
1.464     albertel 2406: 	    $result.='<input type="hidden" name="collaborator'.$counter.
                   2407: 		'" value="'.$part.':'.(join ':',@good_collaborators).'" />'.
                   2408: 		"\n";
                   2409: 	}
                   2410: 	if (scalar(@bad_collaborators) > 0) {
1.466     albertel 2411: 	    $result.='<div class="LC_warning">';
1.464     albertel 2412: 	    $result.=&mt('This student has submitted [quant,_1,invalid collaborator]: [_2]',scalar(@bad_collaborators),join(', ',@bad_collaborators));
                   2413: 	    $result .= '</div>';
                   2414: 	}         
                   2415: 	if (scalar(@bad_collaborators > $ncol)) {
1.466     albertel 2416: 	    $result .= '<div class="LC_warning">';
1.464     albertel 2417: 	    $result .= &mt('This student has submitted too many '.
                   2418: 		'collaborators.  Maximum is [_1].',$ncol);
                   2419: 	    $result .= '</div>';
                   2420: 	}
                   2421:     }
                   2422:     return ($result,$fullname,\@col_fullnames);
                   2423: }
                   2424: 
1.44      ng       2425: #--- Retrieve the last submission for all the parts
1.38      ng       2426: sub get_last_submission {
1.119     ng       2427:     my ($returnhash)=@_;
1.596     raeburn  2428:     my (@string,$timestamp,%lasthidden);
1.119     ng       2429:     if ($$returnhash{'version'}) {
1.46      ng       2430: 	my %lasthash=();
                   2431: 	my ($version);
1.119     ng       2432: 	for ($version=1;$version<=$$returnhash{'version'};$version++) {
1.397     albertel 2433: 	    foreach my $key (sort(split(/\:/,
                   2434: 					$$returnhash{$version.':keys'}))) {
                   2435: 		$lasthash{$key}=$$returnhash{$version.':'.$key};
                   2436: 		$timestamp = 
1.545     raeburn  2437: 		    &Apache::lonlocal::locallocaltime($$returnhash{$version.':timestamp'});
1.46      ng       2438: 	    }
                   2439: 	}
1.596     raeburn  2440:         my %typeparts;
                   2441:         my $showsurv = 
                   2442:             &Apache::lonnet::allowed('vas',$env{'request.course.id'});
                   2443:         foreach my $key (sort(keys(%lasthash))) {
                   2444:             if ($key =~ /\.type$/) {
                   2445:                 if (($lasthash{$key} eq 'anonsurvey') || 
                   2446:                     ($lasthash{$key} eq 'anonsurveycred')) {
                   2447:                     my ($ign,@parts) = split(/\./,$key);
                   2448:                     pop(@parts);
                   2449:                     unless ($showsurv) {
                   2450:                         my $id = join(',',@parts);
                   2451:                         $typeparts{$ign.'.'.$id} = $lasthash{$key};
                   2452:                     }
                   2453:                     delete($lasthash{$key});
                   2454:                 }
                   2455:             }
                   2456:         }
                   2457:         my @hidden = keys(%typeparts);
1.397     albertel 2458: 	foreach my $key (keys(%lasthash)) {
                   2459: 	    next if ($key !~ /\.submission$/);
1.596     raeburn  2460:             my $hide;
                   2461:             if (@hidden) {
                   2462:                 foreach my $id (@hidden) {
                   2463:                     if ($key =~ /^\Q$id\E/) {
                   2464:                         $hide = 1;
                   2465:                         last;
                   2466:                     }
                   2467:                 }
                   2468:             }
1.397     albertel 2469: 	    my ($partid,$foo) = split(/submission$/,$key);
                   2470: 	    my $draft  = $lasthash{$partid.'awarddetail'} eq 'DRAFT' ?
1.398     albertel 2471: 		'<span class="LC_warning">Draft Copy</span> ' : '';
1.596     raeburn  2472: 	    push(@string, join(':', $key, $hide, $draft.$lasthash{$key}));
1.41      ng       2473: 	}
                   2474:     }
1.397     albertel 2475:     if (!@string) {
                   2476: 	$string[0] =
1.539     riegler  2477: 	    '<span class="LC_warning">'.&mt('Nothing submitted - no attempts.').'</span>';
1.397     albertel 2478:     }
                   2479:     return (\@string,\$timestamp);
1.38      ng       2480: }
1.35      ng       2481: 
1.44      ng       2482: #--- High light keywords, with style choosen by user.
1.38      ng       2483: sub keywords_highlight {
1.44      ng       2484:     my $string    = shift;
1.257     albertel 2485:     my $size      = $env{'form.kwsize'} eq '0' ? '' : 'size='.$env{'form.kwsize'};
                   2486:     my $styleon   = $env{'form.kwstyle'} eq ''  ? '' : $env{'form.kwstyle'};
1.41      ng       2487:     (my $styleoff = $styleon) =~ s/\</\<\//;
1.257     albertel 2488:     my @keylist   = split(/[,\s+]/,$env{'form.keywords'});
1.398     albertel 2489:     foreach my $keyword (@keylist) {
                   2490: 	$string =~ s/\b\Q$keyword\E(\b|\.)/<font color\=$env{'form.kwclr'} $size\>$styleon$keyword$styleoff<\/font>/gi;
1.41      ng       2491:     }
                   2492:     return $string;
1.38      ng       2493: }
1.36      ng       2494: 
1.44      ng       2495: #--- Called from submission routine
1.38      ng       2496: sub processHandGrade {
1.41      ng       2497:     my ($request) = shift;
1.324     albertel 2498:     my $symb   = &get_symb($request);
                   2499:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
1.257     albertel 2500:     my $button = $env{'form.gradeOpt'};
                   2501:     my $ngrade = $env{'form.NCT'};
                   2502:     my $ntstu  = $env{'form.NTSTU'};
1.301     albertel 2503:     my $cdom   = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   2504:     my $cnum   = $env{'course.'.$env{'request.course.id'}.'.num'};
                   2505: 
1.44      ng       2506:     if ($button eq 'Save & Next') {
                   2507: 	my $ctr = 0;
                   2508: 	while ($ctr < $ngrade) {
1.257     albertel 2509: 	    my ($uname,$udom) = split(/:/,$env{'form.unamedom'.$ctr});
1.324     albertel 2510: 	    my ($errorflag,$pts,$wgt) = &saveHandGrade($request,$symb,$uname,$udom,$ctr);
1.71      ng       2511: 	    if ($errorflag eq 'no_score') {
                   2512: 		$ctr++;
                   2513: 		next;
                   2514: 	    }
1.104     albertel 2515: 	    if ($errorflag eq 'not_allowed') {
1.398     albertel 2516: 		$request->print("<span class=\"LC_warning\">Not allowed to modify grades for $uname:$udom</span>");
1.104     albertel 2517: 		$ctr++;
                   2518: 		next;
                   2519: 	    }
1.257     albertel 2520: 	    my $includemsg = $env{'form.includemsg'.$ctr};
1.44      ng       2521: 	    my ($subject,$message,$msgstatus) = ('','','');
1.418     albertel 2522: 	    my $restitle = &Apache::lonnet::gettitle($symb);
                   2523:             my ($feedurl,$showsymb) =
                   2524: 		&get_feedurl_and_symb($symb,$uname,$udom);
                   2525: 	    my $messagetail;
1.62      albertel 2526: 	    if ($includemsg =~ /savemsg|newmsg\Q$ctr\E/) {
1.298     www      2527: 		$subject = $env{'form.msgsub'} if ($includemsg =~ /msgsub/);
1.295     www      2528: 		unless ($subject=~/\w/) { $subject=&mt('Grading Feedback'); }
1.386     raeburn  2529: 		$subject.=' ['.$restitle.']';
1.44      ng       2530: 		my (@msgnum) = split(/,/,$includemsg);
                   2531: 		foreach (@msgnum) {
1.257     albertel 2532: 		    $message.=$env{'form.'.$_} if ($_ =~ /savemsg|newmsg/ && $_ ne '');
1.44      ng       2533: 		}
1.80      ng       2534: 		$message =&Apache::lonfeedback::clear_out_html($message);
1.298     www      2535: 		if ($env{'form.withgrades'.$ctr}) {
                   2536: 		    $message.="\n\nPoint".($pts > 1 ? 's':'').' awarded = '.$pts.' out of '.$wgt;
1.386     raeburn  2537: 		    $messagetail = " for <a href=\"".
1.418     albertel 2538: 		                   $feedurl."?symb=$showsymb\">$env{'form.probTitle'}</a>";
1.386     raeburn  2539: 		}
                   2540: 		$msgstatus = 
                   2541:                     &Apache::lonmsg::user_normal_msg($uname,$udom,$subject,
                   2542: 						     $message.$messagetail,
1.418     albertel 2543:                                                      undef,$feedurl,undef,
1.386     raeburn  2544:                                                      undef,undef,$showsymb,
                   2545:                                                      $restitle);
1.574     bisitz   2546: 		$request->print('<br />'.&mt('Sending message to [_1]',$uname.':'.$udom).': '.
1.296     www      2547: 				$msgstatus);
1.44      ng       2548: 	    }
1.257     albertel 2549: 	    if ($env{'form.collaborator'.$ctr}) {
1.155     albertel 2550: 		my @collabstrs=&Apache::loncommon::get_env_multiple("form.collaborator$ctr");
1.150     albertel 2551: 		foreach my $collabstr (@collabstrs) {
                   2552: 		    my ($part,@collaborators) = split(/:/,$collabstr);
1.310     banghart 2553: 		    foreach my $collaborator (@collaborators) {
1.150     albertel 2554: 			my ($errorflag,$pts,$wgt) = 
1.324     albertel 2555: 			    &saveHandGrade($request,$symb,$collaborator,$udom,$ctr,
1.257     albertel 2556: 					   $env{'form.unamedom'.$ctr},$part);
1.150     albertel 2557: 			if ($errorflag eq 'not_allowed') {
1.362     albertel 2558: 			    $request->print("<span class=\"LC_error\">".&mt('Not allowed to modify grades for [_1]',"$collaborator:$udom")."</span>");
1.150     albertel 2559: 			    next;
1.418     albertel 2560: 			} elsif ($message ne '') {
                   2561: 			    my ($baseurl,$showsymb) = 
                   2562: 				&get_feedurl_and_symb($symb,$collaborator,
                   2563: 						      $udom);
                   2564: 			    if ($env{'form.withgrades'.$ctr}) {
                   2565: 				$messagetail = " for <a href=\"".
1.386     raeburn  2566:                                     $baseurl."?symb=$showsymb\">$env{'form.probTitle'}</a>";
1.150     albertel 2567: 			    }
1.418     albertel 2568: 			    $msgstatus = 
                   2569: 				&Apache::lonmsg::user_normal_msg($collaborator,$udom,$subject,$message.$messagetail,undef,$baseurl,undef,undef,undef,$showsymb,$restitle);
1.104     albertel 2570: 			}
1.44      ng       2571: 		    }
                   2572: 		}
                   2573: 	    }
                   2574: 	    $ctr++;
                   2575: 	}
                   2576:     }
                   2577: 
1.257     albertel 2578:     if ($env{'form.handgrade'} eq 'yes') {
1.119     ng       2579: 	# Keywords sorted in alphabatical order
1.257     albertel 2580: 	my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
1.119     ng       2581: 	my %keyhash = ();
1.257     albertel 2582: 	$env{'form.keywords'}           =~ s/,\s{0,}|\s+/ /g;
                   2583: 	$env{'form.keywords'}           =~ s/^\s+|\s+$//;
                   2584: 	my (@keywords) = sort(split(/\s+/,$env{'form.keywords'}));
                   2585: 	$env{'form.keywords'} = join(' ',@keywords);
                   2586: 	$keyhash{$symb.'_keywords'}     = $env{'form.keywords'};
                   2587: 	$keyhash{$symb.'_subject'}      = $env{'form.msgsub'};
                   2588: 	$keyhash{$loginuser.'_kwclr'}   = $env{'form.kwclr'};
                   2589: 	$keyhash{$loginuser.'_kwsize'}  = $env{'form.kwsize'};
                   2590: 	$keyhash{$loginuser.'_kwstyle'} = $env{'form.kwstyle'};
1.119     ng       2591: 
                   2592: 	# message center - Order of message gets changed. Blank line is eliminated.
1.257     albertel 2593: 	# New messages are saved in env for the next student.
1.119     ng       2594: 	# All messages are saved in nohist_handgrade.db
                   2595: 	my ($ctr,$idx) = (1,1);
1.257     albertel 2596: 	while ($ctr <= $env{'form.savemsgN'}) {
                   2597: 	    if ($env{'form.savemsg'.$ctr} ne '') {
                   2598: 		$keyhash{$symb.'_savemsg'.$idx} = $env{'form.savemsg'.$ctr};
1.119     ng       2599: 		$idx++;
                   2600: 	    }
                   2601: 	    $ctr++;
1.41      ng       2602: 	}
1.119     ng       2603: 	$ctr = 0;
                   2604: 	while ($ctr < $ngrade) {
1.257     albertel 2605: 	    if ($env{'form.newmsg'.$ctr} ne '') {
                   2606: 		$keyhash{$symb.'_savemsg'.$idx} = $env{'form.newmsg'.$ctr};
                   2607: 		$env{'form.savemsg'.$idx} = $env{'form.newmsg'.$ctr};
1.119     ng       2608: 		$idx++;
                   2609: 	    }
                   2610: 	    $ctr++;
1.41      ng       2611: 	}
1.257     albertel 2612: 	$env{'form.savemsgN'} = --$idx;
                   2613: 	$keyhash{$symb.'_savemsgN'} = $env{'form.savemsgN'};
1.119     ng       2614: 	my $putresult = &Apache::lonnet::put
1.301     albertel 2615: 	    ('nohist_handgrade',\%keyhash,$cdom,$cnum);
1.41      ng       2616:     }
1.44      ng       2617:     # Called by Save & Refresh from Highlight Attribute Window
1.257     albertel 2618:     my (undef,undef,$fullname) = &getclasslist($env{'form.section'},'1');
                   2619:     if ($env{'form.refresh'} eq 'on') {
1.86      ng       2620: 	my ($ctr,$total) = (0,0);
                   2621: 	while ($ctr < $ngrade) {
1.257     albertel 2622: 	    $total++ if  $env{'form.unamedom'.$ctr} ne '';
1.86      ng       2623: 	    $ctr++;
                   2624: 	}
1.257     albertel 2625: 	$env{'form.NTSTU'}=$ngrade;
1.86      ng       2626: 	$ctr = 0;
                   2627: 	while ($ctr < $total) {
1.257     albertel 2628: 	    my $processUser = $env{'form.unamedom'.$ctr};
                   2629: 	    ($env{'form.student'},$env{'form.userdom'}) = split(/:/,$processUser);
                   2630: 	    $env{'form.fullname'} = $$fullname{$processUser};
1.86      ng       2631: 	    &submission($request,$ctr,$total-1);
1.41      ng       2632: 	    $ctr++;
                   2633: 	}
                   2634: 	return '';
                   2635:     }
1.36      ng       2636: 
1.121     ng       2637: # Go directly to grade student - from submission or link from chart page
1.120     ng       2638:     if ($button eq 'Grade Student') {
1.598     www      2639: #	(undef,undef,$env{'form.handgrade'},undef,undef) = &showResourceInfo($symb);
1.257     albertel 2640: 	my $processUser = $env{'form.unamedom'.$env{'form.studentNo'}};
                   2641: 	($env{'form.student'},$env{'form.userdom'}) = split(/:/,$processUser);
                   2642: 	$env{'form.fullname'} = $$fullname{$processUser};
1.120     ng       2643: 	&submission($request,0,0);
                   2644: 	return '';
                   2645:     }
                   2646: 
1.44      ng       2647:     # Get the next/previous one or group of students
1.257     albertel 2648:     my $firststu = $env{'form.unamedom0'};
                   2649:     my $laststu = $env{'form.unamedom'.($ngrade-1)};
1.119     ng       2650:     my $ctr = 2;
1.41      ng       2651:     while ($laststu eq '') {
1.257     albertel 2652: 	$laststu  = $env{'form.unamedom'.($ngrade-$ctr)};
1.41      ng       2653: 	$ctr++;
                   2654: 	$laststu = $firststu if ($ctr > $ngrade);
                   2655:     }
1.44      ng       2656: 
1.41      ng       2657:     my (@parsedlist,@nextlist);
                   2658:     my ($nextflg) = 0;
1.524     raeburn  2659:     foreach my $item (sort 
1.294     albertel 2660: 	     {
                   2661: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                   2662: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                   2663: 		 }
                   2664: 		 return $a cmp $b;
                   2665: 	     } (keys(%$fullname))) {
1.41      ng       2666: 	if ($nextflg == 1 && $button =~ /Next$/) {
1.524     raeburn  2667: 	    push(@parsedlist,$item);
1.41      ng       2668: 	}
1.524     raeburn  2669: 	$nextflg = 1 if ($item eq $laststu);
1.41      ng       2670: 	if ($button eq 'Previous') {
1.524     raeburn  2671: 	    last if ($item eq $firststu);
                   2672: 	    push(@parsedlist,$item);
1.41      ng       2673: 	}
                   2674:     }
                   2675:     $ctr = 0;
                   2676:     @parsedlist = reverse @parsedlist if ($button eq 'Previous');
1.582     raeburn  2677:     my $res_error;
                   2678:     my ($partlist) = &response_type($symb,\$res_error);
                   2679:     if ($res_error) {
                   2680:         $request->print(&navmap_errormsg());
                   2681:         return;
                   2682:     }
1.41      ng       2683:     foreach my $student (@parsedlist) {
1.257     albertel 2684: 	my $submitonly=$env{'form.submitonly'};
1.41      ng       2685: 	my ($uname,$udom) = split(/:/,$student);
1.301     albertel 2686: 	
                   2687: 	if ($submitonly eq 'queued') {
                   2688: 	    my %queue_status = 
                   2689: 		&Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
                   2690: 							$udom,$uname);
                   2691: 	    next if (!defined($queue_status{'gradingqueue'}));
                   2692: 	}
                   2693: 
1.156     albertel 2694: 	if ($submitonly =~ /^(yes|graded|incorrect)$/) {
1.257     albertel 2695: #	    my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
1.324     albertel 2696: 	    my %status=&student_gradeStatus($symb,$udom,$uname,$partlist);
1.145     albertel 2697: 	    my $submitted = 0;
1.248     albertel 2698: 	    my $ungraded = 0;
                   2699: 	    my $incorrect = 0;
1.524     raeburn  2700: 	    foreach my $item (keys(%status)) {
                   2701: 		$submitted = 1 if ($status{$item} ne 'nothing');
                   2702: 		$ungraded = 1 if ($status{$item} =~ /^ungraded/);
                   2703: 		$incorrect = 1 if ($status{$item} =~ /^incorrect/);
                   2704: 		my ($foo,$partid,$foo1) = split(/\./,$item);
1.145     albertel 2705: 		if ($status{'resource.'.$partid.'.submitted_by'} ne '') {
                   2706: 		    $submitted = 0;
                   2707: 		}
1.41      ng       2708: 	    }
1.156     albertel 2709: 	    next if (!$submitted && ($submitonly eq 'yes' ||
                   2710: 				     $submitonly eq 'incorrect' ||
                   2711: 				     $submitonly eq 'graded'));
1.248     albertel 2712: 	    next if (!$ungraded && ($submitonly eq 'graded'));
                   2713: 	    next if (!$incorrect && $submitonly eq 'incorrect');
1.41      ng       2714: 	}
1.524     raeburn  2715: 	push(@nextlist,$student) if ($ctr < $ntstu);
1.129     ng       2716: 	last if ($ctr == $ntstu);
1.41      ng       2717: 	$ctr++;
                   2718:     }
1.36      ng       2719: 
1.41      ng       2720:     $ctr = 0;
                   2721:     my $total = scalar(@nextlist)-1;
1.39      ng       2722: 
1.524     raeburn  2723:     foreach (sort(@nextlist)) {
1.41      ng       2724: 	my ($uname,$udom,$submitter) = split(/:/);
1.257     albertel 2725: 	$env{'form.student'}  = $uname;
                   2726: 	$env{'form.userdom'}  = $udom;
                   2727: 	$env{'form.fullname'} = $$fullname{$_};
1.41      ng       2728: 	&submission($request,$ctr,$total);
                   2729: 	$ctr++;
                   2730:     }
                   2731:     if ($total < 0) {
1.485     albertel 2732: 	my $the_end = '<h3><span class="LC_info">'.&mt('LON-CAPA User Message').'</span></h3><br />'."\n";
                   2733: 	$the_end.=&mt('<b>Message: </b> No more students for this section or class.').'<br /><br />'."\n";
                   2734: 	$the_end.=&mt('Click on the button below to return to the grading menu.').'<br /><br />'."\n";
1.324     albertel 2735: 	$the_end.=&show_grading_menu_form($symb);
1.41      ng       2736: 	$request->print($the_end);
                   2737:     }
                   2738:     return '';
1.38      ng       2739: }
1.36      ng       2740: 
1.44      ng       2741: #---- Save the score and award for each student, if changed
1.38      ng       2742: sub saveHandGrade {
1.324     albertel 2743:     my ($request,$symb,$stuname,$domain,$newflg,$submitter,$part) = @_;
1.342     banghart 2744:     my @version_parts;
1.104     albertel 2745:     my $usec = &Apache::lonnet::getsection($domain,$stuname,
1.257     albertel 2746: 					   $env{'request.course.id'});
1.104     albertel 2747:     if (!&canmodify($usec)) { return('not_allowed'); }
1.337     banghart 2748:     my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$domain,$stuname);
1.251     banghart 2749:     my @parts_graded;
1.77      ng       2750:     my %newrecord  = ();
                   2751:     my ($pts,$wgt) = ('','');
1.269     raeburn  2752:     my %aggregate = ();
                   2753:     my $aggregateflag = 0;
1.301     albertel 2754:     my @parts = split(/:/,$env{'form.partlist'.$newflg});
                   2755:     foreach my $new_part (@parts) {
1.337     banghart 2756: 	#collaborator ($submi may vary for different parts
1.259     banghart 2757: 	if ($submitter && $new_part ne $part) { next; }
                   2758: 	my $dropMenu = $env{'form.GD_SEL'.$newflg.'_'.$new_part};
1.125     ng       2759: 	if ($dropMenu eq 'excused') {
1.259     banghart 2760: 	    if ($record{'resource.'.$new_part.'.solved'} ne 'excused') {
                   2761: 		$newrecord{'resource.'.$new_part.'.solved'} = 'excused';
                   2762: 		if (exists($record{'resource.'.$new_part.'.awarded'})) {
                   2763: 		    $newrecord{'resource.'.$new_part.'.awarded'} = '';
1.58      albertel 2764: 		}
1.364     banghart 2765: 	        $newrecord{'resource.'.$new_part.'.regrader'}="$env{'user.name'}:$env{'user.domain'}";
1.58      albertel 2766: 	    }
1.125     ng       2767: 	} elsif ($dropMenu eq 'reset status'
1.259     banghart 2768: 		 && exists($record{'resource.'.$new_part.'.solved'})) { #don't bother if no old records -> no attempts
1.524     raeburn  2769: 	    foreach my $key (keys(%record)) {
1.259     banghart 2770: 		if ($key=~/^resource\.\Q$new_part\E\./) { $newrecord{$key} = ''; }
1.197     albertel 2771: 	    }
1.259     banghart 2772: 	    $newrecord{'resource.'.$new_part.'.regrader'}=
1.257     albertel 2773: 		"$env{'user.name'}:$env{'user.domain'}";
1.270     albertel 2774:             my $totaltries = $record{'resource.'.$part.'.tries'};
                   2775: 
                   2776:             my %last_resets = &get_last_resets($symb,$env{'request.course.id'},
                   2777: 					       [$new_part]);
                   2778:             my $aggtries =$totaltries;
1.269     raeburn  2779:             if ($last_resets{$new_part}) {
1.270     albertel 2780:                 $aggtries = &get_num_tries(\%record,$last_resets{$new_part},
                   2781: 					   $new_part);
1.269     raeburn  2782:             }
1.270     albertel 2783: 
                   2784:             my $solvedstatus = $record{'resource.'.$new_part.'.solved'};
1.269     raeburn  2785:             if ($aggtries > 0) {
1.327     albertel 2786:                 &decrement_aggs($symb,$new_part,\%aggregate,$aggtries,$totaltries,$solvedstatus);
1.269     raeburn  2787:                 $aggregateflag = 1;
                   2788:             }
1.125     ng       2789: 	} elsif ($dropMenu eq '') {
1.259     banghart 2790: 	    $pts = ($env{'form.GD_BOX'.$newflg.'_'.$new_part} ne '' ? 
                   2791: 		    $env{'form.GD_BOX'.$newflg.'_'.$new_part} : 
                   2792: 		    $env{'form.RADVAL'.$newflg.'_'.$new_part});
                   2793: 	    if ($pts eq '' && $env{'form.GD_SEL'.$newflg.'_'.$new_part} eq '') {
1.153     albertel 2794: 		next;
                   2795: 	    }
1.259     banghart 2796: 	    $wgt = $env{'form.WGT'.$newflg.'_'.$new_part} eq '' ? 1 : 
                   2797: 		$env{'form.WGT'.$newflg.'_'.$new_part};
1.41      ng       2798: 	    my $partial= $pts/$wgt;
1.259     banghart 2799: 	    if ($partial eq $record{'resource.'.$new_part.'.awarded'}) {
1.153     albertel 2800: 		#do not update score for part if not changed.
1.346     banghart 2801:                 &handback_files($request,$symb,$stuname,$domain,$newflg,$new_part,\%newrecord);
1.153     albertel 2802: 		next;
1.251     banghart 2803: 	    } else {
1.524     raeburn  2804: 	        push(@parts_graded,$new_part);
1.153     albertel 2805: 	    }
1.259     banghart 2806: 	    if ($record{'resource.'.$new_part.'.awarded'} ne $partial) {
                   2807: 		$newrecord{'resource.'.$new_part.'.awarded'}  = $partial;
1.153     albertel 2808: 	    }
1.259     banghart 2809: 	    my $reckey = 'resource.'.$new_part.'.solved';
1.41      ng       2810: 	    if ($partial == 0) {
1.153     albertel 2811: 		if ($record{$reckey} ne 'incorrect_by_override') {
                   2812: 		    $newrecord{$reckey} = 'incorrect_by_override';
                   2813: 		}
1.41      ng       2814: 	    } else {
1.153     albertel 2815: 		if ($record{$reckey} ne 'correct_by_override') {
                   2816: 		    $newrecord{$reckey} = 'correct_by_override';
                   2817: 		}
                   2818: 	    }	    
                   2819: 	    if ($submitter && 
1.259     banghart 2820: 		($record{'resource.'.$new_part.'.submitted_by'} ne $submitter)) {
                   2821: 		$newrecord{'resource.'.$new_part.'.submitted_by'} = $submitter;
1.41      ng       2822: 	    }
1.259     banghart 2823: 	    $newrecord{'resource.'.$new_part.'.regrader'}=
1.257     albertel 2824: 		"$env{'user.name'}:$env{'user.domain'}";
1.41      ng       2825: 	}
1.259     banghart 2826: 	# unless problem has been graded, set flag to version the submitted files
1.305     banghart 2827: 	unless ($record{'resource.'.$new_part.'.solved'} =~ /^correct_/  || 
                   2828: 	        $record{'resource.'.$new_part.'.solved'} eq 'incorrect_by_override' ||
                   2829: 	        $dropMenu eq 'reset status')
                   2830: 	   {
1.524     raeburn  2831: 	    push(@version_parts,$new_part);
1.259     banghart 2832: 	}
1.41      ng       2833:     }
1.301     albertel 2834:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   2835:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   2836: 
1.344     albertel 2837:     if (%newrecord) {
                   2838:         if (@version_parts) {
1.364     banghart 2839:             my @changed_keys = &version_portfiles(\%record, \@parts_graded, 
                   2840:                                 $env{'request.course.id'}, $symb, $domain, $stuname, \@version_parts);
1.344     albertel 2841: 	    @newrecord{@changed_keys} = @record{@changed_keys};
1.367     albertel 2842: 	    foreach my $new_part (@version_parts) {
                   2843: 		&handback_files($request,$symb,$stuname,$domain,$newflg,
                   2844: 				$new_part,\%newrecord);
                   2845: 	    }
1.259     banghart 2846:         }
1.44      ng       2847: 	&Apache::lonnet::cstore(\%newrecord,$symb,
1.257     albertel 2848: 				$env{'request.course.id'},$domain,$stuname);
1.380     albertel 2849: 	&check_and_remove_from_queue(\@parts,\%record,\%newrecord,$symb,
                   2850: 				     $cdom,$cnum,$domain,$stuname);
1.41      ng       2851:     }
1.269     raeburn  2852:     if ($aggregateflag) {
                   2853:         &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
1.301     albertel 2854: 			      $cdom,$cnum);
1.269     raeburn  2855:     }
1.301     albertel 2856:     return ('',$pts,$wgt);
1.36      ng       2857: }
1.322     albertel 2858: 
1.380     albertel 2859: sub check_and_remove_from_queue {
                   2860:     my ($parts,$record,$newrecord,$symb,$cdom,$cnum,$domain,$stuname) = @_;
                   2861:     my @ungraded_parts;
                   2862:     foreach my $part (@{$parts}) {
                   2863: 	if (    $record->{   'resource.'.$part.'.awarded'} eq ''
                   2864: 	     && $record->{   'resource.'.$part.'.solved' } ne 'excused'
                   2865: 	     && $newrecord->{'resource.'.$part.'.awarded'} eq ''
                   2866: 	     && $newrecord->{'resource.'.$part.'.solved' } ne 'excused'
                   2867: 		) {
                   2868: 	    push(@ungraded_parts, $part);
                   2869: 	}
                   2870:     }
                   2871:     if ( !@ungraded_parts ) {
                   2872: 	&Apache::bridgetask::remove_from_queue('gradingqueue',$symb,$cdom,
                   2873: 					       $cnum,$domain,$stuname);
                   2874:     }
                   2875: }
                   2876: 
1.337     banghart 2877: sub handback_files {
                   2878:     my ($request,$symb,$stuname,$domain,$newflg,$new_part,$newrecord) = @_;
1.517     raeburn  2879:     my $portfolio_root = '/userfiles/portfolio';
1.582     raeburn  2880:     my $res_error;
                   2881:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
                   2882:     if ($res_error) {
                   2883:         $request->print('<br />'.&navmap_errormsg().'<br />');
                   2884:         return;
                   2885:     }
1.375     albertel 2886:     my @part_response_id = &flatten_responseType($responseType);
                   2887:     foreach my $part_response_id (@part_response_id) {
                   2888:     	my ($part_id,$resp_id) = @{ $part_response_id };
                   2889: 	my $part_resp = join('_',@{ $part_response_id });
1.337     banghart 2890:             if (($env{'form.'.$newflg.'_'.$part_resp.'_returndoc1'}) && ($new_part == $part_id)) {
                   2891:                 # if multiple files are uploaded names will be 'returndoc2','returndoc3'
                   2892:                 my $file_counter = 1;
1.367     albertel 2893: 		my $file_msg;
1.337     banghart 2894:                 while ($env{'form.'.$newflg.'_'.$part_resp.'_returndoc'.$file_counter}) {
                   2895:                     my $fname=$env{'form.'.$newflg.'_'.$part_resp.'_returndoc'.$file_counter.'.filename'};
1.338     banghart 2896:                     my ($directory,$answer_file) = 
                   2897:                         ($env{'form.'.$newflg.'_'.$part_resp.'_origdoc'.$file_counter} =~ /^(.*?)([^\/]*)$/);
                   2898:                     my ($answer_name,$answer_ver,$answer_ext) =
                   2899: 		        &file_name_version_ext($answer_file);
1.355     banghart 2900: 		    my ($portfolio_path) = ($directory =~ /^.+$stuname\/portfolio(.*)/);
1.517     raeburn  2901:                     my $getpropath = 1;
                   2902: 		    my @dir_list = &Apache::lonnet::dirlist($portfolio_root.$portfolio_path,$domain,$stuname,$getpropath);
1.338     banghart 2903: 		    my $version = &get_next_version($answer_name, $answer_ext, \@dir_list);
1.355     banghart 2904:                     # fix file name
                   2905:                     my ($save_file_name) = (($directory.$answer_name.".$version.".$answer_ext) =~ /^.+\/${stuname}\/(.*)/);
                   2906:                     my $result=&Apache::lonnet::finishuserfileupload($stuname,$domain,
                   2907:             	                                $newflg.'_'.$part_resp.'_returndoc'.$file_counter,
                   2908:             	                                $save_file_name);
1.337     banghart 2909:                     if ($result !~ m|^/uploaded/|) {
1.536     raeburn  2910:                         $request->print('<br /><span class="LC_error">'.
                   2911:                             &mt('An error occurred ([_1]) while trying to upload [_2].',
                   2912:                                 $result,$newflg.'_'.$part_resp.'_returndoc'.$file_counter).
                   2913:                                         '</span>');
1.356     banghart 2914:                     } else {
1.360     banghart 2915:                         # mark the file as read only
                   2916:                         my @files = ($save_file_name);
1.372     albertel 2917:                         my @what = ($symb,$env{'request.course.id'},'handback');
1.360     banghart 2918:                         &Apache::lonnet::mark_as_readonly($domain,$stuname,\@files,\@what);
1.367     albertel 2919: 			if (exists($$newrecord{"resource.$new_part.$resp_id.handback"})) {
                   2920: 			    $$newrecord{"resource.$new_part.$resp_id.handback"}.=',';
                   2921: 			}
                   2922:                         $$newrecord{"resource.$new_part.$resp_id.handback"} .= $save_file_name;
                   2923: 			$file_msg.= "\n".'<br /><span class="LC_filename"><a href="/uploaded/'."$domain/$stuname/".$save_file_name.'">'.$save_file_name."</a></span><br />";
                   2924: 
1.337     banghart 2925:                     }
                   2926:                     $request->print("<br />".$fname." will be the uploaded file name");
1.354     albertel 2927:                     $request->print(" ".$env{'form.'.$newflg.'_'.$part_resp.'_origdoc'.$file_counter});
1.337     banghart 2928:                     $file_counter++;
                   2929:                 }
1.367     albertel 2930: 		my $subject = "File Handed Back by Instructor ";
                   2931: 		my $message = "A file has been returned that was originally submitted in reponse to: <br />";
                   2932: 		$message .= "<strong>".&Apache::lonnet::gettitle($symb)."</strong><br />";
                   2933: 		$message .= ' The returned file(s) are named: '. $file_msg;
                   2934: 		$message .= " and can be found in your portfolio space.";
1.418     albertel 2935: 		my ($feedurl,$showsymb) = 
                   2936: 		    &get_feedurl_and_symb($symb,$domain,$stuname);
1.386     raeburn  2937:                 my $restitle = &Apache::lonnet::gettitle($symb);
                   2938: 		my $msgstatus = 
                   2939:                    &Apache::lonmsg::user_normal_msg($stuname,$domain,$subject.
                   2940: 			 ' (File Returned) ['.$restitle.']',$message,undef,
1.418     albertel 2941:                          $feedurl,undef,undef,undef,$showsymb,$restitle);
1.337     banghart 2942:             }
                   2943:         }
1.338     banghart 2944:     return;
1.337     banghart 2945: }
                   2946: 
1.418     albertel 2947: sub get_feedurl_and_symb {
                   2948:     my ($symb,$uname,$udom) = @_;
                   2949:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
                   2950:     $url = &Apache::lonnet::clutter($url);
                   2951:     my $encrypturl=&Apache::lonnet::EXT('resource.0.encrypturl',
                   2952: 					$symb,$udom,$uname);
                   2953:     if ($encrypturl =~ /^yes$/i) {
                   2954: 	&Apache::lonenc::encrypted(\$url,1);
                   2955: 	&Apache::lonenc::encrypted(\$symb,1);
                   2956:     }
                   2957:     return ($url,$symb);
                   2958: }
                   2959: 
1.313     banghart 2960: sub get_submitted_files {
                   2961:     my ($udom,$uname,$partid,$respid,$record) = @_;
                   2962:     my @files;
                   2963:     if ($$record{"resource.$partid.$respid.portfiles"}) {
                   2964:         my $file_url = '/uploaded/'.$udom.'/'.$uname.'/portfolio';
                   2965:         foreach my $file (split(',',$$record{"resource.$partid.$respid.portfiles"})) {
                   2966:     	    push(@files,$file_url.$file);
                   2967:         }
                   2968:     }
                   2969:     if ($$record{"resource.$partid.$respid.uploadedurl"}) {
                   2970:         push(@files,$$record{"resource.$partid.$respid.uploadedurl"});
                   2971:     }
                   2972:     return (\@files);
                   2973: }
1.322     albertel 2974: 
1.269     raeburn  2975: # ----------- Provides number of tries since last reset.
                   2976: sub get_num_tries {
                   2977:     my ($record,$last_reset,$part) = @_;
                   2978:     my $timestamp = '';
                   2979:     my $num_tries = 0;
                   2980:     if ($$record{'version'}) {
                   2981:         for (my $version=$$record{'version'};$version>=1;$version--) {
                   2982:             if (exists($$record{$version.':resource.'.$part.'.solved'})) {
                   2983:                 $timestamp = $$record{$version.':timestamp'};
                   2984:                 if ($timestamp > $last_reset) {
                   2985:                     $num_tries ++;
                   2986:                 } else {
                   2987:                     last;
                   2988:                 }
                   2989:             }
                   2990:         }
                   2991:     }
                   2992:     return $num_tries;
                   2993: }
                   2994: 
                   2995: # ----------- Determine decrements required in aggregate totals 
                   2996: sub decrement_aggs {
                   2997:     my ($symb,$part,$aggregate,$aggtries,$totaltries,$solvedstatus) = @_;
                   2998:     my %decrement = (
                   2999:                         attempts => 0,
                   3000:                         users => 0,
                   3001:                         correct => 0
                   3002:                     );
                   3003:     $decrement{'attempts'} = $aggtries;
                   3004:     if ($solvedstatus =~ /^correct/) {
                   3005:         $decrement{'correct'} = 1;
                   3006:     }
                   3007:     if ($aggtries == $totaltries) {
                   3008:         $decrement{'users'} = 1;
                   3009:     }
1.524     raeburn  3010:     foreach my $type (keys(%decrement)) {
1.269     raeburn  3011:         $$aggregate{$symb."\0".$part."\0".$type} = -$decrement{$type};
                   3012:     }
                   3013:     return;
                   3014: }
                   3015: 
                   3016: # ----------- Determine timestamps for last reset of aggregate totals for parts  
                   3017: sub get_last_resets {
1.270     albertel 3018:     my ($symb,$courseid,$partids) =@_;
                   3019:     my %last_resets;
1.269     raeburn  3020:     my $cdom = $env{'course.'.$courseid.'.domain'};
                   3021:     my $cname = $env{'course.'.$courseid.'.num'};
1.271     albertel 3022:     my @keys;
                   3023:     foreach my $part (@{$partids}) {
                   3024: 	push(@keys,"$symb\0$part\0resettime");
                   3025:     }
                   3026:     my %results=&Apache::lonnet::get('nohist_resourcetracker',\@keys,
                   3027: 				     $cdom,$cname);
                   3028:     foreach my $part (@{$partids}) {
                   3029: 	$last_resets{$part}=$results{"$symb\0$part\0resettime"};
1.269     raeburn  3030:     }
1.270     albertel 3031:     return %last_resets;
1.269     raeburn  3032: }
                   3033: 
1.251     banghart 3034: # ----------- Handles creating versions for portfolio files as answers
                   3035: sub version_portfiles {
1.343     banghart 3036:     my ($record, $parts_graded, $courseid, $symb, $domain, $stu_name, $v_flag) = @_;
1.263     banghart 3037:     my $version_parts = join('|',@$v_flag);
1.343     banghart 3038:     my @returned_keys;
1.255     banghart 3039:     my $parts = join('|', @$parts_graded);
1.517     raeburn  3040:     my $portfolio_root = '/userfiles/portfolio';
1.277     albertel 3041:     foreach my $key (keys(%$record)) {
1.259     banghart 3042:         my $new_portfiles;
1.263     banghart 3043:         if ($key =~ /^resource\.($version_parts)\./ && $key =~ /\.portfiles$/ ) {
1.342     banghart 3044:             my @versioned_portfiles;
1.367     albertel 3045:             my @portfiles = split(/\s*,\s*/,$$record{$key});
1.252     banghart 3046:             foreach my $file (@portfiles) {
1.306     banghart 3047:                 &Apache::lonnet::unmark_as_readonly($domain,$stu_name,[$symb,$env{'request.course.id'}],$file);
1.304     albertel 3048:                 my ($directory,$answer_file) =($file =~ /^(.*?)([^\/]*)$/);
                   3049: 		my ($answer_name,$answer_ver,$answer_ext) =
                   3050: 		    &file_name_version_ext($answer_file);
1.517     raeburn  3051:                 my $getpropath = 1;    
                   3052:                 my @dir_list = &Apache::lonnet::dirlist($portfolio_root.$directory,$domain,$stu_name,$getpropath);
1.342     banghart 3053:                 my $version = &get_next_version($answer_name, $answer_ext, \@dir_list);
1.306     banghart 3054:                 my $new_answer = &version_selected_portfile($domain, $stu_name, $directory, $answer_file, $version);
                   3055:                 if ($new_answer ne 'problem getting file') {
1.342     banghart 3056:                     push(@versioned_portfiles, $directory.$new_answer);
1.306     banghart 3057:                     &Apache::lonnet::mark_as_readonly($domain,$stu_name,
1.367     albertel 3058:                         [$directory.$new_answer],
1.306     banghart 3059:                         [$symb,$env{'request.course.id'},'graded']);
1.259     banghart 3060:                 }
1.252     banghart 3061:             }
1.343     banghart 3062:             $$record{$key} = join(',',@versioned_portfiles);
                   3063:             push(@returned_keys,$key);
1.251     banghart 3064:         }
                   3065:     } 
1.343     banghart 3066:     return (@returned_keys);   
1.305     banghart 3067: }
                   3068: 
1.307     banghart 3069: sub get_next_version {
1.341     banghart 3070:     my ($answer_name, $answer_ext, $dir_list) = @_;
1.307     banghart 3071:     my $version;
                   3072:     foreach my $row (@$dir_list) {
                   3073:         my ($file) = split(/\&/,$row,2);
                   3074:         my ($file_name,$file_version,$file_ext) =
                   3075: 	    &file_name_version_ext($file);
                   3076:         if (($file_name eq $answer_name) && 
                   3077: 	    ($file_ext eq $answer_ext)) {
                   3078:                 # gets here if filename and extension match, regardless of version
                   3079:                 if ($file_version ne '') {
                   3080:                 # a versioned file is found  so save it for later
                   3081:                 if ($file_version > $version) {
                   3082: 		    $version = $file_version;
                   3083: 	        }
                   3084:             }
                   3085:         }
                   3086:     } 
                   3087:     $version ++;
                   3088:     return($version);
                   3089: }
                   3090: 
1.305     banghart 3091: sub version_selected_portfile {
1.306     banghart 3092:     my ($domain,$stu_name,$directory,$file_name,$version) = @_;
                   3093:     my ($answer_name,$answer_ver,$answer_ext) =
                   3094:         &file_name_version_ext($file_name);
                   3095:     my $new_answer;
                   3096:     $env{'form.copy'} = &Apache::lonnet::getfile("/uploaded/$domain/$stu_name/portfolio$directory$file_name");
                   3097:     if($env{'form.copy'} eq '-1') {
                   3098:         $new_answer = 'problem getting file';
                   3099:     } else {
                   3100:         $new_answer = $answer_name.'.'.$version.'.'.$answer_ext;
                   3101:         my $copy_result = &Apache::lonnet::finishuserfileupload(
                   3102:                             $stu_name,$domain,'copy',
                   3103: 		        '/portfolio'.$directory.$new_answer);
                   3104:     }    
                   3105:     return ($new_answer);
1.251     banghart 3106: }
                   3107: 
1.304     albertel 3108: sub file_name_version_ext {
                   3109:     my ($file)=@_;
                   3110:     my @file_parts = split(/\./, $file);
                   3111:     my ($name,$version,$ext);
                   3112:     if (@file_parts > 1) {
                   3113: 	$ext=pop(@file_parts);
                   3114: 	if (@file_parts > 1 && $file_parts[-1] =~ /^\d+$/) {
                   3115: 	    $version=pop(@file_parts);
                   3116: 	}
                   3117: 	$name=join('.',@file_parts);
                   3118:     } else {
                   3119: 	$name=join('.',@file_parts);
                   3120:     }
                   3121:     return($name,$version,$ext);
                   3122: }
                   3123: 
1.44      ng       3124: #--------------------------------------------------------------------------------------
                   3125: #
                   3126: #-------------------------- Next few routines handles grading by section or whole class
                   3127: #
                   3128: #--- Javascript to handle grading by section or whole class
1.42      ng       3129: sub viewgrades_js {
                   3130:     my ($request) = shift;
                   3131: 
1.539     riegler  3132:     my $alertmsg = &mt('A number equal or greater than 0 is expected. Entered value = ');
1.597     wenzelju 3133:     $request->print(&Apache::lonhtmlcommon::scripttag(<<VIEWJAVASCRIPT));
1.45      ng       3134:    function writePoint(partid,weight,point) {
1.125     ng       3135: 	var radioButton = document.classgrade["RADVAL_"+partid];
                   3136: 	var textbox = document.classgrade["TEXTVAL_"+partid];
1.42      ng       3137: 	if (point == "textval") {
1.125     ng       3138: 	    point = document.classgrade["TEXTVAL_"+partid].value;
1.109     matthew  3139: 	    if (isNaN(point) || parseFloat(point) < 0) {
1.539     riegler  3140: 		alert("$alertmsg"+parseFloat(point));
1.42      ng       3141: 		var resetbox = false;
                   3142: 		for (var i=0; i<radioButton.length; i++) {
                   3143: 		    if (radioButton[i].checked) {
                   3144: 			textbox.value = i;
                   3145: 			resetbox = true;
                   3146: 		    }
                   3147: 		}
                   3148: 		if (!resetbox) {
                   3149: 		    textbox.value = "";
                   3150: 		}
                   3151: 		return;
                   3152: 	    }
1.109     matthew  3153: 	    if (parseFloat(point) > parseFloat(weight)) {
                   3154: 		var resp = confirm("You entered a value ("+parseFloat(point)+
1.44      ng       3155: 				   ") greater than the weight for the part. Accept?");
                   3156: 		if (resp == false) {
                   3157: 		    textbox.value = "";
                   3158: 		    return;
                   3159: 		}
                   3160: 	    }
1.42      ng       3161: 	    for (var i=0; i<radioButton.length; i++) {
                   3162: 		radioButton[i].checked=false;
1.109     matthew  3163: 		if (parseFloat(point) == i) {
1.42      ng       3164: 		    radioButton[i].checked=true;
                   3165: 		}
                   3166: 	    }
1.41      ng       3167: 
1.42      ng       3168: 	} else {
1.125     ng       3169: 	    textbox.value = parseFloat(point);
1.42      ng       3170: 	}
1.41      ng       3171: 	for (i=0;i<document.classgrade.total.value;i++) {
1.125     ng       3172: 	    var user = document.classgrade["ctr"+i].value;
1.289     albertel 3173: 	    user = user.replace(new RegExp(':', 'g'),"_");
1.125     ng       3174: 	    var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
                   3175: 	    var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
                   3176: 	    var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
1.42      ng       3177: 	    if (saveval != "correct") {
                   3178: 		scorename.value = point;
1.43      ng       3179: 		if (selname[0].selected != true) {
                   3180: 		    selname[0].selected = true;
                   3181: 		}
1.42      ng       3182: 	    }
                   3183: 	}
1.125     ng       3184: 	document.classgrade["SELVAL_"+partid][0].selected = true;
1.42      ng       3185:     }
                   3186: 
                   3187:     function writeRadText(partid,weight) {
1.125     ng       3188: 	var selval   = document.classgrade["SELVAL_"+partid];
                   3189: 	var radioButton = document.classgrade["RADVAL_"+partid];
1.265     www      3190:         var override = document.classgrade["FORCE_"+partid].checked;
1.125     ng       3191: 	var textbox = document.classgrade["TEXTVAL_"+partid];
                   3192: 	if (selval[1].selected || selval[2].selected) {
1.42      ng       3193: 	    for (var i=0; i<radioButton.length; i++) {
                   3194: 		radioButton[i].checked=false;
                   3195: 
                   3196: 	    }
                   3197: 	    textbox.value = "";
                   3198: 
                   3199: 	    for (i=0;i<document.classgrade.total.value;i++) {
1.125     ng       3200: 		var user = document.classgrade["ctr"+i].value;
1.289     albertel 3201: 		user = user.replace(new RegExp(':', 'g'),"_");
1.125     ng       3202: 		var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
                   3203: 		var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
                   3204: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
1.265     www      3205: 		if ((saveval != "correct") || override) {
1.42      ng       3206: 		    scorename.value = "";
1.125     ng       3207: 		    if (selval[1].selected) {
                   3208: 			selname[1].selected = true;
                   3209: 		    } else {
                   3210: 			selname[2].selected = true;
                   3211: 			if (Number(document.classgrade["GD_"+user+"_"+partid+"_tries"].value)) 
                   3212: 			{document.classgrade["GD_"+user+"_"+partid+"_tries"].value = '0';}
                   3213: 		    }
1.42      ng       3214: 		}
                   3215: 	    }
1.43      ng       3216: 	} else {
                   3217: 	    for (i=0;i<document.classgrade.total.value;i++) {
1.125     ng       3218: 		var user = document.classgrade["ctr"+i].value;
1.289     albertel 3219: 		user = user.replace(new RegExp(':', 'g'),"_");
1.125     ng       3220: 		var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
                   3221: 		var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
                   3222: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
1.265     www      3223: 		if ((saveval != "correct") || override) {
1.125     ng       3224: 		    scorename.value = document.classgrade["GD_"+user+"_"+partid+"_awarded_s"].value;
1.43      ng       3225: 		    selname[0].selected = true;
                   3226: 		}
                   3227: 	    }
                   3228: 	}	    
1.42      ng       3229:     }
                   3230: 
                   3231:     function changeSelect(partid,user) {
1.125     ng       3232: 	var selval = document.classgrade["GD_"+user+'_'+partid+"_solved"];
                   3233: 	var textbox = document.classgrade["GD_"+user+'_'+partid+"_awarded"];
1.44      ng       3234: 	var point  = textbox.value;
1.125     ng       3235: 	var weight = document.classgrade["weight_"+partid].value;
1.44      ng       3236: 
1.109     matthew  3237: 	if (isNaN(point) || parseFloat(point) < 0) {
1.539     riegler  3238: 	    alert("$alertmsg"+parseFloat(point));
1.44      ng       3239: 	    textbox.value = "";
                   3240: 	    return;
                   3241: 	}
1.109     matthew  3242: 	if (parseFloat(point) > parseFloat(weight)) {
                   3243: 	    var resp = confirm("You entered a value ("+parseFloat(point)+
1.44      ng       3244: 			       ") greater than the weight of the part. Accept?");
                   3245: 	    if (resp == false) {
                   3246: 		textbox.value = "";
                   3247: 		return;
                   3248: 	    }
                   3249: 	}
1.42      ng       3250: 	selval[0].selected = true;
                   3251:     }
                   3252: 
                   3253:     function changeOneScore(partid,user) {
1.125     ng       3254: 	var selval = document.classgrade["GD_"+user+'_'+partid+"_solved"];
                   3255: 	if (selval[1].selected || selval[2].selected) {
                   3256: 	    document.classgrade["GD_"+user+'_'+partid+"_awarded"].value = "";
                   3257: 	    if (selval[2].selected) {
                   3258: 		document.classgrade["GD_"+user+'_'+partid+"_tries"].value = "0";
                   3259: 	    }
1.269     raeburn  3260:         }
1.42      ng       3261:     }
                   3262: 
                   3263:     function resetEntry(numpart) {
                   3264: 	for (ctpart=0;ctpart<numpart;ctpart++) {
1.125     ng       3265: 	    var partid = document.classgrade["partid_"+ctpart].value;
                   3266: 	    var radioButton = document.classgrade["RADVAL_"+partid];
                   3267: 	    var textbox = document.classgrade["TEXTVAL_"+partid];
                   3268: 	    var selval  = document.classgrade["SELVAL_"+partid];
1.42      ng       3269: 	    for (var i=0; i<radioButton.length; i++) {
                   3270: 		radioButton[i].checked=false;
                   3271: 
                   3272: 	    }
                   3273: 	    textbox.value = "";
                   3274: 	    selval[0].selected = true;
                   3275: 
                   3276: 	    for (i=0;i<document.classgrade.total.value;i++) {
1.125     ng       3277: 		var user = document.classgrade["ctr"+i].value;
1.289     albertel 3278: 		user = user.replace(new RegExp(':', 'g'),"_");
1.125     ng       3279: 		var resetscore = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
                   3280: 		resetscore.value = document.classgrade["GD_"+user+"_"+partid+"_awarded_s"].value;
                   3281: 		var resettries = document.classgrade["GD_"+user+"_"+partid+"_tries"];
                   3282: 		resettries.value = document.classgrade["GD_"+user+"_"+partid+"_tries_s"].value;
                   3283: 		var saveselval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
                   3284: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
1.42      ng       3285: 		if (saveselval == "excused") {
1.43      ng       3286: 		    if (selname[1].selected == false) { selname[1].selected = true;}
1.42      ng       3287: 		} else {
1.43      ng       3288: 		    if (selname[0].selected == false) {selname[0].selected = true};
1.42      ng       3289: 		}
                   3290: 	    }
1.41      ng       3291: 	}
1.42      ng       3292:     }
                   3293: 
1.41      ng       3294: VIEWJAVASCRIPT
1.42      ng       3295: }
                   3296: 
1.44      ng       3297: #--- show scores for a section or whole class w/ option to change/update a score
1.42      ng       3298: sub viewgrades {
                   3299:     my ($request) = shift;
                   3300:     &viewgrades_js($request);
1.41      ng       3301: 
1.324     albertel 3302:     my ($symb) = &get_symb($request);
1.168     albertel 3303:     #need to make sure we have the correct data for later EXT calls, 
                   3304:     #thus invalidate the cache
                   3305:     &Apache::lonnet::devalidatecourseresdata(
1.257     albertel 3306:                  $env{'course.'.$env{'request.course.id'}.'.num'},
                   3307:                  $env{'course.'.$env{'request.course.id'}.'.domain'});
1.168     albertel 3308:     &Apache::lonnet::clear_EXT_cache_status();
                   3309: 
1.398     albertel 3310:     my $result='<h3><span class="LC_info">'.&mt('Manual Grading').'</span></h3>';
1.485     albertel 3311:     $result.='<h4>'.&mt('<b>Current Resource: </b>[_1]',$env{'form.probTitle'}).'</h4>'."\n";
1.41      ng       3312: 
                   3313:     #view individual student submission form - called using Javascript viewOneStudent
1.324     albertel 3314:     $result.=&jscriptNform($symb);
1.41      ng       3315: 
1.44      ng       3316:     #beginning of class grading form
1.442     banghart 3317:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
1.41      ng       3318:     $result.= '<form action="/adm/grades" method="post" name="classgrade">'."\n".
1.418     albertel 3319: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.38      ng       3320: 	'<input type="hidden" name="command" value="editgrades" />'."\n".
1.432     banghart 3321: 	&build_section_inputs().
1.257     albertel 3322: 	'<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n".
1.442     banghart 3323: 	'<input type="hidden" name="Status" value="'.$env{'stu_status'}.'" />'."\n".
1.257     albertel 3324: 	'<input type="hidden" name="probTitle" value="'.$env{'form.probTitle'}.'" />'."\n";
1.72      ng       3325: 
1.560     raeburn  3326:     my ($common_header,$specific_header);
1.257     albertel 3327:     if ($env{'form.section'} eq 'all') {
1.560     raeburn  3328: 	$common_header = &mt('Assign Common Grade to Class');
                   3329:         $specific_header = &mt('Assign Grade to Specific Students in Class');
1.257     albertel 3330:     } elsif ($env{'form.section'} eq 'none') {
1.560     raeburn  3331:         $common_header = &mt('Assign Common Grade to Students in no Section');
                   3332: 	$specific_header = &mt('Assign Grade to Specific Students in no Section');
1.52      albertel 3333:     } else {
1.560     raeburn  3334:         my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
                   3335:         $common_header = &mt('Assign Common Grade to Students in Section(s) [_1]',$section_display);
                   3336: 	$specific_header = &mt('Assign Grade to Specific Students in Section(s) [_1]',$section_display);
1.52      albertel 3337:     }
1.560     raeburn  3338:     $result.= '<h3>'.$common_header.'</h3>'.&Apache::loncommon::start_data_table();
1.44      ng       3339:     #radio buttons/text box for assigning points for a section or class.
                   3340:     #handles different parts of a problem
1.582     raeburn  3341:     my $res_error;
                   3342:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
                   3343:     if ($res_error) {
                   3344:         return &navmap_errormsg();
                   3345:     }
1.42      ng       3346:     my %weight = ();
                   3347:     my $ctsparts = 0;
1.45      ng       3348:     my %seen = ();
1.375     albertel 3349:     my @part_response_id = &flatten_responseType($responseType);
                   3350:     foreach my $part_response_id (@part_response_id) {
                   3351:     	my ($partid,$respid) = @{ $part_response_id };
                   3352: 	my $part_resp = join('_',@{ $part_response_id });
1.45      ng       3353: 	next if $seen{$partid};
                   3354: 	$seen{$partid}++;
1.375     albertel 3355: 	my $handgrade=$$handgrade{$part_resp};
1.42      ng       3356: 	my $wgt = &Apache::lonnet::EXT('resource.'.$partid.'.weight',$symb);
                   3357: 	$weight{$partid} = $wgt eq '' ? '1' : $wgt;
                   3358: 
1.324     albertel 3359: 	my $display_part=&get_display_part($partid,$symb);
1.485     albertel 3360: 	my $radio.='<table border="0"><tr>';  
1.41      ng       3361: 	my $ctr = 0;
1.42      ng       3362: 	while ($ctr<=$weight{$partid}) { # display radio buttons in a nice table 10 across
1.485     albertel 3363: 	    $radio.= '<td><label><input type="radio" name="RADVAL_'.$partid.'" '.
1.54      albertel 3364: 		'onclick="javascript:writePoint(\''.$partid.'\','.$weight{$partid}.
1.288     albertel 3365: 		','.$ctr.')" />'.$ctr."</label></td>\n";
1.41      ng       3366: 	    $result.=(($ctr+1)%10 == 0 ? '</tr><tr>' : '');
                   3367: 	    $ctr++;
                   3368: 	}
1.485     albertel 3369: 	$radio.='</tr></table>';
                   3370: 	my $line = '<input type="text" name="TEXTVAL_'.
1.589     bisitz   3371: 	    $partid.'" size="4" '.'onchange="javascript:writePoint(\''.
1.54      albertel 3372: 		$partid.'\','.$weight{$partid}.',\'textval\')" /> /'.
1.539     riegler  3373: 	    $weight{$partid}.' '.&mt('(problem weight)').'</td>'."\n";
                   3374: 	$line.= '<td><b>'.&mt('Grade Status').':</b><select name="SELVAL_'.$partid.'"'.
1.589     bisitz   3375: 	    'onchange="javascript:writeRadText(\''.$partid.'\','.
1.59      albertel 3376: 		$weight{$partid}.')"> '.
1.401     albertel 3377: 	    '<option selected="selected"> </option>'.
1.485     albertel 3378: 	    '<option value="excused">'.&mt('excused').'</option>'.
                   3379: 	    '<option value="reset status">'.&mt('reset status').'</option>'.
                   3380: 	    '</select></td>'.
                   3381:             '<td><label><input type="checkbox" name="FORCE_'.$partid.'" />'.&mt('Override "Correct"').'</label>';
                   3382: 	$line.='<input type="hidden" name="partid_'.
                   3383: 	    $ctsparts.'" value="'.$partid.'" />'."\n";
                   3384: 	$line.='<input type="hidden" name="weight_'.
                   3385: 	    $partid.'" value="'.$weight{$partid}.'" />'."\n";
                   3386: 
                   3387: 	$result.=
                   3388: 	    &Apache::loncommon::start_data_table_row()."\n".
1.577     bisitz   3389: 	    '<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 3390: 	    &Apache::loncommon::end_data_table_row()."\n";
1.42      ng       3391: 	$ctsparts++;
1.41      ng       3392:     }
1.474     albertel 3393:     $result.=&Apache::loncommon::end_data_table()."\n".
1.52      albertel 3394: 	'<input type="hidden" name="totalparts" value="'.$ctsparts.'" />';
1.485     albertel 3395:     $result.='<input type="button" value="'.&mt('Revert to Default').'" '.
1.589     bisitz   3396: 	'onclick="javascript:resetEntry('.$ctsparts.');" />';
1.41      ng       3397: 
1.44      ng       3398:     #table listing all the students in a section/class
                   3399:     #header of table
1.560     raeburn  3400:     $result.= '<h3>'.$specific_header.'</h3>'.
                   3401:               &Apache::loncommon::start_data_table().
                   3402: 	      &Apache::loncommon::start_data_table_header_row().
                   3403: 	      '<th>'.&mt('No.').'</th>'.
                   3404: 	      '<th>'.&nameUserString('header')."</th>\n";
1.582     raeburn  3405:     my $partserror;
                   3406:     my (@parts) = sort(&getpartlist($symb,\$partserror));
                   3407:     if ($partserror) {
                   3408:         return &navmap_errormsg();
                   3409:     }
1.324     albertel 3410:     my (undef,undef,$url)=&Apache::lonnet::decode_symb($symb);
1.269     raeburn  3411:     my @partids = ();
1.41      ng       3412:     foreach my $part (@parts) {
                   3413: 	my $display=&Apache::lonnet::metadata($url,$part.'.display');
1.539     riegler  3414:         my $narrowtext = &mt('Tries');
                   3415: 	$display =~ s|^Number of Attempts|$narrowtext <br />|; # makes the column narrower
1.41      ng       3416: 	if  (!$display) { $display = &Apache::lonnet::metadata($url,$part.'.name'); }
1.207     albertel 3417: 	my ($partid) = &split_part_type($part);
1.524     raeburn  3418:         push(@partids,$partid);
1.324     albertel 3419: 	my $display_part=&get_display_part($partid,$symb);
1.41      ng       3420: 	if ($display =~ /^Partial Credit Factor/) {
1.485     albertel 3421: 	    $result.='<th>'.
                   3422: 		&mt('Score Part: [_1]<br /> (weight = [_2])',
                   3423: 		    $display_part,$weight{$partid}).'</th>'."\n";
1.41      ng       3424: 	    next;
1.485     albertel 3425: 	    
1.207     albertel 3426: 	} else {
1.485     albertel 3427: 	    if ($display =~ /Problem Status/) {
                   3428: 		my $grade_status_mt = &mt('Grade Status');
                   3429: 		$display =~ s{Problem Status}{$grade_status_mt<br />};
                   3430: 	    }
                   3431: 	    my $part_mt = &mt('Part:');
                   3432: 	    $display =~s{\[Part: \Q$partid\E\]}{$part_mt $display_part};
1.41      ng       3433: 	}
1.485     albertel 3434: 
1.474     albertel 3435: 	$result.='<th>'.$display.'</th>'."\n";
1.41      ng       3436:     }
1.474     albertel 3437:     $result.=&Apache::loncommon::end_data_table_header_row();
1.44      ng       3438: 
1.270     albertel 3439:     my %last_resets = 
                   3440: 	&get_last_resets($symb,$env{'request.course.id'},\@partids);
1.269     raeburn  3441: 
1.41      ng       3442:     #get info for each student
1.44      ng       3443:     #list all the students - with points and grade status
1.257     albertel 3444:     my (undef,undef,$fullname) = &getclasslist($env{'form.section'},'1');
1.41      ng       3445:     my $ctr = 0;
1.294     albertel 3446:     foreach (sort 
                   3447: 	     {
                   3448: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                   3449: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                   3450: 		 }
                   3451: 		 return $a cmp $b;
                   3452: 	     } (keys(%$fullname))) {
1.126     ng       3453: 	$ctr++;
1.324     albertel 3454: 	$result.=&viewstudentgrade($symb,$env{'request.course.id'},
1.269     raeburn  3455: 				   $_,$$fullname{$_},\@parts,\%weight,$ctr,\%last_resets);
1.41      ng       3456:     }
1.474     albertel 3457:     $result.=&Apache::loncommon::end_data_table();
1.41      ng       3458:     $result.='<input type="hidden" name="total" value="'.$ctr.'" />'."\n";
1.485     albertel 3459:     $result.='<input type="button" value="'.&mt('Save').'" '.
1.589     bisitz   3460: 	'onclick="javascript:submit();" target="_self" /></form>'."\n";
1.96      albertel 3461:     if (scalar(%$fullname) eq 0) {
                   3462: 	my $colspan=3+scalar(@parts);
1.433     banghart 3463: 	my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
1.442     banghart 3464:         my $stu_status = join(' or ',&Apache::loncommon::get_env_multiple('form.Status'));
1.433     banghart 3465: 	$result='<span class="LC_warning">'.
1.485     albertel 3466: 	    &mt('There are no students in section(s) [_1] with enrollment status [_2] to modify or grade.',
1.442     banghart 3467: 	        $section_display, $stu_status).
1.433     banghart 3468: 	    '</span>';
1.96      albertel 3469:     }
1.324     albertel 3470:     $result.=&show_grading_menu_form($symb);
1.41      ng       3471:     return $result;
                   3472: }
                   3473: 
1.44      ng       3474: #--- call by previous routine to display each student
1.41      ng       3475: sub viewstudentgrade {
1.324     albertel 3476:     my ($symb,$courseid,$student,$fullname,$parts,$weight,$ctr,$last_resets) = @_;
1.44      ng       3477:     my ($uname,$udom) = split(/:/,$student);
                   3478:     my %record=&Apache::lonnet::restore($symb,$courseid,$udom,$uname);
1.269     raeburn  3479:     my %aggregates = (); 
1.474     albertel 3480:     my $result=&Apache::loncommon::start_data_table_row().'<td align="right">'.
1.233     albertel 3481: 	'<input type="hidden" name="ctr'.($ctr-1).'" value="'.$student.'" />'.
                   3482: 	"\n".$ctr.'&nbsp;</td><td>&nbsp;'.
1.44      ng       3483: 	'<a href="javascript:viewOneStudent(\''.$uname.'\',\''.$udom.
1.417     albertel 3484: 	'\');" target="_self">'.$fullname.'</a> '.
1.398     albertel 3485: 	'<span class="LC_internal_info">('.$uname.($env{'user.domain'} eq $udom ? '' : ':'.$udom).')</span></td>'."\n";
1.281     albertel 3486:     $student=~s/:/_/; # colon doen't work in javascript for names
1.63      albertel 3487:     foreach my $apart (@$parts) {
                   3488: 	my ($part,$type) = &split_part_type($apart);
1.41      ng       3489: 	my $score=$record{"resource.$part.$type"};
1.276     albertel 3490:         $result.='<td align="center">';
1.269     raeburn  3491:         my ($aggtries,$totaltries);
                   3492:         unless (exists($aggregates{$part})) {
1.270     albertel 3493: 	    $totaltries = $record{'resource.'.$part.'.tries'};
                   3494: 
                   3495: 	    $aggtries = $totaltries;
1.269     raeburn  3496:             if ($$last_resets{$part}) {  
1.270     albertel 3497:                 $aggtries = &get_num_tries(\%record,$$last_resets{$part},
                   3498: 					   $part);
                   3499:             }
1.269     raeburn  3500:             $result.='<input type="hidden" name="'.
                   3501:                 'GD_'.$student.'_'.$part.'_aggtries" value="'.$aggtries.'" />'."\n";
                   3502:             $result.='<input type="hidden" name="'.
                   3503:                 'GD_'.$student.'_'.$part.'_totaltries" value="'.$totaltries.'" />'."\n";
                   3504:             $aggregates{$part} = 1;
                   3505:         }
1.41      ng       3506: 	if ($type eq 'awarded') {
1.320     albertel 3507: 	    my $pts = $score eq '' ? '' : &compute_points($score,$$weight{$part});
1.42      ng       3508: 	    $result.='<input type="hidden" name="'.
1.89      albertel 3509: 		'GD_'.$student.'_'.$part.'_awarded_s" value="'.$pts.'" />'."\n";
1.233     albertel 3510: 	    $result.='<input type="text" name="'.
1.89      albertel 3511: 		'GD_'.$student.'_'.$part.'_awarded" '.
1.589     bisitz   3512:                 'onchange="javascript:changeSelect(\''.$part.'\',\''.$student.
1.44      ng       3513: 		'\')" value="'.$pts.'" size="4" /></td>'."\n";
1.41      ng       3514: 	} elsif ($type eq 'solved') {
                   3515: 	    my ($status,$foo)=split(/_/,$score,2);
                   3516: 	    $status = 'nothing' if ($status eq '');
1.89      albertel 3517: 	    $result.='<input type="hidden" name="'.'GD_'.$student.'_'.
1.54      albertel 3518: 		$part.'_solved_s" value="'.$status.'" />'."\n";
1.233     albertel 3519: 	    $result.='&nbsp;<select name="'.
1.89      albertel 3520: 		'GD_'.$student.'_'.$part.'_solved" '.
1.589     bisitz   3521:                 'onchange="javascript:changeOneScore(\''.$part.'\',\''.$student.'\')" >'."\n";
1.485     albertel 3522: 	    $result.= (($status eq 'excused') ? '<option> </option><option selected="selected" value="excused">'.&mt('excused').'</option>' 
                   3523: 		: '<option selected="selected"> </option><option value="excused">'.&mt('excused').'</option>')."\n";
                   3524: 	    $result.='<option value="reset status">'.&mt('reset status').'</option>';
1.126     ng       3525: 	    $result.="</select>&nbsp;</td>\n";
1.122     ng       3526: 	} else {
                   3527: 	    $result.='<input type="hidden" name="'.
                   3528: 		'GD_'.$student.'_'.$part.'_'.$type.'_s" value="'.$score.'" />'.
                   3529: 		    "\n";
1.233     albertel 3530: 	    $result.='<input type="text" name="'.
1.122     ng       3531: 		'GD_'.$student.'_'.$part.'_'.$type.'" '.
                   3532: 		'value="'.$score.'" size="4" /></td>'."\n";
1.41      ng       3533: 	}
                   3534:     }
1.474     albertel 3535:     $result.=&Apache::loncommon::end_data_table_row();
1.41      ng       3536:     return $result;
1.38      ng       3537: }
                   3538: 
1.44      ng       3539: #--- change scores for all the students in a section/class
                   3540: #    record does not get update if unchanged
1.38      ng       3541: sub editgrades {
1.41      ng       3542:     my ($request) = @_;
                   3543: 
1.324     albertel 3544:     my $symb=&get_symb($request);
1.433     banghart 3545:     my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
1.477     albertel 3546:     my $title='<h2>'.&mt('Current Grade Status').'</h2>';
                   3547:     $title.='<h4>'.&mt('<b>Current Resource: </b>[_1]',$env{'form.probTitle'}).'</h4>'."\n";
1.433     banghart 3548:     $title.='<h4>'.&mt('<b>Section: </b>[_1]',$section_display).'</h4>'."\n";
1.126     ng       3549: 
1.477     albertel 3550:     my $result= &Apache::loncommon::start_data_table().
                   3551: 	&Apache::loncommon::start_data_table_header_row().
                   3552: 	'<th rowspan="2" valign="middle">'.&mt('No.').'</th>'.
                   3553: 	'<th rowspan="2" valign="middle">'.&nameUserString('header')."</th>\n";
1.43      ng       3554:     my %scoreptr = (
                   3555: 		    'correct'  =>'correct_by_override',
                   3556: 		    'incorrect'=>'incorrect_by_override',
                   3557: 		    'excused'  =>'excused',
                   3558: 		    'ungraded' =>'ungraded_attempted',
1.596     raeburn  3559:                     'credited' =>'credit_attempted',
1.43      ng       3560: 		    'nothing'  => '',
                   3561: 		    );
1.257     albertel 3562:     my ($classlist,undef,$fullname) = &getclasslist($env{'form.section'},'0');
1.34      ng       3563: 
1.44      ng       3564:     my (@partid);
                   3565:     my %weight = ();
1.54      albertel 3566:     my %columns = ();
1.44      ng       3567:     my ($i,$ctr,$count,$rec_update) = (0,0,0,0);
1.54      albertel 3568: 
1.582     raeburn  3569:     my $partserror;
                   3570:     my (@parts) = sort(&getpartlist($symb,\$partserror));
                   3571:     if ($partserror) {
                   3572:         return &navmap_errormsg();
                   3573:     }
1.54      albertel 3574:     my $header;
1.257     albertel 3575:     while ($ctr < $env{'form.totalparts'}) {
                   3576: 	my $partid = $env{'form.partid_'.$ctr};
1.524     raeburn  3577: 	push(@partid,$partid);
1.257     albertel 3578: 	$weight{$partid} = $env{'form.weight_'.$partid};
1.44      ng       3579: 	$ctr++;
1.54      albertel 3580:     }
1.324     albertel 3581:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
1.54      albertel 3582:     foreach my $partid (@partid) {
1.478     albertel 3583: 	$header .= '<th align="center">'.&mt('Old Score').'</th>'.
                   3584: 	    '<th align="center">'.&mt('New Score').'</th>';
1.54      albertel 3585: 	$columns{$partid}=2;
                   3586: 	foreach my $stores (@parts) {
                   3587: 	    my ($part,$type) = &split_part_type($stores);
                   3588: 	    if ($part !~ m/^\Q$partid\E/) { next;}
                   3589: 	    if ($type eq 'awarded' || $type eq 'solved') { next; }
                   3590: 	    my $display=&Apache::lonnet::metadata($url,$stores.'.display');
1.551     raeburn  3591: 	    $display =~ s/\[Part: \Q$part\E\]//;
1.539     riegler  3592:             my $narrowtext = &mt('Tries');
                   3593: 	    $display =~ s/Number of Attempts/$narrowtext/;
                   3594: 	    $header .= '<th align="center">'.&mt('Old').' '.$display.'</th>'.
                   3595: 		'<th align="center">'.&mt('New').' '.$display.'</th>';
1.54      albertel 3596: 	    $columns{$partid}+=2;
                   3597: 	}
                   3598:     }
                   3599:     foreach my $partid (@partid) {
1.324     albertel 3600: 	my $display_part=&get_display_part($partid,$symb);
1.478     albertel 3601: 	$result .= '<th colspan="'.$columns{$partid}.'" align="center">'.
                   3602: 	    &mt('Part: [_1] (Weight = [_2])',$display_part,$weight{$partid}).
                   3603: 	    '</th>';
1.54      albertel 3604: 
1.44      ng       3605:     }
1.477     albertel 3606:     $result .= &Apache::loncommon::end_data_table_header_row().
                   3607: 	&Apache::loncommon::start_data_table_header_row().
                   3608: 	$header.
                   3609: 	&Apache::loncommon::end_data_table_header_row();
                   3610:     my @noupdate;
1.126     ng       3611:     my ($updateCtr,$noupdateCtr) = (1,1);
1.257     albertel 3612:     for ($i=0; $i<$env{'form.total'}; $i++) {
1.93      albertel 3613: 	my $line;
1.257     albertel 3614: 	my $user = $env{'form.ctr'.$i};
1.281     albertel 3615: 	my ($uname,$udom)=split(/:/,$user);
1.44      ng       3616: 	my %newrecord;
                   3617: 	my $updateflag = 0;
1.281     albertel 3618: 	$line .= '<td>'.&nameUserString(undef,$$fullname{$user},$uname,$udom).'</td>';
1.108     albertel 3619: 	my $usec=$classlist->{"$uname:$udom"}[5];
1.105     albertel 3620: 	if (!&canmodify($usec)) {
1.126     ng       3621: 	    my $numcols=scalar(@partid)*4+2;
1.477     albertel 3622: 	    push(@noupdate,
1.478     albertel 3623: 		 $line."<td colspan=\"$numcols\"><span class=\"LC_warning\">".
                   3624: 		 &mt('Not allowed to modify student')."</span></td></tr>");
1.105     albertel 3625: 	    next;
                   3626: 	}
1.269     raeburn  3627:         my %aggregate = ();
                   3628:         my $aggregateflag = 0;
1.281     albertel 3629: 	$user=~s/:/_/; # colon doen't work in javascript for names
1.44      ng       3630: 	foreach (@partid) {
1.257     albertel 3631: 	    my $old_aw    = $env{'form.GD_'.$user.'_'.$_.'_awarded_s'};
1.54      albertel 3632: 	    my $old_part_pcr = $old_aw/($weight{$_} ne '0' ? $weight{$_}:1);
                   3633: 	    my $old_part  = $old_aw eq '' ? '' : $old_part_pcr;
1.257     albertel 3634: 	    my $old_score = $scoreptr{$env{'form.GD_'.$user.'_'.$_.'_solved_s'}};
                   3635: 	    my $awarded   = $env{'form.GD_'.$user.'_'.$_.'_awarded'};
1.54      albertel 3636: 	    my $pcr       = $awarded/($weight{$_} ne '0' ? $weight{$_} : 1);
                   3637: 	    my $partial   = $awarded eq '' ? '' : $pcr;
1.44      ng       3638: 	    my $score;
                   3639: 	    if ($partial eq '') {
1.257     albertel 3640: 		$score = $scoreptr{$env{'form.GD_'.$user.'_'.$_.'_solved_s'}};
1.44      ng       3641: 	    } elsif ($partial > 0) {
                   3642: 		$score = 'correct_by_override';
                   3643: 	    } elsif ($partial == 0) {
                   3644: 		$score = 'incorrect_by_override';
                   3645: 	    }
1.257     albertel 3646: 	    my $dropMenu = $env{'form.GD_'.$user.'_'.$_.'_solved'};
1.125     ng       3647: 	    $score = 'excused' if (($dropMenu eq 'excused') && ($score ne 'excused'));
                   3648: 
1.292     albertel 3649: 	    $newrecord{'resource.'.$_.'.regrader'}=
                   3650: 		"$env{'user.name'}:$env{'user.domain'}";
1.125     ng       3651: 	    if ($dropMenu eq 'reset status' &&
                   3652: 		$old_score ne '') { # ignore if no previous attempts => nothing to reset
1.299     albertel 3653: 		$newrecord{'resource.'.$_.'.tries'} = '';
1.125     ng       3654: 		$newrecord{'resource.'.$_.'.solved'} = '';
                   3655: 		$newrecord{'resource.'.$_.'.award'} = '';
1.299     albertel 3656: 		$newrecord{'resource.'.$_.'.awarded'} = '';
1.125     ng       3657: 		$updateflag = 1;
1.269     raeburn  3658:                 if ($env{'form.GD_'.$user.'_'.$_.'_aggtries'} > 0) {
                   3659:                     my $aggtries = $env{'form.GD_'.$user.'_'.$_.'_aggtries'};
                   3660:                     my $totaltries = $env{'form.GD_'.$user.'_'.$_.'_totaltries'};
                   3661:                     my $solvedstatus = $env{'form.GD_'.$user.'_'.$_.'_solved_s'};
                   3662:                     &decrement_aggs($symb,$_,\%aggregate,$aggtries,$totaltries,$solvedstatus);
                   3663:                     $aggregateflag = 1;
                   3664:                 }
1.139     albertel 3665: 	    } elsif (!($old_part eq $partial && $old_score eq $score)) {
                   3666: 		$updateflag = 1;
                   3667: 		$newrecord{'resource.'.$_.'.awarded'}  = $partial if $partial ne '';
                   3668: 		$newrecord{'resource.'.$_.'.solved'}   = $score;
                   3669: 		$rec_update++;
1.125     ng       3670: 	    }
                   3671: 
1.93      albertel 3672: 	    $line .= '<td align="center">'.$old_aw.'&nbsp;</td>'.
1.44      ng       3673: 		'<td align="center">'.$awarded.
                   3674: 		($score eq 'excused' ? $score : '').'&nbsp;</td>';
1.5       albertel 3675: 
1.54      albertel 3676: 
                   3677: 	    my $partid=$_;
                   3678: 	    foreach my $stores (@parts) {
                   3679: 		my ($part,$type) = &split_part_type($stores);
                   3680: 		if ($part !~ m/^\Q$partid\E/) { next;}
                   3681: 		if ($type eq 'awarded' || $type eq 'solved') { next; }
1.257     albertel 3682: 		my $old_aw    = $env{'form.GD_'.$user.'_'.$part.'_'.$type.'_s'};
                   3683: 		my $awarded   = $env{'form.GD_'.$user.'_'.$part.'_'.$type};
1.54      albertel 3684: 		if ($awarded ne '' && $awarded ne $old_aw) {
                   3685: 		    $newrecord{'resource.'.$part.'.'.$type}= $awarded;
1.257     albertel 3686: 		    $newrecord{'resource.'.$part.'.regrader'}="$env{'user.name'}:$env{'user.domain'}";
1.54      albertel 3687: 		    $updateflag=1;
                   3688: 		}
1.93      albertel 3689: 		$line .= '<td align="center">'.$old_aw.'&nbsp;</td>'.
1.54      albertel 3690: 		    '<td align="center">'.$awarded.'&nbsp;</td>';
                   3691: 	    }
1.44      ng       3692: 	}
1.477     albertel 3693: 	$line.="\n";
1.301     albertel 3694: 
                   3695: 	my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   3696: 	my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   3697: 
1.44      ng       3698: 	if ($updateflag) {
                   3699: 	    $count++;
1.257     albertel 3700: 	    &Apache::lonnet::cstore(\%newrecord,$symb,$env{'request.course.id'},
1.89      albertel 3701: 				    $udom,$uname);
1.301     albertel 3702: 
                   3703: 	    if (&Apache::bridgetask::in_queue('gradingqueue',$symb,$cdom,
                   3704: 					      $cnum,$udom,$uname)) {
                   3705: 		# need to figure out if should be in queue.
                   3706: 		my %record =  
                   3707: 		    &Apache::lonnet::restore($symb,$env{'request.course.id'},
                   3708: 					     $udom,$uname);
                   3709: 		my $all_graded = 1;
                   3710: 		my $none_graded = 1;
                   3711: 		foreach my $part (@parts) {
                   3712: 		    if ( $record{'resource.'.$part.'.awarded'} eq '' ) {
                   3713: 			$all_graded = 0;
                   3714: 		    } else {
                   3715: 			$none_graded = 0;
                   3716: 		    }
                   3717: 		}
                   3718: 
                   3719: 		if ($all_graded || $none_graded) {
                   3720: 		    &Apache::bridgetask::remove_from_queue('gradingqueue',
                   3721: 							   $symb,$cdom,$cnum,
                   3722: 							   $udom,$uname);
                   3723: 		}
                   3724: 	    }
                   3725: 
1.477     albertel 3726: 	    $result.=&Apache::loncommon::start_data_table_row().
                   3727: 		'<td align="right">&nbsp;'.$updateCtr.'&nbsp;</td>'.$line.
                   3728: 		&Apache::loncommon::end_data_table_row();
1.126     ng       3729: 	    $updateCtr++;
1.93      albertel 3730: 	} else {
1.477     albertel 3731: 	    push(@noupdate,
                   3732: 		 '<td align="right">&nbsp;'.$noupdateCtr.'&nbsp;</td>'.$line);
1.126     ng       3733: 	    $noupdateCtr++;
1.44      ng       3734: 	}
1.269     raeburn  3735:         if ($aggregateflag) {
                   3736:             &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
1.301     albertel 3737: 				  $cdom,$cnum);
1.269     raeburn  3738:         }
1.93      albertel 3739:     }
1.477     albertel 3740:     if (@noupdate) {
1.126     ng       3741: #	my $numcols=(scalar(@partid)*(scalar(@parts)-1)*2)+3;
                   3742: 	my $numcols=scalar(@partid)*4+2;
1.477     albertel 3743: 	$result .= &Apache::loncommon::start_data_table_row('LC_empty_row').
1.478     albertel 3744: 	    '<td align="center" colspan="'.$numcols.'">'.
                   3745: 	    &mt('No Changes Occurred For the Students Below').
                   3746: 	    '</td>'.
1.477     albertel 3747: 	    &Apache::loncommon::end_data_table_row();
                   3748: 	foreach my $line (@noupdate) {
                   3749: 	    $result.=
                   3750: 		&Apache::loncommon::start_data_table_row().
                   3751: 		$line.
                   3752: 		&Apache::loncommon::end_data_table_row();
                   3753: 	}
1.44      ng       3754:     }
1.477     albertel 3755:     $result .= &Apache::loncommon::end_data_table().
                   3756: 	&show_grading_menu_form($symb);
1.478     albertel 3757:     my $msg = '<p><b>'.
                   3758: 	&mt('Number of records updated = [_1] for [quant,_2,student].',
                   3759: 	    $rec_update,$count).'</b><br />'.
                   3760: 	'<b>'.&mt('Total number of students = [_1]',$env{'form.total'}).
                   3761: 	'</b></p>';
1.44      ng       3762:     return $title.$msg.$result;
1.5       albertel 3763: }
1.54      albertel 3764: 
                   3765: sub split_part_type {
                   3766:     my ($partstr) = @_;
                   3767:     my ($temp,@allparts)=split(/_/,$partstr);
                   3768:     my $type=pop(@allparts);
1.439     albertel 3769:     my $part=join('_',@allparts);
1.54      albertel 3770:     return ($part,$type);
                   3771: }
                   3772: 
1.44      ng       3773: #------------- end of section for handling grading by section/class ---------
                   3774: #
                   3775: #----------------------------------------------------------------------------
                   3776: 
1.5       albertel 3777: 
1.44      ng       3778: #----------------------------------------------------------------------------
                   3779: #
                   3780: #-------------------------- Next few routines handles grading by csv upload
                   3781: #
                   3782: #--- Javascript to handle csv upload
1.27      albertel 3783: sub csvupload_javascript_reverse_associate {
1.573     bisitz   3784:     my $error1=&mt('You need to specify the username or the student/employee ID');
1.246     albertel 3785:     my $error2=&mt('You need to specify at least one grading field');
1.27      albertel 3786:   return(<<ENDPICK);
                   3787:   function verify(vf) {
                   3788:     var foundsomething=0;
                   3789:     var founduname=0;
1.243     albertel 3790:     var foundID=0;
1.27      albertel 3791:     for (i=0;i<=vf.nfields.value;i++) {
                   3792:       tw=eval('vf.f'+i+'.selectedIndex');
1.243     albertel 3793:       if (i==0 && tw!=0) { foundID=1; }
                   3794:       if (i==1 && tw!=0) { founduname=1; }
                   3795:       if (i!=0 && i!=1 && i!=2 && tw!=0) { foundsomething=1; }
1.27      albertel 3796:     }
1.246     albertel 3797:     if (founduname==0 && foundID==0) {
                   3798: 	alert('$error1');
                   3799: 	return;
1.27      albertel 3800:     }
                   3801:     if (foundsomething==0) {
1.246     albertel 3802: 	alert('$error2');
                   3803: 	return;
1.27      albertel 3804:     }
                   3805:     vf.submit();
                   3806:   }
                   3807:   function flip(vf,tf) {
                   3808:     var nw=eval('vf.f'+tf+'.selectedIndex');
                   3809:     var i;
                   3810:     for (i=0;i<=vf.nfields.value;i++) {
                   3811:       //can not pick the same destination field for both name and domain
                   3812:       if (((i ==0)||(i ==1)) && 
                   3813:           ((tf==0)||(tf==1)) && 
                   3814:           (i!=tf) &&
                   3815:           (eval('vf.f'+i+'.selectedIndex')==nw)) {
                   3816:         eval('vf.f'+i+'.selectedIndex=0;')
                   3817:       }
                   3818:     }
                   3819:   }
                   3820: ENDPICK
                   3821: }
                   3822: 
                   3823: sub csvupload_javascript_forward_associate {
1.573     bisitz   3824:     my $error1=&mt('You need to specify the username or the student/employee ID');
1.246     albertel 3825:     my $error2=&mt('You need to specify at least one grading field');
1.27      albertel 3826:   return(<<ENDPICK);
                   3827:   function verify(vf) {
                   3828:     var foundsomething=0;
                   3829:     var founduname=0;
1.243     albertel 3830:     var foundID=0;
1.27      albertel 3831:     for (i=0;i<=vf.nfields.value;i++) {
                   3832:       tw=eval('vf.f'+i+'.selectedIndex');
1.243     albertel 3833:       if (tw==1) { foundID=1; }
                   3834:       if (tw==2) { founduname=1; }
                   3835:       if (tw>3) { foundsomething=1; }
1.27      albertel 3836:     }
1.246     albertel 3837:     if (founduname==0 && foundID==0) {
                   3838: 	alert('$error1');
                   3839: 	return;
1.27      albertel 3840:     }
                   3841:     if (foundsomething==0) {
1.246     albertel 3842: 	alert('$error2');
                   3843: 	return;
1.27      albertel 3844:     }
                   3845:     vf.submit();
                   3846:   }
                   3847:   function flip(vf,tf) {
                   3848:     var nw=eval('vf.f'+tf+'.selectedIndex');
                   3849:     var i;
                   3850:     //can not pick the same destination field twice
                   3851:     for (i=0;i<=vf.nfields.value;i++) {
                   3852:       if ((i!=tf) && (eval('vf.f'+i+'.selectedIndex')==nw)) {
                   3853:         eval('vf.f'+i+'.selectedIndex=0;')
                   3854:       }
                   3855:     }
                   3856:   }
                   3857: ENDPICK
                   3858: }
                   3859: 
1.26      albertel 3860: sub csvuploadmap_header {
1.324     albertel 3861:     my ($request,$symb,$datatoken,$distotal)= @_;
1.41      ng       3862:     my $javascript;
1.257     albertel 3863:     if ($env{'form.upfile_associate'} eq 'reverse') {
1.41      ng       3864: 	$javascript=&csvupload_javascript_reverse_associate();
                   3865:     } else {
                   3866: 	$javascript=&csvupload_javascript_forward_associate();
                   3867:     }
1.45      ng       3868: 
1.598     www      3869: #    my ($result) = &showResourceInfo($symb,$env{'form.probTitle'});
                   3870:     my $result='';
1.257     albertel 3871:     my $checked=(($env{'form.noFirstLine'})?' checked="checked"':'');
1.245     albertel 3872:     my $ignore=&mt('Ignore First Line');
1.418     albertel 3873:     $symb = &Apache::lonenc::check_encrypt($symb);
1.41      ng       3874:     $request->print(<<ENDPICK);
1.26      albertel 3875: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
1.398     albertel 3876: <h3><span class="LC_info">Uploading Class Grades</span></h3>
1.45      ng       3877: $result
1.326     albertel 3878: <hr />
1.26      albertel 3879: <h3>Identify fields</h3>
                   3880: Total number of records found in file: $distotal <hr />
                   3881: Enter as many fields as you can. The system will inform you and bring you back
                   3882: to this page if the data selected is insufficient to run your class.<hr />
1.589     bisitz   3883: <input type="button" value="Reverse Association" onclick="javascript:this.form.associate.value='Reverse Association';submit(this.form);" />
1.245     albertel 3884: <label><input type="checkbox" name="noFirstLine" $checked />$ignore</label>
1.26      albertel 3885: <input type="hidden" name="associate"  value="" />
                   3886: <input type="hidden" name="phase"      value="three" />
                   3887: <input type="hidden" name="datatoken"  value="$datatoken" />
1.257     albertel 3888: <input type="hidden" name="fileupload" value="$env{'form.fileupload'}" />
                   3889: <input type="hidden" name="upfiletype" value="$env{'form.upfiletype'}" />
1.26      albertel 3890: <input type="hidden" name="upfile_associate" 
1.257     albertel 3891:                                        value="$env{'form.upfile_associate'}" />
1.26      albertel 3892: <input type="hidden" name="symb"       value="$symb" />
1.257     albertel 3893: <input type="hidden" name="saveState"  value="$env{'form.saveState'}" />
                   3894: <input type="hidden" name="probTitle"  value="$env{'form.probTitle'}" />
1.246     albertel 3895: <input type="hidden" name="command"    value="csvuploadoptions" />
1.26      albertel 3896: <hr />
                   3897: ENDPICK
1.597     wenzelju 3898:     $request->print(&Apache::lonhtmlcommon::scripttag($javascript));
1.118     ng       3899:     return '';
1.26      albertel 3900: 
                   3901: }
                   3902: 
                   3903: sub csvupload_fields {
1.582     raeburn  3904:     my ($symb,$errorref) = @_;
                   3905:     my (@parts) = &getpartlist($symb,$errorref);
                   3906:     if (ref($errorref)) {
                   3907:         if ($$errorref) {
                   3908:             return;
                   3909:         }
                   3910:     }
                   3911: 
1.556     weissno  3912:     my @fields=(['ID','Student/Employee ID'],
1.243     albertel 3913: 		['username','Student Username'],
                   3914: 		['domain','Student Domain']);
1.324     albertel 3915:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
1.41      ng       3916:     foreach my $part (sort(@parts)) {
                   3917: 	my @datum;
                   3918: 	my $display=&Apache::lonnet::metadata($url,$part.'.display');
                   3919: 	my $name=$part;
                   3920: 	if  (!$display) { $display = $name; }
                   3921: 	@datum=($name,$display);
1.244     albertel 3922: 	if ($name=~/^stores_(.*)_awarded/) {
                   3923: 	    push(@fields,['stores_'.$1.'_points',"Points [Part: $1]"]);
                   3924: 	}
1.41      ng       3925: 	push(@fields,\@datum);
                   3926:     }
                   3927:     return (@fields);
1.26      albertel 3928: }
                   3929: 
                   3930: sub csvuploadmap_footer {
1.41      ng       3931:     my ($request,$i,$keyfields) =@_;
                   3932:     $request->print(<<ENDPICK);
1.26      albertel 3933: </table>
                   3934: <input type="hidden" name="nfields" value="$i" />
                   3935: <input type="hidden" name="keyfields" value="$keyfields" />
1.589     bisitz   3936: <input type="button" onclick="javascript:verify(this.form)" value="Assign Grades" /><br />
1.26      albertel 3937: </form>
                   3938: ENDPICK
                   3939: }
                   3940: 
1.283     albertel 3941: sub checkforfile_js {
1.539     riegler  3942:     my $alertmsg = &mt('Please use the browse button to select a file from your local directory.');
1.597     wenzelju 3943:     my $result = &Apache::lonhtmlcommon::scripttag(<<CSVFORMJS);
1.86      ng       3944:     function checkUpload(formname) {
                   3945: 	if (formname.upfile.value == "") {
1.539     riegler  3946: 	    alert("$alertmsg");
1.86      ng       3947: 	    return false;
                   3948: 	}
                   3949: 	formname.submit();
                   3950:     }
                   3951: CSVFORMJS
1.283     albertel 3952:     return $result;
                   3953: }
                   3954: 
                   3955: sub upcsvScores_form {
                   3956:     my ($request) = shift;
1.324     albertel 3957:     my ($symb)=&get_symb($request);
1.283     albertel 3958:     if (!$symb) {return '';}
                   3959:     my $result=&checkforfile_js();
1.257     albertel 3960:     $env{'form.probTitle'} = &Apache::lonnet::gettitle($symb);
1.598     www      3961: #    my ($table) = &showResourceInfo($symb,$env{'form.probTitle'});
                   3962: #    $result.=$table;
1.326     albertel 3963:     $result.='<br /><table width="100%" border="0"><tr><td bgcolor="#777777">'."\n";
                   3964:     $result.='<table width="100%" border="0"><tr bgcolor="#e6ffff"><td>'."\n";
1.538     schulted 3965:     $result.='&nbsp;<b>'.&mt('Specify a file containing the class scores for current resource.').
                   3966: 	'</b></td></tr>'."\n";
1.86      ng       3967:     $result.='<tr bgcolor=#ffffe6><td>'."\n";
1.370     www      3968:     my $upload=&mt("Upload Scores");
1.86      ng       3969:     my $upfile_select=&Apache::loncommon::upfile_select_html();
1.245     albertel 3970:     my $ignore=&mt('Ignore First Line');
1.418     albertel 3971:     $symb = &Apache::lonenc::check_encrypt($symb);
1.86      ng       3972:     $result.=<<ENDUPFORM;
1.106     albertel 3973: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
1.86      ng       3974: <input type="hidden" name="symb" value="$symb" />
                   3975: <input type="hidden" name="command" value="csvuploadmap" />
1.257     albertel 3976: <input type="hidden" name="probTitle" value="$env{'form.probTitle'}" />
                   3977: <input type="hidden" name="saveState"  value="$env{'form.saveState'}" />
1.86      ng       3978: $upfile_select
1.589     bisitz   3979: <br /><input type="button" onclick="javascript:checkUpload(this.form);" value="$upload" />
1.283     albertel 3980: <label><input type="checkbox" name="noFirstLine" />$ignore</label>
1.86      ng       3981: </form>
                   3982: ENDUPFORM
1.370     www      3983:     $result.=&Apache::loncommon::help_open_topic("Course_Convert_To_CSV",
                   3984:                            &mt("How do I create a CSV file from a spreadsheet"))
                   3985:     .'</td></tr></table>'."\n";
1.86      ng       3986:     $result.='</td></tr></table><br /><br />'."\n";
1.324     albertel 3987:     $result.=&show_grading_menu_form($symb);
1.86      ng       3988:     return $result;
                   3989: }
                   3990: 
                   3991: 
1.26      albertel 3992: sub csvuploadmap {
1.41      ng       3993:     my ($request)= @_;
1.324     albertel 3994:     my ($symb)=&get_symb($request);
1.41      ng       3995:     if (!$symb) {return '';}
1.72      ng       3996: 
1.41      ng       3997:     my $datatoken;
1.257     albertel 3998:     if (!$env{'form.datatoken'}) {
1.41      ng       3999: 	$datatoken=&Apache::loncommon::upfile_store($request);
1.26      albertel 4000:     } else {
1.257     albertel 4001: 	$datatoken=$env{'form.datatoken'};
1.41      ng       4002: 	&Apache::loncommon::load_tmp_file($request);
1.26      albertel 4003:     }
1.41      ng       4004:     my @records=&Apache::loncommon::upfile_record_sep();
1.257     albertel 4005:     if ($env{'form.noFirstLine'}) { shift(@records); }
1.324     albertel 4006:     &csvuploadmap_header($request,$symb,$datatoken,$#records+1);
1.41      ng       4007:     my ($i,$keyfields);
                   4008:     if (@records) {
1.582     raeburn  4009:         my $fieldserror;
                   4010: 	my @fields=&csvupload_fields($symb,\$fieldserror);
                   4011:         if ($fieldserror) {
                   4012:             $request->print(&navmap_errormsg());
                   4013:             return;
                   4014:         }
1.257     albertel 4015: 	if ($env{'form.upfile_associate'} eq 'reverse') {	
1.41      ng       4016: 	    &Apache::loncommon::csv_print_samples($request,\@records);
                   4017: 	    $i=&Apache::loncommon::csv_print_select_table($request,\@records,
                   4018: 							  \@fields);
                   4019: 	    foreach (@fields) { $keyfields.=$_->[0].','; }
                   4020: 	    chop($keyfields);
                   4021: 	} else {
                   4022: 	    unshift(@fields,['none','']);
                   4023: 	    $i=&Apache::loncommon::csv_samples_select_table($request,\@records,
                   4024: 							    \@fields);
1.311     banghart 4025:             foreach my $rec (@records) {
                   4026:                 my %temp = &Apache::loncommon::record_sep($rec);
                   4027:                 if (%temp) {
                   4028:                     $keyfields=join(',',sort(keys(%temp)));
                   4029:                     last;
                   4030:                 }
                   4031:             }
1.41      ng       4032: 	}
                   4033:     }
                   4034:     &csvuploadmap_footer($request,$i,$keyfields);
1.324     albertel 4035:     $request->print(&show_grading_menu_form($symb));
1.72      ng       4036: 
1.41      ng       4037:     return '';
1.27      albertel 4038: }
                   4039: 
1.246     albertel 4040: sub csvuploadoptions {
1.41      ng       4041:     my ($request)= @_;
1.324     albertel 4042:     my ($symb)=&get_symb($request);
1.257     albertel 4043:     my $checked=(($env{'form.noFirstLine'})?'1':'0');
1.246     albertel 4044:     my $ignore=&mt('Ignore First Line');
                   4045:     $request->print(<<ENDPICK);
                   4046: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
1.398     albertel 4047: <h3><span class="LC_info">Uploading Class Grade Options</span></h3>
1.246     albertel 4048: <input type="hidden" name="command"    value="csvuploadassign" />
1.302     albertel 4049: <!--
1.246     albertel 4050: <p>
                   4051: <label>
                   4052:    <input type="checkbox" name="show_full_results" />
                   4053:    Show a table of all changes
                   4054: </label>
                   4055: </p>
1.302     albertel 4056: -->
1.246     albertel 4057: <p>
                   4058: <label>
                   4059:    <input type="checkbox" name="overwite_scores" checked="checked" />
                   4060:    Overwrite any existing score
                   4061: </label>
                   4062: </p>
                   4063: ENDPICK
                   4064:     my %fields=&get_fields();
                   4065:     if (!defined($fields{'domain'})) {
1.257     albertel 4066: 	my $domform = &Apache::loncommon::select_dom_form($env{'request.role.domain'},'default_domain');
1.246     albertel 4067: 	$request->print("\n<p> Users are in domain: ".$domform."</p>\n");
                   4068:     }
1.257     albertel 4069:     foreach my $key (sort(keys(%env))) {
1.246     albertel 4070: 	if ($key !~ /^form\.(.*)$/) { next; }
                   4071: 	my $cleankey=$1;
                   4072: 	if ($cleankey eq 'command') { next; }
                   4073: 	$request->print('<input type="hidden" name="'.$cleankey.
1.257     albertel 4074: 			'"  value="'.$env{$key}.'" />'."\n");
1.246     albertel 4075:     }
                   4076:     # FIXME do a check for any duplicated user ids...
                   4077:     # FIXME do a check for any invalid user ids?...
1.290     albertel 4078:     $request->print('<input type="submit" value="Assign Grades" /><br />
                   4079: <hr /></form>'."\n");
1.324     albertel 4080:     $request->print(&show_grading_menu_form($symb));
1.246     albertel 4081:     return '';
                   4082: }
                   4083: 
                   4084: sub get_fields {
                   4085:     my %fields;
1.257     albertel 4086:     my @keyfields = split(/\,/,$env{'form.keyfields'});
                   4087:     for (my $i=0; $i<=$env{'form.nfields'}; $i++) {
                   4088: 	if ($env{'form.upfile_associate'} eq 'reverse') {
                   4089: 	    if ($env{'form.f'.$i} ne 'none') {
                   4090: 		$fields{$keyfields[$i]}=$env{'form.f'.$i};
1.41      ng       4091: 	    }
                   4092: 	} else {
1.257     albertel 4093: 	    if ($env{'form.f'.$i} ne 'none') {
                   4094: 		$fields{$env{'form.f'.$i}}=$keyfields[$i];
1.41      ng       4095: 	    }
                   4096: 	}
1.27      albertel 4097:     }
1.246     albertel 4098:     return %fields;
                   4099: }
                   4100: 
                   4101: sub csvuploadassign {
                   4102:     my ($request)= @_;
1.324     albertel 4103:     my ($symb)=&get_symb($request);
1.246     albertel 4104:     if (!$symb) {return '';}
1.345     bowersj2 4105:     my $error_msg = '';
1.246     albertel 4106:     &Apache::loncommon::load_tmp_file($request);
                   4107:     my @gradedata = &Apache::loncommon::upfile_record_sep();
1.257     albertel 4108:     if ($env{'form.noFirstLine'}) { shift(@gradedata); }
1.246     albertel 4109:     my %fields=&get_fields();
1.41      ng       4110:     $request->print('<h3>Assigning Grades</h3>');
1.257     albertel 4111:     my $courseid=$env{'request.course.id'};
1.97      albertel 4112:     my ($classlist) = &getclasslist('all',0);
1.106     albertel 4113:     my @notallowed;
1.41      ng       4114:     my @skipped;
                   4115:     my $countdone=0;
                   4116:     foreach my $grade (@gradedata) {
                   4117: 	my %entries=&Apache::loncommon::record_sep($grade);
1.246     albertel 4118: 	my $domain;
                   4119: 	if ($entries{$fields{'domain'}}) {
                   4120: 	    $domain=$entries{$fields{'domain'}};
                   4121: 	} else {
1.257     albertel 4122: 	    $domain=$env{'form.default_domain'};
1.246     albertel 4123: 	}
1.243     albertel 4124: 	$domain=~s/\s//g;
1.41      ng       4125: 	my $username=$entries{$fields{'username'}};
1.160     albertel 4126: 	$username=~s/\s//g;
1.243     albertel 4127: 	if (!$username) {
                   4128: 	    my $id=$entries{$fields{'ID'}};
1.247     albertel 4129: 	    $id=~s/\s//g;
1.243     albertel 4130: 	    my %ids=&Apache::lonnet::idget($domain,$id);
                   4131: 	    $username=$ids{$id};
                   4132: 	}
1.41      ng       4133: 	if (!exists($$classlist{"$username:$domain"})) {
1.247     albertel 4134: 	    my $id=$entries{$fields{'ID'}};
                   4135: 	    $id=~s/\s//g;
                   4136: 	    if ($id) {
                   4137: 		push(@skipped,"$id:$domain");
                   4138: 	    } else {
                   4139: 		push(@skipped,"$username:$domain");
                   4140: 	    }
1.41      ng       4141: 	    next;
                   4142: 	}
1.108     albertel 4143: 	my $usec=$classlist->{"$username:$domain"}[5];
1.106     albertel 4144: 	if (!&canmodify($usec)) {
                   4145: 	    push(@notallowed,"$username:$domain");
                   4146: 	    next;
                   4147: 	}
1.244     albertel 4148: 	my %points;
1.41      ng       4149: 	my %grades;
                   4150: 	foreach my $dest (keys(%fields)) {
1.244     albertel 4151: 	    if ($dest eq 'ID' || $dest eq 'username' ||
                   4152: 		$dest eq 'domain') { next; }
                   4153: 	    if ($entries{$fields{$dest}} =~ /^\s*$/) { next; }
                   4154: 	    if ($dest=~/stores_(.*)_points/) {
                   4155: 		my $part=$1;
                   4156: 		my $wgt =&Apache::lonnet::EXT('resource.'.$part.'.weight',
                   4157: 					      $symb,$domain,$username);
1.345     bowersj2 4158:                 if ($wgt) {
                   4159:                     $entries{$fields{$dest}}=~s/\s//g;
                   4160:                     my $pcr=$entries{$fields{$dest}} / $wgt;
1.463     albertel 4161:                     my $award=($pcr == 0) ? 'incorrect_by_override'
                   4162:                                           : 'correct_by_override';
1.345     bowersj2 4163:                     $grades{"resource.$part.awarded"}=$pcr;
                   4164:                     $grades{"resource.$part.solved"}=$award;
                   4165:                     $points{$part}=1;
                   4166:                 } else {
                   4167:                     $error_msg = "<br />" .
                   4168:                         &mt("Some point values were assigned"
                   4169:                             ." for problems with a weight "
                   4170:                             ."of zero. These values were "
                   4171:                             ."ignored.");
                   4172:                 }
1.244     albertel 4173: 	    } else {
                   4174: 		if ($dest=~/stores_(.*)_awarded/) { if ($points{$1}) {next;} }
                   4175: 		if ($dest=~/stores_(.*)_solved/)  { if ($points{$1}) {next;} }
                   4176: 		my $store_key=$dest;
                   4177: 		$store_key=~s/^stores/resource/;
                   4178: 		$store_key=~s/_/\./g;
                   4179: 		$grades{$store_key}=$entries{$fields{$dest}};
                   4180: 	    }
1.41      ng       4181: 	}
1.508     www      4182: 	if (! %grades) { 
                   4183:            push(@skipped,&mt("[_1]: no data to save","$username:$domain")); 
                   4184:         } else {
                   4185: 	   $grades{"resource.regrader"}="$env{'user.name'}:$env{'user.domain'}";
                   4186: 	   my $result=&Apache::lonnet::cstore(\%grades,$symb,
1.302     albertel 4187: 					   $env{'request.course.id'},
                   4188: 					   $domain,$username);
1.508     www      4189: 	   if ($result eq 'ok') {
                   4190: 	      $request->print('.');
                   4191: 	   } else {
                   4192: 	      $request->print("<p><span class=\"LC_error\">".
                   4193:                               &mt("Failed to save data for student [_1]. Message when trying to save was: [_2]",
                   4194:                                   "$username:$domain",$result)."</span></p>");
                   4195: 	   }
                   4196: 	   $request->rflush();
                   4197: 	   $countdone++;
                   4198:         }
1.41      ng       4199:     }
1.570     www      4200:     $request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt("Saved scores for [quant,_1,student]",$countdone),$countdone==0));
1.41      ng       4201:     if (@skipped) {
1.571     www      4202: 	$request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt('No scores stored for the following username(s):'),1).'<br />');
                   4203:         $request->print(join(', ',@skipped));
1.106     albertel 4204:     }
                   4205:     if (@notallowed) {
1.571     www      4206: 	$request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt('Modification of scores not allowed for the following username(s):'),1).'<br />');
                   4207: 	$request->print(join(', ',@notallowed));
1.41      ng       4208:     }
1.106     albertel 4209:     $request->print("<br />\n");
1.324     albertel 4210:     $request->print(&show_grading_menu_form($symb));
1.345     bowersj2 4211:     return $error_msg;
1.26      albertel 4212: }
1.44      ng       4213: #------------- end of section for handling csv file upload ---------
                   4214: #
                   4215: #-------------------------------------------------------------------
                   4216: #
1.122     ng       4217: #-------------- Next few routines handle grading by page/sequence
1.72      ng       4218: #
                   4219: #--- Select a page/sequence and a student to grade
1.68      ng       4220: sub pickStudentPage {
                   4221:     my ($request) = shift;
                   4222: 
1.539     riegler  4223:     my $alertmsg = &mt('Please select the student you wish to grade.');
1.597     wenzelju 4224:     $request->print(&Apache::lonhtmlcommon::scripttag(<<LISTJAVASCRIPT));
1.68      ng       4225: 
                   4226: function checkPickOne(formname) {
1.76      ng       4227:     if (radioSelection(formname.student) == null) {
1.539     riegler  4228: 	alert("$alertmsg");
1.68      ng       4229: 	return;
                   4230:     }
1.125     ng       4231:     ptr = pullDownSelection(formname.selectpage);
                   4232:     formname.page.value = formname["page"+ptr].value;
                   4233:     formname.title.value = formname["title"+ptr].value;
1.68      ng       4234:     formname.submit();
                   4235: }
                   4236: 
                   4237: LISTJAVASCRIPT
1.118     ng       4238:     &commonJSfunctions($request);
1.324     albertel 4239:     my ($symb) = &get_symb($request);
1.257     albertel 4240:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
                   4241:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
                   4242:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
1.68      ng       4243: 
1.398     albertel 4244:     my $result='<h3><span class="LC_info">&nbsp;'.
1.485     albertel 4245: 	&mt('Manual Grading by Page or Sequence').'</span></h3>';
1.68      ng       4246: 
1.80      ng       4247:     $result.='<form action="/adm/grades" method="post" name="displayPage">'."\n";
1.582     raeburn  4248:     my $map_error;
                   4249:     my ($titles,$symbx) = &getSymbMap($map_error);
                   4250:     if ($map_error) {
                   4251:         $request->print(&navmap_errormsg());
                   4252:         return; 
                   4253:     }
1.137     albertel 4254:     my ($curpage) =&Apache::lonnet::decode_symb($symb); 
                   4255: #    my ($curpage,$mapId) =&Apache::lonnet::decode_symb($symb); 
                   4256: #    my $type=($curpage =~ /\.(page|sequence)/);
1.485     albertel 4257:     my $select = '<select name="selectpage">'."\n";
1.70      ng       4258:     my $ctr=0;
1.68      ng       4259:     foreach (@$titles) {
                   4260: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
1.485     albertel 4261: 	$select.='<option value="'.$ctr.'" '.
1.401     albertel 4262: 	    ($$symbx{$_} =~ /$curpage$/ ? 'selected="selected"' : '').
1.71      ng       4263: 	    '>'.$showtitle.'</option>'."\n";
1.70      ng       4264: 	$ctr++;
1.68      ng       4265:     }
1.485     albertel 4266:     $select.= '</select>';
1.539     riegler  4267:     $result.='&nbsp;<b>'.&mt('Problems from').':</b> '.$select."<br />\n";
1.485     albertel 4268: 
1.70      ng       4269:     $ctr=0;
                   4270:     foreach (@$titles) {
                   4271: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
                   4272: 	$result.='<input type="hidden" name="page'.$ctr.'" value="'.$$symbx{$_}.'" />'."\n";
                   4273: 	$result.='<input type="hidden" name="title'.$ctr.'" value="'.$showtitle.'" />'."\n";
                   4274: 	$ctr++;
                   4275:     }
1.72      ng       4276:     $result.='<input type="hidden" name="page" />'."\n".
                   4277: 	'<input type="hidden" name="title" />'."\n";
1.68      ng       4278: 
1.485     albertel 4279:     my $options =
                   4280: 	'<label><input type="radio" name="vProb" value="no" checked="checked" /> '.&mt('no').' </label>'."\n".
                   4281: 	'<label><input type="radio" name="vProb" value="yes" /> '.&mt('yes').' </label>'."<br />\n";
1.539     riegler  4282:     $result.='&nbsp;<b>'.&mt('View Problem Text').': </b>'.$options;
1.485     albertel 4283: 
                   4284:     $options =
                   4285: 	'<label><input type="radio" name="lastSub" value="none" /> '.&mt('none').' </label>'."\n".
                   4286: 	'<label><input type="radio" name="lastSub" value="datesub" checked="checked" /> '.&mt('by dates and submissions').'</label>'."\n".
                   4287: 	'<label><input type="radio" name="lastSub" value="all" /> '.&mt('all details').' </label>'."\n";
1.539     riegler  4288:     $result.='&nbsp;<b>'.&mt('Submissions').': </b>'.$options;
1.432     banghart 4289:     
                   4290:     $result.=&build_section_inputs();
1.442     banghart 4291:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
                   4292:     $result.='<input type="hidden" name="Status"  value="'.$stu_status.'" />'."\n".
1.72      ng       4293: 	'<input type="hidden" name="command" value="displayPage" />'."\n".
1.418     albertel 4294: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.257     albertel 4295: 	'<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."<br />\n";
1.72      ng       4296: 
1.539     riegler  4297:     $result.='&nbsp;<b>'.&mt('Use CODE').': </b> <input type="text" name="CODE" value="" /> <br />'."\n";
1.382     albertel 4298: 
1.80      ng       4299:     $result.='&nbsp;<input type="button" '.
1.589     bisitz   4300:              'onclick="javascript:checkPickOne(this.form);" value="'.&mt('Next').' &rarr;" /><br />'."\n";
1.72      ng       4301: 
1.68      ng       4302:     $request->print($result);
                   4303: 
1.485     albertel 4304:     my $studentTable.='&nbsp;<b>'.&mt('Select a student you wish to grade and then click on the Next button.').'</b><br />'.
1.484     albertel 4305: 	&Apache::loncommon::start_data_table().
                   4306: 	&Apache::loncommon::start_data_table_header_row().
1.485     albertel 4307: 	'<th align="right">&nbsp;'.&mt('No.').'</th>'.
1.484     albertel 4308: 	'<th>'.&nameUserString('header').'</th>'.
1.485     albertel 4309: 	'<th align="right">&nbsp;'.&mt('No.').'</th>'.
1.484     albertel 4310: 	'<th>'.&nameUserString('header').'</th>'.
                   4311: 	&Apache::loncommon::end_data_table_header_row();
1.68      ng       4312:  
1.76      ng       4313:     my (undef,undef,$fullname) = &getclasslist($getsec,'1');
1.68      ng       4314:     my $ptr = 1;
1.294     albertel 4315:     foreach my $student (sort 
                   4316: 			 {
                   4317: 			     if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                   4318: 				 return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                   4319: 			     }
                   4320: 			     return $a cmp $b;
                   4321: 			 } (keys(%$fullname))) {
1.68      ng       4322: 	my ($uname,$udom) = split(/:/,$student);
1.484     albertel 4323: 	$studentTable.=($ptr%2==1 ? &Apache::loncommon::start_data_table_row()
                   4324:                                   : '</td>');
1.126     ng       4325: 	$studentTable.='<td align="right">'.$ptr.'&nbsp;</td>';
1.288     albertel 4326: 	$studentTable.='<td>&nbsp;<label><input type="radio" name="student" value="'.$student.'" /> '
                   4327: 	    .&nameUserString(undef,$$fullname{$student},$uname,$udom)."</label>\n";
1.484     albertel 4328: 	$studentTable.=
                   4329: 	    ($ptr%2 == 0 ? '</td>'.&Apache::loncommon::end_data_table_row() 
                   4330:                          : '');
1.68      ng       4331: 	$ptr++;
                   4332:     }
1.484     albertel 4333:     if ($ptr%2 == 0) {
                   4334: 	$studentTable.='</td><td>&nbsp;</td><td>&nbsp;</td>'.
                   4335: 	    &Apache::loncommon::end_data_table_row();
                   4336:     }
                   4337:     $studentTable.=&Apache::loncommon::end_data_table()."\n";
1.126     ng       4338:     $studentTable.='<input type="button" '.
1.589     bisitz   4339:                    'onclick="javascript:checkPickOne(this.form);" value="'.&mt('Next').' &rarr;" /></form>'."\n";
1.68      ng       4340: 
1.324     albertel 4341:     $studentTable.=&show_grading_menu_form($symb);
1.68      ng       4342:     $request->print($studentTable);
                   4343: 
                   4344:     return '';
                   4345: }
                   4346: 
                   4347: sub getSymbMap {
1.582     raeburn  4348:     my ($map_error) = @_;
1.132     bowersj2 4349:     my $navmap = Apache::lonnavmaps::navmap->new();
1.582     raeburn  4350:     unless (ref($navmap)) {
                   4351:         if (ref($map_error)) {
                   4352:             $$map_error = 'navmap';
                   4353:         }
                   4354:         return;
                   4355:     }
1.68      ng       4356:     my %symbx = ();
                   4357:     my @titles = ();
1.117     bowersj2 4358:     my $minder = 0;
                   4359: 
                   4360:     # Gather every sequence that has problems.
1.240     albertel 4361:     my @sequences = $navmap->retrieveResources(undef, sub { shift->is_map(); },
                   4362: 					       1,0,1);
1.117     bowersj2 4363:     for my $sequence ($navmap->getById('0.0'), @sequences) {
1.241     albertel 4364: 	if ($navmap->hasResource($sequence, sub { shift->is_problem(); }, 0) ) {
1.381     albertel 4365: 	    my $title = $minder.'.'.
                   4366: 		&HTML::Entities::encode($sequence->compTitle(),'"\'&');
                   4367: 	    push(@titles, $title); # minder in case two titles are identical
                   4368: 	    $symbx{$title} = &HTML::Entities::encode($sequence->symb(),'"\'&');
1.117     bowersj2 4369: 	    $minder++;
1.241     albertel 4370: 	}
1.68      ng       4371:     }
                   4372:     return \@titles,\%symbx;
                   4373: }
                   4374: 
1.72      ng       4375: #
                   4376: #--- Displays a page/sequence w/wo problems, w/wo submissions
1.68      ng       4377: sub displayPage {
                   4378:     my ($request) = shift;
                   4379: 
1.324     albertel 4380:     my ($symb) = &get_symb($request);
1.257     albertel 4381:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
                   4382:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
                   4383:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
                   4384:     my $pageTitle = $env{'form.page'};
1.103     albertel 4385:     my ($classlist,undef,$fullname) = &getclasslist($getsec,'1');
1.257     albertel 4386:     my ($uname,$udom) = split(/:/,$env{'form.student'});
                   4387:     my $usec=$classlist->{$env{'form.student'}}[5];
1.168     albertel 4388: 
                   4389:     #need to make sure we have the correct data for later EXT calls, 
                   4390:     #thus invalidate the cache
                   4391:     &Apache::lonnet::devalidatecourseresdata(
1.257     albertel 4392:                  $env{'course.'.$env{'request.course.id'}.'.num'},
                   4393:                  $env{'course.'.$env{'request.course.id'}.'.domain'});
1.168     albertel 4394:     &Apache::lonnet::clear_EXT_cache_status();
                   4395: 
1.103     albertel 4396:     if (!&canview($usec)) {
1.485     albertel 4397: 	$request->print('<span class="LC_warning">'.&mt('Unable to view requested student. ([_1])',$env{'form.student'}).'</span>');
1.324     albertel 4398: 	$request->print(&show_grading_menu_form($symb));
1.103     albertel 4399: 	return;
                   4400:     }
1.398     albertel 4401:     my $result='<h3><span class="LC_info">&nbsp;'.$env{'form.title'}.'</span></h3>';
1.485     albertel 4402:     $result.='<h3>&nbsp;'.&mt('Student: [_1]',&nameUserString(undef,$$fullname{$env{'form.student'}},$uname,$udom)).
1.129     ng       4403: 	'</h3>'."\n";
1.500     albertel 4404:     $env{'form.CODE'} = uc($env{'form.CODE'});
1.501     foxr     4405:     if (&Apache::lonnet::validCODE(uc($env{'form.CODE'}))) {
1.485     albertel 4406: 	$result.='<h3>&nbsp;'.&mt('CODE: [_1]',$env{'form.CODE'}).'</h3>'."\n";
1.382     albertel 4407:     } else {
                   4408: 	delete($env{'form.CODE'});
                   4409:     }
1.71      ng       4410:     &sub_page_js($request);
                   4411:     $request->print($result);
                   4412: 
1.132     bowersj2 4413:     my $navmap = Apache::lonnavmaps::navmap->new();
1.582     raeburn  4414:     unless (ref($navmap)) {
                   4415:         $request->print(&navmap_errormsg());
                   4416:         $request->print(&show_grading_menu_form($symb));
                   4417:         return;
                   4418:     }
1.257     albertel 4419:     my ($mapUrl, $id, $resUrl)=&Apache::lonnet::decode_symb($env{'form.page'});
1.68      ng       4420:     my $map = $navmap->getResourceByUrl($resUrl); # add to navmaps
1.288     albertel 4421:     if (!$map) {
1.485     albertel 4422: 	$request->print('<span class="LC_warning">'.&mt('Unable to view requested sequence. ([_1])',$resUrl).'</span>');
1.324     albertel 4423: 	$request->print(&show_grading_menu_form($symb));
1.288     albertel 4424: 	return; 
                   4425:     }
1.68      ng       4426:     my $iterator = $navmap->getIterator($map->map_start(),
                   4427: 					$map->map_finish());
                   4428: 
1.71      ng       4429:     my $studentTable='<form action="/adm/grades" method="post" name="gradePage">'."\n".
1.72      ng       4430: 	'<input type="hidden" name="command" value="gradeByPage" />'."\n".
1.257     albertel 4431: 	'<input type="hidden" name="fullname" value="'.$$fullname{$env{'form.student'}}.'" />'."\n".
                   4432: 	'<input type="hidden" name="student" value="'.$env{'form.student'}.'" />'."\n".
1.72      ng       4433: 	'<input type="hidden" name="page"    value="'.$pageTitle.'" />'."\n".
1.257     albertel 4434: 	'<input type="hidden" name="title"   value="'.$env{'form.title'}.'" />'."\n".
1.418     albertel 4435: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.125     ng       4436: 	'<input type="hidden" name="overRideScore" value="no" />'."\n".
1.257     albertel 4437: 	'<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n";
1.71      ng       4438: 
1.382     albertel 4439:     if (defined($env{'form.CODE'})) {
                   4440: 	$studentTable.=
                   4441: 	    '<input type="hidden" name="CODE" value="'.$env{'form.CODE'}.'" />'."\n";
                   4442:     }
1.381     albertel 4443:     my $checkIcon = '<img alt="'.&mt('Check Mark').
1.485     albertel 4444: 	'" src="'.&Apache::loncommon::lonhttpdurl($request->dir_config('lonIconsURL').'/check.gif').'" height="16" border="0" />';
1.71      ng       4445: 
1.594     bisitz   4446:     $studentTable.='&nbsp;<span class="LC_info">'.
                   4447:         &mt('Problems graded correct by the computer are marked with a [_1] symbol.',$checkIcon).
                   4448:         '</span>'."\n".
1.484     albertel 4449: 	&Apache::loncommon::start_data_table().
                   4450: 	&Apache::loncommon::start_data_table_header_row().
                   4451: 	'<th align="center">&nbsp;Prob.&nbsp;</th>'.
1.485     albertel 4452: 	'<th>&nbsp;'.($env{'form.vProb'} eq 'no' ? &mt('Title') : &mt('Problem Text')).'/'.&mt('Grade').'</th>'.
1.484     albertel 4453: 	&Apache::loncommon::end_data_table_header_row();
1.71      ng       4454: 
1.329     albertel 4455:     &Apache::lonxml::clear_problem_counter();
1.196     albertel 4456:     my ($depth,$question,$prob) = (1,1,1);
1.68      ng       4457:     $iterator->next(); # skip the first BEGIN_MAP
                   4458:     my $curRes = $iterator->next(); # for "current resource"
1.101     albertel 4459:     while ($depth > 0) {
1.68      ng       4460:         if($curRes == $iterator->BEGIN_MAP) { $depth++; }
1.100     bowersj2 4461:         if($curRes == $iterator->END_MAP) { $depth--; }
1.68      ng       4462: 
1.385     albertel 4463:         if (ref($curRes) && $curRes->is_problem()) {
1.91      albertel 4464: 	    my $parts = $curRes->parts();
1.68      ng       4465:             my $title = $curRes->compTitle();
1.71      ng       4466: 	    my $symbx = $curRes->symb();
1.484     albertel 4467: 	    $studentTable.=
                   4468: 		&Apache::loncommon::start_data_table_row().
                   4469: 		'<td align="center" valign="top" >'.$prob.
1.485     albertel 4470: 		(scalar(@{$parts}) == 1 ? '' 
                   4471: 		                        : '<br />('.&mt('[_1]&nbsp;parts)',
                   4472: 							scalar(@{$parts}))
                   4473: 		 ).
                   4474: 		 '</td>';
1.71      ng       4475: 	    $studentTable.='<td valign="top">';
1.382     albertel 4476: 	    my %form = ('CODE' => $env{'form.CODE'},);
1.257     albertel 4477: 	    if ($env{'form.vProb'} eq 'yes' ) {
1.144     albertel 4478: 		$studentTable.=&show_problem($request,$symbx,$uname,$udom,1,
1.383     albertel 4479: 					     undef,'both',\%form);
1.71      ng       4480: 	    } else {
1.382     albertel 4481: 		my $companswer = &Apache::loncommon::get_student_answers($symbx,$uname,$udom,$env{'request.course.id'},%form);
1.80      ng       4482: 		$companswer =~ s|<form(.*?)>||g;
                   4483: 		$companswer =~ s|</form>||g;
1.71      ng       4484: #		while ($companswer =~ /(<a href\=\"javascript:newWindow.*?Script Vars<\/a>)/s) { #<a href="javascript:newWindow</a>
1.116     ng       4485: #		    $companswer =~ s/$1/ /ms;
1.326     albertel 4486: #		    $request->print('match='.$1."<br />\n");
1.71      ng       4487: #		}
1.116     ng       4488: #		$companswer =~ s|<table border=\"1\">|<table border=\"0\">|g;
1.539     riegler  4489: 		$studentTable.='&nbsp;<b>'.$title.'</b>&nbsp;<br />&nbsp;<b>'.&mt('Correct answer').':</b><br />'.$companswer;
1.71      ng       4490: 	    }
                   4491: 
1.257     albertel 4492: 	    my %record = &Apache::lonnet::restore($symbx,$env{'request.course.id'},$udom,$uname);
1.125     ng       4493: 
1.257     albertel 4494: 	    if ($env{'form.lastSub'} eq 'datesub') {
1.71      ng       4495: 		if ($record{'version'} eq '') {
1.485     albertel 4496: 		    $studentTable.='<br />&nbsp;<span class="LC_warning">'.&mt('No recorded submission for this problem.').'</span><br />';
1.71      ng       4497: 		} else {
1.116     ng       4498: 		    my %responseType = ();
                   4499: 		    foreach my $partid (@{$parts}) {
1.147     albertel 4500: 			my @responseIds =$curRes->responseIds($partid);
                   4501: 			my @responseType =$curRes->responseType($partid);
                   4502: 			my %responseIds;
                   4503: 			for (my $i=0;$i<=$#responseIds;$i++) {
                   4504: 			    $responseIds{$responseIds[$i]}=$responseType[$i];
                   4505: 			}
                   4506: 			$responseType{$partid} = \%responseIds;
1.116     ng       4507: 		    }
1.148     albertel 4508: 		    $studentTable.= &displaySubByDates($symbx,\%record,$parts,\%responseType,$checkIcon,$uname,$udom);
1.147     albertel 4509: 
1.71      ng       4510: 		}
1.257     albertel 4511: 	    } elsif ($env{'form.lastSub'} eq 'all') {
                   4512: 		my $last = ($env{'form.lastSub'} eq 'last' ? 'last' : '');
1.71      ng       4513: 		$studentTable.=&Apache::loncommon::get_previous_attempt($symbx,$uname,$udom,
1.257     albertel 4514: 									$env{'request.course.id'},
1.71      ng       4515: 									'','.submission');
                   4516:  
                   4517: 	    }
1.103     albertel 4518: 	    if (&canmodify($usec)) {
1.585     bisitz   4519:             $studentTable.=&gradeBox_start();
1.103     albertel 4520: 		foreach my $partid (@{$parts}) {
                   4521: 		    $studentTable.=&gradeBox($request,$symbx,$uname,$udom,$question,$partid,\%record);
                   4522: 		    $studentTable.='<input type="hidden" name="q_'.$question.'" value="'.$partid.'" />'."\n";
                   4523: 		    $question++;
                   4524: 		}
1.585     bisitz   4525:             $studentTable.=&gradeBox_end();
1.196     albertel 4526: 		$prob++;
1.71      ng       4527: 	    }
                   4528: 	    $studentTable.='</td></tr>';
1.68      ng       4529: 
1.103     albertel 4530: 	}
1.68      ng       4531:         $curRes = $iterator->next();
                   4532:     }
                   4533: 
1.589     bisitz   4534:     $studentTable.=
                   4535:         '</table>'."\n".
                   4536:         '<input type="button" value="'.&mt('Save').'" '.
                   4537:         'onclick="javascript:checkSubmitPage(this.form,'.$question.');" />'.
                   4538:         '</form>'."\n";
1.324     albertel 4539:     $studentTable.=&show_grading_menu_form($symb);
1.71      ng       4540:     $request->print($studentTable);
                   4541: 
                   4542:     return '';
1.119     ng       4543: }
                   4544: 
                   4545: sub displaySubByDates {
1.148     albertel 4546:     my ($symb,$record,$parts,$responseType,$checkIcon,$uname,$udom) = @_;
1.224     albertel 4547:     my $isCODE=0;
1.335     albertel 4548:     my $isTask = ($symb =~/\.task$/);
1.224     albertel 4549:     if (exists($record->{'resource.CODE'})) { $isCODE=1; }
1.467     albertel 4550:     my $studentTable=&Apache::loncommon::start_data_table().
                   4551: 	&Apache::loncommon::start_data_table_header_row().
                   4552: 	'<th>'.&mt('Date/Time').'</th>'.
                   4553: 	($isCODE?'<th>'.&mt('CODE').'</th>':'').
                   4554: 	'<th>'.&mt('Submission').'</th>'.
                   4555: 	'<th>'.&mt('Status').'</th>'.
                   4556: 	&Apache::loncommon::end_data_table_header_row();
1.119     ng       4557:     my ($version);
                   4558:     my %mark;
1.148     albertel 4559:     my %orders;
1.119     ng       4560:     $mark{'correct_by_student'} = $checkIcon;
1.147     albertel 4561:     if (!exists($$record{'1:timestamp'})) {
1.539     riegler  4562: 	return '<br />&nbsp;<span class="LC_warning">'.&mt('Nothing submitted - no attempts.').'</span><br />';
1.147     albertel 4563:     }
1.335     albertel 4564: 
                   4565:     my $interaction;
1.525     raeburn  4566:     my $no_increment = 1;
1.119     ng       4567:     for ($version=1;$version<=$$record{'version'};$version++) {
1.467     albertel 4568: 	my $timestamp = 
                   4569: 	    &Apache::lonlocal::locallocaltime($$record{$version.':timestamp'});
1.335     albertel 4570: 	if (exists($$record{$version.':resource.0.version'})) {
                   4571: 	    $interaction = $$record{$version.':resource.0.version'};
                   4572: 	}
                   4573: 
                   4574: 	my $where = ($isTask ? "$version:resource.$interaction"
                   4575: 		             : "$version:resource");
1.467     albertel 4576: 	$studentTable.=&Apache::loncommon::start_data_table_row().
                   4577: 	    '<td>'.$timestamp.'</td>';
1.224     albertel 4578: 	if ($isCODE) {
                   4579: 	    $studentTable.='<td>'.$record->{$version.':resource.CODE'}.'</td>';
                   4580: 	}
1.119     ng       4581: 	my @versionKeys = split(/\:/,$$record{$version.':keys'});
                   4582: 	my @displaySub = ();
                   4583: 	foreach my $partid (@{$parts}) {
1.596     raeburn  4584:             my $hidden;
                   4585:             if (($$record{$version.':resource.'.$partid.'.type'} eq 'anonsurvey') ||
                   4586:                 ($$record{$version.':resource.'.$partid.'.type'} eq 'anonsurveycred')) {
                   4587:                 $hidden = 1;
                   4588:             }
1.335     albertel 4589: 	    my @matchKey = ($isTask ? sort(grep /^resource\.\d+\.\Q$partid\E\.award$/,@versionKeys)
                   4590: 			            : sort(grep /^resource\.\Q$partid\E\..*?\.submission$/,@versionKeys));
                   4591: 	    
1.122     ng       4592: #	    next if ($$record{"$version:resource.$partid.solved"} eq '');
1.324     albertel 4593: 	    my $display_part=&get_display_part($partid,$symb);
1.147     albertel 4594: 	    foreach my $matchKey (@matchKey) {
1.198     albertel 4595: 		if (exists($$record{$version.':'.$matchKey}) &&
                   4596: 		    $$record{$version.':'.$matchKey} ne '') {
1.596     raeburn  4597:                     
1.335     albertel 4598: 		    my ($responseId)= ($isTask ? ($matchKey=~ /^resource\.(.*?)\.\Q$partid\E\.award$/)
                   4599: 				               : ($matchKey=~ /^resource\.\Q$partid\E\.(.*?)\.submission$/));
1.577     bisitz   4600:                     $displaySub[0].='<span class="LC_nobreak"';
                   4601:                     $displaySub[0].='<b>'.&mt('Part: [_1]',$display_part).'</b>'
                   4602:                                    .' <span class="LC_internal_info">'
                   4603:                                    .'('.&mt('Part ID: [_1]',$responseId).')'
                   4604:                                    .'</span>'
                   4605:                                    .' <b>';
1.596     raeburn  4606:                     if ($hidden) {
                   4607:                         $displaySub[0].= &mt('Anonymous Survey').'</b>';
                   4608:                     } else {
                   4609: 		        if ($$record{"$where.$partid.tries"} eq '') {
                   4610: 			    $displaySub[0].=&mt('Trial not counted');
                   4611: 		        } else {
                   4612: 			    $displaySub[0].=&mt('Trial: [_1]',
1.467     albertel 4613: 					    $$record{"$where.$partid.tries"});
1.596     raeburn  4614: 		        }
                   4615: 		        my $responseType=($isTask ? 'Task'
1.335     albertel 4616:                                               : $responseType->{$partid}->{$responseId});
1.596     raeburn  4617: 		        if (!exists($orders{$partid})) { $orders{$partid}={}; }
                   4618: 		        if (!exists($orders{$partid}->{$responseId})) {
                   4619: 			    $orders{$partid}->{$responseId}=
                   4620: 			        &get_order($partid,$responseId,$symb,$uname,$udom,
                   4621:                                            $no_increment);
                   4622: 		        }
                   4623: 		        $displaySub[0].='</b></span>'; # /nobreak
                   4624: 		        $displaySub[0].='&nbsp; '.
                   4625: 			    &cleanRecord($$record{$version.':'.$matchKey},$responseType,$symb,$partid,$responseId,$record,$orders{$partid}->{$responseId},"$version:",$uname,$udom).'<br />';
                   4626:                     }
1.147     albertel 4627: 		}
                   4628: 	    }
1.335     albertel 4629: 	    if (exists($$record{"$where.$partid.checkedin"})) {
1.485     albertel 4630: 		$displaySub[1].=&mt('Checked in by [_1] into slot [_2]',
                   4631: 				    $$record{"$where.$partid.checkedin"},
                   4632: 				    $$record{"$where.$partid.checkedin.slot"}).
                   4633: 					'<br />';
1.335     albertel 4634: 	    }
                   4635: 	    if (exists $$record{"$where.$partid.award"}) {
1.485     albertel 4636: 		$displaySub[1].='<b>'.&mt('Part:').'</b>&nbsp;'.$display_part.' &nbsp;'.
1.335     albertel 4637: 		    lc($$record{"$where.$partid.award"}).' '.
                   4638: 		    $mark{$$record{"$where.$partid.solved"}}.
1.147     albertel 4639: 		    '<br />';
                   4640: 	    }
1.335     albertel 4641: 	    if (exists $$record{"$where.$partid.regrader"}) {
                   4642: 		$displaySub[2].=$$record{"$where.$partid.regrader"}.
                   4643: 		    ' (<b>'.&mt('Part').':</b> '.$display_part.')';
                   4644: 	    } elsif ($$record{"$version:resource.$partid.regrader"} =~ /\S/) {
                   4645: 		$displaySub[2].=
                   4646: 		    $$record{"$version:resource.$partid.regrader"}.
1.207     albertel 4647: 		    ' (<b>'.&mt('Part').':</b> '.$display_part.')';
1.147     albertel 4648: 	    }
                   4649: 	}
                   4650: 	# needed because old essay regrader has not parts info
                   4651: 	if (exists $$record{"$version:resource.regrader"}) {
                   4652: 	    $displaySub[2].=$$record{"$version:resource.regrader"};
                   4653: 	}
                   4654: 	$studentTable.='<td>'.$displaySub[0].'&nbsp;</td><td>'.$displaySub[1];
                   4655: 	if ($displaySub[2]) {
1.467     albertel 4656: 	    $studentTable.=&mt('Manually graded by [_1]',$displaySub[2]);
1.147     albertel 4657: 	}
1.467     albertel 4658: 	$studentTable.='&nbsp;</td>'.
                   4659: 	    &Apache::loncommon::end_data_table_row();
1.119     ng       4660:     }
1.467     albertel 4661:     $studentTable.=&Apache::loncommon::end_data_table();
1.119     ng       4662:     return $studentTable;
1.71      ng       4663: }
                   4664: 
                   4665: sub updateGradeByPage {
                   4666:     my ($request) = shift;
                   4667: 
1.257     albertel 4668:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
                   4669:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
                   4670:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
                   4671:     my $pageTitle = $env{'form.page'};
1.103     albertel 4672:     my ($classlist,undef,$fullname) = &getclasslist($getsec,'1');
1.257     albertel 4673:     my ($uname,$udom) = split(/:/,$env{'form.student'});
                   4674:     my $usec=$classlist->{$env{'form.student'}}[5];
1.103     albertel 4675:     if (!&canmodify($usec)) {
1.526     raeburn  4676: 	$request->print('<span class="LC_warning">'.&mt('Unable to modify requested student ([_1])',$env{'form.student'}).'</span>');
1.324     albertel 4677: 	$request->print(&show_grading_menu_form($env{'form.symb'}));
1.103     albertel 4678: 	return;
                   4679:     }
1.398     albertel 4680:     my $result='<h3><span class="LC_info">&nbsp;'.$env{'form.title'}.'</span></h3>';
1.526     raeburn  4681:     $result.='<h3>&nbsp;'.&mt('Student: ').&nameUserString(undef,$env{'form.fullname'},$uname,$udom).
1.129     ng       4682: 	'</h3>'."\n";
1.70      ng       4683: 
1.68      ng       4684:     $request->print($result);
                   4685: 
1.582     raeburn  4686: 
1.132     bowersj2 4687:     my $navmap = Apache::lonnavmaps::navmap->new();
1.582     raeburn  4688:     unless (ref($navmap)) {
                   4689:         $request->print(&navmap_errormsg());
                   4690:         return;
                   4691:     }
1.257     albertel 4692:     my ($mapUrl, $id, $resUrl) = &Apache::lonnet::decode_symb( $env{'form.page'});
1.71      ng       4693:     my $map = $navmap->getResourceByUrl($resUrl); # add to navmaps
1.288     albertel 4694:     if (!$map) {
1.527     raeburn  4695: 	$request->print('<span class="LC_warning">'.&mt('Unable to grade requested sequence ([_1]).',$resUrl).'</span>');
1.324     albertel 4696: 	my ($symb)=&get_symb($request);
                   4697: 	$request->print(&show_grading_menu_form($symb));
1.288     albertel 4698: 	return; 
                   4699:     }
1.71      ng       4700:     my $iterator = $navmap->getIterator($map->map_start(),
                   4701: 					$map->map_finish());
1.70      ng       4702: 
1.484     albertel 4703:     my $studentTable=
                   4704: 	&Apache::loncommon::start_data_table().
                   4705: 	&Apache::loncommon::start_data_table_header_row().
1.485     albertel 4706: 	'<th align="center">&nbsp;'.&mt('Prob.').'&nbsp;</th>'.
                   4707: 	'<th>&nbsp;'.&mt('Title').'&nbsp;</th>'.
                   4708: 	'<th>&nbsp;'.&mt('Previous Score').'&nbsp;</th>'.
                   4709: 	'<th>&nbsp;'.&mt('New Score').'&nbsp;</th>'.
1.484     albertel 4710: 	&Apache::loncommon::end_data_table_header_row();
1.71      ng       4711: 
                   4712:     $iterator->next(); # skip the first BEGIN_MAP
                   4713:     my $curRes = $iterator->next(); # for "current resource"
1.196     albertel 4714:     my ($depth,$question,$prob,$changeflag)= (1,1,1,0);
1.101     albertel 4715:     while ($depth > 0) {
1.71      ng       4716:         if($curRes == $iterator->BEGIN_MAP) { $depth++; }
1.100     bowersj2 4717:         if($curRes == $iterator->END_MAP) { $depth--; }
1.71      ng       4718: 
1.385     albertel 4719:         if (ref($curRes) && $curRes->is_problem()) {
1.91      albertel 4720: 	    my $parts = $curRes->parts();
1.71      ng       4721:             my $title = $curRes->compTitle();
                   4722: 	    my $symbx = $curRes->symb();
1.484     albertel 4723: 	    $studentTable.=
                   4724: 		&Apache::loncommon::start_data_table_row().
                   4725: 		'<td align="center" valign="top" >'.$prob.
1.485     albertel 4726: 		(scalar(@{$parts}) == 1 ? '' 
1.526     raeburn  4727:                                         : '<br />('.&mt('[quant,_1,&nbsp;part]',scalar(@{$parts}))
                   4728: 		.')').'</td>';
1.71      ng       4729: 	    $studentTable.='<td valign="top">&nbsp;<b>'.$title.'</b>&nbsp;</td>';
                   4730: 
                   4731: 	    my %newrecord=();
                   4732: 	    my @displayPts=();
1.269     raeburn  4733:             my %aggregate = ();
                   4734:             my $aggregateflag = 0;
1.71      ng       4735: 	    foreach my $partid (@{$parts}) {
1.257     albertel 4736: 		my $newpts = $env{'form.GD_BOX'.$question.'_'.$partid};
                   4737: 		my $oldpts = $env{'form.oldpts'.$question.'_'.$partid};
1.71      ng       4738: 
1.257     albertel 4739: 		my $wgt = $env{'form.WGT'.$question.'_'.$partid} != 0 ? 
                   4740: 		    $env{'form.WGT'.$question.'_'.$partid} : 1;
1.71      ng       4741: 		my $partial = $newpts/$wgt;
                   4742: 		my $score;
                   4743: 		if ($partial > 0) {
                   4744: 		    $score = 'correct_by_override';
1.125     ng       4745: 		} elsif ($newpts ne '') { #empty is taken as 0
1.71      ng       4746: 		    $score = 'incorrect_by_override';
                   4747: 		}
1.257     albertel 4748: 		my $dropMenu = $env{'form.GD_SEL'.$question.'_'.$partid};
1.125     ng       4749: 		if ($dropMenu eq 'excused') {
1.71      ng       4750: 		    $partial = '';
                   4751: 		    $score = 'excused';
1.125     ng       4752: 		} elsif ($dropMenu eq 'reset status'
1.257     albertel 4753: 			 && $env{'form.solved'.$question.'_'.$partid} ne '') { #update only if previous record exists
1.125     ng       4754: 		    $newrecord{'resource.'.$partid.'.tries'} = 0;
                   4755: 		    $newrecord{'resource.'.$partid.'.solved'} = '';
                   4756: 		    $newrecord{'resource.'.$partid.'.award'} = '';
                   4757: 		    $newrecord{'resource.'.$partid.'.awarded'} = 0;
1.257     albertel 4758: 		    $newrecord{'resource.'.$partid.'.regrader'} = "$env{'user.name'}:$env{'user.domain'}";
1.125     ng       4759: 		    $changeflag++;
                   4760: 		    $newpts = '';
1.269     raeburn  4761:                     
                   4762:                     my $aggtries =  $env{'form.aggtries'.$question.'_'.$partid};
                   4763:                     my $totaltries = $env{'form.totaltries'.$question.'_'.$partid};
                   4764:                     my $solvedstatus = $env{'form.solved'.$question.'_'.$partid};
                   4765:                     if ($aggtries > 0) {
                   4766:                         &decrement_aggs($symbx,$partid,\%aggregate,$aggtries,$totaltries,$solvedstatus);
                   4767:                         $aggregateflag = 1;
                   4768:                     }
1.71      ng       4769: 		}
1.324     albertel 4770: 		my $display_part=&get_display_part($partid,$curRes->symb());
1.257     albertel 4771: 		my $oldstatus = $env{'form.solved'.$question.'_'.$partid};
1.526     raeburn  4772: 		$displayPts[0].='&nbsp;<b>'.&mt('Part').':</b> '.$display_part.' = '.
1.71      ng       4773: 		    (($oldstatus eq 'excused') ? 'excused' : $oldpts).
1.326     albertel 4774: 		    '&nbsp;<br />';
1.526     raeburn  4775: 		$displayPts[1].='&nbsp;<b>'.&mt('Part').':</b> '.$display_part.' = '.
1.125     ng       4776: 		     (($score eq 'excused') ? 'excused' : $newpts).
1.326     albertel 4777: 		    '&nbsp;<br />';
1.71      ng       4778: 		$question++;
1.380     albertel 4779: 		next if ($dropMenu eq 'reset status' || ($newpts eq $oldpts && $score ne 'excused'));
1.125     ng       4780: 
1.71      ng       4781: 		$newrecord{'resource.'.$partid.'.awarded'}  = $partial if $partial ne '';
1.125     ng       4782: 		$newrecord{'resource.'.$partid.'.solved'}   = $score if $score ne '';
1.257     albertel 4783: 		$newrecord{'resource.'.$partid.'.regrader'} = "$env{'user.name'}:$env{'user.domain'}"
1.125     ng       4784: 		    if (scalar(keys(%newrecord)) > 0);
1.71      ng       4785: 
                   4786: 		$changeflag++;
                   4787: 	    }
                   4788: 	    if (scalar(keys(%newrecord)) > 0) {
1.382     albertel 4789: 		my %record = 
                   4790: 		    &Apache::lonnet::restore($symbx,$env{'request.course.id'},
                   4791: 					     $udom,$uname);
                   4792: 
                   4793: 		if (&Apache::lonnet::validCODE($env{'form.CODE'})) {
                   4794: 		    $newrecord{'resource.CODE'} = $env{'form.CODE'};
                   4795: 		} elsif (&Apache::lonnet::validCODE($record{'resource.CODE'})) {
                   4796: 		    $newrecord{'resource.CODE'} = '';
                   4797: 		}
1.257     albertel 4798: 		&Apache::lonnet::cstore(\%newrecord,$symbx,$env{'request.course.id'},
1.71      ng       4799: 					$udom,$uname);
1.382     albertel 4800: 		%record = &Apache::lonnet::restore($symbx,
                   4801: 						   $env{'request.course.id'},
                   4802: 						   $udom,$uname);
1.380     albertel 4803: 		&check_and_remove_from_queue($parts,\%record,undef,$symbx,
                   4804: 					     $cdom,$cnum,$udom,$uname);
1.71      ng       4805: 	    }
1.380     albertel 4806: 	    
1.269     raeburn  4807:             if ($aggregateflag) {
                   4808:                 &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
                   4809:                       $env{'course.'.$env{'request.course.id'}.'.domain'},
                   4810:                       $env{'course.'.$env{'request.course.id'}.'.num'});
                   4811:             }
1.125     ng       4812: 
1.71      ng       4813: 	    $studentTable.='<td valign="top">'.$displayPts[0].'</td>'.
                   4814: 		'<td valign="top">'.$displayPts[1].'</td>'.
1.484     albertel 4815: 		&Apache::loncommon::end_data_table_row();
1.68      ng       4816: 
1.196     albertel 4817: 	    $prob++;
1.68      ng       4818: 	}
1.71      ng       4819:         $curRes = $iterator->next();
1.68      ng       4820:     }
1.98      albertel 4821: 
1.484     albertel 4822:     $studentTable.=&Apache::loncommon::end_data_table();
1.324     albertel 4823:     $studentTable.=&show_grading_menu_form($env{'form.symb'});
1.526     raeburn  4824:     my $grademsg=($changeflag == 0 ? &mt('No score was changed or updated.') :
                   4825: 		  &mt('The scores were changed for [quant,_1,problem].',
                   4826: 		  $changeflag));
1.76      ng       4827:     $request->print($grademsg.$studentTable);
1.68      ng       4828: 
1.70      ng       4829:     return '';
                   4830: }
                   4831: 
1.72      ng       4832: #-------- end of section for handling grading by page/sequence ---------
                   4833: #
                   4834: #-------------------------------------------------------------------
                   4835: 
1.581     www      4836: #-------------------- Bubblesheet (Scantron) Grading -------------------
1.75      albertel 4837: #
                   4838: #------ start of section for handling grading by page/sequence ---------
                   4839: 
1.423     albertel 4840: =pod
                   4841: 
                   4842: =head1 Bubble sheet grading routines
                   4843: 
1.424     albertel 4844:   For this documentation:
                   4845: 
                   4846:    'scanline' refers to the full line of characters
                   4847:    from the file that we are parsing that represents one entire sheet
                   4848: 
                   4849:    'bubble line' refers to the data
                   4850:    representing the line of bubbles that are on the physical bubble sheet
                   4851: 
                   4852: 
                   4853: The overall process is that a scanned in bubble sheet data is uploaded
                   4854: into a course. When a user wants to grade, they select a
                   4855: sequence/folder of resources, a file of bubble sheet info, and pick
                   4856: one of the predefined configurations for what each scanline looks
                   4857: like.
                   4858: 
                   4859: Next each scanline is checked for any errors of either 'missing
1.435     foxr     4860: bubbles' (it's an error because it may have been mis-scanned
1.424     albertel 4861: because too light bubbling), 'double bubble' (each bubble line should
                   4862: have no more that one letter picked), invalid or duplicated CODE,
1.556     weissno  4863: invalid student/employee ID
1.424     albertel 4864: 
                   4865: If the CODE option is used that determines the randomization of the
1.556     weissno  4866: homework problems, either way the student/employee ID is looked up into a
1.424     albertel 4867: username:domain.
                   4868: 
                   4869: During the validation phase the instructor can choose to skip scanlines. 
                   4870: 
1.435     foxr     4871: After the validation phase, there are now 3 bubble sheet files
1.424     albertel 4872: 
                   4873:   scantron_original_filename (unmodified original file)
                   4874:   scantron_corrected_filename (file where the corrected information has replaced the original information)
                   4875:   scantron_skipped_filename (contains the exact text of scanlines that where skipped)
                   4876: 
                   4877: Also there is a separate hash nohist_scantrondata that contains extra
                   4878: correction information that isn't representable in the bubble sheet
                   4879: file (see &scantron_getfile() for more information)
                   4880: 
                   4881: After all scanlines are either valid, marked as valid or skipped, then
                   4882: foreach line foreach problem in the picked sequence, an ssi request is
                   4883: made that simulates a user submitting their selected letter(s) against
                   4884: the homework problem.
1.423     albertel 4885: 
                   4886: =over 4
                   4887: 
                   4888: 
                   4889: 
                   4890: =item defaultFormData
                   4891: 
                   4892:   Returns html hidden inputs used to hold context/default values.
                   4893: 
                   4894:  Arguments:
                   4895:   $symb - $symb of the current resource 
                   4896: 
                   4897: =cut
1.422     foxr     4898: 
1.81      albertel 4899: sub defaultFormData {
1.324     albertel 4900:     my ($symb)=@_;
1.447     foxr     4901:     return '<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.257     albertel 4902:      '<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n".
                   4903:      '<input type="hidden" name="probTitle" value="'.$env{'form.probTitle'}.'" />'."\n";
1.81      albertel 4904: }
                   4905: 
1.447     foxr     4906: 
1.423     albertel 4907: =pod 
                   4908: 
                   4909: =item getSequenceDropDown
                   4910: 
                   4911:    Return html dropdown of possible sequences to grade
                   4912:  
                   4913:  Arguments:
1.582     raeburn  4914:    $symb - $symb of the current resource
                   4915:    $map_error - ref to scalar which will container error if
                   4916:                 $navmap object is unavailable in &getSymbMap().
1.423     albertel 4917: 
                   4918: =cut
1.422     foxr     4919: 
1.75      albertel 4920: sub getSequenceDropDown {
1.582     raeburn  4921:     my ($symb,$map_error)=@_;
1.75      albertel 4922:     my $result='<select name="selectpage">'."\n";
1.582     raeburn  4923:     my ($titles,$symbx) = &getSymbMap($map_error);
                   4924:     if (ref($map_error)) {
                   4925:         return if ($$map_error);
                   4926:     }
1.137     albertel 4927:     my ($curpage)=&Apache::lonnet::decode_symb($symb); 
1.75      albertel 4928:     my $ctr=0;
                   4929:     foreach (@$titles) {
                   4930: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
                   4931: 	$result.='<option value="'.$$symbx{$_}.'" '.
1.401     albertel 4932: 	    ($$symbx{$_} =~ /$curpage$/ ? 'selected="selected"' : '').
1.75      albertel 4933: 	    '>'.$showtitle.'</option>'."\n";
                   4934: 	$ctr++;
                   4935:     }
                   4936:     $result.= '</select>';
                   4937:     return $result;
                   4938: }
                   4939: 
1.495     albertel 4940: my %bubble_lines_per_response;     # no. bubble lines for each response.
1.554     raeburn  4941:                                    # key is zero-based index - 0, 1, 2 ...
1.495     albertel 4942: 
                   4943: my %first_bubble_line;             # First bubble line no. for each bubble.
                   4944: 
1.509     raeburn  4945: my %subdivided_bubble_lines;       # no. bubble lines for optionresponse, 
                   4946:                                    # matchresponse or rankresponse, where 
                   4947:                                    # an individual response can have multiple 
                   4948:                                    # lines
1.503     raeburn  4949: 
                   4950: my %responsetype_per_response;     # responsetype for each response
                   4951: 
1.495     albertel 4952: # Save and restore the bubble lines array to the form env.
                   4953: 
                   4954: 
                   4955: sub save_bubble_lines {
                   4956:     foreach my $line (keys(%bubble_lines_per_response)) {
                   4957: 	$env{"form.scantron.bubblelines.$line"}  = $bubble_lines_per_response{$line};
                   4958: 	$env{"form.scantron.first_bubble_line.$line"} =
                   4959: 	    $first_bubble_line{$line};
1.503     raeburn  4960:         $env{"form.scantron.sub_bubblelines.$line"} = 
                   4961:             $subdivided_bubble_lines{$line};
                   4962:         $env{"form.scantron.responsetype.$line"} =
                   4963:             $responsetype_per_response{$line};
1.495     albertel 4964:     }
                   4965: }
                   4966: 
                   4967: 
                   4968: sub restore_bubble_lines {
                   4969:     my $line = 0;
                   4970:     %bubble_lines_per_response = ();
                   4971:     while ($env{"form.scantron.bubblelines.$line"}) {
                   4972: 	my $value = $env{"form.scantron.bubblelines.$line"};
                   4973: 	$bubble_lines_per_response{$line} = $value;
                   4974: 	$first_bubble_line{$line}  =
                   4975: 	    $env{"form.scantron.first_bubble_line.$line"};
1.503     raeburn  4976:         $subdivided_bubble_lines{$line} =
                   4977:             $env{"form.scantron.sub_bubblelines.$line"};
                   4978:         $responsetype_per_response{$line} =
                   4979:             $env{"form.scantron.responsetype.$line"};
1.495     albertel 4980: 	$line++;
                   4981:     }
                   4982: }
                   4983: 
                   4984: #  Given the parsed scanline, get the response for 
                   4985: #  'answer' number n:
                   4986: 
                   4987: sub get_response_bubbles {
                   4988:     my ($parsed_line, $response)  = @_;
                   4989: 
                   4990:     my $bubble_line = $first_bubble_line{$response-1} +1;
                   4991:     my $bubble_lines= $bubble_lines_per_response{$response-1};
                   4992:     
                   4993:     my $selected = "";
                   4994: 
                   4995:     for (my $bline = 0; $bline < $bubble_lines; $bline++) {
                   4996: 	$selected .= $$parsed_line{"scantron.$bubble_line.answer"}.":";
                   4997: 	$bubble_line++;
                   4998:     }
                   4999:     return $selected;
                   5000: }
1.423     albertel 5001: 
                   5002: =pod 
                   5003: 
                   5004: =item scantron_filenames
                   5005: 
                   5006:    Returns a list of the scantron files in the current course 
                   5007: 
                   5008: =cut
1.422     foxr     5009: 
1.202     albertel 5010: sub scantron_filenames {
1.257     albertel 5011:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   5012:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
1.517     raeburn  5013:     my $getpropath = 1;
1.157     albertel 5014:     my @files=&Apache::lonnet::dirlist('userfiles',$cdom,$cname,
1.517     raeburn  5015:                                        $getpropath);
1.202     albertel 5016:     my @possiblenames;
1.201     albertel 5017:     foreach my $filename (sort(@files)) {
1.157     albertel 5018: 	($filename)=split(/&/,$filename);
                   5019: 	if ($filename!~/^scantron_orig_/) { next ; }
                   5020: 	$filename=~s/^scantron_orig_//;
1.202     albertel 5021: 	push(@possiblenames,$filename);
                   5022:     }
                   5023:     return @possiblenames;
                   5024: }
                   5025: 
1.423     albertel 5026: =pod 
                   5027: 
                   5028: =item scantron_uploads
                   5029: 
                   5030:    Returns  html drop-down list of scantron files in current course.
                   5031: 
                   5032:  Arguments:
                   5033:    $file2grade - filename to set as selected in the dropdown
                   5034: 
                   5035: =cut
1.422     foxr     5036: 
1.202     albertel 5037: sub scantron_uploads {
1.209     ng       5038:     my ($file2grade) = @_;
1.202     albertel 5039:     my $result=	'<select name="scantron_selectfile">';
                   5040:     $result.="<option></option>";
                   5041:     foreach my $filename (sort(&scantron_filenames())) {
1.401     albertel 5042: 	$result.="<option".($filename eq $file2grade ? ' selected="selected"':'').">$filename</option>\n";
1.81      albertel 5043:     }
                   5044:     $result.="</select>";
                   5045:     return $result;
                   5046: }
                   5047: 
1.423     albertel 5048: =pod 
                   5049: 
                   5050: =item scantron_scantab
                   5051: 
                   5052:   Returns html drop down of the scantron formats in the scantronformat.tab
                   5053:   file.
                   5054: 
                   5055: =cut
1.422     foxr     5056: 
1.82      albertel 5057: sub scantron_scantab {
                   5058:     my $result='<select name="scantron_format">'."\n";
1.191     albertel 5059:     $result.='<option></option>'."\n";
1.518     raeburn  5060:     my @lines = &get_scantronformat_file();
                   5061:     if (@lines > 0) {
                   5062:         foreach my $line (@lines) {
                   5063:             next if (($line =~ /^\#/) || ($line eq ''));
                   5064: 	    my ($name,$descrip)=split(/:/,$line);
                   5065: 	    $result.='<option value="'.$name.'">'.$descrip.'</option>'."\n";
                   5066:         }
1.82      albertel 5067:     }
                   5068:     $result.='</select>'."\n";
1.518     raeburn  5069:     return $result;
                   5070: }
                   5071: 
                   5072: =pod
                   5073: 
                   5074: =item get_scantronformat_file
                   5075: 
                   5076:   Returns an array containing lines from the scantron format file for
                   5077:   the domain of the course.
                   5078: 
                   5079:   If a url for a custom.tab file is listed in domain's configuration.db, 
                   5080:   lines are from this file.
                   5081: 
                   5082:   Otherwise, if a default.tab has been published in RES space by the 
                   5083:   domainconfig user, lines are from this file.
                   5084: 
                   5085:   Otherwise, fall back to getting lines from the legacy file on the
1.519     raeburn  5086:   local server:  /home/httpd/lonTabs/default_scantronformat.tab    
1.82      albertel 5087: 
1.518     raeburn  5088: =cut
                   5089: 
                   5090: sub get_scantronformat_file {
                   5091:     my $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
                   5092:     my %domconfig = &Apache::lonnet::get_dom('configuration',['scantron'],$cdom);
                   5093:     my $gottab = 0;
                   5094:     my @lines;
                   5095:     if (ref($domconfig{'scantron'}) eq 'HASH') {
                   5096:         if ($domconfig{'scantron'}{'scantronformat'} ne '') {
                   5097:             my $formatfile = &Apache::lonnet::getfile($Apache::lonnet::perlvar{'lonDocRoot'}.$domconfig{'scantron'}{'scantronformat'});
                   5098:             if ($formatfile ne '-1') {
                   5099:                 @lines = split("\n",$formatfile,-1);
                   5100:                 $gottab = 1;
                   5101:             }
                   5102:         }
                   5103:     }
                   5104:     if (!$gottab) {
                   5105:         my $confname = $cdom.'-domainconfig';
                   5106:         my $default = $Apache::lonnet::perlvar{'lonDocRoot'}.'/res/'.$cdom.'/'.$confname.'/default.tab';
                   5107:         my $formatfile =  &Apache::lonnet::getfile($default);
                   5108:         if ($formatfile ne '-1') {
                   5109:             @lines = split("\n",$formatfile,-1);
                   5110:             $gottab = 1;
                   5111:         }
                   5112:     }
                   5113:     if (!$gottab) {
1.519     raeburn  5114:         my @domains = &Apache::lonnet::current_machine_domains();
                   5115:         if (grep(/^\Q$cdom\E$/,@domains)) {
                   5116:             my $fh=Apache::File->new($Apache::lonnet::perlvar{'lonTabDir'}.'/scantronformat.tab');
                   5117:             @lines = <$fh>;
                   5118:             close($fh);
                   5119:         } else {
                   5120:             my $fh=Apache::File->new($Apache::lonnet::perlvar{'lonTabDir'}.'/default_scantronformat.tab');
                   5121:             @lines = <$fh>;
                   5122:             close($fh);
                   5123:         }
1.518     raeburn  5124:     }
                   5125:     return @lines;
1.82      albertel 5126: }
                   5127: 
1.423     albertel 5128: =pod 
                   5129: 
                   5130: =item scantron_CODElist
                   5131: 
                   5132:   Returns html drop down of the saved CODE lists from current course,
                   5133:   generated from earlier printings.
                   5134: 
                   5135: =cut
1.422     foxr     5136: 
1.186     albertel 5137: sub scantron_CODElist {
1.257     albertel 5138:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   5139:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
1.186     albertel 5140:     my @names=&Apache::lonnet::getkeys('CODEs',$cdom,$cnum);
                   5141:     my $namechoice='<option></option>';
1.225     albertel 5142:     foreach my $name (sort {uc($a) cmp uc($b)} @names) {
1.191     albertel 5143: 	if ($name =~ /^error: 2 /) { next; }
1.278     albertel 5144: 	if ($name =~ /^type\0/) { next; }
1.186     albertel 5145: 	$namechoice.='<option value="'.$name.'">'.$name.'</option>';
                   5146:     }
                   5147:     $namechoice='<select name="scantron_CODElist">'.$namechoice.'</select>';
                   5148:     return $namechoice;
                   5149: }
                   5150: 
1.423     albertel 5151: =pod 
                   5152: 
                   5153: =item scantron_CODEunique
                   5154: 
                   5155:   Returns the html for "Each CODE to be used once" radio.
                   5156: 
                   5157: =cut
1.422     foxr     5158: 
1.186     albertel 5159: sub scantron_CODEunique {
1.532     bisitz   5160:     my $result='<span class="LC_nobreak">
1.272     albertel 5161:                  <label><input type="radio" name="scantron_CODEunique"
1.423     albertel 5162:                         value="yes" checked="checked" />'.&mt('Yes').' </label>
1.381     albertel 5163:                 </span>
1.532     bisitz   5164:                 <span class="LC_nobreak">
1.272     albertel 5165:                  <label><input type="radio" name="scantron_CODEunique"
1.423     albertel 5166:                         value="no" />'.&mt('No').' </label>
1.381     albertel 5167:                 </span>';
1.186     albertel 5168:     return $result;
                   5169: }
1.423     albertel 5170: 
                   5171: =pod 
                   5172: 
                   5173: =item scantron_selectphase
                   5174: 
                   5175:   Generates the initial screen to start the bubble sheet process.
                   5176:   Allows for - starting a grading run.
1.424     albertel 5177:              - downloading existing scan data (original, corrected
1.423     albertel 5178:                                                 or skipped info)
                   5179: 
                   5180:              - uploading new scan data
                   5181: 
                   5182:  Arguments:
                   5183:   $r          - The Apache request object
                   5184:   $file2grade - name of the file that contain the scanned data to score
                   5185: 
                   5186: =cut
1.186     albertel 5187: 
1.75      albertel 5188: sub scantron_selectphase {
1.209     ng       5189:     my ($r,$file2grade) = @_;
1.324     albertel 5190:     my ($symb)=&get_symb($r);
1.75      albertel 5191:     if (!$symb) {return '';}
1.582     raeburn  5192:     my $map_error;
                   5193:     my $sequence_selector=&getSequenceDropDown($symb,\$map_error);
                   5194:     if ($map_error) {
                   5195:         $r->print('<br />'.&navmap_errormsg().'<br />');
                   5196:         return;
                   5197:     }
1.324     albertel 5198:     my $default_form_data=&defaultFormData($symb);
                   5199:     my $grading_menu_button=&show_grading_menu_form($symb);
1.209     ng       5200:     my $file_selector=&scantron_uploads($file2grade);
1.82      albertel 5201:     my $format_selector=&scantron_scantab();
1.186     albertel 5202:     my $CODE_selector=&scantron_CODElist();
                   5203:     my $CODE_unique=&scantron_CODEunique();
1.75      albertel 5204:     my $result;
1.422     foxr     5205: 
1.513     foxr     5206:     $ssi_error = 0;
                   5207: 
1.422     foxr     5208:     # Chunk of form to prompt for a file to grade and how:
                   5209: 
1.489     albertel 5210:     $result.= '
                   5211:     <br />
                   5212:     <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantron_process">
                   5213:     <input type="hidden" name="command" value="scantron_warning" />
                   5214:     '.$default_form_data.'
                   5215:     '.&Apache::loncommon::start_data_table('LC_scantron_action').'
                   5216:        '.&Apache::loncommon::start_data_table_header_row().'
                   5217:             <th colspan="2">
1.492     albertel 5218:               &nbsp;'.&mt('Specify file and which Folder/Sequence to grade').'
1.489     albertel 5219:             </th>
                   5220:        '.&Apache::loncommon::end_data_table_header_row().'
                   5221:        '.&Apache::loncommon::start_data_table_row().'
1.492     albertel 5222:             <td> '.&mt('Sequence to grade:').' </td><td> '.$sequence_selector.' </td>
1.489     albertel 5223:        '.&Apache::loncommon::end_data_table_row().'
                   5224:        '.&Apache::loncommon::start_data_table_row().'
1.572     www      5225:             <td> '.&mt('Filename of bubblesheet data file:').' </td><td> '.$file_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('Format of bubblesheet data file:').' </td><td> '.$format_selector.' </td>
1.489     albertel 5229:        '.&Apache::loncommon::end_data_table_row().'
                   5230:        '.&Apache::loncommon::start_data_table_row().'
1.492     albertel 5231:             <td> '.&mt('Saved CODEs to validate against:').' </td><td> '.$CODE_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('Each CODE is only to be used once:').'</td><td> '.$CODE_unique.' </td>
1.489     albertel 5235:        '.&Apache::loncommon::end_data_table_row().'
                   5236:        '.&Apache::loncommon::start_data_table_row().'
1.492     albertel 5237: 	    <td> '.&mt('Options:').' </td>
1.187     albertel 5238:             <td>
1.492     albertel 5239: 	       <label><input type="checkbox" name="scantron_options_redo" value="redo_skipped"/> '.&mt('Do only previously skipped records').'</label> <br />
                   5240:                <label><input type="checkbox" name="scantron_options_ignore" value="ignore_corrections"/> '.&mt('Remove all existing corrections').'</label> <br />
                   5241:                <label><input type="checkbox" name="scantron_options_hidden" value="ignore_hidden"/> '.&mt('Skip hidden resources when grading').'</label>
1.187     albertel 5242: 	    </td>
1.489     albertel 5243:        '.&Apache::loncommon::end_data_table_row().'
                   5244:        '.&Apache::loncommon::start_data_table_row().'
1.174     albertel 5245:             <td colspan="2">
1.572     www      5246:               <input type="submit" value="'.&mt('Grading: Validate Bubblesheet Records').'" />
1.162     albertel 5247:             </td>
1.489     albertel 5248:        '.&Apache::loncommon::end_data_table_row().'
                   5249:     '.&Apache::loncommon::end_data_table().'
                   5250:     </form>
                   5251: ';
1.162     albertel 5252:    
                   5253:     $r->print($result);
                   5254: 
1.257     albertel 5255:     if (&Apache::lonnet::allowed('usc',$env{'request.role.domain'}) ||
                   5256:         &Apache::lonnet::allowed('usc',$env{'request.course.id'})) {
1.162     albertel 5257: 
1.422     foxr     5258: 	# Chunk of form to prompt for a scantron file upload.
                   5259: 
1.489     albertel 5260:         $r->print('
                   5261:     <br />
                   5262:     '.&Apache::loncommon::start_data_table('LC_scantron_action').'
                   5263:        '.&Apache::loncommon::start_data_table_header_row().'
                   5264:             <th>
1.572     www      5265:               &nbsp;'.&mt('Specify a bubblesheet data file to upload.').'
1.489     albertel 5266:             </th>
                   5267:        '.&Apache::loncommon::end_data_table_header_row().'
                   5268:        '.&Apache::loncommon::start_data_table_row().'
1.162     albertel 5269:             <td>
1.489     albertel 5270: ');
1.324     albertel 5271:     my $default_form_data=&defaultFormData(&get_symb($r,1));
1.257     albertel 5272:     my $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
                   5273:     my $cnum= $env{'course.'.$env{'request.course.id'}.'.num'};
1.597     wenzelju 5274:     $r->print(&Apache::lonhtmlcommon::scripttag('
1.174     albertel 5275:     function checkUpload(formname) {
                   5276: 	if (formname.upfile.value == "") {
1.492     albertel 5277: 	    alert("'.&mt('Please use the browse button to select a file from your local directory.').'");
1.174     albertel 5278: 	    return false;
                   5279: 	}
                   5280: 	formname.submit();
1.597     wenzelju 5281:     }'));
                   5282:     $r->print('
1.492     albertel 5283:               <form enctype="multipart/form-data" action="/adm/grades" name="rules" method="post">
                   5284:                 '.$default_form_data.'
                   5285:                 <input name="courseid" type="hidden" value="'.$cnum.'" />
                   5286:                 <input name="domainid" type="hidden" value="'.$cdom.'" />
                   5287:                 <input name="command" value="scantronupload_save" type="hidden" />
                   5288:                 '.&mt('File to upload: [_1]','<input type="file" name="upfile" size="50" />').'
1.174     albertel 5289:                 <br />
1.589     bisitz   5290:                 <input type="button" onclick="javascript:checkUpload(this.form);" value="'.&mt('Upload Bubblesheet Data').'" />
1.174     albertel 5291:               </form>
1.492     albertel 5292: ');
1.162     albertel 5293: 
1.489     albertel 5294:         $r->print('
1.162     albertel 5295:             </td>
1.489     albertel 5296:        '.&Apache::loncommon::end_data_table_row().'
                   5297:        '.&Apache::loncommon::end_data_table().'
                   5298: ');
1.162     albertel 5299:     }
1.422     foxr     5300: 
                   5301:     # Chunk of the form that prompts to view a scoring office file,
                   5302:     # corrected file, skipped records in a file.
                   5303: 
1.489     albertel 5304:     $r->print('
                   5305:    <br />
                   5306:    <form action="/adm/grades" name="scantron_download">
                   5307:      '.$default_form_data.'
                   5308:      <input type="hidden" name="command" value="scantron_download" />
                   5309:      '.&Apache::loncommon::start_data_table('LC_scantron_action').'
                   5310:        '.&Apache::loncommon::start_data_table_header_row().'
                   5311:               <th>
1.492     albertel 5312:                 &nbsp;'.&mt('Download a scoring office file').'
1.489     albertel 5313:               </th>
                   5314:        '.&Apache::loncommon::end_data_table_header_row().'
                   5315:        '.&Apache::loncommon::start_data_table_row().'
1.492     albertel 5316:               <td> '.&mt('Filename of scoring office file: [_1]',$file_selector).' 
1.489     albertel 5317:                 <br />
1.492     albertel 5318:                 <input type="submit" value="'.&mt('Download: Show List of Associated Files').'" />
1.489     albertel 5319:        '.&Apache::loncommon::end_data_table_row().'
                   5320:      '.&Apache::loncommon::end_data_table().'
                   5321:    </form>
                   5322:    <br />
                   5323: ');
1.162     albertel 5324: 
1.457     banghart 5325:     &Apache::lonpickcode::code_list($r,2);
1.523     raeburn  5326: 
1.528     raeburn  5327:     $r->print('<br /><form method="post" name="checkscantron">'.
1.523     raeburn  5328:              $default_form_data."\n".
                   5329:              &Apache::loncommon::start_data_table('LC_scantron_action')."\n".
                   5330:              &Apache::loncommon::start_data_table_header_row()."\n".
                   5331:              '<th colspan="2">
1.572     www      5332:               &nbsp;'.&mt('Review bubblesheet data and submissions for a previously graded folder/sequence')."\n".
1.523     raeburn  5333:              '</th>'."\n".
                   5334:               &Apache::loncommon::end_data_table_header_row()."\n".
                   5335:               &Apache::loncommon::start_data_table_row()."\n".
                   5336:               '<td> '.&mt('Graded folder/sequence:').' </td>'."\n".
                   5337:               '<td> '.$sequence_selector.' </td>'.
                   5338:               &Apache::loncommon::end_data_table_row()."\n".
                   5339:               &Apache::loncommon::start_data_table_row()."\n".
                   5340:               '<td> '.&mt('Filename of scoring office file:').' </td>'."\n".
                   5341:               '<td> '.$file_selector.' </td>'."\n".
                   5342:               &Apache::loncommon::end_data_table_row()."\n".
                   5343:               &Apache::loncommon::start_data_table_row()."\n".
                   5344:               '<td> '.&mt('Format of data file:').' </td>'."\n".
                   5345:               '<td> '.$format_selector.' </td>'."\n".
                   5346:               &Apache::loncommon::end_data_table_row()."\n".
                   5347:               &Apache::loncommon::start_data_table_row()."\n".
1.557     raeburn  5348:               '<td> '.&mt('Options').' </td>'."\n".
                   5349:               '<td> <label><input type="checkbox" name="scantron_options_hidden" value="ignore_hidden"/> '.&mt('Skip hidden resources').'</label></td>'.
                   5350:               &Apache::loncommon::end_data_table_row()."\n".
                   5351:               &Apache::loncommon::start_data_table_row()."\n".
1.523     raeburn  5352:               '<td colspan="2">'."\n".
                   5353:               '<input type="hidden" name="command" value="checksubmissions" />'."\n".
1.575     www      5354:               '<input type="submit" value="'.&mt('Review Bubblesheet Data and Submission Records').'" />'."\n".
1.523     raeburn  5355:               '</td>'."\n".
                   5356:               &Apache::loncommon::end_data_table_row()."\n".
                   5357:               &Apache::loncommon::end_data_table()."\n".
                   5358:               '</form><br />');
1.457     banghart 5359:     $r->print($grading_menu_button);
1.523     raeburn  5360:     return;
1.75      albertel 5361: }
                   5362: 
1.423     albertel 5363: =pod
                   5364: 
                   5365: =item get_scantron_config
                   5366: 
                   5367:    Parse and return the scantron configuration line selected as a
                   5368:    hash of configuration file fields.
                   5369: 
                   5370:  Arguments:
                   5371:     which - the name of the configuration to parse from the file.
                   5372: 
                   5373: 
                   5374:  Returns:
                   5375:             If the named configuration is not in the file, an empty
                   5376:             hash is returned.
                   5377:     a hash with the fields
                   5378:       name         - internal name for the this configuration setup
                   5379:       description  - text to display to operator that describes this config
                   5380:       CODElocation - if 0 or the string 'none'
                   5381:                           - no CODE exists for this config
                   5382:                      if -1 || the string 'letter'
                   5383:                           - a CODE exists for this config and is
                   5384:                             a string of letters
                   5385:                      Unsupported value (but planned for future support)
                   5386:                           if a positive integer
                   5387:                                - The CODE exists as the first n items from
                   5388:                                  the question section of the form
                   5389:                           if the string 'number'
                   5390:                                - The CODE exists for this config and is
                   5391:                                  a string of numbers
                   5392:       CODEstart   - (only matter if a CODE exists) column in the line where
                   5393:                      the CODE starts
                   5394:       CODElength  - length of the CODE
1.573     bisitz   5395:       IDstart     - column where the student/employee ID starts
1.556     weissno  5396:       IDlength    - length of the student/employee ID info
1.423     albertel 5397:       Qstart      - column where the information from the bubbled
                   5398:                     'questions' start
                   5399:       Qlength     - number of columns comprising a single bubble line from
                   5400:                     the sheet. (usually either 1 or 10)
1.424     albertel 5401:       Qon         - either a single character representing the character used
1.423     albertel 5402:                     to signal a bubble was chosen in the positional setup, or
                   5403:                     the string 'letter' if the letter of the chosen bubble is
                   5404:                     in the final, or 'number' if a number representing the
                   5405:                     chosen bubble is in the file (1->A 0->J)
1.424     albertel 5406:       Qoff        - the character used to represent that a bubble was
                   5407:                     left blank
1.423     albertel 5408:       PaperID     - if the scanning process generates a unique number for each
                   5409:                     sheet scanned the column that this ID number starts in
                   5410:       PaperIDlength - number of columns that comprise the unique ID number
                   5411:                       for the sheet of paper
1.424     albertel 5412:       FirstName   - column that the first name starts in
1.423     albertel 5413:       FirstNameLength - number of columns that the first name spans
                   5414:  
                   5415:       LastName    - column that the last name starts in
                   5416:       LastNameLength - number of columns that the last name spans
                   5417: 
                   5418: =cut
1.422     foxr     5419: 
1.82      albertel 5420: sub get_scantron_config {
                   5421:     my ($which) = @_;
1.518     raeburn  5422:     my @lines = &get_scantronformat_file();
1.82      albertel 5423:     my %config;
1.157     albertel 5424:     #FIXME probably should move to XML it has already gotten a bit much now
1.518     raeburn  5425:     foreach my $line (@lines) {
1.82      albertel 5426: 	my ($name,$descrip)=split(/:/,$line);
                   5427: 	if ($name ne $which ) { next; }
                   5428: 	chomp($line);
                   5429: 	my @config=split(/:/,$line);
                   5430: 	$config{'name'}=$config[0];
                   5431: 	$config{'description'}=$config[1];
                   5432: 	$config{'CODElocation'}=$config[2];
                   5433: 	$config{'CODEstart'}=$config[3];
                   5434: 	$config{'CODElength'}=$config[4];
                   5435: 	$config{'IDstart'}=$config[5];
                   5436: 	$config{'IDlength'}=$config[6];
                   5437: 	$config{'Qstart'}=$config[7];
1.497     foxr     5438:  	$config{'Qlength'}=$config[8];
1.82      albertel 5439: 	$config{'Qoff'}=$config[9];
                   5440: 	$config{'Qon'}=$config[10];
1.157     albertel 5441: 	$config{'PaperID'}=$config[11];
                   5442: 	$config{'PaperIDlength'}=$config[12];
                   5443: 	$config{'FirstName'}=$config[13];
                   5444: 	$config{'FirstNamelength'}=$config[14];
                   5445: 	$config{'LastName'}=$config[15];
                   5446: 	$config{'LastNamelength'}=$config[16];
1.82      albertel 5447: 	last;
                   5448:     }
                   5449:     return %config;
                   5450: }
                   5451: 
1.423     albertel 5452: =pod 
                   5453: 
                   5454: =item username_to_idmap
                   5455: 
1.556     weissno  5456:     creates a hash keyed by student/employee ID with values of the corresponding
1.423     albertel 5457:     student username:domain.
                   5458: 
                   5459:   Arguments:
                   5460: 
                   5461:     $classlist - reference to the class list hash. This is a hash
                   5462:                  keyed by student name:domain  whose elements are references
1.424     albertel 5463:                  to arrays containing various chunks of information
1.423     albertel 5464:                  about the student. (See loncoursedata for more info).
                   5465: 
                   5466:   Returns
                   5467:     %idmap - the constructed hash
                   5468: 
                   5469: =cut
                   5470: 
1.82      albertel 5471: sub username_to_idmap {
                   5472:     my ($classlist)= @_;
                   5473:     my %idmap;
                   5474:     foreach my $student (keys(%$classlist)) {
                   5475: 	$idmap{$classlist->{$student}->[&Apache::loncoursedata::CL_ID]}=
                   5476: 	    $student;
                   5477:     }
                   5478:     return %idmap;
                   5479: }
1.423     albertel 5480: 
                   5481: =pod
                   5482: 
1.424     albertel 5483: =item scantron_fixup_scanline
1.423     albertel 5484: 
                   5485:    Process a requested correction to a scanline.
                   5486: 
                   5487:   Arguments:
                   5488:     $scantron_config   - hash from &get_scantron_config()
                   5489:     $scan_data         - hash of correction information 
                   5490:                           (see &scantron_getfile())
                   5491:     $line              - existing scanline
                   5492:     $whichline         - line number of the passed in scanline
                   5493:     $field             - type of change to process 
                   5494:                          (either 
1.573     bisitz   5495:                           'ID'     -> correct the student/employee ID
1.423     albertel 5496:                           'CODE'   -> correct the CODE
                   5497:                           'answer' -> fixup the submitted answers)
                   5498:     
                   5499:    $args               - hash of additional info,
                   5500:                           - 'ID' 
                   5501:                                'newid' -> studentID to use in replacement
1.424     albertel 5502:                                           of existing one
1.423     albertel 5503:                           - 'CODE' 
                   5504:                                'CODE_ignore_dup' - set to true if duplicates
                   5505:                                                    should be ignored.
                   5506: 	                       'CODE' - is new code or 'use_unfound'
1.424     albertel 5507:                                         if the existing unfound code should
1.423     albertel 5508:                                         be used as is
                   5509:                           - 'answer'
                   5510:                                'response' - new answer or 'none' if blank
                   5511:                                'question' - the bubble line to change
1.503     raeburn  5512:                                'questionnum' - the question identifier,
                   5513:                                                may include subquestion. 
1.423     albertel 5514: 
                   5515:   Returns:
                   5516:     $line - the modified scanline
                   5517: 
                   5518:   Side effects: 
                   5519:     $scan_data - may be updated
                   5520: 
                   5521: =cut
                   5522: 
1.82      albertel 5523: 
1.157     albertel 5524: sub scantron_fixup_scanline {
                   5525:     my ($scantron_config,$scan_data,$line,$whichline,$field,$args)=@_;
                   5526:     if ($field eq 'ID') {
                   5527: 	if (length($args->{'newid'}) > $$scantron_config{'IDlength'}) {
1.186     albertel 5528: 	    return ($line,1,'New value too large');
1.157     albertel 5529: 	}
                   5530: 	if (length($args->{'newid'}) < $$scantron_config{'IDlength'}) {
                   5531: 	    $args->{'newid'}=sprintf('%-'.$$scantron_config{'IDlength'}.'s',
                   5532: 				     $args->{'newid'});
                   5533: 	}
                   5534: 	substr($line,$$scantron_config{'IDstart'}-1,
                   5535: 	       $$scantron_config{'IDlength'})=$args->{'newid'};
                   5536: 	if ($args->{'newid'}=~/^\s*$/) {
                   5537: 	    &scan_data($scan_data,"$whichline.user",
                   5538: 		       $args->{'username'}.':'.$args->{'domain'});
                   5539: 	}
1.186     albertel 5540:     } elsif ($field eq 'CODE') {
1.192     albertel 5541: 	if ($args->{'CODE_ignore_dup'}) {
                   5542: 	    &scan_data($scan_data,"$whichline.CODE_ignore_dup",'1');
                   5543: 	}
                   5544: 	&scan_data($scan_data,"$whichline.useCODE",'1');
                   5545: 	if ($args->{'CODE'} ne 'use_unfound') {
1.191     albertel 5546: 	    if (length($args->{'CODE'}) > $$scantron_config{'CODElength'}) {
                   5547: 		return ($line,1,'New CODE value too large');
                   5548: 	    }
                   5549: 	    if (length($args->{'CODE'}) < $$scantron_config{'CODElength'}) {
                   5550: 		$args->{'CODE'}=sprintf('%-'.$$scantron_config{'CODElength'}.'s',$args->{'CODE'});
                   5551: 	    }
                   5552: 	    substr($line,$$scantron_config{'CODEstart'}-1,
                   5553: 		   $$scantron_config{'CODElength'})=$args->{'CODE'};
1.186     albertel 5554: 	}
1.157     albertel 5555:     } elsif ($field eq 'answer') {
1.497     foxr     5556: 	my $length=$scantron_config->{'Qlength'};
1.157     albertel 5557: 	my $off=$scantron_config->{'Qoff'};
                   5558: 	my $on=$scantron_config->{'Qon'};
1.497     foxr     5559: 	my $answer=${off}x$length;
                   5560: 	if ($args->{'response'} eq 'none') {
                   5561: 	    &scan_data($scan_data,
1.503     raeburn  5562: 		       "$whichline.no_bubble.".$args->{'questionnum'},'1');
1.497     foxr     5563: 	} else {
                   5564: 	    if ($on eq 'letter') {
                   5565: 		my @alphabet=('A'..'Z');
                   5566: 		$answer=$alphabet[$args->{'response'}];
                   5567: 	    } elsif ($on eq 'number') {
                   5568: 		$answer=$args->{'response'}+1;
                   5569: 		if ($answer == 10) { $answer = '0'; }
1.274     albertel 5570: 	    } else {
1.497     foxr     5571: 		substr($answer,$args->{'response'},1)=$on;
1.274     albertel 5572: 	    }
1.497     foxr     5573: 	    &scan_data($scan_data,
1.503     raeburn  5574: 		       "$whichline.no_bubble.".$args->{'questionnum'},undef,'1');
1.157     albertel 5575: 	}
1.497     foxr     5576: 	my $where=$length*($args->{'question'}-1)+$scantron_config->{'Qstart'};
                   5577: 	substr($line,$where-1,$length)=$answer;
1.157     albertel 5578:     }
                   5579:     return $line;
                   5580: }
1.423     albertel 5581: 
                   5582: =pod
                   5583: 
                   5584: =item scan_data
                   5585: 
                   5586:     Edit or look up  an item in the scan_data hash.
                   5587: 
                   5588:   Arguments:
                   5589:     $scan_data  - The hash (see scantron_getfile)
                   5590:     $key        - shorthand of the key to edit (actual key is
1.424     albertel 5591:                   scantronfilename_key).
1.423     albertel 5592:     $data        - New value of the hash entry.
                   5593:     $delete      - If true, the entry is removed from the hash.
                   5594: 
                   5595:   Returns:
                   5596:     The new value of the hash table field (undefined if deleted).
                   5597: 
                   5598: =cut
                   5599: 
                   5600: 
1.157     albertel 5601: sub scan_data {
                   5602:     my ($scan_data,$key,$value,$delete)=@_;
1.257     albertel 5603:     my $filename=$env{'form.scantron_selectfile'};
1.157     albertel 5604:     if (defined($value)) {
                   5605: 	$scan_data->{$filename.'_'.$key} = $value;
                   5606:     }
                   5607:     if ($delete) { delete($scan_data->{$filename.'_'.$key}); }
                   5608:     return $scan_data->{$filename.'_'.$key};
                   5609: }
1.423     albertel 5610: 
1.495     albertel 5611: # ----- These first few routines are general use routines.----
                   5612: 
                   5613: # Return the number of occurences of a pattern in a string.
                   5614: 
                   5615: sub occurence_count {
                   5616:     my ($string, $pattern) = @_;
                   5617: 
                   5618:     my @matches = ($string =~ /$pattern/g);
                   5619: 
                   5620:     return scalar(@matches);
                   5621: }
                   5622: 
                   5623: 
                   5624: # Take a string known to have digits and convert all the
                   5625: # digits into letters in the range J,A..I.
                   5626: 
                   5627: sub digits_to_letters {
                   5628:     my ($input) = @_;
                   5629: 
                   5630:     my @alphabet = ('J', 'A'..'I');
                   5631: 
                   5632:     my @input    = split(//, $input);
                   5633:     my $output ='';
                   5634:     for (my $i = 0; $i < scalar(@input); $i++) {
                   5635: 	if ($input[$i] =~ /\d/) {
                   5636: 	    $output .= $alphabet[$input[$i]];
                   5637: 	} else {
                   5638: 	    $output .= $input[$i];
                   5639: 	}
                   5640:     }
                   5641:     return $output;
                   5642: }
                   5643: 
1.423     albertel 5644: =pod 
                   5645: 
                   5646: =item scantron_parse_scanline
                   5647: 
                   5648:   Decodes a scanline from the selected scantron file
                   5649: 
                   5650:  Arguments:
                   5651:     line             - The text of the scantron file line to process
                   5652:     whichline        - Line number
                   5653:     scantron_config  - Hash describing the format of the scantron lines.
                   5654:     scan_data        - Hash of extra information about the scanline
                   5655:                        (see scantron_getfile for more information)
                   5656:     just_header      - True if should not process question answers but only
                   5657:                        the stuff to the left of the answers.
                   5658:  Returns:
                   5659:    Hash containing the result of parsing the scanline
                   5660: 
                   5661:    Keys are all proceeded by the string 'scantron.'
                   5662: 
                   5663:        CODE    - the CODE in use for this scanline
                   5664:        useCODE - 1 if the CODE is invalid but it usage has been forced
                   5665:                  by the operator
                   5666:        CODE_ignore_dup - 1 if the CODE is a duplicated use when unique
                   5667:                             CODEs were selected, but the usage has been
                   5668:                             forced by the operator
1.556     weissno  5669:        ID  - student/employee ID
1.423     albertel 5670:        PaperID - if used, the ID number printed on the sheet when the 
                   5671:                  paper was scanned
                   5672:        FirstName - first name from the sheet
                   5673:        LastName  - last name from the sheet
                   5674: 
                   5675:      if just_header was not true these key may also exist
                   5676: 
1.447     foxr     5677:        missingerror - a list of bubble ranges that are considered to be answers
                   5678:                       to a single question that don't have any bubbles filled in.
                   5679:                       Of the form questionnumber:firstbubblenumber:count.
                   5680:        doubleerror  - a list of bubble ranges that are considered to be answers
                   5681:                       to a single question that have more than one bubble filled in.
                   5682:                       Of the form questionnumber::firstbubblenumber:count
                   5683:    
                   5684:                 In the above, count is the number of bubble responses in the
                   5685:                 input line needed to represent the possible answers to the question.
                   5686:                 e.g. a radioresponse with 15 choices in an answer sheet with 10 choices
                   5687:                 per line would have count = 2.
                   5688: 
1.423     albertel 5689:        maxquest     - the number of the last bubble line that was parsed
                   5690: 
                   5691:        (<number> starts at 1)
                   5692:        <number>.answer - zero or more letters representing the selected
                   5693:                          letters from the scanline for the bubble line 
                   5694:                          <number>.
                   5695:                          if blank there was either no bubble or there where
                   5696:                          multiple bubbles, (consult the keys missingerror and
                   5697:                          doubleerror if this is an error condition)
                   5698: 
                   5699: =cut
                   5700: 
1.82      albertel 5701: sub scantron_parse_scanline {
1.423     albertel 5702:     my ($line,$whichline,$scantron_config,$scan_data,$just_header)=@_;
1.470     foxr     5703: 
1.82      albertel 5704:     my %record;
1.550     raeburn  5705:     my $lastpos = $env{'form.scantron_maxbubble'}*$$scantron_config{'Qlength'};
                   5706:     my $questions=substr($line,$$scantron_config{'Qstart'}-1,$lastpos);  # Answers
1.422     foxr     5707:     my $data=substr($line,0,$$scantron_config{'Qstart'}-1);     # earlier stuff
1.278     albertel 5708:     if (!($$scantron_config{'CODElocation'} eq 0 ||
                   5709: 	  $$scantron_config{'CODElocation'} eq 'none')) {
                   5710: 	if ($$scantron_config{'CODElocation'} < 0 ||
                   5711: 	    $$scantron_config{'CODElocation'} eq 'letter' ||
                   5712: 	    $$scantron_config{'CODElocation'} eq 'number') {
1.191     albertel 5713: 	    $record{'scantron.CODE'}=substr($data,
                   5714: 					    $$scantron_config{'CODEstart'}-1,
1.83      albertel 5715: 					    $$scantron_config{'CODElength'});
1.191     albertel 5716: 	    if (&scan_data($scan_data,"$whichline.useCODE")) {
                   5717: 		$record{'scantron.useCODE'}=1;
                   5718: 	    }
1.192     albertel 5719: 	    if (&scan_data($scan_data,"$whichline.CODE_ignore_dup")) {
                   5720: 		$record{'scantron.CODE_ignore_dup'}=1;
                   5721: 	    }
1.82      albertel 5722: 	} else {
                   5723: 	    #FIXME interpret first N questions
                   5724: 	}
                   5725:     }
1.83      albertel 5726:     $record{'scantron.ID'}=substr($data,$$scantron_config{'IDstart'}-1,
                   5727: 				  $$scantron_config{'IDlength'});
1.157     albertel 5728:     $record{'scantron.PaperID'}=
                   5729: 	substr($data,$$scantron_config{'PaperID'}-1,
                   5730: 	       $$scantron_config{'PaperIDlength'});
                   5731:     $record{'scantron.FirstName'}=
                   5732: 	substr($data,$$scantron_config{'FirstName'}-1,
                   5733: 	       $$scantron_config{'FirstNamelength'});
                   5734:     $record{'scantron.LastName'}=
                   5735: 	substr($data,$$scantron_config{'LastName'}-1,
                   5736: 	       $$scantron_config{'LastNamelength'});
1.423     albertel 5737:     if ($just_header) { return \%record; }
1.194     albertel 5738: 
1.82      albertel 5739:     my @alphabet=('A'..'Z');
                   5740:     my $questnum=0;
1.447     foxr     5741:     my $ansnum  =1;		# Multiple 'answer lines'/question.
                   5742: 
1.470     foxr     5743:     chomp($questions);		# Get rid of any trailing \n.
                   5744:     $questions =~ s/\r$//;      # Get rid of trailing \r too (MAC or Win uploads).
                   5745:     while (length($questions)) {
1.447     foxr     5746: 	my $answers_needed = $bubble_lines_per_response{$questnum};
1.503     raeburn  5747:         my $answer_length  = ($$scantron_config{'Qlength'} * $answers_needed)
                   5748:                              || 1;
                   5749:         $questnum++;
                   5750:         my $quest_id = $questnum;
                   5751:         my $currentquest = substr($questions,0,$answer_length);
                   5752:         $questions       = substr($questions,$answer_length);
                   5753:         if (length($currentquest) < $answer_length) { next; }
                   5754: 
                   5755:         if ($subdivided_bubble_lines{$questnum-1} =~ /,/) {
                   5756:             my $subquestnum = 1;
                   5757:             my $subquestions = $currentquest;
                   5758:             my @subanswers_needed = 
                   5759:                 split(/,/,$subdivided_bubble_lines{$questnum-1});  
                   5760:             foreach my $subans (@subanswers_needed) {
                   5761:                 my $subans_length =
                   5762:                     ($$scantron_config{'Qlength'} * $subans)  || 1;
                   5763:                 my $currsubquest = substr($subquestions,0,$subans_length);
                   5764:                 $subquestions   = substr($subquestions,$subans_length);
                   5765:                 $quest_id = "$questnum.$subquestnum";
                   5766:                 if (($$scantron_config{'Qon'} eq 'letter') ||
                   5767:                     ($$scantron_config{'Qon'} eq 'number')) {
                   5768:                     $ansnum = &scantron_validator_lettnum($ansnum, 
                   5769:                         $questnum,$quest_id,$subans,$currsubquest,$whichline,
                   5770:                         \@alphabet,\%record,$scantron_config,$scan_data);
                   5771:                 } else {
                   5772:                     $ansnum = &scantron_validator_positional($ansnum,
                   5773:                         $questnum,$quest_id,$subans,$currsubquest,$whichline,                        \@alphabet,\%record,$scantron_config,$scan_data);
                   5774:                 }
                   5775:                 $subquestnum ++;
                   5776:             }
                   5777:         } else {
                   5778:             if (($$scantron_config{'Qon'} eq 'letter') ||
                   5779:                 ($$scantron_config{'Qon'} eq 'number')) {
                   5780:                 $ansnum = &scantron_validator_lettnum($ansnum,$questnum,
                   5781:                     $quest_id,$answers_needed,$currentquest,$whichline,
                   5782:                     \@alphabet,\%record,$scantron_config,$scan_data);
                   5783:             } else {
                   5784:                 $ansnum = &scantron_validator_positional($ansnum,$questnum,
                   5785:                     $quest_id,$answers_needed,$currentquest,$whichline,
                   5786:                     \@alphabet,\%record,$scantron_config,$scan_data);
                   5787:             }
                   5788:         }
                   5789:     }
                   5790:     $record{'scantron.maxquest'}=$questnum;
                   5791:     return \%record;
                   5792: }
1.447     foxr     5793: 
1.503     raeburn  5794: sub scantron_validator_lettnum {
                   5795:     my ($ansnum,$questnum,$quest_id,$answers_needed,$currquest,$whichline,
                   5796:         $alphabet,$record,$scantron_config,$scan_data) = @_;
                   5797: 
                   5798:     # Qon 'letter' implies for each slot in currquest we have:
                   5799:     #    ? or * for doubles, a letter in A-Z for a bubble, and
                   5800:     #    about anything else (esp. a value of Qoff) for missing
                   5801:     #    bubbles.
                   5802:     #
                   5803:     # Qon 'number' implies each slot gives a digit that indexes the
                   5804:     #    bubbles filled, or Qoff, or a non-number for unbubbled lines,
                   5805:     #    and * or ? for double bubbles on a single line.
                   5806:     #
1.447     foxr     5807: 
1.503     raeburn  5808:     my $matchon;
                   5809:     if ($$scantron_config{'Qon'} eq 'letter') {
                   5810:         $matchon = '[A-Z]';
                   5811:     } elsif ($$scantron_config{'Qon'} eq 'number') {
                   5812:         $matchon = '\d';
                   5813:     }
                   5814:     my $occurrences = 0;
                   5815:     if (($responsetype_per_response{$questnum-1} eq 'essayresponse') ||
                   5816:         ($responsetype_per_response{$questnum-1} eq 'formularesponse') ||
1.510     raeburn  5817:         ($responsetype_per_response{$questnum-1} eq 'stringresponse') ||
                   5818:         ($responsetype_per_response{$questnum-1} eq 'imageresponse') ||
                   5819:         ($responsetype_per_response{$questnum-1} eq 'reactionresponse') ||
                   5820:         ($responsetype_per_response{$questnum-1} eq 'organicresponse')) {
1.503     raeburn  5821:         my @singlelines = split('',$currquest);
                   5822:         foreach my $entry (@singlelines) {
                   5823:             $occurrences = &occurence_count($entry,$matchon);
                   5824:             if ($occurrences > 1) {
                   5825:                 last;
                   5826:             }
                   5827:         } 
                   5828:     } else {
                   5829:         $occurrences = &occurence_count($currquest,$matchon); 
                   5830:     }
                   5831:     if (($currquest =~ /\?/ || $currquest =~ /\*/) || ($occurrences > 1)) {
                   5832:         push(@{$record->{'scantron.doubleerror'}},$quest_id);
                   5833:         for (my $ans=0; $ans<$answers_needed; $ans++) {
                   5834:             my $bubble = substr($currquest,$ans,1);
                   5835:             if ($bubble =~ /$matchon/ ) {
                   5836:                 if ($$scantron_config{'Qon'} eq 'number') {
                   5837:                     if ($bubble == 0) {
                   5838:                         $bubble = 10; 
                   5839:                     }
                   5840:                     $record->{"scantron.$ansnum.answer"} = 
                   5841:                         $alphabet->[$bubble-1];
                   5842:                 } else {
                   5843:                     $record->{"scantron.$ansnum.answer"} = $bubble;
                   5844:                 }
                   5845:             } else {
                   5846:                 $record->{"scantron.$ansnum.answer"}='';
                   5847:             }
                   5848:             $ansnum++;
                   5849:         }
                   5850:     } elsif (!defined($currquest)
                   5851:             || (&occurence_count($currquest, $$scantron_config{'Qoff'}) == length($currquest))
                   5852:             || (&occurence_count($currquest,$matchon) == 0)) {
                   5853:         for (my $ans=0; $ans<$answers_needed; $ans++ ) {
                   5854:             $record->{"scantron.$ansnum.answer"}='';
                   5855:             $ansnum++;
                   5856:         }
                   5857:         if (!&scan_data($scan_data,"$whichline.no_bubble.$quest_id")) {
                   5858:             push(@{$record->{'scantron.missingerror'}},$quest_id);
                   5859:         }
                   5860:     } else {
                   5861:         if ($$scantron_config{'Qon'} eq 'number') {
                   5862:             $currquest = &digits_to_letters($currquest);            
                   5863:         }
                   5864:         for (my $ans=0; $ans<$answers_needed; $ans++) {
                   5865:             my $bubble = substr($currquest,$ans,1);
                   5866:             $record->{"scantron.$ansnum.answer"} = $bubble;
                   5867:             $ansnum++;
                   5868:         }
                   5869:     }
                   5870:     return $ansnum;
                   5871: }
1.447     foxr     5872: 
1.503     raeburn  5873: sub scantron_validator_positional {
                   5874:     my ($ansnum,$questnum,$quest_id,$answers_needed,$currquest,
                   5875:         $whichline,$alphabet,$record,$scantron_config,$scan_data) = @_;
1.447     foxr     5876: 
1.503     raeburn  5877:     # Otherwise there's a positional notation;
                   5878:     # each bubble line requires Qlength items, and there are filled in
                   5879:     # bubbles for each case where there 'Qon' characters.
                   5880:     #
1.447     foxr     5881: 
1.503     raeburn  5882:     my @array=split($$scantron_config{'Qon'},$currquest,-1);
1.447     foxr     5883: 
1.503     raeburn  5884:     # If the split only gives us one element.. the full length of the
                   5885:     # answer string, no bubbles are filled in:
1.447     foxr     5886: 
1.507     raeburn  5887:     if ($answers_needed eq '') {
                   5888:         return;
                   5889:     }
                   5890: 
1.503     raeburn  5891:     if (length($array[0]) eq $$scantron_config{'Qlength'}*$answers_needed) {
                   5892:         for (my $ans=0; $ans<$answers_needed; $ans++ ) {
                   5893:             $record->{"scantron.$ansnum.answer"}='';
                   5894:             $ansnum++;
                   5895:         }
                   5896:         if (!&scan_data($scan_data,"$whichline.no_bubble.$quest_id")) {
                   5897:             push(@{$record->{"scantron.missingerror"}},$quest_id);
                   5898:         }
                   5899:     } elsif (scalar(@array) == 2) {
                   5900:         my $location = length($array[0]);
                   5901:         my $line_num = int($location / $$scantron_config{'Qlength'});
                   5902:         my $bubble   = $alphabet->[$location % $$scantron_config{'Qlength'}];
                   5903:         for (my $ans=0; $ans<$answers_needed; $ans++) {
                   5904:             if ($ans eq $line_num) {
                   5905:                 $record->{"scantron.$ansnum.answer"} = $bubble;
                   5906:             } else {
                   5907:                 $record->{"scantron.$ansnum.answer"} = ' ';
                   5908:             }
                   5909:             $ansnum++;
                   5910:          }
                   5911:     } else {
                   5912:         #  If there's more than one instance of a bubble character
                   5913:         #  That's a double bubble; with positional notation we can
                   5914:         #  record all the bubbles filled in as well as the
                   5915:         #  fact this response consists of multiple bubbles.
                   5916:         #
                   5917:         if (($responsetype_per_response{$questnum-1} eq 'essayresponse') ||
                   5918:             ($responsetype_per_response{$questnum-1} eq 'formularesponse') ||
1.510     raeburn  5919:             ($responsetype_per_response{$questnum-1} eq 'stringresponse') ||
                   5920:             ($responsetype_per_response{$questnum-1} eq 'imageresponse') ||
                   5921:             ($responsetype_per_response{$questnum-1} eq 'reactionresponse') ||
                   5922:             ($responsetype_per_response{$questnum-1} eq 'organicresponse')) {
1.503     raeburn  5923:             my $doubleerror = 0;
                   5924:             while (($currquest >= $$scantron_config{'Qlength'}) && 
                   5925:                    (!$doubleerror)) {
                   5926:                my $currline = substr($currquest,0,$$scantron_config{'Qlength'});
                   5927:                $currquest = substr($currquest,$$scantron_config{'Qlength'});
                   5928:                my @currarray = split($$scantron_config{'Qon'},$currline,-1);
                   5929:                if (length(@currarray) > 2) {
                   5930:                    $doubleerror = 1;
                   5931:                } 
                   5932:             }
                   5933:             if ($doubleerror) {
                   5934:                 push(@{$record->{'scantron.doubleerror'}},$quest_id);
                   5935:             }
                   5936:         } else {
                   5937:             push(@{$record->{'scantron.doubleerror'}},$quest_id);
                   5938:         }
                   5939:         my $item = $ansnum;
                   5940:         for (my $ans=0; $ans<$answers_needed; $ans++) {
                   5941:             $record->{"scantron.$item.answer"} = '';
                   5942:             $item ++;
                   5943:         }
1.447     foxr     5944: 
1.503     raeburn  5945:         my @ans=@array;
                   5946:         my $i=0;
                   5947:         my $increment = 0;
                   5948:         while ($#ans) {
                   5949:             $i+=length($ans[0]) + $increment;
                   5950:             my $line   = int($i/$$scantron_config{'Qlength'} + $ansnum);
                   5951:             my $bubble = $i%$$scantron_config{'Qlength'};
                   5952:             $record->{"scantron.$line.answer"}.=$alphabet->[$bubble];
                   5953:             shift(@ans);
                   5954:             $increment = 1;
                   5955:         }
                   5956:         $ansnum += $answers_needed;
1.82      albertel 5957:     }
1.503     raeburn  5958:     return $ansnum;
1.82      albertel 5959: }
                   5960: 
1.423     albertel 5961: =pod
                   5962: 
                   5963: =item scantron_add_delay
                   5964: 
                   5965:    Adds an error message that occurred during the grading phase to a
                   5966:    queue of messages to be shown after grading pass is complete
                   5967: 
                   5968:  Arguments:
1.424     albertel 5969:    $delayqueue  - arrary ref of hash ref of error messages
1.423     albertel 5970:    $scanline    - the scanline that caused the error
                   5971:    $errormesage - the error message
                   5972:    $errorcode   - a numeric code for the error
                   5973: 
                   5974:  Side Effects:
1.424     albertel 5975:    updates the $delayqueue to have a new hash ref of the error
1.423     albertel 5976: 
                   5977: =cut
                   5978: 
1.82      albertel 5979: sub scantron_add_delay {
1.140     albertel 5980:     my ($delayqueue,$scanline,$errormessage,$errorcode)=@_;
                   5981:     push(@$delayqueue,
                   5982: 	 {'line' => $scanline, 'emsg' => $errormessage,
                   5983: 	  'ecode' => $errorcode }
                   5984: 	 );
1.82      albertel 5985: }
                   5986: 
1.423     albertel 5987: =pod
                   5988: 
                   5989: =item scantron_find_student
                   5990: 
1.424     albertel 5991:    Finds the username for the current scanline
                   5992: 
                   5993:   Arguments:
                   5994:    $scantron_record - hash result from scantron_parse_scanline
                   5995:    $scan_data       - hash of correction information 
                   5996:                       (see &scantron_getfile() form more information)
                   5997:    $idmap           - hash from &username_to_idmap()
                   5998:    $line            - number of current scanline
                   5999:  
                   6000:   Returns:
                   6001:    Either 'username:domain' or undef if unknown
                   6002: 
1.423     albertel 6003: =cut
                   6004: 
1.82      albertel 6005: sub scantron_find_student {
1.157     albertel 6006:     my ($scantron_record,$scan_data,$idmap,$line)=@_;
1.83      albertel 6007:     my $scanID=$$scantron_record{'scantron.ID'};
1.157     albertel 6008:     if ($scanID =~ /^\s*$/) {
                   6009:  	return &scan_data($scan_data,"$line.user");
                   6010:     }
1.83      albertel 6011:     foreach my $id (keys(%$idmap)) {
1.157     albertel 6012:  	if (lc($id) eq lc($scanID)) {
                   6013:  	    return $$idmap{$id};
                   6014:  	}
1.83      albertel 6015:     }
                   6016:     return undef;
                   6017: }
                   6018: 
1.423     albertel 6019: =pod
                   6020: 
                   6021: =item scantron_filter
                   6022: 
1.424     albertel 6023:    Filter sub for lonnavmaps, filters out hidden resources if ignore
                   6024:    hidden resources was selected
                   6025: 
1.423     albertel 6026: =cut
                   6027: 
1.83      albertel 6028: sub scantron_filter {
                   6029:     my ($curres)=@_;
1.331     albertel 6030: 
                   6031:     if (ref($curres) && $curres->is_problem()) {
                   6032: 	# if the user has asked to not have either hidden
                   6033: 	# or 'randomout' controlled resources to be graded
                   6034: 	# don't include them
                   6035: 	if ($env{'form.scantron_options_hidden'} eq 'ignore_hidden'
                   6036: 	    && $curres->randomout) {
                   6037: 	    return 0;
                   6038: 	}
1.83      albertel 6039: 	return 1;
                   6040:     }
                   6041:     return 0;
1.82      albertel 6042: }
                   6043: 
1.423     albertel 6044: =pod
                   6045: 
                   6046: =item scantron_process_corrections
                   6047: 
1.424     albertel 6048:    Gets correction information out of submitted form data and corrects
                   6049:    the scanline
                   6050: 
1.423     albertel 6051: =cut
                   6052: 
1.157     albertel 6053: sub scantron_process_corrections {
                   6054:     my ($r) = @_;
1.257     albertel 6055:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.157     albertel 6056:     my ($scanlines,$scan_data)=&scantron_getfile();
                   6057:     my $classlist=&Apache::loncoursedata::get_classlist();
1.257     albertel 6058:     my $which=$env{'form.scantron_line'};
1.200     albertel 6059:     my $line=&scantron_get_line($scanlines,$scan_data,$which);
1.157     albertel 6060:     my ($skip,$err,$errmsg);
1.257     albertel 6061:     if ($env{'form.scantron_skip_record'}) {
1.157     albertel 6062: 	$skip=1;
1.257     albertel 6063:     } elsif ($env{'form.scantron_corrections'} =~ /^(duplicate|incorrect)ID$/) {
                   6064: 	my $newstudent=$env{'form.scantron_username'}.':'.
                   6065: 	    $env{'form.scantron_domain'};
1.157     albertel 6066: 	my $newid=$classlist->{$newstudent}->[&Apache::loncoursedata::CL_ID];
                   6067: 	($line,$err,$errmsg)=
                   6068: 	    &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,$which,
                   6069: 				     'ID',{'newid'=>$newid,
1.257     albertel 6070: 				    'username'=>$env{'form.scantron_username'},
                   6071: 				    'domain'=>$env{'form.scantron_domain'}});
                   6072:     } elsif ($env{'form.scantron_corrections'} =~ /^(duplicate|incorrect)CODE$/) {
                   6073: 	my $resolution=$env{'form.scantron_CODE_resolution'};
1.190     albertel 6074: 	my $newCODE;
1.192     albertel 6075: 	my %args;
1.190     albertel 6076: 	if      ($resolution eq 'use_unfound') {
1.191     albertel 6077: 	    $newCODE='use_unfound';
1.190     albertel 6078: 	} elsif ($resolution eq 'use_found') {
1.257     albertel 6079: 	    $newCODE=$env{'form.scantron_CODE_selectedvalue'};
1.190     albertel 6080: 	} elsif ($resolution eq 'use_typed') {
1.257     albertel 6081: 	    $newCODE=$env{'form.scantron_CODE_newvalue'};
1.194     albertel 6082: 	} elsif ($resolution =~ /^use_closest_(\d+)/) {
1.257     albertel 6083: 	    $newCODE=$env{"form.scantron_CODE_closest_$1"};
1.190     albertel 6084: 	}
1.257     albertel 6085: 	if ($env{'form.scantron_corrections'} eq 'duplicateCODE') {
1.192     albertel 6086: 	    $args{'CODE_ignore_dup'}=1;
                   6087: 	}
                   6088: 	$args{'CODE'}=$newCODE;
1.186     albertel 6089: 	($line,$err,$errmsg)=
                   6090: 	    &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,$which,
1.192     albertel 6091: 				     'CODE',\%args);
1.257     albertel 6092:     } elsif ($env{'form.scantron_corrections'} =~ /^(missing|double)bubble$/) {
                   6093: 	foreach my $question (split(',',$env{'form.scantron_questions'})) {
1.157     albertel 6094: 	    ($line,$err,$errmsg)=
                   6095: 		&scantron_fixup_scanline(\%scantron_config,$scan_data,$line,
                   6096: 					 $which,'answer',
                   6097: 					 { 'question'=>$question,
1.503     raeburn  6098: 		      		   'response'=>$env{"form.scantron_correct_Q_$question"},
                   6099:                                    'questionnum'=>$env{"form.scantron_questionnum_Q_$question"}});
1.157     albertel 6100: 	    if ($err) { last; }
                   6101: 	}
                   6102:     }
                   6103:     if ($err) {
1.398     albertel 6104: 	$r->print("<span class=\"LC_warning\">Unable to accept last correction, an error occurred :$errmsg:</span>");
1.157     albertel 6105:     } else {
1.200     albertel 6106: 	&scantron_put_line($scanlines,$scan_data,$which,$line,$skip);
1.157     albertel 6107: 	&scantron_putfile($scanlines,$scan_data);
                   6108:     }
                   6109: }
                   6110: 
1.423     albertel 6111: =pod
                   6112: 
                   6113: =item reset_skipping_status
                   6114: 
1.424     albertel 6115:    Forgets the current set of remember skipped scanlines (and thus
                   6116:    reverts back to considering all lines in the
                   6117:    scantron_skipped_<filename> file)
                   6118: 
1.423     albertel 6119: =cut
                   6120: 
1.200     albertel 6121: sub reset_skipping_status {
                   6122:     my ($scanlines,$scan_data)=&scantron_getfile();
                   6123:     &scan_data($scan_data,'remember_skipping',undef,1);
                   6124:     &scantron_putfile(undef,$scan_data);
                   6125: }
                   6126: 
1.423     albertel 6127: =pod
                   6128: 
                   6129: =item start_skipping
                   6130: 
1.424     albertel 6131:    Marks a scanline to be skipped. 
                   6132: 
1.423     albertel 6133: =cut
                   6134: 
1.376     albertel 6135: sub start_skipping {
1.200     albertel 6136:     my ($scan_data,$i)=@_;
                   6137:     my %remembered=split(':',&scan_data($scan_data,'remember_skipping'));
1.376     albertel 6138:     if ($env{'form.scantron_options_redo'} =~ /^redo_/) {
                   6139: 	$remembered{$i}=2;
                   6140:     } else {
                   6141: 	$remembered{$i}=1;
                   6142:     }
1.200     albertel 6143:     &scan_data($scan_data,'remember_skipping',join(':',%remembered));
                   6144: }
                   6145: 
1.423     albertel 6146: =pod
                   6147: 
                   6148: =item should_be_skipped
                   6149: 
1.424     albertel 6150:    Checks whether a scanline should be skipped.
                   6151: 
1.423     albertel 6152: =cut
                   6153: 
1.200     albertel 6154: sub should_be_skipped {
1.376     albertel 6155:     my ($scanlines,$scan_data,$i)=@_;
1.257     albertel 6156:     if ($env{'form.scantron_options_redo'} !~ /^redo_/) {
1.200     albertel 6157: 	# not redoing old skips
1.376     albertel 6158: 	if ($scanlines->{'skipped'}[$i]) { return 1; }
1.200     albertel 6159: 	return 0;
                   6160:     }
                   6161:     my %remembered=split(':',&scan_data($scan_data,'remember_skipping'));
1.376     albertel 6162: 
                   6163:     if (exists($remembered{$i}) && $remembered{$i} != 2 ) {
                   6164: 	return 0;
                   6165:     }
1.200     albertel 6166:     return 1;
                   6167: }
                   6168: 
1.423     albertel 6169: =pod
                   6170: 
                   6171: =item remember_current_skipped
                   6172: 
1.424     albertel 6173:    Discovers what scanlines are in the scantron_skipped_<filename>
                   6174:    file and remembers them into scan_data for later use.
                   6175: 
1.423     albertel 6176: =cut
                   6177: 
1.200     albertel 6178: sub remember_current_skipped {
                   6179:     my ($scanlines,$scan_data)=&scantron_getfile();
                   6180:     my %to_remember;
                   6181:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
                   6182: 	if ($scanlines->{'skipped'}[$i]) {
                   6183: 	    $to_remember{$i}=1;
                   6184: 	}
                   6185:     }
1.376     albertel 6186: 
1.200     albertel 6187:     &scan_data($scan_data,'remember_skipping',join(':',%to_remember));
                   6188:     &scantron_putfile(undef,$scan_data);
                   6189: }
                   6190: 
1.423     albertel 6191: =pod
                   6192: 
                   6193: =item check_for_error
                   6194: 
1.424     albertel 6195:     Checks if there was an error when attempting to remove a specific
                   6196:     scantron_.. bubble sheet data file. Prints out an error if
                   6197:     something went wrong.
                   6198: 
1.423     albertel 6199: =cut
                   6200: 
1.200     albertel 6201: sub check_for_error {
                   6202:     my ($r,$result)=@_;
                   6203:     if ($result ne 'ok' && $result ne 'not_found' ) {
1.492     albertel 6204: 	$r->print(&mt("An error occurred ([_1]) when trying to remove the existing corrections.",$result));
1.200     albertel 6205:     }
                   6206: }
1.157     albertel 6207: 
1.423     albertel 6208: =pod
                   6209: 
                   6210: =item scantron_warning_screen
                   6211: 
1.424     albertel 6212:    Interstitial screen to make sure the operator has selected the
                   6213:    correct options before we start the validation phase.
                   6214: 
1.423     albertel 6215: =cut
                   6216: 
1.203     albertel 6217: sub scantron_warning_screen {
                   6218:     my ($button_text)=@_;
1.257     albertel 6219:     my $title=&Apache::lonnet::gettitle($env{'form.selectpage'});
1.284     albertel 6220:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.373     albertel 6221:     my $CODElist;
1.284     albertel 6222:     if ($scantron_config{'CODElocation'} &&
                   6223: 	$scantron_config{'CODEstart'} &&
                   6224: 	$scantron_config{'CODElength'}) {
                   6225: 	$CODElist=$env{'form.scantron_CODElist'};
1.398     albertel 6226: 	if ($env{'form.scantron_CODElist'} eq '') { $CODElist='<span class="LC_warning">None</span>'; }
1.284     albertel 6227: 	$CODElist=
1.492     albertel 6228: 	    '<tr><td><b>'.&mt('List of CODES to validate against:').'</b></td><td><tt>'.
1.373     albertel 6229: 	    $env{'form.scantron_CODElist'}.'</tt></td></tr>';
1.284     albertel 6230:     }
1.492     albertel 6231:     return ('
1.203     albertel 6232: <p>
1.492     albertel 6233: <span class="LC_warning">
                   6234: '.&mt('Please double check the information below before clicking on \'[_1]\'',&mt($button_text)).'</span>
1.203     albertel 6235: </p>
                   6236: <table>
1.492     albertel 6237: <tr><td><b>'.&mt('Sequence to be Graded:').'</b></td><td>'.$title.'</td></tr>
                   6238: <tr><td><b>'.&mt('Data File that will be used:').'</b></td><td><tt>'.$env{'form.scantron_selectfile'}.'</tt></td></tr>
                   6239: '.$CODElist.'
1.203     albertel 6240: </table>
                   6241: <br />
1.492     albertel 6242: <p> '.&mt('If this information is correct, please click on \'[_1]\'.',&mt($button_text)).'</p>
                   6243: <p> '.&mt('If something is incorrect, please click the \'Grading Menu\' button to start over.').'</p>
1.203     albertel 6244: 
                   6245: <br />
1.492     albertel 6246: ');
1.203     albertel 6247: }
                   6248: 
1.423     albertel 6249: =pod
                   6250: 
                   6251: =item scantron_do_warning
                   6252: 
1.424     albertel 6253:    Check if the operator has picked something for all required
                   6254:    fields. Error out if something is missing.
                   6255: 
1.423     albertel 6256: =cut
                   6257: 
1.203     albertel 6258: sub scantron_do_warning {
                   6259:     my ($r)=@_;
1.324     albertel 6260:     my ($symb)=&get_symb($r);
1.203     albertel 6261:     if (!$symb) {return '';}
1.324     albertel 6262:     my $default_form_data=&defaultFormData($symb);
1.203     albertel 6263:     $r->print(&scantron_form_start().$default_form_data);
1.257     albertel 6264:     if ( $env{'form.selectpage'} eq '' ||
                   6265: 	 $env{'form.scantron_selectfile'} eq '' ||
                   6266: 	 $env{'form.scantron_format'} eq '' ) {
1.492     albertel 6267: 	$r->print("<p>".&mt('You have forgetten to specify some information. Please go Back and try again.')."</p>");
1.257     albertel 6268: 	if ( $env{'form.selectpage'} eq '') {
1.492     albertel 6269: 	    $r->print('<p><span class="LC_error">'.&mt('You have not selected a Sequence to grade').'</span></p>');
1.237     albertel 6270: 	} 
1.257     albertel 6271: 	if ( $env{'form.scantron_selectfile'} eq '') {
1.492     albertel 6272: 	    $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 6273: 	} 
1.257     albertel 6274: 	if ( $env{'form.scantron_format'} eq '') {
1.492     albertel 6275: 	    $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 6276: 	} 
                   6277:     } else {
1.265     www      6278: 	my $warning=&scantron_warning_screen('Grading: Validate Records');
1.492     albertel 6279: 	$r->print('
                   6280: '.$warning.'
                   6281: <input type="submit" name="submit" value="'.&mt('Grading: Validate Records').'" />
1.203     albertel 6282: <input type="hidden" name="command" value="scantron_validate" />
1.492     albertel 6283: ');
1.237     albertel 6284:     }
1.352     albertel 6285:     $r->print("</form><br />".&show_grading_menu_form($symb));
1.203     albertel 6286:     return '';
                   6287: }
                   6288: 
1.423     albertel 6289: =pod
                   6290: 
                   6291: =item scantron_form_start
                   6292: 
1.424     albertel 6293:     html hidden input for remembering all selected grading options
                   6294: 
1.423     albertel 6295: =cut
                   6296: 
1.203     albertel 6297: sub scantron_form_start {
                   6298:     my ($max_bubble)=@_;
                   6299:     my $result= <<SCANTRONFORM;
                   6300: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantronupload">
1.257     albertel 6301:   <input type="hidden" name="selectpage" value="$env{'form.selectpage'}" />
                   6302:   <input type="hidden" name="scantron_format" value="$env{'form.scantron_format'}" />
                   6303:   <input type="hidden" name="scantron_selectfile" value="$env{'form.scantron_selectfile'}" />
1.218     albertel 6304:   <input type="hidden" name="scantron_maxbubble" value="$max_bubble" />
1.257     albertel 6305:   <input type="hidden" name="scantron_CODElist" value="$env{'form.scantron_CODElist'}" />
                   6306:   <input type="hidden" name="scantron_CODEunique" value="$env{'form.scantron_CODEunique'}" />
                   6307:   <input type="hidden" name="scantron_options_redo" value="$env{'form.scantron_options_redo'}" />
                   6308:   <input type="hidden" name="scantron_options_ignore" value="$env{'form.scantron_options_ignore'}" />
1.331     albertel 6309:   <input type="hidden" name="scantron_options_hidden" value="$env{'form.scantron_options_hidden'}" />
1.203     albertel 6310: SCANTRONFORM
1.447     foxr     6311: 
                   6312:   my $line = 0;
                   6313:     while (defined($env{"form.scantron.bubblelines.$line"})) {
                   6314:        my $chunk =
                   6315: 	   '<input type="hidden" name="scantron.bubblelines.'.$line.'" value="'.$env{"form.scantron.bubblelines.$line"}.'" />'."\n";
1.448     foxr     6316:        $chunk .=
                   6317: 	   '<input type="hidden" name="scantron.first_bubble_line.'.$line.'" value="'.$env{"form.scantron.first_bubble_line.$line"}.'" />'."\n";
1.503     raeburn  6318:        $chunk .= 
                   6319:            '<input type="hidden" name="scantron.sub_bubblelines.'.$line.'" value="'.$env{"form.scantron.sub_bubblelines.$line"}.'" />'."\n";
1.504     raeburn  6320:        $chunk .=
                   6321:            '<input type="hidden" name="scantron.responsetype.'.$line.'" value="'.$env{"form.scantron.responsetype.$line"}.'" />'."\n";
1.447     foxr     6322:        $result .= $chunk;
                   6323:        $line++;
                   6324:    }
1.203     albertel 6325:     return $result;
                   6326: }
                   6327: 
1.423     albertel 6328: =pod
                   6329: 
                   6330: =item scantron_validate_file
                   6331: 
1.424     albertel 6332:     Dispatch routine for doing validation of a bubble sheet data file.
                   6333: 
                   6334:     Also processes any necessary information resets that need to
                   6335:     occur before validation begins (ignore previous corrections,
                   6336:     restarting the skipped records processing)
                   6337: 
1.423     albertel 6338: =cut
                   6339: 
1.157     albertel 6340: sub scantron_validate_file {
                   6341:     my ($r) = @_;
1.324     albertel 6342:     my ($symb)=&get_symb($r);
1.157     albertel 6343:     if (!$symb) {return '';}
1.324     albertel 6344:     my $default_form_data=&defaultFormData($symb);
1.200     albertel 6345:     
                   6346:     # do the detection of only doing skipped records first befroe we delete
1.424     albertel 6347:     # them when doing the corrections reset
1.257     albertel 6348:     if ($env{'form.scantron_options_redo'} ne 'redo_skipped_ready') {
1.200     albertel 6349: 	&reset_skipping_status();
                   6350:     }
1.257     albertel 6351:     if ($env{'form.scantron_options_redo'} eq 'redo_skipped') {
1.200     albertel 6352: 	&remember_current_skipped();
1.257     albertel 6353: 	$env{'form.scantron_options_redo'}='redo_skipped_ready';
1.200     albertel 6354:     }
                   6355: 
1.257     albertel 6356:     if ($env{'form.scantron_options_ignore'} eq 'ignore_corrections') {
1.200     albertel 6357: 	&check_for_error($r,&scantron_remove_file('corrected'));
                   6358: 	&check_for_error($r,&scantron_remove_file('skipped'));
                   6359: 	&check_for_error($r,&scantron_remove_scan_data());
1.257     albertel 6360: 	$env{'form.scantron_options_ignore'}='done';
1.192     albertel 6361:     }
1.200     albertel 6362: 
1.257     albertel 6363:     if ($env{'form.scantron_corrections'}) {
1.157     albertel 6364: 	&scantron_process_corrections($r);
                   6365:     }
1.503     raeburn  6366:     $r->print('<p>'.&mt('Gathering necessary information.').'</p>');$r->rflush();
1.157     albertel 6367:     #get the student pick code ready
                   6368:     $r->print(&Apache::loncommon::studentbrowser_javascript());
1.582     raeburn  6369:     my $nav_error;
                   6370:     my $max_bubble=&scantron_get_maxbubble(\$nav_error);
                   6371:     if ($nav_error) {
                   6372:         $r->print(&navmap_errormsg());
                   6373:         return '';
                   6374:     }
1.203     albertel 6375:     my $result=&scantron_form_start($max_bubble).$default_form_data;
1.157     albertel 6376:     $r->print($result);
                   6377:     
1.334     albertel 6378:     my @validate_phases=( 'sequence',
                   6379: 			  'ID',
1.157     albertel 6380: 			  'CODE',
                   6381: 			  'doublebubble',
                   6382: 			  'missingbubbles');
1.257     albertel 6383:     if (!$env{'form.validatepass'}) {
                   6384: 	$env{'form.validatepass'} = 0;
1.157     albertel 6385:     }
1.257     albertel 6386:     my $currentphase=$env{'form.validatepass'};
1.157     albertel 6387: 
1.448     foxr     6388: 
1.157     albertel 6389:     my $stop=0;
                   6390:     while (!$stop && $currentphase < scalar(@validate_phases)) {
1.503     raeburn  6391: 	$r->print(&mt('Validating '.$validate_phases[$currentphase]).'<br />');
1.157     albertel 6392: 	$r->rflush();
                   6393: 	my $which="scantron_validate_".$validate_phases[$currentphase];
                   6394: 	{
                   6395: 	    no strict 'refs';
                   6396: 	    ($stop,$currentphase)=&$which($r,$currentphase);
                   6397: 	}
                   6398:     }
                   6399:     if (!$stop) {
1.203     albertel 6400: 	my $warning=&scantron_warning_screen('Start Grading');
1.542     raeburn  6401: 	$r->print(&mt('Validation process complete.').'<br />'.
                   6402:                   $warning.
                   6403:                   &mt('Perform verification for each student after storage of submissions?').
                   6404:                   '&nbsp;<span class="LC_nobreak"><label>'.
                   6405:                   '<input type="radio" name="verifyrecord" value="1" />'.&mt('Yes').'</label>'.
                   6406:                   ('&nbsp;'x3).'<label>'.
                   6407:                   '<input type="radio" name="verifyrecord" value="0" checked="checked" />'.&mt('No').
                   6408:                   '</label></span><br />'.
                   6409:                   &mt('Grading will take longer if you use verification.').'<br />'.
1.572     www      6410:                   &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  6411:                   '<input type="submit" name="submit" value="'.&mt('Start Grading').'" />'.
                   6412:                   '<input type="hidden" name="command" value="scantron_process" />'."\n");
1.157     albertel 6413:     } else {
                   6414: 	$r->print('<input type="hidden" name="command" value="scantron_validate" />');
                   6415: 	$r->print("<input type='hidden' name='validatepass' value='".$currentphase."' />");
                   6416:     }
                   6417:     if ($stop) {
1.334     albertel 6418: 	if ($validate_phases[$currentphase] eq 'sequence') {
1.539     riegler  6419: 	    $r->print('<input type="submit" name="submit" value="'.&mt('Ignore').' &rarr; " />');
1.492     albertel 6420: 	    $r->print(' '.&mt('this error').' <br />');
1.334     albertel 6421: 
1.492     albertel 6422: 	    $r->print(" <p>".&mt("Or click the 'Grading Menu' button to start over.")."</p>");
1.334     albertel 6423: 	} else {
1.503     raeburn  6424:             if ($validate_phases[$currentphase] eq 'doublebubble' || $validate_phases[$currentphase] eq 'missingbubbles') {
1.539     riegler  6425: 	        $r->print('<input type="button" name="submitbutton" value="'.&mt('Continue').' &rarr;" onclick="javascript:verify_bubble_radio(this.form)" />');
1.503     raeburn  6426:             } else {
1.539     riegler  6427:                 $r->print('<input type="submit" name="submit" value="'.&mt('Continue').' &rarr;" />');
1.503     raeburn  6428:             }
1.492     albertel 6429: 	    $r->print(' '.&mt('using corrected info').' <br />');
                   6430: 	    $r->print("<input type='submit' value='".&mt("Skip")."' name='scantron_skip_record' />");
                   6431: 	    $r->print(" ".&mt("this scanline saving it for later."));
1.334     albertel 6432: 	}
1.157     albertel 6433:     }
1.352     albertel 6434:     $r->print(" </form><br />".&show_grading_menu_form($symb));
1.157     albertel 6435:     return '';
                   6436: }
                   6437: 
1.423     albertel 6438: 
                   6439: =pod
                   6440: 
                   6441: =item scantron_remove_file
                   6442: 
1.424     albertel 6443:    Removes the requested bubble sheet data file, makes sure that
                   6444:    scantron_original_<filename> is never removed
                   6445: 
                   6446: 
1.423     albertel 6447: =cut
                   6448: 
1.200     albertel 6449: sub scantron_remove_file {
1.192     albertel 6450:     my ($which)=@_;
1.257     albertel 6451:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   6452:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.192     albertel 6453:     my $file='scantron_';
1.200     albertel 6454:     if ($which eq 'corrected' || $which eq 'skipped') {
                   6455: 	$file.=$which.'_';
1.192     albertel 6456:     } else {
                   6457: 	return 'refused';
                   6458:     }
1.257     albertel 6459:     $file.=$env{'form.scantron_selectfile'};
1.200     albertel 6460:     return &Apache::lonnet::removeuserfile($cname,$cdom,$file);
                   6461: }
                   6462: 
1.423     albertel 6463: 
                   6464: =pod
                   6465: 
                   6466: =item scantron_remove_scan_data
                   6467: 
1.424     albertel 6468:    Removes all scan_data correction for the requested bubble sheet
                   6469:    data file.  (In the case that both the are doing skipped records we need
                   6470:    to remember the old skipped lines for the time being so that element
                   6471:    persists for a while.)
                   6472: 
1.423     albertel 6473: =cut
                   6474: 
1.200     albertel 6475: sub scantron_remove_scan_data {
1.257     albertel 6476:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   6477:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.192     albertel 6478:     my @keys=&Apache::lonnet::getkeys('nohist_scantrondata',$cdom,$cname);
                   6479:     my @todelete;
1.257     albertel 6480:     my $filename=$env{'form.scantron_selectfile'};
1.192     albertel 6481:     foreach my $key (@keys) {
                   6482: 	if ($key=~/^\Q$filename\E_/) {
1.257     albertel 6483: 	    if ($env{'form.scantron_options_redo'} eq 'redo_skipped_ready' &&
1.200     albertel 6484: 		$key=~/remember_skipping/) {
                   6485: 		next;
                   6486: 	    }
1.192     albertel 6487: 	    push(@todelete,$key);
                   6488: 	}
                   6489:     }
1.200     albertel 6490:     my $result;
1.192     albertel 6491:     if (@todelete) {
1.491     albertel 6492: 	$result = &Apache::lonnet::del('nohist_scantrondata',
                   6493: 				       \@todelete,$cdom,$cname);
                   6494:     } else {
                   6495: 	$result = 'ok';
1.192     albertel 6496:     }
                   6497:     return $result;
                   6498: }
                   6499: 
1.423     albertel 6500: 
                   6501: =pod
                   6502: 
                   6503: =item scantron_getfile
                   6504: 
1.424     albertel 6505:     Fetches the requested bubble sheet data file (all 3 versions), and
                   6506:     the scan_data hash
                   6507:   
                   6508:   Arguments:
                   6509:     None
                   6510: 
                   6511:   Returns:
                   6512:     2 hash references
                   6513: 
                   6514:      - first one has 
                   6515:          orig      -
                   6516:          corrected -
                   6517:          skipped   -  each of which points to an array ref of the specified
                   6518:                       file broken up into individual lines
                   6519:          count     - number of scanlines
                   6520:  
                   6521:      - second is the scan_data hash possible keys are
1.425     albertel 6522:        ($number refers to scanline numbered $number and thus the key affects
                   6523:         only that scanline
                   6524:         $bubline refers to the specific bubble line element and the aspects
                   6525:         refers to that specific bubble line element)
                   6526: 
                   6527:        $number.user - username:domain to use
                   6528:        $number.CODE_ignore_dup 
                   6529:                     - ignore the duplicate CODE error 
                   6530:        $number.useCODE
                   6531:                     - use the CODE in the scanline as is
                   6532:        $number.no_bubble.$bubline
                   6533:                     - it is valid that there is no bubbled in bubble
                   6534:                       at $number $bubline
                   6535:        remember_skipping
                   6536:                     - a frozen hash containing keys of $number and values
                   6537:                       of either 
                   6538:                         1 - we are on a 'do skipped records pass' and plan
                   6539:                             on processing this line
                   6540:                         2 - we are on a 'do skipped records pass' and this
                   6541:                             scanline has been marked to skip yet again
1.424     albertel 6542: 
1.423     albertel 6543: =cut
                   6544: 
1.157     albertel 6545: sub scantron_getfile {
1.200     albertel 6546:     #FIXME really would prefer a scantron directory
1.257     albertel 6547:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   6548:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.157     albertel 6549:     my $lines;
                   6550:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
1.257     albertel 6551: 		       'scantron_orig_'.$env{'form.scantron_selectfile'});
1.157     albertel 6552:     my %scanlines;
                   6553:     $scanlines{'orig'}=[(split("\n",$lines,-1))];
                   6554:     my $temp=$scanlines{'orig'};
                   6555:     $scanlines{'count'}=$#$temp;
                   6556: 
                   6557:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
1.257     albertel 6558: 		       'scantron_corrected_'.$env{'form.scantron_selectfile'});
1.157     albertel 6559:     if ($lines eq '-1') {
                   6560: 	$scanlines{'corrected'}=[];
                   6561:     } else {
                   6562: 	$scanlines{'corrected'}=[(split("\n",$lines,-1))];
                   6563:     }
                   6564:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
1.257     albertel 6565: 		       'scantron_skipped_'.$env{'form.scantron_selectfile'});
1.157     albertel 6566:     if ($lines eq '-1') {
                   6567: 	$scanlines{'skipped'}=[];
                   6568:     } else {
                   6569: 	$scanlines{'skipped'}=[(split("\n",$lines,-1))];
                   6570:     }
1.175     albertel 6571:     my @tmp=&Apache::lonnet::dump('nohist_scantrondata',$cdom,$cname);
1.157     albertel 6572:     if ($tmp[0] =~ /^(error:|no_such_host)/) { @tmp=(); }
                   6573:     my %scan_data = @tmp;
                   6574:     return (\%scanlines,\%scan_data);
                   6575: }
                   6576: 
1.423     albertel 6577: =pod
                   6578: 
                   6579: =item lonnet_putfile
                   6580: 
1.424     albertel 6581:    Wrapper routine to call &Apache::lonnet::finishuserfileupload
                   6582: 
                   6583:  Arguments:
                   6584:    $contents - data to store
                   6585:    $filename - filename to store $contents into
                   6586: 
                   6587:  Returns:
                   6588:    result value from &Apache::lonnet::finishuserfileupload
                   6589: 
1.423     albertel 6590: =cut
                   6591: 
1.157     albertel 6592: sub lonnet_putfile {
                   6593:     my ($contents,$filename)=@_;
1.257     albertel 6594:     my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   6595:     my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   6596:     $env{'form.sillywaytopassafilearound'}=$contents;
1.275     albertel 6597:     &Apache::lonnet::finishuserfileupload($docuname,$docudom,'sillywaytopassafilearound',$filename);
1.157     albertel 6598: 
                   6599: }
                   6600: 
1.423     albertel 6601: =pod
                   6602: 
                   6603: =item scantron_putfile
                   6604: 
1.424     albertel 6605:     Stores the current version of the bubble sheet data files, and the
                   6606:     scan_data hash. (Does not modify the original version only the
                   6607:     corrected and skipped versions.
                   6608: 
                   6609:  Arguments:
                   6610:     $scanlines - hash ref that looks like the first return value from
                   6611:                  &scantron_getfile()
                   6612:     $scan_data - hash ref that looks like the second return value from
                   6613:                  &scantron_getfile()
                   6614: 
1.423     albertel 6615: =cut
                   6616: 
1.157     albertel 6617: sub scantron_putfile {
                   6618:     my ($scanlines,$scan_data) = @_;
1.200     albertel 6619:     #FIXME really would prefer a scantron directory
1.257     albertel 6620:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   6621:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.200     albertel 6622:     if ($scanlines) {
                   6623: 	my $prefix='scantron_';
1.157     albertel 6624: # no need to update orig, shouldn't change
                   6625: #   &lonnet_putfile(join("\n",@{$scanlines->{'orig'}}),$prefix.'orig_'.
1.257     albertel 6626: #		    $env{'form.scantron_selectfile'});
1.200     albertel 6627: 	&lonnet_putfile(join("\n",@{$scanlines->{'corrected'}}),
                   6628: 			$prefix.'corrected_'.
1.257     albertel 6629: 			$env{'form.scantron_selectfile'});
1.200     albertel 6630: 	&lonnet_putfile(join("\n",@{$scanlines->{'skipped'}}),
                   6631: 			$prefix.'skipped_'.
1.257     albertel 6632: 			$env{'form.scantron_selectfile'});
1.200     albertel 6633:     }
1.175     albertel 6634:     &Apache::lonnet::put('nohist_scantrondata',$scan_data,$cdom,$cname);
1.157     albertel 6635: }
                   6636: 
1.423     albertel 6637: =pod
                   6638: 
                   6639: =item scantron_get_line
                   6640: 
1.424     albertel 6641:    Returns the correct version of the scanline
                   6642: 
                   6643:  Arguments:
                   6644:     $scanlines - hash ref that looks like the first return value from
                   6645:                  &scantron_getfile()
                   6646:     $scan_data - hash ref that looks like the second return value from
                   6647:                  &scantron_getfile()
                   6648:     $i         - number of the requested line (starts at 0)
                   6649: 
                   6650:  Returns:
                   6651:    A scanline, (either the original or the corrected one if it
                   6652:    exists), or undef if the requested scanline should be
                   6653:    skipped. (Either because it's an skipped scanline, or it's an
                   6654:    unskipped scanline and we are not doing a 'do skipped scanlines'
                   6655:    pass.
                   6656: 
1.423     albertel 6657: =cut
                   6658: 
1.157     albertel 6659: sub scantron_get_line {
1.200     albertel 6660:     my ($scanlines,$scan_data,$i)=@_;
1.376     albertel 6661:     if (&should_be_skipped($scanlines,$scan_data,$i)) { return undef; }
                   6662:     #if ($scanlines->{'skipped'}[$i]) { return undef; }
1.157     albertel 6663:     if ($scanlines->{'corrected'}[$i]) {return $scanlines->{'corrected'}[$i];}
                   6664:     return $scanlines->{'orig'}[$i]; 
                   6665: }
                   6666: 
1.423     albertel 6667: =pod
                   6668: 
                   6669: =item scantron_todo_count
                   6670: 
1.424     albertel 6671:     Counts the number of scanlines that need processing.
                   6672: 
                   6673:  Arguments:
                   6674:     $scanlines - hash ref that looks like the first return value from
                   6675:                  &scantron_getfile()
                   6676:     $scan_data - hash ref that looks like the second return value from
                   6677:                  &scantron_getfile()
                   6678: 
                   6679:  Returns:
                   6680:     $count - number of scanlines to process
                   6681: 
1.423     albertel 6682: =cut
                   6683: 
1.200     albertel 6684: sub get_todo_count {
                   6685:     my ($scanlines,$scan_data)=@_;
                   6686:     my $count=0;
                   6687:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
                   6688: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
                   6689: 	if ($line=~/^[\s\cz]*$/) { next; }
                   6690: 	$count++;
                   6691:     }
                   6692:     return $count;
                   6693: }
                   6694: 
1.423     albertel 6695: =pod
                   6696: 
                   6697: =item scantron_put_line
                   6698: 
1.424     albertel 6699:     Updates the 'corrected' or 'skipped' versions of the bubble sheet
                   6700:     data file.
                   6701: 
                   6702:  Arguments:
                   6703:     $scanlines - hash ref that looks like the first return value from
                   6704:                  &scantron_getfile()
                   6705:     $scan_data - hash ref that looks like the second return value from
                   6706:                  &scantron_getfile()
                   6707:     $i         - line number to update
                   6708:     $newline   - contents of the updated scanline
                   6709:     $skip      - if true make the line for skipping and update the
                   6710:                  'skipped' file
                   6711: 
1.423     albertel 6712: =cut
                   6713: 
1.157     albertel 6714: sub scantron_put_line {
1.200     albertel 6715:     my ($scanlines,$scan_data,$i,$newline,$skip)=@_;
1.157     albertel 6716:     if ($skip) {
                   6717: 	$scanlines->{'skipped'}[$i]=$newline;
1.376     albertel 6718: 	&start_skipping($scan_data,$i);
1.157     albertel 6719: 	return;
                   6720:     }
                   6721:     $scanlines->{'corrected'}[$i]=$newline;
                   6722: }
                   6723: 
1.423     albertel 6724: =pod
                   6725: 
                   6726: =item scantron_clear_skip
                   6727: 
1.424     albertel 6728:    Remove a line from the 'skipped' file
                   6729: 
                   6730:  Arguments:
                   6731:     $scanlines - hash ref that looks like the first return value from
                   6732:                  &scantron_getfile()
                   6733:     $scan_data - hash ref that looks like the second return value from
                   6734:                  &scantron_getfile()
                   6735:     $i         - line number to update
                   6736: 
1.423     albertel 6737: =cut
                   6738: 
1.376     albertel 6739: sub scantron_clear_skip {
                   6740:     my ($scanlines,$scan_data,$i)=@_;
                   6741:     if (exists($scanlines->{'skipped'}[$i])) {
                   6742: 	undef($scanlines->{'skipped'}[$i]);
                   6743: 	return 1;
                   6744:     }
                   6745:     return 0;
                   6746: }
                   6747: 
1.423     albertel 6748: =pod
                   6749: 
                   6750: =item scantron_filter_not_exam
                   6751: 
1.424     albertel 6752:    Filter routine used by &Apache::lonnavmaps::retrieveResources(), to
                   6753:    filter out resources that are not marked as 'exam' mode
                   6754: 
1.423     albertel 6755: =cut
                   6756: 
1.334     albertel 6757: sub scantron_filter_not_exam {
                   6758:     my ($curres)=@_;
                   6759:     
                   6760:     if (ref($curres) && $curres->is_problem() && !$curres->is_exam()) {
                   6761: 	# if the user has asked to not have either hidden
                   6762: 	# or 'randomout' controlled resources to be graded
                   6763: 	# don't include them
                   6764: 	if ($env{'form.scantron_options_hidden'} eq 'ignore_hidden'
                   6765: 	    && $curres->randomout) {
                   6766: 	    return 0;
                   6767: 	}
                   6768: 	return 1;
                   6769:     }
                   6770:     return 0;
                   6771: }
                   6772: 
1.423     albertel 6773: =pod
                   6774: 
                   6775: =item scantron_validate_sequence
                   6776: 
1.424     albertel 6777:     Validates the selected sequence, checking for resource that are
                   6778:     not set to exam mode.
                   6779: 
1.423     albertel 6780: =cut
                   6781: 
1.334     albertel 6782: sub scantron_validate_sequence {
                   6783:     my ($r,$currentphase) = @_;
                   6784: 
                   6785:     my $navmap=Apache::lonnavmaps::navmap->new();
1.582     raeburn  6786:     unless (ref($navmap)) {
                   6787:         $r->print(&navmap_errormsg());
                   6788:         return (1,$currentphase);
                   6789:     }
1.334     albertel 6790:     my (undef,undef,$sequence)=
                   6791: 	&Apache::lonnet::decode_symb($env{'form.selectpage'});
                   6792: 
                   6793:     my $map=$navmap->getResourceByUrl($sequence);
                   6794: 
                   6795:     $r->print('<input type="hidden" name="validate_sequence_exam"
                   6796:                                     value="ignore" />');
                   6797:     if ($env{'form.validate_sequence_exam'} ne 'ignore') {
                   6798: 	my @resources=
                   6799: 	    $navmap->retrieveResources($map,\&scantron_filter_not_exam,1,0);
                   6800: 	if (@resources) {
1.357     banghart 6801: 	    $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 6802: 	    return (1,$currentphase);
                   6803: 	}
                   6804:     }
                   6805: 
                   6806:     return (0,$currentphase+1);
                   6807: }
                   6808: 
1.423     albertel 6809: 
                   6810: 
1.157     albertel 6811: sub scantron_validate_ID {
                   6812:     my ($r,$currentphase) = @_;
                   6813:     
                   6814:     #get student info
                   6815:     my $classlist=&Apache::loncoursedata::get_classlist();
                   6816:     my %idmap=&username_to_idmap($classlist);
                   6817: 
                   6818:     #get scantron line setup
1.257     albertel 6819:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.157     albertel 6820:     my ($scanlines,$scan_data)=&scantron_getfile();
1.582     raeburn  6821: 
                   6822:     my $nav_error;
                   6823:     &scantron_get_maxbubble(\$nav_error); # parse needs the bubble_lines.. array.
                   6824:     if ($nav_error) {
                   6825:         $r->print(&navmap_errormsg());
                   6826:         return(1,$currentphase);
                   6827:     }
1.157     albertel 6828: 
                   6829:     my %found=('ids'=>{},'usernames'=>{});
                   6830:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
1.200     albertel 6831: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.157     albertel 6832: 	if ($line=~/^[\s\cz]*$/) { next; }
                   6833: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
                   6834: 						 $scan_data);
                   6835: 	my $id=$$scan_record{'scantron.ID'};
                   6836: 	my $found;
                   6837: 	foreach my $checkid (keys(%idmap)) {
                   6838: 	    if (lc($checkid) eq lc($id)) { $found=$checkid;last; }
                   6839: 	}
                   6840: 	if ($found) {
                   6841: 	    my $username=$idmap{$found};
                   6842: 	    if ($found{'ids'}{$found}) {
                   6843: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
                   6844: 					 $line,'duplicateID',$found);
1.194     albertel 6845: 		return(1,$currentphase);
1.157     albertel 6846: 	    } elsif ($found{'usernames'}{$username}) {
                   6847: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
                   6848: 					 $line,'duplicateID',$username);
1.194     albertel 6849: 		return(1,$currentphase);
1.157     albertel 6850: 	    }
1.186     albertel 6851: 	    #FIXME store away line we previously saw the ID on to use above
1.157     albertel 6852: 	    $found{'ids'}{$found}++;
                   6853: 	    $found{'usernames'}{$username}++;
                   6854: 	} else {
                   6855: 	    if ($id =~ /^\s*$/) {
1.158     albertel 6856: 		my $username=&scan_data($scan_data,"$i.user");
1.157     albertel 6857: 		if (defined($username) && $found{'usernames'}{$username}) {
                   6858: 		    &scantron_get_correction($r,$i,$scan_record,
                   6859: 					     \%scantron_config,
                   6860: 					     $line,'duplicateID',$username);
1.194     albertel 6861: 		    return(1,$currentphase);
1.157     albertel 6862: 		} elsif (!defined($username)) {
                   6863: 		    &scantron_get_correction($r,$i,$scan_record,
                   6864: 					     \%scantron_config,
                   6865: 					     $line,'incorrectID');
1.194     albertel 6866: 		    return(1,$currentphase);
1.157     albertel 6867: 		}
                   6868: 		$found{'usernames'}{$username}++;
                   6869: 	    } else {
                   6870: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
                   6871: 					 $line,'incorrectID');
1.194     albertel 6872: 		return(1,$currentphase);
1.157     albertel 6873: 	    }
                   6874: 	}
                   6875:     }
                   6876: 
                   6877:     return (0,$currentphase+1);
                   6878: }
                   6879: 
1.423     albertel 6880: 
1.157     albertel 6881: sub scantron_get_correction {
                   6882:     my ($r,$i,$scan_record,$scan_config,$line,$error,$arg)=@_;
1.454     banghart 6883: #FIXME in the case of a duplicated ID the previous line, probably need
1.157     albertel 6884: #to show both the current line and the previous one and allow skipping
                   6885: #the previous one or the current one
                   6886: 
1.333     albertel 6887:     if ( $$scan_record{'scantron.PaperID'} =~ /\S/) {
1.492     albertel 6888: 	$r->print("<p>".&mt("<b>An error was detected ($error)</b>".
                   6889: 			    " for PaperID <tt>[_1]</tt>",
                   6890: 			    $$scan_record{'scantron.PaperID'})."</p> \n");
1.157     albertel 6891:     } else {
1.492     albertel 6892: 	$r->print("<p>".&mt("<b>An error was detected ($error)</b>".
                   6893: 			    " in scanline [_1] <pre>[_2]</pre>",
                   6894: 			    $i,$line)."</p> \n");
                   6895:     }
                   6896:     my $message="<p>".&mt("The ID on the form is  <tt>[_1]</tt><br />".
                   6897: 			  "The name on the paper is [_2],[_3]",
                   6898: 			  $$scan_record{'scantron.ID'},
                   6899: 			  $$scan_record{'scantron.LastName'},
                   6900: 			  $$scan_record{'scantron.FirstName'})."</p>";
1.242     albertel 6901: 
1.157     albertel 6902:     $r->print('<input type="hidden" name="scantron_corrections" value="'.$error.'" />'."\n");
                   6903:     $r->print('<input type="hidden" name="scantron_line" value="'.$i.'" />'."\n");
1.503     raeburn  6904:                            # Array populated for doublebubble or
                   6905:     my @lines_to_correct;  # missingbubble errors to build javascript
                   6906:                            # to validate radio button checking   
                   6907: 
1.157     albertel 6908:     if ($error =~ /ID$/) {
1.186     albertel 6909: 	if ($error eq 'incorrectID') {
1.492     albertel 6910: 	    $r->print("<p>".&mt("The encoded ID is not in the classlist").
                   6911: 		      "</p>\n");
1.157     albertel 6912: 	} elsif ($error eq 'duplicateID') {
1.492     albertel 6913: 	    $r->print("<p>".&mt("The encoded ID has also been used by a previous paper [_1]",$arg)."</p>\n");
1.157     albertel 6914: 	}
1.242     albertel 6915: 	$r->print($message);
1.492     albertel 6916: 	$r->print("<p>".&mt("How should I handle this?")." <br /> \n");
1.157     albertel 6917: 	$r->print("\n<ul><li> ");
                   6918: 	#FIXME it would be nice if this sent back the user ID and
                   6919: 	#could do partial userID matches
                   6920: 	$r->print(&Apache::loncommon::selectstudent_link('scantronupload',
                   6921: 				       'scantron_username','scantron_domain'));
                   6922: 	$r->print(": <input type='text' name='scantron_username' value='' />");
                   6923: 	$r->print("\n@".
1.257     albertel 6924: 		 &Apache::loncommon::select_dom_form($env{'request.role.domain'},'scantron_domain'));
1.157     albertel 6925: 
                   6926: 	$r->print('</li>');
1.186     albertel 6927:     } elsif ($error =~ /CODE$/) {
                   6928: 	if ($error eq 'incorrectCODE') {
1.492     albertel 6929: 	    $r->print("<p>".&mt("The encoded CODE is not in the list of possible CODEs.")."</p>\n");
1.186     albertel 6930: 	} elsif ($error eq 'duplicateCODE') {
1.492     albertel 6931: 	    $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 6932: 	}
1.492     albertel 6933: 	$r->print("<p>".&mt("The CODE on the form is  <tt>'[_1]'</tt>",
                   6934: 			    $$scan_record{'scantron.CODE'})."<br />\n");
1.242     albertel 6935: 	$r->print($message);
1.492     albertel 6936: 	$r->print("<p>".&mt("How should I handle this?")." <br /> \n");
1.187     albertel 6937: 	$r->print("\n<br /> ");
1.194     albertel 6938: 	my $i=0;
1.273     albertel 6939: 	if ($error eq 'incorrectCODE' 
                   6940: 	    && $$scan_record{'scantron.CODE'}=~/\S/ ) {
1.194     albertel 6941: 	    my ($max,$closest)=&scantron_get_closely_matching_CODEs($arg,$$scan_record{'scantron.CODE'});
1.278     albertel 6942: 	    if ($closest > 0) {
                   6943: 		foreach my $testcode (@{$closest}) {
                   6944: 		    my $checked='';
1.569     bisitz   6945: 		    if (!$i) { $checked=' checked="checked"'; }
1.492     albertel 6946: 		    $r->print("
                   6947:    <label>
1.569     bisitz   6948:        <input type='radio' name='scantron_CODE_resolution' value='use_closest_$i'$checked />
1.492     albertel 6949:        ".&mt("Use the similar CODE [_1] instead.",
                   6950: 	    "<b><tt>".$testcode."</tt></b>")."
                   6951:     </label>
                   6952:     <input type='hidden' name='scantron_CODE_closest_$i' value='$testcode' />");
1.278     albertel 6953: 		    $r->print("\n<br />");
                   6954: 		    $i++;
                   6955: 		}
1.194     albertel 6956: 	    }
                   6957: 	}
1.273     albertel 6958: 	if ($$scan_record{'scantron.CODE'}=~/\S/ ) {
1.569     bisitz   6959: 	    my $checked; if (!$i) { $checked=' checked="checked"'; }
1.492     albertel 6960: 	    $r->print("
                   6961:     <label>
1.569     bisitz   6962:         <input type='radio' name='scantron_CODE_resolution' value='use_unfound'$checked />
1.492     albertel 6963:        ".&mt("Use the CODE [_1] that is was on the paper, ignoring the error.",
                   6964: 	     "<b><tt>".$$scan_record{'scantron.CODE'}."</tt></b>")."
                   6965:     </label>");
1.273     albertel 6966: 	    $r->print("\n<br />");
                   6967: 	}
1.194     albertel 6968: 
1.597     wenzelju 6969: 	$r->print(&Apache::lonhtmlcommon::scripttag(<<ENDSCRIPT));
1.188     albertel 6970: function change_radio(field) {
1.190     albertel 6971:     var slct=document.scantronupload.scantron_CODE_resolution;
1.188     albertel 6972:     var i;
                   6973:     for (i=0;i<slct.length;i++) {
                   6974:         if (slct[i].value==field) { slct[i].checked=true; }
                   6975:     }
                   6976: }
                   6977: ENDSCRIPT
1.187     albertel 6978: 	my $href="/adm/pickcode?".
1.359     www      6979: 	   "form=".&escape("scantronupload").
                   6980: 	   "&scantron_format=".&escape($env{'form.scantron_format'}).
                   6981: 	   "&scantron_CODElist=".&escape($env{'form.scantron_CODElist'}).
                   6982: 	   "&curCODE=".&escape($$scan_record{'scantron.CODE'}).
                   6983: 	   "&scantron_selectfile=".&escape($env{'form.scantron_selectfile'});
1.332     albertel 6984: 	if ($env{'form.scantron_CODElist'} =~ /\S/) { 
1.492     albertel 6985: 	    $r->print("
                   6986:     <label>
                   6987:        <input type='radio' name='scantron_CODE_resolution' value='use_found' />
                   6988:        ".&mt("[_1]Select[_2] a CODE from the list of all CODEs and use it.",
                   6989: 	     "<a target='_blank' href='$href'>","</a>")."
                   6990:     </label> 
1.558     bisitz   6991:     ".&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 6992: 	    $r->print("\n<br />");
                   6993: 	}
1.492     albertel 6994: 	$r->print("
                   6995:     <label>
                   6996:        <input type='radio' name='scantron_CODE_resolution' value='use_typed' />
                   6997:        ".&mt("Use [_1] as the CODE.",
                   6998: 	     "</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 6999: 	$r->print("\n<br /><br />");
1.157     albertel 7000:     } elsif ($error eq 'doublebubble') {
1.503     raeburn  7001: 	$r->print("<p>".&mt("There have been multiple bubbles scanned for some question(s)")."</p>\n");
1.497     foxr     7002: 
                   7003: 	# The form field scantron_questions is acutally a list of line numbers.
                   7004: 	# represented by this form so:
                   7005: 
                   7006: 	my $line_list = &questions_to_line_list($arg);
                   7007: 
1.157     albertel 7008: 	$r->print('<input type="hidden" name="scantron_questions" value="'.
1.497     foxr     7009: 		  $line_list.'" />');
1.242     albertel 7010: 	$r->print($message);
1.492     albertel 7011: 	$r->print("<p>".&mt("Please indicate which bubble should be used for grading")."</p>");
1.157     albertel 7012: 	foreach my $question (@{$arg}) {
1.503     raeburn  7013: 	    my @linenums = &prompt_for_corrections($r,$question,$scan_config,
                   7014:                                                    $scan_record, $error);
1.524     raeburn  7015:             push(@lines_to_correct,@linenums);
1.157     albertel 7016: 	}
1.503     raeburn  7017:         $r->print(&verify_bubbles_checked(@lines_to_correct));
1.157     albertel 7018:     } elsif ($error eq 'missingbubble') {
1.492     albertel 7019: 	$r->print("<p>".&mt("There have been <b>no</b> bubbles scanned for some question(s)")."</p>\n");
1.242     albertel 7020: 	$r->print($message);
1.492     albertel 7021: 	$r->print("<p>".&mt("Please indicate which bubble should be used for grading.")."</p>");
1.503     raeburn  7022: 	$r->print(&mt("Some questions have no scanned bubbles.")."\n");
1.497     foxr     7023: 
1.503     raeburn  7024: 	# The form field scantron_questions is actually a list of line numbers not
1.497     foxr     7025: 	# a list of question numbers. Therefore:
                   7026: 	#
                   7027: 	
                   7028: 	my $line_list = &questions_to_line_list($arg);
                   7029: 
1.157     albertel 7030: 	$r->print('<input type="hidden" name="scantron_questions" value="'.
1.497     foxr     7031: 		  $line_list.'" />');
1.157     albertel 7032: 	foreach my $question (@{$arg}) {
1.503     raeburn  7033: 	    my @linenums = &prompt_for_corrections($r,$question,$scan_config,
                   7034:                                                    $scan_record, $error);
1.524     raeburn  7035:             push(@lines_to_correct,@linenums);
1.157     albertel 7036: 	}
1.503     raeburn  7037:         $r->print(&verify_bubbles_checked(@lines_to_correct));
1.157     albertel 7038:     } else {
                   7039: 	$r->print("\n<ul>");
                   7040:     }
                   7041:     $r->print("\n</li></ul>");
1.497     foxr     7042: }
                   7043: 
1.503     raeburn  7044: sub verify_bubbles_checked {
                   7045:     my (@ansnums) = @_;
                   7046:     my $ansnumstr = join('","',@ansnums);
                   7047:     my $warning = &mt("A bubble or 'No bubble' selection has not been made for one or more lines.");
1.597     wenzelju 7048:     my $output = &Apache::lonhtmlcommon::scripttag((<<ENDSCRIPT));
1.503     raeburn  7049: function verify_bubble_radio(form) {
                   7050:     var ansnumArray = new Array ("$ansnumstr");
                   7051:     var need_bubble_count = 0;
                   7052:     for (var i=0; i<ansnumArray.length; i++) {
                   7053:         if (form.elements["scantron_correct_Q_"+ansnumArray[i]].length > 1) {
                   7054:             var bubble_picked = 0; 
                   7055:             for (var j=0; j<form.elements["scantron_correct_Q_"+ansnumArray[i]].length; j++) {
                   7056:                 if (form.elements["scantron_correct_Q_"+ansnumArray[i]][j].checked == true) {
                   7057:                     bubble_picked = 1;
                   7058:                 }
                   7059:             }
                   7060:             if (bubble_picked == 0) {
                   7061:                 need_bubble_count ++;
                   7062:             }
                   7063:         }
                   7064:     }
                   7065:     if (need_bubble_count) {
                   7066:         alert("$warning");
                   7067:         return;
                   7068:     }
                   7069:     form.submit(); 
                   7070: }
                   7071: ENDSCRIPT
                   7072:     return $output;
                   7073: }
                   7074: 
1.497     foxr     7075: =pod
                   7076: 
                   7077: =item  questions_to_line_list
1.157     albertel 7078: 
1.497     foxr     7079: Converts a list of questions into a string of comma separated
                   7080: line numbers in the answer sheet used by the questions.  This is
                   7081: used to fill in the scantron_questions form field.
                   7082: 
                   7083:   Arguments:
                   7084:      questions    - Reference to an array of questions.
                   7085: 
                   7086: =cut
                   7087: 
                   7088: 
                   7089: sub questions_to_line_list {
                   7090:     my ($questions) = @_;
                   7091:     my @lines;
                   7092: 
1.503     raeburn  7093:     foreach my $item (@{$questions}) {
                   7094:         my $question = $item;
                   7095:         my ($first,$count,$last);
                   7096:         if ($item =~ /^(\d+)\.(\d+)$/) {
                   7097:             $question = $1;
                   7098:             my $subquestion = $2;
                   7099:             $first = $first_bubble_line{$question-1} + 1;
                   7100:             my @subans = split(/,/,$subdivided_bubble_lines{$question-1});
                   7101:             my $subcount = 1;
                   7102:             while ($subcount<$subquestion) {
                   7103:                 $first += $subans[$subcount-1];
                   7104:                 $subcount ++;
                   7105:             }
                   7106:             $count = $subans[$subquestion-1];
                   7107:         } else {
                   7108: 	    $first   = $first_bubble_line{$question-1} + 1;
                   7109: 	    $count   = $bubble_lines_per_response{$question-1};
                   7110:         }
1.506     raeburn  7111:         $last = $first+$count-1;
1.503     raeburn  7112:         push(@lines, ($first..$last));
1.497     foxr     7113:     }
                   7114:     return join(',', @lines);
                   7115: }
                   7116: 
                   7117: =pod 
                   7118: 
                   7119: =item prompt_for_corrections
                   7120: 
                   7121: Prompts for a potentially multiline correction to the
                   7122: user's bubbling (factors out common code from scantron_get_correction
                   7123: for multi and missing bubble cases).
                   7124: 
                   7125:  Arguments:
                   7126:    $r           - Apache request object.
                   7127:    $question    - The question number to prompt for.
                   7128:    $scan_config - The scantron file configuration hash.
                   7129:    $scan_record - Reference to the hash that has the the parsed scanlines.
1.503     raeburn  7130:    $error       - Type of error
1.497     foxr     7131: 
                   7132:  Implicit inputs:
                   7133:    %bubble_lines_per_response   - Starting line numbers for each question.
                   7134:                                   Numbered from 0 (but question numbers are from
                   7135:                                   1.
                   7136:    %first_bubble_line           - Starting bubble line for each question.
1.509     raeburn  7137:    %subdivided_bubble_lines     - optionresponse, matchresponse and rankresponse 
                   7138:                                   type problems render as separate sub-questions, 
1.503     raeburn  7139:                                   in exam mode. This hash contains a 
                   7140:                                   comma-separated list of the lines per 
                   7141:                                   sub-question.
1.510     raeburn  7142:    %responsetype_per_response   - essayresponse, formularesponse,
                   7143:                                   stringresponse, imageresponse, reactionresponse,
                   7144:                                   and organicresponse type problem parts can have
1.503     raeburn  7145:                                   multiple lines per response if the weight
                   7146:                                   assigned exceeds 10.  In this case, only
                   7147:                                   one bubble per line is permitted, but more 
                   7148:                                   than one line might contain bubbles, e.g.
                   7149:                                   bubbling of: line 1 - J, line 2 - J, 
                   7150:                                   line 3 - B would assign 22 points.  
1.497     foxr     7151: 
                   7152: =cut
                   7153: 
                   7154: sub prompt_for_corrections {
1.503     raeburn  7155:     my ($r, $question, $scan_config, $scan_record, $error) = @_;
                   7156:     my ($current_line,$lines);
                   7157:     my @linenums;
                   7158:     my $questionnum = $question;
                   7159:     if ($question =~ /^(\d+)\.(\d+)$/) {
                   7160:         $question = $1;
                   7161:         $current_line = $first_bubble_line{$question-1} + 1 ;
                   7162:         my $subquestion = $2;
                   7163:         my @subans = split(/,/,$subdivided_bubble_lines{$question-1});
                   7164:         my $subcount = 1;
                   7165:         while ($subcount<$subquestion) {
                   7166:             $current_line += $subans[$subcount-1];
                   7167:             $subcount ++;
                   7168:         }
                   7169:         $lines = $subans[$subquestion-1];
                   7170:     } else {
                   7171:         $current_line = $first_bubble_line{$question-1} + 1 ;
                   7172:         $lines        = $bubble_lines_per_response{$question-1};
                   7173:     }
1.497     foxr     7174:     if ($lines > 1) {
1.503     raeburn  7175:         $r->print(&mt('The group of bubble lines below responds to a single question.').'<br />');
                   7176:         if (($responsetype_per_response{$question-1} eq 'essayresponse') ||
                   7177:             ($responsetype_per_response{$question-1} eq 'formularesponse') ||
1.510     raeburn  7178:             ($responsetype_per_response{$question-1} eq 'stringresponse') ||
                   7179:             ($responsetype_per_response{$question-1} eq 'imageresponse') ||
                   7180:             ($responsetype_per_response{$question-1} eq 'reactionresponse') ||
                   7181:             ($responsetype_per_response{$question-1} eq 'organicresponse')) {
1.572     www      7182:             $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  7183:         } else {
                   7184:             $r->print(&mt("Select at most one bubble in a single line and select 'No Bubble' in all the other lines. ")."<br />");
                   7185:         }
1.497     foxr     7186:     }
                   7187:     for (my $i =0; $i < $lines; $i++) {
1.503     raeburn  7188:         my $selected = $$scan_record{"scantron.$current_line.answer"};
                   7189: 	&scantron_bubble_selector($r,$scan_config,$current_line, 
                   7190: 	        		  $questionnum,$error,split('', $selected));
1.524     raeburn  7191:         push(@linenums,$current_line);
1.497     foxr     7192: 	$current_line++;
                   7193:     }
                   7194:     if ($lines > 1) {
                   7195: 	$r->print("<hr /><br />");
                   7196:     }
1.503     raeburn  7197:     return @linenums;
1.157     albertel 7198: }
1.423     albertel 7199: 
                   7200: =pod
                   7201: 
                   7202: =item scantron_bubble_selector
                   7203:   
                   7204:    Generates the html radiobuttons to correct a single bubble line
1.424     albertel 7205:    possibly showing the existing the selected bubbles if known
1.423     albertel 7206: 
                   7207:  Arguments:
                   7208:     $r           - Apache request object
                   7209:     $scan_config - hash from &get_scantron_config()
1.497     foxr     7210:     $line        - Number of the line being displayed.
1.503     raeburn  7211:     $questionnum - Question number (may include subquestion)
                   7212:     $error       - Type of error.
1.497     foxr     7213:     @selected    - Array of bubbles picked on this line.
1.423     albertel 7214: 
                   7215: =cut
                   7216: 
1.157     albertel 7217: sub scantron_bubble_selector {
1.503     raeburn  7218:     my ($r,$scan_config,$line,$questionnum,$error,@selected)=@_;
1.157     albertel 7219:     my $max=$$scan_config{'Qlength'};
1.274     albertel 7220: 
                   7221:     my $scmode=$$scan_config{'Qon'};
                   7222:     if ($scmode eq 'number' || $scmode eq 'letter') { $max=10; }	     
                   7223: 
1.157     albertel 7224:     my @alphabet=('A'..'Z');
1.503     raeburn  7225:     $r->print(&Apache::loncommon::start_data_table().
                   7226:               &Apache::loncommon::start_data_table_row());
                   7227:     $r->print('<td rowspan="2" class="LC_leftcol_header">'.$line.'</td>');
1.497     foxr     7228:     for (my $i=0;$i<$max+1;$i++) {
                   7229: 	$r->print("\n".'<td align="center">');
                   7230: 	if ($selected[0] eq $alphabet[$i]) { $r->print('X'); shift(@selected) }
                   7231: 	else { $r->print('&nbsp;'); }
                   7232: 	$r->print('</td>');
                   7233:     }
1.503     raeburn  7234:     $r->print(&Apache::loncommon::end_data_table_row().
                   7235:               &Apache::loncommon::start_data_table_row());
1.497     foxr     7236:     for (my $i=0;$i<$max;$i++) {
                   7237: 	$r->print("\n".
                   7238: 		  '<td><label><input type="radio" name="scantron_correct_Q_'.
                   7239: 		  $line.'" value="'.$i.'" />'.$alphabet[$i]."</label></td>");
                   7240:     }
1.503     raeburn  7241:     my $nobub_checked = ' ';
                   7242:     if ($error eq 'missingbubble') {
                   7243:         $nobub_checked = ' checked = "checked" ';
                   7244:     }
                   7245:     $r->print("\n".'<td><label><input type="radio" name="scantron_correct_Q_'.
                   7246: 	      $line.'" value="none"'.$nobub_checked.'/>'.&mt('No bubble').
                   7247:               '</label>'."\n".'<input type="hidden" name="scantron_questionnum_Q_'.
                   7248:               $line.'" value="'.$questionnum.'" /></td>');
                   7249:     $r->print(&Apache::loncommon::end_data_table_row().
                   7250:               &Apache::loncommon::end_data_table());
1.157     albertel 7251: }
                   7252: 
1.423     albertel 7253: =pod
                   7254: 
                   7255: =item num_matches
                   7256: 
1.424     albertel 7257:    Counts the number of characters that are the same between the two arguments.
                   7258: 
                   7259:  Arguments:
                   7260:    $orig - CODE from the scanline
                   7261:    $code - CODE to match against
                   7262: 
                   7263:  Returns:
                   7264:    $count - integer count of the number of same characters between the
                   7265:             two arguments
                   7266: 
1.423     albertel 7267: =cut
                   7268: 
1.194     albertel 7269: sub num_matches {
                   7270:     my ($orig,$code) = @_;
                   7271:     my @code=split(//,$code);
                   7272:     my @orig=split(//,$orig);
                   7273:     my $same=0;
                   7274:     for (my $i=0;$i<scalar(@code);$i++) {
                   7275: 	if ($code[$i] eq $orig[$i]) { $same++; }
                   7276:     }
                   7277:     return $same;
                   7278: }
                   7279: 
1.423     albertel 7280: =pod
                   7281: 
                   7282: =item scantron_get_closely_matching_CODEs
                   7283: 
1.424     albertel 7284:    Cycles through all CODEs and finds the set that has the greatest
                   7285:    number of same characters as the provided CODE
                   7286: 
                   7287:  Arguments:
                   7288:    $allcodes - hash ref returned by &get_codes()
                   7289:    $CODE     - CODE from the current scanline
                   7290: 
                   7291:  Returns:
                   7292:    2 element list
                   7293:     - first elements is number of how closely matching the best fit is 
                   7294:       (5 means best set has 5 matching characters)
                   7295:     - second element is an arrary ref containing the set of valid CODEs
                   7296:       that best fit the passed in CODE
                   7297: 
1.423     albertel 7298: =cut
                   7299: 
1.194     albertel 7300: sub scantron_get_closely_matching_CODEs {
                   7301:     my ($allcodes,$CODE)=@_;
                   7302:     my @CODEs;
                   7303:     foreach my $testcode (sort(keys(%{$allcodes}))) {
                   7304: 	push(@{$CODEs[&num_matches($CODE,$testcode)]},$testcode);
                   7305:     }
                   7306: 
                   7307:     return ($#CODEs,$CODEs[-1]);
                   7308: }
                   7309: 
1.423     albertel 7310: =pod
                   7311: 
                   7312: =item get_codes
                   7313: 
1.424     albertel 7314:    Builds a hash which has keys of all of the valid CODEs from the selected
                   7315:    set of remembered CODEs.
                   7316: 
                   7317:  Arguments:
                   7318:   $old_name - name of the set of remembered CODEs
                   7319:   $cdom     - domain of the course
                   7320:   $cnum     - internal course name
                   7321: 
                   7322:  Returns:
                   7323:   %allcodes - keys are the valid CODEs, values are all 1
                   7324: 
1.423     albertel 7325: =cut
                   7326: 
1.194     albertel 7327: sub get_codes {
1.280     foxr     7328:     my ($old_name, $cdom, $cnum) = @_;
                   7329:     if (!$old_name) {
                   7330: 	$old_name=$env{'form.scantron_CODElist'};
                   7331:     }
                   7332:     if (!$cdom) {
                   7333: 	$cdom =$env{'course.'.$env{'request.course.id'}.'.domain'};
                   7334:     }
                   7335:     if (!$cnum) {
                   7336: 	$cnum =$env{'course.'.$env{'request.course.id'}.'.num'};
                   7337:     }
1.278     albertel 7338:     my %result=&Apache::lonnet::get('CODEs',[$old_name,"type\0$old_name"],
                   7339: 				    $cdom,$cnum);
                   7340:     my %allcodes;
                   7341:     if ($result{"type\0$old_name"} eq 'number') {
                   7342: 	%allcodes=map {($_,1)} split(',',$result{$old_name});
                   7343:     } else {
                   7344: 	%allcodes=map {(&Apache::lonprintout::num_to_letters($_),1)} split(',',$result{$old_name});
                   7345:     }
1.194     albertel 7346:     return %allcodes;
                   7347: }
                   7348: 
1.423     albertel 7349: =pod
                   7350: 
                   7351: =item scantron_validate_CODE
                   7352: 
1.424     albertel 7353:    Validates all scanlines in the selected file to not have any
                   7354:    invalid or underspecified CODEs and that none of the codes are
                   7355:    duplicated if this was requested.
                   7356: 
1.423     albertel 7357: =cut
                   7358: 
1.157     albertel 7359: sub scantron_validate_CODE {
                   7360:     my ($r,$currentphase) = @_;
1.257     albertel 7361:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.186     albertel 7362:     if ($scantron_config{'CODElocation'} &&
                   7363: 	$scantron_config{'CODEstart'} &&
                   7364: 	$scantron_config{'CODElength'}) {
1.257     albertel 7365: 	if (!defined($env{'form.scantron_CODElist'})) {
1.186     albertel 7366: 	    &FIXME_blow_up()
                   7367: 	}
                   7368:     } else {
                   7369: 	return (0,$currentphase+1);
                   7370:     }
                   7371:     
                   7372:     my %usedCODEs;
                   7373: 
1.194     albertel 7374:     my %allcodes=&get_codes();
1.186     albertel 7375: 
1.582     raeburn  7376:     my $nav_error;
                   7377:     &scantron_get_maxbubble(\$nav_error); # parse needs the lines per response array.
                   7378:     if ($nav_error) {
                   7379:         $r->print(&navmap_errormsg());
                   7380:         return(1,$currentphase);
                   7381:     }
1.447     foxr     7382: 
1.186     albertel 7383:     my ($scanlines,$scan_data)=&scantron_getfile();
                   7384:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
1.200     albertel 7385: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.186     albertel 7386: 	if ($line=~/^[\s\cz]*$/) { next; }
                   7387: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
                   7388: 						 $scan_data);
                   7389: 	my $CODE=$$scan_record{'scantron.CODE'};
                   7390: 	my $error=0;
1.224     albertel 7391: 	if (!&Apache::lonnet::validCODE($CODE)) {
                   7392: 	    &scantron_get_correction($r,$i,$scan_record,
                   7393: 				     \%scantron_config,
                   7394: 				     $line,'incorrectCODE',\%allcodes);
                   7395: 	    return(1,$currentphase);
                   7396: 	}
1.221     albertel 7397: 	if (%allcodes && !exists($allcodes{$CODE}) 
                   7398: 	    && !$$scan_record{'scantron.useCODE'}) {
1.186     albertel 7399: 	    &scantron_get_correction($r,$i,$scan_record,
                   7400: 				     \%scantron_config,
1.194     albertel 7401: 				     $line,'incorrectCODE',\%allcodes);
                   7402: 	    return(1,$currentphase);
1.186     albertel 7403: 	}
1.214     albertel 7404: 	if (exists($usedCODEs{$CODE}) 
1.257     albertel 7405: 	    && $env{'form.scantron_CODEunique'} eq 'yes'
1.192     albertel 7406: 	    && !$$scan_record{'scantron.CODE_ignore_dup'}) {
1.186     albertel 7407: 	    &scantron_get_correction($r,$i,$scan_record,
                   7408: 				     \%scantron_config,
1.194     albertel 7409: 				     $line,'duplicateCODE',$usedCODEs{$CODE});
                   7410: 	    return(1,$currentphase);
1.186     albertel 7411: 	}
1.524     raeburn  7412: 	push(@{$usedCODEs{$CODE}},$$scan_record{'scantron.PaperID'});
1.186     albertel 7413:     }
1.157     albertel 7414:     return (0,$currentphase+1);
                   7415: }
                   7416: 
1.423     albertel 7417: =pod
                   7418: 
                   7419: =item scantron_validate_doublebubble
                   7420: 
1.424     albertel 7421:    Validates all scanlines in the selected file to not have any
                   7422:    bubble lines with multiple bubbles marked.
                   7423: 
1.423     albertel 7424: =cut
                   7425: 
1.157     albertel 7426: sub scantron_validate_doublebubble {
                   7427:     my ($r,$currentphase) = @_;
                   7428:     #get student info
                   7429:     my $classlist=&Apache::loncoursedata::get_classlist();
                   7430:     my %idmap=&username_to_idmap($classlist);
                   7431: 
                   7432:     #get scantron line setup
1.257     albertel 7433:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.157     albertel 7434:     my ($scanlines,$scan_data)=&scantron_getfile();
1.583     raeburn  7435:     my $nav_error;
                   7436:     &scantron_get_maxbubble(\$nav_error); # parse needs the bubble line array.
                   7437:     if ($nav_error) {
                   7438:         $r->print(&navmap_errormsg());
                   7439:         return(1,$currentphase);
                   7440:     }
1.447     foxr     7441: 
1.157     albertel 7442:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
1.200     albertel 7443: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.157     albertel 7444: 	if ($line=~/^[\s\cz]*$/) { next; }
                   7445: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
                   7446: 						 $scan_data);
                   7447: 	if (!defined($$scan_record{'scantron.doubleerror'})) { next; }
                   7448: 	&scantron_get_correction($r,$i,$scan_record,\%scantron_config,$line,
                   7449: 				 'doublebubble',
                   7450: 				 $$scan_record{'scantron.doubleerror'});
                   7451:     	return (1,$currentphase);
                   7452:     }
                   7453:     return (0,$currentphase+1);
                   7454: }
                   7455: 
1.423     albertel 7456: 
1.503     raeburn  7457: sub scantron_get_maxbubble {
1.582     raeburn  7458:     my ($nav_error) = @_;
1.257     albertel 7459:     if (defined($env{'form.scantron_maxbubble'}) &&
                   7460: 	$env{'form.scantron_maxbubble'}) {
1.447     foxr     7461: 	&restore_bubble_lines();
1.257     albertel 7462: 	return $env{'form.scantron_maxbubble'};
1.191     albertel 7463:     }
1.330     albertel 7464: 
1.447     foxr     7465:     my (undef, undef, $sequence) =
1.257     albertel 7466: 	&Apache::lonnet::decode_symb($env{'form.selectpage'});
1.330     albertel 7467: 
1.447     foxr     7468:     my $navmap=Apache::lonnavmaps::navmap->new();
1.582     raeburn  7469:     unless (ref($navmap)) {
                   7470:         if (ref($nav_error)) {
                   7471:             $$nav_error = 1;
                   7472:         }
1.591     raeburn  7473:         return;
1.582     raeburn  7474:     }
1.191     albertel 7475:     my $map=$navmap->getResourceByUrl($sequence);
                   7476:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
1.330     albertel 7477: 
                   7478:     &Apache::lonxml::clear_problem_counter();
                   7479: 
1.557     raeburn  7480:     my $uname       = $env{'user.name'};
                   7481:     my $udom        = $env{'user.domain'};
1.435     foxr     7482:     my $cid         = $env{'request.course.id'};
                   7483:     my $total_lines = 0;
                   7484:     %bubble_lines_per_response = ();
1.447     foxr     7485:     %first_bubble_line         = ();
1.503     raeburn  7486:     %subdivided_bubble_lines   = ();
                   7487:     %responsetype_per_response = ();
1.554     raeburn  7488: 
1.447     foxr     7489:     my $response_number = 0;
                   7490:     my $bubble_line     = 0;
1.191     albertel 7491:     foreach my $resource (@resources) {
1.542     raeburn  7492:         my ($analysis,$parts) = &scantron_partids_tograde($resource,$cid,$uname,$udom);
                   7493:         if ((ref($analysis) eq 'HASH') && (ref($parts) eq 'ARRAY')) {
                   7494: 	    foreach my $part_id (@{$parts}) {
                   7495:                 my $lines;
                   7496: 
                   7497: 	        # TODO - make this a persistent hash not an array.
                   7498: 
                   7499:                 # optionresponse, matchresponse and rankresponse type items 
                   7500:                 # render as separate sub-questions in exam mode.
                   7501:                 if (($analysis->{$part_id.'.type'} eq 'optionresponse') ||
                   7502:                     ($analysis->{$part_id.'.type'} eq 'matchresponse') ||
                   7503:                     ($analysis->{$part_id.'.type'} eq 'rankresponse')) {
                   7504:                     my ($numbub,$numshown);
                   7505:                     if ($analysis->{$part_id.'.type'} eq 'optionresponse') {
                   7506:                         if (ref($analysis->{$part_id.'.options'}) eq 'ARRAY') {
                   7507:                             $numbub = scalar(@{$analysis->{$part_id.'.options'}});
                   7508:                         }
                   7509:                     } elsif ($analysis->{$part_id.'.type'} eq 'matchresponse') {
                   7510:                         if (ref($analysis->{$part_id.'.items'}) eq 'ARRAY') {
                   7511:                             $numbub = scalar(@{$analysis->{$part_id.'.items'}});
                   7512:                         }
                   7513:                     } elsif ($analysis->{$part_id.'.type'} eq 'rankresponse') {
                   7514:                         if (ref($analysis->{$part_id.'.foils'}) eq 'ARRAY') {
                   7515:                             $numbub = scalar(@{$analysis->{$part_id.'.foils'}});
                   7516:                         }
                   7517:                     }
                   7518:                     if (ref($analysis->{$part_id.'.shown'}) eq 'ARRAY') {
                   7519:                         $numshown = scalar(@{$analysis->{$part_id.'.shown'}});
                   7520:                     }
                   7521:                     my $bubbles_per_line = 10;
                   7522:                     my $inner_bubble_lines = int($numbub/$bubbles_per_line);
                   7523:                     if (($numbub % $bubbles_per_line) != 0) {
                   7524:                         $inner_bubble_lines++;
                   7525:                     }
                   7526:                     for (my $i=0; $i<$numshown; $i++) {
                   7527:                         $subdivided_bubble_lines{$response_number} .= 
                   7528:                             $inner_bubble_lines.',';
                   7529:                     }
                   7530:                     $subdivided_bubble_lines{$response_number} =~ s/,$//;
                   7531:                     $lines = $numshown * $inner_bubble_lines;
                   7532:                 } else {
                   7533:                     $lines = $analysis->{"$part_id.bubble_lines"};
                   7534:                 } 
                   7535: 
                   7536:                 $first_bubble_line{$response_number} = $bubble_line;
                   7537: 	        $bubble_lines_per_response{$response_number} = $lines;
                   7538:                 $responsetype_per_response{$response_number} = 
                   7539:                     $analysis->{$part_id.'.type'};
                   7540: 	        $response_number++;
                   7541: 
                   7542: 	        $bubble_line +=  $lines;
                   7543: 	        $total_lines +=  $lines;
                   7544: 	    }
                   7545:         }
                   7546:     }
1.552     raeburn  7547:     &Apache::lonnet::delenv('scantron.');
1.542     raeburn  7548: 
                   7549:     &save_bubble_lines();
                   7550:     $env{'form.scantron_maxbubble'} =
                   7551: 	$total_lines;
                   7552:     return $env{'form.scantron_maxbubble'};
                   7553: }
1.523     raeburn  7554: 
1.157     albertel 7555: sub scantron_validate_missingbubbles {
                   7556:     my ($r,$currentphase) = @_;
                   7557:     #get student info
                   7558:     my $classlist=&Apache::loncoursedata::get_classlist();
                   7559:     my %idmap=&username_to_idmap($classlist);
                   7560: 
                   7561:     #get scantron line setup
1.257     albertel 7562:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.157     albertel 7563:     my ($scanlines,$scan_data)=&scantron_getfile();
1.582     raeburn  7564:     my $nav_error;
                   7565:     my $max_bubble=&scantron_get_maxbubble(\$nav_error);
                   7566:     if ($nav_error) {
                   7567:         return(1,$currentphase);
                   7568:     }
1.157     albertel 7569:     if (!$max_bubble) { $max_bubble=2**31; }
                   7570:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
1.200     albertel 7571: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.157     albertel 7572: 	if ($line=~/^[\s\cz]*$/) { next; }
                   7573: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
                   7574: 						 $scan_data);
                   7575: 	if (!defined($$scan_record{'scantron.missingerror'})) { next; }
                   7576: 	my @to_correct;
1.470     foxr     7577: 	
                   7578: 	# Probably here's where the error is...
                   7579: 
1.157     albertel 7580: 	foreach my $missing (@{$$scan_record{'scantron.missingerror'}}) {
1.505     raeburn  7581:             my $lastbubble;
                   7582:             if ($missing =~ /^(\d+)\.(\d+)$/) {
                   7583:                my $question = $1;
                   7584:                my $subquestion = $2;
                   7585:                if (!defined($first_bubble_line{$question -1})) { next; }
                   7586:                my $first = $first_bubble_line{$question-1};
                   7587:                my @subans = split(/,/,$subdivided_bubble_lines{$question-1});
                   7588:                my $subcount = 1;
                   7589:                while ($subcount<$subquestion) {
                   7590:                    $first += $subans[$subcount-1];
                   7591:                    $subcount ++;
                   7592:                }
                   7593:                my $count = $subans[$subquestion-1];
                   7594:                $lastbubble = $first + $count;
                   7595:             } else {
                   7596:                 if (!defined($first_bubble_line{$missing - 1})) { next; }
                   7597:                 $lastbubble = $first_bubble_line{$missing - 1} + $bubble_lines_per_response{$missing - 1};
                   7598:             }
                   7599:             if ($lastbubble > $max_bubble) { next; }
1.157     albertel 7600: 	    push(@to_correct,$missing);
                   7601: 	}
                   7602: 	if (@to_correct) {
                   7603: 	    &scantron_get_correction($r,$i,$scan_record,\%scantron_config,
                   7604: 				     $line,'missingbubble',\@to_correct);
                   7605: 	    return (1,$currentphase);
                   7606: 	}
                   7607: 
                   7608:     }
                   7609:     return (0,$currentphase+1);
                   7610: }
                   7611: 
1.423     albertel 7612: 
1.82      albertel 7613: sub scantron_process_students {
1.75      albertel 7614:     my ($r) = @_;
1.513     foxr     7615: 
1.257     albertel 7616:     my (undef,undef,$sequence)=&Apache::lonnet::decode_symb($env{'form.selectpage'});
1.324     albertel 7617:     my ($symb)=&get_symb($r);
1.513     foxr     7618:     if (!$symb) {
                   7619: 	return '';
                   7620:     }
1.324     albertel 7621:     my $default_form_data=&defaultFormData($symb);
1.82      albertel 7622: 
1.257     albertel 7623:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.157     albertel 7624:     my ($scanlines,$scan_data)=&scantron_getfile();
1.82      albertel 7625:     my $classlist=&Apache::loncoursedata::get_classlist();
                   7626:     my %idmap=&username_to_idmap($classlist);
1.132     bowersj2 7627:     my $navmap=Apache::lonnavmaps::navmap->new();
1.582     raeburn  7628:     unless (ref($navmap)) {
                   7629:         $r->print(&navmap_errormsg());
                   7630:         return '';
                   7631:     }  
1.83      albertel 7632:     my $map=$navmap->getResourceByUrl($sequence);
                   7633:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
1.557     raeburn  7634:     my (%grader_partids_by_symb,%grader_randomlists_by_symb);
                   7635:     &graders_resources_pass(\@resources,\%grader_partids_by_symb,
                   7636:                             \%grader_randomlists_by_symb);
1.586     raeburn  7637:     my $resource_error;
1.557     raeburn  7638:     foreach my $resource (@resources) {
1.586     raeburn  7639:         my $ressymb;
                   7640:         if (ref($resource)) {
                   7641:             $ressymb = $resource->symb();
                   7642:         } else {
                   7643:             $resource_error = 1;
                   7644:             last;
                   7645:         }
1.557     raeburn  7646:         my ($analysis,$parts) =
                   7647:             &scantron_partids_tograde($resource,$env{'request.course.id'},
                   7648:                                       $env{'user.name'},$env{'user.domain'},1);
                   7649:         $grader_partids_by_symb{$ressymb} = $parts;
                   7650:         if (ref($analysis) eq 'HASH') {
                   7651:             if (ref($analysis->{'parts_withrandomlist'}) eq 'ARRAY') {
                   7652:                 $grader_randomlists_by_symb{$ressymb} = 
                   7653:                     $analysis->{'parts_withrandomlist'};
                   7654:             }
                   7655:         }
                   7656:     }
1.586     raeburn  7657:     if ($resource_error) {
                   7658:         $r->print(&navmap_errormsg());
                   7659:         return '';
                   7660:     }
1.557     raeburn  7661: 
1.554     raeburn  7662:     my ($uname,$udom);
1.82      albertel 7663:     my $result= <<SCANTRONFORM;
1.81      albertel 7664: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantronupload">
                   7665:   <input type="hidden" name="command" value="scantron_configphase" />
                   7666:   $default_form_data
                   7667: SCANTRONFORM
1.82      albertel 7668:     $r->print($result);
                   7669: 
                   7670:     my @delayqueue;
1.542     raeburn  7671:     my (%completedstudents,%scandata);
1.140     albertel 7672:     
1.520     www      7673:     my $lock=&Apache::lonnet::set_lock(&mt('Grading bubblesheet exam'));
1.200     albertel 7674:     my $count=&get_todo_count($scanlines,$scan_data);
1.575     www      7675:     my %prog_state=&Apache::lonhtmlcommon::Create_PrgWin($r,'Bubblesheet Status',
                   7676:  				    'Bubblesheet Progress',$count,
1.195     albertel 7677: 				    'inline',undef,'scantronupload');
1.140     albertel 7678:     &Apache::lonhtmlcommon::Update_PrgWin($r,\%prog_state,
                   7679: 					  'Processing first student');
1.542     raeburn  7680:     $r->print('<br />');
1.140     albertel 7681:     my $start=&Time::HiRes::time();
1.158     albertel 7682:     my $i=-1;
1.542     raeburn  7683:     my $started;
1.447     foxr     7684: 
1.582     raeburn  7685:     my $nav_error;
                   7686:     &scantron_get_maxbubble(\$nav_error); # Need the bubble lines array to parse.
                   7687:     if ($nav_error) {
                   7688:         $r->print(&navmap_errormsg());
                   7689:         return '';
                   7690:     }
                   7691: 
1.513     foxr     7692:     # If an ssi failed in scantron_get_maxbubble, put an error message out to
                   7693:     # the user and return.
                   7694: 
                   7695:     if ($ssi_error) {
                   7696: 	$r->print("</form>");
                   7697: 	&ssi_print_error($r);
                   7698: 	$r->print(&show_grading_menu_form($symb));
1.520     www      7699:         &Apache::lonnet::remove_lock($lock);
1.513     foxr     7700: 	return '';		# Dunno why the other returns return '' rather than just returning.
                   7701:     }
1.447     foxr     7702: 
1.542     raeburn  7703:     my %lettdig = &letter_to_digits();
                   7704:     my $numletts = scalar(keys(%lettdig));
                   7705: 
1.157     albertel 7706:     while ($i<$scanlines->{'count'}) {
                   7707:  	($uname,$udom)=('','');
                   7708:  	$i++;
1.200     albertel 7709:  	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.157     albertel 7710:  	if ($line=~/^[\s\cz]*$/) { next; }
1.200     albertel 7711: 	if ($started) {
                   7712: 	    &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state,
                   7713: 						     'last student');
                   7714: 	}
                   7715: 	$started=1;
1.157     albertel 7716:  	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
                   7717:  						 $scan_data);
                   7718:  	unless ($uname=&scantron_find_student($scan_record,$scan_data,
                   7719:  					      \%idmap,$i)) {
                   7720:   	    &scantron_add_delay(\@delayqueue,$line,
                   7721:  				'Unable to find a student that matches',1);
                   7722:  	    next;
                   7723:   	}
                   7724:  	if (exists $completedstudents{$uname}) {
                   7725:  	    &scantron_add_delay(\@delayqueue,$line,
                   7726:  				'Student '.$uname.' has multiple sheets',2);
                   7727:  	    next;
                   7728:  	}
                   7729:   	($uname,$udom)=split(/:/,$uname);
1.330     albertel 7730: 
1.586     raeburn  7731:         my (%partids_by_symb,$res_error);
1.554     raeburn  7732:         foreach my $resource (@resources) {
1.586     raeburn  7733:             my $ressymb;
                   7734:             if (ref($resource)) {
                   7735:                 $ressymb = $resource->symb();
                   7736:             } else {
                   7737:                 $res_error = 1;
                   7738:                 last;
                   7739:             }
1.557     raeburn  7740:             if ((exists($grader_randomlists_by_symb{$ressymb})) ||
                   7741:                 (ref($grader_partids_by_symb{$ressymb}) ne 'ARRAY')) {
                   7742:                 my ($analysis,$parts) =
                   7743:                     &scantron_partids_tograde($resource,$env{'request.course.id'},$uname,$udom);
                   7744:                 $partids_by_symb{$ressymb} = $parts;
                   7745:             } else {
                   7746:                 $partids_by_symb{$ressymb} = $grader_partids_by_symb{$ressymb};
                   7747:             }
1.554     raeburn  7748:         }
                   7749: 
1.586     raeburn  7750:         if ($res_error) {
                   7751:             &scantron_add_delay(\@delayqueue,$line,
                   7752:                                 'An error occurred while grading student '.$uname,2);
                   7753:             next;
                   7754:         }
                   7755: 
1.330     albertel 7756: 	&Apache::lonxml::clear_problem_counter();
1.514     raeburn  7757:   	&Apache::lonnet::appenv($scan_record);
1.376     albertel 7758: 
                   7759: 	if (&scantron_clear_skip($scanlines,$scan_data,$i)) {
                   7760: 	    &scantron_putfile($scanlines,$scan_data);
                   7761: 	}
1.161     albertel 7762: 	
1.542     raeburn  7763:         my $scancode;
                   7764:         if ((exists($scan_record->{'scantron.CODE'})) &&
                   7765:             (&Apache::lonnet::validCODE($scan_record->{'scantron.CODE'}))) {
                   7766:             $scancode = $scan_record->{'scantron.CODE'};
                   7767:         } else {
                   7768:             $scancode = '';
                   7769:         }
                   7770: 
                   7771:         if (&grade_student_bubbles($r,$uname,$udom,$scan_record,$scancode,
1.554     raeburn  7772:                                    \@resources,\%partids_by_symb) eq 'ssi_error') {
1.542     raeburn  7773:             $ssi_error = 0; # So end of handler error message does not trigger.
                   7774:             $r->print("</form>");
                   7775:             &ssi_print_error($r);
                   7776:             $r->print(&show_grading_menu_form($symb));
                   7777:             &Apache::lonnet::remove_lock($lock);
                   7778:             return '';      # Why return ''?  Beats me.
                   7779:         }
1.513     foxr     7780: 
1.140     albertel 7781: 	$completedstudents{$uname}={'line'=>$line};
1.542     raeburn  7782:         if ($env{'form.verifyrecord'}) {
                   7783:             my $lastpos = $env{'form.scantron_maxbubble'}*$scantron_config{'Qlength'};
                   7784:             my $studentdata = substr($line,$scantron_config{'Qstart'}-1,$lastpos);
                   7785:             chomp($studentdata);
                   7786:             $studentdata =~ s/\r$//;
                   7787:             my $studentrecord = '';
                   7788:             my $counter = -1;
                   7789:             foreach my $resource (@resources) {
1.554     raeburn  7790:                 my $ressymb = $resource->symb();
1.542     raeburn  7791:                 ($counter,my $recording) =
                   7792:                     &verify_scantron_grading($resource,$udom,$uname,$env{'request.course.id'},
1.554     raeburn  7793:                                              $counter,$studentdata,$partids_by_symb{$ressymb},
1.542     raeburn  7794:                                              \%scantron_config,\%lettdig,$numletts);
                   7795:                 $studentrecord .= $recording;
                   7796:             }
                   7797:             if ($studentrecord ne $studentdata) {
1.554     raeburn  7798:                 &Apache::lonxml::clear_problem_counter();
                   7799:                 if (&grade_student_bubbles($r,$uname,$udom,$scan_record,$scancode,
                   7800:                                            \@resources,\%partids_by_symb) eq 'ssi_error') {
                   7801:                     $ssi_error = 0; # So end of handler error message does not trigger.
                   7802:                     $r->print("</form>");
                   7803:                     &ssi_print_error($r);
                   7804:                     $r->print(&show_grading_menu_form($symb));
                   7805:                     &Apache::lonnet::remove_lock($lock);
                   7806:                     delete($completedstudents{$uname});
                   7807:                     return '';
                   7808:                 }
1.542     raeburn  7809:                 $counter = -1;
                   7810:                 $studentrecord = '';
                   7811:                 foreach my $resource (@resources) {
1.554     raeburn  7812:                     my $ressymb = $resource->symb();
1.542     raeburn  7813:                     ($counter,my $recording) =
                   7814:                         &verify_scantron_grading($resource,$udom,$uname,$env{'request.course.id'},
1.554     raeburn  7815:                                                  $counter,$studentdata,$partids_by_symb{$ressymb},
1.542     raeburn  7816:                                                  \%scantron_config,\%lettdig,$numletts);
                   7817:                     $studentrecord .= $recording;
                   7818:                 }
                   7819:                 if ($studentrecord ne $studentdata) {
                   7820:                     $r->print('<p><span class="LC_error">');
                   7821:                     if ($scancode eq '') {
                   7822:                         $r->print(&mt('Mismatch grading bubble sheet for user: [_1] with ID: [_2].',
                   7823:                                   $uname.':'.$udom,$scan_record->{'scantron.ID'}));
                   7824:                     } else {
                   7825:                         $r->print(&mt('Mismatch grading bubble sheet for user: [_1] with ID: [_2] and CODE: [_3].',
                   7826:                                   $uname.':'.$udom,$scan_record->{'scantron.ID'},$scancode));
                   7827:                     }
                   7828:                     $r->print('</span><br />'.&Apache::loncommon::start_data_table()."\n".
                   7829:                               &Apache::loncommon::start_data_table_header_row()."\n".
                   7830:                               '<th>'.&mt('Source').'</th><th>'.&mt('Bubbled responses').'</th>'.
                   7831:                               &Apache::loncommon::end_data_table_header_row()."\n".
                   7832:                               &Apache::loncommon::start_data_table_row().
                   7833:                               '<td>'.&mt('Bubble Sheet').'</td>'.
                   7834:                               '<td><span class="LC_nobreak">'.$studentdata.'</span></td>'.
                   7835:                               &Apache::loncommon::end_data_table_row().
                   7836:                               &Apache::loncommon::start_data_table_row().
                   7837:                               '<td>Stored submissions</td>'.
                   7838:                               '<td><span class="LC_nobreak">'.$studentrecord.'</span></td>'."\n".
                   7839:                               &Apache::loncommon::end_data_table_row().
                   7840:                               &Apache::loncommon::end_data_table().'</p>');
                   7841:                 } else {
                   7842:                     $r->print('<br /><span class="LC_warning">'.
                   7843:                              &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 />'.
                   7844:                              &mt("As a consequence, this user's submission history records two tries.").
                   7845:                                  '</span><br />');
                   7846:                 }
                   7847:             }
                   7848:         }
1.543     raeburn  7849:         if (&Apache::loncommon::connection_aborted($r)) { last; }
1.140     albertel 7850:     } continue {
1.330     albertel 7851: 	&Apache::lonxml::clear_problem_counter();
1.552     raeburn  7852: 	&Apache::lonnet::delenv('scantron.');
1.82      albertel 7853:     }
1.140     albertel 7854:     &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
1.520     www      7855:     &Apache::lonnet::remove_lock($lock);
1.172     albertel 7856: #    my $lasttime = &Time::HiRes::time()-$start;
                   7857: #    $r->print("<p>took $lasttime</p>");
1.140     albertel 7858: 
1.200     albertel 7859:     $r->print("</form>");
1.324     albertel 7860:     $r->print(&show_grading_menu_form($symb));
1.157     albertel 7861:     return '';
1.75      albertel 7862: }
1.157     albertel 7863: 
1.557     raeburn  7864: sub graders_resources_pass {
                   7865:     my ($resources,$grader_partids_by_symb,$grader_randomlists_by_symb) = @_;
                   7866:     if ((ref($resources) eq 'ARRAY') && (ref($grader_partids_by_symb)) && 
                   7867:         (ref($grader_randomlists_by_symb) eq 'HASH')) {
                   7868:         foreach my $resource (@{$resources}) {
                   7869:             my $ressymb = $resource->symb();
                   7870:             my ($analysis,$parts) =
                   7871:                 &scantron_partids_tograde($resource,$env{'request.course.id'},
                   7872:                                           $env{'user.name'},$env{'user.domain'},1);
                   7873:             $grader_partids_by_symb->{$ressymb} = $parts;
                   7874:             if (ref($analysis) eq 'HASH') {
                   7875:                 if (ref($analysis->{'parts_withrandomlist'}) eq 'ARRAY') {
                   7876:                     $grader_randomlists_by_symb->{$ressymb} =
                   7877:                         $analysis->{'parts_withrandomlist'};
                   7878:                 }
                   7879:             }
                   7880:         }
                   7881:     }
                   7882:     return;
                   7883: }
                   7884: 
1.542     raeburn  7885: sub grade_student_bubbles {
1.554     raeburn  7886:     my ($r,$uname,$udom,$scan_record,$scancode,$resources,$parts) = @_;
                   7887:     if (ref($resources) eq 'ARRAY') {
                   7888:         my $count = 0;
                   7889:         foreach my $resource (@{$resources}) {
                   7890:             my $ressymb = $resource->symb();
                   7891:             my %form = ('submitted'      => 'scantron',
                   7892:                         'grade_target'   => 'grade',
                   7893:                         'grade_username' => $uname,
                   7894:                         'grade_domain'   => $udom,
                   7895:                         'grade_courseid' => $env{'request.course.id'},
                   7896:                         'grade_symb'     => $ressymb,
                   7897:                         'CODE'           => $scancode
                   7898:                        );
                   7899:             if (ref($parts) eq 'HASH') {
                   7900:                 if (ref($parts->{$ressymb}) eq 'ARRAY') {
                   7901:                     foreach my $part (@{$parts->{$ressymb}}) {
                   7902:                         $form{'scantron_questnum_start.'.$part} =
                   7903:                             1+$env{'form.scantron.first_bubble_line.'.$count};
                   7904:                         $count++;
                   7905:                     }
                   7906:                 }
                   7907:             }
                   7908:             my $result=&ssi_with_retries($resource->src(),$ssi_retries,%form);
                   7909:             return 'ssi_error' if ($ssi_error);
                   7910:             last if (&Apache::loncommon::connection_aborted($r));
                   7911:         }
1.542     raeburn  7912:     }
                   7913:     return;
                   7914: }
                   7915: 
1.157     albertel 7916: sub scantron_upload_scantron_data {
                   7917:     my ($r)=@_;
1.565     raeburn  7918:     my $dom = $env{'request.role.domain'};
                   7919:     my $domdesc = &Apache::lonnet::domain($dom,'description');
                   7920:     $r->print(&Apache::loncommon::coursebrowser_javascript($dom));
1.157     albertel 7921:     my $select_link=&Apache::loncommon::selectcourse_link('rules','courseid',
1.181     albertel 7922: 							  'domainid',
1.565     raeburn  7923: 							  'coursename',$dom);
                   7924:     my $syllabuslink = '<a href="javascript:ToSyllabus();">'.&mt('Syllabus').'</a>'.
                   7925:                        ('&nbsp'x2).&mt('(shows course personnel)'); 
1.324     albertel 7926:     my $default_form_data=&defaultFormData(&get_symb($r,1));
1.579     raeburn  7927:     my $nofile_alert = &mt('Please use the browse button to select a file from your local directory.');
                   7928:     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 7929:     $r->print(&Apache::lonhtmlcommon::scripttag('
1.157     albertel 7930:     function checkUpload(formname) {
                   7931: 	if (formname.upfile.value == "") {
1.579     raeburn  7932: 	    alert("'.$nofile_alert.'");
1.157     albertel 7933: 	    return false;
                   7934: 	}
1.565     raeburn  7935:         if (formname.courseid.value == "") {
1.579     raeburn  7936:             alert("'.$nocourseid_alert.'");
1.565     raeburn  7937:             return false;
                   7938:         }
1.157     albertel 7939: 	formname.submit();
                   7940:     }
1.565     raeburn  7941: 
                   7942:     function ToSyllabus() {
                   7943:         var cdom = '."'$dom'".';
                   7944:         var cnum = document.rules.courseid.value;
                   7945:         if (cdom == "" || cdom == null) {
                   7946:             return;
                   7947:         }
                   7948:         if (cnum == "" || cnum == null) {
                   7949:            return;
                   7950:         }
                   7951:         syllwin=window.open("/public/"+cdom+"/"+cnum+"/syllabus","LONCAPASyllabus",
                   7952:                             "height=350,width=350,scrollbars=yes,menubar=no");
                   7953:         return;
                   7954:     }
                   7955: 
1.597     wenzelju 7956: '));
                   7957:     $r->print('
1.566     raeburn  7958: <h3>'.&mt('Send scanned bubblesheet data to a course').'</h3>
                   7959: 
1.492     albertel 7960: <form enctype="multipart/form-data" action="/adm/grades" name="rules" method="post">
1.565     raeburn  7961: '.$default_form_data.
                   7962:   &Apache::lonhtmlcommon::start_pick_box().
                   7963:   &Apache::lonhtmlcommon::row_title(&mt('Course ID')).
                   7964:   '<input name="courseid" type="text" size="30" />'.$select_link.
                   7965:   &Apache::lonhtmlcommon::row_closure().
                   7966:   &Apache::lonhtmlcommon::row_title(&mt('Course Name')).
                   7967:   '<input name="coursename" type="text" size="30" />'.$syllabuslink.
                   7968:   &Apache::lonhtmlcommon::row_closure().
                   7969:   &Apache::lonhtmlcommon::row_title(&mt('Domain')).
                   7970:   '<input name="domainid" type="hidden" />'.$domdesc.
                   7971:   &Apache::lonhtmlcommon::row_closure().
                   7972:   &Apache::lonhtmlcommon::row_title(&mt('File to upload')).
                   7973:   '<input type="file" name="upfile" size="50" />'.
                   7974:   &Apache::lonhtmlcommon::row_closure(1).
                   7975:   &Apache::lonhtmlcommon::end_pick_box().'<br />
                   7976: 
1.492     albertel 7977: <input name="command" value="scantronupload_save" type="hidden" />
1.589     bisitz   7978: <input type="button" onclick="javascript:checkUpload(this.form);" value="'.&mt('Upload Bubblesheet Data').'" />
1.157     albertel 7979: </form>
1.492     albertel 7980: ');
1.157     albertel 7981:     return '';
                   7982: }
                   7983: 
1.423     albertel 7984: 
1.157     albertel 7985: sub scantron_upload_scantron_data_save {
                   7986:     my($r)=@_;
1.324     albertel 7987:     my ($symb)=&get_symb($r,1);
1.182     albertel 7988:     my $doanotherupload=
                   7989: 	'<br /><form action="/adm/grades" method="post">'."\n".
                   7990: 	'<input type="hidden" name="command" value="scantronupload" />'."\n".
1.492     albertel 7991: 	'<input type="submit" name="submit" value="'.&mt('Do Another Upload').'" />'."\n".
1.182     albertel 7992: 	'</form>'."\n";
1.257     albertel 7993:     if (!&Apache::lonnet::allowed('usc',$env{'form.domainid'}) &&
1.162     albertel 7994: 	!&Apache::lonnet::allowed('usc',
1.257     albertel 7995: 			    $env{'form.domainid'}.'_'.$env{'form.courseid'})) {
1.575     www      7996: 	$r->print(&mt("You are not allowed to upload bubblesheet data to the requested course.")."<br />");
1.182     albertel 7997: 	if ($symb) {
1.324     albertel 7998: 	    $r->print(&show_grading_menu_form($symb));
1.182     albertel 7999: 	} else {
                   8000: 	    $r->print($doanotherupload);
                   8001: 	}
1.162     albertel 8002: 	return '';
                   8003:     }
1.257     albertel 8004:     my %coursedata=&Apache::lonnet::coursedescription($env{'form.domainid'}.'_'.$env{'form.courseid'});
1.568     raeburn  8005:     my $uploadedfile;
1.567     raeburn  8006:     $r->print('<h3>'.&mt("Uploading file to [_1]",$coursedata{'description'}).'</h3>');
1.257     albertel 8007:     if (length($env{'form.upfile'}) < 2) {
1.568     raeburn  8008:         $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 8009:     } else {
1.568     raeburn  8010:         my $result = 
                   8011:             &Apache::lonnet::userfileupload('upfile','','scantron','','','',
                   8012:                                             $env{'form.courseid'},$env{'form.domainid'});
                   8013: 	if ($result =~ m{^/uploaded/}) {
1.567     raeburn  8014: 	    $r->print(&mt('[_1]Success:[_2] Successfully uploaded [_3] bytes of data into location: [_4]',
                   8015:                           '<span class="LC_success">','</span>',(length($env{'form.upfile'})-1),
                   8016: 			  '<span class="LC_filename">'.$result.'</span>'));
1.568     raeburn  8017:             ($uploadedfile) = ($result =~ m{/([^/]+)$});
1.567     raeburn  8018:             $r->print(&validate_uploaded_scantron_file($env{'form.domainid'},
1.568     raeburn  8019:                                                        $env{'form.courseid'},$uploadedfile));
1.210     albertel 8020: 	} else {
1.567     raeburn  8021: 	    $r->print(&mt('[_1]Error:[_2] An error ([_3]) occurred when attempting to upload the file, [_4]',
                   8022:                           '<span class="LC_error">','</span>',$result,
1.568     raeburn  8023: 			  '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>'));
1.183     albertel 8024: 	}
                   8025:     }
1.174     albertel 8026:     if ($symb) {
1.209     ng       8027: 	$r->print(&scantron_selectphase($r,$uploadedfile));
1.174     albertel 8028:     } else {
1.182     albertel 8029: 	$r->print($doanotherupload);
1.174     albertel 8030:     }
1.157     albertel 8031:     return '';
                   8032: }
                   8033: 
1.567     raeburn  8034: sub validate_uploaded_scantron_file {
                   8035:     my ($cdom,$cname,$fname) = @_;
                   8036:     my $scanlines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.$fname);
                   8037:     my @lines;
                   8038:     if ($scanlines ne '-1') {
                   8039:         @lines=split("\n",$scanlines,-1);
                   8040:     }
                   8041:     my $output;
                   8042:     if (@lines) {
                   8043:         my (%counts,$max_match_format);
                   8044:         my ($max_match_count,$max_match_pct) = (0,0);
                   8045:         my $classlist = &Apache::loncoursedata::get_classlist($cdom,$cname);
                   8046:         my %idmap = &username_to_idmap($classlist);
                   8047:         foreach my $key (keys(%idmap)) {
                   8048:             my $lckey = lc($key);
                   8049:             $idmap{$lckey} = $idmap{$key};
                   8050:         }
                   8051:         my %unique_formats;
                   8052:         my @formatlines = &get_scantronformat_file();
                   8053:         foreach my $line (@formatlines) {
                   8054:             chomp($line);
                   8055:             my @config = split(/:/,$line);
                   8056:             my $idstart = $config[5];
                   8057:             my $idlength = $config[6];
                   8058:             if (($idstart ne '') && ($idlength > 0)) {
                   8059:                 if (ref($unique_formats{$idstart.':'.$idlength}) eq 'ARRAY') {
                   8060:                     push(@{$unique_formats{$idstart.':'.$idlength}},$config[0].':'.$config[1]); 
                   8061:                 } else {
                   8062:                     $unique_formats{$idstart.':'.$idlength} = [$config[0].':'.$config[1]];
                   8063:                 }
                   8064:             }
                   8065:         }
                   8066:         foreach my $key (keys(%unique_formats)) {
                   8067:             my ($idstart,$idlength) = split(':',$key);
                   8068:             %{$counts{$key}} = (
                   8069:                                'found'   => 0,
                   8070:                                'total'   => 0,
                   8071:                               );
                   8072:             foreach my $line (@lines) {
                   8073:                 next if ($line =~ /^#/);
                   8074:                 next if ($line =~ /^[\s\cz]*$/);
                   8075:                 my $id = substr($line,$idstart-1,$idlength);
                   8076:                 $id = lc($id);
                   8077:                 if (exists($idmap{$id})) {
                   8078:                     $counts{$key}{'found'} ++;
                   8079:                 }
                   8080:                 $counts{$key}{'total'} ++;
                   8081:             }
                   8082:             if ($counts{$key}{'total'}) {
                   8083:                 my $percent_match = (100*$counts{$key}{'found'})/($counts{$key}{'total'});
                   8084:                 if (($max_match_format eq '') || ($percent_match > $max_match_pct)) {
                   8085:                     $max_match_pct = $percent_match;
                   8086:                     $max_match_format = $key;
                   8087:                     $max_match_count = $counts{$key}{'total'};
                   8088:                 }
                   8089:             }
                   8090:         }
                   8091:         if (ref($unique_formats{$max_match_format}) eq 'ARRAY') {
                   8092:             my $format_descs;
                   8093:             my $numwithformat = @{$unique_formats{$max_match_format}};
                   8094:             for (my $i=0; $i<$numwithformat; $i++) {
                   8095:                 my ($name,$desc) = split(':',$unique_formats{$max_match_format}[$i]);
                   8096:                 if ($i<$numwithformat-2) {
                   8097:                     $format_descs .= '"<i>'.$desc.'</i>", ';
                   8098:                 } elsif ($i==$numwithformat-2) {
                   8099:                     $format_descs .= '"<i>'.$desc.'</i>" '.&mt('and').' ';
                   8100:                 } elsif ($i==$numwithformat-1) {
                   8101:                     $format_descs .= '"<i>'.$desc.'</i>"';
                   8102:                 }
                   8103:             }
                   8104:             my $showpct = sprintf("%.0f",$max_match_pct).'%';
                   8105:             $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).
                   8106:                        '<br />'.&mt('A low percentage of matches results from one of the following:').'<ul>'.
                   8107:                        '<li>'.&mt('The file was uploaded to the wrong course').'</li>'.
                   8108:                        '<li>'.&mt('The data are not in the format expected for the domain: [_1]',
                   8109:                                   '<i>'.$cdom.'</i>').'</li>'.
                   8110:                        '<li>'.&mt('Students did not bubble their IDs, or mis-bubbled them').'</li>'.
                   8111:                        '<li>'.&mt('The course roster is not up to date').'</li>'.
                   8112:                        '</ul>';
                   8113:         }
                   8114:     } else {
                   8115:         $output = '<span class="LC_warning">'.&mt('Uploaded file contained no data').'</span>';
                   8116:     }
                   8117:     return $output;
                   8118: }
                   8119: 
1.202     albertel 8120: sub valid_file {
                   8121:     my ($requested_file)=@_;
                   8122:     foreach my $filename (sort(&scantron_filenames())) {
                   8123: 	if ($requested_file eq $filename) { return 1; }
                   8124:     }
                   8125:     return 0;
                   8126: }
                   8127: 
                   8128: sub scantron_download_scantron_data {
                   8129:     my ($r)=@_;
1.324     albertel 8130:     my $default_form_data=&defaultFormData(&get_symb($r,1));
1.257     albertel 8131:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   8132:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   8133:     my $file=$env{'form.scantron_selectfile'};
1.202     albertel 8134:     if (! &valid_file($file)) {
1.492     albertel 8135: 	$r->print('
1.202     albertel 8136: 	<p>
1.492     albertel 8137: 	    '.&mt('The requested file name was invalid.').'
1.202     albertel 8138:         </p>
1.492     albertel 8139: ');
1.324     albertel 8140: 	$r->print(&show_grading_menu_form(&get_symb($r,1)));
1.202     albertel 8141: 	return;
                   8142:     }
                   8143:     my $orig='/uploaded/'.$cdom.'/'.$cname.'/scantron_orig_'.$file;
                   8144:     my $corrected='/uploaded/'.$cdom.'/'.$cname.'/scantron_corrected_'.$file;
                   8145:     my $skipped='/uploaded/'.$cdom.'/'.$cname.'/scantron_skipped_'.$file;
                   8146:     &Apache::lonnet::allowuploaded('/adm/grades',$orig);
                   8147:     &Apache::lonnet::allowuploaded('/adm/grades',$corrected);
                   8148:     &Apache::lonnet::allowuploaded('/adm/grades',$skipped);
1.492     albertel 8149:     $r->print('
1.202     albertel 8150:     <p>
1.492     albertel 8151: 	'.&mt('[_1]Original[_2] file as uploaded by the scantron office.',
                   8152: 	      '<a href="'.$orig.'">','</a>').'
1.202     albertel 8153:     </p>
                   8154:     <p>
1.492     albertel 8155: 	'.&mt('[_1]Corrections[_2], a file of corrected records that were used in grading.',
                   8156: 	      '<a href="'.$corrected.'">','</a>').'
1.202     albertel 8157:     </p>
                   8158:     <p>
1.492     albertel 8159: 	'.&mt('[_1]Skipped[_2], a file of records that were skipped.',
                   8160: 	      '<a href="'.$skipped.'">','</a>').'
1.202     albertel 8161:     </p>
1.492     albertel 8162: ');
1.324     albertel 8163:     $r->print(&show_grading_menu_form(&get_symb($r,1)));
1.202     albertel 8164:     return '';
                   8165: }
1.157     albertel 8166: 
1.523     raeburn  8167: sub checkscantron_results {
                   8168:     my ($r) = @_;
                   8169:     my ($symb)=&get_symb($r);
                   8170:     if (!$symb) {return '';}
                   8171:     my $grading_menu_button=&show_grading_menu_form($symb);
                   8172:     my $cid = $env{'request.course.id'};
1.542     raeburn  8173:     my %lettdig = &letter_to_digits();
1.523     raeburn  8174:     my $numletts = scalar(keys(%lettdig));
                   8175:     my $cnum = $env{'course.'.$cid.'.num'};
                   8176:     my $cdom = $env{'course.'.$cid.'.domain'};
                   8177:     my (undef, undef, $sequence) = &Apache::lonnet::decode_symb($env{'form.selectpage'});
                   8178:     my %record;
                   8179:     my %scantron_config =
                   8180:         &Apache::grades::get_scantron_config($env{'form.scantron_format'});
                   8181:     my ($scanlines,$scan_data)=&Apache::grades::scantron_getfile();
                   8182:     my $classlist=&Apache::loncoursedata::get_classlist();
                   8183:     my %idmap=&Apache::grades::username_to_idmap($classlist);
                   8184:     my $navmap=Apache::lonnavmaps::navmap->new();
1.582     raeburn  8185:     unless (ref($navmap)) {
                   8186:         $r->print(&navmap_errormsg());
                   8187:         return '';
                   8188:     }
1.523     raeburn  8189:     my $map=$navmap->getResourceByUrl($sequence);
1.557     raeburn  8190:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
                   8191:     my (%grader_partids_by_symb,%grader_randomlists_by_symb);
                   8192:     &graders_resources_pass(\@resources,\%grader_partids_by_symb,                             \%grader_randomlists_by_symb);
                   8193: 
1.554     raeburn  8194:     my ($uname,$udom);
1.523     raeburn  8195:     my (%scandata,%lastname,%bylast);
                   8196:     $r->print('
                   8197: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="checkscantron">'."\n");
                   8198: 
                   8199:     my @delayqueue;
                   8200:     my %completedstudents;
                   8201: 
                   8202:     my $count=&Apache::grades::get_todo_count($scanlines,$scan_data);
1.581     www      8203:     my %prog_state=&Apache::lonhtmlcommon::Create_PrgWin($r,'Bubblesheet/Submissions Comparison Status',
                   8204:                                     'Progress of Bubblesheet Data/Submission Records Comparison',$count,
1.523     raeburn  8205:                                     'inline',undef,'checkscantron');
1.546     raeburn  8206:     my ($username,$domain,$started);
1.582     raeburn  8207:     my $nav_error;
                   8208:     &scantron_get_maxbubble(\$nav_error); # Need the bubble lines array to parse.
                   8209:     if ($nav_error) {
                   8210:         $r->print(&navmap_errormsg());
                   8211:         return '';
                   8212:     }
1.523     raeburn  8213: 
                   8214:     &Apache::lonhtmlcommon::Update_PrgWin($r,\%prog_state,
                   8215:                                           'Processing first student');
                   8216:     my $start=&Time::HiRes::time();
                   8217:     my $i=-1;
                   8218: 
                   8219:     while ($i<$scanlines->{'count'}) {
                   8220:         ($username,$domain,$uname)=('','','');
                   8221:         $i++;
                   8222:         my $line=&Apache::grades::scantron_get_line($scanlines,$scan_data,$i);
                   8223:         if ($line=~/^[\s\cz]*$/) { next; }
                   8224:         if ($started) {
                   8225:             &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state,
                   8226:                                                      'last student');
                   8227:         }
                   8228:         $started=1;
                   8229:         my $scan_record=
                   8230:             &Apache::grades::scantron_parse_scanline($line,$i,\%scantron_config,
                   8231:                                                      $scan_data);
                   8232:         unless ($uname=&Apache::grades::scantron_find_student($scan_record,$scan_data,
                   8233:                                                               \%idmap,$i)) {
                   8234:             &Apache::grades::scantron_add_delay(\@delayqueue,$line,
                   8235:                                 'Unable to find a student that matches',1);
                   8236:             next;
                   8237:         }
                   8238:         if (exists $completedstudents{$uname}) {
                   8239:             &Apache::grades::scantron_add_delay(\@delayqueue,$line,
                   8240:                                 'Student '.$uname.' has multiple sheets',2);
                   8241:             next;
                   8242:         }
                   8243:         my $pid = $scan_record->{'scantron.ID'};
                   8244:         $lastname{$pid} = $scan_record->{'scantron.LastName'};
                   8245:         push(@{$bylast{$lastname{$pid}}},$pid);
                   8246:         my $lastpos = $env{'form.scantron_maxbubble'}*$scantron_config{'Qlength'};
                   8247:         $scandata{$pid} = substr($line,$scantron_config{'Qstart'}-1,$lastpos);
                   8248:         chomp($scandata{$pid});
                   8249:         $scandata{$pid} =~ s/\r$//;
                   8250:         ($username,$domain)=split(/:/,$uname);
                   8251:         my $counter = -1;
                   8252:         foreach my $resource (@resources) {
1.557     raeburn  8253:             my $parts;
1.554     raeburn  8254:             my $ressymb = $resource->symb();
1.557     raeburn  8255:             if ((exists($grader_randomlists_by_symb{$ressymb})) ||
                   8256:                 (ref($grader_partids_by_symb{$ressymb}) ne 'ARRAY')) {
                   8257:                 (my $analysis,$parts) =
                   8258:                     &scantron_partids_tograde($resource,$env{'request.course.id'},$username,$domain);
                   8259:             } else {
                   8260:                 $parts = $grader_partids_by_symb{$ressymb};
                   8261:             }
1.542     raeburn  8262:             ($counter,my $recording) =
                   8263:                 &verify_scantron_grading($resource,$domain,$username,$cid,$counter,
1.554     raeburn  8264:                                          $scandata{$pid},$parts,
1.542     raeburn  8265:                                          \%scantron_config,\%lettdig,$numletts);
                   8266:             $record{$pid} .= $recording;
1.523     raeburn  8267:         }
                   8268:     }
                   8269:     &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
                   8270:     $r->print('<br />');
                   8271:     my ($okstudents,$badstudents,$numstudents,$passed,$failed);
                   8272:     $passed = 0;
                   8273:     $failed = 0;
                   8274:     $numstudents = 0;
                   8275:     foreach my $last (sort(keys(%bylast))) {
                   8276:         if (ref($bylast{$last}) eq 'ARRAY') {
                   8277:             foreach my $pid (sort(@{$bylast{$last}})) {
                   8278:                 my $showscandata = $scandata{$pid};
                   8279:                 my $showrecord = $record{$pid};
                   8280:                 $showscandata =~ s/\s/&nbsp;/g;
                   8281:                 $showrecord =~ s/\s/&nbsp;/g;
                   8282:                 if ($scandata{$pid} eq $record{$pid}) {
                   8283:                     my $css_class = ($passed % 2)?'LC_odd_row':'LC_even_row';
                   8284:                     $okstudents .= '<tr class="'.$css_class.'">'.
1.581     www      8285: '<td>'.&mt('Bubblesheet').'</td><td>'.$showscandata.'</td><td rowspan="2">'.$last.'</td><td rowspan="2">'.$pid.'</td>'."\n".
1.523     raeburn  8286: '</tr>'."\n".
                   8287: '<tr class="'.$css_class.'">'."\n".
                   8288: '<td>Submissions</td><td>'.$showrecord.'</td></tr>'."\n";
                   8289:                     $passed ++;
                   8290:                 } else {
                   8291:                     my $css_class = ($failed % 2)?'LC_odd_row':'LC_even_row';
1.581     www      8292:                     $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  8293: '</tr>'."\n".
                   8294: '<tr class="'.$css_class.'">'."\n".
                   8295: '<td>Submissions</td><td><span class="LC_nobreak">'.$record{$pid}.'</span></td>'."\n".
                   8296: '</tr>'."\n";
                   8297:                     $failed ++;
                   8298:                 }
                   8299:                 $numstudents ++;
                   8300:             }
                   8301:         }
                   8302:     }
1.572     www      8303:     $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  8304:     $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>');
                   8305:     if ($passed) {
1.572     www      8306:         $r->print(&mt('Students with exact correspondence between bubblesheet data and submissions are as follows:').'<br /><br />');
1.523     raeburn  8307:         $r->print(&Apache::loncommon::start_data_table()."\n".
                   8308:                  &Apache::loncommon::start_data_table_header_row()."\n".
                   8309:                  '<th>'.&mt('Source').'</th><th>'.&mt('Bubble records').'</th><th>'.&mt('Name').'</th><th>'.&mt('ID').'</th>'.
                   8310:                  &Apache::loncommon::end_data_table_header_row()."\n".
                   8311:                  $okstudents."\n".
                   8312:                  &Apache::loncommon::end_data_table().'<br />');
                   8313:     }
                   8314:     if ($failed) {
1.572     www      8315:         $r->print(&mt('Students with differences between bubblesheet data and submissions are as follows:').'<br /><br />');
1.523     raeburn  8316:         $r->print(&Apache::loncommon::start_data_table()."\n".
                   8317:                  &Apache::loncommon::start_data_table_header_row()."\n".
                   8318:                  '<th>'.&mt('Source').'</th><th>'.&mt('Bubble records').'</th><th>'.&mt('Name').'</th><th>'.&mt('ID').'</th>'.
                   8319:                  &Apache::loncommon::end_data_table_header_row()."\n".
                   8320:                  $badstudents."\n".
                   8321:                  &Apache::loncommon::end_data_table()).'<br />'.
1.572     www      8322:                  &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  8323:     }
                   8324:     $r->print('</form><br />'.$grading_menu_button);
                   8325:     return;
                   8326: }
                   8327: 
1.542     raeburn  8328: sub verify_scantron_grading {
1.554     raeburn  8329:     my ($resource,$domain,$username,$cid,$counter,$scandata,$partids,
1.542     raeburn  8330:         $scantron_config,$lettdig,$numletts) = @_;
                   8331:     my ($record,%expected,%startpos);
                   8332:     return ($counter,$record) if (!ref($resource));
                   8333:     return ($counter,$record) if (!$resource->is_problem());
                   8334:     my $symb = $resource->symb();
1.554     raeburn  8335:     return ($counter,$record) if (ref($partids) ne 'ARRAY');
                   8336:     foreach my $part_id (@{$partids}) {
1.542     raeburn  8337:         $counter ++;
                   8338:         $expected{$part_id} = 0;
                   8339:         if ($env{"form.scantron.sub_bubblelines.$counter"}) {
                   8340:             my @sub_lines = split(/,/,$env{"form.scantron.sub_bubblelines.$counter"});
                   8341:             foreach my $item (@sub_lines) {
                   8342:                 $expected{$part_id} += $item;
                   8343:             }
                   8344:         } else {
                   8345:             $expected{$part_id} = $env{"form.scantron.bubblelines.$counter"};
                   8346:         }
                   8347:         $startpos{$part_id} = $env{"form.scantron.first_bubble_line.$counter"};
                   8348:     }
                   8349:     if ($symb) {
                   8350:         my %recorded;
                   8351:         my (%returnhash) = &Apache::lonnet::restore($symb,$cid,$domain,$username);
                   8352:         if ($returnhash{'version'}) {
                   8353:             my %lasthash=();
                   8354:             my $version;
                   8355:             for ($version=1;$version<=$returnhash{'version'};$version++) {
                   8356:                 foreach my $key (sort(split(/\:/,$returnhash{$version.':keys'}))) {
                   8357:                     $lasthash{$key}=$returnhash{$version.':'.$key};
                   8358:                 }
                   8359:             }
                   8360:             foreach my $key (keys(%lasthash)) {
                   8361:                 if ($key =~ /\.scantron$/) {
                   8362:                     my $value = &unescape($lasthash{$key});
                   8363:                     my ($part_id) = ($key =~ /^resource\.(.+)\.scantron$/);
                   8364:                     if ($value eq '') {
                   8365:                         for (my $i=0; $i<$expected{$part_id}; $i++) {
                   8366:                             for (my $j=0; $j<$scantron_config->{'length'}; $j++) {
                   8367:                                 $recorded{$part_id} .= $scantron_config->{'Qoff'};
                   8368:                             }
                   8369:                         }
                   8370:                     } else {
                   8371:                         my @tocheck;
                   8372:                         my @items = split(//,$value);
                   8373:                         if (($scantron_config->{'Qon'} eq 'letter') ||
                   8374:                             ($scantron_config->{'Qon'} eq 'number')) {
                   8375:                             if (@items < $expected{$part_id}) {
                   8376:                                 my $fragment = substr($scandata,$startpos{$part_id},$expected{$part_id});
                   8377:                                 my @singles = split(//,$fragment);
                   8378:                                 foreach my $pos (@singles) {
                   8379:                                     if ($pos eq ' ') {
                   8380:                                         push(@tocheck,$pos);
                   8381:                                     } else {
                   8382:                                         my $next = shift(@items);
                   8383:                                         push(@tocheck,$next);
                   8384:                                     }
                   8385:                                 }
                   8386:                             } else {
                   8387:                                 @tocheck = @items;
                   8388:                             }
                   8389:                             foreach my $letter (@tocheck) {
                   8390:                                 if ($scantron_config->{'Qon'} eq 'letter') {
                   8391:                                     if ($letter !~ /^[A-J]$/) {
                   8392:                                         $letter = $scantron_config->{'Qoff'};
                   8393:                                     }
                   8394:                                     $recorded{$part_id} .= $letter;
                   8395:                                 } elsif ($scantron_config->{'Qon'} eq 'number') {
                   8396:                                     my $digit;
                   8397:                                     if ($letter !~ /^[A-J]$/) {
                   8398:                                         $digit = $scantron_config->{'Qoff'};
                   8399:                                     } else {
                   8400:                                         $digit = $lettdig->{$letter};
                   8401:                                     }
                   8402:                                     $recorded{$part_id} .= $digit;
                   8403:                                 }
                   8404:                             }
                   8405:                         } else {
                   8406:                             @tocheck = @items;
                   8407:                             for (my $i=0; $i<$expected{$part_id}; $i++) {
                   8408:                                 my $curr_sub = shift(@tocheck);
                   8409:                                 my $digit;
                   8410:                                 if ($curr_sub =~ /^[A-J]$/) {
                   8411:                                     $digit = $lettdig->{$curr_sub}-1;
                   8412:                                 }
                   8413:                                 if ($curr_sub eq 'J') {
                   8414:                                     $digit += scalar($numletts);
                   8415:                                 }
                   8416:                                 for (my $j=0; $j<$scantron_config->{'Qlength'}; $j++) {
                   8417:                                     if ($j == $digit) {
                   8418:                                         $recorded{$part_id} .= $scantron_config->{'Qon'};
                   8419:                                     } else {
                   8420:                                         $recorded{$part_id} .= $scantron_config->{'Qoff'};
                   8421:                                     }
                   8422:                                 }
                   8423:                             }
                   8424:                         }
                   8425:                     }
                   8426:                 }
                   8427:             }
                   8428:         }
1.554     raeburn  8429:         foreach my $part_id (@{$partids}) {
1.542     raeburn  8430:             if ($recorded{$part_id} eq '') {
                   8431:                 for (my $i=0; $i<$expected{$part_id}; $i++) {
                   8432:                     for (my $j=0; $j<$scantron_config->{'Qlength'}; $j++) {
                   8433:                         $recorded{$part_id} .= $scantron_config->{'Qoff'};
                   8434:                     }
                   8435:                 }
                   8436:             }
                   8437:             $record .= $recorded{$part_id};
                   8438:         }
                   8439:     }
                   8440:     return ($counter,$record);
                   8441: }
                   8442: 
                   8443: sub letter_to_digits { 
                   8444:     my %lettdig = (
                   8445:                     A => 1,
                   8446:                     B => 2,
                   8447:                     C => 3,
                   8448:                     D => 4,
                   8449:                     E => 5,
                   8450:                     F => 6,
                   8451:                     G => 7,
                   8452:                     H => 8,
                   8453:                     I => 9,
                   8454:                     J => 0,
                   8455:                   );
                   8456:     return %lettdig;
                   8457: }
                   8458: 
1.423     albertel 8459: 
1.75      albertel 8460: #-------- end of section for handling grading scantron forms -------
                   8461: #
                   8462: #-------------------------------------------------------------------
                   8463: 
1.72      ng       8464: #-------------------------- Menu interface -------------------------
                   8465: #
                   8466: #--- Show a Grading Menu button - Calls the next routine ---
                   8467: sub show_grading_menu_form {
1.324     albertel 8468:     my ($symb)=@_;
1.125     ng       8469:     my $result.='<br /><form action="/adm/grades" method="post">'."\n".
1.418     albertel 8470: 	'<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.257     albertel 8471: 	'<input type="hidden" name="saveState"  value="'.$env{'form.saveState'}.'" />'."\n".
1.72      ng       8472: 	'<input type="hidden" name="command" value="gradingmenu" />'."\n".
1.478     albertel 8473: 	'<input type="submit" name="submit" value="'.&mt('Grading Menu').'" />'."\n".
1.72      ng       8474: 	'</form>'."\n";
                   8475:     return $result;
                   8476: }
                   8477: 
1.443     banghart 8478: sub grading_menu {
                   8479:     my ($request) = @_;
                   8480:     my ($symb)=&get_symb($request);
                   8481:     if (!$symb) {return '';}
                   8482:     my $probTitle = &Apache::lonnet::gettitle($symb);
                   8483: 
                   8484:     my %fields = ('symb'=>&Apache::lonenc::check_encrypt($symb),
                   8485:                   'probTitle'=>$probTitle,
1.598     www      8486:                   'command'=>'individual',
1.443     banghart 8487:                   'gradingMenu'=>1,
                   8488:                   'showgrading'=>"yes");
1.538     schulted 8489:     
1.598     www      8490:     my $url1a = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   8491: 
                   8492:     $fields{'command'}='ungraded';
                   8493:     my $url1b=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   8494: 
                   8495:     $fields{'command'}='table';
                   8496:     my $url1c=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   8497: 
                   8498:     $fields{'command'}='all_for_one';
                   8499:     my $url1d=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   8500: 
1.443     banghart 8501:     $fields{'command'} = 'csvform';
1.538     schulted 8502:     my $url2 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   8503:     
1.443     banghart 8504:     $fields{'command'} = 'processclicker';
1.538     schulted 8505:     my $url3 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   8506:     
1.443     banghart 8507:     $fields{'command'} = 'scantron_selectphase';
1.538     schulted 8508:     my $url4 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
1.602   ! www      8509: 
        !          8510:     $fields{'command'} = 'initialverifyreceipt';
        !          8511:     my $url5 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
1.538     schulted 8512:     
1.598     www      8513:     my @menu = ({	categorytitle=>'Hand Grading',
1.538     schulted 8514:             items =>[
1.598     www      8515:                         {	linktext => 'Select individual students to grade',
                   8516:                     		url => $url1a,
1.538     schulted 8517:                     		permission => 'F',
                   8518:                     		icon => 'edit-find-replace.png',
1.598     www      8519:                     		linktitle => 'Grade current resource for a selection of students.'
                   8520:                         }, 
                   8521:                         {       linktext => 'Grade ungraded submissions.',
                   8522:                                 url => $url1b,
                   8523:                                 permission => 'F',
                   8524:                                 icon => 'edit-find-replace.png',
                   8525:                                 linktitle => 'Grade all submissions that have not been graded yet.'
1.538     schulted 8526:                         },
1.598     www      8527: 
                   8528:                         {       linktext => 'Grading table',
                   8529:                                 url => $url1c,
                   8530:                                 permission => 'F',
                   8531:                                 icon => 'edit-find-replace.png',
                   8532:                                 linktitle => 'Grade current resource for all students.'
                   8533:                         },
1.600     www      8534:                         {       linktext => 'Grade complete page/sequence/folder for one student',
1.598     www      8535:                                 url => $url1d,
                   8536:                                 permission => 'F',
                   8537:                                 icon => 'edit-find-replace.png',
                   8538:                                 linktitle => 'Grade all resources in current page/sequence/folder for one student.'
                   8539:                         }]},
                   8540:                          { categorytitle=>'Automated Grading',
                   8541:                items =>[
                   8542: 
1.538     schulted 8543:                 	    {	linktext => 'Upload Scores',
                   8544:                     		url => $url2,
                   8545:                     		permission => 'F',
                   8546:                     		icon => 'uploadscores.png',
                   8547:                     		linktitle => 'Specify a file containing the class scores for current resource.'
                   8548:                 	    },
                   8549:                 	    {	linktext => 'Process Clicker',
                   8550:                     		url => $url3,
                   8551:                     		permission => 'F',
                   8552:                     		icon => 'addClickerInfoFile.png',
                   8553:                     		linktitle => 'Specify a file containing the clicker information for this resource.'
                   8554:                 	    },
1.587     raeburn  8555:                 	    {	linktext => 'Grade/Manage/Review Bubblesheets',
1.538     schulted 8556:                     		url => $url4,
                   8557:                     		permission => 'F',
                   8558:                     		icon => 'stat.png',
                   8559:                     		linktitle => 'Grade scantron exams, upload/download scantron data files, and review previously graded scantron exams.'
1.602   ! www      8560:                 	    },
        !          8561:                             {   linktext => 'Verify Receipt No.',
        !          8562:                                 url => $url5,
        !          8563:                                 permission => 'F',
        !          8564:                                 icon => 'edit-find-replace.png',
        !          8565:                                 linktitle => 'Verify a system-generated receipt number for correct problem solution.'
        !          8566:                             }
        !          8567: 
1.538     schulted 8568:                     ]
                   8569:             });
                   8570: 
1.443     banghart 8571:     # Create the menu
                   8572:     my $Str;
1.445     banghart 8573:     $Str .= '<form method="post" action="" name="gradingMenu">';
                   8574:     $Str .= '<input type="hidden" name="command" value="" />'.
                   8575:     	'<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.476     albertel 8576: 	'<input type="hidden" name="probTitle"   value="'.$probTitle.'" />'."\n".
1.445     banghart 8577: 	'<input type="hidden" name="gradingMenu" value="1" />'."\n".
                   8578: 	'<input type="hidden" name="showgrading" value="yes" />'."\n";
                   8579: 
1.602   ! www      8580:     $Str .= &Apache::lonhtmlcommon::generate_menu(@menu);
1.443     banghart 8581:     return $Str;    
                   8582: }
                   8583: 
1.598     www      8584: 
                   8585: sub ungraded {
                   8586:     my ($request)=@_;
                   8587:     &submit_options($request);
                   8588: }
                   8589: 
1.599     www      8590: sub submit_options_sequence {
                   8591:     my ($request) = @_;
                   8592:     my ($symb)=&get_symb($request);
                   8593:     if (!$symb) {return '';}
1.600     www      8594:     &commonJSfunctions($request);
                   8595:     my $result;
1.599     www      8596: 
1.600     www      8597:     $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
                   8598:         '<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
                   8599:         '<input type="hidden" name="gradingMenu" value="1" />'."\n".
                   8600:         '<input type="hidden" name="showgrading" value="yes" />'."\n";
                   8601: 
                   8602:     $result.='
                   8603: <h2>
                   8604:   '.&mt('Grade complete page/sequence/folder for one student').'
1.601     www      8605: </h2>'.
                   8606:             &selectfield(0).
                   8607:             '<input type="hidden" name="command" value="pickStudentPage" />
1.600     www      8608:             <div>
                   8609:               <input type="submit" value="'.&mt('Next').' &rarr;" />
                   8610:             </div>
                   8611:         </div>
                   8612:   </form>';
                   8613:     $result .= &show_grading_menu_form($symb);
                   8614:     return $result;
                   8615: }
                   8616: 
                   8617: sub submit_options_table {
                   8618:     my ($request) = @_;
                   8619:     my ($symb)=&get_symb($request);
                   8620:     if (!$symb) {return '';}
1.599     www      8621:     &commonJSfunctions($request);
                   8622:     my $result;
                   8623: 
                   8624:     $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
                   8625:         '<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
                   8626:         '<input type="hidden" name="gradingMenu" value="1" />'."\n".
                   8627:         '<input type="hidden" name="showgrading" value="yes" />'."\n";
                   8628: 
                   8629:     $result.='
                   8630: <h2>
1.600     www      8631:   '.&mt('Grading table').'
1.601     www      8632: </h2>'.
                   8633:             &selectfield(0).
                   8634:             '<input type="hidden" name="command" value="viewgrades" />
1.599     www      8635:             <div>
                   8636:               <input type="submit" value="'.&mt('Next').' &rarr;" />
                   8637:             </div>
                   8638:         </div>
                   8639:   </form>';
                   8640:     $result .= &show_grading_menu_form($symb);
                   8641:     return $result;
                   8642: }
1.443     banghart 8643: 
1.600     www      8644: 
                   8645: 
1.443     banghart 8646: #--- Displays the submissions first page -------
                   8647: sub submit_options {
1.72      ng       8648:     my ($request) = @_;
1.324     albertel 8649:     my ($symb)=&get_symb($request);
1.72      ng       8650:     if (!$symb) {return '';}
1.76      ng       8651:     my $probTitle = &Apache::lonnet::gettitle($symb);
1.72      ng       8652: 
1.118     ng       8653:     &commonJSfunctions($request);
1.473     albertel 8654:     my $result;
1.533     bisitz   8655: 
1.72      ng       8656:     $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
1.418     albertel 8657: 	'<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.72      ng       8658: 	'<input type="hidden" name="probTitle"   value="'.$probTitle.'" />'."\n".
1.124     ng       8659: 	'<input type="hidden" name="gradingMenu" value="1" />'."\n".
1.72      ng       8660: 	'<input type="hidden" name="showgrading" value="yes" />'."\n";
                   8661: 
1.472     albertel 8662:     $result.='
1.533     bisitz   8663: <h2>
1.600     www      8664:   '.&mt('Select individual students to grade').'
1.601     www      8665: </h2>'.&selectfield(1).'
                   8666:                 <input type="hidden" name="command" value="submission" /> 
                   8667: 	      <input type="submit" value="'.&mt('Next').' &rarr;" />
                   8668:             </div>
                   8669:           </div>
                   8670: 
                   8671: 
                   8672:   </form>';
                   8673:     $result .= &show_grading_menu_form($symb);
                   8674:     return $result;
                   8675: }
1.533     bisitz   8676: 
1.601     www      8677: sub selectfield {
                   8678:    my ($full)=@_;
                   8679:    my $result='<div class="LC_columnSection">
1.537     harmsja  8680:   
1.533     bisitz   8681:     <fieldset>
                   8682:       <legend>
                   8683:        '.&mt('Sections').'
                   8684:       </legend>
1.601     www      8685:       '.&Apache::lonstatistics::SectionSelect('section','multiple',5).'
1.533     bisitz   8686:     </fieldset>
1.537     harmsja  8687:   
1.533     bisitz   8688:     <fieldset>
                   8689:       <legend>
                   8690:         '.&mt('Groups').'
                   8691:       </legend>
                   8692:       '.&Apache::lonstatistics::GroupSelect('group','multiple',5).'
                   8693:     </fieldset>
1.537     harmsja  8694:   
1.533     bisitz   8695:     <fieldset>
                   8696:       <legend>
                   8697:         '.&mt('Access Status').'
                   8698:       </legend>
1.601     www      8699:       '.&Apache::lonhtmlcommon::StatusOptions(undef,undef,5,undef,'mult').'
                   8700:     </fieldset>';
                   8701:     if ($full) {
                   8702:        $result.='
1.533     bisitz   8703:     <fieldset>
                   8704:       <legend>
                   8705:         '.&mt('Submission Status').'
1.601     www      8706:       </legend>'.
                   8707:        &Apache::loncommon::select_form('all','submitonly',
                   8708:           (&Apache::lonlocal::texthash(
                   8709:              'yes'       => 'with submissions',
                   8710:              'queued'    => 'in grading queue',
                   8711:              'graded'    => 'with ungraded submissions',
                   8712:              'incorrect' => 'with incorrect submissions',
                   8713:              'all'       => 'with any status'),
                   8714:              'select_form_order' => ['yes','queued','graded','incorrect','all'])).
                   8715:    '</fieldset>';
                   8716:     }
                   8717:     $result.='</div><br />';
1.44      ng       8718:     return $result;
1.2       albertel 8719: }
                   8720: 
1.285     albertel 8721: sub reset_perm {
                   8722:     undef(%perm);
                   8723: }
                   8724: 
                   8725: sub init_perm {
                   8726:     &reset_perm();
1.300     albertel 8727:     foreach my $test_perm ('vgr','mgr','opa') {
                   8728: 
                   8729: 	my $scope = $env{'request.course.id'};
                   8730: 	if (!($perm{$test_perm}=&Apache::lonnet::allowed($test_perm,$scope))) {
                   8731: 
                   8732: 	    $scope .= '/'.$env{'request.course.sec'};
                   8733: 	    if ( $perm{$test_perm}=
                   8734: 		 &Apache::lonnet::allowed($test_perm,$scope)) {
                   8735: 		$perm{$test_perm.'_section'}=$env{'request.course.sec'};
                   8736: 	    } else {
                   8737: 		delete($perm{$test_perm});
                   8738: 	    }
1.285     albertel 8739: 	}
                   8740:     }
                   8741: }
                   8742: 
1.400     www      8743: sub gather_clicker_ids {
1.408     albertel 8744:     my %clicker_ids;
1.400     www      8745: 
                   8746:     my $classlist = &Apache::loncoursedata::get_classlist();
                   8747: 
                   8748:     # Set up a couple variables.
1.407     albertel 8749:     my $username_idx = &Apache::loncoursedata::CL_SNAME();
                   8750:     my $domain_idx   = &Apache::loncoursedata::CL_SDOM();
1.438     www      8751:     my $status_idx   = &Apache::loncoursedata::CL_STATUS();
1.400     www      8752: 
1.407     albertel 8753:     foreach my $student (keys(%$classlist)) {
1.438     www      8754:         if ($classlist->{$student}->[$status_idx] ne 'Active') { next; }
1.407     albertel 8755:         my $username = $classlist->{$student}->[$username_idx];
                   8756:         my $domain   = $classlist->{$student}->[$domain_idx];
1.400     www      8757:         my $clickers =
1.408     albertel 8758: 	    (&Apache::lonnet::userenvironment($domain,$username,'clickers'))[1];
1.400     www      8759:         foreach my $id (split(/\,/,$clickers)) {
1.414     www      8760:             $id=~s/^[\#0]+//;
1.421     www      8761:             $id=~s/[\-\:]//g;
1.407     albertel 8762:             if (exists($clicker_ids{$id})) {
1.408     albertel 8763: 		$clicker_ids{$id}.=','.$username.':'.$domain;
1.400     www      8764:             } else {
1.408     albertel 8765: 		$clicker_ids{$id}=$username.':'.$domain;
1.400     www      8766:             }
                   8767:         }
                   8768:     }
1.407     albertel 8769:     return %clicker_ids;
1.400     www      8770: }
                   8771: 
1.402     www      8772: sub gather_adv_clicker_ids {
1.408     albertel 8773:     my %clicker_ids;
1.402     www      8774:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
                   8775:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   8776:     my %coursepersonnel=&Apache::lonnet::get_course_adv_roles($cdom.'/'.$cnum);
1.409     albertel 8777:     foreach my $element (sort(keys(%coursepersonnel))) {
1.402     www      8778:         foreach my $person (split(/\,/,$coursepersonnel{$element})) {
                   8779:             my ($puname,$pudom)=split(/\:/,$person);
                   8780:             my $clickers =
1.408     albertel 8781: 		(&Apache::lonnet::userenvironment($pudom,$puname,'clickers'))[1];
1.405     www      8782:             foreach my $id (split(/\,/,$clickers)) {
1.414     www      8783: 		$id=~s/^[\#0]+//;
1.421     www      8784:                 $id=~s/[\-\:]//g;
1.408     albertel 8785: 		if (exists($clicker_ids{$id})) {
                   8786: 		    $clicker_ids{$id}.=','.$puname.':'.$pudom;
                   8787: 		} else {
                   8788: 		    $clicker_ids{$id}=$puname.':'.$pudom;
                   8789: 		}
1.405     www      8790:             }
1.402     www      8791:         }
                   8792:     }
1.407     albertel 8793:     return %clicker_ids;
1.402     www      8794: }
                   8795: 
1.413     www      8796: sub clicker_grading_parameters {
                   8797:     return ('gradingmechanism' => 'scalar',
                   8798:             'upfiletype' => 'scalar',
                   8799:             'specificid' => 'scalar',
                   8800:             'pcorrect' => 'scalar',
                   8801:             'pincorrect' => 'scalar');
                   8802: }
                   8803: 
1.400     www      8804: sub process_clicker {
                   8805:     my ($r)=@_;
                   8806:     my ($symb)=&get_symb($r);
                   8807:     if (!$symb) {return '';}
                   8808:     my $result=&checkforfile_js();
                   8809:     $env{'form.probTitle'} = &Apache::lonnet::gettitle($symb);
                   8810:     $result.='<br /><table width="100%" border="0"><tr><td bgcolor="#777777">'."\n";
                   8811:     $result.='<table width="100%" border="0"><tr bgcolor="#e6ffff"><td>'."\n";
1.538     schulted 8812:     $result.='&nbsp;<b>'.&mt('Specify a file containing the clicker information for this resource.').
                   8813:         '</b></td></tr>'."\n";
1.601     www      8814:     $result.='<tr bgcolor="#ffffe6"><td>'."\n";
1.413     www      8815: # Attempt to restore parameters from last session, set defaults if not present
                   8816:     my %Saveable_Parameters=&clicker_grading_parameters();
                   8817:     &Apache::loncommon::restore_course_settings('grades_clicker',
                   8818:                                                  \%Saveable_Parameters);
                   8819:     if (!$env{'form.pcorrect'}) { $env{'form.pcorrect'}=100; }
                   8820:     if (!$env{'form.pincorrect'}) { $env{'form.pincorrect'}=100; }
                   8821:     if (!$env{'form.gradingmechanism'}) { $env{'form.gradingmechanism'}='attendance'; }
                   8822:     if (!$env{'form.upfiletype'}) { $env{'form.upfiletype'}='iclicker'; }
                   8823: 
                   8824:     my %checked;
1.521     www      8825:     foreach my $gradingmechanism ('attendance','personnel','specific','given') {
1.413     www      8826:        if ($env{'form.gradingmechanism'} eq $gradingmechanism) {
1.569     bisitz   8827:           $checked{$gradingmechanism}=' checked="checked"';
1.413     www      8828:        }
                   8829:     }
                   8830: 
1.400     www      8831:     my $upload=&mt("Upload File");
                   8832:     my $type=&mt("Type");
1.402     www      8833:     my $attendance=&mt("Award points just for participation");
                   8834:     my $personnel=&mt("Correctness determined from response by course personnel");
1.414     www      8835:     my $specific=&mt("Correctness determined from response with clicker ID(s)"); 
1.521     www      8836:     my $given=&mt("Correctness determined from given list of answers").' '.
                   8837:               '<font size="-2"><tt>('.&mt("Provide comma-separated list. Use '*' for any answer correct, '-' for skip").')</tt></font>';
1.402     www      8838:     my $pcorrect=&mt("Percentage points for correct solution");
                   8839:     my $pincorrect=&mt("Percentage points for incorrect solution");
1.413     www      8840:     my $selectform=&Apache::loncommon::select_form($env{'form.upfiletype'},'upfiletype',
1.419     www      8841: 						   ('iclicker' => 'i>clicker',
                   8842:                                                     'interwrite' => 'interwrite PRS'));
1.418     albertel 8843:     $symb = &Apache::lonenc::check_encrypt($symb);
1.597     wenzelju 8844:     $result.= &Apache::lonhtmlcommon::scripttag(<<ENDUPFORM);
1.402     www      8845: function sanitycheck() {
                   8846: // Accept only integer percentages
                   8847:    document.forms.gradesupload.pcorrect.value=Math.round(document.forms.gradesupload.pcorrect.value);
                   8848:    document.forms.gradesupload.pincorrect.value=Math.round(document.forms.gradesupload.pincorrect.value);
                   8849: // Find out grading choice
                   8850:    for (i=0; i<document.forms.gradesupload.gradingmechanism.length; i++) {
                   8851:       if (document.forms.gradesupload.gradingmechanism[i].checked) {
                   8852:          gradingchoice=document.forms.gradesupload.gradingmechanism[i].value;
                   8853:       }
                   8854:    }
                   8855: // By default, new choice equals user selection
                   8856:    newgradingchoice=gradingchoice;
                   8857: // Not good to give more points for false answers than correct ones
                   8858:    if (Math.round(document.forms.gradesupload.pcorrect.value)<Math.round(document.forms.gradesupload.pincorrect.value)) {
                   8859:       document.forms.gradesupload.pcorrect.value=document.forms.gradesupload.pincorrect.value;
                   8860:    }
                   8861: // If new choice is attendance only, and old choice was correctness-based, restore defaults
                   8862:    if ((gradingchoice=='attendance') && (document.forms.gradesupload.waschecked.value!='attendance')) {
                   8863:       document.forms.gradesupload.pcorrect.value=100;
                   8864:       document.forms.gradesupload.pincorrect.value=100;
                   8865:    }
                   8866: // If the values are different, cannot be attendance only
                   8867:    if ((Math.round(document.forms.gradesupload.pcorrect.value)!=Math.round(document.forms.gradesupload.pincorrect.value)) &&
                   8868:        (gradingchoice=='attendance')) {
                   8869:        newgradingchoice='personnel';
                   8870:    }
                   8871: // Change grading choice to new one
                   8872:    for (i=0; i<document.forms.gradesupload.gradingmechanism.length; i++) {
                   8873:       if (document.forms.gradesupload.gradingmechanism[i].value==newgradingchoice) {
                   8874:          document.forms.gradesupload.gradingmechanism[i].checked=true;
                   8875:       } else {
                   8876:          document.forms.gradesupload.gradingmechanism[i].checked=false;
                   8877:       }
                   8878:    }
                   8879: // Remember the old state
                   8880:    document.forms.gradesupload.waschecked.value=newgradingchoice;
                   8881: }
1.597     wenzelju 8882: ENDUPFORM
                   8883:     $result.= <<ENDUPFORM;
1.400     www      8884: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
                   8885: <input type="hidden" name="symb" value="$symb" />
                   8886: <input type="hidden" name="command" value="processclickerfile" />
                   8887: <input type="hidden" name="probTitle" value="$env{'form.probTitle'}" />
                   8888: <input type="hidden" name="saveState"  value="$env{'form.saveState'}" />
                   8889: <input type="file" name="upfile" size="50" />
                   8890: <br /><label>$type: $selectform</label>
1.589     bisitz   8891: <br /><label><input type="radio" name="gradingmechanism" value="attendance"$checked{'attendance'} onclick="sanitycheck()" />$attendance </label>
                   8892: <br /><label><input type="radio" name="gradingmechanism" value="personnel"$checked{'personnel'} onclick="sanitycheck()" />$personnel</label>
                   8893: <br /><label><input type="radio" name="gradingmechanism" value="specific"$checked{'specific'} onclick="sanitycheck()" />$specific </label>
1.414     www      8894: <input type="text" name="specificid" value="$env{'form.specificid'}" size="20" />
1.589     bisitz   8895: <br /><label><input type="radio" name="gradingmechanism" value="given"$checked{'given'} onclick="sanitycheck()" />$given </label>
1.521     www      8896: <br />&nbsp;&nbsp;&nbsp;
                   8897: <input type="text" name="givenanswer" size="50" />
1.413     www      8898: <input type="hidden" name="waschecked" value="$env{'form.gradingmechanism'}" />
1.589     bisitz   8899: <br /><label>$pcorrect: <input type="text" name="pcorrect" size="4" value="$env{'form.pcorrect'}" onchange="sanitycheck()" /></label>
                   8900: <br /><label>$pincorrect: <input type="text" name="pincorrect" size="4" value="$env{'form.pincorrect'}" onchange="sanitycheck()" /></label>
                   8901: <br /><input type="button" onclick="javascript:checkUpload(this.form);" value="$upload" />
1.597     wenzelju 8902: </form>'
1.400     www      8903: ENDUPFORM
                   8904:     $result.='</td></tr></table>'."\n".
                   8905:              '</td></tr></table><br /><br />'."\n";
                   8906:     $result.=&show_grading_menu_form($symb);
                   8907:     return $result;
                   8908: }
                   8909: 
                   8910: sub process_clicker_file {
                   8911:     my ($r)=@_;
                   8912:     my ($symb)=&get_symb($r);
                   8913:     if (!$symb) {return '';}
1.413     www      8914: 
                   8915:     my %Saveable_Parameters=&clicker_grading_parameters();
                   8916:     &Apache::loncommon::store_course_settings('grades_clicker',
                   8917:                                               \%Saveable_Parameters);
1.598     www      8918:     my $result='';
                   8919: #    my ($result) = &showResourceInfo($symb,$env{'form.probTitle'});
1.404     www      8920:     if (($env{'form.gradingmechanism'} eq 'specific') && ($env{'form.specificid'}!~/\w/)) {
1.408     albertel 8921: 	$result.='<span class="LC_error">'.&mt('You need to specify a clicker ID for the correct answer').'</span>';
                   8922: 	return $result.&show_grading_menu_form($symb);
1.404     www      8923:     }
1.522     www      8924:     if (($env{'form.gradingmechanism'} eq 'given') && ($env{'form.givenanswer'}!~/\S/)) {
1.521     www      8925:         $result.='<span class="LC_error">'.&mt('You need to specify the correct answer').'</span>';
                   8926:         return $result.&show_grading_menu_form($symb);
                   8927:     }
1.522     www      8928:     my $foundgiven=0;
1.521     www      8929:     if ($env{'form.gradingmechanism'} eq 'given') {
                   8930:         $env{'form.givenanswer'}=~s/^\s*//gs;
                   8931:         $env{'form.givenanswer'}=~s/\s*$//gs;
                   8932:         $env{'form.givenanswer'}=~s/[^a-zA-Z0-9\.\*\-]+/\,/g;
                   8933:         $env{'form.givenanswer'}=uc($env{'form.givenanswer'});
1.522     www      8934:         my @answers=split(/\,/,$env{'form.givenanswer'});
                   8935:         $foundgiven=$#answers+1;
1.521     www      8936:     }
1.407     albertel 8937:     my %clicker_ids=&gather_clicker_ids();
1.408     albertel 8938:     my %correct_ids;
1.404     www      8939:     if ($env{'form.gradingmechanism'} eq 'personnel') {
1.408     albertel 8940: 	%correct_ids=&gather_adv_clicker_ids();
1.404     www      8941:     }
                   8942:     if ($env{'form.gradingmechanism'} eq 'specific') {
1.414     www      8943: 	foreach my $correct_id (split(/[\s\,]/,$env{'form.specificid'})) {;
                   8944: 	   $correct_id=~tr/a-z/A-Z/;
                   8945: 	   $correct_id=~s/\s//gs;
                   8946: 	   $correct_id=~s/^[\#0]+//;
1.421     www      8947:            $correct_id=~s/[\-\:]//g;
1.414     www      8948:            if ($correct_id) {
                   8949: 	      $correct_ids{$correct_id}='specified';
                   8950:            }
                   8951:         }
1.400     www      8952:     }
1.404     www      8953:     if ($env{'form.gradingmechanism'} eq 'attendance') {
1.408     albertel 8954: 	$result.=&mt('Score based on attendance only');
1.521     www      8955:     } elsif ($env{'form.gradingmechanism'} eq 'given') {
1.522     www      8956:         $result.=&mt('Score based on [_1] ([_2] answers)','<tt>'.$env{'form.givenanswer'}.'</tt>',$foundgiven);
1.404     www      8957:     } else {
1.408     albertel 8958: 	my $number=0;
1.411     www      8959: 	$result.='<p><b>'.&mt('Correctness determined by the following IDs').'</b>';
1.408     albertel 8960: 	foreach my $id (sort(keys(%correct_ids))) {
1.411     www      8961: 	    $result.='<br /><tt>'.$id.'</tt> - ';
1.408     albertel 8962: 	    if ($correct_ids{$id} eq 'specified') {
                   8963: 		$result.=&mt('specified');
                   8964: 	    } else {
                   8965: 		my ($uname,$udom)=split(/\:/,$correct_ids{$id});
                   8966: 		$result.=&Apache::loncommon::plainname($uname,$udom);
                   8967: 	    }
                   8968: 	    $number++;
                   8969: 	}
1.411     www      8970:         $result.="</p>\n";
1.408     albertel 8971: 	if ($number==0) {
                   8972: 	    $result.='<span class="LC_error">'.&mt('No IDs found to determine correct answer').'</span>';
                   8973: 	    return $result.&show_grading_menu_form($symb);
                   8974: 	}
1.404     www      8975:     }
1.405     www      8976:     if (length($env{'form.upfile'}) < 2) {
1.407     albertel 8977:         $result.=&mt('[_1] Error: [_2] The file you attempted to upload, [_3] contained no information. Please check that you entered the correct filename.',
                   8978: 		     '<span class="LC_error">',
                   8979: 		     '</span>',
                   8980: 		     '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>');
1.405     www      8981:         return $result.&show_grading_menu_form($symb);
                   8982:     }
1.410     www      8983: 
                   8984: # Were able to get all the info needed, now analyze the file
                   8985: 
1.411     www      8986:     $result.=&Apache::loncommon::studentbrowser_javascript();
1.418     albertel 8987:     $symb = &Apache::lonenc::check_encrypt($symb);
1.410     www      8988:     my $heading=&mt('Scanning clicker file');
                   8989:     $result.=(<<ENDHEADER);
                   8990: <br /><table width="100%" border="0"><tr><td bgcolor="#777777">
                   8991: <table width="100%" border="0"><tr bgcolor="#e6ffff"><td>
                   8992: <b>$heading</b></td></tr><tr bgcolor=#ffffe6><td>
                   8993: <form method="post" action="/adm/grades" name="clickeranalysis">
                   8994: <input type="hidden" name="symb" value="$symb" />
                   8995: <input type="hidden" name="command" value="assignclickergrades" />
                   8996: <input type="hidden" name="probTitle" value="$env{'form.probTitle'}" />
                   8997: <input type="hidden" name="saveState"  value="$env{'form.saveState'}" />
1.411     www      8998: <input type="hidden" name="gradingmechanism" value="$env{'form.gradingmechanism'}" />
                   8999: <input type="hidden" name="pcorrect" value="$env{'form.pcorrect'}" />
                   9000: <input type="hidden" name="pincorrect" value="$env{'form.pincorrect'}" />
1.410     www      9001: ENDHEADER
1.522     www      9002:     if ($env{'form.gradingmechanism'} eq 'given') {
                   9003:        $result.='<input type="hidden" name="correct:given" value="'.$env{'form.givenanswer'}.'" />';
                   9004:     } 
1.408     albertel 9005:     my %responses;
                   9006:     my @questiontitles;
1.405     www      9007:     my $errormsg='';
                   9008:     my $number=0;
                   9009:     if ($env{'form.upfiletype'} eq 'iclicker') {
1.408     albertel 9010: 	($errormsg,$number)=&iclicker_eval(\@questiontitles,\%responses);
1.406     www      9011:     }
1.419     www      9012:     if ($env{'form.upfiletype'} eq 'interwrite') {
                   9013:         ($errormsg,$number)=&interwrite_eval(\@questiontitles,\%responses);
                   9014:     }
1.411     www      9015:     $result.='<br />'.&mt('Found [_1] question(s)',$number).'<br />'.
                   9016:              '<input type="hidden" name="number" value="'.$number.'" />'.
                   9017:              &mt('Awarding [_1] percent for correct and [_2] percent for incorrect responses',
                   9018:                  $env{'form.pcorrect'},$env{'form.pincorrect'}).
                   9019:              '<br />';
1.522     www      9020:     if (($env{'form.gradingmechanism'} eq 'given') && ($number!=$foundgiven)) {
                   9021:        $result.='<span class="LC_error">'.&mt('Number of given answers does not agree with number of questions in file.').'</span>';
                   9022:        return $result.&show_grading_menu_form($symb);
                   9023:     } 
1.414     www      9024: # Remember Question Titles
                   9025: # FIXME: Possibly need delimiter other than ":"
                   9026:     for (my $i=0;$i<$number;$i++) {
                   9027:         $result.='<input type="hidden" name="question:'.$i.'" value="'.
                   9028:                  &HTML::Entities::encode($questiontitles[$i],'"&<>').'" />';
                   9029:     }
1.411     www      9030:     my $correct_count=0;
                   9031:     my $student_count=0;
                   9032:     my $unknown_count=0;
1.414     www      9033: # Match answers with usernames
                   9034: # FIXME: Possibly need delimiter other than ":"
1.409     albertel 9035:     foreach my $id (keys(%responses)) {
1.410     www      9036:        if ($correct_ids{$id}) {
1.414     www      9037:           $result.="\n".'<input type="hidden" name="correct:'.$correct_count.':'.$correct_ids{$id}.'" value="'.$responses{$id}.'" />';
1.411     www      9038:           $correct_count++;
1.410     www      9039:        } elsif ($clicker_ids{$id}) {
1.437     www      9040:           if ($clicker_ids{$id}=~/\,/) {
                   9041: # More than one user with the same clicker!
                   9042:              $result.="\n<hr />".&mt('Clicker registered more than once').": <tt>".$id."</tt><br />";
                   9043:              $result.="\n".'<input type="hidden" name="unknown:'.$id.'" value="'.$responses{$id}.'" />'.
                   9044:                            "<select name='multi".$id."'>";
                   9045:              foreach my $reguser (sort(split(/\,/,$clicker_ids{$id}))) {
                   9046:                  $result.="<option value='".$reguser."'>".&Apache::loncommon::plainname(split(/\:/,$reguser)).' ('.$reguser.')</option>';
                   9047:              }
                   9048:              $result.='</select>';
                   9049:              $unknown_count++;
                   9050:           } else {
                   9051: # Good: found one and only one user with the right clicker
                   9052:              $result.="\n".'<input type="hidden" name="student:'.$clicker_ids{$id}.'" value="'.$responses{$id}.'" />';
                   9053:              $student_count++;
                   9054:           }
1.410     www      9055:        } else {
1.411     www      9056:           $result.="\n<hr />".&mt('Unregistered Clicker')." <tt>".$id."</tt><br />";
                   9057:           $result.="\n".'<input type="hidden" name="unknown:'.$id.'" value="'.$responses{$id}.'" />'.
                   9058:                    "\n".&mt("Username").": <input type='text' name='uname".$id."' />&nbsp;".
                   9059:                    "\n".&mt("Domain").": ".
                   9060:                    &Apache::loncommon::select_dom_form($env{'course.'.$env{'request.course.id'}.'.domain'},'udom'.$id).'&nbsp;'.
                   9061:                    &Apache::loncommon::selectstudent_link('clickeranalysis','uname'.$id,'udom'.$id);
                   9062:           $unknown_count++;
1.410     www      9063:        }
1.405     www      9064:     }
1.412     www      9065:     $result.='<hr />'.
                   9066:              &mt('Found [_1] registered and [_2] unregistered clickers.',$student_count,$unknown_count);
1.521     www      9067:     if (($env{'form.gradingmechanism'} ne 'attendance') && ($env{'form.gradingmechanism'} ne 'given')) {
1.412     www      9068:        if ($correct_count==0) {
                   9069:           $errormsg.="Found no correct answers answers for grading!";
                   9070:        } elsif ($correct_count>1) {
1.414     www      9071:           $result.='<br /><span class="LC_warning">'.&mt("Found [_1] entries for grading!",$correct_count).'</span>';
1.412     www      9072:        }
                   9073:     }
1.428     www      9074:     if ($number<1) {
                   9075:        $errormsg.="Found no questions.";
                   9076:     }
1.412     www      9077:     if ($errormsg) {
                   9078:        $result.='<br /><span class="LC_error">'.&mt($errormsg).'</span>';
                   9079:     } else {
                   9080:        $result.='<br /><input type="submit" name="finalize" value="'.&mt('Finalize Grading').'" />';
                   9081:     }
                   9082:     $result.='</form></td></tr></table>'."\n".
1.410     www      9083:              '</td></tr></table><br /><br />'."\n";
1.404     www      9084:     return $result.&show_grading_menu_form($symb);
1.400     www      9085: }
                   9086: 
1.405     www      9087: sub iclicker_eval {
1.406     www      9088:     my ($questiontitles,$responses)=@_;
1.405     www      9089:     my $number=0;
                   9090:     my $errormsg='';
                   9091:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
1.410     www      9092:         my %components=&Apache::loncommon::record_sep($line);
                   9093:         my @entries=map {$components{$_}} (sort(keys(%components)));
1.408     albertel 9094: 	if ($entries[0] eq 'Question') {
                   9095: 	    for (my $i=3;$i<$#entries;$i+=6) {
                   9096: 		$$questiontitles[$number]=$entries[$i];
                   9097: 		$number++;
                   9098: 	    }
                   9099: 	}
                   9100: 	if ($entries[0]=~/^\#/) {
                   9101: 	    my $id=$entries[0];
                   9102: 	    my @idresponses;
                   9103: 	    $id=~s/^[\#0]+//;
                   9104: 	    for (my $i=0;$i<$number;$i++) {
                   9105: 		my $idx=3+$i*6;
                   9106: 		push(@idresponses,$entries[$idx]);
                   9107: 	    }
                   9108: 	    $$responses{$id}=join(',',@idresponses);
                   9109: 	}
1.405     www      9110:     }
                   9111:     return ($errormsg,$number);
                   9112: }
                   9113: 
1.419     www      9114: sub interwrite_eval {
                   9115:     my ($questiontitles,$responses)=@_;
                   9116:     my $number=0;
                   9117:     my $errormsg='';
1.420     www      9118:     my $skipline=1;
                   9119:     my $questionnumber=0;
                   9120:     my %idresponses=();
1.419     www      9121:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
                   9122:         my %components=&Apache::loncommon::record_sep($line);
                   9123:         my @entries=map {$components{$_}} (sort(keys(%components)));
1.420     www      9124:         if ($entries[1] eq 'Time') { $skipline=0; next; }
                   9125:         if ($entries[1] eq 'Response') { $skipline=1; }
                   9126:         next if $skipline;
                   9127:         if ($entries[0]!=$questionnumber) {
                   9128:            $questionnumber=$entries[0];
                   9129:            $$questiontitles[$number]=&mt('Question [_1]',$questionnumber);
                   9130:            $number++;
1.419     www      9131:         }
1.420     www      9132:         my $id=$entries[4];
                   9133:         $id=~s/^[\#0]+//;
1.421     www      9134:         $id=~s/^v\d*\://i;
                   9135:         $id=~s/[\-\:]//g;
1.420     www      9136:         $idresponses{$id}[$number]=$entries[6];
                   9137:     }
1.524     raeburn  9138:     foreach my $id (keys(%idresponses)) {
1.420     www      9139:        $$responses{$id}=join(',',@{$idresponses{$id}});
                   9140:        $$responses{$id}=~s/^\s*\,//;
1.419     www      9141:     }
                   9142:     return ($errormsg,$number);
                   9143: }
                   9144: 
1.414     www      9145: sub assign_clicker_grades {
                   9146:     my ($r)=@_;
                   9147:     my ($symb)=&get_symb($r);
                   9148:     if (!$symb) {return '';}
1.416     www      9149: # See which part we are saving to
1.582     raeburn  9150:     my $res_error;
                   9151:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
                   9152:     if ($res_error) {
                   9153:         return &navmap_errormsg();
                   9154:     }
1.416     www      9155: # FIXME: This should probably look for the first handgradeable part
                   9156:     my $part=$$partlist[0];
                   9157: # Start screen output
1.598     www      9158:     my $result='';
                   9159: #    my ($result) = &showResourceInfo($symb,$env{'form.probTitle'});
1.416     www      9160: 
1.414     www      9161:     my $heading=&mt('Assigning grades based on clicker file');
                   9162:     $result.=(<<ENDHEADER);
                   9163: <br /><table width="100%" border="0"><tr><td bgcolor="#777777">
                   9164: <table width="100%" border="0"><tr bgcolor="#e6ffff"><td>
                   9165: <b>$heading</b></td></tr><tr bgcolor=#ffffe6><td>
                   9166: ENDHEADER
                   9167: # Get correct result
                   9168: # FIXME: Possibly need delimiter other than ":"
                   9169:     my @correct=();
1.415     www      9170:     my $gradingmechanism=$env{'form.gradingmechanism'};
                   9171:     my $number=$env{'form.number'};
                   9172:     if ($gradingmechanism ne 'attendance') {
1.414     www      9173:        foreach my $key (keys(%env)) {
                   9174:           if ($key=~/^form\.correct\:/) {
                   9175:              my @input=split(/\,/,$env{$key});
                   9176:              for (my $i=0;$i<=$#input;$i++) {
                   9177:                  if (($correct[$i]) && ($input[$i]) &&
                   9178:                      ($correct[$i] ne $input[$i])) {
                   9179:                     $result.='<br /><span class="LC_warning">'.
                   9180:                              &mt('More than one correct result given for question "[_1]": [_2] versus [_3].',
                   9181:                                  $env{'form.question:'.$i},$correct[$i],$input[$i]).'</span>';
                   9182:                  } elsif ($input[$i]) {
                   9183:                     $correct[$i]=$input[$i];
                   9184:                  }
                   9185:              }
                   9186:           }
                   9187:        }
1.415     www      9188:        for (my $i=0;$i<$number;$i++) {
1.414     www      9189:           if (!$correct[$i]) {
                   9190:              $result.='<br /><span class="LC_error">'.
                   9191:                       &mt('No correct result given for question "[_1]"!',
                   9192:                           $env{'form.question:'.$i}).'</span>';
                   9193:           }
                   9194:        }
                   9195:        $result.='<br />'.&mt("Correct answer: [_1]",join(', ',map { ($_?$_:'-') } @correct));
                   9196:     }
                   9197: # Start grading
1.415     www      9198:     my $pcorrect=$env{'form.pcorrect'};
                   9199:     my $pincorrect=$env{'form.pincorrect'};
1.416     www      9200:     my $storecount=0;
1.415     www      9201:     foreach my $key (keys(%env)) {
1.420     www      9202:        my $user='';
1.415     www      9203:        if ($key=~/^form\.student\:(.*)$/) {
1.420     www      9204:           $user=$1;
                   9205:        }
                   9206:        if ($key=~/^form\.unknown\:(.*)$/) {
                   9207:           my $id=$1;
                   9208:           if (($env{'form.uname'.$id}) && ($env{'form.udom'.$id})) {
                   9209:              $user=$env{'form.uname'.$id}.':'.$env{'form.udom'.$id};
1.437     www      9210:           } elsif ($env{'form.multi'.$id}) {
                   9211:              $user=$env{'form.multi'.$id};
1.420     www      9212:           }
                   9213:        }
                   9214:        if ($user) { 
1.415     www      9215:           my @answer=split(/\,/,$env{$key});
                   9216:           my $sum=0;
1.522     www      9217:           my $realnumber=$number;
1.415     www      9218:           for (my $i=0;$i<$number;$i++) {
1.576     www      9219:              if  ($correct[$i] eq '-') {
                   9220:                 $realnumber--;
                   9221:              } elsif ($answer[$i]) {
1.415     www      9222:                 if ($gradingmechanism eq 'attendance') {
                   9223:                    $sum+=$pcorrect;
1.576     www      9224:                 } elsif ($correct[$i] eq '*') {
1.522     www      9225:                    $sum+=$pcorrect;
1.415     www      9226:                 } else {
                   9227:                    if ($answer[$i] eq $correct[$i]) {
                   9228:                       $sum+=$pcorrect;
                   9229:                    } else {
                   9230:                       $sum+=$pincorrect;
                   9231:                    }
                   9232:                 }
                   9233:              }
                   9234:           }
1.522     www      9235:           my $ave=$sum/(100*$realnumber);
1.416     www      9236: # Store
                   9237:           my ($username,$domain)=split(/\:/,$user);
                   9238:           my %grades=();
                   9239:           $grades{"resource.$part.solved"}='correct_by_override';
                   9240:           $grades{"resource.$part.awarded"}=$ave;
                   9241:           $grades{"resource.regrader"}="$env{'user.name'}:$env{'user.domain'}";
                   9242:           my $returncode=&Apache::lonnet::cstore(\%grades,$symb,
                   9243:                                                  $env{'request.course.id'},
                   9244:                                                  $domain,$username);
                   9245:           if ($returncode ne 'ok') {
                   9246:              $result.="<br /><span class=\"LC_error\">Failed to save student $username:$domain. Message when trying to save was ($returncode)</span>";
                   9247:           } else {
                   9248:              $storecount++;
                   9249:           }
1.415     www      9250:        }
                   9251:     }
                   9252: # We are done
1.549     hauer    9253:     $result.='<br />'.&mt('Successfully stored grades for [quant,_1,student].',$storecount).
1.416     www      9254:              '</td></tr></table>'."\n".
1.414     www      9255:              '</td></tr></table><br /><br />'."\n";
                   9256:     return $result.&show_grading_menu_form($symb);
                   9257: }
                   9258: 
1.582     raeburn  9259: sub navmap_errormsg {
                   9260:     return '<div class="LC_error">'.
                   9261:            &mt('An error occurred retrieving information about resources in the course.').'<br />'.
1.595     raeburn  9262:            &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  9263:            '</div>';
                   9264: }
                   9265: 
1.1       albertel 9266: sub handler {
1.41      ng       9267:     my $request=$_[0];
1.434     albertel 9268:     &reset_caches();
1.257     albertel 9269:     if ($env{'browser.mathml'}) {
1.141     www      9270: 	&Apache::loncommon::content_type($request,'text/xml');
1.41      ng       9271:     } else {
1.141     www      9272: 	&Apache::loncommon::content_type($request,'text/html');
1.41      ng       9273:     }
                   9274:     $request->send_http_header;
1.44      ng       9275:     return '' if $request->header_only;
1.41      ng       9276:     &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'});
1.324     albertel 9277:     my $symb=&get_symb($request,1);
1.160     albertel 9278:     my @commands=&Apache::loncommon::get_env_multiple('form.command');
                   9279:     my $command=$commands[0];
1.447     foxr     9280: 
1.160     albertel 9281:     if ($#commands > 0) {
                   9282: 	&Apache::lonnet::logthis("grades got multiple commands ".join(':',@commands));
                   9283:     }
1.447     foxr     9284: 
1.513     foxr     9285:     $ssi_error = 0;
1.535     raeburn  9286:     my $brcrum = [{href=>"/adm/grades",text=>"Grading"}];
                   9287:     $request->print(&Apache::loncommon::start_page('Grading',undef,
                   9288:                                           {'bread_crumbs' => $brcrum}));
1.324     albertel 9289:     if ($symb eq '' && $command eq '') {
1.601     www      9290: #
                   9291: # Not called from a resource
                   9292: #    
                   9293: 
1.41      ng       9294:     } else {
1.285     albertel 9295: 	&init_perm();
1.104     albertel 9296: 	if ($command eq 'submission' && $perm{'vgr'}) {
1.257     albertel 9297: 	    ($env{'form.student'} eq '' ? &listStudents($request) : &submission($request,0,0));
1.103     albertel 9298: 	} elsif ($command eq 'pickStudentPage' && $perm{'vgr'}) {
1.68      ng       9299: 	    &pickStudentPage($request);
1.103     albertel 9300: 	} elsif ($command eq 'displayPage' && $perm{'vgr'}) {
1.68      ng       9301: 	    &displayPage($request);
1.104     albertel 9302: 	} elsif ($command eq 'gradeByPage' && $perm{'mgr'}) {
1.71      ng       9303: 	    &updateGradeByPage($request);
1.104     albertel 9304: 	} elsif ($command eq 'processGroup' && $perm{'vgr'}) {
1.41      ng       9305: 	    &processGroup($request);
1.104     albertel 9306: 	} elsif ($command eq 'gradingmenu' && $perm{'vgr'}) {
1.443     banghart 9307: 	    $request->print(&grading_menu($request));
1.598     www      9308: 	} elsif ($command eq 'individual' && $perm{'vgr'}) {
1.600     www      9309: 	    $request->print(&submit_options($request));
1.598     www      9310:         } elsif ($command eq 'ungraded' && $perm{'vgr'}) {
                   9311:             $request->print(&submit_options($request));
                   9312:         } elsif ($command eq 'table' && $perm{'vgr'}) {
1.600     www      9313:             $request->print(&submit_options_table($request));
1.598     www      9314:         } elsif ($command eq 'all_for_one' && $perm{'vgr'}) {
1.599     www      9315:             $request->print(&submit_options_sequence($request));
1.104     albertel 9316: 	} elsif ($command eq 'viewgrades' && $perm{'vgr'}) {
1.41      ng       9317: 	    $request->print(&viewgrades($request));
1.104     albertel 9318: 	} elsif ($command eq 'handgrade' && $perm{'mgr'}) {
1.41      ng       9319: 	    $request->print(&processHandGrade($request));
1.106     albertel 9320: 	} elsif ($command eq 'editgrades' && $perm{'mgr'}) {
1.41      ng       9321: 	    $request->print(&editgrades($request));
1.602   ! www      9322:         } elsif ($command eq 'initialverifyreceipt' && $perm{'vgr'}) {
        !          9323:             $request->print(&initialverifyreceipt($request));
1.106     albertel 9324: 	} elsif ($command eq 'verify' && $perm{'vgr'}) {
1.41      ng       9325: 	    $request->print(&verifyreceipt($request));
1.400     www      9326:         } elsif ($command eq 'processclicker' && $perm{'mgr'}) {
                   9327:             $request->print(&process_clicker($request));
                   9328:         } elsif ($command eq 'processclickerfile' && $perm{'mgr'}) {
                   9329:             $request->print(&process_clicker_file($request));
1.414     www      9330:         } elsif ($command eq 'assignclickergrades' && $perm{'mgr'}) {
                   9331:             $request->print(&assign_clicker_grades($request));
1.106     albertel 9332: 	} elsif ($command eq 'csvform' && $perm{'mgr'}) {
1.72      ng       9333: 	    $request->print(&upcsvScores_form($request));
1.106     albertel 9334: 	} elsif ($command eq 'csvupload' && $perm{'mgr'}) {
1.41      ng       9335: 	    $request->print(&csvupload($request));
1.106     albertel 9336: 	} elsif ($command eq 'csvuploadmap' && $perm{'mgr'} ) {
1.41      ng       9337: 	    $request->print(&csvuploadmap($request));
1.246     albertel 9338: 	} elsif ($command eq 'csvuploadoptions' && $perm{'mgr'}) {
1.257     albertel 9339: 	    if ($env{'form.associate'} ne 'Reverse Association') {
1.246     albertel 9340: 		$request->print(&csvuploadoptions($request));
1.41      ng       9341: 	    } else {
1.257     albertel 9342: 		if ( $env{'form.upfile_associate'} ne 'reverse' ) {
                   9343: 		    $env{'form.upfile_associate'} = 'reverse';
1.41      ng       9344: 		} else {
1.257     albertel 9345: 		    $env{'form.upfile_associate'} = 'forward';
1.41      ng       9346: 		}
                   9347: 		$request->print(&csvuploadmap($request));
                   9348: 	    }
1.246     albertel 9349: 	} elsif ($command eq 'csvuploadassign' && $perm{'mgr'} ) {
                   9350: 	    $request->print(&csvuploadassign($request));
1.106     albertel 9351: 	} elsif ($command eq 'scantron_selectphase' && $perm{'mgr'}) {
1.75      albertel 9352: 	    $request->print(&scantron_selectphase($request));
1.203     albertel 9353:  	} elsif ($command eq 'scantron_warning' && $perm{'mgr'}) {
                   9354:  	    $request->print(&scantron_do_warning($request));
1.142     albertel 9355: 	} elsif ($command eq 'scantron_validate' && $perm{'mgr'}) {
                   9356: 	    $request->print(&scantron_validate_file($request));
1.106     albertel 9357: 	} elsif ($command eq 'scantron_process' && $perm{'mgr'}) {
1.82      albertel 9358: 	    $request->print(&scantron_process_students($request));
1.157     albertel 9359:  	} elsif ($command eq 'scantronupload' && 
1.257     albertel 9360:  		 (&Apache::lonnet::allowed('usc',$env{'request.role.domain'})||
                   9361: 		  &Apache::lonnet::allowed('usc',$env{'request.course.id'}))) {
1.162     albertel 9362:  	    $request->print(&scantron_upload_scantron_data($request)); 
1.157     albertel 9363:  	} elsif ($command eq 'scantronupload_save' &&
1.257     albertel 9364:  		 (&Apache::lonnet::allowed('usc',$env{'request.role.domain'})||
                   9365: 		  &Apache::lonnet::allowed('usc',$env{'request.course.id'}))) {
1.157     albertel 9366:  	    $request->print(&scantron_upload_scantron_data_save($request));
1.202     albertel 9367:  	} elsif ($command eq 'scantron_download' &&
1.257     albertel 9368: 		 &Apache::lonnet::allowed('usc',$env{'request.course.id'})) {
1.162     albertel 9369:  	    $request->print(&scantron_download_scantron_data($request));
1.523     raeburn  9370:         } elsif ($command eq 'checksubmissions' && $perm{'vgr'}) {
                   9371:             $request->print(&checkscantron_results($request));     
1.106     albertel 9372: 	} elsif ($command) {
1.562     bisitz   9373: 	    $request->print('<p class="LC_error">'.&mt('Access Denied ([_1])',$command).'</p>');
1.26      albertel 9374: 	}
1.2       albertel 9375:     }
1.513     foxr     9376:     if ($ssi_error) {
                   9377: 	&ssi_print_error($request);
                   9378:     }
1.353     albertel 9379:     $request->print(&Apache::loncommon::end_page());
1.434     albertel 9380:     &reset_caches();
1.44      ng       9381:     return '';
                   9382: }
                   9383: 
1.1       albertel 9384: 1;
                   9385: 
1.13      albertel 9386: __END__;
1.531     jms      9387: 
                   9388: 
                   9389: =head1 NAME
                   9390: 
                   9391: Apache::grades
                   9392: 
                   9393: =head1 SYNOPSIS
                   9394: 
                   9395: Handles the viewing of grades.
                   9396: 
                   9397: This is part of the LearningOnline Network with CAPA project
                   9398: described at http://www.lon-capa.org.
                   9399: 
                   9400: =head1 OVERVIEW
                   9401: 
                   9402: Do an ssi with retries:
                   9403: While I'd love to factor out this with the vesrion in lonprintout,
                   9404: 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
                   9405: I'm not quite ready to invent (e.g. an ssi_with_retry object).
                   9406: 
                   9407: At least the logic that drives this has been pulled out into loncommon.
                   9408: 
                   9409: 
                   9410: 
                   9411: ssi_with_retries - Does the server side include of a resource.
                   9412:                      if the ssi call returns an error we'll retry it up to
                   9413:                      the number of times requested by the caller.
                   9414:                      If we still have a proble, no text is appended to the
                   9415:                      output and we set some global variables.
                   9416:                      to indicate to the caller an SSI error occurred.  
                   9417:                      All of this is supposed to deal with the issues described
                   9418:                      in LonCAPA BZ 5631 see:
                   9419:                      http://bugs.lon-capa.org/show_bug.cgi?id=5631
                   9420:                      by informing the user that this happened.
                   9421: 
                   9422: Parameters:
                   9423:   resource   - The resource to include.  This is passed directly, without
                   9424:                interpretation to lonnet::ssi.
                   9425:   form       - The form hash parameters that guide the interpretation of the resource
                   9426:                
                   9427:   retries    - Number of retries allowed before giving up completely.
                   9428: Returns:
                   9429:   On success, returns the rendered resource identified by the resource parameter.
                   9430: Side Effects:
                   9431:   The following global variables can be set:
                   9432:    ssi_error                - If an unrecoverable error occurred this becomes true.
                   9433:                               It is up to the caller to initialize this to false
                   9434:                               if desired.
                   9435:    ssi_error_resource  - If an unrecoverable error occurred, this is the value
                   9436:                               of the resource that could not be rendered by the ssi
                   9437:                               call.
                   9438:    ssi_error_message   - The error string fetched from the ssi response
                   9439:                               in the event of an error.
                   9440: 
                   9441: 
                   9442: =head1 HANDLER SUBROUTINE
                   9443: 
                   9444: ssi_with_retries()
                   9445: 
                   9446: =head1 SUBROUTINES
                   9447: 
                   9448: =over
                   9449: 
                   9450: =item scantron_get_correction() : 
                   9451: 
                   9452:    Builds the interface screen to interact with the operator to fix a
                   9453:    specific error condition in a specific scanline
                   9454: 
                   9455:  Arguments:
                   9456:     $r           - Apache request object
                   9457:     $i           - number of the current scanline
                   9458:     $scan_record - hash ref as returned from &scantron_parse_scanline()
                   9459:     $scan_config - hash ref as returned from &get_scantron_config()
                   9460:     $line        - full contents of the current scanline
                   9461:     $error       - error condition, valid values are
                   9462:                    'incorrectCODE', 'duplicateCODE',
                   9463:                    'doublebubble', 'missingbubble',
                   9464:                    'duplicateID', 'incorrectID'
                   9465:     $arg         - extra information needed
                   9466:        For errors:
                   9467:          - duplicateID   - paper number that this studentID was seen before on
                   9468:          - duplicateCODE - array ref of the paper numbers this CODE was
                   9469:                            seen on before
                   9470:          - incorrectCODE - current incorrect CODE 
                   9471:          - doublebubble  - array ref of the bubble lines that have double
                   9472:                            bubble errors
                   9473:          - missingbubble - array ref of the bubble lines that have missing
                   9474:                            bubble errors
                   9475: 
                   9476: =item  scantron_get_maxbubble() : 
                   9477: 
1.582     raeburn  9478:    Arguments:
                   9479:        $nav_error  - Reference to scalar which is a flag to indicate a
                   9480:                       failure to retrieve a navmap object.
                   9481:        if $nav_error is set to 1 by scantron_get_maxbubble(), the 
                   9482:        calling routine should trap the error condition and display the warning
                   9483:        found in &navmap_errormsg().
                   9484: 
1.531     jms      9485:    Returns the maximum number of bubble lines that are expected to
                   9486:    occur. Does this by walking the selected sequence rendering the
                   9487:    resource and then checking &Apache::lonxml::get_problem_counter()
                   9488:    for what the current value of the problem counter is.
                   9489: 
                   9490:    Caches the results to $env{'form.scantron_maxbubble'},
                   9491:    $env{'form.scantron.bubble_lines.n'}, 
                   9492:    $env{'form.scantron.first_bubble_line.n'} and
                   9493:    $env{"form.scantron.sub_bubblelines.n"}
                   9494:    which are the total number of bubble, lines, the number of bubble
                   9495:    lines for response n and number of the first bubble line for response n,
                   9496:    and a comma separated list of numbers of bubble lines for sub-questions
                   9497:    (for optionresponse, matchresponse, and rankresponse items), for response n.  
                   9498: 
                   9499: 
                   9500: =item  scantron_validate_missingbubbles() : 
                   9501: 
                   9502:    Validates all scanlines in the selected file to not have any
                   9503:     answers that don't have bubbles that have not been verified
                   9504:     to be bubble free.
                   9505: 
                   9506: =item  scantron_process_students() : 
                   9507: 
                   9508:    Routine that does the actual grading of the bubble sheet information.
                   9509: 
                   9510:    The parsed scanline hash is added to %env 
                   9511: 
                   9512:    Then foreach unskipped scanline it does an &Apache::lonnet::ssi()
                   9513:    foreach resource , with the form data of
                   9514: 
                   9515: 	'submitted'     =>'scantron' 
                   9516: 	'grade_target'  =>'grade',
                   9517: 	'grade_username'=> username of student
                   9518: 	'grade_domain'  => domain of student
                   9519: 	'grade_courseid'=> of course
                   9520: 	'grade_symb'    => symb of resource to grade
                   9521: 
                   9522:     This triggers a grading pass. The problem grading code takes care
                   9523:     of converting the bubbled letter information (now in %env) into a
                   9524:     valid submission.
                   9525: 
                   9526: =item  scantron_upload_scantron_data() :
                   9527: 
                   9528:     Creates the screen for adding a new bubble sheet data file to a course.
                   9529: 
                   9530: =item  scantron_upload_scantron_data_save() : 
                   9531: 
                   9532:    Adds a provided bubble information data file to the course if user
                   9533:    has the correct privileges to do so. 
                   9534: 
                   9535: =item  valid_file() :
                   9536: 
                   9537:    Validates that the requested bubble data file exists in the course.
                   9538: 
                   9539: =item  scantron_download_scantron_data() : 
                   9540: 
                   9541:    Shows a list of the three internal files (original, corrected,
                   9542:    skipped) for a specific bubble sheet data file that exists in the
                   9543:    course.
                   9544: 
                   9545: =item  scantron_validate_ID() : 
                   9546: 
                   9547:    Validates all scanlines in the selected file to not have any
1.556     weissno  9548:    invalid or underspecified student/employee IDs
1.531     jms      9549: 
1.582     raeburn  9550: =item navmap_errormsg() :
                   9551: 
                   9552:    Returns HTML mark-up inside a <div></div> with a link to re-initialize the course.
                   9553:    Should be called whenever the request to instantiate a navmap object fails.  
                   9554: 
1.531     jms      9555: =back
                   9556: 
                   9557: =cut

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