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

1.17      albertel    1: # The LearningOnline Network with CAPA
1.13      albertel    2: # The LON-CAPA Grading handler
1.17      albertel    3: #
1.604   ! raeburn     4: # $Id: grades.pm,v 1.603 2010/03/26 15:40:55 www Exp $
1.17      albertel    5: #
                      6: # Copyright Michigan State University Board of Trustees
                      7: #
                      8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
                      9: #
                     10: # LON-CAPA is free software; you can redistribute it and/or modify
                     11: # it under the terms of the GNU General Public License as published by
                     12: # the Free Software Foundation; either version 2 of the License, or
                     13: # (at your option) any later version.
                     14: #
                     15: # LON-CAPA is distributed in the hope that it will be useful,
                     16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
                     17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
                     18: # GNU General Public License for more details.
                     19: #
                     20: # You should have received a copy of the GNU General Public License
                     21: # along with LON-CAPA; if not, write to the Free Software
                     22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
                     23: #
                     24: # /home/httpd/html/adm/gpl.txt
                     25: #
                     26: # http://www.lon-capa.org/
                     27: #
1.1       albertel   28: 
1.529     jms        29: 
                     30: 
1.1       albertel   31: package Apache::grades;
                     32: use strict;
                     33: use Apache::style;
                     34: use Apache::lonxml;
                     35: use Apache::lonnet;
1.3       albertel   36: use Apache::loncommon;
1.112     ng         37: use Apache::lonhtmlcommon;
1.68      ng         38: use Apache::lonnavmaps;
1.1       albertel   39: use Apache::lonhomework;
1.456     banghart   40: use Apache::lonpickcode;
1.55      matthew    41: use Apache::loncoursedata;
1.362     albertel   42: use Apache::lonmsg();
1.1       albertel   43: use Apache::Constants qw(:common);
1.167     sakharuk   44: use Apache::lonlocal;
1.386     raeburn    45: use Apache::lonenc;
1.170     albertel   46: use String::Similarity;
1.359     www        47: use LONCAPA;
                     48: 
1.315     bowersj2   49: use POSIX qw(floor);
1.87      www        50: 
1.435     foxr       51: 
1.513     foxr       52: 
1.435     foxr       53: my %perm=();
1.447     foxr       54: 
1.513     foxr       55: #  These variables are used to recover from ssi errors
                     56: 
                     57: my $ssi_retries = 5;
                     58: my $ssi_error;
                     59: my $ssi_error_resource;
                     60: my $ssi_error_message;
                     61: 
                     62: 
                     63: sub ssi_with_retries {
                     64:     my ($resource, $retries, %form) = @_;
                     65:     my ($content, $response) = &Apache::loncommon::ssi_with_retries($resource, $retries, %form);
                     66:     if ($response->is_error) {
                     67: 	$ssi_error          = 1;
                     68: 	$ssi_error_resource = $resource;
                     69: 	$ssi_error_message  = $response->code . " " . $response->message;
                     70:     }
                     71: 
                     72:     return $content;
                     73: 
                     74: }
                     75: #
                     76: #  Prodcuces an ssi retry failure error message to the user:
                     77: #
                     78: 
                     79: sub ssi_print_error {
                     80:     my ($r) = @_;
1.516     raeburn    81:     my $helpurl = &Apache::loncommon::top_nav_help('Helpdesk');
                     82:     $r->print('
                     83: <br />
                     84: <h2>'.&mt('An unrecoverable network error occurred:').'</h2>
                     85: <p>
                     86: '.&mt('Unable to retrieve a resource from a server:').'<br />
                     87: '.&mt('Resource:').' '.$ssi_error_resource.'<br />
                     88: '.&mt('Error:').' '.$ssi_error_message.'
                     89: </p>
                     90: <p>'.
                     91: &mt('It is recommended that you try again later, as this error may mean the server was just temporarily unavailable, or is down for maintenance.').'<br />'.
                     92: &mt('If the error persists, please contact the [_1] for assistance.',$helpurl).
                     93: '</p>');
                     94:     return;
1.513     foxr       95: }
                     96: 
1.44      ng         97: #
1.146     albertel   98: # --- Retrieve the parts from the metadata file.---
1.598     www        99: # Returns an array of everything that the resources stores away
                    100: #
                    101: 
1.44      ng        102: sub getpartlist {
1.582     raeburn   103:     my ($symb,$errorref) = @_;
1.439     albertel  104: 
                    105:     my $navmap   = Apache::lonnavmaps::navmap->new();
1.582     raeburn   106:     unless (ref($navmap)) {
                    107:         if (ref($errorref)) { 
                    108:             $$errorref = 'navmap';
                    109:             return;
                    110:         }
                    111:     }
1.439     albertel  112:     my $res      = $navmap->getBySymb($symb);
                    113:     my $partlist = $res->parts();
                    114:     my $url      = $res->src();
                    115:     my @metakeys = split(/,/,&Apache::lonnet::metadata($url,'keys'));
                    116: 
1.146     albertel  117:     my @stores;
1.439     albertel  118:     foreach my $part (@{ $partlist }) {
1.146     albertel  119: 	foreach my $key (@metakeys) {
                    120: 	    if ($key =~ m/^stores_\Q$part\E_/) { push(@stores,$key); }
                    121: 	}
                    122:     }
                    123:     return @stores;
1.2       albertel  124: }
                    125: 
1.44      ng        126: # --- Get the symbolic name of a problem and the url
1.598     www       127: # Generate an error message if symb could not be found unless silent flag is set
                    128: # Takes $env{'form.symb'} by default; if not present, takes $env{'form.url'} and tries to get symb from that
                    129: #
                    130:  
1.324     albertel  131: sub get_symb {
1.173     albertel  132:     my ($request,$silent) = @_;
1.257     albertel  133:     (my $url=$env{'form.url'}) =~ s-^http://($ENV{'SERVER_NAME'}|$ENV{'HTTP_HOST'})--;
                    134:     my $symb=($env{'form.symb'} ne '' ? $env{'form.symb'} : (&Apache::lonnet::symbread($url)));
1.173     albertel  135:     if ($symb eq '') { 
                    136: 	if (!$silent) {
1.598     www       137: 	    $request->print(&mt("Unable to handle ambiguous references: [_1].",$url));
1.173     albertel  138: 	    return ();
                    139: 	}
                    140:     }
1.418     albertel  141:     &Apache::lonenc::check_decrypt(\$symb);
1.324     albertel  142:     return ($symb);
1.32      ng        143: }
                    144: 
1.129     ng        145: #--- Format fullname, username:domain if different for display
                    146: #--- Use anywhere where the student names are listed
                    147: sub nameUserString {
                    148:     my ($type,$fullname,$uname,$udom) = @_;
                    149:     if ($type eq 'header') {
1.485     albertel  150: 	return '<b>&nbsp;'.&mt('Fullname').'&nbsp;</b><span class="LC_internal_info">('.&mt('Username').')</span>';
1.129     ng        151:     } else {
1.398     albertel  152: 	return '&nbsp;'.$fullname.'<span class="LC_internal_info">&nbsp;('.$uname.
                    153: 	    ($env{'user.domain'} eq $udom ? '' : ' ('.$udom.')').')</span>';
1.129     ng        154:     }
                    155: }
                    156: 
1.44      ng        157: #--- Get the partlist and the response type for a given problem. ---
                    158: #--- Indicate if a response type is coded handgraded or not. ---
1.39      ng        159: sub response_type {
1.582     raeburn   160:     my ($symb,$response_error) = @_;
1.377     albertel  161: 
                    162:     my $navmap = Apache::lonnavmaps::navmap->new();
1.582     raeburn   163:     unless (ref($navmap)) {
                    164:         if (ref($response_error)) {
                    165:             $$response_error = 1;
                    166:         }
                    167:         return;
                    168:     }
1.377     albertel  169:     my $res = $navmap->getBySymb($symb);
1.593     raeburn   170:     unless (ref($res)) {
                    171:         $$response_error = 1;
                    172:         return;
                    173:     }
1.377     albertel  174:     my $partlist = $res->parts();
1.392     albertel  175:     my %vPart = 
                    176: 	map { $_ => 1 } (&Apache::loncommon::get_env_multiple('form.vPart'));
1.377     albertel  177:     my (%response_types,%handgrade);
                    178:     foreach my $part (@{ $partlist }) {
1.392     albertel  179: 	next if (%vPart && !exists($vPart{$part}));
                    180: 
1.377     albertel  181: 	my @types = $res->responseType($part);
                    182: 	my @ids = $res->responseIds($part);
                    183: 	for (my $i=0; $i < scalar(@ids); $i++) {
                    184: 	    $response_types{$part}{$ids[$i]} = $types[$i];
                    185: 	    $handgrade{$part.'_'.$ids[$i]} = 
                    186: 		&Apache::lonnet::EXT('resource.'.$part.'_'.$ids[$i].
                    187: 				     '.handgrade',$symb);
1.41      ng        188: 	}
                    189:     }
1.377     albertel  190:     return ($partlist,\%handgrade,\%response_types);
1.39      ng        191: }
                    192: 
1.375     albertel  193: sub flatten_responseType {
                    194:     my ($responseType) = @_;
                    195:     my @part_response_id =
                    196: 	map { 
                    197: 	    my $part = $_;
                    198: 	    map {
                    199: 		[$part,$_]
                    200: 		} sort(keys(%{ $responseType->{$part} }));
                    201: 	} sort(keys(%$responseType));
                    202:     return @part_response_id;
                    203: }
                    204: 
1.207     albertel  205: sub get_display_part {
1.324     albertel  206:     my ($partID,$symb)=@_;
1.207     albertel  207:     my $display=&Apache::lonnet::EXT('resource.'.$partID.'.display',$symb);
                    208:     if (defined($display) and $display ne '') {
1.577     bisitz    209:         $display.= ' (<span class="LC_internal_info">'
                    210:                   .&mt('Part ID: [_1]',$partID).'</span>)';
1.207     albertel  211:     } else {
                    212: 	$display=$partID;
                    213:     }
                    214:     return $display;
                    215: }
1.269     raeburn   216: 
1.434     albertel  217: sub reset_caches {
                    218:     &reset_analyze_cache();
                    219:     &reset_perm();
                    220: }
                    221: 
                    222: {
                    223:     my %analyze_cache;
1.557     raeburn   224:     my %analyze_cache_formkeys;
1.148     albertel  225: 
1.434     albertel  226:     sub reset_analyze_cache {
                    227: 	undef(%analyze_cache);
1.557     raeburn   228:         undef(%analyze_cache_formkeys);
1.434     albertel  229:     }
                    230: 
                    231:     sub get_analyze {
1.557     raeburn   232: 	my ($symb,$uname,$udom,$no_increment,$add_to_hash)=@_;
1.434     albertel  233: 	my $key = "$symb\0$uname\0$udom";
1.557     raeburn   234: 	if (exists($analyze_cache{$key})) {
                    235:             my $getupdate = 0;
                    236:             if (ref($add_to_hash) eq 'HASH') {
                    237:                 foreach my $item (keys(%{$add_to_hash})) {
                    238:                     if (ref($analyze_cache_formkeys{$key}) eq 'HASH') {
                    239:                         if (!exists($analyze_cache_formkeys{$key}{$item})) {
                    240:                             $getupdate = 1;
                    241:                             last;
                    242:                         }
                    243:                     } else {
                    244:                         $getupdate = 1;
                    245:                     }
                    246:                 }
                    247:             }
                    248:             if (!$getupdate) {
                    249:                 return $analyze_cache{$key};
                    250:             }
                    251:         }
1.434     albertel  252: 
                    253: 	my (undef,undef,$url)=&Apache::lonnet::decode_symb($symb);
                    254: 	$url=&Apache::lonnet::clutter($url);
1.557     raeburn   255:         my %form = ('grade_target'      => 'analyze',
                    256:                     'grade_domain'      => $udom,
                    257:                     'grade_symb'        => $symb,
                    258:                     'grade_courseid'    =>  $env{'request.course.id'},
                    259:                     'grade_username'    => $uname,
                    260:                     'grade_noincrement' => $no_increment);
                    261:         if (ref($add_to_hash)) {
                    262:             %form = (%form,%{$add_to_hash});
                    263:         } 
                    264: 	my $subresult=&ssi_with_retries($url, $ssi_retries,%form);
1.434     albertel  265: 	(undef,$subresult)=split(/_HASH_REF__/,$subresult,2);
                    266: 	my %analyze=&Apache::lonnet::str2hash($subresult);
1.557     raeburn   267:         if (ref($add_to_hash) eq 'HASH') {
                    268:             $analyze_cache_formkeys{$key} = $add_to_hash;
                    269:         } else {
                    270:             $analyze_cache_formkeys{$key} = {};
                    271:         }
1.434     albertel  272: 	return $analyze_cache{$key} = \%analyze;
                    273:     }
                    274: 
                    275:     sub get_order {
1.525     raeburn   276: 	my ($partid,$respid,$symb,$uname,$udom,$no_increment)=@_;
                    277: 	my $analyze = &get_analyze($symb,$uname,$udom,$no_increment);
1.434     albertel  278: 	return $analyze->{"$partid.$respid.shown"};
                    279:     }
                    280: 
                    281:     sub get_radiobutton_correct_foil {
                    282: 	my ($partid,$respid,$symb,$uname,$udom)=@_;
                    283: 	my $analyze = &get_analyze($symb,$uname,$udom);
1.555     raeburn   284:         my $foils = &get_order($partid,$respid,$symb,$uname,$udom);
                    285:         if (ref($foils) eq 'ARRAY') {
                    286: 	    foreach my $foil (@{$foils}) {
                    287: 	        if ($analyze->{"$partid.$respid.foil.value.$foil"} eq 'true') {
                    288: 		    return $foil;
                    289: 	        }
1.434     albertel  290: 	    }
                    291: 	}
                    292:     }
1.554     raeburn   293: 
                    294:     sub scantron_partids_tograde {
1.557     raeburn   295:         my ($resource,$cid,$uname,$udom,$check_for_randomlist) = @_;
1.554     raeburn   296:         my (%analysis,@parts);
                    297:         if (ref($resource)) {
                    298:             my $symb = $resource->symb();
1.557     raeburn   299:             my $add_to_form;
                    300:             if ($check_for_randomlist) {
                    301:                 $add_to_form = { 'check_parts_withrandomlist' => 1,};
                    302:             }
                    303:             my $analyze = &get_analyze($symb,$uname,$udom,undef,$add_to_form);
1.554     raeburn   304:             if (ref($analyze) eq 'HASH') {
                    305:                 %analysis = %{$analyze};
                    306:             }
                    307:             if (ref($analysis{'parts'}) eq 'ARRAY') {
                    308:                 foreach my $part (@{$analysis{'parts'}}) {
                    309:                     my ($id,$respid) = split(/\./,$part);
                    310:                     if (!&Apache::loncommon::check_if_partid_hidden($id,$symb,$udom,$uname)) {
                    311:                         push(@parts,$part);
                    312:                     }
                    313:                 }
                    314:             }
                    315:         }
                    316:         return (\%analysis,\@parts);
                    317:     }
                    318: 
1.148     albertel  319: }
1.434     albertel  320: 
1.118     ng        321: #--- Clean response type for display
1.335     albertel  322: #--- Currently filters option/rank/radiobutton/match/essay/Task
                    323: #        response types only.
1.118     ng        324: sub cleanRecord {
1.336     albertel  325:     my ($answer,$response,$symb,$partid,$respid,$record,$order,$version,
                    326: 	$uname,$udom) = @_;
1.398     albertel  327:     my $grayFont = '<span class="LC_internal_info">';
1.148     albertel  328:     if ($response =~ /^(option|rank)$/) {
                    329: 	my %answer=&Apache::lonnet::str2hash($answer);
                    330: 	my %grading=&Apache::lonnet::str2hash($record->{$version."resource.$partid.$respid.submissiongrading"});
                    331: 	my ($toprow,$bottomrow);
                    332: 	foreach my $foil (@$order) {
                    333: 	    if ($grading{$foil} == 1) {
                    334: 		$toprow.='<td><b>'.$answer{$foil}.'&nbsp;</b></td>';
                    335: 	    } else {
                    336: 		$toprow.='<td><i>'.$answer{$foil}.'&nbsp;</i></td>';
                    337: 	    }
1.398     albertel  338: 	    $bottomrow.='<td>'.$grayFont.$foil.'</span>&nbsp;</td>';
1.148     albertel  339: 	}
                    340: 	return '<blockquote><table border="1">'.
1.466     albertel  341: 	    '<tr valign="top"><td>'.&mt('Answer').'</td>'.$toprow.'</tr>'.
                    342: 	    '<tr valign="top"><td>'.$grayFont.&mt('Option ID').'</span></td>'.
1.148     albertel  343: 	    $grayFont.$bottomrow.'</tr>'.'</table></blockquote>';
                    344:     } elsif ($response eq 'match') {
                    345: 	my %answer=&Apache::lonnet::str2hash($answer);
                    346: 	my %grading=&Apache::lonnet::str2hash($record->{$version."resource.$partid.$respid.submissiongrading"});
                    347: 	my @items=&Apache::lonnet::str2array($record->{$version."resource.$partid.$respid.submissionitems"});
                    348: 	my ($toprow,$middlerow,$bottomrow);
                    349: 	foreach my $foil (@$order) {
                    350: 	    my $item=shift(@items);
                    351: 	    if ($grading{$foil} == 1) {
                    352: 		$toprow.='<td><b>'.$item.'&nbsp;</b></td>';
1.398     albertel  353: 		$middlerow.='<td><b>'.$grayFont.$answer{$foil}.'&nbsp;</span></b></td>';
1.148     albertel  354: 	    } else {
                    355: 		$toprow.='<td><i>'.$item.'&nbsp;</i></td>';
1.398     albertel  356: 		$middlerow.='<td><i>'.$grayFont.$answer{$foil}.'&nbsp;</span></i></td>';
1.148     albertel  357: 	    }
1.398     albertel  358: 	    $bottomrow.='<td>'.$grayFont.$foil.'</span>&nbsp;</td>';
1.118     ng        359: 	}
1.126     ng        360: 	return '<blockquote><table border="1">'.
1.466     albertel  361: 	    '<tr valign="top"><td>'.&mt('Answer').'</td>'.$toprow.'</tr>'.
                    362: 	    '<tr valign="top"><td>'.$grayFont.&mt('Item ID').'</span></td>'.
1.148     albertel  363: 	    $middlerow.'</tr>'.
1.466     albertel  364: 	    '<tr valign="top"><td>'.$grayFont.&mt('Option ID').'</span></td>'.
1.148     albertel  365: 	    $bottomrow.'</tr>'.'</table></blockquote>';
                    366:     } elsif ($response eq 'radiobutton') {
                    367: 	my %answer=&Apache::lonnet::str2hash($answer);
                    368: 	my ($toprow,$bottomrow);
1.434     albertel  369: 	my $correct = 
                    370: 	    &get_radiobutton_correct_foil($partid,$respid,$symb,$uname,$udom);
                    371: 	foreach my $foil (@$order) {
1.148     albertel  372: 	    if (exists($answer{$foil})) {
1.434     albertel  373: 		if ($foil eq $correct) {
1.466     albertel  374: 		    $toprow.='<td><b>'.&mt('true').'</b></td>';
1.148     albertel  375: 		} else {
1.466     albertel  376: 		    $toprow.='<td><i>'.&mt('true').'</i></td>';
1.148     albertel  377: 		}
                    378: 	    } else {
1.466     albertel  379: 		$toprow.='<td>'.&mt('false').'</td>';
1.148     albertel  380: 	    }
1.398     albertel  381: 	    $bottomrow.='<td>'.$grayFont.$foil.'</span>&nbsp;</td>';
1.148     albertel  382: 	}
                    383: 	return '<blockquote><table border="1">'.
1.466     albertel  384: 	    '<tr valign="top"><td>'.&mt('Answer').'</td>'.$toprow.'</tr>'.
                    385: 	    '<tr valign="top"><td>'.$grayFont.&mt('Option ID').'</span></td>'.
1.597     wenzelju  386: 	    $bottomrow.'</tr>'.'</table></blockquote>';
1.148     albertel  387:     } elsif ($response eq 'essay') {
1.257     albertel  388: 	if (! exists ($env{'form.'.$symb})) {
1.122     ng        389: 	    my (%keyhash) = &Apache::lonnet::dump('nohist_handgrade',
1.257     albertel  390: 						  $env{'course.'.$env{'request.course.id'}.'.domain'},
                    391: 						  $env{'course.'.$env{'request.course.id'}.'.num'});
1.122     ng        392: 
1.257     albertel  393: 	    my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
                    394: 	    $env{'form.keywords'} = $keyhash{$symb.'_keywords'} ne '' ? $keyhash{$symb.'_keywords'} : '';
                    395: 	    $env{'form.kwclr'}    = $keyhash{$loginuser.'_kwclr'} ne '' ? $keyhash{$loginuser.'_kwclr'} : 'red';
                    396: 	    $env{'form.kwsize'}   = $keyhash{$loginuser.'_kwsize'} ne '' ? $keyhash{$loginuser.'_kwsize'} : '0';
                    397: 	    $env{'form.kwstyle'}  = $keyhash{$loginuser.'_kwstyle'} ne '' ? $keyhash{$loginuser.'_kwstyle'} : '';
                    398: 	    $env{'form.'.$symb} = 1; # so that we don't have to read it from disk for multiple sub of the same prob.
1.122     ng        399: 	}
1.166     albertel  400: 	$answer =~ s-\n-<br />-g;
                    401: 	return '<br /><br /><blockquote><tt>'.&keywords_highlight($answer).'</tt></blockquote>';
1.268     albertel  402:     } elsif ( $response eq 'organic') {
                    403: 	my $result='Smile representation: "<tt>'.$answer.'</tt>"';
                    404: 	my $jme=$record->{$version."resource.$partid.$respid.molecule"};
                    405: 	$result.=&Apache::chemresponse::jme_img($jme,$answer,400);
                    406: 	return $result;
1.335     albertel  407:     } elsif ( $response eq 'Task') {
                    408: 	if ( $answer eq 'SUBMITTED') {
                    409: 	    my $files = $record->{$version."resource.$respid.$partid.bridgetask.portfiles"};
1.336     albertel  410: 	    my $result = &Apache::bridgetask::file_list($files,$uname,$udom);
1.335     albertel  411: 	    return $result;
                    412: 	} elsif ( grep(/^\Q$version\E.*?\.instance$/, keys(%{$record})) ) {
                    413: 	    my @matches = grep(/^\Q$version\E.*?\.instance$/,
                    414: 			       keys(%{$record}));
                    415: 	    return join('<br />',($version,@matches));
                    416: 			       
                    417: 			       
                    418: 	} else {
                    419: 	    my $result =
                    420: 		'<p>'
                    421: 		.&mt('Overall result: [_1]',
                    422: 		     $record->{$version."resource.$respid.$partid.status"})
                    423: 		.'</p>';
                    424: 	    
                    425: 	    $result .= '<ul>';
                    426: 	    my @grade = grep(/^\Q${version}resource.$respid.$partid.\E[^.]*[.]status$/,
                    427: 			     keys(%{$record}));
                    428: 	    foreach my $grade (sort(@grade)) {
                    429: 		my ($dim) = ($grade =~/[.]([^.]+)[.]status$/);
                    430: 		$result.= '<li>'.&mt("Dimension: [_1], status [_2] ",
                    431: 				     $dim, $record->{$grade}).
                    432: 			  '</li>';
                    433: 	    }
                    434: 	    $result.='</ul>';
                    435: 	    return $result;
                    436: 	}
1.440     albertel  437:     } elsif ( $response =~ m/(?:numerical|formula)/) {
                    438: 	$answer = 
                    439: 	    &Apache::loncommon::format_previous_attempt_value('submission',
                    440: 							      $answer);
1.122     ng        441:     }
1.118     ng        442:     return $answer;
                    443: }
                    444: 
                    445: #-- A couple of common js functions
                    446: sub commonJSfunctions {
                    447:     my $request = shift;
1.597     wenzelju  448:     $request->print(&Apache::lonhtmlcommon::scripttag(<<COMMONJSFUNCTIONS));
1.118     ng        449:     function radioSelection(radioButton) {
                    450: 	var selection=null;
                    451: 	if (radioButton.length > 1) {
                    452: 	    for (var i=0; i<radioButton.length; i++) {
                    453: 		if (radioButton[i].checked) {
                    454: 		    return radioButton[i].value;
                    455: 		}
                    456: 	    }
                    457: 	} else {
                    458: 	    if (radioButton.checked) return radioButton.value;
                    459: 	}
                    460: 	return selection;
                    461:     }
                    462: 
                    463:     function pullDownSelection(selectOne) {
                    464: 	var selection="";
                    465: 	if (selectOne.length > 1) {
                    466: 	    for (var i=0; i<selectOne.length; i++) {
                    467: 		if (selectOne[i].selected) {
                    468: 		    return selectOne[i].value;
                    469: 		}
                    470: 	    }
                    471: 	} else {
1.138     albertel  472:             // only one value it must be the selected one
                    473: 	    return selectOne.value;
1.118     ng        474: 	}
                    475:     }
                    476: COMMONJSFUNCTIONS
                    477: }
                    478: 
1.44      ng        479: #--- Dumps the class list with usernames,list of sections,
                    480: #--- section, ids and fullnames for each user.
                    481: sub getclasslist {
1.449     banghart  482:     my ($getsec,$filterlist,$getgroup) = @_;
1.291     albertel  483:     my @getsec;
1.450     banghart  484:     my @getgroup;
1.442     banghart  485:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
1.291     albertel  486:     if (!ref($getsec)) {
                    487: 	if ($getsec ne '' && $getsec ne 'all') {
                    488: 	    @getsec=($getsec);
                    489: 	}
                    490:     } else {
                    491: 	@getsec=@{$getsec};
                    492:     }
                    493:     if (grep(/^all$/,@getsec)) { undef(@getsec); }
1.450     banghart  494:     if (!ref($getgroup)) {
                    495: 	if ($getgroup ne '' && $getgroup ne 'all') {
                    496: 	    @getgroup=($getgroup);
                    497: 	}
                    498:     } else {
                    499: 	@getgroup=@{$getgroup};
                    500:     }
                    501:     if (grep(/^all$/,@getgroup)) { undef(@getgroup); }
1.291     albertel  502: 
1.449     banghart  503:     my ($classlist,$keylist)=&Apache::loncoursedata::get_classlist();
1.49      albertel  504:     # Bail out if we were unable to get the classlist
1.56      matthew   505:     return if (! defined($classlist));
1.449     banghart  506:     &Apache::loncoursedata::get_group_memberships($classlist,$keylist);
1.56      matthew   507:     #
                    508:     my %sections;
                    509:     my %fullnames;
1.205     matthew   510:     foreach my $student (keys(%$classlist)) {
                    511:         my $end      = 
                    512:             $classlist->{$student}->[&Apache::loncoursedata::CL_END()];
                    513:         my $start    = 
                    514:             $classlist->{$student}->[&Apache::loncoursedata::CL_START()];
                    515:         my $id       = 
                    516:             $classlist->{$student}->[&Apache::loncoursedata::CL_ID()];
                    517:         my $section  = 
                    518:             $classlist->{$student}->[&Apache::loncoursedata::CL_SECTION()];
                    519:         my $fullname = 
                    520:             $classlist->{$student}->[&Apache::loncoursedata::CL_FULLNAME()];
                    521:         my $status   = 
                    522:             $classlist->{$student}->[&Apache::loncoursedata::CL_STATUS()];
1.449     banghart  523:         my $group   = 
                    524:             $classlist->{$student}->[&Apache::loncoursedata::CL_GROUP()];
1.76      ng        525: 	# filter students according to status selected
1.442     banghart  526: 	if ($filterlist && (!($stu_status =~ /Any/))) {
                    527: 	    if (!($stu_status =~ $status)) {
1.450     banghart  528: 		delete($classlist->{$student});
1.76      ng        529: 		next;
                    530: 	    }
                    531: 	}
1.450     banghart  532: 	# filter students according to groups selected
1.453     banghart  533: 	my @stu_groups = split(/,/,$group);
1.450     banghart  534: 	if (@getgroup) {
                    535: 	    my $exclude = 1;
1.454     banghart  536: 	    foreach my $grp (@getgroup) {
                    537: 	        foreach my $stu_group (@stu_groups) {
1.453     banghart  538: 	            if ($stu_group eq $grp) {
                    539: 	                $exclude = 0;
                    540:     	            } 
1.450     banghart  541: 	        }
1.453     banghart  542:     	        if (($grp eq 'none') && !$group) {
                    543:         	        $exclude = 0;
                    544:         	}
1.450     banghart  545: 	    }
                    546: 	    if ($exclude) {
                    547: 	        delete($classlist->{$student});
                    548: 	    }
                    549: 	}
1.205     matthew   550: 	$section = ($section ne '' ? $section : 'none');
1.106     albertel  551: 	if (&canview($section)) {
1.291     albertel  552: 	    if (!@getsec || grep(/^\Q$section\E$/,@getsec)) {
1.103     albertel  553: 		$sections{$section}++;
1.450     banghart  554: 		if ($classlist->{$student}) {
                    555: 		    $fullnames{$student}=$fullname;
                    556: 		}
1.103     albertel  557: 	    } else {
1.205     matthew   558: 		delete($classlist->{$student});
1.103     albertel  559: 	    }
                    560: 	} else {
1.205     matthew   561: 	    delete($classlist->{$student});
1.103     albertel  562: 	}
1.44      ng        563:     }
                    564:     my %seen = ();
1.56      matthew   565:     my @sections = sort(keys(%sections));
                    566:     return ($classlist,\@sections,\%fullnames);
1.44      ng        567: }
                    568: 
1.103     albertel  569: sub canmodify {
                    570:     my ($sec)=@_;
                    571:     if ($perm{'mgr'}) {
                    572: 	if (!defined($perm{'mgr_section'})) {
                    573: 	    # can modify whole class
                    574: 	    return 1;
                    575: 	} else {
                    576: 	    if ($sec eq $perm{'mgr_section'}) {
                    577: 		#can modify the requested section
                    578: 		return 1;
                    579: 	    } else {
                    580: 		# can't modify the request section
                    581: 		return 0;
                    582: 	    }
                    583: 	}
                    584:     }
                    585:     #can't modify
                    586:     return 0;
                    587: }
                    588: 
                    589: sub canview {
                    590:     my ($sec)=@_;
                    591:     if ($perm{'vgr'}) {
                    592: 	if (!defined($perm{'vgr_section'})) {
                    593: 	    # can modify whole class
                    594: 	    return 1;
                    595: 	} else {
                    596: 	    if ($sec eq $perm{'vgr_section'}) {
                    597: 		#can modify the requested section
                    598: 		return 1;
                    599: 	    } else {
                    600: 		# can't modify the request section
                    601: 		return 0;
                    602: 	    }
                    603: 	}
                    604:     }
                    605:     #can't modify
                    606:     return 0;
                    607: }
                    608: 
1.44      ng        609: #--- Retrieve the grade status of a student for all the parts
                    610: sub student_gradeStatus {
1.324     albertel  611:     my ($symb,$udom,$uname,$partlist) = @_;
1.257     albertel  612:     my %record     = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
1.44      ng        613:     my %partstatus = ();
                    614:     foreach (@$partlist) {
1.128     ng        615: 	my ($status,undef)   = split(/_/,$record{"resource.$_.solved"},2);
1.44      ng        616: 	$status              = 'nothing' if ($status eq '');
                    617: 	$partstatus{$_}      = $status;
                    618: 	my $subkey           = "resource.$_.submitted_by";
                    619: 	$partstatus{$subkey} = $record{$subkey} if ($record{$subkey} ne '');
                    620:     }
                    621:     return %partstatus;
                    622: }
                    623: 
1.45      ng        624: # hidden form and javascript that calls the form
                    625: # Use by verifyscript and viewgrades
                    626: # Shows a student's view of problem and submission
                    627: sub jscriptNform {
1.324     albertel  628:     my ($symb) = @_;
1.442     banghart  629:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
1.597     wenzelju  630:     my $jscript= &Apache::lonhtmlcommon::scripttag(
1.45      ng        631: 	'    function viewOneStudent(user,domain) {'."\n".
                    632: 	'	document.onestudent.student.value = user;'."\n".
                    633: 	'	document.onestudent.userdom.value = domain;'."\n".
                    634: 	'	document.onestudent.submit();'."\n".
                    635: 	'    }'."\n".
1.597     wenzelju  636: 	"\n");
1.45      ng        637:     $jscript.= '<form action="/adm/grades" method="post" name="onestudent">'."\n".
1.418     albertel  638: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.257     albertel  639: 	'<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n".
                    640: 	'<input type="hidden" name="probTitle" value="'.$env{'form.probTitle'}.'" />'."\n".
1.442     banghart  641: 	'<input type="hidden" name="Status"  value="'.$stu_status.'" />'."\n".
1.45      ng        642: 	'<input type="hidden" name="command" value="submission" />'."\n".
                    643: 	'<input type="hidden" name="student" value="" />'."\n".
                    644: 	'<input type="hidden" name="userdom" value="" />'."\n".
                    645: 	'</form>'."\n";
                    646:     return $jscript;
                    647: }
1.39      ng        648: 
1.447     foxr      649: 
                    650: 
1.315     bowersj2  651: # Given the score (as a number [0-1] and the weight) what is the final
                    652: # point value? This function will round to the nearest tenth, third,
                    653: # or quarter if one of those is within the tolerance of .00001.
1.316     albertel  654: sub compute_points {
1.315     bowersj2  655:     my ($score, $weight) = @_;
                    656:     
                    657:     my $tolerance = .00001;
                    658:     my $points = $score * $weight;
                    659: 
                    660:     # Check for nearness to 1/x.
                    661:     my $check_for_nearness = sub {
                    662:         my ($factor) = @_;
                    663:         my $num = ($points * $factor) + $tolerance;
                    664:         my $floored_num = floor($num);
1.316     albertel  665:         if ($num - $floored_num < 2 * $tolerance * $factor) {
1.315     bowersj2  666:             return $floored_num / $factor;
                    667:         }
                    668:         return $points;
                    669:     };
                    670: 
                    671:     $points = $check_for_nearness->(10);
                    672:     $points = $check_for_nearness->(3);
                    673:     $points = $check_for_nearness->(4);
                    674:     
                    675:     return $points;
                    676: }
                    677: 
1.44      ng        678: #------------------ End of general use routines --------------------
1.87      www       679: 
                    680: #
                    681: # Find most similar essay
                    682: #
                    683: 
                    684: sub most_similar {
1.426     albertel  685:     my ($uname,$udom,$uessay,$old_essays)=@_;
1.87      www       686: 
                    687: # ignore spaces and punctuation
                    688: 
                    689:     $uessay=~s/\W+/ /gs;
                    690: 
1.282     www       691: # ignore empty submissions (occuring when only files are sent)
                    692: 
1.598     www       693:     unless ($uessay=~/\w+/s) { return ''; }
1.282     www       694: 
1.87      www       695: # these will be returned. Do not care if not at least 50 percent similar
1.88      www       696:     my $limit=0.6;
1.87      www       697:     my $sname='';
                    698:     my $sdom='';
                    699:     my $scrsid='';
                    700:     my $sessay='';
                    701: # go through all essays ...
1.426     albertel  702:     foreach my $tkey (keys(%$old_essays)) {
                    703: 	my ($tname,$tdom,$tcrsid)=map {&unescape($_)} (split(/\./,$tkey));
1.87      www       704: # ... except the same student
1.426     albertel  705:         next if (($tname eq $uname) && ($tdom eq $udom));
                    706: 	my $tessay=$old_essays->{$tkey};
                    707: 	$tessay=~s/\W+/ /gs;
1.87      www       708: # String similarity gives up if not even limit
1.426     albertel  709: 	my $tsimilar=&String::Similarity::similarity($uessay,$tessay,$limit);
1.87      www       710: # Found one
1.426     albertel  711: 	if ($tsimilar>$limit) {
                    712: 	    $limit=$tsimilar;
                    713: 	    $sname=$tname;
                    714: 	    $sdom=$tdom;
                    715: 	    $scrsid=$tcrsid;
                    716: 	    $sessay=$old_essays->{$tkey};
                    717: 	}
1.87      www       718:     }
1.88      www       719:     if ($limit>0.6) {
1.87      www       720:        return ($sname,$sdom,$scrsid,$sessay,$limit);
                    721:     } else {
                    722:        return ('','','','',0);
                    723:     }
                    724: }
                    725: 
1.44      ng        726: #-------------------------------------------------------------------
                    727: 
                    728: #------------------------------------ Receipt Verification Routines
1.45      ng        729: #
1.602     www       730: 
                    731: sub initialverifyreceipt {
                    732:    my $request = shift;
                    733:    &commonJSfunctions($request);
1.603     www       734:    my ($symb)   = &get_symb($request);
                    735:    return '<form name="gradingMenu"><input type="submit" value="'.&mt('Verify Receipt No.').'" />'.
1.602     www       736:         &Apache::lonnet::recprefix($env{'request.course.id'}).
                    737:         '-<input type="text" name="receipt" size="4" />'.
1.603     www       738:         '<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
                    739:         '<input type="hidden" name="command" value="verify" />'.
                    740:         "</form>\n";
1.602     www       741: }
                    742: 
1.44      ng        743: #--- Check whether a receipt number is valid.---
                    744: sub verifyreceipt {
                    745:     my $request  = shift;
                    746: 
1.257     albertel  747:     my $courseid = $env{'request.course.id'};
1.184     www       748:     my $receipt  = &Apache::lonnet::recprefix($courseid).'-'.
1.257     albertel  749: 	$env{'form.receipt'};
1.44      ng        750:     $receipt     =~ s/[^\-\d]//g;
1.378     albertel  751:     my ($symb)   = &get_symb($request);
1.44      ng        752: 
1.487     albertel  753:     my $title.=
                    754: 	'<h3><span class="LC_info">'.
1.584     bisitz    755: 	&mt('Verifying Receipt No. [_1]',$receipt).
1.487     albertel  756: 	'</span></h3>'."\n".
                    757: 	'<h4>'.&mt('<b>Resource: </b>[_1]',$env{'form.probTitle'}).
                    758: 	'</h4>'."\n";
1.44      ng        759: 
                    760:     my ($string,$contents,$matches) = ('','',0);
1.56      matthew   761:     my (undef,undef,$fullname) = &getclasslist('all','0');
1.177     albertel  762:     
                    763:     my $receiptparts=0;
1.390     albertel  764:     if ($env{"course.$courseid.receiptalg"} eq 'receipt2' ||
                    765: 	$env{"course.$courseid.receiptalg"} eq 'receipt3') { $receiptparts=1; }
1.177     albertel  766:     my $parts=['0'];
1.582     raeburn   767:     if ($receiptparts) {
                    768:         my $res_error; 
                    769:         ($parts)=&response_type($symb,\$res_error);
                    770:         if ($res_error) {
                    771:             return &navmap_errormsg();
                    772:         } 
                    773:     }
1.486     albertel  774:     
                    775:     my $header = 
                    776: 	&Apache::loncommon::start_data_table().
                    777: 	&Apache::loncommon::start_data_table_header_row().
1.487     albertel  778: 	'<th>&nbsp;'.&mt('Fullname').'&nbsp;</th>'."\n".
                    779: 	'<th>&nbsp;'.&mt('Username').'&nbsp;</th>'."\n".
                    780: 	'<th>&nbsp;'.&mt('Domain').'&nbsp;</th>';
1.486     albertel  781:     if ($receiptparts) {
1.487     albertel  782: 	$header.='<th>&nbsp;'.&mt('Problem Part').'&nbsp;</th>';
1.486     albertel  783:     }
                    784:     $header.=
                    785: 	&Apache::loncommon::end_data_table_header_row();
                    786: 
1.294     albertel  787:     foreach (sort 
                    788: 	     {
                    789: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                    790: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                    791: 		 }
                    792: 		 return $a cmp $b;
                    793: 	     } (keys(%$fullname))) {
1.44      ng        794: 	my ($uname,$udom)=split(/\:/);
1.177     albertel  795: 	foreach my $part (@$parts) {
                    796: 	    if ($receipt eq &Apache::lonnet::ireceipt($uname,$udom,$courseid,$symb,$part)) {
1.486     albertel  797: 		$contents.=
                    798: 		    &Apache::loncommon::start_data_table_row().
                    799: 		    '<td>&nbsp;'."\n".
1.177     albertel  800: 		    '<a href="javascript:viewOneStudent(\''.$uname.'\',\''.$udom.
1.417     albertel  801: 		    '\');" target="_self">'.$$fullname{$_}.'</a>&nbsp;</td>'."\n".
1.177     albertel  802: 		    '<td>&nbsp;'.$uname.'&nbsp;</td>'.
                    803: 		    '<td>&nbsp;'.$udom.'&nbsp;</td>';
                    804: 		if ($receiptparts) {
                    805: 		    $contents.='<td>&nbsp;'.$part.'&nbsp;</td>';
                    806: 		}
1.486     albertel  807: 		$contents.= 
                    808: 		    &Apache::loncommon::end_data_table_row()."\n";
1.177     albertel  809: 		
                    810: 		$matches++;
                    811: 	    }
1.44      ng        812: 	}
                    813:     }
                    814:     if ($matches == 0) {
1.584     bisitz    815:         $string = $title
                    816:                  .'<p class="LC_warning">'
                    817:                  .&mt('No match found for the above receipt number.')
                    818:                  .'</p>';
1.44      ng        819:     } else {
1.324     albertel  820: 	$string = &jscriptNform($symb).$title.
1.487     albertel  821: 	    '<p>'.
1.584     bisitz    822: 	    &mt('The above receipt number matches the following [quant,_1,student].',$matches).
1.487     albertel  823: 	    '</p>'.
1.486     albertel  824: 	    $header.
                    825: 	    $contents.
                    826: 	    &Apache::loncommon::end_data_table()."\n";
1.44      ng        827:     }
1.324     albertel  828:     return $string.&show_grading_menu_form($symb);
1.44      ng        829: }
                    830: 
                    831: #--- This is called by a number of programs.
                    832: #--- Called from the Grading Menu - View/Grade an individual student
                    833: #--- Also called directly when one clicks on the subm button 
                    834: #    on the problem page.
1.30      ng        835: sub listStudents {
1.41      ng        836:     my ($request) = shift;
1.49      albertel  837: 
1.324     albertel  838:     my ($symb) = &get_symb($request);
1.257     albertel  839:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
                    840:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
                    841:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
1.449     banghart  842:     my $getgroup  = $env{'form.group'} eq '' ? 'all' : $env{'form.group'};
1.257     albertel  843:     my $submitonly= $env{'form.submitonly'} eq '' ? 'all' : $env{'form.submitonly'};
1.548     bisitz    844:     my $viewgrade = $env{'form.showgrading'} eq 'yes' ? 'View/Grade/Regrade' : 'View';
1.257     albertel  845:     $env{'form.probTitle'} = $env{'form.probTitle'} eq '' ? 
                    846: 	&Apache::lonnet::gettitle($symb) : $env{'form.probTitle'};
1.49      albertel  847: 
1.548     bisitz    848:     my $result='<h3><span class="LC_info">&nbsp;'
                    849: 	.&mt("$viewgrade Submissions for a Student or a Group of Students")
1.485     albertel  850: 	.'</span></h3>';
1.118     ng        851: 
1.598     www       852:     my ($partlist,$handgrade,$responseType) = &response_type($symb
                    853: #,$res_error
                    854:     );
1.49      albertel  855: 
1.559     raeburn   856:     my %lt = &Apache::lonlocal::texthash (
                    857: 		'multiple' => 'Please select a student or group of students before clicking on the Next button.',
                    858: 		'single'   => 'Please select the student before clicking on the Next button.',
                    859: 	     );
1.597     wenzelju  860:     $request->print(&Apache::lonhtmlcommon::scripttag(<<LISTJAVASCRIPT));
1.110     ng        861:     function checkSelect(checkBox) {
                    862: 	var ctr=0;
                    863: 	var sense="";
                    864: 	if (checkBox.length > 1) {
                    865: 	    for (var i=0; i<checkBox.length; i++) {
                    866: 		if (checkBox[i].checked) {
                    867: 		    ctr++;
                    868: 		}
                    869: 	    }
1.485     albertel  870: 	    sense = '$lt{'multiple'}';
1.110     ng        871: 	} else {
                    872: 	    if (checkBox.checked) {
                    873: 		ctr = 1;
                    874: 	    }
1.485     albertel  875: 	    sense = '$lt{'single'}';
1.110     ng        876: 	}
                    877: 	if (ctr == 0) {
1.485     albertel  878: 	    alert(sense);
1.110     ng        879: 	    return false;
                    880: 	}
                    881: 	document.gradesub.submit();
                    882:     }
                    883: 
                    884:     function reLoadList(formname) {
1.112     ng        885: 	if (formname.saveStatusOld.value == pullDownSelection(formname.Status)) {return;}
1.110     ng        886: 	formname.command.value = 'submission';
                    887: 	formname.submit();
                    888:     }
1.45      ng        889: LISTJAVASCRIPT
                    890: 
1.118     ng        891:     &commonJSfunctions($request);
1.41      ng        892:     $request->print($result);
1.39      ng        893: 
1.401     albertel  894:     my $checkhdgrade = ($env{'form.handgrade'} eq 'yes' && scalar(@$partlist) > 1 ) ? 'checked="checked"' : '';
                    895:     my $checklastsub = $checkhdgrade eq '' ? 'checked="checked"' : '';
1.154     albertel  896:     my $gradeTable='<form action="/adm/grades" method="post" name="gradesub">'.
1.598     www       897: 	"\n";
1.485     albertel  898: 	
1.561     bisitz    899:     $gradeTable .= &Apache::lonhtmlcommon::start_pick_box();
                    900:     $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('View Problem Text'))
                    901:                   .'<label><input type="radio" name="vProb" value="no" checked="checked" /> '.&mt('no').' </label>'."\n"
                    902:                   .'<label><input type="radio" name="vProb" value="yes" /> '.&mt('one student').' </label>'."\n"
                    903:                   .'<label><input type="radio" name="vProb" value="all" /> '.&mt('all students').' </label><br />'."\n"
                    904:                   .&Apache::lonhtmlcommon::row_closure();
                    905:     $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('View Answer'))
                    906:                   .'<label><input type="radio" name="vAns" value="no"  /> '.&mt('no').' </label>'."\n"
                    907:                   .'<label><input type="radio" name="vAns" value="yes" /> '.&mt('one student').' </label>'."\n"
                    908:                   .'<label><input type="radio" name="vAns" value="all" checked="checked" /> '.&mt('all students').' </label><br />'."\n"
                    909:                   .&Apache::lonhtmlcommon::row_closure();
1.485     albertel  910: 
                    911:     my $submission_options;
1.257     albertel  912:     if ($env{'form.handgrade'} eq 'yes' && scalar(@$partlist) > 1) {
1.485     albertel  913: 	$submission_options.=
                    914: 	    '<label><input type="radio" name="lastSub" value="hdgrade" '.$checkhdgrade.' /> '.&mt('essay part only').' </label>'."\n";
1.49      albertel  915:     }
1.442     banghart  916:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
                    917:     my $saveStatus = $stu_status eq '' ? 'Active' : $stu_status;
1.257     albertel  918:     $env{'form.Status'} = $saveStatus;
1.485     albertel  919:     $submission_options.=
1.592     bisitz    920:         '<span class="LC_nobreak">'.
                    921:         '<label><input type="radio" name="lastSub" value="lastonly" '.$checklastsub.' /> '.
                    922:         &mt('last submission only').' </label></span>'."\n".
                    923:         '<span class="LC_nobreak">'.
                    924:         '<label><input type="radio" name="lastSub" value="last" /> '.
                    925:         &mt('last submission &amp; parts info').' </label></span>'."\n".
                    926:         '<span class="LC_nobreak">'.
                    927:         '<label><input type="radio" name="lastSub" value="datesub" /> '.
                    928:         &mt('by dates and submissions').'</label></span>'."\n".
                    929:         '<span class="LC_nobreak">'.
                    930:         '<label><input type="radio" name="lastSub" value="all" /> '.
                    931:         &mt('all details').'</label></span>';
1.561     bisitz    932:     $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('Submissions'))
                    933:                   .$submission_options
                    934:                   .&Apache::lonhtmlcommon::row_closure();
                    935: 
                    936:     $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('Grading Increments'))
                    937:                   .'<select name="increment">'
                    938:                   .'<option value="1">'.&mt('Whole Points').'</option>'
                    939:                   .'<option value=".5">'.&mt('Half Points').'</option>'
                    940:                   .'<option value=".25">'.&mt('Quarter Points').'</option>'
                    941:                   .'<option value=".1">'.&mt('Tenths of a Point').'</option>'
                    942:                   .'</select>'
                    943:                   .&Apache::lonhtmlcommon::row_closure();
1.485     albertel  944: 
                    945:     $gradeTable .= 
1.432     banghart  946:         &build_section_inputs().
1.45      ng        947: 	'<input type="hidden" name="submitonly"  value="'.$submitonly.'" />'."\n".
1.257     albertel  948: 	'<input type="hidden" name="handgrade"   value="'.$env{'form.handgrade'}.'" /><br />'."\n".
                    949: 	'<input type="hidden" name="showgrading" value="'.$env{'form.showgrading'}.'" /><br />'."\n".
                    950: 	'<input type="hidden" name="saveState"   value="'.$env{'form.saveState'}.'" />'."\n".
                    951: 	'<input type="hidden" name="probTitle"   value="'.$env{'form.probTitle'}.'" />'."\n".
1.418     albertel  952: 	'<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.110     ng        953: 	'<input type="hidden" name="saveStatusOld" value="'.$saveStatus.'" />'."\n";
                    954: 
1.257     albertel  955:     if (exists($env{'form.gradingMenu'}) && exists($env{'form.Status'})) {
1.561     bisitz    956: 	$gradeTable .= '<input type="hidden" name="Status" value="'.$stu_status.'" />'."\n";
1.124     ng        957:     } else {
1.561     bisitz    958:         $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('Student Status'))
                    959:                       .&Apache::lonhtmlcommon::StatusOptions(
                    960:                            $saveStatus,undef,1,'javascript:reLoadList(this.form);')
                    961:                       .&Apache::lonhtmlcommon::row_closure();
1.124     ng        962:     }
1.112     ng        963: 
1.561     bisitz    964:     $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('Check For Plagiarism'))
                    965:                   .'<input type="checkbox" name="checkPlag" checked="checked" />'
                    966:                   .&Apache::lonhtmlcommon::row_closure(1)
                    967:                   .&Apache::lonhtmlcommon::end_pick_box();
                    968: 
                    969:     $gradeTable .= '<p>'
                    970:                   .&mt('To '.lc($viewgrade)." a submission or a group of submissions, click on the check box(es) next to the student's name(s). Then click on the Next button.")."\n"
                    971:                   .'<input type="hidden" name="command" value="processGroup" />'
                    972:                   .'</p>';
1.249     albertel  973: 
                    974: # checkall buttons
                    975:     $gradeTable.=&check_script('gradesub', 'stuinfo');
1.110     ng        976:     $gradeTable.='<input type="button" '."\n".
1.589     bisitz    977:         'onclick="javascript:checkSelect(this.form.stuinfo);" '."\n".
                    978:         'value="'.&mt('Next').' &rarr;" /> <br />'."\n";
1.249     albertel  979:     $gradeTable.=&check_buttons();
1.450     banghart  980:     my ($classlist, undef, $fullname) = &getclasslist($getsec,'1',$getgroup);
1.474     albertel  981:     $gradeTable.= &Apache::loncommon::start_data_table().
                    982: 	&Apache::loncommon::start_data_table_header_row();
1.110     ng        983:     my $loop = 0;
                    984:     while ($loop < 2) {
1.485     albertel  985: 	$gradeTable.='<th>'.&mt('No.').'</th><th>'.&mt('Select').'</th>'.
                    986: 	    '<th>'.&nameUserString('header').'&nbsp;'.&mt('Section/Group').'</th>';
1.301     albertel  987: 	if ($env{'form.showgrading'} eq 'yes' 
                    988: 	    && $submitonly ne 'queued'
                    989: 	    && $submitonly ne 'all') {
1.485     albertel  990: 	    foreach my $part (sort(@$partlist)) {
                    991: 		my $display_part=
                    992: 		    &get_display_part((split(/_/,$part))[0],$symb);
                    993: 		$gradeTable.=
                    994: 		    '<th>'.&mt('Part: [_1] Status',$display_part).'</th>';
1.110     ng        995: 	    }
1.301     albertel  996: 	} elsif ($submitonly eq 'queued') {
1.474     albertel  997: 	    $gradeTable.='<th>'.&mt('Queue Status').'&nbsp;</th>';
1.110     ng        998: 	}
                    999: 	$loop++;
1.126     ng       1000: #	$gradeTable.='<td></td>' if ($loop%2 ==1);
1.41      ng       1001:     }
1.474     albertel 1002:     $gradeTable.=&Apache::loncommon::end_data_table_header_row()."\n";
1.41      ng       1003: 
1.45      ng       1004:     my $ctr = 0;
1.294     albertel 1005:     foreach my $student (sort 
                   1006: 			 {
                   1007: 			     if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                   1008: 				 return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                   1009: 			     }
                   1010: 			     return $a cmp $b;
                   1011: 			 }
                   1012: 			 (keys(%$fullname))) {
1.41      ng       1013: 	my ($uname,$udom) = split(/:/,$student);
1.301     albertel 1014: 
1.110     ng       1015: 	my %status = ();
1.301     albertel 1016: 
                   1017: 	if ($submitonly eq 'queued') {
                   1018: 	    my %queue_status = 
                   1019: 		&Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
                   1020: 							$udom,$uname);
                   1021: 	    next if (!defined($queue_status{'gradingqueue'}));
                   1022: 	    $status{'gradingqueue'} = $queue_status{'gradingqueue'};
                   1023: 	}
                   1024: 
                   1025: 	if ($env{'form.showgrading'} eq 'yes' 
                   1026: 	    && $submitonly ne 'queued'
                   1027: 	    && $submitonly ne 'all') {
1.324     albertel 1028: 	    (%status) =&student_gradeStatus($symb,$udom,$uname,$partlist);
1.145     albertel 1029: 	    my $submitted = 0;
1.164     albertel 1030: 	    my $graded = 0;
1.248     albertel 1031: 	    my $incorrect = 0;
1.110     ng       1032: 	    foreach (keys(%status)) {
1.145     albertel 1033: 		$submitted = 1 if ($status{$_} ne 'nothing');
1.248     albertel 1034: 		$graded = 1 if ($status{$_} =~ /^ungraded/);
                   1035: 		$incorrect = 1 if ($status{$_} =~ /^incorrect/);
                   1036: 		
1.110     ng       1037: 		my ($foo,$partid,$foo1) = split(/\./,$_);
                   1038: 		if ($status{'resource.'.$partid.'.submitted_by'} ne '') {
1.145     albertel 1039: 		    $submitted = 0;
1.150     albertel 1040: 		    my ($part)=split(/\./,$partid);
1.110     ng       1041: 		    $gradeTable.='<input type="hidden" name="'.
1.150     albertel 1042: 			$student.':'.$part.':submitted_by" value="'.
1.110     ng       1043: 			$status{'resource.'.$partid.'.submitted_by'}.'" />';
                   1044: 		}
1.41      ng       1045: 	    }
1.248     albertel 1046: 	    
1.156     albertel 1047: 	    next if (!$submitted && ($submitonly eq 'yes' ||
                   1048: 				     $submitonly eq 'incorrect' ||
                   1049: 				     $submitonly eq 'graded'));
1.248     albertel 1050: 	    next if (!$graded && ($submitonly eq 'graded'));
                   1051: 	    next if (!$incorrect && $submitonly eq 'incorrect');
1.41      ng       1052: 	}
1.34      ng       1053: 
1.45      ng       1054: 	$ctr++;
1.249     albertel 1055: 	my $section = $classlist->{$student}->[&Apache::loncoursedata::CL_SECTION()];
1.452     banghart 1056:         my $group = $classlist->{$student}->[&Apache::loncoursedata::CL_GROUP()];
1.104     albertel 1057: 	if ( $perm{'vgr'} eq 'F' ) {
1.474     albertel 1058: 	    if ($ctr%2 ==1) {
                   1059: 		$gradeTable.= &Apache::loncommon::start_data_table_row();
                   1060: 	    }
1.126     ng       1061: 	    $gradeTable.='<td align="right">'.$ctr.'&nbsp;</td>'.
1.563     bisitz   1062:                '<td align="center"><label><input type="checkbox" name="stuinfo" value="'.
1.249     albertel 1063:                $student.':'.$$fullname{$student}.':::SECTION'.$section.
                   1064: 	       ')&nbsp;" />&nbsp;&nbsp;</label></td>'."\n".'<td>'.
                   1065: 	       &nameUserString(undef,$$fullname{$student},$uname,$udom).
1.474     albertel 1066: 	       '&nbsp;'.$section.($group ne '' ?'/'.$group:'').'</td>'."\n";
1.110     ng       1067: 
1.257     albertel 1068: 	    if ($env{'form.showgrading'} eq 'yes' && $submitonly ne 'all') {
1.524     raeburn  1069: 		foreach (sort(keys(%status))) {
1.485     albertel 1070: 		    next if ($_ =~ /^resource.*?submitted_by$/);
                   1071: 		    $gradeTable.='<td align="center">&nbsp;'.&mt($status{$_}).'&nbsp;</td>'."\n";
1.110     ng       1072: 		}
1.41      ng       1073: 	    }
1.126     ng       1074: #	    $gradeTable.='<td></td>' if ($ctr%2 ==1);
1.474     albertel 1075: 	    if ($ctr%2 ==0) {
                   1076: 		$gradeTable.=&Apache::loncommon::end_data_table_row()."\n";
                   1077: 	    }
1.41      ng       1078: 	}
                   1079:     }
1.110     ng       1080:     if ($ctr%2 ==1) {
1.126     ng       1081: 	$gradeTable.='<td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td>';
1.301     albertel 1082: 	    if ($env{'form.showgrading'} eq 'yes' 
                   1083: 		&& $submitonly ne 'queued'
                   1084: 		&& $submitonly ne 'all') {
1.110     ng       1085: 		foreach (@$partlist) {
                   1086: 		    $gradeTable.='<td>&nbsp;</td>';
                   1087: 		}
1.301     albertel 1088: 	    } elsif ($submitonly eq 'queued') {
                   1089: 		$gradeTable.='<td>&nbsp;</td>';
1.110     ng       1090: 	    }
1.474     albertel 1091: 	$gradeTable.=&Apache::loncommon::end_data_table_row();
1.110     ng       1092:     }
                   1093: 
1.474     albertel 1094:     $gradeTable.=&Apache::loncommon::end_data_table()."\n".
1.589     bisitz   1095:         '<input type="button" '.
                   1096:         'onclick="javascript:checkSelect(this.form.stuinfo);" '.
                   1097:         'value="'.&mt('Next').' &rarr;" /></form>'."\n";
1.45      ng       1098:     if ($ctr == 0) {
1.96      albertel 1099: 	my $num_students=(scalar(keys(%$fullname)));
                   1100: 	if ($num_students eq 0) {
1.485     albertel 1101: 	    $gradeTable='<br />&nbsp;<span class="LC_warning">'.&mt('There are no students currently enrolled.').'</span>';
1.96      albertel 1102: 	} else {
1.171     albertel 1103: 	    my $submissions='submissions';
                   1104: 	    if ($submitonly eq 'incorrect') { $submissions = 'incorrect submissions'; }
                   1105: 	    if ($submitonly eq 'graded'   ) { $submissions = 'ungraded submissions'; }
1.301     albertel 1106: 	    if ($submitonly eq 'queued'   ) { $submissions = 'queued submissions'; }
1.398     albertel 1107: 	    $gradeTable='<br />&nbsp;<span class="LC_warning">'.
1.485     albertel 1108: 		&mt('No '.$submissions.' found for this resource for any students. ([_1] students checked for '.$submissions.')',
                   1109: 		    $num_students).
                   1110: 		'</span><br />';
1.96      albertel 1111: 	}
1.46      ng       1112:     } elsif ($ctr == 1) {
1.474     albertel 1113: 	$gradeTable =~ s/type="checkbox"/type="checkbox" checked="checked"/;
1.45      ng       1114:     }
1.324     albertel 1115:     $gradeTable.=&show_grading_menu_form($symb);
1.45      ng       1116:     $request->print($gradeTable);
1.44      ng       1117:     return '';
1.10      ng       1118: }
                   1119: 
1.44      ng       1120: #---- Called from the listStudents routine
1.249     albertel 1121: 
                   1122: sub check_script {
                   1123:     my ($form, $type)=@_;
1.597     wenzelju 1124:     my $chkallscript= &Apache::lonhtmlcommon::scripttag('
1.249     albertel 1125:     function checkall() {
                   1126:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
                   1127:             ele = document.forms.'.$form.'.elements[i];
                   1128:             if (ele.name == "'.$type.'") {
                   1129:             document.forms.'.$form.'.elements[i].checked=true;
                   1130:                                        }
                   1131:         }
                   1132:     }
                   1133: 
                   1134:     function checksec() {
                   1135:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
                   1136:             ele = document.forms.'.$form.'.elements[i];
                   1137:            string = document.forms.'.$form.'.chksec.value;
                   1138:            if
                   1139:           (ele.value.indexOf(":::SECTION"+string)>0) {
                   1140:               document.forms.'.$form.'.elements[i].checked=true;
                   1141:             }
                   1142:         }
                   1143:     }
                   1144: 
                   1145: 
                   1146:     function uncheckall() {
                   1147:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
                   1148:             ele = document.forms.'.$form.'.elements[i];
                   1149:             if (ele.name == "'.$type.'") {
                   1150:             document.forms.'.$form.'.elements[i].checked=false;
                   1151:                                        }
                   1152:         }
                   1153:     }
                   1154: 
1.597     wenzelju 1155: '."\n");
1.249     albertel 1156:     return $chkallscript;
                   1157: }
                   1158: 
                   1159: sub check_buttons {
1.485     albertel 1160:     my $buttons.='<input type="button" onclick="checkall()" value="'.&mt('Check All').'" />';
                   1161:     $buttons.='<input type="button" onclick="uncheckall()" value="'.&mt('Uncheck All').'" />&nbsp;';
                   1162:     $buttons.='<input type="button" onclick="checksec()" value="'.&mt('Check Section/Group').'" />';
1.249     albertel 1163:     $buttons.='<input type="text" size="5" name="chksec" />&nbsp;';
                   1164:     return $buttons;
                   1165: }
                   1166: 
1.44      ng       1167: #     Displays the submissions for one student or a group of students
1.34      ng       1168: sub processGroup {
1.41      ng       1169:     my ($request)  = shift;
                   1170:     my $ctr        = 0;
1.155     albertel 1171:     my @stuchecked = &Apache::loncommon::get_env_multiple('form.stuinfo');
1.41      ng       1172:     my $total      = scalar(@stuchecked)-1;
1.45      ng       1173: 
1.396     banghart 1174:     foreach my $student (@stuchecked) {
                   1175: 	my ($uname,$udom,$fullname) = split(/:/,$student);
1.257     albertel 1176: 	$env{'form.student'}        = $uname;
                   1177: 	$env{'form.userdom'}        = $udom;
                   1178: 	$env{'form.fullname'}       = $fullname;
1.41      ng       1179: 	&submission($request,$ctr,$total);
                   1180: 	$ctr++;
                   1181:     }
                   1182:     return '';
1.35      ng       1183: }
1.34      ng       1184: 
1.44      ng       1185: #------------------------------------------------------------------------------------
                   1186: #
                   1187: #-------------------------- Next few routines handles grading by student, essentially
                   1188: #                           handles essay response type problem/part
                   1189: #
                   1190: #--- Javascript to handle the submission page functionality ---
                   1191: sub sub_page_js {
                   1192:     my $request = shift;
1.539     riegler  1193: 	    my $alertmsg = &mt('A number equal or greater than 0 is expected. Entered value = ');
1.597     wenzelju 1194:     $request->print(&Apache::lonhtmlcommon::scripttag(<<SUBJAVASCRIPT));
1.71      ng       1195:     function updateRadio(formname,id,weight) {
1.125     ng       1196: 	var gradeBox = formname["GD_BOX"+id];
                   1197: 	var radioButton = formname["RADVAL"+id];
                   1198: 	var oldpts = formname["oldpts"+id].value;
1.72      ng       1199: 	var pts = checkSolved(formname,id) == 'update' ? gradeBox.value : oldpts;
1.71      ng       1200: 	gradeBox.value = pts;
                   1201: 	var resetbox = false;
                   1202: 	if (isNaN(pts) || pts < 0) {
1.539     riegler  1203: 	    alert("$alertmsg"+pts);
1.71      ng       1204: 	    for (var i=0; i<radioButton.length; i++) {
                   1205: 		if (radioButton[i].checked) {
                   1206: 		    gradeBox.value = i;
                   1207: 		    resetbox = true;
                   1208: 		}
                   1209: 	    }
                   1210: 	    if (!resetbox) {
                   1211: 		formtextbox.value = "";
                   1212: 	    }
                   1213: 	    return;
1.44      ng       1214: 	}
1.71      ng       1215: 
                   1216: 	if (pts > weight) {
                   1217: 	    var resp = confirm("You entered a value ("+pts+
                   1218: 			       ") greater than the weight for the part. Accept?");
                   1219: 	    if (resp == false) {
1.125     ng       1220: 		gradeBox.value = oldpts;
1.71      ng       1221: 		return;
                   1222: 	    }
1.44      ng       1223: 	}
1.13      albertel 1224: 
1.71      ng       1225: 	for (var i=0; i<radioButton.length; i++) {
                   1226: 	    radioButton[i].checked=false;
                   1227: 	    if (pts == i && pts != "") {
                   1228: 		radioButton[i].checked=true;
                   1229: 	    }
                   1230: 	}
                   1231: 	updateSelect(formname,id);
1.125     ng       1232: 	formname["stores"+id].value = "0";
1.41      ng       1233:     }
1.5       albertel 1234: 
1.72      ng       1235:     function writeBox(formname,id,pts) {
1.125     ng       1236: 	var gradeBox = formname["GD_BOX"+id];
1.71      ng       1237: 	if (checkSolved(formname,id) == 'update') {
                   1238: 	    gradeBox.value = pts;
                   1239: 	} else {
1.125     ng       1240: 	    var oldpts = formname["oldpts"+id].value;
1.72      ng       1241: 	    gradeBox.value = oldpts;
1.125     ng       1242: 	    var radioButton = formname["RADVAL"+id];
1.71      ng       1243: 	    for (var i=0; i<radioButton.length; i++) {
                   1244: 		radioButton[i].checked=false;
1.72      ng       1245: 		if (i == oldpts) {
1.71      ng       1246: 		    radioButton[i].checked=true;
                   1247: 		}
                   1248: 	    }
1.41      ng       1249: 	}
1.125     ng       1250: 	formname["stores"+id].value = "0";
1.71      ng       1251: 	updateSelect(formname,id);
                   1252: 	return;
1.41      ng       1253:     }
1.44      ng       1254: 
1.71      ng       1255:     function clearRadBox(formname,id) {
                   1256: 	if (checkSolved(formname,id) == 'noupdate') {
                   1257: 	    updateSelect(formname,id);
                   1258: 	    return;
                   1259: 	}
1.125     ng       1260: 	gradeSelect = formname["GD_SEL"+id];
1.71      ng       1261: 	for (var i=0; i<gradeSelect.length; i++) {
                   1262: 	    if (gradeSelect[i].selected) {
                   1263: 		var selectx=i;
                   1264: 	    }
                   1265: 	}
1.125     ng       1266: 	var stores = formname["stores"+id];
1.71      ng       1267: 	if (selectx == stores.value) { return };
1.125     ng       1268: 	var gradeBox = formname["GD_BOX"+id];
1.71      ng       1269: 	gradeBox.value = "";
1.125     ng       1270: 	var radioButton = formname["RADVAL"+id];
1.71      ng       1271: 	for (var i=0; i<radioButton.length; i++) {
                   1272: 	    radioButton[i].checked=false;
                   1273: 	}
                   1274: 	stores.value = selectx;
                   1275:     }
1.5       albertel 1276: 
1.71      ng       1277:     function checkSolved(formname,id) {
1.125     ng       1278: 	if (formname["solved"+id].value == "correct_by_student" && formname.overRideScore.value == 'no') {
1.118     ng       1279: 	    var reply = confirm("This problem has been graded correct by the computer. Do you want to change the score?");
                   1280: 	    if (!reply) {return "noupdate";}
1.120     ng       1281: 	    formname.overRideScore.value = 'yes';
1.41      ng       1282: 	}
1.71      ng       1283: 	return "update";
1.13      albertel 1284:     }
1.71      ng       1285: 
                   1286:     function updateSelect(formname,id) {
1.125     ng       1287: 	formname["GD_SEL"+id][0].selected = true;
1.71      ng       1288: 	return;
1.41      ng       1289:     }
1.33      ng       1290: 
1.121     ng       1291: //=========== Check that a point is assigned for all the parts  ============
1.71      ng       1292:     function checksubmit(formname,val,total,parttot) {
1.121     ng       1293: 	formname.gradeOpt.value = val;
1.71      ng       1294: 	if (val == "Save & Next") {
                   1295: 	    for (i=0;i<=total;i++) {
                   1296: 		for (j=0;j<parttot;j++) {
1.125     ng       1297: 		    var partid = formname["partid"+i+"_"+j].value;
1.127     ng       1298: 		    if (formname["GD_SEL"+i+"_"+partid][0].selected) {
1.125     ng       1299: 			var points = formname["GD_BOX"+i+"_"+partid].value;
1.71      ng       1300: 			if (points == "") {
1.125     ng       1301: 			    var name = formname["name"+i].value;
1.129     ng       1302: 			    var studentID = (name != '' ? name : formname["unamedom"+i].value);
                   1303: 			    var resp = confirm("You did not assign a score for "+studentID+
                   1304: 					       ", part "+partid+". Continue?");
1.71      ng       1305: 			    if (resp == false) {
1.125     ng       1306: 				formname["GD_BOX"+i+"_"+partid].focus();
1.71      ng       1307: 				return false;
                   1308: 			    }
                   1309: 			}
                   1310: 		    }
                   1311: 		    
                   1312: 		}
                   1313: 	    }
                   1314: 	    
                   1315: 	}
1.121     ng       1316: 	if (val == "Grade Student") {
                   1317: 	    formname.showgrading.value = "yes";
                   1318: 	    if (formname.Status.value == "") {
                   1319: 		formname.Status.value = "Active";
                   1320: 	    }
                   1321: 	    formname.studentNo.value = total;
                   1322: 	}
1.120     ng       1323: 	formname.submit();
                   1324:     }
                   1325: 
1.71      ng       1326: //======= Check that a score is assigned for all the problems (page/sequence grading only) =========
                   1327:     function checkSubmitPage(formname,total) {
                   1328: 	noscore = new Array(100);
                   1329: 	var ptr = 0;
                   1330: 	for (i=1;i<total;i++) {
1.125     ng       1331: 	    var partid = formname["q_"+i].value;
1.127     ng       1332: 	    if (formname["GD_SEL"+i+"_"+partid][0].selected) {
1.125     ng       1333: 		var points = formname["GD_BOX"+i+"_"+partid].value;
                   1334: 		var status = formname["solved"+i+"_"+partid].value;
1.71      ng       1335: 		if (points == "" && status != "correct_by_student") {
                   1336: 		    noscore[ptr] = i;
                   1337: 		    ptr++;
                   1338: 		}
                   1339: 	    }
                   1340: 	}
                   1341: 	if (ptr != 0) {
                   1342: 	    var sense = ptr == 1 ? ": " : "s: ";
                   1343: 	    var prolist = "";
                   1344: 	    if (ptr == 1) {
                   1345: 		prolist = noscore[0];
                   1346: 	    } else {
                   1347: 		var i = 0;
                   1348: 		while (i < ptr-1) {
                   1349: 		    prolist += noscore[i]+", ";
                   1350: 		    i++;
                   1351: 		}
                   1352: 		prolist += "and "+noscore[i];
                   1353: 	    }
                   1354: 	    var resp = confirm("You did not assign any score for the following problem"+sense+prolist+". Continue?");
                   1355: 	    if (resp == false) {
                   1356: 		return false;
                   1357: 	    }
                   1358: 	}
1.45      ng       1359: 
1.71      ng       1360: 	formname.submit();
                   1361:     }
                   1362: SUBJAVASCRIPT
                   1363: }
1.45      ng       1364: 
1.71      ng       1365: #--- javascript for essay type problem --
                   1366: sub sub_page_kw_js {
                   1367:     my $request = shift;
1.80      ng       1368:     my $iconpath = $request->dir_config('lonIconsURL');
1.118     ng       1369:     &commonJSfunctions($request);
1.350     albertel 1370: 
1.597     wenzelju 1371:     my $inner_js_msg_central= &Apache::lonhtmlcommon::scripttag(<<INNERJS);
1.350     albertel 1372:     function checkInput() {
                   1373:       opener.document.SCORE.msgsub.value = opener.checkEntities(document.msgcenter.msgsub.value);
                   1374:       var nmsg   = opener.document.SCORE.savemsgN.value;
                   1375:       var usrctr = document.msgcenter.usrctr.value;
                   1376:       var newval = opener.document.SCORE["newmsg"+usrctr];
                   1377:       newval.value = opener.checkEntities(document.msgcenter.newmsg.value);
                   1378: 
                   1379:       var msgchk = "";
                   1380:       if (document.msgcenter.subchk.checked) {
                   1381:          msgchk = "msgsub,";
                   1382:       }
                   1383:       var includemsg = 0;
                   1384:       for (var i=1; i<=nmsg; i++) {
                   1385:           var opnmsg = opener.document.SCORE["savemsg"+i];
                   1386:           var frmmsg = document.msgcenter["msg"+i];
                   1387:           opnmsg.value = opener.checkEntities(frmmsg.value);
                   1388:           var showflg = opener.document.SCORE["shownOnce"+i];
                   1389:           showflg.value = "1";
                   1390:           var chkbox = document.msgcenter["msgn"+i];
                   1391:           if (chkbox.checked) {
                   1392:              msgchk += "savemsg"+i+",";
                   1393:              includemsg = 1;
                   1394:           }
                   1395:       }
                   1396:       if (document.msgcenter.newmsgchk.checked) {
                   1397:          msgchk += "newmsg"+usrctr;
                   1398:          includemsg = 1;
                   1399:       }
                   1400:       imgformname = opener.document.SCORE["mailicon"+usrctr];
                   1401:       imgformname.src = "$iconpath/"+((includemsg) ? "mailto.gif" : "mailbkgrd.gif");
                   1402:       var includemsg = opener.document.SCORE["includemsg"+usrctr];
                   1403:       includemsg.value = msgchk;
                   1404: 
                   1405:       self.close()
                   1406: 
                   1407:     }
                   1408: INNERJS
                   1409: 
1.597     wenzelju 1410:     my $inner_js_highlight_central= &Apache::lonhtmlcommon::scripttag(<<INNERJS);
1.351     albertel 1411:     function updateChoice(flag) {
                   1412:       opener.document.SCORE.kwclr.value = opener.radioSelection(document.hlCenter.kwdclr);
                   1413:       opener.document.SCORE.kwsize.value = opener.radioSelection(document.hlCenter.kwdsize);
                   1414:       opener.document.SCORE.kwstyle.value = opener.radioSelection(document.hlCenter.kwdstyle);
                   1415:       opener.document.SCORE.refresh.value = "on";
                   1416:       if (opener.document.SCORE.keywords.value!=""){
                   1417:          opener.document.SCORE.submit();
                   1418:       }
                   1419:       self.close()
                   1420:     }
                   1421: INNERJS
                   1422: 
                   1423:     my $start_page_msg_central = 
                   1424:         &Apache::loncommon::start_page('Message Central',$inner_js_msg_central,
                   1425: 				       {'js_ready'  => 1,
                   1426: 					'only_body' => 1,
                   1427: 					'bgcolor'   =>'#FFFFFF',});
                   1428:     my $end_page_msg_central = 
                   1429: 	&Apache::loncommon::end_page({'js_ready' => 1});
                   1430: 
                   1431: 
                   1432:     my $start_page_highlight_central = 
                   1433:         &Apache::loncommon::start_page('Highlight Central',
                   1434: 				       $inner_js_highlight_central,
1.350     albertel 1435: 				       {'js_ready'  => 1,
                   1436: 					'only_body' => 1,
                   1437: 					'bgcolor'   =>'#FFFFFF',});
1.351     albertel 1438:     my $end_page_highlight_central = 
1.350     albertel 1439: 	&Apache::loncommon::end_page({'js_ready' => 1});
                   1440: 
1.219     www      1441:     my $docopen=&Apache::lonhtmlcommon::javascript_docopen();
1.236     albertel 1442:     $docopen=~s/^document\.//;
1.539     riegler  1443:     my $alertmsg = &mt('Please select a word or group of words from document and then click this link.');
1.597     wenzelju 1444:     $request->print(&Apache::lonhtmlcommon::scripttag(<<SUBJAVASCRIPT));
1.45      ng       1445: 
1.44      ng       1446: //===================== Show list of keywords ====================
1.122     ng       1447:   function keywords(formname) {
                   1448:     var nret = prompt("Keywords list, separated by a space. Add/delete to list if desired.",formname.keywords.value);
1.44      ng       1449:     if (nret==null) return;
1.122     ng       1450:     formname.keywords.value = nret;
1.44      ng       1451: 
1.122     ng       1452:     if (formname.keywords.value != "") {
1.128     ng       1453: 	formname.refresh.value = "on";
1.122     ng       1454: 	formname.submit();
1.44      ng       1455:     }
                   1456:     return;
                   1457:   }
                   1458: 
                   1459: //===================== Script to view submitted by ==================
                   1460:   function viewSubmitter(submitter) {
                   1461:     document.SCORE.refresh.value = "on";
                   1462:     document.SCORE.NCT.value = "1";
                   1463:     document.SCORE.unamedom0.value = submitter;
                   1464:     document.SCORE.submit();
                   1465:     return;
                   1466:   }
                   1467: 
                   1468: //===================== Script to add keyword(s) ==================
                   1469:   function getSel() {
                   1470:     if (document.getSelection) txt = document.getSelection();
                   1471:     else if (document.selection) txt = document.selection.createRange().text;
                   1472:     else return;
                   1473:     var cleantxt = txt.replace(new RegExp('([\\f\\n\\r\\t\\v ])+', 'g')," ");
                   1474:     if (cleantxt=="") {
1.539     riegler  1475: 	alert("$alertmsg");
1.44      ng       1476: 	return;
                   1477:     }
                   1478:     var nret = prompt("Add selection to keyword list? Edit if desired.",cleantxt);
                   1479:     if (nret==null) return;
1.127     ng       1480:     document.SCORE.keywords.value = document.SCORE.keywords.value+" "+nret;
1.44      ng       1481:     if (document.SCORE.keywords.value != "") {
1.127     ng       1482: 	document.SCORE.refresh.value = "on";
1.44      ng       1483: 	document.SCORE.submit();
                   1484:     }
                   1485:     return;
                   1486:   }
                   1487: 
                   1488: //====================== Script for composing message ==============
1.80      ng       1489:    // preload images
                   1490:    img1 = new Image();
                   1491:    img1.src = "$iconpath/mailbkgrd.gif";
                   1492:    img2 = new Image();
                   1493:    img2.src = "$iconpath/mailto.gif";
                   1494: 
1.44      ng       1495:   function msgCenter(msgform,usrctr,fullname) {
                   1496:     var Nmsg  = msgform.savemsgN.value;
                   1497:     savedMsgHeader(Nmsg,usrctr,fullname);
                   1498:     var subject = msgform.msgsub.value;
1.127     ng       1499:     var msgchk = document.SCORE["includemsg"+usrctr].value;
1.44      ng       1500:     re = /msgsub/;
                   1501:     var shwsel = "";
                   1502:     if (re.test(msgchk)) { shwsel = "checked" }
1.123     ng       1503:     subject = (document.SCORE.shownSub.value == 0 ? checkEntities(subject) : subject);
                   1504:     displaySubject(checkEntities(subject),shwsel);
1.44      ng       1505:     for (var i=1; i<=Nmsg; i++) {
1.123     ng       1506: 	var testmsg = "savemsg"+i+",";
                   1507: 	re = new RegExp(testmsg,"g");
1.44      ng       1508: 	shwsel = "";
                   1509: 	if (re.test(msgchk)) { shwsel = "checked" }
1.125     ng       1510: 	var message = document.SCORE["savemsg"+i].value;
1.126     ng       1511: 	message = (document.SCORE["shownOnce"+i].value == 0 ? checkEntities(message) : message);
1.123     ng       1512: 	displaySavedMsg(i,message,shwsel); //I do not get it. w/o checkEntities on saved messages,
                   1513: 	                                   //any &lt; is already converted to <, etc. However, only once!!
1.44      ng       1514:     }
1.125     ng       1515:     newmsg = document.SCORE["newmsg"+usrctr].value;
1.44      ng       1516:     shwsel = "";
                   1517:     re = /newmsg/;
                   1518:     if (re.test(msgchk)) { shwsel = "checked" }
                   1519:     newMsg(newmsg,shwsel);
                   1520:     msgTail(); 
                   1521:     return;
                   1522:   }
                   1523: 
1.123     ng       1524:   function checkEntities(strx) {
                   1525:     if (strx.length == 0) return strx;
                   1526:     var orgStr = ["&", "<", ">", '"']; 
                   1527:     var newStr = ["&amp;", "&lt;", "&gt;", "&quot;"];
                   1528:     var counter = 0;
                   1529:     while (counter < 4) {
                   1530: 	strx = strReplace(strx,orgStr[counter],newStr[counter]);
                   1531: 	counter++;
                   1532:     }
                   1533:     return strx;
                   1534:   }
                   1535: 
                   1536:   function strReplace(strx, orgStr, newStr) {
                   1537:     return strx.split(orgStr).join(newStr);
                   1538:   }
                   1539: 
1.44      ng       1540:   function savedMsgHeader(Nmsg,usrctr,fullname) {
1.76      ng       1541:     var height = 70*Nmsg+250;
1.44      ng       1542:     var scrollbar = "no";
                   1543:     if (height > 600) {
                   1544: 	height = 600;
                   1545: 	scrollbar = "yes";
                   1546:     }
1.118     ng       1547:     var xpos = (screen.width-600)/2;
                   1548:     xpos = (xpos < 0) ? '0' : xpos;
                   1549:     var ypos = (screen.height-height)/2-30;
                   1550:     ypos = (ypos < 0) ? '0' : ypos;
                   1551: 
1.206     albertel 1552:     pWin = window.open('', 'MessageCenter', 'resizable=yes,toolbar=no,location=no,scrollbars='+scrollbar+',screenx='+xpos+',screeny='+ypos+',width=600,height='+height);
1.76      ng       1553:     pWin.focus();
                   1554:     pDoc = pWin.document;
1.219     www      1555:     pDoc.$docopen;
1.351     albertel 1556:     pDoc.write('$start_page_msg_central');
1.76      ng       1557: 
                   1558:     pDoc.write("<form action=\\"inactive\\" name=\\"msgcenter\\">");
                   1559:     pDoc.write("<input value=\\""+usrctr+"\\" name=\\"usrctr\\" type=\\"hidden\\">");
1.465     albertel 1560:     pDoc.write("<h3><span class=\\"LC_info\\">&nbsp;Compose Message for \"+fullname+\"<\\/span><\\/h3><br /><br />");
1.76      ng       1561: 
1.564     bisitz   1562:     pDoc.write('<table border="0" width="100%"><tr><td bgcolor="#777777">');
                   1563:     pDoc.write('<table border="0" width="100%"><tr bgcolor="#DDFFFF">');
1.465     albertel 1564:     pDoc.write("<td><b>Type<\\/b><\\/td><td><b>Include<\\/b><\\/td><td><b>Message<\\/td><\\/tr>");
1.44      ng       1565: }
                   1566:     function displaySubject(msg,shwsel) {
1.76      ng       1567:     pDoc = pWin.document;
                   1568:     pDoc.write("<tr bgcolor=\\"#ffffdd\\">");
1.465     albertel 1569:     pDoc.write("<td>Subject<\\/td>");
                   1570:     pDoc.write("<td align=\\"center\\"><input name=\\"subchk\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
                   1571:     pDoc.write("<td><input name=\\"msgsub\\" type=\\"text\\" value=\\""+msg+"\\"size=\\"60\\" maxlength=\\"80\\"><\\/td><\\/tr>");
1.44      ng       1572: }
                   1573: 
1.72      ng       1574:   function displaySavedMsg(ctr,msg,shwsel) {
1.76      ng       1575:     pDoc = pWin.document;
                   1576:     pDoc.write("<tr bgcolor=\\"#ffffdd\\">");
1.465     albertel 1577:     pDoc.write("<td align=\\"center\\">"+ctr+"<\\/td>");
                   1578:     pDoc.write("<td align=\\"center\\"><input name=\\"msgn"+ctr+"\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
                   1579:     pDoc.write("<td><textarea name=\\"msg"+ctr+"\\" cols=\\"60\\" rows=\\"3\\">"+msg+"<\\/textarea><\\/td><\\/tr>");
1.44      ng       1580: }
                   1581: 
                   1582:   function newMsg(newmsg,shwsel) {
1.76      ng       1583:     pDoc = pWin.document;
                   1584:     pDoc.write("<tr bgcolor=\\"#ffffdd\\">");
1.465     albertel 1585:     pDoc.write("<td align=\\"center\\">New<\\/td>");
                   1586:     pDoc.write("<td align=\\"center\\"><input name=\\"newmsgchk\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
                   1587:     pDoc.write("<td><textarea name=\\"newmsg\\" cols=\\"60\\" rows=\\"3\\" onchange=\\"javascript:this.form.newmsgchk.checked=true\\" >"+newmsg+"<\\/textarea><\\/td><\\/tr>");
1.44      ng       1588: }
                   1589: 
                   1590:   function msgTail() {
1.76      ng       1591:     pDoc = pWin.document;
1.465     albertel 1592:     pDoc.write("<\\/table>");
                   1593:     pDoc.write("<\\/td><\\/tr><\\/table>&nbsp;");
1.589     bisitz   1594:     pDoc.write("<input type=\\"button\\" value=\\"Save\\" onclick=\\"javascript:checkInput()\\">&nbsp;&nbsp;");
                   1595:     pDoc.write("<input type=\\"button\\" value=\\"Cancel\\" onclick=\\"self.close()\\"><br /><br />");
1.465     albertel 1596:     pDoc.write("<\\/form>");
1.351     albertel 1597:     pDoc.write('$end_page_msg_central');
1.128     ng       1598:     pDoc.close();
1.44      ng       1599: }
                   1600: 
                   1601: //====================== Script for keyword highlight options ==============
                   1602:   function kwhighlight() {
                   1603:     var kwclr    = document.SCORE.kwclr.value;
                   1604:     var kwsize   = document.SCORE.kwsize.value;
                   1605:     var kwstyle  = document.SCORE.kwstyle.value;
                   1606:     var redsel = "";
                   1607:     var grnsel = "";
                   1608:     var blusel = "";
                   1609:     if (kwclr=="red")   {var redsel="checked"};
                   1610:     if (kwclr=="green") {var grnsel="checked"};
                   1611:     if (kwclr=="blue")  {var blusel="checked"};
                   1612:     var sznsel = "";
                   1613:     var sz1sel = "";
                   1614:     var sz2sel = "";
                   1615:     if (kwsize=="0")  {var sznsel="checked"};
                   1616:     if (kwsize=="+1") {var sz1sel="checked"};
                   1617:     if (kwsize=="+2") {var sz2sel="checked"};
                   1618:     var synsel = "";
                   1619:     var syisel = "";
                   1620:     var sybsel = "";
                   1621:     if (kwstyle=="")    {var synsel="checked"};
                   1622:     if (kwstyle=="<i>") {var syisel="checked"};
                   1623:     if (kwstyle=="<b>") {var sybsel="checked"};
                   1624:     highlightCentral();
                   1625:     highlightbody('red','red',redsel,'0','normal',sznsel,'','normal',synsel);
                   1626:     highlightbody('green','green',grnsel,'+1','+1',sz1sel,'<i>','italic',syisel);
                   1627:     highlightbody('blue','blue',blusel,'+2','+2',sz2sel,'<b>','bold',sybsel);
                   1628:     highlightend();
                   1629:     return;
                   1630:   }
                   1631: 
                   1632:   function highlightCentral() {
1.76      ng       1633: //    if (window.hwdWin) window.hwdWin.close();
1.118     ng       1634:     var xpos = (screen.width-400)/2;
                   1635:     xpos = (xpos < 0) ? '0' : xpos;
                   1636:     var ypos = (screen.height-330)/2-30;
                   1637:     ypos = (ypos < 0) ? '0' : ypos;
                   1638: 
1.206     albertel 1639:     hwdWin = window.open('', 'KeywordHighlightCentral', 'resizeable=yes,toolbar=no,location=no,scrollbars=no,width=400,height=300,screenx='+xpos+',screeny='+ypos);
1.76      ng       1640:     hwdWin.focus();
                   1641:     var hDoc = hwdWin.document;
1.219     www      1642:     hDoc.$docopen;
1.351     albertel 1643:     hDoc.write('$start_page_highlight_central');
1.76      ng       1644:     hDoc.write("<form action=\\"inactive\\" name=\\"hlCenter\\">");
1.465     albertel 1645:     hDoc.write("<h3><span class=\\"LC_info\\">&nbsp;Keyword Highlight Options<\\/span><\\/h3><br /><br />");
1.76      ng       1646: 
1.564     bisitz   1647:     hDoc.write('<table border="0" width="100%"><tr><td bgcolor="#777777">');
                   1648:     hDoc.write('<table border="0" width="100%"><tr bgcolor="#DDFFFF">');
1.465     albertel 1649:     hDoc.write("<td><b>Text Color<\\/b><\\/td><td><b>Font Size<\\/b><\\/td><td><b>Font Style<\\/td><\\/tr>");
1.44      ng       1650:   }
                   1651: 
                   1652:   function highlightbody(clrval,clrtxt,clrsel,szval,sztxt,szsel,syval,sytxt,sysel) { 
1.76      ng       1653:     var hDoc = hwdWin.document;
                   1654:     hDoc.write("<tr bgcolor=\\"#ffffdd\\">");
                   1655:     hDoc.write("<td align=\\"left\\">");
1.465     albertel 1656:     hDoc.write("<input name=\\"kwdclr\\" type=\\"radio\\" value=\\""+clrval+"\\" "+clrsel+">&nbsp;"+clrtxt+"<\\/td>");
1.76      ng       1657:     hDoc.write("<td align=\\"left\\">");
1.465     albertel 1658:     hDoc.write("<input name=\\"kwdsize\\" type=\\"radio\\" value=\\""+szval+"\\" "+szsel+">&nbsp;"+sztxt+"<\\/td>");
1.76      ng       1659:     hDoc.write("<td align=\\"left\\">");
1.465     albertel 1660:     hDoc.write("<input name=\\"kwdstyle\\" type=\\"radio\\" value=\\""+syval+"\\" "+sysel+">&nbsp;"+sytxt+"<\\/td>");
                   1661:     hDoc.write("<\\/tr>");
1.44      ng       1662:   }
                   1663: 
                   1664:   function highlightend() { 
1.76      ng       1665:     var hDoc = hwdWin.document;
1.465     albertel 1666:     hDoc.write("<\\/table>");
                   1667:     hDoc.write("<\\/td><\\/tr><\\/table>&nbsp;");
1.589     bisitz   1668:     hDoc.write("<input type=\\"button\\" value=\\"Save\\" onclick=\\"javascript:updateChoice(1)\\">&nbsp;&nbsp;");
                   1669:     hDoc.write("<input type=\\"button\\" value=\\"Cancel\\" onclick=\\"self.close()\\"><br /><br />");
1.465     albertel 1670:     hDoc.write("<\\/form>");
1.351     albertel 1671:     hDoc.write('$end_page_highlight_central');
1.128     ng       1672:     hDoc.close();
1.44      ng       1673:   }
                   1674: 
                   1675: SUBJAVASCRIPT
                   1676: }
                   1677: 
1.349     albertel 1678: sub get_increment {
1.348     bowersj2 1679:     my $increment = $env{'form.increment'};
                   1680:     if ($increment != 1 && $increment != .5 && $increment != .25 &&
                   1681:         $increment != .1) {
                   1682:         $increment = 1;
                   1683:     }
                   1684:     return $increment;
                   1685: }
                   1686: 
1.585     bisitz   1687: sub gradeBox_start {
                   1688:     return (
                   1689:         &Apache::loncommon::start_data_table()
                   1690:        .&Apache::loncommon::start_data_table_header_row()
                   1691:        .'<th>'.&mt('Part').'</th>'
                   1692:        .'<th>'.&mt('Points').'</th>'
                   1693:        .'<th>&nbsp;</th>'
                   1694:        .'<th>'.&mt('Assign Grade').'</th>'
                   1695:        .'<th>'.&mt('Weight').'</th>'
                   1696:        .'<th>'.&mt('Grade Status').'</th>'
                   1697:        .&Apache::loncommon::end_data_table_header_row()
                   1698:     );
                   1699: }
                   1700: 
                   1701: sub gradeBox_end {
                   1702:     return (
                   1703:         &Apache::loncommon::end_data_table()
                   1704:     );
                   1705: }
1.71      ng       1706: #--- displays the grading box, used in essay type problem and grading by page/sequence
                   1707: sub gradeBox {
1.322     albertel 1708:     my ($request,$symb,$uname,$udom,$counter,$partid,$record) = @_;
1.381     albertel 1709:     my $checkIcon = '<img alt="'.&mt('Check Mark').
1.485     albertel 1710: 	'" src="'.&Apache::loncommon::lonhttpdurl($request->dir_config('lonIconsURL').'/check.gif').'" height="16" border="0" />';
1.71      ng       1711:     my $wgt    = &Apache::lonnet::EXT('resource.'.$partid.'.weight',$symb,$udom,$uname);
1.466     albertel 1712:     my $wgtmsg = ($wgt > 0) ? &mt('(problem weight)') 
                   1713:                            : '<span class="LC_info">'.&mt('problem weight assigned by computer').'</span>';
1.71      ng       1714:     $wgt       = ($wgt > 0 ? $wgt : '1');
                   1715:     my $score  = ($$record{'resource.'.$partid.'.awarded'} eq '' ?
1.320     albertel 1716: 		  '' : &compute_points($$record{'resource.'.$partid.'.awarded'},$wgt));
1.71      ng       1717:     my $result='<input type="hidden" name="WGT'.$counter.'_'.$partid.'" value="'.$wgt.'" />'."\n";
1.466     albertel 1718:     my $display_part= &get_display_part($partid,$symb);
1.270     albertel 1719:     my %last_resets = &get_last_resets($symb,$env{'request.course.id'},
                   1720: 				       [$partid]);
                   1721:     my $aggtries = $$record{'resource.'.$partid.'.tries'};
1.269     raeburn  1722:     if ($last_resets{$partid}) {
                   1723:         $aggtries = &get_num_tries($record,$last_resets{$partid},$partid);
                   1724:     }
1.585     bisitz   1725:     $result.=&Apache::loncommon::start_data_table_row();
1.71      ng       1726:     my $ctr = 0;
1.348     bowersj2 1727:     my $thisweight = 0;
1.349     albertel 1728:     my $increment = &get_increment();
1.485     albertel 1729: 
                   1730:     my $radio.='<table border="0"><tr>'."\n";  # display radio buttons in a nice table 10 across
1.348     bowersj2 1731:     while ($thisweight<=$wgt) {
1.532     bisitz   1732: 	$radio.= '<td><span class="LC_nobreak"><label><input type="radio" name="RADVAL'.$counter.'_'.$partid.'" '.
1.589     bisitz   1733:         'onclick="javascript:writeBox(this.form,\''.$counter.'_'.$partid.'\','.
1.348     bowersj2 1734: 	    $thisweight.')" value="'.$thisweight.'" '.
1.401     albertel 1735: 	    ($score eq $thisweight ? 'checked="checked"':'').' /> '.$thisweight."</label></span></td>\n";
1.485     albertel 1736: 	$radio.=(($ctr+1)%10 == 0 ? '</tr><tr>' : '');
1.348     bowersj2 1737:         $thisweight += $increment;
1.71      ng       1738: 	$ctr++;
                   1739:     }
1.485     albertel 1740:     $radio.='</tr></table>';
                   1741: 
                   1742:     my $line.='<input type="text" name="GD_BOX'.$counter.'_'.$partid.'"'.
1.71      ng       1743: 	($score ne ''? ' value = "'.$score.'"':'').' size="4" '.
1.589     bisitz   1744: 	'onchange="javascript:updateRadio(this.form,\''.$counter.'_'.$partid.'\','.
1.71      ng       1745: 	$wgt.')" /></td>'."\n";
1.485     albertel 1746:     $line.='<td>/'.$wgt.' '.$wgtmsg.
1.71      ng       1747: 	($$record{'resource.'.$partid.'.solved'} eq 'correct_by_student' ? '&nbsp;'.$checkIcon : '').
1.585     bisitz   1748: 	' </td>'."\n";
                   1749:     $line.='<td><select name="GD_SEL'.$counter.'_'.$partid.'" '.
1.589     bisitz   1750: 	'onchange="javascript:clearRadBox(this.form,\''.$counter.'_'.$partid.'\')" >'."\n";
1.71      ng       1751:     if ($$record{'resource.'.$partid.'.solved'} eq 'excused') {
1.485     albertel 1752: 	$line.='<option></option>'.
                   1753: 	    '<option value="excused" selected="selected">'.&mt('excused').'</option>';
1.71      ng       1754:     } else {
1.485     albertel 1755: 	$line.='<option selected="selected"></option>'.
                   1756: 	    '<option value="excused" >'.&mt('excused').'</option>';
1.71      ng       1757:     }
1.485     albertel 1758:     $line.='<option value="reset status">'.&mt('reset status').'</option></select>'."\n";
                   1759: 
                   1760: 
                   1761:     $result .= 
1.585     bisitz   1762: 	    '<td>'.$display_part.'</td><td>'.$radio.'</td><td>'.&mt('or').'</td><td>'.$line.'</td>';
                   1763:     $result.=&Apache::loncommon::end_data_table_row();
1.71      ng       1764:     $result.='<input type="hidden" name="stores'.$counter.'_'.$partid.'" value="" />'."\n".
                   1765: 	'<input type="hidden" name="oldpts'.$counter.'_'.$partid.'" value="'.$score.'" />'."\n".
                   1766: 	'<input type="hidden" name="solved'.$counter.'_'.$partid.'" value="'.
1.269     raeburn  1767: 	$$record{'resource.'.$partid.'.solved'}.'" />'."\n".
                   1768:         '<input type="hidden" name="totaltries'.$counter.'_'.$partid.'" value="'.
                   1769:         $$record{'resource.'.$partid.'.tries'}.'" />'."\n".
                   1770:         '<input type="hidden" name="aggtries'.$counter.'_'.$partid.'" value="'.
                   1771:         $aggtries.'" />'."\n";
1.582     raeburn  1772:     my $res_error;
                   1773:     $result.=&handback_box($symb,$uname,$udom,$counter,$partid,$record,\$res_error);
                   1774:     if ($res_error) {
                   1775:         return &navmap_errormsg();
                   1776:     }
1.318     banghart 1777:     return $result;
                   1778: }
1.322     albertel 1779: 
                   1780: sub handback_box {
1.582     raeburn  1781:     my ($symb,$uname,$udom,$counter,$partid,$record,$res_error) = @_;
                   1782:     my ($partlist,$handgrade,$responseType) = &response_type($symb,$res_error);
1.323     banghart 1783:     my (@respids);
1.375     albertel 1784:      my @part_response_id = &flatten_responseType($responseType);
                   1785:     foreach my $part_response_id (@part_response_id) {
                   1786:     	my ($part,$resp) = @{ $part_response_id };
1.323     banghart 1787:         if ($part eq $partid) {
1.375     albertel 1788:             push(@respids,$resp);
1.323     banghart 1789:         }
                   1790:     }
1.318     banghart 1791:     my $result;
1.323     banghart 1792:     foreach my $respid (@respids) {
1.322     albertel 1793: 	my $prefix = $counter.'_'.$partid.'_'.$respid.'_';
                   1794: 	my $files=&get_submitted_files($udom,$uname,$partid,$respid,$record);
                   1795: 	next if (!@$files);
                   1796: 	my $file_counter = 1;
1.313     banghart 1797: 	foreach my $file (@$files) {
1.368     banghart 1798: 	    if ($file =~ /\/portfolio\//) {
                   1799:     	        my ($file_path, $file_disp) = ($file =~ m|(.+/)(.+)$|);
                   1800:     	        my ($name,$version,$ext) = &file_name_version_ext($file_disp);
                   1801:     	        $file_disp = "$name.$ext";
                   1802:     	        $file = $file_path.$file_disp;
                   1803:     	        $result.=&mt('Return commented version of [_1] to student.',
                   1804:     			 '<span class="LC_filename">'.$file_disp.'</span>');
                   1805:     	        $result.='<input type="file"   name="'.$prefix.'returndoc'.$file_counter.'" />'."\n";
                   1806:     	        $result.='<input type="hidden" name="'.$prefix.'origdoc'.$file_counter.'" value="'.$file.'" /><br />';
1.485     albertel 1807:     	        $result.='('.&mt('File will be uploaded when you click on Save &amp; Next below.').')<br />';
1.368     banghart 1808:     	        $file_counter++;
                   1809: 	    }
1.322     albertel 1810: 	}
1.313     banghart 1811:     }
1.318     banghart 1812:     return $result;    
1.71      ng       1813: }
1.44      ng       1814: 
1.58      albertel 1815: sub show_problem {
1.382     albertel 1816:     my ($request,$symb,$uname,$udom,$removeform,$viewon,$mode,$form) = @_;
1.144     albertel 1817:     my $rendered;
1.382     albertel 1818:     my %form = ((ref($form) eq 'HASH')? %{$form} : ());
1.329     albertel 1819:     &Apache::lonxml::remember_problem_counter();
1.144     albertel 1820:     if ($mode eq 'both' or $mode eq 'text') {
                   1821: 	$rendered=&Apache::loncommon::get_student_view($symb,$uname,$udom,
1.382     albertel 1822: 						       $env{'request.course.id'},
                   1823: 						       undef,\%form);
1.144     albertel 1824:     }
1.58      albertel 1825:     if ($removeform) {
                   1826: 	$rendered=~s|<form(.*?)>||g;
                   1827: 	$rendered=~s|</form>||g;
1.374     albertel 1828: 	$rendered=~s|(<input[^>]*name\s*=\s*"?)(\w+)("?)|$1would_have_been_$2$3|g;
1.58      albertel 1829:     }
1.144     albertel 1830:     my $companswer;
                   1831:     if ($mode eq 'both' or $mode eq 'answer') {
1.329     albertel 1832: 	&Apache::lonxml::restore_problem_counter();
1.382     albertel 1833: 	$companswer=
                   1834: 	    &Apache::loncommon::get_student_answers($symb,$uname,$udom,
                   1835: 						    $env{'request.course.id'},
                   1836: 						    %form);
1.144     albertel 1837:     }
1.58      albertel 1838:     if ($removeform) {
                   1839: 	$companswer=~s|<form(.*?)>||g;
                   1840: 	$companswer=~s|</form>||g;
1.144     albertel 1841: 	$companswer=~s|name="submit"|name="would_have_been_submit"|g;
1.58      albertel 1842:     }
1.468     albertel 1843:     $rendered=
1.588     bisitz   1844:         '<div class="LC_Box">'
                   1845:        .'<h3 class="LC_hcell">'.&mt('View of the problem').'</h3>'
                   1846:        .$rendered
                   1847:        .'</div>';
1.468     albertel 1848:     $companswer=
1.588     bisitz   1849:         '<div class="LC_Box">'
                   1850:        .'<h3 class="LC_hcell">'.&mt('Correct answer').'</h3>'
                   1851:        .$companswer
                   1852:        .'</div>';
1.468     albertel 1853:     my $result;
1.144     albertel 1854:     if ($mode eq 'both') {
1.588     bisitz   1855:         $result=$rendered.$companswer;
1.144     albertel 1856:     } elsif ($mode eq 'text') {
1.588     bisitz   1857:         $result=$rendered;
1.144     albertel 1858:     } elsif ($mode eq 'answer') {
1.588     bisitz   1859:         $result=$companswer;
1.144     albertel 1860:     }
1.71      ng       1861:     return $result;
1.58      albertel 1862: }
1.397     albertel 1863: 
1.396     banghart 1864: sub files_exist {
                   1865:     my ($r, $symb) = @_;
                   1866:     my @students = &Apache::loncommon::get_env_multiple('form.stuinfo');
1.397     albertel 1867: 
1.396     banghart 1868:     foreach my $student (@students) {
                   1869:         my ($uname,$udom,$fullname) = split(/:/,$student);
1.397     albertel 1870:         my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},
                   1871: 					      $udom,$uname);
1.396     banghart 1872:         my ($string,$timestamp)= &get_last_submission(\%record);
1.397     albertel 1873:         foreach my $submission (@$string) {
                   1874:             my ($partid,$respid) =
                   1875: 		($submission =~ /^resource\.([^\.]*)\.([^\.]*)\.submission/);
                   1876:             my $files=&get_submitted_files($udom,$uname,$partid,$respid,
                   1877: 					   \%record);
                   1878:             return 1 if (@$files);
1.396     banghart 1879:         }
                   1880:     }
1.397     albertel 1881:     return 0;
1.396     banghart 1882: }
1.397     albertel 1883: 
1.394     banghart 1884: sub download_all_link {
                   1885:     my ($r,$symb) = @_;
1.395     albertel 1886:     my $all_students = 
                   1887: 	join("\n", &Apache::loncommon::get_env_multiple('form.stuinfo'));
                   1888: 
                   1889:     my $parts =
                   1890: 	join("\n",&Apache::loncommon::get_env_multiple('form.vPart'));
                   1891: 
1.394     banghart 1892:     my $identifier = &Apache::loncommon::get_cgi_id();
1.514     raeburn  1893:     &Apache::lonnet::appenv({'cgi.'.$identifier.'.students' => $all_students,
                   1894:                              'cgi.'.$identifier.'.symb' => $symb,
                   1895:                              'cgi.'.$identifier.'.parts' => $parts,});
1.395     albertel 1896:     $r->print('<a href="/cgi-bin/multidownload.pl?'.$identifier.'">'.
                   1897: 	      &mt('Download All Submitted Documents').'</a>');
1.394     banghart 1898:     return
                   1899: }
1.395     albertel 1900: 
1.432     banghart 1901: sub build_section_inputs {
                   1902:     my $section_inputs;
                   1903:     if ($env{'form.section'} eq '') {
                   1904:         $section_inputs .= '<input type="hidden" name="section" value="all" />'."\n";
                   1905:     } else {
                   1906:         my @sections = &Apache::loncommon::get_env_multiple('form.section');
1.434     albertel 1907:         foreach my $section (@sections) {
1.432     banghart 1908:             $section_inputs .= '<input type="hidden" name="section" value="'.$section.'" />'."\n";
                   1909:         }
                   1910:     }
                   1911:     return $section_inputs;
                   1912: }
                   1913: 
1.44      ng       1914: # --------------------------- show submissions of a student, option to grade 
                   1915: sub submission {
                   1916:     my ($request,$counter,$total) = @_;
1.257     albertel 1917:     my ($uname,$udom)     = ($env{'form.student'},$env{'form.userdom'});
                   1918:     $udom = ($udom eq '' ? $env{'user.domain'} : $udom); #has form.userdom changed for a student?
                   1919:     my $usec = &Apache::lonnet::getsection($udom,$uname,$env{'request.course.id'});
                   1920:     $env{'form.fullname'} = &Apache::loncommon::plainname($uname,$udom,'lastname') if $env{'form.fullname'} eq '';
1.324     albertel 1921:     my $symb = &get_symb($request); 
                   1922:     if ($symb eq '') { $request->print("Unable to handle ambiguous references:."); return ''; }
1.104     albertel 1923: 
                   1924:     if (!&canview($usec)) {
1.398     albertel 1925: 	$request->print('<span class="LC_warning">Unable to view requested student.('.
                   1926: 			$uname.':'.$udom.' in section '.$usec.' in course id '.
                   1927: 			$env{'request.course.id'}.')</span>');
1.324     albertel 1928: 	$request->print(&show_grading_menu_form($symb));
1.104     albertel 1929: 	return;
                   1930:     }
                   1931: 
1.257     albertel 1932:     if (!$env{'form.lastSub'}) { $env{'form.lastSub'} = 'datesub'; }
                   1933:     if (!$env{'form.vProb'}) { $env{'form.vProb'} = 'yes'; }
                   1934:     if (!$env{'form.vAns'}) { $env{'form.vAns'} = 'yes'; }
                   1935:     my $last = ($env{'form.lastSub'} eq 'last' ? 'last' : '');
1.381     albertel 1936:     my $checkIcon = '<img alt="'.&mt('Check Mark').
                   1937: 	'" src="'.$request->dir_config('lonIconsURL').
1.122     ng       1938: 	'/check.gif" height="16" border="0" />';
1.41      ng       1939: 
1.426     albertel 1940:     my %old_essays;
1.41      ng       1941:     # header info
                   1942:     if ($counter == 0) {
                   1943: 	&sub_page_js($request);
1.257     albertel 1944: 	&sub_page_kw_js($request) if ($env{'form.handgrade'} eq 'yes');
                   1945: 	$env{'form.probTitle'} = $env{'form.probTitle'} eq '' ? 
                   1946: 	    &Apache::lonnet::gettitle($symb) : $env{'form.probTitle'};
1.397     albertel 1947: 	if ($env{'form.handgrade'} eq 'yes' && &files_exist($request, $symb)) {
1.396     banghart 1948: 	    &download_all_link($request, $symb);
                   1949: 	}
1.485     albertel 1950: 	$request->print('<h3>&nbsp;<span class="LC_info">'.&mt('Submission Record').'</span></h3>'."\n".
                   1951: 			'<h4>&nbsp;'.&mt('<b>Resource: </b> [_1]',$env{'form.probTitle'}).'</h4>'."\n");
1.118     ng       1952: 
1.44      ng       1953: 	# option to display problem, only once else it cause problems 
                   1954:         # with the form later since the problem has a form.
1.257     albertel 1955: 	if ($env{'form.vProb'} eq 'yes' or $env{'form.vAns'} eq 'yes') {
1.144     albertel 1956: 	    my $mode;
1.257     albertel 1957: 	    if ($env{'form.vProb'} eq 'yes' && $env{'form.vAns'} eq 'yes') {
1.144     albertel 1958: 		$mode='both';
1.257     albertel 1959: 	    } elsif ($env{'form.vProb'} eq 'yes') {
1.144     albertel 1960: 		$mode='text';
1.257     albertel 1961: 	    } elsif ($env{'form.vAns'} eq 'yes') {
1.144     albertel 1962: 		$mode='answer';
                   1963: 	    }
1.329     albertel 1964: 	    &Apache::lonxml::clear_problem_counter();
1.144     albertel 1965: 	    $request->print(&show_problem($request,$symb,$uname,$udom,0,1,$mode));
1.41      ng       1966: 	}
1.441     www      1967: 
1.44      ng       1968: 	# kwclr is the only variable that is guaranteed to be non blank 
                   1969:         # if this subroutine has been called once.
1.41      ng       1970: 	my %keyhash = ();
1.257     albertel 1971: 	if ($env{'form.kwclr'} eq '' && $env{'form.handgrade'} eq 'yes') {
1.41      ng       1972: 	    %keyhash = &Apache::lonnet::dump('nohist_handgrade',
1.257     albertel 1973: 					     $env{'course.'.$env{'request.course.id'}.'.domain'},
                   1974: 					     $env{'course.'.$env{'request.course.id'}.'.num'});
1.41      ng       1975: 
1.257     albertel 1976: 	    my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
                   1977: 	    $env{'form.keywords'} = $keyhash{$symb.'_keywords'} ne '' ? $keyhash{$symb.'_keywords'} : '';
                   1978: 	    $env{'form.kwclr'}    = $keyhash{$loginuser.'_kwclr'} ne '' ? $keyhash{$loginuser.'_kwclr'} : 'red';
                   1979: 	    $env{'form.kwsize'}   = $keyhash{$loginuser.'_kwsize'} ne '' ? $keyhash{$loginuser.'_kwsize'} : '0';
                   1980: 	    $env{'form.kwstyle'}  = $keyhash{$loginuser.'_kwstyle'} ne '' ? $keyhash{$loginuser.'_kwstyle'} : '';
                   1981: 	    $env{'form.msgsub'}   = $keyhash{$symb.'_subject'} ne '' ? 
                   1982: 		$keyhash{$symb.'_subject'} : $env{'form.probTitle'};
                   1983: 	    $env{'form.savemsgN'} = $keyhash{$symb.'_savemsgN'} ne '' ? $keyhash{$symb.'_savemsgN'} : '0';
1.41      ng       1984: 	}
1.257     albertel 1985: 	my $overRideScore = $env{'form.overRideScore'} eq '' ? 'no' : $env{'form.overRideScore'};
1.442     banghart 1986: 	my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
1.303     banghart 1987: 	$request->print('<form action="/adm/grades" method="post" name="SCORE" enctype="multipart/form-data">'."\n".
1.41      ng       1988: 			'<input type="hidden" name="command"    value="handgrade" />'."\n".
1.257     albertel 1989: 			'<input type="hidden" name="saveState"  value="'.$env{'form.saveState'}.'" />'."\n".
1.442     banghart 1990: 			'<input type="hidden" name="Status"     value="'.$stu_status.'" />'."\n".
1.120     ng       1991: 			'<input type="hidden" name="overRideScore" value="'.$overRideScore.'" />'."\n".
1.257     albertel 1992: 			'<input type="hidden" name="probTitle"  value="'.$env{'form.probTitle'}.'" />'."\n".
1.41      ng       1993: 			'<input type="hidden" name="refresh"    value="off" />'."\n".
1.120     ng       1994: 			'<input type="hidden" name="studentNo"  value="" />'."\n".
                   1995: 			'<input type="hidden" name="gradeOpt"   value="" />'."\n".
1.418     albertel 1996: 			'<input type="hidden" name="symb"       value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.257     albertel 1997: 			'<input type="hidden" name="showgrading" value="'.$env{'form.showgrading'}.'" />'."\n".
                   1998: 			'<input type="hidden" name="vProb"      value="'.$env{'form.vProb'}.'" />'."\n".
                   1999: 			'<input type="hidden" name="vAns"       value="'.$env{'form.vAns'}.'" />'."\n".
                   2000: 			'<input type="hidden" name="lastSub"    value="'.$env{'form.lastSub'}.'" />'."\n".
1.432     banghart 2001: 			&build_section_inputs().
1.326     albertel 2002: 			'<input type="hidden" name="submitonly" value="'.$env{'form.submitonly'}.'" />'."\n".
                   2003: 			'<input type="hidden" name="handgrade"  value="'.$env{'form.handgrade'}.'" />'."\n".
1.41      ng       2004: 			'<input type="hidden" name="NCT"'.
1.257     albertel 2005: 			' value="'.($env{'form.NTSTU'} ne '' ? $env{'form.NTSTU'} : $total+1).'" />'."\n");
                   2006: 	if ($env{'form.handgrade'} eq 'yes') {
                   2007: 	    $request->print('<input type="hidden" name="keywords" value="'.$env{'form.keywords'}.'" />'."\n".
                   2008: 			    '<input type="hidden" name="kwclr"    value="'.$env{'form.kwclr'}.'" />'."\n".
                   2009: 			    '<input type="hidden" name="kwsize"   value="'.$env{'form.kwsize'}.'" />'."\n".
                   2010: 			    '<input type="hidden" name="kwstyle"  value="'.$env{'form.kwstyle'}.'" />'."\n".
                   2011: 			    '<input type="hidden" name="msgsub"   value="'.$env{'form.msgsub'}.'" />'."\n".
1.123     ng       2012: 			    '<input type="hidden" name="shownSub" value="0" />'."\n".
1.257     albertel 2013: 			    '<input type="hidden" name="savemsgN" value="'.$env{'form.savemsgN'}.'" />'."\n");
1.154     albertel 2014: 	    foreach my $partid (&Apache::loncommon::get_env_multiple('form.vPart')) {
                   2015: 		$request->print('<input type="hidden" name="vPart" value="'.$partid.'" />'."\n");
                   2016: 	    }
1.123     ng       2017: 	}
1.41      ng       2018: 	
                   2019: 	my ($cts,$prnmsg) = (1,'');
1.257     albertel 2020: 	while ($cts <= $env{'form.savemsgN'}) {
1.41      ng       2021: 	    $prnmsg.='<input type="hidden" name="savemsg'.$cts.'" value="'.
1.123     ng       2022: 		(!exists($keyhash{$symb.'_savemsg'.$cts}) ? 
1.257     albertel 2023: 		 &Apache::lonfeedback::clear_out_html($env{'form.savemsg'.$cts}) :
1.80      ng       2024: 		 &Apache::lonfeedback::clear_out_html($keyhash{$symb.'_savemsg'.$cts})).
1.123     ng       2025: 		'" />'."\n".
                   2026: 		'<input type="hidden" name="shownOnce'.$cts.'" value="0" />'."\n";
1.41      ng       2027: 	    $cts++;
                   2028: 	}
                   2029: 	$request->print($prnmsg);
1.32      ng       2030: 
1.257     albertel 2031: 	if ($env{'form.handgrade'} eq 'yes' && $env{'form.showgrading'} eq 'yes') {
1.88      www      2032: #
                   2033: # Print out the keyword options line
                   2034: #
1.41      ng       2035: 	    $request->print(<<KEYWORDS);
1.38      ng       2036: &nbsp;<b>Keyword Options:</b>&nbsp;
1.417     albertel 2037: <a href="javascript:keywords(document.SCORE);" target="_self">List</a>&nbsp; &nbsp;
1.589     bisitz   2038: <a href="#" onmousedown="javascript:getSel(); return false"
1.38      ng       2039:  CLASS="page">Paste Selection to List</a>&nbsp; &nbsp;
1.417     albertel 2040: <a href="javascript:kwhighlight();" target="_self">Highlight Attribute</a><br /><br />
1.38      ng       2041: KEYWORDS
1.88      www      2042: #
                   2043: # Load the other essays for similarity check
                   2044: #
1.324     albertel 2045:             my (undef,undef,$essayurl) = &Apache::lonnet::decode_symb($symb);
1.384     albertel 2046: 	    my ($adom,$aname,$apath)=($essayurl=~/^($LONCAPA::domain_re)\/($LONCAPA::username_re)\/(.*)$/);
1.359     www      2047: 	    $apath=&escape($apath);
1.88      www      2048: 	    $apath=~s/\W/\_/gs;
1.426     albertel 2049: 	    %old_essays=&Apache::lonnet::dump('nohist_essay_'.$apath,$adom,$aname);
1.41      ng       2050:         }
                   2051:     }
1.44      ng       2052: 
1.441     www      2053: # This is where output for one specific student would start
1.592     bisitz   2054:     my $add_class = ($counter%2) ? ' LC_grade_show_user_odd_row' : '';
                   2055:     $request->print(
                   2056:         "\n\n"
                   2057:        .'<div class="LC_grade_show_user'.$add_class.'">'
                   2058:        .'<h2>'.&nameUserString(undef,$env{'form.fullname'},$uname,$udom).'</h2>'
                   2059:        ."\n"
                   2060:     );
1.441     www      2061: 
1.592     bisitz   2062:     # Show additional functions if allowed
                   2063:     if ($perm{'vgr'}) {
                   2064:         $request->print(
                   2065:             &Apache::loncommon::track_student_link(
                   2066:                 &mt('View recent activity'),
                   2067:                 $uname,$udom,'check')
                   2068:            .' '
                   2069:         );
                   2070:     }
                   2071:     if ($perm{'opa'}) {
                   2072:         $request->print(
                   2073:             &Apache::loncommon::pprmlink(
                   2074:                 &mt('Set/Change parameters'),
                   2075:                 $uname,$udom,$symb,'check'));
                   2076:     }
                   2077: 
                   2078:     # Show Problem
1.257     albertel 2079:     if ($env{'form.vProb'} eq 'all' or $env{'form.vAns'} eq 'all') {
1.144     albertel 2080: 	my $mode;
1.257     albertel 2081: 	if ($env{'form.vProb'} eq 'all' && $env{'form.vAns'} eq 'all') {
1.144     albertel 2082: 	    $mode='both';
1.257     albertel 2083: 	} elsif ($env{'form.vProb'} eq 'all' ) {
1.144     albertel 2084: 	    $mode='text';
1.257     albertel 2085: 	} elsif ($env{'form.vAns'} eq 'all') {
1.144     albertel 2086: 	    $mode='answer';
                   2087: 	}
1.329     albertel 2088: 	&Apache::lonxml::clear_problem_counter();
1.475     albertel 2089: 	$request->print(&show_problem($request,$symb,$uname,$udom,1,1,$mode,{'request.prefix' => 'ctr'.$counter}));
1.58      albertel 2090:     }
1.144     albertel 2091: 
1.257     albertel 2092:     my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
1.582     raeburn  2093:     my $res_error;
                   2094:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
                   2095:     if ($res_error) {
                   2096:         $request->print(&navmap_errormsg());
                   2097:         return;
                   2098:     }
1.41      ng       2099: 
1.44      ng       2100:     # Display student info
1.41      ng       2101:     $request->print(($counter == 0 ? '' : '<br />'));
1.590     bisitz   2102: 
                   2103:     my $result='<div class="LC_Box">'
                   2104:               .'<h3 class="LC_hcell">'.&mt('Submissions').'</h3>';
1.45      ng       2105:     $result.='<input type="hidden" name="name'.$counter.
1.588     bisitz   2106:              '" value="'.$env{'form.fullname'}.'" />'."\n";
1.469     albertel 2107:     if ($env{'form.handgrade'} eq 'no') {
1.588     bisitz   2108:         $result.='<p class="LC_info">'
                   2109:                 .&mt('Part(s) graded correct by the computer is marked with a [_1] symbol.',$checkIcon)
                   2110:                 ."</p>\n";
1.469     albertel 2111:     }
                   2112: 
1.118     ng       2113:     # If any part of the problem is an essay-response (handgraded), then check for collaborators
1.464     albertel 2114:     my $fullname;
                   2115:     my $col_fullnames = [];
1.257     albertel 2116:     if ($env{'form.handgrade'} eq 'yes') {
1.464     albertel 2117: 	(my $sub_result,$fullname,$col_fullnames)=
                   2118: 	    &check_collaborators($symb,$uname,$udom,\%record,$handgrade,
                   2119: 				 $counter);
                   2120: 	$result.=$sub_result;
1.41      ng       2121:     }
1.44      ng       2122:     $request->print($result."\n");
1.588     bisitz   2123: 
1.44      ng       2124:     # print student answer/submission
1.588     bisitz   2125:     # Options are (1) Handgraded submission only
1.44      ng       2126:     #             (2) Last submission, includes submission that is not handgraded 
                   2127:     #                  (for multi-response type part)
                   2128:     #             (3) Last submission plus the parts info
                   2129:     #             (4) The whole record for this student
1.257     albertel 2130:     if ($env{'form.lastSub'} =~ /^(lastonly|hdgrade)$/) {
1.151     albertel 2131: 	my ($string,$timestamp)= &get_last_submission(\%record);
1.468     albertel 2132: 	
                   2133: 	my $lastsubonly;
                   2134: 
1.588     bisitz   2135:         if ($$timestamp eq '') {
                   2136:             $lastsubonly.='<div class="LC_grade_submissions_body">'.$$string[0].'</div>'; 
                   2137:         } else {
1.592     bisitz   2138:             $lastsubonly =
                   2139:                 '<div class="LC_grade_submissions_body">'
                   2140:                .'<b>'.&mt('Date Submitted:').'</b> '.$$timestamp."\n";
1.468     albertel 2141: 
1.151     albertel 2142: 	    my %seenparts;
1.375     albertel 2143: 	    my @part_response_id = &flatten_responseType($responseType);
                   2144: 	    foreach my $part (@part_response_id) {
1.393     albertel 2145: 		next if ($env{'form.lastSub'} eq 'hdgrade' 
                   2146: 			 && $$handgrade{$$part[0].'_'.$$part[1]} ne 'yes');
                   2147: 
1.375     albertel 2148: 		my ($partid,$respid) = @{ $part };
1.324     albertel 2149: 		my $display_part=&get_display_part($partid,$symb);
1.257     albertel 2150: 		if ($env{"form.$uname:$udom:$partid:submitted_by"}) {
1.151     albertel 2151: 		    if (exists($seenparts{$partid})) { next; }
                   2152: 		    $seenparts{$partid}=1;
1.207     albertel 2153: 		    my $submitby='<b>Part:</b> '.$display_part.
                   2154: 			' <b>Collaborative submission by:</b> '.
1.151     albertel 2155: 			'<a href="javascript:viewSubmitter(\''.
1.257     albertel 2156: 			$env{"form.$uname:$udom:$partid:submitted_by"}.
1.417     albertel 2157: 			'\');" target="_self">'.
1.257     albertel 2158: 			$$fullname{$env{"form.$uname:$udom:$partid:submitted_by"}}.'</a><br />';
1.151     albertel 2159: 		    $request->print($submitby);
                   2160: 		    next;
                   2161: 		}
                   2162: 		my $responsetype = $responseType->{$partid}->{$respid};
                   2163: 		if (!exists($record{"resource.$partid.$respid.submission"})) {
1.577     bisitz   2164:                     $lastsubonly.="\n".'<div class="LC_grade_submission_part">'.
                   2165:                         '<b>'.&mt('Part: [_1]',$display_part).'</b>'.
                   2166:                         ' <span class="LC_internal_info">'.
1.597     wenzelju 2167:                         '('.&mt('Part ID: [_1]',$respid).')'.
1.577     bisitz   2168:                         '</span>&nbsp; &nbsp;'.
1.539     riegler  2169: 			'<span class="LC_warning">'.&mt('Nothing submitted - no attempts.').'</span><br /><br /></div>';
1.151     albertel 2170: 		    next;
                   2171: 		}
1.468     albertel 2172: 		foreach my $submission (@$string) {
                   2173: 		    my ($partid,$respid) = ($submission =~ /^resource\.([^\.]*)\.([^\.]*)\.submission/);
1.375     albertel 2174: 		    if (join('_',@{$part}) ne ($partid.'_'.$respid)) { next; }
1.596     raeburn  2175: 		    my ($ressub,$hide,$subval) = split(/:/,$submission,3);
1.151     albertel 2176: 		    # Similarity check
                   2177: 		    my $similar='';
1.257     albertel 2178: 		    if($env{'form.checkPlag'}){
1.151     albertel 2179: 			my ($oname,$odom,$ocrsid,$oessay,$osim)=
1.426     albertel 2180: 			    &most_similar($uname,$udom,$subval,\%old_essays);
1.151     albertel 2181: 			if ($osim) {
                   2182: 			    $osim=int($osim*100.0);
1.426     albertel 2183: 			    my %old_course_desc = 
                   2184: 				&Apache::lonnet::coursedescription($ocrsid,
                   2185: 								   {'one_time' => 1});
                   2186: 
1.596     raeburn  2187:                             if ($hide) {
                   2188:                                 $similar='<hr /><span class="LC_warning">'.&mt("Essay was found to be similar to another essay submitted for this assignment.").'<br />'.
                   2189:                                          &mt('As the current submission is for an anonymous survey, no other details are available.').'</span><hr />';
                   2190:                             } else {
                   2191: 			        $similar="<hr /><h3><span class=\"LC_warning\">".
                   2192: 				    &mt('Essay is [_1]% similar to an essay by [_2] in course [_3] (course id [_4]:[_5])',
                   2193: 				        $osim,
                   2194: 				        &Apache::loncommon::plainname($oname,$odom).' ('.$oname.':'.$odom.')',
                   2195: 				        $old_course_desc{'description'},
                   2196: 				        $old_course_desc{'num'},
                   2197: 				        $old_course_desc{'domain'}).
                   2198: 				    '</span></h3><blockquote><i>'.
                   2199: 				    &keywords_highlight($oessay).
                   2200: 				    '</i></blockquote><hr />';
                   2201:                             }
1.151     albertel 2202: 			}
1.150     albertel 2203: 		    }
1.151     albertel 2204: 		    my $order=&get_order($partid,$respid,$symb,$uname,$udom);
1.257     albertel 2205: 		    if ($env{'form.lastSub'} eq 'lastonly' || 
                   2206: 			($env{'form.lastSub'} eq 'hdgrade' && 
1.377     albertel 2207: 			 $$handgrade{$$part[0].'_'.$$part[1]} eq 'yes')) {
1.324     albertel 2208: 			my $display_part=&get_display_part($partid,$symb);
1.577     bisitz   2209:                         $lastsubonly.='<div class="LC_grade_submission_part">'.
                   2210:                             '<b>'.&mt('Part: [_1]',$display_part).'</b>'.
                   2211:                             ' <span class="LC_internal_info">'.
                   2212:                             '('.&mt('Part ID: [_1]',$respid).')'.
1.597     wenzelju 2213:                             '</span>&nbsp; &nbsp;';
1.313     banghart 2214: 			my $files=&get_submitted_files($udom,$uname,$partid,$respid,\%record);
                   2215: 			if (@$files) {
1.596     raeburn  2216:                             if ($hide) {
                   2217:                                 $lastsubonly.='<br />'.&mt('[quant,_1,file] uploaded to this anonymous survey',scalar(@{$files}));
                   2218:                             } else {
                   2219:                                 $lastsubonly.='<br /><span class="LC_warning">'.&mt('Like all files provided by users, this file may contain viruses').'</span><br />';
                   2220:                                 foreach my $file (@$files) {
                   2221:                                     &Apache::lonnet::allowuploaded('/adm/grades',$file);
                   2222:                                     $lastsubonly.='<br /><a href="'.$file.'?rawmode=1" target="lonGRDs"><img src="'.&Apache::loncommon::icon($file).'" border="0" /> '.$file.'</a>';
                   2223:                                 }
                   2224:                             }
1.236     albertel 2225: 			    $lastsubonly.='<br />';
1.41      ng       2226: 			}
1.596     raeburn  2227:                         if ($hide) {
                   2228:                             $lastsubonly.='<b>'.&mt('Anonymous Survey').'</b>'; 
                   2229:                         } else {
                   2230: 			    $lastsubonly.='<b>'.&mt('Submitted Answer:').' </b>'.
                   2231: 			        &cleanRecord($subval,$responsetype,$symb,$partid,
                   2232: 					     $respid,\%record,$order,undef,$uname,$udom);
                   2233:                         }
1.151     albertel 2234: 			if ($similar) {$lastsubonly.="<br /><br />$similar\n";}
1.468     albertel 2235: 			$lastsubonly.='</div>';
1.41      ng       2236: 		    }
                   2237: 		}
                   2238: 	    }
1.588     bisitz   2239: 	    $lastsubonly.='</div>'."\n"; # End: LC_grade_submissions_body
1.151     albertel 2240: 	}
                   2241: 	$request->print($lastsubonly);
1.468     albertel 2242:    } elsif ($env{'form.lastSub'} eq 'datesub') {
1.598     www      2243: #	my (undef,$responseType,undef,$parts) = &showResourceInfo($symb);
                   2244:     my ($parts,$handgrade,$responseType) = &response_type($symb);
                   2245: 
1.148     albertel 2246: 	$request->print(&displaySubByDates($symb,\%record,$parts,$responseType,$checkIcon,$uname,$udom));
1.257     albertel 2247:     } elsif ($env{'form.lastSub'} =~ /^(last|all)$/) {
1.41      ng       2248: 	$request->print(&Apache::loncommon::get_previous_attempt($symb,$uname,$udom,
1.257     albertel 2249: 								 $env{'request.course.id'},
1.44      ng       2250: 								 $last,'.submission',
                   2251: 								 'Apache::grades::keywords_highlight'));
1.41      ng       2252:     }
1.120     ng       2253: 
1.121     ng       2254:     $request->print('<input type="hidden" name="unamedom'.$counter.'" value="'.$uname.':'
                   2255: 	.$udom.'" />'."\n");
1.44      ng       2256:     # return if view submission with no grading option
1.257     albertel 2257:     if ($env{'form.showgrading'} eq '' || (!&canmodify($usec))) {
1.120     ng       2258: 	my $toGrade.='<input type="button" value="Grade Student" '.
1.589     bisitz   2259: 	    'onclick="javascript:checksubmit(this.form,\'Grade Student\',\''
1.417     albertel 2260: 	    .$counter.'\');" target="_self" /> &nbsp;'."\n" if (&canmodify($usec));
1.468     albertel 2261: 	$toGrade.='</div>'."\n";
1.257     albertel 2262: 	if (($env{'form.command'} eq 'submission') || 
                   2263: 	    ($env{'form.command'} eq 'processGroup' && $counter == $total)) {
1.324     albertel 2264: 	    $toGrade.='</form>'.&show_grading_menu_form($symb); 
1.169     albertel 2265: 	}
1.180     albertel 2266: 	$request->print($toGrade);
1.41      ng       2267: 	return;
1.180     albertel 2268:     } else {
1.468     albertel 2269: 	$request->print('</div>'."\n");
1.41      ng       2270:     }
1.33      ng       2271: 
1.121     ng       2272:     # essay grading message center
1.257     albertel 2273:     if ($env{'form.handgrade'} eq 'yes') {
1.468     albertel 2274: 	my $result='<div class="LC_grade_message_center">';
                   2275:     
                   2276: 	$result.='<div class="LC_grade_message_center_header">'.
                   2277: 	    &mt('Send Message').'</div><div class="LC_grade_message_center_body">';
1.257     albertel 2278: 	my ($lastname,$givenn) = split(/,/,$env{'form.fullname'});
1.118     ng       2279: 	my $msgfor = $givenn.' '.$lastname;
1.464     albertel 2280: 	if (scalar(@$col_fullnames) > 0) {
                   2281: 	    my $lastone = pop(@$col_fullnames);
                   2282: 	    $msgfor .= ', '.(join ', ',@$col_fullnames).' and '.$lastone.'.';
1.118     ng       2283: 	}
                   2284: 	$msgfor =~ s/\'/\\'/g; #' stupid emacs - no! javascript
1.468     albertel 2285: 	$result.='<input type="hidden" name="includemsg'.$counter.'" value="" />'."\n".
1.121     ng       2286: 	    '<input type="hidden" name="newmsg'.$counter.'" value="" />'."\n";
                   2287: 	$result.='&nbsp;<a href="javascript:msgCenter(document.SCORE,'.$counter.
1.417     albertel 2288: 	    ',\''.$msgfor.'\');" target="_self">'.
1.464     albertel 2289: 	    &mt('Compose message to student').(scalar(@$col_fullnames) >= 1 ? 's' : '').'</a><label> ('.
1.350     albertel 2290: 	    &mt('incl. grades').' <input type="checkbox" name="withgrades'.$counter.'" /></label>)'.
1.118     ng       2291: 	    '<img src="'.$request->dir_config('lonIconsURL').
                   2292: 	    '/mailbkgrd.gif" width="14" height="10" name="mailicon'.$counter.'" />'."\n".
1.298     www      2293: 	    '<br />&nbsp;('.
1.468     albertel 2294: 	    &mt('Message will be sent when you click on Save &amp; Next below.').")\n";
                   2295: 	$result.='</div></div>';
1.121     ng       2296: 	$request->print($result);
1.118     ng       2297:     }
1.41      ng       2298: 
                   2299:     my %seen = ();
                   2300:     my @partlist;
1.129     ng       2301:     my @gradePartRespid;
1.375     albertel 2302:     my @part_response_id = &flatten_responseType($responseType);
1.585     bisitz   2303:     $request->print(
1.588     bisitz   2304:         '<div class="LC_Box">'
                   2305:        .'<h3 class="LC_hcell">'.&mt('Assign Grades').'</h3>'
1.585     bisitz   2306:     );
1.592     bisitz   2307:     $request->print(&gradeBox_start());
1.375     albertel 2308:     foreach my $part_response_id (@part_response_id) {
                   2309:     	my ($partid,$respid) = @{ $part_response_id };
                   2310: 	my $part_resp = join('_',@{ $part_response_id });
1.322     albertel 2311: 	next if ($seen{$partid} > 0);
1.41      ng       2312: 	$seen{$partid}++;
1.393     albertel 2313: 	next if ($$handgrade{$part_resp} ne 'yes' 
                   2314: 		 && $env{'form.lastSub'} eq 'hdgrade');
1.524     raeburn  2315: 	push(@partlist,$partid);
                   2316: 	push(@gradePartRespid,$partid.'.'.$respid);
1.322     albertel 2317: 	$request->print(&gradeBox($request,$symb,$uname,$udom,$counter,$partid,\%record));
1.41      ng       2318:     }
1.585     bisitz   2319:     $request->print(&gradeBox_end()); # </div>
                   2320:     $request->print('</div>');
1.468     albertel 2321: 
                   2322:     $request->print('<div class="LC_grade_info_links">');
                   2323:     $request->print('</div>');
                   2324: 
1.45      ng       2325:     $result='<input type="hidden" name="partlist'.$counter.
                   2326: 	'" value="'.(join ":",@partlist).'" />'."\n";
1.129     ng       2327:     $result.='<input type="hidden" name="gradePartRespid'.
                   2328: 	'" value="'.(join ":",@gradePartRespid).'" />'."\n" if ($counter == 0);
1.45      ng       2329:     my $ctr = 0;
                   2330:     while ($ctr < scalar(@partlist)) {
                   2331: 	$result.='<input type="hidden" name="partid'.$counter.'_'.$ctr.'" value="'.
                   2332: 	    $partlist[$ctr].'" />'."\n";
                   2333: 	$ctr++;
                   2334:     }
1.468     albertel 2335:     $request->print($result.''."\n");
1.41      ng       2336: 
1.441     www      2337: # Done with printing info for one student
                   2338: 
1.468     albertel 2339:     $request->print('</div>');#LC_grade_show_user
1.441     www      2340: 
                   2341: 
1.41      ng       2342:     # print end of form
                   2343:     if ($counter == $total) {
1.592     bisitz   2344:         my $endform='<br /><hr /><table border="0"><tr><td>'."\n";
1.485     albertel 2345: 	$endform.='<input type="button" value="'.&mt('Save &amp; Next').'" '.
1.589     bisitz   2346: 	    'onclick="javascript:checksubmit(this.form,\'Save & Next\','.
1.417     albertel 2347: 	    $total.','.scalar(@partlist).');" target="_self" /> &nbsp;'."\n";
1.119     ng       2348: 	my $ntstu ='<select name="NTSTU">'.
                   2349: 	    '<option>1</option><option>2</option>'.
                   2350: 	    '<option>3</option><option>5</option>'.
                   2351: 	    '<option>7</option><option>10</option></select>'."\n";
1.257     albertel 2352: 	my $nsel = ($env{'form.NTSTU'} ne '' ? $env{'form.NTSTU'} : '1');
1.401     albertel 2353: 	$ntstu =~ s/<option>$nsel</<option selected="selected">$nsel</;
1.578     raeburn  2354:         $endform.=&mt('[_1]student(s)',$ntstu);
1.485     albertel 2355: 	$endform.='&nbsp;&nbsp;<input type="button" value="'.&mt('Previous').'" '.
1.589     bisitz   2356: 	    'onclick="javascript:checksubmit(this.form,\'Previous\');" target="_self" /> &nbsp;'."\n".
1.485     albertel 2357: 	    '<input type="button" value="'.&mt('Next').'" '.
1.589     bisitz   2358: 	    'onclick="javascript:checksubmit(this.form,\'Next\');" target="_self" /> &nbsp;';
1.592     bisitz   2359:         $endform.='<span class="LC_warning">'.
                   2360:                   &mt('(Next and Previous (student) do not save the scores.)').
                   2361:                   '</span>'."\n" ;
1.349     albertel 2362:         $endform.="<input type='hidden' value='".&get_increment().
1.348     bowersj2 2363:             "' name='increment' />";
1.485     albertel 2364: 	$endform.='</td></tr></table></form>';
1.324     albertel 2365: 	$endform.=&show_grading_menu_form($symb);
1.41      ng       2366: 	$request->print($endform);
                   2367:     }
                   2368:     return '';
1.38      ng       2369: }
                   2370: 
1.464     albertel 2371: sub check_collaborators {
                   2372:     my ($symb,$uname,$udom,$record,$handgrade,$counter) = @_;
                   2373:     my ($result,@col_fullnames);
                   2374:     my ($classlist,undef,$fullname) = &getclasslist('all','0');
                   2375:     foreach my $part (keys(%$handgrade)) {
                   2376: 	my $ncol = &Apache::lonnet::EXT('resource.'.$part.
                   2377: 					'.maxcollaborators',
                   2378: 					$symb,$udom,$uname);
                   2379: 	next if ($ncol <= 0);
                   2380: 	$part =~ s/\_/\./g;
                   2381: 	next if ($record->{'resource.'.$part.'.collaborators'} eq '');
                   2382: 	my (@good_collaborators, @bad_collaborators);
                   2383: 	foreach my $possible_collaborator
                   2384: 	    (split(/,?\s+/,$record->{'resource.'.$part.'.collaborators'})) { 
                   2385: 	    $possible_collaborator =~ s/[\$\^\(\)]//g;
                   2386: 	    next if ($possible_collaborator eq '');
                   2387: 	    my ($co_name,$co_dom) = split(/\@|:/,$possible_collaborator);
                   2388: 	    $co_dom = $udom if (! defined($co_dom) || $co_dom =~ /^domain$/i);
                   2389: 	    next if ($co_name eq $uname && $co_dom eq $udom);
                   2390: 	    # Doing this grep allows 'fuzzy' specification
                   2391: 	    my @matches = grep(/^\Q$co_name\E:\Q$co_dom\E$/i, 
                   2392: 			       keys(%$classlist));
                   2393: 	    if (! scalar(@matches)) {
                   2394: 		push(@bad_collaborators, $possible_collaborator);
                   2395: 	    } else {
                   2396: 		push(@good_collaborators, @matches);
                   2397: 	    }
                   2398: 	}
                   2399: 	if (scalar(@good_collaborators) != 0) {
1.466     albertel 2400: 	    $result.='<br />'.&mt('Collaborators: ');
1.464     albertel 2401: 	    foreach my $name (@good_collaborators) {
                   2402: 		my ($lastname,$givenn) = split(/,/,$$fullname{$name});
                   2403: 		push(@col_fullnames, $givenn.' '.$lastname);
                   2404: 		$result.=$fullname->{$name}.'&nbsp; &nbsp; &nbsp;';
                   2405: 	    }
                   2406: 	    $result.='<br />'."\n";
1.466     albertel 2407: 	    my ($part)=split(/\./,$part);
1.464     albertel 2408: 	    $result.='<input type="hidden" name="collaborator'.$counter.
                   2409: 		'" value="'.$part.':'.(join ':',@good_collaborators).'" />'.
                   2410: 		"\n";
                   2411: 	}
                   2412: 	if (scalar(@bad_collaborators) > 0) {
1.466     albertel 2413: 	    $result.='<div class="LC_warning">';
1.464     albertel 2414: 	    $result.=&mt('This student has submitted [quant,_1,invalid collaborator]: [_2]',scalar(@bad_collaborators),join(', ',@bad_collaborators));
                   2415: 	    $result .= '</div>';
                   2416: 	}         
                   2417: 	if (scalar(@bad_collaborators > $ncol)) {
1.466     albertel 2418: 	    $result .= '<div class="LC_warning">';
1.464     albertel 2419: 	    $result .= &mt('This student has submitted too many '.
                   2420: 		'collaborators.  Maximum is [_1].',$ncol);
                   2421: 	    $result .= '</div>';
                   2422: 	}
                   2423:     }
                   2424:     return ($result,$fullname,\@col_fullnames);
                   2425: }
                   2426: 
1.44      ng       2427: #--- Retrieve the last submission for all the parts
1.38      ng       2428: sub get_last_submission {
1.119     ng       2429:     my ($returnhash)=@_;
1.596     raeburn  2430:     my (@string,$timestamp,%lasthidden);
1.119     ng       2431:     if ($$returnhash{'version'}) {
1.46      ng       2432: 	my %lasthash=();
                   2433: 	my ($version);
1.119     ng       2434: 	for ($version=1;$version<=$$returnhash{'version'};$version++) {
1.397     albertel 2435: 	    foreach my $key (sort(split(/\:/,
                   2436: 					$$returnhash{$version.':keys'}))) {
                   2437: 		$lasthash{$key}=$$returnhash{$version.':'.$key};
                   2438: 		$timestamp = 
1.545     raeburn  2439: 		    &Apache::lonlocal::locallocaltime($$returnhash{$version.':timestamp'});
1.46      ng       2440: 	    }
                   2441: 	}
1.596     raeburn  2442:         my %typeparts;
                   2443:         my $showsurv = 
                   2444:             &Apache::lonnet::allowed('vas',$env{'request.course.id'});
                   2445:         foreach my $key (sort(keys(%lasthash))) {
                   2446:             if ($key =~ /\.type$/) {
                   2447:                 if (($lasthash{$key} eq 'anonsurvey') || 
                   2448:                     ($lasthash{$key} eq 'anonsurveycred')) {
                   2449:                     my ($ign,@parts) = split(/\./,$key);
                   2450:                     pop(@parts);
                   2451:                     unless ($showsurv) {
                   2452:                         my $id = join(',',@parts);
                   2453:                         $typeparts{$ign.'.'.$id} = $lasthash{$key};
                   2454:                     }
                   2455:                     delete($lasthash{$key});
                   2456:                 }
                   2457:             }
                   2458:         }
                   2459:         my @hidden = keys(%typeparts);
1.397     albertel 2460: 	foreach my $key (keys(%lasthash)) {
                   2461: 	    next if ($key !~ /\.submission$/);
1.596     raeburn  2462:             my $hide;
                   2463:             if (@hidden) {
                   2464:                 foreach my $id (@hidden) {
                   2465:                     if ($key =~ /^\Q$id\E/) {
                   2466:                         $hide = 1;
                   2467:                         last;
                   2468:                     }
                   2469:                 }
                   2470:             }
1.397     albertel 2471: 	    my ($partid,$foo) = split(/submission$/,$key);
                   2472: 	    my $draft  = $lasthash{$partid.'awarddetail'} eq 'DRAFT' ?
1.398     albertel 2473: 		'<span class="LC_warning">Draft Copy</span> ' : '';
1.596     raeburn  2474: 	    push(@string, join(':', $key, $hide, $draft.$lasthash{$key}));
1.41      ng       2475: 	}
                   2476:     }
1.397     albertel 2477:     if (!@string) {
                   2478: 	$string[0] =
1.539     riegler  2479: 	    '<span class="LC_warning">'.&mt('Nothing submitted - no attempts.').'</span>';
1.397     albertel 2480:     }
                   2481:     return (\@string,\$timestamp);
1.38      ng       2482: }
1.35      ng       2483: 
1.44      ng       2484: #--- High light keywords, with style choosen by user.
1.38      ng       2485: sub keywords_highlight {
1.44      ng       2486:     my $string    = shift;
1.257     albertel 2487:     my $size      = $env{'form.kwsize'} eq '0' ? '' : 'size='.$env{'form.kwsize'};
                   2488:     my $styleon   = $env{'form.kwstyle'} eq ''  ? '' : $env{'form.kwstyle'};
1.41      ng       2489:     (my $styleoff = $styleon) =~ s/\</\<\//;
1.257     albertel 2490:     my @keylist   = split(/[,\s+]/,$env{'form.keywords'});
1.398     albertel 2491:     foreach my $keyword (@keylist) {
                   2492: 	$string =~ s/\b\Q$keyword\E(\b|\.)/<font color\=$env{'form.kwclr'} $size\>$styleon$keyword$styleoff<\/font>/gi;
1.41      ng       2493:     }
                   2494:     return $string;
1.38      ng       2495: }
1.36      ng       2496: 
1.44      ng       2497: #--- Called from submission routine
1.38      ng       2498: sub processHandGrade {
1.41      ng       2499:     my ($request) = shift;
1.324     albertel 2500:     my $symb   = &get_symb($request);
                   2501:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
1.257     albertel 2502:     my $button = $env{'form.gradeOpt'};
                   2503:     my $ngrade = $env{'form.NCT'};
                   2504:     my $ntstu  = $env{'form.NTSTU'};
1.301     albertel 2505:     my $cdom   = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   2506:     my $cnum   = $env{'course.'.$env{'request.course.id'}.'.num'};
                   2507: 
1.44      ng       2508:     if ($button eq 'Save & Next') {
                   2509: 	my $ctr = 0;
                   2510: 	while ($ctr < $ngrade) {
1.257     albertel 2511: 	    my ($uname,$udom) = split(/:/,$env{'form.unamedom'.$ctr});
1.324     albertel 2512: 	    my ($errorflag,$pts,$wgt) = &saveHandGrade($request,$symb,$uname,$udom,$ctr);
1.71      ng       2513: 	    if ($errorflag eq 'no_score') {
                   2514: 		$ctr++;
                   2515: 		next;
                   2516: 	    }
1.104     albertel 2517: 	    if ($errorflag eq 'not_allowed') {
1.398     albertel 2518: 		$request->print("<span class=\"LC_warning\">Not allowed to modify grades for $uname:$udom</span>");
1.104     albertel 2519: 		$ctr++;
                   2520: 		next;
                   2521: 	    }
1.257     albertel 2522: 	    my $includemsg = $env{'form.includemsg'.$ctr};
1.44      ng       2523: 	    my ($subject,$message,$msgstatus) = ('','','');
1.418     albertel 2524: 	    my $restitle = &Apache::lonnet::gettitle($symb);
                   2525:             my ($feedurl,$showsymb) =
                   2526: 		&get_feedurl_and_symb($symb,$uname,$udom);
                   2527: 	    my $messagetail;
1.62      albertel 2528: 	    if ($includemsg =~ /savemsg|newmsg\Q$ctr\E/) {
1.298     www      2529: 		$subject = $env{'form.msgsub'} if ($includemsg =~ /msgsub/);
1.295     www      2530: 		unless ($subject=~/\w/) { $subject=&mt('Grading Feedback'); }
1.386     raeburn  2531: 		$subject.=' ['.$restitle.']';
1.44      ng       2532: 		my (@msgnum) = split(/,/,$includemsg);
                   2533: 		foreach (@msgnum) {
1.257     albertel 2534: 		    $message.=$env{'form.'.$_} if ($_ =~ /savemsg|newmsg/ && $_ ne '');
1.44      ng       2535: 		}
1.80      ng       2536: 		$message =&Apache::lonfeedback::clear_out_html($message);
1.298     www      2537: 		if ($env{'form.withgrades'.$ctr}) {
                   2538: 		    $message.="\n\nPoint".($pts > 1 ? 's':'').' awarded = '.$pts.' out of '.$wgt;
1.386     raeburn  2539: 		    $messagetail = " for <a href=\"".
1.418     albertel 2540: 		                   $feedurl."?symb=$showsymb\">$env{'form.probTitle'}</a>";
1.386     raeburn  2541: 		}
                   2542: 		$msgstatus = 
                   2543:                     &Apache::lonmsg::user_normal_msg($uname,$udom,$subject,
                   2544: 						     $message.$messagetail,
1.418     albertel 2545:                                                      undef,$feedurl,undef,
1.386     raeburn  2546:                                                      undef,undef,$showsymb,
                   2547:                                                      $restitle);
1.574     bisitz   2548: 		$request->print('<br />'.&mt('Sending message to [_1]',$uname.':'.$udom).': '.
1.296     www      2549: 				$msgstatus);
1.44      ng       2550: 	    }
1.257     albertel 2551: 	    if ($env{'form.collaborator'.$ctr}) {
1.155     albertel 2552: 		my @collabstrs=&Apache::loncommon::get_env_multiple("form.collaborator$ctr");
1.150     albertel 2553: 		foreach my $collabstr (@collabstrs) {
                   2554: 		    my ($part,@collaborators) = split(/:/,$collabstr);
1.310     banghart 2555: 		    foreach my $collaborator (@collaborators) {
1.150     albertel 2556: 			my ($errorflag,$pts,$wgt) = 
1.324     albertel 2557: 			    &saveHandGrade($request,$symb,$collaborator,$udom,$ctr,
1.257     albertel 2558: 					   $env{'form.unamedom'.$ctr},$part);
1.150     albertel 2559: 			if ($errorflag eq 'not_allowed') {
1.362     albertel 2560: 			    $request->print("<span class=\"LC_error\">".&mt('Not allowed to modify grades for [_1]',"$collaborator:$udom")."</span>");
1.150     albertel 2561: 			    next;
1.418     albertel 2562: 			} elsif ($message ne '') {
                   2563: 			    my ($baseurl,$showsymb) = 
                   2564: 				&get_feedurl_and_symb($symb,$collaborator,
                   2565: 						      $udom);
                   2566: 			    if ($env{'form.withgrades'.$ctr}) {
                   2567: 				$messagetail = " for <a href=\"".
1.386     raeburn  2568:                                     $baseurl."?symb=$showsymb\">$env{'form.probTitle'}</a>";
1.150     albertel 2569: 			    }
1.418     albertel 2570: 			    $msgstatus = 
                   2571: 				&Apache::lonmsg::user_normal_msg($collaborator,$udom,$subject,$message.$messagetail,undef,$baseurl,undef,undef,undef,$showsymb,$restitle);
1.104     albertel 2572: 			}
1.44      ng       2573: 		    }
                   2574: 		}
                   2575: 	    }
                   2576: 	    $ctr++;
                   2577: 	}
                   2578:     }
                   2579: 
1.257     albertel 2580:     if ($env{'form.handgrade'} eq 'yes') {
1.119     ng       2581: 	# Keywords sorted in alphabatical order
1.257     albertel 2582: 	my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
1.119     ng       2583: 	my %keyhash = ();
1.257     albertel 2584: 	$env{'form.keywords'}           =~ s/,\s{0,}|\s+/ /g;
                   2585: 	$env{'form.keywords'}           =~ s/^\s+|\s+$//;
                   2586: 	my (@keywords) = sort(split(/\s+/,$env{'form.keywords'}));
                   2587: 	$env{'form.keywords'} = join(' ',@keywords);
                   2588: 	$keyhash{$symb.'_keywords'}     = $env{'form.keywords'};
                   2589: 	$keyhash{$symb.'_subject'}      = $env{'form.msgsub'};
                   2590: 	$keyhash{$loginuser.'_kwclr'}   = $env{'form.kwclr'};
                   2591: 	$keyhash{$loginuser.'_kwsize'}  = $env{'form.kwsize'};
                   2592: 	$keyhash{$loginuser.'_kwstyle'} = $env{'form.kwstyle'};
1.119     ng       2593: 
                   2594: 	# message center - Order of message gets changed. Blank line is eliminated.
1.257     albertel 2595: 	# New messages are saved in env for the next student.
1.119     ng       2596: 	# All messages are saved in nohist_handgrade.db
                   2597: 	my ($ctr,$idx) = (1,1);
1.257     albertel 2598: 	while ($ctr <= $env{'form.savemsgN'}) {
                   2599: 	    if ($env{'form.savemsg'.$ctr} ne '') {
                   2600: 		$keyhash{$symb.'_savemsg'.$idx} = $env{'form.savemsg'.$ctr};
1.119     ng       2601: 		$idx++;
                   2602: 	    }
                   2603: 	    $ctr++;
1.41      ng       2604: 	}
1.119     ng       2605: 	$ctr = 0;
                   2606: 	while ($ctr < $ngrade) {
1.257     albertel 2607: 	    if ($env{'form.newmsg'.$ctr} ne '') {
                   2608: 		$keyhash{$symb.'_savemsg'.$idx} = $env{'form.newmsg'.$ctr};
                   2609: 		$env{'form.savemsg'.$idx} = $env{'form.newmsg'.$ctr};
1.119     ng       2610: 		$idx++;
                   2611: 	    }
                   2612: 	    $ctr++;
1.41      ng       2613: 	}
1.257     albertel 2614: 	$env{'form.savemsgN'} = --$idx;
                   2615: 	$keyhash{$symb.'_savemsgN'} = $env{'form.savemsgN'};
1.119     ng       2616: 	my $putresult = &Apache::lonnet::put
1.301     albertel 2617: 	    ('nohist_handgrade',\%keyhash,$cdom,$cnum);
1.41      ng       2618:     }
1.44      ng       2619:     # Called by Save & Refresh from Highlight Attribute Window
1.257     albertel 2620:     my (undef,undef,$fullname) = &getclasslist($env{'form.section'},'1');
                   2621:     if ($env{'form.refresh'} eq 'on') {
1.86      ng       2622: 	my ($ctr,$total) = (0,0);
                   2623: 	while ($ctr < $ngrade) {
1.257     albertel 2624: 	    $total++ if  $env{'form.unamedom'.$ctr} ne '';
1.86      ng       2625: 	    $ctr++;
                   2626: 	}
1.257     albertel 2627: 	$env{'form.NTSTU'}=$ngrade;
1.86      ng       2628: 	$ctr = 0;
                   2629: 	while ($ctr < $total) {
1.257     albertel 2630: 	    my $processUser = $env{'form.unamedom'.$ctr};
                   2631: 	    ($env{'form.student'},$env{'form.userdom'}) = split(/:/,$processUser);
                   2632: 	    $env{'form.fullname'} = $$fullname{$processUser};
1.86      ng       2633: 	    &submission($request,$ctr,$total-1);
1.41      ng       2634: 	    $ctr++;
                   2635: 	}
                   2636: 	return '';
                   2637:     }
1.36      ng       2638: 
1.121     ng       2639: # Go directly to grade student - from submission or link from chart page
1.120     ng       2640:     if ($button eq 'Grade Student') {
1.598     www      2641: #	(undef,undef,$env{'form.handgrade'},undef,undef) = &showResourceInfo($symb);
1.257     albertel 2642: 	my $processUser = $env{'form.unamedom'.$env{'form.studentNo'}};
                   2643: 	($env{'form.student'},$env{'form.userdom'}) = split(/:/,$processUser);
                   2644: 	$env{'form.fullname'} = $$fullname{$processUser};
1.120     ng       2645: 	&submission($request,0,0);
                   2646: 	return '';
                   2647:     }
                   2648: 
1.44      ng       2649:     # Get the next/previous one or group of students
1.257     albertel 2650:     my $firststu = $env{'form.unamedom0'};
                   2651:     my $laststu = $env{'form.unamedom'.($ngrade-1)};
1.119     ng       2652:     my $ctr = 2;
1.41      ng       2653:     while ($laststu eq '') {
1.257     albertel 2654: 	$laststu  = $env{'form.unamedom'.($ngrade-$ctr)};
1.41      ng       2655: 	$ctr++;
                   2656: 	$laststu = $firststu if ($ctr > $ngrade);
                   2657:     }
1.44      ng       2658: 
1.41      ng       2659:     my (@parsedlist,@nextlist);
                   2660:     my ($nextflg) = 0;
1.524     raeburn  2661:     foreach my $item (sort 
1.294     albertel 2662: 	     {
                   2663: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                   2664: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                   2665: 		 }
                   2666: 		 return $a cmp $b;
                   2667: 	     } (keys(%$fullname))) {
1.41      ng       2668: 	if ($nextflg == 1 && $button =~ /Next$/) {
1.524     raeburn  2669: 	    push(@parsedlist,$item);
1.41      ng       2670: 	}
1.524     raeburn  2671: 	$nextflg = 1 if ($item eq $laststu);
1.41      ng       2672: 	if ($button eq 'Previous') {
1.524     raeburn  2673: 	    last if ($item eq $firststu);
                   2674: 	    push(@parsedlist,$item);
1.41      ng       2675: 	}
                   2676:     }
                   2677:     $ctr = 0;
                   2678:     @parsedlist = reverse @parsedlist if ($button eq 'Previous');
1.582     raeburn  2679:     my $res_error;
                   2680:     my ($partlist) = &response_type($symb,\$res_error);
                   2681:     if ($res_error) {
                   2682:         $request->print(&navmap_errormsg());
                   2683:         return;
                   2684:     }
1.41      ng       2685:     foreach my $student (@parsedlist) {
1.257     albertel 2686: 	my $submitonly=$env{'form.submitonly'};
1.41      ng       2687: 	my ($uname,$udom) = split(/:/,$student);
1.301     albertel 2688: 	
                   2689: 	if ($submitonly eq 'queued') {
                   2690: 	    my %queue_status = 
                   2691: 		&Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
                   2692: 							$udom,$uname);
                   2693: 	    next if (!defined($queue_status{'gradingqueue'}));
                   2694: 	}
                   2695: 
1.156     albertel 2696: 	if ($submitonly =~ /^(yes|graded|incorrect)$/) {
1.257     albertel 2697: #	    my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
1.324     albertel 2698: 	    my %status=&student_gradeStatus($symb,$udom,$uname,$partlist);
1.145     albertel 2699: 	    my $submitted = 0;
1.248     albertel 2700: 	    my $ungraded = 0;
                   2701: 	    my $incorrect = 0;
1.524     raeburn  2702: 	    foreach my $item (keys(%status)) {
                   2703: 		$submitted = 1 if ($status{$item} ne 'nothing');
                   2704: 		$ungraded = 1 if ($status{$item} =~ /^ungraded/);
                   2705: 		$incorrect = 1 if ($status{$item} =~ /^incorrect/);
                   2706: 		my ($foo,$partid,$foo1) = split(/\./,$item);
1.145     albertel 2707: 		if ($status{'resource.'.$partid.'.submitted_by'} ne '') {
                   2708: 		    $submitted = 0;
                   2709: 		}
1.41      ng       2710: 	    }
1.156     albertel 2711: 	    next if (!$submitted && ($submitonly eq 'yes' ||
                   2712: 				     $submitonly eq 'incorrect' ||
                   2713: 				     $submitonly eq 'graded'));
1.248     albertel 2714: 	    next if (!$ungraded && ($submitonly eq 'graded'));
                   2715: 	    next if (!$incorrect && $submitonly eq 'incorrect');
1.41      ng       2716: 	}
1.524     raeburn  2717: 	push(@nextlist,$student) if ($ctr < $ntstu);
1.129     ng       2718: 	last if ($ctr == $ntstu);
1.41      ng       2719: 	$ctr++;
                   2720:     }
1.36      ng       2721: 
1.41      ng       2722:     $ctr = 0;
                   2723:     my $total = scalar(@nextlist)-1;
1.39      ng       2724: 
1.524     raeburn  2725:     foreach (sort(@nextlist)) {
1.41      ng       2726: 	my ($uname,$udom,$submitter) = split(/:/);
1.257     albertel 2727: 	$env{'form.student'}  = $uname;
                   2728: 	$env{'form.userdom'}  = $udom;
                   2729: 	$env{'form.fullname'} = $$fullname{$_};
1.41      ng       2730: 	&submission($request,$ctr,$total);
                   2731: 	$ctr++;
                   2732:     }
                   2733:     if ($total < 0) {
1.485     albertel 2734: 	my $the_end = '<h3><span class="LC_info">'.&mt('LON-CAPA User Message').'</span></h3><br />'."\n";
                   2735: 	$the_end.=&mt('<b>Message: </b> No more students for this section or class.').'<br /><br />'."\n";
                   2736: 	$the_end.=&mt('Click on the button below to return to the grading menu.').'<br /><br />'."\n";
1.324     albertel 2737: 	$the_end.=&show_grading_menu_form($symb);
1.41      ng       2738: 	$request->print($the_end);
                   2739:     }
                   2740:     return '';
1.38      ng       2741: }
1.36      ng       2742: 
1.44      ng       2743: #---- Save the score and award for each student, if changed
1.38      ng       2744: sub saveHandGrade {
1.324     albertel 2745:     my ($request,$symb,$stuname,$domain,$newflg,$submitter,$part) = @_;
1.342     banghart 2746:     my @version_parts;
1.104     albertel 2747:     my $usec = &Apache::lonnet::getsection($domain,$stuname,
1.257     albertel 2748: 					   $env{'request.course.id'});
1.104     albertel 2749:     if (!&canmodify($usec)) { return('not_allowed'); }
1.337     banghart 2750:     my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$domain,$stuname);
1.251     banghart 2751:     my @parts_graded;
1.77      ng       2752:     my %newrecord  = ();
                   2753:     my ($pts,$wgt) = ('','');
1.269     raeburn  2754:     my %aggregate = ();
                   2755:     my $aggregateflag = 0;
1.301     albertel 2756:     my @parts = split(/:/,$env{'form.partlist'.$newflg});
                   2757:     foreach my $new_part (@parts) {
1.337     banghart 2758: 	#collaborator ($submi may vary for different parts
1.259     banghart 2759: 	if ($submitter && $new_part ne $part) { next; }
                   2760: 	my $dropMenu = $env{'form.GD_SEL'.$newflg.'_'.$new_part};
1.125     ng       2761: 	if ($dropMenu eq 'excused') {
1.259     banghart 2762: 	    if ($record{'resource.'.$new_part.'.solved'} ne 'excused') {
                   2763: 		$newrecord{'resource.'.$new_part.'.solved'} = 'excused';
                   2764: 		if (exists($record{'resource.'.$new_part.'.awarded'})) {
                   2765: 		    $newrecord{'resource.'.$new_part.'.awarded'} = '';
1.58      albertel 2766: 		}
1.364     banghart 2767: 	        $newrecord{'resource.'.$new_part.'.regrader'}="$env{'user.name'}:$env{'user.domain'}";
1.58      albertel 2768: 	    }
1.125     ng       2769: 	} elsif ($dropMenu eq 'reset status'
1.259     banghart 2770: 		 && exists($record{'resource.'.$new_part.'.solved'})) { #don't bother if no old records -> no attempts
1.524     raeburn  2771: 	    foreach my $key (keys(%record)) {
1.259     banghart 2772: 		if ($key=~/^resource\.\Q$new_part\E\./) { $newrecord{$key} = ''; }
1.197     albertel 2773: 	    }
1.259     banghart 2774: 	    $newrecord{'resource.'.$new_part.'.regrader'}=
1.257     albertel 2775: 		"$env{'user.name'}:$env{'user.domain'}";
1.270     albertel 2776:             my $totaltries = $record{'resource.'.$part.'.tries'};
                   2777: 
                   2778:             my %last_resets = &get_last_resets($symb,$env{'request.course.id'},
                   2779: 					       [$new_part]);
                   2780:             my $aggtries =$totaltries;
1.269     raeburn  2781:             if ($last_resets{$new_part}) {
1.270     albertel 2782:                 $aggtries = &get_num_tries(\%record,$last_resets{$new_part},
                   2783: 					   $new_part);
1.269     raeburn  2784:             }
1.270     albertel 2785: 
                   2786:             my $solvedstatus = $record{'resource.'.$new_part.'.solved'};
1.269     raeburn  2787:             if ($aggtries > 0) {
1.327     albertel 2788:                 &decrement_aggs($symb,$new_part,\%aggregate,$aggtries,$totaltries,$solvedstatus);
1.269     raeburn  2789:                 $aggregateflag = 1;
                   2790:             }
1.125     ng       2791: 	} elsif ($dropMenu eq '') {
1.259     banghart 2792: 	    $pts = ($env{'form.GD_BOX'.$newflg.'_'.$new_part} ne '' ? 
                   2793: 		    $env{'form.GD_BOX'.$newflg.'_'.$new_part} : 
                   2794: 		    $env{'form.RADVAL'.$newflg.'_'.$new_part});
                   2795: 	    if ($pts eq '' && $env{'form.GD_SEL'.$newflg.'_'.$new_part} eq '') {
1.153     albertel 2796: 		next;
                   2797: 	    }
1.259     banghart 2798: 	    $wgt = $env{'form.WGT'.$newflg.'_'.$new_part} eq '' ? 1 : 
                   2799: 		$env{'form.WGT'.$newflg.'_'.$new_part};
1.41      ng       2800: 	    my $partial= $pts/$wgt;
1.259     banghart 2801: 	    if ($partial eq $record{'resource.'.$new_part.'.awarded'}) {
1.153     albertel 2802: 		#do not update score for part if not changed.
1.346     banghart 2803:                 &handback_files($request,$symb,$stuname,$domain,$newflg,$new_part,\%newrecord);
1.153     albertel 2804: 		next;
1.251     banghart 2805: 	    } else {
1.524     raeburn  2806: 	        push(@parts_graded,$new_part);
1.153     albertel 2807: 	    }
1.259     banghart 2808: 	    if ($record{'resource.'.$new_part.'.awarded'} ne $partial) {
                   2809: 		$newrecord{'resource.'.$new_part.'.awarded'}  = $partial;
1.153     albertel 2810: 	    }
1.259     banghart 2811: 	    my $reckey = 'resource.'.$new_part.'.solved';
1.41      ng       2812: 	    if ($partial == 0) {
1.153     albertel 2813: 		if ($record{$reckey} ne 'incorrect_by_override') {
                   2814: 		    $newrecord{$reckey} = 'incorrect_by_override';
                   2815: 		}
1.41      ng       2816: 	    } else {
1.153     albertel 2817: 		if ($record{$reckey} ne 'correct_by_override') {
                   2818: 		    $newrecord{$reckey} = 'correct_by_override';
                   2819: 		}
                   2820: 	    }	    
                   2821: 	    if ($submitter && 
1.259     banghart 2822: 		($record{'resource.'.$new_part.'.submitted_by'} ne $submitter)) {
                   2823: 		$newrecord{'resource.'.$new_part.'.submitted_by'} = $submitter;
1.41      ng       2824: 	    }
1.259     banghart 2825: 	    $newrecord{'resource.'.$new_part.'.regrader'}=
1.257     albertel 2826: 		"$env{'user.name'}:$env{'user.domain'}";
1.41      ng       2827: 	}
1.259     banghart 2828: 	# unless problem has been graded, set flag to version the submitted files
1.305     banghart 2829: 	unless ($record{'resource.'.$new_part.'.solved'} =~ /^correct_/  || 
                   2830: 	        $record{'resource.'.$new_part.'.solved'} eq 'incorrect_by_override' ||
                   2831: 	        $dropMenu eq 'reset status')
                   2832: 	   {
1.524     raeburn  2833: 	    push(@version_parts,$new_part);
1.259     banghart 2834: 	}
1.41      ng       2835:     }
1.301     albertel 2836:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   2837:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   2838: 
1.344     albertel 2839:     if (%newrecord) {
                   2840:         if (@version_parts) {
1.364     banghart 2841:             my @changed_keys = &version_portfiles(\%record, \@parts_graded, 
                   2842:                                 $env{'request.course.id'}, $symb, $domain, $stuname, \@version_parts);
1.344     albertel 2843: 	    @newrecord{@changed_keys} = @record{@changed_keys};
1.367     albertel 2844: 	    foreach my $new_part (@version_parts) {
                   2845: 		&handback_files($request,$symb,$stuname,$domain,$newflg,
                   2846: 				$new_part,\%newrecord);
                   2847: 	    }
1.259     banghart 2848:         }
1.44      ng       2849: 	&Apache::lonnet::cstore(\%newrecord,$symb,
1.257     albertel 2850: 				$env{'request.course.id'},$domain,$stuname);
1.380     albertel 2851: 	&check_and_remove_from_queue(\@parts,\%record,\%newrecord,$symb,
                   2852: 				     $cdom,$cnum,$domain,$stuname);
1.41      ng       2853:     }
1.269     raeburn  2854:     if ($aggregateflag) {
                   2855:         &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
1.301     albertel 2856: 			      $cdom,$cnum);
1.269     raeburn  2857:     }
1.301     albertel 2858:     return ('',$pts,$wgt);
1.36      ng       2859: }
1.322     albertel 2860: 
1.380     albertel 2861: sub check_and_remove_from_queue {
                   2862:     my ($parts,$record,$newrecord,$symb,$cdom,$cnum,$domain,$stuname) = @_;
                   2863:     my @ungraded_parts;
                   2864:     foreach my $part (@{$parts}) {
                   2865: 	if (    $record->{   'resource.'.$part.'.awarded'} eq ''
                   2866: 	     && $record->{   'resource.'.$part.'.solved' } ne 'excused'
                   2867: 	     && $newrecord->{'resource.'.$part.'.awarded'} eq ''
                   2868: 	     && $newrecord->{'resource.'.$part.'.solved' } ne 'excused'
                   2869: 		) {
                   2870: 	    push(@ungraded_parts, $part);
                   2871: 	}
                   2872:     }
                   2873:     if ( !@ungraded_parts ) {
                   2874: 	&Apache::bridgetask::remove_from_queue('gradingqueue',$symb,$cdom,
                   2875: 					       $cnum,$domain,$stuname);
                   2876:     }
                   2877: }
                   2878: 
1.337     banghart 2879: sub handback_files {
                   2880:     my ($request,$symb,$stuname,$domain,$newflg,$new_part,$newrecord) = @_;
1.517     raeburn  2881:     my $portfolio_root = '/userfiles/portfolio';
1.582     raeburn  2882:     my $res_error;
                   2883:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
                   2884:     if ($res_error) {
                   2885:         $request->print('<br />'.&navmap_errormsg().'<br />');
                   2886:         return;
                   2887:     }
1.375     albertel 2888:     my @part_response_id = &flatten_responseType($responseType);
                   2889:     foreach my $part_response_id (@part_response_id) {
                   2890:     	my ($part_id,$resp_id) = @{ $part_response_id };
                   2891: 	my $part_resp = join('_',@{ $part_response_id });
1.337     banghart 2892:             if (($env{'form.'.$newflg.'_'.$part_resp.'_returndoc1'}) && ($new_part == $part_id)) {
                   2893:                 # if multiple files are uploaded names will be 'returndoc2','returndoc3'
                   2894:                 my $file_counter = 1;
1.367     albertel 2895: 		my $file_msg;
1.337     banghart 2896:                 while ($env{'form.'.$newflg.'_'.$part_resp.'_returndoc'.$file_counter}) {
                   2897:                     my $fname=$env{'form.'.$newflg.'_'.$part_resp.'_returndoc'.$file_counter.'.filename'};
1.338     banghart 2898:                     my ($directory,$answer_file) = 
                   2899:                         ($env{'form.'.$newflg.'_'.$part_resp.'_origdoc'.$file_counter} =~ /^(.*?)([^\/]*)$/);
                   2900:                     my ($answer_name,$answer_ver,$answer_ext) =
                   2901: 		        &file_name_version_ext($answer_file);
1.355     banghart 2902: 		    my ($portfolio_path) = ($directory =~ /^.+$stuname\/portfolio(.*)/);
1.517     raeburn  2903:                     my $getpropath = 1;
                   2904: 		    my @dir_list = &Apache::lonnet::dirlist($portfolio_root.$portfolio_path,$domain,$stuname,$getpropath);
1.338     banghart 2905: 		    my $version = &get_next_version($answer_name, $answer_ext, \@dir_list);
1.355     banghart 2906:                     # fix file name
                   2907:                     my ($save_file_name) = (($directory.$answer_name.".$version.".$answer_ext) =~ /^.+\/${stuname}\/(.*)/);
                   2908:                     my $result=&Apache::lonnet::finishuserfileupload($stuname,$domain,
                   2909:             	                                $newflg.'_'.$part_resp.'_returndoc'.$file_counter,
                   2910:             	                                $save_file_name);
1.337     banghart 2911:                     if ($result !~ m|^/uploaded/|) {
1.536     raeburn  2912:                         $request->print('<br /><span class="LC_error">'.
                   2913:                             &mt('An error occurred ([_1]) while trying to upload [_2].',
                   2914:                                 $result,$newflg.'_'.$part_resp.'_returndoc'.$file_counter).
                   2915:                                         '</span>');
1.356     banghart 2916:                     } else {
1.360     banghart 2917:                         # mark the file as read only
                   2918:                         my @files = ($save_file_name);
1.372     albertel 2919:                         my @what = ($symb,$env{'request.course.id'},'handback');
1.360     banghart 2920:                         &Apache::lonnet::mark_as_readonly($domain,$stuname,\@files,\@what);
1.367     albertel 2921: 			if (exists($$newrecord{"resource.$new_part.$resp_id.handback"})) {
                   2922: 			    $$newrecord{"resource.$new_part.$resp_id.handback"}.=',';
                   2923: 			}
                   2924:                         $$newrecord{"resource.$new_part.$resp_id.handback"} .= $save_file_name;
                   2925: 			$file_msg.= "\n".'<br /><span class="LC_filename"><a href="/uploaded/'."$domain/$stuname/".$save_file_name.'">'.$save_file_name."</a></span><br />";
                   2926: 
1.337     banghart 2927:                     }
                   2928:                     $request->print("<br />".$fname." will be the uploaded file name");
1.354     albertel 2929:                     $request->print(" ".$env{'form.'.$newflg.'_'.$part_resp.'_origdoc'.$file_counter});
1.337     banghart 2930:                     $file_counter++;
                   2931:                 }
1.367     albertel 2932: 		my $subject = "File Handed Back by Instructor ";
                   2933: 		my $message = "A file has been returned that was originally submitted in reponse to: <br />";
                   2934: 		$message .= "<strong>".&Apache::lonnet::gettitle($symb)."</strong><br />";
                   2935: 		$message .= ' The returned file(s) are named: '. $file_msg;
                   2936: 		$message .= " and can be found in your portfolio space.";
1.418     albertel 2937: 		my ($feedurl,$showsymb) = 
                   2938: 		    &get_feedurl_and_symb($symb,$domain,$stuname);
1.386     raeburn  2939:                 my $restitle = &Apache::lonnet::gettitle($symb);
                   2940: 		my $msgstatus = 
                   2941:                    &Apache::lonmsg::user_normal_msg($stuname,$domain,$subject.
                   2942: 			 ' (File Returned) ['.$restitle.']',$message,undef,
1.418     albertel 2943:                          $feedurl,undef,undef,undef,$showsymb,$restitle);
1.337     banghart 2944:             }
                   2945:         }
1.338     banghart 2946:     return;
1.337     banghart 2947: }
                   2948: 
1.418     albertel 2949: sub get_feedurl_and_symb {
                   2950:     my ($symb,$uname,$udom) = @_;
                   2951:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
                   2952:     $url = &Apache::lonnet::clutter($url);
                   2953:     my $encrypturl=&Apache::lonnet::EXT('resource.0.encrypturl',
                   2954: 					$symb,$udom,$uname);
                   2955:     if ($encrypturl =~ /^yes$/i) {
                   2956: 	&Apache::lonenc::encrypted(\$url,1);
                   2957: 	&Apache::lonenc::encrypted(\$symb,1);
                   2958:     }
                   2959:     return ($url,$symb);
                   2960: }
                   2961: 
1.313     banghart 2962: sub get_submitted_files {
                   2963:     my ($udom,$uname,$partid,$respid,$record) = @_;
                   2964:     my @files;
                   2965:     if ($$record{"resource.$partid.$respid.portfiles"}) {
                   2966:         my $file_url = '/uploaded/'.$udom.'/'.$uname.'/portfolio';
                   2967:         foreach my $file (split(',',$$record{"resource.$partid.$respid.portfiles"})) {
                   2968:     	    push(@files,$file_url.$file);
                   2969:         }
                   2970:     }
                   2971:     if ($$record{"resource.$partid.$respid.uploadedurl"}) {
                   2972:         push(@files,$$record{"resource.$partid.$respid.uploadedurl"});
                   2973:     }
                   2974:     return (\@files);
                   2975: }
1.322     albertel 2976: 
1.269     raeburn  2977: # ----------- Provides number of tries since last reset.
                   2978: sub get_num_tries {
                   2979:     my ($record,$last_reset,$part) = @_;
                   2980:     my $timestamp = '';
                   2981:     my $num_tries = 0;
                   2982:     if ($$record{'version'}) {
                   2983:         for (my $version=$$record{'version'};$version>=1;$version--) {
                   2984:             if (exists($$record{$version.':resource.'.$part.'.solved'})) {
                   2985:                 $timestamp = $$record{$version.':timestamp'};
                   2986:                 if ($timestamp > $last_reset) {
                   2987:                     $num_tries ++;
                   2988:                 } else {
                   2989:                     last;
                   2990:                 }
                   2991:             }
                   2992:         }
                   2993:     }
                   2994:     return $num_tries;
                   2995: }
                   2996: 
                   2997: # ----------- Determine decrements required in aggregate totals 
                   2998: sub decrement_aggs {
                   2999:     my ($symb,$part,$aggregate,$aggtries,$totaltries,$solvedstatus) = @_;
                   3000:     my %decrement = (
                   3001:                         attempts => 0,
                   3002:                         users => 0,
                   3003:                         correct => 0
                   3004:                     );
                   3005:     $decrement{'attempts'} = $aggtries;
                   3006:     if ($solvedstatus =~ /^correct/) {
                   3007:         $decrement{'correct'} = 1;
                   3008:     }
                   3009:     if ($aggtries == $totaltries) {
                   3010:         $decrement{'users'} = 1;
                   3011:     }
1.524     raeburn  3012:     foreach my $type (keys(%decrement)) {
1.269     raeburn  3013:         $$aggregate{$symb."\0".$part."\0".$type} = -$decrement{$type};
                   3014:     }
                   3015:     return;
                   3016: }
                   3017: 
                   3018: # ----------- Determine timestamps for last reset of aggregate totals for parts  
                   3019: sub get_last_resets {
1.270     albertel 3020:     my ($symb,$courseid,$partids) =@_;
                   3021:     my %last_resets;
1.269     raeburn  3022:     my $cdom = $env{'course.'.$courseid.'.domain'};
                   3023:     my $cname = $env{'course.'.$courseid.'.num'};
1.271     albertel 3024:     my @keys;
                   3025:     foreach my $part (@{$partids}) {
                   3026: 	push(@keys,"$symb\0$part\0resettime");
                   3027:     }
                   3028:     my %results=&Apache::lonnet::get('nohist_resourcetracker',\@keys,
                   3029: 				     $cdom,$cname);
                   3030:     foreach my $part (@{$partids}) {
                   3031: 	$last_resets{$part}=$results{"$symb\0$part\0resettime"};
1.269     raeburn  3032:     }
1.270     albertel 3033:     return %last_resets;
1.269     raeburn  3034: }
                   3035: 
1.251     banghart 3036: # ----------- Handles creating versions for portfolio files as answers
                   3037: sub version_portfiles {
1.343     banghart 3038:     my ($record, $parts_graded, $courseid, $symb, $domain, $stu_name, $v_flag) = @_;
1.263     banghart 3039:     my $version_parts = join('|',@$v_flag);
1.343     banghart 3040:     my @returned_keys;
1.255     banghart 3041:     my $parts = join('|', @$parts_graded);
1.517     raeburn  3042:     my $portfolio_root = '/userfiles/portfolio';
1.277     albertel 3043:     foreach my $key (keys(%$record)) {
1.259     banghart 3044:         my $new_portfiles;
1.263     banghart 3045:         if ($key =~ /^resource\.($version_parts)\./ && $key =~ /\.portfiles$/ ) {
1.342     banghart 3046:             my @versioned_portfiles;
1.367     albertel 3047:             my @portfiles = split(/\s*,\s*/,$$record{$key});
1.252     banghart 3048:             foreach my $file (@portfiles) {
1.306     banghart 3049:                 &Apache::lonnet::unmark_as_readonly($domain,$stu_name,[$symb,$env{'request.course.id'}],$file);
1.304     albertel 3050:                 my ($directory,$answer_file) =($file =~ /^(.*?)([^\/]*)$/);
                   3051: 		my ($answer_name,$answer_ver,$answer_ext) =
                   3052: 		    &file_name_version_ext($answer_file);
1.517     raeburn  3053:                 my $getpropath = 1;    
                   3054:                 my @dir_list = &Apache::lonnet::dirlist($portfolio_root.$directory,$domain,$stu_name,$getpropath);
1.342     banghart 3055:                 my $version = &get_next_version($answer_name, $answer_ext, \@dir_list);
1.306     banghart 3056:                 my $new_answer = &version_selected_portfile($domain, $stu_name, $directory, $answer_file, $version);
                   3057:                 if ($new_answer ne 'problem getting file') {
1.342     banghart 3058:                     push(@versioned_portfiles, $directory.$new_answer);
1.306     banghart 3059:                     &Apache::lonnet::mark_as_readonly($domain,$stu_name,
1.367     albertel 3060:                         [$directory.$new_answer],
1.306     banghart 3061:                         [$symb,$env{'request.course.id'},'graded']);
1.259     banghart 3062:                 }
1.252     banghart 3063:             }
1.343     banghart 3064:             $$record{$key} = join(',',@versioned_portfiles);
                   3065:             push(@returned_keys,$key);
1.251     banghart 3066:         }
                   3067:     } 
1.343     banghart 3068:     return (@returned_keys);   
1.305     banghart 3069: }
                   3070: 
1.307     banghart 3071: sub get_next_version {
1.341     banghart 3072:     my ($answer_name, $answer_ext, $dir_list) = @_;
1.307     banghart 3073:     my $version;
                   3074:     foreach my $row (@$dir_list) {
                   3075:         my ($file) = split(/\&/,$row,2);
                   3076:         my ($file_name,$file_version,$file_ext) =
                   3077: 	    &file_name_version_ext($file);
                   3078:         if (($file_name eq $answer_name) && 
                   3079: 	    ($file_ext eq $answer_ext)) {
                   3080:                 # gets here if filename and extension match, regardless of version
                   3081:                 if ($file_version ne '') {
                   3082:                 # a versioned file is found  so save it for later
                   3083:                 if ($file_version > $version) {
                   3084: 		    $version = $file_version;
                   3085: 	        }
                   3086:             }
                   3087:         }
                   3088:     } 
                   3089:     $version ++;
                   3090:     return($version);
                   3091: }
                   3092: 
1.305     banghart 3093: sub version_selected_portfile {
1.306     banghart 3094:     my ($domain,$stu_name,$directory,$file_name,$version) = @_;
                   3095:     my ($answer_name,$answer_ver,$answer_ext) =
                   3096:         &file_name_version_ext($file_name);
                   3097:     my $new_answer;
                   3098:     $env{'form.copy'} = &Apache::lonnet::getfile("/uploaded/$domain/$stu_name/portfolio$directory$file_name");
                   3099:     if($env{'form.copy'} eq '-1') {
                   3100:         $new_answer = 'problem getting file';
                   3101:     } else {
                   3102:         $new_answer = $answer_name.'.'.$version.'.'.$answer_ext;
                   3103:         my $copy_result = &Apache::lonnet::finishuserfileupload(
                   3104:                             $stu_name,$domain,'copy',
                   3105: 		        '/portfolio'.$directory.$new_answer);
                   3106:     }    
                   3107:     return ($new_answer);
1.251     banghart 3108: }
                   3109: 
1.304     albertel 3110: sub file_name_version_ext {
                   3111:     my ($file)=@_;
                   3112:     my @file_parts = split(/\./, $file);
                   3113:     my ($name,$version,$ext);
                   3114:     if (@file_parts > 1) {
                   3115: 	$ext=pop(@file_parts);
                   3116: 	if (@file_parts > 1 && $file_parts[-1] =~ /^\d+$/) {
                   3117: 	    $version=pop(@file_parts);
                   3118: 	}
                   3119: 	$name=join('.',@file_parts);
                   3120:     } else {
                   3121: 	$name=join('.',@file_parts);
                   3122:     }
                   3123:     return($name,$version,$ext);
                   3124: }
                   3125: 
1.44      ng       3126: #--------------------------------------------------------------------------------------
                   3127: #
                   3128: #-------------------------- Next few routines handles grading by section or whole class
                   3129: #
                   3130: #--- Javascript to handle grading by section or whole class
1.42      ng       3131: sub viewgrades_js {
                   3132:     my ($request) = shift;
                   3133: 
1.539     riegler  3134:     my $alertmsg = &mt('A number equal or greater than 0 is expected. Entered value = ');
1.597     wenzelju 3135:     $request->print(&Apache::lonhtmlcommon::scripttag(<<VIEWJAVASCRIPT));
1.45      ng       3136:    function writePoint(partid,weight,point) {
1.125     ng       3137: 	var radioButton = document.classgrade["RADVAL_"+partid];
                   3138: 	var textbox = document.classgrade["TEXTVAL_"+partid];
1.42      ng       3139: 	if (point == "textval") {
1.125     ng       3140: 	    point = document.classgrade["TEXTVAL_"+partid].value;
1.109     matthew  3141: 	    if (isNaN(point) || parseFloat(point) < 0) {
1.539     riegler  3142: 		alert("$alertmsg"+parseFloat(point));
1.42      ng       3143: 		var resetbox = false;
                   3144: 		for (var i=0; i<radioButton.length; i++) {
                   3145: 		    if (radioButton[i].checked) {
                   3146: 			textbox.value = i;
                   3147: 			resetbox = true;
                   3148: 		    }
                   3149: 		}
                   3150: 		if (!resetbox) {
                   3151: 		    textbox.value = "";
                   3152: 		}
                   3153: 		return;
                   3154: 	    }
1.109     matthew  3155: 	    if (parseFloat(point) > parseFloat(weight)) {
                   3156: 		var resp = confirm("You entered a value ("+parseFloat(point)+
1.44      ng       3157: 				   ") greater than the weight for the part. Accept?");
                   3158: 		if (resp == false) {
                   3159: 		    textbox.value = "";
                   3160: 		    return;
                   3161: 		}
                   3162: 	    }
1.42      ng       3163: 	    for (var i=0; i<radioButton.length; i++) {
                   3164: 		radioButton[i].checked=false;
1.109     matthew  3165: 		if (parseFloat(point) == i) {
1.42      ng       3166: 		    radioButton[i].checked=true;
                   3167: 		}
                   3168: 	    }
1.41      ng       3169: 
1.42      ng       3170: 	} else {
1.125     ng       3171: 	    textbox.value = parseFloat(point);
1.42      ng       3172: 	}
1.41      ng       3173: 	for (i=0;i<document.classgrade.total.value;i++) {
1.125     ng       3174: 	    var user = document.classgrade["ctr"+i].value;
1.289     albertel 3175: 	    user = user.replace(new RegExp(':', 'g'),"_");
1.125     ng       3176: 	    var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
                   3177: 	    var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
                   3178: 	    var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
1.42      ng       3179: 	    if (saveval != "correct") {
                   3180: 		scorename.value = point;
1.43      ng       3181: 		if (selname[0].selected != true) {
                   3182: 		    selname[0].selected = true;
                   3183: 		}
1.42      ng       3184: 	    }
                   3185: 	}
1.125     ng       3186: 	document.classgrade["SELVAL_"+partid][0].selected = true;
1.42      ng       3187:     }
                   3188: 
                   3189:     function writeRadText(partid,weight) {
1.125     ng       3190: 	var selval   = document.classgrade["SELVAL_"+partid];
                   3191: 	var radioButton = document.classgrade["RADVAL_"+partid];
1.265     www      3192:         var override = document.classgrade["FORCE_"+partid].checked;
1.125     ng       3193: 	var textbox = document.classgrade["TEXTVAL_"+partid];
                   3194: 	if (selval[1].selected || selval[2].selected) {
1.42      ng       3195: 	    for (var i=0; i<radioButton.length; i++) {
                   3196: 		radioButton[i].checked=false;
                   3197: 
                   3198: 	    }
                   3199: 	    textbox.value = "";
                   3200: 
                   3201: 	    for (i=0;i<document.classgrade.total.value;i++) {
1.125     ng       3202: 		var user = document.classgrade["ctr"+i].value;
1.289     albertel 3203: 		user = user.replace(new RegExp(':', 'g'),"_");
1.125     ng       3204: 		var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
                   3205: 		var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
                   3206: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
1.265     www      3207: 		if ((saveval != "correct") || override) {
1.42      ng       3208: 		    scorename.value = "";
1.125     ng       3209: 		    if (selval[1].selected) {
                   3210: 			selname[1].selected = true;
                   3211: 		    } else {
                   3212: 			selname[2].selected = true;
                   3213: 			if (Number(document.classgrade["GD_"+user+"_"+partid+"_tries"].value)) 
                   3214: 			{document.classgrade["GD_"+user+"_"+partid+"_tries"].value = '0';}
                   3215: 		    }
1.42      ng       3216: 		}
                   3217: 	    }
1.43      ng       3218: 	} else {
                   3219: 	    for (i=0;i<document.classgrade.total.value;i++) {
1.125     ng       3220: 		var user = document.classgrade["ctr"+i].value;
1.289     albertel 3221: 		user = user.replace(new RegExp(':', 'g'),"_");
1.125     ng       3222: 		var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
                   3223: 		var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
                   3224: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
1.265     www      3225: 		if ((saveval != "correct") || override) {
1.125     ng       3226: 		    scorename.value = document.classgrade["GD_"+user+"_"+partid+"_awarded_s"].value;
1.43      ng       3227: 		    selname[0].selected = true;
                   3228: 		}
                   3229: 	    }
                   3230: 	}	    
1.42      ng       3231:     }
                   3232: 
                   3233:     function changeSelect(partid,user) {
1.125     ng       3234: 	var selval = document.classgrade["GD_"+user+'_'+partid+"_solved"];
                   3235: 	var textbox = document.classgrade["GD_"+user+'_'+partid+"_awarded"];
1.44      ng       3236: 	var point  = textbox.value;
1.125     ng       3237: 	var weight = document.classgrade["weight_"+partid].value;
1.44      ng       3238: 
1.109     matthew  3239: 	if (isNaN(point) || parseFloat(point) < 0) {
1.539     riegler  3240: 	    alert("$alertmsg"+parseFloat(point));
1.44      ng       3241: 	    textbox.value = "";
                   3242: 	    return;
                   3243: 	}
1.109     matthew  3244: 	if (parseFloat(point) > parseFloat(weight)) {
                   3245: 	    var resp = confirm("You entered a value ("+parseFloat(point)+
1.44      ng       3246: 			       ") greater than the weight of the part. Accept?");
                   3247: 	    if (resp == false) {
                   3248: 		textbox.value = "";
                   3249: 		return;
                   3250: 	    }
                   3251: 	}
1.42      ng       3252: 	selval[0].selected = true;
                   3253:     }
                   3254: 
                   3255:     function changeOneScore(partid,user) {
1.125     ng       3256: 	var selval = document.classgrade["GD_"+user+'_'+partid+"_solved"];
                   3257: 	if (selval[1].selected || selval[2].selected) {
                   3258: 	    document.classgrade["GD_"+user+'_'+partid+"_awarded"].value = "";
                   3259: 	    if (selval[2].selected) {
                   3260: 		document.classgrade["GD_"+user+'_'+partid+"_tries"].value = "0";
                   3261: 	    }
1.269     raeburn  3262:         }
1.42      ng       3263:     }
                   3264: 
                   3265:     function resetEntry(numpart) {
                   3266: 	for (ctpart=0;ctpart<numpart;ctpart++) {
1.125     ng       3267: 	    var partid = document.classgrade["partid_"+ctpart].value;
                   3268: 	    var radioButton = document.classgrade["RADVAL_"+partid];
                   3269: 	    var textbox = document.classgrade["TEXTVAL_"+partid];
                   3270: 	    var selval  = document.classgrade["SELVAL_"+partid];
1.42      ng       3271: 	    for (var i=0; i<radioButton.length; i++) {
                   3272: 		radioButton[i].checked=false;
                   3273: 
                   3274: 	    }
                   3275: 	    textbox.value = "";
                   3276: 	    selval[0].selected = true;
                   3277: 
                   3278: 	    for (i=0;i<document.classgrade.total.value;i++) {
1.125     ng       3279: 		var user = document.classgrade["ctr"+i].value;
1.289     albertel 3280: 		user = user.replace(new RegExp(':', 'g'),"_");
1.125     ng       3281: 		var resetscore = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
                   3282: 		resetscore.value = document.classgrade["GD_"+user+"_"+partid+"_awarded_s"].value;
                   3283: 		var resettries = document.classgrade["GD_"+user+"_"+partid+"_tries"];
                   3284: 		resettries.value = document.classgrade["GD_"+user+"_"+partid+"_tries_s"].value;
                   3285: 		var saveselval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
                   3286: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
1.42      ng       3287: 		if (saveselval == "excused") {
1.43      ng       3288: 		    if (selname[1].selected == false) { selname[1].selected = true;}
1.42      ng       3289: 		} else {
1.43      ng       3290: 		    if (selname[0].selected == false) {selname[0].selected = true};
1.42      ng       3291: 		}
                   3292: 	    }
1.41      ng       3293: 	}
1.42      ng       3294:     }
                   3295: 
1.41      ng       3296: VIEWJAVASCRIPT
1.42      ng       3297: }
                   3298: 
1.44      ng       3299: #--- show scores for a section or whole class w/ option to change/update a score
1.42      ng       3300: sub viewgrades {
                   3301:     my ($request) = shift;
                   3302:     &viewgrades_js($request);
1.41      ng       3303: 
1.324     albertel 3304:     my ($symb) = &get_symb($request);
1.168     albertel 3305:     #need to make sure we have the correct data for later EXT calls, 
                   3306:     #thus invalidate the cache
                   3307:     &Apache::lonnet::devalidatecourseresdata(
1.257     albertel 3308:                  $env{'course.'.$env{'request.course.id'}.'.num'},
                   3309:                  $env{'course.'.$env{'request.course.id'}.'.domain'});
1.168     albertel 3310:     &Apache::lonnet::clear_EXT_cache_status();
                   3311: 
1.398     albertel 3312:     my $result='<h3><span class="LC_info">'.&mt('Manual Grading').'</span></h3>';
1.485     albertel 3313:     $result.='<h4>'.&mt('<b>Current Resource: </b>[_1]',$env{'form.probTitle'}).'</h4>'."\n";
1.41      ng       3314: 
                   3315:     #view individual student submission form - called using Javascript viewOneStudent
1.324     albertel 3316:     $result.=&jscriptNform($symb);
1.41      ng       3317: 
1.44      ng       3318:     #beginning of class grading form
1.442     banghart 3319:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
1.41      ng       3320:     $result.= '<form action="/adm/grades" method="post" name="classgrade">'."\n".
1.418     albertel 3321: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.38      ng       3322: 	'<input type="hidden" name="command" value="editgrades" />'."\n".
1.432     banghart 3323: 	&build_section_inputs().
1.257     albertel 3324: 	'<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n".
1.442     banghart 3325: 	'<input type="hidden" name="Status" value="'.$env{'stu_status'}.'" />'."\n".
1.257     albertel 3326: 	'<input type="hidden" name="probTitle" value="'.$env{'form.probTitle'}.'" />'."\n";
1.72      ng       3327: 
1.560     raeburn  3328:     my ($common_header,$specific_header);
1.257     albertel 3329:     if ($env{'form.section'} eq 'all') {
1.560     raeburn  3330: 	$common_header = &mt('Assign Common Grade to Class');
                   3331:         $specific_header = &mt('Assign Grade to Specific Students in Class');
1.257     albertel 3332:     } elsif ($env{'form.section'} eq 'none') {
1.560     raeburn  3333:         $common_header = &mt('Assign Common Grade to Students in no Section');
                   3334: 	$specific_header = &mt('Assign Grade to Specific Students in no Section');
1.52      albertel 3335:     } else {
1.560     raeburn  3336:         my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
                   3337:         $common_header = &mt('Assign Common Grade to Students in Section(s) [_1]',$section_display);
                   3338: 	$specific_header = &mt('Assign Grade to Specific Students in Section(s) [_1]',$section_display);
1.52      albertel 3339:     }
1.560     raeburn  3340:     $result.= '<h3>'.$common_header.'</h3>'.&Apache::loncommon::start_data_table();
1.44      ng       3341:     #radio buttons/text box for assigning points for a section or class.
                   3342:     #handles different parts of a problem
1.582     raeburn  3343:     my $res_error;
                   3344:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
                   3345:     if ($res_error) {
                   3346:         return &navmap_errormsg();
                   3347:     }
1.42      ng       3348:     my %weight = ();
                   3349:     my $ctsparts = 0;
1.45      ng       3350:     my %seen = ();
1.375     albertel 3351:     my @part_response_id = &flatten_responseType($responseType);
                   3352:     foreach my $part_response_id (@part_response_id) {
                   3353:     	my ($partid,$respid) = @{ $part_response_id };
                   3354: 	my $part_resp = join('_',@{ $part_response_id });
1.45      ng       3355: 	next if $seen{$partid};
                   3356: 	$seen{$partid}++;
1.375     albertel 3357: 	my $handgrade=$$handgrade{$part_resp};
1.42      ng       3358: 	my $wgt = &Apache::lonnet::EXT('resource.'.$partid.'.weight',$symb);
                   3359: 	$weight{$partid} = $wgt eq '' ? '1' : $wgt;
                   3360: 
1.324     albertel 3361: 	my $display_part=&get_display_part($partid,$symb);
1.485     albertel 3362: 	my $radio.='<table border="0"><tr>';  
1.41      ng       3363: 	my $ctr = 0;
1.42      ng       3364: 	while ($ctr<=$weight{$partid}) { # display radio buttons in a nice table 10 across
1.485     albertel 3365: 	    $radio.= '<td><label><input type="radio" name="RADVAL_'.$partid.'" '.
1.54      albertel 3366: 		'onclick="javascript:writePoint(\''.$partid.'\','.$weight{$partid}.
1.288     albertel 3367: 		','.$ctr.')" />'.$ctr."</label></td>\n";
1.41      ng       3368: 	    $result.=(($ctr+1)%10 == 0 ? '</tr><tr>' : '');
                   3369: 	    $ctr++;
                   3370: 	}
1.485     albertel 3371: 	$radio.='</tr></table>';
                   3372: 	my $line = '<input type="text" name="TEXTVAL_'.
1.589     bisitz   3373: 	    $partid.'" size="4" '.'onchange="javascript:writePoint(\''.
1.54      albertel 3374: 		$partid.'\','.$weight{$partid}.',\'textval\')" /> /'.
1.539     riegler  3375: 	    $weight{$partid}.' '.&mt('(problem weight)').'</td>'."\n";
                   3376: 	$line.= '<td><b>'.&mt('Grade Status').':</b><select name="SELVAL_'.$partid.'"'.
1.589     bisitz   3377: 	    'onchange="javascript:writeRadText(\''.$partid.'\','.
1.59      albertel 3378: 		$weight{$partid}.')"> '.
1.401     albertel 3379: 	    '<option selected="selected"> </option>'.
1.485     albertel 3380: 	    '<option value="excused">'.&mt('excused').'</option>'.
                   3381: 	    '<option value="reset status">'.&mt('reset status').'</option>'.
                   3382: 	    '</select></td>'.
                   3383:             '<td><label><input type="checkbox" name="FORCE_'.$partid.'" />'.&mt('Override "Correct"').'</label>';
                   3384: 	$line.='<input type="hidden" name="partid_'.
                   3385: 	    $ctsparts.'" value="'.$partid.'" />'."\n";
                   3386: 	$line.='<input type="hidden" name="weight_'.
                   3387: 	    $partid.'" value="'.$weight{$partid}.'" />'."\n";
                   3388: 
                   3389: 	$result.=
                   3390: 	    &Apache::loncommon::start_data_table_row()."\n".
1.577     bisitz   3391: 	    '<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 3392: 	    &Apache::loncommon::end_data_table_row()."\n";
1.42      ng       3393: 	$ctsparts++;
1.41      ng       3394:     }
1.474     albertel 3395:     $result.=&Apache::loncommon::end_data_table()."\n".
1.52      albertel 3396: 	'<input type="hidden" name="totalparts" value="'.$ctsparts.'" />';
1.485     albertel 3397:     $result.='<input type="button" value="'.&mt('Revert to Default').'" '.
1.589     bisitz   3398: 	'onclick="javascript:resetEntry('.$ctsparts.');" />';
1.41      ng       3399: 
1.44      ng       3400:     #table listing all the students in a section/class
                   3401:     #header of table
1.560     raeburn  3402:     $result.= '<h3>'.$specific_header.'</h3>'.
                   3403:               &Apache::loncommon::start_data_table().
                   3404: 	      &Apache::loncommon::start_data_table_header_row().
                   3405: 	      '<th>'.&mt('No.').'</th>'.
                   3406: 	      '<th>'.&nameUserString('header')."</th>\n";
1.582     raeburn  3407:     my $partserror;
                   3408:     my (@parts) = sort(&getpartlist($symb,\$partserror));
                   3409:     if ($partserror) {
                   3410:         return &navmap_errormsg();
                   3411:     }
1.324     albertel 3412:     my (undef,undef,$url)=&Apache::lonnet::decode_symb($symb);
1.269     raeburn  3413:     my @partids = ();
1.41      ng       3414:     foreach my $part (@parts) {
                   3415: 	my $display=&Apache::lonnet::metadata($url,$part.'.display');
1.539     riegler  3416:         my $narrowtext = &mt('Tries');
                   3417: 	$display =~ s|^Number of Attempts|$narrowtext <br />|; # makes the column narrower
1.41      ng       3418: 	if  (!$display) { $display = &Apache::lonnet::metadata($url,$part.'.name'); }
1.207     albertel 3419: 	my ($partid) = &split_part_type($part);
1.524     raeburn  3420:         push(@partids,$partid);
1.324     albertel 3421: 	my $display_part=&get_display_part($partid,$symb);
1.41      ng       3422: 	if ($display =~ /^Partial Credit Factor/) {
1.485     albertel 3423: 	    $result.='<th>'.
                   3424: 		&mt('Score Part: [_1]<br /> (weight = [_2])',
                   3425: 		    $display_part,$weight{$partid}).'</th>'."\n";
1.41      ng       3426: 	    next;
1.485     albertel 3427: 	    
1.207     albertel 3428: 	} else {
1.485     albertel 3429: 	    if ($display =~ /Problem Status/) {
                   3430: 		my $grade_status_mt = &mt('Grade Status');
                   3431: 		$display =~ s{Problem Status}{$grade_status_mt<br />};
                   3432: 	    }
                   3433: 	    my $part_mt = &mt('Part:');
                   3434: 	    $display =~s{\[Part: \Q$partid\E\]}{$part_mt $display_part};
1.41      ng       3435: 	}
1.485     albertel 3436: 
1.474     albertel 3437: 	$result.='<th>'.$display.'</th>'."\n";
1.41      ng       3438:     }
1.474     albertel 3439:     $result.=&Apache::loncommon::end_data_table_header_row();
1.44      ng       3440: 
1.270     albertel 3441:     my %last_resets = 
                   3442: 	&get_last_resets($symb,$env{'request.course.id'},\@partids);
1.269     raeburn  3443: 
1.41      ng       3444:     #get info for each student
1.44      ng       3445:     #list all the students - with points and grade status
1.257     albertel 3446:     my (undef,undef,$fullname) = &getclasslist($env{'form.section'},'1');
1.41      ng       3447:     my $ctr = 0;
1.294     albertel 3448:     foreach (sort 
                   3449: 	     {
                   3450: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                   3451: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                   3452: 		 }
                   3453: 		 return $a cmp $b;
                   3454: 	     } (keys(%$fullname))) {
1.126     ng       3455: 	$ctr++;
1.324     albertel 3456: 	$result.=&viewstudentgrade($symb,$env{'request.course.id'},
1.269     raeburn  3457: 				   $_,$$fullname{$_},\@parts,\%weight,$ctr,\%last_resets);
1.41      ng       3458:     }
1.474     albertel 3459:     $result.=&Apache::loncommon::end_data_table();
1.41      ng       3460:     $result.='<input type="hidden" name="total" value="'.$ctr.'" />'."\n";
1.485     albertel 3461:     $result.='<input type="button" value="'.&mt('Save').'" '.
1.589     bisitz   3462: 	'onclick="javascript:submit();" target="_self" /></form>'."\n";
1.96      albertel 3463:     if (scalar(%$fullname) eq 0) {
                   3464: 	my $colspan=3+scalar(@parts);
1.433     banghart 3465: 	my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
1.442     banghart 3466:         my $stu_status = join(' or ',&Apache::loncommon::get_env_multiple('form.Status'));
1.433     banghart 3467: 	$result='<span class="LC_warning">'.
1.485     albertel 3468: 	    &mt('There are no students in section(s) [_1] with enrollment status [_2] to modify or grade.',
1.442     banghart 3469: 	        $section_display, $stu_status).
1.433     banghart 3470: 	    '</span>';
1.96      albertel 3471:     }
1.324     albertel 3472:     $result.=&show_grading_menu_form($symb);
1.41      ng       3473:     return $result;
                   3474: }
                   3475: 
1.44      ng       3476: #--- call by previous routine to display each student
1.41      ng       3477: sub viewstudentgrade {
1.324     albertel 3478:     my ($symb,$courseid,$student,$fullname,$parts,$weight,$ctr,$last_resets) = @_;
1.44      ng       3479:     my ($uname,$udom) = split(/:/,$student);
                   3480:     my %record=&Apache::lonnet::restore($symb,$courseid,$udom,$uname);
1.269     raeburn  3481:     my %aggregates = (); 
1.474     albertel 3482:     my $result=&Apache::loncommon::start_data_table_row().'<td align="right">'.
1.233     albertel 3483: 	'<input type="hidden" name="ctr'.($ctr-1).'" value="'.$student.'" />'.
                   3484: 	"\n".$ctr.'&nbsp;</td><td>&nbsp;'.
1.44      ng       3485: 	'<a href="javascript:viewOneStudent(\''.$uname.'\',\''.$udom.
1.417     albertel 3486: 	'\');" target="_self">'.$fullname.'</a> '.
1.398     albertel 3487: 	'<span class="LC_internal_info">('.$uname.($env{'user.domain'} eq $udom ? '' : ':'.$udom).')</span></td>'."\n";
1.281     albertel 3488:     $student=~s/:/_/; # colon doen't work in javascript for names
1.63      albertel 3489:     foreach my $apart (@$parts) {
                   3490: 	my ($part,$type) = &split_part_type($apart);
1.41      ng       3491: 	my $score=$record{"resource.$part.$type"};
1.276     albertel 3492:         $result.='<td align="center">';
1.269     raeburn  3493:         my ($aggtries,$totaltries);
                   3494:         unless (exists($aggregates{$part})) {
1.270     albertel 3495: 	    $totaltries = $record{'resource.'.$part.'.tries'};
                   3496: 
                   3497: 	    $aggtries = $totaltries;
1.269     raeburn  3498:             if ($$last_resets{$part}) {  
1.270     albertel 3499:                 $aggtries = &get_num_tries(\%record,$$last_resets{$part},
                   3500: 					   $part);
                   3501:             }
1.269     raeburn  3502:             $result.='<input type="hidden" name="'.
                   3503:                 'GD_'.$student.'_'.$part.'_aggtries" value="'.$aggtries.'" />'."\n";
                   3504:             $result.='<input type="hidden" name="'.
                   3505:                 'GD_'.$student.'_'.$part.'_totaltries" value="'.$totaltries.'" />'."\n";
                   3506:             $aggregates{$part} = 1;
                   3507:         }
1.41      ng       3508: 	if ($type eq 'awarded') {
1.320     albertel 3509: 	    my $pts = $score eq '' ? '' : &compute_points($score,$$weight{$part});
1.42      ng       3510: 	    $result.='<input type="hidden" name="'.
1.89      albertel 3511: 		'GD_'.$student.'_'.$part.'_awarded_s" value="'.$pts.'" />'."\n";
1.233     albertel 3512: 	    $result.='<input type="text" name="'.
1.89      albertel 3513: 		'GD_'.$student.'_'.$part.'_awarded" '.
1.589     bisitz   3514:                 'onchange="javascript:changeSelect(\''.$part.'\',\''.$student.
1.44      ng       3515: 		'\')" value="'.$pts.'" size="4" /></td>'."\n";
1.41      ng       3516: 	} elsif ($type eq 'solved') {
                   3517: 	    my ($status,$foo)=split(/_/,$score,2);
                   3518: 	    $status = 'nothing' if ($status eq '');
1.89      albertel 3519: 	    $result.='<input type="hidden" name="'.'GD_'.$student.'_'.
1.54      albertel 3520: 		$part.'_solved_s" value="'.$status.'" />'."\n";
1.233     albertel 3521: 	    $result.='&nbsp;<select name="'.
1.89      albertel 3522: 		'GD_'.$student.'_'.$part.'_solved" '.
1.589     bisitz   3523:                 'onchange="javascript:changeOneScore(\''.$part.'\',\''.$student.'\')" >'."\n";
1.485     albertel 3524: 	    $result.= (($status eq 'excused') ? '<option> </option><option selected="selected" value="excused">'.&mt('excused').'</option>' 
                   3525: 		: '<option selected="selected"> </option><option value="excused">'.&mt('excused').'</option>')."\n";
                   3526: 	    $result.='<option value="reset status">'.&mt('reset status').'</option>';
1.126     ng       3527: 	    $result.="</select>&nbsp;</td>\n";
1.122     ng       3528: 	} else {
                   3529: 	    $result.='<input type="hidden" name="'.
                   3530: 		'GD_'.$student.'_'.$part.'_'.$type.'_s" value="'.$score.'" />'.
                   3531: 		    "\n";
1.233     albertel 3532: 	    $result.='<input type="text" name="'.
1.122     ng       3533: 		'GD_'.$student.'_'.$part.'_'.$type.'" '.
                   3534: 		'value="'.$score.'" size="4" /></td>'."\n";
1.41      ng       3535: 	}
                   3536:     }
1.474     albertel 3537:     $result.=&Apache::loncommon::end_data_table_row();
1.41      ng       3538:     return $result;
1.38      ng       3539: }
                   3540: 
1.44      ng       3541: #--- change scores for all the students in a section/class
                   3542: #    record does not get update if unchanged
1.38      ng       3543: sub editgrades {
1.41      ng       3544:     my ($request) = @_;
                   3545: 
1.324     albertel 3546:     my $symb=&get_symb($request);
1.433     banghart 3547:     my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
1.477     albertel 3548:     my $title='<h2>'.&mt('Current Grade Status').'</h2>';
                   3549:     $title.='<h4>'.&mt('<b>Current Resource: </b>[_1]',$env{'form.probTitle'}).'</h4>'."\n";
1.433     banghart 3550:     $title.='<h4>'.&mt('<b>Section: </b>[_1]',$section_display).'</h4>'."\n";
1.126     ng       3551: 
1.477     albertel 3552:     my $result= &Apache::loncommon::start_data_table().
                   3553: 	&Apache::loncommon::start_data_table_header_row().
                   3554: 	'<th rowspan="2" valign="middle">'.&mt('No.').'</th>'.
                   3555: 	'<th rowspan="2" valign="middle">'.&nameUserString('header')."</th>\n";
1.43      ng       3556:     my %scoreptr = (
                   3557: 		    'correct'  =>'correct_by_override',
                   3558: 		    'incorrect'=>'incorrect_by_override',
                   3559: 		    'excused'  =>'excused',
                   3560: 		    'ungraded' =>'ungraded_attempted',
1.596     raeburn  3561:                     'credited' =>'credit_attempted',
1.43      ng       3562: 		    'nothing'  => '',
                   3563: 		    );
1.257     albertel 3564:     my ($classlist,undef,$fullname) = &getclasslist($env{'form.section'},'0');
1.34      ng       3565: 
1.44      ng       3566:     my (@partid);
                   3567:     my %weight = ();
1.54      albertel 3568:     my %columns = ();
1.44      ng       3569:     my ($i,$ctr,$count,$rec_update) = (0,0,0,0);
1.54      albertel 3570: 
1.582     raeburn  3571:     my $partserror;
                   3572:     my (@parts) = sort(&getpartlist($symb,\$partserror));
                   3573:     if ($partserror) {
                   3574:         return &navmap_errormsg();
                   3575:     }
1.54      albertel 3576:     my $header;
1.257     albertel 3577:     while ($ctr < $env{'form.totalparts'}) {
                   3578: 	my $partid = $env{'form.partid_'.$ctr};
1.524     raeburn  3579: 	push(@partid,$partid);
1.257     albertel 3580: 	$weight{$partid} = $env{'form.weight_'.$partid};
1.44      ng       3581: 	$ctr++;
1.54      albertel 3582:     }
1.324     albertel 3583:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
1.54      albertel 3584:     foreach my $partid (@partid) {
1.478     albertel 3585: 	$header .= '<th align="center">'.&mt('Old Score').'</th>'.
                   3586: 	    '<th align="center">'.&mt('New Score').'</th>';
1.54      albertel 3587: 	$columns{$partid}=2;
                   3588: 	foreach my $stores (@parts) {
                   3589: 	    my ($part,$type) = &split_part_type($stores);
                   3590: 	    if ($part !~ m/^\Q$partid\E/) { next;}
                   3591: 	    if ($type eq 'awarded' || $type eq 'solved') { next; }
                   3592: 	    my $display=&Apache::lonnet::metadata($url,$stores.'.display');
1.551     raeburn  3593: 	    $display =~ s/\[Part: \Q$part\E\]//;
1.539     riegler  3594:             my $narrowtext = &mt('Tries');
                   3595: 	    $display =~ s/Number of Attempts/$narrowtext/;
                   3596: 	    $header .= '<th align="center">'.&mt('Old').' '.$display.'</th>'.
                   3597: 		'<th align="center">'.&mt('New').' '.$display.'</th>';
1.54      albertel 3598: 	    $columns{$partid}+=2;
                   3599: 	}
                   3600:     }
                   3601:     foreach my $partid (@partid) {
1.324     albertel 3602: 	my $display_part=&get_display_part($partid,$symb);
1.478     albertel 3603: 	$result .= '<th colspan="'.$columns{$partid}.'" align="center">'.
                   3604: 	    &mt('Part: [_1] (Weight = [_2])',$display_part,$weight{$partid}).
                   3605: 	    '</th>';
1.54      albertel 3606: 
1.44      ng       3607:     }
1.477     albertel 3608:     $result .= &Apache::loncommon::end_data_table_header_row().
                   3609: 	&Apache::loncommon::start_data_table_header_row().
                   3610: 	$header.
                   3611: 	&Apache::loncommon::end_data_table_header_row();
                   3612:     my @noupdate;
1.126     ng       3613:     my ($updateCtr,$noupdateCtr) = (1,1);
1.257     albertel 3614:     for ($i=0; $i<$env{'form.total'}; $i++) {
1.93      albertel 3615: 	my $line;
1.257     albertel 3616: 	my $user = $env{'form.ctr'.$i};
1.281     albertel 3617: 	my ($uname,$udom)=split(/:/,$user);
1.44      ng       3618: 	my %newrecord;
                   3619: 	my $updateflag = 0;
1.281     albertel 3620: 	$line .= '<td>'.&nameUserString(undef,$$fullname{$user},$uname,$udom).'</td>';
1.108     albertel 3621: 	my $usec=$classlist->{"$uname:$udom"}[5];
1.105     albertel 3622: 	if (!&canmodify($usec)) {
1.126     ng       3623: 	    my $numcols=scalar(@partid)*4+2;
1.477     albertel 3624: 	    push(@noupdate,
1.478     albertel 3625: 		 $line."<td colspan=\"$numcols\"><span class=\"LC_warning\">".
                   3626: 		 &mt('Not allowed to modify student')."</span></td></tr>");
1.105     albertel 3627: 	    next;
                   3628: 	}
1.269     raeburn  3629:         my %aggregate = ();
                   3630:         my $aggregateflag = 0;
1.281     albertel 3631: 	$user=~s/:/_/; # colon doen't work in javascript for names
1.44      ng       3632: 	foreach (@partid) {
1.257     albertel 3633: 	    my $old_aw    = $env{'form.GD_'.$user.'_'.$_.'_awarded_s'};
1.54      albertel 3634: 	    my $old_part_pcr = $old_aw/($weight{$_} ne '0' ? $weight{$_}:1);
                   3635: 	    my $old_part  = $old_aw eq '' ? '' : $old_part_pcr;
1.257     albertel 3636: 	    my $old_score = $scoreptr{$env{'form.GD_'.$user.'_'.$_.'_solved_s'}};
                   3637: 	    my $awarded   = $env{'form.GD_'.$user.'_'.$_.'_awarded'};
1.54      albertel 3638: 	    my $pcr       = $awarded/($weight{$_} ne '0' ? $weight{$_} : 1);
                   3639: 	    my $partial   = $awarded eq '' ? '' : $pcr;
1.44      ng       3640: 	    my $score;
                   3641: 	    if ($partial eq '') {
1.257     albertel 3642: 		$score = $scoreptr{$env{'form.GD_'.$user.'_'.$_.'_solved_s'}};
1.44      ng       3643: 	    } elsif ($partial > 0) {
                   3644: 		$score = 'correct_by_override';
                   3645: 	    } elsif ($partial == 0) {
                   3646: 		$score = 'incorrect_by_override';
                   3647: 	    }
1.257     albertel 3648: 	    my $dropMenu = $env{'form.GD_'.$user.'_'.$_.'_solved'};
1.125     ng       3649: 	    $score = 'excused' if (($dropMenu eq 'excused') && ($score ne 'excused'));
                   3650: 
1.292     albertel 3651: 	    $newrecord{'resource.'.$_.'.regrader'}=
                   3652: 		"$env{'user.name'}:$env{'user.domain'}";
1.125     ng       3653: 	    if ($dropMenu eq 'reset status' &&
                   3654: 		$old_score ne '') { # ignore if no previous attempts => nothing to reset
1.299     albertel 3655: 		$newrecord{'resource.'.$_.'.tries'} = '';
1.125     ng       3656: 		$newrecord{'resource.'.$_.'.solved'} = '';
                   3657: 		$newrecord{'resource.'.$_.'.award'} = '';
1.299     albertel 3658: 		$newrecord{'resource.'.$_.'.awarded'} = '';
1.125     ng       3659: 		$updateflag = 1;
1.269     raeburn  3660:                 if ($env{'form.GD_'.$user.'_'.$_.'_aggtries'} > 0) {
                   3661:                     my $aggtries = $env{'form.GD_'.$user.'_'.$_.'_aggtries'};
                   3662:                     my $totaltries = $env{'form.GD_'.$user.'_'.$_.'_totaltries'};
                   3663:                     my $solvedstatus = $env{'form.GD_'.$user.'_'.$_.'_solved_s'};
                   3664:                     &decrement_aggs($symb,$_,\%aggregate,$aggtries,$totaltries,$solvedstatus);
                   3665:                     $aggregateflag = 1;
                   3666:                 }
1.139     albertel 3667: 	    } elsif (!($old_part eq $partial && $old_score eq $score)) {
                   3668: 		$updateflag = 1;
                   3669: 		$newrecord{'resource.'.$_.'.awarded'}  = $partial if $partial ne '';
                   3670: 		$newrecord{'resource.'.$_.'.solved'}   = $score;
                   3671: 		$rec_update++;
1.125     ng       3672: 	    }
                   3673: 
1.93      albertel 3674: 	    $line .= '<td align="center">'.$old_aw.'&nbsp;</td>'.
1.44      ng       3675: 		'<td align="center">'.$awarded.
                   3676: 		($score eq 'excused' ? $score : '').'&nbsp;</td>';
1.5       albertel 3677: 
1.54      albertel 3678: 
                   3679: 	    my $partid=$_;
                   3680: 	    foreach my $stores (@parts) {
                   3681: 		my ($part,$type) = &split_part_type($stores);
                   3682: 		if ($part !~ m/^\Q$partid\E/) { next;}
                   3683: 		if ($type eq 'awarded' || $type eq 'solved') { next; }
1.257     albertel 3684: 		my $old_aw    = $env{'form.GD_'.$user.'_'.$part.'_'.$type.'_s'};
                   3685: 		my $awarded   = $env{'form.GD_'.$user.'_'.$part.'_'.$type};
1.54      albertel 3686: 		if ($awarded ne '' && $awarded ne $old_aw) {
                   3687: 		    $newrecord{'resource.'.$part.'.'.$type}= $awarded;
1.257     albertel 3688: 		    $newrecord{'resource.'.$part.'.regrader'}="$env{'user.name'}:$env{'user.domain'}";
1.54      albertel 3689: 		    $updateflag=1;
                   3690: 		}
1.93      albertel 3691: 		$line .= '<td align="center">'.$old_aw.'&nbsp;</td>'.
1.54      albertel 3692: 		    '<td align="center">'.$awarded.'&nbsp;</td>';
                   3693: 	    }
1.44      ng       3694: 	}
1.477     albertel 3695: 	$line.="\n";
1.301     albertel 3696: 
                   3697: 	my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   3698: 	my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   3699: 
1.44      ng       3700: 	if ($updateflag) {
                   3701: 	    $count++;
1.257     albertel 3702: 	    &Apache::lonnet::cstore(\%newrecord,$symb,$env{'request.course.id'},
1.89      albertel 3703: 				    $udom,$uname);
1.301     albertel 3704: 
                   3705: 	    if (&Apache::bridgetask::in_queue('gradingqueue',$symb,$cdom,
                   3706: 					      $cnum,$udom,$uname)) {
                   3707: 		# need to figure out if should be in queue.
                   3708: 		my %record =  
                   3709: 		    &Apache::lonnet::restore($symb,$env{'request.course.id'},
                   3710: 					     $udom,$uname);
                   3711: 		my $all_graded = 1;
                   3712: 		my $none_graded = 1;
                   3713: 		foreach my $part (@parts) {
                   3714: 		    if ( $record{'resource.'.$part.'.awarded'} eq '' ) {
                   3715: 			$all_graded = 0;
                   3716: 		    } else {
                   3717: 			$none_graded = 0;
                   3718: 		    }
                   3719: 		}
                   3720: 
                   3721: 		if ($all_graded || $none_graded) {
                   3722: 		    &Apache::bridgetask::remove_from_queue('gradingqueue',
                   3723: 							   $symb,$cdom,$cnum,
                   3724: 							   $udom,$uname);
                   3725: 		}
                   3726: 	    }
                   3727: 
1.477     albertel 3728: 	    $result.=&Apache::loncommon::start_data_table_row().
                   3729: 		'<td align="right">&nbsp;'.$updateCtr.'&nbsp;</td>'.$line.
                   3730: 		&Apache::loncommon::end_data_table_row();
1.126     ng       3731: 	    $updateCtr++;
1.93      albertel 3732: 	} else {
1.477     albertel 3733: 	    push(@noupdate,
                   3734: 		 '<td align="right">&nbsp;'.$noupdateCtr.'&nbsp;</td>'.$line);
1.126     ng       3735: 	    $noupdateCtr++;
1.44      ng       3736: 	}
1.269     raeburn  3737:         if ($aggregateflag) {
                   3738:             &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
1.301     albertel 3739: 				  $cdom,$cnum);
1.269     raeburn  3740:         }
1.93      albertel 3741:     }
1.477     albertel 3742:     if (@noupdate) {
1.126     ng       3743: #	my $numcols=(scalar(@partid)*(scalar(@parts)-1)*2)+3;
                   3744: 	my $numcols=scalar(@partid)*4+2;
1.477     albertel 3745: 	$result .= &Apache::loncommon::start_data_table_row('LC_empty_row').
1.478     albertel 3746: 	    '<td align="center" colspan="'.$numcols.'">'.
                   3747: 	    &mt('No Changes Occurred For the Students Below').
                   3748: 	    '</td>'.
1.477     albertel 3749: 	    &Apache::loncommon::end_data_table_row();
                   3750: 	foreach my $line (@noupdate) {
                   3751: 	    $result.=
                   3752: 		&Apache::loncommon::start_data_table_row().
                   3753: 		$line.
                   3754: 		&Apache::loncommon::end_data_table_row();
                   3755: 	}
1.44      ng       3756:     }
1.477     albertel 3757:     $result .= &Apache::loncommon::end_data_table().
                   3758: 	&show_grading_menu_form($symb);
1.478     albertel 3759:     my $msg = '<p><b>'.
                   3760: 	&mt('Number of records updated = [_1] for [quant,_2,student].',
                   3761: 	    $rec_update,$count).'</b><br />'.
                   3762: 	'<b>'.&mt('Total number of students = [_1]',$env{'form.total'}).
                   3763: 	'</b></p>';
1.44      ng       3764:     return $title.$msg.$result;
1.5       albertel 3765: }
1.54      albertel 3766: 
                   3767: sub split_part_type {
                   3768:     my ($partstr) = @_;
                   3769:     my ($temp,@allparts)=split(/_/,$partstr);
                   3770:     my $type=pop(@allparts);
1.439     albertel 3771:     my $part=join('_',@allparts);
1.54      albertel 3772:     return ($part,$type);
                   3773: }
                   3774: 
1.44      ng       3775: #------------- end of section for handling grading by section/class ---------
                   3776: #
                   3777: #----------------------------------------------------------------------------
                   3778: 
1.5       albertel 3779: 
1.44      ng       3780: #----------------------------------------------------------------------------
                   3781: #
                   3782: #-------------------------- Next few routines handles grading by csv upload
                   3783: #
                   3784: #--- Javascript to handle csv upload
1.27      albertel 3785: sub csvupload_javascript_reverse_associate {
1.573     bisitz   3786:     my $error1=&mt('You need to specify the username or the student/employee ID');
1.246     albertel 3787:     my $error2=&mt('You need to specify at least one grading field');
1.27      albertel 3788:   return(<<ENDPICK);
                   3789:   function verify(vf) {
                   3790:     var foundsomething=0;
                   3791:     var founduname=0;
1.243     albertel 3792:     var foundID=0;
1.27      albertel 3793:     for (i=0;i<=vf.nfields.value;i++) {
                   3794:       tw=eval('vf.f'+i+'.selectedIndex');
1.243     albertel 3795:       if (i==0 && tw!=0) { foundID=1; }
                   3796:       if (i==1 && tw!=0) { founduname=1; }
                   3797:       if (i!=0 && i!=1 && i!=2 && tw!=0) { foundsomething=1; }
1.27      albertel 3798:     }
1.246     albertel 3799:     if (founduname==0 && foundID==0) {
                   3800: 	alert('$error1');
                   3801: 	return;
1.27      albertel 3802:     }
                   3803:     if (foundsomething==0) {
1.246     albertel 3804: 	alert('$error2');
                   3805: 	return;
1.27      albertel 3806:     }
                   3807:     vf.submit();
                   3808:   }
                   3809:   function flip(vf,tf) {
                   3810:     var nw=eval('vf.f'+tf+'.selectedIndex');
                   3811:     var i;
                   3812:     for (i=0;i<=vf.nfields.value;i++) {
                   3813:       //can not pick the same destination field for both name and domain
                   3814:       if (((i ==0)||(i ==1)) && 
                   3815:           ((tf==0)||(tf==1)) && 
                   3816:           (i!=tf) &&
                   3817:           (eval('vf.f'+i+'.selectedIndex')==nw)) {
                   3818:         eval('vf.f'+i+'.selectedIndex=0;')
                   3819:       }
                   3820:     }
                   3821:   }
                   3822: ENDPICK
                   3823: }
                   3824: 
                   3825: sub csvupload_javascript_forward_associate {
1.573     bisitz   3826:     my $error1=&mt('You need to specify the username or the student/employee ID');
1.246     albertel 3827:     my $error2=&mt('You need to specify at least one grading field');
1.27      albertel 3828:   return(<<ENDPICK);
                   3829:   function verify(vf) {
                   3830:     var foundsomething=0;
                   3831:     var founduname=0;
1.243     albertel 3832:     var foundID=0;
1.27      albertel 3833:     for (i=0;i<=vf.nfields.value;i++) {
                   3834:       tw=eval('vf.f'+i+'.selectedIndex');
1.243     albertel 3835:       if (tw==1) { foundID=1; }
                   3836:       if (tw==2) { founduname=1; }
                   3837:       if (tw>3) { foundsomething=1; }
1.27      albertel 3838:     }
1.246     albertel 3839:     if (founduname==0 && foundID==0) {
                   3840: 	alert('$error1');
                   3841: 	return;
1.27      albertel 3842:     }
                   3843:     if (foundsomething==0) {
1.246     albertel 3844: 	alert('$error2');
                   3845: 	return;
1.27      albertel 3846:     }
                   3847:     vf.submit();
                   3848:   }
                   3849:   function flip(vf,tf) {
                   3850:     var nw=eval('vf.f'+tf+'.selectedIndex');
                   3851:     var i;
                   3852:     //can not pick the same destination field twice
                   3853:     for (i=0;i<=vf.nfields.value;i++) {
                   3854:       if ((i!=tf) && (eval('vf.f'+i+'.selectedIndex')==nw)) {
                   3855:         eval('vf.f'+i+'.selectedIndex=0;')
                   3856:       }
                   3857:     }
                   3858:   }
                   3859: ENDPICK
                   3860: }
                   3861: 
1.26      albertel 3862: sub csvuploadmap_header {
1.324     albertel 3863:     my ($request,$symb,$datatoken,$distotal)= @_;
1.41      ng       3864:     my $javascript;
1.257     albertel 3865:     if ($env{'form.upfile_associate'} eq 'reverse') {
1.41      ng       3866: 	$javascript=&csvupload_javascript_reverse_associate();
                   3867:     } else {
                   3868: 	$javascript=&csvupload_javascript_forward_associate();
                   3869:     }
1.45      ng       3870: 
1.598     www      3871: #    my ($result) = &showResourceInfo($symb,$env{'form.probTitle'});
                   3872:     my $result='';
1.257     albertel 3873:     my $checked=(($env{'form.noFirstLine'})?' checked="checked"':'');
1.245     albertel 3874:     my $ignore=&mt('Ignore First Line');
1.418     albertel 3875:     $symb = &Apache::lonenc::check_encrypt($symb);
1.41      ng       3876:     $request->print(<<ENDPICK);
1.26      albertel 3877: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
1.398     albertel 3878: <h3><span class="LC_info">Uploading Class Grades</span></h3>
1.45      ng       3879: $result
1.326     albertel 3880: <hr />
1.26      albertel 3881: <h3>Identify fields</h3>
                   3882: Total number of records found in file: $distotal <hr />
                   3883: Enter as many fields as you can. The system will inform you and bring you back
                   3884: to this page if the data selected is insufficient to run your class.<hr />
1.589     bisitz   3885: <input type="button" value="Reverse Association" onclick="javascript:this.form.associate.value='Reverse Association';submit(this.form);" />
1.245     albertel 3886: <label><input type="checkbox" name="noFirstLine" $checked />$ignore</label>
1.26      albertel 3887: <input type="hidden" name="associate"  value="" />
                   3888: <input type="hidden" name="phase"      value="three" />
                   3889: <input type="hidden" name="datatoken"  value="$datatoken" />
1.257     albertel 3890: <input type="hidden" name="fileupload" value="$env{'form.fileupload'}" />
                   3891: <input type="hidden" name="upfiletype" value="$env{'form.upfiletype'}" />
1.26      albertel 3892: <input type="hidden" name="upfile_associate" 
1.257     albertel 3893:                                        value="$env{'form.upfile_associate'}" />
1.26      albertel 3894: <input type="hidden" name="symb"       value="$symb" />
1.257     albertel 3895: <input type="hidden" name="saveState"  value="$env{'form.saveState'}" />
                   3896: <input type="hidden" name="probTitle"  value="$env{'form.probTitle'}" />
1.246     albertel 3897: <input type="hidden" name="command"    value="csvuploadoptions" />
1.26      albertel 3898: <hr />
                   3899: ENDPICK
1.597     wenzelju 3900:     $request->print(&Apache::lonhtmlcommon::scripttag($javascript));
1.118     ng       3901:     return '';
1.26      albertel 3902: 
                   3903: }
                   3904: 
                   3905: sub csvupload_fields {
1.582     raeburn  3906:     my ($symb,$errorref) = @_;
                   3907:     my (@parts) = &getpartlist($symb,$errorref);
                   3908:     if (ref($errorref)) {
                   3909:         if ($$errorref) {
                   3910:             return;
                   3911:         }
                   3912:     }
                   3913: 
1.556     weissno  3914:     my @fields=(['ID','Student/Employee ID'],
1.243     albertel 3915: 		['username','Student Username'],
                   3916: 		['domain','Student Domain']);
1.324     albertel 3917:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
1.41      ng       3918:     foreach my $part (sort(@parts)) {
                   3919: 	my @datum;
                   3920: 	my $display=&Apache::lonnet::metadata($url,$part.'.display');
                   3921: 	my $name=$part;
                   3922: 	if  (!$display) { $display = $name; }
                   3923: 	@datum=($name,$display);
1.244     albertel 3924: 	if ($name=~/^stores_(.*)_awarded/) {
                   3925: 	    push(@fields,['stores_'.$1.'_points',"Points [Part: $1]"]);
                   3926: 	}
1.41      ng       3927: 	push(@fields,\@datum);
                   3928:     }
                   3929:     return (@fields);
1.26      albertel 3930: }
                   3931: 
                   3932: sub csvuploadmap_footer {
1.41      ng       3933:     my ($request,$i,$keyfields) =@_;
                   3934:     $request->print(<<ENDPICK);
1.26      albertel 3935: </table>
                   3936: <input type="hidden" name="nfields" value="$i" />
                   3937: <input type="hidden" name="keyfields" value="$keyfields" />
1.589     bisitz   3938: <input type="button" onclick="javascript:verify(this.form)" value="Assign Grades" /><br />
1.26      albertel 3939: </form>
                   3940: ENDPICK
                   3941: }
                   3942: 
1.283     albertel 3943: sub checkforfile_js {
1.539     riegler  3944:     my $alertmsg = &mt('Please use the browse button to select a file from your local directory.');
1.597     wenzelju 3945:     my $result = &Apache::lonhtmlcommon::scripttag(<<CSVFORMJS);
1.86      ng       3946:     function checkUpload(formname) {
                   3947: 	if (formname.upfile.value == "") {
1.539     riegler  3948: 	    alert("$alertmsg");
1.86      ng       3949: 	    return false;
                   3950: 	}
                   3951: 	formname.submit();
                   3952:     }
                   3953: CSVFORMJS
1.283     albertel 3954:     return $result;
                   3955: }
                   3956: 
                   3957: sub upcsvScores_form {
                   3958:     my ($request) = shift;
1.324     albertel 3959:     my ($symb)=&get_symb($request);
1.283     albertel 3960:     if (!$symb) {return '';}
                   3961:     my $result=&checkforfile_js();
1.257     albertel 3962:     $env{'form.probTitle'} = &Apache::lonnet::gettitle($symb);
1.598     www      3963: #    my ($table) = &showResourceInfo($symb,$env{'form.probTitle'});
                   3964: #    $result.=$table;
1.326     albertel 3965:     $result.='<br /><table width="100%" border="0"><tr><td bgcolor="#777777">'."\n";
                   3966:     $result.='<table width="100%" border="0"><tr bgcolor="#e6ffff"><td>'."\n";
1.538     schulted 3967:     $result.='&nbsp;<b>'.&mt('Specify a file containing the class scores for current resource.').
                   3968: 	'</b></td></tr>'."\n";
1.86      ng       3969:     $result.='<tr bgcolor=#ffffe6><td>'."\n";
1.370     www      3970:     my $upload=&mt("Upload Scores");
1.86      ng       3971:     my $upfile_select=&Apache::loncommon::upfile_select_html();
1.245     albertel 3972:     my $ignore=&mt('Ignore First Line');
1.418     albertel 3973:     $symb = &Apache::lonenc::check_encrypt($symb);
1.86      ng       3974:     $result.=<<ENDUPFORM;
1.106     albertel 3975: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
1.86      ng       3976: <input type="hidden" name="symb" value="$symb" />
                   3977: <input type="hidden" name="command" value="csvuploadmap" />
1.257     albertel 3978: <input type="hidden" name="probTitle" value="$env{'form.probTitle'}" />
                   3979: <input type="hidden" name="saveState"  value="$env{'form.saveState'}" />
1.86      ng       3980: $upfile_select
1.589     bisitz   3981: <br /><input type="button" onclick="javascript:checkUpload(this.form);" value="$upload" />
1.283     albertel 3982: <label><input type="checkbox" name="noFirstLine" />$ignore</label>
1.86      ng       3983: </form>
                   3984: ENDUPFORM
1.370     www      3985:     $result.=&Apache::loncommon::help_open_topic("Course_Convert_To_CSV",
                   3986:                            &mt("How do I create a CSV file from a spreadsheet"))
                   3987:     .'</td></tr></table>'."\n";
1.86      ng       3988:     $result.='</td></tr></table><br /><br />'."\n";
1.324     albertel 3989:     $result.=&show_grading_menu_form($symb);
1.86      ng       3990:     return $result;
                   3991: }
                   3992: 
                   3993: 
1.26      albertel 3994: sub csvuploadmap {
1.41      ng       3995:     my ($request)= @_;
1.324     albertel 3996:     my ($symb)=&get_symb($request);
1.41      ng       3997:     if (!$symb) {return '';}
1.72      ng       3998: 
1.41      ng       3999:     my $datatoken;
1.257     albertel 4000:     if (!$env{'form.datatoken'}) {
1.41      ng       4001: 	$datatoken=&Apache::loncommon::upfile_store($request);
1.26      albertel 4002:     } else {
1.257     albertel 4003: 	$datatoken=$env{'form.datatoken'};
1.41      ng       4004: 	&Apache::loncommon::load_tmp_file($request);
1.26      albertel 4005:     }
1.41      ng       4006:     my @records=&Apache::loncommon::upfile_record_sep();
1.257     albertel 4007:     if ($env{'form.noFirstLine'}) { shift(@records); }
1.324     albertel 4008:     &csvuploadmap_header($request,$symb,$datatoken,$#records+1);
1.41      ng       4009:     my ($i,$keyfields);
                   4010:     if (@records) {
1.582     raeburn  4011:         my $fieldserror;
                   4012: 	my @fields=&csvupload_fields($symb,\$fieldserror);
                   4013:         if ($fieldserror) {
                   4014:             $request->print(&navmap_errormsg());
                   4015:             return;
                   4016:         }
1.257     albertel 4017: 	if ($env{'form.upfile_associate'} eq 'reverse') {	
1.41      ng       4018: 	    &Apache::loncommon::csv_print_samples($request,\@records);
                   4019: 	    $i=&Apache::loncommon::csv_print_select_table($request,\@records,
                   4020: 							  \@fields);
                   4021: 	    foreach (@fields) { $keyfields.=$_->[0].','; }
                   4022: 	    chop($keyfields);
                   4023: 	} else {
                   4024: 	    unshift(@fields,['none','']);
                   4025: 	    $i=&Apache::loncommon::csv_samples_select_table($request,\@records,
                   4026: 							    \@fields);
1.311     banghart 4027:             foreach my $rec (@records) {
                   4028:                 my %temp = &Apache::loncommon::record_sep($rec);
                   4029:                 if (%temp) {
                   4030:                     $keyfields=join(',',sort(keys(%temp)));
                   4031:                     last;
                   4032:                 }
                   4033:             }
1.41      ng       4034: 	}
                   4035:     }
                   4036:     &csvuploadmap_footer($request,$i,$keyfields);
1.324     albertel 4037:     $request->print(&show_grading_menu_form($symb));
1.72      ng       4038: 
1.41      ng       4039:     return '';
1.27      albertel 4040: }
                   4041: 
1.246     albertel 4042: sub csvuploadoptions {
1.41      ng       4043:     my ($request)= @_;
1.324     albertel 4044:     my ($symb)=&get_symb($request);
1.257     albertel 4045:     my $checked=(($env{'form.noFirstLine'})?'1':'0');
1.246     albertel 4046:     my $ignore=&mt('Ignore First Line');
                   4047:     $request->print(<<ENDPICK);
                   4048: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
1.398     albertel 4049: <h3><span class="LC_info">Uploading Class Grade Options</span></h3>
1.246     albertel 4050: <input type="hidden" name="command"    value="csvuploadassign" />
1.302     albertel 4051: <!--
1.246     albertel 4052: <p>
                   4053: <label>
                   4054:    <input type="checkbox" name="show_full_results" />
                   4055:    Show a table of all changes
                   4056: </label>
                   4057: </p>
1.302     albertel 4058: -->
1.246     albertel 4059: <p>
                   4060: <label>
                   4061:    <input type="checkbox" name="overwite_scores" checked="checked" />
                   4062:    Overwrite any existing score
                   4063: </label>
                   4064: </p>
                   4065: ENDPICK
                   4066:     my %fields=&get_fields();
                   4067:     if (!defined($fields{'domain'})) {
1.257     albertel 4068: 	my $domform = &Apache::loncommon::select_dom_form($env{'request.role.domain'},'default_domain');
1.246     albertel 4069: 	$request->print("\n<p> Users are in domain: ".$domform."</p>\n");
                   4070:     }
1.257     albertel 4071:     foreach my $key (sort(keys(%env))) {
1.246     albertel 4072: 	if ($key !~ /^form\.(.*)$/) { next; }
                   4073: 	my $cleankey=$1;
                   4074: 	if ($cleankey eq 'command') { next; }
                   4075: 	$request->print('<input type="hidden" name="'.$cleankey.
1.257     albertel 4076: 			'"  value="'.$env{$key}.'" />'."\n");
1.246     albertel 4077:     }
                   4078:     # FIXME do a check for any duplicated user ids...
                   4079:     # FIXME do a check for any invalid user ids?...
1.290     albertel 4080:     $request->print('<input type="submit" value="Assign Grades" /><br />
                   4081: <hr /></form>'."\n");
1.324     albertel 4082:     $request->print(&show_grading_menu_form($symb));
1.246     albertel 4083:     return '';
                   4084: }
                   4085: 
                   4086: sub get_fields {
                   4087:     my %fields;
1.257     albertel 4088:     my @keyfields = split(/\,/,$env{'form.keyfields'});
                   4089:     for (my $i=0; $i<=$env{'form.nfields'}; $i++) {
                   4090: 	if ($env{'form.upfile_associate'} eq 'reverse') {
                   4091: 	    if ($env{'form.f'.$i} ne 'none') {
                   4092: 		$fields{$keyfields[$i]}=$env{'form.f'.$i};
1.41      ng       4093: 	    }
                   4094: 	} else {
1.257     albertel 4095: 	    if ($env{'form.f'.$i} ne 'none') {
                   4096: 		$fields{$env{'form.f'.$i}}=$keyfields[$i];
1.41      ng       4097: 	    }
                   4098: 	}
1.27      albertel 4099:     }
1.246     albertel 4100:     return %fields;
                   4101: }
                   4102: 
                   4103: sub csvuploadassign {
                   4104:     my ($request)= @_;
1.324     albertel 4105:     my ($symb)=&get_symb($request);
1.246     albertel 4106:     if (!$symb) {return '';}
1.345     bowersj2 4107:     my $error_msg = '';
1.246     albertel 4108:     &Apache::loncommon::load_tmp_file($request);
                   4109:     my @gradedata = &Apache::loncommon::upfile_record_sep();
1.257     albertel 4110:     if ($env{'form.noFirstLine'}) { shift(@gradedata); }
1.246     albertel 4111:     my %fields=&get_fields();
1.41      ng       4112:     $request->print('<h3>Assigning Grades</h3>');
1.257     albertel 4113:     my $courseid=$env{'request.course.id'};
1.97      albertel 4114:     my ($classlist) = &getclasslist('all',0);
1.106     albertel 4115:     my @notallowed;
1.41      ng       4116:     my @skipped;
                   4117:     my $countdone=0;
                   4118:     foreach my $grade (@gradedata) {
                   4119: 	my %entries=&Apache::loncommon::record_sep($grade);
1.246     albertel 4120: 	my $domain;
                   4121: 	if ($entries{$fields{'domain'}}) {
                   4122: 	    $domain=$entries{$fields{'domain'}};
                   4123: 	} else {
1.257     albertel 4124: 	    $domain=$env{'form.default_domain'};
1.246     albertel 4125: 	}
1.243     albertel 4126: 	$domain=~s/\s//g;
1.41      ng       4127: 	my $username=$entries{$fields{'username'}};
1.160     albertel 4128: 	$username=~s/\s//g;
1.243     albertel 4129: 	if (!$username) {
                   4130: 	    my $id=$entries{$fields{'ID'}};
1.247     albertel 4131: 	    $id=~s/\s//g;
1.243     albertel 4132: 	    my %ids=&Apache::lonnet::idget($domain,$id);
                   4133: 	    $username=$ids{$id};
                   4134: 	}
1.41      ng       4135: 	if (!exists($$classlist{"$username:$domain"})) {
1.247     albertel 4136: 	    my $id=$entries{$fields{'ID'}};
                   4137: 	    $id=~s/\s//g;
                   4138: 	    if ($id) {
                   4139: 		push(@skipped,"$id:$domain");
                   4140: 	    } else {
                   4141: 		push(@skipped,"$username:$domain");
                   4142: 	    }
1.41      ng       4143: 	    next;
                   4144: 	}
1.108     albertel 4145: 	my $usec=$classlist->{"$username:$domain"}[5];
1.106     albertel 4146: 	if (!&canmodify($usec)) {
                   4147: 	    push(@notallowed,"$username:$domain");
                   4148: 	    next;
                   4149: 	}
1.244     albertel 4150: 	my %points;
1.41      ng       4151: 	my %grades;
                   4152: 	foreach my $dest (keys(%fields)) {
1.244     albertel 4153: 	    if ($dest eq 'ID' || $dest eq 'username' ||
                   4154: 		$dest eq 'domain') { next; }
                   4155: 	    if ($entries{$fields{$dest}} =~ /^\s*$/) { next; }
                   4156: 	    if ($dest=~/stores_(.*)_points/) {
                   4157: 		my $part=$1;
                   4158: 		my $wgt =&Apache::lonnet::EXT('resource.'.$part.'.weight',
                   4159: 					      $symb,$domain,$username);
1.345     bowersj2 4160:                 if ($wgt) {
                   4161:                     $entries{$fields{$dest}}=~s/\s//g;
                   4162:                     my $pcr=$entries{$fields{$dest}} / $wgt;
1.463     albertel 4163:                     my $award=($pcr == 0) ? 'incorrect_by_override'
                   4164:                                           : 'correct_by_override';
1.345     bowersj2 4165:                     $grades{"resource.$part.awarded"}=$pcr;
                   4166:                     $grades{"resource.$part.solved"}=$award;
                   4167:                     $points{$part}=1;
                   4168:                 } else {
                   4169:                     $error_msg = "<br />" .
                   4170:                         &mt("Some point values were assigned"
                   4171:                             ." for problems with a weight "
                   4172:                             ."of zero. These values were "
                   4173:                             ."ignored.");
                   4174:                 }
1.244     albertel 4175: 	    } else {
                   4176: 		if ($dest=~/stores_(.*)_awarded/) { if ($points{$1}) {next;} }
                   4177: 		if ($dest=~/stores_(.*)_solved/)  { if ($points{$1}) {next;} }
                   4178: 		my $store_key=$dest;
                   4179: 		$store_key=~s/^stores/resource/;
                   4180: 		$store_key=~s/_/\./g;
                   4181: 		$grades{$store_key}=$entries{$fields{$dest}};
                   4182: 	    }
1.41      ng       4183: 	}
1.508     www      4184: 	if (! %grades) { 
                   4185:            push(@skipped,&mt("[_1]: no data to save","$username:$domain")); 
                   4186:         } else {
                   4187: 	   $grades{"resource.regrader"}="$env{'user.name'}:$env{'user.domain'}";
                   4188: 	   my $result=&Apache::lonnet::cstore(\%grades,$symb,
1.302     albertel 4189: 					   $env{'request.course.id'},
                   4190: 					   $domain,$username);
1.508     www      4191: 	   if ($result eq 'ok') {
                   4192: 	      $request->print('.');
                   4193: 	   } else {
                   4194: 	      $request->print("<p><span class=\"LC_error\">".
                   4195:                               &mt("Failed to save data for student [_1]. Message when trying to save was: [_2]",
                   4196:                                   "$username:$domain",$result)."</span></p>");
                   4197: 	   }
                   4198: 	   $request->rflush();
                   4199: 	   $countdone++;
                   4200:         }
1.41      ng       4201:     }
1.570     www      4202:     $request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt("Saved scores for [quant,_1,student]",$countdone),$countdone==0));
1.41      ng       4203:     if (@skipped) {
1.571     www      4204: 	$request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt('No scores stored for the following username(s):'),1).'<br />');
                   4205:         $request->print(join(', ',@skipped));
1.106     albertel 4206:     }
                   4207:     if (@notallowed) {
1.571     www      4208: 	$request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt('Modification of scores not allowed for the following username(s):'),1).'<br />');
                   4209: 	$request->print(join(', ',@notallowed));
1.41      ng       4210:     }
1.106     albertel 4211:     $request->print("<br />\n");
1.324     albertel 4212:     $request->print(&show_grading_menu_form($symb));
1.345     bowersj2 4213:     return $error_msg;
1.26      albertel 4214: }
1.44      ng       4215: #------------- end of section for handling csv file upload ---------
                   4216: #
                   4217: #-------------------------------------------------------------------
                   4218: #
1.122     ng       4219: #-------------- Next few routines handle grading by page/sequence
1.72      ng       4220: #
                   4221: #--- Select a page/sequence and a student to grade
1.68      ng       4222: sub pickStudentPage {
                   4223:     my ($request) = shift;
                   4224: 
1.539     riegler  4225:     my $alertmsg = &mt('Please select the student you wish to grade.');
1.597     wenzelju 4226:     $request->print(&Apache::lonhtmlcommon::scripttag(<<LISTJAVASCRIPT));
1.68      ng       4227: 
                   4228: function checkPickOne(formname) {
1.76      ng       4229:     if (radioSelection(formname.student) == null) {
1.539     riegler  4230: 	alert("$alertmsg");
1.68      ng       4231: 	return;
                   4232:     }
1.125     ng       4233:     ptr = pullDownSelection(formname.selectpage);
                   4234:     formname.page.value = formname["page"+ptr].value;
                   4235:     formname.title.value = formname["title"+ptr].value;
1.68      ng       4236:     formname.submit();
                   4237: }
                   4238: 
                   4239: LISTJAVASCRIPT
1.118     ng       4240:     &commonJSfunctions($request);
1.324     albertel 4241:     my ($symb) = &get_symb($request);
1.257     albertel 4242:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
                   4243:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
                   4244:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
1.68      ng       4245: 
1.398     albertel 4246:     my $result='<h3><span class="LC_info">&nbsp;'.
1.485     albertel 4247: 	&mt('Manual Grading by Page or Sequence').'</span></h3>';
1.68      ng       4248: 
1.80      ng       4249:     $result.='<form action="/adm/grades" method="post" name="displayPage">'."\n";
1.582     raeburn  4250:     my $map_error;
                   4251:     my ($titles,$symbx) = &getSymbMap($map_error);
                   4252:     if ($map_error) {
                   4253:         $request->print(&navmap_errormsg());
                   4254:         return; 
                   4255:     }
1.137     albertel 4256:     my ($curpage) =&Apache::lonnet::decode_symb($symb); 
                   4257: #    my ($curpage,$mapId) =&Apache::lonnet::decode_symb($symb); 
                   4258: #    my $type=($curpage =~ /\.(page|sequence)/);
1.485     albertel 4259:     my $select = '<select name="selectpage">'."\n";
1.70      ng       4260:     my $ctr=0;
1.68      ng       4261:     foreach (@$titles) {
                   4262: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
1.485     albertel 4263: 	$select.='<option value="'.$ctr.'" '.
1.401     albertel 4264: 	    ($$symbx{$_} =~ /$curpage$/ ? 'selected="selected"' : '').
1.71      ng       4265: 	    '>'.$showtitle.'</option>'."\n";
1.70      ng       4266: 	$ctr++;
1.68      ng       4267:     }
1.485     albertel 4268:     $select.= '</select>';
1.539     riegler  4269:     $result.='&nbsp;<b>'.&mt('Problems from').':</b> '.$select."<br />\n";
1.485     albertel 4270: 
1.70      ng       4271:     $ctr=0;
                   4272:     foreach (@$titles) {
                   4273: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
                   4274: 	$result.='<input type="hidden" name="page'.$ctr.'" value="'.$$symbx{$_}.'" />'."\n";
                   4275: 	$result.='<input type="hidden" name="title'.$ctr.'" value="'.$showtitle.'" />'."\n";
                   4276: 	$ctr++;
                   4277:     }
1.72      ng       4278:     $result.='<input type="hidden" name="page" />'."\n".
                   4279: 	'<input type="hidden" name="title" />'."\n";
1.68      ng       4280: 
1.485     albertel 4281:     my $options =
                   4282: 	'<label><input type="radio" name="vProb" value="no" checked="checked" /> '.&mt('no').' </label>'."\n".
                   4283: 	'<label><input type="radio" name="vProb" value="yes" /> '.&mt('yes').' </label>'."<br />\n";
1.539     riegler  4284:     $result.='&nbsp;<b>'.&mt('View Problem Text').': </b>'.$options;
1.485     albertel 4285: 
                   4286:     $options =
                   4287: 	'<label><input type="radio" name="lastSub" value="none" /> '.&mt('none').' </label>'."\n".
                   4288: 	'<label><input type="radio" name="lastSub" value="datesub" checked="checked" /> '.&mt('by dates and submissions').'</label>'."\n".
                   4289: 	'<label><input type="radio" name="lastSub" value="all" /> '.&mt('all details').' </label>'."\n";
1.539     riegler  4290:     $result.='&nbsp;<b>'.&mt('Submissions').': </b>'.$options;
1.432     banghart 4291:     
                   4292:     $result.=&build_section_inputs();
1.442     banghart 4293:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
                   4294:     $result.='<input type="hidden" name="Status"  value="'.$stu_status.'" />'."\n".
1.72      ng       4295: 	'<input type="hidden" name="command" value="displayPage" />'."\n".
1.418     albertel 4296: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.257     albertel 4297: 	'<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."<br />\n";
1.72      ng       4298: 
1.539     riegler  4299:     $result.='&nbsp;<b>'.&mt('Use CODE').': </b> <input type="text" name="CODE" value="" /> <br />'."\n";
1.382     albertel 4300: 
1.80      ng       4301:     $result.='&nbsp;<input type="button" '.
1.589     bisitz   4302:              'onclick="javascript:checkPickOne(this.form);" value="'.&mt('Next').' &rarr;" /><br />'."\n";
1.72      ng       4303: 
1.68      ng       4304:     $request->print($result);
                   4305: 
1.485     albertel 4306:     my $studentTable.='&nbsp;<b>'.&mt('Select a student you wish to grade and then click on the Next button.').'</b><br />'.
1.484     albertel 4307: 	&Apache::loncommon::start_data_table().
                   4308: 	&Apache::loncommon::start_data_table_header_row().
1.485     albertel 4309: 	'<th align="right">&nbsp;'.&mt('No.').'</th>'.
1.484     albertel 4310: 	'<th>'.&nameUserString('header').'</th>'.
1.485     albertel 4311: 	'<th align="right">&nbsp;'.&mt('No.').'</th>'.
1.484     albertel 4312: 	'<th>'.&nameUserString('header').'</th>'.
                   4313: 	&Apache::loncommon::end_data_table_header_row();
1.68      ng       4314:  
1.76      ng       4315:     my (undef,undef,$fullname) = &getclasslist($getsec,'1');
1.68      ng       4316:     my $ptr = 1;
1.294     albertel 4317:     foreach my $student (sort 
                   4318: 			 {
                   4319: 			     if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                   4320: 				 return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                   4321: 			     }
                   4322: 			     return $a cmp $b;
                   4323: 			 } (keys(%$fullname))) {
1.68      ng       4324: 	my ($uname,$udom) = split(/:/,$student);
1.484     albertel 4325: 	$studentTable.=($ptr%2==1 ? &Apache::loncommon::start_data_table_row()
                   4326:                                   : '</td>');
1.126     ng       4327: 	$studentTable.='<td align="right">'.$ptr.'&nbsp;</td>';
1.288     albertel 4328: 	$studentTable.='<td>&nbsp;<label><input type="radio" name="student" value="'.$student.'" /> '
                   4329: 	    .&nameUserString(undef,$$fullname{$student},$uname,$udom)."</label>\n";
1.484     albertel 4330: 	$studentTable.=
                   4331: 	    ($ptr%2 == 0 ? '</td>'.&Apache::loncommon::end_data_table_row() 
                   4332:                          : '');
1.68      ng       4333: 	$ptr++;
                   4334:     }
1.484     albertel 4335:     if ($ptr%2 == 0) {
                   4336: 	$studentTable.='</td><td>&nbsp;</td><td>&nbsp;</td>'.
                   4337: 	    &Apache::loncommon::end_data_table_row();
                   4338:     }
                   4339:     $studentTable.=&Apache::loncommon::end_data_table()."\n";
1.126     ng       4340:     $studentTable.='<input type="button" '.
1.589     bisitz   4341:                    'onclick="javascript:checkPickOne(this.form);" value="'.&mt('Next').' &rarr;" /></form>'."\n";
1.68      ng       4342: 
1.324     albertel 4343:     $studentTable.=&show_grading_menu_form($symb);
1.68      ng       4344:     $request->print($studentTable);
                   4345: 
                   4346:     return '';
                   4347: }
                   4348: 
                   4349: sub getSymbMap {
1.582     raeburn  4350:     my ($map_error) = @_;
1.132     bowersj2 4351:     my $navmap = Apache::lonnavmaps::navmap->new();
1.582     raeburn  4352:     unless (ref($navmap)) {
                   4353:         if (ref($map_error)) {
                   4354:             $$map_error = 'navmap';
                   4355:         }
                   4356:         return;
                   4357:     }
1.68      ng       4358:     my %symbx = ();
                   4359:     my @titles = ();
1.117     bowersj2 4360:     my $minder = 0;
                   4361: 
                   4362:     # Gather every sequence that has problems.
1.240     albertel 4363:     my @sequences = $navmap->retrieveResources(undef, sub { shift->is_map(); },
                   4364: 					       1,0,1);
1.117     bowersj2 4365:     for my $sequence ($navmap->getById('0.0'), @sequences) {
1.241     albertel 4366: 	if ($navmap->hasResource($sequence, sub { shift->is_problem(); }, 0) ) {
1.381     albertel 4367: 	    my $title = $minder.'.'.
                   4368: 		&HTML::Entities::encode($sequence->compTitle(),'"\'&');
                   4369: 	    push(@titles, $title); # minder in case two titles are identical
                   4370: 	    $symbx{$title} = &HTML::Entities::encode($sequence->symb(),'"\'&');
1.117     bowersj2 4371: 	    $minder++;
1.241     albertel 4372: 	}
1.68      ng       4373:     }
                   4374:     return \@titles,\%symbx;
                   4375: }
                   4376: 
1.72      ng       4377: #
                   4378: #--- Displays a page/sequence w/wo problems, w/wo submissions
1.68      ng       4379: sub displayPage {
                   4380:     my ($request) = shift;
                   4381: 
1.324     albertel 4382:     my ($symb) = &get_symb($request);
1.257     albertel 4383:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
                   4384:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
                   4385:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
                   4386:     my $pageTitle = $env{'form.page'};
1.103     albertel 4387:     my ($classlist,undef,$fullname) = &getclasslist($getsec,'1');
1.257     albertel 4388:     my ($uname,$udom) = split(/:/,$env{'form.student'});
                   4389:     my $usec=$classlist->{$env{'form.student'}}[5];
1.168     albertel 4390: 
                   4391:     #need to make sure we have the correct data for later EXT calls, 
                   4392:     #thus invalidate the cache
                   4393:     &Apache::lonnet::devalidatecourseresdata(
1.257     albertel 4394:                  $env{'course.'.$env{'request.course.id'}.'.num'},
                   4395:                  $env{'course.'.$env{'request.course.id'}.'.domain'});
1.168     albertel 4396:     &Apache::lonnet::clear_EXT_cache_status();
                   4397: 
1.103     albertel 4398:     if (!&canview($usec)) {
1.485     albertel 4399: 	$request->print('<span class="LC_warning">'.&mt('Unable to view requested student. ([_1])',$env{'form.student'}).'</span>');
1.324     albertel 4400: 	$request->print(&show_grading_menu_form($symb));
1.103     albertel 4401: 	return;
                   4402:     }
1.398     albertel 4403:     my $result='<h3><span class="LC_info">&nbsp;'.$env{'form.title'}.'</span></h3>';
1.485     albertel 4404:     $result.='<h3>&nbsp;'.&mt('Student: [_1]',&nameUserString(undef,$$fullname{$env{'form.student'}},$uname,$udom)).
1.129     ng       4405: 	'</h3>'."\n";
1.500     albertel 4406:     $env{'form.CODE'} = uc($env{'form.CODE'});
1.501     foxr     4407:     if (&Apache::lonnet::validCODE(uc($env{'form.CODE'}))) {
1.485     albertel 4408: 	$result.='<h3>&nbsp;'.&mt('CODE: [_1]',$env{'form.CODE'}).'</h3>'."\n";
1.382     albertel 4409:     } else {
                   4410: 	delete($env{'form.CODE'});
                   4411:     }
1.71      ng       4412:     &sub_page_js($request);
                   4413:     $request->print($result);
                   4414: 
1.132     bowersj2 4415:     my $navmap = Apache::lonnavmaps::navmap->new();
1.582     raeburn  4416:     unless (ref($navmap)) {
                   4417:         $request->print(&navmap_errormsg());
                   4418:         $request->print(&show_grading_menu_form($symb));
                   4419:         return;
                   4420:     }
1.257     albertel 4421:     my ($mapUrl, $id, $resUrl)=&Apache::lonnet::decode_symb($env{'form.page'});
1.68      ng       4422:     my $map = $navmap->getResourceByUrl($resUrl); # add to navmaps
1.288     albertel 4423:     if (!$map) {
1.485     albertel 4424: 	$request->print('<span class="LC_warning">'.&mt('Unable to view requested sequence. ([_1])',$resUrl).'</span>');
1.324     albertel 4425: 	$request->print(&show_grading_menu_form($symb));
1.288     albertel 4426: 	return; 
                   4427:     }
1.68      ng       4428:     my $iterator = $navmap->getIterator($map->map_start(),
                   4429: 					$map->map_finish());
                   4430: 
1.71      ng       4431:     my $studentTable='<form action="/adm/grades" method="post" name="gradePage">'."\n".
1.72      ng       4432: 	'<input type="hidden" name="command" value="gradeByPage" />'."\n".
1.257     albertel 4433: 	'<input type="hidden" name="fullname" value="'.$$fullname{$env{'form.student'}}.'" />'."\n".
                   4434: 	'<input type="hidden" name="student" value="'.$env{'form.student'}.'" />'."\n".
1.72      ng       4435: 	'<input type="hidden" name="page"    value="'.$pageTitle.'" />'."\n".
1.257     albertel 4436: 	'<input type="hidden" name="title"   value="'.$env{'form.title'}.'" />'."\n".
1.418     albertel 4437: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.125     ng       4438: 	'<input type="hidden" name="overRideScore" value="no" />'."\n".
1.257     albertel 4439: 	'<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n";
1.71      ng       4440: 
1.382     albertel 4441:     if (defined($env{'form.CODE'})) {
                   4442: 	$studentTable.=
                   4443: 	    '<input type="hidden" name="CODE" value="'.$env{'form.CODE'}.'" />'."\n";
                   4444:     }
1.381     albertel 4445:     my $checkIcon = '<img alt="'.&mt('Check Mark').
1.485     albertel 4446: 	'" src="'.&Apache::loncommon::lonhttpdurl($request->dir_config('lonIconsURL').'/check.gif').'" height="16" border="0" />';
1.71      ng       4447: 
1.594     bisitz   4448:     $studentTable.='&nbsp;<span class="LC_info">'.
                   4449:         &mt('Problems graded correct by the computer are marked with a [_1] symbol.',$checkIcon).
                   4450:         '</span>'."\n".
1.484     albertel 4451: 	&Apache::loncommon::start_data_table().
                   4452: 	&Apache::loncommon::start_data_table_header_row().
                   4453: 	'<th align="center">&nbsp;Prob.&nbsp;</th>'.
1.485     albertel 4454: 	'<th>&nbsp;'.($env{'form.vProb'} eq 'no' ? &mt('Title') : &mt('Problem Text')).'/'.&mt('Grade').'</th>'.
1.484     albertel 4455: 	&Apache::loncommon::end_data_table_header_row();
1.71      ng       4456: 
1.329     albertel 4457:     &Apache::lonxml::clear_problem_counter();
1.196     albertel 4458:     my ($depth,$question,$prob) = (1,1,1);
1.68      ng       4459:     $iterator->next(); # skip the first BEGIN_MAP
                   4460:     my $curRes = $iterator->next(); # for "current resource"
1.101     albertel 4461:     while ($depth > 0) {
1.68      ng       4462:         if($curRes == $iterator->BEGIN_MAP) { $depth++; }
1.100     bowersj2 4463:         if($curRes == $iterator->END_MAP) { $depth--; }
1.68      ng       4464: 
1.385     albertel 4465:         if (ref($curRes) && $curRes->is_problem()) {
1.91      albertel 4466: 	    my $parts = $curRes->parts();
1.68      ng       4467:             my $title = $curRes->compTitle();
1.71      ng       4468: 	    my $symbx = $curRes->symb();
1.484     albertel 4469: 	    $studentTable.=
                   4470: 		&Apache::loncommon::start_data_table_row().
                   4471: 		'<td align="center" valign="top" >'.$prob.
1.485     albertel 4472: 		(scalar(@{$parts}) == 1 ? '' 
                   4473: 		                        : '<br />('.&mt('[_1]&nbsp;parts)',
                   4474: 							scalar(@{$parts}))
                   4475: 		 ).
                   4476: 		 '</td>';
1.71      ng       4477: 	    $studentTable.='<td valign="top">';
1.382     albertel 4478: 	    my %form = ('CODE' => $env{'form.CODE'},);
1.257     albertel 4479: 	    if ($env{'form.vProb'} eq 'yes' ) {
1.144     albertel 4480: 		$studentTable.=&show_problem($request,$symbx,$uname,$udom,1,
1.383     albertel 4481: 					     undef,'both',\%form);
1.71      ng       4482: 	    } else {
1.382     albertel 4483: 		my $companswer = &Apache::loncommon::get_student_answers($symbx,$uname,$udom,$env{'request.course.id'},%form);
1.80      ng       4484: 		$companswer =~ s|<form(.*?)>||g;
                   4485: 		$companswer =~ s|</form>||g;
1.71      ng       4486: #		while ($companswer =~ /(<a href\=\"javascript:newWindow.*?Script Vars<\/a>)/s) { #<a href="javascript:newWindow</a>
1.116     ng       4487: #		    $companswer =~ s/$1/ /ms;
1.326     albertel 4488: #		    $request->print('match='.$1."<br />\n");
1.71      ng       4489: #		}
1.116     ng       4490: #		$companswer =~ s|<table border=\"1\">|<table border=\"0\">|g;
1.539     riegler  4491: 		$studentTable.='&nbsp;<b>'.$title.'</b>&nbsp;<br />&nbsp;<b>'.&mt('Correct answer').':</b><br />'.$companswer;
1.71      ng       4492: 	    }
                   4493: 
1.257     albertel 4494: 	    my %record = &Apache::lonnet::restore($symbx,$env{'request.course.id'},$udom,$uname);
1.125     ng       4495: 
1.257     albertel 4496: 	    if ($env{'form.lastSub'} eq 'datesub') {
1.71      ng       4497: 		if ($record{'version'} eq '') {
1.485     albertel 4498: 		    $studentTable.='<br />&nbsp;<span class="LC_warning">'.&mt('No recorded submission for this problem.').'</span><br />';
1.71      ng       4499: 		} else {
1.116     ng       4500: 		    my %responseType = ();
                   4501: 		    foreach my $partid (@{$parts}) {
1.147     albertel 4502: 			my @responseIds =$curRes->responseIds($partid);
                   4503: 			my @responseType =$curRes->responseType($partid);
                   4504: 			my %responseIds;
                   4505: 			for (my $i=0;$i<=$#responseIds;$i++) {
                   4506: 			    $responseIds{$responseIds[$i]}=$responseType[$i];
                   4507: 			}
                   4508: 			$responseType{$partid} = \%responseIds;
1.116     ng       4509: 		    }
1.148     albertel 4510: 		    $studentTable.= &displaySubByDates($symbx,\%record,$parts,\%responseType,$checkIcon,$uname,$udom);
1.147     albertel 4511: 
1.71      ng       4512: 		}
1.257     albertel 4513: 	    } elsif ($env{'form.lastSub'} eq 'all') {
                   4514: 		my $last = ($env{'form.lastSub'} eq 'last' ? 'last' : '');
1.71      ng       4515: 		$studentTable.=&Apache::loncommon::get_previous_attempt($symbx,$uname,$udom,
1.257     albertel 4516: 									$env{'request.course.id'},
1.71      ng       4517: 									'','.submission');
                   4518:  
                   4519: 	    }
1.103     albertel 4520: 	    if (&canmodify($usec)) {
1.585     bisitz   4521:             $studentTable.=&gradeBox_start();
1.103     albertel 4522: 		foreach my $partid (@{$parts}) {
                   4523: 		    $studentTable.=&gradeBox($request,$symbx,$uname,$udom,$question,$partid,\%record);
                   4524: 		    $studentTable.='<input type="hidden" name="q_'.$question.'" value="'.$partid.'" />'."\n";
                   4525: 		    $question++;
                   4526: 		}
1.585     bisitz   4527:             $studentTable.=&gradeBox_end();
1.196     albertel 4528: 		$prob++;
1.71      ng       4529: 	    }
                   4530: 	    $studentTable.='</td></tr>';
1.68      ng       4531: 
1.103     albertel 4532: 	}
1.68      ng       4533:         $curRes = $iterator->next();
                   4534:     }
                   4535: 
1.589     bisitz   4536:     $studentTable.=
                   4537:         '</table>'."\n".
                   4538:         '<input type="button" value="'.&mt('Save').'" '.
                   4539:         'onclick="javascript:checkSubmitPage(this.form,'.$question.');" />'.
                   4540:         '</form>'."\n";
1.324     albertel 4541:     $studentTable.=&show_grading_menu_form($symb);
1.71      ng       4542:     $request->print($studentTable);
                   4543: 
                   4544:     return '';
1.119     ng       4545: }
                   4546: 
                   4547: sub displaySubByDates {
1.148     albertel 4548:     my ($symb,$record,$parts,$responseType,$checkIcon,$uname,$udom) = @_;
1.224     albertel 4549:     my $isCODE=0;
1.335     albertel 4550:     my $isTask = ($symb =~/\.task$/);
1.224     albertel 4551:     if (exists($record->{'resource.CODE'})) { $isCODE=1; }
1.467     albertel 4552:     my $studentTable=&Apache::loncommon::start_data_table().
                   4553: 	&Apache::loncommon::start_data_table_header_row().
                   4554: 	'<th>'.&mt('Date/Time').'</th>'.
                   4555: 	($isCODE?'<th>'.&mt('CODE').'</th>':'').
                   4556: 	'<th>'.&mt('Submission').'</th>'.
                   4557: 	'<th>'.&mt('Status').'</th>'.
                   4558: 	&Apache::loncommon::end_data_table_header_row();
1.119     ng       4559:     my ($version);
                   4560:     my %mark;
1.148     albertel 4561:     my %orders;
1.119     ng       4562:     $mark{'correct_by_student'} = $checkIcon;
1.147     albertel 4563:     if (!exists($$record{'1:timestamp'})) {
1.539     riegler  4564: 	return '<br />&nbsp;<span class="LC_warning">'.&mt('Nothing submitted - no attempts.').'</span><br />';
1.147     albertel 4565:     }
1.335     albertel 4566: 
                   4567:     my $interaction;
1.525     raeburn  4568:     my $no_increment = 1;
1.119     ng       4569:     for ($version=1;$version<=$$record{'version'};$version++) {
1.467     albertel 4570: 	my $timestamp = 
                   4571: 	    &Apache::lonlocal::locallocaltime($$record{$version.':timestamp'});
1.335     albertel 4572: 	if (exists($$record{$version.':resource.0.version'})) {
                   4573: 	    $interaction = $$record{$version.':resource.0.version'};
                   4574: 	}
                   4575: 
                   4576: 	my $where = ($isTask ? "$version:resource.$interaction"
                   4577: 		             : "$version:resource");
1.467     albertel 4578: 	$studentTable.=&Apache::loncommon::start_data_table_row().
                   4579: 	    '<td>'.$timestamp.'</td>';
1.224     albertel 4580: 	if ($isCODE) {
                   4581: 	    $studentTable.='<td>'.$record->{$version.':resource.CODE'}.'</td>';
                   4582: 	}
1.119     ng       4583: 	my @versionKeys = split(/\:/,$$record{$version.':keys'});
                   4584: 	my @displaySub = ();
                   4585: 	foreach my $partid (@{$parts}) {
1.596     raeburn  4586:             my $hidden;
                   4587:             if (($$record{$version.':resource.'.$partid.'.type'} eq 'anonsurvey') ||
                   4588:                 ($$record{$version.':resource.'.$partid.'.type'} eq 'anonsurveycred')) {
                   4589:                 $hidden = 1;
                   4590:             }
1.335     albertel 4591: 	    my @matchKey = ($isTask ? sort(grep /^resource\.\d+\.\Q$partid\E\.award$/,@versionKeys)
                   4592: 			            : sort(grep /^resource\.\Q$partid\E\..*?\.submission$/,@versionKeys));
                   4593: 	    
1.122     ng       4594: #	    next if ($$record{"$version:resource.$partid.solved"} eq '');
1.324     albertel 4595: 	    my $display_part=&get_display_part($partid,$symb);
1.147     albertel 4596: 	    foreach my $matchKey (@matchKey) {
1.198     albertel 4597: 		if (exists($$record{$version.':'.$matchKey}) &&
                   4598: 		    $$record{$version.':'.$matchKey} ne '') {
1.596     raeburn  4599:                     
1.335     albertel 4600: 		    my ($responseId)= ($isTask ? ($matchKey=~ /^resource\.(.*?)\.\Q$partid\E\.award$/)
                   4601: 				               : ($matchKey=~ /^resource\.\Q$partid\E\.(.*?)\.submission$/));
1.577     bisitz   4602:                     $displaySub[0].='<span class="LC_nobreak"';
                   4603:                     $displaySub[0].='<b>'.&mt('Part: [_1]',$display_part).'</b>'
                   4604:                                    .' <span class="LC_internal_info">'
                   4605:                                    .'('.&mt('Part ID: [_1]',$responseId).')'
                   4606:                                    .'</span>'
                   4607:                                    .' <b>';
1.596     raeburn  4608:                     if ($hidden) {
                   4609:                         $displaySub[0].= &mt('Anonymous Survey').'</b>';
                   4610:                     } else {
                   4611: 		        if ($$record{"$where.$partid.tries"} eq '') {
                   4612: 			    $displaySub[0].=&mt('Trial not counted');
                   4613: 		        } else {
                   4614: 			    $displaySub[0].=&mt('Trial: [_1]',
1.467     albertel 4615: 					    $$record{"$where.$partid.tries"});
1.596     raeburn  4616: 		        }
                   4617: 		        my $responseType=($isTask ? 'Task'
1.335     albertel 4618:                                               : $responseType->{$partid}->{$responseId});
1.596     raeburn  4619: 		        if (!exists($orders{$partid})) { $orders{$partid}={}; }
                   4620: 		        if (!exists($orders{$partid}->{$responseId})) {
                   4621: 			    $orders{$partid}->{$responseId}=
                   4622: 			        &get_order($partid,$responseId,$symb,$uname,$udom,
                   4623:                                            $no_increment);
                   4624: 		        }
                   4625: 		        $displaySub[0].='</b></span>'; # /nobreak
                   4626: 		        $displaySub[0].='&nbsp; '.
                   4627: 			    &cleanRecord($$record{$version.':'.$matchKey},$responseType,$symb,$partid,$responseId,$record,$orders{$partid}->{$responseId},"$version:",$uname,$udom).'<br />';
                   4628:                     }
1.147     albertel 4629: 		}
                   4630: 	    }
1.335     albertel 4631: 	    if (exists($$record{"$where.$partid.checkedin"})) {
1.485     albertel 4632: 		$displaySub[1].=&mt('Checked in by [_1] into slot [_2]',
                   4633: 				    $$record{"$where.$partid.checkedin"},
                   4634: 				    $$record{"$where.$partid.checkedin.slot"}).
                   4635: 					'<br />';
1.335     albertel 4636: 	    }
                   4637: 	    if (exists $$record{"$where.$partid.award"}) {
1.485     albertel 4638: 		$displaySub[1].='<b>'.&mt('Part:').'</b>&nbsp;'.$display_part.' &nbsp;'.
1.335     albertel 4639: 		    lc($$record{"$where.$partid.award"}).' '.
                   4640: 		    $mark{$$record{"$where.$partid.solved"}}.
1.147     albertel 4641: 		    '<br />';
                   4642: 	    }
1.335     albertel 4643: 	    if (exists $$record{"$where.$partid.regrader"}) {
                   4644: 		$displaySub[2].=$$record{"$where.$partid.regrader"}.
                   4645: 		    ' (<b>'.&mt('Part').':</b> '.$display_part.')';
                   4646: 	    } elsif ($$record{"$version:resource.$partid.regrader"} =~ /\S/) {
                   4647: 		$displaySub[2].=
                   4648: 		    $$record{"$version:resource.$partid.regrader"}.
1.207     albertel 4649: 		    ' (<b>'.&mt('Part').':</b> '.$display_part.')';
1.147     albertel 4650: 	    }
                   4651: 	}
                   4652: 	# needed because old essay regrader has not parts info
                   4653: 	if (exists $$record{"$version:resource.regrader"}) {
                   4654: 	    $displaySub[2].=$$record{"$version:resource.regrader"};
                   4655: 	}
                   4656: 	$studentTable.='<td>'.$displaySub[0].'&nbsp;</td><td>'.$displaySub[1];
                   4657: 	if ($displaySub[2]) {
1.467     albertel 4658: 	    $studentTable.=&mt('Manually graded by [_1]',$displaySub[2]);
1.147     albertel 4659: 	}
1.467     albertel 4660: 	$studentTable.='&nbsp;</td>'.
                   4661: 	    &Apache::loncommon::end_data_table_row();
1.119     ng       4662:     }
1.467     albertel 4663:     $studentTable.=&Apache::loncommon::end_data_table();
1.119     ng       4664:     return $studentTable;
1.71      ng       4665: }
                   4666: 
                   4667: sub updateGradeByPage {
                   4668:     my ($request) = shift;
                   4669: 
1.257     albertel 4670:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
                   4671:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
                   4672:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
                   4673:     my $pageTitle = $env{'form.page'};
1.103     albertel 4674:     my ($classlist,undef,$fullname) = &getclasslist($getsec,'1');
1.257     albertel 4675:     my ($uname,$udom) = split(/:/,$env{'form.student'});
                   4676:     my $usec=$classlist->{$env{'form.student'}}[5];
1.103     albertel 4677:     if (!&canmodify($usec)) {
1.526     raeburn  4678: 	$request->print('<span class="LC_warning">'.&mt('Unable to modify requested student ([_1])',$env{'form.student'}).'</span>');
1.324     albertel 4679: 	$request->print(&show_grading_menu_form($env{'form.symb'}));
1.103     albertel 4680: 	return;
                   4681:     }
1.398     albertel 4682:     my $result='<h3><span class="LC_info">&nbsp;'.$env{'form.title'}.'</span></h3>';
1.526     raeburn  4683:     $result.='<h3>&nbsp;'.&mt('Student: ').&nameUserString(undef,$env{'form.fullname'},$uname,$udom).
1.129     ng       4684: 	'</h3>'."\n";
1.70      ng       4685: 
1.68      ng       4686:     $request->print($result);
                   4687: 
1.582     raeburn  4688: 
1.132     bowersj2 4689:     my $navmap = Apache::lonnavmaps::navmap->new();
1.582     raeburn  4690:     unless (ref($navmap)) {
                   4691:         $request->print(&navmap_errormsg());
                   4692:         return;
                   4693:     }
1.257     albertel 4694:     my ($mapUrl, $id, $resUrl) = &Apache::lonnet::decode_symb( $env{'form.page'});
1.71      ng       4695:     my $map = $navmap->getResourceByUrl($resUrl); # add to navmaps
1.288     albertel 4696:     if (!$map) {
1.527     raeburn  4697: 	$request->print('<span class="LC_warning">'.&mt('Unable to grade requested sequence ([_1]).',$resUrl).'</span>');
1.324     albertel 4698: 	my ($symb)=&get_symb($request);
                   4699: 	$request->print(&show_grading_menu_form($symb));
1.288     albertel 4700: 	return; 
                   4701:     }
1.71      ng       4702:     my $iterator = $navmap->getIterator($map->map_start(),
                   4703: 					$map->map_finish());
1.70      ng       4704: 
1.484     albertel 4705:     my $studentTable=
                   4706: 	&Apache::loncommon::start_data_table().
                   4707: 	&Apache::loncommon::start_data_table_header_row().
1.485     albertel 4708: 	'<th align="center">&nbsp;'.&mt('Prob.').'&nbsp;</th>'.
                   4709: 	'<th>&nbsp;'.&mt('Title').'&nbsp;</th>'.
                   4710: 	'<th>&nbsp;'.&mt('Previous Score').'&nbsp;</th>'.
                   4711: 	'<th>&nbsp;'.&mt('New Score').'&nbsp;</th>'.
1.484     albertel 4712: 	&Apache::loncommon::end_data_table_header_row();
1.71      ng       4713: 
                   4714:     $iterator->next(); # skip the first BEGIN_MAP
                   4715:     my $curRes = $iterator->next(); # for "current resource"
1.196     albertel 4716:     my ($depth,$question,$prob,$changeflag)= (1,1,1,0);
1.101     albertel 4717:     while ($depth > 0) {
1.71      ng       4718:         if($curRes == $iterator->BEGIN_MAP) { $depth++; }
1.100     bowersj2 4719:         if($curRes == $iterator->END_MAP) { $depth--; }
1.71      ng       4720: 
1.385     albertel 4721:         if (ref($curRes) && $curRes->is_problem()) {
1.91      albertel 4722: 	    my $parts = $curRes->parts();
1.71      ng       4723:             my $title = $curRes->compTitle();
                   4724: 	    my $symbx = $curRes->symb();
1.484     albertel 4725: 	    $studentTable.=
                   4726: 		&Apache::loncommon::start_data_table_row().
                   4727: 		'<td align="center" valign="top" >'.$prob.
1.485     albertel 4728: 		(scalar(@{$parts}) == 1 ? '' 
1.526     raeburn  4729:                                         : '<br />('.&mt('[quant,_1,&nbsp;part]',scalar(@{$parts}))
                   4730: 		.')').'</td>';
1.71      ng       4731: 	    $studentTable.='<td valign="top">&nbsp;<b>'.$title.'</b>&nbsp;</td>';
                   4732: 
                   4733: 	    my %newrecord=();
                   4734: 	    my @displayPts=();
1.269     raeburn  4735:             my %aggregate = ();
                   4736:             my $aggregateflag = 0;
1.71      ng       4737: 	    foreach my $partid (@{$parts}) {
1.257     albertel 4738: 		my $newpts = $env{'form.GD_BOX'.$question.'_'.$partid};
                   4739: 		my $oldpts = $env{'form.oldpts'.$question.'_'.$partid};
1.71      ng       4740: 
1.257     albertel 4741: 		my $wgt = $env{'form.WGT'.$question.'_'.$partid} != 0 ? 
                   4742: 		    $env{'form.WGT'.$question.'_'.$partid} : 1;
1.71      ng       4743: 		my $partial = $newpts/$wgt;
                   4744: 		my $score;
                   4745: 		if ($partial > 0) {
                   4746: 		    $score = 'correct_by_override';
1.125     ng       4747: 		} elsif ($newpts ne '') { #empty is taken as 0
1.71      ng       4748: 		    $score = 'incorrect_by_override';
                   4749: 		}
1.257     albertel 4750: 		my $dropMenu = $env{'form.GD_SEL'.$question.'_'.$partid};
1.125     ng       4751: 		if ($dropMenu eq 'excused') {
1.71      ng       4752: 		    $partial = '';
                   4753: 		    $score = 'excused';
1.125     ng       4754: 		} elsif ($dropMenu eq 'reset status'
1.257     albertel 4755: 			 && $env{'form.solved'.$question.'_'.$partid} ne '') { #update only if previous record exists
1.125     ng       4756: 		    $newrecord{'resource.'.$partid.'.tries'} = 0;
                   4757: 		    $newrecord{'resource.'.$partid.'.solved'} = '';
                   4758: 		    $newrecord{'resource.'.$partid.'.award'} = '';
                   4759: 		    $newrecord{'resource.'.$partid.'.awarded'} = 0;
1.257     albertel 4760: 		    $newrecord{'resource.'.$partid.'.regrader'} = "$env{'user.name'}:$env{'user.domain'}";
1.125     ng       4761: 		    $changeflag++;
                   4762: 		    $newpts = '';
1.269     raeburn  4763:                     
                   4764:                     my $aggtries =  $env{'form.aggtries'.$question.'_'.$partid};
                   4765:                     my $totaltries = $env{'form.totaltries'.$question.'_'.$partid};
                   4766:                     my $solvedstatus = $env{'form.solved'.$question.'_'.$partid};
                   4767:                     if ($aggtries > 0) {
                   4768:                         &decrement_aggs($symbx,$partid,\%aggregate,$aggtries,$totaltries,$solvedstatus);
                   4769:                         $aggregateflag = 1;
                   4770:                     }
1.71      ng       4771: 		}
1.324     albertel 4772: 		my $display_part=&get_display_part($partid,$curRes->symb());
1.257     albertel 4773: 		my $oldstatus = $env{'form.solved'.$question.'_'.$partid};
1.526     raeburn  4774: 		$displayPts[0].='&nbsp;<b>'.&mt('Part').':</b> '.$display_part.' = '.
1.71      ng       4775: 		    (($oldstatus eq 'excused') ? 'excused' : $oldpts).
1.326     albertel 4776: 		    '&nbsp;<br />';
1.526     raeburn  4777: 		$displayPts[1].='&nbsp;<b>'.&mt('Part').':</b> '.$display_part.' = '.
1.125     ng       4778: 		     (($score eq 'excused') ? 'excused' : $newpts).
1.326     albertel 4779: 		    '&nbsp;<br />';
1.71      ng       4780: 		$question++;
1.380     albertel 4781: 		next if ($dropMenu eq 'reset status' || ($newpts eq $oldpts && $score ne 'excused'));
1.125     ng       4782: 
1.71      ng       4783: 		$newrecord{'resource.'.$partid.'.awarded'}  = $partial if $partial ne '';
1.125     ng       4784: 		$newrecord{'resource.'.$partid.'.solved'}   = $score if $score ne '';
1.257     albertel 4785: 		$newrecord{'resource.'.$partid.'.regrader'} = "$env{'user.name'}:$env{'user.domain'}"
1.125     ng       4786: 		    if (scalar(keys(%newrecord)) > 0);
1.71      ng       4787: 
                   4788: 		$changeflag++;
                   4789: 	    }
                   4790: 	    if (scalar(keys(%newrecord)) > 0) {
1.382     albertel 4791: 		my %record = 
                   4792: 		    &Apache::lonnet::restore($symbx,$env{'request.course.id'},
                   4793: 					     $udom,$uname);
                   4794: 
                   4795: 		if (&Apache::lonnet::validCODE($env{'form.CODE'})) {
                   4796: 		    $newrecord{'resource.CODE'} = $env{'form.CODE'};
                   4797: 		} elsif (&Apache::lonnet::validCODE($record{'resource.CODE'})) {
                   4798: 		    $newrecord{'resource.CODE'} = '';
                   4799: 		}
1.257     albertel 4800: 		&Apache::lonnet::cstore(\%newrecord,$symbx,$env{'request.course.id'},
1.71      ng       4801: 					$udom,$uname);
1.382     albertel 4802: 		%record = &Apache::lonnet::restore($symbx,
                   4803: 						   $env{'request.course.id'},
                   4804: 						   $udom,$uname);
1.380     albertel 4805: 		&check_and_remove_from_queue($parts,\%record,undef,$symbx,
                   4806: 					     $cdom,$cnum,$udom,$uname);
1.71      ng       4807: 	    }
1.380     albertel 4808: 	    
1.269     raeburn  4809:             if ($aggregateflag) {
                   4810:                 &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
                   4811:                       $env{'course.'.$env{'request.course.id'}.'.domain'},
                   4812:                       $env{'course.'.$env{'request.course.id'}.'.num'});
                   4813:             }
1.125     ng       4814: 
1.71      ng       4815: 	    $studentTable.='<td valign="top">'.$displayPts[0].'</td>'.
                   4816: 		'<td valign="top">'.$displayPts[1].'</td>'.
1.484     albertel 4817: 		&Apache::loncommon::end_data_table_row();
1.68      ng       4818: 
1.196     albertel 4819: 	    $prob++;
1.68      ng       4820: 	}
1.71      ng       4821:         $curRes = $iterator->next();
1.68      ng       4822:     }
1.98      albertel 4823: 
1.484     albertel 4824:     $studentTable.=&Apache::loncommon::end_data_table();
1.324     albertel 4825:     $studentTable.=&show_grading_menu_form($env{'form.symb'});
1.526     raeburn  4826:     my $grademsg=($changeflag == 0 ? &mt('No score was changed or updated.') :
                   4827: 		  &mt('The scores were changed for [quant,_1,problem].',
                   4828: 		  $changeflag));
1.76      ng       4829:     $request->print($grademsg.$studentTable);
1.68      ng       4830: 
1.70      ng       4831:     return '';
                   4832: }
                   4833: 
1.72      ng       4834: #-------- end of section for handling grading by page/sequence ---------
                   4835: #
                   4836: #-------------------------------------------------------------------
                   4837: 
1.581     www      4838: #-------------------- Bubblesheet (Scantron) Grading -------------------
1.75      albertel 4839: #
                   4840: #------ start of section for handling grading by page/sequence ---------
                   4841: 
1.423     albertel 4842: =pod
                   4843: 
                   4844: =head1 Bubble sheet grading routines
                   4845: 
1.424     albertel 4846:   For this documentation:
                   4847: 
                   4848:    'scanline' refers to the full line of characters
                   4849:    from the file that we are parsing that represents one entire sheet
                   4850: 
                   4851:    'bubble line' refers to the data
                   4852:    representing the line of bubbles that are on the physical bubble sheet
                   4853: 
                   4854: 
                   4855: The overall process is that a scanned in bubble sheet data is uploaded
                   4856: into a course. When a user wants to grade, they select a
                   4857: sequence/folder of resources, a file of bubble sheet info, and pick
                   4858: one of the predefined configurations for what each scanline looks
                   4859: like.
                   4860: 
                   4861: Next each scanline is checked for any errors of either 'missing
1.435     foxr     4862: bubbles' (it's an error because it may have been mis-scanned
1.424     albertel 4863: because too light bubbling), 'double bubble' (each bubble line should
                   4864: have no more that one letter picked), invalid or duplicated CODE,
1.556     weissno  4865: invalid student/employee ID
1.424     albertel 4866: 
                   4867: If the CODE option is used that determines the randomization of the
1.556     weissno  4868: homework problems, either way the student/employee ID is looked up into a
1.424     albertel 4869: username:domain.
                   4870: 
                   4871: During the validation phase the instructor can choose to skip scanlines. 
                   4872: 
1.435     foxr     4873: After the validation phase, there are now 3 bubble sheet files
1.424     albertel 4874: 
                   4875:   scantron_original_filename (unmodified original file)
                   4876:   scantron_corrected_filename (file where the corrected information has replaced the original information)
                   4877:   scantron_skipped_filename (contains the exact text of scanlines that where skipped)
                   4878: 
                   4879: Also there is a separate hash nohist_scantrondata that contains extra
                   4880: correction information that isn't representable in the bubble sheet
                   4881: file (see &scantron_getfile() for more information)
                   4882: 
                   4883: After all scanlines are either valid, marked as valid or skipped, then
                   4884: foreach line foreach problem in the picked sequence, an ssi request is
                   4885: made that simulates a user submitting their selected letter(s) against
                   4886: the homework problem.
1.423     albertel 4887: 
                   4888: =over 4
                   4889: 
                   4890: 
                   4891: 
                   4892: =item defaultFormData
                   4893: 
                   4894:   Returns html hidden inputs used to hold context/default values.
                   4895: 
                   4896:  Arguments:
                   4897:   $symb - $symb of the current resource 
                   4898: 
                   4899: =cut
1.422     foxr     4900: 
1.81      albertel 4901: sub defaultFormData {
1.324     albertel 4902:     my ($symb)=@_;
1.447     foxr     4903:     return '<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.257     albertel 4904:      '<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n".
                   4905:      '<input type="hidden" name="probTitle" value="'.$env{'form.probTitle'}.'" />'."\n";
1.81      albertel 4906: }
                   4907: 
1.447     foxr     4908: 
1.423     albertel 4909: =pod 
                   4910: 
                   4911: =item getSequenceDropDown
                   4912: 
                   4913:    Return html dropdown of possible sequences to grade
                   4914:  
                   4915:  Arguments:
1.582     raeburn  4916:    $symb - $symb of the current resource
                   4917:    $map_error - ref to scalar which will container error if
                   4918:                 $navmap object is unavailable in &getSymbMap().
1.423     albertel 4919: 
                   4920: =cut
1.422     foxr     4921: 
1.75      albertel 4922: sub getSequenceDropDown {
1.582     raeburn  4923:     my ($symb,$map_error)=@_;
1.75      albertel 4924:     my $result='<select name="selectpage">'."\n";
1.582     raeburn  4925:     my ($titles,$symbx) = &getSymbMap($map_error);
                   4926:     if (ref($map_error)) {
                   4927:         return if ($$map_error);
                   4928:     }
1.137     albertel 4929:     my ($curpage)=&Apache::lonnet::decode_symb($symb); 
1.75      albertel 4930:     my $ctr=0;
                   4931:     foreach (@$titles) {
                   4932: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
                   4933: 	$result.='<option value="'.$$symbx{$_}.'" '.
1.401     albertel 4934: 	    ($$symbx{$_} =~ /$curpage$/ ? 'selected="selected"' : '').
1.75      albertel 4935: 	    '>'.$showtitle.'</option>'."\n";
                   4936: 	$ctr++;
                   4937:     }
                   4938:     $result.= '</select>';
                   4939:     return $result;
                   4940: }
                   4941: 
1.495     albertel 4942: my %bubble_lines_per_response;     # no. bubble lines for each response.
1.554     raeburn  4943:                                    # key is zero-based index - 0, 1, 2 ...
1.495     albertel 4944: 
                   4945: my %first_bubble_line;             # First bubble line no. for each bubble.
                   4946: 
1.509     raeburn  4947: my %subdivided_bubble_lines;       # no. bubble lines for optionresponse, 
                   4948:                                    # matchresponse or rankresponse, where 
                   4949:                                    # an individual response can have multiple 
                   4950:                                    # lines
1.503     raeburn  4951: 
                   4952: my %responsetype_per_response;     # responsetype for each response
                   4953: 
1.495     albertel 4954: # Save and restore the bubble lines array to the form env.
                   4955: 
                   4956: 
                   4957: sub save_bubble_lines {
                   4958:     foreach my $line (keys(%bubble_lines_per_response)) {
                   4959: 	$env{"form.scantron.bubblelines.$line"}  = $bubble_lines_per_response{$line};
                   4960: 	$env{"form.scantron.first_bubble_line.$line"} =
                   4961: 	    $first_bubble_line{$line};
1.503     raeburn  4962:         $env{"form.scantron.sub_bubblelines.$line"} = 
                   4963:             $subdivided_bubble_lines{$line};
                   4964:         $env{"form.scantron.responsetype.$line"} =
                   4965:             $responsetype_per_response{$line};
1.495     albertel 4966:     }
                   4967: }
                   4968: 
                   4969: 
                   4970: sub restore_bubble_lines {
                   4971:     my $line = 0;
                   4972:     %bubble_lines_per_response = ();
                   4973:     while ($env{"form.scantron.bubblelines.$line"}) {
                   4974: 	my $value = $env{"form.scantron.bubblelines.$line"};
                   4975: 	$bubble_lines_per_response{$line} = $value;
                   4976: 	$first_bubble_line{$line}  =
                   4977: 	    $env{"form.scantron.first_bubble_line.$line"};
1.503     raeburn  4978:         $subdivided_bubble_lines{$line} =
                   4979:             $env{"form.scantron.sub_bubblelines.$line"};
                   4980:         $responsetype_per_response{$line} =
                   4981:             $env{"form.scantron.responsetype.$line"};
1.495     albertel 4982: 	$line++;
                   4983:     }
                   4984: }
                   4985: 
                   4986: #  Given the parsed scanline, get the response for 
                   4987: #  'answer' number n:
                   4988: 
                   4989: sub get_response_bubbles {
                   4990:     my ($parsed_line, $response)  = @_;
                   4991: 
                   4992:     my $bubble_line = $first_bubble_line{$response-1} +1;
                   4993:     my $bubble_lines= $bubble_lines_per_response{$response-1};
                   4994:     
                   4995:     my $selected = "";
                   4996: 
                   4997:     for (my $bline = 0; $bline < $bubble_lines; $bline++) {
                   4998: 	$selected .= $$parsed_line{"scantron.$bubble_line.answer"}.":";
                   4999: 	$bubble_line++;
                   5000:     }
                   5001:     return $selected;
                   5002: }
1.423     albertel 5003: 
                   5004: =pod 
                   5005: 
                   5006: =item scantron_filenames
                   5007: 
                   5008:    Returns a list of the scantron files in the current course 
                   5009: 
                   5010: =cut
1.422     foxr     5011: 
1.202     albertel 5012: sub scantron_filenames {
1.257     albertel 5013:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   5014:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
1.517     raeburn  5015:     my $getpropath = 1;
1.157     albertel 5016:     my @files=&Apache::lonnet::dirlist('userfiles',$cdom,$cname,
1.517     raeburn  5017:                                        $getpropath);
1.202     albertel 5018:     my @possiblenames;
1.201     albertel 5019:     foreach my $filename (sort(@files)) {
1.157     albertel 5020: 	($filename)=split(/&/,$filename);
                   5021: 	if ($filename!~/^scantron_orig_/) { next ; }
                   5022: 	$filename=~s/^scantron_orig_//;
1.202     albertel 5023: 	push(@possiblenames,$filename);
                   5024:     }
                   5025:     return @possiblenames;
                   5026: }
                   5027: 
1.423     albertel 5028: =pod 
                   5029: 
                   5030: =item scantron_uploads
                   5031: 
                   5032:    Returns  html drop-down list of scantron files in current course.
                   5033: 
                   5034:  Arguments:
                   5035:    $file2grade - filename to set as selected in the dropdown
                   5036: 
                   5037: =cut
1.422     foxr     5038: 
1.202     albertel 5039: sub scantron_uploads {
1.209     ng       5040:     my ($file2grade) = @_;
1.202     albertel 5041:     my $result=	'<select name="scantron_selectfile">';
                   5042:     $result.="<option></option>";
                   5043:     foreach my $filename (sort(&scantron_filenames())) {
1.401     albertel 5044: 	$result.="<option".($filename eq $file2grade ? ' selected="selected"':'').">$filename</option>\n";
1.81      albertel 5045:     }
                   5046:     $result.="</select>";
                   5047:     return $result;
                   5048: }
                   5049: 
1.423     albertel 5050: =pod 
                   5051: 
                   5052: =item scantron_scantab
                   5053: 
                   5054:   Returns html drop down of the scantron formats in the scantronformat.tab
                   5055:   file.
                   5056: 
                   5057: =cut
1.422     foxr     5058: 
1.82      albertel 5059: sub scantron_scantab {
                   5060:     my $result='<select name="scantron_format">'."\n";
1.191     albertel 5061:     $result.='<option></option>'."\n";
1.518     raeburn  5062:     my @lines = &get_scantronformat_file();
                   5063:     if (@lines > 0) {
                   5064:         foreach my $line (@lines) {
                   5065:             next if (($line =~ /^\#/) || ($line eq ''));
                   5066: 	    my ($name,$descrip)=split(/:/,$line);
                   5067: 	    $result.='<option value="'.$name.'">'.$descrip.'</option>'."\n";
                   5068:         }
1.82      albertel 5069:     }
                   5070:     $result.='</select>'."\n";
1.518     raeburn  5071:     return $result;
                   5072: }
                   5073: 
                   5074: =pod
                   5075: 
                   5076: =item get_scantronformat_file
                   5077: 
                   5078:   Returns an array containing lines from the scantron format file for
                   5079:   the domain of the course.
                   5080: 
                   5081:   If a url for a custom.tab file is listed in domain's configuration.db, 
                   5082:   lines are from this file.
                   5083: 
                   5084:   Otherwise, if a default.tab has been published in RES space by the 
                   5085:   domainconfig user, lines are from this file.
                   5086: 
                   5087:   Otherwise, fall back to getting lines from the legacy file on the
1.519     raeburn  5088:   local server:  /home/httpd/lonTabs/default_scantronformat.tab    
1.82      albertel 5089: 
1.518     raeburn  5090: =cut
                   5091: 
                   5092: sub get_scantronformat_file {
                   5093:     my $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
                   5094:     my %domconfig = &Apache::lonnet::get_dom('configuration',['scantron'],$cdom);
                   5095:     my $gottab = 0;
                   5096:     my @lines;
                   5097:     if (ref($domconfig{'scantron'}) eq 'HASH') {
                   5098:         if ($domconfig{'scantron'}{'scantronformat'} ne '') {
                   5099:             my $formatfile = &Apache::lonnet::getfile($Apache::lonnet::perlvar{'lonDocRoot'}.$domconfig{'scantron'}{'scantronformat'});
                   5100:             if ($formatfile ne '-1') {
                   5101:                 @lines = split("\n",$formatfile,-1);
                   5102:                 $gottab = 1;
                   5103:             }
                   5104:         }
                   5105:     }
                   5106:     if (!$gottab) {
                   5107:         my $confname = $cdom.'-domainconfig';
                   5108:         my $default = $Apache::lonnet::perlvar{'lonDocRoot'}.'/res/'.$cdom.'/'.$confname.'/default.tab';
                   5109:         my $formatfile =  &Apache::lonnet::getfile($default);
                   5110:         if ($formatfile ne '-1') {
                   5111:             @lines = split("\n",$formatfile,-1);
                   5112:             $gottab = 1;
                   5113:         }
                   5114:     }
                   5115:     if (!$gottab) {
1.519     raeburn  5116:         my @domains = &Apache::lonnet::current_machine_domains();
                   5117:         if (grep(/^\Q$cdom\E$/,@domains)) {
                   5118:             my $fh=Apache::File->new($Apache::lonnet::perlvar{'lonTabDir'}.'/scantronformat.tab');
                   5119:             @lines = <$fh>;
                   5120:             close($fh);
                   5121:         } else {
                   5122:             my $fh=Apache::File->new($Apache::lonnet::perlvar{'lonTabDir'}.'/default_scantronformat.tab');
                   5123:             @lines = <$fh>;
                   5124:             close($fh);
                   5125:         }
1.518     raeburn  5126:     }
                   5127:     return @lines;
1.82      albertel 5128: }
                   5129: 
1.423     albertel 5130: =pod 
                   5131: 
                   5132: =item scantron_CODElist
                   5133: 
                   5134:   Returns html drop down of the saved CODE lists from current course,
                   5135:   generated from earlier printings.
                   5136: 
                   5137: =cut
1.422     foxr     5138: 
1.186     albertel 5139: sub scantron_CODElist {
1.257     albertel 5140:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   5141:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
1.186     albertel 5142:     my @names=&Apache::lonnet::getkeys('CODEs',$cdom,$cnum);
                   5143:     my $namechoice='<option></option>';
1.225     albertel 5144:     foreach my $name (sort {uc($a) cmp uc($b)} @names) {
1.191     albertel 5145: 	if ($name =~ /^error: 2 /) { next; }
1.278     albertel 5146: 	if ($name =~ /^type\0/) { next; }
1.186     albertel 5147: 	$namechoice.='<option value="'.$name.'">'.$name.'</option>';
                   5148:     }
                   5149:     $namechoice='<select name="scantron_CODElist">'.$namechoice.'</select>';
                   5150:     return $namechoice;
                   5151: }
                   5152: 
1.423     albertel 5153: =pod 
                   5154: 
                   5155: =item scantron_CODEunique
                   5156: 
                   5157:   Returns the html for "Each CODE to be used once" radio.
                   5158: 
                   5159: =cut
1.422     foxr     5160: 
1.186     albertel 5161: sub scantron_CODEunique {
1.532     bisitz   5162:     my $result='<span class="LC_nobreak">
1.272     albertel 5163:                  <label><input type="radio" name="scantron_CODEunique"
1.423     albertel 5164:                         value="yes" checked="checked" />'.&mt('Yes').' </label>
1.381     albertel 5165:                 </span>
1.532     bisitz   5166:                 <span class="LC_nobreak">
1.272     albertel 5167:                  <label><input type="radio" name="scantron_CODEunique"
1.423     albertel 5168:                         value="no" />'.&mt('No').' </label>
1.381     albertel 5169:                 </span>';
1.186     albertel 5170:     return $result;
                   5171: }
1.423     albertel 5172: 
                   5173: =pod 
                   5174: 
                   5175: =item scantron_selectphase
                   5176: 
                   5177:   Generates the initial screen to start the bubble sheet process.
                   5178:   Allows for - starting a grading run.
1.424     albertel 5179:              - downloading existing scan data (original, corrected
1.423     albertel 5180:                                                 or skipped info)
                   5181: 
                   5182:              - uploading new scan data
                   5183: 
                   5184:  Arguments:
                   5185:   $r          - The Apache request object
                   5186:   $file2grade - name of the file that contain the scanned data to score
                   5187: 
                   5188: =cut
1.186     albertel 5189: 
1.75      albertel 5190: sub scantron_selectphase {
1.209     ng       5191:     my ($r,$file2grade) = @_;
1.324     albertel 5192:     my ($symb)=&get_symb($r);
1.75      albertel 5193:     if (!$symb) {return '';}
1.582     raeburn  5194:     my $map_error;
                   5195:     my $sequence_selector=&getSequenceDropDown($symb,\$map_error);
                   5196:     if ($map_error) {
                   5197:         $r->print('<br />'.&navmap_errormsg().'<br />');
                   5198:         return;
                   5199:     }
1.324     albertel 5200:     my $default_form_data=&defaultFormData($symb);
                   5201:     my $grading_menu_button=&show_grading_menu_form($symb);
1.209     ng       5202:     my $file_selector=&scantron_uploads($file2grade);
1.82      albertel 5203:     my $format_selector=&scantron_scantab();
1.186     albertel 5204:     my $CODE_selector=&scantron_CODElist();
                   5205:     my $CODE_unique=&scantron_CODEunique();
1.75      albertel 5206:     my $result;
1.422     foxr     5207: 
1.513     foxr     5208:     $ssi_error = 0;
                   5209: 
1.422     foxr     5210:     # Chunk of form to prompt for a file to grade and how:
                   5211: 
1.489     albertel 5212:     $result.= '
                   5213:     <br />
                   5214:     <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantron_process">
                   5215:     <input type="hidden" name="command" value="scantron_warning" />
                   5216:     '.$default_form_data.'
                   5217:     '.&Apache::loncommon::start_data_table('LC_scantron_action').'
                   5218:        '.&Apache::loncommon::start_data_table_header_row().'
                   5219:             <th colspan="2">
1.492     albertel 5220:               &nbsp;'.&mt('Specify file and which Folder/Sequence to grade').'
1.489     albertel 5221:             </th>
                   5222:        '.&Apache::loncommon::end_data_table_header_row().'
                   5223:        '.&Apache::loncommon::start_data_table_row().'
1.492     albertel 5224:             <td> '.&mt('Sequence to grade:').' </td><td> '.$sequence_selector.' </td>
1.489     albertel 5225:        '.&Apache::loncommon::end_data_table_row().'
                   5226:        '.&Apache::loncommon::start_data_table_row().'
1.572     www      5227:             <td> '.&mt('Filename of bubblesheet data file:').' </td><td> '.$file_selector.' </td>
1.489     albertel 5228:        '.&Apache::loncommon::end_data_table_row().'
                   5229:        '.&Apache::loncommon::start_data_table_row().'
1.572     www      5230:             <td> '.&mt('Format of bubblesheet data file:').' </td><td> '.$format_selector.' </td>
1.489     albertel 5231:        '.&Apache::loncommon::end_data_table_row().'
                   5232:        '.&Apache::loncommon::start_data_table_row().'
1.492     albertel 5233:             <td> '.&mt('Saved CODEs to validate against:').' </td><td> '.$CODE_selector.' </td>
1.489     albertel 5234:        '.&Apache::loncommon::end_data_table_row().'
                   5235:        '.&Apache::loncommon::start_data_table_row().'
1.492     albertel 5236:             <td> '.&mt('Each CODE is only to be used once:').'</td><td> '.$CODE_unique.' </td>
1.489     albertel 5237:        '.&Apache::loncommon::end_data_table_row().'
                   5238:        '.&Apache::loncommon::start_data_table_row().'
1.492     albertel 5239: 	    <td> '.&mt('Options:').' </td>
1.187     albertel 5240:             <td>
1.492     albertel 5241: 	       <label><input type="checkbox" name="scantron_options_redo" value="redo_skipped"/> '.&mt('Do only previously skipped records').'</label> <br />
                   5242:                <label><input type="checkbox" name="scantron_options_ignore" value="ignore_corrections"/> '.&mt('Remove all existing corrections').'</label> <br />
                   5243:                <label><input type="checkbox" name="scantron_options_hidden" value="ignore_hidden"/> '.&mt('Skip hidden resources when grading').'</label>
1.187     albertel 5244: 	    </td>
1.489     albertel 5245:        '.&Apache::loncommon::end_data_table_row().'
                   5246:        '.&Apache::loncommon::start_data_table_row().'
1.174     albertel 5247:             <td colspan="2">
1.572     www      5248:               <input type="submit" value="'.&mt('Grading: Validate Bubblesheet Records').'" />
1.162     albertel 5249:             </td>
1.489     albertel 5250:        '.&Apache::loncommon::end_data_table_row().'
                   5251:     '.&Apache::loncommon::end_data_table().'
                   5252:     </form>
                   5253: ';
1.162     albertel 5254:    
                   5255:     $r->print($result);
                   5256: 
1.257     albertel 5257:     if (&Apache::lonnet::allowed('usc',$env{'request.role.domain'}) ||
                   5258:         &Apache::lonnet::allowed('usc',$env{'request.course.id'})) {
1.162     albertel 5259: 
1.422     foxr     5260: 	# Chunk of form to prompt for a scantron file upload.
                   5261: 
1.489     albertel 5262:         $r->print('
                   5263:     <br />
                   5264:     '.&Apache::loncommon::start_data_table('LC_scantron_action').'
                   5265:        '.&Apache::loncommon::start_data_table_header_row().'
                   5266:             <th>
1.572     www      5267:               &nbsp;'.&mt('Specify a bubblesheet data file to upload.').'
1.489     albertel 5268:             </th>
                   5269:        '.&Apache::loncommon::end_data_table_header_row().'
                   5270:        '.&Apache::loncommon::start_data_table_row().'
1.162     albertel 5271:             <td>
1.489     albertel 5272: ');
1.324     albertel 5273:     my $default_form_data=&defaultFormData(&get_symb($r,1));
1.257     albertel 5274:     my $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
                   5275:     my $cnum= $env{'course.'.$env{'request.course.id'}.'.num'};
1.597     wenzelju 5276:     $r->print(&Apache::lonhtmlcommon::scripttag('
1.174     albertel 5277:     function checkUpload(formname) {
                   5278: 	if (formname.upfile.value == "") {
1.492     albertel 5279: 	    alert("'.&mt('Please use the browse button to select a file from your local directory.').'");
1.174     albertel 5280: 	    return false;
                   5281: 	}
                   5282: 	formname.submit();
1.597     wenzelju 5283:     }'));
                   5284:     $r->print('
1.492     albertel 5285:               <form enctype="multipart/form-data" action="/adm/grades" name="rules" method="post">
                   5286:                 '.$default_form_data.'
                   5287:                 <input name="courseid" type="hidden" value="'.$cnum.'" />
                   5288:                 <input name="domainid" type="hidden" value="'.$cdom.'" />
                   5289:                 <input name="command" value="scantronupload_save" type="hidden" />
                   5290:                 '.&mt('File to upload: [_1]','<input type="file" name="upfile" size="50" />').'
1.174     albertel 5291:                 <br />
1.589     bisitz   5292:                 <input type="button" onclick="javascript:checkUpload(this.form);" value="'.&mt('Upload Bubblesheet Data').'" />
1.174     albertel 5293:               </form>
1.492     albertel 5294: ');
1.162     albertel 5295: 
1.489     albertel 5296:         $r->print('
1.162     albertel 5297:             </td>
1.489     albertel 5298:        '.&Apache::loncommon::end_data_table_row().'
                   5299:        '.&Apache::loncommon::end_data_table().'
                   5300: ');
1.162     albertel 5301:     }
1.422     foxr     5302: 
                   5303:     # Chunk of the form that prompts to view a scoring office file,
                   5304:     # corrected file, skipped records in a file.
                   5305: 
1.489     albertel 5306:     $r->print('
                   5307:    <br />
                   5308:    <form action="/adm/grades" name="scantron_download">
                   5309:      '.$default_form_data.'
                   5310:      <input type="hidden" name="command" value="scantron_download" />
                   5311:      '.&Apache::loncommon::start_data_table('LC_scantron_action').'
                   5312:        '.&Apache::loncommon::start_data_table_header_row().'
                   5313:               <th>
1.492     albertel 5314:                 &nbsp;'.&mt('Download a scoring office file').'
1.489     albertel 5315:               </th>
                   5316:        '.&Apache::loncommon::end_data_table_header_row().'
                   5317:        '.&Apache::loncommon::start_data_table_row().'
1.492     albertel 5318:               <td> '.&mt('Filename of scoring office file: [_1]',$file_selector).' 
1.489     albertel 5319:                 <br />
1.492     albertel 5320:                 <input type="submit" value="'.&mt('Download: Show List of Associated Files').'" />
1.489     albertel 5321:        '.&Apache::loncommon::end_data_table_row().'
                   5322:      '.&Apache::loncommon::end_data_table().'
                   5323:    </form>
                   5324:    <br />
                   5325: ');
1.162     albertel 5326: 
1.457     banghart 5327:     &Apache::lonpickcode::code_list($r,2);
1.523     raeburn  5328: 
1.528     raeburn  5329:     $r->print('<br /><form method="post" name="checkscantron">'.
1.523     raeburn  5330:              $default_form_data."\n".
                   5331:              &Apache::loncommon::start_data_table('LC_scantron_action')."\n".
                   5332:              &Apache::loncommon::start_data_table_header_row()."\n".
                   5333:              '<th colspan="2">
1.572     www      5334:               &nbsp;'.&mt('Review bubblesheet data and submissions for a previously graded folder/sequence')."\n".
1.523     raeburn  5335:              '</th>'."\n".
                   5336:               &Apache::loncommon::end_data_table_header_row()."\n".
                   5337:               &Apache::loncommon::start_data_table_row()."\n".
                   5338:               '<td> '.&mt('Graded folder/sequence:').' </td>'."\n".
                   5339:               '<td> '.$sequence_selector.' </td>'.
                   5340:               &Apache::loncommon::end_data_table_row()."\n".
                   5341:               &Apache::loncommon::start_data_table_row()."\n".
                   5342:               '<td> '.&mt('Filename of scoring office file:').' </td>'."\n".
                   5343:               '<td> '.$file_selector.' </td>'."\n".
                   5344:               &Apache::loncommon::end_data_table_row()."\n".
                   5345:               &Apache::loncommon::start_data_table_row()."\n".
                   5346:               '<td> '.&mt('Format of data file:').' </td>'."\n".
                   5347:               '<td> '.$format_selector.' </td>'."\n".
                   5348:               &Apache::loncommon::end_data_table_row()."\n".
                   5349:               &Apache::loncommon::start_data_table_row()."\n".
1.557     raeburn  5350:               '<td> '.&mt('Options').' </td>'."\n".
                   5351:               '<td> <label><input type="checkbox" name="scantron_options_hidden" value="ignore_hidden"/> '.&mt('Skip hidden resources').'</label></td>'.
                   5352:               &Apache::loncommon::end_data_table_row()."\n".
                   5353:               &Apache::loncommon::start_data_table_row()."\n".
1.523     raeburn  5354:               '<td colspan="2">'."\n".
                   5355:               '<input type="hidden" name="command" value="checksubmissions" />'."\n".
1.575     www      5356:               '<input type="submit" value="'.&mt('Review Bubblesheet Data and Submission Records').'" />'."\n".
1.523     raeburn  5357:               '</td>'."\n".
                   5358:               &Apache::loncommon::end_data_table_row()."\n".
                   5359:               &Apache::loncommon::end_data_table()."\n".
                   5360:               '</form><br />');
1.457     banghart 5361:     $r->print($grading_menu_button);
1.523     raeburn  5362:     return;
1.75      albertel 5363: }
                   5364: 
1.423     albertel 5365: =pod
                   5366: 
                   5367: =item get_scantron_config
                   5368: 
                   5369:    Parse and return the scantron configuration line selected as a
                   5370:    hash of configuration file fields.
                   5371: 
                   5372:  Arguments:
                   5373:     which - the name of the configuration to parse from the file.
                   5374: 
                   5375: 
                   5376:  Returns:
                   5377:             If the named configuration is not in the file, an empty
                   5378:             hash is returned.
                   5379:     a hash with the fields
                   5380:       name         - internal name for the this configuration setup
                   5381:       description  - text to display to operator that describes this config
                   5382:       CODElocation - if 0 or the string 'none'
                   5383:                           - no CODE exists for this config
                   5384:                      if -1 || the string 'letter'
                   5385:                           - a CODE exists for this config and is
                   5386:                             a string of letters
                   5387:                      Unsupported value (but planned for future support)
                   5388:                           if a positive integer
                   5389:                                - The CODE exists as the first n items from
                   5390:                                  the question section of the form
                   5391:                           if the string 'number'
                   5392:                                - The CODE exists for this config and is
                   5393:                                  a string of numbers
                   5394:       CODEstart   - (only matter if a CODE exists) column in the line where
                   5395:                      the CODE starts
                   5396:       CODElength  - length of the CODE
1.573     bisitz   5397:       IDstart     - column where the student/employee ID starts
1.556     weissno  5398:       IDlength    - length of the student/employee ID info
1.423     albertel 5399:       Qstart      - column where the information from the bubbled
                   5400:                     'questions' start
                   5401:       Qlength     - number of columns comprising a single bubble line from
                   5402:                     the sheet. (usually either 1 or 10)
1.424     albertel 5403:       Qon         - either a single character representing the character used
1.423     albertel 5404:                     to signal a bubble was chosen in the positional setup, or
                   5405:                     the string 'letter' if the letter of the chosen bubble is
                   5406:                     in the final, or 'number' if a number representing the
                   5407:                     chosen bubble is in the file (1->A 0->J)
1.424     albertel 5408:       Qoff        - the character used to represent that a bubble was
                   5409:                     left blank
1.423     albertel 5410:       PaperID     - if the scanning process generates a unique number for each
                   5411:                     sheet scanned the column that this ID number starts in
                   5412:       PaperIDlength - number of columns that comprise the unique ID number
                   5413:                       for the sheet of paper
1.424     albertel 5414:       FirstName   - column that the first name starts in
1.423     albertel 5415:       FirstNameLength - number of columns that the first name spans
                   5416:  
                   5417:       LastName    - column that the last name starts in
                   5418:       LastNameLength - number of columns that the last name spans
                   5419: 
                   5420: =cut
1.422     foxr     5421: 
1.82      albertel 5422: sub get_scantron_config {
                   5423:     my ($which) = @_;
1.518     raeburn  5424:     my @lines = &get_scantronformat_file();
1.82      albertel 5425:     my %config;
1.157     albertel 5426:     #FIXME probably should move to XML it has already gotten a bit much now
1.518     raeburn  5427:     foreach my $line (@lines) {
1.82      albertel 5428: 	my ($name,$descrip)=split(/:/,$line);
                   5429: 	if ($name ne $which ) { next; }
                   5430: 	chomp($line);
                   5431: 	my @config=split(/:/,$line);
                   5432: 	$config{'name'}=$config[0];
                   5433: 	$config{'description'}=$config[1];
                   5434: 	$config{'CODElocation'}=$config[2];
                   5435: 	$config{'CODEstart'}=$config[3];
                   5436: 	$config{'CODElength'}=$config[4];
                   5437: 	$config{'IDstart'}=$config[5];
                   5438: 	$config{'IDlength'}=$config[6];
                   5439: 	$config{'Qstart'}=$config[7];
1.497     foxr     5440:  	$config{'Qlength'}=$config[8];
1.82      albertel 5441: 	$config{'Qoff'}=$config[9];
                   5442: 	$config{'Qon'}=$config[10];
1.157     albertel 5443: 	$config{'PaperID'}=$config[11];
                   5444: 	$config{'PaperIDlength'}=$config[12];
                   5445: 	$config{'FirstName'}=$config[13];
                   5446: 	$config{'FirstNamelength'}=$config[14];
                   5447: 	$config{'LastName'}=$config[15];
                   5448: 	$config{'LastNamelength'}=$config[16];
1.82      albertel 5449: 	last;
                   5450:     }
                   5451:     return %config;
                   5452: }
                   5453: 
1.423     albertel 5454: =pod 
                   5455: 
                   5456: =item username_to_idmap
                   5457: 
1.556     weissno  5458:     creates a hash keyed by student/employee ID with values of the corresponding
1.423     albertel 5459:     student username:domain.
                   5460: 
                   5461:   Arguments:
                   5462: 
                   5463:     $classlist - reference to the class list hash. This is a hash
                   5464:                  keyed by student name:domain  whose elements are references
1.424     albertel 5465:                  to arrays containing various chunks of information
1.423     albertel 5466:                  about the student. (See loncoursedata for more info).
                   5467: 
                   5468:   Returns
                   5469:     %idmap - the constructed hash
                   5470: 
                   5471: =cut
                   5472: 
1.82      albertel 5473: sub username_to_idmap {
                   5474:     my ($classlist)= @_;
                   5475:     my %idmap;
                   5476:     foreach my $student (keys(%$classlist)) {
                   5477: 	$idmap{$classlist->{$student}->[&Apache::loncoursedata::CL_ID]}=
                   5478: 	    $student;
                   5479:     }
                   5480:     return %idmap;
                   5481: }
1.423     albertel 5482: 
                   5483: =pod
                   5484: 
1.424     albertel 5485: =item scantron_fixup_scanline
1.423     albertel 5486: 
                   5487:    Process a requested correction to a scanline.
                   5488: 
                   5489:   Arguments:
                   5490:     $scantron_config   - hash from &get_scantron_config()
                   5491:     $scan_data         - hash of correction information 
                   5492:                           (see &scantron_getfile())
                   5493:     $line              - existing scanline
                   5494:     $whichline         - line number of the passed in scanline
                   5495:     $field             - type of change to process 
                   5496:                          (either 
1.573     bisitz   5497:                           'ID'     -> correct the student/employee ID
1.423     albertel 5498:                           'CODE'   -> correct the CODE
                   5499:                           'answer' -> fixup the submitted answers)
                   5500:     
                   5501:    $args               - hash of additional info,
                   5502:                           - 'ID' 
                   5503:                                'newid' -> studentID to use in replacement
1.424     albertel 5504:                                           of existing one
1.423     albertel 5505:                           - 'CODE' 
                   5506:                                'CODE_ignore_dup' - set to true if duplicates
                   5507:                                                    should be ignored.
                   5508: 	                       'CODE' - is new code or 'use_unfound'
1.424     albertel 5509:                                         if the existing unfound code should
1.423     albertel 5510:                                         be used as is
                   5511:                           - 'answer'
                   5512:                                'response' - new answer or 'none' if blank
                   5513:                                'question' - the bubble line to change
1.503     raeburn  5514:                                'questionnum' - the question identifier,
                   5515:                                                may include subquestion. 
1.423     albertel 5516: 
                   5517:   Returns:
                   5518:     $line - the modified scanline
                   5519: 
                   5520:   Side effects: 
                   5521:     $scan_data - may be updated
                   5522: 
                   5523: =cut
                   5524: 
1.82      albertel 5525: 
1.157     albertel 5526: sub scantron_fixup_scanline {
                   5527:     my ($scantron_config,$scan_data,$line,$whichline,$field,$args)=@_;
                   5528:     if ($field eq 'ID') {
                   5529: 	if (length($args->{'newid'}) > $$scantron_config{'IDlength'}) {
1.186     albertel 5530: 	    return ($line,1,'New value too large');
1.157     albertel 5531: 	}
                   5532: 	if (length($args->{'newid'}) < $$scantron_config{'IDlength'}) {
                   5533: 	    $args->{'newid'}=sprintf('%-'.$$scantron_config{'IDlength'}.'s',
                   5534: 				     $args->{'newid'});
                   5535: 	}
                   5536: 	substr($line,$$scantron_config{'IDstart'}-1,
                   5537: 	       $$scantron_config{'IDlength'})=$args->{'newid'};
                   5538: 	if ($args->{'newid'}=~/^\s*$/) {
                   5539: 	    &scan_data($scan_data,"$whichline.user",
                   5540: 		       $args->{'username'}.':'.$args->{'domain'});
                   5541: 	}
1.186     albertel 5542:     } elsif ($field eq 'CODE') {
1.192     albertel 5543: 	if ($args->{'CODE_ignore_dup'}) {
                   5544: 	    &scan_data($scan_data,"$whichline.CODE_ignore_dup",'1');
                   5545: 	}
                   5546: 	&scan_data($scan_data,"$whichline.useCODE",'1');
                   5547: 	if ($args->{'CODE'} ne 'use_unfound') {
1.191     albertel 5548: 	    if (length($args->{'CODE'}) > $$scantron_config{'CODElength'}) {
                   5549: 		return ($line,1,'New CODE value too large');
                   5550: 	    }
                   5551: 	    if (length($args->{'CODE'}) < $$scantron_config{'CODElength'}) {
                   5552: 		$args->{'CODE'}=sprintf('%-'.$$scantron_config{'CODElength'}.'s',$args->{'CODE'});
                   5553: 	    }
                   5554: 	    substr($line,$$scantron_config{'CODEstart'}-1,
                   5555: 		   $$scantron_config{'CODElength'})=$args->{'CODE'};
1.186     albertel 5556: 	}
1.157     albertel 5557:     } elsif ($field eq 'answer') {
1.497     foxr     5558: 	my $length=$scantron_config->{'Qlength'};
1.157     albertel 5559: 	my $off=$scantron_config->{'Qoff'};
                   5560: 	my $on=$scantron_config->{'Qon'};
1.497     foxr     5561: 	my $answer=${off}x$length;
                   5562: 	if ($args->{'response'} eq 'none') {
                   5563: 	    &scan_data($scan_data,
1.503     raeburn  5564: 		       "$whichline.no_bubble.".$args->{'questionnum'},'1');
1.497     foxr     5565: 	} else {
                   5566: 	    if ($on eq 'letter') {
                   5567: 		my @alphabet=('A'..'Z');
                   5568: 		$answer=$alphabet[$args->{'response'}];
                   5569: 	    } elsif ($on eq 'number') {
                   5570: 		$answer=$args->{'response'}+1;
                   5571: 		if ($answer == 10) { $answer = '0'; }
1.274     albertel 5572: 	    } else {
1.497     foxr     5573: 		substr($answer,$args->{'response'},1)=$on;
1.274     albertel 5574: 	    }
1.497     foxr     5575: 	    &scan_data($scan_data,
1.503     raeburn  5576: 		       "$whichline.no_bubble.".$args->{'questionnum'},undef,'1');
1.157     albertel 5577: 	}
1.497     foxr     5578: 	my $where=$length*($args->{'question'}-1)+$scantron_config->{'Qstart'};
                   5579: 	substr($line,$where-1,$length)=$answer;
1.157     albertel 5580:     }
                   5581:     return $line;
                   5582: }
1.423     albertel 5583: 
                   5584: =pod
                   5585: 
                   5586: =item scan_data
                   5587: 
                   5588:     Edit or look up  an item in the scan_data hash.
                   5589: 
                   5590:   Arguments:
                   5591:     $scan_data  - The hash (see scantron_getfile)
                   5592:     $key        - shorthand of the key to edit (actual key is
1.424     albertel 5593:                   scantronfilename_key).
1.423     albertel 5594:     $data        - New value of the hash entry.
                   5595:     $delete      - If true, the entry is removed from the hash.
                   5596: 
                   5597:   Returns:
                   5598:     The new value of the hash table field (undefined if deleted).
                   5599: 
                   5600: =cut
                   5601: 
                   5602: 
1.157     albertel 5603: sub scan_data {
                   5604:     my ($scan_data,$key,$value,$delete)=@_;
1.257     albertel 5605:     my $filename=$env{'form.scantron_selectfile'};
1.157     albertel 5606:     if (defined($value)) {
                   5607: 	$scan_data->{$filename.'_'.$key} = $value;
                   5608:     }
                   5609:     if ($delete) { delete($scan_data->{$filename.'_'.$key}); }
                   5610:     return $scan_data->{$filename.'_'.$key};
                   5611: }
1.423     albertel 5612: 
1.495     albertel 5613: # ----- These first few routines are general use routines.----
                   5614: 
                   5615: # Return the number of occurences of a pattern in a string.
                   5616: 
                   5617: sub occurence_count {
                   5618:     my ($string, $pattern) = @_;
                   5619: 
                   5620:     my @matches = ($string =~ /$pattern/g);
                   5621: 
                   5622:     return scalar(@matches);
                   5623: }
                   5624: 
                   5625: 
                   5626: # Take a string known to have digits and convert all the
                   5627: # digits into letters in the range J,A..I.
                   5628: 
                   5629: sub digits_to_letters {
                   5630:     my ($input) = @_;
                   5631: 
                   5632:     my @alphabet = ('J', 'A'..'I');
                   5633: 
                   5634:     my @input    = split(//, $input);
                   5635:     my $output ='';
                   5636:     for (my $i = 0; $i < scalar(@input); $i++) {
                   5637: 	if ($input[$i] =~ /\d/) {
                   5638: 	    $output .= $alphabet[$input[$i]];
                   5639: 	} else {
                   5640: 	    $output .= $input[$i];
                   5641: 	}
                   5642:     }
                   5643:     return $output;
                   5644: }
                   5645: 
1.423     albertel 5646: =pod 
                   5647: 
                   5648: =item scantron_parse_scanline
                   5649: 
                   5650:   Decodes a scanline from the selected scantron file
                   5651: 
                   5652:  Arguments:
                   5653:     line             - The text of the scantron file line to process
                   5654:     whichline        - Line number
                   5655:     scantron_config  - Hash describing the format of the scantron lines.
                   5656:     scan_data        - Hash of extra information about the scanline
                   5657:                        (see scantron_getfile for more information)
                   5658:     just_header      - True if should not process question answers but only
                   5659:                        the stuff to the left of the answers.
                   5660:  Returns:
                   5661:    Hash containing the result of parsing the scanline
                   5662: 
                   5663:    Keys are all proceeded by the string 'scantron.'
                   5664: 
                   5665:        CODE    - the CODE in use for this scanline
                   5666:        useCODE - 1 if the CODE is invalid but it usage has been forced
                   5667:                  by the operator
                   5668:        CODE_ignore_dup - 1 if the CODE is a duplicated use when unique
                   5669:                             CODEs were selected, but the usage has been
                   5670:                             forced by the operator
1.556     weissno  5671:        ID  - student/employee ID
1.423     albertel 5672:        PaperID - if used, the ID number printed on the sheet when the 
                   5673:                  paper was scanned
                   5674:        FirstName - first name from the sheet
                   5675:        LastName  - last name from the sheet
                   5676: 
                   5677:      if just_header was not true these key may also exist
                   5678: 
1.447     foxr     5679:        missingerror - a list of bubble ranges that are considered to be answers
                   5680:                       to a single question that don't have any bubbles filled in.
                   5681:                       Of the form questionnumber:firstbubblenumber:count.
                   5682:        doubleerror  - a list of bubble ranges that are considered to be answers
                   5683:                       to a single question that have more than one bubble filled in.
                   5684:                       Of the form questionnumber::firstbubblenumber:count
                   5685:    
                   5686:                 In the above, count is the number of bubble responses in the
                   5687:                 input line needed to represent the possible answers to the question.
                   5688:                 e.g. a radioresponse with 15 choices in an answer sheet with 10 choices
                   5689:                 per line would have count = 2.
                   5690: 
1.423     albertel 5691:        maxquest     - the number of the last bubble line that was parsed
                   5692: 
                   5693:        (<number> starts at 1)
                   5694:        <number>.answer - zero or more letters representing the selected
                   5695:                          letters from the scanline for the bubble line 
                   5696:                          <number>.
                   5697:                          if blank there was either no bubble or there where
                   5698:                          multiple bubbles, (consult the keys missingerror and
                   5699:                          doubleerror if this is an error condition)
                   5700: 
                   5701: =cut
                   5702: 
1.82      albertel 5703: sub scantron_parse_scanline {
1.423     albertel 5704:     my ($line,$whichline,$scantron_config,$scan_data,$just_header)=@_;
1.470     foxr     5705: 
1.82      albertel 5706:     my %record;
1.550     raeburn  5707:     my $lastpos = $env{'form.scantron_maxbubble'}*$$scantron_config{'Qlength'};
                   5708:     my $questions=substr($line,$$scantron_config{'Qstart'}-1,$lastpos);  # Answers
1.422     foxr     5709:     my $data=substr($line,0,$$scantron_config{'Qstart'}-1);     # earlier stuff
1.278     albertel 5710:     if (!($$scantron_config{'CODElocation'} eq 0 ||
                   5711: 	  $$scantron_config{'CODElocation'} eq 'none')) {
                   5712: 	if ($$scantron_config{'CODElocation'} < 0 ||
                   5713: 	    $$scantron_config{'CODElocation'} eq 'letter' ||
                   5714: 	    $$scantron_config{'CODElocation'} eq 'number') {
1.191     albertel 5715: 	    $record{'scantron.CODE'}=substr($data,
                   5716: 					    $$scantron_config{'CODEstart'}-1,
1.83      albertel 5717: 					    $$scantron_config{'CODElength'});
1.191     albertel 5718: 	    if (&scan_data($scan_data,"$whichline.useCODE")) {
                   5719: 		$record{'scantron.useCODE'}=1;
                   5720: 	    }
1.192     albertel 5721: 	    if (&scan_data($scan_data,"$whichline.CODE_ignore_dup")) {
                   5722: 		$record{'scantron.CODE_ignore_dup'}=1;
                   5723: 	    }
1.82      albertel 5724: 	} else {
                   5725: 	    #FIXME interpret first N questions
                   5726: 	}
                   5727:     }
1.83      albertel 5728:     $record{'scantron.ID'}=substr($data,$$scantron_config{'IDstart'}-1,
                   5729: 				  $$scantron_config{'IDlength'});
1.157     albertel 5730:     $record{'scantron.PaperID'}=
                   5731: 	substr($data,$$scantron_config{'PaperID'}-1,
                   5732: 	       $$scantron_config{'PaperIDlength'});
                   5733:     $record{'scantron.FirstName'}=
                   5734: 	substr($data,$$scantron_config{'FirstName'}-1,
                   5735: 	       $$scantron_config{'FirstNamelength'});
                   5736:     $record{'scantron.LastName'}=
                   5737: 	substr($data,$$scantron_config{'LastName'}-1,
                   5738: 	       $$scantron_config{'LastNamelength'});
1.423     albertel 5739:     if ($just_header) { return \%record; }
1.194     albertel 5740: 
1.82      albertel 5741:     my @alphabet=('A'..'Z');
                   5742:     my $questnum=0;
1.447     foxr     5743:     my $ansnum  =1;		# Multiple 'answer lines'/question.
                   5744: 
1.470     foxr     5745:     chomp($questions);		# Get rid of any trailing \n.
                   5746:     $questions =~ s/\r$//;      # Get rid of trailing \r too (MAC or Win uploads).
                   5747:     while (length($questions)) {
1.447     foxr     5748: 	my $answers_needed = $bubble_lines_per_response{$questnum};
1.503     raeburn  5749:         my $answer_length  = ($$scantron_config{'Qlength'} * $answers_needed)
                   5750:                              || 1;
                   5751:         $questnum++;
                   5752:         my $quest_id = $questnum;
                   5753:         my $currentquest = substr($questions,0,$answer_length);
                   5754:         $questions       = substr($questions,$answer_length);
                   5755:         if (length($currentquest) < $answer_length) { next; }
                   5756: 
                   5757:         if ($subdivided_bubble_lines{$questnum-1} =~ /,/) {
                   5758:             my $subquestnum = 1;
                   5759:             my $subquestions = $currentquest;
                   5760:             my @subanswers_needed = 
                   5761:                 split(/,/,$subdivided_bubble_lines{$questnum-1});  
                   5762:             foreach my $subans (@subanswers_needed) {
                   5763:                 my $subans_length =
                   5764:                     ($$scantron_config{'Qlength'} * $subans)  || 1;
                   5765:                 my $currsubquest = substr($subquestions,0,$subans_length);
                   5766:                 $subquestions   = substr($subquestions,$subans_length);
                   5767:                 $quest_id = "$questnum.$subquestnum";
                   5768:                 if (($$scantron_config{'Qon'} eq 'letter') ||
                   5769:                     ($$scantron_config{'Qon'} eq 'number')) {
                   5770:                     $ansnum = &scantron_validator_lettnum($ansnum, 
                   5771:                         $questnum,$quest_id,$subans,$currsubquest,$whichline,
                   5772:                         \@alphabet,\%record,$scantron_config,$scan_data);
                   5773:                 } else {
                   5774:                     $ansnum = &scantron_validator_positional($ansnum,
                   5775:                         $questnum,$quest_id,$subans,$currsubquest,$whichline,                        \@alphabet,\%record,$scantron_config,$scan_data);
                   5776:                 }
                   5777:                 $subquestnum ++;
                   5778:             }
                   5779:         } else {
                   5780:             if (($$scantron_config{'Qon'} eq 'letter') ||
                   5781:                 ($$scantron_config{'Qon'} eq 'number')) {
                   5782:                 $ansnum = &scantron_validator_lettnum($ansnum,$questnum,
                   5783:                     $quest_id,$answers_needed,$currentquest,$whichline,
                   5784:                     \@alphabet,\%record,$scantron_config,$scan_data);
                   5785:             } else {
                   5786:                 $ansnum = &scantron_validator_positional($ansnum,$questnum,
                   5787:                     $quest_id,$answers_needed,$currentquest,$whichline,
                   5788:                     \@alphabet,\%record,$scantron_config,$scan_data);
                   5789:             }
                   5790:         }
                   5791:     }
                   5792:     $record{'scantron.maxquest'}=$questnum;
                   5793:     return \%record;
                   5794: }
1.447     foxr     5795: 
1.503     raeburn  5796: sub scantron_validator_lettnum {
                   5797:     my ($ansnum,$questnum,$quest_id,$answers_needed,$currquest,$whichline,
                   5798:         $alphabet,$record,$scantron_config,$scan_data) = @_;
                   5799: 
                   5800:     # Qon 'letter' implies for each slot in currquest we have:
                   5801:     #    ? or * for doubles, a letter in A-Z for a bubble, and
                   5802:     #    about anything else (esp. a value of Qoff) for missing
                   5803:     #    bubbles.
                   5804:     #
                   5805:     # Qon 'number' implies each slot gives a digit that indexes the
                   5806:     #    bubbles filled, or Qoff, or a non-number for unbubbled lines,
                   5807:     #    and * or ? for double bubbles on a single line.
                   5808:     #
1.447     foxr     5809: 
1.503     raeburn  5810:     my $matchon;
                   5811:     if ($$scantron_config{'Qon'} eq 'letter') {
                   5812:         $matchon = '[A-Z]';
                   5813:     } elsif ($$scantron_config{'Qon'} eq 'number') {
                   5814:         $matchon = '\d';
                   5815:     }
                   5816:     my $occurrences = 0;
                   5817:     if (($responsetype_per_response{$questnum-1} eq 'essayresponse') ||
                   5818:         ($responsetype_per_response{$questnum-1} eq 'formularesponse') ||
1.510     raeburn  5819:         ($responsetype_per_response{$questnum-1} eq 'stringresponse') ||
                   5820:         ($responsetype_per_response{$questnum-1} eq 'imageresponse') ||
                   5821:         ($responsetype_per_response{$questnum-1} eq 'reactionresponse') ||
                   5822:         ($responsetype_per_response{$questnum-1} eq 'organicresponse')) {
1.503     raeburn  5823:         my @singlelines = split('',$currquest);
                   5824:         foreach my $entry (@singlelines) {
                   5825:             $occurrences = &occurence_count($entry,$matchon);
                   5826:             if ($occurrences > 1) {
                   5827:                 last;
                   5828:             }
                   5829:         } 
                   5830:     } else {
                   5831:         $occurrences = &occurence_count($currquest,$matchon); 
                   5832:     }
                   5833:     if (($currquest =~ /\?/ || $currquest =~ /\*/) || ($occurrences > 1)) {
                   5834:         push(@{$record->{'scantron.doubleerror'}},$quest_id);
                   5835:         for (my $ans=0; $ans<$answers_needed; $ans++) {
                   5836:             my $bubble = substr($currquest,$ans,1);
                   5837:             if ($bubble =~ /$matchon/ ) {
                   5838:                 if ($$scantron_config{'Qon'} eq 'number') {
                   5839:                     if ($bubble == 0) {
                   5840:                         $bubble = 10; 
                   5841:                     }
                   5842:                     $record->{"scantron.$ansnum.answer"} = 
                   5843:                         $alphabet->[$bubble-1];
                   5844:                 } else {
                   5845:                     $record->{"scantron.$ansnum.answer"} = $bubble;
                   5846:                 }
                   5847:             } else {
                   5848:                 $record->{"scantron.$ansnum.answer"}='';
                   5849:             }
                   5850:             $ansnum++;
                   5851:         }
                   5852:     } elsif (!defined($currquest)
                   5853:             || (&occurence_count($currquest, $$scantron_config{'Qoff'}) == length($currquest))
                   5854:             || (&occurence_count($currquest,$matchon) == 0)) {
                   5855:         for (my $ans=0; $ans<$answers_needed; $ans++ ) {
                   5856:             $record->{"scantron.$ansnum.answer"}='';
                   5857:             $ansnum++;
                   5858:         }
                   5859:         if (!&scan_data($scan_data,"$whichline.no_bubble.$quest_id")) {
                   5860:             push(@{$record->{'scantron.missingerror'}},$quest_id);
                   5861:         }
                   5862:     } else {
                   5863:         if ($$scantron_config{'Qon'} eq 'number') {
                   5864:             $currquest = &digits_to_letters($currquest);            
                   5865:         }
                   5866:         for (my $ans=0; $ans<$answers_needed; $ans++) {
                   5867:             my $bubble = substr($currquest,$ans,1);
                   5868:             $record->{"scantron.$ansnum.answer"} = $bubble;
                   5869:             $ansnum++;
                   5870:         }
                   5871:     }
                   5872:     return $ansnum;
                   5873: }
1.447     foxr     5874: 
1.503     raeburn  5875: sub scantron_validator_positional {
                   5876:     my ($ansnum,$questnum,$quest_id,$answers_needed,$currquest,
                   5877:         $whichline,$alphabet,$record,$scantron_config,$scan_data) = @_;
1.447     foxr     5878: 
1.503     raeburn  5879:     # Otherwise there's a positional notation;
                   5880:     # each bubble line requires Qlength items, and there are filled in
                   5881:     # bubbles for each case where there 'Qon' characters.
                   5882:     #
1.447     foxr     5883: 
1.503     raeburn  5884:     my @array=split($$scantron_config{'Qon'},$currquest,-1);
1.447     foxr     5885: 
1.503     raeburn  5886:     # If the split only gives us one element.. the full length of the
                   5887:     # answer string, no bubbles are filled in:
1.447     foxr     5888: 
1.507     raeburn  5889:     if ($answers_needed eq '') {
                   5890:         return;
                   5891:     }
                   5892: 
1.503     raeburn  5893:     if (length($array[0]) eq $$scantron_config{'Qlength'}*$answers_needed) {
                   5894:         for (my $ans=0; $ans<$answers_needed; $ans++ ) {
                   5895:             $record->{"scantron.$ansnum.answer"}='';
                   5896:             $ansnum++;
                   5897:         }
                   5898:         if (!&scan_data($scan_data,"$whichline.no_bubble.$quest_id")) {
                   5899:             push(@{$record->{"scantron.missingerror"}},$quest_id);
                   5900:         }
                   5901:     } elsif (scalar(@array) == 2) {
                   5902:         my $location = length($array[0]);
                   5903:         my $line_num = int($location / $$scantron_config{'Qlength'});
                   5904:         my $bubble   = $alphabet->[$location % $$scantron_config{'Qlength'}];
                   5905:         for (my $ans=0; $ans<$answers_needed; $ans++) {
                   5906:             if ($ans eq $line_num) {
                   5907:                 $record->{"scantron.$ansnum.answer"} = $bubble;
                   5908:             } else {
                   5909:                 $record->{"scantron.$ansnum.answer"} = ' ';
                   5910:             }
                   5911:             $ansnum++;
                   5912:          }
                   5913:     } else {
                   5914:         #  If there's more than one instance of a bubble character
                   5915:         #  That's a double bubble; with positional notation we can
                   5916:         #  record all the bubbles filled in as well as the
                   5917:         #  fact this response consists of multiple bubbles.
                   5918:         #
                   5919:         if (($responsetype_per_response{$questnum-1} eq 'essayresponse') ||
                   5920:             ($responsetype_per_response{$questnum-1} eq 'formularesponse') ||
1.510     raeburn  5921:             ($responsetype_per_response{$questnum-1} eq 'stringresponse') ||
                   5922:             ($responsetype_per_response{$questnum-1} eq 'imageresponse') ||
                   5923:             ($responsetype_per_response{$questnum-1} eq 'reactionresponse') ||
                   5924:             ($responsetype_per_response{$questnum-1} eq 'organicresponse')) {
1.503     raeburn  5925:             my $doubleerror = 0;
                   5926:             while (($currquest >= $$scantron_config{'Qlength'}) && 
                   5927:                    (!$doubleerror)) {
                   5928:                my $currline = substr($currquest,0,$$scantron_config{'Qlength'});
                   5929:                $currquest = substr($currquest,$$scantron_config{'Qlength'});
                   5930:                my @currarray = split($$scantron_config{'Qon'},$currline,-1);
                   5931:                if (length(@currarray) > 2) {
                   5932:                    $doubleerror = 1;
                   5933:                } 
                   5934:             }
                   5935:             if ($doubleerror) {
                   5936:                 push(@{$record->{'scantron.doubleerror'}},$quest_id);
                   5937:             }
                   5938:         } else {
                   5939:             push(@{$record->{'scantron.doubleerror'}},$quest_id);
                   5940:         }
                   5941:         my $item = $ansnum;
                   5942:         for (my $ans=0; $ans<$answers_needed; $ans++) {
                   5943:             $record->{"scantron.$item.answer"} = '';
                   5944:             $item ++;
                   5945:         }
1.447     foxr     5946: 
1.503     raeburn  5947:         my @ans=@array;
                   5948:         my $i=0;
                   5949:         my $increment = 0;
                   5950:         while ($#ans) {
                   5951:             $i+=length($ans[0]) + $increment;
                   5952:             my $line   = int($i/$$scantron_config{'Qlength'} + $ansnum);
                   5953:             my $bubble = $i%$$scantron_config{'Qlength'};
                   5954:             $record->{"scantron.$line.answer"}.=$alphabet->[$bubble];
                   5955:             shift(@ans);
                   5956:             $increment = 1;
                   5957:         }
                   5958:         $ansnum += $answers_needed;
1.82      albertel 5959:     }
1.503     raeburn  5960:     return $ansnum;
1.82      albertel 5961: }
                   5962: 
1.423     albertel 5963: =pod
                   5964: 
                   5965: =item scantron_add_delay
                   5966: 
                   5967:    Adds an error message that occurred during the grading phase to a
                   5968:    queue of messages to be shown after grading pass is complete
                   5969: 
                   5970:  Arguments:
1.424     albertel 5971:    $delayqueue  - arrary ref of hash ref of error messages
1.423     albertel 5972:    $scanline    - the scanline that caused the error
                   5973:    $errormesage - the error message
                   5974:    $errorcode   - a numeric code for the error
                   5975: 
                   5976:  Side Effects:
1.424     albertel 5977:    updates the $delayqueue to have a new hash ref of the error
1.423     albertel 5978: 
                   5979: =cut
                   5980: 
1.82      albertel 5981: sub scantron_add_delay {
1.140     albertel 5982:     my ($delayqueue,$scanline,$errormessage,$errorcode)=@_;
                   5983:     push(@$delayqueue,
                   5984: 	 {'line' => $scanline, 'emsg' => $errormessage,
                   5985: 	  'ecode' => $errorcode }
                   5986: 	 );
1.82      albertel 5987: }
                   5988: 
1.423     albertel 5989: =pod
                   5990: 
                   5991: =item scantron_find_student
                   5992: 
1.424     albertel 5993:    Finds the username for the current scanline
                   5994: 
                   5995:   Arguments:
                   5996:    $scantron_record - hash result from scantron_parse_scanline
                   5997:    $scan_data       - hash of correction information 
                   5998:                       (see &scantron_getfile() form more information)
                   5999:    $idmap           - hash from &username_to_idmap()
                   6000:    $line            - number of current scanline
                   6001:  
                   6002:   Returns:
                   6003:    Either 'username:domain' or undef if unknown
                   6004: 
1.423     albertel 6005: =cut
                   6006: 
1.82      albertel 6007: sub scantron_find_student {
1.157     albertel 6008:     my ($scantron_record,$scan_data,$idmap,$line)=@_;
1.83      albertel 6009:     my $scanID=$$scantron_record{'scantron.ID'};
1.157     albertel 6010:     if ($scanID =~ /^\s*$/) {
                   6011:  	return &scan_data($scan_data,"$line.user");
                   6012:     }
1.83      albertel 6013:     foreach my $id (keys(%$idmap)) {
1.157     albertel 6014:  	if (lc($id) eq lc($scanID)) {
                   6015:  	    return $$idmap{$id};
                   6016:  	}
1.83      albertel 6017:     }
                   6018:     return undef;
                   6019: }
                   6020: 
1.423     albertel 6021: =pod
                   6022: 
                   6023: =item scantron_filter
                   6024: 
1.424     albertel 6025:    Filter sub for lonnavmaps, filters out hidden resources if ignore
                   6026:    hidden resources was selected
                   6027: 
1.423     albertel 6028: =cut
                   6029: 
1.83      albertel 6030: sub scantron_filter {
                   6031:     my ($curres)=@_;
1.331     albertel 6032: 
                   6033:     if (ref($curres) && $curres->is_problem()) {
                   6034: 	# if the user has asked to not have either hidden
                   6035: 	# or 'randomout' controlled resources to be graded
                   6036: 	# don't include them
                   6037: 	if ($env{'form.scantron_options_hidden'} eq 'ignore_hidden'
                   6038: 	    && $curres->randomout) {
                   6039: 	    return 0;
                   6040: 	}
1.83      albertel 6041: 	return 1;
                   6042:     }
                   6043:     return 0;
1.82      albertel 6044: }
                   6045: 
1.423     albertel 6046: =pod
                   6047: 
                   6048: =item scantron_process_corrections
                   6049: 
1.424     albertel 6050:    Gets correction information out of submitted form data and corrects
                   6051:    the scanline
                   6052: 
1.423     albertel 6053: =cut
                   6054: 
1.157     albertel 6055: sub scantron_process_corrections {
                   6056:     my ($r) = @_;
1.257     albertel 6057:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.157     albertel 6058:     my ($scanlines,$scan_data)=&scantron_getfile();
                   6059:     my $classlist=&Apache::loncoursedata::get_classlist();
1.257     albertel 6060:     my $which=$env{'form.scantron_line'};
1.200     albertel 6061:     my $line=&scantron_get_line($scanlines,$scan_data,$which);
1.157     albertel 6062:     my ($skip,$err,$errmsg);
1.257     albertel 6063:     if ($env{'form.scantron_skip_record'}) {
1.157     albertel 6064: 	$skip=1;
1.257     albertel 6065:     } elsif ($env{'form.scantron_corrections'} =~ /^(duplicate|incorrect)ID$/) {
                   6066: 	my $newstudent=$env{'form.scantron_username'}.':'.
                   6067: 	    $env{'form.scantron_domain'};
1.157     albertel 6068: 	my $newid=$classlist->{$newstudent}->[&Apache::loncoursedata::CL_ID];
                   6069: 	($line,$err,$errmsg)=
                   6070: 	    &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,$which,
                   6071: 				     'ID',{'newid'=>$newid,
1.257     albertel 6072: 				    'username'=>$env{'form.scantron_username'},
                   6073: 				    'domain'=>$env{'form.scantron_domain'}});
                   6074:     } elsif ($env{'form.scantron_corrections'} =~ /^(duplicate|incorrect)CODE$/) {
                   6075: 	my $resolution=$env{'form.scantron_CODE_resolution'};
1.190     albertel 6076: 	my $newCODE;
1.192     albertel 6077: 	my %args;
1.190     albertel 6078: 	if      ($resolution eq 'use_unfound') {
1.191     albertel 6079: 	    $newCODE='use_unfound';
1.190     albertel 6080: 	} elsif ($resolution eq 'use_found') {
1.257     albertel 6081: 	    $newCODE=$env{'form.scantron_CODE_selectedvalue'};
1.190     albertel 6082: 	} elsif ($resolution eq 'use_typed') {
1.257     albertel 6083: 	    $newCODE=$env{'form.scantron_CODE_newvalue'};
1.194     albertel 6084: 	} elsif ($resolution =~ /^use_closest_(\d+)/) {
1.257     albertel 6085: 	    $newCODE=$env{"form.scantron_CODE_closest_$1"};
1.190     albertel 6086: 	}
1.257     albertel 6087: 	if ($env{'form.scantron_corrections'} eq 'duplicateCODE') {
1.192     albertel 6088: 	    $args{'CODE_ignore_dup'}=1;
                   6089: 	}
                   6090: 	$args{'CODE'}=$newCODE;
1.186     albertel 6091: 	($line,$err,$errmsg)=
                   6092: 	    &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,$which,
1.192     albertel 6093: 				     'CODE',\%args);
1.257     albertel 6094:     } elsif ($env{'form.scantron_corrections'} =~ /^(missing|double)bubble$/) {
                   6095: 	foreach my $question (split(',',$env{'form.scantron_questions'})) {
1.157     albertel 6096: 	    ($line,$err,$errmsg)=
                   6097: 		&scantron_fixup_scanline(\%scantron_config,$scan_data,$line,
                   6098: 					 $which,'answer',
                   6099: 					 { 'question'=>$question,
1.503     raeburn  6100: 		      		   'response'=>$env{"form.scantron_correct_Q_$question"},
                   6101:                                    'questionnum'=>$env{"form.scantron_questionnum_Q_$question"}});
1.157     albertel 6102: 	    if ($err) { last; }
                   6103: 	}
                   6104:     }
                   6105:     if ($err) {
1.398     albertel 6106: 	$r->print("<span class=\"LC_warning\">Unable to accept last correction, an error occurred :$errmsg:</span>");
1.157     albertel 6107:     } else {
1.200     albertel 6108: 	&scantron_put_line($scanlines,$scan_data,$which,$line,$skip);
1.157     albertel 6109: 	&scantron_putfile($scanlines,$scan_data);
                   6110:     }
                   6111: }
                   6112: 
1.423     albertel 6113: =pod
                   6114: 
                   6115: =item reset_skipping_status
                   6116: 
1.424     albertel 6117:    Forgets the current set of remember skipped scanlines (and thus
                   6118:    reverts back to considering all lines in the
                   6119:    scantron_skipped_<filename> file)
                   6120: 
1.423     albertel 6121: =cut
                   6122: 
1.200     albertel 6123: sub reset_skipping_status {
                   6124:     my ($scanlines,$scan_data)=&scantron_getfile();
                   6125:     &scan_data($scan_data,'remember_skipping',undef,1);
                   6126:     &scantron_putfile(undef,$scan_data);
                   6127: }
                   6128: 
1.423     albertel 6129: =pod
                   6130: 
                   6131: =item start_skipping
                   6132: 
1.424     albertel 6133:    Marks a scanline to be skipped. 
                   6134: 
1.423     albertel 6135: =cut
                   6136: 
1.376     albertel 6137: sub start_skipping {
1.200     albertel 6138:     my ($scan_data,$i)=@_;
                   6139:     my %remembered=split(':',&scan_data($scan_data,'remember_skipping'));
1.376     albertel 6140:     if ($env{'form.scantron_options_redo'} =~ /^redo_/) {
                   6141: 	$remembered{$i}=2;
                   6142:     } else {
                   6143: 	$remembered{$i}=1;
                   6144:     }
1.200     albertel 6145:     &scan_data($scan_data,'remember_skipping',join(':',%remembered));
                   6146: }
                   6147: 
1.423     albertel 6148: =pod
                   6149: 
                   6150: =item should_be_skipped
                   6151: 
1.424     albertel 6152:    Checks whether a scanline should be skipped.
                   6153: 
1.423     albertel 6154: =cut
                   6155: 
1.200     albertel 6156: sub should_be_skipped {
1.376     albertel 6157:     my ($scanlines,$scan_data,$i)=@_;
1.257     albertel 6158:     if ($env{'form.scantron_options_redo'} !~ /^redo_/) {
1.200     albertel 6159: 	# not redoing old skips
1.376     albertel 6160: 	if ($scanlines->{'skipped'}[$i]) { return 1; }
1.200     albertel 6161: 	return 0;
                   6162:     }
                   6163:     my %remembered=split(':',&scan_data($scan_data,'remember_skipping'));
1.376     albertel 6164: 
                   6165:     if (exists($remembered{$i}) && $remembered{$i} != 2 ) {
                   6166: 	return 0;
                   6167:     }
1.200     albertel 6168:     return 1;
                   6169: }
                   6170: 
1.423     albertel 6171: =pod
                   6172: 
                   6173: =item remember_current_skipped
                   6174: 
1.424     albertel 6175:    Discovers what scanlines are in the scantron_skipped_<filename>
                   6176:    file and remembers them into scan_data for later use.
                   6177: 
1.423     albertel 6178: =cut
                   6179: 
1.200     albertel 6180: sub remember_current_skipped {
                   6181:     my ($scanlines,$scan_data)=&scantron_getfile();
                   6182:     my %to_remember;
                   6183:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
                   6184: 	if ($scanlines->{'skipped'}[$i]) {
                   6185: 	    $to_remember{$i}=1;
                   6186: 	}
                   6187:     }
1.376     albertel 6188: 
1.200     albertel 6189:     &scan_data($scan_data,'remember_skipping',join(':',%to_remember));
                   6190:     &scantron_putfile(undef,$scan_data);
                   6191: }
                   6192: 
1.423     albertel 6193: =pod
                   6194: 
                   6195: =item check_for_error
                   6196: 
1.424     albertel 6197:     Checks if there was an error when attempting to remove a specific
                   6198:     scantron_.. bubble sheet data file. Prints out an error if
                   6199:     something went wrong.
                   6200: 
1.423     albertel 6201: =cut
                   6202: 
1.200     albertel 6203: sub check_for_error {
                   6204:     my ($r,$result)=@_;
                   6205:     if ($result ne 'ok' && $result ne 'not_found' ) {
1.492     albertel 6206: 	$r->print(&mt("An error occurred ([_1]) when trying to remove the existing corrections.",$result));
1.200     albertel 6207:     }
                   6208: }
1.157     albertel 6209: 
1.423     albertel 6210: =pod
                   6211: 
                   6212: =item scantron_warning_screen
                   6213: 
1.424     albertel 6214:    Interstitial screen to make sure the operator has selected the
                   6215:    correct options before we start the validation phase.
                   6216: 
1.423     albertel 6217: =cut
                   6218: 
1.203     albertel 6219: sub scantron_warning_screen {
                   6220:     my ($button_text)=@_;
1.257     albertel 6221:     my $title=&Apache::lonnet::gettitle($env{'form.selectpage'});
1.284     albertel 6222:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.373     albertel 6223:     my $CODElist;
1.284     albertel 6224:     if ($scantron_config{'CODElocation'} &&
                   6225: 	$scantron_config{'CODEstart'} &&
                   6226: 	$scantron_config{'CODElength'}) {
                   6227: 	$CODElist=$env{'form.scantron_CODElist'};
1.398     albertel 6228: 	if ($env{'form.scantron_CODElist'} eq '') { $CODElist='<span class="LC_warning">None</span>'; }
1.284     albertel 6229: 	$CODElist=
1.492     albertel 6230: 	    '<tr><td><b>'.&mt('List of CODES to validate against:').'</b></td><td><tt>'.
1.373     albertel 6231: 	    $env{'form.scantron_CODElist'}.'</tt></td></tr>';
1.284     albertel 6232:     }
1.492     albertel 6233:     return ('
1.203     albertel 6234: <p>
1.492     albertel 6235: <span class="LC_warning">
                   6236: '.&mt('Please double check the information below before clicking on \'[_1]\'',&mt($button_text)).'</span>
1.203     albertel 6237: </p>
                   6238: <table>
1.492     albertel 6239: <tr><td><b>'.&mt('Sequence to be Graded:').'</b></td><td>'.$title.'</td></tr>
                   6240: <tr><td><b>'.&mt('Data File that will be used:').'</b></td><td><tt>'.$env{'form.scantron_selectfile'}.'</tt></td></tr>
                   6241: '.$CODElist.'
1.203     albertel 6242: </table>
                   6243: <br />
1.492     albertel 6244: <p> '.&mt('If this information is correct, please click on \'[_1]\'.',&mt($button_text)).'</p>
                   6245: <p> '.&mt('If something is incorrect, please click the \'Grading Menu\' button to start over.').'</p>
1.203     albertel 6246: 
                   6247: <br />
1.492     albertel 6248: ');
1.203     albertel 6249: }
                   6250: 
1.423     albertel 6251: =pod
                   6252: 
                   6253: =item scantron_do_warning
                   6254: 
1.424     albertel 6255:    Check if the operator has picked something for all required
                   6256:    fields. Error out if something is missing.
                   6257: 
1.423     albertel 6258: =cut
                   6259: 
1.203     albertel 6260: sub scantron_do_warning {
                   6261:     my ($r)=@_;
1.324     albertel 6262:     my ($symb)=&get_symb($r);
1.203     albertel 6263:     if (!$symb) {return '';}
1.324     albertel 6264:     my $default_form_data=&defaultFormData($symb);
1.203     albertel 6265:     $r->print(&scantron_form_start().$default_form_data);
1.257     albertel 6266:     if ( $env{'form.selectpage'} eq '' ||
                   6267: 	 $env{'form.scantron_selectfile'} eq '' ||
                   6268: 	 $env{'form.scantron_format'} eq '' ) {
1.492     albertel 6269: 	$r->print("<p>".&mt('You have forgetten to specify some information. Please go Back and try again.')."</p>");
1.257     albertel 6270: 	if ( $env{'form.selectpage'} eq '') {
1.492     albertel 6271: 	    $r->print('<p><span class="LC_error">'.&mt('You have not selected a Sequence to grade').'</span></p>');
1.237     albertel 6272: 	} 
1.257     albertel 6273: 	if ( $env{'form.scantron_selectfile'} eq '') {
1.492     albertel 6274: 	    $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 6275: 	} 
1.257     albertel 6276: 	if ( $env{'form.scantron_format'} eq '') {
1.492     albertel 6277: 	    $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 6278: 	} 
                   6279:     } else {
1.265     www      6280: 	my $warning=&scantron_warning_screen('Grading: Validate Records');
1.492     albertel 6281: 	$r->print('
                   6282: '.$warning.'
                   6283: <input type="submit" name="submit" value="'.&mt('Grading: Validate Records').'" />
1.203     albertel 6284: <input type="hidden" name="command" value="scantron_validate" />
1.492     albertel 6285: ');
1.237     albertel 6286:     }
1.352     albertel 6287:     $r->print("</form><br />".&show_grading_menu_form($symb));
1.203     albertel 6288:     return '';
                   6289: }
                   6290: 
1.423     albertel 6291: =pod
                   6292: 
                   6293: =item scantron_form_start
                   6294: 
1.424     albertel 6295:     html hidden input for remembering all selected grading options
                   6296: 
1.423     albertel 6297: =cut
                   6298: 
1.203     albertel 6299: sub scantron_form_start {
                   6300:     my ($max_bubble)=@_;
                   6301:     my $result= <<SCANTRONFORM;
                   6302: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantronupload">
1.257     albertel 6303:   <input type="hidden" name="selectpage" value="$env{'form.selectpage'}" />
                   6304:   <input type="hidden" name="scantron_format" value="$env{'form.scantron_format'}" />
                   6305:   <input type="hidden" name="scantron_selectfile" value="$env{'form.scantron_selectfile'}" />
1.218     albertel 6306:   <input type="hidden" name="scantron_maxbubble" value="$max_bubble" />
1.257     albertel 6307:   <input type="hidden" name="scantron_CODElist" value="$env{'form.scantron_CODElist'}" />
                   6308:   <input type="hidden" name="scantron_CODEunique" value="$env{'form.scantron_CODEunique'}" />
                   6309:   <input type="hidden" name="scantron_options_redo" value="$env{'form.scantron_options_redo'}" />
                   6310:   <input type="hidden" name="scantron_options_ignore" value="$env{'form.scantron_options_ignore'}" />
1.331     albertel 6311:   <input type="hidden" name="scantron_options_hidden" value="$env{'form.scantron_options_hidden'}" />
1.203     albertel 6312: SCANTRONFORM
1.447     foxr     6313: 
                   6314:   my $line = 0;
                   6315:     while (defined($env{"form.scantron.bubblelines.$line"})) {
                   6316:        my $chunk =
                   6317: 	   '<input type="hidden" name="scantron.bubblelines.'.$line.'" value="'.$env{"form.scantron.bubblelines.$line"}.'" />'."\n";
1.448     foxr     6318:        $chunk .=
                   6319: 	   '<input type="hidden" name="scantron.first_bubble_line.'.$line.'" value="'.$env{"form.scantron.first_bubble_line.$line"}.'" />'."\n";
1.503     raeburn  6320:        $chunk .= 
                   6321:            '<input type="hidden" name="scantron.sub_bubblelines.'.$line.'" value="'.$env{"form.scantron.sub_bubblelines.$line"}.'" />'."\n";
1.504     raeburn  6322:        $chunk .=
                   6323:            '<input type="hidden" name="scantron.responsetype.'.$line.'" value="'.$env{"form.scantron.responsetype.$line"}.'" />'."\n";
1.447     foxr     6324:        $result .= $chunk;
                   6325:        $line++;
                   6326:    }
1.203     albertel 6327:     return $result;
                   6328: }
                   6329: 
1.423     albertel 6330: =pod
                   6331: 
                   6332: =item scantron_validate_file
                   6333: 
1.424     albertel 6334:     Dispatch routine for doing validation of a bubble sheet data file.
                   6335: 
                   6336:     Also processes any necessary information resets that need to
                   6337:     occur before validation begins (ignore previous corrections,
                   6338:     restarting the skipped records processing)
                   6339: 
1.423     albertel 6340: =cut
                   6341: 
1.157     albertel 6342: sub scantron_validate_file {
                   6343:     my ($r) = @_;
1.324     albertel 6344:     my ($symb)=&get_symb($r);
1.157     albertel 6345:     if (!$symb) {return '';}
1.324     albertel 6346:     my $default_form_data=&defaultFormData($symb);
1.200     albertel 6347:     
                   6348:     # do the detection of only doing skipped records first befroe we delete
1.424     albertel 6349:     # them when doing the corrections reset
1.257     albertel 6350:     if ($env{'form.scantron_options_redo'} ne 'redo_skipped_ready') {
1.200     albertel 6351: 	&reset_skipping_status();
                   6352:     }
1.257     albertel 6353:     if ($env{'form.scantron_options_redo'} eq 'redo_skipped') {
1.200     albertel 6354: 	&remember_current_skipped();
1.257     albertel 6355: 	$env{'form.scantron_options_redo'}='redo_skipped_ready';
1.200     albertel 6356:     }
                   6357: 
1.257     albertel 6358:     if ($env{'form.scantron_options_ignore'} eq 'ignore_corrections') {
1.200     albertel 6359: 	&check_for_error($r,&scantron_remove_file('corrected'));
                   6360: 	&check_for_error($r,&scantron_remove_file('skipped'));
                   6361: 	&check_for_error($r,&scantron_remove_scan_data());
1.257     albertel 6362: 	$env{'form.scantron_options_ignore'}='done';
1.192     albertel 6363:     }
1.200     albertel 6364: 
1.257     albertel 6365:     if ($env{'form.scantron_corrections'}) {
1.157     albertel 6366: 	&scantron_process_corrections($r);
                   6367:     }
1.503     raeburn  6368:     $r->print('<p>'.&mt('Gathering necessary information.').'</p>');$r->rflush();
1.157     albertel 6369:     #get the student pick code ready
                   6370:     $r->print(&Apache::loncommon::studentbrowser_javascript());
1.582     raeburn  6371:     my $nav_error;
                   6372:     my $max_bubble=&scantron_get_maxbubble(\$nav_error);
                   6373:     if ($nav_error) {
                   6374:         $r->print(&navmap_errormsg());
                   6375:         return '';
                   6376:     }
1.203     albertel 6377:     my $result=&scantron_form_start($max_bubble).$default_form_data;
1.157     albertel 6378:     $r->print($result);
                   6379:     
1.334     albertel 6380:     my @validate_phases=( 'sequence',
                   6381: 			  'ID',
1.157     albertel 6382: 			  'CODE',
                   6383: 			  'doublebubble',
                   6384: 			  'missingbubbles');
1.257     albertel 6385:     if (!$env{'form.validatepass'}) {
                   6386: 	$env{'form.validatepass'} = 0;
1.157     albertel 6387:     }
1.257     albertel 6388:     my $currentphase=$env{'form.validatepass'};
1.157     albertel 6389: 
1.448     foxr     6390: 
1.157     albertel 6391:     my $stop=0;
                   6392:     while (!$stop && $currentphase < scalar(@validate_phases)) {
1.503     raeburn  6393: 	$r->print(&mt('Validating '.$validate_phases[$currentphase]).'<br />');
1.157     albertel 6394: 	$r->rflush();
                   6395: 	my $which="scantron_validate_".$validate_phases[$currentphase];
                   6396: 	{
                   6397: 	    no strict 'refs';
                   6398: 	    ($stop,$currentphase)=&$which($r,$currentphase);
                   6399: 	}
                   6400:     }
                   6401:     if (!$stop) {
1.203     albertel 6402: 	my $warning=&scantron_warning_screen('Start Grading');
1.542     raeburn  6403: 	$r->print(&mt('Validation process complete.').'<br />'.
                   6404:                   $warning.
                   6405:                   &mt('Perform verification for each student after storage of submissions?').
                   6406:                   '&nbsp;<span class="LC_nobreak"><label>'.
                   6407:                   '<input type="radio" name="verifyrecord" value="1" />'.&mt('Yes').'</label>'.
                   6408:                   ('&nbsp;'x3).'<label>'.
                   6409:                   '<input type="radio" name="verifyrecord" value="0" checked="checked" />'.&mt('No').
                   6410:                   '</label></span><br />'.
                   6411:                   &mt('Grading will take longer if you use verification.').'<br />'.
1.572     www      6412:                   &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  6413:                   '<input type="submit" name="submit" value="'.&mt('Start Grading').'" />'.
                   6414:                   '<input type="hidden" name="command" value="scantron_process" />'."\n");
1.157     albertel 6415:     } else {
                   6416: 	$r->print('<input type="hidden" name="command" value="scantron_validate" />');
                   6417: 	$r->print("<input type='hidden' name='validatepass' value='".$currentphase."' />");
                   6418:     }
                   6419:     if ($stop) {
1.334     albertel 6420: 	if ($validate_phases[$currentphase] eq 'sequence') {
1.539     riegler  6421: 	    $r->print('<input type="submit" name="submit" value="'.&mt('Ignore').' &rarr; " />');
1.492     albertel 6422: 	    $r->print(' '.&mt('this error').' <br />');
1.334     albertel 6423: 
1.492     albertel 6424: 	    $r->print(" <p>".&mt("Or click the 'Grading Menu' button to start over.")."</p>");
1.334     albertel 6425: 	} else {
1.503     raeburn  6426:             if ($validate_phases[$currentphase] eq 'doublebubble' || $validate_phases[$currentphase] eq 'missingbubbles') {
1.539     riegler  6427: 	        $r->print('<input type="button" name="submitbutton" value="'.&mt('Continue').' &rarr;" onclick="javascript:verify_bubble_radio(this.form)" />');
1.503     raeburn  6428:             } else {
1.539     riegler  6429:                 $r->print('<input type="submit" name="submit" value="'.&mt('Continue').' &rarr;" />');
1.503     raeburn  6430:             }
1.492     albertel 6431: 	    $r->print(' '.&mt('using corrected info').' <br />');
                   6432: 	    $r->print("<input type='submit' value='".&mt("Skip")."' name='scantron_skip_record' />");
                   6433: 	    $r->print(" ".&mt("this scanline saving it for later."));
1.334     albertel 6434: 	}
1.157     albertel 6435:     }
1.352     albertel 6436:     $r->print(" </form><br />".&show_grading_menu_form($symb));
1.157     albertel 6437:     return '';
                   6438: }
                   6439: 
1.423     albertel 6440: 
                   6441: =pod
                   6442: 
                   6443: =item scantron_remove_file
                   6444: 
1.424     albertel 6445:    Removes the requested bubble sheet data file, makes sure that
                   6446:    scantron_original_<filename> is never removed
                   6447: 
                   6448: 
1.423     albertel 6449: =cut
                   6450: 
1.200     albertel 6451: sub scantron_remove_file {
1.192     albertel 6452:     my ($which)=@_;
1.257     albertel 6453:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   6454:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.192     albertel 6455:     my $file='scantron_';
1.200     albertel 6456:     if ($which eq 'corrected' || $which eq 'skipped') {
                   6457: 	$file.=$which.'_';
1.192     albertel 6458:     } else {
                   6459: 	return 'refused';
                   6460:     }
1.257     albertel 6461:     $file.=$env{'form.scantron_selectfile'};
1.200     albertel 6462:     return &Apache::lonnet::removeuserfile($cname,$cdom,$file);
                   6463: }
                   6464: 
1.423     albertel 6465: 
                   6466: =pod
                   6467: 
                   6468: =item scantron_remove_scan_data
                   6469: 
1.424     albertel 6470:    Removes all scan_data correction for the requested bubble sheet
                   6471:    data file.  (In the case that both the are doing skipped records we need
                   6472:    to remember the old skipped lines for the time being so that element
                   6473:    persists for a while.)
                   6474: 
1.423     albertel 6475: =cut
                   6476: 
1.200     albertel 6477: sub scantron_remove_scan_data {
1.257     albertel 6478:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   6479:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.192     albertel 6480:     my @keys=&Apache::lonnet::getkeys('nohist_scantrondata',$cdom,$cname);
                   6481:     my @todelete;
1.257     albertel 6482:     my $filename=$env{'form.scantron_selectfile'};
1.192     albertel 6483:     foreach my $key (@keys) {
                   6484: 	if ($key=~/^\Q$filename\E_/) {
1.257     albertel 6485: 	    if ($env{'form.scantron_options_redo'} eq 'redo_skipped_ready' &&
1.200     albertel 6486: 		$key=~/remember_skipping/) {
                   6487: 		next;
                   6488: 	    }
1.192     albertel 6489: 	    push(@todelete,$key);
                   6490: 	}
                   6491:     }
1.200     albertel 6492:     my $result;
1.192     albertel 6493:     if (@todelete) {
1.491     albertel 6494: 	$result = &Apache::lonnet::del('nohist_scantrondata',
                   6495: 				       \@todelete,$cdom,$cname);
                   6496:     } else {
                   6497: 	$result = 'ok';
1.192     albertel 6498:     }
                   6499:     return $result;
                   6500: }
                   6501: 
1.423     albertel 6502: 
                   6503: =pod
                   6504: 
                   6505: =item scantron_getfile
                   6506: 
1.424     albertel 6507:     Fetches the requested bubble sheet data file (all 3 versions), and
                   6508:     the scan_data hash
                   6509:   
                   6510:   Arguments:
                   6511:     None
                   6512: 
                   6513:   Returns:
                   6514:     2 hash references
                   6515: 
                   6516:      - first one has 
                   6517:          orig      -
                   6518:          corrected -
                   6519:          skipped   -  each of which points to an array ref of the specified
                   6520:                       file broken up into individual lines
                   6521:          count     - number of scanlines
                   6522:  
                   6523:      - second is the scan_data hash possible keys are
1.425     albertel 6524:        ($number refers to scanline numbered $number and thus the key affects
                   6525:         only that scanline
                   6526:         $bubline refers to the specific bubble line element and the aspects
                   6527:         refers to that specific bubble line element)
                   6528: 
                   6529:        $number.user - username:domain to use
                   6530:        $number.CODE_ignore_dup 
                   6531:                     - ignore the duplicate CODE error 
                   6532:        $number.useCODE
                   6533:                     - use the CODE in the scanline as is
                   6534:        $number.no_bubble.$bubline
                   6535:                     - it is valid that there is no bubbled in bubble
                   6536:                       at $number $bubline
                   6537:        remember_skipping
                   6538:                     - a frozen hash containing keys of $number and values
                   6539:                       of either 
                   6540:                         1 - we are on a 'do skipped records pass' and plan
                   6541:                             on processing this line
                   6542:                         2 - we are on a 'do skipped records pass' and this
                   6543:                             scanline has been marked to skip yet again
1.424     albertel 6544: 
1.423     albertel 6545: =cut
                   6546: 
1.157     albertel 6547: sub scantron_getfile {
1.200     albertel 6548:     #FIXME really would prefer a scantron directory
1.257     albertel 6549:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   6550:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.157     albertel 6551:     my $lines;
                   6552:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
1.257     albertel 6553: 		       'scantron_orig_'.$env{'form.scantron_selectfile'});
1.157     albertel 6554:     my %scanlines;
                   6555:     $scanlines{'orig'}=[(split("\n",$lines,-1))];
                   6556:     my $temp=$scanlines{'orig'};
                   6557:     $scanlines{'count'}=$#$temp;
                   6558: 
                   6559:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
1.257     albertel 6560: 		       'scantron_corrected_'.$env{'form.scantron_selectfile'});
1.157     albertel 6561:     if ($lines eq '-1') {
                   6562: 	$scanlines{'corrected'}=[];
                   6563:     } else {
                   6564: 	$scanlines{'corrected'}=[(split("\n",$lines,-1))];
                   6565:     }
                   6566:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
1.257     albertel 6567: 		       'scantron_skipped_'.$env{'form.scantron_selectfile'});
1.157     albertel 6568:     if ($lines eq '-1') {
                   6569: 	$scanlines{'skipped'}=[];
                   6570:     } else {
                   6571: 	$scanlines{'skipped'}=[(split("\n",$lines,-1))];
                   6572:     }
1.175     albertel 6573:     my @tmp=&Apache::lonnet::dump('nohist_scantrondata',$cdom,$cname);
1.157     albertel 6574:     if ($tmp[0] =~ /^(error:|no_such_host)/) { @tmp=(); }
                   6575:     my %scan_data = @tmp;
                   6576:     return (\%scanlines,\%scan_data);
                   6577: }
                   6578: 
1.423     albertel 6579: =pod
                   6580: 
                   6581: =item lonnet_putfile
                   6582: 
1.424     albertel 6583:    Wrapper routine to call &Apache::lonnet::finishuserfileupload
                   6584: 
                   6585:  Arguments:
                   6586:    $contents - data to store
                   6587:    $filename - filename to store $contents into
                   6588: 
                   6589:  Returns:
                   6590:    result value from &Apache::lonnet::finishuserfileupload
                   6591: 
1.423     albertel 6592: =cut
                   6593: 
1.157     albertel 6594: sub lonnet_putfile {
                   6595:     my ($contents,$filename)=@_;
1.257     albertel 6596:     my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   6597:     my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   6598:     $env{'form.sillywaytopassafilearound'}=$contents;
1.275     albertel 6599:     &Apache::lonnet::finishuserfileupload($docuname,$docudom,'sillywaytopassafilearound',$filename);
1.157     albertel 6600: 
                   6601: }
                   6602: 
1.423     albertel 6603: =pod
                   6604: 
                   6605: =item scantron_putfile
                   6606: 
1.424     albertel 6607:     Stores the current version of the bubble sheet data files, and the
                   6608:     scan_data hash. (Does not modify the original version only the
                   6609:     corrected and skipped versions.
                   6610: 
                   6611:  Arguments:
                   6612:     $scanlines - hash ref that looks like the first return value from
                   6613:                  &scantron_getfile()
                   6614:     $scan_data - hash ref that looks like the second return value from
                   6615:                  &scantron_getfile()
                   6616: 
1.423     albertel 6617: =cut
                   6618: 
1.157     albertel 6619: sub scantron_putfile {
                   6620:     my ($scanlines,$scan_data) = @_;
1.200     albertel 6621:     #FIXME really would prefer a scantron directory
1.257     albertel 6622:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   6623:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.200     albertel 6624:     if ($scanlines) {
                   6625: 	my $prefix='scantron_';
1.157     albertel 6626: # no need to update orig, shouldn't change
                   6627: #   &lonnet_putfile(join("\n",@{$scanlines->{'orig'}}),$prefix.'orig_'.
1.257     albertel 6628: #		    $env{'form.scantron_selectfile'});
1.200     albertel 6629: 	&lonnet_putfile(join("\n",@{$scanlines->{'corrected'}}),
                   6630: 			$prefix.'corrected_'.
1.257     albertel 6631: 			$env{'form.scantron_selectfile'});
1.200     albertel 6632: 	&lonnet_putfile(join("\n",@{$scanlines->{'skipped'}}),
                   6633: 			$prefix.'skipped_'.
1.257     albertel 6634: 			$env{'form.scantron_selectfile'});
1.200     albertel 6635:     }
1.175     albertel 6636:     &Apache::lonnet::put('nohist_scantrondata',$scan_data,$cdom,$cname);
1.157     albertel 6637: }
                   6638: 
1.423     albertel 6639: =pod
                   6640: 
                   6641: =item scantron_get_line
                   6642: 
1.424     albertel 6643:    Returns the correct version of the scanline
                   6644: 
                   6645:  Arguments:
                   6646:     $scanlines - hash ref that looks like the first return value from
                   6647:                  &scantron_getfile()
                   6648:     $scan_data - hash ref that looks like the second return value from
                   6649:                  &scantron_getfile()
                   6650:     $i         - number of the requested line (starts at 0)
                   6651: 
                   6652:  Returns:
                   6653:    A scanline, (either the original or the corrected one if it
                   6654:    exists), or undef if the requested scanline should be
                   6655:    skipped. (Either because it's an skipped scanline, or it's an
                   6656:    unskipped scanline and we are not doing a 'do skipped scanlines'
                   6657:    pass.
                   6658: 
1.423     albertel 6659: =cut
                   6660: 
1.157     albertel 6661: sub scantron_get_line {
1.200     albertel 6662:     my ($scanlines,$scan_data,$i)=@_;
1.376     albertel 6663:     if (&should_be_skipped($scanlines,$scan_data,$i)) { return undef; }
                   6664:     #if ($scanlines->{'skipped'}[$i]) { return undef; }
1.157     albertel 6665:     if ($scanlines->{'corrected'}[$i]) {return $scanlines->{'corrected'}[$i];}
                   6666:     return $scanlines->{'orig'}[$i]; 
                   6667: }
                   6668: 
1.423     albertel 6669: =pod
                   6670: 
                   6671: =item scantron_todo_count
                   6672: 
1.424     albertel 6673:     Counts the number of scanlines that need processing.
                   6674: 
                   6675:  Arguments:
                   6676:     $scanlines - hash ref that looks like the first return value from
                   6677:                  &scantron_getfile()
                   6678:     $scan_data - hash ref that looks like the second return value from
                   6679:                  &scantron_getfile()
                   6680: 
                   6681:  Returns:
                   6682:     $count - number of scanlines to process
                   6683: 
1.423     albertel 6684: =cut
                   6685: 
1.200     albertel 6686: sub get_todo_count {
                   6687:     my ($scanlines,$scan_data)=@_;
                   6688:     my $count=0;
                   6689:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
                   6690: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
                   6691: 	if ($line=~/^[\s\cz]*$/) { next; }
                   6692: 	$count++;
                   6693:     }
                   6694:     return $count;
                   6695: }
                   6696: 
1.423     albertel 6697: =pod
                   6698: 
                   6699: =item scantron_put_line
                   6700: 
1.424     albertel 6701:     Updates the 'corrected' or 'skipped' versions of the bubble sheet
                   6702:     data file.
                   6703: 
                   6704:  Arguments:
                   6705:     $scanlines - hash ref that looks like the first return value from
                   6706:                  &scantron_getfile()
                   6707:     $scan_data - hash ref that looks like the second return value from
                   6708:                  &scantron_getfile()
                   6709:     $i         - line number to update
                   6710:     $newline   - contents of the updated scanline
                   6711:     $skip      - if true make the line for skipping and update the
                   6712:                  'skipped' file
                   6713: 
1.423     albertel 6714: =cut
                   6715: 
1.157     albertel 6716: sub scantron_put_line {
1.200     albertel 6717:     my ($scanlines,$scan_data,$i,$newline,$skip)=@_;
1.157     albertel 6718:     if ($skip) {
                   6719: 	$scanlines->{'skipped'}[$i]=$newline;
1.376     albertel 6720: 	&start_skipping($scan_data,$i);
1.157     albertel 6721: 	return;
                   6722:     }
                   6723:     $scanlines->{'corrected'}[$i]=$newline;
                   6724: }
                   6725: 
1.423     albertel 6726: =pod
                   6727: 
                   6728: =item scantron_clear_skip
                   6729: 
1.424     albertel 6730:    Remove a line from the 'skipped' file
                   6731: 
                   6732:  Arguments:
                   6733:     $scanlines - hash ref that looks like the first return value from
                   6734:                  &scantron_getfile()
                   6735:     $scan_data - hash ref that looks like the second return value from
                   6736:                  &scantron_getfile()
                   6737:     $i         - line number to update
                   6738: 
1.423     albertel 6739: =cut
                   6740: 
1.376     albertel 6741: sub scantron_clear_skip {
                   6742:     my ($scanlines,$scan_data,$i)=@_;
                   6743:     if (exists($scanlines->{'skipped'}[$i])) {
                   6744: 	undef($scanlines->{'skipped'}[$i]);
                   6745: 	return 1;
                   6746:     }
                   6747:     return 0;
                   6748: }
                   6749: 
1.423     albertel 6750: =pod
                   6751: 
                   6752: =item scantron_filter_not_exam
                   6753: 
1.424     albertel 6754:    Filter routine used by &Apache::lonnavmaps::retrieveResources(), to
                   6755:    filter out resources that are not marked as 'exam' mode
                   6756: 
1.423     albertel 6757: =cut
                   6758: 
1.334     albertel 6759: sub scantron_filter_not_exam {
                   6760:     my ($curres)=@_;
                   6761:     
                   6762:     if (ref($curres) && $curres->is_problem() && !$curres->is_exam()) {
                   6763: 	# if the user has asked to not have either hidden
                   6764: 	# or 'randomout' controlled resources to be graded
                   6765: 	# don't include them
                   6766: 	if ($env{'form.scantron_options_hidden'} eq 'ignore_hidden'
                   6767: 	    && $curres->randomout) {
                   6768: 	    return 0;
                   6769: 	}
                   6770: 	return 1;
                   6771:     }
                   6772:     return 0;
                   6773: }
                   6774: 
1.423     albertel 6775: =pod
                   6776: 
                   6777: =item scantron_validate_sequence
                   6778: 
1.424     albertel 6779:     Validates the selected sequence, checking for resource that are
                   6780:     not set to exam mode.
                   6781: 
1.423     albertel 6782: =cut
                   6783: 
1.334     albertel 6784: sub scantron_validate_sequence {
                   6785:     my ($r,$currentphase) = @_;
                   6786: 
                   6787:     my $navmap=Apache::lonnavmaps::navmap->new();
1.582     raeburn  6788:     unless (ref($navmap)) {
                   6789:         $r->print(&navmap_errormsg());
                   6790:         return (1,$currentphase);
                   6791:     }
1.334     albertel 6792:     my (undef,undef,$sequence)=
                   6793: 	&Apache::lonnet::decode_symb($env{'form.selectpage'});
                   6794: 
                   6795:     my $map=$navmap->getResourceByUrl($sequence);
                   6796: 
                   6797:     $r->print('<input type="hidden" name="validate_sequence_exam"
                   6798:                                     value="ignore" />');
                   6799:     if ($env{'form.validate_sequence_exam'} ne 'ignore') {
                   6800: 	my @resources=
                   6801: 	    $navmap->retrieveResources($map,\&scantron_filter_not_exam,1,0);
                   6802: 	if (@resources) {
1.357     banghart 6803: 	    $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 6804: 	    return (1,$currentphase);
                   6805: 	}
                   6806:     }
                   6807: 
                   6808:     return (0,$currentphase+1);
                   6809: }
                   6810: 
1.423     albertel 6811: 
                   6812: 
1.157     albertel 6813: sub scantron_validate_ID {
                   6814:     my ($r,$currentphase) = @_;
                   6815:     
                   6816:     #get student info
                   6817:     my $classlist=&Apache::loncoursedata::get_classlist();
                   6818:     my %idmap=&username_to_idmap($classlist);
                   6819: 
                   6820:     #get scantron line setup
1.257     albertel 6821:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.157     albertel 6822:     my ($scanlines,$scan_data)=&scantron_getfile();
1.582     raeburn  6823: 
                   6824:     my $nav_error;
                   6825:     &scantron_get_maxbubble(\$nav_error); # parse needs the bubble_lines.. array.
                   6826:     if ($nav_error) {
                   6827:         $r->print(&navmap_errormsg());
                   6828:         return(1,$currentphase);
                   6829:     }
1.157     albertel 6830: 
                   6831:     my %found=('ids'=>{},'usernames'=>{});
                   6832:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
1.200     albertel 6833: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.157     albertel 6834: 	if ($line=~/^[\s\cz]*$/) { next; }
                   6835: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
                   6836: 						 $scan_data);
                   6837: 	my $id=$$scan_record{'scantron.ID'};
                   6838: 	my $found;
                   6839: 	foreach my $checkid (keys(%idmap)) {
                   6840: 	    if (lc($checkid) eq lc($id)) { $found=$checkid;last; }
                   6841: 	}
                   6842: 	if ($found) {
                   6843: 	    my $username=$idmap{$found};
                   6844: 	    if ($found{'ids'}{$found}) {
                   6845: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
                   6846: 					 $line,'duplicateID',$found);
1.194     albertel 6847: 		return(1,$currentphase);
1.157     albertel 6848: 	    } elsif ($found{'usernames'}{$username}) {
                   6849: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
                   6850: 					 $line,'duplicateID',$username);
1.194     albertel 6851: 		return(1,$currentphase);
1.157     albertel 6852: 	    }
1.186     albertel 6853: 	    #FIXME store away line we previously saw the ID on to use above
1.157     albertel 6854: 	    $found{'ids'}{$found}++;
                   6855: 	    $found{'usernames'}{$username}++;
                   6856: 	} else {
                   6857: 	    if ($id =~ /^\s*$/) {
1.158     albertel 6858: 		my $username=&scan_data($scan_data,"$i.user");
1.157     albertel 6859: 		if (defined($username) && $found{'usernames'}{$username}) {
                   6860: 		    &scantron_get_correction($r,$i,$scan_record,
                   6861: 					     \%scantron_config,
                   6862: 					     $line,'duplicateID',$username);
1.194     albertel 6863: 		    return(1,$currentphase);
1.157     albertel 6864: 		} elsif (!defined($username)) {
                   6865: 		    &scantron_get_correction($r,$i,$scan_record,
                   6866: 					     \%scantron_config,
                   6867: 					     $line,'incorrectID');
1.194     albertel 6868: 		    return(1,$currentphase);
1.157     albertel 6869: 		}
                   6870: 		$found{'usernames'}{$username}++;
                   6871: 	    } else {
                   6872: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
                   6873: 					 $line,'incorrectID');
1.194     albertel 6874: 		return(1,$currentphase);
1.157     albertel 6875: 	    }
                   6876: 	}
                   6877:     }
                   6878: 
                   6879:     return (0,$currentphase+1);
                   6880: }
                   6881: 
1.423     albertel 6882: 
1.157     albertel 6883: sub scantron_get_correction {
                   6884:     my ($r,$i,$scan_record,$scan_config,$line,$error,$arg)=@_;
1.454     banghart 6885: #FIXME in the case of a duplicated ID the previous line, probably need
1.157     albertel 6886: #to show both the current line and the previous one and allow skipping
                   6887: #the previous one or the current one
                   6888: 
1.333     albertel 6889:     if ( $$scan_record{'scantron.PaperID'} =~ /\S/) {
1.492     albertel 6890: 	$r->print("<p>".&mt("<b>An error was detected ($error)</b>".
                   6891: 			    " for PaperID <tt>[_1]</tt>",
                   6892: 			    $$scan_record{'scantron.PaperID'})."</p> \n");
1.157     albertel 6893:     } else {
1.492     albertel 6894: 	$r->print("<p>".&mt("<b>An error was detected ($error)</b>".
                   6895: 			    " in scanline [_1] <pre>[_2]</pre>",
                   6896: 			    $i,$line)."</p> \n");
                   6897:     }
                   6898:     my $message="<p>".&mt("The ID on the form is  <tt>[_1]</tt><br />".
                   6899: 			  "The name on the paper is [_2],[_3]",
                   6900: 			  $$scan_record{'scantron.ID'},
                   6901: 			  $$scan_record{'scantron.LastName'},
                   6902: 			  $$scan_record{'scantron.FirstName'})."</p>";
1.242     albertel 6903: 
1.157     albertel 6904:     $r->print('<input type="hidden" name="scantron_corrections" value="'.$error.'" />'."\n");
                   6905:     $r->print('<input type="hidden" name="scantron_line" value="'.$i.'" />'."\n");
1.503     raeburn  6906:                            # Array populated for doublebubble or
                   6907:     my @lines_to_correct;  # missingbubble errors to build javascript
                   6908:                            # to validate radio button checking   
                   6909: 
1.157     albertel 6910:     if ($error =~ /ID$/) {
1.186     albertel 6911: 	if ($error eq 'incorrectID') {
1.492     albertel 6912: 	    $r->print("<p>".&mt("The encoded ID is not in the classlist").
                   6913: 		      "</p>\n");
1.157     albertel 6914: 	} elsif ($error eq 'duplicateID') {
1.492     albertel 6915: 	    $r->print("<p>".&mt("The encoded ID has also been used by a previous paper [_1]",$arg)."</p>\n");
1.157     albertel 6916: 	}
1.242     albertel 6917: 	$r->print($message);
1.492     albertel 6918: 	$r->print("<p>".&mt("How should I handle this?")." <br /> \n");
1.157     albertel 6919: 	$r->print("\n<ul><li> ");
                   6920: 	#FIXME it would be nice if this sent back the user ID and
                   6921: 	#could do partial userID matches
                   6922: 	$r->print(&Apache::loncommon::selectstudent_link('scantronupload',
                   6923: 				       'scantron_username','scantron_domain'));
                   6924: 	$r->print(": <input type='text' name='scantron_username' value='' />");
                   6925: 	$r->print("\n@".
1.257     albertel 6926: 		 &Apache::loncommon::select_dom_form($env{'request.role.domain'},'scantron_domain'));
1.157     albertel 6927: 
                   6928: 	$r->print('</li>');
1.186     albertel 6929:     } elsif ($error =~ /CODE$/) {
                   6930: 	if ($error eq 'incorrectCODE') {
1.492     albertel 6931: 	    $r->print("<p>".&mt("The encoded CODE is not in the list of possible CODEs.")."</p>\n");
1.186     albertel 6932: 	} elsif ($error eq 'duplicateCODE') {
1.492     albertel 6933: 	    $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 6934: 	}
1.492     albertel 6935: 	$r->print("<p>".&mt("The CODE on the form is  <tt>'[_1]'</tt>",
                   6936: 			    $$scan_record{'scantron.CODE'})."<br />\n");
1.242     albertel 6937: 	$r->print($message);
1.492     albertel 6938: 	$r->print("<p>".&mt("How should I handle this?")." <br /> \n");
1.187     albertel 6939: 	$r->print("\n<br /> ");
1.194     albertel 6940: 	my $i=0;
1.273     albertel 6941: 	if ($error eq 'incorrectCODE' 
                   6942: 	    && $$scan_record{'scantron.CODE'}=~/\S/ ) {
1.194     albertel 6943: 	    my ($max,$closest)=&scantron_get_closely_matching_CODEs($arg,$$scan_record{'scantron.CODE'});
1.278     albertel 6944: 	    if ($closest > 0) {
                   6945: 		foreach my $testcode (@{$closest}) {
                   6946: 		    my $checked='';
1.569     bisitz   6947: 		    if (!$i) { $checked=' checked="checked"'; }
1.492     albertel 6948: 		    $r->print("
                   6949:    <label>
1.569     bisitz   6950:        <input type='radio' name='scantron_CODE_resolution' value='use_closest_$i'$checked />
1.492     albertel 6951:        ".&mt("Use the similar CODE [_1] instead.",
                   6952: 	    "<b><tt>".$testcode."</tt></b>")."
                   6953:     </label>
                   6954:     <input type='hidden' name='scantron_CODE_closest_$i' value='$testcode' />");
1.278     albertel 6955: 		    $r->print("\n<br />");
                   6956: 		    $i++;
                   6957: 		}
1.194     albertel 6958: 	    }
                   6959: 	}
1.273     albertel 6960: 	if ($$scan_record{'scantron.CODE'}=~/\S/ ) {
1.569     bisitz   6961: 	    my $checked; if (!$i) { $checked=' checked="checked"'; }
1.492     albertel 6962: 	    $r->print("
                   6963:     <label>
1.569     bisitz   6964:         <input type='radio' name='scantron_CODE_resolution' value='use_unfound'$checked />
1.492     albertel 6965:        ".&mt("Use the CODE [_1] that is was on the paper, ignoring the error.",
                   6966: 	     "<b><tt>".$$scan_record{'scantron.CODE'}."</tt></b>")."
                   6967:     </label>");
1.273     albertel 6968: 	    $r->print("\n<br />");
                   6969: 	}
1.194     albertel 6970: 
1.597     wenzelju 6971: 	$r->print(&Apache::lonhtmlcommon::scripttag(<<ENDSCRIPT));
1.188     albertel 6972: function change_radio(field) {
1.190     albertel 6973:     var slct=document.scantronupload.scantron_CODE_resolution;
1.188     albertel 6974:     var i;
                   6975:     for (i=0;i<slct.length;i++) {
                   6976:         if (slct[i].value==field) { slct[i].checked=true; }
                   6977:     }
                   6978: }
                   6979: ENDSCRIPT
1.187     albertel 6980: 	my $href="/adm/pickcode?".
1.359     www      6981: 	   "form=".&escape("scantronupload").
                   6982: 	   "&scantron_format=".&escape($env{'form.scantron_format'}).
                   6983: 	   "&scantron_CODElist=".&escape($env{'form.scantron_CODElist'}).
                   6984: 	   "&curCODE=".&escape($$scan_record{'scantron.CODE'}).
                   6985: 	   "&scantron_selectfile=".&escape($env{'form.scantron_selectfile'});
1.332     albertel 6986: 	if ($env{'form.scantron_CODElist'} =~ /\S/) { 
1.492     albertel 6987: 	    $r->print("
                   6988:     <label>
                   6989:        <input type='radio' name='scantron_CODE_resolution' value='use_found' />
                   6990:        ".&mt("[_1]Select[_2] a CODE from the list of all CODEs and use it.",
                   6991: 	     "<a target='_blank' href='$href'>","</a>")."
                   6992:     </label> 
1.558     bisitz   6993:     ".&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 6994: 	    $r->print("\n<br />");
                   6995: 	}
1.492     albertel 6996: 	$r->print("
                   6997:     <label>
                   6998:        <input type='radio' name='scantron_CODE_resolution' value='use_typed' />
                   6999:        ".&mt("Use [_1] as the CODE.",
                   7000: 	     "</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 7001: 	$r->print("\n<br /><br />");
1.157     albertel 7002:     } elsif ($error eq 'doublebubble') {
1.503     raeburn  7003: 	$r->print("<p>".&mt("There have been multiple bubbles scanned for some question(s)")."</p>\n");
1.497     foxr     7004: 
                   7005: 	# The form field scantron_questions is acutally a list of line numbers.
                   7006: 	# represented by this form so:
                   7007: 
                   7008: 	my $line_list = &questions_to_line_list($arg);
                   7009: 
1.157     albertel 7010: 	$r->print('<input type="hidden" name="scantron_questions" value="'.
1.497     foxr     7011: 		  $line_list.'" />');
1.242     albertel 7012: 	$r->print($message);
1.492     albertel 7013: 	$r->print("<p>".&mt("Please indicate which bubble should be used for grading")."</p>");
1.157     albertel 7014: 	foreach my $question (@{$arg}) {
1.503     raeburn  7015: 	    my @linenums = &prompt_for_corrections($r,$question,$scan_config,
                   7016:                                                    $scan_record, $error);
1.524     raeburn  7017:             push(@lines_to_correct,@linenums);
1.157     albertel 7018: 	}
1.503     raeburn  7019:         $r->print(&verify_bubbles_checked(@lines_to_correct));
1.157     albertel 7020:     } elsif ($error eq 'missingbubble') {
1.492     albertel 7021: 	$r->print("<p>".&mt("There have been <b>no</b> bubbles scanned for some question(s)")."</p>\n");
1.242     albertel 7022: 	$r->print($message);
1.492     albertel 7023: 	$r->print("<p>".&mt("Please indicate which bubble should be used for grading.")."</p>");
1.503     raeburn  7024: 	$r->print(&mt("Some questions have no scanned bubbles.")."\n");
1.497     foxr     7025: 
1.503     raeburn  7026: 	# The form field scantron_questions is actually a list of line numbers not
1.497     foxr     7027: 	# a list of question numbers. Therefore:
                   7028: 	#
                   7029: 	
                   7030: 	my $line_list = &questions_to_line_list($arg);
                   7031: 
1.157     albertel 7032: 	$r->print('<input type="hidden" name="scantron_questions" value="'.
1.497     foxr     7033: 		  $line_list.'" />');
1.157     albertel 7034: 	foreach my $question (@{$arg}) {
1.503     raeburn  7035: 	    my @linenums = &prompt_for_corrections($r,$question,$scan_config,
                   7036:                                                    $scan_record, $error);
1.524     raeburn  7037:             push(@lines_to_correct,@linenums);
1.157     albertel 7038: 	}
1.503     raeburn  7039:         $r->print(&verify_bubbles_checked(@lines_to_correct));
1.157     albertel 7040:     } else {
                   7041: 	$r->print("\n<ul>");
                   7042:     }
                   7043:     $r->print("\n</li></ul>");
1.497     foxr     7044: }
                   7045: 
1.503     raeburn  7046: sub verify_bubbles_checked {
                   7047:     my (@ansnums) = @_;
                   7048:     my $ansnumstr = join('","',@ansnums);
                   7049:     my $warning = &mt("A bubble or 'No bubble' selection has not been made for one or more lines.");
1.597     wenzelju 7050:     my $output = &Apache::lonhtmlcommon::scripttag((<<ENDSCRIPT));
1.503     raeburn  7051: function verify_bubble_radio(form) {
                   7052:     var ansnumArray = new Array ("$ansnumstr");
                   7053:     var need_bubble_count = 0;
                   7054:     for (var i=0; i<ansnumArray.length; i++) {
                   7055:         if (form.elements["scantron_correct_Q_"+ansnumArray[i]].length > 1) {
                   7056:             var bubble_picked = 0; 
                   7057:             for (var j=0; j<form.elements["scantron_correct_Q_"+ansnumArray[i]].length; j++) {
                   7058:                 if (form.elements["scantron_correct_Q_"+ansnumArray[i]][j].checked == true) {
                   7059:                     bubble_picked = 1;
                   7060:                 }
                   7061:             }
                   7062:             if (bubble_picked == 0) {
                   7063:                 need_bubble_count ++;
                   7064:             }
                   7065:         }
                   7066:     }
                   7067:     if (need_bubble_count) {
                   7068:         alert("$warning");
                   7069:         return;
                   7070:     }
                   7071:     form.submit(); 
                   7072: }
                   7073: ENDSCRIPT
                   7074:     return $output;
                   7075: }
                   7076: 
1.497     foxr     7077: =pod
                   7078: 
                   7079: =item  questions_to_line_list
1.157     albertel 7080: 
1.497     foxr     7081: Converts a list of questions into a string of comma separated
                   7082: line numbers in the answer sheet used by the questions.  This is
                   7083: used to fill in the scantron_questions form field.
                   7084: 
                   7085:   Arguments:
                   7086:      questions    - Reference to an array of questions.
                   7087: 
                   7088: =cut
                   7089: 
                   7090: 
                   7091: sub questions_to_line_list {
                   7092:     my ($questions) = @_;
                   7093:     my @lines;
                   7094: 
1.503     raeburn  7095:     foreach my $item (@{$questions}) {
                   7096:         my $question = $item;
                   7097:         my ($first,$count,$last);
                   7098:         if ($item =~ /^(\d+)\.(\d+)$/) {
                   7099:             $question = $1;
                   7100:             my $subquestion = $2;
                   7101:             $first = $first_bubble_line{$question-1} + 1;
                   7102:             my @subans = split(/,/,$subdivided_bubble_lines{$question-1});
                   7103:             my $subcount = 1;
                   7104:             while ($subcount<$subquestion) {
                   7105:                 $first += $subans[$subcount-1];
                   7106:                 $subcount ++;
                   7107:             }
                   7108:             $count = $subans[$subquestion-1];
                   7109:         } else {
                   7110: 	    $first   = $first_bubble_line{$question-1} + 1;
                   7111: 	    $count   = $bubble_lines_per_response{$question-1};
                   7112:         }
1.506     raeburn  7113:         $last = $first+$count-1;
1.503     raeburn  7114:         push(@lines, ($first..$last));
1.497     foxr     7115:     }
                   7116:     return join(',', @lines);
                   7117: }
                   7118: 
                   7119: =pod 
                   7120: 
                   7121: =item prompt_for_corrections
                   7122: 
                   7123: Prompts for a potentially multiline correction to the
                   7124: user's bubbling (factors out common code from scantron_get_correction
                   7125: for multi and missing bubble cases).
                   7126: 
                   7127:  Arguments:
                   7128:    $r           - Apache request object.
                   7129:    $question    - The question number to prompt for.
                   7130:    $scan_config - The scantron file configuration hash.
                   7131:    $scan_record - Reference to the hash that has the the parsed scanlines.
1.503     raeburn  7132:    $error       - Type of error
1.497     foxr     7133: 
                   7134:  Implicit inputs:
                   7135:    %bubble_lines_per_response   - Starting line numbers for each question.
                   7136:                                   Numbered from 0 (but question numbers are from
                   7137:                                   1.
                   7138:    %first_bubble_line           - Starting bubble line for each question.
1.509     raeburn  7139:    %subdivided_bubble_lines     - optionresponse, matchresponse and rankresponse 
                   7140:                                   type problems render as separate sub-questions, 
1.503     raeburn  7141:                                   in exam mode. This hash contains a 
                   7142:                                   comma-separated list of the lines per 
                   7143:                                   sub-question.
1.510     raeburn  7144:    %responsetype_per_response   - essayresponse, formularesponse,
                   7145:                                   stringresponse, imageresponse, reactionresponse,
                   7146:                                   and organicresponse type problem parts can have
1.503     raeburn  7147:                                   multiple lines per response if the weight
                   7148:                                   assigned exceeds 10.  In this case, only
                   7149:                                   one bubble per line is permitted, but more 
                   7150:                                   than one line might contain bubbles, e.g.
                   7151:                                   bubbling of: line 1 - J, line 2 - J, 
                   7152:                                   line 3 - B would assign 22 points.  
1.497     foxr     7153: 
                   7154: =cut
                   7155: 
                   7156: sub prompt_for_corrections {
1.503     raeburn  7157:     my ($r, $question, $scan_config, $scan_record, $error) = @_;
                   7158:     my ($current_line,$lines);
                   7159:     my @linenums;
                   7160:     my $questionnum = $question;
                   7161:     if ($question =~ /^(\d+)\.(\d+)$/) {
                   7162:         $question = $1;
                   7163:         $current_line = $first_bubble_line{$question-1} + 1 ;
                   7164:         my $subquestion = $2;
                   7165:         my @subans = split(/,/,$subdivided_bubble_lines{$question-1});
                   7166:         my $subcount = 1;
                   7167:         while ($subcount<$subquestion) {
                   7168:             $current_line += $subans[$subcount-1];
                   7169:             $subcount ++;
                   7170:         }
                   7171:         $lines = $subans[$subquestion-1];
                   7172:     } else {
                   7173:         $current_line = $first_bubble_line{$question-1} + 1 ;
                   7174:         $lines        = $bubble_lines_per_response{$question-1};
                   7175:     }
1.497     foxr     7176:     if ($lines > 1) {
1.503     raeburn  7177:         $r->print(&mt('The group of bubble lines below responds to a single question.').'<br />');
                   7178:         if (($responsetype_per_response{$question-1} eq 'essayresponse') ||
                   7179:             ($responsetype_per_response{$question-1} eq 'formularesponse') ||
1.510     raeburn  7180:             ($responsetype_per_response{$question-1} eq 'stringresponse') ||
                   7181:             ($responsetype_per_response{$question-1} eq 'imageresponse') ||
                   7182:             ($responsetype_per_response{$question-1} eq 'reactionresponse') ||
                   7183:             ($responsetype_per_response{$question-1} eq 'organicresponse')) {
1.572     www      7184:             $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  7185:         } else {
                   7186:             $r->print(&mt("Select at most one bubble in a single line and select 'No Bubble' in all the other lines. ")."<br />");
                   7187:         }
1.497     foxr     7188:     }
                   7189:     for (my $i =0; $i < $lines; $i++) {
1.503     raeburn  7190:         my $selected = $$scan_record{"scantron.$current_line.answer"};
                   7191: 	&scantron_bubble_selector($r,$scan_config,$current_line, 
                   7192: 	        		  $questionnum,$error,split('', $selected));
1.524     raeburn  7193:         push(@linenums,$current_line);
1.497     foxr     7194: 	$current_line++;
                   7195:     }
                   7196:     if ($lines > 1) {
                   7197: 	$r->print("<hr /><br />");
                   7198:     }
1.503     raeburn  7199:     return @linenums;
1.157     albertel 7200: }
1.423     albertel 7201: 
                   7202: =pod
                   7203: 
                   7204: =item scantron_bubble_selector
                   7205:   
                   7206:    Generates the html radiobuttons to correct a single bubble line
1.424     albertel 7207:    possibly showing the existing the selected bubbles if known
1.423     albertel 7208: 
                   7209:  Arguments:
                   7210:     $r           - Apache request object
                   7211:     $scan_config - hash from &get_scantron_config()
1.497     foxr     7212:     $line        - Number of the line being displayed.
1.503     raeburn  7213:     $questionnum - Question number (may include subquestion)
                   7214:     $error       - Type of error.
1.497     foxr     7215:     @selected    - Array of bubbles picked on this line.
1.423     albertel 7216: 
                   7217: =cut
                   7218: 
1.157     albertel 7219: sub scantron_bubble_selector {
1.503     raeburn  7220:     my ($r,$scan_config,$line,$questionnum,$error,@selected)=@_;
1.157     albertel 7221:     my $max=$$scan_config{'Qlength'};
1.274     albertel 7222: 
                   7223:     my $scmode=$$scan_config{'Qon'};
                   7224:     if ($scmode eq 'number' || $scmode eq 'letter') { $max=10; }	     
                   7225: 
1.157     albertel 7226:     my @alphabet=('A'..'Z');
1.503     raeburn  7227:     $r->print(&Apache::loncommon::start_data_table().
                   7228:               &Apache::loncommon::start_data_table_row());
                   7229:     $r->print('<td rowspan="2" class="LC_leftcol_header">'.$line.'</td>');
1.497     foxr     7230:     for (my $i=0;$i<$max+1;$i++) {
                   7231: 	$r->print("\n".'<td align="center">');
                   7232: 	if ($selected[0] eq $alphabet[$i]) { $r->print('X'); shift(@selected) }
                   7233: 	else { $r->print('&nbsp;'); }
                   7234: 	$r->print('</td>');
                   7235:     }
1.503     raeburn  7236:     $r->print(&Apache::loncommon::end_data_table_row().
                   7237:               &Apache::loncommon::start_data_table_row());
1.497     foxr     7238:     for (my $i=0;$i<$max;$i++) {
                   7239: 	$r->print("\n".
                   7240: 		  '<td><label><input type="radio" name="scantron_correct_Q_'.
                   7241: 		  $line.'" value="'.$i.'" />'.$alphabet[$i]."</label></td>");
                   7242:     }
1.503     raeburn  7243:     my $nobub_checked = ' ';
                   7244:     if ($error eq 'missingbubble') {
                   7245:         $nobub_checked = ' checked = "checked" ';
                   7246:     }
                   7247:     $r->print("\n".'<td><label><input type="radio" name="scantron_correct_Q_'.
                   7248: 	      $line.'" value="none"'.$nobub_checked.'/>'.&mt('No bubble').
                   7249:               '</label>'."\n".'<input type="hidden" name="scantron_questionnum_Q_'.
                   7250:               $line.'" value="'.$questionnum.'" /></td>');
                   7251:     $r->print(&Apache::loncommon::end_data_table_row().
                   7252:               &Apache::loncommon::end_data_table());
1.157     albertel 7253: }
                   7254: 
1.423     albertel 7255: =pod
                   7256: 
                   7257: =item num_matches
                   7258: 
1.424     albertel 7259:    Counts the number of characters that are the same between the two arguments.
                   7260: 
                   7261:  Arguments:
                   7262:    $orig - CODE from the scanline
                   7263:    $code - CODE to match against
                   7264: 
                   7265:  Returns:
                   7266:    $count - integer count of the number of same characters between the
                   7267:             two arguments
                   7268: 
1.423     albertel 7269: =cut
                   7270: 
1.194     albertel 7271: sub num_matches {
                   7272:     my ($orig,$code) = @_;
                   7273:     my @code=split(//,$code);
                   7274:     my @orig=split(//,$orig);
                   7275:     my $same=0;
                   7276:     for (my $i=0;$i<scalar(@code);$i++) {
                   7277: 	if ($code[$i] eq $orig[$i]) { $same++; }
                   7278:     }
                   7279:     return $same;
                   7280: }
                   7281: 
1.423     albertel 7282: =pod
                   7283: 
                   7284: =item scantron_get_closely_matching_CODEs
                   7285: 
1.424     albertel 7286:    Cycles through all CODEs and finds the set that has the greatest
                   7287:    number of same characters as the provided CODE
                   7288: 
                   7289:  Arguments:
                   7290:    $allcodes - hash ref returned by &get_codes()
                   7291:    $CODE     - CODE from the current scanline
                   7292: 
                   7293:  Returns:
                   7294:    2 element list
                   7295:     - first elements is number of how closely matching the best fit is 
                   7296:       (5 means best set has 5 matching characters)
                   7297:     - second element is an arrary ref containing the set of valid CODEs
                   7298:       that best fit the passed in CODE
                   7299: 
1.423     albertel 7300: =cut
                   7301: 
1.194     albertel 7302: sub scantron_get_closely_matching_CODEs {
                   7303:     my ($allcodes,$CODE)=@_;
                   7304:     my @CODEs;
                   7305:     foreach my $testcode (sort(keys(%{$allcodes}))) {
                   7306: 	push(@{$CODEs[&num_matches($CODE,$testcode)]},$testcode);
                   7307:     }
                   7308: 
                   7309:     return ($#CODEs,$CODEs[-1]);
                   7310: }
                   7311: 
1.423     albertel 7312: =pod
                   7313: 
                   7314: =item get_codes
                   7315: 
1.424     albertel 7316:    Builds a hash which has keys of all of the valid CODEs from the selected
                   7317:    set of remembered CODEs.
                   7318: 
                   7319:  Arguments:
                   7320:   $old_name - name of the set of remembered CODEs
                   7321:   $cdom     - domain of the course
                   7322:   $cnum     - internal course name
                   7323: 
                   7324:  Returns:
                   7325:   %allcodes - keys are the valid CODEs, values are all 1
                   7326: 
1.423     albertel 7327: =cut
                   7328: 
1.194     albertel 7329: sub get_codes {
1.280     foxr     7330:     my ($old_name, $cdom, $cnum) = @_;
                   7331:     if (!$old_name) {
                   7332: 	$old_name=$env{'form.scantron_CODElist'};
                   7333:     }
                   7334:     if (!$cdom) {
                   7335: 	$cdom =$env{'course.'.$env{'request.course.id'}.'.domain'};
                   7336:     }
                   7337:     if (!$cnum) {
                   7338: 	$cnum =$env{'course.'.$env{'request.course.id'}.'.num'};
                   7339:     }
1.278     albertel 7340:     my %result=&Apache::lonnet::get('CODEs',[$old_name,"type\0$old_name"],
                   7341: 				    $cdom,$cnum);
                   7342:     my %allcodes;
                   7343:     if ($result{"type\0$old_name"} eq 'number') {
                   7344: 	%allcodes=map {($_,1)} split(',',$result{$old_name});
                   7345:     } else {
                   7346: 	%allcodes=map {(&Apache::lonprintout::num_to_letters($_),1)} split(',',$result{$old_name});
                   7347:     }
1.194     albertel 7348:     return %allcodes;
                   7349: }
                   7350: 
1.423     albertel 7351: =pod
                   7352: 
                   7353: =item scantron_validate_CODE
                   7354: 
1.424     albertel 7355:    Validates all scanlines in the selected file to not have any
                   7356:    invalid or underspecified CODEs and that none of the codes are
                   7357:    duplicated if this was requested.
                   7358: 
1.423     albertel 7359: =cut
                   7360: 
1.157     albertel 7361: sub scantron_validate_CODE {
                   7362:     my ($r,$currentphase) = @_;
1.257     albertel 7363:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.186     albertel 7364:     if ($scantron_config{'CODElocation'} &&
                   7365: 	$scantron_config{'CODEstart'} &&
                   7366: 	$scantron_config{'CODElength'}) {
1.257     albertel 7367: 	if (!defined($env{'form.scantron_CODElist'})) {
1.186     albertel 7368: 	    &FIXME_blow_up()
                   7369: 	}
                   7370:     } else {
                   7371: 	return (0,$currentphase+1);
                   7372:     }
                   7373:     
                   7374:     my %usedCODEs;
                   7375: 
1.194     albertel 7376:     my %allcodes=&get_codes();
1.186     albertel 7377: 
1.582     raeburn  7378:     my $nav_error;
                   7379:     &scantron_get_maxbubble(\$nav_error); # parse needs the lines per response array.
                   7380:     if ($nav_error) {
                   7381:         $r->print(&navmap_errormsg());
                   7382:         return(1,$currentphase);
                   7383:     }
1.447     foxr     7384: 
1.186     albertel 7385:     my ($scanlines,$scan_data)=&scantron_getfile();
                   7386:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
1.200     albertel 7387: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.186     albertel 7388: 	if ($line=~/^[\s\cz]*$/) { next; }
                   7389: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
                   7390: 						 $scan_data);
                   7391: 	my $CODE=$$scan_record{'scantron.CODE'};
                   7392: 	my $error=0;
1.224     albertel 7393: 	if (!&Apache::lonnet::validCODE($CODE)) {
                   7394: 	    &scantron_get_correction($r,$i,$scan_record,
                   7395: 				     \%scantron_config,
                   7396: 				     $line,'incorrectCODE',\%allcodes);
                   7397: 	    return(1,$currentphase);
                   7398: 	}
1.221     albertel 7399: 	if (%allcodes && !exists($allcodes{$CODE}) 
                   7400: 	    && !$$scan_record{'scantron.useCODE'}) {
1.186     albertel 7401: 	    &scantron_get_correction($r,$i,$scan_record,
                   7402: 				     \%scantron_config,
1.194     albertel 7403: 				     $line,'incorrectCODE',\%allcodes);
                   7404: 	    return(1,$currentphase);
1.186     albertel 7405: 	}
1.214     albertel 7406: 	if (exists($usedCODEs{$CODE}) 
1.257     albertel 7407: 	    && $env{'form.scantron_CODEunique'} eq 'yes'
1.192     albertel 7408: 	    && !$$scan_record{'scantron.CODE_ignore_dup'}) {
1.186     albertel 7409: 	    &scantron_get_correction($r,$i,$scan_record,
                   7410: 				     \%scantron_config,
1.194     albertel 7411: 				     $line,'duplicateCODE',$usedCODEs{$CODE});
                   7412: 	    return(1,$currentphase);
1.186     albertel 7413: 	}
1.524     raeburn  7414: 	push(@{$usedCODEs{$CODE}},$$scan_record{'scantron.PaperID'});
1.186     albertel 7415:     }
1.157     albertel 7416:     return (0,$currentphase+1);
                   7417: }
                   7418: 
1.423     albertel 7419: =pod
                   7420: 
                   7421: =item scantron_validate_doublebubble
                   7422: 
1.424     albertel 7423:    Validates all scanlines in the selected file to not have any
                   7424:    bubble lines with multiple bubbles marked.
                   7425: 
1.423     albertel 7426: =cut
                   7427: 
1.157     albertel 7428: sub scantron_validate_doublebubble {
                   7429:     my ($r,$currentphase) = @_;
                   7430:     #get student info
                   7431:     my $classlist=&Apache::loncoursedata::get_classlist();
                   7432:     my %idmap=&username_to_idmap($classlist);
                   7433: 
                   7434:     #get scantron line setup
1.257     albertel 7435:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.157     albertel 7436:     my ($scanlines,$scan_data)=&scantron_getfile();
1.583     raeburn  7437:     my $nav_error;
                   7438:     &scantron_get_maxbubble(\$nav_error); # parse needs the bubble line array.
                   7439:     if ($nav_error) {
                   7440:         $r->print(&navmap_errormsg());
                   7441:         return(1,$currentphase);
                   7442:     }
1.447     foxr     7443: 
1.157     albertel 7444:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
1.200     albertel 7445: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.157     albertel 7446: 	if ($line=~/^[\s\cz]*$/) { next; }
                   7447: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
                   7448: 						 $scan_data);
                   7449: 	if (!defined($$scan_record{'scantron.doubleerror'})) { next; }
                   7450: 	&scantron_get_correction($r,$i,$scan_record,\%scantron_config,$line,
                   7451: 				 'doublebubble',
                   7452: 				 $$scan_record{'scantron.doubleerror'});
                   7453:     	return (1,$currentphase);
                   7454:     }
                   7455:     return (0,$currentphase+1);
                   7456: }
                   7457: 
1.423     albertel 7458: 
1.503     raeburn  7459: sub scantron_get_maxbubble {
1.582     raeburn  7460:     my ($nav_error) = @_;
1.257     albertel 7461:     if (defined($env{'form.scantron_maxbubble'}) &&
                   7462: 	$env{'form.scantron_maxbubble'}) {
1.447     foxr     7463: 	&restore_bubble_lines();
1.257     albertel 7464: 	return $env{'form.scantron_maxbubble'};
1.191     albertel 7465:     }
1.330     albertel 7466: 
1.447     foxr     7467:     my (undef, undef, $sequence) =
1.257     albertel 7468: 	&Apache::lonnet::decode_symb($env{'form.selectpage'});
1.330     albertel 7469: 
1.447     foxr     7470:     my $navmap=Apache::lonnavmaps::navmap->new();
1.582     raeburn  7471:     unless (ref($navmap)) {
                   7472:         if (ref($nav_error)) {
                   7473:             $$nav_error = 1;
                   7474:         }
1.591     raeburn  7475:         return;
1.582     raeburn  7476:     }
1.191     albertel 7477:     my $map=$navmap->getResourceByUrl($sequence);
                   7478:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
1.330     albertel 7479: 
                   7480:     &Apache::lonxml::clear_problem_counter();
                   7481: 
1.557     raeburn  7482:     my $uname       = $env{'user.name'};
                   7483:     my $udom        = $env{'user.domain'};
1.435     foxr     7484:     my $cid         = $env{'request.course.id'};
                   7485:     my $total_lines = 0;
                   7486:     %bubble_lines_per_response = ();
1.447     foxr     7487:     %first_bubble_line         = ();
1.503     raeburn  7488:     %subdivided_bubble_lines   = ();
                   7489:     %responsetype_per_response = ();
1.554     raeburn  7490: 
1.447     foxr     7491:     my $response_number = 0;
                   7492:     my $bubble_line     = 0;
1.191     albertel 7493:     foreach my $resource (@resources) {
1.542     raeburn  7494:         my ($analysis,$parts) = &scantron_partids_tograde($resource,$cid,$uname,$udom);
                   7495:         if ((ref($analysis) eq 'HASH') && (ref($parts) eq 'ARRAY')) {
                   7496: 	    foreach my $part_id (@{$parts}) {
                   7497:                 my $lines;
                   7498: 
                   7499: 	        # TODO - make this a persistent hash not an array.
                   7500: 
                   7501:                 # optionresponse, matchresponse and rankresponse type items 
                   7502:                 # render as separate sub-questions in exam mode.
                   7503:                 if (($analysis->{$part_id.'.type'} eq 'optionresponse') ||
                   7504:                     ($analysis->{$part_id.'.type'} eq 'matchresponse') ||
                   7505:                     ($analysis->{$part_id.'.type'} eq 'rankresponse')) {
                   7506:                     my ($numbub,$numshown);
                   7507:                     if ($analysis->{$part_id.'.type'} eq 'optionresponse') {
                   7508:                         if (ref($analysis->{$part_id.'.options'}) eq 'ARRAY') {
                   7509:                             $numbub = scalar(@{$analysis->{$part_id.'.options'}});
                   7510:                         }
                   7511:                     } elsif ($analysis->{$part_id.'.type'} eq 'matchresponse') {
                   7512:                         if (ref($analysis->{$part_id.'.items'}) eq 'ARRAY') {
                   7513:                             $numbub = scalar(@{$analysis->{$part_id.'.items'}});
                   7514:                         }
                   7515:                     } elsif ($analysis->{$part_id.'.type'} eq 'rankresponse') {
                   7516:                         if (ref($analysis->{$part_id.'.foils'}) eq 'ARRAY') {
                   7517:                             $numbub = scalar(@{$analysis->{$part_id.'.foils'}});
                   7518:                         }
                   7519:                     }
                   7520:                     if (ref($analysis->{$part_id.'.shown'}) eq 'ARRAY') {
                   7521:                         $numshown = scalar(@{$analysis->{$part_id.'.shown'}});
                   7522:                     }
                   7523:                     my $bubbles_per_line = 10;
                   7524:                     my $inner_bubble_lines = int($numbub/$bubbles_per_line);
                   7525:                     if (($numbub % $bubbles_per_line) != 0) {
                   7526:                         $inner_bubble_lines++;
                   7527:                     }
                   7528:                     for (my $i=0; $i<$numshown; $i++) {
                   7529:                         $subdivided_bubble_lines{$response_number} .= 
                   7530:                             $inner_bubble_lines.',';
                   7531:                     }
                   7532:                     $subdivided_bubble_lines{$response_number} =~ s/,$//;
                   7533:                     $lines = $numshown * $inner_bubble_lines;
                   7534:                 } else {
                   7535:                     $lines = $analysis->{"$part_id.bubble_lines"};
                   7536:                 } 
                   7537: 
                   7538:                 $first_bubble_line{$response_number} = $bubble_line;
                   7539: 	        $bubble_lines_per_response{$response_number} = $lines;
                   7540:                 $responsetype_per_response{$response_number} = 
                   7541:                     $analysis->{$part_id.'.type'};
                   7542: 	        $response_number++;
                   7543: 
                   7544: 	        $bubble_line +=  $lines;
                   7545: 	        $total_lines +=  $lines;
                   7546: 	    }
                   7547:         }
                   7548:     }
1.552     raeburn  7549:     &Apache::lonnet::delenv('scantron.');
1.542     raeburn  7550: 
                   7551:     &save_bubble_lines();
                   7552:     $env{'form.scantron_maxbubble'} =
                   7553: 	$total_lines;
                   7554:     return $env{'form.scantron_maxbubble'};
                   7555: }
1.523     raeburn  7556: 
1.157     albertel 7557: sub scantron_validate_missingbubbles {
                   7558:     my ($r,$currentphase) = @_;
                   7559:     #get student info
                   7560:     my $classlist=&Apache::loncoursedata::get_classlist();
                   7561:     my %idmap=&username_to_idmap($classlist);
                   7562: 
                   7563:     #get scantron line setup
1.257     albertel 7564:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.157     albertel 7565:     my ($scanlines,$scan_data)=&scantron_getfile();
1.582     raeburn  7566:     my $nav_error;
                   7567:     my $max_bubble=&scantron_get_maxbubble(\$nav_error);
                   7568:     if ($nav_error) {
                   7569:         return(1,$currentphase);
                   7570:     }
1.157     albertel 7571:     if (!$max_bubble) { $max_bubble=2**31; }
                   7572:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
1.200     albertel 7573: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.157     albertel 7574: 	if ($line=~/^[\s\cz]*$/) { next; }
                   7575: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
                   7576: 						 $scan_data);
                   7577: 	if (!defined($$scan_record{'scantron.missingerror'})) { next; }
                   7578: 	my @to_correct;
1.470     foxr     7579: 	
                   7580: 	# Probably here's where the error is...
                   7581: 
1.157     albertel 7582: 	foreach my $missing (@{$$scan_record{'scantron.missingerror'}}) {
1.505     raeburn  7583:             my $lastbubble;
                   7584:             if ($missing =~ /^(\d+)\.(\d+)$/) {
                   7585:                my $question = $1;
                   7586:                my $subquestion = $2;
                   7587:                if (!defined($first_bubble_line{$question -1})) { next; }
                   7588:                my $first = $first_bubble_line{$question-1};
                   7589:                my @subans = split(/,/,$subdivided_bubble_lines{$question-1});
                   7590:                my $subcount = 1;
                   7591:                while ($subcount<$subquestion) {
                   7592:                    $first += $subans[$subcount-1];
                   7593:                    $subcount ++;
                   7594:                }
                   7595:                my $count = $subans[$subquestion-1];
                   7596:                $lastbubble = $first + $count;
                   7597:             } else {
                   7598:                 if (!defined($first_bubble_line{$missing - 1})) { next; }
                   7599:                 $lastbubble = $first_bubble_line{$missing - 1} + $bubble_lines_per_response{$missing - 1};
                   7600:             }
                   7601:             if ($lastbubble > $max_bubble) { next; }
1.157     albertel 7602: 	    push(@to_correct,$missing);
                   7603: 	}
                   7604: 	if (@to_correct) {
                   7605: 	    &scantron_get_correction($r,$i,$scan_record,\%scantron_config,
                   7606: 				     $line,'missingbubble',\@to_correct);
                   7607: 	    return (1,$currentphase);
                   7608: 	}
                   7609: 
                   7610:     }
                   7611:     return (0,$currentphase+1);
                   7612: }
                   7613: 
1.423     albertel 7614: 
1.82      albertel 7615: sub scantron_process_students {
1.75      albertel 7616:     my ($r) = @_;
1.513     foxr     7617: 
1.257     albertel 7618:     my (undef,undef,$sequence)=&Apache::lonnet::decode_symb($env{'form.selectpage'});
1.324     albertel 7619:     my ($symb)=&get_symb($r);
1.513     foxr     7620:     if (!$symb) {
                   7621: 	return '';
                   7622:     }
1.324     albertel 7623:     my $default_form_data=&defaultFormData($symb);
1.82      albertel 7624: 
1.257     albertel 7625:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.157     albertel 7626:     my ($scanlines,$scan_data)=&scantron_getfile();
1.82      albertel 7627:     my $classlist=&Apache::loncoursedata::get_classlist();
                   7628:     my %idmap=&username_to_idmap($classlist);
1.132     bowersj2 7629:     my $navmap=Apache::lonnavmaps::navmap->new();
1.582     raeburn  7630:     unless (ref($navmap)) {
                   7631:         $r->print(&navmap_errormsg());
                   7632:         return '';
                   7633:     }  
1.83      albertel 7634:     my $map=$navmap->getResourceByUrl($sequence);
                   7635:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
1.557     raeburn  7636:     my (%grader_partids_by_symb,%grader_randomlists_by_symb);
                   7637:     &graders_resources_pass(\@resources,\%grader_partids_by_symb,
                   7638:                             \%grader_randomlists_by_symb);
1.586     raeburn  7639:     my $resource_error;
1.557     raeburn  7640:     foreach my $resource (@resources) {
1.586     raeburn  7641:         my $ressymb;
                   7642:         if (ref($resource)) {
                   7643:             $ressymb = $resource->symb();
                   7644:         } else {
                   7645:             $resource_error = 1;
                   7646:             last;
                   7647:         }
1.557     raeburn  7648:         my ($analysis,$parts) =
                   7649:             &scantron_partids_tograde($resource,$env{'request.course.id'},
                   7650:                                       $env{'user.name'},$env{'user.domain'},1);
                   7651:         $grader_partids_by_symb{$ressymb} = $parts;
                   7652:         if (ref($analysis) eq 'HASH') {
                   7653:             if (ref($analysis->{'parts_withrandomlist'}) eq 'ARRAY') {
                   7654:                 $grader_randomlists_by_symb{$ressymb} = 
                   7655:                     $analysis->{'parts_withrandomlist'};
                   7656:             }
                   7657:         }
                   7658:     }
1.586     raeburn  7659:     if ($resource_error) {
                   7660:         $r->print(&navmap_errormsg());
                   7661:         return '';
                   7662:     }
1.557     raeburn  7663: 
1.554     raeburn  7664:     my ($uname,$udom);
1.82      albertel 7665:     my $result= <<SCANTRONFORM;
1.81      albertel 7666: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantronupload">
                   7667:   <input type="hidden" name="command" value="scantron_configphase" />
                   7668:   $default_form_data
                   7669: SCANTRONFORM
1.82      albertel 7670:     $r->print($result);
                   7671: 
                   7672:     my @delayqueue;
1.542     raeburn  7673:     my (%completedstudents,%scandata);
1.140     albertel 7674:     
1.520     www      7675:     my $lock=&Apache::lonnet::set_lock(&mt('Grading bubblesheet exam'));
1.200     albertel 7676:     my $count=&get_todo_count($scanlines,$scan_data);
1.575     www      7677:     my %prog_state=&Apache::lonhtmlcommon::Create_PrgWin($r,'Bubblesheet Status',
                   7678:  				    'Bubblesheet Progress',$count,
1.195     albertel 7679: 				    'inline',undef,'scantronupload');
1.140     albertel 7680:     &Apache::lonhtmlcommon::Update_PrgWin($r,\%prog_state,
                   7681: 					  'Processing first student');
1.542     raeburn  7682:     $r->print('<br />');
1.140     albertel 7683:     my $start=&Time::HiRes::time();
1.158     albertel 7684:     my $i=-1;
1.542     raeburn  7685:     my $started;
1.447     foxr     7686: 
1.582     raeburn  7687:     my $nav_error;
                   7688:     &scantron_get_maxbubble(\$nav_error); # Need the bubble lines array to parse.
                   7689:     if ($nav_error) {
                   7690:         $r->print(&navmap_errormsg());
                   7691:         return '';
                   7692:     }
                   7693: 
1.513     foxr     7694:     # If an ssi failed in scantron_get_maxbubble, put an error message out to
                   7695:     # the user and return.
                   7696: 
                   7697:     if ($ssi_error) {
                   7698: 	$r->print("</form>");
                   7699: 	&ssi_print_error($r);
                   7700: 	$r->print(&show_grading_menu_form($symb));
1.520     www      7701:         &Apache::lonnet::remove_lock($lock);
1.513     foxr     7702: 	return '';		# Dunno why the other returns return '' rather than just returning.
                   7703:     }
1.447     foxr     7704: 
1.542     raeburn  7705:     my %lettdig = &letter_to_digits();
                   7706:     my $numletts = scalar(keys(%lettdig));
                   7707: 
1.157     albertel 7708:     while ($i<$scanlines->{'count'}) {
                   7709:  	($uname,$udom)=('','');
                   7710:  	$i++;
1.200     albertel 7711:  	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.157     albertel 7712:  	if ($line=~/^[\s\cz]*$/) { next; }
1.200     albertel 7713: 	if ($started) {
                   7714: 	    &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state,
                   7715: 						     'last student');
                   7716: 	}
                   7717: 	$started=1;
1.157     albertel 7718:  	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
                   7719:  						 $scan_data);
                   7720:  	unless ($uname=&scantron_find_student($scan_record,$scan_data,
                   7721:  					      \%idmap,$i)) {
                   7722:   	    &scantron_add_delay(\@delayqueue,$line,
                   7723:  				'Unable to find a student that matches',1);
                   7724:  	    next;
                   7725:   	}
                   7726:  	if (exists $completedstudents{$uname}) {
                   7727:  	    &scantron_add_delay(\@delayqueue,$line,
                   7728:  				'Student '.$uname.' has multiple sheets',2);
                   7729:  	    next;
                   7730:  	}
                   7731:   	($uname,$udom)=split(/:/,$uname);
1.330     albertel 7732: 
1.586     raeburn  7733:         my (%partids_by_symb,$res_error);
1.554     raeburn  7734:         foreach my $resource (@resources) {
1.586     raeburn  7735:             my $ressymb;
                   7736:             if (ref($resource)) {
                   7737:                 $ressymb = $resource->symb();
                   7738:             } else {
                   7739:                 $res_error = 1;
                   7740:                 last;
                   7741:             }
1.557     raeburn  7742:             if ((exists($grader_randomlists_by_symb{$ressymb})) ||
                   7743:                 (ref($grader_partids_by_symb{$ressymb}) ne 'ARRAY')) {
                   7744:                 my ($analysis,$parts) =
                   7745:                     &scantron_partids_tograde($resource,$env{'request.course.id'},$uname,$udom);
                   7746:                 $partids_by_symb{$ressymb} = $parts;
                   7747:             } else {
                   7748:                 $partids_by_symb{$ressymb} = $grader_partids_by_symb{$ressymb};
                   7749:             }
1.554     raeburn  7750:         }
                   7751: 
1.586     raeburn  7752:         if ($res_error) {
                   7753:             &scantron_add_delay(\@delayqueue,$line,
                   7754:                                 'An error occurred while grading student '.$uname,2);
                   7755:             next;
                   7756:         }
                   7757: 
1.330     albertel 7758: 	&Apache::lonxml::clear_problem_counter();
1.514     raeburn  7759:   	&Apache::lonnet::appenv($scan_record);
1.376     albertel 7760: 
                   7761: 	if (&scantron_clear_skip($scanlines,$scan_data,$i)) {
                   7762: 	    &scantron_putfile($scanlines,$scan_data);
                   7763: 	}
1.161     albertel 7764: 	
1.542     raeburn  7765:         my $scancode;
                   7766:         if ((exists($scan_record->{'scantron.CODE'})) &&
                   7767:             (&Apache::lonnet::validCODE($scan_record->{'scantron.CODE'}))) {
                   7768:             $scancode = $scan_record->{'scantron.CODE'};
                   7769:         } else {
                   7770:             $scancode = '';
                   7771:         }
                   7772: 
                   7773:         if (&grade_student_bubbles($r,$uname,$udom,$scan_record,$scancode,
1.554     raeburn  7774:                                    \@resources,\%partids_by_symb) eq 'ssi_error') {
1.542     raeburn  7775:             $ssi_error = 0; # So end of handler error message does not trigger.
                   7776:             $r->print("</form>");
                   7777:             &ssi_print_error($r);
                   7778:             $r->print(&show_grading_menu_form($symb));
                   7779:             &Apache::lonnet::remove_lock($lock);
                   7780:             return '';      # Why return ''?  Beats me.
                   7781:         }
1.513     foxr     7782: 
1.140     albertel 7783: 	$completedstudents{$uname}={'line'=>$line};
1.542     raeburn  7784:         if ($env{'form.verifyrecord'}) {
                   7785:             my $lastpos = $env{'form.scantron_maxbubble'}*$scantron_config{'Qlength'};
                   7786:             my $studentdata = substr($line,$scantron_config{'Qstart'}-1,$lastpos);
                   7787:             chomp($studentdata);
                   7788:             $studentdata =~ s/\r$//;
                   7789:             my $studentrecord = '';
                   7790:             my $counter = -1;
                   7791:             foreach my $resource (@resources) {
1.554     raeburn  7792:                 my $ressymb = $resource->symb();
1.542     raeburn  7793:                 ($counter,my $recording) =
                   7794:                     &verify_scantron_grading($resource,$udom,$uname,$env{'request.course.id'},
1.554     raeburn  7795:                                              $counter,$studentdata,$partids_by_symb{$ressymb},
1.542     raeburn  7796:                                              \%scantron_config,\%lettdig,$numletts);
                   7797:                 $studentrecord .= $recording;
                   7798:             }
                   7799:             if ($studentrecord ne $studentdata) {
1.554     raeburn  7800:                 &Apache::lonxml::clear_problem_counter();
                   7801:                 if (&grade_student_bubbles($r,$uname,$udom,$scan_record,$scancode,
                   7802:                                            \@resources,\%partids_by_symb) eq 'ssi_error') {
                   7803:                     $ssi_error = 0; # So end of handler error message does not trigger.
                   7804:                     $r->print("</form>");
                   7805:                     &ssi_print_error($r);
                   7806:                     $r->print(&show_grading_menu_form($symb));
                   7807:                     &Apache::lonnet::remove_lock($lock);
                   7808:                     delete($completedstudents{$uname});
                   7809:                     return '';
                   7810:                 }
1.542     raeburn  7811:                 $counter = -1;
                   7812:                 $studentrecord = '';
                   7813:                 foreach my $resource (@resources) {
1.554     raeburn  7814:                     my $ressymb = $resource->symb();
1.542     raeburn  7815:                     ($counter,my $recording) =
                   7816:                         &verify_scantron_grading($resource,$udom,$uname,$env{'request.course.id'},
1.554     raeburn  7817:                                                  $counter,$studentdata,$partids_by_symb{$ressymb},
1.542     raeburn  7818:                                                  \%scantron_config,\%lettdig,$numletts);
                   7819:                     $studentrecord .= $recording;
                   7820:                 }
                   7821:                 if ($studentrecord ne $studentdata) {
                   7822:                     $r->print('<p><span class="LC_error">');
                   7823:                     if ($scancode eq '') {
                   7824:                         $r->print(&mt('Mismatch grading bubble sheet for user: [_1] with ID: [_2].',
                   7825:                                   $uname.':'.$udom,$scan_record->{'scantron.ID'}));
                   7826:                     } else {
                   7827:                         $r->print(&mt('Mismatch grading bubble sheet for user: [_1] with ID: [_2] and CODE: [_3].',
                   7828:                                   $uname.':'.$udom,$scan_record->{'scantron.ID'},$scancode));
                   7829:                     }
                   7830:                     $r->print('</span><br />'.&Apache::loncommon::start_data_table()."\n".
                   7831:                               &Apache::loncommon::start_data_table_header_row()."\n".
                   7832:                               '<th>'.&mt('Source').'</th><th>'.&mt('Bubbled responses').'</th>'.
                   7833:                               &Apache::loncommon::end_data_table_header_row()."\n".
                   7834:                               &Apache::loncommon::start_data_table_row().
                   7835:                               '<td>'.&mt('Bubble Sheet').'</td>'.
                   7836:                               '<td><span class="LC_nobreak">'.$studentdata.'</span></td>'.
                   7837:                               &Apache::loncommon::end_data_table_row().
                   7838:                               &Apache::loncommon::start_data_table_row().
                   7839:                               '<td>Stored submissions</td>'.
                   7840:                               '<td><span class="LC_nobreak">'.$studentrecord.'</span></td>'."\n".
                   7841:                               &Apache::loncommon::end_data_table_row().
                   7842:                               &Apache::loncommon::end_data_table().'</p>');
                   7843:                 } else {
                   7844:                     $r->print('<br /><span class="LC_warning">'.
                   7845:                              &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 />'.
                   7846:                              &mt("As a consequence, this user's submission history records two tries.").
                   7847:                                  '</span><br />');
                   7848:                 }
                   7849:             }
                   7850:         }
1.543     raeburn  7851:         if (&Apache::loncommon::connection_aborted($r)) { last; }
1.140     albertel 7852:     } continue {
1.330     albertel 7853: 	&Apache::lonxml::clear_problem_counter();
1.552     raeburn  7854: 	&Apache::lonnet::delenv('scantron.');
1.82      albertel 7855:     }
1.140     albertel 7856:     &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
1.520     www      7857:     &Apache::lonnet::remove_lock($lock);
1.172     albertel 7858: #    my $lasttime = &Time::HiRes::time()-$start;
                   7859: #    $r->print("<p>took $lasttime</p>");
1.140     albertel 7860: 
1.200     albertel 7861:     $r->print("</form>");
1.324     albertel 7862:     $r->print(&show_grading_menu_form($symb));
1.157     albertel 7863:     return '';
1.75      albertel 7864: }
1.157     albertel 7865: 
1.557     raeburn  7866: sub graders_resources_pass {
                   7867:     my ($resources,$grader_partids_by_symb,$grader_randomlists_by_symb) = @_;
                   7868:     if ((ref($resources) eq 'ARRAY') && (ref($grader_partids_by_symb)) && 
                   7869:         (ref($grader_randomlists_by_symb) eq 'HASH')) {
                   7870:         foreach my $resource (@{$resources}) {
                   7871:             my $ressymb = $resource->symb();
                   7872:             my ($analysis,$parts) =
                   7873:                 &scantron_partids_tograde($resource,$env{'request.course.id'},
                   7874:                                           $env{'user.name'},$env{'user.domain'},1);
                   7875:             $grader_partids_by_symb->{$ressymb} = $parts;
                   7876:             if (ref($analysis) eq 'HASH') {
                   7877:                 if (ref($analysis->{'parts_withrandomlist'}) eq 'ARRAY') {
                   7878:                     $grader_randomlists_by_symb->{$ressymb} =
                   7879:                         $analysis->{'parts_withrandomlist'};
                   7880:                 }
                   7881:             }
                   7882:         }
                   7883:     }
                   7884:     return;
                   7885: }
                   7886: 
1.542     raeburn  7887: sub grade_student_bubbles {
1.554     raeburn  7888:     my ($r,$uname,$udom,$scan_record,$scancode,$resources,$parts) = @_;
                   7889:     if (ref($resources) eq 'ARRAY') {
                   7890:         my $count = 0;
                   7891:         foreach my $resource (@{$resources}) {
                   7892:             my $ressymb = $resource->symb();
                   7893:             my %form = ('submitted'      => 'scantron',
                   7894:                         'grade_target'   => 'grade',
                   7895:                         'grade_username' => $uname,
                   7896:                         'grade_domain'   => $udom,
                   7897:                         'grade_courseid' => $env{'request.course.id'},
                   7898:                         'grade_symb'     => $ressymb,
                   7899:                         'CODE'           => $scancode
                   7900:                        );
                   7901:             if (ref($parts) eq 'HASH') {
                   7902:                 if (ref($parts->{$ressymb}) eq 'ARRAY') {
                   7903:                     foreach my $part (@{$parts->{$ressymb}}) {
                   7904:                         $form{'scantron_questnum_start.'.$part} =
                   7905:                             1+$env{'form.scantron.first_bubble_line.'.$count};
                   7906:                         $count++;
                   7907:                     }
                   7908:                 }
                   7909:             }
                   7910:             my $result=&ssi_with_retries($resource->src(),$ssi_retries,%form);
                   7911:             return 'ssi_error' if ($ssi_error);
                   7912:             last if (&Apache::loncommon::connection_aborted($r));
                   7913:         }
1.542     raeburn  7914:     }
                   7915:     return;
                   7916: }
                   7917: 
1.157     albertel 7918: sub scantron_upload_scantron_data {
                   7919:     my ($r)=@_;
1.565     raeburn  7920:     my $dom = $env{'request.role.domain'};
                   7921:     my $domdesc = &Apache::lonnet::domain($dom,'description');
                   7922:     $r->print(&Apache::loncommon::coursebrowser_javascript($dom));
1.157     albertel 7923:     my $select_link=&Apache::loncommon::selectcourse_link('rules','courseid',
1.181     albertel 7924: 							  'domainid',
1.565     raeburn  7925: 							  'coursename',$dom);
                   7926:     my $syllabuslink = '<a href="javascript:ToSyllabus();">'.&mt('Syllabus').'</a>'.
                   7927:                        ('&nbsp'x2).&mt('(shows course personnel)'); 
1.324     albertel 7928:     my $default_form_data=&defaultFormData(&get_symb($r,1));
1.579     raeburn  7929:     my $nofile_alert = &mt('Please use the browse button to select a file from your local directory.');
                   7930:     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 7931:     $r->print(&Apache::lonhtmlcommon::scripttag('
1.157     albertel 7932:     function checkUpload(formname) {
                   7933: 	if (formname.upfile.value == "") {
1.579     raeburn  7934: 	    alert("'.$nofile_alert.'");
1.157     albertel 7935: 	    return false;
                   7936: 	}
1.565     raeburn  7937:         if (formname.courseid.value == "") {
1.579     raeburn  7938:             alert("'.$nocourseid_alert.'");
1.565     raeburn  7939:             return false;
                   7940:         }
1.157     albertel 7941: 	formname.submit();
                   7942:     }
1.565     raeburn  7943: 
                   7944:     function ToSyllabus() {
                   7945:         var cdom = '."'$dom'".';
                   7946:         var cnum = document.rules.courseid.value;
                   7947:         if (cdom == "" || cdom == null) {
                   7948:             return;
                   7949:         }
                   7950:         if (cnum == "" || cnum == null) {
                   7951:            return;
                   7952:         }
                   7953:         syllwin=window.open("/public/"+cdom+"/"+cnum+"/syllabus","LONCAPASyllabus",
                   7954:                             "height=350,width=350,scrollbars=yes,menubar=no");
                   7955:         return;
                   7956:     }
                   7957: 
1.597     wenzelju 7958: '));
                   7959:     $r->print('
1.566     raeburn  7960: <h3>'.&mt('Send scanned bubblesheet data to a course').'</h3>
                   7961: 
1.492     albertel 7962: <form enctype="multipart/form-data" action="/adm/grades" name="rules" method="post">
1.565     raeburn  7963: '.$default_form_data.
                   7964:   &Apache::lonhtmlcommon::start_pick_box().
                   7965:   &Apache::lonhtmlcommon::row_title(&mt('Course ID')).
                   7966:   '<input name="courseid" type="text" size="30" />'.$select_link.
                   7967:   &Apache::lonhtmlcommon::row_closure().
                   7968:   &Apache::lonhtmlcommon::row_title(&mt('Course Name')).
                   7969:   '<input name="coursename" type="text" size="30" />'.$syllabuslink.
                   7970:   &Apache::lonhtmlcommon::row_closure().
                   7971:   &Apache::lonhtmlcommon::row_title(&mt('Domain')).
                   7972:   '<input name="domainid" type="hidden" />'.$domdesc.
                   7973:   &Apache::lonhtmlcommon::row_closure().
                   7974:   &Apache::lonhtmlcommon::row_title(&mt('File to upload')).
                   7975:   '<input type="file" name="upfile" size="50" />'.
                   7976:   &Apache::lonhtmlcommon::row_closure(1).
                   7977:   &Apache::lonhtmlcommon::end_pick_box().'<br />
                   7978: 
1.492     albertel 7979: <input name="command" value="scantronupload_save" type="hidden" />
1.589     bisitz   7980: <input type="button" onclick="javascript:checkUpload(this.form);" value="'.&mt('Upload Bubblesheet Data').'" />
1.157     albertel 7981: </form>
1.492     albertel 7982: ');
1.157     albertel 7983:     return '';
                   7984: }
                   7985: 
1.423     albertel 7986: 
1.157     albertel 7987: sub scantron_upload_scantron_data_save {
                   7988:     my($r)=@_;
1.324     albertel 7989:     my ($symb)=&get_symb($r,1);
1.182     albertel 7990:     my $doanotherupload=
                   7991: 	'<br /><form action="/adm/grades" method="post">'."\n".
                   7992: 	'<input type="hidden" name="command" value="scantronupload" />'."\n".
1.492     albertel 7993: 	'<input type="submit" name="submit" value="'.&mt('Do Another Upload').'" />'."\n".
1.182     albertel 7994: 	'</form>'."\n";
1.257     albertel 7995:     if (!&Apache::lonnet::allowed('usc',$env{'form.domainid'}) &&
1.162     albertel 7996: 	!&Apache::lonnet::allowed('usc',
1.257     albertel 7997: 			    $env{'form.domainid'}.'_'.$env{'form.courseid'})) {
1.575     www      7998: 	$r->print(&mt("You are not allowed to upload bubblesheet data to the requested course.")."<br />");
1.182     albertel 7999: 	if ($symb) {
1.324     albertel 8000: 	    $r->print(&show_grading_menu_form($symb));
1.182     albertel 8001: 	} else {
                   8002: 	    $r->print($doanotherupload);
                   8003: 	}
1.162     albertel 8004: 	return '';
                   8005:     }
1.257     albertel 8006:     my %coursedata=&Apache::lonnet::coursedescription($env{'form.domainid'}.'_'.$env{'form.courseid'});
1.568     raeburn  8007:     my $uploadedfile;
1.567     raeburn  8008:     $r->print('<h3>'.&mt("Uploading file to [_1]",$coursedata{'description'}).'</h3>');
1.257     albertel 8009:     if (length($env{'form.upfile'}) < 2) {
1.568     raeburn  8010:         $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 8011:     } else {
1.568     raeburn  8012:         my $result = 
                   8013:             &Apache::lonnet::userfileupload('upfile','','scantron','','','',
                   8014:                                             $env{'form.courseid'},$env{'form.domainid'});
                   8015: 	if ($result =~ m{^/uploaded/}) {
1.567     raeburn  8016: 	    $r->print(&mt('[_1]Success:[_2] Successfully uploaded [_3] bytes of data into location: [_4]',
                   8017:                           '<span class="LC_success">','</span>',(length($env{'form.upfile'})-1),
                   8018: 			  '<span class="LC_filename">'.$result.'</span>'));
1.568     raeburn  8019:             ($uploadedfile) = ($result =~ m{/([^/]+)$});
1.567     raeburn  8020:             $r->print(&validate_uploaded_scantron_file($env{'form.domainid'},
1.568     raeburn  8021:                                                        $env{'form.courseid'},$uploadedfile));
1.210     albertel 8022: 	} else {
1.567     raeburn  8023: 	    $r->print(&mt('[_1]Error:[_2] An error ([_3]) occurred when attempting to upload the file, [_4]',
                   8024:                           '<span class="LC_error">','</span>',$result,
1.568     raeburn  8025: 			  '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>'));
1.183     albertel 8026: 	}
                   8027:     }
1.174     albertel 8028:     if ($symb) {
1.209     ng       8029: 	$r->print(&scantron_selectphase($r,$uploadedfile));
1.174     albertel 8030:     } else {
1.182     albertel 8031: 	$r->print($doanotherupload);
1.174     albertel 8032:     }
1.157     albertel 8033:     return '';
                   8034: }
                   8035: 
1.567     raeburn  8036: sub validate_uploaded_scantron_file {
                   8037:     my ($cdom,$cname,$fname) = @_;
                   8038:     my $scanlines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.$fname);
                   8039:     my @lines;
                   8040:     if ($scanlines ne '-1') {
                   8041:         @lines=split("\n",$scanlines,-1);
                   8042:     }
                   8043:     my $output;
                   8044:     if (@lines) {
                   8045:         my (%counts,$max_match_format);
                   8046:         my ($max_match_count,$max_match_pct) = (0,0);
                   8047:         my $classlist = &Apache::loncoursedata::get_classlist($cdom,$cname);
                   8048:         my %idmap = &username_to_idmap($classlist);
                   8049:         foreach my $key (keys(%idmap)) {
                   8050:             my $lckey = lc($key);
                   8051:             $idmap{$lckey} = $idmap{$key};
                   8052:         }
                   8053:         my %unique_formats;
                   8054:         my @formatlines = &get_scantronformat_file();
                   8055:         foreach my $line (@formatlines) {
                   8056:             chomp($line);
                   8057:             my @config = split(/:/,$line);
                   8058:             my $idstart = $config[5];
                   8059:             my $idlength = $config[6];
                   8060:             if (($idstart ne '') && ($idlength > 0)) {
                   8061:                 if (ref($unique_formats{$idstart.':'.$idlength}) eq 'ARRAY') {
                   8062:                     push(@{$unique_formats{$idstart.':'.$idlength}},$config[0].':'.$config[1]); 
                   8063:                 } else {
                   8064:                     $unique_formats{$idstart.':'.$idlength} = [$config[0].':'.$config[1]];
                   8065:                 }
                   8066:             }
                   8067:         }
                   8068:         foreach my $key (keys(%unique_formats)) {
                   8069:             my ($idstart,$idlength) = split(':',$key);
                   8070:             %{$counts{$key}} = (
                   8071:                                'found'   => 0,
                   8072:                                'total'   => 0,
                   8073:                               );
                   8074:             foreach my $line (@lines) {
                   8075:                 next if ($line =~ /^#/);
                   8076:                 next if ($line =~ /^[\s\cz]*$/);
                   8077:                 my $id = substr($line,$idstart-1,$idlength);
                   8078:                 $id = lc($id);
                   8079:                 if (exists($idmap{$id})) {
                   8080:                     $counts{$key}{'found'} ++;
                   8081:                 }
                   8082:                 $counts{$key}{'total'} ++;
                   8083:             }
                   8084:             if ($counts{$key}{'total'}) {
                   8085:                 my $percent_match = (100*$counts{$key}{'found'})/($counts{$key}{'total'});
                   8086:                 if (($max_match_format eq '') || ($percent_match > $max_match_pct)) {
                   8087:                     $max_match_pct = $percent_match;
                   8088:                     $max_match_format = $key;
                   8089:                     $max_match_count = $counts{$key}{'total'};
                   8090:                 }
                   8091:             }
                   8092:         }
                   8093:         if (ref($unique_formats{$max_match_format}) eq 'ARRAY') {
                   8094:             my $format_descs;
                   8095:             my $numwithformat = @{$unique_formats{$max_match_format}};
                   8096:             for (my $i=0; $i<$numwithformat; $i++) {
                   8097:                 my ($name,$desc) = split(':',$unique_formats{$max_match_format}[$i]);
                   8098:                 if ($i<$numwithformat-2) {
                   8099:                     $format_descs .= '"<i>'.$desc.'</i>", ';
                   8100:                 } elsif ($i==$numwithformat-2) {
                   8101:                     $format_descs .= '"<i>'.$desc.'</i>" '.&mt('and').' ';
                   8102:                 } elsif ($i==$numwithformat-1) {
                   8103:                     $format_descs .= '"<i>'.$desc.'</i>"';
                   8104:                 }
                   8105:             }
                   8106:             my $showpct = sprintf("%.0f",$max_match_pct).'%';
                   8107:             $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).
                   8108:                        '<br />'.&mt('A low percentage of matches results from one of the following:').'<ul>'.
                   8109:                        '<li>'.&mt('The file was uploaded to the wrong course').'</li>'.
                   8110:                        '<li>'.&mt('The data are not in the format expected for the domain: [_1]',
                   8111:                                   '<i>'.$cdom.'</i>').'</li>'.
                   8112:                        '<li>'.&mt('Students did not bubble their IDs, or mis-bubbled them').'</li>'.
                   8113:                        '<li>'.&mt('The course roster is not up to date').'</li>'.
                   8114:                        '</ul>';
                   8115:         }
                   8116:     } else {
                   8117:         $output = '<span class="LC_warning">'.&mt('Uploaded file contained no data').'</span>';
                   8118:     }
                   8119:     return $output;
                   8120: }
                   8121: 
1.202     albertel 8122: sub valid_file {
                   8123:     my ($requested_file)=@_;
                   8124:     foreach my $filename (sort(&scantron_filenames())) {
                   8125: 	if ($requested_file eq $filename) { return 1; }
                   8126:     }
                   8127:     return 0;
                   8128: }
                   8129: 
                   8130: sub scantron_download_scantron_data {
                   8131:     my ($r)=@_;
1.324     albertel 8132:     my $default_form_data=&defaultFormData(&get_symb($r,1));
1.257     albertel 8133:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   8134:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   8135:     my $file=$env{'form.scantron_selectfile'};
1.202     albertel 8136:     if (! &valid_file($file)) {
1.492     albertel 8137: 	$r->print('
1.202     albertel 8138: 	<p>
1.492     albertel 8139: 	    '.&mt('The requested file name was invalid.').'
1.202     albertel 8140:         </p>
1.492     albertel 8141: ');
1.324     albertel 8142: 	$r->print(&show_grading_menu_form(&get_symb($r,1)));
1.202     albertel 8143: 	return;
                   8144:     }
                   8145:     my $orig='/uploaded/'.$cdom.'/'.$cname.'/scantron_orig_'.$file;
                   8146:     my $corrected='/uploaded/'.$cdom.'/'.$cname.'/scantron_corrected_'.$file;
                   8147:     my $skipped='/uploaded/'.$cdom.'/'.$cname.'/scantron_skipped_'.$file;
                   8148:     &Apache::lonnet::allowuploaded('/adm/grades',$orig);
                   8149:     &Apache::lonnet::allowuploaded('/adm/grades',$corrected);
                   8150:     &Apache::lonnet::allowuploaded('/adm/grades',$skipped);
1.492     albertel 8151:     $r->print('
1.202     albertel 8152:     <p>
1.492     albertel 8153: 	'.&mt('[_1]Original[_2] file as uploaded by the scantron office.',
                   8154: 	      '<a href="'.$orig.'">','</a>').'
1.202     albertel 8155:     </p>
                   8156:     <p>
1.492     albertel 8157: 	'.&mt('[_1]Corrections[_2], a file of corrected records that were used in grading.',
                   8158: 	      '<a href="'.$corrected.'">','</a>').'
1.202     albertel 8159:     </p>
                   8160:     <p>
1.492     albertel 8161: 	'.&mt('[_1]Skipped[_2], a file of records that were skipped.',
                   8162: 	      '<a href="'.$skipped.'">','</a>').'
1.202     albertel 8163:     </p>
1.492     albertel 8164: ');
1.324     albertel 8165:     $r->print(&show_grading_menu_form(&get_symb($r,1)));
1.202     albertel 8166:     return '';
                   8167: }
1.157     albertel 8168: 
1.523     raeburn  8169: sub checkscantron_results {
                   8170:     my ($r) = @_;
                   8171:     my ($symb)=&get_symb($r);
                   8172:     if (!$symb) {return '';}
                   8173:     my $grading_menu_button=&show_grading_menu_form($symb);
                   8174:     my $cid = $env{'request.course.id'};
1.542     raeburn  8175:     my %lettdig = &letter_to_digits();
1.523     raeburn  8176:     my $numletts = scalar(keys(%lettdig));
                   8177:     my $cnum = $env{'course.'.$cid.'.num'};
                   8178:     my $cdom = $env{'course.'.$cid.'.domain'};
                   8179:     my (undef, undef, $sequence) = &Apache::lonnet::decode_symb($env{'form.selectpage'});
                   8180:     my %record;
                   8181:     my %scantron_config =
                   8182:         &Apache::grades::get_scantron_config($env{'form.scantron_format'});
                   8183:     my ($scanlines,$scan_data)=&Apache::grades::scantron_getfile();
                   8184:     my $classlist=&Apache::loncoursedata::get_classlist();
                   8185:     my %idmap=&Apache::grades::username_to_idmap($classlist);
                   8186:     my $navmap=Apache::lonnavmaps::navmap->new();
1.582     raeburn  8187:     unless (ref($navmap)) {
                   8188:         $r->print(&navmap_errormsg());
                   8189:         return '';
                   8190:     }
1.523     raeburn  8191:     my $map=$navmap->getResourceByUrl($sequence);
1.557     raeburn  8192:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
                   8193:     my (%grader_partids_by_symb,%grader_randomlists_by_symb);
                   8194:     &graders_resources_pass(\@resources,\%grader_partids_by_symb,                             \%grader_randomlists_by_symb);
                   8195: 
1.554     raeburn  8196:     my ($uname,$udom);
1.523     raeburn  8197:     my (%scandata,%lastname,%bylast);
                   8198:     $r->print('
                   8199: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="checkscantron">'."\n");
                   8200: 
                   8201:     my @delayqueue;
                   8202:     my %completedstudents;
                   8203: 
                   8204:     my $count=&Apache::grades::get_todo_count($scanlines,$scan_data);
1.581     www      8205:     my %prog_state=&Apache::lonhtmlcommon::Create_PrgWin($r,'Bubblesheet/Submissions Comparison Status',
                   8206:                                     'Progress of Bubblesheet Data/Submission Records Comparison',$count,
1.523     raeburn  8207:                                     'inline',undef,'checkscantron');
1.546     raeburn  8208:     my ($username,$domain,$started);
1.582     raeburn  8209:     my $nav_error;
                   8210:     &scantron_get_maxbubble(\$nav_error); # Need the bubble lines array to parse.
                   8211:     if ($nav_error) {
                   8212:         $r->print(&navmap_errormsg());
                   8213:         return '';
                   8214:     }
1.523     raeburn  8215: 
                   8216:     &Apache::lonhtmlcommon::Update_PrgWin($r,\%prog_state,
                   8217:                                           'Processing first student');
                   8218:     my $start=&Time::HiRes::time();
                   8219:     my $i=-1;
                   8220: 
                   8221:     while ($i<$scanlines->{'count'}) {
                   8222:         ($username,$domain,$uname)=('','','');
                   8223:         $i++;
                   8224:         my $line=&Apache::grades::scantron_get_line($scanlines,$scan_data,$i);
                   8225:         if ($line=~/^[\s\cz]*$/) { next; }
                   8226:         if ($started) {
                   8227:             &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state,
                   8228:                                                      'last student');
                   8229:         }
                   8230:         $started=1;
                   8231:         my $scan_record=
                   8232:             &Apache::grades::scantron_parse_scanline($line,$i,\%scantron_config,
                   8233:                                                      $scan_data);
                   8234:         unless ($uname=&Apache::grades::scantron_find_student($scan_record,$scan_data,
                   8235:                                                               \%idmap,$i)) {
                   8236:             &Apache::grades::scantron_add_delay(\@delayqueue,$line,
                   8237:                                 'Unable to find a student that matches',1);
                   8238:             next;
                   8239:         }
                   8240:         if (exists $completedstudents{$uname}) {
                   8241:             &Apache::grades::scantron_add_delay(\@delayqueue,$line,
                   8242:                                 'Student '.$uname.' has multiple sheets',2);
                   8243:             next;
                   8244:         }
                   8245:         my $pid = $scan_record->{'scantron.ID'};
                   8246:         $lastname{$pid} = $scan_record->{'scantron.LastName'};
                   8247:         push(@{$bylast{$lastname{$pid}}},$pid);
                   8248:         my $lastpos = $env{'form.scantron_maxbubble'}*$scantron_config{'Qlength'};
                   8249:         $scandata{$pid} = substr($line,$scantron_config{'Qstart'}-1,$lastpos);
                   8250:         chomp($scandata{$pid});
                   8251:         $scandata{$pid} =~ s/\r$//;
                   8252:         ($username,$domain)=split(/:/,$uname);
                   8253:         my $counter = -1;
                   8254:         foreach my $resource (@resources) {
1.557     raeburn  8255:             my $parts;
1.554     raeburn  8256:             my $ressymb = $resource->symb();
1.557     raeburn  8257:             if ((exists($grader_randomlists_by_symb{$ressymb})) ||
                   8258:                 (ref($grader_partids_by_symb{$ressymb}) ne 'ARRAY')) {
                   8259:                 (my $analysis,$parts) =
                   8260:                     &scantron_partids_tograde($resource,$env{'request.course.id'},$username,$domain);
                   8261:             } else {
                   8262:                 $parts = $grader_partids_by_symb{$ressymb};
                   8263:             }
1.542     raeburn  8264:             ($counter,my $recording) =
                   8265:                 &verify_scantron_grading($resource,$domain,$username,$cid,$counter,
1.554     raeburn  8266:                                          $scandata{$pid},$parts,
1.542     raeburn  8267:                                          \%scantron_config,\%lettdig,$numletts);
                   8268:             $record{$pid} .= $recording;
1.523     raeburn  8269:         }
                   8270:     }
                   8271:     &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
                   8272:     $r->print('<br />');
                   8273:     my ($okstudents,$badstudents,$numstudents,$passed,$failed);
                   8274:     $passed = 0;
                   8275:     $failed = 0;
                   8276:     $numstudents = 0;
                   8277:     foreach my $last (sort(keys(%bylast))) {
                   8278:         if (ref($bylast{$last}) eq 'ARRAY') {
                   8279:             foreach my $pid (sort(@{$bylast{$last}})) {
                   8280:                 my $showscandata = $scandata{$pid};
                   8281:                 my $showrecord = $record{$pid};
                   8282:                 $showscandata =~ s/\s/&nbsp;/g;
                   8283:                 $showrecord =~ s/\s/&nbsp;/g;
                   8284:                 if ($scandata{$pid} eq $record{$pid}) {
                   8285:                     my $css_class = ($passed % 2)?'LC_odd_row':'LC_even_row';
                   8286:                     $okstudents .= '<tr class="'.$css_class.'">'.
1.581     www      8287: '<td>'.&mt('Bubblesheet').'</td><td>'.$showscandata.'</td><td rowspan="2">'.$last.'</td><td rowspan="2">'.$pid.'</td>'."\n".
1.523     raeburn  8288: '</tr>'."\n".
                   8289: '<tr class="'.$css_class.'">'."\n".
                   8290: '<td>Submissions</td><td>'.$showrecord.'</td></tr>'."\n";
                   8291:                     $passed ++;
                   8292:                 } else {
                   8293:                     my $css_class = ($failed % 2)?'LC_odd_row':'LC_even_row';
1.581     www      8294:                     $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  8295: '</tr>'."\n".
                   8296: '<tr class="'.$css_class.'">'."\n".
                   8297: '<td>Submissions</td><td><span class="LC_nobreak">'.$record{$pid}.'</span></td>'."\n".
                   8298: '</tr>'."\n";
                   8299:                     $failed ++;
                   8300:                 }
                   8301:                 $numstudents ++;
                   8302:             }
                   8303:         }
                   8304:     }
1.572     www      8305:     $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  8306:     $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>');
                   8307:     if ($passed) {
1.572     www      8308:         $r->print(&mt('Students with exact correspondence between bubblesheet data and submissions are as follows:').'<br /><br />');
1.523     raeburn  8309:         $r->print(&Apache::loncommon::start_data_table()."\n".
                   8310:                  &Apache::loncommon::start_data_table_header_row()."\n".
                   8311:                  '<th>'.&mt('Source').'</th><th>'.&mt('Bubble records').'</th><th>'.&mt('Name').'</th><th>'.&mt('ID').'</th>'.
                   8312:                  &Apache::loncommon::end_data_table_header_row()."\n".
                   8313:                  $okstudents."\n".
                   8314:                  &Apache::loncommon::end_data_table().'<br />');
                   8315:     }
                   8316:     if ($failed) {
1.572     www      8317:         $r->print(&mt('Students with differences between bubblesheet data and submissions are as follows:').'<br /><br />');
1.523     raeburn  8318:         $r->print(&Apache::loncommon::start_data_table()."\n".
                   8319:                  &Apache::loncommon::start_data_table_header_row()."\n".
                   8320:                  '<th>'.&mt('Source').'</th><th>'.&mt('Bubble records').'</th><th>'.&mt('Name').'</th><th>'.&mt('ID').'</th>'.
                   8321:                  &Apache::loncommon::end_data_table_header_row()."\n".
                   8322:                  $badstudents."\n".
                   8323:                  &Apache::loncommon::end_data_table()).'<br />'.
1.572     www      8324:                  &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  8325:     }
                   8326:     $r->print('</form><br />'.$grading_menu_button);
                   8327:     return;
                   8328: }
                   8329: 
1.542     raeburn  8330: sub verify_scantron_grading {
1.554     raeburn  8331:     my ($resource,$domain,$username,$cid,$counter,$scandata,$partids,
1.542     raeburn  8332:         $scantron_config,$lettdig,$numletts) = @_;
                   8333:     my ($record,%expected,%startpos);
                   8334:     return ($counter,$record) if (!ref($resource));
                   8335:     return ($counter,$record) if (!$resource->is_problem());
                   8336:     my $symb = $resource->symb();
1.554     raeburn  8337:     return ($counter,$record) if (ref($partids) ne 'ARRAY');
                   8338:     foreach my $part_id (@{$partids}) {
1.542     raeburn  8339:         $counter ++;
                   8340:         $expected{$part_id} = 0;
                   8341:         if ($env{"form.scantron.sub_bubblelines.$counter"}) {
                   8342:             my @sub_lines = split(/,/,$env{"form.scantron.sub_bubblelines.$counter"});
                   8343:             foreach my $item (@sub_lines) {
                   8344:                 $expected{$part_id} += $item;
                   8345:             }
                   8346:         } else {
                   8347:             $expected{$part_id} = $env{"form.scantron.bubblelines.$counter"};
                   8348:         }
                   8349:         $startpos{$part_id} = $env{"form.scantron.first_bubble_line.$counter"};
                   8350:     }
                   8351:     if ($symb) {
                   8352:         my %recorded;
                   8353:         my (%returnhash) = &Apache::lonnet::restore($symb,$cid,$domain,$username);
                   8354:         if ($returnhash{'version'}) {
                   8355:             my %lasthash=();
                   8356:             my $version;
                   8357:             for ($version=1;$version<=$returnhash{'version'};$version++) {
                   8358:                 foreach my $key (sort(split(/\:/,$returnhash{$version.':keys'}))) {
                   8359:                     $lasthash{$key}=$returnhash{$version.':'.$key};
                   8360:                 }
                   8361:             }
                   8362:             foreach my $key (keys(%lasthash)) {
                   8363:                 if ($key =~ /\.scantron$/) {
                   8364:                     my $value = &unescape($lasthash{$key});
                   8365:                     my ($part_id) = ($key =~ /^resource\.(.+)\.scantron$/);
                   8366:                     if ($value eq '') {
                   8367:                         for (my $i=0; $i<$expected{$part_id}; $i++) {
                   8368:                             for (my $j=0; $j<$scantron_config->{'length'}; $j++) {
                   8369:                                 $recorded{$part_id} .= $scantron_config->{'Qoff'};
                   8370:                             }
                   8371:                         }
                   8372:                     } else {
                   8373:                         my @tocheck;
                   8374:                         my @items = split(//,$value);
                   8375:                         if (($scantron_config->{'Qon'} eq 'letter') ||
                   8376:                             ($scantron_config->{'Qon'} eq 'number')) {
                   8377:                             if (@items < $expected{$part_id}) {
                   8378:                                 my $fragment = substr($scandata,$startpos{$part_id},$expected{$part_id});
                   8379:                                 my @singles = split(//,$fragment);
                   8380:                                 foreach my $pos (@singles) {
                   8381:                                     if ($pos eq ' ') {
                   8382:                                         push(@tocheck,$pos);
                   8383:                                     } else {
                   8384:                                         my $next = shift(@items);
                   8385:                                         push(@tocheck,$next);
                   8386:                                     }
                   8387:                                 }
                   8388:                             } else {
                   8389:                                 @tocheck = @items;
                   8390:                             }
                   8391:                             foreach my $letter (@tocheck) {
                   8392:                                 if ($scantron_config->{'Qon'} eq 'letter') {
                   8393:                                     if ($letter !~ /^[A-J]$/) {
                   8394:                                         $letter = $scantron_config->{'Qoff'};
                   8395:                                     }
                   8396:                                     $recorded{$part_id} .= $letter;
                   8397:                                 } elsif ($scantron_config->{'Qon'} eq 'number') {
                   8398:                                     my $digit;
                   8399:                                     if ($letter !~ /^[A-J]$/) {
                   8400:                                         $digit = $scantron_config->{'Qoff'};
                   8401:                                     } else {
                   8402:                                         $digit = $lettdig->{$letter};
                   8403:                                     }
                   8404:                                     $recorded{$part_id} .= $digit;
                   8405:                                 }
                   8406:                             }
                   8407:                         } else {
                   8408:                             @tocheck = @items;
                   8409:                             for (my $i=0; $i<$expected{$part_id}; $i++) {
                   8410:                                 my $curr_sub = shift(@tocheck);
                   8411:                                 my $digit;
                   8412:                                 if ($curr_sub =~ /^[A-J]$/) {
                   8413:                                     $digit = $lettdig->{$curr_sub}-1;
                   8414:                                 }
                   8415:                                 if ($curr_sub eq 'J') {
                   8416:                                     $digit += scalar($numletts);
                   8417:                                 }
                   8418:                                 for (my $j=0; $j<$scantron_config->{'Qlength'}; $j++) {
                   8419:                                     if ($j == $digit) {
                   8420:                                         $recorded{$part_id} .= $scantron_config->{'Qon'};
                   8421:                                     } else {
                   8422:                                         $recorded{$part_id} .= $scantron_config->{'Qoff'};
                   8423:                                     }
                   8424:                                 }
                   8425:                             }
                   8426:                         }
                   8427:                     }
                   8428:                 }
                   8429:             }
                   8430:         }
1.554     raeburn  8431:         foreach my $part_id (@{$partids}) {
1.542     raeburn  8432:             if ($recorded{$part_id} eq '') {
                   8433:                 for (my $i=0; $i<$expected{$part_id}; $i++) {
                   8434:                     for (my $j=0; $j<$scantron_config->{'Qlength'}; $j++) {
                   8435:                         $recorded{$part_id} .= $scantron_config->{'Qoff'};
                   8436:                     }
                   8437:                 }
                   8438:             }
                   8439:             $record .= $recorded{$part_id};
                   8440:         }
                   8441:     }
                   8442:     return ($counter,$record);
                   8443: }
                   8444: 
                   8445: sub letter_to_digits { 
                   8446:     my %lettdig = (
                   8447:                     A => 1,
                   8448:                     B => 2,
                   8449:                     C => 3,
                   8450:                     D => 4,
                   8451:                     E => 5,
                   8452:                     F => 6,
                   8453:                     G => 7,
                   8454:                     H => 8,
                   8455:                     I => 9,
                   8456:                     J => 0,
                   8457:                   );
                   8458:     return %lettdig;
                   8459: }
                   8460: 
1.423     albertel 8461: 
1.75      albertel 8462: #-------- end of section for handling grading scantron forms -------
                   8463: #
                   8464: #-------------------------------------------------------------------
                   8465: 
1.72      ng       8466: #-------------------------- Menu interface -------------------------
                   8467: #
                   8468: #--- Show a Grading Menu button - Calls the next routine ---
                   8469: sub show_grading_menu_form {
1.324     albertel 8470:     my ($symb)=@_;
1.125     ng       8471:     my $result.='<br /><form action="/adm/grades" method="post">'."\n".
1.418     albertel 8472: 	'<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.257     albertel 8473: 	'<input type="hidden" name="saveState"  value="'.$env{'form.saveState'}.'" />'."\n".
1.72      ng       8474: 	'<input type="hidden" name="command" value="gradingmenu" />'."\n".
1.478     albertel 8475: 	'<input type="submit" name="submit" value="'.&mt('Grading Menu').'" />'."\n".
1.72      ng       8476: 	'</form>'."\n";
                   8477:     return $result;
                   8478: }
                   8479: 
1.443     banghart 8480: sub grading_menu {
                   8481:     my ($request) = @_;
                   8482:     my ($symb)=&get_symb($request);
                   8483:     if (!$symb) {return '';}
                   8484:     my $probTitle = &Apache::lonnet::gettitle($symb);
                   8485: 
                   8486:     my %fields = ('symb'=>&Apache::lonenc::check_encrypt($symb),
                   8487:                   'probTitle'=>$probTitle,
1.598     www      8488:                   'command'=>'individual',
1.443     banghart 8489:                   'gradingMenu'=>1,
                   8490:                   'showgrading'=>"yes");
1.538     schulted 8491:     
1.598     www      8492:     my $url1a = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   8493: 
                   8494:     $fields{'command'}='ungraded';
                   8495:     my $url1b=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   8496: 
                   8497:     $fields{'command'}='table';
                   8498:     my $url1c=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   8499: 
                   8500:     $fields{'command'}='all_for_one';
                   8501:     my $url1d=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   8502: 
1.443     banghart 8503:     $fields{'command'} = 'csvform';
1.538     schulted 8504:     my $url2 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   8505:     
1.443     banghart 8506:     $fields{'command'} = 'processclicker';
1.538     schulted 8507:     my $url3 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   8508:     
1.443     banghart 8509:     $fields{'command'} = 'scantron_selectphase';
1.538     schulted 8510:     my $url4 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
1.602     www      8511: 
                   8512:     $fields{'command'} = 'initialverifyreceipt';
                   8513:     my $url5 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
1.538     schulted 8514:     
1.598     www      8515:     my @menu = ({	categorytitle=>'Hand Grading',
1.538     schulted 8516:             items =>[
1.598     www      8517:                         {	linktext => 'Select individual students to grade',
                   8518:                     		url => $url1a,
1.538     schulted 8519:                     		permission => 'F',
                   8520:                     		icon => 'edit-find-replace.png',
1.598     www      8521:                     		linktitle => 'Grade current resource for a selection of students.'
                   8522:                         }, 
                   8523:                         {       linktext => 'Grade ungraded submissions.',
                   8524:                                 url => $url1b,
                   8525:                                 permission => 'F',
                   8526:                                 icon => 'edit-find-replace.png',
                   8527:                                 linktitle => 'Grade all submissions that have not been graded yet.'
1.538     schulted 8528:                         },
1.598     www      8529: 
                   8530:                         {       linktext => 'Grading table',
                   8531:                                 url => $url1c,
                   8532:                                 permission => 'F',
                   8533:                                 icon => 'edit-find-replace.png',
                   8534:                                 linktitle => 'Grade current resource for all students.'
                   8535:                         },
1.600     www      8536:                         {       linktext => 'Grade complete page/sequence/folder for one student',
1.598     www      8537:                                 url => $url1d,
                   8538:                                 permission => 'F',
                   8539:                                 icon => 'edit-find-replace.png',
                   8540:                                 linktitle => 'Grade all resources in current page/sequence/folder for one student.'
                   8541:                         }]},
                   8542:                          { categorytitle=>'Automated Grading',
                   8543:                items =>[
                   8544: 
1.538     schulted 8545:                 	    {	linktext => 'Upload Scores',
                   8546:                     		url => $url2,
                   8547:                     		permission => 'F',
                   8548:                     		icon => 'uploadscores.png',
                   8549:                     		linktitle => 'Specify a file containing the class scores for current resource.'
                   8550:                 	    },
                   8551:                 	    {	linktext => 'Process Clicker',
                   8552:                     		url => $url3,
                   8553:                     		permission => 'F',
                   8554:                     		icon => 'addClickerInfoFile.png',
                   8555:                     		linktitle => 'Specify a file containing the clicker information for this resource.'
                   8556:                 	    },
1.587     raeburn  8557:                 	    {	linktext => 'Grade/Manage/Review Bubblesheets',
1.538     schulted 8558:                     		url => $url4,
                   8559:                     		permission => 'F',
                   8560:                     		icon => 'stat.png',
                   8561:                     		linktitle => 'Grade scantron exams, upload/download scantron data files, and review previously graded scantron exams.'
1.602     www      8562:                 	    },
                   8563:                             {   linktext => 'Verify Receipt No.',
                   8564:                                 url => $url5,
                   8565:                                 permission => 'F',
                   8566:                                 icon => 'edit-find-replace.png',
                   8567:                                 linktitle => 'Verify a system-generated receipt number for correct problem solution.'
                   8568:                             }
                   8569: 
1.538     schulted 8570:                     ]
                   8571:             });
                   8572: 
1.443     banghart 8573:     # Create the menu
                   8574:     my $Str;
1.445     banghart 8575:     $Str .= '<form method="post" action="" name="gradingMenu">';
                   8576:     $Str .= '<input type="hidden" name="command" value="" />'.
                   8577:     	'<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.476     albertel 8578: 	'<input type="hidden" name="probTitle"   value="'.$probTitle.'" />'."\n".
1.445     banghart 8579: 	'<input type="hidden" name="gradingMenu" value="1" />'."\n".
                   8580: 	'<input type="hidden" name="showgrading" value="yes" />'."\n";
                   8581: 
1.602     www      8582:     $Str .= &Apache::lonhtmlcommon::generate_menu(@menu);
1.443     banghart 8583:     return $Str;    
                   8584: }
                   8585: 
1.598     www      8586: 
                   8587: sub ungraded {
                   8588:     my ($request)=@_;
                   8589:     &submit_options($request);
                   8590: }
                   8591: 
1.599     www      8592: sub submit_options_sequence {
                   8593:     my ($request) = @_;
                   8594:     my ($symb)=&get_symb($request);
                   8595:     if (!$symb) {return '';}
1.600     www      8596:     &commonJSfunctions($request);
                   8597:     my $result;
1.599     www      8598: 
1.600     www      8599:     $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
                   8600:         '<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
                   8601:         '<input type="hidden" name="gradingMenu" value="1" />'."\n".
                   8602:         '<input type="hidden" name="showgrading" value="yes" />'."\n";
                   8603: 
                   8604:     $result.='
                   8605: <h2>
                   8606:   '.&mt('Grade complete page/sequence/folder for one student').'
1.601     www      8607: </h2>'.
                   8608:             &selectfield(0).
                   8609:             '<input type="hidden" name="command" value="pickStudentPage" />
1.600     www      8610:             <div>
                   8611:               <input type="submit" value="'.&mt('Next').' &rarr;" />
                   8612:             </div>
                   8613:         </div>
                   8614:   </form>';
                   8615:     $result .= &show_grading_menu_form($symb);
                   8616:     return $result;
                   8617: }
                   8618: 
                   8619: sub submit_options_table {
                   8620:     my ($request) = @_;
                   8621:     my ($symb)=&get_symb($request);
                   8622:     if (!$symb) {return '';}
1.599     www      8623:     &commonJSfunctions($request);
                   8624:     my $result;
                   8625: 
                   8626:     $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
                   8627:         '<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
                   8628:         '<input type="hidden" name="gradingMenu" value="1" />'."\n".
                   8629:         '<input type="hidden" name="showgrading" value="yes" />'."\n";
                   8630: 
                   8631:     $result.='
                   8632: <h2>
1.600     www      8633:   '.&mt('Grading table').'
1.601     www      8634: </h2>'.
                   8635:             &selectfield(0).
                   8636:             '<input type="hidden" name="command" value="viewgrades" />
1.599     www      8637:             <div>
                   8638:               <input type="submit" value="'.&mt('Next').' &rarr;" />
                   8639:             </div>
                   8640:         </div>
                   8641:   </form>';
                   8642:     $result .= &show_grading_menu_form($symb);
                   8643:     return $result;
                   8644: }
1.443     banghart 8645: 
1.600     www      8646: 
                   8647: 
1.443     banghart 8648: #--- Displays the submissions first page -------
                   8649: sub submit_options {
1.72      ng       8650:     my ($request) = @_;
1.324     albertel 8651:     my ($symb)=&get_symb($request);
1.72      ng       8652:     if (!$symb) {return '';}
1.76      ng       8653:     my $probTitle = &Apache::lonnet::gettitle($symb);
1.72      ng       8654: 
1.118     ng       8655:     &commonJSfunctions($request);
1.473     albertel 8656:     my $result;
1.533     bisitz   8657: 
1.72      ng       8658:     $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
1.418     albertel 8659: 	'<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.72      ng       8660: 	'<input type="hidden" name="probTitle"   value="'.$probTitle.'" />'."\n".
1.124     ng       8661: 	'<input type="hidden" name="gradingMenu" value="1" />'."\n".
1.72      ng       8662: 	'<input type="hidden" name="showgrading" value="yes" />'."\n";
                   8663: 
1.472     albertel 8664:     $result.='
1.533     bisitz   8665: <h2>
1.600     www      8666:   '.&mt('Select individual students to grade').'
1.601     www      8667: </h2>'.&selectfield(1).'
                   8668:                 <input type="hidden" name="command" value="submission" /> 
                   8669: 	      <input type="submit" value="'.&mt('Next').' &rarr;" />
                   8670:             </div>
                   8671:           </div>
                   8672: 
                   8673: 
                   8674:   </form>';
                   8675:     $result .= &show_grading_menu_form($symb);
                   8676:     return $result;
                   8677: }
1.533     bisitz   8678: 
1.601     www      8679: sub selectfield {
                   8680:    my ($full)=@_;
                   8681:    my $result='<div class="LC_columnSection">
1.537     harmsja  8682:   
1.533     bisitz   8683:     <fieldset>
                   8684:       <legend>
                   8685:        '.&mt('Sections').'
                   8686:       </legend>
1.601     www      8687:       '.&Apache::lonstatistics::SectionSelect('section','multiple',5).'
1.533     bisitz   8688:     </fieldset>
1.537     harmsja  8689:   
1.533     bisitz   8690:     <fieldset>
                   8691:       <legend>
                   8692:         '.&mt('Groups').'
                   8693:       </legend>
                   8694:       '.&Apache::lonstatistics::GroupSelect('group','multiple',5).'
                   8695:     </fieldset>
1.537     harmsja  8696:   
1.533     bisitz   8697:     <fieldset>
                   8698:       <legend>
                   8699:         '.&mt('Access Status').'
                   8700:       </legend>
1.601     www      8701:       '.&Apache::lonhtmlcommon::StatusOptions(undef,undef,5,undef,'mult').'
                   8702:     </fieldset>';
                   8703:     if ($full) {
                   8704:        $result.='
1.533     bisitz   8705:     <fieldset>
                   8706:       <legend>
                   8707:         '.&mt('Submission Status').'
1.601     www      8708:       </legend>'.
                   8709:        &Apache::loncommon::select_form('all','submitonly',
                   8710:           (&Apache::lonlocal::texthash(
                   8711:              'yes'       => 'with submissions',
                   8712:              'queued'    => 'in grading queue',
                   8713:              'graded'    => 'with ungraded submissions',
                   8714:              'incorrect' => 'with incorrect submissions',
                   8715:              'all'       => 'with any status'),
                   8716:              'select_form_order' => ['yes','queued','graded','incorrect','all'])).
                   8717:    '</fieldset>';
                   8718:     }
                   8719:     $result.='</div><br />';
1.44      ng       8720:     return $result;
1.2       albertel 8721: }
                   8722: 
1.285     albertel 8723: sub reset_perm {
                   8724:     undef(%perm);
                   8725: }
                   8726: 
                   8727: sub init_perm {
                   8728:     &reset_perm();
1.300     albertel 8729:     foreach my $test_perm ('vgr','mgr','opa') {
                   8730: 
                   8731: 	my $scope = $env{'request.course.id'};
                   8732: 	if (!($perm{$test_perm}=&Apache::lonnet::allowed($test_perm,$scope))) {
                   8733: 
                   8734: 	    $scope .= '/'.$env{'request.course.sec'};
                   8735: 	    if ( $perm{$test_perm}=
                   8736: 		 &Apache::lonnet::allowed($test_perm,$scope)) {
                   8737: 		$perm{$test_perm.'_section'}=$env{'request.course.sec'};
                   8738: 	    } else {
                   8739: 		delete($perm{$test_perm});
                   8740: 	    }
1.285     albertel 8741: 	}
                   8742:     }
                   8743: }
                   8744: 
1.400     www      8745: sub gather_clicker_ids {
1.408     albertel 8746:     my %clicker_ids;
1.400     www      8747: 
                   8748:     my $classlist = &Apache::loncoursedata::get_classlist();
                   8749: 
                   8750:     # Set up a couple variables.
1.407     albertel 8751:     my $username_idx = &Apache::loncoursedata::CL_SNAME();
                   8752:     my $domain_idx   = &Apache::loncoursedata::CL_SDOM();
1.438     www      8753:     my $status_idx   = &Apache::loncoursedata::CL_STATUS();
1.400     www      8754: 
1.407     albertel 8755:     foreach my $student (keys(%$classlist)) {
1.438     www      8756:         if ($classlist->{$student}->[$status_idx] ne 'Active') { next; }
1.407     albertel 8757:         my $username = $classlist->{$student}->[$username_idx];
                   8758:         my $domain   = $classlist->{$student}->[$domain_idx];
1.400     www      8759:         my $clickers =
1.408     albertel 8760: 	    (&Apache::lonnet::userenvironment($domain,$username,'clickers'))[1];
1.400     www      8761:         foreach my $id (split(/\,/,$clickers)) {
1.414     www      8762:             $id=~s/^[\#0]+//;
1.421     www      8763:             $id=~s/[\-\:]//g;
1.407     albertel 8764:             if (exists($clicker_ids{$id})) {
1.408     albertel 8765: 		$clicker_ids{$id}.=','.$username.':'.$domain;
1.400     www      8766:             } else {
1.408     albertel 8767: 		$clicker_ids{$id}=$username.':'.$domain;
1.400     www      8768:             }
                   8769:         }
                   8770:     }
1.407     albertel 8771:     return %clicker_ids;
1.400     www      8772: }
                   8773: 
1.402     www      8774: sub gather_adv_clicker_ids {
1.408     albertel 8775:     my %clicker_ids;
1.402     www      8776:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
                   8777:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   8778:     my %coursepersonnel=&Apache::lonnet::get_course_adv_roles($cdom.'/'.$cnum);
1.409     albertel 8779:     foreach my $element (sort(keys(%coursepersonnel))) {
1.402     www      8780:         foreach my $person (split(/\,/,$coursepersonnel{$element})) {
                   8781:             my ($puname,$pudom)=split(/\:/,$person);
                   8782:             my $clickers =
1.408     albertel 8783: 		(&Apache::lonnet::userenvironment($pudom,$puname,'clickers'))[1];
1.405     www      8784:             foreach my $id (split(/\,/,$clickers)) {
1.414     www      8785: 		$id=~s/^[\#0]+//;
1.421     www      8786:                 $id=~s/[\-\:]//g;
1.408     albertel 8787: 		if (exists($clicker_ids{$id})) {
                   8788: 		    $clicker_ids{$id}.=','.$puname.':'.$pudom;
                   8789: 		} else {
                   8790: 		    $clicker_ids{$id}=$puname.':'.$pudom;
                   8791: 		}
1.405     www      8792:             }
1.402     www      8793:         }
                   8794:     }
1.407     albertel 8795:     return %clicker_ids;
1.402     www      8796: }
                   8797: 
1.413     www      8798: sub clicker_grading_parameters {
                   8799:     return ('gradingmechanism' => 'scalar',
                   8800:             'upfiletype' => 'scalar',
                   8801:             'specificid' => 'scalar',
                   8802:             'pcorrect' => 'scalar',
                   8803:             'pincorrect' => 'scalar');
                   8804: }
                   8805: 
1.400     www      8806: sub process_clicker {
                   8807:     my ($r)=@_;
                   8808:     my ($symb)=&get_symb($r);
                   8809:     if (!$symb) {return '';}
                   8810:     my $result=&checkforfile_js();
                   8811:     $env{'form.probTitle'} = &Apache::lonnet::gettitle($symb);
                   8812:     $result.='<br /><table width="100%" border="0"><tr><td bgcolor="#777777">'."\n";
                   8813:     $result.='<table width="100%" border="0"><tr bgcolor="#e6ffff"><td>'."\n";
1.538     schulted 8814:     $result.='&nbsp;<b>'.&mt('Specify a file containing the clicker information for this resource.').
                   8815:         '</b></td></tr>'."\n";
1.601     www      8816:     $result.='<tr bgcolor="#ffffe6"><td>'."\n";
1.413     www      8817: # Attempt to restore parameters from last session, set defaults if not present
                   8818:     my %Saveable_Parameters=&clicker_grading_parameters();
                   8819:     &Apache::loncommon::restore_course_settings('grades_clicker',
                   8820:                                                  \%Saveable_Parameters);
                   8821:     if (!$env{'form.pcorrect'}) { $env{'form.pcorrect'}=100; }
                   8822:     if (!$env{'form.pincorrect'}) { $env{'form.pincorrect'}=100; }
                   8823:     if (!$env{'form.gradingmechanism'}) { $env{'form.gradingmechanism'}='attendance'; }
                   8824:     if (!$env{'form.upfiletype'}) { $env{'form.upfiletype'}='iclicker'; }
                   8825: 
                   8826:     my %checked;
1.521     www      8827:     foreach my $gradingmechanism ('attendance','personnel','specific','given') {
1.413     www      8828:        if ($env{'form.gradingmechanism'} eq $gradingmechanism) {
1.569     bisitz   8829:           $checked{$gradingmechanism}=' checked="checked"';
1.413     www      8830:        }
                   8831:     }
                   8832: 
1.400     www      8833:     my $upload=&mt("Upload File");
                   8834:     my $type=&mt("Type");
1.402     www      8835:     my $attendance=&mt("Award points just for participation");
                   8836:     my $personnel=&mt("Correctness determined from response by course personnel");
1.414     www      8837:     my $specific=&mt("Correctness determined from response with clicker ID(s)"); 
1.521     www      8838:     my $given=&mt("Correctness determined from given list of answers").' '.
                   8839:               '<font size="-2"><tt>('.&mt("Provide comma-separated list. Use '*' for any answer correct, '-' for skip").')</tt></font>';
1.402     www      8840:     my $pcorrect=&mt("Percentage points for correct solution");
                   8841:     my $pincorrect=&mt("Percentage points for incorrect solution");
1.413     www      8842:     my $selectform=&Apache::loncommon::select_form($env{'form.upfiletype'},'upfiletype',
1.419     www      8843: 						   ('iclicker' => 'i>clicker',
                   8844:                                                     'interwrite' => 'interwrite PRS'));
1.418     albertel 8845:     $symb = &Apache::lonenc::check_encrypt($symb);
1.597     wenzelju 8846:     $result.= &Apache::lonhtmlcommon::scripttag(<<ENDUPFORM);
1.402     www      8847: function sanitycheck() {
                   8848: // Accept only integer percentages
                   8849:    document.forms.gradesupload.pcorrect.value=Math.round(document.forms.gradesupload.pcorrect.value);
                   8850:    document.forms.gradesupload.pincorrect.value=Math.round(document.forms.gradesupload.pincorrect.value);
                   8851: // Find out grading choice
                   8852:    for (i=0; i<document.forms.gradesupload.gradingmechanism.length; i++) {
                   8853:       if (document.forms.gradesupload.gradingmechanism[i].checked) {
                   8854:          gradingchoice=document.forms.gradesupload.gradingmechanism[i].value;
                   8855:       }
                   8856:    }
                   8857: // By default, new choice equals user selection
                   8858:    newgradingchoice=gradingchoice;
                   8859: // Not good to give more points for false answers than correct ones
                   8860:    if (Math.round(document.forms.gradesupload.pcorrect.value)<Math.round(document.forms.gradesupload.pincorrect.value)) {
                   8861:       document.forms.gradesupload.pcorrect.value=document.forms.gradesupload.pincorrect.value;
                   8862:    }
                   8863: // If new choice is attendance only, and old choice was correctness-based, restore defaults
                   8864:    if ((gradingchoice=='attendance') && (document.forms.gradesupload.waschecked.value!='attendance')) {
                   8865:       document.forms.gradesupload.pcorrect.value=100;
                   8866:       document.forms.gradesupload.pincorrect.value=100;
                   8867:    }
                   8868: // If the values are different, cannot be attendance only
                   8869:    if ((Math.round(document.forms.gradesupload.pcorrect.value)!=Math.round(document.forms.gradesupload.pincorrect.value)) &&
                   8870:        (gradingchoice=='attendance')) {
                   8871:        newgradingchoice='personnel';
                   8872:    }
                   8873: // Change grading choice to new one
                   8874:    for (i=0; i<document.forms.gradesupload.gradingmechanism.length; i++) {
                   8875:       if (document.forms.gradesupload.gradingmechanism[i].value==newgradingchoice) {
                   8876:          document.forms.gradesupload.gradingmechanism[i].checked=true;
                   8877:       } else {
                   8878:          document.forms.gradesupload.gradingmechanism[i].checked=false;
                   8879:       }
                   8880:    }
                   8881: // Remember the old state
                   8882:    document.forms.gradesupload.waschecked.value=newgradingchoice;
                   8883: }
1.597     wenzelju 8884: ENDUPFORM
                   8885:     $result.= <<ENDUPFORM;
1.400     www      8886: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
                   8887: <input type="hidden" name="symb" value="$symb" />
                   8888: <input type="hidden" name="command" value="processclickerfile" />
                   8889: <input type="hidden" name="probTitle" value="$env{'form.probTitle'}" />
                   8890: <input type="hidden" name="saveState"  value="$env{'form.saveState'}" />
                   8891: <input type="file" name="upfile" size="50" />
                   8892: <br /><label>$type: $selectform</label>
1.589     bisitz   8893: <br /><label><input type="radio" name="gradingmechanism" value="attendance"$checked{'attendance'} onclick="sanitycheck()" />$attendance </label>
                   8894: <br /><label><input type="radio" name="gradingmechanism" value="personnel"$checked{'personnel'} onclick="sanitycheck()" />$personnel</label>
                   8895: <br /><label><input type="radio" name="gradingmechanism" value="specific"$checked{'specific'} onclick="sanitycheck()" />$specific </label>
1.414     www      8896: <input type="text" name="specificid" value="$env{'form.specificid'}" size="20" />
1.589     bisitz   8897: <br /><label><input type="radio" name="gradingmechanism" value="given"$checked{'given'} onclick="sanitycheck()" />$given </label>
1.521     www      8898: <br />&nbsp;&nbsp;&nbsp;
                   8899: <input type="text" name="givenanswer" size="50" />
1.413     www      8900: <input type="hidden" name="waschecked" value="$env{'form.gradingmechanism'}" />
1.589     bisitz   8901: <br /><label>$pcorrect: <input type="text" name="pcorrect" size="4" value="$env{'form.pcorrect'}" onchange="sanitycheck()" /></label>
                   8902: <br /><label>$pincorrect: <input type="text" name="pincorrect" size="4" value="$env{'form.pincorrect'}" onchange="sanitycheck()" /></label>
                   8903: <br /><input type="button" onclick="javascript:checkUpload(this.form);" value="$upload" />
1.597     wenzelju 8904: </form>'
1.400     www      8905: ENDUPFORM
                   8906:     $result.='</td></tr></table>'."\n".
                   8907:              '</td></tr></table><br /><br />'."\n";
                   8908:     $result.=&show_grading_menu_form($symb);
                   8909:     return $result;
                   8910: }
                   8911: 
                   8912: sub process_clicker_file {
                   8913:     my ($r)=@_;
                   8914:     my ($symb)=&get_symb($r);
                   8915:     if (!$symb) {return '';}
1.413     www      8916: 
                   8917:     my %Saveable_Parameters=&clicker_grading_parameters();
                   8918:     &Apache::loncommon::store_course_settings('grades_clicker',
                   8919:                                               \%Saveable_Parameters);
1.598     www      8920:     my $result='';
                   8921: #    my ($result) = &showResourceInfo($symb,$env{'form.probTitle'});
1.404     www      8922:     if (($env{'form.gradingmechanism'} eq 'specific') && ($env{'form.specificid'}!~/\w/)) {
1.408     albertel 8923: 	$result.='<span class="LC_error">'.&mt('You need to specify a clicker ID for the correct answer').'</span>';
                   8924: 	return $result.&show_grading_menu_form($symb);
1.404     www      8925:     }
1.522     www      8926:     if (($env{'form.gradingmechanism'} eq 'given') && ($env{'form.givenanswer'}!~/\S/)) {
1.521     www      8927:         $result.='<span class="LC_error">'.&mt('You need to specify the correct answer').'</span>';
                   8928:         return $result.&show_grading_menu_form($symb);
                   8929:     }
1.522     www      8930:     my $foundgiven=0;
1.521     www      8931:     if ($env{'form.gradingmechanism'} eq 'given') {
                   8932:         $env{'form.givenanswer'}=~s/^\s*//gs;
                   8933:         $env{'form.givenanswer'}=~s/\s*$//gs;
                   8934:         $env{'form.givenanswer'}=~s/[^a-zA-Z0-9\.\*\-]+/\,/g;
                   8935:         $env{'form.givenanswer'}=uc($env{'form.givenanswer'});
1.522     www      8936:         my @answers=split(/\,/,$env{'form.givenanswer'});
                   8937:         $foundgiven=$#answers+1;
1.521     www      8938:     }
1.407     albertel 8939:     my %clicker_ids=&gather_clicker_ids();
1.408     albertel 8940:     my %correct_ids;
1.404     www      8941:     if ($env{'form.gradingmechanism'} eq 'personnel') {
1.408     albertel 8942: 	%correct_ids=&gather_adv_clicker_ids();
1.404     www      8943:     }
                   8944:     if ($env{'form.gradingmechanism'} eq 'specific') {
1.414     www      8945: 	foreach my $correct_id (split(/[\s\,]/,$env{'form.specificid'})) {;
                   8946: 	   $correct_id=~tr/a-z/A-Z/;
                   8947: 	   $correct_id=~s/\s//gs;
                   8948: 	   $correct_id=~s/^[\#0]+//;
1.421     www      8949:            $correct_id=~s/[\-\:]//g;
1.414     www      8950:            if ($correct_id) {
                   8951: 	      $correct_ids{$correct_id}='specified';
                   8952:            }
                   8953:         }
1.400     www      8954:     }
1.404     www      8955:     if ($env{'form.gradingmechanism'} eq 'attendance') {
1.408     albertel 8956: 	$result.=&mt('Score based on attendance only');
1.521     www      8957:     } elsif ($env{'form.gradingmechanism'} eq 'given') {
1.522     www      8958:         $result.=&mt('Score based on [_1] ([_2] answers)','<tt>'.$env{'form.givenanswer'}.'</tt>',$foundgiven);
1.404     www      8959:     } else {
1.408     albertel 8960: 	my $number=0;
1.411     www      8961: 	$result.='<p><b>'.&mt('Correctness determined by the following IDs').'</b>';
1.408     albertel 8962: 	foreach my $id (sort(keys(%correct_ids))) {
1.411     www      8963: 	    $result.='<br /><tt>'.$id.'</tt> - ';
1.408     albertel 8964: 	    if ($correct_ids{$id} eq 'specified') {
                   8965: 		$result.=&mt('specified');
                   8966: 	    } else {
                   8967: 		my ($uname,$udom)=split(/\:/,$correct_ids{$id});
                   8968: 		$result.=&Apache::loncommon::plainname($uname,$udom);
                   8969: 	    }
                   8970: 	    $number++;
                   8971: 	}
1.411     www      8972:         $result.="</p>\n";
1.408     albertel 8973: 	if ($number==0) {
                   8974: 	    $result.='<span class="LC_error">'.&mt('No IDs found to determine correct answer').'</span>';
                   8975: 	    return $result.&show_grading_menu_form($symb);
                   8976: 	}
1.404     www      8977:     }
1.405     www      8978:     if (length($env{'form.upfile'}) < 2) {
1.407     albertel 8979:         $result.=&mt('[_1] Error: [_2] The file you attempted to upload, [_3] contained no information. Please check that you entered the correct filename.',
                   8980: 		     '<span class="LC_error">',
                   8981: 		     '</span>',
                   8982: 		     '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>');
1.405     www      8983:         return $result.&show_grading_menu_form($symb);
                   8984:     }
1.410     www      8985: 
                   8986: # Were able to get all the info needed, now analyze the file
                   8987: 
1.411     www      8988:     $result.=&Apache::loncommon::studentbrowser_javascript();
1.418     albertel 8989:     $symb = &Apache::lonenc::check_encrypt($symb);
1.410     www      8990:     my $heading=&mt('Scanning clicker file');
                   8991:     $result.=(<<ENDHEADER);
                   8992: <br /><table width="100%" border="0"><tr><td bgcolor="#777777">
                   8993: <table width="100%" border="0"><tr bgcolor="#e6ffff"><td>
                   8994: <b>$heading</b></td></tr><tr bgcolor=#ffffe6><td>
                   8995: <form method="post" action="/adm/grades" name="clickeranalysis">
                   8996: <input type="hidden" name="symb" value="$symb" />
                   8997: <input type="hidden" name="command" value="assignclickergrades" />
                   8998: <input type="hidden" name="probTitle" value="$env{'form.probTitle'}" />
                   8999: <input type="hidden" name="saveState"  value="$env{'form.saveState'}" />
1.411     www      9000: <input type="hidden" name="gradingmechanism" value="$env{'form.gradingmechanism'}" />
                   9001: <input type="hidden" name="pcorrect" value="$env{'form.pcorrect'}" />
                   9002: <input type="hidden" name="pincorrect" value="$env{'form.pincorrect'}" />
1.410     www      9003: ENDHEADER
1.522     www      9004:     if ($env{'form.gradingmechanism'} eq 'given') {
                   9005:        $result.='<input type="hidden" name="correct:given" value="'.$env{'form.givenanswer'}.'" />';
                   9006:     } 
1.408     albertel 9007:     my %responses;
                   9008:     my @questiontitles;
1.405     www      9009:     my $errormsg='';
                   9010:     my $number=0;
                   9011:     if ($env{'form.upfiletype'} eq 'iclicker') {
1.408     albertel 9012: 	($errormsg,$number)=&iclicker_eval(\@questiontitles,\%responses);
1.406     www      9013:     }
1.419     www      9014:     if ($env{'form.upfiletype'} eq 'interwrite') {
                   9015:         ($errormsg,$number)=&interwrite_eval(\@questiontitles,\%responses);
                   9016:     }
1.411     www      9017:     $result.='<br />'.&mt('Found [_1] question(s)',$number).'<br />'.
                   9018:              '<input type="hidden" name="number" value="'.$number.'" />'.
                   9019:              &mt('Awarding [_1] percent for correct and [_2] percent for incorrect responses',
                   9020:                  $env{'form.pcorrect'},$env{'form.pincorrect'}).
                   9021:              '<br />';
1.522     www      9022:     if (($env{'form.gradingmechanism'} eq 'given') && ($number!=$foundgiven)) {
                   9023:        $result.='<span class="LC_error">'.&mt('Number of given answers does not agree with number of questions in file.').'</span>';
                   9024:        return $result.&show_grading_menu_form($symb);
                   9025:     } 
1.414     www      9026: # Remember Question Titles
                   9027: # FIXME: Possibly need delimiter other than ":"
                   9028:     for (my $i=0;$i<$number;$i++) {
                   9029:         $result.='<input type="hidden" name="question:'.$i.'" value="'.
                   9030:                  &HTML::Entities::encode($questiontitles[$i],'"&<>').'" />';
                   9031:     }
1.411     www      9032:     my $correct_count=0;
                   9033:     my $student_count=0;
                   9034:     my $unknown_count=0;
1.414     www      9035: # Match answers with usernames
                   9036: # FIXME: Possibly need delimiter other than ":"
1.409     albertel 9037:     foreach my $id (keys(%responses)) {
1.410     www      9038:        if ($correct_ids{$id}) {
1.414     www      9039:           $result.="\n".'<input type="hidden" name="correct:'.$correct_count.':'.$correct_ids{$id}.'" value="'.$responses{$id}.'" />';
1.411     www      9040:           $correct_count++;
1.410     www      9041:        } elsif ($clicker_ids{$id}) {
1.437     www      9042:           if ($clicker_ids{$id}=~/\,/) {
                   9043: # More than one user with the same clicker!
                   9044:              $result.="\n<hr />".&mt('Clicker registered more than once').": <tt>".$id."</tt><br />";
                   9045:              $result.="\n".'<input type="hidden" name="unknown:'.$id.'" value="'.$responses{$id}.'" />'.
                   9046:                            "<select name='multi".$id."'>";
                   9047:              foreach my $reguser (sort(split(/\,/,$clicker_ids{$id}))) {
                   9048:                  $result.="<option value='".$reguser."'>".&Apache::loncommon::plainname(split(/\:/,$reguser)).' ('.$reguser.')</option>';
                   9049:              }
                   9050:              $result.='</select>';
                   9051:              $unknown_count++;
                   9052:           } else {
                   9053: # Good: found one and only one user with the right clicker
                   9054:              $result.="\n".'<input type="hidden" name="student:'.$clicker_ids{$id}.'" value="'.$responses{$id}.'" />';
                   9055:              $student_count++;
                   9056:           }
1.410     www      9057:        } else {
1.411     www      9058:           $result.="\n<hr />".&mt('Unregistered Clicker')." <tt>".$id."</tt><br />";
                   9059:           $result.="\n".'<input type="hidden" name="unknown:'.$id.'" value="'.$responses{$id}.'" />'.
                   9060:                    "\n".&mt("Username").": <input type='text' name='uname".$id."' />&nbsp;".
                   9061:                    "\n".&mt("Domain").": ".
                   9062:                    &Apache::loncommon::select_dom_form($env{'course.'.$env{'request.course.id'}.'.domain'},'udom'.$id).'&nbsp;'.
                   9063:                    &Apache::loncommon::selectstudent_link('clickeranalysis','uname'.$id,'udom'.$id);
                   9064:           $unknown_count++;
1.410     www      9065:        }
1.405     www      9066:     }
1.412     www      9067:     $result.='<hr />'.
                   9068:              &mt('Found [_1] registered and [_2] unregistered clickers.',$student_count,$unknown_count);
1.521     www      9069:     if (($env{'form.gradingmechanism'} ne 'attendance') && ($env{'form.gradingmechanism'} ne 'given')) {
1.412     www      9070:        if ($correct_count==0) {
                   9071:           $errormsg.="Found no correct answers answers for grading!";
                   9072:        } elsif ($correct_count>1) {
1.414     www      9073:           $result.='<br /><span class="LC_warning">'.&mt("Found [_1] entries for grading!",$correct_count).'</span>';
1.412     www      9074:        }
                   9075:     }
1.428     www      9076:     if ($number<1) {
                   9077:        $errormsg.="Found no questions.";
                   9078:     }
1.412     www      9079:     if ($errormsg) {
                   9080:        $result.='<br /><span class="LC_error">'.&mt($errormsg).'</span>';
                   9081:     } else {
                   9082:        $result.='<br /><input type="submit" name="finalize" value="'.&mt('Finalize Grading').'" />';
                   9083:     }
                   9084:     $result.='</form></td></tr></table>'."\n".
1.410     www      9085:              '</td></tr></table><br /><br />'."\n";
1.404     www      9086:     return $result.&show_grading_menu_form($symb);
1.400     www      9087: }
                   9088: 
1.405     www      9089: sub iclicker_eval {
1.406     www      9090:     my ($questiontitles,$responses)=@_;
1.405     www      9091:     my $number=0;
                   9092:     my $errormsg='';
                   9093:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
1.410     www      9094:         my %components=&Apache::loncommon::record_sep($line);
                   9095:         my @entries=map {$components{$_}} (sort(keys(%components)));
1.408     albertel 9096: 	if ($entries[0] eq 'Question') {
                   9097: 	    for (my $i=3;$i<$#entries;$i+=6) {
                   9098: 		$$questiontitles[$number]=$entries[$i];
                   9099: 		$number++;
                   9100: 	    }
                   9101: 	}
                   9102: 	if ($entries[0]=~/^\#/) {
                   9103: 	    my $id=$entries[0];
                   9104: 	    my @idresponses;
                   9105: 	    $id=~s/^[\#0]+//;
                   9106: 	    for (my $i=0;$i<$number;$i++) {
                   9107: 		my $idx=3+$i*6;
                   9108: 		push(@idresponses,$entries[$idx]);
                   9109: 	    }
                   9110: 	    $$responses{$id}=join(',',@idresponses);
                   9111: 	}
1.405     www      9112:     }
                   9113:     return ($errormsg,$number);
                   9114: }
                   9115: 
1.419     www      9116: sub interwrite_eval {
                   9117:     my ($questiontitles,$responses)=@_;
                   9118:     my $number=0;
                   9119:     my $errormsg='';
1.420     www      9120:     my $skipline=1;
                   9121:     my $questionnumber=0;
                   9122:     my %idresponses=();
1.419     www      9123:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
                   9124:         my %components=&Apache::loncommon::record_sep($line);
                   9125:         my @entries=map {$components{$_}} (sort(keys(%components)));
1.420     www      9126:         if ($entries[1] eq 'Time') { $skipline=0; next; }
                   9127:         if ($entries[1] eq 'Response') { $skipline=1; }
                   9128:         next if $skipline;
                   9129:         if ($entries[0]!=$questionnumber) {
                   9130:            $questionnumber=$entries[0];
                   9131:            $$questiontitles[$number]=&mt('Question [_1]',$questionnumber);
                   9132:            $number++;
1.419     www      9133:         }
1.420     www      9134:         my $id=$entries[4];
                   9135:         $id=~s/^[\#0]+//;
1.421     www      9136:         $id=~s/^v\d*\://i;
                   9137:         $id=~s/[\-\:]//g;
1.420     www      9138:         $idresponses{$id}[$number]=$entries[6];
                   9139:     }
1.524     raeburn  9140:     foreach my $id (keys(%idresponses)) {
1.420     www      9141:        $$responses{$id}=join(',',@{$idresponses{$id}});
                   9142:        $$responses{$id}=~s/^\s*\,//;
1.419     www      9143:     }
                   9144:     return ($errormsg,$number);
                   9145: }
                   9146: 
1.414     www      9147: sub assign_clicker_grades {
                   9148:     my ($r)=@_;
                   9149:     my ($symb)=&get_symb($r);
                   9150:     if (!$symb) {return '';}
1.416     www      9151: # See which part we are saving to
1.582     raeburn  9152:     my $res_error;
                   9153:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
                   9154:     if ($res_error) {
                   9155:         return &navmap_errormsg();
                   9156:     }
1.416     www      9157: # FIXME: This should probably look for the first handgradeable part
                   9158:     my $part=$$partlist[0];
                   9159: # Start screen output
1.598     www      9160:     my $result='';
                   9161: #    my ($result) = &showResourceInfo($symb,$env{'form.probTitle'});
1.416     www      9162: 
1.414     www      9163:     my $heading=&mt('Assigning grades based on clicker file');
                   9164:     $result.=(<<ENDHEADER);
                   9165: <br /><table width="100%" border="0"><tr><td bgcolor="#777777">
                   9166: <table width="100%" border="0"><tr bgcolor="#e6ffff"><td>
                   9167: <b>$heading</b></td></tr><tr bgcolor=#ffffe6><td>
                   9168: ENDHEADER
                   9169: # Get correct result
                   9170: # FIXME: Possibly need delimiter other than ":"
                   9171:     my @correct=();
1.415     www      9172:     my $gradingmechanism=$env{'form.gradingmechanism'};
                   9173:     my $number=$env{'form.number'};
                   9174:     if ($gradingmechanism ne 'attendance') {
1.414     www      9175:        foreach my $key (keys(%env)) {
                   9176:           if ($key=~/^form\.correct\:/) {
                   9177:              my @input=split(/\,/,$env{$key});
                   9178:              for (my $i=0;$i<=$#input;$i++) {
                   9179:                  if (($correct[$i]) && ($input[$i]) &&
                   9180:                      ($correct[$i] ne $input[$i])) {
                   9181:                     $result.='<br /><span class="LC_warning">'.
                   9182:                              &mt('More than one correct result given for question "[_1]": [_2] versus [_3].',
                   9183:                                  $env{'form.question:'.$i},$correct[$i],$input[$i]).'</span>';
                   9184:                  } elsif ($input[$i]) {
                   9185:                     $correct[$i]=$input[$i];
                   9186:                  }
                   9187:              }
                   9188:           }
                   9189:        }
1.415     www      9190:        for (my $i=0;$i<$number;$i++) {
1.414     www      9191:           if (!$correct[$i]) {
                   9192:              $result.='<br /><span class="LC_error">'.
                   9193:                       &mt('No correct result given for question "[_1]"!',
                   9194:                           $env{'form.question:'.$i}).'</span>';
                   9195:           }
                   9196:        }
                   9197:        $result.='<br />'.&mt("Correct answer: [_1]",join(', ',map { ($_?$_:'-') } @correct));
                   9198:     }
                   9199: # Start grading
1.415     www      9200:     my $pcorrect=$env{'form.pcorrect'};
                   9201:     my $pincorrect=$env{'form.pincorrect'};
1.416     www      9202:     my $storecount=0;
1.415     www      9203:     foreach my $key (keys(%env)) {
1.420     www      9204:        my $user='';
1.415     www      9205:        if ($key=~/^form\.student\:(.*)$/) {
1.420     www      9206:           $user=$1;
                   9207:        }
                   9208:        if ($key=~/^form\.unknown\:(.*)$/) {
                   9209:           my $id=$1;
                   9210:           if (($env{'form.uname'.$id}) && ($env{'form.udom'.$id})) {
                   9211:              $user=$env{'form.uname'.$id}.':'.$env{'form.udom'.$id};
1.437     www      9212:           } elsif ($env{'form.multi'.$id}) {
                   9213:              $user=$env{'form.multi'.$id};
1.420     www      9214:           }
                   9215:        }
                   9216:        if ($user) { 
1.415     www      9217:           my @answer=split(/\,/,$env{$key});
                   9218:           my $sum=0;
1.522     www      9219:           my $realnumber=$number;
1.415     www      9220:           for (my $i=0;$i<$number;$i++) {
1.576     www      9221:              if  ($correct[$i] eq '-') {
                   9222:                 $realnumber--;
                   9223:              } elsif ($answer[$i]) {
1.415     www      9224:                 if ($gradingmechanism eq 'attendance') {
                   9225:                    $sum+=$pcorrect;
1.576     www      9226:                 } elsif ($correct[$i] eq '*') {
1.522     www      9227:                    $sum+=$pcorrect;
1.415     www      9228:                 } else {
                   9229:                    if ($answer[$i] eq $correct[$i]) {
                   9230:                       $sum+=$pcorrect;
                   9231:                    } else {
                   9232:                       $sum+=$pincorrect;
                   9233:                    }
                   9234:                 }
                   9235:              }
                   9236:           }
1.522     www      9237:           my $ave=$sum/(100*$realnumber);
1.416     www      9238: # Store
                   9239:           my ($username,$domain)=split(/\:/,$user);
                   9240:           my %grades=();
                   9241:           $grades{"resource.$part.solved"}='correct_by_override';
                   9242:           $grades{"resource.$part.awarded"}=$ave;
                   9243:           $grades{"resource.regrader"}="$env{'user.name'}:$env{'user.domain'}";
                   9244:           my $returncode=&Apache::lonnet::cstore(\%grades,$symb,
                   9245:                                                  $env{'request.course.id'},
                   9246:                                                  $domain,$username);
                   9247:           if ($returncode ne 'ok') {
                   9248:              $result.="<br /><span class=\"LC_error\">Failed to save student $username:$domain. Message when trying to save was ($returncode)</span>";
                   9249:           } else {
                   9250:              $storecount++;
                   9251:           }
1.415     www      9252:        }
                   9253:     }
                   9254: # We are done
1.549     hauer    9255:     $result.='<br />'.&mt('Successfully stored grades for [quant,_1,student].',$storecount).
1.416     www      9256:              '</td></tr></table>'."\n".
1.414     www      9257:              '</td></tr></table><br /><br />'."\n";
                   9258:     return $result.&show_grading_menu_form($symb);
                   9259: }
                   9260: 
1.582     raeburn  9261: sub navmap_errormsg {
                   9262:     return '<div class="LC_error">'.
                   9263:            &mt('An error occurred retrieving information about resources in the course.').'<br />'.
1.595     raeburn  9264:            &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  9265:            '</div>';
                   9266: }
                   9267: 
1.1       albertel 9268: sub handler {
1.41      ng       9269:     my $request=$_[0];
1.434     albertel 9270:     &reset_caches();
1.257     albertel 9271:     if ($env{'browser.mathml'}) {
1.141     www      9272: 	&Apache::loncommon::content_type($request,'text/xml');
1.41      ng       9273:     } else {
1.141     www      9274: 	&Apache::loncommon::content_type($request,'text/html');
1.41      ng       9275:     }
                   9276:     $request->send_http_header;
1.44      ng       9277:     return '' if $request->header_only;
1.41      ng       9278:     &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'});
1.324     albertel 9279:     my $symb=&get_symb($request,1);
1.160     albertel 9280:     my @commands=&Apache::loncommon::get_env_multiple('form.command');
                   9281:     my $command=$commands[0];
1.447     foxr     9282: 
1.160     albertel 9283:     if ($#commands > 0) {
                   9284: 	&Apache::lonnet::logthis("grades got multiple commands ".join(':',@commands));
                   9285:     }
1.447     foxr     9286: 
1.513     foxr     9287:     $ssi_error = 0;
1.535     raeburn  9288:     my $brcrum = [{href=>"/adm/grades",text=>"Grading"}];
                   9289:     $request->print(&Apache::loncommon::start_page('Grading',undef,
                   9290:                                           {'bread_crumbs' => $brcrum}));
1.324     albertel 9291:     if ($symb eq '' && $command eq '') {
1.601     www      9292: #
                   9293: # Not called from a resource
                   9294: #    
                   9295: 
1.41      ng       9296:     } else {
1.285     albertel 9297: 	&init_perm();
1.104     albertel 9298: 	if ($command eq 'submission' && $perm{'vgr'}) {
1.257     albertel 9299: 	    ($env{'form.student'} eq '' ? &listStudents($request) : &submission($request,0,0));
1.103     albertel 9300: 	} elsif ($command eq 'pickStudentPage' && $perm{'vgr'}) {
1.68      ng       9301: 	    &pickStudentPage($request);
1.103     albertel 9302: 	} elsif ($command eq 'displayPage' && $perm{'vgr'}) {
1.68      ng       9303: 	    &displayPage($request);
1.104     albertel 9304: 	} elsif ($command eq 'gradeByPage' && $perm{'mgr'}) {
1.71      ng       9305: 	    &updateGradeByPage($request);
1.104     albertel 9306: 	} elsif ($command eq 'processGroup' && $perm{'vgr'}) {
1.41      ng       9307: 	    &processGroup($request);
1.104     albertel 9308: 	} elsif ($command eq 'gradingmenu' && $perm{'vgr'}) {
1.443     banghart 9309: 	    $request->print(&grading_menu($request));
1.598     www      9310: 	} elsif ($command eq 'individual' && $perm{'vgr'}) {
1.600     www      9311: 	    $request->print(&submit_options($request));
1.598     www      9312:         } elsif ($command eq 'ungraded' && $perm{'vgr'}) {
                   9313:             $request->print(&submit_options($request));
                   9314:         } elsif ($command eq 'table' && $perm{'vgr'}) {
1.600     www      9315:             $request->print(&submit_options_table($request));
1.598     www      9316:         } elsif ($command eq 'all_for_one' && $perm{'vgr'}) {
1.599     www      9317:             $request->print(&submit_options_sequence($request));
1.104     albertel 9318: 	} elsif ($command eq 'viewgrades' && $perm{'vgr'}) {
1.41      ng       9319: 	    $request->print(&viewgrades($request));
1.104     albertel 9320: 	} elsif ($command eq 'handgrade' && $perm{'mgr'}) {
1.41      ng       9321: 	    $request->print(&processHandGrade($request));
1.106     albertel 9322: 	} elsif ($command eq 'editgrades' && $perm{'mgr'}) {
1.41      ng       9323: 	    $request->print(&editgrades($request));
1.602     www      9324:         } elsif ($command eq 'initialverifyreceipt' && $perm{'vgr'}) {
                   9325:             $request->print(&initialverifyreceipt($request));
1.106     albertel 9326: 	} elsif ($command eq 'verify' && $perm{'vgr'}) {
1.41      ng       9327: 	    $request->print(&verifyreceipt($request));
1.400     www      9328:         } elsif ($command eq 'processclicker' && $perm{'mgr'}) {
                   9329:             $request->print(&process_clicker($request));
                   9330:         } elsif ($command eq 'processclickerfile' && $perm{'mgr'}) {
                   9331:             $request->print(&process_clicker_file($request));
1.414     www      9332:         } elsif ($command eq 'assignclickergrades' && $perm{'mgr'}) {
                   9333:             $request->print(&assign_clicker_grades($request));
1.106     albertel 9334: 	} elsif ($command eq 'csvform' && $perm{'mgr'}) {
1.72      ng       9335: 	    $request->print(&upcsvScores_form($request));
1.106     albertel 9336: 	} elsif ($command eq 'csvupload' && $perm{'mgr'}) {
1.41      ng       9337: 	    $request->print(&csvupload($request));
1.106     albertel 9338: 	} elsif ($command eq 'csvuploadmap' && $perm{'mgr'} ) {
1.41      ng       9339: 	    $request->print(&csvuploadmap($request));
1.246     albertel 9340: 	} elsif ($command eq 'csvuploadoptions' && $perm{'mgr'}) {
1.257     albertel 9341: 	    if ($env{'form.associate'} ne 'Reverse Association') {
1.246     albertel 9342: 		$request->print(&csvuploadoptions($request));
1.41      ng       9343: 	    } else {
1.257     albertel 9344: 		if ( $env{'form.upfile_associate'} ne 'reverse' ) {
                   9345: 		    $env{'form.upfile_associate'} = 'reverse';
1.41      ng       9346: 		} else {
1.257     albertel 9347: 		    $env{'form.upfile_associate'} = 'forward';
1.41      ng       9348: 		}
                   9349: 		$request->print(&csvuploadmap($request));
                   9350: 	    }
1.246     albertel 9351: 	} elsif ($command eq 'csvuploadassign' && $perm{'mgr'} ) {
                   9352: 	    $request->print(&csvuploadassign($request));
1.106     albertel 9353: 	} elsif ($command eq 'scantron_selectphase' && $perm{'mgr'}) {
1.75      albertel 9354: 	    $request->print(&scantron_selectphase($request));
1.203     albertel 9355:  	} elsif ($command eq 'scantron_warning' && $perm{'mgr'}) {
                   9356:  	    $request->print(&scantron_do_warning($request));
1.142     albertel 9357: 	} elsif ($command eq 'scantron_validate' && $perm{'mgr'}) {
                   9358: 	    $request->print(&scantron_validate_file($request));
1.106     albertel 9359: 	} elsif ($command eq 'scantron_process' && $perm{'mgr'}) {
1.82      albertel 9360: 	    $request->print(&scantron_process_students($request));
1.157     albertel 9361:  	} elsif ($command eq 'scantronupload' && 
1.257     albertel 9362:  		 (&Apache::lonnet::allowed('usc',$env{'request.role.domain'})||
                   9363: 		  &Apache::lonnet::allowed('usc',$env{'request.course.id'}))) {
1.162     albertel 9364:  	    $request->print(&scantron_upload_scantron_data($request)); 
1.157     albertel 9365:  	} elsif ($command eq 'scantronupload_save' &&
1.257     albertel 9366:  		 (&Apache::lonnet::allowed('usc',$env{'request.role.domain'})||
                   9367: 		  &Apache::lonnet::allowed('usc',$env{'request.course.id'}))) {
1.157     albertel 9368:  	    $request->print(&scantron_upload_scantron_data_save($request));
1.202     albertel 9369:  	} elsif ($command eq 'scantron_download' &&
1.257     albertel 9370: 		 &Apache::lonnet::allowed('usc',$env{'request.course.id'})) {
1.162     albertel 9371:  	    $request->print(&scantron_download_scantron_data($request));
1.523     raeburn  9372:         } elsif ($command eq 'checksubmissions' && $perm{'vgr'}) {
                   9373:             $request->print(&checkscantron_results($request));     
1.106     albertel 9374: 	} elsif ($command) {
1.562     bisitz   9375: 	    $request->print('<p class="LC_error">'.&mt('Access Denied ([_1])',$command).'</p>');
1.26      albertel 9376: 	}
1.2       albertel 9377:     }
1.513     foxr     9378:     if ($ssi_error) {
                   9379: 	&ssi_print_error($request);
                   9380:     }
1.353     albertel 9381:     $request->print(&Apache::loncommon::end_page());
1.434     albertel 9382:     &reset_caches();
1.44      ng       9383:     return '';
                   9384: }
                   9385: 
1.1       albertel 9386: 1;
                   9387: 
1.13      albertel 9388: __END__;
1.531     jms      9389: 
                   9390: 
                   9391: =head1 NAME
                   9392: 
                   9393: Apache::grades
                   9394: 
                   9395: =head1 SYNOPSIS
                   9396: 
                   9397: Handles the viewing of grades.
                   9398: 
                   9399: This is part of the LearningOnline Network with CAPA project
                   9400: described at http://www.lon-capa.org.
                   9401: 
                   9402: =head1 OVERVIEW
                   9403: 
                   9404: Do an ssi with retries:
                   9405: While I'd love to factor out this with the vesrion in lonprintout,
                   9406: 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
                   9407: I'm not quite ready to invent (e.g. an ssi_with_retry object).
                   9408: 
                   9409: At least the logic that drives this has been pulled out into loncommon.
                   9410: 
                   9411: 
                   9412: 
                   9413: ssi_with_retries - Does the server side include of a resource.
                   9414:                      if the ssi call returns an error we'll retry it up to
                   9415:                      the number of times requested by the caller.
                   9416:                      If we still have a proble, no text is appended to the
                   9417:                      output and we set some global variables.
                   9418:                      to indicate to the caller an SSI error occurred.  
                   9419:                      All of this is supposed to deal with the issues described
                   9420:                      in LonCAPA BZ 5631 see:
                   9421:                      http://bugs.lon-capa.org/show_bug.cgi?id=5631
                   9422:                      by informing the user that this happened.
                   9423: 
                   9424: Parameters:
                   9425:   resource   - The resource to include.  This is passed directly, without
                   9426:                interpretation to lonnet::ssi.
                   9427:   form       - The form hash parameters that guide the interpretation of the resource
                   9428:                
                   9429:   retries    - Number of retries allowed before giving up completely.
                   9430: Returns:
                   9431:   On success, returns the rendered resource identified by the resource parameter.
                   9432: Side Effects:
                   9433:   The following global variables can be set:
                   9434:    ssi_error                - If an unrecoverable error occurred this becomes true.
                   9435:                               It is up to the caller to initialize this to false
                   9436:                               if desired.
                   9437:    ssi_error_resource  - If an unrecoverable error occurred, this is the value
                   9438:                               of the resource that could not be rendered by the ssi
                   9439:                               call.
                   9440:    ssi_error_message   - The error string fetched from the ssi response
                   9441:                               in the event of an error.
                   9442: 
                   9443: 
                   9444: =head1 HANDLER SUBROUTINE
                   9445: 
                   9446: ssi_with_retries()
                   9447: 
                   9448: =head1 SUBROUTINES
                   9449: 
                   9450: =over
                   9451: 
                   9452: =item scantron_get_correction() : 
                   9453: 
                   9454:    Builds the interface screen to interact with the operator to fix a
                   9455:    specific error condition in a specific scanline
                   9456: 
                   9457:  Arguments:
                   9458:     $r           - Apache request object
                   9459:     $i           - number of the current scanline
                   9460:     $scan_record - hash ref as returned from &scantron_parse_scanline()
                   9461:     $scan_config - hash ref as returned from &get_scantron_config()
                   9462:     $line        - full contents of the current scanline
                   9463:     $error       - error condition, valid values are
                   9464:                    'incorrectCODE', 'duplicateCODE',
                   9465:                    'doublebubble', 'missingbubble',
                   9466:                    'duplicateID', 'incorrectID'
                   9467:     $arg         - extra information needed
                   9468:        For errors:
                   9469:          - duplicateID   - paper number that this studentID was seen before on
                   9470:          - duplicateCODE - array ref of the paper numbers this CODE was
                   9471:                            seen on before
                   9472:          - incorrectCODE - current incorrect CODE 
                   9473:          - doublebubble  - array ref of the bubble lines that have double
                   9474:                            bubble errors
                   9475:          - missingbubble - array ref of the bubble lines that have missing
                   9476:                            bubble errors
                   9477: 
                   9478: =item  scantron_get_maxbubble() : 
                   9479: 
1.582     raeburn  9480:    Arguments:
                   9481:        $nav_error  - Reference to scalar which is a flag to indicate a
                   9482:                       failure to retrieve a navmap object.
                   9483:        if $nav_error is set to 1 by scantron_get_maxbubble(), the 
                   9484:        calling routine should trap the error condition and display the warning
                   9485:        found in &navmap_errormsg().
                   9486: 
1.531     jms      9487:    Returns the maximum number of bubble lines that are expected to
                   9488:    occur. Does this by walking the selected sequence rendering the
                   9489:    resource and then checking &Apache::lonxml::get_problem_counter()
                   9490:    for what the current value of the problem counter is.
                   9491: 
                   9492:    Caches the results to $env{'form.scantron_maxbubble'},
                   9493:    $env{'form.scantron.bubble_lines.n'}, 
                   9494:    $env{'form.scantron.first_bubble_line.n'} and
                   9495:    $env{"form.scantron.sub_bubblelines.n"}
                   9496:    which are the total number of bubble, lines, the number of bubble
                   9497:    lines for response n and number of the first bubble line for response n,
                   9498:    and a comma separated list of numbers of bubble lines for sub-questions
                   9499:    (for optionresponse, matchresponse, and rankresponse items), for response n.  
                   9500: 
                   9501: 
                   9502: =item  scantron_validate_missingbubbles() : 
                   9503: 
                   9504:    Validates all scanlines in the selected file to not have any
                   9505:     answers that don't have bubbles that have not been verified
                   9506:     to be bubble free.
                   9507: 
                   9508: =item  scantron_process_students() : 
                   9509: 
                   9510:    Routine that does the actual grading of the bubble sheet information.
                   9511: 
                   9512:    The parsed scanline hash is added to %env 
                   9513: 
                   9514:    Then foreach unskipped scanline it does an &Apache::lonnet::ssi()
                   9515:    foreach resource , with the form data of
                   9516: 
                   9517: 	'submitted'     =>'scantron' 
                   9518: 	'grade_target'  =>'grade',
                   9519: 	'grade_username'=> username of student
                   9520: 	'grade_domain'  => domain of student
                   9521: 	'grade_courseid'=> of course
                   9522: 	'grade_symb'    => symb of resource to grade
                   9523: 
                   9524:     This triggers a grading pass. The problem grading code takes care
                   9525:     of converting the bubbled letter information (now in %env) into a
                   9526:     valid submission.
                   9527: 
                   9528: =item  scantron_upload_scantron_data() :
                   9529: 
                   9530:     Creates the screen for adding a new bubble sheet data file to a course.
                   9531: 
                   9532: =item  scantron_upload_scantron_data_save() : 
                   9533: 
                   9534:    Adds a provided bubble information data file to the course if user
                   9535:    has the correct privileges to do so. 
                   9536: 
                   9537: =item  valid_file() :
                   9538: 
                   9539:    Validates that the requested bubble data file exists in the course.
                   9540: 
                   9541: =item  scantron_download_scantron_data() : 
                   9542: 
                   9543:    Shows a list of the three internal files (original, corrected,
                   9544:    skipped) for a specific bubble sheet data file that exists in the
                   9545:    course.
                   9546: 
                   9547: =item  scantron_validate_ID() : 
                   9548: 
                   9549:    Validates all scanlines in the selected file to not have any
1.556     weissno  9550:    invalid or underspecified student/employee IDs
1.531     jms      9551: 
1.582     raeburn  9552: =item navmap_errormsg() :
                   9553: 
                   9554:    Returns HTML mark-up inside a <div></div> with a link to re-initialize the course.
                   9555:    Should be called whenever the request to instantiate a navmap object fails.  
                   9556: 
1.531     jms      9557: =back
                   9558: 
                   9559: =cut

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