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

1.17      albertel    1: # The LearningOnline Network with CAPA
1.13      albertel    2: # The LON-CAPA Grading handler
1.17      albertel    3: #
1.640   ! raeburn     4: # $Id: grades.pm,v 1.639 2010/12/04 15:02:26 www Exp $
1.17      albertel    5: #
                      6: # Copyright Michigan State University Board of Trustees
                      7: #
                      8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
                      9: #
                     10: # LON-CAPA is free software; you can redistribute it and/or modify
                     11: # it under the terms of the GNU General Public License as published by
                     12: # the Free Software Foundation; either version 2 of the License, or
                     13: # (at your option) any later version.
                     14: #
                     15: # LON-CAPA is distributed in the hope that it will be useful,
                     16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
                     17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
                     18: # GNU General Public License for more details.
                     19: #
                     20: # You should have received a copy of the GNU General Public License
                     21: # along with LON-CAPA; if not, write to the Free Software
                     22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
                     23: #
                     24: # /home/httpd/html/adm/gpl.txt
                     25: #
                     26: # http://www.lon-capa.org/
                     27: #
1.1       albertel   28: 
1.529     jms        29: 
                     30: 
1.1       albertel   31: package Apache::grades;
                     32: use strict;
                     33: use Apache::style;
                     34: use Apache::lonxml;
                     35: use Apache::lonnet;
1.3       albertel   36: use Apache::loncommon;
1.112     ng         37: use Apache::lonhtmlcommon;
1.68      ng         38: use Apache::lonnavmaps;
1.1       albertel   39: use Apache::lonhomework;
1.456     banghart   40: use Apache::lonpickcode;
1.55      matthew    41: use Apache::loncoursedata;
1.362     albertel   42: use Apache::lonmsg();
1.1       albertel   43: use Apache::Constants qw(:common);
1.167     sakharuk   44: use Apache::lonlocal;
1.386     raeburn    45: use Apache::lonenc;
1.622     www        46: use Apache::lonstathelpers;
1.639     www        47: use Apache::lonquickgrades;
1.170     albertel   48: use String::Similarity;
1.359     www        49: use LONCAPA;
                     50: 
1.315     bowersj2   51: use POSIX qw(floor);
1.87      www        52: 
1.435     foxr       53: 
1.513     foxr       54: 
1.435     foxr       55: my %perm=();
1.447     foxr       56: 
1.513     foxr       57: #  These variables are used to recover from ssi errors
                     58: 
                     59: my $ssi_retries = 5;
                     60: my $ssi_error;
                     61: my $ssi_error_resource;
                     62: my $ssi_error_message;
                     63: 
                     64: 
                     65: sub ssi_with_retries {
                     66:     my ($resource, $retries, %form) = @_;
                     67:     my ($content, $response) = &Apache::loncommon::ssi_with_retries($resource, $retries, %form);
                     68:     if ($response->is_error) {
                     69: 	$ssi_error          = 1;
                     70: 	$ssi_error_resource = $resource;
                     71: 	$ssi_error_message  = $response->code . " " . $response->message;
                     72:     }
                     73: 
                     74:     return $content;
                     75: 
                     76: }
                     77: #
                     78: #  Prodcuces an ssi retry failure error message to the user:
                     79: #
                     80: 
                     81: sub ssi_print_error {
                     82:     my ($r) = @_;
1.516     raeburn    83:     my $helpurl = &Apache::loncommon::top_nav_help('Helpdesk');
                     84:     $r->print('
                     85: <br />
                     86: <h2>'.&mt('An unrecoverable network error occurred:').'</h2>
                     87: <p>
                     88: '.&mt('Unable to retrieve a resource from a server:').'<br />
                     89: '.&mt('Resource:').' '.$ssi_error_resource.'<br />
                     90: '.&mt('Error:').' '.$ssi_error_message.'
                     91: </p>
                     92: <p>'.
                     93: &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 />'.
                     94: &mt('If the error persists, please contact the [_1] for assistance.',$helpurl).
                     95: '</p>');
                     96:     return;
1.513     foxr       97: }
                     98: 
1.44      ng         99: #
1.146     albertel  100: # --- Retrieve the parts from the metadata file.---
1.598     www       101: # Returns an array of everything that the resources stores away
                    102: #
                    103: 
1.44      ng        104: sub getpartlist {
1.582     raeburn   105:     my ($symb,$errorref) = @_;
1.439     albertel  106: 
                    107:     my $navmap   = Apache::lonnavmaps::navmap->new();
1.582     raeburn   108:     unless (ref($navmap)) {
                    109:         if (ref($errorref)) { 
                    110:             $$errorref = 'navmap';
                    111:             return;
                    112:         }
                    113:     }
1.439     albertel  114:     my $res      = $navmap->getBySymb($symb);
                    115:     my $partlist = $res->parts();
                    116:     my $url      = $res->src();
                    117:     my @metakeys = split(/,/,&Apache::lonnet::metadata($url,'keys'));
                    118: 
1.146     albertel  119:     my @stores;
1.439     albertel  120:     foreach my $part (@{ $partlist }) {
1.146     albertel  121: 	foreach my $key (@metakeys) {
                    122: 	    if ($key =~ m/^stores_\Q$part\E_/) { push(@stores,$key); }
                    123: 	}
                    124:     }
                    125:     return @stores;
1.2       albertel  126: }
                    127: 
1.129     ng        128: #--- Format fullname, username:domain if different for display
                    129: #--- Use anywhere where the student names are listed
                    130: sub nameUserString {
                    131:     my ($type,$fullname,$uname,$udom) = @_;
                    132:     if ($type eq 'header') {
1.485     albertel  133: 	return '<b>&nbsp;'.&mt('Fullname').'&nbsp;</b><span class="LC_internal_info">('.&mt('Username').')</span>';
1.129     ng        134:     } else {
1.398     albertel  135: 	return '&nbsp;'.$fullname.'<span class="LC_internal_info">&nbsp;('.$uname.
                    136: 	    ($env{'user.domain'} eq $udom ? '' : ' ('.$udom.')').')</span>';
1.129     ng        137:     }
                    138: }
                    139: 
1.44      ng        140: #--- Get the partlist and the response type for a given problem. ---
                    141: #--- Indicate if a response type is coded handgraded or not. ---
1.623     www       142: #--- Sets response_error pointer to "1" if navmaps object broken ---
1.39      ng        143: sub response_type {
1.582     raeburn   144:     my ($symb,$response_error) = @_;
1.377     albertel  145: 
                    146:     my $navmap = Apache::lonnavmaps::navmap->new();
1.582     raeburn   147:     unless (ref($navmap)) {
                    148:         if (ref($response_error)) {
                    149:             $$response_error = 1;
                    150:         }
                    151:         return;
                    152:     }
1.377     albertel  153:     my $res = $navmap->getBySymb($symb);
1.593     raeburn   154:     unless (ref($res)) {
                    155:         $$response_error = 1;
                    156:         return;
                    157:     }
1.377     albertel  158:     my $partlist = $res->parts();
1.392     albertel  159:     my %vPart = 
                    160: 	map { $_ => 1 } (&Apache::loncommon::get_env_multiple('form.vPart'));
1.377     albertel  161:     my (%response_types,%handgrade);
                    162:     foreach my $part (@{ $partlist }) {
1.392     albertel  163: 	next if (%vPart && !exists($vPart{$part}));
                    164: 
1.377     albertel  165: 	my @types = $res->responseType($part);
                    166: 	my @ids = $res->responseIds($part);
                    167: 	for (my $i=0; $i < scalar(@ids); $i++) {
                    168: 	    $response_types{$part}{$ids[$i]} = $types[$i];
                    169: 	    $handgrade{$part.'_'.$ids[$i]} = 
                    170: 		&Apache::lonnet::EXT('resource.'.$part.'_'.$ids[$i].
                    171: 				     '.handgrade',$symb);
1.41      ng        172: 	}
                    173:     }
1.377     albertel  174:     return ($partlist,\%handgrade,\%response_types);
1.39      ng        175: }
                    176: 
1.375     albertel  177: sub flatten_responseType {
                    178:     my ($responseType) = @_;
                    179:     my @part_response_id =
                    180: 	map { 
                    181: 	    my $part = $_;
                    182: 	    map {
                    183: 		[$part,$_]
                    184: 		} sort(keys(%{ $responseType->{$part} }));
                    185: 	} sort(keys(%$responseType));
                    186:     return @part_response_id;
                    187: }
                    188: 
1.207     albertel  189: sub get_display_part {
1.324     albertel  190:     my ($partID,$symb)=@_;
1.207     albertel  191:     my $display=&Apache::lonnet::EXT('resource.'.$partID.'.display',$symb);
                    192:     if (defined($display) and $display ne '') {
1.577     bisitz    193:         $display.= ' (<span class="LC_internal_info">'
                    194:                   .&mt('Part ID: [_1]',$partID).'</span>)';
1.207     albertel  195:     } else {
                    196: 	$display=$partID;
                    197:     }
                    198:     return $display;
                    199: }
1.269     raeburn   200: 
1.434     albertel  201: sub reset_caches {
                    202:     &reset_analyze_cache();
                    203:     &reset_perm();
                    204: }
                    205: 
                    206: {
                    207:     my %analyze_cache;
1.557     raeburn   208:     my %analyze_cache_formkeys;
1.148     albertel  209: 
1.434     albertel  210:     sub reset_analyze_cache {
                    211: 	undef(%analyze_cache);
1.557     raeburn   212:         undef(%analyze_cache_formkeys);
1.434     albertel  213:     }
                    214: 
                    215:     sub get_analyze {
1.640   ! raeburn   216: 	my ($symb,$uname,$udom,$no_increment,$add_to_hash,$type,$trial,$rndseed)=@_;
1.434     albertel  217: 	my $key = "$symb\0$uname\0$udom";
1.640   ! raeburn   218:         if ($type eq 'randomizetry') {
        !           219:             if ($trial ne '') {
        !           220:                 $key .= "\0".$trial;
        !           221:             }
        !           222:         }
1.557     raeburn   223: 	if (exists($analyze_cache{$key})) {
                    224:             my $getupdate = 0;
                    225:             if (ref($add_to_hash) eq 'HASH') {
                    226:                 foreach my $item (keys(%{$add_to_hash})) {
                    227:                     if (ref($analyze_cache_formkeys{$key}) eq 'HASH') {
                    228:                         if (!exists($analyze_cache_formkeys{$key}{$item})) {
                    229:                             $getupdate = 1;
                    230:                             last;
                    231:                         }
                    232:                     } else {
                    233:                         $getupdate = 1;
                    234:                     }
                    235:                 }
                    236:             }
                    237:             if (!$getupdate) {
                    238:                 return $analyze_cache{$key};
                    239:             }
                    240:         }
1.434     albertel  241: 
                    242: 	my (undef,undef,$url)=&Apache::lonnet::decode_symb($symb);
                    243: 	$url=&Apache::lonnet::clutter($url);
1.557     raeburn   244:         my %form = ('grade_target'      => 'analyze',
                    245:                     'grade_domain'      => $udom,
                    246:                     'grade_symb'        => $symb,
                    247:                     'grade_courseid'    =>  $env{'request.course.id'},
                    248:                     'grade_username'    => $uname,
                    249:                     'grade_noincrement' => $no_increment);
1.640   ! raeburn   250:         if ($type eq 'randomizetry') {
        !           251:             $form{'grade_questiontype'} = $type;
        !           252:             if ($rndseed ne '') {
        !           253:                 $form{'grade_rndseed'} = $rndseed;
        !           254:             }
        !           255:         }
1.557     raeburn   256:         if (ref($add_to_hash)) {
                    257:             %form = (%form,%{$add_to_hash});
1.640   ! raeburn   258:         }
1.557     raeburn   259: 	my $subresult=&ssi_with_retries($url, $ssi_retries,%form);
1.434     albertel  260: 	(undef,$subresult)=split(/_HASH_REF__/,$subresult,2);
                    261: 	my %analyze=&Apache::lonnet::str2hash($subresult);
1.557     raeburn   262:         if (ref($add_to_hash) eq 'HASH') {
                    263:             $analyze_cache_formkeys{$key} = $add_to_hash;
                    264:         } else {
                    265:             $analyze_cache_formkeys{$key} = {};
                    266:         }
1.434     albertel  267: 	return $analyze_cache{$key} = \%analyze;
                    268:     }
                    269: 
                    270:     sub get_order {
1.640   ! raeburn   271: 	my ($partid,$respid,$symb,$uname,$udom,$no_increment,$type,$trial,$rndseed)=@_;
        !           272: 	my $analyze = &get_analyze($symb,$uname,$udom,$no_increment,undef,$type,$trial,$rndseed);
1.434     albertel  273: 	return $analyze->{"$partid.$respid.shown"};
                    274:     }
                    275: 
                    276:     sub get_radiobutton_correct_foil {
1.640   ! raeburn   277: 	my ($partid,$respid,$symb,$uname,$udom,$type,$trial,$rndseed)=@_;
        !           278: 	my $analyze = &get_analyze($symb,$uname,$udom,undef,undef,$type,$trial,$rndseed);
        !           279:         my $foils = &get_order($partid,$respid,$symb,$uname,$udom,undef,$type,$trial,$rndseed);
1.555     raeburn   280:         if (ref($foils) eq 'ARRAY') {
                    281: 	    foreach my $foil (@{$foils}) {
                    282: 	        if ($analyze->{"$partid.$respid.foil.value.$foil"} eq 'true') {
                    283: 		    return $foil;
                    284: 	        }
1.434     albertel  285: 	    }
                    286: 	}
                    287:     }
1.554     raeburn   288: 
                    289:     sub scantron_partids_tograde {
1.557     raeburn   290:         my ($resource,$cid,$uname,$udom,$check_for_randomlist) = @_;
1.554     raeburn   291:         my (%analysis,@parts);
                    292:         if (ref($resource)) {
                    293:             my $symb = $resource->symb();
1.557     raeburn   294:             my $add_to_form;
                    295:             if ($check_for_randomlist) {
                    296:                 $add_to_form = { 'check_parts_withrandomlist' => 1,};
                    297:             }
                    298:             my $analyze = &get_analyze($symb,$uname,$udom,undef,$add_to_form);
1.554     raeburn   299:             if (ref($analyze) eq 'HASH') {
                    300:                 %analysis = %{$analyze};
                    301:             }
                    302:             if (ref($analysis{'parts'}) eq 'ARRAY') {
                    303:                 foreach my $part (@{$analysis{'parts'}}) {
                    304:                     my ($id,$respid) = split(/\./,$part);
                    305:                     if (!&Apache::loncommon::check_if_partid_hidden($id,$symb,$udom,$uname)) {
                    306:                         push(@parts,$part);
                    307:                     }
                    308:                 }
                    309:             }
                    310:         }
                    311:         return (\%analysis,\@parts);
                    312:     }
                    313: 
1.148     albertel  314: }
1.434     albertel  315: 
1.118     ng        316: #--- Clean response type for display
1.335     albertel  317: #--- Currently filters option/rank/radiobutton/match/essay/Task
                    318: #        response types only.
1.118     ng        319: sub cleanRecord {
1.336     albertel  320:     my ($answer,$response,$symb,$partid,$respid,$record,$order,$version,
1.640   ! raeburn   321: 	$uname,$udom,$type,$trial,$rndseed) = @_;
1.398     albertel  322:     my $grayFont = '<span class="LC_internal_info">';
1.148     albertel  323:     if ($response =~ /^(option|rank)$/) {
                    324: 	my %answer=&Apache::lonnet::str2hash($answer);
                    325: 	my %grading=&Apache::lonnet::str2hash($record->{$version."resource.$partid.$respid.submissiongrading"});
                    326: 	my ($toprow,$bottomrow);
                    327: 	foreach my $foil (@$order) {
                    328: 	    if ($grading{$foil} == 1) {
                    329: 		$toprow.='<td><b>'.$answer{$foil}.'&nbsp;</b></td>';
                    330: 	    } else {
                    331: 		$toprow.='<td><i>'.$answer{$foil}.'&nbsp;</i></td>';
                    332: 	    }
1.398     albertel  333: 	    $bottomrow.='<td>'.$grayFont.$foil.'</span>&nbsp;</td>';
1.148     albertel  334: 	}
                    335: 	return '<blockquote><table border="1">'.
1.466     albertel  336: 	    '<tr valign="top"><td>'.&mt('Answer').'</td>'.$toprow.'</tr>'.
                    337: 	    '<tr valign="top"><td>'.$grayFont.&mt('Option ID').'</span></td>'.
1.148     albertel  338: 	    $grayFont.$bottomrow.'</tr>'.'</table></blockquote>';
                    339:     } elsif ($response eq 'match') {
                    340: 	my %answer=&Apache::lonnet::str2hash($answer);
                    341: 	my %grading=&Apache::lonnet::str2hash($record->{$version."resource.$partid.$respid.submissiongrading"});
                    342: 	my @items=&Apache::lonnet::str2array($record->{$version."resource.$partid.$respid.submissionitems"});
                    343: 	my ($toprow,$middlerow,$bottomrow);
                    344: 	foreach my $foil (@$order) {
                    345: 	    my $item=shift(@items);
                    346: 	    if ($grading{$foil} == 1) {
                    347: 		$toprow.='<td><b>'.$item.'&nbsp;</b></td>';
1.398     albertel  348: 		$middlerow.='<td><b>'.$grayFont.$answer{$foil}.'&nbsp;</span></b></td>';
1.148     albertel  349: 	    } else {
                    350: 		$toprow.='<td><i>'.$item.'&nbsp;</i></td>';
1.398     albertel  351: 		$middlerow.='<td><i>'.$grayFont.$answer{$foil}.'&nbsp;</span></i></td>';
1.148     albertel  352: 	    }
1.398     albertel  353: 	    $bottomrow.='<td>'.$grayFont.$foil.'</span>&nbsp;</td>';
1.118     ng        354: 	}
1.126     ng        355: 	return '<blockquote><table border="1">'.
1.466     albertel  356: 	    '<tr valign="top"><td>'.&mt('Answer').'</td>'.$toprow.'</tr>'.
                    357: 	    '<tr valign="top"><td>'.$grayFont.&mt('Item ID').'</span></td>'.
1.148     albertel  358: 	    $middlerow.'</tr>'.
1.466     albertel  359: 	    '<tr valign="top"><td>'.$grayFont.&mt('Option ID').'</span></td>'.
1.148     albertel  360: 	    $bottomrow.'</tr>'.'</table></blockquote>';
                    361:     } elsif ($response eq 'radiobutton') {
                    362: 	my %answer=&Apache::lonnet::str2hash($answer);
                    363: 	my ($toprow,$bottomrow);
1.434     albertel  364: 	my $correct = 
1.640   ! raeburn   365: 	    &get_radiobutton_correct_foil($partid,$respid,$symb,$uname,$udom,$type,$trial,$rndseed);
1.434     albertel  366: 	foreach my $foil (@$order) {
1.148     albertel  367: 	    if (exists($answer{$foil})) {
1.434     albertel  368: 		if ($foil eq $correct) {
1.466     albertel  369: 		    $toprow.='<td><b>'.&mt('true').'</b></td>';
1.148     albertel  370: 		} else {
1.466     albertel  371: 		    $toprow.='<td><i>'.&mt('true').'</i></td>';
1.148     albertel  372: 		}
                    373: 	    } else {
1.466     albertel  374: 		$toprow.='<td>'.&mt('false').'</td>';
1.148     albertel  375: 	    }
1.398     albertel  376: 	    $bottomrow.='<td>'.$grayFont.$foil.'</span>&nbsp;</td>';
1.148     albertel  377: 	}
                    378: 	return '<blockquote><table border="1">'.
1.466     albertel  379: 	    '<tr valign="top"><td>'.&mt('Answer').'</td>'.$toprow.'</tr>'.
                    380: 	    '<tr valign="top"><td>'.$grayFont.&mt('Option ID').'</span></td>'.
1.597     wenzelju  381: 	    $bottomrow.'</tr>'.'</table></blockquote>';
1.148     albertel  382:     } elsif ($response eq 'essay') {
1.257     albertel  383: 	if (! exists ($env{'form.'.$symb})) {
1.122     ng        384: 	    my (%keyhash) = &Apache::lonnet::dump('nohist_handgrade',
1.257     albertel  385: 						  $env{'course.'.$env{'request.course.id'}.'.domain'},
                    386: 						  $env{'course.'.$env{'request.course.id'}.'.num'});
1.122     ng        387: 
1.257     albertel  388: 	    my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
                    389: 	    $env{'form.keywords'} = $keyhash{$symb.'_keywords'} ne '' ? $keyhash{$symb.'_keywords'} : '';
                    390: 	    $env{'form.kwclr'}    = $keyhash{$loginuser.'_kwclr'} ne '' ? $keyhash{$loginuser.'_kwclr'} : 'red';
                    391: 	    $env{'form.kwsize'}   = $keyhash{$loginuser.'_kwsize'} ne '' ? $keyhash{$loginuser.'_kwsize'} : '0';
                    392: 	    $env{'form.kwstyle'}  = $keyhash{$loginuser.'_kwstyle'} ne '' ? $keyhash{$loginuser.'_kwstyle'} : '';
                    393: 	    $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        394: 	}
1.166     albertel  395: 	$answer =~ s-\n-<br />-g;
                    396: 	return '<br /><br /><blockquote><tt>'.&keywords_highlight($answer).'</tt></blockquote>';
1.268     albertel  397:     } elsif ( $response eq 'organic') {
                    398: 	my $result='Smile representation: "<tt>'.$answer.'</tt>"';
                    399: 	my $jme=$record->{$version."resource.$partid.$respid.molecule"};
                    400: 	$result.=&Apache::chemresponse::jme_img($jme,$answer,400);
                    401: 	return $result;
1.335     albertel  402:     } elsif ( $response eq 'Task') {
                    403: 	if ( $answer eq 'SUBMITTED') {
                    404: 	    my $files = $record->{$version."resource.$respid.$partid.bridgetask.portfiles"};
1.336     albertel  405: 	    my $result = &Apache::bridgetask::file_list($files,$uname,$udom);
1.335     albertel  406: 	    return $result;
                    407: 	} elsif ( grep(/^\Q$version\E.*?\.instance$/, keys(%{$record})) ) {
                    408: 	    my @matches = grep(/^\Q$version\E.*?\.instance$/,
                    409: 			       keys(%{$record}));
                    410: 	    return join('<br />',($version,@matches));
                    411: 			       
                    412: 			       
                    413: 	} else {
                    414: 	    my $result =
                    415: 		'<p>'
                    416: 		.&mt('Overall result: [_1]',
                    417: 		     $record->{$version."resource.$respid.$partid.status"})
                    418: 		.'</p>';
                    419: 	    
                    420: 	    $result .= '<ul>';
                    421: 	    my @grade = grep(/^\Q${version}resource.$respid.$partid.\E[^.]*[.]status$/,
                    422: 			     keys(%{$record}));
                    423: 	    foreach my $grade (sort(@grade)) {
                    424: 		my ($dim) = ($grade =~/[.]([^.]+)[.]status$/);
                    425: 		$result.= '<li>'.&mt("Dimension: [_1], status [_2] ",
                    426: 				     $dim, $record->{$grade}).
                    427: 			  '</li>';
                    428: 	    }
                    429: 	    $result.='</ul>';
                    430: 	    return $result;
                    431: 	}
1.440     albertel  432:     } elsif ( $response =~ m/(?:numerical|formula)/) {
                    433: 	$answer = 
                    434: 	    &Apache::loncommon::format_previous_attempt_value('submission',
                    435: 							      $answer);
1.122     ng        436:     }
1.118     ng        437:     return $answer;
                    438: }
                    439: 
                    440: #-- A couple of common js functions
                    441: sub commonJSfunctions {
                    442:     my $request = shift;
1.597     wenzelju  443:     $request->print(&Apache::lonhtmlcommon::scripttag(<<COMMONJSFUNCTIONS));
1.118     ng        444:     function radioSelection(radioButton) {
                    445: 	var selection=null;
                    446: 	if (radioButton.length > 1) {
                    447: 	    for (var i=0; i<radioButton.length; i++) {
                    448: 		if (radioButton[i].checked) {
                    449: 		    return radioButton[i].value;
                    450: 		}
                    451: 	    }
                    452: 	} else {
                    453: 	    if (radioButton.checked) return radioButton.value;
                    454: 	}
                    455: 	return selection;
                    456:     }
                    457: 
                    458:     function pullDownSelection(selectOne) {
                    459: 	var selection="";
                    460: 	if (selectOne.length > 1) {
                    461: 	    for (var i=0; i<selectOne.length; i++) {
                    462: 		if (selectOne[i].selected) {
                    463: 		    return selectOne[i].value;
                    464: 		}
                    465: 	    }
                    466: 	} else {
1.138     albertel  467:             // only one value it must be the selected one
                    468: 	    return selectOne.value;
1.118     ng        469: 	}
                    470:     }
                    471: COMMONJSFUNCTIONS
                    472: }
                    473: 
1.44      ng        474: #--- Dumps the class list with usernames,list of sections,
                    475: #--- section, ids and fullnames for each user.
                    476: sub getclasslist {
1.449     banghart  477:     my ($getsec,$filterlist,$getgroup) = @_;
1.291     albertel  478:     my @getsec;
1.450     banghart  479:     my @getgroup;
1.442     banghart  480:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
1.291     albertel  481:     if (!ref($getsec)) {
                    482: 	if ($getsec ne '' && $getsec ne 'all') {
                    483: 	    @getsec=($getsec);
                    484: 	}
                    485:     } else {
                    486: 	@getsec=@{$getsec};
                    487:     }
                    488:     if (grep(/^all$/,@getsec)) { undef(@getsec); }
1.450     banghart  489:     if (!ref($getgroup)) {
                    490: 	if ($getgroup ne '' && $getgroup ne 'all') {
                    491: 	    @getgroup=($getgroup);
                    492: 	}
                    493:     } else {
                    494: 	@getgroup=@{$getgroup};
                    495:     }
                    496:     if (grep(/^all$/,@getgroup)) { undef(@getgroup); }
1.291     albertel  497: 
1.449     banghart  498:     my ($classlist,$keylist)=&Apache::loncoursedata::get_classlist();
1.49      albertel  499:     # Bail out if we were unable to get the classlist
1.56      matthew   500:     return if (! defined($classlist));
1.449     banghart  501:     &Apache::loncoursedata::get_group_memberships($classlist,$keylist);
1.56      matthew   502:     #
                    503:     my %sections;
                    504:     my %fullnames;
1.205     matthew   505:     foreach my $student (keys(%$classlist)) {
                    506:         my $end      = 
                    507:             $classlist->{$student}->[&Apache::loncoursedata::CL_END()];
                    508:         my $start    = 
                    509:             $classlist->{$student}->[&Apache::loncoursedata::CL_START()];
                    510:         my $id       = 
                    511:             $classlist->{$student}->[&Apache::loncoursedata::CL_ID()];
                    512:         my $section  = 
                    513:             $classlist->{$student}->[&Apache::loncoursedata::CL_SECTION()];
                    514:         my $fullname = 
                    515:             $classlist->{$student}->[&Apache::loncoursedata::CL_FULLNAME()];
                    516:         my $status   = 
                    517:             $classlist->{$student}->[&Apache::loncoursedata::CL_STATUS()];
1.449     banghart  518:         my $group   = 
                    519:             $classlist->{$student}->[&Apache::loncoursedata::CL_GROUP()];
1.76      ng        520: 	# filter students according to status selected
1.442     banghart  521: 	if ($filterlist && (!($stu_status =~ /Any/))) {
                    522: 	    if (!($stu_status =~ $status)) {
1.450     banghart  523: 		delete($classlist->{$student});
1.76      ng        524: 		next;
                    525: 	    }
                    526: 	}
1.450     banghart  527: 	# filter students according to groups selected
1.453     banghart  528: 	my @stu_groups = split(/,/,$group);
1.450     banghart  529: 	if (@getgroup) {
                    530: 	    my $exclude = 1;
1.454     banghart  531: 	    foreach my $grp (@getgroup) {
                    532: 	        foreach my $stu_group (@stu_groups) {
1.453     banghart  533: 	            if ($stu_group eq $grp) {
                    534: 	                $exclude = 0;
                    535:     	            } 
1.450     banghart  536: 	        }
1.453     banghart  537:     	        if (($grp eq 'none') && !$group) {
                    538:         	        $exclude = 0;
                    539:         	}
1.450     banghart  540: 	    }
                    541: 	    if ($exclude) {
                    542: 	        delete($classlist->{$student});
                    543: 	    }
                    544: 	}
1.205     matthew   545: 	$section = ($section ne '' ? $section : 'none');
1.106     albertel  546: 	if (&canview($section)) {
1.291     albertel  547: 	    if (!@getsec || grep(/^\Q$section\E$/,@getsec)) {
1.103     albertel  548: 		$sections{$section}++;
1.450     banghart  549: 		if ($classlist->{$student}) {
                    550: 		    $fullnames{$student}=$fullname;
                    551: 		}
1.103     albertel  552: 	    } else {
1.205     matthew   553: 		delete($classlist->{$student});
1.103     albertel  554: 	    }
                    555: 	} else {
1.205     matthew   556: 	    delete($classlist->{$student});
1.103     albertel  557: 	}
1.44      ng        558:     }
                    559:     my %seen = ();
1.56      matthew   560:     my @sections = sort(keys(%sections));
                    561:     return ($classlist,\@sections,\%fullnames);
1.44      ng        562: }
                    563: 
1.103     albertel  564: sub canmodify {
                    565:     my ($sec)=@_;
                    566:     if ($perm{'mgr'}) {
                    567: 	if (!defined($perm{'mgr_section'})) {
                    568: 	    # can modify whole class
                    569: 	    return 1;
                    570: 	} else {
                    571: 	    if ($sec eq $perm{'mgr_section'}) {
                    572: 		#can modify the requested section
                    573: 		return 1;
                    574: 	    } else {
                    575: 		# can't modify the request section
                    576: 		return 0;
                    577: 	    }
                    578: 	}
                    579:     }
                    580:     #can't modify
                    581:     return 0;
                    582: }
                    583: 
                    584: sub canview {
                    585:     my ($sec)=@_;
                    586:     if ($perm{'vgr'}) {
                    587: 	if (!defined($perm{'vgr_section'})) {
                    588: 	    # can modify whole class
                    589: 	    return 1;
                    590: 	} else {
                    591: 	    if ($sec eq $perm{'vgr_section'}) {
                    592: 		#can modify the requested section
                    593: 		return 1;
                    594: 	    } else {
                    595: 		# can't modify the request section
                    596: 		return 0;
                    597: 	    }
                    598: 	}
                    599:     }
                    600:     #can't modify
                    601:     return 0;
                    602: }
                    603: 
1.44      ng        604: #--- Retrieve the grade status of a student for all the parts
                    605: sub student_gradeStatus {
1.324     albertel  606:     my ($symb,$udom,$uname,$partlist) = @_;
1.257     albertel  607:     my %record     = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
1.44      ng        608:     my %partstatus = ();
                    609:     foreach (@$partlist) {
1.128     ng        610: 	my ($status,undef)   = split(/_/,$record{"resource.$_.solved"},2);
1.44      ng        611: 	$status              = 'nothing' if ($status eq '');
                    612: 	$partstatus{$_}      = $status;
                    613: 	my $subkey           = "resource.$_.submitted_by";
                    614: 	$partstatus{$subkey} = $record{$subkey} if ($record{$subkey} ne '');
                    615:     }
                    616:     return %partstatus;
                    617: }
                    618: 
1.45      ng        619: # hidden form and javascript that calls the form
                    620: # Use by verifyscript and viewgrades
                    621: # Shows a student's view of problem and submission
                    622: sub jscriptNform {
1.324     albertel  623:     my ($symb) = @_;
1.442     banghart  624:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
1.597     wenzelju  625:     my $jscript= &Apache::lonhtmlcommon::scripttag(
1.45      ng        626: 	'    function viewOneStudent(user,domain) {'."\n".
                    627: 	'	document.onestudent.student.value = user;'."\n".
                    628: 	'	document.onestudent.userdom.value = domain;'."\n".
                    629: 	'	document.onestudent.submit();'."\n".
                    630: 	'    }'."\n".
1.597     wenzelju  631: 	"\n");
1.45      ng        632:     $jscript.= '<form action="/adm/grades" method="post" name="onestudent">'."\n".
1.418     albertel  633: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.442     banghart  634: 	'<input type="hidden" name="Status"  value="'.$stu_status.'" />'."\n".
1.45      ng        635: 	'<input type="hidden" name="command" value="submission" />'."\n".
                    636: 	'<input type="hidden" name="student" value="" />'."\n".
                    637: 	'<input type="hidden" name="userdom" value="" />'."\n".
                    638: 	'</form>'."\n";
                    639:     return $jscript;
                    640: }
1.39      ng        641: 
1.447     foxr      642: 
                    643: 
1.315     bowersj2  644: # Given the score (as a number [0-1] and the weight) what is the final
                    645: # point value? This function will round to the nearest tenth, third,
                    646: # or quarter if one of those is within the tolerance of .00001.
1.316     albertel  647: sub compute_points {
1.315     bowersj2  648:     my ($score, $weight) = @_;
                    649:     
                    650:     my $tolerance = .00001;
                    651:     my $points = $score * $weight;
                    652: 
                    653:     # Check for nearness to 1/x.
                    654:     my $check_for_nearness = sub {
                    655:         my ($factor) = @_;
                    656:         my $num = ($points * $factor) + $tolerance;
                    657:         my $floored_num = floor($num);
1.316     albertel  658:         if ($num - $floored_num < 2 * $tolerance * $factor) {
1.315     bowersj2  659:             return $floored_num / $factor;
                    660:         }
                    661:         return $points;
                    662:     };
                    663: 
                    664:     $points = $check_for_nearness->(10);
                    665:     $points = $check_for_nearness->(3);
                    666:     $points = $check_for_nearness->(4);
                    667:     
                    668:     return $points;
                    669: }
                    670: 
1.44      ng        671: #------------------ End of general use routines --------------------
1.87      www       672: 
                    673: #
                    674: # Find most similar essay
                    675: #
                    676: 
                    677: sub most_similar {
1.426     albertel  678:     my ($uname,$udom,$uessay,$old_essays)=@_;
1.87      www       679: 
                    680: # ignore spaces and punctuation
                    681: 
                    682:     $uessay=~s/\W+/ /gs;
                    683: 
1.282     www       684: # ignore empty submissions (occuring when only files are sent)
                    685: 
1.598     www       686:     unless ($uessay=~/\w+/s) { return ''; }
1.282     www       687: 
1.87      www       688: # these will be returned. Do not care if not at least 50 percent similar
1.88      www       689:     my $limit=0.6;
1.87      www       690:     my $sname='';
                    691:     my $sdom='';
                    692:     my $scrsid='';
                    693:     my $sessay='';
                    694: # go through all essays ...
1.426     albertel  695:     foreach my $tkey (keys(%$old_essays)) {
                    696: 	my ($tname,$tdom,$tcrsid)=map {&unescape($_)} (split(/\./,$tkey));
1.87      www       697: # ... except the same student
1.426     albertel  698:         next if (($tname eq $uname) && ($tdom eq $udom));
                    699: 	my $tessay=$old_essays->{$tkey};
                    700: 	$tessay=~s/\W+/ /gs;
1.87      www       701: # String similarity gives up if not even limit
1.426     albertel  702: 	my $tsimilar=&String::Similarity::similarity($uessay,$tessay,$limit);
1.87      www       703: # Found one
1.426     albertel  704: 	if ($tsimilar>$limit) {
                    705: 	    $limit=$tsimilar;
                    706: 	    $sname=$tname;
                    707: 	    $sdom=$tdom;
                    708: 	    $scrsid=$tcrsid;
                    709: 	    $sessay=$old_essays->{$tkey};
                    710: 	}
1.87      www       711:     }
1.88      www       712:     if ($limit>0.6) {
1.87      www       713:        return ($sname,$sdom,$scrsid,$sessay,$limit);
                    714:     } else {
                    715:        return ('','','','',0);
                    716:     }
                    717: }
                    718: 
1.44      ng        719: #-------------------------------------------------------------------
                    720: 
                    721: #------------------------------------ Receipt Verification Routines
1.45      ng        722: #
1.602     www       723: 
                    724: sub initialverifyreceipt {
1.608     www       725:    my ($request,$symb) = @_;
1.602     www       726:    &commonJSfunctions($request);
1.605     www       727:    return '<form name="gradingMenu"><input type="submit" value="'.&mt('Verify Receipt Number.').'" />'.
1.602     www       728:         &Apache::lonnet::recprefix($env{'request.course.id'}).
                    729:         '-<input type="text" name="receipt" size="4" />'.
1.603     www       730:         '<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
                    731:         '<input type="hidden" name="command" value="verify" />'.
                    732:         "</form>\n";
1.602     www       733: }
                    734: 
1.44      ng        735: #--- Check whether a receipt number is valid.---
                    736: sub verifyreceipt {
1.608     www       737:     my ($request,$symb)  = @_;
1.44      ng        738: 
1.257     albertel  739:     my $courseid = $env{'request.course.id'};
1.184     www       740:     my $receipt  = &Apache::lonnet::recprefix($courseid).'-'.
1.257     albertel  741: 	$env{'form.receipt'};
1.44      ng        742:     $receipt     =~ s/[^\-\d]//g;
                    743: 
1.487     albertel  744:     my $title.=
                    745: 	'<h3><span class="LC_info">'.
1.605     www       746: 	&mt('Verifying Receipt Number [_1]',$receipt).
                    747: 	'</span></h3>'."\n";
1.44      ng        748: 
                    749:     my ($string,$contents,$matches) = ('','',0);
1.56      matthew   750:     my (undef,undef,$fullname) = &getclasslist('all','0');
1.177     albertel  751:     
                    752:     my $receiptparts=0;
1.390     albertel  753:     if ($env{"course.$courseid.receiptalg"} eq 'receipt2' ||
                    754: 	$env{"course.$courseid.receiptalg"} eq 'receipt3') { $receiptparts=1; }
1.177     albertel  755:     my $parts=['0'];
1.582     raeburn   756:     if ($receiptparts) {
                    757:         my $res_error; 
                    758:         ($parts)=&response_type($symb,\$res_error);
                    759:         if ($res_error) {
                    760:             return &navmap_errormsg();
                    761:         } 
                    762:     }
1.486     albertel  763:     
                    764:     my $header = 
                    765: 	&Apache::loncommon::start_data_table().
                    766: 	&Apache::loncommon::start_data_table_header_row().
1.487     albertel  767: 	'<th>&nbsp;'.&mt('Fullname').'&nbsp;</th>'."\n".
                    768: 	'<th>&nbsp;'.&mt('Username').'&nbsp;</th>'."\n".
                    769: 	'<th>&nbsp;'.&mt('Domain').'&nbsp;</th>';
1.486     albertel  770:     if ($receiptparts) {
1.487     albertel  771: 	$header.='<th>&nbsp;'.&mt('Problem Part').'&nbsp;</th>';
1.486     albertel  772:     }
                    773:     $header.=
                    774: 	&Apache::loncommon::end_data_table_header_row();
                    775: 
1.294     albertel  776:     foreach (sort 
                    777: 	     {
                    778: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                    779: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                    780: 		 }
                    781: 		 return $a cmp $b;
                    782: 	     } (keys(%$fullname))) {
1.44      ng        783: 	my ($uname,$udom)=split(/\:/);
1.177     albertel  784: 	foreach my $part (@$parts) {
                    785: 	    if ($receipt eq &Apache::lonnet::ireceipt($uname,$udom,$courseid,$symb,$part)) {
1.486     albertel  786: 		$contents.=
                    787: 		    &Apache::loncommon::start_data_table_row().
                    788: 		    '<td>&nbsp;'."\n".
1.177     albertel  789: 		    '<a href="javascript:viewOneStudent(\''.$uname.'\',\''.$udom.
1.417     albertel  790: 		    '\');" target="_self">'.$$fullname{$_}.'</a>&nbsp;</td>'."\n".
1.177     albertel  791: 		    '<td>&nbsp;'.$uname.'&nbsp;</td>'.
                    792: 		    '<td>&nbsp;'.$udom.'&nbsp;</td>';
                    793: 		if ($receiptparts) {
                    794: 		    $contents.='<td>&nbsp;'.$part.'&nbsp;</td>';
                    795: 		}
1.486     albertel  796: 		$contents.= 
                    797: 		    &Apache::loncommon::end_data_table_row()."\n";
1.177     albertel  798: 		
                    799: 		$matches++;
                    800: 	    }
1.44      ng        801: 	}
                    802:     }
                    803:     if ($matches == 0) {
1.584     bisitz    804:         $string = $title
                    805:                  .'<p class="LC_warning">'
                    806:                  .&mt('No match found for the above receipt number.')
                    807:                  .'</p>';
1.44      ng        808:     } else {
1.324     albertel  809: 	$string = &jscriptNform($symb).$title.
1.487     albertel  810: 	    '<p>'.
1.584     bisitz    811: 	    &mt('The above receipt number matches the following [quant,_1,student].',$matches).
1.487     albertel  812: 	    '</p>'.
1.486     albertel  813: 	    $header.
                    814: 	    $contents.
                    815: 	    &Apache::loncommon::end_data_table()."\n";
1.44      ng        816:     }
1.614     www       817:     return $string;
1.44      ng        818: }
                    819: 
                    820: #--- This is called by a number of programs.
                    821: #--- Called from the Grading Menu - View/Grade an individual student
                    822: #--- Also called directly when one clicks on the subm button 
                    823: #    on the problem page.
1.30      ng        824: sub listStudents {
1.617     www       825:     my ($request,$symb,$submitonly) = @_;
1.49      albertel  826: 
1.257     albertel  827:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
                    828:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
                    829:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
1.449     banghart  830:     my $getgroup  = $env{'form.group'} eq '' ? 'all' : $env{'form.group'};
1.617     www       831:     unless ($submitonly) {
                    832:        $submitonly= $env{'form.submitonly'} eq '' ? 'all' : $env{'form.submitonly'};
                    833:     }
1.49      albertel  834: 
1.632     www       835:     my $result='';
1.623     www       836:     my $res_error;
                    837:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
1.49      albertel  838: 
1.559     raeburn   839:     my %lt = &Apache::lonlocal::texthash (
                    840: 		'multiple' => 'Please select a student or group of students before clicking on the Next button.',
                    841: 		'single'   => 'Please select the student before clicking on the Next button.',
                    842: 	     );
1.597     wenzelju  843:     $request->print(&Apache::lonhtmlcommon::scripttag(<<LISTJAVASCRIPT));
1.110     ng        844:     function checkSelect(checkBox) {
                    845: 	var ctr=0;
                    846: 	var sense="";
                    847: 	if (checkBox.length > 1) {
                    848: 	    for (var i=0; i<checkBox.length; i++) {
                    849: 		if (checkBox[i].checked) {
                    850: 		    ctr++;
                    851: 		}
                    852: 	    }
1.485     albertel  853: 	    sense = '$lt{'multiple'}';
1.110     ng        854: 	} else {
                    855: 	    if (checkBox.checked) {
                    856: 		ctr = 1;
                    857: 	    }
1.485     albertel  858: 	    sense = '$lt{'single'}';
1.110     ng        859: 	}
                    860: 	if (ctr == 0) {
1.485     albertel  861: 	    alert(sense);
1.110     ng        862: 	    return false;
                    863: 	}
                    864: 	document.gradesub.submit();
                    865:     }
                    866: 
                    867:     function reLoadList(formname) {
1.112     ng        868: 	if (formname.saveStatusOld.value == pullDownSelection(formname.Status)) {return;}
1.110     ng        869: 	formname.command.value = 'submission';
                    870: 	formname.submit();
                    871:     }
1.45      ng        872: LISTJAVASCRIPT
                    873: 
1.118     ng        874:     &commonJSfunctions($request);
1.41      ng        875:     $request->print($result);
1.39      ng        876: 
1.154     albertel  877:     my $gradeTable='<form action="/adm/grades" method="post" name="gradesub">'.
1.598     www       878: 	"\n";
1.485     albertel  879: 	
1.561     bisitz    880:     $gradeTable .= &Apache::lonhtmlcommon::start_pick_box();
                    881:     $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('View Problem Text'))
                    882:                   .'<label><input type="radio" name="vProb" value="no" checked="checked" /> '.&mt('no').' </label>'."\n"
                    883:                   .'<label><input type="radio" name="vProb" value="yes" /> '.&mt('one student').' </label>'."\n"
                    884:                   .'<label><input type="radio" name="vProb" value="all" /> '.&mt('all students').' </label><br />'."\n"
                    885:                   .&Apache::lonhtmlcommon::row_closure();
                    886:     $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('View Answer'))
                    887:                   .'<label><input type="radio" name="vAns" value="no"  /> '.&mt('no').' </label>'."\n"
                    888:                   .'<label><input type="radio" name="vAns" value="yes" /> '.&mt('one student').' </label>'."\n"
                    889:                   .'<label><input type="radio" name="vAns" value="all" checked="checked" /> '.&mt('all students').' </label><br />'."\n"
                    890:                   .&Apache::lonhtmlcommon::row_closure();
1.485     albertel  891: 
                    892:     my $submission_options;
1.442     banghart  893:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
                    894:     my $saveStatus = $stu_status eq '' ? 'Active' : $stu_status;
1.257     albertel  895:     $env{'form.Status'} = $saveStatus;
1.485     albertel  896:     $submission_options.=
1.592     bisitz    897:         '<span class="LC_nobreak">'.
1.624     www       898:         '<label><input type="radio" name="lastSub" value="lastonly" /> '.
1.592     bisitz    899:         &mt('last submission only').' </label></span>'."\n".
                    900:         '<span class="LC_nobreak">'.
                    901:         '<label><input type="radio" name="lastSub" value="last" /> '.
                    902:         &mt('last submission &amp; parts info').' </label></span>'."\n".
                    903:         '<span class="LC_nobreak">'.
1.628     www       904:         '<label><input type="radio" name="lastSub" value="datesub" checked="checked" /> '.
1.592     bisitz    905:         &mt('by dates and submissions').'</label></span>'."\n".
                    906:         '<span class="LC_nobreak">'.
                    907:         '<label><input type="radio" name="lastSub" value="all" /> '.
                    908:         &mt('all details').'</label></span>';
1.561     bisitz    909:     $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('Submissions'))
                    910:                   .$submission_options
                    911:                   .&Apache::lonhtmlcommon::row_closure();
                    912: 
                    913:     $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('Grading Increments'))
                    914:                   .'<select name="increment">'
                    915:                   .'<option value="1">'.&mt('Whole Points').'</option>'
                    916:                   .'<option value=".5">'.&mt('Half Points').'</option>'
                    917:                   .'<option value=".25">'.&mt('Quarter Points').'</option>'
                    918:                   .'<option value=".1">'.&mt('Tenths of a Point').'</option>'
                    919:                   .'</select>'
                    920:                   .&Apache::lonhtmlcommon::row_closure();
1.485     albertel  921: 
                    922:     $gradeTable .= 
1.432     banghart  923:         &build_section_inputs().
1.45      ng        924: 	'<input type="hidden" name="submitonly"  value="'.$submitonly.'" />'."\n".
1.418     albertel  925: 	'<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.110     ng        926: 	'<input type="hidden" name="saveStatusOld" value="'.$saveStatus.'" />'."\n";
                    927: 
1.618     www       928:     if (exists($env{'form.Status'})) {
1.561     bisitz    929: 	$gradeTable .= '<input type="hidden" name="Status" value="'.$stu_status.'" />'."\n";
1.124     ng        930:     } else {
1.561     bisitz    931:         $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('Student Status'))
                    932:                       .&Apache::lonhtmlcommon::StatusOptions(
                    933:                            $saveStatus,undef,1,'javascript:reLoadList(this.form);')
                    934:                       .&Apache::lonhtmlcommon::row_closure();
1.124     ng        935:     }
1.112     ng        936: 
1.561     bisitz    937:     $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('Check For Plagiarism'))
                    938:                   .'<input type="checkbox" name="checkPlag" checked="checked" />'
                    939:                   .&Apache::lonhtmlcommon::row_closure(1)
                    940:                   .&Apache::lonhtmlcommon::end_pick_box();
                    941: 
                    942:     $gradeTable .= '<p>'
1.618     www       943:                   .&mt("To view/grade/regrade a submission or a group of submissions, click on the check box(es) next to the student's name(s). Then click on the Next button.")."\n"
1.561     bisitz    944:                   .'<input type="hidden" name="command" value="processGroup" />'
                    945:                   .'</p>';
1.249     albertel  946: 
                    947: # checkall buttons
                    948:     $gradeTable.=&check_script('gradesub', 'stuinfo');
1.110     ng        949:     $gradeTable.='<input type="button" '."\n".
1.589     bisitz    950:         'onclick="javascript:checkSelect(this.form.stuinfo);" '."\n".
                    951:         'value="'.&mt('Next').' &rarr;" /> <br />'."\n";
1.249     albertel  952:     $gradeTable.=&check_buttons();
1.450     banghart  953:     my ($classlist, undef, $fullname) = &getclasslist($getsec,'1',$getgroup);
1.474     albertel  954:     $gradeTable.= &Apache::loncommon::start_data_table().
                    955: 	&Apache::loncommon::start_data_table_header_row();
1.110     ng        956:     my $loop = 0;
                    957:     while ($loop < 2) {
1.485     albertel  958: 	$gradeTable.='<th>'.&mt('No.').'</th><th>'.&mt('Select').'</th>'.
                    959: 	    '<th>'.&nameUserString('header').'&nbsp;'.&mt('Section/Group').'</th>';
1.618     www       960: 	if (($submitonly ne 'queued') && ($submitonly ne 'all')) {
1.485     albertel  961: 	    foreach my $part (sort(@$partlist)) {
                    962: 		my $display_part=
                    963: 		    &get_display_part((split(/_/,$part))[0],$symb);
                    964: 		$gradeTable.=
                    965: 		    '<th>'.&mt('Part: [_1] Status',$display_part).'</th>';
1.110     ng        966: 	    }
1.301     albertel  967: 	} elsif ($submitonly eq 'queued') {
1.474     albertel  968: 	    $gradeTable.='<th>'.&mt('Queue Status').'&nbsp;</th>';
1.110     ng        969: 	}
                    970: 	$loop++;
1.126     ng        971: #	$gradeTable.='<td></td>' if ($loop%2 ==1);
1.41      ng        972:     }
1.474     albertel  973:     $gradeTable.=&Apache::loncommon::end_data_table_header_row()."\n";
1.41      ng        974: 
1.45      ng        975:     my $ctr = 0;
1.294     albertel  976:     foreach my $student (sort 
                    977: 			 {
                    978: 			     if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                    979: 				 return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                    980: 			     }
                    981: 			     return $a cmp $b;
                    982: 			 }
                    983: 			 (keys(%$fullname))) {
1.41      ng        984: 	my ($uname,$udom) = split(/:/,$student);
1.301     albertel  985: 
1.110     ng        986: 	my %status = ();
1.301     albertel  987: 
                    988: 	if ($submitonly eq 'queued') {
                    989: 	    my %queue_status = 
                    990: 		&Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
                    991: 							$udom,$uname);
                    992: 	    next if (!defined($queue_status{'gradingqueue'}));
                    993: 	    $status{'gradingqueue'} = $queue_status{'gradingqueue'};
                    994: 	}
                    995: 
1.618     www       996: 	if (($submitonly ne 'queued') && ($submitonly ne 'all')) {
1.324     albertel  997: 	    (%status) =&student_gradeStatus($symb,$udom,$uname,$partlist);
1.145     albertel  998: 	    my $submitted = 0;
1.164     albertel  999: 	    my $graded = 0;
1.248     albertel 1000: 	    my $incorrect = 0;
1.110     ng       1001: 	    foreach (keys(%status)) {
1.145     albertel 1002: 		$submitted = 1 if ($status{$_} ne 'nothing');
1.248     albertel 1003: 		$graded = 1 if ($status{$_} =~ /^ungraded/);
                   1004: 		$incorrect = 1 if ($status{$_} =~ /^incorrect/);
                   1005: 		
1.110     ng       1006: 		my ($foo,$partid,$foo1) = split(/\./,$_);
                   1007: 		if ($status{'resource.'.$partid.'.submitted_by'} ne '') {
1.145     albertel 1008: 		    $submitted = 0;
1.150     albertel 1009: 		    my ($part)=split(/\./,$partid);
1.110     ng       1010: 		    $gradeTable.='<input type="hidden" name="'.
1.150     albertel 1011: 			$student.':'.$part.':submitted_by" value="'.
1.110     ng       1012: 			$status{'resource.'.$partid.'.submitted_by'}.'" />';
                   1013: 		}
1.41      ng       1014: 	    }
1.248     albertel 1015: 	    
1.156     albertel 1016: 	    next if (!$submitted && ($submitonly eq 'yes' ||
                   1017: 				     $submitonly eq 'incorrect' ||
                   1018: 				     $submitonly eq 'graded'));
1.248     albertel 1019: 	    next if (!$graded && ($submitonly eq 'graded'));
                   1020: 	    next if (!$incorrect && $submitonly eq 'incorrect');
1.41      ng       1021: 	}
1.34      ng       1022: 
1.45      ng       1023: 	$ctr++;
1.249     albertel 1024: 	my $section = $classlist->{$student}->[&Apache::loncoursedata::CL_SECTION()];
1.452     banghart 1025:         my $group = $classlist->{$student}->[&Apache::loncoursedata::CL_GROUP()];
1.104     albertel 1026: 	if ( $perm{'vgr'} eq 'F' ) {
1.474     albertel 1027: 	    if ($ctr%2 ==1) {
                   1028: 		$gradeTable.= &Apache::loncommon::start_data_table_row();
                   1029: 	    }
1.126     ng       1030: 	    $gradeTable.='<td align="right">'.$ctr.'&nbsp;</td>'.
1.563     bisitz   1031:                '<td align="center"><label><input type="checkbox" name="stuinfo" value="'.
1.249     albertel 1032:                $student.':'.$$fullname{$student}.':::SECTION'.$section.
                   1033: 	       ')&nbsp;" />&nbsp;&nbsp;</label></td>'."\n".'<td>'.
                   1034: 	       &nameUserString(undef,$$fullname{$student},$uname,$udom).
1.474     albertel 1035: 	       '&nbsp;'.$section.($group ne '' ?'/'.$group:'').'</td>'."\n";
1.110     ng       1036: 
1.618     www      1037: 	    if ($submitonly ne 'all') {
1.524     raeburn  1038: 		foreach (sort(keys(%status))) {
1.485     albertel 1039: 		    next if ($_ =~ /^resource.*?submitted_by$/);
                   1040: 		    $gradeTable.='<td align="center">&nbsp;'.&mt($status{$_}).'&nbsp;</td>'."\n";
1.110     ng       1041: 		}
1.41      ng       1042: 	    }
1.126     ng       1043: #	    $gradeTable.='<td></td>' if ($ctr%2 ==1);
1.474     albertel 1044: 	    if ($ctr%2 ==0) {
                   1045: 		$gradeTable.=&Apache::loncommon::end_data_table_row()."\n";
                   1046: 	    }
1.41      ng       1047: 	}
                   1048:     }
1.110     ng       1049:     if ($ctr%2 ==1) {
1.126     ng       1050: 	$gradeTable.='<td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td>';
1.618     www      1051: 	    if (($submitonly ne 'queued') && ($submitonly ne 'all')) {
1.110     ng       1052: 		foreach (@$partlist) {
                   1053: 		    $gradeTable.='<td>&nbsp;</td>';
                   1054: 		}
1.301     albertel 1055: 	    } elsif ($submitonly eq 'queued') {
                   1056: 		$gradeTable.='<td>&nbsp;</td>';
1.110     ng       1057: 	    }
1.474     albertel 1058: 	$gradeTable.=&Apache::loncommon::end_data_table_row();
1.110     ng       1059:     }
                   1060: 
1.474     albertel 1061:     $gradeTable.=&Apache::loncommon::end_data_table()."\n".
1.589     bisitz   1062:         '<input type="button" '.
                   1063:         'onclick="javascript:checkSelect(this.form.stuinfo);" '.
                   1064:         'value="'.&mt('Next').' &rarr;" /></form>'."\n";
1.45      ng       1065:     if ($ctr == 0) {
1.96      albertel 1066: 	my $num_students=(scalar(keys(%$fullname)));
                   1067: 	if ($num_students eq 0) {
1.485     albertel 1068: 	    $gradeTable='<br />&nbsp;<span class="LC_warning">'.&mt('There are no students currently enrolled.').'</span>';
1.96      albertel 1069: 	} else {
1.171     albertel 1070: 	    my $submissions='submissions';
                   1071: 	    if ($submitonly eq 'incorrect') { $submissions = 'incorrect submissions'; }
                   1072: 	    if ($submitonly eq 'graded'   ) { $submissions = 'ungraded submissions'; }
1.301     albertel 1073: 	    if ($submitonly eq 'queued'   ) { $submissions = 'queued submissions'; }
1.398     albertel 1074: 	    $gradeTable='<br />&nbsp;<span class="LC_warning">'.
1.485     albertel 1075: 		&mt('No '.$submissions.' found for this resource for any students. ([_1] students checked for '.$submissions.')',
                   1076: 		    $num_students).
                   1077: 		'</span><br />';
1.96      albertel 1078: 	}
1.46      ng       1079:     } elsif ($ctr == 1) {
1.474     albertel 1080: 	$gradeTable =~ s/type="checkbox"/type="checkbox" checked="checked"/;
1.45      ng       1081:     }
                   1082:     $request->print($gradeTable);
1.44      ng       1083:     return '';
1.10      ng       1084: }
                   1085: 
1.44      ng       1086: #---- Called from the listStudents routine
1.249     albertel 1087: 
                   1088: sub check_script {
                   1089:     my ($form, $type)=@_;
1.597     wenzelju 1090:     my $chkallscript= &Apache::lonhtmlcommon::scripttag('
1.249     albertel 1091:     function checkall() {
                   1092:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
                   1093:             ele = document.forms.'.$form.'.elements[i];
                   1094:             if (ele.name == "'.$type.'") {
                   1095:             document.forms.'.$form.'.elements[i].checked=true;
                   1096:                                        }
                   1097:         }
                   1098:     }
                   1099: 
                   1100:     function checksec() {
                   1101:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
                   1102:             ele = document.forms.'.$form.'.elements[i];
                   1103:            string = document.forms.'.$form.'.chksec.value;
                   1104:            if
                   1105:           (ele.value.indexOf(":::SECTION"+string)>0) {
                   1106:               document.forms.'.$form.'.elements[i].checked=true;
                   1107:             }
                   1108:         }
                   1109:     }
                   1110: 
                   1111: 
                   1112:     function uncheckall() {
                   1113:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
                   1114:             ele = document.forms.'.$form.'.elements[i];
                   1115:             if (ele.name == "'.$type.'") {
                   1116:             document.forms.'.$form.'.elements[i].checked=false;
                   1117:                                        }
                   1118:         }
                   1119:     }
                   1120: 
1.597     wenzelju 1121: '."\n");
1.249     albertel 1122:     return $chkallscript;
                   1123: }
                   1124: 
                   1125: sub check_buttons {
1.485     albertel 1126:     my $buttons.='<input type="button" onclick="checkall()" value="'.&mt('Check All').'" />';
                   1127:     $buttons.='<input type="button" onclick="uncheckall()" value="'.&mt('Uncheck All').'" />&nbsp;';
                   1128:     $buttons.='<input type="button" onclick="checksec()" value="'.&mt('Check Section/Group').'" />';
1.249     albertel 1129:     $buttons.='<input type="text" size="5" name="chksec" />&nbsp;';
                   1130:     return $buttons;
                   1131: }
                   1132: 
1.44      ng       1133: #     Displays the submissions for one student or a group of students
1.34      ng       1134: sub processGroup {
1.619     www      1135:     my ($request,$symb)  = @_;
1.41      ng       1136:     my $ctr        = 0;
1.155     albertel 1137:     my @stuchecked = &Apache::loncommon::get_env_multiple('form.stuinfo');
1.41      ng       1138:     my $total      = scalar(@stuchecked)-1;
1.45      ng       1139: 
1.396     banghart 1140:     foreach my $student (@stuchecked) {
                   1141: 	my ($uname,$udom,$fullname) = split(/:/,$student);
1.257     albertel 1142: 	$env{'form.student'}        = $uname;
                   1143: 	$env{'form.userdom'}        = $udom;
                   1144: 	$env{'form.fullname'}       = $fullname;
1.619     www      1145: 	&submission($request,$ctr,$total,$symb);
1.41      ng       1146: 	$ctr++;
                   1147:     }
                   1148:     return '';
1.35      ng       1149: }
1.34      ng       1150: 
1.44      ng       1151: #------------------------------------------------------------------------------------
                   1152: #
                   1153: #-------------------------- Next few routines handles grading by student, essentially
                   1154: #                           handles essay response type problem/part
                   1155: #
                   1156: #--- Javascript to handle the submission page functionality ---
                   1157: sub sub_page_js {
                   1158:     my $request = shift;
1.539     riegler  1159: 	    my $alertmsg = &mt('A number equal or greater than 0 is expected. Entered value = ');
1.597     wenzelju 1160:     $request->print(&Apache::lonhtmlcommon::scripttag(<<SUBJAVASCRIPT));
1.71      ng       1161:     function updateRadio(formname,id,weight) {
1.125     ng       1162: 	var gradeBox = formname["GD_BOX"+id];
                   1163: 	var radioButton = formname["RADVAL"+id];
                   1164: 	var oldpts = formname["oldpts"+id].value;
1.72      ng       1165: 	var pts = checkSolved(formname,id) == 'update' ? gradeBox.value : oldpts;
1.71      ng       1166: 	gradeBox.value = pts;
                   1167: 	var resetbox = false;
                   1168: 	if (isNaN(pts) || pts < 0) {
1.539     riegler  1169: 	    alert("$alertmsg"+pts);
1.71      ng       1170: 	    for (var i=0; i<radioButton.length; i++) {
                   1171: 		if (radioButton[i].checked) {
                   1172: 		    gradeBox.value = i;
                   1173: 		    resetbox = true;
                   1174: 		}
                   1175: 	    }
                   1176: 	    if (!resetbox) {
                   1177: 		formtextbox.value = "";
                   1178: 	    }
                   1179: 	    return;
1.44      ng       1180: 	}
1.71      ng       1181: 
                   1182: 	if (pts > weight) {
                   1183: 	    var resp = confirm("You entered a value ("+pts+
                   1184: 			       ") greater than the weight for the part. Accept?");
                   1185: 	    if (resp == false) {
1.125     ng       1186: 		gradeBox.value = oldpts;
1.71      ng       1187: 		return;
                   1188: 	    }
1.44      ng       1189: 	}
1.13      albertel 1190: 
1.71      ng       1191: 	for (var i=0; i<radioButton.length; i++) {
                   1192: 	    radioButton[i].checked=false;
                   1193: 	    if (pts == i && pts != "") {
                   1194: 		radioButton[i].checked=true;
                   1195: 	    }
                   1196: 	}
                   1197: 	updateSelect(formname,id);
1.125     ng       1198: 	formname["stores"+id].value = "0";
1.41      ng       1199:     }
1.5       albertel 1200: 
1.72      ng       1201:     function writeBox(formname,id,pts) {
1.125     ng       1202: 	var gradeBox = formname["GD_BOX"+id];
1.71      ng       1203: 	if (checkSolved(formname,id) == 'update') {
                   1204: 	    gradeBox.value = pts;
                   1205: 	} else {
1.125     ng       1206: 	    var oldpts = formname["oldpts"+id].value;
1.72      ng       1207: 	    gradeBox.value = oldpts;
1.125     ng       1208: 	    var radioButton = formname["RADVAL"+id];
1.71      ng       1209: 	    for (var i=0; i<radioButton.length; i++) {
                   1210: 		radioButton[i].checked=false;
1.72      ng       1211: 		if (i == oldpts) {
1.71      ng       1212: 		    radioButton[i].checked=true;
                   1213: 		}
                   1214: 	    }
1.41      ng       1215: 	}
1.125     ng       1216: 	formname["stores"+id].value = "0";
1.71      ng       1217: 	updateSelect(formname,id);
                   1218: 	return;
1.41      ng       1219:     }
1.44      ng       1220: 
1.71      ng       1221:     function clearRadBox(formname,id) {
                   1222: 	if (checkSolved(formname,id) == 'noupdate') {
                   1223: 	    updateSelect(formname,id);
                   1224: 	    return;
                   1225: 	}
1.125     ng       1226: 	gradeSelect = formname["GD_SEL"+id];
1.71      ng       1227: 	for (var i=0; i<gradeSelect.length; i++) {
                   1228: 	    if (gradeSelect[i].selected) {
                   1229: 		var selectx=i;
                   1230: 	    }
                   1231: 	}
1.125     ng       1232: 	var stores = formname["stores"+id];
1.71      ng       1233: 	if (selectx == stores.value) { return };
1.125     ng       1234: 	var gradeBox = formname["GD_BOX"+id];
1.71      ng       1235: 	gradeBox.value = "";
1.125     ng       1236: 	var radioButton = formname["RADVAL"+id];
1.71      ng       1237: 	for (var i=0; i<radioButton.length; i++) {
                   1238: 	    radioButton[i].checked=false;
                   1239: 	}
                   1240: 	stores.value = selectx;
                   1241:     }
1.5       albertel 1242: 
1.71      ng       1243:     function checkSolved(formname,id) {
1.125     ng       1244: 	if (formname["solved"+id].value == "correct_by_student" && formname.overRideScore.value == 'no') {
1.118     ng       1245: 	    var reply = confirm("This problem has been graded correct by the computer. Do you want to change the score?");
                   1246: 	    if (!reply) {return "noupdate";}
1.120     ng       1247: 	    formname.overRideScore.value = 'yes';
1.41      ng       1248: 	}
1.71      ng       1249: 	return "update";
1.13      albertel 1250:     }
1.71      ng       1251: 
                   1252:     function updateSelect(formname,id) {
1.125     ng       1253: 	formname["GD_SEL"+id][0].selected = true;
1.71      ng       1254: 	return;
1.41      ng       1255:     }
1.33      ng       1256: 
1.121     ng       1257: //=========== Check that a point is assigned for all the parts  ============
1.71      ng       1258:     function checksubmit(formname,val,total,parttot) {
1.121     ng       1259: 	formname.gradeOpt.value = val;
1.71      ng       1260: 	if (val == "Save & Next") {
                   1261: 	    for (i=0;i<=total;i++) {
                   1262: 		for (j=0;j<parttot;j++) {
1.125     ng       1263: 		    var partid = formname["partid"+i+"_"+j].value;
1.127     ng       1264: 		    if (formname["GD_SEL"+i+"_"+partid][0].selected) {
1.125     ng       1265: 			var points = formname["GD_BOX"+i+"_"+partid].value;
1.71      ng       1266: 			if (points == "") {
1.125     ng       1267: 			    var name = formname["name"+i].value;
1.129     ng       1268: 			    var studentID = (name != '' ? name : formname["unamedom"+i].value);
                   1269: 			    var resp = confirm("You did not assign a score for "+studentID+
                   1270: 					       ", part "+partid+". Continue?");
1.71      ng       1271: 			    if (resp == false) {
1.125     ng       1272: 				formname["GD_BOX"+i+"_"+partid].focus();
1.71      ng       1273: 				return false;
                   1274: 			    }
                   1275: 			}
                   1276: 		    }
                   1277: 		    
                   1278: 		}
                   1279: 	    }
                   1280: 	    
                   1281: 	}
1.120     ng       1282: 	formname.submit();
                   1283:     }
                   1284: 
1.71      ng       1285: //======= Check that a score is assigned for all the problems (page/sequence grading only) =========
                   1286:     function checkSubmitPage(formname,total) {
                   1287: 	noscore = new Array(100);
                   1288: 	var ptr = 0;
                   1289: 	for (i=1;i<total;i++) {
1.125     ng       1290: 	    var partid = formname["q_"+i].value;
1.127     ng       1291: 	    if (formname["GD_SEL"+i+"_"+partid][0].selected) {
1.125     ng       1292: 		var points = formname["GD_BOX"+i+"_"+partid].value;
                   1293: 		var status = formname["solved"+i+"_"+partid].value;
1.71      ng       1294: 		if (points == "" && status != "correct_by_student") {
                   1295: 		    noscore[ptr] = i;
                   1296: 		    ptr++;
                   1297: 		}
                   1298: 	    }
                   1299: 	}
                   1300: 	if (ptr != 0) {
                   1301: 	    var sense = ptr == 1 ? ": " : "s: ";
                   1302: 	    var prolist = "";
                   1303: 	    if (ptr == 1) {
                   1304: 		prolist = noscore[0];
                   1305: 	    } else {
                   1306: 		var i = 0;
                   1307: 		while (i < ptr-1) {
                   1308: 		    prolist += noscore[i]+", ";
                   1309: 		    i++;
                   1310: 		}
                   1311: 		prolist += "and "+noscore[i];
                   1312: 	    }
                   1313: 	    var resp = confirm("You did not assign any score for the following problem"+sense+prolist+". Continue?");
                   1314: 	    if (resp == false) {
                   1315: 		return false;
                   1316: 	    }
                   1317: 	}
1.45      ng       1318: 
1.71      ng       1319: 	formname.submit();
                   1320:     }
                   1321: SUBJAVASCRIPT
                   1322: }
1.45      ng       1323: 
1.71      ng       1324: #--- javascript for essay type problem --
                   1325: sub sub_page_kw_js {
                   1326:     my $request = shift;
1.80      ng       1327:     my $iconpath = $request->dir_config('lonIconsURL');
1.118     ng       1328:     &commonJSfunctions($request);
1.350     albertel 1329: 
1.629     www      1330:     my $inner_js_msg_central= (<<INNERJS);
                   1331: <script type="text/javascript">
1.350     albertel 1332:     function checkInput() {
                   1333:       opener.document.SCORE.msgsub.value = opener.checkEntities(document.msgcenter.msgsub.value);
                   1334:       var nmsg   = opener.document.SCORE.savemsgN.value;
                   1335:       var usrctr = document.msgcenter.usrctr.value;
                   1336:       var newval = opener.document.SCORE["newmsg"+usrctr];
                   1337:       newval.value = opener.checkEntities(document.msgcenter.newmsg.value);
                   1338: 
                   1339:       var msgchk = "";
                   1340:       if (document.msgcenter.subchk.checked) {
                   1341:          msgchk = "msgsub,";
                   1342:       }
                   1343:       var includemsg = 0;
                   1344:       for (var i=1; i<=nmsg; i++) {
                   1345:           var opnmsg = opener.document.SCORE["savemsg"+i];
                   1346:           var frmmsg = document.msgcenter["msg"+i];
                   1347:           opnmsg.value = opener.checkEntities(frmmsg.value);
                   1348:           var showflg = opener.document.SCORE["shownOnce"+i];
                   1349:           showflg.value = "1";
                   1350:           var chkbox = document.msgcenter["msgn"+i];
                   1351:           if (chkbox.checked) {
                   1352:              msgchk += "savemsg"+i+",";
                   1353:              includemsg = 1;
                   1354:           }
                   1355:       }
                   1356:       if (document.msgcenter.newmsgchk.checked) {
                   1357:          msgchk += "newmsg"+usrctr;
                   1358:          includemsg = 1;
                   1359:       }
                   1360:       imgformname = opener.document.SCORE["mailicon"+usrctr];
                   1361:       imgformname.src = "$iconpath/"+((includemsg) ? "mailto.gif" : "mailbkgrd.gif");
                   1362:       var includemsg = opener.document.SCORE["includemsg"+usrctr];
                   1363:       includemsg.value = msgchk;
                   1364: 
                   1365:       self.close()
                   1366: 
                   1367:     }
1.629     www      1368: </script>
1.350     albertel 1369: INNERJS
                   1370: 
1.629     www      1371:     my $inner_js_highlight_central= (<<INNERJS);
                   1372: <script type="text/javascript">
1.351     albertel 1373:     function updateChoice(flag) {
                   1374:       opener.document.SCORE.kwclr.value = opener.radioSelection(document.hlCenter.kwdclr);
                   1375:       opener.document.SCORE.kwsize.value = opener.radioSelection(document.hlCenter.kwdsize);
                   1376:       opener.document.SCORE.kwstyle.value = opener.radioSelection(document.hlCenter.kwdstyle);
                   1377:       opener.document.SCORE.refresh.value = "on";
                   1378:       if (opener.document.SCORE.keywords.value!=""){
                   1379:          opener.document.SCORE.submit();
                   1380:       }
                   1381:       self.close()
                   1382:     }
1.629     www      1383: </script>
1.351     albertel 1384: INNERJS
                   1385: 
                   1386:     my $start_page_msg_central = 
                   1387:         &Apache::loncommon::start_page('Message Central',$inner_js_msg_central,
                   1388: 				       {'js_ready'  => 1,
                   1389: 					'only_body' => 1,
                   1390: 					'bgcolor'   =>'#FFFFFF',});
                   1391:     my $end_page_msg_central = 
                   1392: 	&Apache::loncommon::end_page({'js_ready' => 1});
                   1393: 
                   1394: 
                   1395:     my $start_page_highlight_central = 
                   1396:         &Apache::loncommon::start_page('Highlight Central',
                   1397: 				       $inner_js_highlight_central,
1.350     albertel 1398: 				       {'js_ready'  => 1,
                   1399: 					'only_body' => 1,
                   1400: 					'bgcolor'   =>'#FFFFFF',});
1.351     albertel 1401:     my $end_page_highlight_central = 
1.350     albertel 1402: 	&Apache::loncommon::end_page({'js_ready' => 1});
                   1403: 
1.219     www      1404:     my $docopen=&Apache::lonhtmlcommon::javascript_docopen();
1.236     albertel 1405:     $docopen=~s/^document\.//;
1.539     riegler  1406:     my $alertmsg = &mt('Please select a word or group of words from document and then click this link.');
1.597     wenzelju 1407:     $request->print(&Apache::lonhtmlcommon::scripttag(<<SUBJAVASCRIPT));
1.45      ng       1408: 
1.44      ng       1409: //===================== Show list of keywords ====================
1.122     ng       1410:   function keywords(formname) {
                   1411:     var nret = prompt("Keywords list, separated by a space. Add/delete to list if desired.",formname.keywords.value);
1.44      ng       1412:     if (nret==null) return;
1.122     ng       1413:     formname.keywords.value = nret;
1.44      ng       1414: 
1.122     ng       1415:     if (formname.keywords.value != "") {
1.128     ng       1416: 	formname.refresh.value = "on";
1.122     ng       1417: 	formname.submit();
1.44      ng       1418:     }
                   1419:     return;
                   1420:   }
                   1421: 
                   1422: //===================== Script to view submitted by ==================
                   1423:   function viewSubmitter(submitter) {
                   1424:     document.SCORE.refresh.value = "on";
                   1425:     document.SCORE.NCT.value = "1";
                   1426:     document.SCORE.unamedom0.value = submitter;
                   1427:     document.SCORE.submit();
                   1428:     return;
                   1429:   }
                   1430: 
                   1431: //===================== Script to add keyword(s) ==================
                   1432:   function getSel() {
                   1433:     if (document.getSelection) txt = document.getSelection();
                   1434:     else if (document.selection) txt = document.selection.createRange().text;
                   1435:     else return;
                   1436:     var cleantxt = txt.replace(new RegExp('([\\f\\n\\r\\t\\v ])+', 'g')," ");
                   1437:     if (cleantxt=="") {
1.539     riegler  1438: 	alert("$alertmsg");
1.44      ng       1439: 	return;
                   1440:     }
                   1441:     var nret = prompt("Add selection to keyword list? Edit if desired.",cleantxt);
                   1442:     if (nret==null) return;
1.127     ng       1443:     document.SCORE.keywords.value = document.SCORE.keywords.value+" "+nret;
1.44      ng       1444:     if (document.SCORE.keywords.value != "") {
1.127     ng       1445: 	document.SCORE.refresh.value = "on";
1.44      ng       1446: 	document.SCORE.submit();
                   1447:     }
                   1448:     return;
                   1449:   }
                   1450: 
                   1451: //====================== Script for composing message ==============
1.80      ng       1452:    // preload images
                   1453:    img1 = new Image();
                   1454:    img1.src = "$iconpath/mailbkgrd.gif";
                   1455:    img2 = new Image();
                   1456:    img2.src = "$iconpath/mailto.gif";
                   1457: 
1.44      ng       1458:   function msgCenter(msgform,usrctr,fullname) {
                   1459:     var Nmsg  = msgform.savemsgN.value;
                   1460:     savedMsgHeader(Nmsg,usrctr,fullname);
                   1461:     var subject = msgform.msgsub.value;
1.127     ng       1462:     var msgchk = document.SCORE["includemsg"+usrctr].value;
1.44      ng       1463:     re = /msgsub/;
                   1464:     var shwsel = "";
                   1465:     if (re.test(msgchk)) { shwsel = "checked" }
1.123     ng       1466:     subject = (document.SCORE.shownSub.value == 0 ? checkEntities(subject) : subject);
                   1467:     displaySubject(checkEntities(subject),shwsel);
1.44      ng       1468:     for (var i=1; i<=Nmsg; i++) {
1.123     ng       1469: 	var testmsg = "savemsg"+i+",";
                   1470: 	re = new RegExp(testmsg,"g");
1.44      ng       1471: 	shwsel = "";
                   1472: 	if (re.test(msgchk)) { shwsel = "checked" }
1.125     ng       1473: 	var message = document.SCORE["savemsg"+i].value;
1.126     ng       1474: 	message = (document.SCORE["shownOnce"+i].value == 0 ? checkEntities(message) : message);
1.123     ng       1475: 	displaySavedMsg(i,message,shwsel); //I do not get it. w/o checkEntities on saved messages,
                   1476: 	                                   //any &lt; is already converted to <, etc. However, only once!!
1.44      ng       1477:     }
1.125     ng       1478:     newmsg = document.SCORE["newmsg"+usrctr].value;
1.44      ng       1479:     shwsel = "";
                   1480:     re = /newmsg/;
                   1481:     if (re.test(msgchk)) { shwsel = "checked" }
                   1482:     newMsg(newmsg,shwsel);
                   1483:     msgTail(); 
                   1484:     return;
                   1485:   }
                   1486: 
1.123     ng       1487:   function checkEntities(strx) {
                   1488:     if (strx.length == 0) return strx;
                   1489:     var orgStr = ["&", "<", ">", '"']; 
                   1490:     var newStr = ["&amp;", "&lt;", "&gt;", "&quot;"];
                   1491:     var counter = 0;
                   1492:     while (counter < 4) {
                   1493: 	strx = strReplace(strx,orgStr[counter],newStr[counter]);
                   1494: 	counter++;
                   1495:     }
                   1496:     return strx;
                   1497:   }
                   1498: 
                   1499:   function strReplace(strx, orgStr, newStr) {
                   1500:     return strx.split(orgStr).join(newStr);
                   1501:   }
                   1502: 
1.44      ng       1503:   function savedMsgHeader(Nmsg,usrctr,fullname) {
1.76      ng       1504:     var height = 70*Nmsg+250;
1.44      ng       1505:     var scrollbar = "no";
                   1506:     if (height > 600) {
                   1507: 	height = 600;
                   1508: 	scrollbar = "yes";
                   1509:     }
1.118     ng       1510:     var xpos = (screen.width-600)/2;
                   1511:     xpos = (xpos < 0) ? '0' : xpos;
                   1512:     var ypos = (screen.height-height)/2-30;
                   1513:     ypos = (ypos < 0) ? '0' : ypos;
                   1514: 
1.206     albertel 1515:     pWin = window.open('', 'MessageCenter', 'resizable=yes,toolbar=no,location=no,scrollbars='+scrollbar+',screenx='+xpos+',screeny='+ypos+',width=600,height='+height);
1.76      ng       1516:     pWin.focus();
                   1517:     pDoc = pWin.document;
1.219     www      1518:     pDoc.$docopen;
1.351     albertel 1519:     pDoc.write('$start_page_msg_central');
1.76      ng       1520: 
                   1521:     pDoc.write("<form action=\\"inactive\\" name=\\"msgcenter\\">");
                   1522:     pDoc.write("<input value=\\""+usrctr+"\\" name=\\"usrctr\\" type=\\"hidden\\">");
1.465     albertel 1523:     pDoc.write("<h3><span class=\\"LC_info\\">&nbsp;Compose Message for \"+fullname+\"<\\/span><\\/h3><br /><br />");
1.76      ng       1524: 
1.564     bisitz   1525:     pDoc.write('<table border="0" width="100%"><tr><td bgcolor="#777777">');
                   1526:     pDoc.write('<table border="0" width="100%"><tr bgcolor="#DDFFFF">');
1.465     albertel 1527:     pDoc.write("<td><b>Type<\\/b><\\/td><td><b>Include<\\/b><\\/td><td><b>Message<\\/td><\\/tr>");
1.44      ng       1528: }
                   1529:     function displaySubject(msg,shwsel) {
1.76      ng       1530:     pDoc = pWin.document;
                   1531:     pDoc.write("<tr bgcolor=\\"#ffffdd\\">");
1.465     albertel 1532:     pDoc.write("<td>Subject<\\/td>");
                   1533:     pDoc.write("<td align=\\"center\\"><input name=\\"subchk\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
                   1534:     pDoc.write("<td><input name=\\"msgsub\\" type=\\"text\\" value=\\""+msg+"\\"size=\\"60\\" maxlength=\\"80\\"><\\/td><\\/tr>");
1.44      ng       1535: }
                   1536: 
1.72      ng       1537:   function displaySavedMsg(ctr,msg,shwsel) {
1.76      ng       1538:     pDoc = pWin.document;
                   1539:     pDoc.write("<tr bgcolor=\\"#ffffdd\\">");
1.465     albertel 1540:     pDoc.write("<td align=\\"center\\">"+ctr+"<\\/td>");
                   1541:     pDoc.write("<td align=\\"center\\"><input name=\\"msgn"+ctr+"\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
                   1542:     pDoc.write("<td><textarea name=\\"msg"+ctr+"\\" cols=\\"60\\" rows=\\"3\\">"+msg+"<\\/textarea><\\/td><\\/tr>");
1.44      ng       1543: }
                   1544: 
                   1545:   function newMsg(newmsg,shwsel) {
1.76      ng       1546:     pDoc = pWin.document;
                   1547:     pDoc.write("<tr bgcolor=\\"#ffffdd\\">");
1.465     albertel 1548:     pDoc.write("<td align=\\"center\\">New<\\/td>");
                   1549:     pDoc.write("<td align=\\"center\\"><input name=\\"newmsgchk\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
                   1550:     pDoc.write("<td><textarea name=\\"newmsg\\" cols=\\"60\\" rows=\\"3\\" onchange=\\"javascript:this.form.newmsgchk.checked=true\\" >"+newmsg+"<\\/textarea><\\/td><\\/tr>");
1.44      ng       1551: }
                   1552: 
                   1553:   function msgTail() {
1.76      ng       1554:     pDoc = pWin.document;
1.465     albertel 1555:     pDoc.write("<\\/table>");
                   1556:     pDoc.write("<\\/td><\\/tr><\\/table>&nbsp;");
1.589     bisitz   1557:     pDoc.write("<input type=\\"button\\" value=\\"Save\\" onclick=\\"javascript:checkInput()\\">&nbsp;&nbsp;");
                   1558:     pDoc.write("<input type=\\"button\\" value=\\"Cancel\\" onclick=\\"self.close()\\"><br /><br />");
1.465     albertel 1559:     pDoc.write("<\\/form>");
1.351     albertel 1560:     pDoc.write('$end_page_msg_central');
1.128     ng       1561:     pDoc.close();
1.44      ng       1562: }
                   1563: 
                   1564: //====================== Script for keyword highlight options ==============
                   1565:   function kwhighlight() {
                   1566:     var kwclr    = document.SCORE.kwclr.value;
                   1567:     var kwsize   = document.SCORE.kwsize.value;
                   1568:     var kwstyle  = document.SCORE.kwstyle.value;
                   1569:     var redsel = "";
                   1570:     var grnsel = "";
                   1571:     var blusel = "";
                   1572:     if (kwclr=="red")   {var redsel="checked"};
                   1573:     if (kwclr=="green") {var grnsel="checked"};
                   1574:     if (kwclr=="blue")  {var blusel="checked"};
                   1575:     var sznsel = "";
                   1576:     var sz1sel = "";
                   1577:     var sz2sel = "";
                   1578:     if (kwsize=="0")  {var sznsel="checked"};
                   1579:     if (kwsize=="+1") {var sz1sel="checked"};
                   1580:     if (kwsize=="+2") {var sz2sel="checked"};
                   1581:     var synsel = "";
                   1582:     var syisel = "";
                   1583:     var sybsel = "";
                   1584:     if (kwstyle=="")    {var synsel="checked"};
                   1585:     if (kwstyle=="<i>") {var syisel="checked"};
                   1586:     if (kwstyle=="<b>") {var sybsel="checked"};
                   1587:     highlightCentral();
                   1588:     highlightbody('red','red',redsel,'0','normal',sznsel,'','normal',synsel);
                   1589:     highlightbody('green','green',grnsel,'+1','+1',sz1sel,'<i>','italic',syisel);
                   1590:     highlightbody('blue','blue',blusel,'+2','+2',sz2sel,'<b>','bold',sybsel);
                   1591:     highlightend();
                   1592:     return;
                   1593:   }
                   1594: 
                   1595:   function highlightCentral() {
1.76      ng       1596: //    if (window.hwdWin) window.hwdWin.close();
1.118     ng       1597:     var xpos = (screen.width-400)/2;
                   1598:     xpos = (xpos < 0) ? '0' : xpos;
                   1599:     var ypos = (screen.height-330)/2-30;
                   1600:     ypos = (ypos < 0) ? '0' : ypos;
                   1601: 
1.206     albertel 1602:     hwdWin = window.open('', 'KeywordHighlightCentral', 'resizeable=yes,toolbar=no,location=no,scrollbars=no,width=400,height=300,screenx='+xpos+',screeny='+ypos);
1.76      ng       1603:     hwdWin.focus();
                   1604:     var hDoc = hwdWin.document;
1.219     www      1605:     hDoc.$docopen;
1.351     albertel 1606:     hDoc.write('$start_page_highlight_central');
1.76      ng       1607:     hDoc.write("<form action=\\"inactive\\" name=\\"hlCenter\\">");
1.465     albertel 1608:     hDoc.write("<h3><span class=\\"LC_info\\">&nbsp;Keyword Highlight Options<\\/span><\\/h3><br /><br />");
1.76      ng       1609: 
1.564     bisitz   1610:     hDoc.write('<table border="0" width="100%"><tr><td bgcolor="#777777">');
                   1611:     hDoc.write('<table border="0" width="100%"><tr bgcolor="#DDFFFF">');
1.465     albertel 1612:     hDoc.write("<td><b>Text Color<\\/b><\\/td><td><b>Font Size<\\/b><\\/td><td><b>Font Style<\\/td><\\/tr>");
1.44      ng       1613:   }
                   1614: 
                   1615:   function highlightbody(clrval,clrtxt,clrsel,szval,sztxt,szsel,syval,sytxt,sysel) { 
1.76      ng       1616:     var hDoc = hwdWin.document;
                   1617:     hDoc.write("<tr bgcolor=\\"#ffffdd\\">");
                   1618:     hDoc.write("<td align=\\"left\\">");
1.465     albertel 1619:     hDoc.write("<input name=\\"kwdclr\\" type=\\"radio\\" value=\\""+clrval+"\\" "+clrsel+">&nbsp;"+clrtxt+"<\\/td>");
1.76      ng       1620:     hDoc.write("<td align=\\"left\\">");
1.465     albertel 1621:     hDoc.write("<input name=\\"kwdsize\\" type=\\"radio\\" value=\\""+szval+"\\" "+szsel+">&nbsp;"+sztxt+"<\\/td>");
1.76      ng       1622:     hDoc.write("<td align=\\"left\\">");
1.465     albertel 1623:     hDoc.write("<input name=\\"kwdstyle\\" type=\\"radio\\" value=\\""+syval+"\\" "+sysel+">&nbsp;"+sytxt+"<\\/td>");
                   1624:     hDoc.write("<\\/tr>");
1.44      ng       1625:   }
                   1626: 
                   1627:   function highlightend() { 
1.76      ng       1628:     var hDoc = hwdWin.document;
1.465     albertel 1629:     hDoc.write("<\\/table>");
                   1630:     hDoc.write("<\\/td><\\/tr><\\/table>&nbsp;");
1.589     bisitz   1631:     hDoc.write("<input type=\\"button\\" value=\\"Save\\" onclick=\\"javascript:updateChoice(1)\\">&nbsp;&nbsp;");
                   1632:     hDoc.write("<input type=\\"button\\" value=\\"Cancel\\" onclick=\\"self.close()\\"><br /><br />");
1.465     albertel 1633:     hDoc.write("<\\/form>");
1.351     albertel 1634:     hDoc.write('$end_page_highlight_central');
1.128     ng       1635:     hDoc.close();
1.44      ng       1636:   }
                   1637: 
                   1638: SUBJAVASCRIPT
                   1639: }
                   1640: 
1.349     albertel 1641: sub get_increment {
1.348     bowersj2 1642:     my $increment = $env{'form.increment'};
                   1643:     if ($increment != 1 && $increment != .5 && $increment != .25 &&
                   1644:         $increment != .1) {
                   1645:         $increment = 1;
                   1646:     }
                   1647:     return $increment;
                   1648: }
                   1649: 
1.585     bisitz   1650: sub gradeBox_start {
                   1651:     return (
                   1652:         &Apache::loncommon::start_data_table()
                   1653:        .&Apache::loncommon::start_data_table_header_row()
                   1654:        .'<th>'.&mt('Part').'</th>'
                   1655:        .'<th>'.&mt('Points').'</th>'
                   1656:        .'<th>&nbsp;</th>'
                   1657:        .'<th>'.&mt('Assign Grade').'</th>'
                   1658:        .'<th>'.&mt('Weight').'</th>'
                   1659:        .'<th>'.&mt('Grade Status').'</th>'
                   1660:        .&Apache::loncommon::end_data_table_header_row()
                   1661:     );
                   1662: }
                   1663: 
                   1664: sub gradeBox_end {
                   1665:     return (
                   1666:         &Apache::loncommon::end_data_table()
                   1667:     );
                   1668: }
1.71      ng       1669: #--- displays the grading box, used in essay type problem and grading by page/sequence
                   1670: sub gradeBox {
1.322     albertel 1671:     my ($request,$symb,$uname,$udom,$counter,$partid,$record) = @_;
1.381     albertel 1672:     my $checkIcon = '<img alt="'.&mt('Check Mark').
1.485     albertel 1673: 	'" src="'.&Apache::loncommon::lonhttpdurl($request->dir_config('lonIconsURL').'/check.gif').'" height="16" border="0" />';
1.71      ng       1674:     my $wgt    = &Apache::lonnet::EXT('resource.'.$partid.'.weight',$symb,$udom,$uname);
1.466     albertel 1675:     my $wgtmsg = ($wgt > 0) ? &mt('(problem weight)') 
                   1676:                            : '<span class="LC_info">'.&mt('problem weight assigned by computer').'</span>';
1.71      ng       1677:     $wgt       = ($wgt > 0 ? $wgt : '1');
                   1678:     my $score  = ($$record{'resource.'.$partid.'.awarded'} eq '' ?
1.320     albertel 1679: 		  '' : &compute_points($$record{'resource.'.$partid.'.awarded'},$wgt));
1.71      ng       1680:     my $result='<input type="hidden" name="WGT'.$counter.'_'.$partid.'" value="'.$wgt.'" />'."\n";
1.466     albertel 1681:     my $display_part= &get_display_part($partid,$symb);
1.270     albertel 1682:     my %last_resets = &get_last_resets($symb,$env{'request.course.id'},
                   1683: 				       [$partid]);
                   1684:     my $aggtries = $$record{'resource.'.$partid.'.tries'};
1.269     raeburn  1685:     if ($last_resets{$partid}) {
                   1686:         $aggtries = &get_num_tries($record,$last_resets{$partid},$partid);
                   1687:     }
1.585     bisitz   1688:     $result.=&Apache::loncommon::start_data_table_row();
1.71      ng       1689:     my $ctr = 0;
1.348     bowersj2 1690:     my $thisweight = 0;
1.349     albertel 1691:     my $increment = &get_increment();
1.485     albertel 1692: 
                   1693:     my $radio.='<table border="0"><tr>'."\n";  # display radio buttons in a nice table 10 across
1.348     bowersj2 1694:     while ($thisweight<=$wgt) {
1.532     bisitz   1695: 	$radio.= '<td><span class="LC_nobreak"><label><input type="radio" name="RADVAL'.$counter.'_'.$partid.'" '.
1.589     bisitz   1696:         'onclick="javascript:writeBox(this.form,\''.$counter.'_'.$partid.'\','.
1.348     bowersj2 1697: 	    $thisweight.')" value="'.$thisweight.'" '.
1.401     albertel 1698: 	    ($score eq $thisweight ? 'checked="checked"':'').' /> '.$thisweight."</label></span></td>\n";
1.485     albertel 1699: 	$radio.=(($ctr+1)%10 == 0 ? '</tr><tr>' : '');
1.348     bowersj2 1700:         $thisweight += $increment;
1.71      ng       1701: 	$ctr++;
                   1702:     }
1.485     albertel 1703:     $radio.='</tr></table>';
                   1704: 
                   1705:     my $line.='<input type="text" name="GD_BOX'.$counter.'_'.$partid.'"'.
1.71      ng       1706: 	($score ne ''? ' value = "'.$score.'"':'').' size="4" '.
1.589     bisitz   1707: 	'onchange="javascript:updateRadio(this.form,\''.$counter.'_'.$partid.'\','.
1.71      ng       1708: 	$wgt.')" /></td>'."\n";
1.485     albertel 1709:     $line.='<td>/'.$wgt.' '.$wgtmsg.
1.71      ng       1710: 	($$record{'resource.'.$partid.'.solved'} eq 'correct_by_student' ? '&nbsp;'.$checkIcon : '').
1.585     bisitz   1711: 	' </td>'."\n";
                   1712:     $line.='<td><select name="GD_SEL'.$counter.'_'.$partid.'" '.
1.589     bisitz   1713: 	'onchange="javascript:clearRadBox(this.form,\''.$counter.'_'.$partid.'\')" >'."\n";
1.71      ng       1714:     if ($$record{'resource.'.$partid.'.solved'} eq 'excused') {
1.485     albertel 1715: 	$line.='<option></option>'.
                   1716: 	    '<option value="excused" selected="selected">'.&mt('excused').'</option>';
1.71      ng       1717:     } else {
1.485     albertel 1718: 	$line.='<option selected="selected"></option>'.
                   1719: 	    '<option value="excused" >'.&mt('excused').'</option>';
1.71      ng       1720:     }
1.485     albertel 1721:     $line.='<option value="reset status">'.&mt('reset status').'</option></select>'."\n";
                   1722: 
                   1723: 
                   1724:     $result .= 
1.585     bisitz   1725: 	    '<td>'.$display_part.'</td><td>'.$radio.'</td><td>'.&mt('or').'</td><td>'.$line.'</td>';
                   1726:     $result.=&Apache::loncommon::end_data_table_row();
1.71      ng       1727:     $result.='<input type="hidden" name="stores'.$counter.'_'.$partid.'" value="" />'."\n".
                   1728: 	'<input type="hidden" name="oldpts'.$counter.'_'.$partid.'" value="'.$score.'" />'."\n".
                   1729: 	'<input type="hidden" name="solved'.$counter.'_'.$partid.'" value="'.
1.269     raeburn  1730: 	$$record{'resource.'.$partid.'.solved'}.'" />'."\n".
                   1731:         '<input type="hidden" name="totaltries'.$counter.'_'.$partid.'" value="'.
                   1732:         $$record{'resource.'.$partid.'.tries'}.'" />'."\n".
                   1733:         '<input type="hidden" name="aggtries'.$counter.'_'.$partid.'" value="'.
                   1734:         $aggtries.'" />'."\n";
1.582     raeburn  1735:     my $res_error;
                   1736:     $result.=&handback_box($symb,$uname,$udom,$counter,$partid,$record,\$res_error);
                   1737:     if ($res_error) {
                   1738:         return &navmap_errormsg();
                   1739:     }
1.318     banghart 1740:     return $result;
                   1741: }
1.322     albertel 1742: 
                   1743: sub handback_box {
1.623     www      1744:     my ($symb,$uname,$udom,$counter,$partid,$record,$res_error_pointer) = @_;
                   1745:     my ($partlist,$handgrade,$responseType) = &response_type($symb,$res_error_pointer);
1.323     banghart 1746:     my (@respids);
1.375     albertel 1747:      my @part_response_id = &flatten_responseType($responseType);
                   1748:     foreach my $part_response_id (@part_response_id) {
                   1749:     	my ($part,$resp) = @{ $part_response_id };
1.323     banghart 1750:         if ($part eq $partid) {
1.375     albertel 1751:             push(@respids,$resp);
1.323     banghart 1752:         }
                   1753:     }
1.318     banghart 1754:     my $result;
1.323     banghart 1755:     foreach my $respid (@respids) {
1.322     albertel 1756: 	my $prefix = $counter.'_'.$partid.'_'.$respid.'_';
                   1757: 	my $files=&get_submitted_files($udom,$uname,$partid,$respid,$record);
                   1758: 	next if (!@$files);
                   1759: 	my $file_counter = 1;
1.313     banghart 1760: 	foreach my $file (@$files) {
1.368     banghart 1761: 	    if ($file =~ /\/portfolio\//) {
                   1762:     	        my ($file_path, $file_disp) = ($file =~ m|(.+/)(.+)$|);
                   1763:     	        my ($name,$version,$ext) = &file_name_version_ext($file_disp);
                   1764:     	        $file_disp = "$name.$ext";
                   1765:     	        $file = $file_path.$file_disp;
                   1766:     	        $result.=&mt('Return commented version of [_1] to student.',
                   1767:     			 '<span class="LC_filename">'.$file_disp.'</span>');
                   1768:     	        $result.='<input type="file"   name="'.$prefix.'returndoc'.$file_counter.'" />'."\n";
                   1769:     	        $result.='<input type="hidden" name="'.$prefix.'origdoc'.$file_counter.'" value="'.$file.'" /><br />';
1.485     albertel 1770:     	        $result.='('.&mt('File will be uploaded when you click on Save &amp; Next below.').')<br />';
1.368     banghart 1771:     	        $file_counter++;
                   1772: 	    }
1.322     albertel 1773: 	}
1.313     banghart 1774:     }
1.318     banghart 1775:     return $result;    
1.71      ng       1776: }
1.44      ng       1777: 
1.58      albertel 1778: sub show_problem {
1.382     albertel 1779:     my ($request,$symb,$uname,$udom,$removeform,$viewon,$mode,$form) = @_;
1.144     albertel 1780:     my $rendered;
1.382     albertel 1781:     my %form = ((ref($form) eq 'HASH')? %{$form} : ());
1.329     albertel 1782:     &Apache::lonxml::remember_problem_counter();
1.144     albertel 1783:     if ($mode eq 'both' or $mode eq 'text') {
                   1784: 	$rendered=&Apache::loncommon::get_student_view($symb,$uname,$udom,
1.382     albertel 1785: 						       $env{'request.course.id'},
                   1786: 						       undef,\%form);
1.144     albertel 1787:     }
1.58      albertel 1788:     if ($removeform) {
                   1789: 	$rendered=~s|<form(.*?)>||g;
                   1790: 	$rendered=~s|</form>||g;
1.374     albertel 1791: 	$rendered=~s|(<input[^>]*name\s*=\s*"?)(\w+)("?)|$1would_have_been_$2$3|g;
1.58      albertel 1792:     }
1.144     albertel 1793:     my $companswer;
                   1794:     if ($mode eq 'both' or $mode eq 'answer') {
1.329     albertel 1795: 	&Apache::lonxml::restore_problem_counter();
1.382     albertel 1796: 	$companswer=
                   1797: 	    &Apache::loncommon::get_student_answers($symb,$uname,$udom,
                   1798: 						    $env{'request.course.id'},
                   1799: 						    %form);
1.144     albertel 1800:     }
1.58      albertel 1801:     if ($removeform) {
                   1802: 	$companswer=~s|<form(.*?)>||g;
                   1803: 	$companswer=~s|</form>||g;
1.144     albertel 1804: 	$companswer=~s|name="submit"|name="would_have_been_submit"|g;
1.58      albertel 1805:     }
1.468     albertel 1806:     $rendered=
1.588     bisitz   1807:         '<div class="LC_Box">'
                   1808:        .'<h3 class="LC_hcell">'.&mt('View of the problem').'</h3>'
                   1809:        .$rendered
                   1810:        .'</div>';
1.468     albertel 1811:     $companswer=
1.588     bisitz   1812:         '<div class="LC_Box">'
                   1813:        .'<h3 class="LC_hcell">'.&mt('Correct answer').'</h3>'
                   1814:        .$companswer
                   1815:        .'</div>';
1.468     albertel 1816:     my $result;
1.144     albertel 1817:     if ($mode eq 'both') {
1.588     bisitz   1818:         $result=$rendered.$companswer;
1.144     albertel 1819:     } elsif ($mode eq 'text') {
1.588     bisitz   1820:         $result=$rendered;
1.144     albertel 1821:     } elsif ($mode eq 'answer') {
1.588     bisitz   1822:         $result=$companswer;
1.144     albertel 1823:     }
1.71      ng       1824:     return $result;
1.58      albertel 1825: }
1.397     albertel 1826: 
1.396     banghart 1827: sub files_exist {
                   1828:     my ($r, $symb) = @_;
                   1829:     my @students = &Apache::loncommon::get_env_multiple('form.stuinfo');
1.397     albertel 1830: 
1.396     banghart 1831:     foreach my $student (@students) {
                   1832:         my ($uname,$udom,$fullname) = split(/:/,$student);
1.397     albertel 1833:         my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},
                   1834: 					      $udom,$uname);
1.396     banghart 1835:         my ($string,$timestamp)= &get_last_submission(\%record);
1.397     albertel 1836:         foreach my $submission (@$string) {
                   1837:             my ($partid,$respid) =
                   1838: 		($submission =~ /^resource\.([^\.]*)\.([^\.]*)\.submission/);
                   1839:             my $files=&get_submitted_files($udom,$uname,$partid,$respid,
                   1840: 					   \%record);
                   1841:             return 1 if (@$files);
1.396     banghart 1842:         }
                   1843:     }
1.397     albertel 1844:     return 0;
1.396     banghart 1845: }
1.397     albertel 1846: 
1.394     banghart 1847: sub download_all_link {
                   1848:     my ($r,$symb) = @_;
1.621     www      1849:     unless (&files_exist($r, $symb)) {
                   1850:        $r->print(&mt('There are currently no submitted documents.'));
                   1851:        return;
                   1852:     }
                   1853: 
1.395     albertel 1854:     my $all_students = 
                   1855: 	join("\n", &Apache::loncommon::get_env_multiple('form.stuinfo'));
                   1856: 
                   1857:     my $parts =
                   1858: 	join("\n",&Apache::loncommon::get_env_multiple('form.vPart'));
                   1859: 
1.394     banghart 1860:     my $identifier = &Apache::loncommon::get_cgi_id();
1.514     raeburn  1861:     &Apache::lonnet::appenv({'cgi.'.$identifier.'.students' => $all_students,
                   1862:                              'cgi.'.$identifier.'.symb' => $symb,
                   1863:                              'cgi.'.$identifier.'.parts' => $parts,});
1.395     albertel 1864:     $r->print('<a href="/cgi-bin/multidownload.pl?'.$identifier.'">'.
                   1865: 	      &mt('Download All Submitted Documents').'</a>');
1.621     www      1866:     return;
                   1867: }
                   1868: 
                   1869: sub submit_download_link {
                   1870:     my ($request,$symb) = @_;
                   1871:     if (!$symb) { return ''; }
                   1872: #FIXME: Figure out which type of problem this is and provide appropriate download
                   1873:     &download_all_link($request,$symb);
1.394     banghart 1874: }
1.395     albertel 1875: 
1.432     banghart 1876: sub build_section_inputs {
                   1877:     my $section_inputs;
                   1878:     if ($env{'form.section'} eq '') {
                   1879:         $section_inputs .= '<input type="hidden" name="section" value="all" />'."\n";
                   1880:     } else {
                   1881:         my @sections = &Apache::loncommon::get_env_multiple('form.section');
1.434     albertel 1882:         foreach my $section (@sections) {
1.432     banghart 1883:             $section_inputs .= '<input type="hidden" name="section" value="'.$section.'" />'."\n";
                   1884:         }
                   1885:     }
                   1886:     return $section_inputs;
                   1887: }
                   1888: 
1.44      ng       1889: # --------------------------- show submissions of a student, option to grade 
                   1890: sub submission {
1.608     www      1891:     my ($request,$counter,$total,$symb) = @_;
1.257     albertel 1892:     my ($uname,$udom)     = ($env{'form.student'},$env{'form.userdom'});
                   1893:     $udom = ($udom eq '' ? $env{'user.domain'} : $udom); #has form.userdom changed for a student?
                   1894:     my $usec = &Apache::lonnet::getsection($udom,$uname,$env{'request.course.id'});
                   1895:     $env{'form.fullname'} = &Apache::loncommon::plainname($uname,$udom,'lastname') if $env{'form.fullname'} eq '';
1.608     www      1896: 
1.605     www      1897:     my $probtitle=&Apache::lonnet::gettitle($symb); 
1.324     albertel 1898:     if ($symb eq '') { $request->print("Unable to handle ambiguous references:."); return ''; }
1.104     albertel 1899: 
                   1900:     if (!&canview($usec)) {
1.398     albertel 1901: 	$request->print('<span class="LC_warning">Unable to view requested student.('.
                   1902: 			$uname.':'.$udom.' in section '.$usec.' in course id '.
                   1903: 			$env{'request.course.id'}.')</span>');
1.104     albertel 1904: 	return;
                   1905:     }
                   1906: 
1.257     albertel 1907:     if (!$env{'form.lastSub'}) { $env{'form.lastSub'} = 'datesub'; }
                   1908:     if (!$env{'form.vProb'}) { $env{'form.vProb'} = 'yes'; }
                   1909:     if (!$env{'form.vAns'}) { $env{'form.vAns'} = 'yes'; }
                   1910:     my $last = ($env{'form.lastSub'} eq 'last' ? 'last' : '');
1.381     albertel 1911:     my $checkIcon = '<img alt="'.&mt('Check Mark').
                   1912: 	'" src="'.$request->dir_config('lonIconsURL').
1.122     ng       1913: 	'/check.gif" height="16" border="0" />';
1.41      ng       1914: 
1.426     albertel 1915:     my %old_essays;
1.41      ng       1916:     # header info
                   1917:     if ($counter == 0) {
                   1918: 	&sub_page_js($request);
1.621     www      1919: 	&sub_page_kw_js($request);
1.118     ng       1920: 
1.44      ng       1921: 	# option to display problem, only once else it cause problems 
                   1922:         # with the form later since the problem has a form.
1.257     albertel 1923: 	if ($env{'form.vProb'} eq 'yes' or $env{'form.vAns'} eq 'yes') {
1.144     albertel 1924: 	    my $mode;
1.257     albertel 1925: 	    if ($env{'form.vProb'} eq 'yes' && $env{'form.vAns'} eq 'yes') {
1.144     albertel 1926: 		$mode='both';
1.257     albertel 1927: 	    } elsif ($env{'form.vProb'} eq 'yes') {
1.144     albertel 1928: 		$mode='text';
1.257     albertel 1929: 	    } elsif ($env{'form.vAns'} eq 'yes') {
1.144     albertel 1930: 		$mode='answer';
                   1931: 	    }
1.329     albertel 1932: 	    &Apache::lonxml::clear_problem_counter();
1.144     albertel 1933: 	    $request->print(&show_problem($request,$symb,$uname,$udom,0,1,$mode));
1.41      ng       1934: 	}
1.441     www      1935: 
1.44      ng       1936: 	# kwclr is the only variable that is guaranteed to be non blank 
                   1937:         # if this subroutine has been called once.
1.41      ng       1938: 	my %keyhash = ();
1.624     www      1939: #	if ($env{'form.kwclr'} eq '' && $env{'form.handgrade'} eq 'yes') {
                   1940:         if (1) {
1.41      ng       1941: 	    %keyhash = &Apache::lonnet::dump('nohist_handgrade',
1.257     albertel 1942: 					     $env{'course.'.$env{'request.course.id'}.'.domain'},
                   1943: 					     $env{'course.'.$env{'request.course.id'}.'.num'});
1.41      ng       1944: 
1.257     albertel 1945: 	    my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
                   1946: 	    $env{'form.keywords'} = $keyhash{$symb.'_keywords'} ne '' ? $keyhash{$symb.'_keywords'} : '';
                   1947: 	    $env{'form.kwclr'}    = $keyhash{$loginuser.'_kwclr'} ne '' ? $keyhash{$loginuser.'_kwclr'} : 'red';
                   1948: 	    $env{'form.kwsize'}   = $keyhash{$loginuser.'_kwsize'} ne '' ? $keyhash{$loginuser.'_kwsize'} : '0';
                   1949: 	    $env{'form.kwstyle'}  = $keyhash{$loginuser.'_kwstyle'} ne '' ? $keyhash{$loginuser.'_kwstyle'} : '';
                   1950: 	    $env{'form.msgsub'}   = $keyhash{$symb.'_subject'} ne '' ? 
1.605     www      1951: 		$keyhash{$symb.'_subject'} : $probtitle;
1.257     albertel 1952: 	    $env{'form.savemsgN'} = $keyhash{$symb.'_savemsgN'} ne '' ? $keyhash{$symb.'_savemsgN'} : '0';
1.41      ng       1953: 	}
1.257     albertel 1954: 	my $overRideScore = $env{'form.overRideScore'} eq '' ? 'no' : $env{'form.overRideScore'};
1.442     banghart 1955: 	my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
1.303     banghart 1956: 	$request->print('<form action="/adm/grades" method="post" name="SCORE" enctype="multipart/form-data">'."\n".
1.41      ng       1957: 			'<input type="hidden" name="command"    value="handgrade" />'."\n".
1.442     banghart 1958: 			'<input type="hidden" name="Status"     value="'.$stu_status.'" />'."\n".
1.120     ng       1959: 			'<input type="hidden" name="overRideScore" value="'.$overRideScore.'" />'."\n".
1.41      ng       1960: 			'<input type="hidden" name="refresh"    value="off" />'."\n".
1.120     ng       1961: 			'<input type="hidden" name="studentNo"  value="" />'."\n".
                   1962: 			'<input type="hidden" name="gradeOpt"   value="" />'."\n".
1.418     albertel 1963: 			'<input type="hidden" name="symb"       value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.257     albertel 1964: 			'<input type="hidden" name="vProb"      value="'.$env{'form.vProb'}.'" />'."\n".
                   1965: 			'<input type="hidden" name="vAns"       value="'.$env{'form.vAns'}.'" />'."\n".
                   1966: 			'<input type="hidden" name="lastSub"    value="'.$env{'form.lastSub'}.'" />'."\n".
1.432     banghart 1967: 			&build_section_inputs().
1.326     albertel 1968: 			'<input type="hidden" name="submitonly" value="'.$env{'form.submitonly'}.'" />'."\n".
1.41      ng       1969: 			'<input type="hidden" name="NCT"'.
1.257     albertel 1970: 			' value="'.($env{'form.NTSTU'} ne '' ? $env{'form.NTSTU'} : $total+1).'" />'."\n");
1.624     www      1971: #	if ($env{'form.handgrade'} eq 'yes') {
                   1972:         if (1) {
1.257     albertel 1973: 	    $request->print('<input type="hidden" name="keywords" value="'.$env{'form.keywords'}.'" />'."\n".
                   1974: 			    '<input type="hidden" name="kwclr"    value="'.$env{'form.kwclr'}.'" />'."\n".
                   1975: 			    '<input type="hidden" name="kwsize"   value="'.$env{'form.kwsize'}.'" />'."\n".
                   1976: 			    '<input type="hidden" name="kwstyle"  value="'.$env{'form.kwstyle'}.'" />'."\n".
                   1977: 			    '<input type="hidden" name="msgsub"   value="'.$env{'form.msgsub'}.'" />'."\n".
1.123     ng       1978: 			    '<input type="hidden" name="shownSub" value="0" />'."\n".
1.257     albertel 1979: 			    '<input type="hidden" name="savemsgN" value="'.$env{'form.savemsgN'}.'" />'."\n");
1.154     albertel 1980: 	    foreach my $partid (&Apache::loncommon::get_env_multiple('form.vPart')) {
                   1981: 		$request->print('<input type="hidden" name="vPart" value="'.$partid.'" />'."\n");
                   1982: 	    }
1.123     ng       1983: 	}
1.41      ng       1984: 	
                   1985: 	my ($cts,$prnmsg) = (1,'');
1.257     albertel 1986: 	while ($cts <= $env{'form.savemsgN'}) {
1.41      ng       1987: 	    $prnmsg.='<input type="hidden" name="savemsg'.$cts.'" value="'.
1.123     ng       1988: 		(!exists($keyhash{$symb.'_savemsg'.$cts}) ? 
1.257     albertel 1989: 		 &Apache::lonfeedback::clear_out_html($env{'form.savemsg'.$cts}) :
1.80      ng       1990: 		 &Apache::lonfeedback::clear_out_html($keyhash{$symb.'_savemsg'.$cts})).
1.123     ng       1991: 		'" />'."\n".
                   1992: 		'<input type="hidden" name="shownOnce'.$cts.'" value="0" />'."\n";
1.41      ng       1993: 	    $cts++;
                   1994: 	}
                   1995: 	$request->print($prnmsg);
1.32      ng       1996: 
1.624     www      1997: #	if ($env{'form.handgrade'} eq 'yes') {
                   1998:         if (1) {
1.88      www      1999: #
                   2000: # Print out the keyword options line
                   2001: #
1.41      ng       2002: 	    $request->print(<<KEYWORDS);
1.38      ng       2003: &nbsp;<b>Keyword Options:</b>&nbsp;
1.417     albertel 2004: <a href="javascript:keywords(document.SCORE);" target="_self">List</a>&nbsp; &nbsp;
1.589     bisitz   2005: <a href="#" onmousedown="javascript:getSel(); return false"
1.38      ng       2006:  CLASS="page">Paste Selection to List</a>&nbsp; &nbsp;
1.417     albertel 2007: <a href="javascript:kwhighlight();" target="_self">Highlight Attribute</a><br /><br />
1.38      ng       2008: KEYWORDS
1.88      www      2009: #
                   2010: # Load the other essays for similarity check
                   2011: #
1.324     albertel 2012:             my (undef,undef,$essayurl) = &Apache::lonnet::decode_symb($symb);
1.384     albertel 2013: 	    my ($adom,$aname,$apath)=($essayurl=~/^($LONCAPA::domain_re)\/($LONCAPA::username_re)\/(.*)$/);
1.359     www      2014: 	    $apath=&escape($apath);
1.88      www      2015: 	    $apath=~s/\W/\_/gs;
1.426     albertel 2016: 	    %old_essays=&Apache::lonnet::dump('nohist_essay_'.$apath,$adom,$aname);
1.41      ng       2017:         }
                   2018:     }
1.44      ng       2019: 
1.441     www      2020: # This is where output for one specific student would start
1.592     bisitz   2021:     my $add_class = ($counter%2) ? ' LC_grade_show_user_odd_row' : '';
                   2022:     $request->print(
                   2023:         "\n\n"
                   2024:        .'<div class="LC_grade_show_user'.$add_class.'">'
                   2025:        .'<h2>'.&nameUserString(undef,$env{'form.fullname'},$uname,$udom).'</h2>'
                   2026:        ."\n"
                   2027:     );
1.441     www      2028: 
1.592     bisitz   2029:     # Show additional functions if allowed
                   2030:     if ($perm{'vgr'}) {
                   2031:         $request->print(
                   2032:             &Apache::loncommon::track_student_link(
                   2033:                 &mt('View recent activity'),
                   2034:                 $uname,$udom,'check')
                   2035:            .' '
                   2036:         );
                   2037:     }
                   2038:     if ($perm{'opa'}) {
                   2039:         $request->print(
                   2040:             &Apache::loncommon::pprmlink(
                   2041:                 &mt('Set/Change parameters'),
                   2042:                 $uname,$udom,$symb,'check'));
                   2043:     }
                   2044: 
                   2045:     # Show Problem
1.257     albertel 2046:     if ($env{'form.vProb'} eq 'all' or $env{'form.vAns'} eq 'all') {
1.144     albertel 2047: 	my $mode;
1.257     albertel 2048: 	if ($env{'form.vProb'} eq 'all' && $env{'form.vAns'} eq 'all') {
1.144     albertel 2049: 	    $mode='both';
1.257     albertel 2050: 	} elsif ($env{'form.vProb'} eq 'all' ) {
1.144     albertel 2051: 	    $mode='text';
1.257     albertel 2052: 	} elsif ($env{'form.vAns'} eq 'all') {
1.144     albertel 2053: 	    $mode='answer';
                   2054: 	}
1.329     albertel 2055: 	&Apache::lonxml::clear_problem_counter();
1.475     albertel 2056: 	$request->print(&show_problem($request,$symb,$uname,$udom,1,1,$mode,{'request.prefix' => 'ctr'.$counter}));
1.58      albertel 2057:     }
1.144     albertel 2058: 
1.257     albertel 2059:     my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
1.582     raeburn  2060:     my $res_error;
                   2061:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
                   2062:     if ($res_error) {
                   2063:         $request->print(&navmap_errormsg());
                   2064:         return;
                   2065:     }
1.41      ng       2066: 
1.44      ng       2067:     # Display student info
1.41      ng       2068:     $request->print(($counter == 0 ? '' : '<br />'));
1.590     bisitz   2069: 
                   2070:     my $result='<div class="LC_Box">'
                   2071:               .'<h3 class="LC_hcell">'.&mt('Submissions').'</h3>';
1.45      ng       2072:     $result.='<input type="hidden" name="name'.$counter.
1.588     bisitz   2073:              '" value="'.$env{'form.fullname'}.'" />'."\n";
1.624     www      2074: #    if ($env{'form.handgrade'} eq 'no') {
                   2075:     if (1) {
1.588     bisitz   2076:         $result.='<p class="LC_info">'
                   2077:                 .&mt('Part(s) graded correct by the computer is marked with a [_1] symbol.',$checkIcon)
                   2078:                 ."</p>\n";
1.469     albertel 2079:     }
                   2080: 
1.118     ng       2081:     # If any part of the problem is an essay-response (handgraded), then check for collaborators
1.464     albertel 2082:     my $fullname;
                   2083:     my $col_fullnames = [];
1.624     www      2084: #    if ($env{'form.handgrade'} eq 'yes') {
                   2085:     if (1) {
1.464     albertel 2086: 	(my $sub_result,$fullname,$col_fullnames)=
                   2087: 	    &check_collaborators($symb,$uname,$udom,\%record,$handgrade,
                   2088: 				 $counter);
                   2089: 	$result.=$sub_result;
1.41      ng       2090:     }
1.44      ng       2091:     $request->print($result."\n");
1.588     bisitz   2092: 
1.44      ng       2093:     # print student answer/submission
1.588     bisitz   2094:     # Options are (1) Handgraded submission only
1.44      ng       2095:     #             (2) Last submission, includes submission that is not handgraded 
                   2096:     #                  (for multi-response type part)
                   2097:     #             (3) Last submission plus the parts info
                   2098:     #             (4) The whole record for this student
1.257     albertel 2099:     if ($env{'form.lastSub'} =~ /^(lastonly|hdgrade)$/) {
1.151     albertel 2100: 	my ($string,$timestamp)= &get_last_submission(\%record);
1.468     albertel 2101: 	
                   2102: 	my $lastsubonly;
                   2103: 
1.588     bisitz   2104:         if ($$timestamp eq '') {
                   2105:             $lastsubonly.='<div class="LC_grade_submissions_body">'.$$string[0].'</div>'; 
                   2106:         } else {
1.592     bisitz   2107:             $lastsubonly =
                   2108:                 '<div class="LC_grade_submissions_body">'
                   2109:                .'<b>'.&mt('Date Submitted:').'</b> '.$$timestamp."\n";
1.468     albertel 2110: 
1.151     albertel 2111: 	    my %seenparts;
1.375     albertel 2112: 	    my @part_response_id = &flatten_responseType($responseType);
                   2113: 	    foreach my $part (@part_response_id) {
1.393     albertel 2114: 		next if ($env{'form.lastSub'} eq 'hdgrade' 
                   2115: 			 && $$handgrade{$$part[0].'_'.$$part[1]} ne 'yes');
                   2116: 
1.375     albertel 2117: 		my ($partid,$respid) = @{ $part };
1.324     albertel 2118: 		my $display_part=&get_display_part($partid,$symb);
1.257     albertel 2119: 		if ($env{"form.$uname:$udom:$partid:submitted_by"}) {
1.151     albertel 2120: 		    if (exists($seenparts{$partid})) { next; }
                   2121: 		    $seenparts{$partid}=1;
1.207     albertel 2122: 		    my $submitby='<b>Part:</b> '.$display_part.
                   2123: 			' <b>Collaborative submission by:</b> '.
1.151     albertel 2124: 			'<a href="javascript:viewSubmitter(\''.
1.257     albertel 2125: 			$env{"form.$uname:$udom:$partid:submitted_by"}.
1.417     albertel 2126: 			'\');" target="_self">'.
1.257     albertel 2127: 			$$fullname{$env{"form.$uname:$udom:$partid:submitted_by"}}.'</a><br />';
1.151     albertel 2128: 		    $request->print($submitby);
                   2129: 		    next;
                   2130: 		}
                   2131: 		my $responsetype = $responseType->{$partid}->{$respid};
                   2132: 		if (!exists($record{"resource.$partid.$respid.submission"})) {
1.577     bisitz   2133:                     $lastsubonly.="\n".'<div class="LC_grade_submission_part">'.
                   2134:                         '<b>'.&mt('Part: [_1]',$display_part).'</b>'.
                   2135:                         ' <span class="LC_internal_info">'.
1.623     www      2136:                         '('.&mt('Response ID: [_1]',$respid).')'.
1.577     bisitz   2137:                         '</span>&nbsp; &nbsp;'.
1.539     riegler  2138: 			'<span class="LC_warning">'.&mt('Nothing submitted - no attempts.').'</span><br /><br /></div>';
1.151     albertel 2139: 		    next;
                   2140: 		}
1.468     albertel 2141: 		foreach my $submission (@$string) {
                   2142: 		    my ($partid,$respid) = ($submission =~ /^resource\.([^\.]*)\.([^\.]*)\.submission/);
1.375     albertel 2143: 		    if (join('_',@{$part}) ne ($partid.'_'.$respid)) { next; }
1.596     raeburn  2144: 		    my ($ressub,$hide,$subval) = split(/:/,$submission,3);
1.151     albertel 2145: 		    # Similarity check
                   2146: 		    my $similar='';
1.640   ! raeburn  2147:                     my ($type,$trial,$rndseed);
        !          2148:                     if ($hide eq 'rand') {
        !          2149:                         $type = 'randomizetry';
        !          2150:                         $trial = $record{"resource.$partid.tries"};
        !          2151:                         $rndseed = $record{"resource.$partid.rndseed"};
        !          2152:                     }
1.257     albertel 2153: 		    if($env{'form.checkPlag'}){
1.151     albertel 2154: 			my ($oname,$odom,$ocrsid,$oessay,$osim)=
1.426     albertel 2155: 			    &most_similar($uname,$udom,$subval,\%old_essays);
1.151     albertel 2156: 			if ($osim) {
                   2157: 			    $osim=int($osim*100.0);
1.426     albertel 2158: 			    my %old_course_desc = 
                   2159: 				&Apache::lonnet::coursedescription($ocrsid,
                   2160: 								   {'one_time' => 1});
                   2161: 
1.640   ! raeburn  2162:                             if ($hide eq 'anon') {
1.596     raeburn  2163:                                 $similar='<hr /><span class="LC_warning">'.&mt("Essay was found to be similar to another essay submitted for this assignment.").'<br />'.
                   2164:                                          &mt('As the current submission is for an anonymous survey, no other details are available.').'</span><hr />';
                   2165:                             } else {
                   2166: 			        $similar="<hr /><h3><span class=\"LC_warning\">".
                   2167: 				    &mt('Essay is [_1]% similar to an essay by [_2] in course [_3] (course id [_4]:[_5])',
                   2168: 				        $osim,
                   2169: 				        &Apache::loncommon::plainname($oname,$odom).' ('.$oname.':'.$odom.')',
                   2170: 				        $old_course_desc{'description'},
                   2171: 				        $old_course_desc{'num'},
                   2172: 				        $old_course_desc{'domain'}).
                   2173: 				    '</span></h3><blockquote><i>'.
                   2174: 				    &keywords_highlight($oessay).
                   2175: 				    '</i></blockquote><hr />';
                   2176:                             }
1.151     albertel 2177: 			}
1.150     albertel 2178: 		    }
1.640   ! raeburn  2179: 		    my $order=&get_order($partid,$respid,$symb,$uname,$udom,
        !          2180:                                          undef,$type,$trial,$rndseed);
1.257     albertel 2181: 		    if ($env{'form.lastSub'} eq 'lastonly' || 
                   2182: 			($env{'form.lastSub'} eq 'hdgrade' && 
1.377     albertel 2183: 			 $$handgrade{$$part[0].'_'.$$part[1]} eq 'yes')) {
1.324     albertel 2184: 			my $display_part=&get_display_part($partid,$symb);
1.577     bisitz   2185:                         $lastsubonly.='<div class="LC_grade_submission_part">'.
                   2186:                             '<b>'.&mt('Part: [_1]',$display_part).'</b>'.
                   2187:                             ' <span class="LC_internal_info">'.
1.623     www      2188:                             '('.&mt('Response ID: [_1]',$respid).')'.
1.597     wenzelju 2189:                             '</span>&nbsp; &nbsp;';
1.313     banghart 2190: 			my $files=&get_submitted_files($udom,$uname,$partid,$respid,\%record);
                   2191: 			if (@$files) {
1.640   ! raeburn  2192:                             if ($hide eq 'anon') {
1.596     raeburn  2193:                                 $lastsubonly.='<br />'.&mt('[quant,_1,file] uploaded to this anonymous survey',scalar(@{$files}));
                   2194:                             } else {
                   2195:                                 $lastsubonly.='<br /><span class="LC_warning">'.&mt('Like all files provided by users, this file may contain viruses').'</span><br />';
                   2196:                                 foreach my $file (@$files) {
                   2197:                                     &Apache::lonnet::allowuploaded('/adm/grades',$file);
                   2198:                                     $lastsubonly.='<br /><a href="'.$file.'?rawmode=1" target="lonGRDs"><img src="'.&Apache::loncommon::icon($file).'" border="0" /> '.$file.'</a>';
                   2199:                                 }
                   2200:                             }
1.236     albertel 2201: 			    $lastsubonly.='<br />';
1.41      ng       2202: 			}
1.640   ! raeburn  2203:                         if ($hide eq 'anon') {
1.596     raeburn  2204:                             $lastsubonly.='<b>'.&mt('Anonymous Survey').'</b>'; 
                   2205:                         } else {
                   2206: 			    $lastsubonly.='<b>'.&mt('Submitted Answer:').' </b>'.
                   2207: 			        &cleanRecord($subval,$responsetype,$symb,$partid,
1.640   ! raeburn  2208: 					     $respid,\%record,$order,undef,$uname,$udom,$type,$trial,$rndseed);
1.596     raeburn  2209:                         }
1.151     albertel 2210: 			if ($similar) {$lastsubonly.="<br /><br />$similar\n";}
1.468     albertel 2211: 			$lastsubonly.='</div>';
1.41      ng       2212: 		    }
                   2213: 		}
                   2214: 	    }
1.588     bisitz   2215: 	    $lastsubonly.='</div>'."\n"; # End: LC_grade_submissions_body
1.151     albertel 2216: 	}
                   2217: 	$request->print($lastsubonly);
1.468     albertel 2218:    } elsif ($env{'form.lastSub'} eq 'datesub') {
1.623     www      2219:         my ($parts,$handgrade,$responseType) = &response_type($symb,\$res_error);
1.148     albertel 2220: 	$request->print(&displaySubByDates($symb,\%record,$parts,$responseType,$checkIcon,$uname,$udom));
1.257     albertel 2221:     } elsif ($env{'form.lastSub'} =~ /^(last|all)$/) {
1.41      ng       2222: 	$request->print(&Apache::loncommon::get_previous_attempt($symb,$uname,$udom,
1.257     albertel 2223: 								 $env{'request.course.id'},
1.44      ng       2224: 								 $last,'.submission',
                   2225: 								 'Apache::grades::keywords_highlight'));
1.41      ng       2226:     }
1.121     ng       2227:     $request->print('<input type="hidden" name="unamedom'.$counter.'" value="'.$uname.':'
                   2228: 	.$udom.'" />'."\n");
1.44      ng       2229:     # return if view submission with no grading option
1.618     www      2230:     if (!&canmodify($usec)) {
1.633     www      2231: 	$request->print('<p><span class="LC_warning">'.&mt('No grading privileges').'</span></p></div>');
1.41      ng       2232: 	return;
1.180     albertel 2233:     } else {
1.468     albertel 2234: 	$request->print('</div>'."\n");
1.41      ng       2235:     }
1.33      ng       2236: 
1.121     ng       2237:     # essay grading message center
1.624     www      2238: #    if ($env{'form.handgrade'} eq 'yes') {
                   2239:     if (1) {
1.468     albertel 2240: 	my $result='<div class="LC_grade_message_center">';
                   2241:     
                   2242: 	$result.='<div class="LC_grade_message_center_header">'.
                   2243: 	    &mt('Send Message').'</div><div class="LC_grade_message_center_body">';
1.257     albertel 2244: 	my ($lastname,$givenn) = split(/,/,$env{'form.fullname'});
1.118     ng       2245: 	my $msgfor = $givenn.' '.$lastname;
1.464     albertel 2246: 	if (scalar(@$col_fullnames) > 0) {
                   2247: 	    my $lastone = pop(@$col_fullnames);
                   2248: 	    $msgfor .= ', '.(join ', ',@$col_fullnames).' and '.$lastone.'.';
1.118     ng       2249: 	}
                   2250: 	$msgfor =~ s/\'/\\'/g; #' stupid emacs - no! javascript
1.468     albertel 2251: 	$result.='<input type="hidden" name="includemsg'.$counter.'" value="" />'."\n".
1.121     ng       2252: 	    '<input type="hidden" name="newmsg'.$counter.'" value="" />'."\n";
                   2253: 	$result.='&nbsp;<a href="javascript:msgCenter(document.SCORE,'.$counter.
1.417     albertel 2254: 	    ',\''.$msgfor.'\');" target="_self">'.
1.464     albertel 2255: 	    &mt('Compose message to student').(scalar(@$col_fullnames) >= 1 ? 's' : '').'</a><label> ('.
1.350     albertel 2256: 	    &mt('incl. grades').' <input type="checkbox" name="withgrades'.$counter.'" /></label>)'.
1.118     ng       2257: 	    '<img src="'.$request->dir_config('lonIconsURL').
                   2258: 	    '/mailbkgrd.gif" width="14" height="10" name="mailicon'.$counter.'" />'."\n".
1.298     www      2259: 	    '<br />&nbsp;('.
1.468     albertel 2260: 	    &mt('Message will be sent when you click on Save &amp; Next below.').")\n";
                   2261: 	$result.='</div></div>';
1.121     ng       2262: 	$request->print($result);
1.118     ng       2263:     }
1.41      ng       2264: 
                   2265:     my %seen = ();
                   2266:     my @partlist;
1.129     ng       2267:     my @gradePartRespid;
1.375     albertel 2268:     my @part_response_id = &flatten_responseType($responseType);
1.585     bisitz   2269:     $request->print(
1.588     bisitz   2270:         '<div class="LC_Box">'
                   2271:        .'<h3 class="LC_hcell">'.&mt('Assign Grades').'</h3>'
1.585     bisitz   2272:     );
1.592     bisitz   2273:     $request->print(&gradeBox_start());
1.375     albertel 2274:     foreach my $part_response_id (@part_response_id) {
                   2275:     	my ($partid,$respid) = @{ $part_response_id };
                   2276: 	my $part_resp = join('_',@{ $part_response_id });
1.322     albertel 2277: 	next if ($seen{$partid} > 0);
1.41      ng       2278: 	$seen{$partid}++;
1.393     albertel 2279: 	next if ($$handgrade{$part_resp} ne 'yes' 
                   2280: 		 && $env{'form.lastSub'} eq 'hdgrade');
1.524     raeburn  2281: 	push(@partlist,$partid);
                   2282: 	push(@gradePartRespid,$partid.'.'.$respid);
1.322     albertel 2283: 	$request->print(&gradeBox($request,$symb,$uname,$udom,$counter,$partid,\%record));
1.41      ng       2284:     }
1.585     bisitz   2285:     $request->print(&gradeBox_end()); # </div>
                   2286:     $request->print('</div>');
1.468     albertel 2287: 
                   2288:     $request->print('<div class="LC_grade_info_links">');
                   2289:     $request->print('</div>');
                   2290: 
1.45      ng       2291:     $result='<input type="hidden" name="partlist'.$counter.
                   2292: 	'" value="'.(join ":",@partlist).'" />'."\n";
1.129     ng       2293:     $result.='<input type="hidden" name="gradePartRespid'.
                   2294: 	'" value="'.(join ":",@gradePartRespid).'" />'."\n" if ($counter == 0);
1.45      ng       2295:     my $ctr = 0;
                   2296:     while ($ctr < scalar(@partlist)) {
                   2297: 	$result.='<input type="hidden" name="partid'.$counter.'_'.$ctr.'" value="'.
                   2298: 	    $partlist[$ctr].'" />'."\n";
                   2299: 	$ctr++;
                   2300:     }
1.468     albertel 2301:     $request->print($result.''."\n");
1.41      ng       2302: 
1.441     www      2303: # Done with printing info for one student
                   2304: 
1.468     albertel 2305:     $request->print('</div>');#LC_grade_show_user
1.441     www      2306: 
                   2307: 
1.41      ng       2308:     # print end of form
                   2309:     if ($counter == $total) {
1.592     bisitz   2310:         my $endform='<br /><hr /><table border="0"><tr><td>'."\n";
1.485     albertel 2311: 	$endform.='<input type="button" value="'.&mt('Save &amp; Next').'" '.
1.589     bisitz   2312: 	    'onclick="javascript:checksubmit(this.form,\'Save & Next\','.
1.417     albertel 2313: 	    $total.','.scalar(@partlist).');" target="_self" /> &nbsp;'."\n";
1.119     ng       2314: 	my $ntstu ='<select name="NTSTU">'.
                   2315: 	    '<option>1</option><option>2</option>'.
                   2316: 	    '<option>3</option><option>5</option>'.
                   2317: 	    '<option>7</option><option>10</option></select>'."\n";
1.257     albertel 2318: 	my $nsel = ($env{'form.NTSTU'} ne '' ? $env{'form.NTSTU'} : '1');
1.401     albertel 2319: 	$ntstu =~ s/<option>$nsel</<option selected="selected">$nsel</;
1.578     raeburn  2320:         $endform.=&mt('[_1]student(s)',$ntstu);
1.485     albertel 2321: 	$endform.='&nbsp;&nbsp;<input type="button" value="'.&mt('Previous').'" '.
1.589     bisitz   2322: 	    'onclick="javascript:checksubmit(this.form,\'Previous\');" target="_self" /> &nbsp;'."\n".
1.485     albertel 2323: 	    '<input type="button" value="'.&mt('Next').'" '.
1.589     bisitz   2324: 	    'onclick="javascript:checksubmit(this.form,\'Next\');" target="_self" /> &nbsp;';
1.592     bisitz   2325:         $endform.='<span class="LC_warning">'.
                   2326:                   &mt('(Next and Previous (student) do not save the scores.)').
                   2327:                   '</span>'."\n" ;
1.349     albertel 2328:         $endform.="<input type='hidden' value='".&get_increment().
1.348     bowersj2 2329:             "' name='increment' />";
1.485     albertel 2330: 	$endform.='</td></tr></table></form>';
1.41      ng       2331: 	$request->print($endform);
                   2332:     }
                   2333:     return '';
1.38      ng       2334: }
                   2335: 
1.464     albertel 2336: sub check_collaborators {
                   2337:     my ($symb,$uname,$udom,$record,$handgrade,$counter) = @_;
                   2338:     my ($result,@col_fullnames);
                   2339:     my ($classlist,undef,$fullname) = &getclasslist('all','0');
                   2340:     foreach my $part (keys(%$handgrade)) {
                   2341: 	my $ncol = &Apache::lonnet::EXT('resource.'.$part.
                   2342: 					'.maxcollaborators',
                   2343: 					$symb,$udom,$uname);
                   2344: 	next if ($ncol <= 0);
                   2345: 	$part =~ s/\_/\./g;
                   2346: 	next if ($record->{'resource.'.$part.'.collaborators'} eq '');
                   2347: 	my (@good_collaborators, @bad_collaborators);
                   2348: 	foreach my $possible_collaborator
1.630     www      2349: 	    (split(/[,;\s]+/,$record->{'resource.'.$part.'.collaborators'})) { 
1.464     albertel 2350: 	    $possible_collaborator =~ s/[\$\^\(\)]//g;
                   2351: 	    next if ($possible_collaborator eq '');
1.631     www      2352: 	    my ($co_name,$co_dom) = split(/:/,$possible_collaborator);
1.464     albertel 2353: 	    $co_dom = $udom if (! defined($co_dom) || $co_dom =~ /^domain$/i);
                   2354: 	    next if ($co_name eq $uname && $co_dom eq $udom);
                   2355: 	    # Doing this grep allows 'fuzzy' specification
                   2356: 	    my @matches = grep(/^\Q$co_name\E:\Q$co_dom\E$/i, 
                   2357: 			       keys(%$classlist));
                   2358: 	    if (! scalar(@matches)) {
                   2359: 		push(@bad_collaborators, $possible_collaborator);
                   2360: 	    } else {
                   2361: 		push(@good_collaborators, @matches);
                   2362: 	    }
                   2363: 	}
                   2364: 	if (scalar(@good_collaborators) != 0) {
1.630     www      2365: 	    $result.='<br />'.&mt('Collaborators:').'<ol>';
1.464     albertel 2366: 	    foreach my $name (@good_collaborators) {
                   2367: 		my ($lastname,$givenn) = split(/,/,$$fullname{$name});
                   2368: 		push(@col_fullnames, $givenn.' '.$lastname);
1.630     www      2369: 		$result.='<li>'.$fullname->{$name}.'</li>';
1.464     albertel 2370: 	    }
1.630     www      2371: 	    $result.='</ol><br />'."\n";
1.466     albertel 2372: 	    my ($part)=split(/\./,$part);
1.464     albertel 2373: 	    $result.='<input type="hidden" name="collaborator'.$counter.
                   2374: 		'" value="'.$part.':'.(join ':',@good_collaborators).'" />'.
                   2375: 		"\n";
                   2376: 	}
                   2377: 	if (scalar(@bad_collaborators) > 0) {
1.466     albertel 2378: 	    $result.='<div class="LC_warning">';
1.464     albertel 2379: 	    $result.=&mt('This student has submitted [quant,_1,invalid collaborator]: [_2]',scalar(@bad_collaborators),join(', ',@bad_collaborators));
                   2380: 	    $result .= '</div>';
                   2381: 	}         
                   2382: 	if (scalar(@bad_collaborators > $ncol)) {
1.466     albertel 2383: 	    $result .= '<div class="LC_warning">';
1.464     albertel 2384: 	    $result .= &mt('This student has submitted too many '.
                   2385: 		'collaborators.  Maximum is [_1].',$ncol);
                   2386: 	    $result .= '</div>';
                   2387: 	}
                   2388:     }
                   2389:     return ($result,$fullname,\@col_fullnames);
                   2390: }
                   2391: 
1.44      ng       2392: #--- Retrieve the last submission for all the parts
1.38      ng       2393: sub get_last_submission {
1.119     ng       2394:     my ($returnhash)=@_;
1.596     raeburn  2395:     my (@string,$timestamp,%lasthidden);
1.119     ng       2396:     if ($$returnhash{'version'}) {
1.46      ng       2397: 	my %lasthash=();
                   2398: 	my ($version);
1.119     ng       2399: 	for ($version=1;$version<=$$returnhash{'version'};$version++) {
1.397     albertel 2400: 	    foreach my $key (sort(split(/\:/,
                   2401: 					$$returnhash{$version.':keys'}))) {
                   2402: 		$lasthash{$key}=$$returnhash{$version.':'.$key};
                   2403: 		$timestamp = 
1.545     raeburn  2404: 		    &Apache::lonlocal::locallocaltime($$returnhash{$version.':timestamp'});
1.46      ng       2405: 	    }
                   2406: 	}
1.640   ! raeburn  2407:         my (%typeparts,%randombytry);
1.596     raeburn  2408:         my $showsurv = 
                   2409:             &Apache::lonnet::allowed('vas',$env{'request.course.id'});
                   2410:         foreach my $key (sort(keys(%lasthash))) {
                   2411:             if ($key =~ /\.type$/) {
                   2412:                 if (($lasthash{$key} eq 'anonsurvey') || 
1.640   ! raeburn  2413:                     ($lasthash{$key} eq 'anonsurveycred') ||
        !          2414:                     ($lasthash{$key} eq 'randomizetry')) {
1.596     raeburn  2415:                     my ($ign,@parts) = split(/\./,$key);
                   2416:                     pop(@parts);
1.640   ! raeburn  2417:                     if ($lasthash{$key} eq 'randomizetry') {
1.596     raeburn  2418:                         my $id = join(',',@parts);
1.640   ! raeburn  2419:                         $randombytry{$ign.'.'.$id} = $lasthash{$key};
        !          2420:                     } else {
        !          2421:                         unless ($showsurv) {
        !          2422:                             my $id = join(',',@parts);
        !          2423:                             $typeparts{$ign.'.'.$id} = $lasthash{$key};
        !          2424:                         }
1.596     raeburn  2425:                     }
                   2426:                     delete($lasthash{$key});
                   2427:                 }
                   2428:             }
                   2429:         }
                   2430:         my @hidden = keys(%typeparts);
1.640   ! raeburn  2431:         my @randomize = keys(%randombytry);
1.397     albertel 2432: 	foreach my $key (keys(%lasthash)) {
                   2433: 	    next if ($key !~ /\.submission$/);
1.596     raeburn  2434:             my $hide;
                   2435:             if (@hidden) {
                   2436:                 foreach my $id (@hidden) {
                   2437:                     if ($key =~ /^\Q$id\E/) {
1.640   ! raeburn  2438:                         $hide = 'anon';
1.596     raeburn  2439:                         last;
                   2440:                     }
                   2441:                 }
                   2442:             }
1.640   ! raeburn  2443:             unless ($hide) {
        !          2444:                 if (@randomize) {
        !          2445:                     foreach my $id (@hidden) {
        !          2446:                         if ($key =~ /^\Q$id\E/) {
        !          2447:                             $hide = 'rand';
        !          2448:                             last;
        !          2449:                         }
        !          2450:                     }
        !          2451:                 }
        !          2452:             }
1.397     albertel 2453: 	    my ($partid,$foo) = split(/submission$/,$key);
                   2454: 	    my $draft  = $lasthash{$partid.'awarddetail'} eq 'DRAFT' ?
1.398     albertel 2455: 		'<span class="LC_warning">Draft Copy</span> ' : '';
1.596     raeburn  2456: 	    push(@string, join(':', $key, $hide, $draft.$lasthash{$key}));
1.41      ng       2457: 	}
                   2458:     }
1.397     albertel 2459:     if (!@string) {
                   2460: 	$string[0] =
1.539     riegler  2461: 	    '<span class="LC_warning">'.&mt('Nothing submitted - no attempts.').'</span>';
1.397     albertel 2462:     }
                   2463:     return (\@string,\$timestamp);
1.38      ng       2464: }
1.35      ng       2465: 
1.44      ng       2466: #--- High light keywords, with style choosen by user.
1.38      ng       2467: sub keywords_highlight {
1.44      ng       2468:     my $string    = shift;
1.257     albertel 2469:     my $size      = $env{'form.kwsize'} eq '0' ? '' : 'size='.$env{'form.kwsize'};
                   2470:     my $styleon   = $env{'form.kwstyle'} eq ''  ? '' : $env{'form.kwstyle'};
1.41      ng       2471:     (my $styleoff = $styleon) =~ s/\</\<\//;
1.257     albertel 2472:     my @keylist   = split(/[,\s+]/,$env{'form.keywords'});
1.398     albertel 2473:     foreach my $keyword (@keylist) {
                   2474: 	$string =~ s/\b\Q$keyword\E(\b|\.)/<font color\=$env{'form.kwclr'} $size\>$styleon$keyword$styleoff<\/font>/gi;
1.41      ng       2475:     }
                   2476:     return $string;
1.38      ng       2477: }
1.36      ng       2478: 
1.44      ng       2479: #--- Called from submission routine
1.38      ng       2480: sub processHandGrade {
1.608     www      2481:     my ($request,$symb) = @_;
1.324     albertel 2482:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
1.257     albertel 2483:     my $button = $env{'form.gradeOpt'};
                   2484:     my $ngrade = $env{'form.NCT'};
                   2485:     my $ntstu  = $env{'form.NTSTU'};
1.301     albertel 2486:     my $cdom   = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   2487:     my $cnum   = $env{'course.'.$env{'request.course.id'}.'.num'};
                   2488: 
1.44      ng       2489:     if ($button eq 'Save & Next') {
                   2490: 	my $ctr = 0;
                   2491: 	while ($ctr < $ngrade) {
1.257     albertel 2492: 	    my ($uname,$udom) = split(/:/,$env{'form.unamedom'.$ctr});
1.324     albertel 2493: 	    my ($errorflag,$pts,$wgt) = &saveHandGrade($request,$symb,$uname,$udom,$ctr);
1.71      ng       2494: 	    if ($errorflag eq 'no_score') {
                   2495: 		$ctr++;
                   2496: 		next;
                   2497: 	    }
1.104     albertel 2498: 	    if ($errorflag eq 'not_allowed') {
1.398     albertel 2499: 		$request->print("<span class=\"LC_warning\">Not allowed to modify grades for $uname:$udom</span>");
1.104     albertel 2500: 		$ctr++;
                   2501: 		next;
                   2502: 	    }
1.257     albertel 2503: 	    my $includemsg = $env{'form.includemsg'.$ctr};
1.44      ng       2504: 	    my ($subject,$message,$msgstatus) = ('','','');
1.418     albertel 2505: 	    my $restitle = &Apache::lonnet::gettitle($symb);
                   2506:             my ($feedurl,$showsymb) =
                   2507: 		&get_feedurl_and_symb($symb,$uname,$udom);
                   2508: 	    my $messagetail;
1.62      albertel 2509: 	    if ($includemsg =~ /savemsg|newmsg\Q$ctr\E/) {
1.298     www      2510: 		$subject = $env{'form.msgsub'} if ($includemsg =~ /msgsub/);
1.295     www      2511: 		unless ($subject=~/\w/) { $subject=&mt('Grading Feedback'); }
1.386     raeburn  2512: 		$subject.=' ['.$restitle.']';
1.44      ng       2513: 		my (@msgnum) = split(/,/,$includemsg);
                   2514: 		foreach (@msgnum) {
1.257     albertel 2515: 		    $message.=$env{'form.'.$_} if ($_ =~ /savemsg|newmsg/ && $_ ne '');
1.44      ng       2516: 		}
1.80      ng       2517: 		$message =&Apache::lonfeedback::clear_out_html($message);
1.298     www      2518: 		if ($env{'form.withgrades'.$ctr}) {
                   2519: 		    $message.="\n\nPoint".($pts > 1 ? 's':'').' awarded = '.$pts.' out of '.$wgt;
1.386     raeburn  2520: 		    $messagetail = " for <a href=\"".
1.605     www      2521: 		                   $feedurl."?symb=$showsymb\">$restitle</a>";
1.386     raeburn  2522: 		}
                   2523: 		$msgstatus = 
                   2524:                     &Apache::lonmsg::user_normal_msg($uname,$udom,$subject,
                   2525: 						     $message.$messagetail,
1.418     albertel 2526:                                                      undef,$feedurl,undef,
1.386     raeburn  2527:                                                      undef,undef,$showsymb,
                   2528:                                                      $restitle);
1.574     bisitz   2529: 		$request->print('<br />'.&mt('Sending message to [_1]',$uname.':'.$udom).': '.
1.296     www      2530: 				$msgstatus);
1.44      ng       2531: 	    }
1.257     albertel 2532: 	    if ($env{'form.collaborator'.$ctr}) {
1.155     albertel 2533: 		my @collabstrs=&Apache::loncommon::get_env_multiple("form.collaborator$ctr");
1.150     albertel 2534: 		foreach my $collabstr (@collabstrs) {
                   2535: 		    my ($part,@collaborators) = split(/:/,$collabstr);
1.310     banghart 2536: 		    foreach my $collaborator (@collaborators) {
1.150     albertel 2537: 			my ($errorflag,$pts,$wgt) = 
1.324     albertel 2538: 			    &saveHandGrade($request,$symb,$collaborator,$udom,$ctr,
1.257     albertel 2539: 					   $env{'form.unamedom'.$ctr},$part);
1.150     albertel 2540: 			if ($errorflag eq 'not_allowed') {
1.362     albertel 2541: 			    $request->print("<span class=\"LC_error\">".&mt('Not allowed to modify grades for [_1]',"$collaborator:$udom")."</span>");
1.150     albertel 2542: 			    next;
1.418     albertel 2543: 			} elsif ($message ne '') {
                   2544: 			    my ($baseurl,$showsymb) = 
                   2545: 				&get_feedurl_and_symb($symb,$collaborator,
                   2546: 						      $udom);
                   2547: 			    if ($env{'form.withgrades'.$ctr}) {
                   2548: 				$messagetail = " for <a href=\"".
1.605     www      2549:                                     $baseurl."?symb=$showsymb\">$restitle</a>";
1.150     albertel 2550: 			    }
1.418     albertel 2551: 			    $msgstatus = 
                   2552: 				&Apache::lonmsg::user_normal_msg($collaborator,$udom,$subject,$message.$messagetail,undef,$baseurl,undef,undef,undef,$showsymb,$restitle);
1.104     albertel 2553: 			}
1.44      ng       2554: 		    }
                   2555: 		}
                   2556: 	    }
                   2557: 	    $ctr++;
                   2558: 	}
                   2559:     }
                   2560: 
1.624     www      2561: #    if ($env{'form.handgrade'} eq 'yes') {
                   2562:     if (1) {
1.119     ng       2563: 	# Keywords sorted in alphabatical order
1.257     albertel 2564: 	my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
1.119     ng       2565: 	my %keyhash = ();
1.257     albertel 2566: 	$env{'form.keywords'}           =~ s/,\s{0,}|\s+/ /g;
                   2567: 	$env{'form.keywords'}           =~ s/^\s+|\s+$//;
                   2568: 	my (@keywords) = sort(split(/\s+/,$env{'form.keywords'}));
                   2569: 	$env{'form.keywords'} = join(' ',@keywords);
                   2570: 	$keyhash{$symb.'_keywords'}     = $env{'form.keywords'};
                   2571: 	$keyhash{$symb.'_subject'}      = $env{'form.msgsub'};
                   2572: 	$keyhash{$loginuser.'_kwclr'}   = $env{'form.kwclr'};
                   2573: 	$keyhash{$loginuser.'_kwsize'}  = $env{'form.kwsize'};
                   2574: 	$keyhash{$loginuser.'_kwstyle'} = $env{'form.kwstyle'};
1.119     ng       2575: 
                   2576: 	# message center - Order of message gets changed. Blank line is eliminated.
1.257     albertel 2577: 	# New messages are saved in env for the next student.
1.119     ng       2578: 	# All messages are saved in nohist_handgrade.db
                   2579: 	my ($ctr,$idx) = (1,1);
1.257     albertel 2580: 	while ($ctr <= $env{'form.savemsgN'}) {
                   2581: 	    if ($env{'form.savemsg'.$ctr} ne '') {
                   2582: 		$keyhash{$symb.'_savemsg'.$idx} = $env{'form.savemsg'.$ctr};
1.119     ng       2583: 		$idx++;
                   2584: 	    }
                   2585: 	    $ctr++;
1.41      ng       2586: 	}
1.119     ng       2587: 	$ctr = 0;
                   2588: 	while ($ctr < $ngrade) {
1.257     albertel 2589: 	    if ($env{'form.newmsg'.$ctr} ne '') {
                   2590: 		$keyhash{$symb.'_savemsg'.$idx} = $env{'form.newmsg'.$ctr};
                   2591: 		$env{'form.savemsg'.$idx} = $env{'form.newmsg'.$ctr};
1.119     ng       2592: 		$idx++;
                   2593: 	    }
                   2594: 	    $ctr++;
1.41      ng       2595: 	}
1.257     albertel 2596: 	$env{'form.savemsgN'} = --$idx;
                   2597: 	$keyhash{$symb.'_savemsgN'} = $env{'form.savemsgN'};
1.119     ng       2598: 	my $putresult = &Apache::lonnet::put
1.301     albertel 2599: 	    ('nohist_handgrade',\%keyhash,$cdom,$cnum);
1.41      ng       2600:     }
1.44      ng       2601:     # Called by Save & Refresh from Highlight Attribute Window
1.257     albertel 2602:     my (undef,undef,$fullname) = &getclasslist($env{'form.section'},'1');
                   2603:     if ($env{'form.refresh'} eq 'on') {
1.86      ng       2604: 	my ($ctr,$total) = (0,0);
                   2605: 	while ($ctr < $ngrade) {
1.257     albertel 2606: 	    $total++ if  $env{'form.unamedom'.$ctr} ne '';
1.86      ng       2607: 	    $ctr++;
                   2608: 	}
1.257     albertel 2609: 	$env{'form.NTSTU'}=$ngrade;
1.86      ng       2610: 	$ctr = 0;
                   2611: 	while ($ctr < $total) {
1.257     albertel 2612: 	    my $processUser = $env{'form.unamedom'.$ctr};
                   2613: 	    ($env{'form.student'},$env{'form.userdom'}) = split(/:/,$processUser);
                   2614: 	    $env{'form.fullname'} = $$fullname{$processUser};
1.625     www      2615: 	    &submission($request,$ctr,$total-1,$symb);
1.41      ng       2616: 	    $ctr++;
                   2617: 	}
                   2618: 	return '';
                   2619:     }
1.36      ng       2620: 
1.44      ng       2621:     # Get the next/previous one or group of students
1.257     albertel 2622:     my $firststu = $env{'form.unamedom0'};
                   2623:     my $laststu = $env{'form.unamedom'.($ngrade-1)};
1.119     ng       2624:     my $ctr = 2;
1.41      ng       2625:     while ($laststu eq '') {
1.257     albertel 2626: 	$laststu  = $env{'form.unamedom'.($ngrade-$ctr)};
1.41      ng       2627: 	$ctr++;
                   2628: 	$laststu = $firststu if ($ctr > $ngrade);
                   2629:     }
1.44      ng       2630: 
1.41      ng       2631:     my (@parsedlist,@nextlist);
                   2632:     my ($nextflg) = 0;
1.524     raeburn  2633:     foreach my $item (sort 
1.294     albertel 2634: 	     {
                   2635: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                   2636: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                   2637: 		 }
                   2638: 		 return $a cmp $b;
                   2639: 	     } (keys(%$fullname))) {
1.605     www      2640: # FIXME: this is fishy, looks like the button label
1.41      ng       2641: 	if ($nextflg == 1 && $button =~ /Next$/) {
1.524     raeburn  2642: 	    push(@parsedlist,$item);
1.41      ng       2643: 	}
1.524     raeburn  2644: 	$nextflg = 1 if ($item eq $laststu);
1.41      ng       2645: 	if ($button eq 'Previous') {
1.524     raeburn  2646: 	    last if ($item eq $firststu);
                   2647: 	    push(@parsedlist,$item);
1.41      ng       2648: 	}
                   2649:     }
                   2650:     $ctr = 0;
1.605     www      2651: # FIXME: this is fishy, looks like the button label
1.41      ng       2652:     @parsedlist = reverse @parsedlist if ($button eq 'Previous');
1.582     raeburn  2653:     my $res_error;
                   2654:     my ($partlist) = &response_type($symb,\$res_error);
                   2655:     if ($res_error) {
                   2656:         $request->print(&navmap_errormsg());
                   2657:         return;
                   2658:     }
1.41      ng       2659:     foreach my $student (@parsedlist) {
1.257     albertel 2660: 	my $submitonly=$env{'form.submitonly'};
1.41      ng       2661: 	my ($uname,$udom) = split(/:/,$student);
1.301     albertel 2662: 	
                   2663: 	if ($submitonly eq 'queued') {
                   2664: 	    my %queue_status = 
                   2665: 		&Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
                   2666: 							$udom,$uname);
                   2667: 	    next if (!defined($queue_status{'gradingqueue'}));
                   2668: 	}
                   2669: 
1.156     albertel 2670: 	if ($submitonly =~ /^(yes|graded|incorrect)$/) {
1.257     albertel 2671: #	    my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
1.324     albertel 2672: 	    my %status=&student_gradeStatus($symb,$udom,$uname,$partlist);
1.145     albertel 2673: 	    my $submitted = 0;
1.248     albertel 2674: 	    my $ungraded = 0;
                   2675: 	    my $incorrect = 0;
1.524     raeburn  2676: 	    foreach my $item (keys(%status)) {
                   2677: 		$submitted = 1 if ($status{$item} ne 'nothing');
                   2678: 		$ungraded = 1 if ($status{$item} =~ /^ungraded/);
                   2679: 		$incorrect = 1 if ($status{$item} =~ /^incorrect/);
                   2680: 		my ($foo,$partid,$foo1) = split(/\./,$item);
1.145     albertel 2681: 		if ($status{'resource.'.$partid.'.submitted_by'} ne '') {
                   2682: 		    $submitted = 0;
                   2683: 		}
1.41      ng       2684: 	    }
1.156     albertel 2685: 	    next if (!$submitted && ($submitonly eq 'yes' ||
                   2686: 				     $submitonly eq 'incorrect' ||
                   2687: 				     $submitonly eq 'graded'));
1.248     albertel 2688: 	    next if (!$ungraded && ($submitonly eq 'graded'));
                   2689: 	    next if (!$incorrect && $submitonly eq 'incorrect');
1.41      ng       2690: 	}
1.524     raeburn  2691: 	push(@nextlist,$student) if ($ctr < $ntstu);
1.129     ng       2692: 	last if ($ctr == $ntstu);
1.41      ng       2693: 	$ctr++;
                   2694:     }
1.36      ng       2695: 
1.41      ng       2696:     $ctr = 0;
                   2697:     my $total = scalar(@nextlist)-1;
1.39      ng       2698: 
1.524     raeburn  2699:     foreach (sort(@nextlist)) {
1.41      ng       2700: 	my ($uname,$udom,$submitter) = split(/:/);
1.257     albertel 2701: 	$env{'form.student'}  = $uname;
                   2702: 	$env{'form.userdom'}  = $udom;
                   2703: 	$env{'form.fullname'} = $$fullname{$_};
1.625     www      2704: 	&submission($request,$ctr,$total,$symb);
1.41      ng       2705: 	$ctr++;
                   2706:     }
                   2707:     if ($total < 0) {
1.632     www      2708: 	my $the_end.=&mt('<b>Message: </b> No more students for this section or class.').'<br /><br />'."\n";
1.41      ng       2709: 	$request->print($the_end);
                   2710:     }
                   2711:     return '';
1.38      ng       2712: }
1.36      ng       2713: 
1.44      ng       2714: #---- Save the score and award for each student, if changed
1.38      ng       2715: sub saveHandGrade {
1.324     albertel 2716:     my ($request,$symb,$stuname,$domain,$newflg,$submitter,$part) = @_;
1.342     banghart 2717:     my @version_parts;
1.104     albertel 2718:     my $usec = &Apache::lonnet::getsection($domain,$stuname,
1.257     albertel 2719: 					   $env{'request.course.id'});
1.104     albertel 2720:     if (!&canmodify($usec)) { return('not_allowed'); }
1.337     banghart 2721:     my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$domain,$stuname);
1.251     banghart 2722:     my @parts_graded;
1.77      ng       2723:     my %newrecord  = ();
                   2724:     my ($pts,$wgt) = ('','');
1.269     raeburn  2725:     my %aggregate = ();
                   2726:     my $aggregateflag = 0;
1.301     albertel 2727:     my @parts = split(/:/,$env{'form.partlist'.$newflg});
                   2728:     foreach my $new_part (@parts) {
1.337     banghart 2729: 	#collaborator ($submi may vary for different parts
1.259     banghart 2730: 	if ($submitter && $new_part ne $part) { next; }
                   2731: 	my $dropMenu = $env{'form.GD_SEL'.$newflg.'_'.$new_part};
1.125     ng       2732: 	if ($dropMenu eq 'excused') {
1.259     banghart 2733: 	    if ($record{'resource.'.$new_part.'.solved'} ne 'excused') {
                   2734: 		$newrecord{'resource.'.$new_part.'.solved'} = 'excused';
                   2735: 		if (exists($record{'resource.'.$new_part.'.awarded'})) {
                   2736: 		    $newrecord{'resource.'.$new_part.'.awarded'} = '';
1.58      albertel 2737: 		}
1.364     banghart 2738: 	        $newrecord{'resource.'.$new_part.'.regrader'}="$env{'user.name'}:$env{'user.domain'}";
1.58      albertel 2739: 	    }
1.125     ng       2740: 	} elsif ($dropMenu eq 'reset status'
1.259     banghart 2741: 		 && exists($record{'resource.'.$new_part.'.solved'})) { #don't bother if no old records -> no attempts
1.524     raeburn  2742: 	    foreach my $key (keys(%record)) {
1.259     banghart 2743: 		if ($key=~/^resource\.\Q$new_part\E\./) { $newrecord{$key} = ''; }
1.197     albertel 2744: 	    }
1.259     banghart 2745: 	    $newrecord{'resource.'.$new_part.'.regrader'}=
1.257     albertel 2746: 		"$env{'user.name'}:$env{'user.domain'}";
1.270     albertel 2747:             my $totaltries = $record{'resource.'.$part.'.tries'};
                   2748: 
                   2749:             my %last_resets = &get_last_resets($symb,$env{'request.course.id'},
                   2750: 					       [$new_part]);
                   2751:             my $aggtries =$totaltries;
1.269     raeburn  2752:             if ($last_resets{$new_part}) {
1.270     albertel 2753:                 $aggtries = &get_num_tries(\%record,$last_resets{$new_part},
                   2754: 					   $new_part);
1.269     raeburn  2755:             }
1.270     albertel 2756: 
                   2757:             my $solvedstatus = $record{'resource.'.$new_part.'.solved'};
1.269     raeburn  2758:             if ($aggtries > 0) {
1.327     albertel 2759:                 &decrement_aggs($symb,$new_part,\%aggregate,$aggtries,$totaltries,$solvedstatus);
1.269     raeburn  2760:                 $aggregateflag = 1;
                   2761:             }
1.125     ng       2762: 	} elsif ($dropMenu eq '') {
1.259     banghart 2763: 	    $pts = ($env{'form.GD_BOX'.$newflg.'_'.$new_part} ne '' ? 
                   2764: 		    $env{'form.GD_BOX'.$newflg.'_'.$new_part} : 
                   2765: 		    $env{'form.RADVAL'.$newflg.'_'.$new_part});
                   2766: 	    if ($pts eq '' && $env{'form.GD_SEL'.$newflg.'_'.$new_part} eq '') {
1.153     albertel 2767: 		next;
                   2768: 	    }
1.259     banghart 2769: 	    $wgt = $env{'form.WGT'.$newflg.'_'.$new_part} eq '' ? 1 : 
                   2770: 		$env{'form.WGT'.$newflg.'_'.$new_part};
1.41      ng       2771: 	    my $partial= $pts/$wgt;
1.259     banghart 2772: 	    if ($partial eq $record{'resource.'.$new_part.'.awarded'}) {
1.153     albertel 2773: 		#do not update score for part if not changed.
1.346     banghart 2774:                 &handback_files($request,$symb,$stuname,$domain,$newflg,$new_part,\%newrecord);
1.153     albertel 2775: 		next;
1.251     banghart 2776: 	    } else {
1.524     raeburn  2777: 	        push(@parts_graded,$new_part);
1.153     albertel 2778: 	    }
1.259     banghart 2779: 	    if ($record{'resource.'.$new_part.'.awarded'} ne $partial) {
                   2780: 		$newrecord{'resource.'.$new_part.'.awarded'}  = $partial;
1.153     albertel 2781: 	    }
1.259     banghart 2782: 	    my $reckey = 'resource.'.$new_part.'.solved';
1.41      ng       2783: 	    if ($partial == 0) {
1.153     albertel 2784: 		if ($record{$reckey} ne 'incorrect_by_override') {
                   2785: 		    $newrecord{$reckey} = 'incorrect_by_override';
                   2786: 		}
1.41      ng       2787: 	    } else {
1.153     albertel 2788: 		if ($record{$reckey} ne 'correct_by_override') {
                   2789: 		    $newrecord{$reckey} = 'correct_by_override';
                   2790: 		}
                   2791: 	    }	    
                   2792: 	    if ($submitter && 
1.259     banghart 2793: 		($record{'resource.'.$new_part.'.submitted_by'} ne $submitter)) {
                   2794: 		$newrecord{'resource.'.$new_part.'.submitted_by'} = $submitter;
1.41      ng       2795: 	    }
1.259     banghart 2796: 	    $newrecord{'resource.'.$new_part.'.regrader'}=
1.257     albertel 2797: 		"$env{'user.name'}:$env{'user.domain'}";
1.41      ng       2798: 	}
1.259     banghart 2799: 	# unless problem has been graded, set flag to version the submitted files
1.305     banghart 2800: 	unless ($record{'resource.'.$new_part.'.solved'} =~ /^correct_/  || 
                   2801: 	        $record{'resource.'.$new_part.'.solved'} eq 'incorrect_by_override' ||
                   2802: 	        $dropMenu eq 'reset status')
                   2803: 	   {
1.524     raeburn  2804: 	    push(@version_parts,$new_part);
1.259     banghart 2805: 	}
1.41      ng       2806:     }
1.301     albertel 2807:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   2808:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   2809: 
1.344     albertel 2810:     if (%newrecord) {
                   2811:         if (@version_parts) {
1.364     banghart 2812:             my @changed_keys = &version_portfiles(\%record, \@parts_graded, 
                   2813:                                 $env{'request.course.id'}, $symb, $domain, $stuname, \@version_parts);
1.344     albertel 2814: 	    @newrecord{@changed_keys} = @record{@changed_keys};
1.367     albertel 2815: 	    foreach my $new_part (@version_parts) {
                   2816: 		&handback_files($request,$symb,$stuname,$domain,$newflg,
                   2817: 				$new_part,\%newrecord);
                   2818: 	    }
1.259     banghart 2819:         }
1.44      ng       2820: 	&Apache::lonnet::cstore(\%newrecord,$symb,
1.257     albertel 2821: 				$env{'request.course.id'},$domain,$stuname);
1.380     albertel 2822: 	&check_and_remove_from_queue(\@parts,\%record,\%newrecord,$symb,
                   2823: 				     $cdom,$cnum,$domain,$stuname);
1.41      ng       2824:     }
1.269     raeburn  2825:     if ($aggregateflag) {
                   2826:         &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
1.301     albertel 2827: 			      $cdom,$cnum);
1.269     raeburn  2828:     }
1.301     albertel 2829:     return ('',$pts,$wgt);
1.36      ng       2830: }
1.322     albertel 2831: 
1.380     albertel 2832: sub check_and_remove_from_queue {
                   2833:     my ($parts,$record,$newrecord,$symb,$cdom,$cnum,$domain,$stuname) = @_;
                   2834:     my @ungraded_parts;
                   2835:     foreach my $part (@{$parts}) {
                   2836: 	if (    $record->{   'resource.'.$part.'.awarded'} eq ''
                   2837: 	     && $record->{   'resource.'.$part.'.solved' } ne 'excused'
                   2838: 	     && $newrecord->{'resource.'.$part.'.awarded'} eq ''
                   2839: 	     && $newrecord->{'resource.'.$part.'.solved' } ne 'excused'
                   2840: 		) {
                   2841: 	    push(@ungraded_parts, $part);
                   2842: 	}
                   2843:     }
                   2844:     if ( !@ungraded_parts ) {
                   2845: 	&Apache::bridgetask::remove_from_queue('gradingqueue',$symb,$cdom,
                   2846: 					       $cnum,$domain,$stuname);
                   2847:     }
                   2848: }
                   2849: 
1.337     banghart 2850: sub handback_files {
                   2851:     my ($request,$symb,$stuname,$domain,$newflg,$new_part,$newrecord) = @_;
1.517     raeburn  2852:     my $portfolio_root = '/userfiles/portfolio';
1.582     raeburn  2853:     my $res_error;
                   2854:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
                   2855:     if ($res_error) {
                   2856:         $request->print('<br />'.&navmap_errormsg().'<br />');
                   2857:         return;
                   2858:     }
1.375     albertel 2859:     my @part_response_id = &flatten_responseType($responseType);
                   2860:     foreach my $part_response_id (@part_response_id) {
                   2861:     	my ($part_id,$resp_id) = @{ $part_response_id };
                   2862: 	my $part_resp = join('_',@{ $part_response_id });
1.337     banghart 2863:             if (($env{'form.'.$newflg.'_'.$part_resp.'_returndoc1'}) && ($new_part == $part_id)) {
                   2864:                 # if multiple files are uploaded names will be 'returndoc2','returndoc3'
                   2865:                 my $file_counter = 1;
1.367     albertel 2866: 		my $file_msg;
1.337     banghart 2867:                 while ($env{'form.'.$newflg.'_'.$part_resp.'_returndoc'.$file_counter}) {
                   2868:                     my $fname=$env{'form.'.$newflg.'_'.$part_resp.'_returndoc'.$file_counter.'.filename'};
1.338     banghart 2869:                     my ($directory,$answer_file) = 
                   2870:                         ($env{'form.'.$newflg.'_'.$part_resp.'_origdoc'.$file_counter} =~ /^(.*?)([^\/]*)$/);
                   2871:                     my ($answer_name,$answer_ver,$answer_ext) =
                   2872: 		        &file_name_version_ext($answer_file);
1.355     banghart 2873: 		    my ($portfolio_path) = ($directory =~ /^.+$stuname\/portfolio(.*)/);
1.517     raeburn  2874:                     my $getpropath = 1;
                   2875: 		    my @dir_list = &Apache::lonnet::dirlist($portfolio_root.$portfolio_path,$domain,$stuname,$getpropath);
1.338     banghart 2876: 		    my $version = &get_next_version($answer_name, $answer_ext, \@dir_list);
1.355     banghart 2877:                     # fix file name
                   2878:                     my ($save_file_name) = (($directory.$answer_name.".$version.".$answer_ext) =~ /^.+\/${stuname}\/(.*)/);
                   2879:                     my $result=&Apache::lonnet::finishuserfileupload($stuname,$domain,
                   2880:             	                                $newflg.'_'.$part_resp.'_returndoc'.$file_counter,
                   2881:             	                                $save_file_name);
1.337     banghart 2882:                     if ($result !~ m|^/uploaded/|) {
1.536     raeburn  2883:                         $request->print('<br /><span class="LC_error">'.
                   2884:                             &mt('An error occurred ([_1]) while trying to upload [_2].',
                   2885:                                 $result,$newflg.'_'.$part_resp.'_returndoc'.$file_counter).
                   2886:                                         '</span>');
1.356     banghart 2887:                     } else {
1.360     banghart 2888:                         # mark the file as read only
                   2889:                         my @files = ($save_file_name);
1.372     albertel 2890:                         my @what = ($symb,$env{'request.course.id'},'handback');
1.360     banghart 2891:                         &Apache::lonnet::mark_as_readonly($domain,$stuname,\@files,\@what);
1.367     albertel 2892: 			if (exists($$newrecord{"resource.$new_part.$resp_id.handback"})) {
                   2893: 			    $$newrecord{"resource.$new_part.$resp_id.handback"}.=',';
                   2894: 			}
                   2895:                         $$newrecord{"resource.$new_part.$resp_id.handback"} .= $save_file_name;
                   2896: 			$file_msg.= "\n".'<br /><span class="LC_filename"><a href="/uploaded/'."$domain/$stuname/".$save_file_name.'">'.$save_file_name."</a></span><br />";
                   2897: 
1.337     banghart 2898:                     }
                   2899:                     $request->print("<br />".$fname." will be the uploaded file name");
1.354     albertel 2900:                     $request->print(" ".$env{'form.'.$newflg.'_'.$part_resp.'_origdoc'.$file_counter});
1.337     banghart 2901:                     $file_counter++;
                   2902:                 }
1.367     albertel 2903: 		my $subject = "File Handed Back by Instructor ";
                   2904: 		my $message = "A file has been returned that was originally submitted in reponse to: <br />";
                   2905: 		$message .= "<strong>".&Apache::lonnet::gettitle($symb)."</strong><br />";
                   2906: 		$message .= ' The returned file(s) are named: '. $file_msg;
                   2907: 		$message .= " and can be found in your portfolio space.";
1.418     albertel 2908: 		my ($feedurl,$showsymb) = 
                   2909: 		    &get_feedurl_and_symb($symb,$domain,$stuname);
1.386     raeburn  2910:                 my $restitle = &Apache::lonnet::gettitle($symb);
                   2911: 		my $msgstatus = 
                   2912:                    &Apache::lonmsg::user_normal_msg($stuname,$domain,$subject.
                   2913: 			 ' (File Returned) ['.$restitle.']',$message,undef,
1.418     albertel 2914:                          $feedurl,undef,undef,undef,$showsymb,$restitle);
1.337     banghart 2915:             }
                   2916:         }
1.338     banghart 2917:     return;
1.337     banghart 2918: }
                   2919: 
1.418     albertel 2920: sub get_feedurl_and_symb {
                   2921:     my ($symb,$uname,$udom) = @_;
                   2922:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
                   2923:     $url = &Apache::lonnet::clutter($url);
                   2924:     my $encrypturl=&Apache::lonnet::EXT('resource.0.encrypturl',
                   2925: 					$symb,$udom,$uname);
                   2926:     if ($encrypturl =~ /^yes$/i) {
                   2927: 	&Apache::lonenc::encrypted(\$url,1);
                   2928: 	&Apache::lonenc::encrypted(\$symb,1);
                   2929:     }
                   2930:     return ($url,$symb);
                   2931: }
                   2932: 
1.313     banghart 2933: sub get_submitted_files {
                   2934:     my ($udom,$uname,$partid,$respid,$record) = @_;
                   2935:     my @files;
                   2936:     if ($$record{"resource.$partid.$respid.portfiles"}) {
                   2937:         my $file_url = '/uploaded/'.$udom.'/'.$uname.'/portfolio';
                   2938:         foreach my $file (split(',',$$record{"resource.$partid.$respid.portfiles"})) {
                   2939:     	    push(@files,$file_url.$file);
                   2940:         }
                   2941:     }
                   2942:     if ($$record{"resource.$partid.$respid.uploadedurl"}) {
                   2943:         push(@files,$$record{"resource.$partid.$respid.uploadedurl"});
                   2944:     }
                   2945:     return (\@files);
                   2946: }
1.322     albertel 2947: 
1.269     raeburn  2948: # ----------- Provides number of tries since last reset.
                   2949: sub get_num_tries {
                   2950:     my ($record,$last_reset,$part) = @_;
                   2951:     my $timestamp = '';
                   2952:     my $num_tries = 0;
                   2953:     if ($$record{'version'}) {
                   2954:         for (my $version=$$record{'version'};$version>=1;$version--) {
                   2955:             if (exists($$record{$version.':resource.'.$part.'.solved'})) {
                   2956:                 $timestamp = $$record{$version.':timestamp'};
                   2957:                 if ($timestamp > $last_reset) {
                   2958:                     $num_tries ++;
                   2959:                 } else {
                   2960:                     last;
                   2961:                 }
                   2962:             }
                   2963:         }
                   2964:     }
                   2965:     return $num_tries;
                   2966: }
                   2967: 
                   2968: # ----------- Determine decrements required in aggregate totals 
                   2969: sub decrement_aggs {
                   2970:     my ($symb,$part,$aggregate,$aggtries,$totaltries,$solvedstatus) = @_;
                   2971:     my %decrement = (
                   2972:                         attempts => 0,
                   2973:                         users => 0,
                   2974:                         correct => 0
                   2975:                     );
                   2976:     $decrement{'attempts'} = $aggtries;
                   2977:     if ($solvedstatus =~ /^correct/) {
                   2978:         $decrement{'correct'} = 1;
                   2979:     }
                   2980:     if ($aggtries == $totaltries) {
                   2981:         $decrement{'users'} = 1;
                   2982:     }
1.524     raeburn  2983:     foreach my $type (keys(%decrement)) {
1.269     raeburn  2984:         $$aggregate{$symb."\0".$part."\0".$type} = -$decrement{$type};
                   2985:     }
                   2986:     return;
                   2987: }
                   2988: 
                   2989: # ----------- Determine timestamps for last reset of aggregate totals for parts  
                   2990: sub get_last_resets {
1.270     albertel 2991:     my ($symb,$courseid,$partids) =@_;
                   2992:     my %last_resets;
1.269     raeburn  2993:     my $cdom = $env{'course.'.$courseid.'.domain'};
                   2994:     my $cname = $env{'course.'.$courseid.'.num'};
1.271     albertel 2995:     my @keys;
                   2996:     foreach my $part (@{$partids}) {
                   2997: 	push(@keys,"$symb\0$part\0resettime");
                   2998:     }
                   2999:     my %results=&Apache::lonnet::get('nohist_resourcetracker',\@keys,
                   3000: 				     $cdom,$cname);
                   3001:     foreach my $part (@{$partids}) {
                   3002: 	$last_resets{$part}=$results{"$symb\0$part\0resettime"};
1.269     raeburn  3003:     }
1.270     albertel 3004:     return %last_resets;
1.269     raeburn  3005: }
                   3006: 
1.251     banghart 3007: # ----------- Handles creating versions for portfolio files as answers
                   3008: sub version_portfiles {
1.343     banghart 3009:     my ($record, $parts_graded, $courseid, $symb, $domain, $stu_name, $v_flag) = @_;
1.263     banghart 3010:     my $version_parts = join('|',@$v_flag);
1.343     banghart 3011:     my @returned_keys;
1.255     banghart 3012:     my $parts = join('|', @$parts_graded);
1.517     raeburn  3013:     my $portfolio_root = '/userfiles/portfolio';
1.277     albertel 3014:     foreach my $key (keys(%$record)) {
1.259     banghart 3015:         my $new_portfiles;
1.263     banghart 3016:         if ($key =~ /^resource\.($version_parts)\./ && $key =~ /\.portfiles$/ ) {
1.342     banghart 3017:             my @versioned_portfiles;
1.367     albertel 3018:             my @portfiles = split(/\s*,\s*/,$$record{$key});
1.252     banghart 3019:             foreach my $file (@portfiles) {
1.306     banghart 3020:                 &Apache::lonnet::unmark_as_readonly($domain,$stu_name,[$symb,$env{'request.course.id'}],$file);
1.304     albertel 3021:                 my ($directory,$answer_file) =($file =~ /^(.*?)([^\/]*)$/);
                   3022: 		my ($answer_name,$answer_ver,$answer_ext) =
                   3023: 		    &file_name_version_ext($answer_file);
1.517     raeburn  3024:                 my $getpropath = 1;    
                   3025:                 my @dir_list = &Apache::lonnet::dirlist($portfolio_root.$directory,$domain,$stu_name,$getpropath);
1.342     banghart 3026:                 my $version = &get_next_version($answer_name, $answer_ext, \@dir_list);
1.306     banghart 3027:                 my $new_answer = &version_selected_portfile($domain, $stu_name, $directory, $answer_file, $version);
                   3028:                 if ($new_answer ne 'problem getting file') {
1.342     banghart 3029:                     push(@versioned_portfiles, $directory.$new_answer);
1.306     banghart 3030:                     &Apache::lonnet::mark_as_readonly($domain,$stu_name,
1.367     albertel 3031:                         [$directory.$new_answer],
1.306     banghart 3032:                         [$symb,$env{'request.course.id'},'graded']);
1.259     banghart 3033:                 }
1.252     banghart 3034:             }
1.343     banghart 3035:             $$record{$key} = join(',',@versioned_portfiles);
                   3036:             push(@returned_keys,$key);
1.251     banghart 3037:         }
                   3038:     } 
1.343     banghart 3039:     return (@returned_keys);   
1.305     banghart 3040: }
                   3041: 
1.307     banghart 3042: sub get_next_version {
1.341     banghart 3043:     my ($answer_name, $answer_ext, $dir_list) = @_;
1.307     banghart 3044:     my $version;
                   3045:     foreach my $row (@$dir_list) {
                   3046:         my ($file) = split(/\&/,$row,2);
                   3047:         my ($file_name,$file_version,$file_ext) =
                   3048: 	    &file_name_version_ext($file);
                   3049:         if (($file_name eq $answer_name) && 
                   3050: 	    ($file_ext eq $answer_ext)) {
                   3051:                 # gets here if filename and extension match, regardless of version
                   3052:                 if ($file_version ne '') {
                   3053:                 # a versioned file is found  so save it for later
                   3054:                 if ($file_version > $version) {
                   3055: 		    $version = $file_version;
                   3056: 	        }
                   3057:             }
                   3058:         }
                   3059:     } 
                   3060:     $version ++;
                   3061:     return($version);
                   3062: }
                   3063: 
1.305     banghart 3064: sub version_selected_portfile {
1.306     banghart 3065:     my ($domain,$stu_name,$directory,$file_name,$version) = @_;
                   3066:     my ($answer_name,$answer_ver,$answer_ext) =
                   3067:         &file_name_version_ext($file_name);
                   3068:     my $new_answer;
                   3069:     $env{'form.copy'} = &Apache::lonnet::getfile("/uploaded/$domain/$stu_name/portfolio$directory$file_name");
                   3070:     if($env{'form.copy'} eq '-1') {
                   3071:         $new_answer = 'problem getting file';
                   3072:     } else {
                   3073:         $new_answer = $answer_name.'.'.$version.'.'.$answer_ext;
                   3074:         my $copy_result = &Apache::lonnet::finishuserfileupload(
                   3075:                             $stu_name,$domain,'copy',
                   3076: 		        '/portfolio'.$directory.$new_answer);
                   3077:     }    
                   3078:     return ($new_answer);
1.251     banghart 3079: }
                   3080: 
1.304     albertel 3081: sub file_name_version_ext {
                   3082:     my ($file)=@_;
                   3083:     my @file_parts = split(/\./, $file);
                   3084:     my ($name,$version,$ext);
                   3085:     if (@file_parts > 1) {
                   3086: 	$ext=pop(@file_parts);
                   3087: 	if (@file_parts > 1 && $file_parts[-1] =~ /^\d+$/) {
                   3088: 	    $version=pop(@file_parts);
                   3089: 	}
                   3090: 	$name=join('.',@file_parts);
                   3091:     } else {
                   3092: 	$name=join('.',@file_parts);
                   3093:     }
                   3094:     return($name,$version,$ext);
                   3095: }
                   3096: 
1.44      ng       3097: #--------------------------------------------------------------------------------------
                   3098: #
                   3099: #-------------------------- Next few routines handles grading by section or whole class
                   3100: #
                   3101: #--- Javascript to handle grading by section or whole class
1.42      ng       3102: sub viewgrades_js {
                   3103:     my ($request) = shift;
                   3104: 
1.539     riegler  3105:     my $alertmsg = &mt('A number equal or greater than 0 is expected. Entered value = ');
1.597     wenzelju 3106:     $request->print(&Apache::lonhtmlcommon::scripttag(<<VIEWJAVASCRIPT));
1.45      ng       3107:    function writePoint(partid,weight,point) {
1.125     ng       3108: 	var radioButton = document.classgrade["RADVAL_"+partid];
                   3109: 	var textbox = document.classgrade["TEXTVAL_"+partid];
1.42      ng       3110: 	if (point == "textval") {
1.125     ng       3111: 	    point = document.classgrade["TEXTVAL_"+partid].value;
1.109     matthew  3112: 	    if (isNaN(point) || parseFloat(point) < 0) {
1.539     riegler  3113: 		alert("$alertmsg"+parseFloat(point));
1.42      ng       3114: 		var resetbox = false;
                   3115: 		for (var i=0; i<radioButton.length; i++) {
                   3116: 		    if (radioButton[i].checked) {
                   3117: 			textbox.value = i;
                   3118: 			resetbox = true;
                   3119: 		    }
                   3120: 		}
                   3121: 		if (!resetbox) {
                   3122: 		    textbox.value = "";
                   3123: 		}
                   3124: 		return;
                   3125: 	    }
1.109     matthew  3126: 	    if (parseFloat(point) > parseFloat(weight)) {
                   3127: 		var resp = confirm("You entered a value ("+parseFloat(point)+
1.44      ng       3128: 				   ") greater than the weight for the part. Accept?");
                   3129: 		if (resp == false) {
                   3130: 		    textbox.value = "";
                   3131: 		    return;
                   3132: 		}
                   3133: 	    }
1.42      ng       3134: 	    for (var i=0; i<radioButton.length; i++) {
                   3135: 		radioButton[i].checked=false;
1.109     matthew  3136: 		if (parseFloat(point) == i) {
1.42      ng       3137: 		    radioButton[i].checked=true;
                   3138: 		}
                   3139: 	    }
1.41      ng       3140: 
1.42      ng       3141: 	} else {
1.125     ng       3142: 	    textbox.value = parseFloat(point);
1.42      ng       3143: 	}
1.41      ng       3144: 	for (i=0;i<document.classgrade.total.value;i++) {
1.125     ng       3145: 	    var user = document.classgrade["ctr"+i].value;
1.289     albertel 3146: 	    user = user.replace(new RegExp(':', 'g'),"_");
1.125     ng       3147: 	    var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
                   3148: 	    var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
                   3149: 	    var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
1.42      ng       3150: 	    if (saveval != "correct") {
                   3151: 		scorename.value = point;
1.43      ng       3152: 		if (selname[0].selected != true) {
                   3153: 		    selname[0].selected = true;
                   3154: 		}
1.42      ng       3155: 	    }
                   3156: 	}
1.125     ng       3157: 	document.classgrade["SELVAL_"+partid][0].selected = true;
1.42      ng       3158:     }
                   3159: 
                   3160:     function writeRadText(partid,weight) {
1.125     ng       3161: 	var selval   = document.classgrade["SELVAL_"+partid];
                   3162: 	var radioButton = document.classgrade["RADVAL_"+partid];
1.265     www      3163:         var override = document.classgrade["FORCE_"+partid].checked;
1.125     ng       3164: 	var textbox = document.classgrade["TEXTVAL_"+partid];
                   3165: 	if (selval[1].selected || selval[2].selected) {
1.42      ng       3166: 	    for (var i=0; i<radioButton.length; i++) {
                   3167: 		radioButton[i].checked=false;
                   3168: 
                   3169: 	    }
                   3170: 	    textbox.value = "";
                   3171: 
                   3172: 	    for (i=0;i<document.classgrade.total.value;i++) {
1.125     ng       3173: 		var user = document.classgrade["ctr"+i].value;
1.289     albertel 3174: 		user = user.replace(new RegExp(':', 'g'),"_");
1.125     ng       3175: 		var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
                   3176: 		var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
                   3177: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
1.265     www      3178: 		if ((saveval != "correct") || override) {
1.42      ng       3179: 		    scorename.value = "";
1.125     ng       3180: 		    if (selval[1].selected) {
                   3181: 			selname[1].selected = true;
                   3182: 		    } else {
                   3183: 			selname[2].selected = true;
                   3184: 			if (Number(document.classgrade["GD_"+user+"_"+partid+"_tries"].value)) 
                   3185: 			{document.classgrade["GD_"+user+"_"+partid+"_tries"].value = '0';}
                   3186: 		    }
1.42      ng       3187: 		}
                   3188: 	    }
1.43      ng       3189: 	} else {
                   3190: 	    for (i=0;i<document.classgrade.total.value;i++) {
1.125     ng       3191: 		var user = document.classgrade["ctr"+i].value;
1.289     albertel 3192: 		user = user.replace(new RegExp(':', 'g'),"_");
1.125     ng       3193: 		var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
                   3194: 		var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
                   3195: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
1.265     www      3196: 		if ((saveval != "correct") || override) {
1.125     ng       3197: 		    scorename.value = document.classgrade["GD_"+user+"_"+partid+"_awarded_s"].value;
1.43      ng       3198: 		    selname[0].selected = true;
                   3199: 		}
                   3200: 	    }
                   3201: 	}	    
1.42      ng       3202:     }
                   3203: 
                   3204:     function changeSelect(partid,user) {
1.125     ng       3205: 	var selval = document.classgrade["GD_"+user+'_'+partid+"_solved"];
                   3206: 	var textbox = document.classgrade["GD_"+user+'_'+partid+"_awarded"];
1.44      ng       3207: 	var point  = textbox.value;
1.125     ng       3208: 	var weight = document.classgrade["weight_"+partid].value;
1.44      ng       3209: 
1.109     matthew  3210: 	if (isNaN(point) || parseFloat(point) < 0) {
1.539     riegler  3211: 	    alert("$alertmsg"+parseFloat(point));
1.44      ng       3212: 	    textbox.value = "";
                   3213: 	    return;
                   3214: 	}
1.109     matthew  3215: 	if (parseFloat(point) > parseFloat(weight)) {
                   3216: 	    var resp = confirm("You entered a value ("+parseFloat(point)+
1.44      ng       3217: 			       ") greater than the weight of the part. Accept?");
                   3218: 	    if (resp == false) {
                   3219: 		textbox.value = "";
                   3220: 		return;
                   3221: 	    }
                   3222: 	}
1.42      ng       3223: 	selval[0].selected = true;
                   3224:     }
                   3225: 
                   3226:     function changeOneScore(partid,user) {
1.125     ng       3227: 	var selval = document.classgrade["GD_"+user+'_'+partid+"_solved"];
                   3228: 	if (selval[1].selected || selval[2].selected) {
                   3229: 	    document.classgrade["GD_"+user+'_'+partid+"_awarded"].value = "";
                   3230: 	    if (selval[2].selected) {
                   3231: 		document.classgrade["GD_"+user+'_'+partid+"_tries"].value = "0";
                   3232: 	    }
1.269     raeburn  3233:         }
1.42      ng       3234:     }
                   3235: 
                   3236:     function resetEntry(numpart) {
                   3237: 	for (ctpart=0;ctpart<numpart;ctpart++) {
1.125     ng       3238: 	    var partid = document.classgrade["partid_"+ctpart].value;
                   3239: 	    var radioButton = document.classgrade["RADVAL_"+partid];
                   3240: 	    var textbox = document.classgrade["TEXTVAL_"+partid];
                   3241: 	    var selval  = document.classgrade["SELVAL_"+partid];
1.42      ng       3242: 	    for (var i=0; i<radioButton.length; i++) {
                   3243: 		radioButton[i].checked=false;
                   3244: 
                   3245: 	    }
                   3246: 	    textbox.value = "";
                   3247: 	    selval[0].selected = true;
                   3248: 
                   3249: 	    for (i=0;i<document.classgrade.total.value;i++) {
1.125     ng       3250: 		var user = document.classgrade["ctr"+i].value;
1.289     albertel 3251: 		user = user.replace(new RegExp(':', 'g'),"_");
1.125     ng       3252: 		var resetscore = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
                   3253: 		resetscore.value = document.classgrade["GD_"+user+"_"+partid+"_awarded_s"].value;
                   3254: 		var resettries = document.classgrade["GD_"+user+"_"+partid+"_tries"];
                   3255: 		resettries.value = document.classgrade["GD_"+user+"_"+partid+"_tries_s"].value;
                   3256: 		var saveselval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
                   3257: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
1.42      ng       3258: 		if (saveselval == "excused") {
1.43      ng       3259: 		    if (selname[1].selected == false) { selname[1].selected = true;}
1.42      ng       3260: 		} else {
1.43      ng       3261: 		    if (selname[0].selected == false) {selname[0].selected = true};
1.42      ng       3262: 		}
                   3263: 	    }
1.41      ng       3264: 	}
1.42      ng       3265:     }
                   3266: 
1.41      ng       3267: VIEWJAVASCRIPT
1.42      ng       3268: }
                   3269: 
1.44      ng       3270: #--- show scores for a section or whole class w/ option to change/update a score
1.42      ng       3271: sub viewgrades {
1.608     www      3272:     my ($request,$symb) = @_;
1.42      ng       3273:     &viewgrades_js($request);
1.41      ng       3274: 
1.168     albertel 3275:     #need to make sure we have the correct data for later EXT calls, 
                   3276:     #thus invalidate the cache
                   3277:     &Apache::lonnet::devalidatecourseresdata(
1.257     albertel 3278:                  $env{'course.'.$env{'request.course.id'}.'.num'},
                   3279:                  $env{'course.'.$env{'request.course.id'}.'.domain'});
1.168     albertel 3280:     &Apache::lonnet::clear_EXT_cache_status();
                   3281: 
1.398     albertel 3282:     my $result='<h3><span class="LC_info">'.&mt('Manual Grading').'</span></h3>';
1.41      ng       3283: 
                   3284:     #view individual student submission form - called using Javascript viewOneStudent
1.324     albertel 3285:     $result.=&jscriptNform($symb);
1.41      ng       3286: 
1.44      ng       3287:     #beginning of class grading form
1.442     banghart 3288:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
1.41      ng       3289:     $result.= '<form action="/adm/grades" method="post" name="classgrade">'."\n".
1.418     albertel 3290: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.38      ng       3291: 	'<input type="hidden" name="command" value="editgrades" />'."\n".
1.432     banghart 3292: 	&build_section_inputs().
1.442     banghart 3293: 	'<input type="hidden" name="Status" value="'.$env{'stu_status'}.'" />'."\n".
1.72      ng       3294: 
1.560     raeburn  3295:     my ($common_header,$specific_header);
1.257     albertel 3296:     if ($env{'form.section'} eq 'all') {
1.560     raeburn  3297: 	$common_header = &mt('Assign Common Grade to Class');
                   3298:         $specific_header = &mt('Assign Grade to Specific Students in Class');
1.257     albertel 3299:     } elsif ($env{'form.section'} eq 'none') {
1.560     raeburn  3300:         $common_header = &mt('Assign Common Grade to Students in no Section');
                   3301: 	$specific_header = &mt('Assign Grade to Specific Students in no Section');
1.52      albertel 3302:     } else {
1.560     raeburn  3303:         my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
                   3304:         $common_header = &mt('Assign Common Grade to Students in Section(s) [_1]',$section_display);
                   3305: 	$specific_header = &mt('Assign Grade to Specific Students in Section(s) [_1]',$section_display);
1.52      albertel 3306:     }
1.560     raeburn  3307:     $result.= '<h3>'.$common_header.'</h3>'.&Apache::loncommon::start_data_table();
1.44      ng       3308:     #radio buttons/text box for assigning points for a section or class.
                   3309:     #handles different parts of a problem
1.582     raeburn  3310:     my $res_error;
                   3311:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
                   3312:     if ($res_error) {
                   3313:         return &navmap_errormsg();
                   3314:     }
1.42      ng       3315:     my %weight = ();
                   3316:     my $ctsparts = 0;
1.45      ng       3317:     my %seen = ();
1.375     albertel 3318:     my @part_response_id = &flatten_responseType($responseType);
                   3319:     foreach my $part_response_id (@part_response_id) {
                   3320:     	my ($partid,$respid) = @{ $part_response_id };
                   3321: 	my $part_resp = join('_',@{ $part_response_id });
1.45      ng       3322: 	next if $seen{$partid};
                   3323: 	$seen{$partid}++;
1.375     albertel 3324: 	my $handgrade=$$handgrade{$part_resp};
1.42      ng       3325: 	my $wgt = &Apache::lonnet::EXT('resource.'.$partid.'.weight',$symb);
                   3326: 	$weight{$partid} = $wgt eq '' ? '1' : $wgt;
                   3327: 
1.324     albertel 3328: 	my $display_part=&get_display_part($partid,$symb);
1.485     albertel 3329: 	my $radio.='<table border="0"><tr>';  
1.41      ng       3330: 	my $ctr = 0;
1.42      ng       3331: 	while ($ctr<=$weight{$partid}) { # display radio buttons in a nice table 10 across
1.485     albertel 3332: 	    $radio.= '<td><label><input type="radio" name="RADVAL_'.$partid.'" '.
1.54      albertel 3333: 		'onclick="javascript:writePoint(\''.$partid.'\','.$weight{$partid}.
1.288     albertel 3334: 		','.$ctr.')" />'.$ctr."</label></td>\n";
1.41      ng       3335: 	    $result.=(($ctr+1)%10 == 0 ? '</tr><tr>' : '');
                   3336: 	    $ctr++;
                   3337: 	}
1.485     albertel 3338: 	$radio.='</tr></table>';
                   3339: 	my $line = '<input type="text" name="TEXTVAL_'.
1.589     bisitz   3340: 	    $partid.'" size="4" '.'onchange="javascript:writePoint(\''.
1.54      albertel 3341: 		$partid.'\','.$weight{$partid}.',\'textval\')" /> /'.
1.539     riegler  3342: 	    $weight{$partid}.' '.&mt('(problem weight)').'</td>'."\n";
                   3343: 	$line.= '<td><b>'.&mt('Grade Status').':</b><select name="SELVAL_'.$partid.'"'.
1.589     bisitz   3344: 	    'onchange="javascript:writeRadText(\''.$partid.'\','.
1.59      albertel 3345: 		$weight{$partid}.')"> '.
1.401     albertel 3346: 	    '<option selected="selected"> </option>'.
1.485     albertel 3347: 	    '<option value="excused">'.&mt('excused').'</option>'.
                   3348: 	    '<option value="reset status">'.&mt('reset status').'</option>'.
                   3349: 	    '</select></td>'.
                   3350:             '<td><label><input type="checkbox" name="FORCE_'.$partid.'" />'.&mt('Override "Correct"').'</label>';
                   3351: 	$line.='<input type="hidden" name="partid_'.
                   3352: 	    $ctsparts.'" value="'.$partid.'" />'."\n";
                   3353: 	$line.='<input type="hidden" name="weight_'.
                   3354: 	    $partid.'" value="'.$weight{$partid}.'" />'."\n";
                   3355: 
                   3356: 	$result.=
                   3357: 	    &Apache::loncommon::start_data_table_row()."\n".
1.577     bisitz   3358: 	    '<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 3359: 	    &Apache::loncommon::end_data_table_row()."\n";
1.42      ng       3360: 	$ctsparts++;
1.41      ng       3361:     }
1.474     albertel 3362:     $result.=&Apache::loncommon::end_data_table()."\n".
1.52      albertel 3363: 	'<input type="hidden" name="totalparts" value="'.$ctsparts.'" />';
1.485     albertel 3364:     $result.='<input type="button" value="'.&mt('Revert to Default').'" '.
1.589     bisitz   3365: 	'onclick="javascript:resetEntry('.$ctsparts.');" />';
1.41      ng       3366: 
1.44      ng       3367:     #table listing all the students in a section/class
                   3368:     #header of table
1.560     raeburn  3369:     $result.= '<h3>'.$specific_header.'</h3>'.
                   3370:               &Apache::loncommon::start_data_table().
                   3371: 	      &Apache::loncommon::start_data_table_header_row().
                   3372: 	      '<th>'.&mt('No.').'</th>'.
                   3373: 	      '<th>'.&nameUserString('header')."</th>\n";
1.582     raeburn  3374:     my $partserror;
                   3375:     my (@parts) = sort(&getpartlist($symb,\$partserror));
                   3376:     if ($partserror) {
                   3377:         return &navmap_errormsg();
                   3378:     }
1.324     albertel 3379:     my (undef,undef,$url)=&Apache::lonnet::decode_symb($symb);
1.269     raeburn  3380:     my @partids = ();
1.41      ng       3381:     foreach my $part (@parts) {
                   3382: 	my $display=&Apache::lonnet::metadata($url,$part.'.display');
1.539     riegler  3383:         my $narrowtext = &mt('Tries');
                   3384: 	$display =~ s|^Number of Attempts|$narrowtext <br />|; # makes the column narrower
1.41      ng       3385: 	if  (!$display) { $display = &Apache::lonnet::metadata($url,$part.'.name'); }
1.207     albertel 3386: 	my ($partid) = &split_part_type($part);
1.524     raeburn  3387:         push(@partids,$partid);
1.628     www      3388: #
                   3389: # FIXME: Looks like $display looks at English text
                   3390: #
1.324     albertel 3391: 	my $display_part=&get_display_part($partid,$symb);
1.41      ng       3392: 	if ($display =~ /^Partial Credit Factor/) {
1.485     albertel 3393: 	    $result.='<th>'.
                   3394: 		&mt('Score Part: [_1]<br /> (weight = [_2])',
                   3395: 		    $display_part,$weight{$partid}).'</th>'."\n";
1.41      ng       3396: 	    next;
1.485     albertel 3397: 	    
1.207     albertel 3398: 	} else {
1.485     albertel 3399: 	    if ($display =~ /Problem Status/) {
                   3400: 		my $grade_status_mt = &mt('Grade Status');
                   3401: 		$display =~ s{Problem Status}{$grade_status_mt<br />};
                   3402: 	    }
                   3403: 	    my $part_mt = &mt('Part:');
                   3404: 	    $display =~s{\[Part: \Q$partid\E\]}{$part_mt $display_part};
1.41      ng       3405: 	}
1.485     albertel 3406: 
1.474     albertel 3407: 	$result.='<th>'.$display.'</th>'."\n";
1.41      ng       3408:     }
1.474     albertel 3409:     $result.=&Apache::loncommon::end_data_table_header_row();
1.44      ng       3410: 
1.270     albertel 3411:     my %last_resets = 
                   3412: 	&get_last_resets($symb,$env{'request.course.id'},\@partids);
1.269     raeburn  3413: 
1.41      ng       3414:     #get info for each student
1.44      ng       3415:     #list all the students - with points and grade status
1.257     albertel 3416:     my (undef,undef,$fullname) = &getclasslist($env{'form.section'},'1');
1.41      ng       3417:     my $ctr = 0;
1.294     albertel 3418:     foreach (sort 
                   3419: 	     {
                   3420: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                   3421: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                   3422: 		 }
                   3423: 		 return $a cmp $b;
                   3424: 	     } (keys(%$fullname))) {
1.126     ng       3425: 	$ctr++;
1.324     albertel 3426: 	$result.=&viewstudentgrade($symb,$env{'request.course.id'},
1.269     raeburn  3427: 				   $_,$$fullname{$_},\@parts,\%weight,$ctr,\%last_resets);
1.41      ng       3428:     }
1.474     albertel 3429:     $result.=&Apache::loncommon::end_data_table();
1.41      ng       3430:     $result.='<input type="hidden" name="total" value="'.$ctr.'" />'."\n";
1.485     albertel 3431:     $result.='<input type="button" value="'.&mt('Save').'" '.
1.589     bisitz   3432: 	'onclick="javascript:submit();" target="_self" /></form>'."\n";
1.96      albertel 3433:     if (scalar(%$fullname) eq 0) {
                   3434: 	my $colspan=3+scalar(@parts);
1.433     banghart 3435: 	my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
1.442     banghart 3436:         my $stu_status = join(' or ',&Apache::loncommon::get_env_multiple('form.Status'));
1.433     banghart 3437: 	$result='<span class="LC_warning">'.
1.485     albertel 3438: 	    &mt('There are no students in section(s) [_1] with enrollment status [_2] to modify or grade.',
1.442     banghart 3439: 	        $section_display, $stu_status).
1.433     banghart 3440: 	    '</span>';
1.96      albertel 3441:     }
1.41      ng       3442:     return $result;
                   3443: }
                   3444: 
1.44      ng       3445: #--- call by previous routine to display each student
1.41      ng       3446: sub viewstudentgrade {
1.324     albertel 3447:     my ($symb,$courseid,$student,$fullname,$parts,$weight,$ctr,$last_resets) = @_;
1.44      ng       3448:     my ($uname,$udom) = split(/:/,$student);
                   3449:     my %record=&Apache::lonnet::restore($symb,$courseid,$udom,$uname);
1.269     raeburn  3450:     my %aggregates = (); 
1.474     albertel 3451:     my $result=&Apache::loncommon::start_data_table_row().'<td align="right">'.
1.233     albertel 3452: 	'<input type="hidden" name="ctr'.($ctr-1).'" value="'.$student.'" />'.
                   3453: 	"\n".$ctr.'&nbsp;</td><td>&nbsp;'.
1.44      ng       3454: 	'<a href="javascript:viewOneStudent(\''.$uname.'\',\''.$udom.
1.417     albertel 3455: 	'\');" target="_self">'.$fullname.'</a> '.
1.398     albertel 3456: 	'<span class="LC_internal_info">('.$uname.($env{'user.domain'} eq $udom ? '' : ':'.$udom).')</span></td>'."\n";
1.281     albertel 3457:     $student=~s/:/_/; # colon doen't work in javascript for names
1.63      albertel 3458:     foreach my $apart (@$parts) {
                   3459: 	my ($part,$type) = &split_part_type($apart);
1.41      ng       3460: 	my $score=$record{"resource.$part.$type"};
1.276     albertel 3461:         $result.='<td align="center">';
1.269     raeburn  3462:         my ($aggtries,$totaltries);
                   3463:         unless (exists($aggregates{$part})) {
1.270     albertel 3464: 	    $totaltries = $record{'resource.'.$part.'.tries'};
                   3465: 
                   3466: 	    $aggtries = $totaltries;
1.269     raeburn  3467:             if ($$last_resets{$part}) {  
1.270     albertel 3468:                 $aggtries = &get_num_tries(\%record,$$last_resets{$part},
                   3469: 					   $part);
                   3470:             }
1.269     raeburn  3471:             $result.='<input type="hidden" name="'.
                   3472:                 'GD_'.$student.'_'.$part.'_aggtries" value="'.$aggtries.'" />'."\n";
                   3473:             $result.='<input type="hidden" name="'.
                   3474:                 'GD_'.$student.'_'.$part.'_totaltries" value="'.$totaltries.'" />'."\n";
                   3475:             $aggregates{$part} = 1;
                   3476:         }
1.41      ng       3477: 	if ($type eq 'awarded') {
1.320     albertel 3478: 	    my $pts = $score eq '' ? '' : &compute_points($score,$$weight{$part});
1.42      ng       3479: 	    $result.='<input type="hidden" name="'.
1.89      albertel 3480: 		'GD_'.$student.'_'.$part.'_awarded_s" value="'.$pts.'" />'."\n";
1.233     albertel 3481: 	    $result.='<input type="text" name="'.
1.89      albertel 3482: 		'GD_'.$student.'_'.$part.'_awarded" '.
1.589     bisitz   3483:                 'onchange="javascript:changeSelect(\''.$part.'\',\''.$student.
1.44      ng       3484: 		'\')" value="'.$pts.'" size="4" /></td>'."\n";
1.41      ng       3485: 	} elsif ($type eq 'solved') {
                   3486: 	    my ($status,$foo)=split(/_/,$score,2);
                   3487: 	    $status = 'nothing' if ($status eq '');
1.89      albertel 3488: 	    $result.='<input type="hidden" name="'.'GD_'.$student.'_'.
1.54      albertel 3489: 		$part.'_solved_s" value="'.$status.'" />'."\n";
1.233     albertel 3490: 	    $result.='&nbsp;<select name="'.
1.89      albertel 3491: 		'GD_'.$student.'_'.$part.'_solved" '.
1.589     bisitz   3492:                 'onchange="javascript:changeOneScore(\''.$part.'\',\''.$student.'\')" >'."\n";
1.485     albertel 3493: 	    $result.= (($status eq 'excused') ? '<option> </option><option selected="selected" value="excused">'.&mt('excused').'</option>' 
                   3494: 		: '<option selected="selected"> </option><option value="excused">'.&mt('excused').'</option>')."\n";
                   3495: 	    $result.='<option value="reset status">'.&mt('reset status').'</option>';
1.126     ng       3496: 	    $result.="</select>&nbsp;</td>\n";
1.122     ng       3497: 	} else {
                   3498: 	    $result.='<input type="hidden" name="'.
                   3499: 		'GD_'.$student.'_'.$part.'_'.$type.'_s" value="'.$score.'" />'.
                   3500: 		    "\n";
1.233     albertel 3501: 	    $result.='<input type="text" name="'.
1.122     ng       3502: 		'GD_'.$student.'_'.$part.'_'.$type.'" '.
                   3503: 		'value="'.$score.'" size="4" /></td>'."\n";
1.41      ng       3504: 	}
                   3505:     }
1.474     albertel 3506:     $result.=&Apache::loncommon::end_data_table_row();
1.41      ng       3507:     return $result;
1.38      ng       3508: }
                   3509: 
1.44      ng       3510: #--- change scores for all the students in a section/class
                   3511: #    record does not get update if unchanged
1.38      ng       3512: sub editgrades {
1.608     www      3513:     my ($request,$symb) = @_;
1.41      ng       3514: 
1.433     banghart 3515:     my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
1.477     albertel 3516:     my $title='<h2>'.&mt('Current Grade Status').'</h2>';
1.433     banghart 3517:     $title.='<h4>'.&mt('<b>Section: </b>[_1]',$section_display).'</h4>'."\n";
1.126     ng       3518: 
1.477     albertel 3519:     my $result= &Apache::loncommon::start_data_table().
                   3520: 	&Apache::loncommon::start_data_table_header_row().
                   3521: 	'<th rowspan="2" valign="middle">'.&mt('No.').'</th>'.
                   3522: 	'<th rowspan="2" valign="middle">'.&nameUserString('header')."</th>\n";
1.43      ng       3523:     my %scoreptr = (
                   3524: 		    'correct'  =>'correct_by_override',
                   3525: 		    'incorrect'=>'incorrect_by_override',
                   3526: 		    'excused'  =>'excused',
                   3527: 		    'ungraded' =>'ungraded_attempted',
1.596     raeburn  3528:                     'credited' =>'credit_attempted',
1.43      ng       3529: 		    'nothing'  => '',
                   3530: 		    );
1.257     albertel 3531:     my ($classlist,undef,$fullname) = &getclasslist($env{'form.section'},'0');
1.34      ng       3532: 
1.44      ng       3533:     my (@partid);
                   3534:     my %weight = ();
1.54      albertel 3535:     my %columns = ();
1.44      ng       3536:     my ($i,$ctr,$count,$rec_update) = (0,0,0,0);
1.54      albertel 3537: 
1.582     raeburn  3538:     my $partserror;
                   3539:     my (@parts) = sort(&getpartlist($symb,\$partserror));
                   3540:     if ($partserror) {
                   3541:         return &navmap_errormsg();
                   3542:     }
1.54      albertel 3543:     my $header;
1.257     albertel 3544:     while ($ctr < $env{'form.totalparts'}) {
                   3545: 	my $partid = $env{'form.partid_'.$ctr};
1.524     raeburn  3546: 	push(@partid,$partid);
1.257     albertel 3547: 	$weight{$partid} = $env{'form.weight_'.$partid};
1.44      ng       3548: 	$ctr++;
1.54      albertel 3549:     }
1.324     albertel 3550:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
1.54      albertel 3551:     foreach my $partid (@partid) {
1.478     albertel 3552: 	$header .= '<th align="center">'.&mt('Old Score').'</th>'.
                   3553: 	    '<th align="center">'.&mt('New Score').'</th>';
1.54      albertel 3554: 	$columns{$partid}=2;
                   3555: 	foreach my $stores (@parts) {
                   3556: 	    my ($part,$type) = &split_part_type($stores);
                   3557: 	    if ($part !~ m/^\Q$partid\E/) { next;}
                   3558: 	    if ($type eq 'awarded' || $type eq 'solved') { next; }
                   3559: 	    my $display=&Apache::lonnet::metadata($url,$stores.'.display');
1.551     raeburn  3560: 	    $display =~ s/\[Part: \Q$part\E\]//;
1.539     riegler  3561:             my $narrowtext = &mt('Tries');
                   3562: 	    $display =~ s/Number of Attempts/$narrowtext/;
                   3563: 	    $header .= '<th align="center">'.&mt('Old').' '.$display.'</th>'.
                   3564: 		'<th align="center">'.&mt('New').' '.$display.'</th>';
1.54      albertel 3565: 	    $columns{$partid}+=2;
                   3566: 	}
                   3567:     }
                   3568:     foreach my $partid (@partid) {
1.324     albertel 3569: 	my $display_part=&get_display_part($partid,$symb);
1.478     albertel 3570: 	$result .= '<th colspan="'.$columns{$partid}.'" align="center">'.
                   3571: 	    &mt('Part: [_1] (Weight = [_2])',$display_part,$weight{$partid}).
                   3572: 	    '</th>';
1.54      albertel 3573: 
1.44      ng       3574:     }
1.477     albertel 3575:     $result .= &Apache::loncommon::end_data_table_header_row().
                   3576: 	&Apache::loncommon::start_data_table_header_row().
                   3577: 	$header.
                   3578: 	&Apache::loncommon::end_data_table_header_row();
                   3579:     my @noupdate;
1.126     ng       3580:     my ($updateCtr,$noupdateCtr) = (1,1);
1.257     albertel 3581:     for ($i=0; $i<$env{'form.total'}; $i++) {
1.93      albertel 3582: 	my $line;
1.257     albertel 3583: 	my $user = $env{'form.ctr'.$i};
1.281     albertel 3584: 	my ($uname,$udom)=split(/:/,$user);
1.44      ng       3585: 	my %newrecord;
                   3586: 	my $updateflag = 0;
1.281     albertel 3587: 	$line .= '<td>'.&nameUserString(undef,$$fullname{$user},$uname,$udom).'</td>';
1.108     albertel 3588: 	my $usec=$classlist->{"$uname:$udom"}[5];
1.105     albertel 3589: 	if (!&canmodify($usec)) {
1.126     ng       3590: 	    my $numcols=scalar(@partid)*4+2;
1.477     albertel 3591: 	    push(@noupdate,
1.478     albertel 3592: 		 $line."<td colspan=\"$numcols\"><span class=\"LC_warning\">".
                   3593: 		 &mt('Not allowed to modify student')."</span></td></tr>");
1.105     albertel 3594: 	    next;
                   3595: 	}
1.269     raeburn  3596:         my %aggregate = ();
                   3597:         my $aggregateflag = 0;
1.281     albertel 3598: 	$user=~s/:/_/; # colon doen't work in javascript for names
1.44      ng       3599: 	foreach (@partid) {
1.257     albertel 3600: 	    my $old_aw    = $env{'form.GD_'.$user.'_'.$_.'_awarded_s'};
1.54      albertel 3601: 	    my $old_part_pcr = $old_aw/($weight{$_} ne '0' ? $weight{$_}:1);
                   3602: 	    my $old_part  = $old_aw eq '' ? '' : $old_part_pcr;
1.257     albertel 3603: 	    my $old_score = $scoreptr{$env{'form.GD_'.$user.'_'.$_.'_solved_s'}};
                   3604: 	    my $awarded   = $env{'form.GD_'.$user.'_'.$_.'_awarded'};
1.54      albertel 3605: 	    my $pcr       = $awarded/($weight{$_} ne '0' ? $weight{$_} : 1);
                   3606: 	    my $partial   = $awarded eq '' ? '' : $pcr;
1.44      ng       3607: 	    my $score;
                   3608: 	    if ($partial eq '') {
1.257     albertel 3609: 		$score = $scoreptr{$env{'form.GD_'.$user.'_'.$_.'_solved_s'}};
1.44      ng       3610: 	    } elsif ($partial > 0) {
                   3611: 		$score = 'correct_by_override';
                   3612: 	    } elsif ($partial == 0) {
                   3613: 		$score = 'incorrect_by_override';
                   3614: 	    }
1.257     albertel 3615: 	    my $dropMenu = $env{'form.GD_'.$user.'_'.$_.'_solved'};
1.125     ng       3616: 	    $score = 'excused' if (($dropMenu eq 'excused') && ($score ne 'excused'));
                   3617: 
1.292     albertel 3618: 	    $newrecord{'resource.'.$_.'.regrader'}=
                   3619: 		"$env{'user.name'}:$env{'user.domain'}";
1.125     ng       3620: 	    if ($dropMenu eq 'reset status' &&
                   3621: 		$old_score ne '') { # ignore if no previous attempts => nothing to reset
1.299     albertel 3622: 		$newrecord{'resource.'.$_.'.tries'} = '';
1.125     ng       3623: 		$newrecord{'resource.'.$_.'.solved'} = '';
                   3624: 		$newrecord{'resource.'.$_.'.award'} = '';
1.299     albertel 3625: 		$newrecord{'resource.'.$_.'.awarded'} = '';
1.125     ng       3626: 		$updateflag = 1;
1.269     raeburn  3627:                 if ($env{'form.GD_'.$user.'_'.$_.'_aggtries'} > 0) {
                   3628:                     my $aggtries = $env{'form.GD_'.$user.'_'.$_.'_aggtries'};
                   3629:                     my $totaltries = $env{'form.GD_'.$user.'_'.$_.'_totaltries'};
                   3630:                     my $solvedstatus = $env{'form.GD_'.$user.'_'.$_.'_solved_s'};
                   3631:                     &decrement_aggs($symb,$_,\%aggregate,$aggtries,$totaltries,$solvedstatus);
                   3632:                     $aggregateflag = 1;
                   3633:                 }
1.139     albertel 3634: 	    } elsif (!($old_part eq $partial && $old_score eq $score)) {
                   3635: 		$updateflag = 1;
                   3636: 		$newrecord{'resource.'.$_.'.awarded'}  = $partial if $partial ne '';
                   3637: 		$newrecord{'resource.'.$_.'.solved'}   = $score;
                   3638: 		$rec_update++;
1.125     ng       3639: 	    }
                   3640: 
1.93      albertel 3641: 	    $line .= '<td align="center">'.$old_aw.'&nbsp;</td>'.
1.44      ng       3642: 		'<td align="center">'.$awarded.
                   3643: 		($score eq 'excused' ? $score : '').'&nbsp;</td>';
1.5       albertel 3644: 
1.54      albertel 3645: 
                   3646: 	    my $partid=$_;
                   3647: 	    foreach my $stores (@parts) {
                   3648: 		my ($part,$type) = &split_part_type($stores);
                   3649: 		if ($part !~ m/^\Q$partid\E/) { next;}
                   3650: 		if ($type eq 'awarded' || $type eq 'solved') { next; }
1.257     albertel 3651: 		my $old_aw    = $env{'form.GD_'.$user.'_'.$part.'_'.$type.'_s'};
                   3652: 		my $awarded   = $env{'form.GD_'.$user.'_'.$part.'_'.$type};
1.54      albertel 3653: 		if ($awarded ne '' && $awarded ne $old_aw) {
                   3654: 		    $newrecord{'resource.'.$part.'.'.$type}= $awarded;
1.257     albertel 3655: 		    $newrecord{'resource.'.$part.'.regrader'}="$env{'user.name'}:$env{'user.domain'}";
1.54      albertel 3656: 		    $updateflag=1;
                   3657: 		}
1.93      albertel 3658: 		$line .= '<td align="center">'.$old_aw.'&nbsp;</td>'.
1.54      albertel 3659: 		    '<td align="center">'.$awarded.'&nbsp;</td>';
                   3660: 	    }
1.44      ng       3661: 	}
1.477     albertel 3662: 	$line.="\n";
1.301     albertel 3663: 
                   3664: 	my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   3665: 	my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   3666: 
1.44      ng       3667: 	if ($updateflag) {
                   3668: 	    $count++;
1.257     albertel 3669: 	    &Apache::lonnet::cstore(\%newrecord,$symb,$env{'request.course.id'},
1.89      albertel 3670: 				    $udom,$uname);
1.301     albertel 3671: 
                   3672: 	    if (&Apache::bridgetask::in_queue('gradingqueue',$symb,$cdom,
                   3673: 					      $cnum,$udom,$uname)) {
                   3674: 		# need to figure out if should be in queue.
                   3675: 		my %record =  
                   3676: 		    &Apache::lonnet::restore($symb,$env{'request.course.id'},
                   3677: 					     $udom,$uname);
                   3678: 		my $all_graded = 1;
                   3679: 		my $none_graded = 1;
                   3680: 		foreach my $part (@parts) {
                   3681: 		    if ( $record{'resource.'.$part.'.awarded'} eq '' ) {
                   3682: 			$all_graded = 0;
                   3683: 		    } else {
                   3684: 			$none_graded = 0;
                   3685: 		    }
                   3686: 		}
                   3687: 
                   3688: 		if ($all_graded || $none_graded) {
                   3689: 		    &Apache::bridgetask::remove_from_queue('gradingqueue',
                   3690: 							   $symb,$cdom,$cnum,
                   3691: 							   $udom,$uname);
                   3692: 		}
                   3693: 	    }
                   3694: 
1.477     albertel 3695: 	    $result.=&Apache::loncommon::start_data_table_row().
                   3696: 		'<td align="right">&nbsp;'.$updateCtr.'&nbsp;</td>'.$line.
                   3697: 		&Apache::loncommon::end_data_table_row();
1.126     ng       3698: 	    $updateCtr++;
1.93      albertel 3699: 	} else {
1.477     albertel 3700: 	    push(@noupdate,
                   3701: 		 '<td align="right">&nbsp;'.$noupdateCtr.'&nbsp;</td>'.$line);
1.126     ng       3702: 	    $noupdateCtr++;
1.44      ng       3703: 	}
1.269     raeburn  3704:         if ($aggregateflag) {
                   3705:             &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
1.301     albertel 3706: 				  $cdom,$cnum);
1.269     raeburn  3707:         }
1.93      albertel 3708:     }
1.477     albertel 3709:     if (@noupdate) {
1.126     ng       3710: #	my $numcols=(scalar(@partid)*(scalar(@parts)-1)*2)+3;
                   3711: 	my $numcols=scalar(@partid)*4+2;
1.477     albertel 3712: 	$result .= &Apache::loncommon::start_data_table_row('LC_empty_row').
1.478     albertel 3713: 	    '<td align="center" colspan="'.$numcols.'">'.
                   3714: 	    &mt('No Changes Occurred For the Students Below').
                   3715: 	    '</td>'.
1.477     albertel 3716: 	    &Apache::loncommon::end_data_table_row();
                   3717: 	foreach my $line (@noupdate) {
                   3718: 	    $result.=
                   3719: 		&Apache::loncommon::start_data_table_row().
                   3720: 		$line.
                   3721: 		&Apache::loncommon::end_data_table_row();
                   3722: 	}
1.44      ng       3723:     }
1.614     www      3724:     $result .= &Apache::loncommon::end_data_table();
1.478     albertel 3725:     my $msg = '<p><b>'.
                   3726: 	&mt('Number of records updated = [_1] for [quant,_2,student].',
                   3727: 	    $rec_update,$count).'</b><br />'.
                   3728: 	'<b>'.&mt('Total number of students = [_1]',$env{'form.total'}).
                   3729: 	'</b></p>';
1.44      ng       3730:     return $title.$msg.$result;
1.5       albertel 3731: }
1.54      albertel 3732: 
                   3733: sub split_part_type {
                   3734:     my ($partstr) = @_;
                   3735:     my ($temp,@allparts)=split(/_/,$partstr);
                   3736:     my $type=pop(@allparts);
1.439     albertel 3737:     my $part=join('_',@allparts);
1.54      albertel 3738:     return ($part,$type);
                   3739: }
                   3740: 
1.44      ng       3741: #------------- end of section for handling grading by section/class ---------
                   3742: #
                   3743: #----------------------------------------------------------------------------
                   3744: 
1.5       albertel 3745: 
1.44      ng       3746: #----------------------------------------------------------------------------
                   3747: #
                   3748: #-------------------------- Next few routines handles grading by csv upload
                   3749: #
                   3750: #--- Javascript to handle csv upload
1.27      albertel 3751: sub csvupload_javascript_reverse_associate {
1.573     bisitz   3752:     my $error1=&mt('You need to specify the username or the student/employee ID');
1.246     albertel 3753:     my $error2=&mt('You need to specify at least one grading field');
1.27      albertel 3754:   return(<<ENDPICK);
                   3755:   function verify(vf) {
                   3756:     var foundsomething=0;
                   3757:     var founduname=0;
1.243     albertel 3758:     var foundID=0;
1.27      albertel 3759:     for (i=0;i<=vf.nfields.value;i++) {
                   3760:       tw=eval('vf.f'+i+'.selectedIndex');
1.243     albertel 3761:       if (i==0 && tw!=0) { foundID=1; }
                   3762:       if (i==1 && tw!=0) { founduname=1; }
                   3763:       if (i!=0 && i!=1 && i!=2 && tw!=0) { foundsomething=1; }
1.27      albertel 3764:     }
1.246     albertel 3765:     if (founduname==0 && foundID==0) {
                   3766: 	alert('$error1');
                   3767: 	return;
1.27      albertel 3768:     }
                   3769:     if (foundsomething==0) {
1.246     albertel 3770: 	alert('$error2');
                   3771: 	return;
1.27      albertel 3772:     }
                   3773:     vf.submit();
                   3774:   }
                   3775:   function flip(vf,tf) {
                   3776:     var nw=eval('vf.f'+tf+'.selectedIndex');
                   3777:     var i;
                   3778:     for (i=0;i<=vf.nfields.value;i++) {
                   3779:       //can not pick the same destination field for both name and domain
                   3780:       if (((i ==0)||(i ==1)) && 
                   3781:           ((tf==0)||(tf==1)) && 
                   3782:           (i!=tf) &&
                   3783:           (eval('vf.f'+i+'.selectedIndex')==nw)) {
                   3784:         eval('vf.f'+i+'.selectedIndex=0;')
                   3785:       }
                   3786:     }
                   3787:   }
                   3788: ENDPICK
                   3789: }
                   3790: 
                   3791: sub csvupload_javascript_forward_associate {
1.573     bisitz   3792:     my $error1=&mt('You need to specify the username or the student/employee ID');
1.246     albertel 3793:     my $error2=&mt('You need to specify at least one grading field');
1.27      albertel 3794:   return(<<ENDPICK);
                   3795:   function verify(vf) {
                   3796:     var foundsomething=0;
                   3797:     var founduname=0;
1.243     albertel 3798:     var foundID=0;
1.27      albertel 3799:     for (i=0;i<=vf.nfields.value;i++) {
                   3800:       tw=eval('vf.f'+i+'.selectedIndex');
1.243     albertel 3801:       if (tw==1) { foundID=1; }
                   3802:       if (tw==2) { founduname=1; }
                   3803:       if (tw>3) { foundsomething=1; }
1.27      albertel 3804:     }
1.246     albertel 3805:     if (founduname==0 && foundID==0) {
                   3806: 	alert('$error1');
                   3807: 	return;
1.27      albertel 3808:     }
                   3809:     if (foundsomething==0) {
1.246     albertel 3810: 	alert('$error2');
                   3811: 	return;
1.27      albertel 3812:     }
                   3813:     vf.submit();
                   3814:   }
                   3815:   function flip(vf,tf) {
                   3816:     var nw=eval('vf.f'+tf+'.selectedIndex');
                   3817:     var i;
                   3818:     //can not pick the same destination field twice
                   3819:     for (i=0;i<=vf.nfields.value;i++) {
                   3820:       if ((i!=tf) && (eval('vf.f'+i+'.selectedIndex')==nw)) {
                   3821:         eval('vf.f'+i+'.selectedIndex=0;')
                   3822:       }
                   3823:     }
                   3824:   }
                   3825: ENDPICK
                   3826: }
                   3827: 
1.26      albertel 3828: sub csvuploadmap_header {
1.324     albertel 3829:     my ($request,$symb,$datatoken,$distotal)= @_;
1.41      ng       3830:     my $javascript;
1.257     albertel 3831:     if ($env{'form.upfile_associate'} eq 'reverse') {
1.41      ng       3832: 	$javascript=&csvupload_javascript_reverse_associate();
                   3833:     } else {
                   3834: 	$javascript=&csvupload_javascript_forward_associate();
                   3835:     }
1.45      ng       3836: 
1.418     albertel 3837:     $symb = &Apache::lonenc::check_encrypt($symb);
1.632     www      3838:     $request->print('<form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">'.
                   3839:                     &mt('Total number of records found in file: [_1]',$distotal).'<hr />'.
                   3840:                     &mt('Associate entries from the uploaded file with as many fields as you can.'));
                   3841:     my $reverse=&mt("Reverse Association");
1.41      ng       3842:     $request->print(<<ENDPICK);
1.632     www      3843: <br />
                   3844: <input type="button" value="$reverse" onclick="javascript:this.form.associate.value='Reverse Association';submit(this.form);" />
1.26      albertel 3845: <input type="hidden" name="associate"  value="" />
                   3846: <input type="hidden" name="phase"      value="three" />
                   3847: <input type="hidden" name="datatoken"  value="$datatoken" />
1.257     albertel 3848: <input type="hidden" name="fileupload" value="$env{'form.fileupload'}" />
                   3849: <input type="hidden" name="upfiletype" value="$env{'form.upfiletype'}" />
1.26      albertel 3850: <input type="hidden" name="upfile_associate" 
1.257     albertel 3851:                                        value="$env{'form.upfile_associate'}" />
1.26      albertel 3852: <input type="hidden" name="symb"       value="$symb" />
1.246     albertel 3853: <input type="hidden" name="command"    value="csvuploadoptions" />
1.26      albertel 3854: <hr />
                   3855: ENDPICK
1.597     wenzelju 3856:     $request->print(&Apache::lonhtmlcommon::scripttag($javascript));
1.118     ng       3857:     return '';
1.26      albertel 3858: 
                   3859: }
                   3860: 
                   3861: sub csvupload_fields {
1.582     raeburn  3862:     my ($symb,$errorref) = @_;
                   3863:     my (@parts) = &getpartlist($symb,$errorref);
                   3864:     if (ref($errorref)) {
                   3865:         if ($$errorref) {
                   3866:             return;
                   3867:         }
                   3868:     }
                   3869: 
1.556     weissno  3870:     my @fields=(['ID','Student/Employee ID'],
1.243     albertel 3871: 		['username','Student Username'],
                   3872: 		['domain','Student Domain']);
1.324     albertel 3873:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
1.41      ng       3874:     foreach my $part (sort(@parts)) {
                   3875: 	my @datum;
                   3876: 	my $display=&Apache::lonnet::metadata($url,$part.'.display');
                   3877: 	my $name=$part;
                   3878: 	if  (!$display) { $display = $name; }
                   3879: 	@datum=($name,$display);
1.244     albertel 3880: 	if ($name=~/^stores_(.*)_awarded/) {
                   3881: 	    push(@fields,['stores_'.$1.'_points',"Points [Part: $1]"]);
                   3882: 	}
1.41      ng       3883: 	push(@fields,\@datum);
                   3884:     }
                   3885:     return (@fields);
1.26      albertel 3886: }
                   3887: 
                   3888: sub csvuploadmap_footer {
1.41      ng       3889:     my ($request,$i,$keyfields) =@_;
                   3890:     $request->print(<<ENDPICK);
1.26      albertel 3891: </table>
                   3892: <input type="hidden" name="nfields" value="$i" />
                   3893: <input type="hidden" name="keyfields" value="$keyfields" />
1.589     bisitz   3894: <input type="button" onclick="javascript:verify(this.form)" value="Assign Grades" /><br />
1.26      albertel 3895: </form>
                   3896: ENDPICK
                   3897: }
                   3898: 
1.283     albertel 3899: sub checkforfile_js {
1.638     www      3900:     my $alertmsg = &mt('Please use the browse button to select a file from your local directory.');
1.597     wenzelju 3901:     my $result = &Apache::lonhtmlcommon::scripttag(<<CSVFORMJS);
1.86      ng       3902:     function checkUpload(formname) {
                   3903: 	if (formname.upfile.value == "") {
1.539     riegler  3904: 	    alert("$alertmsg");
1.86      ng       3905: 	    return false;
                   3906: 	}
                   3907: 	formname.submit();
                   3908:     }
                   3909: CSVFORMJS
1.283     albertel 3910:     return $result;
                   3911: }
                   3912: 
                   3913: sub upcsvScores_form {
1.608     www      3914:     my ($request,$symb) = @_;
1.283     albertel 3915:     if (!$symb) {return '';}
                   3916:     my $result=&checkforfile_js();
1.632     www      3917:     $result.=&Apache::loncommon::start_data_table().
                   3918:              &Apache::loncommon::start_data_table_header_row().
                   3919:              '<th>'.&mt('Specify a file containing the class scores for current resource.').'</th>'.
                   3920:              &Apache::loncommon::end_data_table_header_row().
                   3921:              &Apache::loncommon::start_data_table_row().'<td>';
1.370     www      3922:     my $upload=&mt("Upload Scores");
1.86      ng       3923:     my $upfile_select=&Apache::loncommon::upfile_select_html();
1.245     albertel 3924:     my $ignore=&mt('Ignore First Line');
1.418     albertel 3925:     $symb = &Apache::lonenc::check_encrypt($symb);
1.86      ng       3926:     $result.=<<ENDUPFORM;
1.106     albertel 3927: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
1.86      ng       3928: <input type="hidden" name="symb" value="$symb" />
                   3929: <input type="hidden" name="command" value="csvuploadmap" />
                   3930: $upfile_select
1.589     bisitz   3931: <br /><input type="button" onclick="javascript:checkUpload(this.form);" value="$upload" />
1.86      ng       3932: </form>
                   3933: ENDUPFORM
1.370     www      3934:     $result.=&Apache::loncommon::help_open_topic("Course_Convert_To_CSV",
1.632     www      3935:                            &mt("How do I create a CSV file from a spreadsheet")).
                   3936:              '</td>'.
                   3937:             &Apache::loncommon::end_data_table_row().
                   3938:             &Apache::loncommon::end_data_table();
1.86      ng       3939:     return $result;
                   3940: }
                   3941: 
                   3942: 
1.26      albertel 3943: sub csvuploadmap {
1.608     www      3944:     my ($request,$symb)= @_;
1.41      ng       3945:     if (!$symb) {return '';}
1.72      ng       3946: 
1.41      ng       3947:     my $datatoken;
1.257     albertel 3948:     if (!$env{'form.datatoken'}) {
1.41      ng       3949: 	$datatoken=&Apache::loncommon::upfile_store($request);
1.26      albertel 3950:     } else {
1.257     albertel 3951: 	$datatoken=$env{'form.datatoken'};
1.41      ng       3952: 	&Apache::loncommon::load_tmp_file($request);
1.26      albertel 3953:     }
1.41      ng       3954:     my @records=&Apache::loncommon::upfile_record_sep();
1.324     albertel 3955:     &csvuploadmap_header($request,$symb,$datatoken,$#records+1);
1.41      ng       3956:     my ($i,$keyfields);
                   3957:     if (@records) {
1.582     raeburn  3958:         my $fieldserror;
                   3959: 	my @fields=&csvupload_fields($symb,\$fieldserror);
                   3960:         if ($fieldserror) {
                   3961:             $request->print(&navmap_errormsg());
                   3962:             return;
                   3963:         }
1.257     albertel 3964: 	if ($env{'form.upfile_associate'} eq 'reverse') {	
1.41      ng       3965: 	    &Apache::loncommon::csv_print_samples($request,\@records);
                   3966: 	    $i=&Apache::loncommon::csv_print_select_table($request,\@records,
                   3967: 							  \@fields);
                   3968: 	    foreach (@fields) { $keyfields.=$_->[0].','; }
                   3969: 	    chop($keyfields);
                   3970: 	} else {
                   3971: 	    unshift(@fields,['none','']);
                   3972: 	    $i=&Apache::loncommon::csv_samples_select_table($request,\@records,
                   3973: 							    \@fields);
1.311     banghart 3974:             foreach my $rec (@records) {
                   3975:                 my %temp = &Apache::loncommon::record_sep($rec);
                   3976:                 if (%temp) {
                   3977:                     $keyfields=join(',',sort(keys(%temp)));
                   3978:                     last;
                   3979:                 }
                   3980:             }
1.41      ng       3981: 	}
                   3982:     }
                   3983:     &csvuploadmap_footer($request,$i,$keyfields);
1.72      ng       3984: 
1.41      ng       3985:     return '';
1.27      albertel 3986: }
                   3987: 
1.246     albertel 3988: sub csvuploadoptions {
1.608     www      3989:     my ($request,$symb)= @_;
1.632     www      3990:     my $overwrite=&mt('Overwrite any existing score');
1.246     albertel 3991:     $request->print(<<ENDPICK);
                   3992: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
                   3993: <input type="hidden" name="command"    value="csvuploadassign" />
                   3994: <p>
                   3995: <label>
                   3996:    <input type="checkbox" name="overwite_scores" checked="checked" />
1.632     www      3997:    $overwrite
1.246     albertel 3998: </label>
                   3999: </p>
                   4000: ENDPICK
                   4001:     my %fields=&get_fields();
                   4002:     if (!defined($fields{'domain'})) {
1.257     albertel 4003: 	my $domform = &Apache::loncommon::select_dom_form($env{'request.role.domain'},'default_domain');
1.632     www      4004: 	$request->print("\n<p>".&mt('Users are in domain: [_1]',$domform)."</p>\n");
1.246     albertel 4005:     }
1.257     albertel 4006:     foreach my $key (sort(keys(%env))) {
1.246     albertel 4007: 	if ($key !~ /^form\.(.*)$/) { next; }
                   4008: 	my $cleankey=$1;
                   4009: 	if ($cleankey eq 'command') { next; }
                   4010: 	$request->print('<input type="hidden" name="'.$cleankey.
1.257     albertel 4011: 			'"  value="'.$env{$key}.'" />'."\n");
1.246     albertel 4012:     }
                   4013:     # FIXME do a check for any duplicated user ids...
                   4014:     # FIXME do a check for any invalid user ids?...
1.290     albertel 4015:     $request->print('<input type="submit" value="Assign Grades" /><br />
                   4016: <hr /></form>'."\n");
1.246     albertel 4017:     return '';
                   4018: }
                   4019: 
                   4020: sub get_fields {
                   4021:     my %fields;
1.257     albertel 4022:     my @keyfields = split(/\,/,$env{'form.keyfields'});
                   4023:     for (my $i=0; $i<=$env{'form.nfields'}; $i++) {
                   4024: 	if ($env{'form.upfile_associate'} eq 'reverse') {
                   4025: 	    if ($env{'form.f'.$i} ne 'none') {
                   4026: 		$fields{$keyfields[$i]}=$env{'form.f'.$i};
1.41      ng       4027: 	    }
                   4028: 	} else {
1.257     albertel 4029: 	    if ($env{'form.f'.$i} ne 'none') {
                   4030: 		$fields{$env{'form.f'.$i}}=$keyfields[$i];
1.41      ng       4031: 	    }
                   4032: 	}
1.27      albertel 4033:     }
1.246     albertel 4034:     return %fields;
                   4035: }
                   4036: 
                   4037: sub csvuploadassign {
1.608     www      4038:     my ($request,$symb)= @_;
1.246     albertel 4039:     if (!$symb) {return '';}
1.345     bowersj2 4040:     my $error_msg = '';
1.246     albertel 4041:     &Apache::loncommon::load_tmp_file($request);
                   4042:     my @gradedata = &Apache::loncommon::upfile_record_sep();
                   4043:     my %fields=&get_fields();
1.257     albertel 4044:     my $courseid=$env{'request.course.id'};
1.97      albertel 4045:     my ($classlist) = &getclasslist('all',0);
1.106     albertel 4046:     my @notallowed;
1.41      ng       4047:     my @skipped;
                   4048:     my $countdone=0;
                   4049:     foreach my $grade (@gradedata) {
                   4050: 	my %entries=&Apache::loncommon::record_sep($grade);
1.246     albertel 4051: 	my $domain;
                   4052: 	if ($entries{$fields{'domain'}}) {
                   4053: 	    $domain=$entries{$fields{'domain'}};
                   4054: 	} else {
1.257     albertel 4055: 	    $domain=$env{'form.default_domain'};
1.246     albertel 4056: 	}
1.243     albertel 4057: 	$domain=~s/\s//g;
1.41      ng       4058: 	my $username=$entries{$fields{'username'}};
1.160     albertel 4059: 	$username=~s/\s//g;
1.243     albertel 4060: 	if (!$username) {
                   4061: 	    my $id=$entries{$fields{'ID'}};
1.247     albertel 4062: 	    $id=~s/\s//g;
1.243     albertel 4063: 	    my %ids=&Apache::lonnet::idget($domain,$id);
                   4064: 	    $username=$ids{$id};
                   4065: 	}
1.41      ng       4066: 	if (!exists($$classlist{"$username:$domain"})) {
1.247     albertel 4067: 	    my $id=$entries{$fields{'ID'}};
                   4068: 	    $id=~s/\s//g;
                   4069: 	    if ($id) {
                   4070: 		push(@skipped,"$id:$domain");
                   4071: 	    } else {
                   4072: 		push(@skipped,"$username:$domain");
                   4073: 	    }
1.41      ng       4074: 	    next;
                   4075: 	}
1.108     albertel 4076: 	my $usec=$classlist->{"$username:$domain"}[5];
1.106     albertel 4077: 	if (!&canmodify($usec)) {
                   4078: 	    push(@notallowed,"$username:$domain");
                   4079: 	    next;
                   4080: 	}
1.244     albertel 4081: 	my %points;
1.41      ng       4082: 	my %grades;
                   4083: 	foreach my $dest (keys(%fields)) {
1.244     albertel 4084: 	    if ($dest eq 'ID' || $dest eq 'username' ||
                   4085: 		$dest eq 'domain') { next; }
                   4086: 	    if ($entries{$fields{$dest}} =~ /^\s*$/) { next; }
                   4087: 	    if ($dest=~/stores_(.*)_points/) {
                   4088: 		my $part=$1;
                   4089: 		my $wgt =&Apache::lonnet::EXT('resource.'.$part.'.weight',
                   4090: 					      $symb,$domain,$username);
1.345     bowersj2 4091:                 if ($wgt) {
                   4092:                     $entries{$fields{$dest}}=~s/\s//g;
                   4093:                     my $pcr=$entries{$fields{$dest}} / $wgt;
1.463     albertel 4094:                     my $award=($pcr == 0) ? 'incorrect_by_override'
                   4095:                                           : 'correct_by_override';
1.638     www      4096:                     if ($pcr>1) {
                   4097:                        push(@skipped,&mt("[_1]: point value larger than weight","$username:$domain"));
                   4098:                     }
1.345     bowersj2 4099:                     $grades{"resource.$part.awarded"}=$pcr;
                   4100:                     $grades{"resource.$part.solved"}=$award;
                   4101:                     $points{$part}=1;
                   4102:                 } else {
                   4103:                     $error_msg = "<br />" .
                   4104:                         &mt("Some point values were assigned"
                   4105:                             ." for problems with a weight "
                   4106:                             ."of zero. These values were "
                   4107:                             ."ignored.");
                   4108:                 }
1.244     albertel 4109: 	    } else {
                   4110: 		if ($dest=~/stores_(.*)_awarded/) { if ($points{$1}) {next;} }
                   4111: 		if ($dest=~/stores_(.*)_solved/)  { if ($points{$1}) {next;} }
                   4112: 		my $store_key=$dest;
                   4113: 		$store_key=~s/^stores/resource/;
                   4114: 		$store_key=~s/_/\./g;
                   4115: 		$grades{$store_key}=$entries{$fields{$dest}};
                   4116: 	    }
1.41      ng       4117: 	}
1.508     www      4118: 	if (! %grades) { 
                   4119:            push(@skipped,&mt("[_1]: no data to save","$username:$domain")); 
                   4120:         } else {
                   4121: 	   $grades{"resource.regrader"}="$env{'user.name'}:$env{'user.domain'}";
                   4122: 	   my $result=&Apache::lonnet::cstore(\%grades,$symb,
1.302     albertel 4123: 					   $env{'request.course.id'},
                   4124: 					   $domain,$username);
1.508     www      4125: 	   if ($result eq 'ok') {
1.627     www      4126: # Successfully stored
1.508     www      4127: 	      $request->print('.');
1.627     www      4128: # Remove from grading queue
                   4129:               &Apache::bridgetask::remove_from_queue('gradingqueue',$symb,
                   4130:                                              $env{'course.'.$env{'request.course.id'}.'.domain'},
                   4131:                                              $env{'course.'.$env{'request.course.id'}.'.num'},
                   4132:                                              $domain,$username);
                   4133:               $countdone++;
                   4134:            } else {
1.508     www      4135: 	      $request->print("<p><span class=\"LC_error\">".
                   4136:                               &mt("Failed to save data for student [_1]. Message when trying to save was: [_2]",
                   4137:                                   "$username:$domain",$result)."</span></p>");
                   4138: 	   }
                   4139: 	   $request->rflush();
                   4140:         }
1.41      ng       4141:     }
1.570     www      4142:     $request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt("Saved scores for [quant,_1,student]",$countdone),$countdone==0));
1.41      ng       4143:     if (@skipped) {
1.571     www      4144: 	$request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt('No scores stored for the following username(s):'),1).'<br />');
                   4145:         $request->print(join(', ',@skipped));
1.106     albertel 4146:     }
                   4147:     if (@notallowed) {
1.571     www      4148: 	$request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt('Modification of scores not allowed for the following username(s):'),1).'<br />');
                   4149: 	$request->print(join(', ',@notallowed));
1.41      ng       4150:     }
1.106     albertel 4151:     $request->print("<br />\n");
1.345     bowersj2 4152:     return $error_msg;
1.26      albertel 4153: }
1.44      ng       4154: #------------- end of section for handling csv file upload ---------
                   4155: #
                   4156: #-------------------------------------------------------------------
                   4157: #
1.122     ng       4158: #-------------- Next few routines handle grading by page/sequence
1.72      ng       4159: #
                   4160: #--- Select a page/sequence and a student to grade
1.68      ng       4161: sub pickStudentPage {
1.608     www      4162:     my ($request,$symb) = @_;
1.68      ng       4163: 
1.539     riegler  4164:     my $alertmsg = &mt('Please select the student you wish to grade.');
1.597     wenzelju 4165:     $request->print(&Apache::lonhtmlcommon::scripttag(<<LISTJAVASCRIPT));
1.68      ng       4166: 
                   4167: function checkPickOne(formname) {
1.76      ng       4168:     if (radioSelection(formname.student) == null) {
1.539     riegler  4169: 	alert("$alertmsg");
1.68      ng       4170: 	return;
                   4171:     }
1.125     ng       4172:     ptr = pullDownSelection(formname.selectpage);
                   4173:     formname.page.value = formname["page"+ptr].value;
                   4174:     formname.title.value = formname["title"+ptr].value;
1.68      ng       4175:     formname.submit();
                   4176: }
                   4177: 
                   4178: LISTJAVASCRIPT
1.118     ng       4179:     &commonJSfunctions($request);
1.608     www      4180: 
1.257     albertel 4181:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
                   4182:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
                   4183:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
1.68      ng       4184: 
1.398     albertel 4185:     my $result='<h3><span class="LC_info">&nbsp;'.
1.485     albertel 4186: 	&mt('Manual Grading by Page or Sequence').'</span></h3>';
1.68      ng       4187: 
1.80      ng       4188:     $result.='<form action="/adm/grades" method="post" name="displayPage">'."\n";
1.582     raeburn  4189:     my $map_error;
                   4190:     my ($titles,$symbx) = &getSymbMap($map_error);
                   4191:     if ($map_error) {
                   4192:         $request->print(&navmap_errormsg());
                   4193:         return; 
                   4194:     }
1.137     albertel 4195:     my ($curpage) =&Apache::lonnet::decode_symb($symb); 
                   4196: #    my ($curpage,$mapId) =&Apache::lonnet::decode_symb($symb); 
                   4197: #    my $type=($curpage =~ /\.(page|sequence)/);
1.485     albertel 4198:     my $select = '<select name="selectpage">'."\n";
1.70      ng       4199:     my $ctr=0;
1.68      ng       4200:     foreach (@$titles) {
                   4201: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
1.485     albertel 4202: 	$select.='<option value="'.$ctr.'" '.
1.401     albertel 4203: 	    ($$symbx{$_} =~ /$curpage$/ ? 'selected="selected"' : '').
1.71      ng       4204: 	    '>'.$showtitle.'</option>'."\n";
1.70      ng       4205: 	$ctr++;
1.68      ng       4206:     }
1.485     albertel 4207:     $select.= '</select>';
1.539     riegler  4208:     $result.='&nbsp;<b>'.&mt('Problems from').':</b> '.$select."<br />\n";
1.485     albertel 4209: 
1.70      ng       4210:     $ctr=0;
                   4211:     foreach (@$titles) {
                   4212: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
                   4213: 	$result.='<input type="hidden" name="page'.$ctr.'" value="'.$$symbx{$_}.'" />'."\n";
                   4214: 	$result.='<input type="hidden" name="title'.$ctr.'" value="'.$showtitle.'" />'."\n";
                   4215: 	$ctr++;
                   4216:     }
1.72      ng       4217:     $result.='<input type="hidden" name="page" />'."\n".
                   4218: 	'<input type="hidden" name="title" />'."\n";
1.68      ng       4219: 
1.485     albertel 4220:     my $options =
                   4221: 	'<label><input type="radio" name="vProb" value="no" checked="checked" /> '.&mt('no').' </label>'."\n".
                   4222: 	'<label><input type="radio" name="vProb" value="yes" /> '.&mt('yes').' </label>'."<br />\n";
1.539     riegler  4223:     $result.='&nbsp;<b>'.&mt('View Problem Text').': </b>'.$options;
1.485     albertel 4224: 
                   4225:     $options =
                   4226: 	'<label><input type="radio" name="lastSub" value="none" /> '.&mt('none').' </label>'."\n".
                   4227: 	'<label><input type="radio" name="lastSub" value="datesub" checked="checked" /> '.&mt('by dates and submissions').'</label>'."\n".
                   4228: 	'<label><input type="radio" name="lastSub" value="all" /> '.&mt('all details').' </label>'."\n";
1.539     riegler  4229:     $result.='&nbsp;<b>'.&mt('Submissions').': </b>'.$options;
1.432     banghart 4230:     
                   4231:     $result.=&build_section_inputs();
1.442     banghart 4232:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
                   4233:     $result.='<input type="hidden" name="Status"  value="'.$stu_status.'" />'."\n".
1.72      ng       4234: 	'<input type="hidden" name="command" value="displayPage" />'."\n".
1.613     www      4235: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."<br />\n";
1.72      ng       4236: 
1.539     riegler  4237:     $result.='&nbsp;<b>'.&mt('Use CODE').': </b> <input type="text" name="CODE" value="" /> <br />'."\n";
1.382     albertel 4238: 
1.80      ng       4239:     $result.='&nbsp;<input type="button" '.
1.589     bisitz   4240:              'onclick="javascript:checkPickOne(this.form);" value="'.&mt('Next').' &rarr;" /><br />'."\n";
1.72      ng       4241: 
1.68      ng       4242:     $request->print($result);
                   4243: 
1.485     albertel 4244:     my $studentTable.='&nbsp;<b>'.&mt('Select a student you wish to grade and then click on the Next button.').'</b><br />'.
1.484     albertel 4245: 	&Apache::loncommon::start_data_table().
                   4246: 	&Apache::loncommon::start_data_table_header_row().
1.485     albertel 4247: 	'<th align="right">&nbsp;'.&mt('No.').'</th>'.
1.484     albertel 4248: 	'<th>'.&nameUserString('header').'</th>'.
1.485     albertel 4249: 	'<th align="right">&nbsp;'.&mt('No.').'</th>'.
1.484     albertel 4250: 	'<th>'.&nameUserString('header').'</th>'.
                   4251: 	&Apache::loncommon::end_data_table_header_row();
1.68      ng       4252:  
1.76      ng       4253:     my (undef,undef,$fullname) = &getclasslist($getsec,'1');
1.68      ng       4254:     my $ptr = 1;
1.294     albertel 4255:     foreach my $student (sort 
                   4256: 			 {
                   4257: 			     if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                   4258: 				 return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                   4259: 			     }
                   4260: 			     return $a cmp $b;
                   4261: 			 } (keys(%$fullname))) {
1.68      ng       4262: 	my ($uname,$udom) = split(/:/,$student);
1.484     albertel 4263: 	$studentTable.=($ptr%2==1 ? &Apache::loncommon::start_data_table_row()
                   4264:                                   : '</td>');
1.126     ng       4265: 	$studentTable.='<td align="right">'.$ptr.'&nbsp;</td>';
1.288     albertel 4266: 	$studentTable.='<td>&nbsp;<label><input type="radio" name="student" value="'.$student.'" /> '
                   4267: 	    .&nameUserString(undef,$$fullname{$student},$uname,$udom)."</label>\n";
1.484     albertel 4268: 	$studentTable.=
                   4269: 	    ($ptr%2 == 0 ? '</td>'.&Apache::loncommon::end_data_table_row() 
                   4270:                          : '');
1.68      ng       4271: 	$ptr++;
                   4272:     }
1.484     albertel 4273:     if ($ptr%2 == 0) {
                   4274: 	$studentTable.='</td><td>&nbsp;</td><td>&nbsp;</td>'.
                   4275: 	    &Apache::loncommon::end_data_table_row();
                   4276:     }
                   4277:     $studentTable.=&Apache::loncommon::end_data_table()."\n";
1.126     ng       4278:     $studentTable.='<input type="button" '.
1.589     bisitz   4279:                    'onclick="javascript:checkPickOne(this.form);" value="'.&mt('Next').' &rarr;" /></form>'."\n";
1.68      ng       4280: 
                   4281:     $request->print($studentTable);
                   4282: 
                   4283:     return '';
                   4284: }
                   4285: 
                   4286: sub getSymbMap {
1.582     raeburn  4287:     my ($map_error) = @_;
1.132     bowersj2 4288:     my $navmap = Apache::lonnavmaps::navmap->new();
1.582     raeburn  4289:     unless (ref($navmap)) {
                   4290:         if (ref($map_error)) {
                   4291:             $$map_error = 'navmap';
                   4292:         }
                   4293:         return;
                   4294:     }
1.68      ng       4295:     my %symbx = ();
                   4296:     my @titles = ();
1.117     bowersj2 4297:     my $minder = 0;
                   4298: 
                   4299:     # Gather every sequence that has problems.
1.240     albertel 4300:     my @sequences = $navmap->retrieveResources(undef, sub { shift->is_map(); },
                   4301: 					       1,0,1);
1.117     bowersj2 4302:     for my $sequence ($navmap->getById('0.0'), @sequences) {
1.241     albertel 4303: 	if ($navmap->hasResource($sequence, sub { shift->is_problem(); }, 0) ) {
1.381     albertel 4304: 	    my $title = $minder.'.'.
                   4305: 		&HTML::Entities::encode($sequence->compTitle(),'"\'&');
                   4306: 	    push(@titles, $title); # minder in case two titles are identical
                   4307: 	    $symbx{$title} = &HTML::Entities::encode($sequence->symb(),'"\'&');
1.117     bowersj2 4308: 	    $minder++;
1.241     albertel 4309: 	}
1.68      ng       4310:     }
                   4311:     return \@titles,\%symbx;
                   4312: }
                   4313: 
1.72      ng       4314: #
                   4315: #--- Displays a page/sequence w/wo problems, w/wo submissions
1.68      ng       4316: sub displayPage {
1.608     www      4317:     my ($request,$symb) = @_;
1.257     albertel 4318:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
                   4319:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
                   4320:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
                   4321:     my $pageTitle = $env{'form.page'};
1.103     albertel 4322:     my ($classlist,undef,$fullname) = &getclasslist($getsec,'1');
1.257     albertel 4323:     my ($uname,$udom) = split(/:/,$env{'form.student'});
                   4324:     my $usec=$classlist->{$env{'form.student'}}[5];
1.168     albertel 4325: 
                   4326:     #need to make sure we have the correct data for later EXT calls, 
                   4327:     #thus invalidate the cache
                   4328:     &Apache::lonnet::devalidatecourseresdata(
1.257     albertel 4329:                  $env{'course.'.$env{'request.course.id'}.'.num'},
                   4330:                  $env{'course.'.$env{'request.course.id'}.'.domain'});
1.168     albertel 4331:     &Apache::lonnet::clear_EXT_cache_status();
                   4332: 
1.103     albertel 4333:     if (!&canview($usec)) {
1.485     albertel 4334: 	$request->print('<span class="LC_warning">'.&mt('Unable to view requested student. ([_1])',$env{'form.student'}).'</span>');
1.103     albertel 4335: 	return;
                   4336:     }
1.398     albertel 4337:     my $result='<h3><span class="LC_info">&nbsp;'.$env{'form.title'}.'</span></h3>';
1.485     albertel 4338:     $result.='<h3>&nbsp;'.&mt('Student: [_1]',&nameUserString(undef,$$fullname{$env{'form.student'}},$uname,$udom)).
1.129     ng       4339: 	'</h3>'."\n";
1.500     albertel 4340:     $env{'form.CODE'} = uc($env{'form.CODE'});
1.501     foxr     4341:     if (&Apache::lonnet::validCODE(uc($env{'form.CODE'}))) {
1.485     albertel 4342: 	$result.='<h3>&nbsp;'.&mt('CODE: [_1]',$env{'form.CODE'}).'</h3>'."\n";
1.382     albertel 4343:     } else {
                   4344: 	delete($env{'form.CODE'});
                   4345:     }
1.71      ng       4346:     &sub_page_js($request);
                   4347:     $request->print($result);
                   4348: 
1.132     bowersj2 4349:     my $navmap = Apache::lonnavmaps::navmap->new();
1.582     raeburn  4350:     unless (ref($navmap)) {
                   4351:         $request->print(&navmap_errormsg());
                   4352:         return;
                   4353:     }
1.257     albertel 4354:     my ($mapUrl, $id, $resUrl)=&Apache::lonnet::decode_symb($env{'form.page'});
1.68      ng       4355:     my $map = $navmap->getResourceByUrl($resUrl); # add to navmaps
1.288     albertel 4356:     if (!$map) {
1.485     albertel 4357: 	$request->print('<span class="LC_warning">'.&mt('Unable to view requested sequence. ([_1])',$resUrl).'</span>');
1.288     albertel 4358: 	return; 
                   4359:     }
1.68      ng       4360:     my $iterator = $navmap->getIterator($map->map_start(),
                   4361: 					$map->map_finish());
                   4362: 
1.71      ng       4363:     my $studentTable='<form action="/adm/grades" method="post" name="gradePage">'."\n".
1.72      ng       4364: 	'<input type="hidden" name="command" value="gradeByPage" />'."\n".
1.257     albertel 4365: 	'<input type="hidden" name="fullname" value="'.$$fullname{$env{'form.student'}}.'" />'."\n".
                   4366: 	'<input type="hidden" name="student" value="'.$env{'form.student'}.'" />'."\n".
1.72      ng       4367: 	'<input type="hidden" name="page"    value="'.$pageTitle.'" />'."\n".
1.257     albertel 4368: 	'<input type="hidden" name="title"   value="'.$env{'form.title'}.'" />'."\n".
1.418     albertel 4369: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.613     www      4370: 	'<input type="hidden" name="overRideScore" value="no" />'."\n";
1.71      ng       4371: 
1.382     albertel 4372:     if (defined($env{'form.CODE'})) {
                   4373: 	$studentTable.=
                   4374: 	    '<input type="hidden" name="CODE" value="'.$env{'form.CODE'}.'" />'."\n";
                   4375:     }
1.381     albertel 4376:     my $checkIcon = '<img alt="'.&mt('Check Mark').
1.485     albertel 4377: 	'" src="'.&Apache::loncommon::lonhttpdurl($request->dir_config('lonIconsURL').'/check.gif').'" height="16" border="0" />';
1.71      ng       4378: 
1.594     bisitz   4379:     $studentTable.='&nbsp;<span class="LC_info">'.
                   4380:         &mt('Problems graded correct by the computer are marked with a [_1] symbol.',$checkIcon).
                   4381:         '</span>'."\n".
1.484     albertel 4382: 	&Apache::loncommon::start_data_table().
                   4383: 	&Apache::loncommon::start_data_table_header_row().
                   4384: 	'<th align="center">&nbsp;Prob.&nbsp;</th>'.
1.485     albertel 4385: 	'<th>&nbsp;'.($env{'form.vProb'} eq 'no' ? &mt('Title') : &mt('Problem Text')).'/'.&mt('Grade').'</th>'.
1.484     albertel 4386: 	&Apache::loncommon::end_data_table_header_row();
1.71      ng       4387: 
1.329     albertel 4388:     &Apache::lonxml::clear_problem_counter();
1.196     albertel 4389:     my ($depth,$question,$prob) = (1,1,1);
1.68      ng       4390:     $iterator->next(); # skip the first BEGIN_MAP
                   4391:     my $curRes = $iterator->next(); # for "current resource"
1.101     albertel 4392:     while ($depth > 0) {
1.68      ng       4393:         if($curRes == $iterator->BEGIN_MAP) { $depth++; }
1.100     bowersj2 4394:         if($curRes == $iterator->END_MAP) { $depth--; }
1.68      ng       4395: 
1.385     albertel 4396:         if (ref($curRes) && $curRes->is_problem()) {
1.91      albertel 4397: 	    my $parts = $curRes->parts();
1.68      ng       4398:             my $title = $curRes->compTitle();
1.71      ng       4399: 	    my $symbx = $curRes->symb();
1.484     albertel 4400: 	    $studentTable.=
                   4401: 		&Apache::loncommon::start_data_table_row().
                   4402: 		'<td align="center" valign="top" >'.$prob.
1.485     albertel 4403: 		(scalar(@{$parts}) == 1 ? '' 
1.640   ! raeburn  4404: 		                        : '<br />('.&mt('[_1]parts)',
        !          4405: 							scalar(@{$parts}).'&nbsp;')
1.485     albertel 4406: 		 ).
                   4407: 		 '</td>';
1.71      ng       4408: 	    $studentTable.='<td valign="top">';
1.382     albertel 4409: 	    my %form = ('CODE' => $env{'form.CODE'},);
1.257     albertel 4410: 	    if ($env{'form.vProb'} eq 'yes' ) {
1.144     albertel 4411: 		$studentTable.=&show_problem($request,$symbx,$uname,$udom,1,
1.383     albertel 4412: 					     undef,'both',\%form);
1.71      ng       4413: 	    } else {
1.382     albertel 4414: 		my $companswer = &Apache::loncommon::get_student_answers($symbx,$uname,$udom,$env{'request.course.id'},%form);
1.80      ng       4415: 		$companswer =~ s|<form(.*?)>||g;
                   4416: 		$companswer =~ s|</form>||g;
1.71      ng       4417: #		while ($companswer =~ /(<a href\=\"javascript:newWindow.*?Script Vars<\/a>)/s) { #<a href="javascript:newWindow</a>
1.116     ng       4418: #		    $companswer =~ s/$1/ /ms;
1.326     albertel 4419: #		    $request->print('match='.$1."<br />\n");
1.71      ng       4420: #		}
1.116     ng       4421: #		$companswer =~ s|<table border=\"1\">|<table border=\"0\">|g;
1.539     riegler  4422: 		$studentTable.='&nbsp;<b>'.$title.'</b>&nbsp;<br />&nbsp;<b>'.&mt('Correct answer').':</b><br />'.$companswer;
1.71      ng       4423: 	    }
                   4424: 
1.257     albertel 4425: 	    my %record = &Apache::lonnet::restore($symbx,$env{'request.course.id'},$udom,$uname);
1.125     ng       4426: 
1.257     albertel 4427: 	    if ($env{'form.lastSub'} eq 'datesub') {
1.71      ng       4428: 		if ($record{'version'} eq '') {
1.485     albertel 4429: 		    $studentTable.='<br />&nbsp;<span class="LC_warning">'.&mt('No recorded submission for this problem.').'</span><br />';
1.71      ng       4430: 		} else {
1.116     ng       4431: 		    my %responseType = ();
                   4432: 		    foreach my $partid (@{$parts}) {
1.147     albertel 4433: 			my @responseIds =$curRes->responseIds($partid);
                   4434: 			my @responseType =$curRes->responseType($partid);
                   4435: 			my %responseIds;
                   4436: 			for (my $i=0;$i<=$#responseIds;$i++) {
                   4437: 			    $responseIds{$responseIds[$i]}=$responseType[$i];
                   4438: 			}
                   4439: 			$responseType{$partid} = \%responseIds;
1.116     ng       4440: 		    }
1.148     albertel 4441: 		    $studentTable.= &displaySubByDates($symbx,\%record,$parts,\%responseType,$checkIcon,$uname,$udom);
1.147     albertel 4442: 
1.71      ng       4443: 		}
1.257     albertel 4444: 	    } elsif ($env{'form.lastSub'} eq 'all') {
                   4445: 		my $last = ($env{'form.lastSub'} eq 'last' ? 'last' : '');
1.71      ng       4446: 		$studentTable.=&Apache::loncommon::get_previous_attempt($symbx,$uname,$udom,
1.257     albertel 4447: 									$env{'request.course.id'},
1.71      ng       4448: 									'','.submission');
                   4449:  
                   4450: 	    }
1.103     albertel 4451: 	    if (&canmodify($usec)) {
1.585     bisitz   4452:             $studentTable.=&gradeBox_start();
1.103     albertel 4453: 		foreach my $partid (@{$parts}) {
                   4454: 		    $studentTable.=&gradeBox($request,$symbx,$uname,$udom,$question,$partid,\%record);
                   4455: 		    $studentTable.='<input type="hidden" name="q_'.$question.'" value="'.$partid.'" />'."\n";
                   4456: 		    $question++;
                   4457: 		}
1.585     bisitz   4458:             $studentTable.=&gradeBox_end();
1.196     albertel 4459: 		$prob++;
1.71      ng       4460: 	    }
                   4461: 	    $studentTable.='</td></tr>';
1.68      ng       4462: 
1.103     albertel 4463: 	}
1.68      ng       4464:         $curRes = $iterator->next();
                   4465:     }
                   4466: 
1.589     bisitz   4467:     $studentTable.=
                   4468:         '</table>'."\n".
                   4469:         '<input type="button" value="'.&mt('Save').'" '.
                   4470:         'onclick="javascript:checkSubmitPage(this.form,'.$question.');" />'.
                   4471:         '</form>'."\n";
1.71      ng       4472:     $request->print($studentTable);
                   4473: 
                   4474:     return '';
1.119     ng       4475: }
                   4476: 
                   4477: sub displaySubByDates {
1.148     albertel 4478:     my ($symb,$record,$parts,$responseType,$checkIcon,$uname,$udom) = @_;
1.224     albertel 4479:     my $isCODE=0;
1.335     albertel 4480:     my $isTask = ($symb =~/\.task$/);
1.224     albertel 4481:     if (exists($record->{'resource.CODE'})) { $isCODE=1; }
1.467     albertel 4482:     my $studentTable=&Apache::loncommon::start_data_table().
                   4483: 	&Apache::loncommon::start_data_table_header_row().
                   4484: 	'<th>'.&mt('Date/Time').'</th>'.
                   4485: 	($isCODE?'<th>'.&mt('CODE').'</th>':'').
                   4486: 	'<th>'.&mt('Submission').'</th>'.
                   4487: 	'<th>'.&mt('Status').'</th>'.
                   4488: 	&Apache::loncommon::end_data_table_header_row();
1.119     ng       4489:     my ($version);
                   4490:     my %mark;
1.148     albertel 4491:     my %orders;
1.119     ng       4492:     $mark{'correct_by_student'} = $checkIcon;
1.147     albertel 4493:     if (!exists($$record{'1:timestamp'})) {
1.539     riegler  4494: 	return '<br />&nbsp;<span class="LC_warning">'.&mt('Nothing submitted - no attempts.').'</span><br />';
1.147     albertel 4495:     }
1.335     albertel 4496: 
                   4497:     my $interaction;
1.525     raeburn  4498:     my $no_increment = 1;
1.640   ! raeburn  4499:     my %lastrndseed;
1.119     ng       4500:     for ($version=1;$version<=$$record{'version'};$version++) {
1.467     albertel 4501: 	my $timestamp = 
                   4502: 	    &Apache::lonlocal::locallocaltime($$record{$version.':timestamp'});
1.335     albertel 4503: 	if (exists($$record{$version.':resource.0.version'})) {
                   4504: 	    $interaction = $$record{$version.':resource.0.version'};
                   4505: 	}
                   4506: 
                   4507: 	my $where = ($isTask ? "$version:resource.$interaction"
                   4508: 		             : "$version:resource");
1.467     albertel 4509: 	$studentTable.=&Apache::loncommon::start_data_table_row().
                   4510: 	    '<td>'.$timestamp.'</td>';
1.224     albertel 4511: 	if ($isCODE) {
                   4512: 	    $studentTable.='<td>'.$record->{$version.':resource.CODE'}.'</td>';
                   4513: 	}
1.119     ng       4514: 	my @versionKeys = split(/\:/,$$record{$version.':keys'});
                   4515: 	my @displaySub = ();
                   4516: 	foreach my $partid (@{$parts}) {
1.640   ! raeburn  4517:             my ($hidden,$type);
        !          4518:             $type = $$record{$version.':resource.'.$partid.'.type'};
        !          4519:             if (($type eq 'anonsurvey') || ($type eq 'anonsurveycred')) {
1.596     raeburn  4520:                 $hidden = 1;
                   4521:             }
1.335     albertel 4522: 	    my @matchKey = ($isTask ? sort(grep /^resource\.\d+\.\Q$partid\E\.award$/,@versionKeys)
                   4523: 			            : sort(grep /^resource\.\Q$partid\E\..*?\.submission$/,@versionKeys));
                   4524: 	    
1.122     ng       4525: #	    next if ($$record{"$version:resource.$partid.solved"} eq '');
1.324     albertel 4526: 	    my $display_part=&get_display_part($partid,$symb);
1.147     albertel 4527: 	    foreach my $matchKey (@matchKey) {
1.198     albertel 4528: 		if (exists($$record{$version.':'.$matchKey}) &&
                   4529: 		    $$record{$version.':'.$matchKey} ne '') {
1.596     raeburn  4530:                     
1.335     albertel 4531: 		    my ($responseId)= ($isTask ? ($matchKey=~ /^resource\.(.*?)\.\Q$partid\E\.award$/)
                   4532: 				               : ($matchKey=~ /^resource\.\Q$partid\E\.(.*?)\.submission$/));
1.577     bisitz   4533:                     $displaySub[0].='<span class="LC_nobreak"';
                   4534:                     $displaySub[0].='<b>'.&mt('Part: [_1]',$display_part).'</b>'
                   4535:                                    .' <span class="LC_internal_info">'
1.625     www      4536:                                    .'('.&mt('Response ID: [_1]',$responseId).')'
1.577     bisitz   4537:                                    .'</span>'
                   4538:                                    .' <b>';
1.596     raeburn  4539:                     if ($hidden) {
                   4540:                         $displaySub[0].= &mt('Anonymous Survey').'</b>';
                   4541:                     } else {
1.640   ! raeburn  4542:                         my ($trial,$rndseed,$newvariation);
        !          4543:                         if ($type eq 'randomizetry') {
        !          4544:                             $trial = $$record{"$where.$partid.tries"};
        !          4545:                             $rndseed = $$record{"$where.$partid.rndseed"};
        !          4546:                         }
1.596     raeburn  4547: 		        if ($$record{"$where.$partid.tries"} eq '') {
                   4548: 			    $displaySub[0].=&mt('Trial not counted');
                   4549: 		        } else {
                   4550: 			    $displaySub[0].=&mt('Trial: [_1]',
1.467     albertel 4551: 					    $$record{"$where.$partid.tries"});
1.640   ! raeburn  4552:                             if ($rndseed || $lastrndseed{$partid}) {
        !          4553:                                 if ($rndseed ne $lastrndseed{$partid}) {
        !          4554:                                     $newvariation = '&nbsp;('.&mt('New variation this try').')';
        !          4555:                                 }
        !          4556:                             }
        !          4557:                             $lastrndseed{$partid} = $rndseed;
1.596     raeburn  4558: 		        }
                   4559: 		        my $responseType=($isTask ? 'Task'
1.335     albertel 4560:                                               : $responseType->{$partid}->{$responseId});
1.596     raeburn  4561: 		        if (!exists($orders{$partid})) { $orders{$partid}={}; }
1.640   ! raeburn  4562: 		        if ((!exists($orders{$partid}->{$responseId})) || ($trial)) {
1.596     raeburn  4563: 			    $orders{$partid}->{$responseId}=
                   4564: 			        &get_order($partid,$responseId,$symb,$uname,$udom,
1.640   ! raeburn  4565:                                            $no_increment,$type,$trial,$rndseed);
1.596     raeburn  4566: 		        }
1.640   ! raeburn  4567: 		        $displaySub[0].='</b>'.$newvariation.'</span>'; # /nobreak
1.596     raeburn  4568: 		        $displaySub[0].='&nbsp; '.
1.640   ! raeburn  4569: 			    &cleanRecord($$record{$version.':'.$matchKey},$responseType,$symb,$partid,$responseId,$record,$orders{$partid}->{$responseId},"$version:",$uname,$udom,$type,$trial,$rndseed).'<br />';
1.596     raeburn  4570:                     }
1.147     albertel 4571: 		}
                   4572: 	    }
1.335     albertel 4573: 	    if (exists($$record{"$where.$partid.checkedin"})) {
1.485     albertel 4574: 		$displaySub[1].=&mt('Checked in by [_1] into slot [_2]',
                   4575: 				    $$record{"$where.$partid.checkedin"},
                   4576: 				    $$record{"$where.$partid.checkedin.slot"}).
                   4577: 					'<br />';
1.335     albertel 4578: 	    }
                   4579: 	    if (exists $$record{"$where.$partid.award"}) {
1.485     albertel 4580: 		$displaySub[1].='<b>'.&mt('Part:').'</b>&nbsp;'.$display_part.' &nbsp;'.
1.335     albertel 4581: 		    lc($$record{"$where.$partid.award"}).' '.
                   4582: 		    $mark{$$record{"$where.$partid.solved"}}.
1.147     albertel 4583: 		    '<br />';
                   4584: 	    }
1.335     albertel 4585: 	    if (exists $$record{"$where.$partid.regrader"}) {
                   4586: 		$displaySub[2].=$$record{"$where.$partid.regrader"}.
                   4587: 		    ' (<b>'.&mt('Part').':</b> '.$display_part.')';
                   4588: 	    } elsif ($$record{"$version:resource.$partid.regrader"} =~ /\S/) {
                   4589: 		$displaySub[2].=
                   4590: 		    $$record{"$version:resource.$partid.regrader"}.
1.207     albertel 4591: 		    ' (<b>'.&mt('Part').':</b> '.$display_part.')';
1.147     albertel 4592: 	    }
                   4593: 	}
                   4594: 	# needed because old essay regrader has not parts info
                   4595: 	if (exists $$record{"$version:resource.regrader"}) {
                   4596: 	    $displaySub[2].=$$record{"$version:resource.regrader"};
                   4597: 	}
                   4598: 	$studentTable.='<td>'.$displaySub[0].'&nbsp;</td><td>'.$displaySub[1];
                   4599: 	if ($displaySub[2]) {
1.467     albertel 4600: 	    $studentTable.=&mt('Manually graded by [_1]',$displaySub[2]);
1.147     albertel 4601: 	}
1.467     albertel 4602: 	$studentTable.='&nbsp;</td>'.
                   4603: 	    &Apache::loncommon::end_data_table_row();
1.119     ng       4604:     }
1.467     albertel 4605:     $studentTable.=&Apache::loncommon::end_data_table();
1.119     ng       4606:     return $studentTable;
1.71      ng       4607: }
                   4608: 
                   4609: sub updateGradeByPage {
1.608     www      4610:     my ($request,$symb) = @_;
1.71      ng       4611: 
1.257     albertel 4612:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
                   4613:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
                   4614:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
                   4615:     my $pageTitle = $env{'form.page'};
1.103     albertel 4616:     my ($classlist,undef,$fullname) = &getclasslist($getsec,'1');
1.257     albertel 4617:     my ($uname,$udom) = split(/:/,$env{'form.student'});
                   4618:     my $usec=$classlist->{$env{'form.student'}}[5];
1.103     albertel 4619:     if (!&canmodify($usec)) {
1.526     raeburn  4620: 	$request->print('<span class="LC_warning">'.&mt('Unable to modify requested student ([_1])',$env{'form.student'}).'</span>');
1.103     albertel 4621: 	return;
                   4622:     }
1.398     albertel 4623:     my $result='<h3><span class="LC_info">&nbsp;'.$env{'form.title'}.'</span></h3>';
1.526     raeburn  4624:     $result.='<h3>&nbsp;'.&mt('Student: ').&nameUserString(undef,$env{'form.fullname'},$uname,$udom).
1.129     ng       4625: 	'</h3>'."\n";
1.70      ng       4626: 
1.68      ng       4627:     $request->print($result);
                   4628: 
1.582     raeburn  4629: 
1.132     bowersj2 4630:     my $navmap = Apache::lonnavmaps::navmap->new();
1.582     raeburn  4631:     unless (ref($navmap)) {
                   4632:         $request->print(&navmap_errormsg());
                   4633:         return;
                   4634:     }
1.257     albertel 4635:     my ($mapUrl, $id, $resUrl) = &Apache::lonnet::decode_symb( $env{'form.page'});
1.71      ng       4636:     my $map = $navmap->getResourceByUrl($resUrl); # add to navmaps
1.288     albertel 4637:     if (!$map) {
1.527     raeburn  4638: 	$request->print('<span class="LC_warning">'.&mt('Unable to grade requested sequence ([_1]).',$resUrl).'</span>');
1.288     albertel 4639: 	return; 
                   4640:     }
1.71      ng       4641:     my $iterator = $navmap->getIterator($map->map_start(),
                   4642: 					$map->map_finish());
1.70      ng       4643: 
1.484     albertel 4644:     my $studentTable=
                   4645: 	&Apache::loncommon::start_data_table().
                   4646: 	&Apache::loncommon::start_data_table_header_row().
1.485     albertel 4647: 	'<th align="center">&nbsp;'.&mt('Prob.').'&nbsp;</th>'.
                   4648: 	'<th>&nbsp;'.&mt('Title').'&nbsp;</th>'.
                   4649: 	'<th>&nbsp;'.&mt('Previous Score').'&nbsp;</th>'.
                   4650: 	'<th>&nbsp;'.&mt('New Score').'&nbsp;</th>'.
1.484     albertel 4651: 	&Apache::loncommon::end_data_table_header_row();
1.71      ng       4652: 
                   4653:     $iterator->next(); # skip the first BEGIN_MAP
                   4654:     my $curRes = $iterator->next(); # for "current resource"
1.196     albertel 4655:     my ($depth,$question,$prob,$changeflag)= (1,1,1,0);
1.101     albertel 4656:     while ($depth > 0) {
1.71      ng       4657:         if($curRes == $iterator->BEGIN_MAP) { $depth++; }
1.100     bowersj2 4658:         if($curRes == $iterator->END_MAP) { $depth--; }
1.71      ng       4659: 
1.385     albertel 4660:         if (ref($curRes) && $curRes->is_problem()) {
1.91      albertel 4661: 	    my $parts = $curRes->parts();
1.71      ng       4662:             my $title = $curRes->compTitle();
                   4663: 	    my $symbx = $curRes->symb();
1.484     albertel 4664: 	    $studentTable.=
                   4665: 		&Apache::loncommon::start_data_table_row().
                   4666: 		'<td align="center" valign="top" >'.$prob.
1.485     albertel 4667: 		(scalar(@{$parts}) == 1 ? '' 
1.640   ! raeburn  4668:                                         : '<br />('.&mt('[quant,_1,part]',scalar(@{$parts}))
1.526     raeburn  4669: 		.')').'</td>';
1.71      ng       4670: 	    $studentTable.='<td valign="top">&nbsp;<b>'.$title.'</b>&nbsp;</td>';
                   4671: 
                   4672: 	    my %newrecord=();
                   4673: 	    my @displayPts=();
1.269     raeburn  4674:             my %aggregate = ();
                   4675:             my $aggregateflag = 0;
1.71      ng       4676: 	    foreach my $partid (@{$parts}) {
1.257     albertel 4677: 		my $newpts = $env{'form.GD_BOX'.$question.'_'.$partid};
                   4678: 		my $oldpts = $env{'form.oldpts'.$question.'_'.$partid};
1.71      ng       4679: 
1.257     albertel 4680: 		my $wgt = $env{'form.WGT'.$question.'_'.$partid} != 0 ? 
                   4681: 		    $env{'form.WGT'.$question.'_'.$partid} : 1;
1.71      ng       4682: 		my $partial = $newpts/$wgt;
                   4683: 		my $score;
                   4684: 		if ($partial > 0) {
                   4685: 		    $score = 'correct_by_override';
1.125     ng       4686: 		} elsif ($newpts ne '') { #empty is taken as 0
1.71      ng       4687: 		    $score = 'incorrect_by_override';
                   4688: 		}
1.257     albertel 4689: 		my $dropMenu = $env{'form.GD_SEL'.$question.'_'.$partid};
1.125     ng       4690: 		if ($dropMenu eq 'excused') {
1.71      ng       4691: 		    $partial = '';
                   4692: 		    $score = 'excused';
1.125     ng       4693: 		} elsif ($dropMenu eq 'reset status'
1.257     albertel 4694: 			 && $env{'form.solved'.$question.'_'.$partid} ne '') { #update only if previous record exists
1.125     ng       4695: 		    $newrecord{'resource.'.$partid.'.tries'} = 0;
                   4696: 		    $newrecord{'resource.'.$partid.'.solved'} = '';
                   4697: 		    $newrecord{'resource.'.$partid.'.award'} = '';
                   4698: 		    $newrecord{'resource.'.$partid.'.awarded'} = 0;
1.257     albertel 4699: 		    $newrecord{'resource.'.$partid.'.regrader'} = "$env{'user.name'}:$env{'user.domain'}";
1.125     ng       4700: 		    $changeflag++;
                   4701: 		    $newpts = '';
1.269     raeburn  4702:                     
                   4703:                     my $aggtries =  $env{'form.aggtries'.$question.'_'.$partid};
                   4704:                     my $totaltries = $env{'form.totaltries'.$question.'_'.$partid};
                   4705:                     my $solvedstatus = $env{'form.solved'.$question.'_'.$partid};
                   4706:                     if ($aggtries > 0) {
                   4707:                         &decrement_aggs($symbx,$partid,\%aggregate,$aggtries,$totaltries,$solvedstatus);
                   4708:                         $aggregateflag = 1;
                   4709:                     }
1.71      ng       4710: 		}
1.324     albertel 4711: 		my $display_part=&get_display_part($partid,$curRes->symb());
1.257     albertel 4712: 		my $oldstatus = $env{'form.solved'.$question.'_'.$partid};
1.526     raeburn  4713: 		$displayPts[0].='&nbsp;<b>'.&mt('Part').':</b> '.$display_part.' = '.
1.71      ng       4714: 		    (($oldstatus eq 'excused') ? 'excused' : $oldpts).
1.326     albertel 4715: 		    '&nbsp;<br />';
1.526     raeburn  4716: 		$displayPts[1].='&nbsp;<b>'.&mt('Part').':</b> '.$display_part.' = '.
1.125     ng       4717: 		     (($score eq 'excused') ? 'excused' : $newpts).
1.326     albertel 4718: 		    '&nbsp;<br />';
1.71      ng       4719: 		$question++;
1.380     albertel 4720: 		next if ($dropMenu eq 'reset status' || ($newpts eq $oldpts && $score ne 'excused'));
1.125     ng       4721: 
1.71      ng       4722: 		$newrecord{'resource.'.$partid.'.awarded'}  = $partial if $partial ne '';
1.125     ng       4723: 		$newrecord{'resource.'.$partid.'.solved'}   = $score if $score ne '';
1.257     albertel 4724: 		$newrecord{'resource.'.$partid.'.regrader'} = "$env{'user.name'}:$env{'user.domain'}"
1.125     ng       4725: 		    if (scalar(keys(%newrecord)) > 0);
1.71      ng       4726: 
                   4727: 		$changeflag++;
                   4728: 	    }
                   4729: 	    if (scalar(keys(%newrecord)) > 0) {
1.382     albertel 4730: 		my %record = 
                   4731: 		    &Apache::lonnet::restore($symbx,$env{'request.course.id'},
                   4732: 					     $udom,$uname);
                   4733: 
                   4734: 		if (&Apache::lonnet::validCODE($env{'form.CODE'})) {
                   4735: 		    $newrecord{'resource.CODE'} = $env{'form.CODE'};
                   4736: 		} elsif (&Apache::lonnet::validCODE($record{'resource.CODE'})) {
                   4737: 		    $newrecord{'resource.CODE'} = '';
                   4738: 		}
1.257     albertel 4739: 		&Apache::lonnet::cstore(\%newrecord,$symbx,$env{'request.course.id'},
1.71      ng       4740: 					$udom,$uname);
1.382     albertel 4741: 		%record = &Apache::lonnet::restore($symbx,
                   4742: 						   $env{'request.course.id'},
                   4743: 						   $udom,$uname);
1.380     albertel 4744: 		&check_and_remove_from_queue($parts,\%record,undef,$symbx,
                   4745: 					     $cdom,$cnum,$udom,$uname);
1.71      ng       4746: 	    }
1.380     albertel 4747: 	    
1.269     raeburn  4748:             if ($aggregateflag) {
                   4749:                 &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
                   4750:                       $env{'course.'.$env{'request.course.id'}.'.domain'},
                   4751:                       $env{'course.'.$env{'request.course.id'}.'.num'});
                   4752:             }
1.125     ng       4753: 
1.71      ng       4754: 	    $studentTable.='<td valign="top">'.$displayPts[0].'</td>'.
                   4755: 		'<td valign="top">'.$displayPts[1].'</td>'.
1.484     albertel 4756: 		&Apache::loncommon::end_data_table_row();
1.68      ng       4757: 
1.196     albertel 4758: 	    $prob++;
1.68      ng       4759: 	}
1.71      ng       4760:         $curRes = $iterator->next();
1.68      ng       4761:     }
1.98      albertel 4762: 
1.484     albertel 4763:     $studentTable.=&Apache::loncommon::end_data_table();
1.526     raeburn  4764:     my $grademsg=($changeflag == 0 ? &mt('No score was changed or updated.') :
                   4765: 		  &mt('The scores were changed for [quant,_1,problem].',
                   4766: 		  $changeflag));
1.76      ng       4767:     $request->print($grademsg.$studentTable);
1.68      ng       4768: 
1.70      ng       4769:     return '';
                   4770: }
                   4771: 
1.72      ng       4772: #-------- end of section for handling grading by page/sequence ---------
                   4773: #
                   4774: #-------------------------------------------------------------------
                   4775: 
1.581     www      4776: #-------------------- Bubblesheet (Scantron) Grading -------------------
1.75      albertel 4777: #
                   4778: #------ start of section for handling grading by page/sequence ---------
                   4779: 
1.423     albertel 4780: =pod
                   4781: 
                   4782: =head1 Bubble sheet grading routines
                   4783: 
1.424     albertel 4784:   For this documentation:
                   4785: 
                   4786:    'scanline' refers to the full line of characters
                   4787:    from the file that we are parsing that represents one entire sheet
                   4788: 
                   4789:    'bubble line' refers to the data
                   4790:    representing the line of bubbles that are on the physical bubble sheet
                   4791: 
                   4792: 
                   4793: The overall process is that a scanned in bubble sheet data is uploaded
                   4794: into a course. When a user wants to grade, they select a
                   4795: sequence/folder of resources, a file of bubble sheet info, and pick
                   4796: one of the predefined configurations for what each scanline looks
                   4797: like.
                   4798: 
                   4799: Next each scanline is checked for any errors of either 'missing
1.435     foxr     4800: bubbles' (it's an error because it may have been mis-scanned
1.424     albertel 4801: because too light bubbling), 'double bubble' (each bubble line should
                   4802: have no more that one letter picked), invalid or duplicated CODE,
1.556     weissno  4803: invalid student/employee ID
1.424     albertel 4804: 
                   4805: If the CODE option is used that determines the randomization of the
1.556     weissno  4806: homework problems, either way the student/employee ID is looked up into a
1.424     albertel 4807: username:domain.
                   4808: 
                   4809: During the validation phase the instructor can choose to skip scanlines. 
                   4810: 
1.435     foxr     4811: After the validation phase, there are now 3 bubble sheet files
1.424     albertel 4812: 
                   4813:   scantron_original_filename (unmodified original file)
                   4814:   scantron_corrected_filename (file where the corrected information has replaced the original information)
                   4815:   scantron_skipped_filename (contains the exact text of scanlines that where skipped)
                   4816: 
                   4817: Also there is a separate hash nohist_scantrondata that contains extra
                   4818: correction information that isn't representable in the bubble sheet
                   4819: file (see &scantron_getfile() for more information)
                   4820: 
                   4821: After all scanlines are either valid, marked as valid or skipped, then
                   4822: foreach line foreach problem in the picked sequence, an ssi request is
                   4823: made that simulates a user submitting their selected letter(s) against
                   4824: the homework problem.
1.423     albertel 4825: 
                   4826: =over 4
                   4827: 
                   4828: 
                   4829: 
                   4830: =item defaultFormData
                   4831: 
                   4832:   Returns html hidden inputs used to hold context/default values.
                   4833: 
                   4834:  Arguments:
                   4835:   $symb - $symb of the current resource 
                   4836: 
                   4837: =cut
1.422     foxr     4838: 
1.81      albertel 4839: sub defaultFormData {
1.324     albertel 4840:     my ($symb)=@_;
1.613     www      4841:     return '<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />';
1.81      albertel 4842: }
                   4843: 
1.447     foxr     4844: 
1.423     albertel 4845: =pod 
                   4846: 
                   4847: =item getSequenceDropDown
                   4848: 
                   4849:    Return html dropdown of possible sequences to grade
                   4850:  
                   4851:  Arguments:
1.582     raeburn  4852:    $symb - $symb of the current resource
                   4853:    $map_error - ref to scalar which will container error if
                   4854:                 $navmap object is unavailable in &getSymbMap().
1.423     albertel 4855: 
                   4856: =cut
1.422     foxr     4857: 
1.75      albertel 4858: sub getSequenceDropDown {
1.582     raeburn  4859:     my ($symb,$map_error)=@_;
1.75      albertel 4860:     my $result='<select name="selectpage">'."\n";
1.582     raeburn  4861:     my ($titles,$symbx) = &getSymbMap($map_error);
                   4862:     if (ref($map_error)) {
                   4863:         return if ($$map_error);
                   4864:     }
1.137     albertel 4865:     my ($curpage)=&Apache::lonnet::decode_symb($symb); 
1.75      albertel 4866:     my $ctr=0;
                   4867:     foreach (@$titles) {
                   4868: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
                   4869: 	$result.='<option value="'.$$symbx{$_}.'" '.
1.401     albertel 4870: 	    ($$symbx{$_} =~ /$curpage$/ ? 'selected="selected"' : '').
1.75      albertel 4871: 	    '>'.$showtitle.'</option>'."\n";
                   4872: 	$ctr++;
                   4873:     }
                   4874:     $result.= '</select>';
                   4875:     return $result;
                   4876: }
                   4877: 
1.495     albertel 4878: my %bubble_lines_per_response;     # no. bubble lines for each response.
1.554     raeburn  4879:                                    # key is zero-based index - 0, 1, 2 ...
1.495     albertel 4880: 
                   4881: my %first_bubble_line;             # First bubble line no. for each bubble.
                   4882: 
1.509     raeburn  4883: my %subdivided_bubble_lines;       # no. bubble lines for optionresponse, 
                   4884:                                    # matchresponse or rankresponse, where 
                   4885:                                    # an individual response can have multiple 
                   4886:                                    # lines
1.503     raeburn  4887: 
                   4888: my %responsetype_per_response;     # responsetype for each response
                   4889: 
1.495     albertel 4890: # Save and restore the bubble lines array to the form env.
                   4891: 
                   4892: 
                   4893: sub save_bubble_lines {
                   4894:     foreach my $line (keys(%bubble_lines_per_response)) {
                   4895: 	$env{"form.scantron.bubblelines.$line"}  = $bubble_lines_per_response{$line};
                   4896: 	$env{"form.scantron.first_bubble_line.$line"} =
                   4897: 	    $first_bubble_line{$line};
1.503     raeburn  4898:         $env{"form.scantron.sub_bubblelines.$line"} = 
                   4899:             $subdivided_bubble_lines{$line};
                   4900:         $env{"form.scantron.responsetype.$line"} =
                   4901:             $responsetype_per_response{$line};
1.495     albertel 4902:     }
                   4903: }
                   4904: 
                   4905: 
                   4906: sub restore_bubble_lines {
                   4907:     my $line = 0;
                   4908:     %bubble_lines_per_response = ();
                   4909:     while ($env{"form.scantron.bubblelines.$line"}) {
                   4910: 	my $value = $env{"form.scantron.bubblelines.$line"};
                   4911: 	$bubble_lines_per_response{$line} = $value;
                   4912: 	$first_bubble_line{$line}  =
                   4913: 	    $env{"form.scantron.first_bubble_line.$line"};
1.503     raeburn  4914:         $subdivided_bubble_lines{$line} =
                   4915:             $env{"form.scantron.sub_bubblelines.$line"};
                   4916:         $responsetype_per_response{$line} =
                   4917:             $env{"form.scantron.responsetype.$line"};
1.495     albertel 4918: 	$line++;
                   4919:     }
                   4920: }
                   4921: 
                   4922: #  Given the parsed scanline, get the response for 
                   4923: #  'answer' number n:
                   4924: 
                   4925: sub get_response_bubbles {
                   4926:     my ($parsed_line, $response)  = @_;
                   4927: 
                   4928:     my $bubble_line = $first_bubble_line{$response-1} +1;
                   4929:     my $bubble_lines= $bubble_lines_per_response{$response-1};
                   4930:     
                   4931:     my $selected = "";
                   4932: 
                   4933:     for (my $bline = 0; $bline < $bubble_lines; $bline++) {
                   4934: 	$selected .= $$parsed_line{"scantron.$bubble_line.answer"}.":";
                   4935: 	$bubble_line++;
                   4936:     }
                   4937:     return $selected;
                   4938: }
1.423     albertel 4939: 
                   4940: =pod 
                   4941: 
                   4942: =item scantron_filenames
                   4943: 
                   4944:    Returns a list of the scantron files in the current course 
                   4945: 
                   4946: =cut
1.422     foxr     4947: 
1.202     albertel 4948: sub scantron_filenames {
1.257     albertel 4949:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   4950:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
1.517     raeburn  4951:     my $getpropath = 1;
1.157     albertel 4952:     my @files=&Apache::lonnet::dirlist('userfiles',$cdom,$cname,
1.517     raeburn  4953:                                        $getpropath);
1.202     albertel 4954:     my @possiblenames;
1.201     albertel 4955:     foreach my $filename (sort(@files)) {
1.157     albertel 4956: 	($filename)=split(/&/,$filename);
                   4957: 	if ($filename!~/^scantron_orig_/) { next ; }
                   4958: 	$filename=~s/^scantron_orig_//;
1.202     albertel 4959: 	push(@possiblenames,$filename);
                   4960:     }
                   4961:     return @possiblenames;
                   4962: }
                   4963: 
1.423     albertel 4964: =pod 
                   4965: 
                   4966: =item scantron_uploads
                   4967: 
                   4968:    Returns  html drop-down list of scantron files in current course.
                   4969: 
                   4970:  Arguments:
                   4971:    $file2grade - filename to set as selected in the dropdown
                   4972: 
                   4973: =cut
1.422     foxr     4974: 
1.202     albertel 4975: sub scantron_uploads {
1.209     ng       4976:     my ($file2grade) = @_;
1.202     albertel 4977:     my $result=	'<select name="scantron_selectfile">';
                   4978:     $result.="<option></option>";
                   4979:     foreach my $filename (sort(&scantron_filenames())) {
1.401     albertel 4980: 	$result.="<option".($filename eq $file2grade ? ' selected="selected"':'').">$filename</option>\n";
1.81      albertel 4981:     }
                   4982:     $result.="</select>";
                   4983:     return $result;
                   4984: }
                   4985: 
1.423     albertel 4986: =pod 
                   4987: 
                   4988: =item scantron_scantab
                   4989: 
                   4990:   Returns html drop down of the scantron formats in the scantronformat.tab
                   4991:   file.
                   4992: 
                   4993: =cut
1.422     foxr     4994: 
1.82      albertel 4995: sub scantron_scantab {
                   4996:     my $result='<select name="scantron_format">'."\n";
1.191     albertel 4997:     $result.='<option></option>'."\n";
1.518     raeburn  4998:     my @lines = &get_scantronformat_file();
                   4999:     if (@lines > 0) {
                   5000:         foreach my $line (@lines) {
                   5001:             next if (($line =~ /^\#/) || ($line eq ''));
                   5002: 	    my ($name,$descrip)=split(/:/,$line);
                   5003: 	    $result.='<option value="'.$name.'">'.$descrip.'</option>'."\n";
                   5004:         }
1.82      albertel 5005:     }
                   5006:     $result.='</select>'."\n";
1.518     raeburn  5007:     return $result;
                   5008: }
                   5009: 
                   5010: =pod
                   5011: 
                   5012: =item get_scantronformat_file
                   5013: 
                   5014:   Returns an array containing lines from the scantron format file for
                   5015:   the domain of the course.
                   5016: 
                   5017:   If a url for a custom.tab file is listed in domain's configuration.db, 
                   5018:   lines are from this file.
                   5019: 
                   5020:   Otherwise, if a default.tab has been published in RES space by the 
                   5021:   domainconfig user, lines are from this file.
                   5022: 
                   5023:   Otherwise, fall back to getting lines from the legacy file on the
1.519     raeburn  5024:   local server:  /home/httpd/lonTabs/default_scantronformat.tab    
1.82      albertel 5025: 
1.518     raeburn  5026: =cut
                   5027: 
                   5028: sub get_scantronformat_file {
                   5029:     my $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
                   5030:     my %domconfig = &Apache::lonnet::get_dom('configuration',['scantron'],$cdom);
                   5031:     my $gottab = 0;
                   5032:     my @lines;
                   5033:     if (ref($domconfig{'scantron'}) eq 'HASH') {
                   5034:         if ($domconfig{'scantron'}{'scantronformat'} ne '') {
                   5035:             my $formatfile = &Apache::lonnet::getfile($Apache::lonnet::perlvar{'lonDocRoot'}.$domconfig{'scantron'}{'scantronformat'});
                   5036:             if ($formatfile ne '-1') {
                   5037:                 @lines = split("\n",$formatfile,-1);
                   5038:                 $gottab = 1;
                   5039:             }
                   5040:         }
                   5041:     }
                   5042:     if (!$gottab) {
                   5043:         my $confname = $cdom.'-domainconfig';
                   5044:         my $default = $Apache::lonnet::perlvar{'lonDocRoot'}.'/res/'.$cdom.'/'.$confname.'/default.tab';
                   5045:         my $formatfile =  &Apache::lonnet::getfile($default);
                   5046:         if ($formatfile ne '-1') {
                   5047:             @lines = split("\n",$formatfile,-1);
                   5048:             $gottab = 1;
                   5049:         }
                   5050:     }
                   5051:     if (!$gottab) {
1.519     raeburn  5052:         my @domains = &Apache::lonnet::current_machine_domains();
                   5053:         if (grep(/^\Q$cdom\E$/,@domains)) {
                   5054:             my $fh=Apache::File->new($Apache::lonnet::perlvar{'lonTabDir'}.'/scantronformat.tab');
                   5055:             @lines = <$fh>;
                   5056:             close($fh);
                   5057:         } else {
                   5058:             my $fh=Apache::File->new($Apache::lonnet::perlvar{'lonTabDir'}.'/default_scantronformat.tab');
                   5059:             @lines = <$fh>;
                   5060:             close($fh);
                   5061:         }
1.518     raeburn  5062:     }
                   5063:     return @lines;
1.82      albertel 5064: }
                   5065: 
1.423     albertel 5066: =pod 
                   5067: 
                   5068: =item scantron_CODElist
                   5069: 
                   5070:   Returns html drop down of the saved CODE lists from current course,
                   5071:   generated from earlier printings.
                   5072: 
                   5073: =cut
1.422     foxr     5074: 
1.186     albertel 5075: sub scantron_CODElist {
1.257     albertel 5076:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   5077:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
1.186     albertel 5078:     my @names=&Apache::lonnet::getkeys('CODEs',$cdom,$cnum);
                   5079:     my $namechoice='<option></option>';
1.225     albertel 5080:     foreach my $name (sort {uc($a) cmp uc($b)} @names) {
1.191     albertel 5081: 	if ($name =~ /^error: 2 /) { next; }
1.278     albertel 5082: 	if ($name =~ /^type\0/) { next; }
1.186     albertel 5083: 	$namechoice.='<option value="'.$name.'">'.$name.'</option>';
                   5084:     }
                   5085:     $namechoice='<select name="scantron_CODElist">'.$namechoice.'</select>';
                   5086:     return $namechoice;
                   5087: }
                   5088: 
1.423     albertel 5089: =pod 
                   5090: 
                   5091: =item scantron_CODEunique
                   5092: 
                   5093:   Returns the html for "Each CODE to be used once" radio.
                   5094: 
                   5095: =cut
1.422     foxr     5096: 
1.186     albertel 5097: sub scantron_CODEunique {
1.532     bisitz   5098:     my $result='<span class="LC_nobreak">
1.272     albertel 5099:                  <label><input type="radio" name="scantron_CODEunique"
1.423     albertel 5100:                         value="yes" checked="checked" />'.&mt('Yes').' </label>
1.381     albertel 5101:                 </span>
1.532     bisitz   5102:                 <span class="LC_nobreak">
1.272     albertel 5103:                  <label><input type="radio" name="scantron_CODEunique"
1.423     albertel 5104:                         value="no" />'.&mt('No').' </label>
1.381     albertel 5105:                 </span>';
1.186     albertel 5106:     return $result;
                   5107: }
1.423     albertel 5108: 
                   5109: =pod 
                   5110: 
                   5111: =item scantron_selectphase
                   5112: 
                   5113:   Generates the initial screen to start the bubble sheet process.
                   5114:   Allows for - starting a grading run.
1.424     albertel 5115:              - downloading existing scan data (original, corrected
1.423     albertel 5116:                                                 or skipped info)
                   5117: 
                   5118:              - uploading new scan data
                   5119: 
                   5120:  Arguments:
                   5121:   $r          - The Apache request object
                   5122:   $file2grade - name of the file that contain the scanned data to score
                   5123: 
                   5124: =cut
1.186     albertel 5125: 
1.75      albertel 5126: sub scantron_selectphase {
1.608     www      5127:     my ($r,$file2grade,$symb) = @_;
1.75      albertel 5128:     if (!$symb) {return '';}
1.582     raeburn  5129:     my $map_error;
                   5130:     my $sequence_selector=&getSequenceDropDown($symb,\$map_error);
                   5131:     if ($map_error) {
                   5132:         $r->print('<br />'.&navmap_errormsg().'<br />');
                   5133:         return;
                   5134:     }
1.324     albertel 5135:     my $default_form_data=&defaultFormData($symb);
1.209     ng       5136:     my $file_selector=&scantron_uploads($file2grade);
1.82      albertel 5137:     my $format_selector=&scantron_scantab();
1.186     albertel 5138:     my $CODE_selector=&scantron_CODElist();
                   5139:     my $CODE_unique=&scantron_CODEunique();
1.75      albertel 5140:     my $result;
1.422     foxr     5141: 
1.513     foxr     5142:     $ssi_error = 0;
                   5143: 
1.606     wenzelju 5144:     if (&Apache::lonnet::allowed('usc',$env{'request.role.domain'}) ||
                   5145:         &Apache::lonnet::allowed('usc',$env{'request.course.id'})) {
                   5146: 
                   5147: 	# Chunk of form to prompt for a scantron file upload.
                   5148: 
                   5149:         $r->print('
                   5150:     <br />
                   5151:     '.&Apache::loncommon::start_data_table('LC_scantron_action').'
                   5152:        '.&Apache::loncommon::start_data_table_header_row().'
                   5153:             <th>
                   5154:               &nbsp;'.&mt('Specify a bubblesheet data file to upload.').'
                   5155:             </th>
                   5156:        '.&Apache::loncommon::end_data_table_header_row().'
                   5157:        '.&Apache::loncommon::start_data_table_row().'
                   5158:             <td>
                   5159: ');
1.608     www      5160:     my $default_form_data=&defaultFormData($symb);
1.606     wenzelju 5161:     my $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
                   5162:     my $cnum= $env{'course.'.$env{'request.course.id'}.'.num'};
                   5163:     $r->print(&Apache::lonhtmlcommon::scripttag('
                   5164:     function checkUpload(formname) {
                   5165: 	if (formname.upfile.value == "") {
                   5166: 	    alert("'.&mt('Please use the browse button to select a file from your local directory.').'");
                   5167: 	    return false;
                   5168: 	}
                   5169: 	formname.submit();
                   5170:     }'));
                   5171:     $r->print('
                   5172:               <form enctype="multipart/form-data" action="/adm/grades" name="rules" method="post">
                   5173:                 '.$default_form_data.'
                   5174:                 <input name="courseid" type="hidden" value="'.$cnum.'" />
                   5175:                 <input name="domainid" type="hidden" value="'.$cdom.'" />
                   5176:                 <input name="command" value="scantronupload_save" type="hidden" />
                   5177:                 '.&mt('File to upload: [_1]','<input type="file" name="upfile" size="50" />').'
                   5178:                 <br />
                   5179:                 <input type="button" onclick="javascript:checkUpload(this.form);" value="'.&mt('Upload Bubblesheet Data').'" />
                   5180:               </form>
                   5181: ');
                   5182: 
                   5183:         $r->print('
                   5184:             </td>
                   5185:        '.&Apache::loncommon::end_data_table_row().'
                   5186:        '.&Apache::loncommon::end_data_table().'
                   5187: ');
                   5188:     }
                   5189: 
1.422     foxr     5190:     # Chunk of form to prompt for a file to grade and how:
                   5191: 
1.489     albertel 5192:     $result.= '
                   5193:     <br />
                   5194:     <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantron_process">
                   5195:     <input type="hidden" name="command" value="scantron_warning" />
                   5196:     '.$default_form_data.'
                   5197:     '.&Apache::loncommon::start_data_table('LC_scantron_action').'
                   5198:        '.&Apache::loncommon::start_data_table_header_row().'
                   5199:             <th colspan="2">
1.492     albertel 5200:               &nbsp;'.&mt('Specify file and which Folder/Sequence to grade').'
1.489     albertel 5201:             </th>
                   5202:        '.&Apache::loncommon::end_data_table_header_row().'
                   5203:        '.&Apache::loncommon::start_data_table_row().'
1.492     albertel 5204:             <td> '.&mt('Sequence to grade:').' </td><td> '.$sequence_selector.' </td>
1.489     albertel 5205:        '.&Apache::loncommon::end_data_table_row().'
                   5206:        '.&Apache::loncommon::start_data_table_row().'
1.572     www      5207:             <td> '.&mt('Filename of bubblesheet data file:').' </td><td> '.$file_selector.' </td>
1.489     albertel 5208:        '.&Apache::loncommon::end_data_table_row().'
                   5209:        '.&Apache::loncommon::start_data_table_row().'
1.572     www      5210:             <td> '.&mt('Format of bubblesheet data file:').' </td><td> '.$format_selector.' </td>
1.489     albertel 5211:        '.&Apache::loncommon::end_data_table_row().'
                   5212:        '.&Apache::loncommon::start_data_table_row().'
1.492     albertel 5213:             <td> '.&mt('Saved CODEs to validate against:').' </td><td> '.$CODE_selector.' </td>
1.489     albertel 5214:        '.&Apache::loncommon::end_data_table_row().'
                   5215:        '.&Apache::loncommon::start_data_table_row().'
1.492     albertel 5216:             <td> '.&mt('Each CODE is only to be used once:').'</td><td> '.$CODE_unique.' </td>
1.489     albertel 5217:        '.&Apache::loncommon::end_data_table_row().'
                   5218:        '.&Apache::loncommon::start_data_table_row().'
1.492     albertel 5219: 	    <td> '.&mt('Options:').' </td>
1.187     albertel 5220:             <td>
1.492     albertel 5221: 	       <label><input type="checkbox" name="scantron_options_redo" value="redo_skipped"/> '.&mt('Do only previously skipped records').'</label> <br />
                   5222:                <label><input type="checkbox" name="scantron_options_ignore" value="ignore_corrections"/> '.&mt('Remove all existing corrections').'</label> <br />
                   5223:                <label><input type="checkbox" name="scantron_options_hidden" value="ignore_hidden"/> '.&mt('Skip hidden resources when grading').'</label>
1.187     albertel 5224: 	    </td>
1.489     albertel 5225:        '.&Apache::loncommon::end_data_table_row().'
                   5226:        '.&Apache::loncommon::start_data_table_row().'
1.174     albertel 5227:             <td colspan="2">
1.572     www      5228:               <input type="submit" value="'.&mt('Grading: Validate Bubblesheet Records').'" />
1.162     albertel 5229:             </td>
1.489     albertel 5230:        '.&Apache::loncommon::end_data_table_row().'
                   5231:     '.&Apache::loncommon::end_data_table().'
                   5232:     </form>
                   5233: ';
1.162     albertel 5234:    
                   5235:     $r->print($result);
                   5236: 
1.422     foxr     5237: 
                   5238: 
                   5239:     # Chunk of the form that prompts to view a scoring office file,
                   5240:     # corrected file, skipped records in a file.
                   5241: 
1.489     albertel 5242:     $r->print('
                   5243:    <br />
                   5244:    <form action="/adm/grades" name="scantron_download">
                   5245:      '.$default_form_data.'
                   5246:      <input type="hidden" name="command" value="scantron_download" />
                   5247:      '.&Apache::loncommon::start_data_table('LC_scantron_action').'
                   5248:        '.&Apache::loncommon::start_data_table_header_row().'
                   5249:               <th>
1.492     albertel 5250:                 &nbsp;'.&mt('Download a scoring office file').'
1.489     albertel 5251:               </th>
                   5252:        '.&Apache::loncommon::end_data_table_header_row().'
                   5253:        '.&Apache::loncommon::start_data_table_row().'
1.492     albertel 5254:               <td> '.&mt('Filename of scoring office file: [_1]',$file_selector).' 
1.489     albertel 5255:                 <br />
1.492     albertel 5256:                 <input type="submit" value="'.&mt('Download: Show List of Associated Files').'" />
1.489     albertel 5257:        '.&Apache::loncommon::end_data_table_row().'
                   5258:      '.&Apache::loncommon::end_data_table().'
                   5259:    </form>
                   5260:    <br />
                   5261: ');
1.162     albertel 5262: 
1.457     banghart 5263:     &Apache::lonpickcode::code_list($r,2);
1.523     raeburn  5264: 
1.528     raeburn  5265:     $r->print('<br /><form method="post" name="checkscantron">'.
1.523     raeburn  5266:              $default_form_data."\n".
                   5267:              &Apache::loncommon::start_data_table('LC_scantron_action')."\n".
                   5268:              &Apache::loncommon::start_data_table_header_row()."\n".
                   5269:              '<th colspan="2">
1.572     www      5270:               &nbsp;'.&mt('Review bubblesheet data and submissions for a previously graded folder/sequence')."\n".
1.523     raeburn  5271:              '</th>'."\n".
                   5272:               &Apache::loncommon::end_data_table_header_row()."\n".
                   5273:               &Apache::loncommon::start_data_table_row()."\n".
                   5274:               '<td> '.&mt('Graded folder/sequence:').' </td>'."\n".
                   5275:               '<td> '.$sequence_selector.' </td>'.
                   5276:               &Apache::loncommon::end_data_table_row()."\n".
                   5277:               &Apache::loncommon::start_data_table_row()."\n".
                   5278:               '<td> '.&mt('Filename of scoring office file:').' </td>'."\n".
                   5279:               '<td> '.$file_selector.' </td>'."\n".
                   5280:               &Apache::loncommon::end_data_table_row()."\n".
                   5281:               &Apache::loncommon::start_data_table_row()."\n".
                   5282:               '<td> '.&mt('Format of data file:').' </td>'."\n".
                   5283:               '<td> '.$format_selector.' </td>'."\n".
                   5284:               &Apache::loncommon::end_data_table_row()."\n".
                   5285:               &Apache::loncommon::start_data_table_row()."\n".
1.557     raeburn  5286:               '<td> '.&mt('Options').' </td>'."\n".
                   5287:               '<td> <label><input type="checkbox" name="scantron_options_hidden" value="ignore_hidden"/> '.&mt('Skip hidden resources').'</label></td>'.
                   5288:               &Apache::loncommon::end_data_table_row()."\n".
                   5289:               &Apache::loncommon::start_data_table_row()."\n".
1.523     raeburn  5290:               '<td colspan="2">'."\n".
                   5291:               '<input type="hidden" name="command" value="checksubmissions" />'."\n".
1.575     www      5292:               '<input type="submit" value="'.&mt('Review Bubblesheet Data and Submission Records').'" />'."\n".
1.523     raeburn  5293:               '</td>'."\n".
                   5294:               &Apache::loncommon::end_data_table_row()."\n".
                   5295:               &Apache::loncommon::end_data_table()."\n".
                   5296:               '</form><br />');
                   5297:     return;
1.75      albertel 5298: }
                   5299: 
1.423     albertel 5300: =pod
                   5301: 
                   5302: =item get_scantron_config
                   5303: 
                   5304:    Parse and return the scantron configuration line selected as a
                   5305:    hash of configuration file fields.
                   5306: 
                   5307:  Arguments:
                   5308:     which - the name of the configuration to parse from the file.
                   5309: 
                   5310: 
                   5311:  Returns:
                   5312:             If the named configuration is not in the file, an empty
                   5313:             hash is returned.
                   5314:     a hash with the fields
                   5315:       name         - internal name for the this configuration setup
                   5316:       description  - text to display to operator that describes this config
                   5317:       CODElocation - if 0 or the string 'none'
                   5318:                           - no CODE exists for this config
                   5319:                      if -1 || the string 'letter'
                   5320:                           - a CODE exists for this config and is
                   5321:                             a string of letters
                   5322:                      Unsupported value (but planned for future support)
                   5323:                           if a positive integer
                   5324:                                - The CODE exists as the first n items from
                   5325:                                  the question section of the form
                   5326:                           if the string 'number'
                   5327:                                - The CODE exists for this config and is
                   5328:                                  a string of numbers
                   5329:       CODEstart   - (only matter if a CODE exists) column in the line where
                   5330:                      the CODE starts
                   5331:       CODElength  - length of the CODE
1.573     bisitz   5332:       IDstart     - column where the student/employee ID starts
1.556     weissno  5333:       IDlength    - length of the student/employee ID info
1.423     albertel 5334:       Qstart      - column where the information from the bubbled
                   5335:                     'questions' start
                   5336:       Qlength     - number of columns comprising a single bubble line from
                   5337:                     the sheet. (usually either 1 or 10)
1.424     albertel 5338:       Qon         - either a single character representing the character used
1.423     albertel 5339:                     to signal a bubble was chosen in the positional setup, or
                   5340:                     the string 'letter' if the letter of the chosen bubble is
                   5341:                     in the final, or 'number' if a number representing the
                   5342:                     chosen bubble is in the file (1->A 0->J)
1.424     albertel 5343:       Qoff        - the character used to represent that a bubble was
                   5344:                     left blank
1.423     albertel 5345:       PaperID     - if the scanning process generates a unique number for each
                   5346:                     sheet scanned the column that this ID number starts in
                   5347:       PaperIDlength - number of columns that comprise the unique ID number
                   5348:                       for the sheet of paper
1.424     albertel 5349:       FirstName   - column that the first name starts in
1.423     albertel 5350:       FirstNameLength - number of columns that the first name spans
                   5351:  
                   5352:       LastName    - column that the last name starts in
                   5353:       LastNameLength - number of columns that the last name spans
                   5354: 
                   5355: =cut
1.422     foxr     5356: 
1.82      albertel 5357: sub get_scantron_config {
                   5358:     my ($which) = @_;
1.518     raeburn  5359:     my @lines = &get_scantronformat_file();
1.82      albertel 5360:     my %config;
1.157     albertel 5361:     #FIXME probably should move to XML it has already gotten a bit much now
1.518     raeburn  5362:     foreach my $line (@lines) {
1.82      albertel 5363: 	my ($name,$descrip)=split(/:/,$line);
                   5364: 	if ($name ne $which ) { next; }
                   5365: 	chomp($line);
                   5366: 	my @config=split(/:/,$line);
                   5367: 	$config{'name'}=$config[0];
                   5368: 	$config{'description'}=$config[1];
                   5369: 	$config{'CODElocation'}=$config[2];
                   5370: 	$config{'CODEstart'}=$config[3];
                   5371: 	$config{'CODElength'}=$config[4];
                   5372: 	$config{'IDstart'}=$config[5];
                   5373: 	$config{'IDlength'}=$config[6];
                   5374: 	$config{'Qstart'}=$config[7];
1.497     foxr     5375:  	$config{'Qlength'}=$config[8];
1.82      albertel 5376: 	$config{'Qoff'}=$config[9];
                   5377: 	$config{'Qon'}=$config[10];
1.157     albertel 5378: 	$config{'PaperID'}=$config[11];
                   5379: 	$config{'PaperIDlength'}=$config[12];
                   5380: 	$config{'FirstName'}=$config[13];
                   5381: 	$config{'FirstNamelength'}=$config[14];
                   5382: 	$config{'LastName'}=$config[15];
                   5383: 	$config{'LastNamelength'}=$config[16];
1.82      albertel 5384: 	last;
                   5385:     }
                   5386:     return %config;
                   5387: }
                   5388: 
1.423     albertel 5389: =pod 
                   5390: 
                   5391: =item username_to_idmap
                   5392: 
1.556     weissno  5393:     creates a hash keyed by student/employee ID with values of the corresponding
1.423     albertel 5394:     student username:domain.
                   5395: 
                   5396:   Arguments:
                   5397: 
                   5398:     $classlist - reference to the class list hash. This is a hash
                   5399:                  keyed by student name:domain  whose elements are references
1.424     albertel 5400:                  to arrays containing various chunks of information
1.423     albertel 5401:                  about the student. (See loncoursedata for more info).
                   5402: 
                   5403:   Returns
                   5404:     %idmap - the constructed hash
                   5405: 
                   5406: =cut
                   5407: 
1.82      albertel 5408: sub username_to_idmap {
                   5409:     my ($classlist)= @_;
                   5410:     my %idmap;
                   5411:     foreach my $student (keys(%$classlist)) {
                   5412: 	$idmap{$classlist->{$student}->[&Apache::loncoursedata::CL_ID]}=
                   5413: 	    $student;
                   5414:     }
                   5415:     return %idmap;
                   5416: }
1.423     albertel 5417: 
                   5418: =pod
                   5419: 
1.424     albertel 5420: =item scantron_fixup_scanline
1.423     albertel 5421: 
                   5422:    Process a requested correction to a scanline.
                   5423: 
                   5424:   Arguments:
                   5425:     $scantron_config   - hash from &get_scantron_config()
                   5426:     $scan_data         - hash of correction information 
                   5427:                           (see &scantron_getfile())
                   5428:     $line              - existing scanline
                   5429:     $whichline         - line number of the passed in scanline
                   5430:     $field             - type of change to process 
                   5431:                          (either 
1.573     bisitz   5432:                           'ID'     -> correct the student/employee ID
1.423     albertel 5433:                           'CODE'   -> correct the CODE
                   5434:                           'answer' -> fixup the submitted answers)
                   5435:     
                   5436:    $args               - hash of additional info,
                   5437:                           - 'ID' 
                   5438:                                'newid' -> studentID to use in replacement
1.424     albertel 5439:                                           of existing one
1.423     albertel 5440:                           - 'CODE' 
                   5441:                                'CODE_ignore_dup' - set to true if duplicates
                   5442:                                                    should be ignored.
                   5443: 	                       'CODE' - is new code or 'use_unfound'
1.424     albertel 5444:                                         if the existing unfound code should
1.423     albertel 5445:                                         be used as is
                   5446:                           - 'answer'
                   5447:                                'response' - new answer or 'none' if blank
                   5448:                                'question' - the bubble line to change
1.503     raeburn  5449:                                'questionnum' - the question identifier,
                   5450:                                                may include subquestion. 
1.423     albertel 5451: 
                   5452:   Returns:
                   5453:     $line - the modified scanline
                   5454: 
                   5455:   Side effects: 
                   5456:     $scan_data - may be updated
                   5457: 
                   5458: =cut
                   5459: 
1.82      albertel 5460: 
1.157     albertel 5461: sub scantron_fixup_scanline {
                   5462:     my ($scantron_config,$scan_data,$line,$whichline,$field,$args)=@_;
                   5463:     if ($field eq 'ID') {
                   5464: 	if (length($args->{'newid'}) > $$scantron_config{'IDlength'}) {
1.186     albertel 5465: 	    return ($line,1,'New value too large');
1.157     albertel 5466: 	}
                   5467: 	if (length($args->{'newid'}) < $$scantron_config{'IDlength'}) {
                   5468: 	    $args->{'newid'}=sprintf('%-'.$$scantron_config{'IDlength'}.'s',
                   5469: 				     $args->{'newid'});
                   5470: 	}
                   5471: 	substr($line,$$scantron_config{'IDstart'}-1,
                   5472: 	       $$scantron_config{'IDlength'})=$args->{'newid'};
                   5473: 	if ($args->{'newid'}=~/^\s*$/) {
                   5474: 	    &scan_data($scan_data,"$whichline.user",
                   5475: 		       $args->{'username'}.':'.$args->{'domain'});
                   5476: 	}
1.186     albertel 5477:     } elsif ($field eq 'CODE') {
1.192     albertel 5478: 	if ($args->{'CODE_ignore_dup'}) {
                   5479: 	    &scan_data($scan_data,"$whichline.CODE_ignore_dup",'1');
                   5480: 	}
                   5481: 	&scan_data($scan_data,"$whichline.useCODE",'1');
                   5482: 	if ($args->{'CODE'} ne 'use_unfound') {
1.191     albertel 5483: 	    if (length($args->{'CODE'}) > $$scantron_config{'CODElength'}) {
                   5484: 		return ($line,1,'New CODE value too large');
                   5485: 	    }
                   5486: 	    if (length($args->{'CODE'}) < $$scantron_config{'CODElength'}) {
                   5487: 		$args->{'CODE'}=sprintf('%-'.$$scantron_config{'CODElength'}.'s',$args->{'CODE'});
                   5488: 	    }
                   5489: 	    substr($line,$$scantron_config{'CODEstart'}-1,
                   5490: 		   $$scantron_config{'CODElength'})=$args->{'CODE'};
1.186     albertel 5491: 	}
1.157     albertel 5492:     } elsif ($field eq 'answer') {
1.497     foxr     5493: 	my $length=$scantron_config->{'Qlength'};
1.157     albertel 5494: 	my $off=$scantron_config->{'Qoff'};
                   5495: 	my $on=$scantron_config->{'Qon'};
1.497     foxr     5496: 	my $answer=${off}x$length;
                   5497: 	if ($args->{'response'} eq 'none') {
                   5498: 	    &scan_data($scan_data,
1.503     raeburn  5499: 		       "$whichline.no_bubble.".$args->{'questionnum'},'1');
1.497     foxr     5500: 	} else {
                   5501: 	    if ($on eq 'letter') {
                   5502: 		my @alphabet=('A'..'Z');
                   5503: 		$answer=$alphabet[$args->{'response'}];
                   5504: 	    } elsif ($on eq 'number') {
                   5505: 		$answer=$args->{'response'}+1;
                   5506: 		if ($answer == 10) { $answer = '0'; }
1.274     albertel 5507: 	    } else {
1.497     foxr     5508: 		substr($answer,$args->{'response'},1)=$on;
1.274     albertel 5509: 	    }
1.497     foxr     5510: 	    &scan_data($scan_data,
1.503     raeburn  5511: 		       "$whichline.no_bubble.".$args->{'questionnum'},undef,'1');
1.157     albertel 5512: 	}
1.497     foxr     5513: 	my $where=$length*($args->{'question'}-1)+$scantron_config->{'Qstart'};
                   5514: 	substr($line,$where-1,$length)=$answer;
1.157     albertel 5515:     }
                   5516:     return $line;
                   5517: }
1.423     albertel 5518: 
                   5519: =pod
                   5520: 
                   5521: =item scan_data
                   5522: 
                   5523:     Edit or look up  an item in the scan_data hash.
                   5524: 
                   5525:   Arguments:
                   5526:     $scan_data  - The hash (see scantron_getfile)
                   5527:     $key        - shorthand of the key to edit (actual key is
1.424     albertel 5528:                   scantronfilename_key).
1.423     albertel 5529:     $data        - New value of the hash entry.
                   5530:     $delete      - If true, the entry is removed from the hash.
                   5531: 
                   5532:   Returns:
                   5533:     The new value of the hash table field (undefined if deleted).
                   5534: 
                   5535: =cut
                   5536: 
                   5537: 
1.157     albertel 5538: sub scan_data {
                   5539:     my ($scan_data,$key,$value,$delete)=@_;
1.257     albertel 5540:     my $filename=$env{'form.scantron_selectfile'};
1.157     albertel 5541:     if (defined($value)) {
                   5542: 	$scan_data->{$filename.'_'.$key} = $value;
                   5543:     }
                   5544:     if ($delete) { delete($scan_data->{$filename.'_'.$key}); }
                   5545:     return $scan_data->{$filename.'_'.$key};
                   5546: }
1.423     albertel 5547: 
1.495     albertel 5548: # ----- These first few routines are general use routines.----
                   5549: 
                   5550: # Return the number of occurences of a pattern in a string.
                   5551: 
                   5552: sub occurence_count {
                   5553:     my ($string, $pattern) = @_;
                   5554: 
                   5555:     my @matches = ($string =~ /$pattern/g);
                   5556: 
                   5557:     return scalar(@matches);
                   5558: }
                   5559: 
                   5560: 
                   5561: # Take a string known to have digits and convert all the
                   5562: # digits into letters in the range J,A..I.
                   5563: 
                   5564: sub digits_to_letters {
                   5565:     my ($input) = @_;
                   5566: 
                   5567:     my @alphabet = ('J', 'A'..'I');
                   5568: 
                   5569:     my @input    = split(//, $input);
                   5570:     my $output ='';
                   5571:     for (my $i = 0; $i < scalar(@input); $i++) {
                   5572: 	if ($input[$i] =~ /\d/) {
                   5573: 	    $output .= $alphabet[$input[$i]];
                   5574: 	} else {
                   5575: 	    $output .= $input[$i];
                   5576: 	}
                   5577:     }
                   5578:     return $output;
                   5579: }
                   5580: 
1.423     albertel 5581: =pod 
                   5582: 
                   5583: =item scantron_parse_scanline
                   5584: 
                   5585:   Decodes a scanline from the selected scantron file
                   5586: 
                   5587:  Arguments:
                   5588:     line             - The text of the scantron file line to process
                   5589:     whichline        - Line number
                   5590:     scantron_config  - Hash describing the format of the scantron lines.
                   5591:     scan_data        - Hash of extra information about the scanline
                   5592:                        (see scantron_getfile for more information)
                   5593:     just_header      - True if should not process question answers but only
                   5594:                        the stuff to the left of the answers.
                   5595:  Returns:
                   5596:    Hash containing the result of parsing the scanline
                   5597: 
                   5598:    Keys are all proceeded by the string 'scantron.'
                   5599: 
                   5600:        CODE    - the CODE in use for this scanline
                   5601:        useCODE - 1 if the CODE is invalid but it usage has been forced
                   5602:                  by the operator
                   5603:        CODE_ignore_dup - 1 if the CODE is a duplicated use when unique
                   5604:                             CODEs were selected, but the usage has been
                   5605:                             forced by the operator
1.556     weissno  5606:        ID  - student/employee ID
1.423     albertel 5607:        PaperID - if used, the ID number printed on the sheet when the 
                   5608:                  paper was scanned
                   5609:        FirstName - first name from the sheet
                   5610:        LastName  - last name from the sheet
                   5611: 
                   5612:      if just_header was not true these key may also exist
                   5613: 
1.447     foxr     5614:        missingerror - a list of bubble ranges that are considered to be answers
                   5615:                       to a single question that don't have any bubbles filled in.
                   5616:                       Of the form questionnumber:firstbubblenumber:count.
                   5617:        doubleerror  - a list of bubble ranges that are considered to be answers
                   5618:                       to a single question that have more than one bubble filled in.
                   5619:                       Of the form questionnumber::firstbubblenumber:count
                   5620:    
                   5621:                 In the above, count is the number of bubble responses in the
                   5622:                 input line needed to represent the possible answers to the question.
                   5623:                 e.g. a radioresponse with 15 choices in an answer sheet with 10 choices
                   5624:                 per line would have count = 2.
                   5625: 
1.423     albertel 5626:        maxquest     - the number of the last bubble line that was parsed
                   5627: 
                   5628:        (<number> starts at 1)
                   5629:        <number>.answer - zero or more letters representing the selected
                   5630:                          letters from the scanline for the bubble line 
                   5631:                          <number>.
                   5632:                          if blank there was either no bubble or there where
                   5633:                          multiple bubbles, (consult the keys missingerror and
                   5634:                          doubleerror if this is an error condition)
                   5635: 
                   5636: =cut
                   5637: 
1.82      albertel 5638: sub scantron_parse_scanline {
1.423     albertel 5639:     my ($line,$whichline,$scantron_config,$scan_data,$just_header)=@_;
1.470     foxr     5640: 
1.82      albertel 5641:     my %record;
1.550     raeburn  5642:     my $lastpos = $env{'form.scantron_maxbubble'}*$$scantron_config{'Qlength'};
                   5643:     my $questions=substr($line,$$scantron_config{'Qstart'}-1,$lastpos);  # Answers
1.422     foxr     5644:     my $data=substr($line,0,$$scantron_config{'Qstart'}-1);     # earlier stuff
1.278     albertel 5645:     if (!($$scantron_config{'CODElocation'} eq 0 ||
                   5646: 	  $$scantron_config{'CODElocation'} eq 'none')) {
                   5647: 	if ($$scantron_config{'CODElocation'} < 0 ||
                   5648: 	    $$scantron_config{'CODElocation'} eq 'letter' ||
                   5649: 	    $$scantron_config{'CODElocation'} eq 'number') {
1.191     albertel 5650: 	    $record{'scantron.CODE'}=substr($data,
                   5651: 					    $$scantron_config{'CODEstart'}-1,
1.83      albertel 5652: 					    $$scantron_config{'CODElength'});
1.191     albertel 5653: 	    if (&scan_data($scan_data,"$whichline.useCODE")) {
                   5654: 		$record{'scantron.useCODE'}=1;
                   5655: 	    }
1.192     albertel 5656: 	    if (&scan_data($scan_data,"$whichline.CODE_ignore_dup")) {
                   5657: 		$record{'scantron.CODE_ignore_dup'}=1;
                   5658: 	    }
1.82      albertel 5659: 	} else {
                   5660: 	    #FIXME interpret first N questions
                   5661: 	}
                   5662:     }
1.83      albertel 5663:     $record{'scantron.ID'}=substr($data,$$scantron_config{'IDstart'}-1,
                   5664: 				  $$scantron_config{'IDlength'});
1.157     albertel 5665:     $record{'scantron.PaperID'}=
                   5666: 	substr($data,$$scantron_config{'PaperID'}-1,
                   5667: 	       $$scantron_config{'PaperIDlength'});
                   5668:     $record{'scantron.FirstName'}=
                   5669: 	substr($data,$$scantron_config{'FirstName'}-1,
                   5670: 	       $$scantron_config{'FirstNamelength'});
                   5671:     $record{'scantron.LastName'}=
                   5672: 	substr($data,$$scantron_config{'LastName'}-1,
                   5673: 	       $$scantron_config{'LastNamelength'});
1.423     albertel 5674:     if ($just_header) { return \%record; }
1.194     albertel 5675: 
1.82      albertel 5676:     my @alphabet=('A'..'Z');
                   5677:     my $questnum=0;
1.447     foxr     5678:     my $ansnum  =1;		# Multiple 'answer lines'/question.
                   5679: 
1.470     foxr     5680:     chomp($questions);		# Get rid of any trailing \n.
                   5681:     $questions =~ s/\r$//;      # Get rid of trailing \r too (MAC or Win uploads).
                   5682:     while (length($questions)) {
1.447     foxr     5683: 	my $answers_needed = $bubble_lines_per_response{$questnum};
1.503     raeburn  5684:         my $answer_length  = ($$scantron_config{'Qlength'} * $answers_needed)
                   5685:                              || 1;
                   5686:         $questnum++;
                   5687:         my $quest_id = $questnum;
                   5688:         my $currentquest = substr($questions,0,$answer_length);
                   5689:         $questions       = substr($questions,$answer_length);
                   5690:         if (length($currentquest) < $answer_length) { next; }
                   5691: 
                   5692:         if ($subdivided_bubble_lines{$questnum-1} =~ /,/) {
                   5693:             my $subquestnum = 1;
                   5694:             my $subquestions = $currentquest;
                   5695:             my @subanswers_needed = 
                   5696:                 split(/,/,$subdivided_bubble_lines{$questnum-1});  
                   5697:             foreach my $subans (@subanswers_needed) {
                   5698:                 my $subans_length =
                   5699:                     ($$scantron_config{'Qlength'} * $subans)  || 1;
                   5700:                 my $currsubquest = substr($subquestions,0,$subans_length);
                   5701:                 $subquestions   = substr($subquestions,$subans_length);
                   5702:                 $quest_id = "$questnum.$subquestnum";
                   5703:                 if (($$scantron_config{'Qon'} eq 'letter') ||
                   5704:                     ($$scantron_config{'Qon'} eq 'number')) {
                   5705:                     $ansnum = &scantron_validator_lettnum($ansnum, 
                   5706:                         $questnum,$quest_id,$subans,$currsubquest,$whichline,
                   5707:                         \@alphabet,\%record,$scantron_config,$scan_data);
                   5708:                 } else {
                   5709:                     $ansnum = &scantron_validator_positional($ansnum,
                   5710:                         $questnum,$quest_id,$subans,$currsubquest,$whichline,                        \@alphabet,\%record,$scantron_config,$scan_data);
                   5711:                 }
                   5712:                 $subquestnum ++;
                   5713:             }
                   5714:         } else {
                   5715:             if (($$scantron_config{'Qon'} eq 'letter') ||
                   5716:                 ($$scantron_config{'Qon'} eq 'number')) {
                   5717:                 $ansnum = &scantron_validator_lettnum($ansnum,$questnum,
                   5718:                     $quest_id,$answers_needed,$currentquest,$whichline,
                   5719:                     \@alphabet,\%record,$scantron_config,$scan_data);
                   5720:             } else {
                   5721:                 $ansnum = &scantron_validator_positional($ansnum,$questnum,
                   5722:                     $quest_id,$answers_needed,$currentquest,$whichline,
                   5723:                     \@alphabet,\%record,$scantron_config,$scan_data);
                   5724:             }
                   5725:         }
                   5726:     }
                   5727:     $record{'scantron.maxquest'}=$questnum;
                   5728:     return \%record;
                   5729: }
1.447     foxr     5730: 
1.503     raeburn  5731: sub scantron_validator_lettnum {
                   5732:     my ($ansnum,$questnum,$quest_id,$answers_needed,$currquest,$whichline,
                   5733:         $alphabet,$record,$scantron_config,$scan_data) = @_;
                   5734: 
                   5735:     # Qon 'letter' implies for each slot in currquest we have:
                   5736:     #    ? or * for doubles, a letter in A-Z for a bubble, and
                   5737:     #    about anything else (esp. a value of Qoff) for missing
                   5738:     #    bubbles.
                   5739:     #
                   5740:     # Qon 'number' implies each slot gives a digit that indexes the
                   5741:     #    bubbles filled, or Qoff, or a non-number for unbubbled lines,
                   5742:     #    and * or ? for double bubbles on a single line.
                   5743:     #
1.447     foxr     5744: 
1.503     raeburn  5745:     my $matchon;
                   5746:     if ($$scantron_config{'Qon'} eq 'letter') {
                   5747:         $matchon = '[A-Z]';
                   5748:     } elsif ($$scantron_config{'Qon'} eq 'number') {
                   5749:         $matchon = '\d';
                   5750:     }
                   5751:     my $occurrences = 0;
                   5752:     if (($responsetype_per_response{$questnum-1} eq 'essayresponse') ||
                   5753:         ($responsetype_per_response{$questnum-1} eq 'formularesponse') ||
1.510     raeburn  5754:         ($responsetype_per_response{$questnum-1} eq 'stringresponse') ||
                   5755:         ($responsetype_per_response{$questnum-1} eq 'imageresponse') ||
                   5756:         ($responsetype_per_response{$questnum-1} eq 'reactionresponse') ||
                   5757:         ($responsetype_per_response{$questnum-1} eq 'organicresponse')) {
1.503     raeburn  5758:         my @singlelines = split('',$currquest);
                   5759:         foreach my $entry (@singlelines) {
                   5760:             $occurrences = &occurence_count($entry,$matchon);
                   5761:             if ($occurrences > 1) {
                   5762:                 last;
                   5763:             }
                   5764:         } 
                   5765:     } else {
                   5766:         $occurrences = &occurence_count($currquest,$matchon); 
                   5767:     }
                   5768:     if (($currquest =~ /\?/ || $currquest =~ /\*/) || ($occurrences > 1)) {
                   5769:         push(@{$record->{'scantron.doubleerror'}},$quest_id);
                   5770:         for (my $ans=0; $ans<$answers_needed; $ans++) {
                   5771:             my $bubble = substr($currquest,$ans,1);
                   5772:             if ($bubble =~ /$matchon/ ) {
                   5773:                 if ($$scantron_config{'Qon'} eq 'number') {
                   5774:                     if ($bubble == 0) {
                   5775:                         $bubble = 10; 
                   5776:                     }
                   5777:                     $record->{"scantron.$ansnum.answer"} = 
                   5778:                         $alphabet->[$bubble-1];
                   5779:                 } else {
                   5780:                     $record->{"scantron.$ansnum.answer"} = $bubble;
                   5781:                 }
                   5782:             } else {
                   5783:                 $record->{"scantron.$ansnum.answer"}='';
                   5784:             }
                   5785:             $ansnum++;
                   5786:         }
                   5787:     } elsif (!defined($currquest)
                   5788:             || (&occurence_count($currquest, $$scantron_config{'Qoff'}) == length($currquest))
                   5789:             || (&occurence_count($currquest,$matchon) == 0)) {
                   5790:         for (my $ans=0; $ans<$answers_needed; $ans++ ) {
                   5791:             $record->{"scantron.$ansnum.answer"}='';
                   5792:             $ansnum++;
                   5793:         }
                   5794:         if (!&scan_data($scan_data,"$whichline.no_bubble.$quest_id")) {
                   5795:             push(@{$record->{'scantron.missingerror'}},$quest_id);
                   5796:         }
                   5797:     } else {
                   5798:         if ($$scantron_config{'Qon'} eq 'number') {
                   5799:             $currquest = &digits_to_letters($currquest);            
                   5800:         }
                   5801:         for (my $ans=0; $ans<$answers_needed; $ans++) {
                   5802:             my $bubble = substr($currquest,$ans,1);
                   5803:             $record->{"scantron.$ansnum.answer"} = $bubble;
                   5804:             $ansnum++;
                   5805:         }
                   5806:     }
                   5807:     return $ansnum;
                   5808: }
1.447     foxr     5809: 
1.503     raeburn  5810: sub scantron_validator_positional {
                   5811:     my ($ansnum,$questnum,$quest_id,$answers_needed,$currquest,
                   5812:         $whichline,$alphabet,$record,$scantron_config,$scan_data) = @_;
1.447     foxr     5813: 
1.503     raeburn  5814:     # Otherwise there's a positional notation;
                   5815:     # each bubble line requires Qlength items, and there are filled in
                   5816:     # bubbles for each case where there 'Qon' characters.
                   5817:     #
1.447     foxr     5818: 
1.503     raeburn  5819:     my @array=split($$scantron_config{'Qon'},$currquest,-1);
1.447     foxr     5820: 
1.503     raeburn  5821:     # If the split only gives us one element.. the full length of the
                   5822:     # answer string, no bubbles are filled in:
1.447     foxr     5823: 
1.507     raeburn  5824:     if ($answers_needed eq '') {
                   5825:         return;
                   5826:     }
                   5827: 
1.503     raeburn  5828:     if (length($array[0]) eq $$scantron_config{'Qlength'}*$answers_needed) {
                   5829:         for (my $ans=0; $ans<$answers_needed; $ans++ ) {
                   5830:             $record->{"scantron.$ansnum.answer"}='';
                   5831:             $ansnum++;
                   5832:         }
                   5833:         if (!&scan_data($scan_data,"$whichline.no_bubble.$quest_id")) {
                   5834:             push(@{$record->{"scantron.missingerror"}},$quest_id);
                   5835:         }
                   5836:     } elsif (scalar(@array) == 2) {
                   5837:         my $location = length($array[0]);
                   5838:         my $line_num = int($location / $$scantron_config{'Qlength'});
                   5839:         my $bubble   = $alphabet->[$location % $$scantron_config{'Qlength'}];
                   5840:         for (my $ans=0; $ans<$answers_needed; $ans++) {
                   5841:             if ($ans eq $line_num) {
                   5842:                 $record->{"scantron.$ansnum.answer"} = $bubble;
                   5843:             } else {
                   5844:                 $record->{"scantron.$ansnum.answer"} = ' ';
                   5845:             }
                   5846:             $ansnum++;
                   5847:          }
                   5848:     } else {
                   5849:         #  If there's more than one instance of a bubble character
                   5850:         #  That's a double bubble; with positional notation we can
                   5851:         #  record all the bubbles filled in as well as the
                   5852:         #  fact this response consists of multiple bubbles.
                   5853:         #
                   5854:         if (($responsetype_per_response{$questnum-1} eq 'essayresponse') ||
                   5855:             ($responsetype_per_response{$questnum-1} eq 'formularesponse') ||
1.510     raeburn  5856:             ($responsetype_per_response{$questnum-1} eq 'stringresponse') ||
                   5857:             ($responsetype_per_response{$questnum-1} eq 'imageresponse') ||
                   5858:             ($responsetype_per_response{$questnum-1} eq 'reactionresponse') ||
                   5859:             ($responsetype_per_response{$questnum-1} eq 'organicresponse')) {
1.503     raeburn  5860:             my $doubleerror = 0;
                   5861:             while (($currquest >= $$scantron_config{'Qlength'}) && 
                   5862:                    (!$doubleerror)) {
                   5863:                my $currline = substr($currquest,0,$$scantron_config{'Qlength'});
                   5864:                $currquest = substr($currquest,$$scantron_config{'Qlength'});
                   5865:                my @currarray = split($$scantron_config{'Qon'},$currline,-1);
                   5866:                if (length(@currarray) > 2) {
                   5867:                    $doubleerror = 1;
                   5868:                } 
                   5869:             }
                   5870:             if ($doubleerror) {
                   5871:                 push(@{$record->{'scantron.doubleerror'}},$quest_id);
                   5872:             }
                   5873:         } else {
                   5874:             push(@{$record->{'scantron.doubleerror'}},$quest_id);
                   5875:         }
                   5876:         my $item = $ansnum;
                   5877:         for (my $ans=0; $ans<$answers_needed; $ans++) {
                   5878:             $record->{"scantron.$item.answer"} = '';
                   5879:             $item ++;
                   5880:         }
1.447     foxr     5881: 
1.503     raeburn  5882:         my @ans=@array;
                   5883:         my $i=0;
                   5884:         my $increment = 0;
                   5885:         while ($#ans) {
                   5886:             $i+=length($ans[0]) + $increment;
                   5887:             my $line   = int($i/$$scantron_config{'Qlength'} + $ansnum);
                   5888:             my $bubble = $i%$$scantron_config{'Qlength'};
                   5889:             $record->{"scantron.$line.answer"}.=$alphabet->[$bubble];
                   5890:             shift(@ans);
                   5891:             $increment = 1;
                   5892:         }
                   5893:         $ansnum += $answers_needed;
1.82      albertel 5894:     }
1.503     raeburn  5895:     return $ansnum;
1.82      albertel 5896: }
                   5897: 
1.423     albertel 5898: =pod
                   5899: 
                   5900: =item scantron_add_delay
                   5901: 
                   5902:    Adds an error message that occurred during the grading phase to a
                   5903:    queue of messages to be shown after grading pass is complete
                   5904: 
                   5905:  Arguments:
1.424     albertel 5906:    $delayqueue  - arrary ref of hash ref of error messages
1.423     albertel 5907:    $scanline    - the scanline that caused the error
                   5908:    $errormesage - the error message
                   5909:    $errorcode   - a numeric code for the error
                   5910: 
                   5911:  Side Effects:
1.424     albertel 5912:    updates the $delayqueue to have a new hash ref of the error
1.423     albertel 5913: 
                   5914: =cut
                   5915: 
1.82      albertel 5916: sub scantron_add_delay {
1.140     albertel 5917:     my ($delayqueue,$scanline,$errormessage,$errorcode)=@_;
                   5918:     push(@$delayqueue,
                   5919: 	 {'line' => $scanline, 'emsg' => $errormessage,
                   5920: 	  'ecode' => $errorcode }
                   5921: 	 );
1.82      albertel 5922: }
                   5923: 
1.423     albertel 5924: =pod
                   5925: 
                   5926: =item scantron_find_student
                   5927: 
1.424     albertel 5928:    Finds the username for the current scanline
                   5929: 
                   5930:   Arguments:
                   5931:    $scantron_record - hash result from scantron_parse_scanline
                   5932:    $scan_data       - hash of correction information 
                   5933:                       (see &scantron_getfile() form more information)
                   5934:    $idmap           - hash from &username_to_idmap()
                   5935:    $line            - number of current scanline
                   5936:  
                   5937:   Returns:
                   5938:    Either 'username:domain' or undef if unknown
                   5939: 
1.423     albertel 5940: =cut
                   5941: 
1.82      albertel 5942: sub scantron_find_student {
1.157     albertel 5943:     my ($scantron_record,$scan_data,$idmap,$line)=@_;
1.83      albertel 5944:     my $scanID=$$scantron_record{'scantron.ID'};
1.157     albertel 5945:     if ($scanID =~ /^\s*$/) {
                   5946:  	return &scan_data($scan_data,"$line.user");
                   5947:     }
1.83      albertel 5948:     foreach my $id (keys(%$idmap)) {
1.157     albertel 5949:  	if (lc($id) eq lc($scanID)) {
                   5950:  	    return $$idmap{$id};
                   5951:  	}
1.83      albertel 5952:     }
                   5953:     return undef;
                   5954: }
                   5955: 
1.423     albertel 5956: =pod
                   5957: 
                   5958: =item scantron_filter
                   5959: 
1.424     albertel 5960:    Filter sub for lonnavmaps, filters out hidden resources if ignore
                   5961:    hidden resources was selected
                   5962: 
1.423     albertel 5963: =cut
                   5964: 
1.83      albertel 5965: sub scantron_filter {
                   5966:     my ($curres)=@_;
1.331     albertel 5967: 
                   5968:     if (ref($curres) && $curres->is_problem()) {
                   5969: 	# if the user has asked to not have either hidden
                   5970: 	# or 'randomout' controlled resources to be graded
                   5971: 	# don't include them
                   5972: 	if ($env{'form.scantron_options_hidden'} eq 'ignore_hidden'
                   5973: 	    && $curres->randomout) {
                   5974: 	    return 0;
                   5975: 	}
1.83      albertel 5976: 	return 1;
                   5977:     }
                   5978:     return 0;
1.82      albertel 5979: }
                   5980: 
1.423     albertel 5981: =pod
                   5982: 
                   5983: =item scantron_process_corrections
                   5984: 
1.424     albertel 5985:    Gets correction information out of submitted form data and corrects
                   5986:    the scanline
                   5987: 
1.423     albertel 5988: =cut
                   5989: 
1.157     albertel 5990: sub scantron_process_corrections {
                   5991:     my ($r) = @_;
1.257     albertel 5992:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.157     albertel 5993:     my ($scanlines,$scan_data)=&scantron_getfile();
                   5994:     my $classlist=&Apache::loncoursedata::get_classlist();
1.257     albertel 5995:     my $which=$env{'form.scantron_line'};
1.200     albertel 5996:     my $line=&scantron_get_line($scanlines,$scan_data,$which);
1.157     albertel 5997:     my ($skip,$err,$errmsg);
1.257     albertel 5998:     if ($env{'form.scantron_skip_record'}) {
1.157     albertel 5999: 	$skip=1;
1.257     albertel 6000:     } elsif ($env{'form.scantron_corrections'} =~ /^(duplicate|incorrect)ID$/) {
                   6001: 	my $newstudent=$env{'form.scantron_username'}.':'.
                   6002: 	    $env{'form.scantron_domain'};
1.157     albertel 6003: 	my $newid=$classlist->{$newstudent}->[&Apache::loncoursedata::CL_ID];
                   6004: 	($line,$err,$errmsg)=
                   6005: 	    &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,$which,
                   6006: 				     'ID',{'newid'=>$newid,
1.257     albertel 6007: 				    'username'=>$env{'form.scantron_username'},
                   6008: 				    'domain'=>$env{'form.scantron_domain'}});
                   6009:     } elsif ($env{'form.scantron_corrections'} =~ /^(duplicate|incorrect)CODE$/) {
                   6010: 	my $resolution=$env{'form.scantron_CODE_resolution'};
1.190     albertel 6011: 	my $newCODE;
1.192     albertel 6012: 	my %args;
1.190     albertel 6013: 	if      ($resolution eq 'use_unfound') {
1.191     albertel 6014: 	    $newCODE='use_unfound';
1.190     albertel 6015: 	} elsif ($resolution eq 'use_found') {
1.257     albertel 6016: 	    $newCODE=$env{'form.scantron_CODE_selectedvalue'};
1.190     albertel 6017: 	} elsif ($resolution eq 'use_typed') {
1.257     albertel 6018: 	    $newCODE=$env{'form.scantron_CODE_newvalue'};
1.194     albertel 6019: 	} elsif ($resolution =~ /^use_closest_(\d+)/) {
1.257     albertel 6020: 	    $newCODE=$env{"form.scantron_CODE_closest_$1"};
1.190     albertel 6021: 	}
1.257     albertel 6022: 	if ($env{'form.scantron_corrections'} eq 'duplicateCODE') {
1.192     albertel 6023: 	    $args{'CODE_ignore_dup'}=1;
                   6024: 	}
                   6025: 	$args{'CODE'}=$newCODE;
1.186     albertel 6026: 	($line,$err,$errmsg)=
                   6027: 	    &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,$which,
1.192     albertel 6028: 				     'CODE',\%args);
1.257     albertel 6029:     } elsif ($env{'form.scantron_corrections'} =~ /^(missing|double)bubble$/) {
                   6030: 	foreach my $question (split(',',$env{'form.scantron_questions'})) {
1.157     albertel 6031: 	    ($line,$err,$errmsg)=
                   6032: 		&scantron_fixup_scanline(\%scantron_config,$scan_data,$line,
                   6033: 					 $which,'answer',
                   6034: 					 { 'question'=>$question,
1.503     raeburn  6035: 		      		   'response'=>$env{"form.scantron_correct_Q_$question"},
                   6036:                                    'questionnum'=>$env{"form.scantron_questionnum_Q_$question"}});
1.157     albertel 6037: 	    if ($err) { last; }
                   6038: 	}
                   6039:     }
                   6040:     if ($err) {
1.398     albertel 6041: 	$r->print("<span class=\"LC_warning\">Unable to accept last correction, an error occurred :$errmsg:</span>");
1.157     albertel 6042:     } else {
1.200     albertel 6043: 	&scantron_put_line($scanlines,$scan_data,$which,$line,$skip);
1.157     albertel 6044: 	&scantron_putfile($scanlines,$scan_data);
                   6045:     }
                   6046: }
                   6047: 
1.423     albertel 6048: =pod
                   6049: 
                   6050: =item reset_skipping_status
                   6051: 
1.424     albertel 6052:    Forgets the current set of remember skipped scanlines (and thus
                   6053:    reverts back to considering all lines in the
                   6054:    scantron_skipped_<filename> file)
                   6055: 
1.423     albertel 6056: =cut
                   6057: 
1.200     albertel 6058: sub reset_skipping_status {
                   6059:     my ($scanlines,$scan_data)=&scantron_getfile();
                   6060:     &scan_data($scan_data,'remember_skipping',undef,1);
                   6061:     &scantron_putfile(undef,$scan_data);
                   6062: }
                   6063: 
1.423     albertel 6064: =pod
                   6065: 
                   6066: =item start_skipping
                   6067: 
1.424     albertel 6068:    Marks a scanline to be skipped. 
                   6069: 
1.423     albertel 6070: =cut
                   6071: 
1.376     albertel 6072: sub start_skipping {
1.200     albertel 6073:     my ($scan_data,$i)=@_;
                   6074:     my %remembered=split(':',&scan_data($scan_data,'remember_skipping'));
1.376     albertel 6075:     if ($env{'form.scantron_options_redo'} =~ /^redo_/) {
                   6076: 	$remembered{$i}=2;
                   6077:     } else {
                   6078: 	$remembered{$i}=1;
                   6079:     }
1.200     albertel 6080:     &scan_data($scan_data,'remember_skipping',join(':',%remembered));
                   6081: }
                   6082: 
1.423     albertel 6083: =pod
                   6084: 
                   6085: =item should_be_skipped
                   6086: 
1.424     albertel 6087:    Checks whether a scanline should be skipped.
                   6088: 
1.423     albertel 6089: =cut
                   6090: 
1.200     albertel 6091: sub should_be_skipped {
1.376     albertel 6092:     my ($scanlines,$scan_data,$i)=@_;
1.257     albertel 6093:     if ($env{'form.scantron_options_redo'} !~ /^redo_/) {
1.200     albertel 6094: 	# not redoing old skips
1.376     albertel 6095: 	if ($scanlines->{'skipped'}[$i]) { return 1; }
1.200     albertel 6096: 	return 0;
                   6097:     }
                   6098:     my %remembered=split(':',&scan_data($scan_data,'remember_skipping'));
1.376     albertel 6099: 
                   6100:     if (exists($remembered{$i}) && $remembered{$i} != 2 ) {
                   6101: 	return 0;
                   6102:     }
1.200     albertel 6103:     return 1;
                   6104: }
                   6105: 
1.423     albertel 6106: =pod
                   6107: 
                   6108: =item remember_current_skipped
                   6109: 
1.424     albertel 6110:    Discovers what scanlines are in the scantron_skipped_<filename>
                   6111:    file and remembers them into scan_data for later use.
                   6112: 
1.423     albertel 6113: =cut
                   6114: 
1.200     albertel 6115: sub remember_current_skipped {
                   6116:     my ($scanlines,$scan_data)=&scantron_getfile();
                   6117:     my %to_remember;
                   6118:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
                   6119: 	if ($scanlines->{'skipped'}[$i]) {
                   6120: 	    $to_remember{$i}=1;
                   6121: 	}
                   6122:     }
1.376     albertel 6123: 
1.200     albertel 6124:     &scan_data($scan_data,'remember_skipping',join(':',%to_remember));
                   6125:     &scantron_putfile(undef,$scan_data);
                   6126: }
                   6127: 
1.423     albertel 6128: =pod
                   6129: 
                   6130: =item check_for_error
                   6131: 
1.424     albertel 6132:     Checks if there was an error when attempting to remove a specific
                   6133:     scantron_.. bubble sheet data file. Prints out an error if
                   6134:     something went wrong.
                   6135: 
1.423     albertel 6136: =cut
                   6137: 
1.200     albertel 6138: sub check_for_error {
                   6139:     my ($r,$result)=@_;
                   6140:     if ($result ne 'ok' && $result ne 'not_found' ) {
1.492     albertel 6141: 	$r->print(&mt("An error occurred ([_1]) when trying to remove the existing corrections.",$result));
1.200     albertel 6142:     }
                   6143: }
1.157     albertel 6144: 
1.423     albertel 6145: =pod
                   6146: 
                   6147: =item scantron_warning_screen
                   6148: 
1.424     albertel 6149:    Interstitial screen to make sure the operator has selected the
                   6150:    correct options before we start the validation phase.
                   6151: 
1.423     albertel 6152: =cut
                   6153: 
1.203     albertel 6154: sub scantron_warning_screen {
                   6155:     my ($button_text)=@_;
1.257     albertel 6156:     my $title=&Apache::lonnet::gettitle($env{'form.selectpage'});
1.284     albertel 6157:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.373     albertel 6158:     my $CODElist;
1.284     albertel 6159:     if ($scantron_config{'CODElocation'} &&
                   6160: 	$scantron_config{'CODEstart'} &&
                   6161: 	$scantron_config{'CODElength'}) {
                   6162: 	$CODElist=$env{'form.scantron_CODElist'};
1.398     albertel 6163: 	if ($env{'form.scantron_CODElist'} eq '') { $CODElist='<span class="LC_warning">None</span>'; }
1.284     albertel 6164: 	$CODElist=
1.492     albertel 6165: 	    '<tr><td><b>'.&mt('List of CODES to validate against:').'</b></td><td><tt>'.
1.373     albertel 6166: 	    $env{'form.scantron_CODElist'}.'</tt></td></tr>';
1.284     albertel 6167:     }
1.492     albertel 6168:     return ('
1.203     albertel 6169: <p>
1.492     albertel 6170: <span class="LC_warning">
                   6171: '.&mt('Please double check the information below before clicking on \'[_1]\'',&mt($button_text)).'</span>
1.203     albertel 6172: </p>
                   6173: <table>
1.492     albertel 6174: <tr><td><b>'.&mt('Sequence to be Graded:').'</b></td><td>'.$title.'</td></tr>
                   6175: <tr><td><b>'.&mt('Data File that will be used:').'</b></td><td><tt>'.$env{'form.scantron_selectfile'}.'</tt></td></tr>
                   6176: '.$CODElist.'
1.203     albertel 6177: </table>
                   6178: <br />
1.492     albertel 6179: <p> '.&mt('If this information is correct, please click on \'[_1]\'.',&mt($button_text)).'</p>
                   6180: <p> '.&mt('If something is incorrect, please click the \'Grading Menu\' button to start over.').'</p>
1.203     albertel 6181: 
                   6182: <br />
1.492     albertel 6183: ');
1.203     albertel 6184: }
                   6185: 
1.423     albertel 6186: =pod
                   6187: 
                   6188: =item scantron_do_warning
                   6189: 
1.424     albertel 6190:    Check if the operator has picked something for all required
                   6191:    fields. Error out if something is missing.
                   6192: 
1.423     albertel 6193: =cut
                   6194: 
1.203     albertel 6195: sub scantron_do_warning {
1.608     www      6196:     my ($r,$symb)=@_;
1.203     albertel 6197:     if (!$symb) {return '';}
1.324     albertel 6198:     my $default_form_data=&defaultFormData($symb);
1.203     albertel 6199:     $r->print(&scantron_form_start().$default_form_data);
1.257     albertel 6200:     if ( $env{'form.selectpage'} eq '' ||
                   6201: 	 $env{'form.scantron_selectfile'} eq '' ||
                   6202: 	 $env{'form.scantron_format'} eq '' ) {
1.492     albertel 6203: 	$r->print("<p>".&mt('You have forgetten to specify some information. Please go Back and try again.')."</p>");
1.257     albertel 6204: 	if ( $env{'form.selectpage'} eq '') {
1.492     albertel 6205: 	    $r->print('<p><span class="LC_error">'.&mt('You have not selected a Sequence to grade').'</span></p>');
1.237     albertel 6206: 	} 
1.257     albertel 6207: 	if ( $env{'form.scantron_selectfile'} eq '') {
1.492     albertel 6208: 	    $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 6209: 	} 
1.257     albertel 6210: 	if ( $env{'form.scantron_format'} eq '') {
1.492     albertel 6211: 	    $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 6212: 	} 
                   6213:     } else {
1.265     www      6214: 	my $warning=&scantron_warning_screen('Grading: Validate Records');
1.492     albertel 6215: 	$r->print('
                   6216: '.$warning.'
                   6217: <input type="submit" name="submit" value="'.&mt('Grading: Validate Records').'" />
1.203     albertel 6218: <input type="hidden" name="command" value="scantron_validate" />
1.492     albertel 6219: ');
1.237     albertel 6220:     }
1.614     www      6221:     $r->print("</form><br />");
1.203     albertel 6222:     return '';
                   6223: }
                   6224: 
1.423     albertel 6225: =pod
                   6226: 
                   6227: =item scantron_form_start
                   6228: 
1.424     albertel 6229:     html hidden input for remembering all selected grading options
                   6230: 
1.423     albertel 6231: =cut
                   6232: 
1.203     albertel 6233: sub scantron_form_start {
                   6234:     my ($max_bubble)=@_;
                   6235:     my $result= <<SCANTRONFORM;
                   6236: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantronupload">
1.257     albertel 6237:   <input type="hidden" name="selectpage" value="$env{'form.selectpage'}" />
                   6238:   <input type="hidden" name="scantron_format" value="$env{'form.scantron_format'}" />
                   6239:   <input type="hidden" name="scantron_selectfile" value="$env{'form.scantron_selectfile'}" />
1.218     albertel 6240:   <input type="hidden" name="scantron_maxbubble" value="$max_bubble" />
1.257     albertel 6241:   <input type="hidden" name="scantron_CODElist" value="$env{'form.scantron_CODElist'}" />
                   6242:   <input type="hidden" name="scantron_CODEunique" value="$env{'form.scantron_CODEunique'}" />
                   6243:   <input type="hidden" name="scantron_options_redo" value="$env{'form.scantron_options_redo'}" />
                   6244:   <input type="hidden" name="scantron_options_ignore" value="$env{'form.scantron_options_ignore'}" />
1.331     albertel 6245:   <input type="hidden" name="scantron_options_hidden" value="$env{'form.scantron_options_hidden'}" />
1.203     albertel 6246: SCANTRONFORM
1.447     foxr     6247: 
                   6248:   my $line = 0;
                   6249:     while (defined($env{"form.scantron.bubblelines.$line"})) {
                   6250:        my $chunk =
                   6251: 	   '<input type="hidden" name="scantron.bubblelines.'.$line.'" value="'.$env{"form.scantron.bubblelines.$line"}.'" />'."\n";
1.448     foxr     6252:        $chunk .=
                   6253: 	   '<input type="hidden" name="scantron.first_bubble_line.'.$line.'" value="'.$env{"form.scantron.first_bubble_line.$line"}.'" />'."\n";
1.503     raeburn  6254:        $chunk .= 
                   6255:            '<input type="hidden" name="scantron.sub_bubblelines.'.$line.'" value="'.$env{"form.scantron.sub_bubblelines.$line"}.'" />'."\n";
1.504     raeburn  6256:        $chunk .=
                   6257:            '<input type="hidden" name="scantron.responsetype.'.$line.'" value="'.$env{"form.scantron.responsetype.$line"}.'" />'."\n";
1.447     foxr     6258:        $result .= $chunk;
                   6259:        $line++;
                   6260:    }
1.203     albertel 6261:     return $result;
                   6262: }
                   6263: 
1.423     albertel 6264: =pod
                   6265: 
                   6266: =item scantron_validate_file
                   6267: 
1.424     albertel 6268:     Dispatch routine for doing validation of a bubble sheet data file.
                   6269: 
                   6270:     Also processes any necessary information resets that need to
                   6271:     occur before validation begins (ignore previous corrections,
                   6272:     restarting the skipped records processing)
                   6273: 
1.423     albertel 6274: =cut
                   6275: 
1.157     albertel 6276: sub scantron_validate_file {
1.608     www      6277:     my ($r,$symb) = @_;
1.157     albertel 6278:     if (!$symb) {return '';}
1.324     albertel 6279:     my $default_form_data=&defaultFormData($symb);
1.200     albertel 6280:     
                   6281:     # do the detection of only doing skipped records first befroe we delete
1.424     albertel 6282:     # them when doing the corrections reset
1.257     albertel 6283:     if ($env{'form.scantron_options_redo'} ne 'redo_skipped_ready') {
1.200     albertel 6284: 	&reset_skipping_status();
                   6285:     }
1.257     albertel 6286:     if ($env{'form.scantron_options_redo'} eq 'redo_skipped') {
1.200     albertel 6287: 	&remember_current_skipped();
1.257     albertel 6288: 	$env{'form.scantron_options_redo'}='redo_skipped_ready';
1.200     albertel 6289:     }
                   6290: 
1.257     albertel 6291:     if ($env{'form.scantron_options_ignore'} eq 'ignore_corrections') {
1.200     albertel 6292: 	&check_for_error($r,&scantron_remove_file('corrected'));
                   6293: 	&check_for_error($r,&scantron_remove_file('skipped'));
                   6294: 	&check_for_error($r,&scantron_remove_scan_data());
1.257     albertel 6295: 	$env{'form.scantron_options_ignore'}='done';
1.192     albertel 6296:     }
1.200     albertel 6297: 
1.257     albertel 6298:     if ($env{'form.scantron_corrections'}) {
1.157     albertel 6299: 	&scantron_process_corrections($r);
                   6300:     }
1.503     raeburn  6301:     $r->print('<p>'.&mt('Gathering necessary information.').'</p>');$r->rflush();
1.157     albertel 6302:     #get the student pick code ready
                   6303:     $r->print(&Apache::loncommon::studentbrowser_javascript());
1.582     raeburn  6304:     my $nav_error;
                   6305:     my $max_bubble=&scantron_get_maxbubble(\$nav_error);
                   6306:     if ($nav_error) {
                   6307:         $r->print(&navmap_errormsg());
                   6308:         return '';
                   6309:     }
1.203     albertel 6310:     my $result=&scantron_form_start($max_bubble).$default_form_data;
1.157     albertel 6311:     $r->print($result);
                   6312:     
1.334     albertel 6313:     my @validate_phases=( 'sequence',
                   6314: 			  'ID',
1.157     albertel 6315: 			  'CODE',
                   6316: 			  'doublebubble',
                   6317: 			  'missingbubbles');
1.257     albertel 6318:     if (!$env{'form.validatepass'}) {
                   6319: 	$env{'form.validatepass'} = 0;
1.157     albertel 6320:     }
1.257     albertel 6321:     my $currentphase=$env{'form.validatepass'};
1.157     albertel 6322: 
1.448     foxr     6323: 
1.157     albertel 6324:     my $stop=0;
                   6325:     while (!$stop && $currentphase < scalar(@validate_phases)) {
1.503     raeburn  6326: 	$r->print(&mt('Validating '.$validate_phases[$currentphase]).'<br />');
1.157     albertel 6327: 	$r->rflush();
                   6328: 	my $which="scantron_validate_".$validate_phases[$currentphase];
                   6329: 	{
                   6330: 	    no strict 'refs';
                   6331: 	    ($stop,$currentphase)=&$which($r,$currentphase);
                   6332: 	}
                   6333:     }
                   6334:     if (!$stop) {
1.203     albertel 6335: 	my $warning=&scantron_warning_screen('Start Grading');
1.542     raeburn  6336: 	$r->print(&mt('Validation process complete.').'<br />'.
                   6337:                   $warning.
                   6338:                   &mt('Perform verification for each student after storage of submissions?').
                   6339:                   '&nbsp;<span class="LC_nobreak"><label>'.
                   6340:                   '<input type="radio" name="verifyrecord" value="1" />'.&mt('Yes').'</label>'.
                   6341:                   ('&nbsp;'x3).'<label>'.
                   6342:                   '<input type="radio" name="verifyrecord" value="0" checked="checked" />'.&mt('No').
                   6343:                   '</label></span><br />'.
                   6344:                   &mt('Grading will take longer if you use verification.').'<br />'.
1.572     www      6345:                   &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  6346:                   '<input type="submit" name="submit" value="'.&mt('Start Grading').'" />'.
                   6347:                   '<input type="hidden" name="command" value="scantron_process" />'."\n");
1.157     albertel 6348:     } else {
                   6349: 	$r->print('<input type="hidden" name="command" value="scantron_validate" />');
                   6350: 	$r->print("<input type='hidden' name='validatepass' value='".$currentphase."' />");
                   6351:     }
                   6352:     if ($stop) {
1.334     albertel 6353: 	if ($validate_phases[$currentphase] eq 'sequence') {
1.539     riegler  6354: 	    $r->print('<input type="submit" name="submit" value="'.&mt('Ignore').' &rarr; " />');
1.492     albertel 6355: 	    $r->print(' '.&mt('this error').' <br />');
1.334     albertel 6356: 
1.492     albertel 6357: 	    $r->print(" <p>".&mt("Or click the 'Grading Menu' button to start over.")."</p>");
1.334     albertel 6358: 	} else {
1.503     raeburn  6359:             if ($validate_phases[$currentphase] eq 'doublebubble' || $validate_phases[$currentphase] eq 'missingbubbles') {
1.539     riegler  6360: 	        $r->print('<input type="button" name="submitbutton" value="'.&mt('Continue').' &rarr;" onclick="javascript:verify_bubble_radio(this.form)" />');
1.503     raeburn  6361:             } else {
1.539     riegler  6362:                 $r->print('<input type="submit" name="submit" value="'.&mt('Continue').' &rarr;" />');
1.503     raeburn  6363:             }
1.492     albertel 6364: 	    $r->print(' '.&mt('using corrected info').' <br />');
                   6365: 	    $r->print("<input type='submit' value='".&mt("Skip")."' name='scantron_skip_record' />");
                   6366: 	    $r->print(" ".&mt("this scanline saving it for later."));
1.334     albertel 6367: 	}
1.157     albertel 6368:     }
1.614     www      6369:     $r->print(" </form><br />");
1.157     albertel 6370:     return '';
                   6371: }
                   6372: 
1.423     albertel 6373: 
                   6374: =pod
                   6375: 
                   6376: =item scantron_remove_file
                   6377: 
1.424     albertel 6378:    Removes the requested bubble sheet data file, makes sure that
                   6379:    scantron_original_<filename> is never removed
                   6380: 
                   6381: 
1.423     albertel 6382: =cut
                   6383: 
1.200     albertel 6384: sub scantron_remove_file {
1.192     albertel 6385:     my ($which)=@_;
1.257     albertel 6386:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   6387:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.192     albertel 6388:     my $file='scantron_';
1.200     albertel 6389:     if ($which eq 'corrected' || $which eq 'skipped') {
                   6390: 	$file.=$which.'_';
1.192     albertel 6391:     } else {
                   6392: 	return 'refused';
                   6393:     }
1.257     albertel 6394:     $file.=$env{'form.scantron_selectfile'};
1.200     albertel 6395:     return &Apache::lonnet::removeuserfile($cname,$cdom,$file);
                   6396: }
                   6397: 
1.423     albertel 6398: 
                   6399: =pod
                   6400: 
                   6401: =item scantron_remove_scan_data
                   6402: 
1.424     albertel 6403:    Removes all scan_data correction for the requested bubble sheet
                   6404:    data file.  (In the case that both the are doing skipped records we need
                   6405:    to remember the old skipped lines for the time being so that element
                   6406:    persists for a while.)
                   6407: 
1.423     albertel 6408: =cut
                   6409: 
1.200     albertel 6410: sub scantron_remove_scan_data {
1.257     albertel 6411:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   6412:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.192     albertel 6413:     my @keys=&Apache::lonnet::getkeys('nohist_scantrondata',$cdom,$cname);
                   6414:     my @todelete;
1.257     albertel 6415:     my $filename=$env{'form.scantron_selectfile'};
1.192     albertel 6416:     foreach my $key (@keys) {
                   6417: 	if ($key=~/^\Q$filename\E_/) {
1.257     albertel 6418: 	    if ($env{'form.scantron_options_redo'} eq 'redo_skipped_ready' &&
1.200     albertel 6419: 		$key=~/remember_skipping/) {
                   6420: 		next;
                   6421: 	    }
1.192     albertel 6422: 	    push(@todelete,$key);
                   6423: 	}
                   6424:     }
1.200     albertel 6425:     my $result;
1.192     albertel 6426:     if (@todelete) {
1.491     albertel 6427: 	$result = &Apache::lonnet::del('nohist_scantrondata',
                   6428: 				       \@todelete,$cdom,$cname);
                   6429:     } else {
                   6430: 	$result = 'ok';
1.192     albertel 6431:     }
                   6432:     return $result;
                   6433: }
                   6434: 
1.423     albertel 6435: 
                   6436: =pod
                   6437: 
                   6438: =item scantron_getfile
                   6439: 
1.424     albertel 6440:     Fetches the requested bubble sheet data file (all 3 versions), and
                   6441:     the scan_data hash
                   6442:   
                   6443:   Arguments:
                   6444:     None
                   6445: 
                   6446:   Returns:
                   6447:     2 hash references
                   6448: 
                   6449:      - first one has 
                   6450:          orig      -
                   6451:          corrected -
                   6452:          skipped   -  each of which points to an array ref of the specified
                   6453:                       file broken up into individual lines
                   6454:          count     - number of scanlines
                   6455:  
                   6456:      - second is the scan_data hash possible keys are
1.425     albertel 6457:        ($number refers to scanline numbered $number and thus the key affects
                   6458:         only that scanline
                   6459:         $bubline refers to the specific bubble line element and the aspects
                   6460:         refers to that specific bubble line element)
                   6461: 
                   6462:        $number.user - username:domain to use
                   6463:        $number.CODE_ignore_dup 
                   6464:                     - ignore the duplicate CODE error 
                   6465:        $number.useCODE
                   6466:                     - use the CODE in the scanline as is
                   6467:        $number.no_bubble.$bubline
                   6468:                     - it is valid that there is no bubbled in bubble
                   6469:                       at $number $bubline
                   6470:        remember_skipping
                   6471:                     - a frozen hash containing keys of $number and values
                   6472:                       of either 
                   6473:                         1 - we are on a 'do skipped records pass' and plan
                   6474:                             on processing this line
                   6475:                         2 - we are on a 'do skipped records pass' and this
                   6476:                             scanline has been marked to skip yet again
1.424     albertel 6477: 
1.423     albertel 6478: =cut
                   6479: 
1.157     albertel 6480: sub scantron_getfile {
1.200     albertel 6481:     #FIXME really would prefer a scantron directory
1.257     albertel 6482:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   6483:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.157     albertel 6484:     my $lines;
                   6485:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
1.257     albertel 6486: 		       'scantron_orig_'.$env{'form.scantron_selectfile'});
1.157     albertel 6487:     my %scanlines;
                   6488:     $scanlines{'orig'}=[(split("\n",$lines,-1))];
                   6489:     my $temp=$scanlines{'orig'};
                   6490:     $scanlines{'count'}=$#$temp;
                   6491: 
                   6492:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
1.257     albertel 6493: 		       'scantron_corrected_'.$env{'form.scantron_selectfile'});
1.157     albertel 6494:     if ($lines eq '-1') {
                   6495: 	$scanlines{'corrected'}=[];
                   6496:     } else {
                   6497: 	$scanlines{'corrected'}=[(split("\n",$lines,-1))];
                   6498:     }
                   6499:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
1.257     albertel 6500: 		       'scantron_skipped_'.$env{'form.scantron_selectfile'});
1.157     albertel 6501:     if ($lines eq '-1') {
                   6502: 	$scanlines{'skipped'}=[];
                   6503:     } else {
                   6504: 	$scanlines{'skipped'}=[(split("\n",$lines,-1))];
                   6505:     }
1.175     albertel 6506:     my @tmp=&Apache::lonnet::dump('nohist_scantrondata',$cdom,$cname);
1.157     albertel 6507:     if ($tmp[0] =~ /^(error:|no_such_host)/) { @tmp=(); }
                   6508:     my %scan_data = @tmp;
                   6509:     return (\%scanlines,\%scan_data);
                   6510: }
                   6511: 
1.423     albertel 6512: =pod
                   6513: 
                   6514: =item lonnet_putfile
                   6515: 
1.424     albertel 6516:    Wrapper routine to call &Apache::lonnet::finishuserfileupload
                   6517: 
                   6518:  Arguments:
                   6519:    $contents - data to store
                   6520:    $filename - filename to store $contents into
                   6521: 
                   6522:  Returns:
                   6523:    result value from &Apache::lonnet::finishuserfileupload
                   6524: 
1.423     albertel 6525: =cut
                   6526: 
1.157     albertel 6527: sub lonnet_putfile {
                   6528:     my ($contents,$filename)=@_;
1.257     albertel 6529:     my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   6530:     my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   6531:     $env{'form.sillywaytopassafilearound'}=$contents;
1.275     albertel 6532:     &Apache::lonnet::finishuserfileupload($docuname,$docudom,'sillywaytopassafilearound',$filename);
1.157     albertel 6533: 
                   6534: }
                   6535: 
1.423     albertel 6536: =pod
                   6537: 
                   6538: =item scantron_putfile
                   6539: 
1.424     albertel 6540:     Stores the current version of the bubble sheet data files, and the
                   6541:     scan_data hash. (Does not modify the original version only the
                   6542:     corrected and skipped versions.
                   6543: 
                   6544:  Arguments:
                   6545:     $scanlines - hash ref that looks like the first return value from
                   6546:                  &scantron_getfile()
                   6547:     $scan_data - hash ref that looks like the second return value from
                   6548:                  &scantron_getfile()
                   6549: 
1.423     albertel 6550: =cut
                   6551: 
1.157     albertel 6552: sub scantron_putfile {
                   6553:     my ($scanlines,$scan_data) = @_;
1.200     albertel 6554:     #FIXME really would prefer a scantron directory
1.257     albertel 6555:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   6556:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.200     albertel 6557:     if ($scanlines) {
                   6558: 	my $prefix='scantron_';
1.157     albertel 6559: # no need to update orig, shouldn't change
                   6560: #   &lonnet_putfile(join("\n",@{$scanlines->{'orig'}}),$prefix.'orig_'.
1.257     albertel 6561: #		    $env{'form.scantron_selectfile'});
1.200     albertel 6562: 	&lonnet_putfile(join("\n",@{$scanlines->{'corrected'}}),
                   6563: 			$prefix.'corrected_'.
1.257     albertel 6564: 			$env{'form.scantron_selectfile'});
1.200     albertel 6565: 	&lonnet_putfile(join("\n",@{$scanlines->{'skipped'}}),
                   6566: 			$prefix.'skipped_'.
1.257     albertel 6567: 			$env{'form.scantron_selectfile'});
1.200     albertel 6568:     }
1.175     albertel 6569:     &Apache::lonnet::put('nohist_scantrondata',$scan_data,$cdom,$cname);
1.157     albertel 6570: }
                   6571: 
1.423     albertel 6572: =pod
                   6573: 
                   6574: =item scantron_get_line
                   6575: 
1.424     albertel 6576:    Returns the correct version of the scanline
                   6577: 
                   6578:  Arguments:
                   6579:     $scanlines - hash ref that looks like the first return value from
                   6580:                  &scantron_getfile()
                   6581:     $scan_data - hash ref that looks like the second return value from
                   6582:                  &scantron_getfile()
                   6583:     $i         - number of the requested line (starts at 0)
                   6584: 
                   6585:  Returns:
                   6586:    A scanline, (either the original or the corrected one if it
                   6587:    exists), or undef if the requested scanline should be
                   6588:    skipped. (Either because it's an skipped scanline, or it's an
                   6589:    unskipped scanline and we are not doing a 'do skipped scanlines'
                   6590:    pass.
                   6591: 
1.423     albertel 6592: =cut
                   6593: 
1.157     albertel 6594: sub scantron_get_line {
1.200     albertel 6595:     my ($scanlines,$scan_data,$i)=@_;
1.376     albertel 6596:     if (&should_be_skipped($scanlines,$scan_data,$i)) { return undef; }
                   6597:     #if ($scanlines->{'skipped'}[$i]) { return undef; }
1.157     albertel 6598:     if ($scanlines->{'corrected'}[$i]) {return $scanlines->{'corrected'}[$i];}
                   6599:     return $scanlines->{'orig'}[$i]; 
                   6600: }
                   6601: 
1.423     albertel 6602: =pod
                   6603: 
                   6604: =item scantron_todo_count
                   6605: 
1.424     albertel 6606:     Counts the number of scanlines that need processing.
                   6607: 
                   6608:  Arguments:
                   6609:     $scanlines - hash ref that looks like the first return value from
                   6610:                  &scantron_getfile()
                   6611:     $scan_data - hash ref that looks like the second return value from
                   6612:                  &scantron_getfile()
                   6613: 
                   6614:  Returns:
                   6615:     $count - number of scanlines to process
                   6616: 
1.423     albertel 6617: =cut
                   6618: 
1.200     albertel 6619: sub get_todo_count {
                   6620:     my ($scanlines,$scan_data)=@_;
                   6621:     my $count=0;
                   6622:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
                   6623: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
                   6624: 	if ($line=~/^[\s\cz]*$/) { next; }
                   6625: 	$count++;
                   6626:     }
                   6627:     return $count;
                   6628: }
                   6629: 
1.423     albertel 6630: =pod
                   6631: 
                   6632: =item scantron_put_line
                   6633: 
1.424     albertel 6634:     Updates the 'corrected' or 'skipped' versions of the bubble sheet
                   6635:     data file.
                   6636: 
                   6637:  Arguments:
                   6638:     $scanlines - hash ref that looks like the first return value from
                   6639:                  &scantron_getfile()
                   6640:     $scan_data - hash ref that looks like the second return value from
                   6641:                  &scantron_getfile()
                   6642:     $i         - line number to update
                   6643:     $newline   - contents of the updated scanline
                   6644:     $skip      - if true make the line for skipping and update the
                   6645:                  'skipped' file
                   6646: 
1.423     albertel 6647: =cut
                   6648: 
1.157     albertel 6649: sub scantron_put_line {
1.200     albertel 6650:     my ($scanlines,$scan_data,$i,$newline,$skip)=@_;
1.157     albertel 6651:     if ($skip) {
                   6652: 	$scanlines->{'skipped'}[$i]=$newline;
1.376     albertel 6653: 	&start_skipping($scan_data,$i);
1.157     albertel 6654: 	return;
                   6655:     }
                   6656:     $scanlines->{'corrected'}[$i]=$newline;
                   6657: }
                   6658: 
1.423     albertel 6659: =pod
                   6660: 
                   6661: =item scantron_clear_skip
                   6662: 
1.424     albertel 6663:    Remove a line from the 'skipped' file
                   6664: 
                   6665:  Arguments:
                   6666:     $scanlines - hash ref that looks like the first return value from
                   6667:                  &scantron_getfile()
                   6668:     $scan_data - hash ref that looks like the second return value from
                   6669:                  &scantron_getfile()
                   6670:     $i         - line number to update
                   6671: 
1.423     albertel 6672: =cut
                   6673: 
1.376     albertel 6674: sub scantron_clear_skip {
                   6675:     my ($scanlines,$scan_data,$i)=@_;
                   6676:     if (exists($scanlines->{'skipped'}[$i])) {
                   6677: 	undef($scanlines->{'skipped'}[$i]);
                   6678: 	return 1;
                   6679:     }
                   6680:     return 0;
                   6681: }
                   6682: 
1.423     albertel 6683: =pod
                   6684: 
                   6685: =item scantron_filter_not_exam
                   6686: 
1.424     albertel 6687:    Filter routine used by &Apache::lonnavmaps::retrieveResources(), to
                   6688:    filter out resources that are not marked as 'exam' mode
                   6689: 
1.423     albertel 6690: =cut
                   6691: 
1.334     albertel 6692: sub scantron_filter_not_exam {
                   6693:     my ($curres)=@_;
                   6694:     
                   6695:     if (ref($curres) && $curres->is_problem() && !$curres->is_exam()) {
                   6696: 	# if the user has asked to not have either hidden
                   6697: 	# or 'randomout' controlled resources to be graded
                   6698: 	# don't include them
                   6699: 	if ($env{'form.scantron_options_hidden'} eq 'ignore_hidden'
                   6700: 	    && $curres->randomout) {
                   6701: 	    return 0;
                   6702: 	}
                   6703: 	return 1;
                   6704:     }
                   6705:     return 0;
                   6706: }
                   6707: 
1.423     albertel 6708: =pod
                   6709: 
                   6710: =item scantron_validate_sequence
                   6711: 
1.424     albertel 6712:     Validates the selected sequence, checking for resource that are
                   6713:     not set to exam mode.
                   6714: 
1.423     albertel 6715: =cut
                   6716: 
1.334     albertel 6717: sub scantron_validate_sequence {
                   6718:     my ($r,$currentphase) = @_;
                   6719: 
                   6720:     my $navmap=Apache::lonnavmaps::navmap->new();
1.582     raeburn  6721:     unless (ref($navmap)) {
                   6722:         $r->print(&navmap_errormsg());
                   6723:         return (1,$currentphase);
                   6724:     }
1.334     albertel 6725:     my (undef,undef,$sequence)=
                   6726: 	&Apache::lonnet::decode_symb($env{'form.selectpage'});
                   6727: 
                   6728:     my $map=$navmap->getResourceByUrl($sequence);
                   6729: 
                   6730:     $r->print('<input type="hidden" name="validate_sequence_exam"
                   6731:                                     value="ignore" />');
                   6732:     if ($env{'form.validate_sequence_exam'} ne 'ignore') {
                   6733: 	my @resources=
                   6734: 	    $navmap->retrieveResources($map,\&scantron_filter_not_exam,1,0);
                   6735: 	if (@resources) {
1.357     banghart 6736: 	    $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 6737: 	    return (1,$currentphase);
                   6738: 	}
                   6739:     }
                   6740: 
                   6741:     return (0,$currentphase+1);
                   6742: }
                   6743: 
1.423     albertel 6744: 
                   6745: 
1.157     albertel 6746: sub scantron_validate_ID {
                   6747:     my ($r,$currentphase) = @_;
                   6748:     
                   6749:     #get student info
                   6750:     my $classlist=&Apache::loncoursedata::get_classlist();
                   6751:     my %idmap=&username_to_idmap($classlist);
                   6752: 
                   6753:     #get scantron line setup
1.257     albertel 6754:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.157     albertel 6755:     my ($scanlines,$scan_data)=&scantron_getfile();
1.582     raeburn  6756: 
                   6757:     my $nav_error;
                   6758:     &scantron_get_maxbubble(\$nav_error); # parse needs the bubble_lines.. array.
                   6759:     if ($nav_error) {
                   6760:         $r->print(&navmap_errormsg());
                   6761:         return(1,$currentphase);
                   6762:     }
1.157     albertel 6763: 
                   6764:     my %found=('ids'=>{},'usernames'=>{});
                   6765:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
1.200     albertel 6766: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.157     albertel 6767: 	if ($line=~/^[\s\cz]*$/) { next; }
                   6768: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
                   6769: 						 $scan_data);
                   6770: 	my $id=$$scan_record{'scantron.ID'};
                   6771: 	my $found;
                   6772: 	foreach my $checkid (keys(%idmap)) {
                   6773: 	    if (lc($checkid) eq lc($id)) { $found=$checkid;last; }
                   6774: 	}
                   6775: 	if ($found) {
                   6776: 	    my $username=$idmap{$found};
                   6777: 	    if ($found{'ids'}{$found}) {
                   6778: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
                   6779: 					 $line,'duplicateID',$found);
1.194     albertel 6780: 		return(1,$currentphase);
1.157     albertel 6781: 	    } elsif ($found{'usernames'}{$username}) {
                   6782: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
                   6783: 					 $line,'duplicateID',$username);
1.194     albertel 6784: 		return(1,$currentphase);
1.157     albertel 6785: 	    }
1.186     albertel 6786: 	    #FIXME store away line we previously saw the ID on to use above
1.157     albertel 6787: 	    $found{'ids'}{$found}++;
                   6788: 	    $found{'usernames'}{$username}++;
                   6789: 	} else {
                   6790: 	    if ($id =~ /^\s*$/) {
1.158     albertel 6791: 		my $username=&scan_data($scan_data,"$i.user");
1.157     albertel 6792: 		if (defined($username) && $found{'usernames'}{$username}) {
                   6793: 		    &scantron_get_correction($r,$i,$scan_record,
                   6794: 					     \%scantron_config,
                   6795: 					     $line,'duplicateID',$username);
1.194     albertel 6796: 		    return(1,$currentphase);
1.157     albertel 6797: 		} elsif (!defined($username)) {
                   6798: 		    &scantron_get_correction($r,$i,$scan_record,
                   6799: 					     \%scantron_config,
                   6800: 					     $line,'incorrectID');
1.194     albertel 6801: 		    return(1,$currentphase);
1.157     albertel 6802: 		}
                   6803: 		$found{'usernames'}{$username}++;
                   6804: 	    } else {
                   6805: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
                   6806: 					 $line,'incorrectID');
1.194     albertel 6807: 		return(1,$currentphase);
1.157     albertel 6808: 	    }
                   6809: 	}
                   6810:     }
                   6811: 
                   6812:     return (0,$currentphase+1);
                   6813: }
                   6814: 
1.423     albertel 6815: 
1.157     albertel 6816: sub scantron_get_correction {
                   6817:     my ($r,$i,$scan_record,$scan_config,$line,$error,$arg)=@_;
1.454     banghart 6818: #FIXME in the case of a duplicated ID the previous line, probably need
1.157     albertel 6819: #to show both the current line and the previous one and allow skipping
                   6820: #the previous one or the current one
                   6821: 
1.333     albertel 6822:     if ( $$scan_record{'scantron.PaperID'} =~ /\S/) {
1.492     albertel 6823: 	$r->print("<p>".&mt("<b>An error was detected ($error)</b>".
                   6824: 			    " for PaperID <tt>[_1]</tt>",
                   6825: 			    $$scan_record{'scantron.PaperID'})."</p> \n");
1.157     albertel 6826:     } else {
1.492     albertel 6827: 	$r->print("<p>".&mt("<b>An error was detected ($error)</b>".
                   6828: 			    " in scanline [_1] <pre>[_2]</pre>",
                   6829: 			    $i,$line)."</p> \n");
                   6830:     }
                   6831:     my $message="<p>".&mt("The ID on the form is  <tt>[_1]</tt><br />".
                   6832: 			  "The name on the paper is [_2],[_3]",
                   6833: 			  $$scan_record{'scantron.ID'},
                   6834: 			  $$scan_record{'scantron.LastName'},
                   6835: 			  $$scan_record{'scantron.FirstName'})."</p>";
1.242     albertel 6836: 
1.157     albertel 6837:     $r->print('<input type="hidden" name="scantron_corrections" value="'.$error.'" />'."\n");
                   6838:     $r->print('<input type="hidden" name="scantron_line" value="'.$i.'" />'."\n");
1.503     raeburn  6839:                            # Array populated for doublebubble or
                   6840:     my @lines_to_correct;  # missingbubble errors to build javascript
                   6841:                            # to validate radio button checking   
                   6842: 
1.157     albertel 6843:     if ($error =~ /ID$/) {
1.186     albertel 6844: 	if ($error eq 'incorrectID') {
1.492     albertel 6845: 	    $r->print("<p>".&mt("The encoded ID is not in the classlist").
                   6846: 		      "</p>\n");
1.157     albertel 6847: 	} elsif ($error eq 'duplicateID') {
1.492     albertel 6848: 	    $r->print("<p>".&mt("The encoded ID has also been used by a previous paper [_1]",$arg)."</p>\n");
1.157     albertel 6849: 	}
1.242     albertel 6850: 	$r->print($message);
1.492     albertel 6851: 	$r->print("<p>".&mt("How should I handle this?")." <br /> \n");
1.157     albertel 6852: 	$r->print("\n<ul><li> ");
                   6853: 	#FIXME it would be nice if this sent back the user ID and
                   6854: 	#could do partial userID matches
                   6855: 	$r->print(&Apache::loncommon::selectstudent_link('scantronupload',
                   6856: 				       'scantron_username','scantron_domain'));
                   6857: 	$r->print(": <input type='text' name='scantron_username' value='' />");
                   6858: 	$r->print("\n@".
1.257     albertel 6859: 		 &Apache::loncommon::select_dom_form($env{'request.role.domain'},'scantron_domain'));
1.157     albertel 6860: 
                   6861: 	$r->print('</li>');
1.186     albertel 6862:     } elsif ($error =~ /CODE$/) {
                   6863: 	if ($error eq 'incorrectCODE') {
1.492     albertel 6864: 	    $r->print("<p>".&mt("The encoded CODE is not in the list of possible CODEs.")."</p>\n");
1.186     albertel 6865: 	} elsif ($error eq 'duplicateCODE') {
1.492     albertel 6866: 	    $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 6867: 	}
1.492     albertel 6868: 	$r->print("<p>".&mt("The CODE on the form is  <tt>'[_1]'</tt>",
                   6869: 			    $$scan_record{'scantron.CODE'})."<br />\n");
1.242     albertel 6870: 	$r->print($message);
1.492     albertel 6871: 	$r->print("<p>".&mt("How should I handle this?")." <br /> \n");
1.187     albertel 6872: 	$r->print("\n<br /> ");
1.194     albertel 6873: 	my $i=0;
1.273     albertel 6874: 	if ($error eq 'incorrectCODE' 
                   6875: 	    && $$scan_record{'scantron.CODE'}=~/\S/ ) {
1.194     albertel 6876: 	    my ($max,$closest)=&scantron_get_closely_matching_CODEs($arg,$$scan_record{'scantron.CODE'});
1.278     albertel 6877: 	    if ($closest > 0) {
                   6878: 		foreach my $testcode (@{$closest}) {
                   6879: 		    my $checked='';
1.569     bisitz   6880: 		    if (!$i) { $checked=' checked="checked"'; }
1.492     albertel 6881: 		    $r->print("
                   6882:    <label>
1.569     bisitz   6883:        <input type='radio' name='scantron_CODE_resolution' value='use_closest_$i'$checked />
1.492     albertel 6884:        ".&mt("Use the similar CODE [_1] instead.",
                   6885: 	    "<b><tt>".$testcode."</tt></b>")."
                   6886:     </label>
                   6887:     <input type='hidden' name='scantron_CODE_closest_$i' value='$testcode' />");
1.278     albertel 6888: 		    $r->print("\n<br />");
                   6889: 		    $i++;
                   6890: 		}
1.194     albertel 6891: 	    }
                   6892: 	}
1.273     albertel 6893: 	if ($$scan_record{'scantron.CODE'}=~/\S/ ) {
1.569     bisitz   6894: 	    my $checked; if (!$i) { $checked=' checked="checked"'; }
1.492     albertel 6895: 	    $r->print("
                   6896:     <label>
1.569     bisitz   6897:         <input type='radio' name='scantron_CODE_resolution' value='use_unfound'$checked />
1.492     albertel 6898:        ".&mt("Use the CODE [_1] that is was on the paper, ignoring the error.",
                   6899: 	     "<b><tt>".$$scan_record{'scantron.CODE'}."</tt></b>")."
                   6900:     </label>");
1.273     albertel 6901: 	    $r->print("\n<br />");
                   6902: 	}
1.194     albertel 6903: 
1.597     wenzelju 6904: 	$r->print(&Apache::lonhtmlcommon::scripttag(<<ENDSCRIPT));
1.188     albertel 6905: function change_radio(field) {
1.190     albertel 6906:     var slct=document.scantronupload.scantron_CODE_resolution;
1.188     albertel 6907:     var i;
                   6908:     for (i=0;i<slct.length;i++) {
                   6909:         if (slct[i].value==field) { slct[i].checked=true; }
                   6910:     }
                   6911: }
                   6912: ENDSCRIPT
1.187     albertel 6913: 	my $href="/adm/pickcode?".
1.359     www      6914: 	   "form=".&escape("scantronupload").
                   6915: 	   "&scantron_format=".&escape($env{'form.scantron_format'}).
                   6916: 	   "&scantron_CODElist=".&escape($env{'form.scantron_CODElist'}).
                   6917: 	   "&curCODE=".&escape($$scan_record{'scantron.CODE'}).
                   6918: 	   "&scantron_selectfile=".&escape($env{'form.scantron_selectfile'});
1.332     albertel 6919: 	if ($env{'form.scantron_CODElist'} =~ /\S/) { 
1.492     albertel 6920: 	    $r->print("
                   6921:     <label>
                   6922:        <input type='radio' name='scantron_CODE_resolution' value='use_found' />
                   6923:        ".&mt("[_1]Select[_2] a CODE from the list of all CODEs and use it.",
                   6924: 	     "<a target='_blank' href='$href'>","</a>")."
                   6925:     </label> 
1.558     bisitz   6926:     ".&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 6927: 	    $r->print("\n<br />");
                   6928: 	}
1.492     albertel 6929: 	$r->print("
                   6930:     <label>
                   6931:        <input type='radio' name='scantron_CODE_resolution' value='use_typed' />
                   6932:        ".&mt("Use [_1] as the CODE.",
                   6933: 	     "</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 6934: 	$r->print("\n<br /><br />");
1.157     albertel 6935:     } elsif ($error eq 'doublebubble') {
1.503     raeburn  6936: 	$r->print("<p>".&mt("There have been multiple bubbles scanned for some question(s)")."</p>\n");
1.497     foxr     6937: 
                   6938: 	# The form field scantron_questions is acutally a list of line numbers.
                   6939: 	# represented by this form so:
                   6940: 
                   6941: 	my $line_list = &questions_to_line_list($arg);
                   6942: 
1.157     albertel 6943: 	$r->print('<input type="hidden" name="scantron_questions" value="'.
1.497     foxr     6944: 		  $line_list.'" />');
1.242     albertel 6945: 	$r->print($message);
1.492     albertel 6946: 	$r->print("<p>".&mt("Please indicate which bubble should be used for grading")."</p>");
1.157     albertel 6947: 	foreach my $question (@{$arg}) {
1.503     raeburn  6948: 	    my @linenums = &prompt_for_corrections($r,$question,$scan_config,
                   6949:                                                    $scan_record, $error);
1.524     raeburn  6950:             push(@lines_to_correct,@linenums);
1.157     albertel 6951: 	}
1.503     raeburn  6952:         $r->print(&verify_bubbles_checked(@lines_to_correct));
1.157     albertel 6953:     } elsif ($error eq 'missingbubble') {
1.492     albertel 6954: 	$r->print("<p>".&mt("There have been <b>no</b> bubbles scanned for some question(s)")."</p>\n");
1.242     albertel 6955: 	$r->print($message);
1.492     albertel 6956: 	$r->print("<p>".&mt("Please indicate which bubble should be used for grading.")."</p>");
1.503     raeburn  6957: 	$r->print(&mt("Some questions have no scanned bubbles.")."\n");
1.497     foxr     6958: 
1.503     raeburn  6959: 	# The form field scantron_questions is actually a list of line numbers not
1.497     foxr     6960: 	# a list of question numbers. Therefore:
                   6961: 	#
                   6962: 	
                   6963: 	my $line_list = &questions_to_line_list($arg);
                   6964: 
1.157     albertel 6965: 	$r->print('<input type="hidden" name="scantron_questions" value="'.
1.497     foxr     6966: 		  $line_list.'" />');
1.157     albertel 6967: 	foreach my $question (@{$arg}) {
1.503     raeburn  6968: 	    my @linenums = &prompt_for_corrections($r,$question,$scan_config,
                   6969:                                                    $scan_record, $error);
1.524     raeburn  6970:             push(@lines_to_correct,@linenums);
1.157     albertel 6971: 	}
1.503     raeburn  6972:         $r->print(&verify_bubbles_checked(@lines_to_correct));
1.157     albertel 6973:     } else {
                   6974: 	$r->print("\n<ul>");
                   6975:     }
                   6976:     $r->print("\n</li></ul>");
1.497     foxr     6977: }
                   6978: 
1.503     raeburn  6979: sub verify_bubbles_checked {
                   6980:     my (@ansnums) = @_;
                   6981:     my $ansnumstr = join('","',@ansnums);
                   6982:     my $warning = &mt("A bubble or 'No bubble' selection has not been made for one or more lines.");
1.597     wenzelju 6983:     my $output = &Apache::lonhtmlcommon::scripttag((<<ENDSCRIPT));
1.503     raeburn  6984: function verify_bubble_radio(form) {
                   6985:     var ansnumArray = new Array ("$ansnumstr");
                   6986:     var need_bubble_count = 0;
                   6987:     for (var i=0; i<ansnumArray.length; i++) {
                   6988:         if (form.elements["scantron_correct_Q_"+ansnumArray[i]].length > 1) {
                   6989:             var bubble_picked = 0; 
                   6990:             for (var j=0; j<form.elements["scantron_correct_Q_"+ansnumArray[i]].length; j++) {
                   6991:                 if (form.elements["scantron_correct_Q_"+ansnumArray[i]][j].checked == true) {
                   6992:                     bubble_picked = 1;
                   6993:                 }
                   6994:             }
                   6995:             if (bubble_picked == 0) {
                   6996:                 need_bubble_count ++;
                   6997:             }
                   6998:         }
                   6999:     }
                   7000:     if (need_bubble_count) {
                   7001:         alert("$warning");
                   7002:         return;
                   7003:     }
                   7004:     form.submit(); 
                   7005: }
                   7006: ENDSCRIPT
                   7007:     return $output;
                   7008: }
                   7009: 
1.497     foxr     7010: =pod
                   7011: 
                   7012: =item  questions_to_line_list
1.157     albertel 7013: 
1.497     foxr     7014: Converts a list of questions into a string of comma separated
                   7015: line numbers in the answer sheet used by the questions.  This is
                   7016: used to fill in the scantron_questions form field.
                   7017: 
                   7018:   Arguments:
                   7019:      questions    - Reference to an array of questions.
                   7020: 
                   7021: =cut
                   7022: 
                   7023: 
                   7024: sub questions_to_line_list {
                   7025:     my ($questions) = @_;
                   7026:     my @lines;
                   7027: 
1.503     raeburn  7028:     foreach my $item (@{$questions}) {
                   7029:         my $question = $item;
                   7030:         my ($first,$count,$last);
                   7031:         if ($item =~ /^(\d+)\.(\d+)$/) {
                   7032:             $question = $1;
                   7033:             my $subquestion = $2;
                   7034:             $first = $first_bubble_line{$question-1} + 1;
                   7035:             my @subans = split(/,/,$subdivided_bubble_lines{$question-1});
                   7036:             my $subcount = 1;
                   7037:             while ($subcount<$subquestion) {
                   7038:                 $first += $subans[$subcount-1];
                   7039:                 $subcount ++;
                   7040:             }
                   7041:             $count = $subans[$subquestion-1];
                   7042:         } else {
                   7043: 	    $first   = $first_bubble_line{$question-1} + 1;
                   7044: 	    $count   = $bubble_lines_per_response{$question-1};
                   7045:         }
1.506     raeburn  7046:         $last = $first+$count-1;
1.503     raeburn  7047:         push(@lines, ($first..$last));
1.497     foxr     7048:     }
                   7049:     return join(',', @lines);
                   7050: }
                   7051: 
                   7052: =pod 
                   7053: 
                   7054: =item prompt_for_corrections
                   7055: 
                   7056: Prompts for a potentially multiline correction to the
                   7057: user's bubbling (factors out common code from scantron_get_correction
                   7058: for multi and missing bubble cases).
                   7059: 
                   7060:  Arguments:
                   7061:    $r           - Apache request object.
                   7062:    $question    - The question number to prompt for.
                   7063:    $scan_config - The scantron file configuration hash.
                   7064:    $scan_record - Reference to the hash that has the the parsed scanlines.
1.503     raeburn  7065:    $error       - Type of error
1.497     foxr     7066: 
                   7067:  Implicit inputs:
                   7068:    %bubble_lines_per_response   - Starting line numbers for each question.
                   7069:                                   Numbered from 0 (but question numbers are from
                   7070:                                   1.
                   7071:    %first_bubble_line           - Starting bubble line for each question.
1.509     raeburn  7072:    %subdivided_bubble_lines     - optionresponse, matchresponse and rankresponse 
                   7073:                                   type problems render as separate sub-questions, 
1.503     raeburn  7074:                                   in exam mode. This hash contains a 
                   7075:                                   comma-separated list of the lines per 
                   7076:                                   sub-question.
1.510     raeburn  7077:    %responsetype_per_response   - essayresponse, formularesponse,
                   7078:                                   stringresponse, imageresponse, reactionresponse,
                   7079:                                   and organicresponse type problem parts can have
1.503     raeburn  7080:                                   multiple lines per response if the weight
                   7081:                                   assigned exceeds 10.  In this case, only
                   7082:                                   one bubble per line is permitted, but more 
                   7083:                                   than one line might contain bubbles, e.g.
                   7084:                                   bubbling of: line 1 - J, line 2 - J, 
                   7085:                                   line 3 - B would assign 22 points.  
1.497     foxr     7086: 
                   7087: =cut
                   7088: 
                   7089: sub prompt_for_corrections {
1.503     raeburn  7090:     my ($r, $question, $scan_config, $scan_record, $error) = @_;
                   7091:     my ($current_line,$lines);
                   7092:     my @linenums;
                   7093:     my $questionnum = $question;
                   7094:     if ($question =~ /^(\d+)\.(\d+)$/) {
                   7095:         $question = $1;
                   7096:         $current_line = $first_bubble_line{$question-1} + 1 ;
                   7097:         my $subquestion = $2;
                   7098:         my @subans = split(/,/,$subdivided_bubble_lines{$question-1});
                   7099:         my $subcount = 1;
                   7100:         while ($subcount<$subquestion) {
                   7101:             $current_line += $subans[$subcount-1];
                   7102:             $subcount ++;
                   7103:         }
                   7104:         $lines = $subans[$subquestion-1];
                   7105:     } else {
                   7106:         $current_line = $first_bubble_line{$question-1} + 1 ;
                   7107:         $lines        = $bubble_lines_per_response{$question-1};
                   7108:     }
1.497     foxr     7109:     if ($lines > 1) {
1.503     raeburn  7110:         $r->print(&mt('The group of bubble lines below responds to a single question.').'<br />');
                   7111:         if (($responsetype_per_response{$question-1} eq 'essayresponse') ||
                   7112:             ($responsetype_per_response{$question-1} eq 'formularesponse') ||
1.510     raeburn  7113:             ($responsetype_per_response{$question-1} eq 'stringresponse') ||
                   7114:             ($responsetype_per_response{$question-1} eq 'imageresponse') ||
                   7115:             ($responsetype_per_response{$question-1} eq 'reactionresponse') ||
                   7116:             ($responsetype_per_response{$question-1} eq 'organicresponse')) {
1.572     www      7117:             $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  7118:         } else {
                   7119:             $r->print(&mt("Select at most one bubble in a single line and select 'No Bubble' in all the other lines. ")."<br />");
                   7120:         }
1.497     foxr     7121:     }
                   7122:     for (my $i =0; $i < $lines; $i++) {
1.503     raeburn  7123:         my $selected = $$scan_record{"scantron.$current_line.answer"};
                   7124: 	&scantron_bubble_selector($r,$scan_config,$current_line, 
                   7125: 	        		  $questionnum,$error,split('', $selected));
1.524     raeburn  7126:         push(@linenums,$current_line);
1.497     foxr     7127: 	$current_line++;
                   7128:     }
                   7129:     if ($lines > 1) {
                   7130: 	$r->print("<hr /><br />");
                   7131:     }
1.503     raeburn  7132:     return @linenums;
1.157     albertel 7133: }
1.423     albertel 7134: 
                   7135: =pod
                   7136: 
                   7137: =item scantron_bubble_selector
                   7138:   
                   7139:    Generates the html radiobuttons to correct a single bubble line
1.424     albertel 7140:    possibly showing the existing the selected bubbles if known
1.423     albertel 7141: 
                   7142:  Arguments:
                   7143:     $r           - Apache request object
                   7144:     $scan_config - hash from &get_scantron_config()
1.497     foxr     7145:     $line        - Number of the line being displayed.
1.503     raeburn  7146:     $questionnum - Question number (may include subquestion)
                   7147:     $error       - Type of error.
1.497     foxr     7148:     @selected    - Array of bubbles picked on this line.
1.423     albertel 7149: 
                   7150: =cut
                   7151: 
1.157     albertel 7152: sub scantron_bubble_selector {
1.503     raeburn  7153:     my ($r,$scan_config,$line,$questionnum,$error,@selected)=@_;
1.157     albertel 7154:     my $max=$$scan_config{'Qlength'};
1.274     albertel 7155: 
                   7156:     my $scmode=$$scan_config{'Qon'};
                   7157:     if ($scmode eq 'number' || $scmode eq 'letter') { $max=10; }	     
                   7158: 
1.157     albertel 7159:     my @alphabet=('A'..'Z');
1.503     raeburn  7160:     $r->print(&Apache::loncommon::start_data_table().
                   7161:               &Apache::loncommon::start_data_table_row());
                   7162:     $r->print('<td rowspan="2" class="LC_leftcol_header">'.$line.'</td>');
1.497     foxr     7163:     for (my $i=0;$i<$max+1;$i++) {
                   7164: 	$r->print("\n".'<td align="center">');
                   7165: 	if ($selected[0] eq $alphabet[$i]) { $r->print('X'); shift(@selected) }
                   7166: 	else { $r->print('&nbsp;'); }
                   7167: 	$r->print('</td>');
                   7168:     }
1.503     raeburn  7169:     $r->print(&Apache::loncommon::end_data_table_row().
                   7170:               &Apache::loncommon::start_data_table_row());
1.497     foxr     7171:     for (my $i=0;$i<$max;$i++) {
                   7172: 	$r->print("\n".
                   7173: 		  '<td><label><input type="radio" name="scantron_correct_Q_'.
                   7174: 		  $line.'" value="'.$i.'" />'.$alphabet[$i]."</label></td>");
                   7175:     }
1.503     raeburn  7176:     my $nobub_checked = ' ';
                   7177:     if ($error eq 'missingbubble') {
                   7178:         $nobub_checked = ' checked = "checked" ';
                   7179:     }
                   7180:     $r->print("\n".'<td><label><input type="radio" name="scantron_correct_Q_'.
                   7181: 	      $line.'" value="none"'.$nobub_checked.'/>'.&mt('No bubble').
                   7182:               '</label>'."\n".'<input type="hidden" name="scantron_questionnum_Q_'.
                   7183:               $line.'" value="'.$questionnum.'" /></td>');
                   7184:     $r->print(&Apache::loncommon::end_data_table_row().
                   7185:               &Apache::loncommon::end_data_table());
1.157     albertel 7186: }
                   7187: 
1.423     albertel 7188: =pod
                   7189: 
                   7190: =item num_matches
                   7191: 
1.424     albertel 7192:    Counts the number of characters that are the same between the two arguments.
                   7193: 
                   7194:  Arguments:
                   7195:    $orig - CODE from the scanline
                   7196:    $code - CODE to match against
                   7197: 
                   7198:  Returns:
                   7199:    $count - integer count of the number of same characters between the
                   7200:             two arguments
                   7201: 
1.423     albertel 7202: =cut
                   7203: 
1.194     albertel 7204: sub num_matches {
                   7205:     my ($orig,$code) = @_;
                   7206:     my @code=split(//,$code);
                   7207:     my @orig=split(//,$orig);
                   7208:     my $same=0;
                   7209:     for (my $i=0;$i<scalar(@code);$i++) {
                   7210: 	if ($code[$i] eq $orig[$i]) { $same++; }
                   7211:     }
                   7212:     return $same;
                   7213: }
                   7214: 
1.423     albertel 7215: =pod
                   7216: 
                   7217: =item scantron_get_closely_matching_CODEs
                   7218: 
1.424     albertel 7219:    Cycles through all CODEs and finds the set that has the greatest
                   7220:    number of same characters as the provided CODE
                   7221: 
                   7222:  Arguments:
                   7223:    $allcodes - hash ref returned by &get_codes()
                   7224:    $CODE     - CODE from the current scanline
                   7225: 
                   7226:  Returns:
                   7227:    2 element list
                   7228:     - first elements is number of how closely matching the best fit is 
                   7229:       (5 means best set has 5 matching characters)
                   7230:     - second element is an arrary ref containing the set of valid CODEs
                   7231:       that best fit the passed in CODE
                   7232: 
1.423     albertel 7233: =cut
                   7234: 
1.194     albertel 7235: sub scantron_get_closely_matching_CODEs {
                   7236:     my ($allcodes,$CODE)=@_;
                   7237:     my @CODEs;
                   7238:     foreach my $testcode (sort(keys(%{$allcodes}))) {
                   7239: 	push(@{$CODEs[&num_matches($CODE,$testcode)]},$testcode);
                   7240:     }
                   7241: 
                   7242:     return ($#CODEs,$CODEs[-1]);
                   7243: }
                   7244: 
1.423     albertel 7245: =pod
                   7246: 
                   7247: =item get_codes
                   7248: 
1.424     albertel 7249:    Builds a hash which has keys of all of the valid CODEs from the selected
                   7250:    set of remembered CODEs.
                   7251: 
                   7252:  Arguments:
                   7253:   $old_name - name of the set of remembered CODEs
                   7254:   $cdom     - domain of the course
                   7255:   $cnum     - internal course name
                   7256: 
                   7257:  Returns:
                   7258:   %allcodes - keys are the valid CODEs, values are all 1
                   7259: 
1.423     albertel 7260: =cut
                   7261: 
1.194     albertel 7262: sub get_codes {
1.280     foxr     7263:     my ($old_name, $cdom, $cnum) = @_;
                   7264:     if (!$old_name) {
                   7265: 	$old_name=$env{'form.scantron_CODElist'};
                   7266:     }
                   7267:     if (!$cdom) {
                   7268: 	$cdom =$env{'course.'.$env{'request.course.id'}.'.domain'};
                   7269:     }
                   7270:     if (!$cnum) {
                   7271: 	$cnum =$env{'course.'.$env{'request.course.id'}.'.num'};
                   7272:     }
1.278     albertel 7273:     my %result=&Apache::lonnet::get('CODEs',[$old_name,"type\0$old_name"],
                   7274: 				    $cdom,$cnum);
                   7275:     my %allcodes;
                   7276:     if ($result{"type\0$old_name"} eq 'number') {
                   7277: 	%allcodes=map {($_,1)} split(',',$result{$old_name});
                   7278:     } else {
                   7279: 	%allcodes=map {(&Apache::lonprintout::num_to_letters($_),1)} split(',',$result{$old_name});
                   7280:     }
1.194     albertel 7281:     return %allcodes;
                   7282: }
                   7283: 
1.423     albertel 7284: =pod
                   7285: 
                   7286: =item scantron_validate_CODE
                   7287: 
1.424     albertel 7288:    Validates all scanlines in the selected file to not have any
                   7289:    invalid or underspecified CODEs and that none of the codes are
                   7290:    duplicated if this was requested.
                   7291: 
1.423     albertel 7292: =cut
                   7293: 
1.157     albertel 7294: sub scantron_validate_CODE {
                   7295:     my ($r,$currentphase) = @_;
1.257     albertel 7296:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.186     albertel 7297:     if ($scantron_config{'CODElocation'} &&
                   7298: 	$scantron_config{'CODEstart'} &&
                   7299: 	$scantron_config{'CODElength'}) {
1.257     albertel 7300: 	if (!defined($env{'form.scantron_CODElist'})) {
1.186     albertel 7301: 	    &FIXME_blow_up()
                   7302: 	}
                   7303:     } else {
                   7304: 	return (0,$currentphase+1);
                   7305:     }
                   7306:     
                   7307:     my %usedCODEs;
                   7308: 
1.194     albertel 7309:     my %allcodes=&get_codes();
1.186     albertel 7310: 
1.582     raeburn  7311:     my $nav_error;
                   7312:     &scantron_get_maxbubble(\$nav_error); # parse needs the lines per response array.
                   7313:     if ($nav_error) {
                   7314:         $r->print(&navmap_errormsg());
                   7315:         return(1,$currentphase);
                   7316:     }
1.447     foxr     7317: 
1.186     albertel 7318:     my ($scanlines,$scan_data)=&scantron_getfile();
                   7319:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
1.200     albertel 7320: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.186     albertel 7321: 	if ($line=~/^[\s\cz]*$/) { next; }
                   7322: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
                   7323: 						 $scan_data);
                   7324: 	my $CODE=$$scan_record{'scantron.CODE'};
                   7325: 	my $error=0;
1.224     albertel 7326: 	if (!&Apache::lonnet::validCODE($CODE)) {
                   7327: 	    &scantron_get_correction($r,$i,$scan_record,
                   7328: 				     \%scantron_config,
                   7329: 				     $line,'incorrectCODE',\%allcodes);
                   7330: 	    return(1,$currentphase);
                   7331: 	}
1.221     albertel 7332: 	if (%allcodes && !exists($allcodes{$CODE}) 
                   7333: 	    && !$$scan_record{'scantron.useCODE'}) {
1.186     albertel 7334: 	    &scantron_get_correction($r,$i,$scan_record,
                   7335: 				     \%scantron_config,
1.194     albertel 7336: 				     $line,'incorrectCODE',\%allcodes);
                   7337: 	    return(1,$currentphase);
1.186     albertel 7338: 	}
1.214     albertel 7339: 	if (exists($usedCODEs{$CODE}) 
1.257     albertel 7340: 	    && $env{'form.scantron_CODEunique'} eq 'yes'
1.192     albertel 7341: 	    && !$$scan_record{'scantron.CODE_ignore_dup'}) {
1.186     albertel 7342: 	    &scantron_get_correction($r,$i,$scan_record,
                   7343: 				     \%scantron_config,
1.194     albertel 7344: 				     $line,'duplicateCODE',$usedCODEs{$CODE});
                   7345: 	    return(1,$currentphase);
1.186     albertel 7346: 	}
1.524     raeburn  7347: 	push(@{$usedCODEs{$CODE}},$$scan_record{'scantron.PaperID'});
1.186     albertel 7348:     }
1.157     albertel 7349:     return (0,$currentphase+1);
                   7350: }
                   7351: 
1.423     albertel 7352: =pod
                   7353: 
                   7354: =item scantron_validate_doublebubble
                   7355: 
1.424     albertel 7356:    Validates all scanlines in the selected file to not have any
                   7357:    bubble lines with multiple bubbles marked.
                   7358: 
1.423     albertel 7359: =cut
                   7360: 
1.157     albertel 7361: sub scantron_validate_doublebubble {
                   7362:     my ($r,$currentphase) = @_;
                   7363:     #get student info
                   7364:     my $classlist=&Apache::loncoursedata::get_classlist();
                   7365:     my %idmap=&username_to_idmap($classlist);
                   7366: 
                   7367:     #get scantron line setup
1.257     albertel 7368:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.157     albertel 7369:     my ($scanlines,$scan_data)=&scantron_getfile();
1.583     raeburn  7370:     my $nav_error;
                   7371:     &scantron_get_maxbubble(\$nav_error); # parse needs the bubble line array.
                   7372:     if ($nav_error) {
                   7373:         $r->print(&navmap_errormsg());
                   7374:         return(1,$currentphase);
                   7375:     }
1.447     foxr     7376: 
1.157     albertel 7377:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
1.200     albertel 7378: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.157     albertel 7379: 	if ($line=~/^[\s\cz]*$/) { next; }
                   7380: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
                   7381: 						 $scan_data);
                   7382: 	if (!defined($$scan_record{'scantron.doubleerror'})) { next; }
                   7383: 	&scantron_get_correction($r,$i,$scan_record,\%scantron_config,$line,
                   7384: 				 'doublebubble',
                   7385: 				 $$scan_record{'scantron.doubleerror'});
                   7386:     	return (1,$currentphase);
                   7387:     }
                   7388:     return (0,$currentphase+1);
                   7389: }
                   7390: 
1.423     albertel 7391: 
1.503     raeburn  7392: sub scantron_get_maxbubble {
1.582     raeburn  7393:     my ($nav_error) = @_;
1.257     albertel 7394:     if (defined($env{'form.scantron_maxbubble'}) &&
                   7395: 	$env{'form.scantron_maxbubble'}) {
1.447     foxr     7396: 	&restore_bubble_lines();
1.257     albertel 7397: 	return $env{'form.scantron_maxbubble'};
1.191     albertel 7398:     }
1.330     albertel 7399: 
1.447     foxr     7400:     my (undef, undef, $sequence) =
1.257     albertel 7401: 	&Apache::lonnet::decode_symb($env{'form.selectpage'});
1.330     albertel 7402: 
1.447     foxr     7403:     my $navmap=Apache::lonnavmaps::navmap->new();
1.582     raeburn  7404:     unless (ref($navmap)) {
                   7405:         if (ref($nav_error)) {
                   7406:             $$nav_error = 1;
                   7407:         }
1.591     raeburn  7408:         return;
1.582     raeburn  7409:     }
1.191     albertel 7410:     my $map=$navmap->getResourceByUrl($sequence);
                   7411:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
1.330     albertel 7412: 
                   7413:     &Apache::lonxml::clear_problem_counter();
                   7414: 
1.557     raeburn  7415:     my $uname       = $env{'user.name'};
                   7416:     my $udom        = $env{'user.domain'};
1.435     foxr     7417:     my $cid         = $env{'request.course.id'};
                   7418:     my $total_lines = 0;
                   7419:     %bubble_lines_per_response = ();
1.447     foxr     7420:     %first_bubble_line         = ();
1.503     raeburn  7421:     %subdivided_bubble_lines   = ();
                   7422:     %responsetype_per_response = ();
1.554     raeburn  7423: 
1.447     foxr     7424:     my $response_number = 0;
                   7425:     my $bubble_line     = 0;
1.191     albertel 7426:     foreach my $resource (@resources) {
1.542     raeburn  7427:         my ($analysis,$parts) = &scantron_partids_tograde($resource,$cid,$uname,$udom);
                   7428:         if ((ref($analysis) eq 'HASH') && (ref($parts) eq 'ARRAY')) {
                   7429: 	    foreach my $part_id (@{$parts}) {
                   7430:                 my $lines;
                   7431: 
                   7432: 	        # TODO - make this a persistent hash not an array.
                   7433: 
                   7434:                 # optionresponse, matchresponse and rankresponse type items 
                   7435:                 # render as separate sub-questions in exam mode.
                   7436:                 if (($analysis->{$part_id.'.type'} eq 'optionresponse') ||
                   7437:                     ($analysis->{$part_id.'.type'} eq 'matchresponse') ||
                   7438:                     ($analysis->{$part_id.'.type'} eq 'rankresponse')) {
                   7439:                     my ($numbub,$numshown);
                   7440:                     if ($analysis->{$part_id.'.type'} eq 'optionresponse') {
                   7441:                         if (ref($analysis->{$part_id.'.options'}) eq 'ARRAY') {
                   7442:                             $numbub = scalar(@{$analysis->{$part_id.'.options'}});
                   7443:                         }
                   7444:                     } elsif ($analysis->{$part_id.'.type'} eq 'matchresponse') {
                   7445:                         if (ref($analysis->{$part_id.'.items'}) eq 'ARRAY') {
                   7446:                             $numbub = scalar(@{$analysis->{$part_id.'.items'}});
                   7447:                         }
                   7448:                     } elsif ($analysis->{$part_id.'.type'} eq 'rankresponse') {
                   7449:                         if (ref($analysis->{$part_id.'.foils'}) eq 'ARRAY') {
                   7450:                             $numbub = scalar(@{$analysis->{$part_id.'.foils'}});
                   7451:                         }
                   7452:                     }
                   7453:                     if (ref($analysis->{$part_id.'.shown'}) eq 'ARRAY') {
                   7454:                         $numshown = scalar(@{$analysis->{$part_id.'.shown'}});
                   7455:                     }
                   7456:                     my $bubbles_per_line = 10;
                   7457:                     my $inner_bubble_lines = int($numbub/$bubbles_per_line);
                   7458:                     if (($numbub % $bubbles_per_line) != 0) {
                   7459:                         $inner_bubble_lines++;
                   7460:                     }
                   7461:                     for (my $i=0; $i<$numshown; $i++) {
                   7462:                         $subdivided_bubble_lines{$response_number} .= 
                   7463:                             $inner_bubble_lines.',';
                   7464:                     }
                   7465:                     $subdivided_bubble_lines{$response_number} =~ s/,$//;
                   7466:                     $lines = $numshown * $inner_bubble_lines;
                   7467:                 } else {
                   7468:                     $lines = $analysis->{"$part_id.bubble_lines"};
                   7469:                 } 
                   7470: 
                   7471:                 $first_bubble_line{$response_number} = $bubble_line;
                   7472: 	        $bubble_lines_per_response{$response_number} = $lines;
                   7473:                 $responsetype_per_response{$response_number} = 
                   7474:                     $analysis->{$part_id.'.type'};
                   7475: 	        $response_number++;
                   7476: 
                   7477: 	        $bubble_line +=  $lines;
                   7478: 	        $total_lines +=  $lines;
                   7479: 	    }
                   7480:         }
                   7481:     }
1.552     raeburn  7482:     &Apache::lonnet::delenv('scantron.');
1.542     raeburn  7483: 
                   7484:     &save_bubble_lines();
                   7485:     $env{'form.scantron_maxbubble'} =
                   7486: 	$total_lines;
                   7487:     return $env{'form.scantron_maxbubble'};
                   7488: }
1.523     raeburn  7489: 
1.157     albertel 7490: sub scantron_validate_missingbubbles {
                   7491:     my ($r,$currentphase) = @_;
                   7492:     #get student info
                   7493:     my $classlist=&Apache::loncoursedata::get_classlist();
                   7494:     my %idmap=&username_to_idmap($classlist);
                   7495: 
                   7496:     #get scantron line setup
1.257     albertel 7497:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.157     albertel 7498:     my ($scanlines,$scan_data)=&scantron_getfile();
1.582     raeburn  7499:     my $nav_error;
                   7500:     my $max_bubble=&scantron_get_maxbubble(\$nav_error);
                   7501:     if ($nav_error) {
                   7502:         return(1,$currentphase);
                   7503:     }
1.157     albertel 7504:     if (!$max_bubble) { $max_bubble=2**31; }
                   7505:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
1.200     albertel 7506: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.157     albertel 7507: 	if ($line=~/^[\s\cz]*$/) { next; }
                   7508: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
                   7509: 						 $scan_data);
                   7510: 	if (!defined($$scan_record{'scantron.missingerror'})) { next; }
                   7511: 	my @to_correct;
1.470     foxr     7512: 	
                   7513: 	# Probably here's where the error is...
                   7514: 
1.157     albertel 7515: 	foreach my $missing (@{$$scan_record{'scantron.missingerror'}}) {
1.505     raeburn  7516:             my $lastbubble;
                   7517:             if ($missing =~ /^(\d+)\.(\d+)$/) {
                   7518:                my $question = $1;
                   7519:                my $subquestion = $2;
                   7520:                if (!defined($first_bubble_line{$question -1})) { next; }
                   7521:                my $first = $first_bubble_line{$question-1};
                   7522:                my @subans = split(/,/,$subdivided_bubble_lines{$question-1});
                   7523:                my $subcount = 1;
                   7524:                while ($subcount<$subquestion) {
                   7525:                    $first += $subans[$subcount-1];
                   7526:                    $subcount ++;
                   7527:                }
                   7528:                my $count = $subans[$subquestion-1];
                   7529:                $lastbubble = $first + $count;
                   7530:             } else {
                   7531:                 if (!defined($first_bubble_line{$missing - 1})) { next; }
                   7532:                 $lastbubble = $first_bubble_line{$missing - 1} + $bubble_lines_per_response{$missing - 1};
                   7533:             }
                   7534:             if ($lastbubble > $max_bubble) { next; }
1.157     albertel 7535: 	    push(@to_correct,$missing);
                   7536: 	}
                   7537: 	if (@to_correct) {
                   7538: 	    &scantron_get_correction($r,$i,$scan_record,\%scantron_config,
                   7539: 				     $line,'missingbubble',\@to_correct);
                   7540: 	    return (1,$currentphase);
                   7541: 	}
                   7542: 
                   7543:     }
                   7544:     return (0,$currentphase+1);
                   7545: }
                   7546: 
1.423     albertel 7547: 
1.82      albertel 7548: sub scantron_process_students {
1.608     www      7549:     my ($r,$symb) = @_;
1.513     foxr     7550: 
1.257     albertel 7551:     my (undef,undef,$sequence)=&Apache::lonnet::decode_symb($env{'form.selectpage'});
1.513     foxr     7552:     if (!$symb) {
                   7553: 	return '';
                   7554:     }
1.324     albertel 7555:     my $default_form_data=&defaultFormData($symb);
1.82      albertel 7556: 
1.257     albertel 7557:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.157     albertel 7558:     my ($scanlines,$scan_data)=&scantron_getfile();
1.82      albertel 7559:     my $classlist=&Apache::loncoursedata::get_classlist();
                   7560:     my %idmap=&username_to_idmap($classlist);
1.132     bowersj2 7561:     my $navmap=Apache::lonnavmaps::navmap->new();
1.582     raeburn  7562:     unless (ref($navmap)) {
                   7563:         $r->print(&navmap_errormsg());
                   7564:         return '';
                   7565:     }  
1.83      albertel 7566:     my $map=$navmap->getResourceByUrl($sequence);
                   7567:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
1.557     raeburn  7568:     my (%grader_partids_by_symb,%grader_randomlists_by_symb);
                   7569:     &graders_resources_pass(\@resources,\%grader_partids_by_symb,
                   7570:                             \%grader_randomlists_by_symb);
1.586     raeburn  7571:     my $resource_error;
1.557     raeburn  7572:     foreach my $resource (@resources) {
1.586     raeburn  7573:         my $ressymb;
                   7574:         if (ref($resource)) {
                   7575:             $ressymb = $resource->symb();
                   7576:         } else {
                   7577:             $resource_error = 1;
                   7578:             last;
                   7579:         }
1.557     raeburn  7580:         my ($analysis,$parts) =
                   7581:             &scantron_partids_tograde($resource,$env{'request.course.id'},
                   7582:                                       $env{'user.name'},$env{'user.domain'},1);
                   7583:         $grader_partids_by_symb{$ressymb} = $parts;
                   7584:         if (ref($analysis) eq 'HASH') {
                   7585:             if (ref($analysis->{'parts_withrandomlist'}) eq 'ARRAY') {
                   7586:                 $grader_randomlists_by_symb{$ressymb} = 
                   7587:                     $analysis->{'parts_withrandomlist'};
                   7588:             }
                   7589:         }
                   7590:     }
1.586     raeburn  7591:     if ($resource_error) {
                   7592:         $r->print(&navmap_errormsg());
                   7593:         return '';
                   7594:     }
1.557     raeburn  7595: 
1.554     raeburn  7596:     my ($uname,$udom);
1.82      albertel 7597:     my $result= <<SCANTRONFORM;
1.81      albertel 7598: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantronupload">
                   7599:   <input type="hidden" name="command" value="scantron_configphase" />
                   7600:   $default_form_data
                   7601: SCANTRONFORM
1.82      albertel 7602:     $r->print($result);
                   7603: 
                   7604:     my @delayqueue;
1.542     raeburn  7605:     my (%completedstudents,%scandata);
1.140     albertel 7606:     
1.520     www      7607:     my $lock=&Apache::lonnet::set_lock(&mt('Grading bubblesheet exam'));
1.200     albertel 7608:     my $count=&get_todo_count($scanlines,$scan_data);
1.575     www      7609:     my %prog_state=&Apache::lonhtmlcommon::Create_PrgWin($r,'Bubblesheet Status',
                   7610:  				    'Bubblesheet Progress',$count,
1.195     albertel 7611: 				    'inline',undef,'scantronupload');
1.140     albertel 7612:     &Apache::lonhtmlcommon::Update_PrgWin($r,\%prog_state,
                   7613: 					  'Processing first student');
1.542     raeburn  7614:     $r->print('<br />');
1.140     albertel 7615:     my $start=&Time::HiRes::time();
1.158     albertel 7616:     my $i=-1;
1.542     raeburn  7617:     my $started;
1.447     foxr     7618: 
1.582     raeburn  7619:     my $nav_error;
                   7620:     &scantron_get_maxbubble(\$nav_error); # Need the bubble lines array to parse.
                   7621:     if ($nav_error) {
                   7622:         $r->print(&navmap_errormsg());
                   7623:         return '';
                   7624:     }
                   7625: 
1.513     foxr     7626:     # If an ssi failed in scantron_get_maxbubble, put an error message out to
                   7627:     # the user and return.
                   7628: 
                   7629:     if ($ssi_error) {
                   7630: 	$r->print("</form>");
                   7631: 	&ssi_print_error($r);
1.520     www      7632:         &Apache::lonnet::remove_lock($lock);
1.513     foxr     7633: 	return '';		# Dunno why the other returns return '' rather than just returning.
                   7634:     }
1.447     foxr     7635: 
1.542     raeburn  7636:     my %lettdig = &letter_to_digits();
                   7637:     my $numletts = scalar(keys(%lettdig));
                   7638: 
1.157     albertel 7639:     while ($i<$scanlines->{'count'}) {
                   7640:  	($uname,$udom)=('','');
                   7641:  	$i++;
1.200     albertel 7642:  	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.157     albertel 7643:  	if ($line=~/^[\s\cz]*$/) { next; }
1.200     albertel 7644: 	if ($started) {
                   7645: 	    &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state,
                   7646: 						     'last student');
                   7647: 	}
                   7648: 	$started=1;
1.157     albertel 7649:  	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
                   7650:  						 $scan_data);
                   7651:  	unless ($uname=&scantron_find_student($scan_record,$scan_data,
                   7652:  					      \%idmap,$i)) {
                   7653:   	    &scantron_add_delay(\@delayqueue,$line,
                   7654:  				'Unable to find a student that matches',1);
                   7655:  	    next;
                   7656:   	}
                   7657:  	if (exists $completedstudents{$uname}) {
                   7658:  	    &scantron_add_delay(\@delayqueue,$line,
                   7659:  				'Student '.$uname.' has multiple sheets',2);
                   7660:  	    next;
                   7661:  	}
                   7662:   	($uname,$udom)=split(/:/,$uname);
1.330     albertel 7663: 
1.586     raeburn  7664:         my (%partids_by_symb,$res_error);
1.554     raeburn  7665:         foreach my $resource (@resources) {
1.586     raeburn  7666:             my $ressymb;
                   7667:             if (ref($resource)) {
                   7668:                 $ressymb = $resource->symb();
                   7669:             } else {
                   7670:                 $res_error = 1;
                   7671:                 last;
                   7672:             }
1.557     raeburn  7673:             if ((exists($grader_randomlists_by_symb{$ressymb})) ||
                   7674:                 (ref($grader_partids_by_symb{$ressymb}) ne 'ARRAY')) {
                   7675:                 my ($analysis,$parts) =
                   7676:                     &scantron_partids_tograde($resource,$env{'request.course.id'},$uname,$udom);
                   7677:                 $partids_by_symb{$ressymb} = $parts;
                   7678:             } else {
                   7679:                 $partids_by_symb{$ressymb} = $grader_partids_by_symb{$ressymb};
                   7680:             }
1.554     raeburn  7681:         }
                   7682: 
1.586     raeburn  7683:         if ($res_error) {
                   7684:             &scantron_add_delay(\@delayqueue,$line,
                   7685:                                 'An error occurred while grading student '.$uname,2);
                   7686:             next;
                   7687:         }
                   7688: 
1.330     albertel 7689: 	&Apache::lonxml::clear_problem_counter();
1.514     raeburn  7690:   	&Apache::lonnet::appenv($scan_record);
1.376     albertel 7691: 
                   7692: 	if (&scantron_clear_skip($scanlines,$scan_data,$i)) {
                   7693: 	    &scantron_putfile($scanlines,$scan_data);
                   7694: 	}
1.161     albertel 7695: 	
1.542     raeburn  7696:         my $scancode;
                   7697:         if ((exists($scan_record->{'scantron.CODE'})) &&
                   7698:             (&Apache::lonnet::validCODE($scan_record->{'scantron.CODE'}))) {
                   7699:             $scancode = $scan_record->{'scantron.CODE'};
                   7700:         } else {
                   7701:             $scancode = '';
                   7702:         }
                   7703: 
                   7704:         if (&grade_student_bubbles($r,$uname,$udom,$scan_record,$scancode,
1.554     raeburn  7705:                                    \@resources,\%partids_by_symb) eq 'ssi_error') {
1.542     raeburn  7706:             $ssi_error = 0; # So end of handler error message does not trigger.
                   7707:             $r->print("</form>");
                   7708:             &ssi_print_error($r);
                   7709:             &Apache::lonnet::remove_lock($lock);
                   7710:             return '';      # Why return ''?  Beats me.
                   7711:         }
1.513     foxr     7712: 
1.140     albertel 7713: 	$completedstudents{$uname}={'line'=>$line};
1.542     raeburn  7714:         if ($env{'form.verifyrecord'}) {
                   7715:             my $lastpos = $env{'form.scantron_maxbubble'}*$scantron_config{'Qlength'};
                   7716:             my $studentdata = substr($line,$scantron_config{'Qstart'}-1,$lastpos);
                   7717:             chomp($studentdata);
                   7718:             $studentdata =~ s/\r$//;
                   7719:             my $studentrecord = '';
                   7720:             my $counter = -1;
                   7721:             foreach my $resource (@resources) {
1.554     raeburn  7722:                 my $ressymb = $resource->symb();
1.542     raeburn  7723:                 ($counter,my $recording) =
                   7724:                     &verify_scantron_grading($resource,$udom,$uname,$env{'request.course.id'},
1.554     raeburn  7725:                                              $counter,$studentdata,$partids_by_symb{$ressymb},
1.542     raeburn  7726:                                              \%scantron_config,\%lettdig,$numletts);
                   7727:                 $studentrecord .= $recording;
                   7728:             }
                   7729:             if ($studentrecord ne $studentdata) {
1.554     raeburn  7730:                 &Apache::lonxml::clear_problem_counter();
                   7731:                 if (&grade_student_bubbles($r,$uname,$udom,$scan_record,$scancode,
                   7732:                                            \@resources,\%partids_by_symb) eq 'ssi_error') {
                   7733:                     $ssi_error = 0; # So end of handler error message does not trigger.
                   7734:                     $r->print("</form>");
                   7735:                     &ssi_print_error($r);
                   7736:                     &Apache::lonnet::remove_lock($lock);
                   7737:                     delete($completedstudents{$uname});
                   7738:                     return '';
                   7739:                 }
1.542     raeburn  7740:                 $counter = -1;
                   7741:                 $studentrecord = '';
                   7742:                 foreach my $resource (@resources) {
1.554     raeburn  7743:                     my $ressymb = $resource->symb();
1.542     raeburn  7744:                     ($counter,my $recording) =
                   7745:                         &verify_scantron_grading($resource,$udom,$uname,$env{'request.course.id'},
1.554     raeburn  7746:                                                  $counter,$studentdata,$partids_by_symb{$ressymb},
1.542     raeburn  7747:                                                  \%scantron_config,\%lettdig,$numletts);
                   7748:                     $studentrecord .= $recording;
                   7749:                 }
                   7750:                 if ($studentrecord ne $studentdata) {
                   7751:                     $r->print('<p><span class="LC_error">');
                   7752:                     if ($scancode eq '') {
                   7753:                         $r->print(&mt('Mismatch grading bubble sheet for user: [_1] with ID: [_2].',
                   7754:                                   $uname.':'.$udom,$scan_record->{'scantron.ID'}));
                   7755:                     } else {
                   7756:                         $r->print(&mt('Mismatch grading bubble sheet for user: [_1] with ID: [_2] and CODE: [_3].',
                   7757:                                   $uname.':'.$udom,$scan_record->{'scantron.ID'},$scancode));
                   7758:                     }
                   7759:                     $r->print('</span><br />'.&Apache::loncommon::start_data_table()."\n".
                   7760:                               &Apache::loncommon::start_data_table_header_row()."\n".
                   7761:                               '<th>'.&mt('Source').'</th><th>'.&mt('Bubbled responses').'</th>'.
                   7762:                               &Apache::loncommon::end_data_table_header_row()."\n".
                   7763:                               &Apache::loncommon::start_data_table_row().
                   7764:                               '<td>'.&mt('Bubble Sheet').'</td>'.
                   7765:                               '<td><span class="LC_nobreak">'.$studentdata.'</span></td>'.
                   7766:                               &Apache::loncommon::end_data_table_row().
                   7767:                               &Apache::loncommon::start_data_table_row().
                   7768:                               '<td>Stored submissions</td>'.
                   7769:                               '<td><span class="LC_nobreak">'.$studentrecord.'</span></td>'."\n".
                   7770:                               &Apache::loncommon::end_data_table_row().
                   7771:                               &Apache::loncommon::end_data_table().'</p>');
                   7772:                 } else {
                   7773:                     $r->print('<br /><span class="LC_warning">'.
                   7774:                              &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 />'.
                   7775:                              &mt("As a consequence, this user's submission history records two tries.").
                   7776:                                  '</span><br />');
                   7777:                 }
                   7778:             }
                   7779:         }
1.543     raeburn  7780:         if (&Apache::loncommon::connection_aborted($r)) { last; }
1.140     albertel 7781:     } continue {
1.330     albertel 7782: 	&Apache::lonxml::clear_problem_counter();
1.552     raeburn  7783: 	&Apache::lonnet::delenv('scantron.');
1.82      albertel 7784:     }
1.140     albertel 7785:     &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
1.520     www      7786:     &Apache::lonnet::remove_lock($lock);
1.172     albertel 7787: #    my $lasttime = &Time::HiRes::time()-$start;
                   7788: #    $r->print("<p>took $lasttime</p>");
1.140     albertel 7789: 
1.200     albertel 7790:     $r->print("</form>");
1.157     albertel 7791:     return '';
1.75      albertel 7792: }
1.157     albertel 7793: 
1.557     raeburn  7794: sub graders_resources_pass {
                   7795:     my ($resources,$grader_partids_by_symb,$grader_randomlists_by_symb) = @_;
                   7796:     if ((ref($resources) eq 'ARRAY') && (ref($grader_partids_by_symb)) && 
                   7797:         (ref($grader_randomlists_by_symb) eq 'HASH')) {
                   7798:         foreach my $resource (@{$resources}) {
                   7799:             my $ressymb = $resource->symb();
                   7800:             my ($analysis,$parts) =
                   7801:                 &scantron_partids_tograde($resource,$env{'request.course.id'},
                   7802:                                           $env{'user.name'},$env{'user.domain'},1);
                   7803:             $grader_partids_by_symb->{$ressymb} = $parts;
                   7804:             if (ref($analysis) eq 'HASH') {
                   7805:                 if (ref($analysis->{'parts_withrandomlist'}) eq 'ARRAY') {
                   7806:                     $grader_randomlists_by_symb->{$ressymb} =
                   7807:                         $analysis->{'parts_withrandomlist'};
                   7808:                 }
                   7809:             }
                   7810:         }
                   7811:     }
                   7812:     return;
                   7813: }
                   7814: 
1.542     raeburn  7815: sub grade_student_bubbles {
1.554     raeburn  7816:     my ($r,$uname,$udom,$scan_record,$scancode,$resources,$parts) = @_;
                   7817:     if (ref($resources) eq 'ARRAY') {
                   7818:         my $count = 0;
                   7819:         foreach my $resource (@{$resources}) {
                   7820:             my $ressymb = $resource->symb();
                   7821:             my %form = ('submitted'      => 'scantron',
                   7822:                         'grade_target'   => 'grade',
                   7823:                         'grade_username' => $uname,
                   7824:                         'grade_domain'   => $udom,
                   7825:                         'grade_courseid' => $env{'request.course.id'},
                   7826:                         'grade_symb'     => $ressymb,
                   7827:                         'CODE'           => $scancode
                   7828:                        );
                   7829:             if (ref($parts) eq 'HASH') {
                   7830:                 if (ref($parts->{$ressymb}) eq 'ARRAY') {
                   7831:                     foreach my $part (@{$parts->{$ressymb}}) {
                   7832:                         $form{'scantron_questnum_start.'.$part} =
                   7833:                             1+$env{'form.scantron.first_bubble_line.'.$count};
                   7834:                         $count++;
                   7835:                     }
                   7836:                 }
                   7837:             }
                   7838:             my $result=&ssi_with_retries($resource->src(),$ssi_retries,%form);
                   7839:             return 'ssi_error' if ($ssi_error);
                   7840:             last if (&Apache::loncommon::connection_aborted($r));
                   7841:         }
1.542     raeburn  7842:     }
                   7843:     return;
                   7844: }
                   7845: 
1.157     albertel 7846: sub scantron_upload_scantron_data {
1.608     www      7847:     my ($r,$symb)=@_;
1.565     raeburn  7848:     my $dom = $env{'request.role.domain'};
                   7849:     my $domdesc = &Apache::lonnet::domain($dom,'description');
                   7850:     $r->print(&Apache::loncommon::coursebrowser_javascript($dom));
1.157     albertel 7851:     my $select_link=&Apache::loncommon::selectcourse_link('rules','courseid',
1.181     albertel 7852: 							  'domainid',
1.565     raeburn  7853: 							  'coursename',$dom);
                   7854:     my $syllabuslink = '<a href="javascript:ToSyllabus();">'.&mt('Syllabus').'</a>'.
                   7855:                        ('&nbsp'x2).&mt('(shows course personnel)'); 
1.608     www      7856:     my $default_form_data=&defaultFormData($symb);
1.579     raeburn  7857:     my $nofile_alert = &mt('Please use the browse button to select a file from your local directory.');
                   7858:     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 7859:     $r->print(&Apache::lonhtmlcommon::scripttag('
1.157     albertel 7860:     function checkUpload(formname) {
                   7861: 	if (formname.upfile.value == "") {
1.579     raeburn  7862: 	    alert("'.$nofile_alert.'");
1.157     albertel 7863: 	    return false;
                   7864: 	}
1.565     raeburn  7865:         if (formname.courseid.value == "") {
1.579     raeburn  7866:             alert("'.$nocourseid_alert.'");
1.565     raeburn  7867:             return false;
                   7868:         }
1.157     albertel 7869: 	formname.submit();
                   7870:     }
1.565     raeburn  7871: 
                   7872:     function ToSyllabus() {
                   7873:         var cdom = '."'$dom'".';
                   7874:         var cnum = document.rules.courseid.value;
                   7875:         if (cdom == "" || cdom == null) {
                   7876:             return;
                   7877:         }
                   7878:         if (cnum == "" || cnum == null) {
                   7879:            return;
                   7880:         }
                   7881:         syllwin=window.open("/public/"+cdom+"/"+cnum+"/syllabus","LONCAPASyllabus",
                   7882:                             "height=350,width=350,scrollbars=yes,menubar=no");
                   7883:         return;
                   7884:     }
                   7885: 
1.597     wenzelju 7886: '));
                   7887:     $r->print('
1.566     raeburn  7888: <h3>'.&mt('Send scanned bubblesheet data to a course').'</h3>
                   7889: 
1.492     albertel 7890: <form enctype="multipart/form-data" action="/adm/grades" name="rules" method="post">
1.565     raeburn  7891: '.$default_form_data.
                   7892:   &Apache::lonhtmlcommon::start_pick_box().
                   7893:   &Apache::lonhtmlcommon::row_title(&mt('Course ID')).
                   7894:   '<input name="courseid" type="text" size="30" />'.$select_link.
                   7895:   &Apache::lonhtmlcommon::row_closure().
                   7896:   &Apache::lonhtmlcommon::row_title(&mt('Course Name')).
                   7897:   '<input name="coursename" type="text" size="30" />'.$syllabuslink.
                   7898:   &Apache::lonhtmlcommon::row_closure().
                   7899:   &Apache::lonhtmlcommon::row_title(&mt('Domain')).
                   7900:   '<input name="domainid" type="hidden" />'.$domdesc.
                   7901:   &Apache::lonhtmlcommon::row_closure().
                   7902:   &Apache::lonhtmlcommon::row_title(&mt('File to upload')).
                   7903:   '<input type="file" name="upfile" size="50" />'.
                   7904:   &Apache::lonhtmlcommon::row_closure(1).
                   7905:   &Apache::lonhtmlcommon::end_pick_box().'<br />
                   7906: 
1.492     albertel 7907: <input name="command" value="scantronupload_save" type="hidden" />
1.589     bisitz   7908: <input type="button" onclick="javascript:checkUpload(this.form);" value="'.&mt('Upload Bubblesheet Data').'" />
1.157     albertel 7909: </form>
1.492     albertel 7910: ');
1.157     albertel 7911:     return '';
                   7912: }
                   7913: 
1.423     albertel 7914: 
1.157     albertel 7915: sub scantron_upload_scantron_data_save {
1.608     www      7916:     my($r,$symb)=@_;
1.182     albertel 7917:     my $doanotherupload=
                   7918: 	'<br /><form action="/adm/grades" method="post">'."\n".
                   7919: 	'<input type="hidden" name="command" value="scantronupload" />'."\n".
1.492     albertel 7920: 	'<input type="submit" name="submit" value="'.&mt('Do Another Upload').'" />'."\n".
1.182     albertel 7921: 	'</form>'."\n";
1.257     albertel 7922:     if (!&Apache::lonnet::allowed('usc',$env{'form.domainid'}) &&
1.162     albertel 7923: 	!&Apache::lonnet::allowed('usc',
1.257     albertel 7924: 			    $env{'form.domainid'}.'_'.$env{'form.courseid'})) {
1.575     www      7925: 	$r->print(&mt("You are not allowed to upload bubblesheet data to the requested course.")."<br />");
1.614     www      7926: 	unless ($symb) {
1.182     albertel 7927: 	    $r->print($doanotherupload);
                   7928: 	}
1.162     albertel 7929: 	return '';
                   7930:     }
1.257     albertel 7931:     my %coursedata=&Apache::lonnet::coursedescription($env{'form.domainid'}.'_'.$env{'form.courseid'});
1.568     raeburn  7932:     my $uploadedfile;
1.567     raeburn  7933:     $r->print('<h3>'.&mt("Uploading file to [_1]",$coursedata{'description'}).'</h3>');
1.257     albertel 7934:     if (length($env{'form.upfile'}) < 2) {
1.568     raeburn  7935:         $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 7936:     } else {
1.568     raeburn  7937:         my $result = 
                   7938:             &Apache::lonnet::userfileupload('upfile','','scantron','','','',
                   7939:                                             $env{'form.courseid'},$env{'form.domainid'});
                   7940: 	if ($result =~ m{^/uploaded/}) {
1.567     raeburn  7941: 	    $r->print(&mt('[_1]Success:[_2] Successfully uploaded [_3] bytes of data into location: [_4]',
                   7942:                           '<span class="LC_success">','</span>',(length($env{'form.upfile'})-1),
                   7943: 			  '<span class="LC_filename">'.$result.'</span>'));
1.568     raeburn  7944:             ($uploadedfile) = ($result =~ m{/([^/]+)$});
1.567     raeburn  7945:             $r->print(&validate_uploaded_scantron_file($env{'form.domainid'},
1.568     raeburn  7946:                                                        $env{'form.courseid'},$uploadedfile));
1.210     albertel 7947: 	} else {
1.567     raeburn  7948: 	    $r->print(&mt('[_1]Error:[_2] An error ([_3]) occurred when attempting to upload the file, [_4]',
                   7949:                           '<span class="LC_error">','</span>',$result,
1.568     raeburn  7950: 			  '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>'));
1.183     albertel 7951: 	}
                   7952:     }
1.174     albertel 7953:     if ($symb) {
1.612     www      7954: 	$r->print(&scantron_selectphase($r,$uploadedfile,$symb));
1.174     albertel 7955:     } else {
1.182     albertel 7956: 	$r->print($doanotherupload);
1.174     albertel 7957:     }
1.157     albertel 7958:     return '';
                   7959: }
                   7960: 
1.567     raeburn  7961: sub validate_uploaded_scantron_file {
                   7962:     my ($cdom,$cname,$fname) = @_;
                   7963:     my $scanlines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.$fname);
                   7964:     my @lines;
                   7965:     if ($scanlines ne '-1') {
                   7966:         @lines=split("\n",$scanlines,-1);
                   7967:     }
                   7968:     my $output;
                   7969:     if (@lines) {
                   7970:         my (%counts,$max_match_format);
                   7971:         my ($max_match_count,$max_match_pct) = (0,0);
                   7972:         my $classlist = &Apache::loncoursedata::get_classlist($cdom,$cname);
                   7973:         my %idmap = &username_to_idmap($classlist);
                   7974:         foreach my $key (keys(%idmap)) {
                   7975:             my $lckey = lc($key);
                   7976:             $idmap{$lckey} = $idmap{$key};
                   7977:         }
                   7978:         my %unique_formats;
                   7979:         my @formatlines = &get_scantronformat_file();
                   7980:         foreach my $line (@formatlines) {
                   7981:             chomp($line);
                   7982:             my @config = split(/:/,$line);
                   7983:             my $idstart = $config[5];
                   7984:             my $idlength = $config[6];
                   7985:             if (($idstart ne '') && ($idlength > 0)) {
                   7986:                 if (ref($unique_formats{$idstart.':'.$idlength}) eq 'ARRAY') {
                   7987:                     push(@{$unique_formats{$idstart.':'.$idlength}},$config[0].':'.$config[1]); 
                   7988:                 } else {
                   7989:                     $unique_formats{$idstart.':'.$idlength} = [$config[0].':'.$config[1]];
                   7990:                 }
                   7991:             }
                   7992:         }
                   7993:         foreach my $key (keys(%unique_formats)) {
                   7994:             my ($idstart,$idlength) = split(':',$key);
                   7995:             %{$counts{$key}} = (
                   7996:                                'found'   => 0,
                   7997:                                'total'   => 0,
                   7998:                               );
                   7999:             foreach my $line (@lines) {
                   8000:                 next if ($line =~ /^#/);
                   8001:                 next if ($line =~ /^[\s\cz]*$/);
                   8002:                 my $id = substr($line,$idstart-1,$idlength);
                   8003:                 $id = lc($id);
                   8004:                 if (exists($idmap{$id})) {
                   8005:                     $counts{$key}{'found'} ++;
                   8006:                 }
                   8007:                 $counts{$key}{'total'} ++;
                   8008:             }
                   8009:             if ($counts{$key}{'total'}) {
                   8010:                 my $percent_match = (100*$counts{$key}{'found'})/($counts{$key}{'total'});
                   8011:                 if (($max_match_format eq '') || ($percent_match > $max_match_pct)) {
                   8012:                     $max_match_pct = $percent_match;
                   8013:                     $max_match_format = $key;
                   8014:                     $max_match_count = $counts{$key}{'total'};
                   8015:                 }
                   8016:             }
                   8017:         }
                   8018:         if (ref($unique_formats{$max_match_format}) eq 'ARRAY') {
                   8019:             my $format_descs;
                   8020:             my $numwithformat = @{$unique_formats{$max_match_format}};
                   8021:             for (my $i=0; $i<$numwithformat; $i++) {
                   8022:                 my ($name,$desc) = split(':',$unique_formats{$max_match_format}[$i]);
                   8023:                 if ($i<$numwithformat-2) {
                   8024:                     $format_descs .= '"<i>'.$desc.'</i>", ';
                   8025:                 } elsif ($i==$numwithformat-2) {
                   8026:                     $format_descs .= '"<i>'.$desc.'</i>" '.&mt('and').' ';
                   8027:                 } elsif ($i==$numwithformat-1) {
                   8028:                     $format_descs .= '"<i>'.$desc.'</i>"';
                   8029:                 }
                   8030:             }
                   8031:             my $showpct = sprintf("%.0f",$max_match_pct).'%';
                   8032:             $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).
                   8033:                        '<br />'.&mt('A low percentage of matches results from one of the following:').'<ul>'.
                   8034:                        '<li>'.&mt('The file was uploaded to the wrong course').'</li>'.
                   8035:                        '<li>'.&mt('The data are not in the format expected for the domain: [_1]',
                   8036:                                   '<i>'.$cdom.'</i>').'</li>'.
                   8037:                        '<li>'.&mt('Students did not bubble their IDs, or mis-bubbled them').'</li>'.
                   8038:                        '<li>'.&mt('The course roster is not up to date').'</li>'.
                   8039:                        '</ul>';
                   8040:         }
                   8041:     } else {
                   8042:         $output = '<span class="LC_warning">'.&mt('Uploaded file contained no data').'</span>';
                   8043:     }
                   8044:     return $output;
                   8045: }
                   8046: 
1.202     albertel 8047: sub valid_file {
                   8048:     my ($requested_file)=@_;
                   8049:     foreach my $filename (sort(&scantron_filenames())) {
                   8050: 	if ($requested_file eq $filename) { return 1; }
                   8051:     }
                   8052:     return 0;
                   8053: }
                   8054: 
                   8055: sub scantron_download_scantron_data {
1.608     www      8056:     my ($r,$symb)=@_;
                   8057:     my $default_form_data=&defaultFormData($symb);
1.257     albertel 8058:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   8059:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   8060:     my $file=$env{'form.scantron_selectfile'};
1.202     albertel 8061:     if (! &valid_file($file)) {
1.492     albertel 8062: 	$r->print('
1.202     albertel 8063: 	<p>
1.492     albertel 8064: 	    '.&mt('The requested file name was invalid.').'
1.202     albertel 8065:         </p>
1.492     albertel 8066: ');
1.202     albertel 8067: 	return;
                   8068:     }
                   8069:     my $orig='/uploaded/'.$cdom.'/'.$cname.'/scantron_orig_'.$file;
                   8070:     my $corrected='/uploaded/'.$cdom.'/'.$cname.'/scantron_corrected_'.$file;
                   8071:     my $skipped='/uploaded/'.$cdom.'/'.$cname.'/scantron_skipped_'.$file;
                   8072:     &Apache::lonnet::allowuploaded('/adm/grades',$orig);
                   8073:     &Apache::lonnet::allowuploaded('/adm/grades',$corrected);
                   8074:     &Apache::lonnet::allowuploaded('/adm/grades',$skipped);
1.492     albertel 8075:     $r->print('
1.202     albertel 8076:     <p>
1.492     albertel 8077: 	'.&mt('[_1]Original[_2] file as uploaded by the scantron office.',
                   8078: 	      '<a href="'.$orig.'">','</a>').'
1.202     albertel 8079:     </p>
                   8080:     <p>
1.492     albertel 8081: 	'.&mt('[_1]Corrections[_2], a file of corrected records that were used in grading.',
                   8082: 	      '<a href="'.$corrected.'">','</a>').'
1.202     albertel 8083:     </p>
                   8084:     <p>
1.492     albertel 8085: 	'.&mt('[_1]Skipped[_2], a file of records that were skipped.',
                   8086: 	      '<a href="'.$skipped.'">','</a>').'
1.202     albertel 8087:     </p>
1.492     albertel 8088: ');
1.202     albertel 8089:     return '';
                   8090: }
1.157     albertel 8091: 
1.523     raeburn  8092: sub checkscantron_results {
1.608     www      8093:     my ($r,$symb) = @_;
1.523     raeburn  8094:     if (!$symb) {return '';}
                   8095:     my $cid = $env{'request.course.id'};
1.542     raeburn  8096:     my %lettdig = &letter_to_digits();
1.523     raeburn  8097:     my $numletts = scalar(keys(%lettdig));
                   8098:     my $cnum = $env{'course.'.$cid.'.num'};
                   8099:     my $cdom = $env{'course.'.$cid.'.domain'};
                   8100:     my (undef, undef, $sequence) = &Apache::lonnet::decode_symb($env{'form.selectpage'});
                   8101:     my %record;
                   8102:     my %scantron_config =
                   8103:         &Apache::grades::get_scantron_config($env{'form.scantron_format'});
                   8104:     my ($scanlines,$scan_data)=&Apache::grades::scantron_getfile();
                   8105:     my $classlist=&Apache::loncoursedata::get_classlist();
                   8106:     my %idmap=&Apache::grades::username_to_idmap($classlist);
                   8107:     my $navmap=Apache::lonnavmaps::navmap->new();
1.582     raeburn  8108:     unless (ref($navmap)) {
                   8109:         $r->print(&navmap_errormsg());
                   8110:         return '';
                   8111:     }
1.523     raeburn  8112:     my $map=$navmap->getResourceByUrl($sequence);
1.557     raeburn  8113:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
                   8114:     my (%grader_partids_by_symb,%grader_randomlists_by_symb);
                   8115:     &graders_resources_pass(\@resources,\%grader_partids_by_symb,                             \%grader_randomlists_by_symb);
                   8116: 
1.554     raeburn  8117:     my ($uname,$udom);
1.523     raeburn  8118:     my (%scandata,%lastname,%bylast);
                   8119:     $r->print('
                   8120: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="checkscantron">'."\n");
                   8121: 
                   8122:     my @delayqueue;
                   8123:     my %completedstudents;
                   8124: 
                   8125:     my $count=&Apache::grades::get_todo_count($scanlines,$scan_data);
1.581     www      8126:     my %prog_state=&Apache::lonhtmlcommon::Create_PrgWin($r,'Bubblesheet/Submissions Comparison Status',
                   8127:                                     'Progress of Bubblesheet Data/Submission Records Comparison',$count,
1.523     raeburn  8128:                                     'inline',undef,'checkscantron');
1.546     raeburn  8129:     my ($username,$domain,$started);
1.582     raeburn  8130:     my $nav_error;
                   8131:     &scantron_get_maxbubble(\$nav_error); # Need the bubble lines array to parse.
                   8132:     if ($nav_error) {
                   8133:         $r->print(&navmap_errormsg());
                   8134:         return '';
                   8135:     }
1.523     raeburn  8136: 
                   8137:     &Apache::lonhtmlcommon::Update_PrgWin($r,\%prog_state,
                   8138:                                           'Processing first student');
                   8139:     my $start=&Time::HiRes::time();
                   8140:     my $i=-1;
                   8141: 
                   8142:     while ($i<$scanlines->{'count'}) {
                   8143:         ($username,$domain,$uname)=('','','');
                   8144:         $i++;
                   8145:         my $line=&Apache::grades::scantron_get_line($scanlines,$scan_data,$i);
                   8146:         if ($line=~/^[\s\cz]*$/) { next; }
                   8147:         if ($started) {
                   8148:             &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state,
                   8149:                                                      'last student');
                   8150:         }
                   8151:         $started=1;
                   8152:         my $scan_record=
                   8153:             &Apache::grades::scantron_parse_scanline($line,$i,\%scantron_config,
                   8154:                                                      $scan_data);
                   8155:         unless ($uname=&Apache::grades::scantron_find_student($scan_record,$scan_data,
                   8156:                                                               \%idmap,$i)) {
                   8157:             &Apache::grades::scantron_add_delay(\@delayqueue,$line,
                   8158:                                 'Unable to find a student that matches',1);
                   8159:             next;
                   8160:         }
                   8161:         if (exists $completedstudents{$uname}) {
                   8162:             &Apache::grades::scantron_add_delay(\@delayqueue,$line,
                   8163:                                 'Student '.$uname.' has multiple sheets',2);
                   8164:             next;
                   8165:         }
                   8166:         my $pid = $scan_record->{'scantron.ID'};
                   8167:         $lastname{$pid} = $scan_record->{'scantron.LastName'};
                   8168:         push(@{$bylast{$lastname{$pid}}},$pid);
                   8169:         my $lastpos = $env{'form.scantron_maxbubble'}*$scantron_config{'Qlength'};
                   8170:         $scandata{$pid} = substr($line,$scantron_config{'Qstart'}-1,$lastpos);
                   8171:         chomp($scandata{$pid});
                   8172:         $scandata{$pid} =~ s/\r$//;
                   8173:         ($username,$domain)=split(/:/,$uname);
                   8174:         my $counter = -1;
                   8175:         foreach my $resource (@resources) {
1.557     raeburn  8176:             my $parts;
1.554     raeburn  8177:             my $ressymb = $resource->symb();
1.557     raeburn  8178:             if ((exists($grader_randomlists_by_symb{$ressymb})) ||
                   8179:                 (ref($grader_partids_by_symb{$ressymb}) ne 'ARRAY')) {
                   8180:                 (my $analysis,$parts) =
                   8181:                     &scantron_partids_tograde($resource,$env{'request.course.id'},$username,$domain);
                   8182:             } else {
                   8183:                 $parts = $grader_partids_by_symb{$ressymb};
                   8184:             }
1.542     raeburn  8185:             ($counter,my $recording) =
                   8186:                 &verify_scantron_grading($resource,$domain,$username,$cid,$counter,
1.554     raeburn  8187:                                          $scandata{$pid},$parts,
1.542     raeburn  8188:                                          \%scantron_config,\%lettdig,$numletts);
                   8189:             $record{$pid} .= $recording;
1.523     raeburn  8190:         }
                   8191:     }
                   8192:     &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
                   8193:     $r->print('<br />');
                   8194:     my ($okstudents,$badstudents,$numstudents,$passed,$failed);
                   8195:     $passed = 0;
                   8196:     $failed = 0;
                   8197:     $numstudents = 0;
                   8198:     foreach my $last (sort(keys(%bylast))) {
                   8199:         if (ref($bylast{$last}) eq 'ARRAY') {
                   8200:             foreach my $pid (sort(@{$bylast{$last}})) {
                   8201:                 my $showscandata = $scandata{$pid};
                   8202:                 my $showrecord = $record{$pid};
                   8203:                 $showscandata =~ s/\s/&nbsp;/g;
                   8204:                 $showrecord =~ s/\s/&nbsp;/g;
                   8205:                 if ($scandata{$pid} eq $record{$pid}) {
                   8206:                     my $css_class = ($passed % 2)?'LC_odd_row':'LC_even_row';
                   8207:                     $okstudents .= '<tr class="'.$css_class.'">'.
1.581     www      8208: '<td>'.&mt('Bubblesheet').'</td><td>'.$showscandata.'</td><td rowspan="2">'.$last.'</td><td rowspan="2">'.$pid.'</td>'."\n".
1.523     raeburn  8209: '</tr>'."\n".
                   8210: '<tr class="'.$css_class.'">'."\n".
                   8211: '<td>Submissions</td><td>'.$showrecord.'</td></tr>'."\n";
                   8212:                     $passed ++;
                   8213:                 } else {
                   8214:                     my $css_class = ($failed % 2)?'LC_odd_row':'LC_even_row';
1.581     www      8215:                     $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  8216: '</tr>'."\n".
                   8217: '<tr class="'.$css_class.'">'."\n".
                   8218: '<td>Submissions</td><td><span class="LC_nobreak">'.$record{$pid}.'</span></td>'."\n".
                   8219: '</tr>'."\n";
                   8220:                     $failed ++;
                   8221:                 }
                   8222:                 $numstudents ++;
                   8223:             }
                   8224:         }
                   8225:     }
1.572     www      8226:     $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  8227:     $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>');
                   8228:     if ($passed) {
1.572     www      8229:         $r->print(&mt('Students with exact correspondence between bubblesheet data and submissions are as follows:').'<br /><br />');
1.523     raeburn  8230:         $r->print(&Apache::loncommon::start_data_table()."\n".
                   8231:                  &Apache::loncommon::start_data_table_header_row()."\n".
                   8232:                  '<th>'.&mt('Source').'</th><th>'.&mt('Bubble records').'</th><th>'.&mt('Name').'</th><th>'.&mt('ID').'</th>'.
                   8233:                  &Apache::loncommon::end_data_table_header_row()."\n".
                   8234:                  $okstudents."\n".
                   8235:                  &Apache::loncommon::end_data_table().'<br />');
                   8236:     }
                   8237:     if ($failed) {
1.572     www      8238:         $r->print(&mt('Students with differences between bubblesheet data and submissions are as follows:').'<br /><br />');
1.523     raeburn  8239:         $r->print(&Apache::loncommon::start_data_table()."\n".
                   8240:                  &Apache::loncommon::start_data_table_header_row()."\n".
                   8241:                  '<th>'.&mt('Source').'</th><th>'.&mt('Bubble records').'</th><th>'.&mt('Name').'</th><th>'.&mt('ID').'</th>'.
                   8242:                  &Apache::loncommon::end_data_table_header_row()."\n".
                   8243:                  $badstudents."\n".
                   8244:                  &Apache::loncommon::end_data_table()).'<br />'.
1.572     www      8245:                  &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  8246:     }
1.614     www      8247:     $r->print('</form><br />');
1.523     raeburn  8248:     return;
                   8249: }
                   8250: 
1.542     raeburn  8251: sub verify_scantron_grading {
1.554     raeburn  8252:     my ($resource,$domain,$username,$cid,$counter,$scandata,$partids,
1.542     raeburn  8253:         $scantron_config,$lettdig,$numletts) = @_;
                   8254:     my ($record,%expected,%startpos);
                   8255:     return ($counter,$record) if (!ref($resource));
                   8256:     return ($counter,$record) if (!$resource->is_problem());
                   8257:     my $symb = $resource->symb();
1.554     raeburn  8258:     return ($counter,$record) if (ref($partids) ne 'ARRAY');
                   8259:     foreach my $part_id (@{$partids}) {
1.542     raeburn  8260:         $counter ++;
                   8261:         $expected{$part_id} = 0;
                   8262:         if ($env{"form.scantron.sub_bubblelines.$counter"}) {
                   8263:             my @sub_lines = split(/,/,$env{"form.scantron.sub_bubblelines.$counter"});
                   8264:             foreach my $item (@sub_lines) {
                   8265:                 $expected{$part_id} += $item;
                   8266:             }
                   8267:         } else {
                   8268:             $expected{$part_id} = $env{"form.scantron.bubblelines.$counter"};
                   8269:         }
                   8270:         $startpos{$part_id} = $env{"form.scantron.first_bubble_line.$counter"};
                   8271:     }
                   8272:     if ($symb) {
                   8273:         my %recorded;
                   8274:         my (%returnhash) = &Apache::lonnet::restore($symb,$cid,$domain,$username);
                   8275:         if ($returnhash{'version'}) {
                   8276:             my %lasthash=();
                   8277:             my $version;
                   8278:             for ($version=1;$version<=$returnhash{'version'};$version++) {
                   8279:                 foreach my $key (sort(split(/\:/,$returnhash{$version.':keys'}))) {
                   8280:                     $lasthash{$key}=$returnhash{$version.':'.$key};
                   8281:                 }
                   8282:             }
                   8283:             foreach my $key (keys(%lasthash)) {
                   8284:                 if ($key =~ /\.scantron$/) {
                   8285:                     my $value = &unescape($lasthash{$key});
                   8286:                     my ($part_id) = ($key =~ /^resource\.(.+)\.scantron$/);
                   8287:                     if ($value eq '') {
                   8288:                         for (my $i=0; $i<$expected{$part_id}; $i++) {
                   8289:                             for (my $j=0; $j<$scantron_config->{'length'}; $j++) {
                   8290:                                 $recorded{$part_id} .= $scantron_config->{'Qoff'};
                   8291:                             }
                   8292:                         }
                   8293:                     } else {
                   8294:                         my @tocheck;
                   8295:                         my @items = split(//,$value);
                   8296:                         if (($scantron_config->{'Qon'} eq 'letter') ||
                   8297:                             ($scantron_config->{'Qon'} eq 'number')) {
                   8298:                             if (@items < $expected{$part_id}) {
                   8299:                                 my $fragment = substr($scandata,$startpos{$part_id},$expected{$part_id});
                   8300:                                 my @singles = split(//,$fragment);
                   8301:                                 foreach my $pos (@singles) {
                   8302:                                     if ($pos eq ' ') {
                   8303:                                         push(@tocheck,$pos);
                   8304:                                     } else {
                   8305:                                         my $next = shift(@items);
                   8306:                                         push(@tocheck,$next);
                   8307:                                     }
                   8308:                                 }
                   8309:                             } else {
                   8310:                                 @tocheck = @items;
                   8311:                             }
                   8312:                             foreach my $letter (@tocheck) {
                   8313:                                 if ($scantron_config->{'Qon'} eq 'letter') {
                   8314:                                     if ($letter !~ /^[A-J]$/) {
                   8315:                                         $letter = $scantron_config->{'Qoff'};
                   8316:                                     }
                   8317:                                     $recorded{$part_id} .= $letter;
                   8318:                                 } elsif ($scantron_config->{'Qon'} eq 'number') {
                   8319:                                     my $digit;
                   8320:                                     if ($letter !~ /^[A-J]$/) {
                   8321:                                         $digit = $scantron_config->{'Qoff'};
                   8322:                                     } else {
                   8323:                                         $digit = $lettdig->{$letter};
                   8324:                                     }
                   8325:                                     $recorded{$part_id} .= $digit;
                   8326:                                 }
                   8327:                             }
                   8328:                         } else {
                   8329:                             @tocheck = @items;
                   8330:                             for (my $i=0; $i<$expected{$part_id}; $i++) {
                   8331:                                 my $curr_sub = shift(@tocheck);
                   8332:                                 my $digit;
                   8333:                                 if ($curr_sub =~ /^[A-J]$/) {
                   8334:                                     $digit = $lettdig->{$curr_sub}-1;
                   8335:                                 }
                   8336:                                 if ($curr_sub eq 'J') {
                   8337:                                     $digit += scalar($numletts);
                   8338:                                 }
                   8339:                                 for (my $j=0; $j<$scantron_config->{'Qlength'}; $j++) {
                   8340:                                     if ($j == $digit) {
                   8341:                                         $recorded{$part_id} .= $scantron_config->{'Qon'};
                   8342:                                     } else {
                   8343:                                         $recorded{$part_id} .= $scantron_config->{'Qoff'};
                   8344:                                     }
                   8345:                                 }
                   8346:                             }
                   8347:                         }
                   8348:                     }
                   8349:                 }
                   8350:             }
                   8351:         }
1.554     raeburn  8352:         foreach my $part_id (@{$partids}) {
1.542     raeburn  8353:             if ($recorded{$part_id} eq '') {
                   8354:                 for (my $i=0; $i<$expected{$part_id}; $i++) {
                   8355:                     for (my $j=0; $j<$scantron_config->{'Qlength'}; $j++) {
                   8356:                         $recorded{$part_id} .= $scantron_config->{'Qoff'};
                   8357:                     }
                   8358:                 }
                   8359:             }
                   8360:             $record .= $recorded{$part_id};
                   8361:         }
                   8362:     }
                   8363:     return ($counter,$record);
                   8364: }
                   8365: 
                   8366: sub letter_to_digits { 
                   8367:     my %lettdig = (
                   8368:                     A => 1,
                   8369:                     B => 2,
                   8370:                     C => 3,
                   8371:                     D => 4,
                   8372:                     E => 5,
                   8373:                     F => 6,
                   8374:                     G => 7,
                   8375:                     H => 8,
                   8376:                     I => 9,
                   8377:                     J => 0,
                   8378:                   );
                   8379:     return %lettdig;
                   8380: }
                   8381: 
1.423     albertel 8382: 
1.75      albertel 8383: #-------- end of section for handling grading scantron forms -------
                   8384: #
                   8385: #-------------------------------------------------------------------
                   8386: 
1.72      ng       8387: #-------------------------- Menu interface -------------------------
                   8388: #
1.614     www      8389: #--- Href with symb and command ---
                   8390: 
                   8391: sub href_symb_cmd {
                   8392:     my ($symb,$cmd)=@_;
                   8393:     return '/adm/grades?symb='.&HTML::Entities::encode(&Apache::lonenc::check_encrypt($symb),'<>&"').'&command='.$cmd;
1.72      ng       8394: }
                   8395: 
1.443     banghart 8396: sub grading_menu {
1.608     www      8397:     my ($request,$symb) = @_;
1.443     banghart 8398:     if (!$symb) {return '';}
                   8399: 
                   8400:     my %fields = ('symb'=>&Apache::lonenc::check_encrypt($symb),
1.618     www      8401:                   'command'=>'individual');
1.538     schulted 8402:     
1.598     www      8403:     my $url1a = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   8404: 
                   8405:     $fields{'command'}='ungraded';
                   8406:     my $url1b=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   8407: 
                   8408:     $fields{'command'}='table';
                   8409:     my $url1c=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   8410: 
                   8411:     $fields{'command'}='all_for_one';
                   8412:     my $url1d=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   8413: 
1.621     www      8414:     $fields{'command'}='downloadfilesselect';
                   8415:     my $url1e=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   8416: 
1.443     banghart 8417:     $fields{'command'} = 'csvform';
1.538     schulted 8418:     my $url2 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   8419:     
1.443     banghart 8420:     $fields{'command'} = 'processclicker';
1.538     schulted 8421:     my $url3 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   8422:     
1.443     banghart 8423:     $fields{'command'} = 'scantron_selectphase';
1.538     schulted 8424:     my $url4 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
1.602     www      8425: 
                   8426:     $fields{'command'} = 'initialverifyreceipt';
                   8427:     my $url5 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
1.538     schulted 8428:     
1.598     www      8429:     my @menu = ({	categorytitle=>'Hand Grading',
1.538     schulted 8430:             items =>[
1.598     www      8431:                         {	linktext => 'Select individual students to grade',
                   8432:                     		url => $url1a,
1.538     schulted 8433:                     		permission => 'F',
1.636     wenzelju 8434:                     		icon => 'grade_students.png',
1.598     www      8435:                     		linktitle => 'Grade current resource for a selection of students.'
                   8436:                         }, 
                   8437:                         {       linktext => 'Grade ungraded submissions.',
                   8438:                                 url => $url1b,
                   8439:                                 permission => 'F',
1.636     wenzelju 8440:                                 icon => 'ungrade_sub.png',
1.598     www      8441:                                 linktitle => 'Grade all submissions that have not been graded yet.'
1.538     schulted 8442:                         },
1.598     www      8443: 
                   8444:                         {       linktext => 'Grading table',
                   8445:                                 url => $url1c,
                   8446:                                 permission => 'F',
1.636     wenzelju 8447:                                 icon => 'grading_table.png',
1.598     www      8448:                                 linktitle => 'Grade current resource for all students.'
                   8449:                         },
1.615     www      8450:                         {       linktext => 'Grade page/folder for one student',
1.598     www      8451:                                 url => $url1d,
                   8452:                                 permission => 'F',
1.636     wenzelju 8453:                                 icon => 'grade_PageFolder.png',
1.598     www      8454:                                 linktitle => 'Grade all resources in current page/sequence/folder for one student.'
1.621     www      8455:                         },
                   8456:                         {       linktext => 'Download submissions',
                   8457:                                 url => $url1e,
                   8458:                                 permission => 'F',
1.636     wenzelju 8459:                                 icon => 'download_sub.png',
1.621     www      8460:                                 linktitle => 'Download all students submissions.'
1.598     www      8461:                         }]},
                   8462:                          { categorytitle=>'Automated Grading',
                   8463:                items =>[
                   8464: 
1.538     schulted 8465:                 	    {	linktext => 'Upload Scores',
                   8466:                     		url => $url2,
                   8467:                     		permission => 'F',
                   8468:                     		icon => 'uploadscores.png',
                   8469:                     		linktitle => 'Specify a file containing the class scores for current resource.'
                   8470:                 	    },
                   8471:                 	    {	linktext => 'Process Clicker',
                   8472:                     		url => $url3,
                   8473:                     		permission => 'F',
                   8474:                     		icon => 'addClickerInfoFile.png',
                   8475:                     		linktitle => 'Specify a file containing the clicker information for this resource.'
                   8476:                 	    },
1.587     raeburn  8477:                 	    {	linktext => 'Grade/Manage/Review Bubblesheets',
1.538     schulted 8478:                     		url => $url4,
                   8479:                     		permission => 'F',
1.636     wenzelju 8480:                     		icon => 'bubblesheet.png',
1.538     schulted 8481:                     		linktitle => 'Grade scantron exams, upload/download scantron data files, and review previously graded scantron exams.'
1.602     www      8482:                 	    },
1.616     www      8483:                             {   linktext => 'Verify Receipt Number',
1.602     www      8484:                                 url => $url5,
                   8485:                                 permission => 'F',
1.636     wenzelju 8486:                                 icon => 'receipt_number.png',
1.602     www      8487:                                 linktitle => 'Verify a system-generated receipt number for correct problem solution.'
                   8488:                             }
                   8489: 
1.538     schulted 8490:                     ]
                   8491:             });
                   8492: 
1.443     banghart 8493:     # Create the menu
                   8494:     my $Str;
1.445     banghart 8495:     $Str .= '<form method="post" action="" name="gradingMenu">';
                   8496:     $Str .= '<input type="hidden" name="command" value="" />'.
1.618     www      8497:     	'<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
1.445     banghart 8498: 
1.602     www      8499:     $Str .= &Apache::lonhtmlcommon::generate_menu(@menu);
1.443     banghart 8500:     return $Str;    
                   8501: }
                   8502: 
1.598     www      8503: 
                   8504: sub ungraded {
                   8505:     my ($request)=@_;
                   8506:     &submit_options($request);
                   8507: }
                   8508: 
1.599     www      8509: sub submit_options_sequence {
1.608     www      8510:     my ($request,$symb) = @_;
1.599     www      8511:     if (!$symb) {return '';}
1.600     www      8512:     &commonJSfunctions($request);
                   8513:     my $result;
1.599     www      8514: 
1.600     www      8515:     $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
1.618     www      8516:         '<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
1.632     www      8517:     $result.=&selectfield(0).
1.601     www      8518:             '<input type="hidden" name="command" value="pickStudentPage" />
1.600     www      8519:             <div>
                   8520:               <input type="submit" value="'.&mt('Next').' &rarr;" />
                   8521:             </div>
                   8522:         </div>
                   8523:   </form>';
                   8524:     return $result;
                   8525: }
                   8526: 
                   8527: sub submit_options_table {
1.608     www      8528:     my ($request,$symb) = @_;
1.600     www      8529:     if (!$symb) {return '';}
1.599     www      8530:     &commonJSfunctions($request);
                   8531:     my $result;
                   8532: 
                   8533:     $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
1.618     www      8534:         '<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
1.599     www      8535: 
1.632     www      8536:     $result.=&selectfield(0).
1.601     www      8537:             '<input type="hidden" name="command" value="viewgrades" />
1.599     www      8538:             <div>
                   8539:               <input type="submit" value="'.&mt('Next').' &rarr;" />
                   8540:             </div>
                   8541:         </div>
                   8542:   </form>';
                   8543:     return $result;
                   8544: }
1.443     banghart 8545: 
1.621     www      8546: sub submit_options_download {
                   8547:     my ($request,$symb) = @_;
                   8548:     if (!$symb) {return '';}
                   8549: 
                   8550:     &commonJSfunctions($request);
                   8551: 
                   8552:     my $result='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
                   8553:         '<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
                   8554:     $result.='
                   8555: <h2>
                   8556:   '.&mt('Select Students for Which to Download Submissions').'
                   8557: </h2>'.&selectfield(1).'
                   8558:                 <input type="hidden" name="command" value="downloadfileslink" /> 
                   8559:               <input type="submit" value="'.&mt('Next').' &rarr;" />
                   8560:             </div>
                   8561:           </div>
1.600     www      8562: 
                   8563: 
1.621     www      8564:   </form>';
                   8565:     return $result;
                   8566: }
                   8567: 
1.443     banghart 8568: #--- Displays the submissions first page -------
                   8569: sub submit_options {
1.608     www      8570:     my ($request,$symb) = @_;
1.72      ng       8571:     if (!$symb) {return '';}
                   8572: 
1.118     ng       8573:     &commonJSfunctions($request);
1.473     albertel 8574:     my $result;
1.533     bisitz   8575: 
1.72      ng       8576:     $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
1.618     www      8577: 	'<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
1.632     www      8578:     $result.=&selectfield(1).'
1.601     www      8579:                 <input type="hidden" name="command" value="submission" /> 
                   8580: 	      <input type="submit" value="'.&mt('Next').' &rarr;" />
                   8581:             </div>
                   8582:           </div>
                   8583: 
                   8584: 
                   8585:   </form>';
                   8586:     return $result;
                   8587: }
1.533     bisitz   8588: 
1.601     www      8589: sub selectfield {
                   8590:    my ($full)=@_;
1.635     raeburn  8591:    my %options = 
                   8592:           (&Apache::lonlocal::texthash(
                   8593:              'yes'       => 'with submissions',
                   8594:              'queued'    => 'in grading queue',
                   8595:              'graded'    => 'with ungraded submissions',
                   8596:              'incorrect' => 'with incorrect submissions',
                   8597:              'all'       => 'with any status'),
                   8598:              'select_form_order' => ['yes','queued','graded','incorrect','all']);
1.601     www      8599:    my $result='<div class="LC_columnSection">
1.537     harmsja  8600:   
1.533     bisitz   8601:     <fieldset>
                   8602:       <legend>
                   8603:        '.&mt('Sections').'
                   8604:       </legend>
1.601     www      8605:       '.&Apache::lonstatistics::SectionSelect('section','multiple',5).'
1.533     bisitz   8606:     </fieldset>
1.537     harmsja  8607:   
1.533     bisitz   8608:     <fieldset>
                   8609:       <legend>
                   8610:         '.&mt('Groups').'
                   8611:       </legend>
                   8612:       '.&Apache::lonstatistics::GroupSelect('group','multiple',5).'
                   8613:     </fieldset>
1.537     harmsja  8614:   
1.533     bisitz   8615:     <fieldset>
                   8616:       <legend>
                   8617:         '.&mt('Access Status').'
                   8618:       </legend>
1.601     www      8619:       '.&Apache::lonhtmlcommon::StatusOptions(undef,undef,5,undef,'mult').'
                   8620:     </fieldset>';
                   8621:     if ($full) {
                   8622:        $result.='
1.533     bisitz   8623:     <fieldset>
                   8624:       <legend>
                   8625:         '.&mt('Submission Status').'
1.601     www      8626:       </legend>'.
1.635     raeburn  8627:        &Apache::loncommon::select_form('all','submitonly',\%options).
1.601     www      8628:    '</fieldset>';
                   8629:     }
                   8630:     $result.='</div><br />';
1.44      ng       8631:     return $result;
1.2       albertel 8632: }
                   8633: 
1.285     albertel 8634: sub reset_perm {
                   8635:     undef(%perm);
                   8636: }
                   8637: 
                   8638: sub init_perm {
                   8639:     &reset_perm();
1.300     albertel 8640:     foreach my $test_perm ('vgr','mgr','opa') {
                   8641: 
                   8642: 	my $scope = $env{'request.course.id'};
                   8643: 	if (!($perm{$test_perm}=&Apache::lonnet::allowed($test_perm,$scope))) {
                   8644: 
                   8645: 	    $scope .= '/'.$env{'request.course.sec'};
                   8646: 	    if ( $perm{$test_perm}=
                   8647: 		 &Apache::lonnet::allowed($test_perm,$scope)) {
                   8648: 		$perm{$test_perm.'_section'}=$env{'request.course.sec'};
                   8649: 	    } else {
                   8650: 		delete($perm{$test_perm});
                   8651: 	    }
1.285     albertel 8652: 	}
                   8653:     }
                   8654: }
                   8655: 
1.400     www      8656: sub gather_clicker_ids {
1.408     albertel 8657:     my %clicker_ids;
1.400     www      8658: 
                   8659:     my $classlist = &Apache::loncoursedata::get_classlist();
                   8660: 
                   8661:     # Set up a couple variables.
1.407     albertel 8662:     my $username_idx = &Apache::loncoursedata::CL_SNAME();
                   8663:     my $domain_idx   = &Apache::loncoursedata::CL_SDOM();
1.438     www      8664:     my $status_idx   = &Apache::loncoursedata::CL_STATUS();
1.400     www      8665: 
1.407     albertel 8666:     foreach my $student (keys(%$classlist)) {
1.438     www      8667:         if ($classlist->{$student}->[$status_idx] ne 'Active') { next; }
1.407     albertel 8668:         my $username = $classlist->{$student}->[$username_idx];
                   8669:         my $domain   = $classlist->{$student}->[$domain_idx];
1.400     www      8670:         my $clickers =
1.408     albertel 8671: 	    (&Apache::lonnet::userenvironment($domain,$username,'clickers'))[1];
1.400     www      8672:         foreach my $id (split(/\,/,$clickers)) {
1.414     www      8673:             $id=~s/^[\#0]+//;
1.421     www      8674:             $id=~s/[\-\:]//g;
1.407     albertel 8675:             if (exists($clicker_ids{$id})) {
1.408     albertel 8676: 		$clicker_ids{$id}.=','.$username.':'.$domain;
1.400     www      8677:             } else {
1.408     albertel 8678: 		$clicker_ids{$id}=$username.':'.$domain;
1.400     www      8679:             }
                   8680:         }
                   8681:     }
1.407     albertel 8682:     return %clicker_ids;
1.400     www      8683: }
                   8684: 
1.402     www      8685: sub gather_adv_clicker_ids {
1.408     albertel 8686:     my %clicker_ids;
1.402     www      8687:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
                   8688:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   8689:     my %coursepersonnel=&Apache::lonnet::get_course_adv_roles($cdom.'/'.$cnum);
1.409     albertel 8690:     foreach my $element (sort(keys(%coursepersonnel))) {
1.402     www      8691:         foreach my $person (split(/\,/,$coursepersonnel{$element})) {
                   8692:             my ($puname,$pudom)=split(/\:/,$person);
                   8693:             my $clickers =
1.408     albertel 8694: 		(&Apache::lonnet::userenvironment($pudom,$puname,'clickers'))[1];
1.405     www      8695:             foreach my $id (split(/\,/,$clickers)) {
1.414     www      8696: 		$id=~s/^[\#0]+//;
1.421     www      8697:                 $id=~s/[\-\:]//g;
1.408     albertel 8698: 		if (exists($clicker_ids{$id})) {
                   8699: 		    $clicker_ids{$id}.=','.$puname.':'.$pudom;
                   8700: 		} else {
                   8701: 		    $clicker_ids{$id}=$puname.':'.$pudom;
                   8702: 		}
1.405     www      8703:             }
1.402     www      8704:         }
                   8705:     }
1.407     albertel 8706:     return %clicker_ids;
1.402     www      8707: }
                   8708: 
1.413     www      8709: sub clicker_grading_parameters {
                   8710:     return ('gradingmechanism' => 'scalar',
                   8711:             'upfiletype' => 'scalar',
                   8712:             'specificid' => 'scalar',
                   8713:             'pcorrect' => 'scalar',
                   8714:             'pincorrect' => 'scalar');
                   8715: }
                   8716: 
1.400     www      8717: sub process_clicker {
1.608     www      8718:     my ($r,$symb)=@_;
1.400     www      8719:     if (!$symb) {return '';}
                   8720:     my $result=&checkforfile_js();
1.632     www      8721:     $result.=&Apache::loncommon::start_data_table().
                   8722:              &Apache::loncommon::start_data_table_header_row().
                   8723:              '<th>'.&mt('Specify a file containing clicker information and set grading options.').'</th>'.
                   8724:              &Apache::loncommon::end_data_table_header_row().
                   8725:              &Apache::loncommon::start_data_table_row()."<td>\n";
1.413     www      8726: # Attempt to restore parameters from last session, set defaults if not present
                   8727:     my %Saveable_Parameters=&clicker_grading_parameters();
                   8728:     &Apache::loncommon::restore_course_settings('grades_clicker',
                   8729:                                                  \%Saveable_Parameters);
                   8730:     if (!$env{'form.pcorrect'}) { $env{'form.pcorrect'}=100; }
                   8731:     if (!$env{'form.pincorrect'}) { $env{'form.pincorrect'}=100; }
                   8732:     if (!$env{'form.gradingmechanism'}) { $env{'form.gradingmechanism'}='attendance'; }
                   8733:     if (!$env{'form.upfiletype'}) { $env{'form.upfiletype'}='iclicker'; }
                   8734: 
                   8735:     my %checked;
1.521     www      8736:     foreach my $gradingmechanism ('attendance','personnel','specific','given') {
1.413     www      8737:        if ($env{'form.gradingmechanism'} eq $gradingmechanism) {
1.569     bisitz   8738:           $checked{$gradingmechanism}=' checked="checked"';
1.413     www      8739:        }
                   8740:     }
                   8741: 
1.632     www      8742:     my $upload=&mt("Evaluate File");
1.400     www      8743:     my $type=&mt("Type");
1.402     www      8744:     my $attendance=&mt("Award points just for participation");
                   8745:     my $personnel=&mt("Correctness determined from response by course personnel");
1.414     www      8746:     my $specific=&mt("Correctness determined from response with clicker ID(s)"); 
1.521     www      8747:     my $given=&mt("Correctness determined from given list of answers").' '.
                   8748:               '<font size="-2"><tt>('.&mt("Provide comma-separated list. Use '*' for any answer correct, '-' for skip").')</tt></font>';
1.402     www      8749:     my $pcorrect=&mt("Percentage points for correct solution");
                   8750:     my $pincorrect=&mt("Percentage points for incorrect solution");
1.413     www      8751:     my $selectform=&Apache::loncommon::select_form($env{'form.upfiletype'},'upfiletype',
1.635     raeburn  8752: 						   {'iclicker' => 'i>clicker',
                   8753:                                                     'interwrite' => 'interwrite PRS'});
1.418     albertel 8754:     $symb = &Apache::lonenc::check_encrypt($symb);
1.597     wenzelju 8755:     $result.= &Apache::lonhtmlcommon::scripttag(<<ENDUPFORM);
1.402     www      8756: function sanitycheck() {
                   8757: // Accept only integer percentages
                   8758:    document.forms.gradesupload.pcorrect.value=Math.round(document.forms.gradesupload.pcorrect.value);
                   8759:    document.forms.gradesupload.pincorrect.value=Math.round(document.forms.gradesupload.pincorrect.value);
                   8760: // Find out grading choice
                   8761:    for (i=0; i<document.forms.gradesupload.gradingmechanism.length; i++) {
                   8762:       if (document.forms.gradesupload.gradingmechanism[i].checked) {
                   8763:          gradingchoice=document.forms.gradesupload.gradingmechanism[i].value;
                   8764:       }
                   8765:    }
                   8766: // By default, new choice equals user selection
                   8767:    newgradingchoice=gradingchoice;
                   8768: // Not good to give more points for false answers than correct ones
                   8769:    if (Math.round(document.forms.gradesupload.pcorrect.value)<Math.round(document.forms.gradesupload.pincorrect.value)) {
                   8770:       document.forms.gradesupload.pcorrect.value=document.forms.gradesupload.pincorrect.value;
                   8771:    }
                   8772: // If new choice is attendance only, and old choice was correctness-based, restore defaults
                   8773:    if ((gradingchoice=='attendance') && (document.forms.gradesupload.waschecked.value!='attendance')) {
                   8774:       document.forms.gradesupload.pcorrect.value=100;
                   8775:       document.forms.gradesupload.pincorrect.value=100;
                   8776:    }
                   8777: // If the values are different, cannot be attendance only
                   8778:    if ((Math.round(document.forms.gradesupload.pcorrect.value)!=Math.round(document.forms.gradesupload.pincorrect.value)) &&
                   8779:        (gradingchoice=='attendance')) {
                   8780:        newgradingchoice='personnel';
                   8781:    }
                   8782: // Change grading choice to new one
                   8783:    for (i=0; i<document.forms.gradesupload.gradingmechanism.length; i++) {
                   8784:       if (document.forms.gradesupload.gradingmechanism[i].value==newgradingchoice) {
                   8785:          document.forms.gradesupload.gradingmechanism[i].checked=true;
                   8786:       } else {
                   8787:          document.forms.gradesupload.gradingmechanism[i].checked=false;
                   8788:       }
                   8789:    }
                   8790: // Remember the old state
                   8791:    document.forms.gradesupload.waschecked.value=newgradingchoice;
                   8792: }
1.597     wenzelju 8793: ENDUPFORM
                   8794:     $result.= <<ENDUPFORM;
1.400     www      8795: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
                   8796: <input type="hidden" name="symb" value="$symb" />
                   8797: <input type="hidden" name="command" value="processclickerfile" />
                   8798: <input type="file" name="upfile" size="50" />
                   8799: <br /><label>$type: $selectform</label>
1.632     www      8800: ENDUPFORM
                   8801:     $result.='</td>'.&Apache::loncommon::end_data_table_row().
                   8802:                      &Apache::loncommon::start_data_table_row().'<td>'.(<<ENDGRADINGFORM);
                   8803:       <label><input type="radio" name="gradingmechanism" value="attendance"$checked{'attendance'} onclick="sanitycheck()" />$attendance </label>
1.589     bisitz   8804: <br /><label><input type="radio" name="gradingmechanism" value="personnel"$checked{'personnel'} onclick="sanitycheck()" />$personnel</label>
                   8805: <br /><label><input type="radio" name="gradingmechanism" value="specific"$checked{'specific'} onclick="sanitycheck()" />$specific </label>
1.414     www      8806: <input type="text" name="specificid" value="$env{'form.specificid'}" size="20" />
1.589     bisitz   8807: <br /><label><input type="radio" name="gradingmechanism" value="given"$checked{'given'} onclick="sanitycheck()" />$given </label>
1.521     www      8808: <br />&nbsp;&nbsp;&nbsp;
                   8809: <input type="text" name="givenanswer" size="50" />
1.413     www      8810: <input type="hidden" name="waschecked" value="$env{'form.gradingmechanism'}" />
1.632     www      8811: ENDGRADINGFORM
                   8812:          $result.='</td>'.&Apache::loncommon::end_data_table_row().
                   8813:                      &Apache::loncommon::start_data_table_row().'<td>'.(<<ENDPERCFORM);
                   8814:       <label>$pcorrect: <input type="text" name="pcorrect" size="4" value="$env{'form.pcorrect'}" onchange="sanitycheck()" /></label>
1.589     bisitz   8815: <br /><label>$pincorrect: <input type="text" name="pincorrect" size="4" value="$env{'form.pincorrect'}" onchange="sanitycheck()" /></label>
                   8816: <br /><input type="button" onclick="javascript:checkUpload(this.form);" value="$upload" />
1.597     wenzelju 8817: </form>'
1.632     www      8818: ENDPERCFORM
                   8819:     $result.='</td>'.
                   8820:              &Apache::loncommon::end_data_table_row().
                   8821:              &Apache::loncommon::end_data_table();
1.400     www      8822:     return $result;
                   8823: }
                   8824: 
                   8825: sub process_clicker_file {
1.608     www      8826:     my ($r,$symb)=@_;
1.400     www      8827:     if (!$symb) {return '';}
1.413     www      8828: 
                   8829:     my %Saveable_Parameters=&clicker_grading_parameters();
                   8830:     &Apache::loncommon::store_course_settings('grades_clicker',
                   8831:                                               \%Saveable_Parameters);
1.598     www      8832:     my $result='';
1.404     www      8833:     if (($env{'form.gradingmechanism'} eq 'specific') && ($env{'form.specificid'}!~/\w/)) {
1.408     albertel 8834: 	$result.='<span class="LC_error">'.&mt('You need to specify a clicker ID for the correct answer').'</span>';
1.614     www      8835: 	return $result;
1.404     www      8836:     }
1.522     www      8837:     if (($env{'form.gradingmechanism'} eq 'given') && ($env{'form.givenanswer'}!~/\S/)) {
1.521     www      8838:         $result.='<span class="LC_error">'.&mt('You need to specify the correct answer').'</span>';
1.614     www      8839:         return $result;
1.521     www      8840:     }
1.522     www      8841:     my $foundgiven=0;
1.521     www      8842:     if ($env{'form.gradingmechanism'} eq 'given') {
                   8843:         $env{'form.givenanswer'}=~s/^\s*//gs;
                   8844:         $env{'form.givenanswer'}=~s/\s*$//gs;
                   8845:         $env{'form.givenanswer'}=~s/[^a-zA-Z0-9\.\*\-]+/\,/g;
                   8846:         $env{'form.givenanswer'}=uc($env{'form.givenanswer'});
1.522     www      8847:         my @answers=split(/\,/,$env{'form.givenanswer'});
                   8848:         $foundgiven=$#answers+1;
1.521     www      8849:     }
1.407     albertel 8850:     my %clicker_ids=&gather_clicker_ids();
1.408     albertel 8851:     my %correct_ids;
1.404     www      8852:     if ($env{'form.gradingmechanism'} eq 'personnel') {
1.408     albertel 8853: 	%correct_ids=&gather_adv_clicker_ids();
1.404     www      8854:     }
                   8855:     if ($env{'form.gradingmechanism'} eq 'specific') {
1.414     www      8856: 	foreach my $correct_id (split(/[\s\,]/,$env{'form.specificid'})) {;
                   8857: 	   $correct_id=~tr/a-z/A-Z/;
                   8858: 	   $correct_id=~s/\s//gs;
                   8859: 	   $correct_id=~s/^[\#0]+//;
1.421     www      8860:            $correct_id=~s/[\-\:]//g;
1.414     www      8861:            if ($correct_id) {
                   8862: 	      $correct_ids{$correct_id}='specified';
                   8863:            }
                   8864:         }
1.400     www      8865:     }
1.404     www      8866:     if ($env{'form.gradingmechanism'} eq 'attendance') {
1.408     albertel 8867: 	$result.=&mt('Score based on attendance only');
1.521     www      8868:     } elsif ($env{'form.gradingmechanism'} eq 'given') {
1.522     www      8869:         $result.=&mt('Score based on [_1] ([_2] answers)','<tt>'.$env{'form.givenanswer'}.'</tt>',$foundgiven);
1.404     www      8870:     } else {
1.408     albertel 8871: 	my $number=0;
1.411     www      8872: 	$result.='<p><b>'.&mt('Correctness determined by the following IDs').'</b>';
1.408     albertel 8873: 	foreach my $id (sort(keys(%correct_ids))) {
1.411     www      8874: 	    $result.='<br /><tt>'.$id.'</tt> - ';
1.408     albertel 8875: 	    if ($correct_ids{$id} eq 'specified') {
                   8876: 		$result.=&mt('specified');
                   8877: 	    } else {
                   8878: 		my ($uname,$udom)=split(/\:/,$correct_ids{$id});
                   8879: 		$result.=&Apache::loncommon::plainname($uname,$udom);
                   8880: 	    }
                   8881: 	    $number++;
                   8882: 	}
1.411     www      8883:         $result.="</p>\n";
1.408     albertel 8884: 	if ($number==0) {
                   8885: 	    $result.='<span class="LC_error">'.&mt('No IDs found to determine correct answer').'</span>';
1.614     www      8886: 	    return $result;
1.408     albertel 8887: 	}
1.404     www      8888:     }
1.405     www      8889:     if (length($env{'form.upfile'}) < 2) {
1.407     albertel 8890:         $result.=&mt('[_1] Error: [_2] The file you attempted to upload, [_3] contained no information. Please check that you entered the correct filename.',
                   8891: 		     '<span class="LC_error">',
                   8892: 		     '</span>',
                   8893: 		     '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>');
1.614     www      8894:         return $result;
1.405     www      8895:     }
1.410     www      8896: 
                   8897: # Were able to get all the info needed, now analyze the file
                   8898: 
1.411     www      8899:     $result.=&Apache::loncommon::studentbrowser_javascript();
1.418     albertel 8900:     $symb = &Apache::lonenc::check_encrypt($symb);
1.632     www      8901:     $result.=&Apache::loncommon::start_data_table().
                   8902:              &Apache::loncommon::start_data_table_header_row().
                   8903:              '<th>'.&mt('Evaluate clicker file').'</th>'.
                   8904:              &Apache::loncommon::end_data_table_header_row().
                   8905:              &Apache::loncommon::start_data_table_row().(<<ENDHEADER);
                   8906: <td>
1.410     www      8907: <form method="post" action="/adm/grades" name="clickeranalysis">
                   8908: <input type="hidden" name="symb" value="$symb" />
                   8909: <input type="hidden" name="command" value="assignclickergrades" />
1.411     www      8910: <input type="hidden" name="gradingmechanism" value="$env{'form.gradingmechanism'}" />
                   8911: <input type="hidden" name="pcorrect" value="$env{'form.pcorrect'}" />
                   8912: <input type="hidden" name="pincorrect" value="$env{'form.pincorrect'}" />
1.410     www      8913: ENDHEADER
1.522     www      8914:     if ($env{'form.gradingmechanism'} eq 'given') {
                   8915:        $result.='<input type="hidden" name="correct:given" value="'.$env{'form.givenanswer'}.'" />';
                   8916:     } 
1.408     albertel 8917:     my %responses;
                   8918:     my @questiontitles;
1.405     www      8919:     my $errormsg='';
                   8920:     my $number=0;
                   8921:     if ($env{'form.upfiletype'} eq 'iclicker') {
1.408     albertel 8922: 	($errormsg,$number)=&iclicker_eval(\@questiontitles,\%responses);
1.406     www      8923:     }
1.419     www      8924:     if ($env{'form.upfiletype'} eq 'interwrite') {
                   8925:         ($errormsg,$number)=&interwrite_eval(\@questiontitles,\%responses);
                   8926:     }
1.411     www      8927:     $result.='<br />'.&mt('Found [_1] question(s)',$number).'<br />'.
                   8928:              '<input type="hidden" name="number" value="'.$number.'" />'.
                   8929:              &mt('Awarding [_1] percent for correct and [_2] percent for incorrect responses',
                   8930:                  $env{'form.pcorrect'},$env{'form.pincorrect'}).
                   8931:              '<br />';
1.522     www      8932:     if (($env{'form.gradingmechanism'} eq 'given') && ($number!=$foundgiven)) {
                   8933:        $result.='<span class="LC_error">'.&mt('Number of given answers does not agree with number of questions in file.').'</span>';
1.614     www      8934:        return $result;
1.522     www      8935:     } 
1.414     www      8936: # Remember Question Titles
                   8937: # FIXME: Possibly need delimiter other than ":"
                   8938:     for (my $i=0;$i<$number;$i++) {
                   8939:         $result.='<input type="hidden" name="question:'.$i.'" value="'.
                   8940:                  &HTML::Entities::encode($questiontitles[$i],'"&<>').'" />';
                   8941:     }
1.411     www      8942:     my $correct_count=0;
                   8943:     my $student_count=0;
                   8944:     my $unknown_count=0;
1.414     www      8945: # Match answers with usernames
                   8946: # FIXME: Possibly need delimiter other than ":"
1.409     albertel 8947:     foreach my $id (keys(%responses)) {
1.410     www      8948:        if ($correct_ids{$id}) {
1.414     www      8949:           $result.="\n".'<input type="hidden" name="correct:'.$correct_count.':'.$correct_ids{$id}.'" value="'.$responses{$id}.'" />';
1.411     www      8950:           $correct_count++;
1.410     www      8951:        } elsif ($clicker_ids{$id}) {
1.437     www      8952:           if ($clicker_ids{$id}=~/\,/) {
                   8953: # More than one user with the same clicker!
1.632     www      8954:              $result.="</td>".&Apache::loncommon::end_data_table_row().
                   8955:                            &Apache::loncommon::start_data_table_row()."<td>".
                   8956:                        &mt('Clicker registered more than once').": <tt>".$id."</tt><br />";
1.437     www      8957:              $result.="\n".'<input type="hidden" name="unknown:'.$id.'" value="'.$responses{$id}.'" />'.
                   8958:                            "<select name='multi".$id."'>";
                   8959:              foreach my $reguser (sort(split(/\,/,$clicker_ids{$id}))) {
                   8960:                  $result.="<option value='".$reguser."'>".&Apache::loncommon::plainname(split(/\:/,$reguser)).' ('.$reguser.')</option>';
                   8961:              }
                   8962:              $result.='</select>';
                   8963:              $unknown_count++;
                   8964:           } else {
                   8965: # Good: found one and only one user with the right clicker
                   8966:              $result.="\n".'<input type="hidden" name="student:'.$clicker_ids{$id}.'" value="'.$responses{$id}.'" />';
                   8967:              $student_count++;
                   8968:           }
1.410     www      8969:        } else {
1.632     www      8970:           $result.="</td>".&Apache::loncommon::end_data_table_row().
                   8971:                            &Apache::loncommon::start_data_table_row()."<td>".
                   8972:                     &mt('Unregistered Clicker')." <tt>".$id."</tt><br />";
1.411     www      8973:           $result.="\n".'<input type="hidden" name="unknown:'.$id.'" value="'.$responses{$id}.'" />'.
                   8974:                    "\n".&mt("Username").": <input type='text' name='uname".$id."' />&nbsp;".
                   8975:                    "\n".&mt("Domain").": ".
                   8976:                    &Apache::loncommon::select_dom_form($env{'course.'.$env{'request.course.id'}.'.domain'},'udom'.$id).'&nbsp;'.
                   8977:                    &Apache::loncommon::selectstudent_link('clickeranalysis','uname'.$id,'udom'.$id);
                   8978:           $unknown_count++;
1.410     www      8979:        }
1.405     www      8980:     }
1.412     www      8981:     $result.='<hr />'.
                   8982:              &mt('Found [_1] registered and [_2] unregistered clickers.',$student_count,$unknown_count);
1.521     www      8983:     if (($env{'form.gradingmechanism'} ne 'attendance') && ($env{'form.gradingmechanism'} ne 'given')) {
1.412     www      8984:        if ($correct_count==0) {
                   8985:           $errormsg.="Found no correct answers answers for grading!";
                   8986:        } elsif ($correct_count>1) {
1.414     www      8987:           $result.='<br /><span class="LC_warning">'.&mt("Found [_1] entries for grading!",$correct_count).'</span>';
1.412     www      8988:        }
                   8989:     }
1.428     www      8990:     if ($number<1) {
                   8991:        $errormsg.="Found no questions.";
                   8992:     }
1.412     www      8993:     if ($errormsg) {
                   8994:        $result.='<br /><span class="LC_error">'.&mt($errormsg).'</span>';
                   8995:     } else {
                   8996:        $result.='<br /><input type="submit" name="finalize" value="'.&mt('Finalize Grading').'" />';
                   8997:     }
1.632     www      8998:     $result.='</form></td>'.
                   8999:              &Apache::loncommon::end_data_table_row().
                   9000:              &Apache::loncommon::end_data_table();
1.614     www      9001:     return $result;
1.400     www      9002: }
                   9003: 
1.405     www      9004: sub iclicker_eval {
1.406     www      9005:     my ($questiontitles,$responses)=@_;
1.405     www      9006:     my $number=0;
                   9007:     my $errormsg='';
                   9008:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
1.410     www      9009:         my %components=&Apache::loncommon::record_sep($line);
                   9010:         my @entries=map {$components{$_}} (sort(keys(%components)));
1.408     albertel 9011: 	if ($entries[0] eq 'Question') {
                   9012: 	    for (my $i=3;$i<$#entries;$i+=6) {
                   9013: 		$$questiontitles[$number]=$entries[$i];
                   9014: 		$number++;
                   9015: 	    }
                   9016: 	}
                   9017: 	if ($entries[0]=~/^\#/) {
                   9018: 	    my $id=$entries[0];
                   9019: 	    my @idresponses;
                   9020: 	    $id=~s/^[\#0]+//;
                   9021: 	    for (my $i=0;$i<$number;$i++) {
                   9022: 		my $idx=3+$i*6;
                   9023: 		push(@idresponses,$entries[$idx]);
                   9024: 	    }
                   9025: 	    $$responses{$id}=join(',',@idresponses);
                   9026: 	}
1.405     www      9027:     }
                   9028:     return ($errormsg,$number);
                   9029: }
                   9030: 
1.419     www      9031: sub interwrite_eval {
                   9032:     my ($questiontitles,$responses)=@_;
                   9033:     my $number=0;
                   9034:     my $errormsg='';
1.420     www      9035:     my $skipline=1;
                   9036:     my $questionnumber=0;
                   9037:     my %idresponses=();
1.419     www      9038:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
                   9039:         my %components=&Apache::loncommon::record_sep($line);
                   9040:         my @entries=map {$components{$_}} (sort(keys(%components)));
1.420     www      9041:         if ($entries[1] eq 'Time') { $skipline=0; next; }
                   9042:         if ($entries[1] eq 'Response') { $skipline=1; }
                   9043:         next if $skipline;
                   9044:         if ($entries[0]!=$questionnumber) {
                   9045:            $questionnumber=$entries[0];
                   9046:            $$questiontitles[$number]=&mt('Question [_1]',$questionnumber);
                   9047:            $number++;
1.419     www      9048:         }
1.420     www      9049:         my $id=$entries[4];
                   9050:         $id=~s/^[\#0]+//;
1.421     www      9051:         $id=~s/^v\d*\://i;
                   9052:         $id=~s/[\-\:]//g;
1.420     www      9053:         $idresponses{$id}[$number]=$entries[6];
                   9054:     }
1.524     raeburn  9055:     foreach my $id (keys(%idresponses)) {
1.420     www      9056:        $$responses{$id}=join(',',@{$idresponses{$id}});
                   9057:        $$responses{$id}=~s/^\s*\,//;
1.419     www      9058:     }
                   9059:     return ($errormsg,$number);
                   9060: }
                   9061: 
1.414     www      9062: sub assign_clicker_grades {
1.608     www      9063:     my ($r,$symb)=@_;
1.414     www      9064:     if (!$symb) {return '';}
1.416     www      9065: # See which part we are saving to
1.582     raeburn  9066:     my $res_error;
                   9067:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
                   9068:     if ($res_error) {
                   9069:         return &navmap_errormsg();
                   9070:     }
1.416     www      9071: # FIXME: This should probably look for the first handgradeable part
                   9072:     my $part=$$partlist[0];
                   9073: # Start screen output
1.632     www      9074:     my $result=&Apache::loncommon::start_data_table().
                   9075:              &Apache::loncommon::start_data_table_header_row().
                   9076:              '<th>'.&mt('Assigning grades based on clicker file').'</th>'.
                   9077:              &Apache::loncommon::end_data_table_header_row().
                   9078:              &Apache::loncommon::start_data_table_row().'<td>';
1.414     www      9079: # Get correct result
                   9080: # FIXME: Possibly need delimiter other than ":"
                   9081:     my @correct=();
1.415     www      9082:     my $gradingmechanism=$env{'form.gradingmechanism'};
                   9083:     my $number=$env{'form.number'};
                   9084:     if ($gradingmechanism ne 'attendance') {
1.414     www      9085:        foreach my $key (keys(%env)) {
                   9086:           if ($key=~/^form\.correct\:/) {
                   9087:              my @input=split(/\,/,$env{$key});
                   9088:              for (my $i=0;$i<=$#input;$i++) {
                   9089:                  if (($correct[$i]) && ($input[$i]) &&
                   9090:                      ($correct[$i] ne $input[$i])) {
                   9091:                     $result.='<br /><span class="LC_warning">'.
                   9092:                              &mt('More than one correct result given for question "[_1]": [_2] versus [_3].',
                   9093:                                  $env{'form.question:'.$i},$correct[$i],$input[$i]).'</span>';
                   9094:                  } elsif ($input[$i]) {
                   9095:                     $correct[$i]=$input[$i];
                   9096:                  }
                   9097:              }
                   9098:           }
                   9099:        }
1.415     www      9100:        for (my $i=0;$i<$number;$i++) {
1.414     www      9101:           if (!$correct[$i]) {
                   9102:              $result.='<br /><span class="LC_error">'.
                   9103:                       &mt('No correct result given for question "[_1]"!',
                   9104:                           $env{'form.question:'.$i}).'</span>';
                   9105:           }
                   9106:        }
                   9107:        $result.='<br />'.&mt("Correct answer: [_1]",join(', ',map { ($_?$_:'-') } @correct));
                   9108:     }
                   9109: # Start grading
1.415     www      9110:     my $pcorrect=$env{'form.pcorrect'};
                   9111:     my $pincorrect=$env{'form.pincorrect'};
1.416     www      9112:     my $storecount=0;
1.632     www      9113:     my %users=();
1.415     www      9114:     foreach my $key (keys(%env)) {
1.420     www      9115:        my $user='';
1.415     www      9116:        if ($key=~/^form\.student\:(.*)$/) {
1.420     www      9117:           $user=$1;
                   9118:        }
                   9119:        if ($key=~/^form\.unknown\:(.*)$/) {
                   9120:           my $id=$1;
                   9121:           if (($env{'form.uname'.$id}) && ($env{'form.udom'.$id})) {
                   9122:              $user=$env{'form.uname'.$id}.':'.$env{'form.udom'.$id};
1.437     www      9123:           } elsif ($env{'form.multi'.$id}) {
                   9124:              $user=$env{'form.multi'.$id};
1.420     www      9125:           }
                   9126:        }
1.632     www      9127:        if ($user) {
                   9128:           if ($users{$user}) {
                   9129:              $result.='<br /><span class="LC_warning">'.
                   9130:                       &mt("More than one entry found for <tt>[_1]</tt>!",$user).
                   9131:                       '</span><br />';
                   9132:           }
                   9133:           $users{$user}=1; 
1.415     www      9134:           my @answer=split(/\,/,$env{$key});
                   9135:           my $sum=0;
1.522     www      9136:           my $realnumber=$number;
1.415     www      9137:           for (my $i=0;$i<$number;$i++) {
1.576     www      9138:              if  ($correct[$i] eq '-') {
                   9139:                 $realnumber--;
                   9140:              } elsif ($answer[$i]) {
1.415     www      9141:                 if ($gradingmechanism eq 'attendance') {
                   9142:                    $sum+=$pcorrect;
1.576     www      9143:                 } elsif ($correct[$i] eq '*') {
1.522     www      9144:                    $sum+=$pcorrect;
1.415     www      9145:                 } else {
                   9146:                    if ($answer[$i] eq $correct[$i]) {
                   9147:                       $sum+=$pcorrect;
                   9148:                    } else {
                   9149:                       $sum+=$pincorrect;
                   9150:                    }
                   9151:                 }
                   9152:              }
                   9153:           }
1.522     www      9154:           my $ave=$sum/(100*$realnumber);
1.416     www      9155: # Store
                   9156:           my ($username,$domain)=split(/\:/,$user);
                   9157:           my %grades=();
                   9158:           $grades{"resource.$part.solved"}='correct_by_override';
                   9159:           $grades{"resource.$part.awarded"}=$ave;
                   9160:           $grades{"resource.regrader"}="$env{'user.name'}:$env{'user.domain'}";
                   9161:           my $returncode=&Apache::lonnet::cstore(\%grades,$symb,
                   9162:                                                  $env{'request.course.id'},
                   9163:                                                  $domain,$username);
                   9164:           if ($returncode ne 'ok') {
                   9165:              $result.="<br /><span class=\"LC_error\">Failed to save student $username:$domain. Message when trying to save was ($returncode)</span>";
                   9166:           } else {
                   9167:              $storecount++;
                   9168:           }
1.415     www      9169:        }
                   9170:     }
                   9171: # We are done
1.549     hauer    9172:     $result.='<br />'.&mt('Successfully stored grades for [quant,_1,student].',$storecount).
1.632     www      9173:              '</td>'.
                   9174:              &Apache::loncommon::end_data_table_row().
                   9175:              &Apache::loncommon::end_data_table();
1.614     www      9176:     return $result;
1.414     www      9177: }
                   9178: 
1.582     raeburn  9179: sub navmap_errormsg {
                   9180:     return '<div class="LC_error">'.
                   9181:            &mt('An error occurred retrieving information about resources in the course.').'<br />'.
1.595     raeburn  9182:            &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  9183:            '</div>';
                   9184: }
1.607     droeschl 9185: 
1.609     www      9186: sub startpage {
1.613     www      9187:     my ($r,$symb,$crumbs,$onlyfolderflag,$nodisplayflag) = @_;
1.614     www      9188:     unshift(@$crumbs,{href=>&href_symb_cmd($symb,'gradingmenu'),text=>"Grading"});
1.607     droeschl 9189:     $r->print(&Apache::loncommon::start_page('Grading',undef,
1.610     www      9190:                                           {'bread_crumbs' => $crumbs}));
1.639     www      9191:     &Apache::lonquickgrades::startGradeScreen($r,'grading');
1.613     www      9192:     unless ($nodisplayflag) {
                   9193:        $r->print(&Apache::lonhtmlcommon::resource_info_box($symb,$onlyfolderflag));
                   9194:     }
1.607     droeschl 9195: }
1.582     raeburn  9196: 
1.622     www      9197: sub select_problem {
                   9198:     my ($r)=@_;
1.632     www      9199:     $r->print('<h3>'.&mt('Select the problem or one of the problems you want to grade').'</h3><form action="/adm/grades">');
1.622     www      9200:     $r->print(&Apache::lonstathelpers::problem_selector('.',undef,1));
                   9201:     $r->print('<input type="hidden" name="command" value="gradingmenu" />');
                   9202:     $r->print('<input type="submit" value="'.&mt('Next').' &rarr;" /></form>');
                   9203: }
                   9204: 
1.1       albertel 9205: sub handler {
1.41      ng       9206:     my $request=$_[0];
1.434     albertel 9207:     &reset_caches();
1.257     albertel 9208:     if ($env{'browser.mathml'}) {
1.141     www      9209: 	&Apache::loncommon::content_type($request,'text/xml');
1.41      ng       9210:     } else {
1.141     www      9211: 	&Apache::loncommon::content_type($request,'text/html');
1.41      ng       9212:     }
                   9213:     $request->send_http_header;
1.44      ng       9214:     return '' if $request->header_only;
1.41      ng       9215:     &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'});
1.608     www      9216: 
                   9217: # see what command we need to execute
                   9218: 
1.160     albertel 9219:     my @commands=&Apache::loncommon::get_env_multiple('form.command');
                   9220:     my $command=$commands[0];
1.447     foxr     9221: 
1.160     albertel 9222:     if ($#commands > 0) {
                   9223: 	&Apache::lonnet::logthis("grades got multiple commands ".join(':',@commands));
                   9224:     }
1.608     www      9225: 
                   9226: # see what the symb is
                   9227: 
                   9228:     my $symb=$env{'form.symb'};
                   9229:     unless ($symb) {
                   9230:        (my $url=$env{'form.url'}) =~ s-^https*://($ENV{'SERVER_NAME'}|$ENV{'HTTP_HOST'})--;
                   9231:        $symb=&Apache::lonnet::symbread($url);
                   9232:     }
                   9233:     &Apache::lonenc::check_decrypt(\$symb);                             
                   9234: 
1.513     foxr     9235:     $ssi_error = 0;
1.637     www      9236:     if (($symb eq '' || $command eq '') && ($env{'request.course.id'})) {
1.601     www      9237: #
1.637     www      9238: # Not called from a resource, but inside a course
1.601     www      9239: #    
1.622     www      9240:         &startpage($request,undef,[],1,1);
                   9241:         &select_problem($request);
1.41      ng       9242:     } else {
1.285     albertel 9243: 	&init_perm();
1.104     albertel 9244: 	if ($command eq 'submission' && $perm{'vgr'}) {
1.608     www      9245:             &startpage($request,$symb,[{href=>"", text=>"Student Submissions"}]);
1.611     www      9246: 	    ($env{'form.student'} eq '' ? &listStudents($request,$symb) : &submission($request,0,0,$symb));
1.103     albertel 9247: 	} elsif ($command eq 'pickStudentPage' && $perm{'vgr'}) {
1.615     www      9248:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,'all_for_one'),text=>'Grade page/folder for one student'},
                   9249:                                        {href=>'',text=>'Select student'}],1,1);
1.608     www      9250: 	    &pickStudentPage($request,$symb);
1.103     albertel 9251: 	} elsif ($command eq 'displayPage' && $perm{'vgr'}) {
1.615     www      9252:             &startpage($request,$symb,
                   9253:                                       [{href=>&href_symb_cmd($symb,'all_for_one'),text=>'Grade page/folder for one student'},
                   9254:                                        {href=>'',text=>'Select student'},
                   9255:                                        {href=>'',text=>'Grade student'}],1,1);
1.608     www      9256: 	    &displayPage($request,$symb);
1.104     albertel 9257: 	} elsif ($command eq 'gradeByPage' && $perm{'mgr'}) {
1.616     www      9258:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,'all_for_one'),text=>'Grade page/folder for one student'},
                   9259:                                        {href=>'',text=>'Select student'},
                   9260:                                        {href=>'',text=>'Grade student'},
                   9261:                                        {href=>'',text=>'Store grades'}],1,1);
1.608     www      9262: 	    &updateGradeByPage($request,$symb);
1.104     albertel 9263: 	} elsif ($command eq 'processGroup' && $perm{'vgr'}) {
1.619     www      9264:             &startpage($request,$symb,[{href=>'',text=>'...'},
                   9265:                                        {href=>'',text=>'Modify grades'}]);
1.608     www      9266: 	    &processGroup($request,$symb);
1.104     albertel 9267: 	} elsif ($command eq 'gradingmenu' && $perm{'vgr'}) {
1.608     www      9268:             &startpage($request,$symb);
                   9269: 	    $request->print(&grading_menu($request,$symb));
1.598     www      9270: 	} elsif ($command eq 'individual' && $perm{'vgr'}) {
1.617     www      9271:             &startpage($request,$symb,[{href=>'',text=>'Select individual students to grade'}]);
1.608     www      9272: 	    $request->print(&submit_options($request,$symb));
1.598     www      9273:         } elsif ($command eq 'ungraded' && $perm{'vgr'}) {
1.617     www      9274:             &startpage($request,$symb,[{href=>'',text=>'Grade ungraded submissions'}]);
                   9275:             $request->print(&listStudents($request,$symb,'graded'));
1.598     www      9276:         } elsif ($command eq 'table' && $perm{'vgr'}) {
1.614     www      9277:             &startpage($request,$symb,[{href=>"", text=>"Grading table"}]);
1.611     www      9278:             $request->print(&submit_options_table($request,$symb));
1.598     www      9279:         } elsif ($command eq 'all_for_one' && $perm{'vgr'}) {
1.615     www      9280:             &startpage($request,$symb,[{href=>'',text=>'Grade page/folder for one student'}],1,1);
1.608     www      9281:             $request->print(&submit_options_sequence($request,$symb));
1.104     albertel 9282: 	} elsif ($command eq 'viewgrades' && $perm{'vgr'}) {
1.614     www      9283:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,"table"), text=>"Grading table"},{href=>'', text=>"Modify grades"}]);
1.608     www      9284: 	    $request->print(&viewgrades($request,$symb));
1.104     albertel 9285: 	} elsif ($command eq 'handgrade' && $perm{'mgr'}) {
1.620     www      9286:             &startpage($request,$symb,[{href=>'',text=>'...'},
                   9287:                                        {href=>'',text=>'Store grades'}]);
1.608     www      9288: 	    $request->print(&processHandGrade($request,$symb));
1.106     albertel 9289: 	} elsif ($command eq 'editgrades' && $perm{'mgr'}) {
1.614     www      9290:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,"table"), text=>"Grading table"},
                   9291:                                        {href=>&href_symb_cmd($symb,'viewgrades').'&group=all&section=all&Status=Active',
                   9292:                                                                              text=>"Modify grades"},
                   9293:                                        {href=>'', text=>"Store grades"}]);
1.608     www      9294: 	    $request->print(&editgrades($request,$symb));
1.602     www      9295:         } elsif ($command eq 'initialverifyreceipt' && $perm{'vgr'}) {
1.616     www      9296:             &startpage($request,$symb,[{href=>'',text=>'Verify Receipt Number'}]);
1.611     www      9297:             $request->print(&initialverifyreceipt($request,$symb));
1.106     albertel 9298: 	} elsif ($command eq 'verify' && $perm{'vgr'}) {
1.616     www      9299:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,"initialverifyreceipt"),text=>'Verify Receipt Number'},
                   9300:                                        {href=>'',text=>'Verification Result'}]);
1.608     www      9301: 	    $request->print(&verifyreceipt($request,$symb));
1.400     www      9302:         } elsif ($command eq 'processclicker' && $perm{'mgr'}) {
1.615     www      9303:             &startpage($request,$symb,[{href=>'', text=>'Process clicker'}]);
1.608     www      9304:             $request->print(&process_clicker($request,$symb));
1.400     www      9305:         } elsif ($command eq 'processclickerfile' && $perm{'mgr'}) {
1.615     www      9306:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,'processclicker'), text=>'Process clicker'},
                   9307:                                        {href=>'', text=>'Process clicker file'}]);
1.608     www      9308:             $request->print(&process_clicker_file($request,$symb));
1.414     www      9309:         } elsif ($command eq 'assignclickergrades' && $perm{'mgr'}) {
1.615     www      9310:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,'processclicker'), text=>'Process clicker'},
                   9311:                                        {href=>'', text=>'Process clicker file'},
                   9312:                                        {href=>'', text=>'Store grades'}]);
1.608     www      9313:             $request->print(&assign_clicker_grades($request,$symb));
1.106     albertel 9314: 	} elsif ($command eq 'csvform' && $perm{'mgr'}) {
1.627     www      9315:             &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
1.608     www      9316: 	    $request->print(&upcsvScores_form($request,$symb));
1.106     albertel 9317: 	} elsif ($command eq 'csvupload' && $perm{'mgr'}) {
1.627     www      9318:             &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
1.608     www      9319: 	    $request->print(&csvupload($request,$symb));
1.106     albertel 9320: 	} elsif ($command eq 'csvuploadmap' && $perm{'mgr'} ) {
1.627     www      9321:             &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
1.608     www      9322: 	    $request->print(&csvuploadmap($request,$symb));
1.246     albertel 9323: 	} elsif ($command eq 'csvuploadoptions' && $perm{'mgr'}) {
1.257     albertel 9324: 	    if ($env{'form.associate'} ne 'Reverse Association') {
1.627     www      9325:                 &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
1.608     www      9326: 		$request->print(&csvuploadoptions($request,$symb));
1.41      ng       9327: 	    } else {
1.257     albertel 9328: 		if ( $env{'form.upfile_associate'} ne 'reverse' ) {
                   9329: 		    $env{'form.upfile_associate'} = 'reverse';
1.41      ng       9330: 		} else {
1.257     albertel 9331: 		    $env{'form.upfile_associate'} = 'forward';
1.41      ng       9332: 		}
1.627     www      9333:                 &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
1.608     www      9334: 		$request->print(&csvuploadmap($request,$symb));
1.41      ng       9335: 	    }
1.246     albertel 9336: 	} elsif ($command eq 'csvuploadassign' && $perm{'mgr'} ) {
1.627     www      9337:             &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
1.608     www      9338: 	    $request->print(&csvuploadassign($request,$symb));
1.106     albertel 9339: 	} elsif ($command eq 'scantron_selectphase' && $perm{'mgr'}) {
1.616     www      9340:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
1.612     www      9341: 	    $request->print(&scantron_selectphase($request,undef,$symb));
1.203     albertel 9342:  	} elsif ($command eq 'scantron_warning' && $perm{'mgr'}) {
1.616     www      9343:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
1.608     www      9344:  	    $request->print(&scantron_do_warning($request,$symb));
1.142     albertel 9345: 	} elsif ($command eq 'scantron_validate' && $perm{'mgr'}) {
1.616     www      9346:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
1.608     www      9347: 	    $request->print(&scantron_validate_file($request,$symb));
1.106     albertel 9348: 	} elsif ($command eq 'scantron_process' && $perm{'mgr'}) {
1.616     www      9349:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
1.608     www      9350: 	    $request->print(&scantron_process_students($request,$symb));
1.157     albertel 9351:  	} elsif ($command eq 'scantronupload' && 
1.257     albertel 9352:  		 (&Apache::lonnet::allowed('usc',$env{'request.role.domain'})||
                   9353: 		  &Apache::lonnet::allowed('usc',$env{'request.course.id'}))) {
1.616     www      9354:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
1.608     www      9355:  	    $request->print(&scantron_upload_scantron_data($request,$symb)); 
1.157     albertel 9356:  	} elsif ($command eq 'scantronupload_save' &&
1.257     albertel 9357:  		 (&Apache::lonnet::allowed('usc',$env{'request.role.domain'})||
                   9358: 		  &Apache::lonnet::allowed('usc',$env{'request.course.id'}))) {
1.616     www      9359:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
1.608     www      9360:  	    $request->print(&scantron_upload_scantron_data_save($request,$symb));
1.202     albertel 9361:  	} elsif ($command eq 'scantron_download' &&
1.257     albertel 9362: 		 &Apache::lonnet::allowed('usc',$env{'request.course.id'})) {
1.616     www      9363:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
1.608     www      9364:  	    $request->print(&scantron_download_scantron_data($request,$symb));
1.523     raeburn  9365:         } elsif ($command eq 'checksubmissions' && $perm{'vgr'}) {
1.616     www      9366:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
1.621     www      9367:             $request->print(&checkscantron_results($request,$symb));
                   9368:         } elsif ($command eq 'downloadfilesselect' && $perm{'vgr'}) {
                   9369:             &startpage($request,$symb,[{href=>'', text=>'Select which submissions to download'}]);
                   9370:             $request->print(&submit_options_download($request,$symb));
                   9371:          } elsif ($command eq 'downloadfileslink' && $perm{'vgr'}) {
                   9372:             &startpage($request,$symb,
                   9373:    [{href=>&href_symb_cmd($symb,'downloadfilesselect'), text=>'Select which submissions to download'},
                   9374:     {href=>'', text=>'Download submissions'}]);
                   9375:             &submit_download_link($request,$symb);
1.106     albertel 9376: 	} elsif ($command) {
1.620     www      9377:             &startpage($request,$symb,[{href=>'', text=>'Access denied'}]);
1.562     bisitz   9378: 	    $request->print('<p class="LC_error">'.&mt('Access Denied ([_1])',$command).'</p>');
1.26      albertel 9379: 	}
1.2       albertel 9380:     }
1.513     foxr     9381:     if ($ssi_error) {
                   9382: 	&ssi_print_error($request);
                   9383:     }
1.639     www      9384:     &Apache::lonquickgrades::endGradeScreen($request);
1.353     albertel 9385:     $request->print(&Apache::loncommon::end_page());
1.434     albertel 9386:     &reset_caches();
1.44      ng       9387:     return '';
                   9388: }
                   9389: 
1.1       albertel 9390: 1;
                   9391: 
1.13      albertel 9392: __END__;
1.531     jms      9393: 
                   9394: 
                   9395: =head1 NAME
                   9396: 
                   9397: Apache::grades
                   9398: 
                   9399: =head1 SYNOPSIS
                   9400: 
                   9401: Handles the viewing of grades.
                   9402: 
                   9403: This is part of the LearningOnline Network with CAPA project
                   9404: described at http://www.lon-capa.org.
                   9405: 
                   9406: =head1 OVERVIEW
                   9407: 
                   9408: Do an ssi with retries:
                   9409: While I'd love to factor out this with the vesrion in lonprintout,
                   9410: 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
                   9411: I'm not quite ready to invent (e.g. an ssi_with_retry object).
                   9412: 
                   9413: At least the logic that drives this has been pulled out into loncommon.
                   9414: 
                   9415: 
                   9416: 
                   9417: ssi_with_retries - Does the server side include of a resource.
                   9418:                      if the ssi call returns an error we'll retry it up to
                   9419:                      the number of times requested by the caller.
                   9420:                      If we still have a proble, no text is appended to the
                   9421:                      output and we set some global variables.
                   9422:                      to indicate to the caller an SSI error occurred.  
                   9423:                      All of this is supposed to deal with the issues described
                   9424:                      in LonCAPA BZ 5631 see:
                   9425:                      http://bugs.lon-capa.org/show_bug.cgi?id=5631
                   9426:                      by informing the user that this happened.
                   9427: 
                   9428: Parameters:
                   9429:   resource   - The resource to include.  This is passed directly, without
                   9430:                interpretation to lonnet::ssi.
                   9431:   form       - The form hash parameters that guide the interpretation of the resource
                   9432:                
                   9433:   retries    - Number of retries allowed before giving up completely.
                   9434: Returns:
                   9435:   On success, returns the rendered resource identified by the resource parameter.
                   9436: Side Effects:
                   9437:   The following global variables can be set:
                   9438:    ssi_error                - If an unrecoverable error occurred this becomes true.
                   9439:                               It is up to the caller to initialize this to false
                   9440:                               if desired.
                   9441:    ssi_error_resource  - If an unrecoverable error occurred, this is the value
                   9442:                               of the resource that could not be rendered by the ssi
                   9443:                               call.
                   9444:    ssi_error_message   - The error string fetched from the ssi response
                   9445:                               in the event of an error.
                   9446: 
                   9447: 
                   9448: =head1 HANDLER SUBROUTINE
                   9449: 
                   9450: ssi_with_retries()
                   9451: 
                   9452: =head1 SUBROUTINES
                   9453: 
                   9454: =over
                   9455: 
                   9456: =item scantron_get_correction() : 
                   9457: 
                   9458:    Builds the interface screen to interact with the operator to fix a
                   9459:    specific error condition in a specific scanline
                   9460: 
                   9461:  Arguments:
                   9462:     $r           - Apache request object
                   9463:     $i           - number of the current scanline
                   9464:     $scan_record - hash ref as returned from &scantron_parse_scanline()
                   9465:     $scan_config - hash ref as returned from &get_scantron_config()
                   9466:     $line        - full contents of the current scanline
                   9467:     $error       - error condition, valid values are
                   9468:                    'incorrectCODE', 'duplicateCODE',
                   9469:                    'doublebubble', 'missingbubble',
                   9470:                    'duplicateID', 'incorrectID'
                   9471:     $arg         - extra information needed
                   9472:        For errors:
                   9473:          - duplicateID   - paper number that this studentID was seen before on
                   9474:          - duplicateCODE - array ref of the paper numbers this CODE was
                   9475:                            seen on before
                   9476:          - incorrectCODE - current incorrect CODE 
                   9477:          - doublebubble  - array ref of the bubble lines that have double
                   9478:                            bubble errors
                   9479:          - missingbubble - array ref of the bubble lines that have missing
                   9480:                            bubble errors
                   9481: 
                   9482: =item  scantron_get_maxbubble() : 
                   9483: 
1.582     raeburn  9484:    Arguments:
                   9485:        $nav_error  - Reference to scalar which is a flag to indicate a
                   9486:                       failure to retrieve a navmap object.
                   9487:        if $nav_error is set to 1 by scantron_get_maxbubble(), the 
                   9488:        calling routine should trap the error condition and display the warning
                   9489:        found in &navmap_errormsg().
                   9490: 
1.531     jms      9491:    Returns the maximum number of bubble lines that are expected to
                   9492:    occur. Does this by walking the selected sequence rendering the
                   9493:    resource and then checking &Apache::lonxml::get_problem_counter()
                   9494:    for what the current value of the problem counter is.
                   9495: 
                   9496:    Caches the results to $env{'form.scantron_maxbubble'},
                   9497:    $env{'form.scantron.bubble_lines.n'}, 
                   9498:    $env{'form.scantron.first_bubble_line.n'} and
                   9499:    $env{"form.scantron.sub_bubblelines.n"}
                   9500:    which are the total number of bubble, lines, the number of bubble
                   9501:    lines for response n and number of the first bubble line for response n,
                   9502:    and a comma separated list of numbers of bubble lines for sub-questions
                   9503:    (for optionresponse, matchresponse, and rankresponse items), for response n.  
                   9504: 
                   9505: 
                   9506: =item  scantron_validate_missingbubbles() : 
                   9507: 
                   9508:    Validates all scanlines in the selected file to not have any
                   9509:     answers that don't have bubbles that have not been verified
                   9510:     to be bubble free.
                   9511: 
                   9512: =item  scantron_process_students() : 
                   9513: 
                   9514:    Routine that does the actual grading of the bubble sheet information.
                   9515: 
                   9516:    The parsed scanline hash is added to %env 
                   9517: 
                   9518:    Then foreach unskipped scanline it does an &Apache::lonnet::ssi()
                   9519:    foreach resource , with the form data of
                   9520: 
                   9521: 	'submitted'     =>'scantron' 
                   9522: 	'grade_target'  =>'grade',
                   9523: 	'grade_username'=> username of student
                   9524: 	'grade_domain'  => domain of student
                   9525: 	'grade_courseid'=> of course
                   9526: 	'grade_symb'    => symb of resource to grade
                   9527: 
                   9528:     This triggers a grading pass. The problem grading code takes care
                   9529:     of converting the bubbled letter information (now in %env) into a
                   9530:     valid submission.
                   9531: 
                   9532: =item  scantron_upload_scantron_data() :
                   9533: 
                   9534:     Creates the screen for adding a new bubble sheet data file to a course.
                   9535: 
                   9536: =item  scantron_upload_scantron_data_save() : 
                   9537: 
                   9538:    Adds a provided bubble information data file to the course if user
                   9539:    has the correct privileges to do so. 
                   9540: 
                   9541: =item  valid_file() :
                   9542: 
                   9543:    Validates that the requested bubble data file exists in the course.
                   9544: 
                   9545: =item  scantron_download_scantron_data() : 
                   9546: 
                   9547:    Shows a list of the three internal files (original, corrected,
                   9548:    skipped) for a specific bubble sheet data file that exists in the
                   9549:    course.
                   9550: 
                   9551: =item  scantron_validate_ID() : 
                   9552: 
                   9553:    Validates all scanlines in the selected file to not have any
1.556     weissno  9554:    invalid or underspecified student/employee IDs
1.531     jms      9555: 
1.582     raeburn  9556: =item navmap_errormsg() :
                   9557: 
                   9558:    Returns HTML mark-up inside a <div></div> with a link to re-initialize the course.
                   9559:    Should be called whenever the request to instantiate a navmap object fails.  
                   9560: 
1.531     jms      9561: =back
                   9562: 
                   9563: =cut

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