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

1.17      albertel    1: # The LearningOnline Network with CAPA
1.13      albertel    2: # The LON-CAPA Grading handler
1.17      albertel    3: #
1.720   ! kruse       4: # $Id: grades.pm,v 1.719 2014/02/05 15:09:30 bisitz 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.646     raeburn    43: use Apache::Constants qw(:common :http);
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.657     raeburn    48: use Apache::bridgetask();
1.170     albertel   49: use String::Similarity;
1.359     www        50: use LONCAPA;
                     51: 
1.315     bowersj2   52: use POSIX qw(floor);
1.87      www        53: 
1.435     foxr       54: 
1.513     foxr       55: 
1.435     foxr       56: my %perm=();
1.674     raeburn    57: my %old_essays=();
1.447     foxr       58: 
1.513     foxr       59: #  These variables are used to recover from ssi errors
                     60: 
                     61: my $ssi_retries = 5;
                     62: my $ssi_error;
                     63: my $ssi_error_resource;
                     64: my $ssi_error_message;
                     65: 
                     66: 
                     67: sub ssi_with_retries {
                     68:     my ($resource, $retries, %form) = @_;
                     69:     my ($content, $response) = &Apache::loncommon::ssi_with_retries($resource, $retries, %form);
                     70:     if ($response->is_error) {
                     71: 	$ssi_error          = 1;
                     72: 	$ssi_error_resource = $resource;
                     73: 	$ssi_error_message  = $response->code . " " . $response->message;
                     74:     }
                     75: 
                     76:     return $content;
                     77: 
                     78: }
                     79: #
                     80: #  Prodcuces an ssi retry failure error message to the user:
                     81: #
                     82: 
                     83: sub ssi_print_error {
                     84:     my ($r) = @_;
1.516     raeburn    85:     my $helpurl = &Apache::loncommon::top_nav_help('Helpdesk');
                     86:     $r->print('
                     87: <br />
                     88: <h2>'.&mt('An unrecoverable network error occurred:').'</h2>
                     89: <p>
                     90: '.&mt('Unable to retrieve a resource from a server:').'<br />
                     91: '.&mt('Resource:').' '.$ssi_error_resource.'<br />
                     92: '.&mt('Error:').' '.$ssi_error_message.'
                     93: </p>
                     94: <p>'.
                     95: &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 />'.
                     96: &mt('If the error persists, please contact the [_1] for assistance.',$helpurl).
                     97: '</p>');
                     98:     return;
1.513     foxr       99: }
                    100: 
1.44      ng        101: #
1.146     albertel  102: # --- Retrieve the parts from the metadata file.---
1.598     www       103: # Returns an array of everything that the resources stores away
                    104: #
                    105: 
1.44      ng        106: sub getpartlist {
1.582     raeburn   107:     my ($symb,$errorref) = @_;
1.439     albertel  108: 
                    109:     my $navmap   = Apache::lonnavmaps::navmap->new();
1.582     raeburn   110:     unless (ref($navmap)) {
                    111:         if (ref($errorref)) { 
                    112:             $$errorref = 'navmap';
                    113:             return;
                    114:         }
                    115:     }
1.439     albertel  116:     my $res      = $navmap->getBySymb($symb);
                    117:     my $partlist = $res->parts();
                    118:     my $url      = $res->src();
                    119:     my @metakeys = split(/,/,&Apache::lonnet::metadata($url,'keys'));
                    120: 
1.146     albertel  121:     my @stores;
1.439     albertel  122:     foreach my $part (@{ $partlist }) {
1.146     albertel  123: 	foreach my $key (@metakeys) {
                    124: 	    if ($key =~ m/^stores_\Q$part\E_/) { push(@stores,$key); }
                    125: 	}
                    126:     }
                    127:     return @stores;
1.2       albertel  128: }
                    129: 
1.129     ng        130: #--- Format fullname, username:domain if different for display
                    131: #--- Use anywhere where the student names are listed
                    132: sub nameUserString {
                    133:     my ($type,$fullname,$uname,$udom) = @_;
                    134:     if ($type eq 'header') {
1.485     albertel  135: 	return '<b>&nbsp;'.&mt('Fullname').'&nbsp;</b><span class="LC_internal_info">('.&mt('Username').')</span>';
1.129     ng        136:     } else {
1.398     albertel  137: 	return '&nbsp;'.$fullname.'<span class="LC_internal_info">&nbsp;('.$uname.
                    138: 	    ($env{'user.domain'} eq $udom ? '' : ' ('.$udom.')').')</span>';
1.129     ng        139:     }
                    140: }
                    141: 
1.44      ng        142: #--- Get the partlist and the response type for a given problem. ---
                    143: #--- Indicate if a response type is coded handgraded or not. ---
1.623     www       144: #--- Sets response_error pointer to "1" if navmaps object broken ---
1.39      ng        145: sub response_type {
1.582     raeburn   146:     my ($symb,$response_error) = @_;
1.377     albertel  147: 
                    148:     my $navmap = Apache::lonnavmaps::navmap->new();
1.582     raeburn   149:     unless (ref($navmap)) {
                    150:         if (ref($response_error)) {
                    151:             $$response_error = 1;
                    152:         }
                    153:         return;
                    154:     }
1.377     albertel  155:     my $res = $navmap->getBySymb($symb);
1.593     raeburn   156:     unless (ref($res)) {
                    157:         $$response_error = 1;
                    158:         return;
                    159:     }
1.377     albertel  160:     my $partlist = $res->parts();
1.392     albertel  161:     my %vPart = 
                    162: 	map { $_ => 1 } (&Apache::loncommon::get_env_multiple('form.vPart'));
1.377     albertel  163:     my (%response_types,%handgrade);
                    164:     foreach my $part (@{ $partlist }) {
1.392     albertel  165: 	next if (%vPart && !exists($vPart{$part}));
                    166: 
1.377     albertel  167: 	my @types = $res->responseType($part);
                    168: 	my @ids = $res->responseIds($part);
                    169: 	for (my $i=0; $i < scalar(@ids); $i++) {
                    170: 	    $response_types{$part}{$ids[$i]} = $types[$i];
                    171: 	    $handgrade{$part.'_'.$ids[$i]} = 
                    172: 		&Apache::lonnet::EXT('resource.'.$part.'_'.$ids[$i].
                    173: 				     '.handgrade',$symb);
1.41      ng        174: 	}
                    175:     }
1.377     albertel  176:     return ($partlist,\%handgrade,\%response_types);
1.39      ng        177: }
                    178: 
1.375     albertel  179: sub flatten_responseType {
                    180:     my ($responseType) = @_;
                    181:     my @part_response_id =
                    182: 	map { 
                    183: 	    my $part = $_;
                    184: 	    map {
                    185: 		[$part,$_]
                    186: 		} sort(keys(%{ $responseType->{$part} }));
                    187: 	} sort(keys(%$responseType));
                    188:     return @part_response_id;
                    189: }
                    190: 
1.207     albertel  191: sub get_display_part {
1.324     albertel  192:     my ($partID,$symb)=@_;
1.207     albertel  193:     my $display=&Apache::lonnet::EXT('resource.'.$partID.'.display',$symb);
                    194:     if (defined($display) and $display ne '') {
1.577     bisitz    195:         $display.= ' (<span class="LC_internal_info">'
                    196:                   .&mt('Part ID: [_1]',$partID).'</span>)';
1.207     albertel  197:     } else {
                    198: 	$display=$partID;
                    199:     }
                    200:     return $display;
                    201: }
1.269     raeburn   202: 
1.434     albertel  203: sub reset_caches {
                    204:     &reset_analyze_cache();
                    205:     &reset_perm();
1.674     raeburn   206:     &reset_old_essays();
1.434     albertel  207: }
                    208: 
                    209: {
                    210:     my %analyze_cache;
1.557     raeburn   211:     my %analyze_cache_formkeys;
1.148     albertel  212: 
1.434     albertel  213:     sub reset_analyze_cache {
                    214: 	undef(%analyze_cache);
1.557     raeburn   215:         undef(%analyze_cache_formkeys);
1.434     albertel  216:     }
                    217: 
                    218:     sub get_analyze {
1.649     raeburn   219: 	my ($symb,$uname,$udom,$no_increment,$add_to_hash,$type,$trial,$rndseed,$bubbles_per_row)=@_;
1.434     albertel  220: 	my $key = "$symb\0$uname\0$udom";
1.640     raeburn   221:         if ($type eq 'randomizetry') {
                    222:             if ($trial ne '') {
                    223:                 $key .= "\0".$trial;
                    224:             }
                    225:         }
1.557     raeburn   226: 	if (exists($analyze_cache{$key})) {
                    227:             my $getupdate = 0;
                    228:             if (ref($add_to_hash) eq 'HASH') {
                    229:                 foreach my $item (keys(%{$add_to_hash})) {
                    230:                     if (ref($analyze_cache_formkeys{$key}) eq 'HASH') {
                    231:                         if (!exists($analyze_cache_formkeys{$key}{$item})) {
                    232:                             $getupdate = 1;
                    233:                             last;
                    234:                         }
                    235:                     } else {
                    236:                         $getupdate = 1;
                    237:                     }
                    238:                 }
                    239:             }
                    240:             if (!$getupdate) {
                    241:                 return $analyze_cache{$key};
                    242:             }
                    243:         }
1.434     albertel  244: 
                    245: 	my (undef,undef,$url)=&Apache::lonnet::decode_symb($symb);
                    246: 	$url=&Apache::lonnet::clutter($url);
1.557     raeburn   247:         my %form = ('grade_target'      => 'analyze',
                    248:                     'grade_domain'      => $udom,
                    249:                     'grade_symb'        => $symb,
                    250:                     'grade_courseid'    =>  $env{'request.course.id'},
                    251:                     'grade_username'    => $uname,
                    252:                     'grade_noincrement' => $no_increment);
1.649     raeburn   253:         if ($bubbles_per_row ne '') {
                    254:             $form{'bubbles_per_row'} = $bubbles_per_row;
                    255:         }
1.640     raeburn   256:         if ($type eq 'randomizetry') {
                    257:             $form{'grade_questiontype'} = $type;
                    258:             if ($rndseed ne '') {
                    259:                 $form{'grade_rndseed'} = $rndseed;
                    260:             }
                    261:         }
1.557     raeburn   262:         if (ref($add_to_hash)) {
                    263:             %form = (%form,%{$add_to_hash});
1.640     raeburn   264:         }
1.557     raeburn   265: 	my $subresult=&ssi_with_retries($url, $ssi_retries,%form);
1.434     albertel  266: 	(undef,$subresult)=split(/_HASH_REF__/,$subresult,2);
                    267: 	my %analyze=&Apache::lonnet::str2hash($subresult);
1.557     raeburn   268:         if (ref($add_to_hash) eq 'HASH') {
                    269:             $analyze_cache_formkeys{$key} = $add_to_hash;
                    270:         } else {
                    271:             $analyze_cache_formkeys{$key} = {};
                    272:         }
1.434     albertel  273: 	return $analyze_cache{$key} = \%analyze;
                    274:     }
                    275: 
                    276:     sub get_order {
1.640     raeburn   277: 	my ($partid,$respid,$symb,$uname,$udom,$no_increment,$type,$trial,$rndseed)=@_;
                    278: 	my $analyze = &get_analyze($symb,$uname,$udom,$no_increment,undef,$type,$trial,$rndseed);
1.434     albertel  279: 	return $analyze->{"$partid.$respid.shown"};
                    280:     }
                    281: 
                    282:     sub get_radiobutton_correct_foil {
1.640     raeburn   283: 	my ($partid,$respid,$symb,$uname,$udom,$type,$trial,$rndseed)=@_;
                    284: 	my $analyze = &get_analyze($symb,$uname,$udom,undef,undef,$type,$trial,$rndseed);
                    285:         my $foils = &get_order($partid,$respid,$symb,$uname,$udom,undef,$type,$trial,$rndseed);
1.555     raeburn   286:         if (ref($foils) eq 'ARRAY') {
                    287: 	    foreach my $foil (@{$foils}) {
                    288: 	        if ($analyze->{"$partid.$respid.foil.value.$foil"} eq 'true') {
                    289: 		    return $foil;
                    290: 	        }
1.434     albertel  291: 	    }
                    292: 	}
                    293:     }
1.554     raeburn   294: 
                    295:     sub scantron_partids_tograde {
1.649     raeburn   296:         my ($resource,$cid,$uname,$udom,$check_for_randomlist,$bubbles_per_row) = @_;
1.554     raeburn   297:         my (%analysis,@parts);
                    298:         if (ref($resource)) {
                    299:             my $symb = $resource->symb();
1.557     raeburn   300:             my $add_to_form;
                    301:             if ($check_for_randomlist) {
                    302:                 $add_to_form = { 'check_parts_withrandomlist' => 1,};
                    303:             }
1.649     raeburn   304:             my $analyze = 
                    305:                 &get_analyze($symb,$uname,$udom,undef,$add_to_form,
                    306:                              undef,undef,undef,$bubbles_per_row);
1.554     raeburn   307:             if (ref($analyze) eq 'HASH') {
                    308:                 %analysis = %{$analyze};
                    309:             }
                    310:             if (ref($analysis{'parts'}) eq 'ARRAY') {
                    311:                 foreach my $part (@{$analysis{'parts'}}) {
                    312:                     my ($id,$respid) = split(/\./,$part);
                    313:                     if (!&Apache::loncommon::check_if_partid_hidden($id,$symb,$udom,$uname)) {
                    314:                         push(@parts,$part);
                    315:                     }
                    316:                 }
                    317:             }
                    318:         }
                    319:         return (\%analysis,\@parts);
                    320:     }
                    321: 
1.148     albertel  322: }
1.434     albertel  323: 
1.118     ng        324: #--- Clean response type for display
1.335     albertel  325: #--- Currently filters option/rank/radiobutton/match/essay/Task
                    326: #        response types only.
1.118     ng        327: sub cleanRecord {
1.336     albertel  328:     my ($answer,$response,$symb,$partid,$respid,$record,$order,$version,
1.640     raeburn   329: 	$uname,$udom,$type,$trial,$rndseed) = @_;
1.398     albertel  330:     my $grayFont = '<span class="LC_internal_info">';
1.148     albertel  331:     if ($response =~ /^(option|rank)$/) {
                    332: 	my %answer=&Apache::lonnet::str2hash($answer);
1.720   ! kruse     333:         my @answer = %answer;
        !           334:         %answer = map {&HTML::Entities::encode($_, '"<>&')}  @answer;
1.148     albertel  335: 	my %grading=&Apache::lonnet::str2hash($record->{$version."resource.$partid.$respid.submissiongrading"});
                    336: 	my ($toprow,$bottomrow);
                    337: 	foreach my $foil (@$order) {
                    338: 	    if ($grading{$foil} == 1) {
                    339: 		$toprow.='<td><b>'.$answer{$foil}.'&nbsp;</b></td>';
                    340: 	    } else {
                    341: 		$toprow.='<td><i>'.$answer{$foil}.'&nbsp;</i></td>';
                    342: 	    }
1.398     albertel  343: 	    $bottomrow.='<td>'.$grayFont.$foil.'</span>&nbsp;</td>';
1.148     albertel  344: 	}
                    345: 	return '<blockquote><table border="1">'.
1.466     albertel  346: 	    '<tr valign="top"><td>'.&mt('Answer').'</td>'.$toprow.'</tr>'.
                    347: 	    '<tr valign="top"><td>'.$grayFont.&mt('Option ID').'</span></td>'.
1.660     raeburn   348: 	    $bottomrow.'</tr></table></blockquote>';
1.148     albertel  349:     } elsif ($response eq 'match') {
                    350: 	my %answer=&Apache::lonnet::str2hash($answer);
1.720   ! kruse     351:         my @answer = %answer;
        !           352:         %answer = map {&HTML::Entities::encode($_, '"<>&')}  @answer;
1.148     albertel  353: 	my %grading=&Apache::lonnet::str2hash($record->{$version."resource.$partid.$respid.submissiongrading"});
                    354: 	my @items=&Apache::lonnet::str2array($record->{$version."resource.$partid.$respid.submissionitems"});
                    355: 	my ($toprow,$middlerow,$bottomrow);
                    356: 	foreach my $foil (@$order) {
                    357: 	    my $item=shift(@items);
                    358: 	    if ($grading{$foil} == 1) {
                    359: 		$toprow.='<td><b>'.$item.'&nbsp;</b></td>';
1.398     albertel  360: 		$middlerow.='<td><b>'.$grayFont.$answer{$foil}.'&nbsp;</span></b></td>';
1.148     albertel  361: 	    } else {
                    362: 		$toprow.='<td><i>'.$item.'&nbsp;</i></td>';
1.398     albertel  363: 		$middlerow.='<td><i>'.$grayFont.$answer{$foil}.'&nbsp;</span></i></td>';
1.148     albertel  364: 	    }
1.398     albertel  365: 	    $bottomrow.='<td>'.$grayFont.$foil.'</span>&nbsp;</td>';
1.118     ng        366: 	}
1.126     ng        367: 	return '<blockquote><table border="1">'.
1.466     albertel  368: 	    '<tr valign="top"><td>'.&mt('Answer').'</td>'.$toprow.'</tr>'.
                    369: 	    '<tr valign="top"><td>'.$grayFont.&mt('Item ID').'</span></td>'.
1.148     albertel  370: 	    $middlerow.'</tr>'.
1.466     albertel  371: 	    '<tr valign="top"><td>'.$grayFont.&mt('Option ID').'</span></td>'.
1.660     raeburn   372: 	    $bottomrow.'</tr></table></blockquote>';
1.148     albertel  373:     } elsif ($response eq 'radiobutton') {
                    374: 	my %answer=&Apache::lonnet::str2hash($answer);
1.720   ! kruse     375:         my @answer = %answer;
        !           376:         %answer = map {&HTML::Entities::encode($_, '"<>&')}  @answer;
1.148     albertel  377: 	my ($toprow,$bottomrow);
1.434     albertel  378: 	my $correct = 
1.640     raeburn   379: 	    &get_radiobutton_correct_foil($partid,$respid,$symb,$uname,$udom,$type,$trial,$rndseed);
1.434     albertel  380: 	foreach my $foil (@$order) {
1.148     albertel  381: 	    if (exists($answer{$foil})) {
1.434     albertel  382: 		if ($foil eq $correct) {
1.466     albertel  383: 		    $toprow.='<td><b>'.&mt('true').'</b></td>';
1.148     albertel  384: 		} else {
1.466     albertel  385: 		    $toprow.='<td><i>'.&mt('true').'</i></td>';
1.148     albertel  386: 		}
                    387: 	    } else {
1.466     albertel  388: 		$toprow.='<td>'.&mt('false').'</td>';
1.148     albertel  389: 	    }
1.398     albertel  390: 	    $bottomrow.='<td>'.$grayFont.$foil.'</span>&nbsp;</td>';
1.148     albertel  391: 	}
                    392: 	return '<blockquote><table border="1">'.
1.466     albertel  393: 	    '<tr valign="top"><td>'.&mt('Answer').'</td>'.$toprow.'</tr>'.
                    394: 	    '<tr valign="top"><td>'.$grayFont.&mt('Option ID').'</span></td>'.
1.660     raeburn   395: 	    $bottomrow.'</tr></table></blockquote>';
1.148     albertel  396:     } elsif ($response eq 'essay') {
1.257     albertel  397: 	if (! exists ($env{'form.'.$symb})) {
1.122     ng        398: 	    my (%keyhash) = &Apache::lonnet::dump('nohist_handgrade',
1.257     albertel  399: 						  $env{'course.'.$env{'request.course.id'}.'.domain'},
                    400: 						  $env{'course.'.$env{'request.course.id'}.'.num'});
1.122     ng        401: 
1.257     albertel  402: 	    my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
                    403: 	    $env{'form.keywords'} = $keyhash{$symb.'_keywords'} ne '' ? $keyhash{$symb.'_keywords'} : '';
                    404: 	    $env{'form.kwclr'}    = $keyhash{$loginuser.'_kwclr'} ne '' ? $keyhash{$loginuser.'_kwclr'} : 'red';
                    405: 	    $env{'form.kwsize'}   = $keyhash{$loginuser.'_kwsize'} ne '' ? $keyhash{$loginuser.'_kwsize'} : '0';
                    406: 	    $env{'form.kwstyle'}  = $keyhash{$loginuser.'_kwstyle'} ne '' ? $keyhash{$loginuser.'_kwstyle'} : '';
                    407: 	    $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        408: 	}
1.166     albertel  409: 	$answer =~ s-\n-<br />-g;
1.720   ! kruse     410: 	return '<br /><br /><blockquote><tt>'.&keywords_highlight(&HTML::Entities::encode($answer, '"<>&')).'</tt></blockquote>';
        !           411: 
1.268     albertel  412:     } elsif ( $response eq 'organic') {
1.720   ! kruse     413: 	my $result='Smile representation: "<tt>'.HTML::Entities::encode($answer, '"<>&').'</tt>"';
1.268     albertel  414: 	my $jme=$record->{$version."resource.$partid.$respid.molecule"};
                    415: 	$result.=&Apache::chemresponse::jme_img($jme,$answer,400);
                    416: 	return $result;
1.335     albertel  417:     } elsif ( $response eq 'Task') {
                    418: 	if ( $answer eq 'SUBMITTED') {
                    419: 	    my $files = $record->{$version."resource.$respid.$partid.bridgetask.portfiles"};
1.336     albertel  420: 	    my $result = &Apache::bridgetask::file_list($files,$uname,$udom);
1.335     albertel  421: 	    return $result;
                    422: 	} elsif ( grep(/^\Q$version\E.*?\.instance$/, keys(%{$record})) ) {
                    423: 	    my @matches = grep(/^\Q$version\E.*?\.instance$/,
                    424: 			       keys(%{$record}));
                    425: 	    return join('<br />',($version,@matches));
                    426: 			       
                    427: 			       
                    428: 	} else {
                    429: 	    my $result =
                    430: 		'<p>'
                    431: 		.&mt('Overall result: [_1]',
                    432: 		     $record->{$version."resource.$respid.$partid.status"})
                    433: 		.'</p>';
                    434: 	    
                    435: 	    $result .= '<ul>';
                    436: 	    my @grade = grep(/^\Q${version}resource.$respid.$partid.\E[^.]*[.]status$/,
                    437: 			     keys(%{$record}));
                    438: 	    foreach my $grade (sort(@grade)) {
                    439: 		my ($dim) = ($grade =~/[.]([^.]+)[.]status$/);
                    440: 		$result.= '<li>'.&mt("Dimension: [_1], status [_2] ",
                    441: 				     $dim, $record->{$grade}).
                    442: 			  '</li>';
                    443: 	    }
                    444: 	    $result.='</ul>';
                    445: 	    return $result;
                    446: 	}
1.716     bisitz    447:     } elsif ( $response =~ m/(?:numerical|formula|custom)/) {
                    448:         # Respect multiple input fields, see Bug #5409
1.440     albertel  449: 	$answer = 
                    450: 	    &Apache::loncommon::format_previous_attempt_value('submission',
                    451: 							      $answer);
1.720   ! kruse     452: 	return $answer;
1.122     ng        453:     }
1.720   ! kruse     454:     return &HTML::Entities::encode($answer, '"<>&');
1.118     ng        455: }
                    456: 
                    457: #-- A couple of common js functions
                    458: sub commonJSfunctions {
                    459:     my $request = shift;
1.597     wenzelju  460:     $request->print(&Apache::lonhtmlcommon::scripttag(<<COMMONJSFUNCTIONS));
1.118     ng        461:     function radioSelection(radioButton) {
                    462: 	var selection=null;
                    463: 	if (radioButton.length > 1) {
                    464: 	    for (var i=0; i<radioButton.length; i++) {
                    465: 		if (radioButton[i].checked) {
                    466: 		    return radioButton[i].value;
                    467: 		}
                    468: 	    }
                    469: 	} else {
                    470: 	    if (radioButton.checked) return radioButton.value;
                    471: 	}
                    472: 	return selection;
                    473:     }
                    474: 
                    475:     function pullDownSelection(selectOne) {
                    476: 	var selection="";
                    477: 	if (selectOne.length > 1) {
                    478: 	    for (var i=0; i<selectOne.length; i++) {
                    479: 		if (selectOne[i].selected) {
                    480: 		    return selectOne[i].value;
                    481: 		}
                    482: 	    }
                    483: 	} else {
1.138     albertel  484:             // only one value it must be the selected one
                    485: 	    return selectOne.value;
1.118     ng        486: 	}
                    487:     }
                    488: COMMONJSFUNCTIONS
                    489: }
                    490: 
1.44      ng        491: #--- Dumps the class list with usernames,list of sections,
                    492: #--- section, ids and fullnames for each user.
                    493: sub getclasslist {
1.449     banghart  494:     my ($getsec,$filterlist,$getgroup) = @_;
1.291     albertel  495:     my @getsec;
1.450     banghart  496:     my @getgroup;
1.442     banghart  497:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
1.291     albertel  498:     if (!ref($getsec)) {
                    499: 	if ($getsec ne '' && $getsec ne 'all') {
                    500: 	    @getsec=($getsec);
                    501: 	}
                    502:     } else {
                    503: 	@getsec=@{$getsec};
                    504:     }
                    505:     if (grep(/^all$/,@getsec)) { undef(@getsec); }
1.450     banghart  506:     if (!ref($getgroup)) {
                    507: 	if ($getgroup ne '' && $getgroup ne 'all') {
                    508: 	    @getgroup=($getgroup);
                    509: 	}
                    510:     } else {
                    511: 	@getgroup=@{$getgroup};
                    512:     }
                    513:     if (grep(/^all$/,@getgroup)) { undef(@getgroup); }
1.291     albertel  514: 
1.449     banghart  515:     my ($classlist,$keylist)=&Apache::loncoursedata::get_classlist();
1.49      albertel  516:     # Bail out if we were unable to get the classlist
1.56      matthew   517:     return if (! defined($classlist));
1.449     banghart  518:     &Apache::loncoursedata::get_group_memberships($classlist,$keylist);
1.56      matthew   519:     #
                    520:     my %sections;
                    521:     my %fullnames;
1.205     matthew   522:     foreach my $student (keys(%$classlist)) {
                    523:         my $end      = 
                    524:             $classlist->{$student}->[&Apache::loncoursedata::CL_END()];
                    525:         my $start    = 
                    526:             $classlist->{$student}->[&Apache::loncoursedata::CL_START()];
                    527:         my $id       = 
                    528:             $classlist->{$student}->[&Apache::loncoursedata::CL_ID()];
                    529:         my $section  = 
                    530:             $classlist->{$student}->[&Apache::loncoursedata::CL_SECTION()];
                    531:         my $fullname = 
                    532:             $classlist->{$student}->[&Apache::loncoursedata::CL_FULLNAME()];
                    533:         my $status   = 
                    534:             $classlist->{$student}->[&Apache::loncoursedata::CL_STATUS()];
1.449     banghart  535:         my $group   = 
                    536:             $classlist->{$student}->[&Apache::loncoursedata::CL_GROUP()];
1.76      ng        537: 	# filter students according to status selected
1.442     banghart  538: 	if ($filterlist && (!($stu_status =~ /Any/))) {
                    539: 	    if (!($stu_status =~ $status)) {
1.450     banghart  540: 		delete($classlist->{$student});
1.76      ng        541: 		next;
                    542: 	    }
                    543: 	}
1.450     banghart  544: 	# filter students according to groups selected
1.453     banghart  545: 	my @stu_groups = split(/,/,$group);
1.450     banghart  546: 	if (@getgroup) {
                    547: 	    my $exclude = 1;
1.454     banghart  548: 	    foreach my $grp (@getgroup) {
                    549: 	        foreach my $stu_group (@stu_groups) {
1.453     banghart  550: 	            if ($stu_group eq $grp) {
                    551: 	                $exclude = 0;
                    552:     	            } 
1.450     banghart  553: 	        }
1.453     banghart  554:     	        if (($grp eq 'none') && !$group) {
                    555:         	        $exclude = 0;
                    556:         	}
1.450     banghart  557: 	    }
                    558: 	    if ($exclude) {
                    559: 	        delete($classlist->{$student});
                    560: 	    }
                    561: 	}
1.205     matthew   562: 	$section = ($section ne '' ? $section : 'none');
1.106     albertel  563: 	if (&canview($section)) {
1.291     albertel  564: 	    if (!@getsec || grep(/^\Q$section\E$/,@getsec)) {
1.103     albertel  565: 		$sections{$section}++;
1.450     banghart  566: 		if ($classlist->{$student}) {
                    567: 		    $fullnames{$student}=$fullname;
                    568: 		}
1.103     albertel  569: 	    } else {
1.205     matthew   570: 		delete($classlist->{$student});
1.103     albertel  571: 	    }
                    572: 	} else {
1.205     matthew   573: 	    delete($classlist->{$student});
1.103     albertel  574: 	}
1.44      ng        575:     }
                    576:     my %seen = ();
1.56      matthew   577:     my @sections = sort(keys(%sections));
                    578:     return ($classlist,\@sections,\%fullnames);
1.44      ng        579: }
                    580: 
1.103     albertel  581: sub canmodify {
                    582:     my ($sec)=@_;
                    583:     if ($perm{'mgr'}) {
                    584: 	if (!defined($perm{'mgr_section'})) {
                    585: 	    # can modify whole class
                    586: 	    return 1;
                    587: 	} else {
                    588: 	    if ($sec eq $perm{'mgr_section'}) {
                    589: 		#can modify the requested section
                    590: 		return 1;
                    591: 	    } else {
                    592: 		# can't modify the request section
                    593: 		return 0;
                    594: 	    }
                    595: 	}
                    596:     }
                    597:     #can't modify
                    598:     return 0;
                    599: }
                    600: 
                    601: sub canview {
                    602:     my ($sec)=@_;
                    603:     if ($perm{'vgr'}) {
                    604: 	if (!defined($perm{'vgr_section'})) {
                    605: 	    # can modify whole class
                    606: 	    return 1;
                    607: 	} else {
                    608: 	    if ($sec eq $perm{'vgr_section'}) {
                    609: 		#can modify the requested section
                    610: 		return 1;
                    611: 	    } else {
                    612: 		# can't modify the request section
                    613: 		return 0;
                    614: 	    }
                    615: 	}
                    616:     }
                    617:     #can't modify
                    618:     return 0;
                    619: }
                    620: 
1.44      ng        621: #--- Retrieve the grade status of a student for all the parts
                    622: sub student_gradeStatus {
1.324     albertel  623:     my ($symb,$udom,$uname,$partlist) = @_;
1.257     albertel  624:     my %record     = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
1.44      ng        625:     my %partstatus = ();
                    626:     foreach (@$partlist) {
1.128     ng        627: 	my ($status,undef)   = split(/_/,$record{"resource.$_.solved"},2);
1.44      ng        628: 	$status              = 'nothing' if ($status eq '');
                    629: 	$partstatus{$_}      = $status;
                    630: 	my $subkey           = "resource.$_.submitted_by";
                    631: 	$partstatus{$subkey} = $record{$subkey} if ($record{$subkey} ne '');
                    632:     }
                    633:     return %partstatus;
                    634: }
                    635: 
1.45      ng        636: # hidden form and javascript that calls the form
                    637: # Use by verifyscript and viewgrades
                    638: # Shows a student's view of problem and submission
                    639: sub jscriptNform {
1.324     albertel  640:     my ($symb) = @_;
1.442     banghart  641:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
1.597     wenzelju  642:     my $jscript= &Apache::lonhtmlcommon::scripttag(
1.45      ng        643: 	'    function viewOneStudent(user,domain) {'."\n".
                    644: 	'	document.onestudent.student.value = user;'."\n".
                    645: 	'	document.onestudent.userdom.value = domain;'."\n".
                    646: 	'	document.onestudent.submit();'."\n".
                    647: 	'    }'."\n".
1.597     wenzelju  648: 	"\n");
1.45      ng        649:     $jscript.= '<form action="/adm/grades" method="post" name="onestudent">'."\n".
1.418     albertel  650: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.442     banghart  651: 	'<input type="hidden" name="Status"  value="'.$stu_status.'" />'."\n".
1.45      ng        652: 	'<input type="hidden" name="command" value="submission" />'."\n".
                    653: 	'<input type="hidden" name="student" value="" />'."\n".
                    654: 	'<input type="hidden" name="userdom" value="" />'."\n".
                    655: 	'</form>'."\n";
                    656:     return $jscript;
                    657: }
1.39      ng        658: 
1.447     foxr      659: 
                    660: 
1.315     bowersj2  661: # Given the score (as a number [0-1] and the weight) what is the final
                    662: # point value? This function will round to the nearest tenth, third,
                    663: # or quarter if one of those is within the tolerance of .00001.
1.316     albertel  664: sub compute_points {
1.315     bowersj2  665:     my ($score, $weight) = @_;
                    666:     
                    667:     my $tolerance = .00001;
                    668:     my $points = $score * $weight;
                    669: 
                    670:     # Check for nearness to 1/x.
                    671:     my $check_for_nearness = sub {
                    672:         my ($factor) = @_;
                    673:         my $num = ($points * $factor) + $tolerance;
                    674:         my $floored_num = floor($num);
1.316     albertel  675:         if ($num - $floored_num < 2 * $tolerance * $factor) {
1.315     bowersj2  676:             return $floored_num / $factor;
                    677:         }
                    678:         return $points;
                    679:     };
                    680: 
                    681:     $points = $check_for_nearness->(10);
                    682:     $points = $check_for_nearness->(3);
                    683:     $points = $check_for_nearness->(4);
                    684:     
                    685:     return $points;
                    686: }
                    687: 
1.44      ng        688: #------------------ End of general use routines --------------------
1.87      www       689: 
                    690: #
                    691: # Find most similar essay
                    692: #
                    693: 
                    694: sub most_similar {
1.674     raeburn   695:     my ($uname,$udom,$symb,$uessay)=@_;
                    696: 
                    697:     unless ($symb) { return ''; }
                    698: 
                    699:     unless (ref($old_essays{$symb}) eq 'HASH') { return ''; }
1.87      www       700: 
                    701: # ignore spaces and punctuation
                    702: 
                    703:     $uessay=~s/\W+/ /gs;
                    704: 
1.282     www       705: # ignore empty submissions (occuring when only files are sent)
                    706: 
1.598     www       707:     unless ($uessay=~/\w+/s) { return ''; }
1.282     www       708: 
1.87      www       709: # these will be returned. Do not care if not at least 50 percent similar
1.88      www       710:     my $limit=0.6;
1.87      www       711:     my $sname='';
                    712:     my $sdom='';
                    713:     my $scrsid='';
                    714:     my $sessay='';
                    715: # go through all essays ...
1.674     raeburn   716:     foreach my $tkey (keys(%{$old_essays{$symb}})) {
1.426     albertel  717: 	my ($tname,$tdom,$tcrsid)=map {&unescape($_)} (split(/\./,$tkey));
1.87      www       718: # ... except the same student
1.426     albertel  719:         next if (($tname eq $uname) && ($tdom eq $udom));
1.674     raeburn   720: 	my $tessay=$old_essays{$symb}{$tkey};
1.426     albertel  721: 	$tessay=~s/\W+/ /gs;
1.87      www       722: # String similarity gives up if not even limit
1.426     albertel  723: 	my $tsimilar=&String::Similarity::similarity($uessay,$tessay,$limit);
1.87      www       724: # Found one
1.426     albertel  725: 	if ($tsimilar>$limit) {
                    726: 	    $limit=$tsimilar;
                    727: 	    $sname=$tname;
                    728: 	    $sdom=$tdom;
                    729: 	    $scrsid=$tcrsid;
1.674     raeburn   730: 	    $sessay=$old_essays{$symb}{$tkey};
1.426     albertel  731: 	}
1.87      www       732:     }
1.88      www       733:     if ($limit>0.6) {
1.87      www       734:        return ($sname,$sdom,$scrsid,$sessay,$limit);
                    735:     } else {
                    736:        return ('','','','',0);
                    737:     }
                    738: }
                    739: 
1.44      ng        740: #-------------------------------------------------------------------
                    741: 
                    742: #------------------------------------ Receipt Verification Routines
1.45      ng        743: #
1.602     www       744: 
                    745: sub initialverifyreceipt {
1.608     www       746:    my ($request,$symb) = @_;
1.602     www       747:    &commonJSfunctions($request);
1.694     bisitz    748:    return '<form name="gradingMenu" action=""><input type="submit" value="'.&mt('Verify Receipt Number.').'" />'.
1.602     www       749:         &Apache::lonnet::recprefix($env{'request.course.id'}).
                    750:         '-<input type="text" name="receipt" size="4" />'.
1.603     www       751:         '<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
                    752:         '<input type="hidden" name="command" value="verify" />'.
                    753:         "</form>\n";
1.602     www       754: }
                    755: 
1.44      ng        756: #--- Check whether a receipt number is valid.---
                    757: sub verifyreceipt {
1.608     www       758:     my ($request,$symb)  = @_;
1.44      ng        759: 
1.257     albertel  760:     my $courseid = $env{'request.course.id'};
1.184     www       761:     my $receipt  = &Apache::lonnet::recprefix($courseid).'-'.
1.257     albertel  762: 	$env{'form.receipt'};
1.44      ng        763:     $receipt     =~ s/[^\-\d]//g;
                    764: 
1.487     albertel  765:     my $title.=
                    766: 	'<h3><span class="LC_info">'.
1.605     www       767: 	&mt('Verifying Receipt Number [_1]',$receipt).
                    768: 	'</span></h3>'."\n";
1.44      ng        769: 
                    770:     my ($string,$contents,$matches) = ('','',0);
1.56      matthew   771:     my (undef,undef,$fullname) = &getclasslist('all','0');
1.177     albertel  772:     
                    773:     my $receiptparts=0;
1.390     albertel  774:     if ($env{"course.$courseid.receiptalg"} eq 'receipt2' ||
                    775: 	$env{"course.$courseid.receiptalg"} eq 'receipt3') { $receiptparts=1; }
1.177     albertel  776:     my $parts=['0'];
1.582     raeburn   777:     if ($receiptparts) {
                    778:         my $res_error; 
                    779:         ($parts)=&response_type($symb,\$res_error);
                    780:         if ($res_error) {
                    781:             return &navmap_errormsg();
                    782:         } 
                    783:     }
1.486     albertel  784:     
                    785:     my $header = 
                    786: 	&Apache::loncommon::start_data_table().
                    787: 	&Apache::loncommon::start_data_table_header_row().
1.487     albertel  788: 	'<th>&nbsp;'.&mt('Fullname').'&nbsp;</th>'."\n".
                    789: 	'<th>&nbsp;'.&mt('Username').'&nbsp;</th>'."\n".
                    790: 	'<th>&nbsp;'.&mt('Domain').'&nbsp;</th>';
1.486     albertel  791:     if ($receiptparts) {
1.487     albertel  792: 	$header.='<th>&nbsp;'.&mt('Problem Part').'&nbsp;</th>';
1.486     albertel  793:     }
                    794:     $header.=
                    795: 	&Apache::loncommon::end_data_table_header_row();
                    796: 
1.294     albertel  797:     foreach (sort 
                    798: 	     {
                    799: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                    800: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                    801: 		 }
                    802: 		 return $a cmp $b;
                    803: 	     } (keys(%$fullname))) {
1.44      ng        804: 	my ($uname,$udom)=split(/\:/);
1.177     albertel  805: 	foreach my $part (@$parts) {
                    806: 	    if ($receipt eq &Apache::lonnet::ireceipt($uname,$udom,$courseid,$symb,$part)) {
1.486     albertel  807: 		$contents.=
                    808: 		    &Apache::loncommon::start_data_table_row().
                    809: 		    '<td>&nbsp;'."\n".
1.177     albertel  810: 		    '<a href="javascript:viewOneStudent(\''.$uname.'\',\''.$udom.
1.417     albertel  811: 		    '\');" target="_self">'.$$fullname{$_}.'</a>&nbsp;</td>'."\n".
1.177     albertel  812: 		    '<td>&nbsp;'.$uname.'&nbsp;</td>'.
                    813: 		    '<td>&nbsp;'.$udom.'&nbsp;</td>';
                    814: 		if ($receiptparts) {
                    815: 		    $contents.='<td>&nbsp;'.$part.'&nbsp;</td>';
                    816: 		}
1.486     albertel  817: 		$contents.= 
                    818: 		    &Apache::loncommon::end_data_table_row()."\n";
1.177     albertel  819: 		
                    820: 		$matches++;
                    821: 	    }
1.44      ng        822: 	}
                    823:     }
                    824:     if ($matches == 0) {
1.584     bisitz    825:         $string = $title
                    826:                  .'<p class="LC_warning">'
                    827:                  .&mt('No match found for the above receipt number.')
                    828:                  .'</p>';
1.44      ng        829:     } else {
1.324     albertel  830: 	$string = &jscriptNform($symb).$title.
1.487     albertel  831: 	    '<p>'.
1.584     bisitz    832: 	    &mt('The above receipt number matches the following [quant,_1,student].',$matches).
1.487     albertel  833: 	    '</p>'.
1.486     albertel  834: 	    $header.
                    835: 	    $contents.
                    836: 	    &Apache::loncommon::end_data_table()."\n";
1.44      ng        837:     }
1.614     www       838:     return $string;
1.44      ng        839: }
                    840: 
                    841: #--- This is called by a number of programs.
                    842: #--- Called from the Grading Menu - View/Grade an individual student
                    843: #--- Also called directly when one clicks on the subm button 
                    844: #    on the problem page.
1.30      ng        845: sub listStudents {
1.617     www       846:     my ($request,$symb,$submitonly) = @_;
1.49      albertel  847: 
1.257     albertel  848:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
                    849:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
                    850:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
1.449     banghart  851:     my $getgroup  = $env{'form.group'} eq '' ? 'all' : $env{'form.group'};
1.617     www       852:     unless ($submitonly) {
                    853:        $submitonly= $env{'form.submitonly'} eq '' ? 'all' : $env{'form.submitonly'};
                    854:     }
1.49      albertel  855: 
1.632     www       856:     my $result='';
1.623     www       857:     my $res_error;
                    858:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
1.49      albertel  859: 
1.559     raeburn   860:     my %lt = &Apache::lonlocal::texthash (
                    861: 		'multiple' => 'Please select a student or group of students before clicking on the Next button.',
                    862: 		'single'   => 'Please select the student before clicking on the Next button.',
                    863: 	     );
1.597     wenzelju  864:     $request->print(&Apache::lonhtmlcommon::scripttag(<<LISTJAVASCRIPT));
1.110     ng        865:     function checkSelect(checkBox) {
                    866: 	var ctr=0;
                    867: 	var sense="";
                    868: 	if (checkBox.length > 1) {
                    869: 	    for (var i=0; i<checkBox.length; i++) {
                    870: 		if (checkBox[i].checked) {
                    871: 		    ctr++;
                    872: 		}
                    873: 	    }
1.485     albertel  874: 	    sense = '$lt{'multiple'}';
1.110     ng        875: 	} else {
                    876: 	    if (checkBox.checked) {
                    877: 		ctr = 1;
                    878: 	    }
1.485     albertel  879: 	    sense = '$lt{'single'}';
1.110     ng        880: 	}
                    881: 	if (ctr == 0) {
1.485     albertel  882: 	    alert(sense);
1.110     ng        883: 	    return false;
                    884: 	}
                    885: 	document.gradesub.submit();
                    886:     }
                    887: 
                    888:     function reLoadList(formname) {
1.112     ng        889: 	if (formname.saveStatusOld.value == pullDownSelection(formname.Status)) {return;}
1.110     ng        890: 	formname.command.value = 'submission';
                    891: 	formname.submit();
                    892:     }
1.45      ng        893: LISTJAVASCRIPT
                    894: 
1.118     ng        895:     &commonJSfunctions($request);
1.41      ng        896:     $request->print($result);
1.39      ng        897: 
1.154     albertel  898:     my $gradeTable='<form action="/adm/grades" method="post" name="gradesub">'.
1.598     www       899: 	"\n";
1.485     albertel  900: 	
1.561     bisitz    901:     $gradeTable .= &Apache::lonhtmlcommon::start_pick_box();
                    902:     $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('View Problem Text'))
                    903:                   .'<label><input type="radio" name="vProb" value="no" checked="checked" /> '.&mt('no').' </label>'."\n"
                    904:                   .'<label><input type="radio" name="vProb" value="yes" /> '.&mt('one student').' </label>'."\n"
                    905:                   .'<label><input type="radio" name="vProb" value="all" /> '.&mt('all students').' </label><br />'."\n"
                    906:                   .&Apache::lonhtmlcommon::row_closure();
                    907:     $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('View Answer'))
                    908:                   .'<label><input type="radio" name="vAns" value="no"  /> '.&mt('no').' </label>'."\n"
                    909:                   .'<label><input type="radio" name="vAns" value="yes" /> '.&mt('one student').' </label>'."\n"
                    910:                   .'<label><input type="radio" name="vAns" value="all" checked="checked" /> '.&mt('all students').' </label><br />'."\n"
                    911:                   .&Apache::lonhtmlcommon::row_closure();
1.485     albertel  912: 
                    913:     my $submission_options;
1.442     banghart  914:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
                    915:     my $saveStatus = $stu_status eq '' ? 'Active' : $stu_status;
1.257     albertel  916:     $env{'form.Status'} = $saveStatus;
1.485     albertel  917:     $submission_options.=
1.592     bisitz    918:         '<span class="LC_nobreak">'.
1.624     www       919:         '<label><input type="radio" name="lastSub" value="lastonly" /> '.
1.699     kruse     920:         &mt('last submission').' </label></span>'."\n".
1.592     bisitz    921:         '<span class="LC_nobreak">'.
                    922:         '<label><input type="radio" name="lastSub" value="last" /> '.
1.699     kruse     923:         &mt('last submission with details').' </label></span>'."\n".
1.592     bisitz    924:         '<span class="LC_nobreak">'.
1.628     www       925:         '<label><input type="radio" name="lastSub" value="datesub" checked="checked" /> '.
1.699     kruse     926:         &mt('all submissions').'</label></span>'."\n".
1.592     bisitz    927:         '<span class="LC_nobreak">'.
                    928:         '<label><input type="radio" name="lastSub" value="all" /> '.
1.699     kruse     929:         &mt('all submissions with details').'</label></span>';
                    930:     $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('View Submissions'))
1.561     bisitz    931:                   .$submission_options
                    932:                   .&Apache::lonhtmlcommon::row_closure();
                    933: 
                    934:     $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('Grading Increments'))
                    935:                   .'<select name="increment">'
                    936:                   .'<option value="1">'.&mt('Whole Points').'</option>'
                    937:                   .'<option value=".5">'.&mt('Half Points').'</option>'
                    938:                   .'<option value=".25">'.&mt('Quarter Points').'</option>'
                    939:                   .'<option value=".1">'.&mt('Tenths of a Point').'</option>'
                    940:                   .'</select>'
                    941:                   .&Apache::lonhtmlcommon::row_closure();
1.485     albertel  942: 
                    943:     $gradeTable .= 
1.432     banghart  944:         &build_section_inputs().
1.45      ng        945: 	'<input type="hidden" name="submitonly"  value="'.$submitonly.'" />'."\n".
1.418     albertel  946: 	'<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.110     ng        947: 	'<input type="hidden" name="saveStatusOld" value="'.$saveStatus.'" />'."\n";
                    948: 
1.618     www       949:     if (exists($env{'form.Status'})) {
1.561     bisitz    950: 	$gradeTable .= '<input type="hidden" name="Status" value="'.$stu_status.'" />'."\n";
1.124     ng        951:     } else {
1.561     bisitz    952:         $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('Student Status'))
                    953:                       .&Apache::lonhtmlcommon::StatusOptions(
                    954:                            $saveStatus,undef,1,'javascript:reLoadList(this.form);')
                    955:                       .&Apache::lonhtmlcommon::row_closure();
1.124     ng        956:     }
1.112     ng        957: 
1.561     bisitz    958:     $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('Check For Plagiarism'))
                    959:                   .'<input type="checkbox" name="checkPlag" checked="checked" />'
                    960:                   .&Apache::lonhtmlcommon::row_closure(1)
                    961:                   .&Apache::lonhtmlcommon::end_pick_box();
                    962: 
                    963:     $gradeTable .= '<p>'
1.618     www       964:                   .&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    965:                   .'<input type="hidden" name="command" value="processGroup" />'
                    966:                   .'</p>';
1.249     albertel  967: 
                    968: # checkall buttons
                    969:     $gradeTable.=&check_script('gradesub', 'stuinfo');
1.110     ng        970:     $gradeTable.='<input type="button" '."\n".
1.589     bisitz    971:         'onclick="javascript:checkSelect(this.form.stuinfo);" '."\n".
                    972:         'value="'.&mt('Next').' &rarr;" /> <br />'."\n";
1.249     albertel  973:     $gradeTable.=&check_buttons();
1.450     banghart  974:     my ($classlist, undef, $fullname) = &getclasslist($getsec,'1',$getgroup);
1.474     albertel  975:     $gradeTable.= &Apache::loncommon::start_data_table().
                    976: 	&Apache::loncommon::start_data_table_header_row();
1.110     ng        977:     my $loop = 0;
                    978:     while ($loop < 2) {
1.485     albertel  979: 	$gradeTable.='<th>'.&mt('No.').'</th><th>'.&mt('Select').'</th>'.
                    980: 	    '<th>'.&nameUserString('header').'&nbsp;'.&mt('Section/Group').'</th>';
1.618     www       981: 	if (($submitonly ne 'queued') && ($submitonly ne 'all')) {
1.485     albertel  982: 	    foreach my $part (sort(@$partlist)) {
                    983: 		my $display_part=
                    984: 		    &get_display_part((split(/_/,$part))[0],$symb);
                    985: 		$gradeTable.=
                    986: 		    '<th>'.&mt('Part: [_1] Status',$display_part).'</th>';
1.110     ng        987: 	    }
1.301     albertel  988: 	} elsif ($submitonly eq 'queued') {
1.474     albertel  989: 	    $gradeTable.='<th>'.&mt('Queue Status').'&nbsp;</th>';
1.110     ng        990: 	}
                    991: 	$loop++;
1.126     ng        992: #	$gradeTable.='<td></td>' if ($loop%2 ==1);
1.41      ng        993:     }
1.474     albertel  994:     $gradeTable.=&Apache::loncommon::end_data_table_header_row()."\n";
1.41      ng        995: 
1.45      ng        996:     my $ctr = 0;
1.294     albertel  997:     foreach my $student (sort 
                    998: 			 {
                    999: 			     if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                   1000: 				 return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                   1001: 			     }
                   1002: 			     return $a cmp $b;
                   1003: 			 }
                   1004: 			 (keys(%$fullname))) {
1.41      ng       1005: 	my ($uname,$udom) = split(/:/,$student);
1.301     albertel 1006: 
1.110     ng       1007: 	my %status = ();
1.301     albertel 1008: 
                   1009: 	if ($submitonly eq 'queued') {
                   1010: 	    my %queue_status = 
                   1011: 		&Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
                   1012: 							$udom,$uname);
                   1013: 	    next if (!defined($queue_status{'gradingqueue'}));
                   1014: 	    $status{'gradingqueue'} = $queue_status{'gradingqueue'};
                   1015: 	}
                   1016: 
1.618     www      1017: 	if (($submitonly ne 'queued') && ($submitonly ne 'all')) {
1.324     albertel 1018: 	    (%status) =&student_gradeStatus($symb,$udom,$uname,$partlist);
1.145     albertel 1019: 	    my $submitted = 0;
1.164     albertel 1020: 	    my $graded = 0;
1.248     albertel 1021: 	    my $incorrect = 0;
1.110     ng       1022: 	    foreach (keys(%status)) {
1.145     albertel 1023: 		$submitted = 1 if ($status{$_} ne 'nothing');
1.248     albertel 1024: 		$graded = 1 if ($status{$_} =~ /^ungraded/);
                   1025: 		$incorrect = 1 if ($status{$_} =~ /^incorrect/);
                   1026: 		
1.110     ng       1027: 		my ($foo,$partid,$foo1) = split(/\./,$_);
                   1028: 		if ($status{'resource.'.$partid.'.submitted_by'} ne '') {
1.145     albertel 1029: 		    $submitted = 0;
1.150     albertel 1030: 		    my ($part)=split(/\./,$partid);
1.110     ng       1031: 		    $gradeTable.='<input type="hidden" name="'.
1.150     albertel 1032: 			$student.':'.$part.':submitted_by" value="'.
1.110     ng       1033: 			$status{'resource.'.$partid.'.submitted_by'}.'" />';
                   1034: 		}
1.41      ng       1035: 	    }
1.248     albertel 1036: 	    
1.156     albertel 1037: 	    next if (!$submitted && ($submitonly eq 'yes' ||
                   1038: 				     $submitonly eq 'incorrect' ||
                   1039: 				     $submitonly eq 'graded'));
1.248     albertel 1040: 	    next if (!$graded && ($submitonly eq 'graded'));
                   1041: 	    next if (!$incorrect && $submitonly eq 'incorrect');
1.41      ng       1042: 	}
1.34      ng       1043: 
1.45      ng       1044: 	$ctr++;
1.249     albertel 1045: 	my $section = $classlist->{$student}->[&Apache::loncoursedata::CL_SECTION()];
1.452     banghart 1046:         my $group = $classlist->{$student}->[&Apache::loncoursedata::CL_GROUP()];
1.104     albertel 1047: 	if ( $perm{'vgr'} eq 'F' ) {
1.474     albertel 1048: 	    if ($ctr%2 ==1) {
                   1049: 		$gradeTable.= &Apache::loncommon::start_data_table_row();
                   1050: 	    }
1.126     ng       1051: 	    $gradeTable.='<td align="right">'.$ctr.'&nbsp;</td>'.
1.563     bisitz   1052:                '<td align="center"><label><input type="checkbox" name="stuinfo" value="'.
1.249     albertel 1053:                $student.':'.$$fullname{$student}.':::SECTION'.$section.
                   1054: 	       ')&nbsp;" />&nbsp;&nbsp;</label></td>'."\n".'<td>'.
                   1055: 	       &nameUserString(undef,$$fullname{$student},$uname,$udom).
1.474     albertel 1056: 	       '&nbsp;'.$section.($group ne '' ?'/'.$group:'').'</td>'."\n";
1.110     ng       1057: 
1.618     www      1058: 	    if ($submitonly ne 'all') {
1.524     raeburn  1059: 		foreach (sort(keys(%status))) {
1.485     albertel 1060: 		    next if ($_ =~ /^resource.*?submitted_by$/);
                   1061: 		    $gradeTable.='<td align="center">&nbsp;'.&mt($status{$_}).'&nbsp;</td>'."\n";
1.110     ng       1062: 		}
1.41      ng       1063: 	    }
1.126     ng       1064: #	    $gradeTable.='<td></td>' if ($ctr%2 ==1);
1.474     albertel 1065: 	    if ($ctr%2 ==0) {
                   1066: 		$gradeTable.=&Apache::loncommon::end_data_table_row()."\n";
                   1067: 	    }
1.41      ng       1068: 	}
                   1069:     }
1.110     ng       1070:     if ($ctr%2 ==1) {
1.126     ng       1071: 	$gradeTable.='<td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td>';
1.618     www      1072: 	    if (($submitonly ne 'queued') && ($submitonly ne 'all')) {
1.110     ng       1073: 		foreach (@$partlist) {
                   1074: 		    $gradeTable.='<td>&nbsp;</td>';
                   1075: 		}
1.301     albertel 1076: 	    } elsif ($submitonly eq 'queued') {
                   1077: 		$gradeTable.='<td>&nbsp;</td>';
1.110     ng       1078: 	    }
1.474     albertel 1079: 	$gradeTable.=&Apache::loncommon::end_data_table_row();
1.110     ng       1080:     }
                   1081: 
1.474     albertel 1082:     $gradeTable.=&Apache::loncommon::end_data_table()."\n".
1.589     bisitz   1083:         '<input type="button" '.
                   1084:         'onclick="javascript:checkSelect(this.form.stuinfo);" '.
                   1085:         'value="'.&mt('Next').' &rarr;" /></form>'."\n";
1.45      ng       1086:     if ($ctr == 0) {
1.96      albertel 1087: 	my $num_students=(scalar(keys(%$fullname)));
                   1088: 	if ($num_students eq 0) {
1.485     albertel 1089: 	    $gradeTable='<br />&nbsp;<span class="LC_warning">'.&mt('There are no students currently enrolled.').'</span>';
1.96      albertel 1090: 	} else {
1.171     albertel 1091: 	    my $submissions='submissions';
                   1092: 	    if ($submitonly eq 'incorrect') { $submissions = 'incorrect submissions'; }
                   1093: 	    if ($submitonly eq 'graded'   ) { $submissions = 'ungraded submissions'; }
1.301     albertel 1094: 	    if ($submitonly eq 'queued'   ) { $submissions = 'queued submissions'; }
1.398     albertel 1095: 	    $gradeTable='<br />&nbsp;<span class="LC_warning">'.
1.709     bisitz   1096: 		&mt('No '.$submissions.' found for this resource for any students. ([quant,_1,student] checked for '.$submissions.')',
1.485     albertel 1097: 		    $num_students).
                   1098: 		'</span><br />';
1.96      albertel 1099: 	}
1.46      ng       1100:     } elsif ($ctr == 1) {
1.474     albertel 1101: 	$gradeTable =~ s/type="checkbox"/type="checkbox" checked="checked"/;
1.45      ng       1102:     }
                   1103:     $request->print($gradeTable);
1.44      ng       1104:     return '';
1.10      ng       1105: }
                   1106: 
1.44      ng       1107: #---- Called from the listStudents routine
1.249     albertel 1108: 
                   1109: sub check_script {
                   1110:     my ($form, $type)=@_;
1.597     wenzelju 1111:     my $chkallscript= &Apache::lonhtmlcommon::scripttag('
1.249     albertel 1112:     function checkall() {
                   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=true;
                   1117:                                        }
                   1118:         }
                   1119:     }
                   1120: 
                   1121:     function checksec() {
                   1122:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
                   1123:             ele = document.forms.'.$form.'.elements[i];
                   1124:            string = document.forms.'.$form.'.chksec.value;
                   1125:            if
                   1126:           (ele.value.indexOf(":::SECTION"+string)>0) {
                   1127:               document.forms.'.$form.'.elements[i].checked=true;
                   1128:             }
                   1129:         }
                   1130:     }
                   1131: 
                   1132: 
                   1133:     function uncheckall() {
                   1134:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
                   1135:             ele = document.forms.'.$form.'.elements[i];
                   1136:             if (ele.name == "'.$type.'") {
                   1137:             document.forms.'.$form.'.elements[i].checked=false;
                   1138:                                        }
                   1139:         }
                   1140:     }
                   1141: 
1.597     wenzelju 1142: '."\n");
1.249     albertel 1143:     return $chkallscript;
                   1144: }
                   1145: 
                   1146: sub check_buttons {
1.485     albertel 1147:     my $buttons.='<input type="button" onclick="checkall()" value="'.&mt('Check All').'" />';
                   1148:     $buttons.='<input type="button" onclick="uncheckall()" value="'.&mt('Uncheck All').'" />&nbsp;';
                   1149:     $buttons.='<input type="button" onclick="checksec()" value="'.&mt('Check Section/Group').'" />';
1.249     albertel 1150:     $buttons.='<input type="text" size="5" name="chksec" />&nbsp;';
                   1151:     return $buttons;
                   1152: }
                   1153: 
1.44      ng       1154: #     Displays the submissions for one student or a group of students
1.34      ng       1155: sub processGroup {
1.619     www      1156:     my ($request,$symb)  = @_;
1.41      ng       1157:     my $ctr        = 0;
1.155     albertel 1158:     my @stuchecked = &Apache::loncommon::get_env_multiple('form.stuinfo');
1.41      ng       1159:     my $total      = scalar(@stuchecked)-1;
1.45      ng       1160: 
1.396     banghart 1161:     foreach my $student (@stuchecked) {
                   1162: 	my ($uname,$udom,$fullname) = split(/:/,$student);
1.257     albertel 1163: 	$env{'form.student'}        = $uname;
                   1164: 	$env{'form.userdom'}        = $udom;
                   1165: 	$env{'form.fullname'}       = $fullname;
1.619     www      1166: 	&submission($request,$ctr,$total,$symb);
1.41      ng       1167: 	$ctr++;
                   1168:     }
                   1169:     return '';
1.35      ng       1170: }
1.34      ng       1171: 
1.44      ng       1172: #------------------------------------------------------------------------------------
                   1173: #
                   1174: #-------------------------- Next few routines handles grading by student, essentially
                   1175: #                           handles essay response type problem/part
                   1176: #
                   1177: #--- Javascript to handle the submission page functionality ---
                   1178: sub sub_page_js {
                   1179:     my $request = shift;
1.539     riegler  1180: 	    my $alertmsg = &mt('A number equal or greater than 0 is expected. Entered value = ');
1.597     wenzelju 1181:     $request->print(&Apache::lonhtmlcommon::scripttag(<<SUBJAVASCRIPT));
1.71      ng       1182:     function updateRadio(formname,id,weight) {
1.125     ng       1183: 	var gradeBox = formname["GD_BOX"+id];
                   1184: 	var radioButton = formname["RADVAL"+id];
                   1185: 	var oldpts = formname["oldpts"+id].value;
1.72      ng       1186: 	var pts = checkSolved(formname,id) == 'update' ? gradeBox.value : oldpts;
1.71      ng       1187: 	gradeBox.value = pts;
                   1188: 	var resetbox = false;
                   1189: 	if (isNaN(pts) || pts < 0) {
1.539     riegler  1190: 	    alert("$alertmsg"+pts);
1.71      ng       1191: 	    for (var i=0; i<radioButton.length; i++) {
                   1192: 		if (radioButton[i].checked) {
                   1193: 		    gradeBox.value = i;
                   1194: 		    resetbox = true;
                   1195: 		}
                   1196: 	    }
                   1197: 	    if (!resetbox) {
                   1198: 		formtextbox.value = "";
                   1199: 	    }
                   1200: 	    return;
1.44      ng       1201: 	}
1.71      ng       1202: 
                   1203: 	if (pts > weight) {
                   1204: 	    var resp = confirm("You entered a value ("+pts+
                   1205: 			       ") greater than the weight for the part. Accept?");
                   1206: 	    if (resp == false) {
1.125     ng       1207: 		gradeBox.value = oldpts;
1.71      ng       1208: 		return;
                   1209: 	    }
1.44      ng       1210: 	}
1.13      albertel 1211: 
1.71      ng       1212: 	for (var i=0; i<radioButton.length; i++) {
                   1213: 	    radioButton[i].checked=false;
                   1214: 	    if (pts == i && pts != "") {
                   1215: 		radioButton[i].checked=true;
                   1216: 	    }
                   1217: 	}
                   1218: 	updateSelect(formname,id);
1.125     ng       1219: 	formname["stores"+id].value = "0";
1.41      ng       1220:     }
1.5       albertel 1221: 
1.72      ng       1222:     function writeBox(formname,id,pts) {
1.125     ng       1223: 	var gradeBox = formname["GD_BOX"+id];
1.71      ng       1224: 	if (checkSolved(formname,id) == 'update') {
                   1225: 	    gradeBox.value = pts;
                   1226: 	} else {
1.125     ng       1227: 	    var oldpts = formname["oldpts"+id].value;
1.72      ng       1228: 	    gradeBox.value = oldpts;
1.125     ng       1229: 	    var radioButton = formname["RADVAL"+id];
1.71      ng       1230: 	    for (var i=0; i<radioButton.length; i++) {
                   1231: 		radioButton[i].checked=false;
1.72      ng       1232: 		if (i == oldpts) {
1.71      ng       1233: 		    radioButton[i].checked=true;
                   1234: 		}
                   1235: 	    }
1.41      ng       1236: 	}
1.125     ng       1237: 	formname["stores"+id].value = "0";
1.71      ng       1238: 	updateSelect(formname,id);
                   1239: 	return;
1.41      ng       1240:     }
1.44      ng       1241: 
1.71      ng       1242:     function clearRadBox(formname,id) {
                   1243: 	if (checkSolved(formname,id) == 'noupdate') {
                   1244: 	    updateSelect(formname,id);
                   1245: 	    return;
                   1246: 	}
1.125     ng       1247: 	gradeSelect = formname["GD_SEL"+id];
1.71      ng       1248: 	for (var i=0; i<gradeSelect.length; i++) {
                   1249: 	    if (gradeSelect[i].selected) {
                   1250: 		var selectx=i;
                   1251: 	    }
                   1252: 	}
1.125     ng       1253: 	var stores = formname["stores"+id];
1.71      ng       1254: 	if (selectx == stores.value) { return };
1.125     ng       1255: 	var gradeBox = formname["GD_BOX"+id];
1.71      ng       1256: 	gradeBox.value = "";
1.125     ng       1257: 	var radioButton = formname["RADVAL"+id];
1.71      ng       1258: 	for (var i=0; i<radioButton.length; i++) {
                   1259: 	    radioButton[i].checked=false;
                   1260: 	}
                   1261: 	stores.value = selectx;
                   1262:     }
1.5       albertel 1263: 
1.71      ng       1264:     function checkSolved(formname,id) {
1.125     ng       1265: 	if (formname["solved"+id].value == "correct_by_student" && formname.overRideScore.value == 'no') {
1.118     ng       1266: 	    var reply = confirm("This problem has been graded correct by the computer. Do you want to change the score?");
                   1267: 	    if (!reply) {return "noupdate";}
1.120     ng       1268: 	    formname.overRideScore.value = 'yes';
1.41      ng       1269: 	}
1.71      ng       1270: 	return "update";
1.13      albertel 1271:     }
1.71      ng       1272: 
                   1273:     function updateSelect(formname,id) {
1.125     ng       1274: 	formname["GD_SEL"+id][0].selected = true;
1.71      ng       1275: 	return;
1.41      ng       1276:     }
1.33      ng       1277: 
1.121     ng       1278: //=========== Check that a point is assigned for all the parts  ============
1.71      ng       1279:     function checksubmit(formname,val,total,parttot) {
1.121     ng       1280: 	formname.gradeOpt.value = val;
1.71      ng       1281: 	if (val == "Save & Next") {
                   1282: 	    for (i=0;i<=total;i++) {
                   1283: 		for (j=0;j<parttot;j++) {
1.125     ng       1284: 		    var partid = formname["partid"+i+"_"+j].value;
1.127     ng       1285: 		    if (formname["GD_SEL"+i+"_"+partid][0].selected) {
1.125     ng       1286: 			var points = formname["GD_BOX"+i+"_"+partid].value;
1.71      ng       1287: 			if (points == "") {
1.125     ng       1288: 			    var name = formname["name"+i].value;
1.129     ng       1289: 			    var studentID = (name != '' ? name : formname["unamedom"+i].value);
                   1290: 			    var resp = confirm("You did not assign a score for "+studentID+
                   1291: 					       ", part "+partid+". Continue?");
1.71      ng       1292: 			    if (resp == false) {
1.125     ng       1293: 				formname["GD_BOX"+i+"_"+partid].focus();
1.71      ng       1294: 				return false;
                   1295: 			    }
                   1296: 			}
                   1297: 		    }
                   1298: 		    
                   1299: 		}
                   1300: 	    }
                   1301: 	    
                   1302: 	}
1.120     ng       1303: 	formname.submit();
                   1304:     }
                   1305: 
1.71      ng       1306: //======= Check that a score is assigned for all the problems (page/sequence grading only) =========
                   1307:     function checkSubmitPage(formname,total) {
                   1308: 	noscore = new Array(100);
                   1309: 	var ptr = 0;
                   1310: 	for (i=1;i<total;i++) {
1.125     ng       1311: 	    var partid = formname["q_"+i].value;
1.127     ng       1312: 	    if (formname["GD_SEL"+i+"_"+partid][0].selected) {
1.125     ng       1313: 		var points = formname["GD_BOX"+i+"_"+partid].value;
                   1314: 		var status = formname["solved"+i+"_"+partid].value;
1.71      ng       1315: 		if (points == "" && status != "correct_by_student") {
                   1316: 		    noscore[ptr] = i;
                   1317: 		    ptr++;
                   1318: 		}
                   1319: 	    }
                   1320: 	}
                   1321: 	if (ptr != 0) {
                   1322: 	    var sense = ptr == 1 ? ": " : "s: ";
                   1323: 	    var prolist = "";
                   1324: 	    if (ptr == 1) {
                   1325: 		prolist = noscore[0];
                   1326: 	    } else {
                   1327: 		var i = 0;
                   1328: 		while (i < ptr-1) {
                   1329: 		    prolist += noscore[i]+", ";
                   1330: 		    i++;
                   1331: 		}
                   1332: 		prolist += "and "+noscore[i];
                   1333: 	    }
                   1334: 	    var resp = confirm("You did not assign any score for the following problem"+sense+prolist+". Continue?");
                   1335: 	    if (resp == false) {
                   1336: 		return false;
                   1337: 	    }
                   1338: 	}
1.45      ng       1339: 
1.71      ng       1340: 	formname.submit();
                   1341:     }
                   1342: SUBJAVASCRIPT
                   1343: }
1.45      ng       1344: 
1.71      ng       1345: #--- javascript for essay type problem --
                   1346: sub sub_page_kw_js {
                   1347:     my $request = shift;
1.80      ng       1348:     my $iconpath = $request->dir_config('lonIconsURL');
1.118     ng       1349:     &commonJSfunctions($request);
1.350     albertel 1350: 
1.629     www      1351:     my $inner_js_msg_central= (<<INNERJS);
                   1352: <script type="text/javascript">
1.350     albertel 1353:     function checkInput() {
                   1354:       opener.document.SCORE.msgsub.value = opener.checkEntities(document.msgcenter.msgsub.value);
                   1355:       var nmsg   = opener.document.SCORE.savemsgN.value;
                   1356:       var usrctr = document.msgcenter.usrctr.value;
                   1357:       var newval = opener.document.SCORE["newmsg"+usrctr];
                   1358:       newval.value = opener.checkEntities(document.msgcenter.newmsg.value);
                   1359: 
                   1360:       var msgchk = "";
                   1361:       if (document.msgcenter.subchk.checked) {
                   1362:          msgchk = "msgsub,";
                   1363:       }
                   1364:       var includemsg = 0;
                   1365:       for (var i=1; i<=nmsg; i++) {
                   1366:           var opnmsg = opener.document.SCORE["savemsg"+i];
                   1367:           var frmmsg = document.msgcenter["msg"+i];
                   1368:           opnmsg.value = opener.checkEntities(frmmsg.value);
                   1369:           var showflg = opener.document.SCORE["shownOnce"+i];
                   1370:           showflg.value = "1";
                   1371:           var chkbox = document.msgcenter["msgn"+i];
                   1372:           if (chkbox.checked) {
                   1373:              msgchk += "savemsg"+i+",";
                   1374:              includemsg = 1;
                   1375:           }
                   1376:       }
                   1377:       if (document.msgcenter.newmsgchk.checked) {
                   1378:          msgchk += "newmsg"+usrctr;
                   1379:          includemsg = 1;
                   1380:       }
                   1381:       imgformname = opener.document.SCORE["mailicon"+usrctr];
                   1382:       imgformname.src = "$iconpath/"+((includemsg) ? "mailto.gif" : "mailbkgrd.gif");
                   1383:       var includemsg = opener.document.SCORE["includemsg"+usrctr];
                   1384:       includemsg.value = msgchk;
                   1385: 
                   1386:       self.close()
                   1387: 
                   1388:     }
1.629     www      1389: </script>
1.350     albertel 1390: INNERJS
                   1391: 
1.629     www      1392:     my $inner_js_highlight_central= (<<INNERJS);
                   1393: <script type="text/javascript">
1.351     albertel 1394:     function updateChoice(flag) {
                   1395:       opener.document.SCORE.kwclr.value = opener.radioSelection(document.hlCenter.kwdclr);
                   1396:       opener.document.SCORE.kwsize.value = opener.radioSelection(document.hlCenter.kwdsize);
                   1397:       opener.document.SCORE.kwstyle.value = opener.radioSelection(document.hlCenter.kwdstyle);
                   1398:       opener.document.SCORE.refresh.value = "on";
                   1399:       if (opener.document.SCORE.keywords.value!=""){
                   1400:          opener.document.SCORE.submit();
                   1401:       }
                   1402:       self.close()
                   1403:     }
1.629     www      1404: </script>
1.351     albertel 1405: INNERJS
                   1406: 
                   1407:     my $start_page_msg_central = 
                   1408:         &Apache::loncommon::start_page('Message Central',$inner_js_msg_central,
                   1409: 				       {'js_ready'  => 1,
                   1410: 					'only_body' => 1,
                   1411: 					'bgcolor'   =>'#FFFFFF',});
                   1412:     my $end_page_msg_central = 
                   1413: 	&Apache::loncommon::end_page({'js_ready' => 1});
                   1414: 
                   1415: 
                   1416:     my $start_page_highlight_central = 
                   1417:         &Apache::loncommon::start_page('Highlight Central',
                   1418: 				       $inner_js_highlight_central,
1.350     albertel 1419: 				       {'js_ready'  => 1,
                   1420: 					'only_body' => 1,
                   1421: 					'bgcolor'   =>'#FFFFFF',});
1.351     albertel 1422:     my $end_page_highlight_central = 
1.350     albertel 1423: 	&Apache::loncommon::end_page({'js_ready' => 1});
                   1424: 
1.219     www      1425:     my $docopen=&Apache::lonhtmlcommon::javascript_docopen();
1.236     albertel 1426:     $docopen=~s/^document\.//;
1.652     raeburn  1427:     my %lt = &Apache::lonlocal::texthash(
                   1428:                 keyw => 'Keywords list, separated by a space. Add/delete to list if desired.',
                   1429:                 plse => 'Please select a word or group of words from document and then click this link.',
                   1430:                 adds => 'Add selection to keyword list? Edit if desired.',
                   1431:                 comp => 'Compose Message for: ',
                   1432:                 incl => 'Include',
1.656     raeburn  1433:                 type => 'Type',
1.652     raeburn  1434:                 subj => 'Subject',
                   1435:                 mesa => 'Message',
                   1436:                 new  => 'New',
                   1437:                 save => 'Save',
                   1438:                 canc => 'Cancel',
                   1439:                 kehi => 'Keyword Highlight Options',
                   1440:                 txtc => 'Text Color',
                   1441:                 font => 'Font Size',
1.656     raeburn  1442:                 fnst => 'Font Style',
1.718     bisitz   1443:                 col1 => 'red',
                   1444:                 col2 => 'green',
                   1445:                 col3 => 'blue',
                   1446:                 siz1 => 'normal',
                   1447:                 siz2 => '+1',
                   1448:                 siz3 => '+2',
                   1449:                 sty1 => 'normal',
                   1450:                 sty2 => 'italic',
                   1451:                 sty3 => 'bold',
1.652     raeburn  1452:              );
1.597     wenzelju 1453:     $request->print(&Apache::lonhtmlcommon::scripttag(<<SUBJAVASCRIPT));
1.45      ng       1454: 
1.44      ng       1455: //===================== Show list of keywords ====================
1.122     ng       1456:   function keywords(formname) {
1.652     raeburn  1457:     var nret = prompt("$lt{'keyw'}",formname.keywords.value);
1.44      ng       1458:     if (nret==null) return;
1.122     ng       1459:     formname.keywords.value = nret;
1.44      ng       1460: 
1.122     ng       1461:     if (formname.keywords.value != "") {
1.128     ng       1462: 	formname.refresh.value = "on";
1.122     ng       1463: 	formname.submit();
1.44      ng       1464:     }
                   1465:     return;
                   1466:   }
                   1467: 
                   1468: //===================== Script to view submitted by ==================
                   1469:   function viewSubmitter(submitter) {
                   1470:     document.SCORE.refresh.value = "on";
                   1471:     document.SCORE.NCT.value = "1";
                   1472:     document.SCORE.unamedom0.value = submitter;
                   1473:     document.SCORE.submit();
                   1474:     return;
                   1475:   }
                   1476: 
                   1477: //===================== Script to add keyword(s) ==================
                   1478:   function getSel() {
                   1479:     if (document.getSelection) txt = document.getSelection();
                   1480:     else if (document.selection) txt = document.selection.createRange().text;
                   1481:     else return;
                   1482:     var cleantxt = txt.replace(new RegExp('([\\f\\n\\r\\t\\v ])+', 'g')," ");
                   1483:     if (cleantxt=="") {
1.652     raeburn  1484: 	alert("$lt{'plse'}");
1.44      ng       1485: 	return;
                   1486:     }
1.652     raeburn  1487:     var nret = prompt("$lt{'adds'}",cleantxt);
1.44      ng       1488:     if (nret==null) return;
1.127     ng       1489:     document.SCORE.keywords.value = document.SCORE.keywords.value+" "+nret;
1.44      ng       1490:     if (document.SCORE.keywords.value != "") {
1.127     ng       1491: 	document.SCORE.refresh.value = "on";
1.44      ng       1492: 	document.SCORE.submit();
                   1493:     }
                   1494:     return;
                   1495:   }
                   1496: 
                   1497: //====================== Script for composing message ==============
1.80      ng       1498:    // preload images
                   1499:    img1 = new Image();
                   1500:    img1.src = "$iconpath/mailbkgrd.gif";
                   1501:    img2 = new Image();
                   1502:    img2.src = "$iconpath/mailto.gif";
                   1503: 
1.44      ng       1504:   function msgCenter(msgform,usrctr,fullname) {
                   1505:     var Nmsg  = msgform.savemsgN.value;
                   1506:     savedMsgHeader(Nmsg,usrctr,fullname);
                   1507:     var subject = msgform.msgsub.value;
1.127     ng       1508:     var msgchk = document.SCORE["includemsg"+usrctr].value;
1.44      ng       1509:     re = /msgsub/;
                   1510:     var shwsel = "";
                   1511:     if (re.test(msgchk)) { shwsel = "checked" }
1.123     ng       1512:     subject = (document.SCORE.shownSub.value == 0 ? checkEntities(subject) : subject);
                   1513:     displaySubject(checkEntities(subject),shwsel);
1.44      ng       1514:     for (var i=1; i<=Nmsg; i++) {
1.123     ng       1515: 	var testmsg = "savemsg"+i+",";
                   1516: 	re = new RegExp(testmsg,"g");
1.44      ng       1517: 	shwsel = "";
                   1518: 	if (re.test(msgchk)) { shwsel = "checked" }
1.125     ng       1519: 	var message = document.SCORE["savemsg"+i].value;
1.126     ng       1520: 	message = (document.SCORE["shownOnce"+i].value == 0 ? checkEntities(message) : message);
1.123     ng       1521: 	displaySavedMsg(i,message,shwsel); //I do not get it. w/o checkEntities on saved messages,
                   1522: 	                                   //any &lt; is already converted to <, etc. However, only once!!
1.44      ng       1523:     }
1.125     ng       1524:     newmsg = document.SCORE["newmsg"+usrctr].value;
1.44      ng       1525:     shwsel = "";
                   1526:     re = /newmsg/;
                   1527:     if (re.test(msgchk)) { shwsel = "checked" }
                   1528:     newMsg(newmsg,shwsel);
                   1529:     msgTail(); 
                   1530:     return;
                   1531:   }
                   1532: 
1.123     ng       1533:   function checkEntities(strx) {
                   1534:     if (strx.length == 0) return strx;
                   1535:     var orgStr = ["&", "<", ">", '"']; 
                   1536:     var newStr = ["&amp;", "&lt;", "&gt;", "&quot;"];
                   1537:     var counter = 0;
                   1538:     while (counter < 4) {
                   1539: 	strx = strReplace(strx,orgStr[counter],newStr[counter]);
                   1540: 	counter++;
                   1541:     }
                   1542:     return strx;
                   1543:   }
                   1544: 
                   1545:   function strReplace(strx, orgStr, newStr) {
                   1546:     return strx.split(orgStr).join(newStr);
                   1547:   }
                   1548: 
1.44      ng       1549:   function savedMsgHeader(Nmsg,usrctr,fullname) {
1.76      ng       1550:     var height = 70*Nmsg+250;
1.44      ng       1551:     if (height > 600) {
                   1552: 	height = 600;
                   1553:     }
1.118     ng       1554:     var xpos = (screen.width-600)/2;
                   1555:     xpos = (xpos < 0) ? '0' : xpos;
                   1556:     var ypos = (screen.height-height)/2-30;
                   1557:     ypos = (ypos < 0) ? '0' : ypos;
                   1558: 
1.668     www      1559:     pWin = window.open('', 'MessageCenter', 'resizable=yes,toolbar=no,location=no,scrollbars=yes,screenx='+xpos+',screeny='+ypos+',width=700,height='+height);
1.76      ng       1560:     pWin.focus();
                   1561:     pDoc = pWin.document;
1.219     www      1562:     pDoc.$docopen;
1.351     albertel 1563:     pDoc.write('$start_page_msg_central');
1.76      ng       1564: 
                   1565:     pDoc.write("<form action=\\"inactive\\" name=\\"msgcenter\\">");
                   1566:     pDoc.write("<input value=\\""+usrctr+"\\" name=\\"usrctr\\" type=\\"hidden\\">");
1.676     golterma 1567:     pDoc.write("<h1>&nbsp;$lt{'comp'}\"+fullname+\"<\\/h1>");
1.76      ng       1568: 
1.676     golterma 1569:     pDoc.write('<table style="border:1px solid black;"><tr>');
                   1570:     pDoc.write("<td><b>$lt{'incl'}<\\/b><\\/td><td><b>$lt{'type'}<\\/b><\\/td><td><b>$lt{'mesa'}<\\/td><\\/tr>");
1.44      ng       1571: }
                   1572:     function displaySubject(msg,shwsel) {
1.76      ng       1573:     pDoc = pWin.document;
1.676     golterma 1574:     pDoc.write("<tr>");
                   1575:     pDoc.write("<td align=\\"center\\"><input name=\\"subchk\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
1.652     raeburn  1576:     pDoc.write("<td>$lt{'subj'}<\\/td>");
1.676     golterma 1577:     pDoc.write("<td><input name=\\"msgsub\\" type=\\"text\\" value=\\""+msg+"\\"size=\\"40\\" maxlength=\\"80\\"><\\/td><\\/tr>");
1.44      ng       1578: }
                   1579: 
1.72      ng       1580:   function displaySavedMsg(ctr,msg,shwsel) {
1.76      ng       1581:     pDoc = pWin.document;
1.676     golterma 1582:     pDoc.write("<tr>");
                   1583:     pDoc.write("<td align=\\"center\\"><input name=\\"msgn"+ctr+"\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
1.465     albertel 1584:     pDoc.write("<td align=\\"center\\">"+ctr+"<\\/td>");
                   1585:     pDoc.write("<td><textarea name=\\"msg"+ctr+"\\" cols=\\"60\\" rows=\\"3\\">"+msg+"<\\/textarea><\\/td><\\/tr>");
1.44      ng       1586: }
                   1587: 
                   1588:   function newMsg(newmsg,shwsel) {
1.76      ng       1589:     pDoc = pWin.document;
1.676     golterma 1590:     pDoc.write("<tr>");
                   1591:     pDoc.write("<td align=\\"center\\"><input name=\\"newmsgchk\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
1.652     raeburn  1592:     pDoc.write("<td align=\\"center\\">$lt{'new'}<\\/td>");
1.465     albertel 1593:     pDoc.write("<td><textarea name=\\"newmsg\\" cols=\\"60\\" rows=\\"3\\" onchange=\\"javascript:this.form.newmsgchk.checked=true\\" >"+newmsg+"<\\/textarea><\\/td><\\/tr>");
1.44      ng       1594: }
                   1595: 
                   1596:   function msgTail() {
1.76      ng       1597:     pDoc = pWin.document;
1.676     golterma 1598:     //pDoc.write("<\\/table>");
1.465     albertel 1599:     pDoc.write("<\\/td><\\/tr><\\/table>&nbsp;");
1.652     raeburn  1600:     pDoc.write("<input type=\\"button\\" value=\\"$lt{'save'}\\" onclick=\\"javascript:checkInput()\\">&nbsp;&nbsp;");
                   1601:     pDoc.write("<input type=\\"button\\" value=\\"$lt{'canc'}\\" onclick=\\"self.close()\\"><br /><br />");
1.465     albertel 1602:     pDoc.write("<\\/form>");
1.351     albertel 1603:     pDoc.write('$end_page_msg_central');
1.128     ng       1604:     pDoc.close();
1.44      ng       1605: }
                   1606: 
                   1607: //====================== Script for keyword highlight options ==============
                   1608:   function kwhighlight() {
                   1609:     var kwclr    = document.SCORE.kwclr.value;
                   1610:     var kwsize   = document.SCORE.kwsize.value;
                   1611:     var kwstyle  = document.SCORE.kwstyle.value;
                   1612:     var redsel = "";
                   1613:     var grnsel = "";
                   1614:     var blusel = "";
1.718     bisitz   1615:     var txtcol1 = "$lt{'col1'}";
                   1616:     var txtcol2 = "$lt{'col2'}";
                   1617:     var txtcol3 = "$lt{'col3'}";
                   1618:     var txtsiz1 = "$lt{'siz1'}";
                   1619:     var txtsiz2 = "$lt{'siz2'}";
                   1620:     var txtsiz3 = "$lt{'siz3'}";
                   1621:     var txtsty1 = "$lt{'sty1'}";
                   1622:     var txtsty2 = "$lt{'sty2'}";
                   1623:     var txtsty3 = "$lt{'sty3'}";
                   1624:     if (kwclr=="red")   {var redsel="checked='checked'"};
                   1625:     if (kwclr=="green") {var grnsel="checked='checked'"};
                   1626:     if (kwclr=="blue")  {var blusel="checked='checked'"};
1.44      ng       1627:     var sznsel = "";
                   1628:     var sz1sel = "";
                   1629:     var sz2sel = "";
1.718     bisitz   1630:     if (kwsize=="0")  {var sznsel="checked='checked'"};
                   1631:     if (kwsize=="+1") {var sz1sel="checked='checked'"};
                   1632:     if (kwsize=="+2") {var sz2sel="checked='checked'"};
1.44      ng       1633:     var synsel = "";
                   1634:     var syisel = "";
                   1635:     var sybsel = "";
1.718     bisitz   1636:     if (kwstyle=="")    {var synsel="checked='checked'"};
                   1637:     if (kwstyle=="<i>") {var syisel="checked='checked'"};
                   1638:     if (kwstyle=="<b>") {var sybsel="checked='checked'"};
1.44      ng       1639:     highlightCentral();
1.718     bisitz   1640:     highlightbody('red',txtcol1,redsel,'0',txtsiz1,sznsel,'',txtsty1,synsel);
                   1641:     highlightbody('green',txtcol2,grnsel,'+1',txtsiz2,sz1sel,'<i>',txtsty2,syisel);
                   1642:     highlightbody('blue',txtcol3,blusel,'+2',txtsiz3,sz2sel,'<b>',txtsty3,sybsel);
1.44      ng       1643:     highlightend();
                   1644:     return;
                   1645:   }
                   1646: 
                   1647:   function highlightCentral() {
1.76      ng       1648: //    if (window.hwdWin) window.hwdWin.close();
1.118     ng       1649:     var xpos = (screen.width-400)/2;
                   1650:     xpos = (xpos < 0) ? '0' : xpos;
                   1651:     var ypos = (screen.height-330)/2-30;
                   1652:     ypos = (ypos < 0) ? '0' : ypos;
                   1653: 
1.206     albertel 1654:     hwdWin = window.open('', 'KeywordHighlightCentral', 'resizeable=yes,toolbar=no,location=no,scrollbars=no,width=400,height=300,screenx='+xpos+',screeny='+ypos);
1.76      ng       1655:     hwdWin.focus();
                   1656:     var hDoc = hwdWin.document;
1.219     www      1657:     hDoc.$docopen;
1.351     albertel 1658:     hDoc.write('$start_page_highlight_central');
1.76      ng       1659:     hDoc.write("<form action=\\"inactive\\" name=\\"hlCenter\\">");
1.718     bisitz   1660:     hDoc.write("<h1>$lt{'kehi'}<\\/h1>");
1.76      ng       1661: 
1.718     bisitz   1662:     hDoc.write('<table border="0" width="100%"><tr style="background-color:#A1D676">');
                   1663:     hDoc.write("<th>$lt{'txtc'}<\\/th><th>$lt{'font'}<\\/th><th>$lt{'fnst'}<\\/th><\\/tr>");
1.44      ng       1664:   }
                   1665: 
                   1666:   function highlightbody(clrval,clrtxt,clrsel,szval,sztxt,szsel,syval,sytxt,sysel) { 
1.76      ng       1667:     var hDoc = hwdWin.document;
1.718     bisitz   1668:     hDoc.write("<tr>");
1.76      ng       1669:     hDoc.write("<td align=\\"left\\">");
1.718     bisitz   1670:     hDoc.write("<input name=\\"kwdclr\\" type=\\"radio\\" value=\\""+clrval+"\\" "+clrsel+" \\/>&nbsp;"+clrtxt+"<\\/td>");
1.76      ng       1671:     hDoc.write("<td align=\\"left\\">");
1.718     bisitz   1672:     hDoc.write("<input name=\\"kwdsize\\" type=\\"radio\\" value=\\""+szval+"\\" "+szsel+" \\/>&nbsp;"+sztxt+"<\\/td>");
1.76      ng       1673:     hDoc.write("<td align=\\"left\\">");
1.718     bisitz   1674:     hDoc.write("<input name=\\"kwdstyle\\" type=\\"radio\\" value=\\""+syval+"\\" "+sysel+" \\/>&nbsp;"+sytxt+"<\\/td>");
1.465     albertel 1675:     hDoc.write("<\\/tr>");
1.44      ng       1676:   }
                   1677: 
                   1678:   function highlightend() { 
1.76      ng       1679:     var hDoc = hwdWin.document;
1.718     bisitz   1680:     hDoc.write("<\\/table><br \\/>");
                   1681:     hDoc.write("<input type=\\"button\\" value=\\"$lt{'save'}\\" onclick=\\"javascript:updateChoice(1)\\" \\/>&nbsp;&nbsp;");
                   1682:     hDoc.write("<input type=\\"button\\" value=\\"$lt{'canc'}\\" onclick=\\"self.close()\\" \\/><br /><br />");
1.465     albertel 1683:     hDoc.write("<\\/form>");
1.351     albertel 1684:     hDoc.write('$end_page_highlight_central');
1.128     ng       1685:     hDoc.close();
1.44      ng       1686:   }
                   1687: 
                   1688: SUBJAVASCRIPT
                   1689: }
                   1690: 
1.349     albertel 1691: sub get_increment {
1.348     bowersj2 1692:     my $increment = $env{'form.increment'};
                   1693:     if ($increment != 1 && $increment != .5 && $increment != .25 &&
                   1694:         $increment != .1) {
                   1695:         $increment = 1;
                   1696:     }
                   1697:     return $increment;
                   1698: }
                   1699: 
1.585     bisitz   1700: sub gradeBox_start {
                   1701:     return (
                   1702:         &Apache::loncommon::start_data_table()
                   1703:        .&Apache::loncommon::start_data_table_header_row()
                   1704:        .'<th>'.&mt('Part').'</th>'
                   1705:        .'<th>'.&mt('Points').'</th>'
                   1706:        .'<th>&nbsp;</th>'
                   1707:        .'<th>'.&mt('Assign Grade').'</th>'
                   1708:        .'<th>'.&mt('Weight').'</th>'
                   1709:        .'<th>'.&mt('Grade Status').'</th>'
                   1710:        .&Apache::loncommon::end_data_table_header_row()
                   1711:     );
                   1712: }
                   1713: 
                   1714: sub gradeBox_end {
                   1715:     return (
                   1716:         &Apache::loncommon::end_data_table()
                   1717:     );
                   1718: }
1.71      ng       1719: #--- displays the grading box, used in essay type problem and grading by page/sequence
                   1720: sub gradeBox {
1.322     albertel 1721:     my ($request,$symb,$uname,$udom,$counter,$partid,$record) = @_;
1.381     albertel 1722:     my $checkIcon = '<img alt="'.&mt('Check Mark').
1.485     albertel 1723: 	'" src="'.&Apache::loncommon::lonhttpdurl($request->dir_config('lonIconsURL').'/check.gif').'" height="16" border="0" />';
1.71      ng       1724:     my $wgt    = &Apache::lonnet::EXT('resource.'.$partid.'.weight',$symb,$udom,$uname);
1.466     albertel 1725:     my $wgtmsg = ($wgt > 0) ? &mt('(problem weight)') 
                   1726:                            : '<span class="LC_info">'.&mt('problem weight assigned by computer').'</span>';
1.71      ng       1727:     $wgt       = ($wgt > 0 ? $wgt : '1');
                   1728:     my $score  = ($$record{'resource.'.$partid.'.awarded'} eq '' ?
1.320     albertel 1729: 		  '' : &compute_points($$record{'resource.'.$partid.'.awarded'},$wgt));
1.695     bisitz   1730:     my $data_WGT='<input type="hidden" name="WGT'.$counter.'_'.$partid.'" value="'.$wgt.'" />'."\n";
1.466     albertel 1731:     my $display_part= &get_display_part($partid,$symb);
1.270     albertel 1732:     my %last_resets = &get_last_resets($symb,$env{'request.course.id'},
                   1733: 				       [$partid]);
                   1734:     my $aggtries = $$record{'resource.'.$partid.'.tries'};
1.269     raeburn  1735:     if ($last_resets{$partid}) {
                   1736:         $aggtries = &get_num_tries($record,$last_resets{$partid},$partid);
                   1737:     }
1.695     bisitz   1738:     my $result=&Apache::loncommon::start_data_table_row();
1.71      ng       1739:     my $ctr = 0;
1.348     bowersj2 1740:     my $thisweight = 0;
1.349     albertel 1741:     my $increment = &get_increment();
1.485     albertel 1742: 
                   1743:     my $radio.='<table border="0"><tr>'."\n";  # display radio buttons in a nice table 10 across
1.348     bowersj2 1744:     while ($thisweight<=$wgt) {
1.532     bisitz   1745: 	$radio.= '<td><span class="LC_nobreak"><label><input type="radio" name="RADVAL'.$counter.'_'.$partid.'" '.
1.589     bisitz   1746:         'onclick="javascript:writeBox(this.form,\''.$counter.'_'.$partid.'\','.
1.348     bowersj2 1747: 	    $thisweight.')" value="'.$thisweight.'" '.
1.401     albertel 1748: 	    ($score eq $thisweight ? 'checked="checked"':'').' /> '.$thisweight."</label></span></td>\n";
1.485     albertel 1749: 	$radio.=(($ctr+1)%10 == 0 ? '</tr><tr>' : '');
1.348     bowersj2 1750:         $thisweight += $increment;
1.71      ng       1751: 	$ctr++;
                   1752:     }
1.485     albertel 1753:     $radio.='</tr></table>';
                   1754: 
                   1755:     my $line.='<input type="text" name="GD_BOX'.$counter.'_'.$partid.'"'.
1.71      ng       1756: 	($score ne ''? ' value = "'.$score.'"':'').' size="4" '.
1.589     bisitz   1757: 	'onchange="javascript:updateRadio(this.form,\''.$counter.'_'.$partid.'\','.
1.71      ng       1758: 	$wgt.')" /></td>'."\n";
1.485     albertel 1759:     $line.='<td>/'.$wgt.' '.$wgtmsg.
1.71      ng       1760: 	($$record{'resource.'.$partid.'.solved'} eq 'correct_by_student' ? '&nbsp;'.$checkIcon : '').
1.585     bisitz   1761: 	' </td>'."\n";
                   1762:     $line.='<td><select name="GD_SEL'.$counter.'_'.$partid.'" '.
1.589     bisitz   1763: 	'onchange="javascript:clearRadBox(this.form,\''.$counter.'_'.$partid.'\')" >'."\n";
1.71      ng       1764:     if ($$record{'resource.'.$partid.'.solved'} eq 'excused') {
1.485     albertel 1765: 	$line.='<option></option>'.
                   1766: 	    '<option value="excused" selected="selected">'.&mt('excused').'</option>';
1.71      ng       1767:     } else {
1.485     albertel 1768: 	$line.='<option selected="selected"></option>'.
                   1769: 	    '<option value="excused" >'.&mt('excused').'</option>';
1.71      ng       1770:     }
1.485     albertel 1771:     $line.='<option value="reset status">'.&mt('reset status').'</option></select>'."\n";
                   1772: 
                   1773: 
                   1774:     $result .= 
1.695     bisitz   1775: 	    '<td>'.$data_WGT.$display_part.'</td><td>'.$radio.'</td><td>'.&mt('or').'</td><td>'.$line.'</td>';
1.585     bisitz   1776:     $result.=&Apache::loncommon::end_data_table_row();
1.695     bisitz   1777:     $result.=&Apache::loncommon::start_data_table_row().'<td colspan="6">';
1.71      ng       1778:     $result.='<input type="hidden" name="stores'.$counter.'_'.$partid.'" value="" />'."\n".
                   1779: 	'<input type="hidden" name="oldpts'.$counter.'_'.$partid.'" value="'.$score.'" />'."\n".
                   1780: 	'<input type="hidden" name="solved'.$counter.'_'.$partid.'" value="'.
1.269     raeburn  1781: 	$$record{'resource.'.$partid.'.solved'}.'" />'."\n".
                   1782:         '<input type="hidden" name="totaltries'.$counter.'_'.$partid.'" value="'.
                   1783:         $$record{'resource.'.$partid.'.tries'}.'" />'."\n".
                   1784:         '<input type="hidden" name="aggtries'.$counter.'_'.$partid.'" value="'.
                   1785:         $aggtries.'" />'."\n";
1.582     raeburn  1786:     my $res_error;
                   1787:     $result.=&handback_box($symb,$uname,$udom,$counter,$partid,$record,\$res_error);
1.695     bisitz   1788:     $result.='</td>'.&Apache::loncommon::end_data_table_row();
1.582     raeburn  1789:     if ($res_error) {
                   1790:         return &navmap_errormsg();
                   1791:     }
1.318     banghart 1792:     return $result;
                   1793: }
1.322     albertel 1794: 
                   1795: sub handback_box {
1.623     www      1796:     my ($symb,$uname,$udom,$counter,$partid,$record,$res_error_pointer) = @_;
                   1797:     my ($partlist,$handgrade,$responseType) = &response_type($symb,$res_error_pointer);
1.323     banghart 1798:     my (@respids);
1.652     raeburn  1799:     my @part_response_id = &flatten_responseType($responseType);
1.375     albertel 1800:     foreach my $part_response_id (@part_response_id) {
                   1801:     	my ($part,$resp) = @{ $part_response_id };
1.323     banghart 1802:         if ($part eq $partid) {
1.375     albertel 1803:             push(@respids,$resp);
1.323     banghart 1804:         }
                   1805:     }
1.318     banghart 1806:     my $result;
1.323     banghart 1807:     foreach my $respid (@respids) {
1.322     albertel 1808: 	my $prefix = $counter.'_'.$partid.'_'.$respid.'_';
                   1809: 	my $files=&get_submitted_files($udom,$uname,$partid,$respid,$record);
                   1810: 	next if (!@$files);
1.654     raeburn  1811: 	my $file_counter = 0;
1.313     banghart 1812: 	foreach my $file (@$files) {
1.368     banghart 1813: 	    if ($file =~ /\/portfolio\//) {
1.654     raeburn  1814:                 $file_counter++;
1.368     banghart 1815:     	        my ($file_path, $file_disp) = ($file =~ m|(.+/)(.+)$|);
                   1816:     	        my ($name,$version,$ext) = &file_name_version_ext($file_disp);
                   1817:     	        $file_disp = "$name.$ext";
                   1818:     	        $file = $file_path.$file_disp;
                   1819:     	        $result.=&mt('Return commented version of [_1] to student.',
                   1820:     			 '<span class="LC_filename">'.$file_disp.'</span>');
                   1821:     	        $result.='<input type="file"   name="'.$prefix.'returndoc'.$file_counter.'" />'."\n";
1.654     raeburn  1822:     	        $result.='<input type="hidden" name="'.$prefix.'origdoc'.$file_counter.'" value="'.$file.'" /><br />'."\n";
1.368     banghart 1823: 	    }
1.322     albertel 1824: 	}
1.654     raeburn  1825:         if ($file_counter) {
                   1826:             $result .= '<input type="hidden" name="'.$prefix.'countreturndoc" value="'.$file_counter.'" />'."\n".
                   1827:                        '<span class="LC_info">'.
                   1828:                        '('.&mt('File(s) will be uploaded when you click on Save &amp; Next below.',$file_counter).')</span><br /><br />';
                   1829:         }
1.313     banghart 1830:     }
1.318     banghart 1831:     return $result;    
1.71      ng       1832: }
1.44      ng       1833: 
1.58      albertel 1834: sub show_problem {
1.382     albertel 1835:     my ($request,$symb,$uname,$udom,$removeform,$viewon,$mode,$form) = @_;
1.144     albertel 1836:     my $rendered;
1.382     albertel 1837:     my %form = ((ref($form) eq 'HASH')? %{$form} : ());
1.329     albertel 1838:     &Apache::lonxml::remember_problem_counter();
1.144     albertel 1839:     if ($mode eq 'both' or $mode eq 'text') {
                   1840: 	$rendered=&Apache::loncommon::get_student_view($symb,$uname,$udom,
1.382     albertel 1841: 						       $env{'request.course.id'},
                   1842: 						       undef,\%form);
1.144     albertel 1843:     }
1.58      albertel 1844:     if ($removeform) {
                   1845: 	$rendered=~s|<form(.*?)>||g;
                   1846: 	$rendered=~s|</form>||g;
1.374     albertel 1847: 	$rendered=~s|(<input[^>]*name\s*=\s*"?)(\w+)("?)|$1would_have_been_$2$3|g;
1.58      albertel 1848:     }
1.144     albertel 1849:     my $companswer;
                   1850:     if ($mode eq 'both' or $mode eq 'answer') {
1.329     albertel 1851: 	&Apache::lonxml::restore_problem_counter();
1.382     albertel 1852: 	$companswer=
                   1853: 	    &Apache::loncommon::get_student_answers($symb,$uname,$udom,
                   1854: 						    $env{'request.course.id'},
                   1855: 						    %form);
1.144     albertel 1856:     }
1.58      albertel 1857:     if ($removeform) {
                   1858: 	$companswer=~s|<form(.*?)>||g;
                   1859: 	$companswer=~s|</form>||g;
1.144     albertel 1860: 	$companswer=~s|name="submit"|name="would_have_been_submit"|g;
1.58      albertel 1861:     }
1.671     raeburn  1862:     my $renderheading = &mt('View of the problem');
                   1863:     my $answerheading = &mt('Correct answer');
                   1864:     if (($uname ne $env{'user.name'}) || ($udom ne $env{'user.domain'})) {
                   1865:         my $stu_fullname = $env{'form.fullname'};
                   1866:         if ($stu_fullname eq '') {
                   1867:             $stu_fullname = &Apache::loncommon::plainname($uname,$udom,'lastname');
                   1868:         }
                   1869:         my $forwhom = &nameUserString(undef,$stu_fullname,$uname,$udom);
                   1870:         if ($forwhom ne '') {
                   1871:             $renderheading = &mt('View of the problem for[_1]',$forwhom);
                   1872:             $answerheading = &mt('Correct answer for[_1]',$forwhom);
                   1873:         }
                   1874:     }
1.468     albertel 1875:     $rendered=
1.588     bisitz   1876:         '<div class="LC_Box">'
1.671     raeburn  1877:        .'<h3 class="LC_hcell">'.$renderheading.'</h3>'
1.588     bisitz   1878:        .$rendered
                   1879:        .'</div>';
1.468     albertel 1880:     $companswer=
1.588     bisitz   1881:         '<div class="LC_Box">'
1.671     raeburn  1882:        .'<h3 class="LC_hcell">'.$answerheading.'</h3>'
1.588     bisitz   1883:        .$companswer
                   1884:        .'</div>';
1.468     albertel 1885:     my $result;
1.144     albertel 1886:     if ($mode eq 'both') {
1.588     bisitz   1887:         $result=$rendered.$companswer;
1.144     albertel 1888:     } elsif ($mode eq 'text') {
1.588     bisitz   1889:         $result=$rendered;
1.144     albertel 1890:     } elsif ($mode eq 'answer') {
1.588     bisitz   1891:         $result=$companswer;
1.144     albertel 1892:     }
1.71      ng       1893:     return $result;
1.58      albertel 1894: }
1.397     albertel 1895: 
1.396     banghart 1896: sub files_exist {
                   1897:     my ($r, $symb) = @_;
                   1898:     my @students = &Apache::loncommon::get_env_multiple('form.stuinfo');
1.397     albertel 1899: 
1.396     banghart 1900:     foreach my $student (@students) {
                   1901:         my ($uname,$udom,$fullname) = split(/:/,$student);
1.397     albertel 1902:         my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},
                   1903: 					      $udom,$uname);
1.396     banghart 1904:         my ($string,$timestamp)= &get_last_submission(\%record);
1.397     albertel 1905:         foreach my $submission (@$string) {
                   1906:             my ($partid,$respid) =
                   1907: 		($submission =~ /^resource\.([^\.]*)\.([^\.]*)\.submission/);
                   1908:             my $files=&get_submitted_files($udom,$uname,$partid,$respid,
                   1909: 					   \%record);
                   1910:             return 1 if (@$files);
1.396     banghart 1911:         }
                   1912:     }
1.397     albertel 1913:     return 0;
1.396     banghart 1914: }
1.397     albertel 1915: 
1.394     banghart 1916: sub download_all_link {
                   1917:     my ($r,$symb) = @_;
1.621     www      1918:     unless (&files_exist($r, $symb)) {
                   1919:        $r->print(&mt('There are currently no submitted documents.'));
                   1920:        return;
                   1921:     }
                   1922: 
1.395     albertel 1923:     my $all_students = 
                   1924: 	join("\n", &Apache::loncommon::get_env_multiple('form.stuinfo'));
                   1925: 
                   1926:     my $parts =
                   1927: 	join("\n",&Apache::loncommon::get_env_multiple('form.vPart'));
                   1928: 
1.394     banghart 1929:     my $identifier = &Apache::loncommon::get_cgi_id();
1.514     raeburn  1930:     &Apache::lonnet::appenv({'cgi.'.$identifier.'.students' => $all_students,
                   1931:                              'cgi.'.$identifier.'.symb' => $symb,
                   1932:                              'cgi.'.$identifier.'.parts' => $parts,});
1.395     albertel 1933:     $r->print('<a href="/cgi-bin/multidownload.pl?'.$identifier.'">'.
                   1934: 	      &mt('Download All Submitted Documents').'</a>');
1.621     www      1935:     return;
                   1936: }
                   1937: 
                   1938: sub submit_download_link {
                   1939:     my ($request,$symb) = @_;
                   1940:     if (!$symb) { return ''; }
                   1941: #FIXME: Figure out which type of problem this is and provide appropriate download
                   1942:     &download_all_link($request,$symb);
1.394     banghart 1943: }
1.395     albertel 1944: 
1.432     banghart 1945: sub build_section_inputs {
                   1946:     my $section_inputs;
                   1947:     if ($env{'form.section'} eq '') {
                   1948:         $section_inputs .= '<input type="hidden" name="section" value="all" />'."\n";
                   1949:     } else {
                   1950:         my @sections = &Apache::loncommon::get_env_multiple('form.section');
1.434     albertel 1951:         foreach my $section (@sections) {
1.432     banghart 1952:             $section_inputs .= '<input type="hidden" name="section" value="'.$section.'" />'."\n";
                   1953:         }
                   1954:     }
                   1955:     return $section_inputs;
                   1956: }
                   1957: 
1.44      ng       1958: # --------------------------- show submissions of a student, option to grade 
                   1959: sub submission {
1.608     www      1960:     my ($request,$counter,$total,$symb) = @_;
1.257     albertel 1961:     my ($uname,$udom)     = ($env{'form.student'},$env{'form.userdom'});
                   1962:     $udom = ($udom eq '' ? $env{'user.domain'} : $udom); #has form.userdom changed for a student?
                   1963:     my $usec = &Apache::lonnet::getsection($udom,$uname,$env{'request.course.id'});
                   1964:     $env{'form.fullname'} = &Apache::loncommon::plainname($uname,$udom,'lastname') if $env{'form.fullname'} eq '';
1.608     www      1965: 
1.605     www      1966:     my $probtitle=&Apache::lonnet::gettitle($symb); 
1.324     albertel 1967:     if ($symb eq '') { $request->print("Unable to handle ambiguous references:."); return ''; }
1.104     albertel 1968: 
                   1969:     if (!&canview($usec)) {
1.712     bisitz   1970:         $request->print(
                   1971:             '<span class="LC_warning">'.
1.713     bisitz   1972:             &mt('Unable to view requested student.').
1.712     bisitz   1973:             ' '.&mt('([_1] in section [_2] in course id [_3])',
                   1974:                         $uname.':'.$udom,$usec,$env{'request.course.id'}).
                   1975:             '</span>');
1.104     albertel 1976: 	return;
                   1977:     }
                   1978: 
1.257     albertel 1979:     if (!$env{'form.lastSub'}) { $env{'form.lastSub'} = 'datesub'; }
                   1980:     if (!$env{'form.vProb'}) { $env{'form.vProb'} = 'yes'; }
                   1981:     if (!$env{'form.vAns'}) { $env{'form.vAns'} = 'yes'; }
                   1982:     my $last = ($env{'form.lastSub'} eq 'last' ? 'last' : '');
1.381     albertel 1983:     my $checkIcon = '<img alt="'.&mt('Check Mark').
                   1984: 	'" src="'.$request->dir_config('lonIconsURL').
1.122     ng       1985: 	'/check.gif" height="16" border="0" />';
1.41      ng       1986: 
                   1987:     # header info
                   1988:     if ($counter == 0) {
                   1989: 	&sub_page_js($request);
1.621     www      1990: 	&sub_page_kw_js($request);
1.118     ng       1991: 
1.44      ng       1992: 	# option to display problem, only once else it cause problems 
                   1993:         # with the form later since the problem has a form.
1.257     albertel 1994: 	if ($env{'form.vProb'} eq 'yes' or $env{'form.vAns'} eq 'yes') {
1.144     albertel 1995: 	    my $mode;
1.257     albertel 1996: 	    if ($env{'form.vProb'} eq 'yes' && $env{'form.vAns'} eq 'yes') {
1.144     albertel 1997: 		$mode='both';
1.257     albertel 1998: 	    } elsif ($env{'form.vProb'} eq 'yes') {
1.144     albertel 1999: 		$mode='text';
1.257     albertel 2000: 	    } elsif ($env{'form.vAns'} eq 'yes') {
1.144     albertel 2001: 		$mode='answer';
                   2002: 	    }
1.329     albertel 2003: 	    &Apache::lonxml::clear_problem_counter();
1.144     albertel 2004: 	    $request->print(&show_problem($request,$symb,$uname,$udom,0,1,$mode));
1.41      ng       2005: 	}
1.441     www      2006: 
1.704     raeburn  2007: 	# kwclr is the only variable that is guaranteed not to be blank 
1.44      ng       2008:         # if this subroutine has been called once.
1.41      ng       2009: 	my %keyhash = ();
1.624     www      2010: #	if ($env{'form.kwclr'} eq '' && $env{'form.handgrade'} eq 'yes') {
                   2011:         if (1) {
1.41      ng       2012: 	    %keyhash = &Apache::lonnet::dump('nohist_handgrade',
1.257     albertel 2013: 					     $env{'course.'.$env{'request.course.id'}.'.domain'},
                   2014: 					     $env{'course.'.$env{'request.course.id'}.'.num'});
1.41      ng       2015: 
1.257     albertel 2016: 	    my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
                   2017: 	    $env{'form.keywords'} = $keyhash{$symb.'_keywords'} ne '' ? $keyhash{$symb.'_keywords'} : '';
                   2018: 	    $env{'form.kwclr'}    = $keyhash{$loginuser.'_kwclr'} ne '' ? $keyhash{$loginuser.'_kwclr'} : 'red';
                   2019: 	    $env{'form.kwsize'}   = $keyhash{$loginuser.'_kwsize'} ne '' ? $keyhash{$loginuser.'_kwsize'} : '0';
                   2020: 	    $env{'form.kwstyle'}  = $keyhash{$loginuser.'_kwstyle'} ne '' ? $keyhash{$loginuser.'_kwstyle'} : '';
                   2021: 	    $env{'form.msgsub'}   = $keyhash{$symb.'_subject'} ne '' ? 
1.605     www      2022: 		$keyhash{$symb.'_subject'} : $probtitle;
1.257     albertel 2023: 	    $env{'form.savemsgN'} = $keyhash{$symb.'_savemsgN'} ne '' ? $keyhash{$symb.'_savemsgN'} : '0';
1.41      ng       2024: 	}
1.257     albertel 2025: 	my $overRideScore = $env{'form.overRideScore'} eq '' ? 'no' : $env{'form.overRideScore'};
1.442     banghart 2026: 	my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
1.303     banghart 2027: 	$request->print('<form action="/adm/grades" method="post" name="SCORE" enctype="multipart/form-data">'."\n".
1.41      ng       2028: 			'<input type="hidden" name="command"    value="handgrade" />'."\n".
1.442     banghart 2029: 			'<input type="hidden" name="Status"     value="'.$stu_status.'" />'."\n".
1.120     ng       2030: 			'<input type="hidden" name="overRideScore" value="'.$overRideScore.'" />'."\n".
1.41      ng       2031: 			'<input type="hidden" name="refresh"    value="off" />'."\n".
1.120     ng       2032: 			'<input type="hidden" name="studentNo"  value="" />'."\n".
                   2033: 			'<input type="hidden" name="gradeOpt"   value="" />'."\n".
1.418     albertel 2034: 			'<input type="hidden" name="symb"       value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.257     albertel 2035: 			'<input type="hidden" name="vProb"      value="'.$env{'form.vProb'}.'" />'."\n".
                   2036: 			'<input type="hidden" name="vAns"       value="'.$env{'form.vAns'}.'" />'."\n".
                   2037: 			'<input type="hidden" name="lastSub"    value="'.$env{'form.lastSub'}.'" />'."\n".
1.432     banghart 2038: 			&build_section_inputs().
1.326     albertel 2039: 			'<input type="hidden" name="submitonly" value="'.$env{'form.submitonly'}.'" />'."\n".
1.41      ng       2040: 			'<input type="hidden" name="NCT"'.
1.257     albertel 2041: 			' value="'.($env{'form.NTSTU'} ne '' ? $env{'form.NTSTU'} : $total+1).'" />'."\n");
1.624     www      2042: #	if ($env{'form.handgrade'} eq 'yes') {
                   2043:         if (1) {
1.257     albertel 2044: 	    $request->print('<input type="hidden" name="keywords" value="'.$env{'form.keywords'}.'" />'."\n".
                   2045: 			    '<input type="hidden" name="kwclr"    value="'.$env{'form.kwclr'}.'" />'."\n".
                   2046: 			    '<input type="hidden" name="kwsize"   value="'.$env{'form.kwsize'}.'" />'."\n".
                   2047: 			    '<input type="hidden" name="kwstyle"  value="'.$env{'form.kwstyle'}.'" />'."\n".
                   2048: 			    '<input type="hidden" name="msgsub"   value="'.$env{'form.msgsub'}.'" />'."\n".
1.123     ng       2049: 			    '<input type="hidden" name="shownSub" value="0" />'."\n".
1.257     albertel 2050: 			    '<input type="hidden" name="savemsgN" value="'.$env{'form.savemsgN'}.'" />'."\n");
1.154     albertel 2051: 	    foreach my $partid (&Apache::loncommon::get_env_multiple('form.vPart')) {
                   2052: 		$request->print('<input type="hidden" name="vPart" value="'.$partid.'" />'."\n");
                   2053: 	    }
1.123     ng       2054: 	}
1.41      ng       2055: 	
                   2056: 	my ($cts,$prnmsg) = (1,'');
1.257     albertel 2057: 	while ($cts <= $env{'form.savemsgN'}) {
1.41      ng       2058: 	    $prnmsg.='<input type="hidden" name="savemsg'.$cts.'" value="'.
1.123     ng       2059: 		(!exists($keyhash{$symb.'_savemsg'.$cts}) ? 
1.257     albertel 2060: 		 &Apache::lonfeedback::clear_out_html($env{'form.savemsg'.$cts}) :
1.80      ng       2061: 		 &Apache::lonfeedback::clear_out_html($keyhash{$symb.'_savemsg'.$cts})).
1.123     ng       2062: 		'" />'."\n".
                   2063: 		'<input type="hidden" name="shownOnce'.$cts.'" value="0" />'."\n";
1.41      ng       2064: 	    $cts++;
                   2065: 	}
                   2066: 	$request->print($prnmsg);
1.32      ng       2067: 
1.624     www      2068: #	if ($env{'form.handgrade'} eq 'yes') {
                   2069:         if (1) {
1.652     raeburn  2070: 
                   2071:             my %lt = &Apache::lonlocal::texthash(
1.719     bisitz   2072:                           keyh => 'Keyword Highlighting for Essays',
1.652     raeburn  2073:                           keyw => 'Keyword Options',
1.655     raeburn  2074:                           list => 'List',
1.652     raeburn  2075:                           past => 'Paste Selection to List',
1.661     www      2076:                           high => 'Highlight Attribute',
1.652     raeburn  2077:                      );    
1.88      www      2078: #
                   2079: # Print out the keyword options line
                   2080: #
1.718     bisitz   2081: 	    $request->print(
                   2082:                 '<div class="LC_columnSection">'
                   2083:                .'<fieldset><legend>'.$lt{'keyh'}.'</legend>'
                   2084:                .&Apache::lonhtmlcommon::funclist_from_array(
                   2085:                     ['<a href="javascript:keywords(document.SCORE);" target="_self">'.$lt{'list'}.'</a>',
                   2086:                      '<a href="#" onmousedown="javascript:getSel(); return false"
                   2087:  class="page">'.$lt{'past'}.'</a>',
                   2088:                      '<a href="javascript:kwhighlight();" target="_self">'.$lt{'high'}.'</a>'],
                   2089:                     {legend => $lt{'keyw'}})
                   2090:                .'</fieldset></div>'
                   2091:             );
                   2092: 
1.88      www      2093: #
                   2094: # Load the other essays for similarity check
                   2095: #
1.324     albertel 2096:             my (undef,undef,$essayurl) = &Apache::lonnet::decode_symb($symb);
1.384     albertel 2097: 	    my ($adom,$aname,$apath)=($essayurl=~/^($LONCAPA::domain_re)\/($LONCAPA::username_re)\/(.*)$/);
1.359     www      2098: 	    $apath=&escape($apath);
1.88      www      2099: 	    $apath=~s/\W/\_/gs;
1.674     raeburn  2100:             &init_old_essays($symb,$apath,$adom,$aname);
1.41      ng       2101:         }
                   2102:     }
1.44      ng       2103: 
1.441     www      2104: # This is where output for one specific student would start
1.592     bisitz   2105:     my $add_class = ($counter%2) ? ' LC_grade_show_user_odd_row' : '';
                   2106:     $request->print(
                   2107:         "\n\n"
                   2108:        .'<div class="LC_grade_show_user'.$add_class.'">'
                   2109:        .'<h2>'.&nameUserString(undef,$env{'form.fullname'},$uname,$udom).'</h2>'
                   2110:        ."\n"
                   2111:     );
1.441     www      2112: 
1.592     bisitz   2113:     # Show additional functions if allowed
                   2114:     if ($perm{'vgr'}) {
                   2115:         $request->print(
                   2116:             &Apache::loncommon::track_student_link(
1.708     bisitz   2117:                 'View recent activity',
1.592     bisitz   2118:                 $uname,$udom,'check')
                   2119:            .' '
                   2120:         );
                   2121:     }
                   2122:     if ($perm{'opa'}) {
                   2123:         $request->print(
                   2124:             &Apache::loncommon::pprmlink(
                   2125:                 &mt('Set/Change parameters'),
                   2126:                 $uname,$udom,$symb,'check'));
                   2127:     }
                   2128: 
                   2129:     # Show Problem
1.257     albertel 2130:     if ($env{'form.vProb'} eq 'all' or $env{'form.vAns'} eq 'all') {
1.144     albertel 2131: 	my $mode;
1.257     albertel 2132: 	if ($env{'form.vProb'} eq 'all' && $env{'form.vAns'} eq 'all') {
1.144     albertel 2133: 	    $mode='both';
1.257     albertel 2134: 	} elsif ($env{'form.vProb'} eq 'all' ) {
1.144     albertel 2135: 	    $mode='text';
1.257     albertel 2136: 	} elsif ($env{'form.vAns'} eq 'all') {
1.144     albertel 2137: 	    $mode='answer';
                   2138: 	}
1.329     albertel 2139: 	&Apache::lonxml::clear_problem_counter();
1.475     albertel 2140: 	$request->print(&show_problem($request,$symb,$uname,$udom,1,1,$mode,{'request.prefix' => 'ctr'.$counter}));
1.58      albertel 2141:     }
1.144     albertel 2142: 
1.257     albertel 2143:     my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
1.582     raeburn  2144:     my $res_error;
                   2145:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
                   2146:     if ($res_error) {
                   2147:         $request->print(&navmap_errormsg());
                   2148:         return;
                   2149:     }
1.41      ng       2150: 
1.44      ng       2151:     # Display student info
1.41      ng       2152:     $request->print(($counter == 0 ? '' : '<br />'));
1.590     bisitz   2153: 
                   2154:     my $result='<div class="LC_Box">'
                   2155:               .'<h3 class="LC_hcell">'.&mt('Submissions').'</h3>';
1.45      ng       2156:     $result.='<input type="hidden" name="name'.$counter.
1.588     bisitz   2157:              '" value="'.$env{'form.fullname'}.'" />'."\n";
1.624     www      2158: #    if ($env{'form.handgrade'} eq 'no') {
                   2159:     if (1) {
1.588     bisitz   2160:         $result.='<p class="LC_info">'
                   2161:                 .&mt('Part(s) graded correct by the computer is marked with a [_1] symbol.',$checkIcon)
                   2162:                 ."</p>\n";
1.469     albertel 2163:     }
                   2164: 
1.118     ng       2165:     # If any part of the problem is an essay-response (handgraded), then check for collaborators
1.464     albertel 2166:     my $fullname;
                   2167:     my $col_fullnames = [];
1.624     www      2168: #    if ($env{'form.handgrade'} eq 'yes') {
                   2169:     if (1) {
1.464     albertel 2170: 	(my $sub_result,$fullname,$col_fullnames)=
                   2171: 	    &check_collaborators($symb,$uname,$udom,\%record,$handgrade,
                   2172: 				 $counter);
                   2173: 	$result.=$sub_result;
1.41      ng       2174:     }
1.44      ng       2175:     $request->print($result."\n");
1.702     kruse    2176:     
1.44      ng       2177:     # print student answer/submission
1.588     bisitz   2178:     # Options are (1) Handgraded submission only
1.44      ng       2179:     #             (2) Last submission, includes submission that is not handgraded 
                   2180:     #                  (for multi-response type part)
                   2181:     #             (3) Last submission plus the parts info
                   2182:     #             (4) The whole record for this student
1.702     kruse    2183:     
                   2184:     my ($string,$timestamp)= &get_last_submission(\%record);
1.468     albertel 2185: 	
1.702     kruse    2186:     my $lastsubonly;
1.468     albertel 2187: 
1.702     kruse    2188:     if ($$timestamp eq '') {
                   2189:         $lastsubonly.='<div class="LC_grade_submissions_body">'.$$string[0].'</div>'; 
                   2190:     } else {
                   2191:         $lastsubonly =
                   2192:             '<div class="LC_grade_submissions_body">'
                   2193:            .'<b>'.&mt('Date Submitted:').'</b> '.$$timestamp."\n";
                   2194: 
                   2195: 	my %seenparts;
                   2196: 	my @part_response_id = &flatten_responseType($responseType);
                   2197: 	foreach my $part (@part_response_id) {
                   2198: 	    next if ($env{'form.lastSub'} eq 'hdgrade' 
1.393     albertel 2199: 			 && $$handgrade{$$part[0].'_'.$$part[1]} ne 'yes');
                   2200: 
1.702     kruse    2201: 	    my ($partid,$respid) = @{ $part };
                   2202: 	    my $display_part=&get_display_part($partid,$symb);
                   2203: 	    if ($env{"form.$uname:$udom:$partid:submitted_by"}) {
                   2204: 		if (exists($seenparts{$partid})) { next; }
                   2205: 		$seenparts{$partid}=1;
                   2206:                 $request->print(
                   2207:                     '<b>'.&mt('Part: [_1]',$display_part).'</b>'.
                   2208:                     ' <b>'.&mt('Collaborative submission by: [_1]',
                   2209:                                '<a href="javascript:viewSubmitter(\''.
                   2210:                                $env{"form.$uname:$udom:$partid:submitted_by"}.
                   2211:                                '\');" target="_self">'.
                   2212:                                $$fullname{$env{"form.$uname:$udom:$partid:submitted_by"}}.'</a>').
                   2213:                     '<br />');
                   2214: 		next;
                   2215: 		}
                   2216: 	    my $responsetype = $responseType->{$partid}->{$respid};
                   2217: 	    if (!exists($record{"resource.$partid.$respid.submission"})) {
                   2218:                 $lastsubonly.="\n".'<div class="LC_grade_submission_part">'.
                   2219:                     '<b>'.&mt('Part: [_1]',$display_part).'</b>'.
                   2220:                     ' <span class="LC_internal_info">'.
                   2221:                     '('.&mt('Response ID: [_1]',$respid).')'.
                   2222:                     '</span>&nbsp; &nbsp;'.
                   2223: 	       	    '<span class="LC_warning">'.&mt('Nothing submitted - no attempts.').'</span><br /><br /></div>';
                   2224: 		next;
                   2225: 	    }
                   2226: 	    foreach my $submission (@$string) {
                   2227: 		my ($partid,$respid) = ($submission =~ /^resource\.([^\.]*)\.([^\.]*)\.submission/);
                   2228: 		if (join('_',@{$part}) ne ($partid.'_'.$respid)) { next; }
                   2229: 		my ($ressub,$hide,$subval) = split(/:/,$submission,3);
                   2230: 		# Similarity check
                   2231:                 my $similar='';
                   2232:                 my ($type,$trial,$rndseed);
                   2233:                 if ($hide eq 'rand') {
                   2234:                     $type = 'randomizetry';
                   2235:                     $trial = $record{"resource.$partid.tries"};
                   2236:                     $rndseed = $record{"resource.$partid.rndseed"};
                   2237:                 }
                   2238: 	        if ($env{'form.checkPlag'}) {
                   2239:     		    my ($oname,$odom,$ocrsid,$oessay,$osim)=
                   2240: 		        &most_similar($uname,$udom,$symb,$subval);
                   2241: 		    if ($osim) {
                   2242: 			$osim=int($osim*100.0);
                   2243: 			my %old_course_desc = 
                   2244: 			    &Apache::lonnet::coursedescription($ocrsid,
                   2245: 							{'one_time' => 1});
                   2246: 
                   2247:                         if ($hide eq 'anon') {
                   2248:                             $similar='<hr /><span class="LC_warning">'.&mt("Essay was found to be similar to another essay submitted for this assignment.").'<br />'.
                   2249:                                      &mt('As the current submission is for an anonymous survey, no other details are available.').'</span><hr />';
                   2250:                         } else {
                   2251: 			    $similar="<hr /><h3><span class=\"LC_warning\">".
                   2252: 				&mt('Essay is [_1]% similar to an essay by [_2] in course [_3] (course id [_4]:[_5])',
                   2253: 				    $osim,
                   2254: 				    &Apache::loncommon::plainname($oname,$odom).' ('.$oname.':'.$odom.')',
1.596     raeburn  2255: 				        $old_course_desc{'description'},
                   2256: 				        $old_course_desc{'num'},
                   2257: 				        $old_course_desc{'domain'}).
                   2258: 				    '</span></h3><blockquote><i>'.
                   2259: 				    &keywords_highlight($oessay).
                   2260: 				    '</i></blockquote><hr />';
1.702     kruse    2261:                         }
                   2262: 	            }
                   2263: 		}
                   2264: 		my $order=&get_order($partid,$respid,$symb,$uname,$udom,
                   2265:                                      undef,$type,$trial,$rndseed);
                   2266:                 if ($env{'form.lastSub'} eq 'lastonly' || $env{'form.lastSub'} eq 'datesub' || $env{'form.lastSub'} =~ /^(last|all)$/ || ($env{'form.lastSub'} eq 'hdgrade' && 
1.377     albertel 2267: 			 $$handgrade{$$part[0].'_'.$$part[1]} eq 'yes')) {
1.702     kruse    2268: 		    my $display_part=&get_display_part($partid,$symb);
                   2269:                     $lastsubonly.='<div class="LC_grade_submission_part">'.
                   2270:                         '<b>'.&mt('Part: [_1]',$display_part).'</b>'.
                   2271:                         ' <span class="LC_internal_info">'.
                   2272:                         '('.&mt('Response ID: [_1]',$respid).')'.
                   2273:                         '</span>&nbsp; &nbsp;';
                   2274: 		    my $files=&get_submitted_files($udom,$uname,$partid,$respid,\%record);
                   2275:                         
                   2276: 		    if (@$files) {
                   2277:                         if ($hide eq 'anon') {
                   2278:                             $lastsubonly.='<br />'.&mt('[quant,_1,file] uploaded to this anonymous survey',scalar(@{$files}));
                   2279:                         } else {
                   2280:                             $lastsubonly.='<br /><br />'.'<b>'.&mt('Submitted Files:').'</b>'
                   2281:                                         .'<br /><span class="LC_warning">';
                   2282:                             if(@$files == 1) {
                   2283:                                 $lastsubonly .= &mt('Like all files provided by users, this file may contain viruses!');
1.596     raeburn  2284:                             } else {
1.702     kruse    2285:                                 $lastsubonly .= &mt('Like all files provided by users, these files may contain viruses!');
                   2286:                             }
                   2287:                             $lastsubonly .= '</span>';                         
                   2288:                             foreach my $file (@$files) {
                   2289:                                 &Apache::lonnet::allowuploaded('/adm/grades',$file);
                   2290:                                 $lastsubonly.='<br /><a href="'.$file.'?rawmode=1" target="lonGRDs"><img src="'.&Apache::loncommon::icon($file).'" border="0" alt="" /> '.$file.'</a>';
1.596     raeburn  2291:                             }
                   2292:                         }
1.702     kruse    2293: 			$lastsubonly.='<br />';
                   2294:                     }
                   2295:                     if ($hide eq 'anon') {
                   2296:                         $lastsubonly.='<br /><b>'.&mt('Anonymous Survey').'</b>'; 
                   2297:                     } else {
                   2298:              	        $lastsubonly.='<br /><b>'.&mt('Submitted Answer:').' </b>'.
                   2299: 			    &cleanRecord($subval,$responsetype,$symb,$partid,
                   2300: 					 $respid,\%record,$order,undef,$uname,$udom,$type,$trial,$rndseed);
                   2301:                     }
                   2302: 	            if ($similar) {$lastsubonly.="<br /><br />$similar\n";}
                   2303: 		    $lastsubonly.='</div>';
1.41      ng       2304: 		}
1.702     kruse    2305:             }
1.151     albertel 2306: 	}
1.702     kruse    2307: 	$lastsubonly.='</div>'."\n"; # End: LC_grade_submissions_body
                   2308:     }
                   2309:     $request->print($lastsubonly);
                   2310:     if ($env{'form.lastSub'} eq 'datesub') {
1.623     www      2311:         my ($parts,$handgrade,$responseType) = &response_type($symb,\$res_error);
1.148     albertel 2312: 	$request->print(&displaySubByDates($symb,\%record,$parts,$responseType,$checkIcon,$uname,$udom));
1.720   ! kruse    2313:   
1.702     kruse    2314:     } 
                   2315:     if ($env{'form.lastSub'} =~ /^(last|all)$/) {
                   2316:         $request->print(&Apache::loncommon::get_previous_attempt($symb,$uname,$udom,
1.257     albertel 2317: 								 $env{'request.course.id'},
1.44      ng       2318: 								 $last,'.submission',
                   2319: 								 'Apache::grades::keywords_highlight'));
1.41      ng       2320:     }
1.121     ng       2321:     $request->print('<input type="hidden" name="unamedom'.$counter.'" value="'.$uname.':'
                   2322: 	.$udom.'" />'."\n");
1.44      ng       2323:     # return if view submission with no grading option
1.618     www      2324:     if (!&canmodify($usec)) {
1.633     www      2325: 	$request->print('<p><span class="LC_warning">'.&mt('No grading privileges').'</span></p></div>');
1.41      ng       2326: 	return;
1.180     albertel 2327:     } else {
1.468     albertel 2328: 	$request->print('</div>'."\n");
1.41      ng       2329:     }
1.33      ng       2330: 
1.121     ng       2331:     # essay grading message center
1.624     www      2332: #    if ($env{'form.handgrade'} eq 'yes') {
                   2333:     if (1) {
1.468     albertel 2334: 	my $result='<div class="LC_grade_message_center">';
                   2335:     
                   2336: 	$result.='<div class="LC_grade_message_center_header">'.
                   2337: 	    &mt('Send Message').'</div><div class="LC_grade_message_center_body">';
1.257     albertel 2338: 	my ($lastname,$givenn) = split(/,/,$env{'form.fullname'});
1.118     ng       2339: 	my $msgfor = $givenn.' '.$lastname;
1.464     albertel 2340: 	if (scalar(@$col_fullnames) > 0) {
                   2341: 	    my $lastone = pop(@$col_fullnames);
                   2342: 	    $msgfor .= ', '.(join ', ',@$col_fullnames).' and '.$lastone.'.';
1.118     ng       2343: 	}
                   2344: 	$msgfor =~ s/\'/\\'/g; #' stupid emacs - no! javascript
1.468     albertel 2345: 	$result.='<input type="hidden" name="includemsg'.$counter.'" value="" />'."\n".
1.121     ng       2346: 	    '<input type="hidden" name="newmsg'.$counter.'" value="" />'."\n";
                   2347: 	$result.='&nbsp;<a href="javascript:msgCenter(document.SCORE,'.$counter.
1.417     albertel 2348: 	    ',\''.$msgfor.'\');" target="_self">'.
1.695     bisitz   2349: 	    &mt('Compose message to student'.(scalar(@$col_fullnames) >= 1 ? 's' : '')).'</a><label> ('.
1.350     albertel 2350: 	    &mt('incl. grades').' <input type="checkbox" name="withgrades'.$counter.'" /></label>)'.
1.695     bisitz   2351: 	    ' <img src="'.$request->dir_config('lonIconsURL').
                   2352: 	    '/mailbkgrd.gif" width="14" height="10" alt="" name="mailicon'.$counter.'" />'."\n".
1.298     www      2353: 	    '<br />&nbsp;('.
1.468     albertel 2354: 	    &mt('Message will be sent when you click on Save &amp; Next below.').")\n";
                   2355: 	$result.='</div></div>';
1.121     ng       2356: 	$request->print($result);
1.118     ng       2357:     }
1.41      ng       2358: 
                   2359:     my %seen = ();
                   2360:     my @partlist;
1.129     ng       2361:     my @gradePartRespid;
1.375     albertel 2362:     my @part_response_id = &flatten_responseType($responseType);
1.585     bisitz   2363:     $request->print(
1.588     bisitz   2364:         '<div class="LC_Box">'
                   2365:        .'<h3 class="LC_hcell">'.&mt('Assign Grades').'</h3>'
1.585     bisitz   2366:     );
1.592     bisitz   2367:     $request->print(&gradeBox_start());
1.375     albertel 2368:     foreach my $part_response_id (@part_response_id) {
                   2369:     	my ($partid,$respid) = @{ $part_response_id };
                   2370: 	my $part_resp = join('_',@{ $part_response_id });
1.322     albertel 2371: 	next if ($seen{$partid} > 0);
1.41      ng       2372: 	$seen{$partid}++;
1.393     albertel 2373: 	next if ($$handgrade{$part_resp} ne 'yes' 
                   2374: 		 && $env{'form.lastSub'} eq 'hdgrade');
1.524     raeburn  2375: 	push(@partlist,$partid);
                   2376: 	push(@gradePartRespid,$partid.'.'.$respid);
1.322     albertel 2377: 	$request->print(&gradeBox($request,$symb,$uname,$udom,$counter,$partid,\%record));
1.41      ng       2378:     }
1.585     bisitz   2379:     $request->print(&gradeBox_end()); # </div>
                   2380:     $request->print('</div>');
1.468     albertel 2381: 
                   2382:     $request->print('<div class="LC_grade_info_links">');
                   2383:     $request->print('</div>');
                   2384: 
1.45      ng       2385:     $result='<input type="hidden" name="partlist'.$counter.
                   2386: 	'" value="'.(join ":",@partlist).'" />'."\n";
1.129     ng       2387:     $result.='<input type="hidden" name="gradePartRespid'.
                   2388: 	'" value="'.(join ":",@gradePartRespid).'" />'."\n" if ($counter == 0);
1.45      ng       2389:     my $ctr = 0;
                   2390:     while ($ctr < scalar(@partlist)) {
                   2391: 	$result.='<input type="hidden" name="partid'.$counter.'_'.$ctr.'" value="'.
                   2392: 	    $partlist[$ctr].'" />'."\n";
                   2393: 	$ctr++;
                   2394:     }
1.468     albertel 2395:     $request->print($result.''."\n");
1.41      ng       2396: 
1.441     www      2397: # Done with printing info for one student
                   2398: 
1.468     albertel 2399:     $request->print('</div>');#LC_grade_show_user
1.441     www      2400: 
                   2401: 
1.41      ng       2402:     # print end of form
                   2403:     if ($counter == $total) {
1.592     bisitz   2404:         my $endform='<br /><hr /><table border="0"><tr><td>'."\n";
1.485     albertel 2405: 	$endform.='<input type="button" value="'.&mt('Save &amp; Next').'" '.
1.589     bisitz   2406: 	    'onclick="javascript:checksubmit(this.form,\'Save & Next\','.
1.417     albertel 2407: 	    $total.','.scalar(@partlist).');" target="_self" /> &nbsp;'."\n";
1.119     ng       2408: 	my $ntstu ='<select name="NTSTU">'.
                   2409: 	    '<option>1</option><option>2</option>'.
                   2410: 	    '<option>3</option><option>5</option>'.
                   2411: 	    '<option>7</option><option>10</option></select>'."\n";
1.257     albertel 2412: 	my $nsel = ($env{'form.NTSTU'} ne '' ? $env{'form.NTSTU'} : '1');
1.401     albertel 2413: 	$ntstu =~ s/<option>$nsel</<option selected="selected">$nsel</;
1.578     raeburn  2414:         $endform.=&mt('[_1]student(s)',$ntstu);
1.485     albertel 2415: 	$endform.='&nbsp;&nbsp;<input type="button" value="'.&mt('Previous').'" '.
1.589     bisitz   2416: 	    'onclick="javascript:checksubmit(this.form,\'Previous\');" target="_self" /> &nbsp;'."\n".
1.485     albertel 2417: 	    '<input type="button" value="'.&mt('Next').'" '.
1.589     bisitz   2418: 	    'onclick="javascript:checksubmit(this.form,\'Next\');" target="_self" /> &nbsp;';
1.592     bisitz   2419:         $endform.='<span class="LC_warning">'.
                   2420:                   &mt('(Next and Previous (student) do not save the scores.)').
                   2421:                   '</span>'."\n" ;
1.349     albertel 2422:         $endform.="<input type='hidden' value='".&get_increment().
1.348     bowersj2 2423:             "' name='increment' />";
1.485     albertel 2424: 	$endform.='</td></tr></table></form>';
1.41      ng       2425: 	$request->print($endform);
                   2426:     }
                   2427:     return '';
1.38      ng       2428: }
                   2429: 
1.464     albertel 2430: sub check_collaborators {
                   2431:     my ($symb,$uname,$udom,$record,$handgrade,$counter) = @_;
                   2432:     my ($result,@col_fullnames);
                   2433:     my ($classlist,undef,$fullname) = &getclasslist('all','0');
                   2434:     foreach my $part (keys(%$handgrade)) {
                   2435: 	my $ncol = &Apache::lonnet::EXT('resource.'.$part.
                   2436: 					'.maxcollaborators',
                   2437: 					$symb,$udom,$uname);
                   2438: 	next if ($ncol <= 0);
                   2439: 	$part =~ s/\_/\./g;
                   2440: 	next if ($record->{'resource.'.$part.'.collaborators'} eq '');
                   2441: 	my (@good_collaborators, @bad_collaborators);
                   2442: 	foreach my $possible_collaborator
1.630     www      2443: 	    (split(/[,;\s]+/,$record->{'resource.'.$part.'.collaborators'})) { 
1.464     albertel 2444: 	    $possible_collaborator =~ s/[\$\^\(\)]//g;
                   2445: 	    next if ($possible_collaborator eq '');
1.631     www      2446: 	    my ($co_name,$co_dom) = split(/:/,$possible_collaborator);
1.464     albertel 2447: 	    $co_dom = $udom if (! defined($co_dom) || $co_dom =~ /^domain$/i);
                   2448: 	    next if ($co_name eq $uname && $co_dom eq $udom);
                   2449: 	    # Doing this grep allows 'fuzzy' specification
                   2450: 	    my @matches = grep(/^\Q$co_name\E:\Q$co_dom\E$/i, 
                   2451: 			       keys(%$classlist));
                   2452: 	    if (! scalar(@matches)) {
                   2453: 		push(@bad_collaborators, $possible_collaborator);
                   2454: 	    } else {
                   2455: 		push(@good_collaborators, @matches);
                   2456: 	    }
                   2457: 	}
                   2458: 	if (scalar(@good_collaborators) != 0) {
1.630     www      2459: 	    $result.='<br />'.&mt('Collaborators:').'<ol>';
1.464     albertel 2460: 	    foreach my $name (@good_collaborators) {
                   2461: 		my ($lastname,$givenn) = split(/,/,$$fullname{$name});
                   2462: 		push(@col_fullnames, $givenn.' '.$lastname);
1.630     www      2463: 		$result.='<li>'.$fullname->{$name}.'</li>';
1.464     albertel 2464: 	    }
1.630     www      2465: 	    $result.='</ol><br />'."\n";
1.466     albertel 2466: 	    my ($part)=split(/\./,$part);
1.464     albertel 2467: 	    $result.='<input type="hidden" name="collaborator'.$counter.
                   2468: 		'" value="'.$part.':'.(join ':',@good_collaborators).'" />'.
                   2469: 		"\n";
                   2470: 	}
                   2471: 	if (scalar(@bad_collaborators) > 0) {
1.466     albertel 2472: 	    $result.='<div class="LC_warning">';
1.464     albertel 2473: 	    $result.=&mt('This student has submitted [quant,_1,invalid collaborator]: [_2]',scalar(@bad_collaborators),join(', ',@bad_collaborators));
                   2474: 	    $result .= '</div>';
                   2475: 	}         
                   2476: 	if (scalar(@bad_collaborators > $ncol)) {
1.466     albertel 2477: 	    $result .= '<div class="LC_warning">';
1.464     albertel 2478: 	    $result .= &mt('This student has submitted too many '.
                   2479: 		'collaborators.  Maximum is [_1].',$ncol);
                   2480: 	    $result .= '</div>';
                   2481: 	}
                   2482:     }
                   2483:     return ($result,$fullname,\@col_fullnames);
                   2484: }
                   2485: 
1.44      ng       2486: #--- Retrieve the last submission for all the parts
1.38      ng       2487: sub get_last_submission {
1.119     ng       2488:     my ($returnhash)=@_;
1.596     raeburn  2489:     my (@string,$timestamp,%lasthidden);
1.119     ng       2490:     if ($$returnhash{'version'}) {
1.46      ng       2491: 	my %lasthash=();
                   2492: 	my ($version);
1.119     ng       2493: 	for ($version=1;$version<=$$returnhash{'version'};$version++) {
1.397     albertel 2494: 	    foreach my $key (sort(split(/\:/,
                   2495: 					$$returnhash{$version.':keys'}))) {
                   2496: 		$lasthash{$key}=$$returnhash{$version.':'.$key};
                   2497: 		$timestamp = 
1.545     raeburn  2498: 		    &Apache::lonlocal::locallocaltime($$returnhash{$version.':timestamp'});
1.46      ng       2499: 	    }
                   2500: 	}
1.640     raeburn  2501:         my (%typeparts,%randombytry);
1.596     raeburn  2502:         my $showsurv = 
                   2503:             &Apache::lonnet::allowed('vas',$env{'request.course.id'});
                   2504:         foreach my $key (sort(keys(%lasthash))) {
                   2505:             if ($key =~ /\.type$/) {
                   2506:                 if (($lasthash{$key} eq 'anonsurvey') || 
1.640     raeburn  2507:                     ($lasthash{$key} eq 'anonsurveycred') ||
                   2508:                     ($lasthash{$key} eq 'randomizetry')) {
1.596     raeburn  2509:                     my ($ign,@parts) = split(/\./,$key);
                   2510:                     pop(@parts);
1.641     raeburn  2511:                     my $id = join('.',@parts);
1.640     raeburn  2512:                     if ($lasthash{$key} eq 'randomizetry') {
                   2513:                         $randombytry{$ign.'.'.$id} = $lasthash{$key};
                   2514:                     } else {
                   2515:                         unless ($showsurv) {
                   2516:                             $typeparts{$ign.'.'.$id} = $lasthash{$key};
                   2517:                         }
1.596     raeburn  2518:                     }
                   2519:                     delete($lasthash{$key});
                   2520:                 }
                   2521:             }
                   2522:         }
                   2523:         my @hidden = keys(%typeparts);
1.640     raeburn  2524:         my @randomize = keys(%randombytry);
1.397     albertel 2525: 	foreach my $key (keys(%lasthash)) {
                   2526: 	    next if ($key !~ /\.submission$/);
1.596     raeburn  2527:             my $hide;
                   2528:             if (@hidden) {
                   2529:                 foreach my $id (@hidden) {
                   2530:                     if ($key =~ /^\Q$id\E/) {
1.640     raeburn  2531:                         $hide = 'anon';
1.596     raeburn  2532:                         last;
                   2533:                     }
                   2534:                 }
                   2535:             }
1.640     raeburn  2536:             unless ($hide) {
                   2537:                 if (@randomize) {
                   2538:                     foreach my $id (@hidden) {
                   2539:                         if ($key =~ /^\Q$id\E/) {
                   2540:                             $hide = 'rand';
                   2541:                             last;
                   2542:                         }
                   2543:                     }
                   2544:                 }
                   2545:             }
1.397     albertel 2546: 	    my ($partid,$foo) = split(/submission$/,$key);
                   2547: 	    my $draft  = $lasthash{$partid.'awarddetail'} eq 'DRAFT' ?
1.717     bisitz   2548: 		'<span class="LC_warning">'.&mt('Draft Copy').'</span> ' : '';
1.716     bisitz   2549: 	    #push(@string, join(':', $key, $hide, $draft.$lasthash{$key}));
                   2550:             push(@string, join(':', $key, $hide, $draft.(
                   2551:                 ref($lasthash{$key}) eq 'ARRAY' ?
                   2552:                     join(',', @{$lasthash{$key}}) : $lasthash{$key}) ));
1.41      ng       2553: 	}
                   2554:     }
1.397     albertel 2555:     if (!@string) {
                   2556: 	$string[0] =
1.539     riegler  2557: 	    '<span class="LC_warning">'.&mt('Nothing submitted - no attempts.').'</span>';
1.397     albertel 2558:     }
                   2559:     return (\@string,\$timestamp);
1.38      ng       2560: }
1.35      ng       2561: 
1.44      ng       2562: #--- High light keywords, with style choosen by user.
1.38      ng       2563: sub keywords_highlight {
1.44      ng       2564:     my $string    = shift;
1.257     albertel 2565:     my $size      = $env{'form.kwsize'} eq '0' ? '' : 'size='.$env{'form.kwsize'};
                   2566:     my $styleon   = $env{'form.kwstyle'} eq ''  ? '' : $env{'form.kwstyle'};
1.41      ng       2567:     (my $styleoff = $styleon) =~ s/\</\<\//;
1.257     albertel 2568:     my @keylist   = split(/[,\s+]/,$env{'form.keywords'});
1.398     albertel 2569:     foreach my $keyword (@keylist) {
                   2570: 	$string =~ s/\b\Q$keyword\E(\b|\.)/<font color\=$env{'form.kwclr'} $size\>$styleon$keyword$styleoff<\/font>/gi;
1.41      ng       2571:     }
                   2572:     return $string;
1.38      ng       2573: }
1.36      ng       2574: 
1.671     raeburn  2575: # For Tasks provide a mechanism to display previous version for one specific student
                   2576: 
                   2577: sub show_previous_task_version {
                   2578:     my ($request,$symb) = @_;
                   2579:     if ($symb eq '') {
1.717     bisitz   2580:         $request->print(
                   2581:             '<span class="LC_error">'.
                   2582:             &mt('Unable to handle ambiguous references.').
                   2583:             '</span>');
1.671     raeburn  2584:         return '';
                   2585:     }
                   2586:     my ($uname,$udom) = ($env{'form.student'},$env{'form.userdom'});
                   2587:     my $usec = &Apache::lonnet::getsection($udom,$uname,$env{'request.course.id'});
                   2588:     if (!&canview($usec)) {
1.712     bisitz   2589:         $request->print(
                   2590:             '<span class="LC_warning">'.
1.713     bisitz   2591:             &mt('Unable to view previous version for requested student.').
1.712     bisitz   2592:             ' '.&mt('([_1] in section [_2] in course id [_3])',
                   2593:                     $uname.':'.$udom,$usec,$env{'request.course.id'}).
                   2594:             '</span>');
1.671     raeburn  2595:         return;
                   2596:     }
                   2597:     my $mode = 'both';
                   2598:     my $isTask = ($symb =~/\.task$/);
                   2599:     if ($isTask) {
                   2600:         if ($env{'form.previousversion'} =~ /^\d+$/) {
                   2601:             if ($env{'form.fullname'} eq '') {
                   2602:                 $env{'form.fullname'} =
                   2603:                     &Apache::loncommon::plainname($uname,$udom,'lastname');
                   2604:             }
                   2605:             my $probtitle=&Apache::lonnet::gettitle($symb);
                   2606:             $request->print("\n\n".
                   2607:                             '<div class="LC_grade_show_user">'.
                   2608:                             '<h2>'.&nameUserString(undef,$env{'form.fullname'},$uname,$udom).
                   2609:                             '</h2>'."\n");
                   2610:             &Apache::lonxml::clear_problem_counter();
                   2611:             $request->print(&show_problem($request,$symb,$uname,$udom,1,1,$mode,
                   2612:                             {'previousversion' => $env{'form.previousversion'} }));
                   2613:             $request->print("\n</div>");
                   2614:         }
                   2615:     }
                   2616:     return;
                   2617: }
                   2618: 
                   2619: sub choose_task_version_form {
                   2620:     my ($symb,$uname,$udom,$nomenu) = @_;
                   2621:     my $isTask = ($symb =~/\.task$/);
                   2622:     my ($current,$version,$result,$js,$displayed,$rowtitle);
                   2623:     if ($isTask) {
                   2624:         my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},
                   2625:                                               $udom,$uname);
                   2626:         if (($record{'resource.0.version'} eq '') ||
                   2627:             ($record{'resource.0.version'} < 2)) {
                   2628:             return ($record{'resource.0.version'},
                   2629:                     $record{'resource.0.version'},$result,$js);
                   2630:         } else {
                   2631:             $current = $record{'resource.0.version'};
                   2632:         }
                   2633:         if ($env{'form.previousversion'}) {
                   2634:             $displayed = $env{'form.previousversion'};
                   2635:             $rowtitle = &mt('Choose another version:')
                   2636:         } else {
                   2637:             $displayed = $current;
                   2638:             $rowtitle = &mt('Show earlier version:');
                   2639:         }
                   2640:         $result = '<div class="LC_left_float">';
                   2641:         my $list;
                   2642:         my $numversions = 0;
                   2643:         for (my $i=1; $i<=$record{'resource.0.version'}; $i++) {
                   2644:             if ($i == $current) {
                   2645:                 if (!$env{'form.previousversion'} || $nomenu) {
                   2646:                     next;
                   2647:                 } else {
                   2648:                     $list .= '<option value="'.$i.'">'.&mt('Current').'</option>'."\n";
                   2649:                     $numversions ++;
                   2650:                 }
                   2651:             } elsif (defined($record{'resource.'.$i.'.0.status'})) {
                   2652:                 unless ($i == $env{'form.previousversion'}) {
                   2653:                     $numversions ++;
                   2654:                 }
                   2655:                 $list .= '<option value="'.$i.'">'.$i.'</option>'."\n";
                   2656:             }
                   2657:         }
                   2658:         if ($numversions) {
                   2659:             $symb = &HTML::Entities::encode($symb,'<>"&');
                   2660:             $result .=
                   2661:                 '<form name="getprev" method="post" action=""'.
                   2662:                 ' onsubmit="return previousVersion('."'$uname','$udom','$symb','$displayed'".');">'.
                   2663:                 &Apache::loncommon::start_data_table().
                   2664:                 &Apache::loncommon::start_data_table_row().
                   2665:                 '<th align="left">'.$rowtitle.'</th>'.
                   2666:                 '<td><select name="version">'.
                   2667:                 '<option>'.&mt('Select').'</option>'.
                   2668:                 $list.
                   2669:                 '</select></td>'.
                   2670:                 &Apache::loncommon::end_data_table_row();
                   2671:             unless ($nomenu) {
                   2672:                 $result .= &Apache::loncommon::start_data_table_row().
                   2673:                 '<th align="left">'.&mt('Open in new window').'</th>'.
                   2674:                 '<td><span class="LC_nobreak">'.
                   2675:                 '<label><input type="radio" name="prevwin" value="1" />'.
                   2676:                 &mt('Yes').'</label>'.
                   2677:                 '<label><input type="radio" name="prevwin" value="0" checked="checked" />'.&mt('No').'</label>'.
                   2678:                 '</span></td>'.
                   2679:                 &Apache::loncommon::end_data_table_row();
                   2680:             }
                   2681:             $result .=
                   2682:                 &Apache::loncommon::start_data_table_row().
                   2683:                 '<th align="left">&nbsp;</th>'.
                   2684:                 '<td>'.
                   2685:                 '<input type="submit" name="prevsub" value="'.&mt('Display').'" />'.
                   2686:                 '</td>'.
                   2687:                 &Apache::loncommon::end_data_table_row().
                   2688:                 &Apache::loncommon::end_data_table().
                   2689:                 '</form>';
                   2690:             $js = &previous_display_javascript($nomenu,$current);
                   2691:         } elsif ($displayed && $nomenu) {
                   2692:             $result .= '<a href="javascript:window.close()">'.&mt('Close window').'</a>';
                   2693:         } else {
                   2694:             $result .= &mt('No previous versions to show for this student');
                   2695:         }
                   2696:         $result .= '</div>';
                   2697:     }
                   2698:     return ($current,$displayed,$result,$js);
                   2699: }
                   2700: 
                   2701: sub previous_display_javascript {
                   2702:     my ($nomenu,$current) = @_;
                   2703:     my $js = <<"JSONE";
                   2704: <script type="text/javascript">
                   2705: // <![CDATA[
                   2706: function previousVersion(uname,udom,symb) {
                   2707:     var current = '$current';
                   2708:     var version = document.getprev.version.options[document.getprev.version.selectedIndex].value;
                   2709:     var prevstr = new RegExp("^\\\\d+\$");
                   2710:     if (!prevstr.test(version)) {
                   2711:         return false;
                   2712:     }
                   2713:     var url = '';
                   2714:     if (version == current) {
                   2715:         url = '/adm/grades?student='+uname+'&userdom='+udom+'&symb='+symb+'&command=submission';
                   2716:     } else {
                   2717:         url = '/adm/grades?student='+uname+'&userdom='+udom+'&symb='+symb+'&command=versionsub&previousversion='+version;
                   2718:     }
                   2719: JSONE
                   2720:     if ($nomenu) {
                   2721:         $js .= <<"JSTWO";
                   2722:     document.location.href = url;
                   2723: JSTWO
                   2724:     } else {
                   2725:         $js .= <<"JSTHREE";
                   2726:     var newwin = 0;
                   2727:     for (var i=0; i<document.getprev.prevwin.length; i++) {
                   2728:         if (document.getprev.prevwin[i].checked == true) {
                   2729:             newwin = document.getprev.prevwin[i].value;
                   2730:         }
                   2731:     }
                   2732:     if (newwin == 1) {
                   2733:         var options = 'height=600,width=800,resizable=yes,scrollbars=yes,location=no,menubar=no,toolbar=no';
                   2734:         url = url+'&inhibitmenu=yes';
                   2735:         if (typeof(previousWin) == 'undefined' || previousWin.closed) {
                   2736:             previousWin = window.open(url,'',options,1);
                   2737:         } else {
                   2738:             previousWin.location.href = url;
                   2739:         }
                   2740:         previousWin.focus();
                   2741:         return false;
                   2742:     } else {
                   2743:         document.location.href = url;
                   2744:         return false;
                   2745:     }
                   2746: JSTHREE
                   2747:     }
                   2748:     $js .= <<"ENDJS";
                   2749:     return false;
                   2750: }
                   2751: // ]]>
                   2752: </script>
                   2753: ENDJS
                   2754: 
                   2755: }
                   2756: 
1.44      ng       2757: #--- Called from submission routine
1.38      ng       2758: sub processHandGrade {
1.608     www      2759:     my ($request,$symb) = @_;
1.324     albertel 2760:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
1.257     albertel 2761:     my $button = $env{'form.gradeOpt'};
                   2762:     my $ngrade = $env{'form.NCT'};
                   2763:     my $ntstu  = $env{'form.NTSTU'};
1.301     albertel 2764:     my $cdom   = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   2765:     my $cnum   = $env{'course.'.$env{'request.course.id'}.'.num'};
                   2766: 
1.44      ng       2767:     if ($button eq 'Save & Next') {
                   2768: 	my $ctr = 0;
                   2769: 	while ($ctr < $ngrade) {
1.257     albertel 2770: 	    my ($uname,$udom) = split(/:/,$env{'form.unamedom'.$ctr});
1.324     albertel 2771: 	    my ($errorflag,$pts,$wgt) = &saveHandGrade($request,$symb,$uname,$udom,$ctr);
1.71      ng       2772: 	    if ($errorflag eq 'no_score') {
                   2773: 		$ctr++;
                   2774: 		next;
                   2775: 	    }
1.104     albertel 2776: 	    if ($errorflag eq 'not_allowed') {
1.398     albertel 2777: 		$request->print("<span class=\"LC_warning\">Not allowed to modify grades for $uname:$udom</span>");
1.104     albertel 2778: 		$ctr++;
                   2779: 		next;
                   2780: 	    }
1.257     albertel 2781: 	    my $includemsg = $env{'form.includemsg'.$ctr};
1.44      ng       2782: 	    my ($subject,$message,$msgstatus) = ('','','');
1.418     albertel 2783: 	    my $restitle = &Apache::lonnet::gettitle($symb);
                   2784:             my ($feedurl,$showsymb) =
                   2785: 		&get_feedurl_and_symb($symb,$uname,$udom);
                   2786: 	    my $messagetail;
1.62      albertel 2787: 	    if ($includemsg =~ /savemsg|newmsg\Q$ctr\E/) {
1.298     www      2788: 		$subject = $env{'form.msgsub'} if ($includemsg =~ /msgsub/);
1.295     www      2789: 		unless ($subject=~/\w/) { $subject=&mt('Grading Feedback'); }
1.386     raeburn  2790: 		$subject.=' ['.$restitle.']';
1.44      ng       2791: 		my (@msgnum) = split(/,/,$includemsg);
                   2792: 		foreach (@msgnum) {
1.257     albertel 2793: 		    $message.=$env{'form.'.$_} if ($_ =~ /savemsg|newmsg/ && $_ ne '');
1.44      ng       2794: 		}
1.80      ng       2795: 		$message =&Apache::lonfeedback::clear_out_html($message);
1.298     www      2796: 		if ($env{'form.withgrades'.$ctr}) {
                   2797: 		    $message.="\n\nPoint".($pts > 1 ? 's':'').' awarded = '.$pts.' out of '.$wgt;
1.386     raeburn  2798: 		    $messagetail = " for <a href=\"".
1.605     www      2799: 		                   $feedurl."?symb=$showsymb\">$restitle</a>";
1.386     raeburn  2800: 		}
                   2801: 		$msgstatus = 
                   2802:                     &Apache::lonmsg::user_normal_msg($uname,$udom,$subject,
                   2803: 						     $message.$messagetail,
1.418     albertel 2804:                                                      undef,$feedurl,undef,
1.386     raeburn  2805:                                                      undef,undef,$showsymb,
                   2806:                                                      $restitle);
1.574     bisitz   2807: 		$request->print('<br />'.&mt('Sending message to [_1]',$uname.':'.$udom).': '.
1.652     raeburn  2808: 				$msgstatus.'<br />');
1.44      ng       2809: 	    }
1.257     albertel 2810: 	    if ($env{'form.collaborator'.$ctr}) {
1.155     albertel 2811: 		my @collabstrs=&Apache::loncommon::get_env_multiple("form.collaborator$ctr");
1.150     albertel 2812: 		foreach my $collabstr (@collabstrs) {
                   2813: 		    my ($part,@collaborators) = split(/:/,$collabstr);
1.310     banghart 2814: 		    foreach my $collaborator (@collaborators) {
1.150     albertel 2815: 			my ($errorflag,$pts,$wgt) = 
1.324     albertel 2816: 			    &saveHandGrade($request,$symb,$collaborator,$udom,$ctr,
1.257     albertel 2817: 					   $env{'form.unamedom'.$ctr},$part);
1.150     albertel 2818: 			if ($errorflag eq 'not_allowed') {
1.362     albertel 2819: 			    $request->print("<span class=\"LC_error\">".&mt('Not allowed to modify grades for [_1]',"$collaborator:$udom")."</span>");
1.150     albertel 2820: 			    next;
1.418     albertel 2821: 			} elsif ($message ne '') {
                   2822: 			    my ($baseurl,$showsymb) = 
                   2823: 				&get_feedurl_and_symb($symb,$collaborator,
                   2824: 						      $udom);
                   2825: 			    if ($env{'form.withgrades'.$ctr}) {
                   2826: 				$messagetail = " for <a href=\"".
1.605     www      2827:                                     $baseurl."?symb=$showsymb\">$restitle</a>";
1.150     albertel 2828: 			    }
1.418     albertel 2829: 			    $msgstatus = 
                   2830: 				&Apache::lonmsg::user_normal_msg($collaborator,$udom,$subject,$message.$messagetail,undef,$baseurl,undef,undef,undef,$showsymb,$restitle);
1.104     albertel 2831: 			}
1.44      ng       2832: 		    }
                   2833: 		}
                   2834: 	    }
                   2835: 	    $ctr++;
                   2836: 	}
                   2837:     }
                   2838: 
1.624     www      2839: #    if ($env{'form.handgrade'} eq 'yes') {
                   2840:     if (1) {
1.119     ng       2841: 	# Keywords sorted in alphabatical order
1.257     albertel 2842: 	my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
1.119     ng       2843: 	my %keyhash = ();
1.257     albertel 2844: 	$env{'form.keywords'}           =~ s/,\s{0,}|\s+/ /g;
                   2845: 	$env{'form.keywords'}           =~ s/^\s+|\s+$//;
                   2846: 	my (@keywords) = sort(split(/\s+/,$env{'form.keywords'}));
                   2847: 	$env{'form.keywords'} = join(' ',@keywords);
                   2848: 	$keyhash{$symb.'_keywords'}     = $env{'form.keywords'};
                   2849: 	$keyhash{$symb.'_subject'}      = $env{'form.msgsub'};
                   2850: 	$keyhash{$loginuser.'_kwclr'}   = $env{'form.kwclr'};
                   2851: 	$keyhash{$loginuser.'_kwsize'}  = $env{'form.kwsize'};
                   2852: 	$keyhash{$loginuser.'_kwstyle'} = $env{'form.kwstyle'};
1.119     ng       2853: 
                   2854: 	# message center - Order of message gets changed. Blank line is eliminated.
1.257     albertel 2855: 	# New messages are saved in env for the next student.
1.119     ng       2856: 	# All messages are saved in nohist_handgrade.db
                   2857: 	my ($ctr,$idx) = (1,1);
1.257     albertel 2858: 	while ($ctr <= $env{'form.savemsgN'}) {
                   2859: 	    if ($env{'form.savemsg'.$ctr} ne '') {
                   2860: 		$keyhash{$symb.'_savemsg'.$idx} = $env{'form.savemsg'.$ctr};
1.119     ng       2861: 		$idx++;
                   2862: 	    }
                   2863: 	    $ctr++;
1.41      ng       2864: 	}
1.119     ng       2865: 	$ctr = 0;
                   2866: 	while ($ctr < $ngrade) {
1.257     albertel 2867: 	    if ($env{'form.newmsg'.$ctr} ne '') {
                   2868: 		$keyhash{$symb.'_savemsg'.$idx} = $env{'form.newmsg'.$ctr};
                   2869: 		$env{'form.savemsg'.$idx} = $env{'form.newmsg'.$ctr};
1.119     ng       2870: 		$idx++;
                   2871: 	    }
                   2872: 	    $ctr++;
1.41      ng       2873: 	}
1.257     albertel 2874: 	$env{'form.savemsgN'} = --$idx;
                   2875: 	$keyhash{$symb.'_savemsgN'} = $env{'form.savemsgN'};
1.119     ng       2876: 	my $putresult = &Apache::lonnet::put
1.301     albertel 2877: 	    ('nohist_handgrade',\%keyhash,$cdom,$cnum);
1.41      ng       2878:     }
1.44      ng       2879:     # Called by Save & Refresh from Highlight Attribute Window
1.257     albertel 2880:     my (undef,undef,$fullname) = &getclasslist($env{'form.section'},'1');
                   2881:     if ($env{'form.refresh'} eq 'on') {
1.86      ng       2882: 	my ($ctr,$total) = (0,0);
                   2883: 	while ($ctr < $ngrade) {
1.257     albertel 2884: 	    $total++ if  $env{'form.unamedom'.$ctr} ne '';
1.86      ng       2885: 	    $ctr++;
                   2886: 	}
1.257     albertel 2887: 	$env{'form.NTSTU'}=$ngrade;
1.86      ng       2888: 	$ctr = 0;
                   2889: 	while ($ctr < $total) {
1.257     albertel 2890: 	    my $processUser = $env{'form.unamedom'.$ctr};
                   2891: 	    ($env{'form.student'},$env{'form.userdom'}) = split(/:/,$processUser);
                   2892: 	    $env{'form.fullname'} = $$fullname{$processUser};
1.625     www      2893: 	    &submission($request,$ctr,$total-1,$symb);
1.41      ng       2894: 	    $ctr++;
                   2895: 	}
                   2896: 	return '';
                   2897:     }
1.36      ng       2898: 
1.44      ng       2899:     # Get the next/previous one or group of students
1.257     albertel 2900:     my $firststu = $env{'form.unamedom0'};
                   2901:     my $laststu = $env{'form.unamedom'.($ngrade-1)};
1.119     ng       2902:     my $ctr = 2;
1.41      ng       2903:     while ($laststu eq '') {
1.257     albertel 2904: 	$laststu  = $env{'form.unamedom'.($ngrade-$ctr)};
1.41      ng       2905: 	$ctr++;
                   2906: 	$laststu = $firststu if ($ctr > $ngrade);
                   2907:     }
1.44      ng       2908: 
1.41      ng       2909:     my (@parsedlist,@nextlist);
                   2910:     my ($nextflg) = 0;
1.524     raeburn  2911:     foreach my $item (sort 
1.294     albertel 2912: 	     {
                   2913: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                   2914: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                   2915: 		 }
                   2916: 		 return $a cmp $b;
                   2917: 	     } (keys(%$fullname))) {
1.605     www      2918: # FIXME: this is fishy, looks like the button label
1.41      ng       2919: 	if ($nextflg == 1 && $button =~ /Next$/) {
1.524     raeburn  2920: 	    push(@parsedlist,$item);
1.41      ng       2921: 	}
1.524     raeburn  2922: 	$nextflg = 1 if ($item eq $laststu);
1.41      ng       2923: 	if ($button eq 'Previous') {
1.524     raeburn  2924: 	    last if ($item eq $firststu);
                   2925: 	    push(@parsedlist,$item);
1.41      ng       2926: 	}
                   2927:     }
                   2928:     $ctr = 0;
1.605     www      2929: # FIXME: this is fishy, looks like the button label
1.41      ng       2930:     @parsedlist = reverse @parsedlist if ($button eq 'Previous');
1.582     raeburn  2931:     my $res_error;
                   2932:     my ($partlist) = &response_type($symb,\$res_error);
                   2933:     if ($res_error) {
                   2934:         $request->print(&navmap_errormsg());
                   2935:         return;
                   2936:     }
1.41      ng       2937:     foreach my $student (@parsedlist) {
1.257     albertel 2938: 	my $submitonly=$env{'form.submitonly'};
1.41      ng       2939: 	my ($uname,$udom) = split(/:/,$student);
1.301     albertel 2940: 	
                   2941: 	if ($submitonly eq 'queued') {
                   2942: 	    my %queue_status = 
                   2943: 		&Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
                   2944: 							$udom,$uname);
                   2945: 	    next if (!defined($queue_status{'gradingqueue'}));
                   2946: 	}
                   2947: 
1.156     albertel 2948: 	if ($submitonly =~ /^(yes|graded|incorrect)$/) {
1.257     albertel 2949: #	    my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
1.324     albertel 2950: 	    my %status=&student_gradeStatus($symb,$udom,$uname,$partlist);
1.145     albertel 2951: 	    my $submitted = 0;
1.248     albertel 2952: 	    my $ungraded = 0;
                   2953: 	    my $incorrect = 0;
1.524     raeburn  2954: 	    foreach my $item (keys(%status)) {
                   2955: 		$submitted = 1 if ($status{$item} ne 'nothing');
                   2956: 		$ungraded = 1 if ($status{$item} =~ /^ungraded/);
                   2957: 		$incorrect = 1 if ($status{$item} =~ /^incorrect/);
                   2958: 		my ($foo,$partid,$foo1) = split(/\./,$item);
1.145     albertel 2959: 		if ($status{'resource.'.$partid.'.submitted_by'} ne '') {
                   2960: 		    $submitted = 0;
                   2961: 		}
1.41      ng       2962: 	    }
1.156     albertel 2963: 	    next if (!$submitted && ($submitonly eq 'yes' ||
                   2964: 				     $submitonly eq 'incorrect' ||
                   2965: 				     $submitonly eq 'graded'));
1.248     albertel 2966: 	    next if (!$ungraded && ($submitonly eq 'graded'));
                   2967: 	    next if (!$incorrect && $submitonly eq 'incorrect');
1.41      ng       2968: 	}
1.524     raeburn  2969: 	push(@nextlist,$student) if ($ctr < $ntstu);
1.129     ng       2970: 	last if ($ctr == $ntstu);
1.41      ng       2971: 	$ctr++;
                   2972:     }
1.36      ng       2973: 
1.41      ng       2974:     $ctr = 0;
                   2975:     my $total = scalar(@nextlist)-1;
1.39      ng       2976: 
1.524     raeburn  2977:     foreach (sort(@nextlist)) {
1.41      ng       2978: 	my ($uname,$udom,$submitter) = split(/:/);
1.257     albertel 2979: 	$env{'form.student'}  = $uname;
                   2980: 	$env{'form.userdom'}  = $udom;
                   2981: 	$env{'form.fullname'} = $$fullname{$_};
1.625     www      2982: 	&submission($request,$ctr,$total,$symb);
1.41      ng       2983: 	$ctr++;
                   2984:     }
                   2985:     if ($total < 0) {
1.653     raeburn  2986: 	my $the_end.='<p>'.&mt('[_1]Message:[_2] No more students for this section or class.','<b>','</b>').'</p>'."\n";
1.41      ng       2987: 	$request->print($the_end);
                   2988:     }
                   2989:     return '';
1.38      ng       2990: }
1.36      ng       2991: 
1.44      ng       2992: #---- Save the score and award for each student, if changed
1.38      ng       2993: sub saveHandGrade {
1.324     albertel 2994:     my ($request,$symb,$stuname,$domain,$newflg,$submitter,$part) = @_;
1.342     banghart 2995:     my @version_parts;
1.104     albertel 2996:     my $usec = &Apache::lonnet::getsection($domain,$stuname,
1.257     albertel 2997: 					   $env{'request.course.id'});
1.104     albertel 2998:     if (!&canmodify($usec)) { return('not_allowed'); }
1.337     banghart 2999:     my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$domain,$stuname);
1.251     banghart 3000:     my @parts_graded;
1.77      ng       3001:     my %newrecord  = ();
                   3002:     my ($pts,$wgt) = ('','');
1.269     raeburn  3003:     my %aggregate = ();
                   3004:     my $aggregateflag = 0;
1.301     albertel 3005:     my @parts = split(/:/,$env{'form.partlist'.$newflg});
                   3006:     foreach my $new_part (@parts) {
1.337     banghart 3007: 	#collaborator ($submi may vary for different parts
1.259     banghart 3008: 	if ($submitter && $new_part ne $part) { next; }
                   3009: 	my $dropMenu = $env{'form.GD_SEL'.$newflg.'_'.$new_part};
1.125     ng       3010: 	if ($dropMenu eq 'excused') {
1.259     banghart 3011: 	    if ($record{'resource.'.$new_part.'.solved'} ne 'excused') {
                   3012: 		$newrecord{'resource.'.$new_part.'.solved'} = 'excused';
                   3013: 		if (exists($record{'resource.'.$new_part.'.awarded'})) {
                   3014: 		    $newrecord{'resource.'.$new_part.'.awarded'} = '';
1.58      albertel 3015: 		}
1.364     banghart 3016: 	        $newrecord{'resource.'.$new_part.'.regrader'}="$env{'user.name'}:$env{'user.domain'}";
1.58      albertel 3017: 	    }
1.125     ng       3018: 	} elsif ($dropMenu eq 'reset status'
1.259     banghart 3019: 		 && exists($record{'resource.'.$new_part.'.solved'})) { #don't bother if no old records -> no attempts
1.524     raeburn  3020: 	    foreach my $key (keys(%record)) {
1.259     banghart 3021: 		if ($key=~/^resource\.\Q$new_part\E\./) { $newrecord{$key} = ''; }
1.197     albertel 3022: 	    }
1.259     banghart 3023: 	    $newrecord{'resource.'.$new_part.'.regrader'}=
1.257     albertel 3024: 		"$env{'user.name'}:$env{'user.domain'}";
1.270     albertel 3025:             my $totaltries = $record{'resource.'.$part.'.tries'};
                   3026: 
                   3027:             my %last_resets = &get_last_resets($symb,$env{'request.course.id'},
                   3028: 					       [$new_part]);
                   3029:             my $aggtries =$totaltries;
1.269     raeburn  3030:             if ($last_resets{$new_part}) {
1.270     albertel 3031:                 $aggtries = &get_num_tries(\%record,$last_resets{$new_part},
                   3032: 					   $new_part);
1.269     raeburn  3033:             }
1.270     albertel 3034: 
                   3035:             my $solvedstatus = $record{'resource.'.$new_part.'.solved'};
1.269     raeburn  3036:             if ($aggtries > 0) {
1.327     albertel 3037:                 &decrement_aggs($symb,$new_part,\%aggregate,$aggtries,$totaltries,$solvedstatus);
1.269     raeburn  3038:                 $aggregateflag = 1;
                   3039:             }
1.125     ng       3040: 	} elsif ($dropMenu eq '') {
1.259     banghart 3041: 	    $pts = ($env{'form.GD_BOX'.$newflg.'_'.$new_part} ne '' ? 
                   3042: 		    $env{'form.GD_BOX'.$newflg.'_'.$new_part} : 
                   3043: 		    $env{'form.RADVAL'.$newflg.'_'.$new_part});
                   3044: 	    if ($pts eq '' && $env{'form.GD_SEL'.$newflg.'_'.$new_part} eq '') {
1.153     albertel 3045: 		next;
                   3046: 	    }
1.259     banghart 3047: 	    $wgt = $env{'form.WGT'.$newflg.'_'.$new_part} eq '' ? 1 : 
                   3048: 		$env{'form.WGT'.$newflg.'_'.$new_part};
1.41      ng       3049: 	    my $partial= $pts/$wgt;
1.259     banghart 3050: 	    if ($partial eq $record{'resource.'.$new_part.'.awarded'}) {
1.153     albertel 3051: 		#do not update score for part if not changed.
1.346     banghart 3052:                 &handback_files($request,$symb,$stuname,$domain,$newflg,$new_part,\%newrecord);
1.153     albertel 3053: 		next;
1.251     banghart 3054: 	    } else {
1.524     raeburn  3055: 	        push(@parts_graded,$new_part);
1.153     albertel 3056: 	    }
1.259     banghart 3057: 	    if ($record{'resource.'.$new_part.'.awarded'} ne $partial) {
                   3058: 		$newrecord{'resource.'.$new_part.'.awarded'}  = $partial;
1.153     albertel 3059: 	    }
1.259     banghart 3060: 	    my $reckey = 'resource.'.$new_part.'.solved';
1.41      ng       3061: 	    if ($partial == 0) {
1.153     albertel 3062: 		if ($record{$reckey} ne 'incorrect_by_override') {
                   3063: 		    $newrecord{$reckey} = 'incorrect_by_override';
                   3064: 		}
1.41      ng       3065: 	    } else {
1.153     albertel 3066: 		if ($record{$reckey} ne 'correct_by_override') {
                   3067: 		    $newrecord{$reckey} = 'correct_by_override';
                   3068: 		}
                   3069: 	    }	    
                   3070: 	    if ($submitter && 
1.259     banghart 3071: 		($record{'resource.'.$new_part.'.submitted_by'} ne $submitter)) {
                   3072: 		$newrecord{'resource.'.$new_part.'.submitted_by'} = $submitter;
1.41      ng       3073: 	    }
1.259     banghart 3074: 	    $newrecord{'resource.'.$new_part.'.regrader'}=
1.257     albertel 3075: 		"$env{'user.name'}:$env{'user.domain'}";
1.41      ng       3076: 	}
1.259     banghart 3077: 	# unless problem has been graded, set flag to version the submitted files
1.305     banghart 3078: 	unless ($record{'resource.'.$new_part.'.solved'} =~ /^correct_/  || 
                   3079: 	        $record{'resource.'.$new_part.'.solved'} eq 'incorrect_by_override' ||
                   3080: 	        $dropMenu eq 'reset status')
                   3081: 	   {
1.524     raeburn  3082: 	    push(@version_parts,$new_part);
1.259     banghart 3083: 	}
1.41      ng       3084:     }
1.301     albertel 3085:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   3086:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   3087: 
1.344     albertel 3088:     if (%newrecord) {
                   3089:         if (@version_parts) {
1.364     banghart 3090:             my @changed_keys = &version_portfiles(\%record, \@parts_graded, 
                   3091:                                 $env{'request.course.id'}, $symb, $domain, $stuname, \@version_parts);
1.344     albertel 3092: 	    @newrecord{@changed_keys} = @record{@changed_keys};
1.367     albertel 3093: 	    foreach my $new_part (@version_parts) {
                   3094: 		&handback_files($request,$symb,$stuname,$domain,$newflg,
                   3095: 				$new_part,\%newrecord);
                   3096: 	    }
1.259     banghart 3097:         }
1.44      ng       3098: 	&Apache::lonnet::cstore(\%newrecord,$symb,
1.257     albertel 3099: 				$env{'request.course.id'},$domain,$stuname);
1.380     albertel 3100: 	&check_and_remove_from_queue(\@parts,\%record,\%newrecord,$symb,
                   3101: 				     $cdom,$cnum,$domain,$stuname);
1.41      ng       3102:     }
1.269     raeburn  3103:     if ($aggregateflag) {
                   3104:         &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
1.301     albertel 3105: 			      $cdom,$cnum);
1.269     raeburn  3106:     }
1.301     albertel 3107:     return ('',$pts,$wgt);
1.36      ng       3108: }
1.322     albertel 3109: 
1.380     albertel 3110: sub check_and_remove_from_queue {
                   3111:     my ($parts,$record,$newrecord,$symb,$cdom,$cnum,$domain,$stuname) = @_;
                   3112:     my @ungraded_parts;
                   3113:     foreach my $part (@{$parts}) {
                   3114: 	if (    $record->{   'resource.'.$part.'.awarded'} eq ''
                   3115: 	     && $record->{   'resource.'.$part.'.solved' } ne 'excused'
                   3116: 	     && $newrecord->{'resource.'.$part.'.awarded'} eq ''
                   3117: 	     && $newrecord->{'resource.'.$part.'.solved' } ne 'excused'
                   3118: 		) {
                   3119: 	    push(@ungraded_parts, $part);
                   3120: 	}
                   3121:     }
                   3122:     if ( !@ungraded_parts ) {
                   3123: 	&Apache::bridgetask::remove_from_queue('gradingqueue',$symb,$cdom,
                   3124: 					       $cnum,$domain,$stuname);
                   3125:     }
                   3126: }
                   3127: 
1.337     banghart 3128: sub handback_files {
                   3129:     my ($request,$symb,$stuname,$domain,$newflg,$new_part,$newrecord) = @_;
1.517     raeburn  3130:     my $portfolio_root = '/userfiles/portfolio';
1.582     raeburn  3131:     my $res_error;
                   3132:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
                   3133:     if ($res_error) {
                   3134:         $request->print('<br />'.&navmap_errormsg().'<br />');
                   3135:         return;
                   3136:     }
1.654     raeburn  3137:     my @handedback;
                   3138:     my $file_msg;
1.375     albertel 3139:     my @part_response_id = &flatten_responseType($responseType);
                   3140:     foreach my $part_response_id (@part_response_id) {
                   3141:     	my ($part_id,$resp_id) = @{ $part_response_id };
                   3142: 	my $part_resp = join('_',@{ $part_response_id });
1.654     raeburn  3143:         if (($env{'form.'.$newflg.'_'.$part_resp.'_countreturndoc'} =~ /^\d+$/) & ($new_part eq $part_id)) {
                   3144:             for (my $counter=1; $counter<=$env{'form.'.$newflg.'_'.$part_resp.'_countreturndoc'}; $counter++) {
                   3145:                 # if multiple files are uploaded names will be 'returndoc2','returndoc3' 
                   3146:                 if ($env{'form.'.$newflg.'_'.$part_resp.'_returndoc'.$counter}) {
                   3147:                     my $fname=$env{'form.'.$newflg.'_'.$part_resp.'_returndoc'.$counter.'.filename'};
1.338     banghart 3148:                     my ($directory,$answer_file) = 
1.654     raeburn  3149:                         ($env{'form.'.$newflg.'_'.$part_resp.'_origdoc'.$counter} =~ /^(.*?)([^\/]*)$/);
1.338     banghart 3150:                     my ($answer_name,$answer_ver,$answer_ext) =
                   3151: 		        &file_name_version_ext($answer_file);
1.355     banghart 3152: 		    my ($portfolio_path) = ($directory =~ /^.+$stuname\/portfolio(.*)/);
1.517     raeburn  3153:                     my $getpropath = 1;
1.662     raeburn  3154:                     my ($dir_list,$listerror) = 
                   3155:                         &Apache::lonnet::dirlist($portfolio_root.$portfolio_path,
                   3156:                                                  $domain,$stuname,$getpropath);
                   3157: 		    my $version = &get_next_version($answer_name,$answer_ext,$dir_list);
1.686     bisitz   3158:                     # fix filename
1.355     banghart 3159:                     my ($save_file_name) = (($directory.$answer_name.".$version.".$answer_ext) =~ /^.+\/${stuname}\/(.*)/);
                   3160:                     my $result=&Apache::lonnet::finishuserfileupload($stuname,$domain,
1.654     raeburn  3161:             	                                $newflg.'_'.$part_resp.'_returndoc'.$counter,
1.355     banghart 3162:             	                                $save_file_name);
1.337     banghart 3163:                     if ($result !~ m|^/uploaded/|) {
1.536     raeburn  3164:                         $request->print('<br /><span class="LC_error">'.
                   3165:                             &mt('An error occurred ([_1]) while trying to upload [_2].',
1.654     raeburn  3166:                                 $result,$newflg.'_'.$part_resp.'_returndoc'.$counter).
1.536     raeburn  3167:                                         '</span>');
1.356     banghart 3168:                     } else {
1.360     banghart 3169:                         # mark the file as read only
1.654     raeburn  3170:                         push(@handedback,$save_file_name);
1.367     albertel 3171: 			if (exists($$newrecord{"resource.$new_part.$resp_id.handback"})) {
                   3172: 			    $$newrecord{"resource.$new_part.$resp_id.handback"}.=',';
                   3173: 			}
                   3174:                         $$newrecord{"resource.$new_part.$resp_id.handback"} .= $save_file_name;
1.654     raeburn  3175: 			$file_msg.= '<span class="LC_filename"><a href="/uploaded/'."$domain/$stuname/".$save_file_name.'">'.$save_file_name."</a></span> <br />";
1.337     banghart 3176:                     }
1.686     bisitz   3177:                     $request->print('<br />'.&mt('[_1] will be the uploaded filename [_2]','<span class="LC_info">'.$fname.'</span>','<span class="LC_filename">'.$env{'form.'.$newflg.'_'.$part_resp.'_origdoc'.$counter}.'</span>'));
1.337     banghart 3178:                 }
                   3179:             }
                   3180:         }
1.654     raeburn  3181:     }
                   3182:     if (@handedback > 0) {
                   3183:         $request->print('<br />');
                   3184:         my @what = ($symb,$env{'request.course.id'},'handback');
                   3185:         &Apache::lonnet::mark_as_readonly($domain,$stuname,\@handedback,\@what);
                   3186:         my $user_lh = &Apache::loncommon::user_lang($stuname,$domain,$env{'request.course.id'});    
                   3187:         my ($subject,$message);
                   3188:         if (scalar(@handedback) == 1) {
                   3189:             $subject = &mt_user($user_lh,'File Handed Back by Instructor');
                   3190:             $message = &mt_user($user_lh,'A file has been returned that was originally submitted in response to: ');
                   3191:         } else {
                   3192:             $subject = &mt_user($user_lh,'Files Handed Back by Instructor');
                   3193:             $message = &mt_user($user_lh,'Files have been returned that were originally submitted in response to: ');
                   3194:         }
                   3195:         $message .= "<p><strong>".&Apache::lonnet::gettitle($symb)." </strong></p>";
                   3196:         $message .= &mt_user($user_lh,'The returned file(s) are named: [_1]',"<br />$file_msg <br />").
                   3197:                     &mt_user($user_lh,'The file(s) can be found in your [_1]portfolio[_2].','<a href="/adm/portfolio">','</a>');
                   3198:         my ($feedurl,$showsymb) =
                   3199:             &get_feedurl_and_symb($symb,$domain,$stuname);
                   3200:         my $restitle = &Apache::lonnet::gettitle($symb);
                   3201:         $subject .= ' '.&mt_user($user_lh,'(File Returned)').' ['.$restitle.']';
                   3202:         my $msgstatus =
                   3203:              &Apache::lonmsg::user_normal_msg($stuname,$domain,$subject,
                   3204:                  $message,undef,$feedurl,undef,undef,undef,$showsymb,
                   3205:                  $restitle);
                   3206:         if ($msgstatus) {
                   3207:             $request->print(&mt('Notification message status: [_1]','<span class="LC_info">'.$msgstatus.'</span>').'<br />');
                   3208:         }
                   3209:     }
1.338     banghart 3210:     return;
1.337     banghart 3211: }
                   3212: 
1.418     albertel 3213: sub get_feedurl_and_symb {
                   3214:     my ($symb,$uname,$udom) = @_;
                   3215:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
                   3216:     $url = &Apache::lonnet::clutter($url);
                   3217:     my $encrypturl=&Apache::lonnet::EXT('resource.0.encrypturl',
                   3218: 					$symb,$udom,$uname);
                   3219:     if ($encrypturl =~ /^yes$/i) {
                   3220: 	&Apache::lonenc::encrypted(\$url,1);
                   3221: 	&Apache::lonenc::encrypted(\$symb,1);
                   3222:     }
                   3223:     return ($url,$symb);
                   3224: }
                   3225: 
1.313     banghart 3226: sub get_submitted_files {
                   3227:     my ($udom,$uname,$partid,$respid,$record) = @_;
                   3228:     my @files;
                   3229:     if ($$record{"resource.$partid.$respid.portfiles"}) {
                   3230:         my $file_url = '/uploaded/'.$udom.'/'.$uname.'/portfolio';
                   3231:         foreach my $file (split(',',$$record{"resource.$partid.$respid.portfiles"})) {
                   3232:     	    push(@files,$file_url.$file);
                   3233:         }
                   3234:     }
                   3235:     if ($$record{"resource.$partid.$respid.uploadedurl"}) {
                   3236:         push(@files,$$record{"resource.$partid.$respid.uploadedurl"});
                   3237:     }
                   3238:     return (\@files);
                   3239: }
1.322     albertel 3240: 
1.269     raeburn  3241: # ----------- Provides number of tries since last reset.
                   3242: sub get_num_tries {
                   3243:     my ($record,$last_reset,$part) = @_;
                   3244:     my $timestamp = '';
                   3245:     my $num_tries = 0;
                   3246:     if ($$record{'version'}) {
                   3247:         for (my $version=$$record{'version'};$version>=1;$version--) {
                   3248:             if (exists($$record{$version.':resource.'.$part.'.solved'})) {
                   3249:                 $timestamp = $$record{$version.':timestamp'};
                   3250:                 if ($timestamp > $last_reset) {
                   3251:                     $num_tries ++;
                   3252:                 } else {
                   3253:                     last;
                   3254:                 }
                   3255:             }
                   3256:         }
                   3257:     }
                   3258:     return $num_tries;
                   3259: }
                   3260: 
                   3261: # ----------- Determine decrements required in aggregate totals 
                   3262: sub decrement_aggs {
                   3263:     my ($symb,$part,$aggregate,$aggtries,$totaltries,$solvedstatus) = @_;
                   3264:     my %decrement = (
                   3265:                         attempts => 0,
                   3266:                         users => 0,
                   3267:                         correct => 0
                   3268:                     );
                   3269:     $decrement{'attempts'} = $aggtries;
                   3270:     if ($solvedstatus =~ /^correct/) {
                   3271:         $decrement{'correct'} = 1;
                   3272:     }
                   3273:     if ($aggtries == $totaltries) {
                   3274:         $decrement{'users'} = 1;
                   3275:     }
1.524     raeburn  3276:     foreach my $type (keys(%decrement)) {
1.269     raeburn  3277:         $$aggregate{$symb."\0".$part."\0".$type} = -$decrement{$type};
                   3278:     }
                   3279:     return;
                   3280: }
                   3281: 
                   3282: # ----------- Determine timestamps for last reset of aggregate totals for parts  
                   3283: sub get_last_resets {
1.270     albertel 3284:     my ($symb,$courseid,$partids) =@_;
                   3285:     my %last_resets;
1.269     raeburn  3286:     my $cdom = $env{'course.'.$courseid.'.domain'};
                   3287:     my $cname = $env{'course.'.$courseid.'.num'};
1.271     albertel 3288:     my @keys;
                   3289:     foreach my $part (@{$partids}) {
                   3290: 	push(@keys,"$symb\0$part\0resettime");
                   3291:     }
                   3292:     my %results=&Apache::lonnet::get('nohist_resourcetracker',\@keys,
                   3293: 				     $cdom,$cname);
                   3294:     foreach my $part (@{$partids}) {
                   3295: 	$last_resets{$part}=$results{"$symb\0$part\0resettime"};
1.269     raeburn  3296:     }
1.270     albertel 3297:     return %last_resets;
1.269     raeburn  3298: }
                   3299: 
1.251     banghart 3300: # ----------- Handles creating versions for portfolio files as answers
                   3301: sub version_portfiles {
1.343     banghart 3302:     my ($record, $parts_graded, $courseid, $symb, $domain, $stu_name, $v_flag) = @_;
1.263     banghart 3303:     my $version_parts = join('|',@$v_flag);
1.343     banghart 3304:     my @returned_keys;
1.255     banghart 3305:     my $parts = join('|', @$parts_graded);
1.517     raeburn  3306:     my $portfolio_root = '/userfiles/portfolio';
1.277     albertel 3307:     foreach my $key (keys(%$record)) {
1.259     banghart 3308:         my $new_portfiles;
1.263     banghart 3309:         if ($key =~ /^resource\.($version_parts)\./ && $key =~ /\.portfiles$/ ) {
1.342     banghart 3310:             my @versioned_portfiles;
1.367     albertel 3311:             my @portfiles = split(/\s*,\s*/,$$record{$key});
1.252     banghart 3312:             foreach my $file (@portfiles) {
1.306     banghart 3313:                 &Apache::lonnet::unmark_as_readonly($domain,$stu_name,[$symb,$env{'request.course.id'}],$file);
1.304     albertel 3314:                 my ($directory,$answer_file) =($file =~ /^(.*?)([^\/]*)$/);
                   3315: 		my ($answer_name,$answer_ver,$answer_ext) =
                   3316: 		    &file_name_version_ext($answer_file);
1.517     raeburn  3317:                 my $getpropath = 1;    
1.662     raeburn  3318:                 my ($dir_list,$listerror) = 
                   3319:                     &Apache::lonnet::dirlist($portfolio_root.$directory,$domain,
                   3320:                                              $stu_name,$getpropath);
                   3321:                 my $version = &get_next_version($answer_name,$answer_ext,$dir_list);
1.306     banghart 3322:                 my $new_answer = &version_selected_portfile($domain, $stu_name, $directory, $answer_file, $version);
                   3323:                 if ($new_answer ne 'problem getting file') {
1.342     banghart 3324:                     push(@versioned_portfiles, $directory.$new_answer);
1.306     banghart 3325:                     &Apache::lonnet::mark_as_readonly($domain,$stu_name,
1.367     albertel 3326:                         [$directory.$new_answer],
1.306     banghart 3327:                         [$symb,$env{'request.course.id'},'graded']);
1.259     banghart 3328:                 }
1.252     banghart 3329:             }
1.343     banghart 3330:             $$record{$key} = join(',',@versioned_portfiles);
                   3331:             push(@returned_keys,$key);
1.251     banghart 3332:         }
                   3333:     } 
1.343     banghart 3334:     return (@returned_keys);   
1.305     banghart 3335: }
                   3336: 
1.307     banghart 3337: sub get_next_version {
1.341     banghart 3338:     my ($answer_name, $answer_ext, $dir_list) = @_;
1.307     banghart 3339:     my $version;
1.662     raeburn  3340:     if (ref($dir_list) eq 'ARRAY') {
                   3341:         foreach my $row (@{$dir_list}) {
                   3342:             my ($file) = split(/\&/,$row,2);
                   3343:             my ($file_name,$file_version,$file_ext) =
                   3344: 	        &file_name_version_ext($file);
                   3345:             if (($file_name eq $answer_name) && 
                   3346: 	        ($file_ext eq $answer_ext)) {
                   3347:                      # gets here if filename and extension match, 
                   3348:                      # regardless of version
1.307     banghart 3349:                 if ($file_version ne '') {
1.662     raeburn  3350:                     # a versioned file is found  so save it for later
                   3351:                     if ($file_version > $version) {
                   3352: 		        $version = $file_version;
                   3353: 	            }
                   3354:                 }
1.307     banghart 3355:             }
                   3356:         }
1.662     raeburn  3357:     }
1.307     banghart 3358:     $version ++;
                   3359:     return($version);
                   3360: }
                   3361: 
1.305     banghart 3362: sub version_selected_portfile {
1.306     banghart 3363:     my ($domain,$stu_name,$directory,$file_name,$version) = @_;
                   3364:     my ($answer_name,$answer_ver,$answer_ext) =
                   3365:         &file_name_version_ext($file_name);
                   3366:     my $new_answer;
                   3367:     $env{'form.copy'} = &Apache::lonnet::getfile("/uploaded/$domain/$stu_name/portfolio$directory$file_name");
                   3368:     if($env{'form.copy'} eq '-1') {
                   3369:         $new_answer = 'problem getting file';
                   3370:     } else {
                   3371:         $new_answer = $answer_name.'.'.$version.'.'.$answer_ext;
                   3372:         my $copy_result = &Apache::lonnet::finishuserfileupload(
                   3373:                             $stu_name,$domain,'copy',
                   3374: 		        '/portfolio'.$directory.$new_answer);
                   3375:     }    
                   3376:     return ($new_answer);
1.251     banghart 3377: }
                   3378: 
1.304     albertel 3379: sub file_name_version_ext {
                   3380:     my ($file)=@_;
                   3381:     my @file_parts = split(/\./, $file);
                   3382:     my ($name,$version,$ext);
                   3383:     if (@file_parts > 1) {
                   3384: 	$ext=pop(@file_parts);
                   3385: 	if (@file_parts > 1 && $file_parts[-1] =~ /^\d+$/) {
                   3386: 	    $version=pop(@file_parts);
                   3387: 	}
                   3388: 	$name=join('.',@file_parts);
                   3389:     } else {
                   3390: 	$name=join('.',@file_parts);
                   3391:     }
                   3392:     return($name,$version,$ext);
                   3393: }
                   3394: 
1.44      ng       3395: #--------------------------------------------------------------------------------------
                   3396: #
                   3397: #-------------------------- Next few routines handles grading by section or whole class
                   3398: #
                   3399: #--- Javascript to handle grading by section or whole class
1.42      ng       3400: sub viewgrades_js {
                   3401:     my ($request) = shift;
                   3402: 
1.539     riegler  3403:     my $alertmsg = &mt('A number equal or greater than 0 is expected. Entered value = ');
1.597     wenzelju 3404:     $request->print(&Apache::lonhtmlcommon::scripttag(<<VIEWJAVASCRIPT));
1.45      ng       3405:    function writePoint(partid,weight,point) {
1.125     ng       3406: 	var radioButton = document.classgrade["RADVAL_"+partid];
                   3407: 	var textbox = document.classgrade["TEXTVAL_"+partid];
1.42      ng       3408: 	if (point == "textval") {
1.125     ng       3409: 	    point = document.classgrade["TEXTVAL_"+partid].value;
1.109     matthew  3410: 	    if (isNaN(point) || parseFloat(point) < 0) {
1.539     riegler  3411: 		alert("$alertmsg"+parseFloat(point));
1.42      ng       3412: 		var resetbox = false;
                   3413: 		for (var i=0; i<radioButton.length; i++) {
                   3414: 		    if (radioButton[i].checked) {
                   3415: 			textbox.value = i;
                   3416: 			resetbox = true;
                   3417: 		    }
                   3418: 		}
                   3419: 		if (!resetbox) {
                   3420: 		    textbox.value = "";
                   3421: 		}
                   3422: 		return;
                   3423: 	    }
1.109     matthew  3424: 	    if (parseFloat(point) > parseFloat(weight)) {
                   3425: 		var resp = confirm("You entered a value ("+parseFloat(point)+
1.44      ng       3426: 				   ") greater than the weight for the part. Accept?");
                   3427: 		if (resp == false) {
                   3428: 		    textbox.value = "";
                   3429: 		    return;
                   3430: 		}
                   3431: 	    }
1.42      ng       3432: 	    for (var i=0; i<radioButton.length; i++) {
                   3433: 		radioButton[i].checked=false;
1.109     matthew  3434: 		if (parseFloat(point) == i) {
1.42      ng       3435: 		    radioButton[i].checked=true;
                   3436: 		}
                   3437: 	    }
1.41      ng       3438: 
1.42      ng       3439: 	} else {
1.125     ng       3440: 	    textbox.value = parseFloat(point);
1.42      ng       3441: 	}
1.41      ng       3442: 	for (i=0;i<document.classgrade.total.value;i++) {
1.125     ng       3443: 	    var user = document.classgrade["ctr"+i].value;
1.289     albertel 3444: 	    user = user.replace(new RegExp(':', 'g'),"_");
1.125     ng       3445: 	    var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
                   3446: 	    var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
                   3447: 	    var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
1.42      ng       3448: 	    if (saveval != "correct") {
                   3449: 		scorename.value = point;
1.43      ng       3450: 		if (selname[0].selected != true) {
                   3451: 		    selname[0].selected = true;
                   3452: 		}
1.42      ng       3453: 	    }
                   3454: 	}
1.125     ng       3455: 	document.classgrade["SELVAL_"+partid][0].selected = true;
1.42      ng       3456:     }
                   3457: 
                   3458:     function writeRadText(partid,weight) {
1.125     ng       3459: 	var selval   = document.classgrade["SELVAL_"+partid];
                   3460: 	var radioButton = document.classgrade["RADVAL_"+partid];
1.265     www      3461:         var override = document.classgrade["FORCE_"+partid].checked;
1.125     ng       3462: 	var textbox = document.classgrade["TEXTVAL_"+partid];
                   3463: 	if (selval[1].selected || selval[2].selected) {
1.42      ng       3464: 	    for (var i=0; i<radioButton.length; i++) {
                   3465: 		radioButton[i].checked=false;
                   3466: 
                   3467: 	    }
                   3468: 	    textbox.value = "";
                   3469: 
                   3470: 	    for (i=0;i<document.classgrade.total.value;i++) {
1.125     ng       3471: 		var user = document.classgrade["ctr"+i].value;
1.289     albertel 3472: 		user = user.replace(new RegExp(':', 'g'),"_");
1.125     ng       3473: 		var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
                   3474: 		var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
                   3475: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
1.265     www      3476: 		if ((saveval != "correct") || override) {
1.42      ng       3477: 		    scorename.value = "";
1.125     ng       3478: 		    if (selval[1].selected) {
                   3479: 			selname[1].selected = true;
                   3480: 		    } else {
                   3481: 			selname[2].selected = true;
                   3482: 			if (Number(document.classgrade["GD_"+user+"_"+partid+"_tries"].value)) 
                   3483: 			{document.classgrade["GD_"+user+"_"+partid+"_tries"].value = '0';}
                   3484: 		    }
1.42      ng       3485: 		}
                   3486: 	    }
1.43      ng       3487: 	} else {
                   3488: 	    for (i=0;i<document.classgrade.total.value;i++) {
1.125     ng       3489: 		var user = document.classgrade["ctr"+i].value;
1.289     albertel 3490: 		user = user.replace(new RegExp(':', 'g'),"_");
1.125     ng       3491: 		var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
                   3492: 		var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
                   3493: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
1.265     www      3494: 		if ((saveval != "correct") || override) {
1.125     ng       3495: 		    scorename.value = document.classgrade["GD_"+user+"_"+partid+"_awarded_s"].value;
1.43      ng       3496: 		    selname[0].selected = true;
                   3497: 		}
                   3498: 	    }
                   3499: 	}	    
1.42      ng       3500:     }
                   3501: 
                   3502:     function changeSelect(partid,user) {
1.125     ng       3503: 	var selval = document.classgrade["GD_"+user+'_'+partid+"_solved"];
                   3504: 	var textbox = document.classgrade["GD_"+user+'_'+partid+"_awarded"];
1.44      ng       3505: 	var point  = textbox.value;
1.125     ng       3506: 	var weight = document.classgrade["weight_"+partid].value;
1.44      ng       3507: 
1.109     matthew  3508: 	if (isNaN(point) || parseFloat(point) < 0) {
1.539     riegler  3509: 	    alert("$alertmsg"+parseFloat(point));
1.44      ng       3510: 	    textbox.value = "";
                   3511: 	    return;
                   3512: 	}
1.109     matthew  3513: 	if (parseFloat(point) > parseFloat(weight)) {
                   3514: 	    var resp = confirm("You entered a value ("+parseFloat(point)+
1.44      ng       3515: 			       ") greater than the weight of the part. Accept?");
                   3516: 	    if (resp == false) {
                   3517: 		textbox.value = "";
                   3518: 		return;
                   3519: 	    }
                   3520: 	}
1.42      ng       3521: 	selval[0].selected = true;
                   3522:     }
                   3523: 
                   3524:     function changeOneScore(partid,user) {
1.125     ng       3525: 	var selval = document.classgrade["GD_"+user+'_'+partid+"_solved"];
                   3526: 	if (selval[1].selected || selval[2].selected) {
                   3527: 	    document.classgrade["GD_"+user+'_'+partid+"_awarded"].value = "";
                   3528: 	    if (selval[2].selected) {
                   3529: 		document.classgrade["GD_"+user+'_'+partid+"_tries"].value = "0";
                   3530: 	    }
1.269     raeburn  3531:         }
1.42      ng       3532:     }
                   3533: 
                   3534:     function resetEntry(numpart) {
                   3535: 	for (ctpart=0;ctpart<numpart;ctpart++) {
1.125     ng       3536: 	    var partid = document.classgrade["partid_"+ctpart].value;
                   3537: 	    var radioButton = document.classgrade["RADVAL_"+partid];
                   3538: 	    var textbox = document.classgrade["TEXTVAL_"+partid];
                   3539: 	    var selval  = document.classgrade["SELVAL_"+partid];
1.42      ng       3540: 	    for (var i=0; i<radioButton.length; i++) {
                   3541: 		radioButton[i].checked=false;
                   3542: 
                   3543: 	    }
                   3544: 	    textbox.value = "";
                   3545: 	    selval[0].selected = true;
                   3546: 
                   3547: 	    for (i=0;i<document.classgrade.total.value;i++) {
1.125     ng       3548: 		var user = document.classgrade["ctr"+i].value;
1.289     albertel 3549: 		user = user.replace(new RegExp(':', 'g'),"_");
1.125     ng       3550: 		var resetscore = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
                   3551: 		resetscore.value = document.classgrade["GD_"+user+"_"+partid+"_awarded_s"].value;
                   3552: 		var resettries = document.classgrade["GD_"+user+"_"+partid+"_tries"];
                   3553: 		resettries.value = document.classgrade["GD_"+user+"_"+partid+"_tries_s"].value;
                   3554: 		var saveselval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
                   3555: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
1.42      ng       3556: 		if (saveselval == "excused") {
1.43      ng       3557: 		    if (selname[1].selected == false) { selname[1].selected = true;}
1.42      ng       3558: 		} else {
1.43      ng       3559: 		    if (selname[0].selected == false) {selname[0].selected = true};
1.42      ng       3560: 		}
                   3561: 	    }
1.41      ng       3562: 	}
1.42      ng       3563:     }
                   3564: 
1.41      ng       3565: VIEWJAVASCRIPT
1.42      ng       3566: }
                   3567: 
1.44      ng       3568: #--- show scores for a section or whole class w/ option to change/update a score
1.42      ng       3569: sub viewgrades {
1.608     www      3570:     my ($request,$symb) = @_;
1.42      ng       3571:     &viewgrades_js($request);
1.41      ng       3572: 
1.168     albertel 3573:     #need to make sure we have the correct data for later EXT calls, 
                   3574:     #thus invalidate the cache
                   3575:     &Apache::lonnet::devalidatecourseresdata(
1.257     albertel 3576:                  $env{'course.'.$env{'request.course.id'}.'.num'},
                   3577:                  $env{'course.'.$env{'request.course.id'}.'.domain'});
1.168     albertel 3578:     &Apache::lonnet::clear_EXT_cache_status();
                   3579: 
1.398     albertel 3580:     my $result='<h3><span class="LC_info">'.&mt('Manual Grading').'</span></h3>';
1.41      ng       3581: 
                   3582:     #view individual student submission form - called using Javascript viewOneStudent
1.324     albertel 3583:     $result.=&jscriptNform($symb);
1.41      ng       3584: 
1.44      ng       3585:     #beginning of class grading form
1.442     banghart 3586:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
1.41      ng       3587:     $result.= '<form action="/adm/grades" method="post" name="classgrade">'."\n".
1.418     albertel 3588: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.38      ng       3589: 	'<input type="hidden" name="command" value="editgrades" />'."\n".
1.432     banghart 3590: 	&build_section_inputs().
1.442     banghart 3591: 	'<input type="hidden" name="Status" value="'.$env{'stu_status'}.'" />'."\n".
1.72      ng       3592: 
1.560     raeburn  3593:     my ($common_header,$specific_header);
1.257     albertel 3594:     if ($env{'form.section'} eq 'all') {
1.560     raeburn  3595: 	$common_header = &mt('Assign Common Grade to Class');
                   3596:         $specific_header = &mt('Assign Grade to Specific Students in Class');
1.257     albertel 3597:     } elsif ($env{'form.section'} eq 'none') {
1.560     raeburn  3598:         $common_header = &mt('Assign Common Grade to Students in no Section');
                   3599: 	$specific_header = &mt('Assign Grade to Specific Students in no Section');
1.52      albertel 3600:     } else {
1.560     raeburn  3601:         my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
                   3602:         $common_header = &mt('Assign Common Grade to Students in Section(s) [_1]',$section_display);
                   3603: 	$specific_header = &mt('Assign Grade to Specific Students in Section(s) [_1]',$section_display);
1.52      albertel 3604:     }
1.560     raeburn  3605:     $result.= '<h3>'.$common_header.'</h3>'.&Apache::loncommon::start_data_table();
1.44      ng       3606:     #radio buttons/text box for assigning points for a section or class.
                   3607:     #handles different parts of a problem
1.582     raeburn  3608:     my $res_error;
                   3609:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
                   3610:     if ($res_error) {
                   3611:         return &navmap_errormsg();
                   3612:     }
1.42      ng       3613:     my %weight = ();
                   3614:     my $ctsparts = 0;
1.45      ng       3615:     my %seen = ();
1.375     albertel 3616:     my @part_response_id = &flatten_responseType($responseType);
                   3617:     foreach my $part_response_id (@part_response_id) {
                   3618:     	my ($partid,$respid) = @{ $part_response_id };
                   3619: 	my $part_resp = join('_',@{ $part_response_id });
1.45      ng       3620: 	next if $seen{$partid};
                   3621: 	$seen{$partid}++;
1.375     albertel 3622: 	my $handgrade=$$handgrade{$part_resp};
1.42      ng       3623: 	my $wgt = &Apache::lonnet::EXT('resource.'.$partid.'.weight',$symb);
                   3624: 	$weight{$partid} = $wgt eq '' ? '1' : $wgt;
                   3625: 
1.324     albertel 3626: 	my $display_part=&get_display_part($partid,$symb);
1.485     albertel 3627: 	my $radio.='<table border="0"><tr>';  
1.41      ng       3628: 	my $ctr = 0;
1.42      ng       3629: 	while ($ctr<=$weight{$partid}) { # display radio buttons in a nice table 10 across
1.485     albertel 3630: 	    $radio.= '<td><label><input type="radio" name="RADVAL_'.$partid.'" '.
1.54      albertel 3631: 		'onclick="javascript:writePoint(\''.$partid.'\','.$weight{$partid}.
1.288     albertel 3632: 		','.$ctr.')" />'.$ctr."</label></td>\n";
1.41      ng       3633: 	    $result.=(($ctr+1)%10 == 0 ? '</tr><tr>' : '');
                   3634: 	    $ctr++;
                   3635: 	}
1.485     albertel 3636: 	$radio.='</tr></table>';
                   3637: 	my $line = '<input type="text" name="TEXTVAL_'.
1.589     bisitz   3638: 	    $partid.'" size="4" '.'onchange="javascript:writePoint(\''.
1.54      albertel 3639: 		$partid.'\','.$weight{$partid}.',\'textval\')" /> /'.
1.539     riegler  3640: 	    $weight{$partid}.' '.&mt('(problem weight)').'</td>'."\n";
1.701     bisitz   3641:         $line.= '<td><b>'.&mt('Grade Status').':</b>'.
                   3642:             '<select name="SELVAL_'.$partid.'" '.
                   3643:             'onchange="javascript:writeRadText(\''.$partid.'\','.
                   3644:                 $weight{$partid}.')"> '.
1.401     albertel 3645: 	    '<option selected="selected"> </option>'.
1.485     albertel 3646: 	    '<option value="excused">'.&mt('excused').'</option>'.
                   3647: 	    '<option value="reset status">'.&mt('reset status').'</option>'.
                   3648: 	    '</select></td>'.
                   3649:             '<td><label><input type="checkbox" name="FORCE_'.$partid.'" />'.&mt('Override "Correct"').'</label>';
                   3650: 	$line.='<input type="hidden" name="partid_'.
                   3651: 	    $ctsparts.'" value="'.$partid.'" />'."\n";
                   3652: 	$line.='<input type="hidden" name="weight_'.
                   3653: 	    $partid.'" value="'.$weight{$partid}.'" />'."\n";
                   3654: 
                   3655: 	$result.=
                   3656: 	    &Apache::loncommon::start_data_table_row()."\n".
1.577     bisitz   3657: 	    '<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 3658: 	    &Apache::loncommon::end_data_table_row()."\n";
1.42      ng       3659: 	$ctsparts++;
1.41      ng       3660:     }
1.474     albertel 3661:     $result.=&Apache::loncommon::end_data_table()."\n".
1.52      albertel 3662: 	'<input type="hidden" name="totalparts" value="'.$ctsparts.'" />';
1.485     albertel 3663:     $result.='<input type="button" value="'.&mt('Revert to Default').'" '.
1.589     bisitz   3664: 	'onclick="javascript:resetEntry('.$ctsparts.');" />';
1.41      ng       3665: 
1.44      ng       3666:     #table listing all the students in a section/class
                   3667:     #header of table
1.560     raeburn  3668:     $result.= '<h3>'.$specific_header.'</h3>'.
                   3669:               &Apache::loncommon::start_data_table().
                   3670: 	      &Apache::loncommon::start_data_table_header_row().
                   3671: 	      '<th>'.&mt('No.').'</th>'.
                   3672: 	      '<th>'.&nameUserString('header')."</th>\n";
1.582     raeburn  3673:     my $partserror;
                   3674:     my (@parts) = sort(&getpartlist($symb,\$partserror));
                   3675:     if ($partserror) {
                   3676:         return &navmap_errormsg();
                   3677:     }
1.324     albertel 3678:     my (undef,undef,$url)=&Apache::lonnet::decode_symb($symb);
1.269     raeburn  3679:     my @partids = ();
1.41      ng       3680:     foreach my $part (@parts) {
                   3681: 	my $display=&Apache::lonnet::metadata($url,$part.'.display');
1.539     riegler  3682:         my $narrowtext = &mt('Tries');
                   3683: 	$display =~ s|^Number of Attempts|$narrowtext <br />|; # makes the column narrower
1.41      ng       3684: 	if  (!$display) { $display = &Apache::lonnet::metadata($url,$part.'.name'); }
1.207     albertel 3685: 	my ($partid) = &split_part_type($part);
1.524     raeburn  3686:         push(@partids,$partid);
1.628     www      3687: #
                   3688: # FIXME: Looks like $display looks at English text
                   3689: #
1.324     albertel 3690: 	my $display_part=&get_display_part($partid,$symb);
1.41      ng       3691: 	if ($display =~ /^Partial Credit Factor/) {
1.485     albertel 3692: 	    $result.='<th>'.
1.697     bisitz   3693: 		&mt('Score Part: [_1][_2](weight = [_3])',
                   3694: 		    $display_part,'<br />',$weight{$partid}).'</th>'."\n";
1.41      ng       3695: 	    next;
1.485     albertel 3696: 	    
1.207     albertel 3697: 	} else {
1.485     albertel 3698: 	    if ($display =~ /Problem Status/) {
                   3699: 		my $grade_status_mt = &mt('Grade Status');
                   3700: 		$display =~ s{Problem Status}{$grade_status_mt<br />};
                   3701: 	    }
                   3702: 	    my $part_mt = &mt('Part:');
                   3703: 	    $display =~s{\[Part: \Q$partid\E\]}{$part_mt $display_part};
1.41      ng       3704: 	}
1.485     albertel 3705: 
1.474     albertel 3706: 	$result.='<th>'.$display.'</th>'."\n";
1.41      ng       3707:     }
1.474     albertel 3708:     $result.=&Apache::loncommon::end_data_table_header_row();
1.44      ng       3709: 
1.270     albertel 3710:     my %last_resets = 
                   3711: 	&get_last_resets($symb,$env{'request.course.id'},\@partids);
1.269     raeburn  3712: 
1.41      ng       3713:     #get info for each student
1.44      ng       3714:     #list all the students - with points and grade status
1.257     albertel 3715:     my (undef,undef,$fullname) = &getclasslist($env{'form.section'},'1');
1.41      ng       3716:     my $ctr = 0;
1.294     albertel 3717:     foreach (sort 
                   3718: 	     {
                   3719: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                   3720: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                   3721: 		 }
                   3722: 		 return $a cmp $b;
                   3723: 	     } (keys(%$fullname))) {
1.126     ng       3724: 	$ctr++;
1.324     albertel 3725: 	$result.=&viewstudentgrade($symb,$env{'request.course.id'},
1.269     raeburn  3726: 				   $_,$$fullname{$_},\@parts,\%weight,$ctr,\%last_resets);
1.41      ng       3727:     }
1.474     albertel 3728:     $result.=&Apache::loncommon::end_data_table();
1.41      ng       3729:     $result.='<input type="hidden" name="total" value="'.$ctr.'" />'."\n";
1.485     albertel 3730:     $result.='<input type="button" value="'.&mt('Save').'" '.
1.589     bisitz   3731: 	'onclick="javascript:submit();" target="_self" /></form>'."\n";
1.96      albertel 3732:     if (scalar(%$fullname) eq 0) {
                   3733: 	my $colspan=3+scalar(@parts);
1.433     banghart 3734: 	my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
1.442     banghart 3735:         my $stu_status = join(' or ',&Apache::loncommon::get_env_multiple('form.Status'));
1.433     banghart 3736: 	$result='<span class="LC_warning">'.
1.485     albertel 3737: 	    &mt('There are no students in section(s) [_1] with enrollment status [_2] to modify or grade.',
1.442     banghart 3738: 	        $section_display, $stu_status).
1.433     banghart 3739: 	    '</span>';
1.96      albertel 3740:     }
1.41      ng       3741:     return $result;
                   3742: }
                   3743: 
1.44      ng       3744: #--- call by previous routine to display each student
1.41      ng       3745: sub viewstudentgrade {
1.324     albertel 3746:     my ($symb,$courseid,$student,$fullname,$parts,$weight,$ctr,$last_resets) = @_;
1.44      ng       3747:     my ($uname,$udom) = split(/:/,$student);
                   3748:     my %record=&Apache::lonnet::restore($symb,$courseid,$udom,$uname);
1.269     raeburn  3749:     my %aggregates = (); 
1.474     albertel 3750:     my $result=&Apache::loncommon::start_data_table_row().'<td align="right">'.
1.233     albertel 3751: 	'<input type="hidden" name="ctr'.($ctr-1).'" value="'.$student.'" />'.
                   3752: 	"\n".$ctr.'&nbsp;</td><td>&nbsp;'.
1.44      ng       3753: 	'<a href="javascript:viewOneStudent(\''.$uname.'\',\''.$udom.
1.417     albertel 3754: 	'\');" target="_self">'.$fullname.'</a> '.
1.398     albertel 3755: 	'<span class="LC_internal_info">('.$uname.($env{'user.domain'} eq $udom ? '' : ':'.$udom).')</span></td>'."\n";
1.281     albertel 3756:     $student=~s/:/_/; # colon doen't work in javascript for names
1.63      albertel 3757:     foreach my $apart (@$parts) {
                   3758: 	my ($part,$type) = &split_part_type($apart);
1.41      ng       3759: 	my $score=$record{"resource.$part.$type"};
1.276     albertel 3760:         $result.='<td align="center">';
1.269     raeburn  3761:         my ($aggtries,$totaltries);
                   3762:         unless (exists($aggregates{$part})) {
1.270     albertel 3763: 	    $totaltries = $record{'resource.'.$part.'.tries'};
                   3764: 
                   3765: 	    $aggtries = $totaltries;
1.269     raeburn  3766:             if ($$last_resets{$part}) {  
1.270     albertel 3767:                 $aggtries = &get_num_tries(\%record,$$last_resets{$part},
                   3768: 					   $part);
                   3769:             }
1.269     raeburn  3770:             $result.='<input type="hidden" name="'.
                   3771:                 'GD_'.$student.'_'.$part.'_aggtries" value="'.$aggtries.'" />'."\n";
                   3772:             $result.='<input type="hidden" name="'.
                   3773:                 'GD_'.$student.'_'.$part.'_totaltries" value="'.$totaltries.'" />'."\n";
                   3774:             $aggregates{$part} = 1;
                   3775:         }
1.41      ng       3776: 	if ($type eq 'awarded') {
1.320     albertel 3777: 	    my $pts = $score eq '' ? '' : &compute_points($score,$$weight{$part});
1.42      ng       3778: 	    $result.='<input type="hidden" name="'.
1.89      albertel 3779: 		'GD_'.$student.'_'.$part.'_awarded_s" value="'.$pts.'" />'."\n";
1.233     albertel 3780: 	    $result.='<input type="text" name="'.
1.89      albertel 3781: 		'GD_'.$student.'_'.$part.'_awarded" '.
1.589     bisitz   3782:                 'onchange="javascript:changeSelect(\''.$part.'\',\''.$student.
1.44      ng       3783: 		'\')" value="'.$pts.'" size="4" /></td>'."\n";
1.41      ng       3784: 	} elsif ($type eq 'solved') {
                   3785: 	    my ($status,$foo)=split(/_/,$score,2);
                   3786: 	    $status = 'nothing' if ($status eq '');
1.89      albertel 3787: 	    $result.='<input type="hidden" name="'.'GD_'.$student.'_'.
1.54      albertel 3788: 		$part.'_solved_s" value="'.$status.'" />'."\n";
1.233     albertel 3789: 	    $result.='&nbsp;<select name="'.
1.89      albertel 3790: 		'GD_'.$student.'_'.$part.'_solved" '.
1.589     bisitz   3791:                 'onchange="javascript:changeOneScore(\''.$part.'\',\''.$student.'\')" >'."\n";
1.485     albertel 3792: 	    $result.= (($status eq 'excused') ? '<option> </option><option selected="selected" value="excused">'.&mt('excused').'</option>' 
                   3793: 		: '<option selected="selected"> </option><option value="excused">'.&mt('excused').'</option>')."\n";
                   3794: 	    $result.='<option value="reset status">'.&mt('reset status').'</option>';
1.126     ng       3795: 	    $result.="</select>&nbsp;</td>\n";
1.122     ng       3796: 	} else {
                   3797: 	    $result.='<input type="hidden" name="'.
                   3798: 		'GD_'.$student.'_'.$part.'_'.$type.'_s" value="'.$score.'" />'.
                   3799: 		    "\n";
1.233     albertel 3800: 	    $result.='<input type="text" name="'.
1.122     ng       3801: 		'GD_'.$student.'_'.$part.'_'.$type.'" '.
                   3802: 		'value="'.$score.'" size="4" /></td>'."\n";
1.41      ng       3803: 	}
                   3804:     }
1.474     albertel 3805:     $result.=&Apache::loncommon::end_data_table_row();
1.41      ng       3806:     return $result;
1.38      ng       3807: }
                   3808: 
1.44      ng       3809: #--- change scores for all the students in a section/class
                   3810: #    record does not get update if unchanged
1.38      ng       3811: sub editgrades {
1.608     www      3812:     my ($request,$symb) = @_;
1.41      ng       3813: 
1.433     banghart 3814:     my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
1.477     albertel 3815:     my $title='<h2>'.&mt('Current Grade Status').'</h2>';
1.433     banghart 3816:     $title.='<h4>'.&mt('<b>Section: </b>[_1]',$section_display).'</h4>'."\n";
1.126     ng       3817: 
1.477     albertel 3818:     my $result= &Apache::loncommon::start_data_table().
                   3819: 	&Apache::loncommon::start_data_table_header_row().
                   3820: 	'<th rowspan="2" valign="middle">'.&mt('No.').'</th>'.
                   3821: 	'<th rowspan="2" valign="middle">'.&nameUserString('header')."</th>\n";
1.43      ng       3822:     my %scoreptr = (
                   3823: 		    'correct'  =>'correct_by_override',
                   3824: 		    'incorrect'=>'incorrect_by_override',
                   3825: 		    'excused'  =>'excused',
                   3826: 		    'ungraded' =>'ungraded_attempted',
1.596     raeburn  3827:                     'credited' =>'credit_attempted',
1.43      ng       3828: 		    'nothing'  => '',
                   3829: 		    );
1.257     albertel 3830:     my ($classlist,undef,$fullname) = &getclasslist($env{'form.section'},'0');
1.34      ng       3831: 
1.44      ng       3832:     my (@partid);
                   3833:     my %weight = ();
1.54      albertel 3834:     my %columns = ();
1.44      ng       3835:     my ($i,$ctr,$count,$rec_update) = (0,0,0,0);
1.54      albertel 3836: 
1.582     raeburn  3837:     my $partserror;
                   3838:     my (@parts) = sort(&getpartlist($symb,\$partserror));
                   3839:     if ($partserror) {
                   3840:         return &navmap_errormsg();
                   3841:     }
1.54      albertel 3842:     my $header;
1.257     albertel 3843:     while ($ctr < $env{'form.totalparts'}) {
                   3844: 	my $partid = $env{'form.partid_'.$ctr};
1.524     raeburn  3845: 	push(@partid,$partid);
1.257     albertel 3846: 	$weight{$partid} = $env{'form.weight_'.$partid};
1.44      ng       3847: 	$ctr++;
1.54      albertel 3848:     }
1.324     albertel 3849:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
1.54      albertel 3850:     foreach my $partid (@partid) {
1.478     albertel 3851: 	$header .= '<th align="center">'.&mt('Old Score').'</th>'.
                   3852: 	    '<th align="center">'.&mt('New Score').'</th>';
1.54      albertel 3853: 	$columns{$partid}=2;
                   3854: 	foreach my $stores (@parts) {
                   3855: 	    my ($part,$type) = &split_part_type($stores);
                   3856: 	    if ($part !~ m/^\Q$partid\E/) { next;}
                   3857: 	    if ($type eq 'awarded' || $type eq 'solved') { next; }
                   3858: 	    my $display=&Apache::lonnet::metadata($url,$stores.'.display');
1.551     raeburn  3859: 	    $display =~ s/\[Part: \Q$part\E\]//;
1.539     riegler  3860:             my $narrowtext = &mt('Tries');
                   3861: 	    $display =~ s/Number of Attempts/$narrowtext/;
                   3862: 	    $header .= '<th align="center">'.&mt('Old').' '.$display.'</th>'.
                   3863: 		'<th align="center">'.&mt('New').' '.$display.'</th>';
1.54      albertel 3864: 	    $columns{$partid}+=2;
                   3865: 	}
                   3866:     }
                   3867:     foreach my $partid (@partid) {
1.324     albertel 3868: 	my $display_part=&get_display_part($partid,$symb);
1.478     albertel 3869: 	$result .= '<th colspan="'.$columns{$partid}.'" align="center">'.
                   3870: 	    &mt('Part: [_1] (Weight = [_2])',$display_part,$weight{$partid}).
                   3871: 	    '</th>';
1.54      albertel 3872: 
1.44      ng       3873:     }
1.477     albertel 3874:     $result .= &Apache::loncommon::end_data_table_header_row().
                   3875: 	&Apache::loncommon::start_data_table_header_row().
                   3876: 	$header.
                   3877: 	&Apache::loncommon::end_data_table_header_row();
                   3878:     my @noupdate;
1.126     ng       3879:     my ($updateCtr,$noupdateCtr) = (1,1);
1.257     albertel 3880:     for ($i=0; $i<$env{'form.total'}; $i++) {
1.93      albertel 3881: 	my $line;
1.257     albertel 3882: 	my $user = $env{'form.ctr'.$i};
1.281     albertel 3883: 	my ($uname,$udom)=split(/:/,$user);
1.44      ng       3884: 	my %newrecord;
                   3885: 	my $updateflag = 0;
1.281     albertel 3886: 	$line .= '<td>'.&nameUserString(undef,$$fullname{$user},$uname,$udom).'</td>';
1.108     albertel 3887: 	my $usec=$classlist->{"$uname:$udom"}[5];
1.105     albertel 3888: 	if (!&canmodify($usec)) {
1.126     ng       3889: 	    my $numcols=scalar(@partid)*4+2;
1.477     albertel 3890: 	    push(@noupdate,
1.478     albertel 3891: 		 $line."<td colspan=\"$numcols\"><span class=\"LC_warning\">".
                   3892: 		 &mt('Not allowed to modify student')."</span></td></tr>");
1.105     albertel 3893: 	    next;
                   3894: 	}
1.269     raeburn  3895:         my %aggregate = ();
                   3896:         my $aggregateflag = 0;
1.281     albertel 3897: 	$user=~s/:/_/; # colon doen't work in javascript for names
1.44      ng       3898: 	foreach (@partid) {
1.257     albertel 3899: 	    my $old_aw    = $env{'form.GD_'.$user.'_'.$_.'_awarded_s'};
1.54      albertel 3900: 	    my $old_part_pcr = $old_aw/($weight{$_} ne '0' ? $weight{$_}:1);
                   3901: 	    my $old_part  = $old_aw eq '' ? '' : $old_part_pcr;
1.257     albertel 3902: 	    my $old_score = $scoreptr{$env{'form.GD_'.$user.'_'.$_.'_solved_s'}};
                   3903: 	    my $awarded   = $env{'form.GD_'.$user.'_'.$_.'_awarded'};
1.54      albertel 3904: 	    my $pcr       = $awarded/($weight{$_} ne '0' ? $weight{$_} : 1);
                   3905: 	    my $partial   = $awarded eq '' ? '' : $pcr;
1.44      ng       3906: 	    my $score;
                   3907: 	    if ($partial eq '') {
1.257     albertel 3908: 		$score = $scoreptr{$env{'form.GD_'.$user.'_'.$_.'_solved_s'}};
1.44      ng       3909: 	    } elsif ($partial > 0) {
                   3910: 		$score = 'correct_by_override';
                   3911: 	    } elsif ($partial == 0) {
                   3912: 		$score = 'incorrect_by_override';
                   3913: 	    }
1.257     albertel 3914: 	    my $dropMenu = $env{'form.GD_'.$user.'_'.$_.'_solved'};
1.125     ng       3915: 	    $score = 'excused' if (($dropMenu eq 'excused') && ($score ne 'excused'));
                   3916: 
1.292     albertel 3917: 	    $newrecord{'resource.'.$_.'.regrader'}=
                   3918: 		"$env{'user.name'}:$env{'user.domain'}";
1.125     ng       3919: 	    if ($dropMenu eq 'reset status' &&
                   3920: 		$old_score ne '') { # ignore if no previous attempts => nothing to reset
1.299     albertel 3921: 		$newrecord{'resource.'.$_.'.tries'} = '';
1.125     ng       3922: 		$newrecord{'resource.'.$_.'.solved'} = '';
                   3923: 		$newrecord{'resource.'.$_.'.award'} = '';
1.299     albertel 3924: 		$newrecord{'resource.'.$_.'.awarded'} = '';
1.125     ng       3925: 		$updateflag = 1;
1.269     raeburn  3926:                 if ($env{'form.GD_'.$user.'_'.$_.'_aggtries'} > 0) {
                   3927:                     my $aggtries = $env{'form.GD_'.$user.'_'.$_.'_aggtries'};
                   3928:                     my $totaltries = $env{'form.GD_'.$user.'_'.$_.'_totaltries'};
                   3929:                     my $solvedstatus = $env{'form.GD_'.$user.'_'.$_.'_solved_s'};
                   3930:                     &decrement_aggs($symb,$_,\%aggregate,$aggtries,$totaltries,$solvedstatus);
                   3931:                     $aggregateflag = 1;
                   3932:                 }
1.139     albertel 3933: 	    } elsif (!($old_part eq $partial && $old_score eq $score)) {
                   3934: 		$updateflag = 1;
                   3935: 		$newrecord{'resource.'.$_.'.awarded'}  = $partial if $partial ne '';
                   3936: 		$newrecord{'resource.'.$_.'.solved'}   = $score;
                   3937: 		$rec_update++;
1.125     ng       3938: 	    }
                   3939: 
1.93      albertel 3940: 	    $line .= '<td align="center">'.$old_aw.'&nbsp;</td>'.
1.44      ng       3941: 		'<td align="center">'.$awarded.
                   3942: 		($score eq 'excused' ? $score : '').'&nbsp;</td>';
1.5       albertel 3943: 
1.54      albertel 3944: 
                   3945: 	    my $partid=$_;
                   3946: 	    foreach my $stores (@parts) {
                   3947: 		my ($part,$type) = &split_part_type($stores);
                   3948: 		if ($part !~ m/^\Q$partid\E/) { next;}
                   3949: 		if ($type eq 'awarded' || $type eq 'solved') { next; }
1.257     albertel 3950: 		my $old_aw    = $env{'form.GD_'.$user.'_'.$part.'_'.$type.'_s'};
                   3951: 		my $awarded   = $env{'form.GD_'.$user.'_'.$part.'_'.$type};
1.54      albertel 3952: 		if ($awarded ne '' && $awarded ne $old_aw) {
                   3953: 		    $newrecord{'resource.'.$part.'.'.$type}= $awarded;
1.257     albertel 3954: 		    $newrecord{'resource.'.$part.'.regrader'}="$env{'user.name'}:$env{'user.domain'}";
1.54      albertel 3955: 		    $updateflag=1;
                   3956: 		}
1.93      albertel 3957: 		$line .= '<td align="center">'.$old_aw.'&nbsp;</td>'.
1.54      albertel 3958: 		    '<td align="center">'.$awarded.'&nbsp;</td>';
                   3959: 	    }
1.44      ng       3960: 	}
1.477     albertel 3961: 	$line.="\n";
1.301     albertel 3962: 
                   3963: 	my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   3964: 	my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   3965: 
1.44      ng       3966: 	if ($updateflag) {
                   3967: 	    $count++;
1.257     albertel 3968: 	    &Apache::lonnet::cstore(\%newrecord,$symb,$env{'request.course.id'},
1.89      albertel 3969: 				    $udom,$uname);
1.301     albertel 3970: 
                   3971: 	    if (&Apache::bridgetask::in_queue('gradingqueue',$symb,$cdom,
                   3972: 					      $cnum,$udom,$uname)) {
                   3973: 		# need to figure out if should be in queue.
                   3974: 		my %record =  
                   3975: 		    &Apache::lonnet::restore($symb,$env{'request.course.id'},
                   3976: 					     $udom,$uname);
                   3977: 		my $all_graded = 1;
                   3978: 		my $none_graded = 1;
                   3979: 		foreach my $part (@parts) {
                   3980: 		    if ( $record{'resource.'.$part.'.awarded'} eq '' ) {
                   3981: 			$all_graded = 0;
                   3982: 		    } else {
                   3983: 			$none_graded = 0;
                   3984: 		    }
                   3985: 		}
                   3986: 
                   3987: 		if ($all_graded || $none_graded) {
                   3988: 		    &Apache::bridgetask::remove_from_queue('gradingqueue',
                   3989: 							   $symb,$cdom,$cnum,
                   3990: 							   $udom,$uname);
                   3991: 		}
                   3992: 	    }
                   3993: 
1.477     albertel 3994: 	    $result.=&Apache::loncommon::start_data_table_row().
                   3995: 		'<td align="right">&nbsp;'.$updateCtr.'&nbsp;</td>'.$line.
                   3996: 		&Apache::loncommon::end_data_table_row();
1.126     ng       3997: 	    $updateCtr++;
1.93      albertel 3998: 	} else {
1.477     albertel 3999: 	    push(@noupdate,
                   4000: 		 '<td align="right">&nbsp;'.$noupdateCtr.'&nbsp;</td>'.$line);
1.126     ng       4001: 	    $noupdateCtr++;
1.44      ng       4002: 	}
1.269     raeburn  4003:         if ($aggregateflag) {
                   4004:             &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
1.301     albertel 4005: 				  $cdom,$cnum);
1.269     raeburn  4006:         }
1.93      albertel 4007:     }
1.477     albertel 4008:     if (@noupdate) {
1.126     ng       4009: #	my $numcols=(scalar(@partid)*(scalar(@parts)-1)*2)+3;
                   4010: 	my $numcols=scalar(@partid)*4+2;
1.477     albertel 4011: 	$result .= &Apache::loncommon::start_data_table_row('LC_empty_row').
1.478     albertel 4012: 	    '<td align="center" colspan="'.$numcols.'">'.
                   4013: 	    &mt('No Changes Occurred For the Students Below').
                   4014: 	    '</td>'.
1.477     albertel 4015: 	    &Apache::loncommon::end_data_table_row();
                   4016: 	foreach my $line (@noupdate) {
                   4017: 	    $result.=
                   4018: 		&Apache::loncommon::start_data_table_row().
                   4019: 		$line.
                   4020: 		&Apache::loncommon::end_data_table_row();
                   4021: 	}
1.44      ng       4022:     }
1.614     www      4023:     $result .= &Apache::loncommon::end_data_table();
1.478     albertel 4024:     my $msg = '<p><b>'.
                   4025: 	&mt('Number of records updated = [_1] for [quant,_2,student].',
                   4026: 	    $rec_update,$count).'</b><br />'.
                   4027: 	'<b>'.&mt('Total number of students = [_1]',$env{'form.total'}).
                   4028: 	'</b></p>';
1.44      ng       4029:     return $title.$msg.$result;
1.5       albertel 4030: }
1.54      albertel 4031: 
                   4032: sub split_part_type {
                   4033:     my ($partstr) = @_;
                   4034:     my ($temp,@allparts)=split(/_/,$partstr);
                   4035:     my $type=pop(@allparts);
1.439     albertel 4036:     my $part=join('_',@allparts);
1.54      albertel 4037:     return ($part,$type);
                   4038: }
                   4039: 
1.44      ng       4040: #------------- end of section for handling grading by section/class ---------
                   4041: #
                   4042: #----------------------------------------------------------------------------
                   4043: 
1.5       albertel 4044: 
1.44      ng       4045: #----------------------------------------------------------------------------
                   4046: #
                   4047: #-------------------------- Next few routines handles grading by csv upload
                   4048: #
                   4049: #--- Javascript to handle csv upload
1.27      albertel 4050: sub csvupload_javascript_reverse_associate {
1.573     bisitz   4051:     my $error1=&mt('You need to specify the username or the student/employee ID');
1.246     albertel 4052:     my $error2=&mt('You need to specify at least one grading field');
1.27      albertel 4053:   return(<<ENDPICK);
                   4054:   function verify(vf) {
                   4055:     var foundsomething=0;
                   4056:     var founduname=0;
1.243     albertel 4057:     var foundID=0;
1.27      albertel 4058:     for (i=0;i<=vf.nfields.value;i++) {
                   4059:       tw=eval('vf.f'+i+'.selectedIndex');
1.243     albertel 4060:       if (i==0 && tw!=0) { foundID=1; }
                   4061:       if (i==1 && tw!=0) { founduname=1; }
                   4062:       if (i!=0 && i!=1 && i!=2 && tw!=0) { foundsomething=1; }
1.27      albertel 4063:     }
1.246     albertel 4064:     if (founduname==0 && foundID==0) {
                   4065: 	alert('$error1');
                   4066: 	return;
1.27      albertel 4067:     }
                   4068:     if (foundsomething==0) {
1.246     albertel 4069: 	alert('$error2');
                   4070: 	return;
1.27      albertel 4071:     }
                   4072:     vf.submit();
                   4073:   }
                   4074:   function flip(vf,tf) {
                   4075:     var nw=eval('vf.f'+tf+'.selectedIndex');
                   4076:     var i;
                   4077:     for (i=0;i<=vf.nfields.value;i++) {
                   4078:       //can not pick the same destination field for both name and domain
                   4079:       if (((i ==0)||(i ==1)) && 
                   4080:           ((tf==0)||(tf==1)) && 
                   4081:           (i!=tf) &&
                   4082:           (eval('vf.f'+i+'.selectedIndex')==nw)) {
                   4083:         eval('vf.f'+i+'.selectedIndex=0;')
                   4084:       }
                   4085:     }
                   4086:   }
                   4087: ENDPICK
                   4088: }
                   4089: 
                   4090: sub csvupload_javascript_forward_associate {
1.573     bisitz   4091:     my $error1=&mt('You need to specify the username or the student/employee ID');
1.246     albertel 4092:     my $error2=&mt('You need to specify at least one grading field');
1.27      albertel 4093:   return(<<ENDPICK);
                   4094:   function verify(vf) {
                   4095:     var foundsomething=0;
                   4096:     var founduname=0;
1.243     albertel 4097:     var foundID=0;
1.27      albertel 4098:     for (i=0;i<=vf.nfields.value;i++) {
                   4099:       tw=eval('vf.f'+i+'.selectedIndex');
1.243     albertel 4100:       if (tw==1) { foundID=1; }
                   4101:       if (tw==2) { founduname=1; }
                   4102:       if (tw>3) { foundsomething=1; }
1.27      albertel 4103:     }
1.246     albertel 4104:     if (founduname==0 && foundID==0) {
                   4105: 	alert('$error1');
                   4106: 	return;
1.27      albertel 4107:     }
                   4108:     if (foundsomething==0) {
1.246     albertel 4109: 	alert('$error2');
                   4110: 	return;
1.27      albertel 4111:     }
                   4112:     vf.submit();
                   4113:   }
                   4114:   function flip(vf,tf) {
                   4115:     var nw=eval('vf.f'+tf+'.selectedIndex');
                   4116:     var i;
                   4117:     //can not pick the same destination field twice
                   4118:     for (i=0;i<=vf.nfields.value;i++) {
                   4119:       if ((i!=tf) && (eval('vf.f'+i+'.selectedIndex')==nw)) {
                   4120:         eval('vf.f'+i+'.selectedIndex=0;')
                   4121:       }
                   4122:     }
                   4123:   }
                   4124: ENDPICK
                   4125: }
                   4126: 
1.26      albertel 4127: sub csvuploadmap_header {
1.324     albertel 4128:     my ($request,$symb,$datatoken,$distotal)= @_;
1.41      ng       4129:     my $javascript;
1.257     albertel 4130:     if ($env{'form.upfile_associate'} eq 'reverse') {
1.41      ng       4131: 	$javascript=&csvupload_javascript_reverse_associate();
                   4132:     } else {
                   4133: 	$javascript=&csvupload_javascript_forward_associate();
                   4134:     }
1.45      ng       4135: 
1.418     albertel 4136:     $symb = &Apache::lonenc::check_encrypt($symb);
1.632     www      4137:     $request->print('<form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">'.
                   4138:                     &mt('Total number of records found in file: [_1]',$distotal).'<hr />'.
                   4139:                     &mt('Associate entries from the uploaded file with as many fields as you can.'));
                   4140:     my $reverse=&mt("Reverse Association");
1.41      ng       4141:     $request->print(<<ENDPICK);
1.632     www      4142: <br />
                   4143: <input type="button" value="$reverse" onclick="javascript:this.form.associate.value='Reverse Association';submit(this.form);" />
1.26      albertel 4144: <input type="hidden" name="associate"  value="" />
                   4145: <input type="hidden" name="phase"      value="three" />
                   4146: <input type="hidden" name="datatoken"  value="$datatoken" />
1.257     albertel 4147: <input type="hidden" name="fileupload" value="$env{'form.fileupload'}" />
                   4148: <input type="hidden" name="upfiletype" value="$env{'form.upfiletype'}" />
1.26      albertel 4149: <input type="hidden" name="upfile_associate" 
1.257     albertel 4150:                                        value="$env{'form.upfile_associate'}" />
1.26      albertel 4151: <input type="hidden" name="symb"       value="$symb" />
1.246     albertel 4152: <input type="hidden" name="command"    value="csvuploadoptions" />
1.26      albertel 4153: <hr />
                   4154: ENDPICK
1.597     wenzelju 4155:     $request->print(&Apache::lonhtmlcommon::scripttag($javascript));
1.118     ng       4156:     return '';
1.26      albertel 4157: 
                   4158: }
                   4159: 
                   4160: sub csvupload_fields {
1.582     raeburn  4161:     my ($symb,$errorref) = @_;
                   4162:     my (@parts) = &getpartlist($symb,$errorref);
                   4163:     if (ref($errorref)) {
                   4164:         if ($$errorref) {
                   4165:             return;
                   4166:         }
                   4167:     }
                   4168: 
1.556     weissno  4169:     my @fields=(['ID','Student/Employee ID'],
1.243     albertel 4170: 		['username','Student Username'],
                   4171: 		['domain','Student Domain']);
1.324     albertel 4172:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
1.41      ng       4173:     foreach my $part (sort(@parts)) {
                   4174: 	my @datum;
                   4175: 	my $display=&Apache::lonnet::metadata($url,$part.'.display');
                   4176: 	my $name=$part;
                   4177: 	if  (!$display) { $display = $name; }
                   4178: 	@datum=($name,$display);
1.244     albertel 4179: 	if ($name=~/^stores_(.*)_awarded/) {
                   4180: 	    push(@fields,['stores_'.$1.'_points',"Points [Part: $1]"]);
                   4181: 	}
1.41      ng       4182: 	push(@fields,\@datum);
                   4183:     }
                   4184:     return (@fields);
1.26      albertel 4185: }
                   4186: 
                   4187: sub csvuploadmap_footer {
1.41      ng       4188:     my ($request,$i,$keyfields) =@_;
1.703     bisitz   4189:     my $buttontext = &mt('Assign Grades');
1.41      ng       4190:     $request->print(<<ENDPICK);
1.26      albertel 4191: </table>
                   4192: <input type="hidden" name="nfields" value="$i" />
                   4193: <input type="hidden" name="keyfields" value="$keyfields" />
1.703     bisitz   4194: <input type="button" onclick="javascript:verify(this.form)" value="$buttontext" /><br />
1.26      albertel 4195: </form>
                   4196: ENDPICK
                   4197: }
                   4198: 
1.283     albertel 4199: sub checkforfile_js {
1.638     www      4200:     my $alertmsg = &mt('Please use the browse button to select a file from your local directory.');
1.597     wenzelju 4201:     my $result = &Apache::lonhtmlcommon::scripttag(<<CSVFORMJS);
1.86      ng       4202:     function checkUpload(formname) {
                   4203: 	if (formname.upfile.value == "") {
1.539     riegler  4204: 	    alert("$alertmsg");
1.86      ng       4205: 	    return false;
                   4206: 	}
                   4207: 	formname.submit();
                   4208:     }
                   4209: CSVFORMJS
1.283     albertel 4210:     return $result;
                   4211: }
                   4212: 
                   4213: sub upcsvScores_form {
1.608     www      4214:     my ($request,$symb) = @_;
1.283     albertel 4215:     if (!$symb) {return '';}
                   4216:     my $result=&checkforfile_js();
1.632     www      4217:     $result.=&Apache::loncommon::start_data_table().
                   4218:              &Apache::loncommon::start_data_table_header_row().
                   4219:              '<th>'.&mt('Specify a file containing the class scores for current resource.').'</th>'.
                   4220:              &Apache::loncommon::end_data_table_header_row().
                   4221:              &Apache::loncommon::start_data_table_row().'<td>';
1.370     www      4222:     my $upload=&mt("Upload Scores");
1.86      ng       4223:     my $upfile_select=&Apache::loncommon::upfile_select_html();
1.245     albertel 4224:     my $ignore=&mt('Ignore First Line');
1.418     albertel 4225:     $symb = &Apache::lonenc::check_encrypt($symb);
1.86      ng       4226:     $result.=<<ENDUPFORM;
1.106     albertel 4227: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
1.86      ng       4228: <input type="hidden" name="symb" value="$symb" />
                   4229: <input type="hidden" name="command" value="csvuploadmap" />
                   4230: $upfile_select
1.589     bisitz   4231: <br /><input type="button" onclick="javascript:checkUpload(this.form);" value="$upload" />
1.86      ng       4232: </form>
                   4233: ENDUPFORM
1.370     www      4234:     $result.=&Apache::loncommon::help_open_topic("Course_Convert_To_CSV",
1.632     www      4235:                            &mt("How do I create a CSV file from a spreadsheet")).
                   4236:              '</td>'.
                   4237:             &Apache::loncommon::end_data_table_row().
                   4238:             &Apache::loncommon::end_data_table();
1.86      ng       4239:     return $result;
                   4240: }
                   4241: 
                   4242: 
1.26      albertel 4243: sub csvuploadmap {
1.608     www      4244:     my ($request,$symb)= @_;
1.41      ng       4245:     if (!$symb) {return '';}
1.72      ng       4246: 
1.41      ng       4247:     my $datatoken;
1.257     albertel 4248:     if (!$env{'form.datatoken'}) {
1.41      ng       4249: 	$datatoken=&Apache::loncommon::upfile_store($request);
1.26      albertel 4250:     } else {
1.257     albertel 4251: 	$datatoken=$env{'form.datatoken'};
1.41      ng       4252: 	&Apache::loncommon::load_tmp_file($request);
1.26      albertel 4253:     }
1.41      ng       4254:     my @records=&Apache::loncommon::upfile_record_sep();
1.324     albertel 4255:     &csvuploadmap_header($request,$symb,$datatoken,$#records+1);
1.41      ng       4256:     my ($i,$keyfields);
                   4257:     if (@records) {
1.582     raeburn  4258:         my $fieldserror;
                   4259: 	my @fields=&csvupload_fields($symb,\$fieldserror);
                   4260:         if ($fieldserror) {
                   4261:             $request->print(&navmap_errormsg());
                   4262:             return;
                   4263:         }
1.257     albertel 4264: 	if ($env{'form.upfile_associate'} eq 'reverse') {	
1.41      ng       4265: 	    &Apache::loncommon::csv_print_samples($request,\@records);
                   4266: 	    $i=&Apache::loncommon::csv_print_select_table($request,\@records,
                   4267: 							  \@fields);
                   4268: 	    foreach (@fields) { $keyfields.=$_->[0].','; }
                   4269: 	    chop($keyfields);
                   4270: 	} else {
                   4271: 	    unshift(@fields,['none','']);
                   4272: 	    $i=&Apache::loncommon::csv_samples_select_table($request,\@records,
                   4273: 							    \@fields);
1.311     banghart 4274:             foreach my $rec (@records) {
                   4275:                 my %temp = &Apache::loncommon::record_sep($rec);
                   4276:                 if (%temp) {
                   4277:                     $keyfields=join(',',sort(keys(%temp)));
                   4278:                     last;
                   4279:                 }
                   4280:             }
1.41      ng       4281: 	}
                   4282:     }
                   4283:     &csvuploadmap_footer($request,$i,$keyfields);
1.72      ng       4284: 
1.41      ng       4285:     return '';
1.27      albertel 4286: }
                   4287: 
1.246     albertel 4288: sub csvuploadoptions {
1.608     www      4289:     my ($request,$symb)= @_;
1.632     www      4290:     my $overwrite=&mt('Overwrite any existing score');
1.246     albertel 4291:     $request->print(<<ENDPICK);
                   4292: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
                   4293: <input type="hidden" name="command"    value="csvuploadassign" />
                   4294: <p>
                   4295: <label>
                   4296:    <input type="checkbox" name="overwite_scores" checked="checked" />
1.632     www      4297:    $overwrite
1.246     albertel 4298: </label>
                   4299: </p>
                   4300: ENDPICK
                   4301:     my %fields=&get_fields();
                   4302:     if (!defined($fields{'domain'})) {
1.257     albertel 4303: 	my $domform = &Apache::loncommon::select_dom_form($env{'request.role.domain'},'default_domain');
1.632     www      4304: 	$request->print("\n<p>".&mt('Users are in domain: [_1]',$domform)."</p>\n");
1.246     albertel 4305:     }
1.257     albertel 4306:     foreach my $key (sort(keys(%env))) {
1.246     albertel 4307: 	if ($key !~ /^form\.(.*)$/) { next; }
                   4308: 	my $cleankey=$1;
                   4309: 	if ($cleankey eq 'command') { next; }
                   4310: 	$request->print('<input type="hidden" name="'.$cleankey.
1.257     albertel 4311: 			'"  value="'.$env{$key}.'" />'."\n");
1.246     albertel 4312:     }
                   4313:     # FIXME do a check for any duplicated user ids...
                   4314:     # FIXME do a check for any invalid user ids?...
1.703     bisitz   4315:     $request->print('<input type="submit" value="'.&mt('Assign Grades').'" /><br />
1.290     albertel 4316: <hr /></form>'."\n");
1.246     albertel 4317:     return '';
                   4318: }
                   4319: 
                   4320: sub get_fields {
                   4321:     my %fields;
1.257     albertel 4322:     my @keyfields = split(/\,/,$env{'form.keyfields'});
                   4323:     for (my $i=0; $i<=$env{'form.nfields'}; $i++) {
                   4324: 	if ($env{'form.upfile_associate'} eq 'reverse') {
                   4325: 	    if ($env{'form.f'.$i} ne 'none') {
                   4326: 		$fields{$keyfields[$i]}=$env{'form.f'.$i};
1.41      ng       4327: 	    }
                   4328: 	} else {
1.257     albertel 4329: 	    if ($env{'form.f'.$i} ne 'none') {
                   4330: 		$fields{$env{'form.f'.$i}}=$keyfields[$i];
1.41      ng       4331: 	    }
                   4332: 	}
1.27      albertel 4333:     }
1.246     albertel 4334:     return %fields;
                   4335: }
                   4336: 
                   4337: sub csvuploadassign {
1.608     www      4338:     my ($request,$symb)= @_;
1.246     albertel 4339:     if (!$symb) {return '';}
1.345     bowersj2 4340:     my $error_msg = '';
1.246     albertel 4341:     &Apache::loncommon::load_tmp_file($request);
                   4342:     my @gradedata = &Apache::loncommon::upfile_record_sep();
                   4343:     my %fields=&get_fields();
1.257     albertel 4344:     my $courseid=$env{'request.course.id'};
1.97      albertel 4345:     my ($classlist) = &getclasslist('all',0);
1.106     albertel 4346:     my @notallowed;
1.41      ng       4347:     my @skipped;
1.657     raeburn  4348:     my @warnings;
1.41      ng       4349:     my $countdone=0;
                   4350:     foreach my $grade (@gradedata) {
                   4351: 	my %entries=&Apache::loncommon::record_sep($grade);
1.246     albertel 4352: 	my $domain;
                   4353: 	if ($entries{$fields{'domain'}}) {
                   4354: 	    $domain=$entries{$fields{'domain'}};
                   4355: 	} else {
1.257     albertel 4356: 	    $domain=$env{'form.default_domain'};
1.246     albertel 4357: 	}
1.243     albertel 4358: 	$domain=~s/\s//g;
1.41      ng       4359: 	my $username=$entries{$fields{'username'}};
1.160     albertel 4360: 	$username=~s/\s//g;
1.243     albertel 4361: 	if (!$username) {
                   4362: 	    my $id=$entries{$fields{'ID'}};
1.247     albertel 4363: 	    $id=~s/\s//g;
1.243     albertel 4364: 	    my %ids=&Apache::lonnet::idget($domain,$id);
                   4365: 	    $username=$ids{$id};
                   4366: 	}
1.41      ng       4367: 	if (!exists($$classlist{"$username:$domain"})) {
1.247     albertel 4368: 	    my $id=$entries{$fields{'ID'}};
                   4369: 	    $id=~s/\s//g;
                   4370: 	    if ($id) {
                   4371: 		push(@skipped,"$id:$domain");
                   4372: 	    } else {
                   4373: 		push(@skipped,"$username:$domain");
                   4374: 	    }
1.41      ng       4375: 	    next;
                   4376: 	}
1.108     albertel 4377: 	my $usec=$classlist->{"$username:$domain"}[5];
1.106     albertel 4378: 	if (!&canmodify($usec)) {
                   4379: 	    push(@notallowed,"$username:$domain");
                   4380: 	    next;
                   4381: 	}
1.244     albertel 4382: 	my %points;
1.41      ng       4383: 	my %grades;
                   4384: 	foreach my $dest (keys(%fields)) {
1.244     albertel 4385: 	    if ($dest eq 'ID' || $dest eq 'username' ||
                   4386: 		$dest eq 'domain') { next; }
                   4387: 	    if ($entries{$fields{$dest}} =~ /^\s*$/) { next; }
                   4388: 	    if ($dest=~/stores_(.*)_points/) {
                   4389: 		my $part=$1;
                   4390: 		my $wgt =&Apache::lonnet::EXT('resource.'.$part.'.weight',
                   4391: 					      $symb,$domain,$username);
1.345     bowersj2 4392:                 if ($wgt) {
                   4393:                     $entries{$fields{$dest}}=~s/\s//g;
                   4394:                     my $pcr=$entries{$fields{$dest}} / $wgt;
1.463     albertel 4395:                     my $award=($pcr == 0) ? 'incorrect_by_override'
                   4396:                                           : 'correct_by_override';
1.638     www      4397:                     if ($pcr>1) {
1.657     raeburn  4398:                        push(@warnings,&mt("[_1]: point value larger than weight","$username:$domain"));
1.638     www      4399:                     }
1.345     bowersj2 4400:                     $grades{"resource.$part.awarded"}=$pcr;
                   4401:                     $grades{"resource.$part.solved"}=$award;
                   4402:                     $points{$part}=1;
                   4403:                 } else {
                   4404:                     $error_msg = "<br />" .
                   4405:                         &mt("Some point values were assigned"
                   4406:                             ." for problems with a weight "
                   4407:                             ."of zero. These values were "
                   4408:                             ."ignored.");
                   4409:                 }
1.244     albertel 4410: 	    } else {
                   4411: 		if ($dest=~/stores_(.*)_awarded/) { if ($points{$1}) {next;} }
                   4412: 		if ($dest=~/stores_(.*)_solved/)  { if ($points{$1}) {next;} }
                   4413: 		my $store_key=$dest;
                   4414: 		$store_key=~s/^stores/resource/;
                   4415: 		$store_key=~s/_/\./g;
                   4416: 		$grades{$store_key}=$entries{$fields{$dest}};
                   4417: 	    }
1.41      ng       4418: 	}
1.508     www      4419: 	if (! %grades) { 
                   4420:            push(@skipped,&mt("[_1]: no data to save","$username:$domain")); 
                   4421:         } else {
                   4422: 	   $grades{"resource.regrader"}="$env{'user.name'}:$env{'user.domain'}";
                   4423: 	   my $result=&Apache::lonnet::cstore(\%grades,$symb,
1.302     albertel 4424: 					   $env{'request.course.id'},
                   4425: 					   $domain,$username);
1.508     www      4426: 	   if ($result eq 'ok') {
1.627     www      4427: # Successfully stored
1.508     www      4428: 	      $request->print('.');
1.627     www      4429: # Remove from grading queue
                   4430:               &Apache::bridgetask::remove_from_queue('gradingqueue',$symb,
                   4431:                                              $env{'course.'.$env{'request.course.id'}.'.domain'},
                   4432:                                              $env{'course.'.$env{'request.course.id'}.'.num'},
                   4433:                                              $domain,$username);
                   4434:               $countdone++;
                   4435:            } else {
1.508     www      4436: 	      $request->print("<p><span class=\"LC_error\">".
                   4437:                               &mt("Failed to save data for student [_1]. Message when trying to save was: [_2]",
                   4438:                                   "$username:$domain",$result)."</span></p>");
                   4439: 	   }
                   4440: 	   $request->rflush();
                   4441:         }
1.41      ng       4442:     }
1.570     www      4443:     $request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt("Saved scores for [quant,_1,student]",$countdone),$countdone==0));
1.657     raeburn  4444:     if (@warnings) {
                   4445:         $request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt('Warnings generated for the following saved scores:'),1).'<br />');
                   4446:         $request->print(join(', ',@warnings));
                   4447:     }
1.41      ng       4448:     if (@skipped) {
1.571     www      4449: 	$request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt('No scores stored for the following username(s):'),1).'<br />');
                   4450:         $request->print(join(', ',@skipped));
1.106     albertel 4451:     }
                   4452:     if (@notallowed) {
1.571     www      4453: 	$request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt('Modification of scores not allowed for the following username(s):'),1).'<br />');
                   4454: 	$request->print(join(', ',@notallowed));
1.41      ng       4455:     }
1.106     albertel 4456:     $request->print("<br />\n");
1.345     bowersj2 4457:     return $error_msg;
1.26      albertel 4458: }
1.44      ng       4459: #------------- end of section for handling csv file upload ---------
                   4460: #
                   4461: #-------------------------------------------------------------------
                   4462: #
1.122     ng       4463: #-------------- Next few routines handle grading by page/sequence
1.72      ng       4464: #
                   4465: #--- Select a page/sequence and a student to grade
1.68      ng       4466: sub pickStudentPage {
1.608     www      4467:     my ($request,$symb) = @_;
1.68      ng       4468: 
1.539     riegler  4469:     my $alertmsg = &mt('Please select the student you wish to grade.');
1.597     wenzelju 4470:     $request->print(&Apache::lonhtmlcommon::scripttag(<<LISTJAVASCRIPT));
1.68      ng       4471: 
                   4472: function checkPickOne(formname) {
1.76      ng       4473:     if (radioSelection(formname.student) == null) {
1.539     riegler  4474: 	alert("$alertmsg");
1.68      ng       4475: 	return;
                   4476:     }
1.125     ng       4477:     ptr = pullDownSelection(formname.selectpage);
                   4478:     formname.page.value = formname["page"+ptr].value;
                   4479:     formname.title.value = formname["title"+ptr].value;
1.68      ng       4480:     formname.submit();
                   4481: }
                   4482: 
                   4483: LISTJAVASCRIPT
1.118     ng       4484:     &commonJSfunctions($request);
1.608     www      4485: 
1.257     albertel 4486:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
                   4487:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
                   4488:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
1.68      ng       4489: 
1.398     albertel 4490:     my $result='<h3><span class="LC_info">&nbsp;'.
1.485     albertel 4491: 	&mt('Manual Grading by Page or Sequence').'</span></h3>';
1.68      ng       4492: 
1.80      ng       4493:     $result.='<form action="/adm/grades" method="post" name="displayPage">'."\n";
1.582     raeburn  4494:     my $map_error;
                   4495:     my ($titles,$symbx) = &getSymbMap($map_error);
                   4496:     if ($map_error) {
                   4497:         $request->print(&navmap_errormsg());
                   4498:         return; 
                   4499:     }
1.137     albertel 4500:     my ($curpage) =&Apache::lonnet::decode_symb($symb); 
                   4501: #    my ($curpage,$mapId) =&Apache::lonnet::decode_symb($symb); 
                   4502: #    my $type=($curpage =~ /\.(page|sequence)/);
1.700     bisitz   4503: 
                   4504:     # Collection of hidden fields
1.70      ng       4505:     my $ctr=0;
1.68      ng       4506:     foreach (@$titles) {
1.700     bisitz   4507:         my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
                   4508:         $result.='<input type="hidden" name="page'.$ctr.'" value="'.$$symbx{$_}.'" />'."\n";
                   4509:         $result.='<input type="hidden" name="title'.$ctr.'" value="'.$showtitle.'" />'."\n";
                   4510:         $ctr++;
1.68      ng       4511:     }
1.700     bisitz   4512:     $result.='<input type="hidden" name="page" />'."\n".
                   4513:         '<input type="hidden" name="title" />'."\n";
                   4514: 
                   4515:     $result.=&build_section_inputs();
                   4516:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
                   4517:     $result.='<input type="hidden" name="Status"  value="'.$stu_status.'" />'."\n".
                   4518: 	'<input type="hidden" name="command" value="displayPage" />'."\n".
                   4519: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
1.485     albertel 4520: 
1.700     bisitz   4521:     # Show grading options
                   4522:     $result.=&Apache::lonhtmlcommon::start_pick_box();
                   4523:     my $select = '<select name="selectpage">'."\n";
1.70      ng       4524:     $ctr=0;
                   4525:     foreach (@$titles) {
                   4526: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
1.700     bisitz   4527: 	$select.='<option value="'.$ctr.'"'.
                   4528: 	    ($$symbx{$_} =~ /$curpage$/ ? ' selected="selected"' : '').
                   4529: 	    '>'.$showtitle.'</option>'."\n";
1.70      ng       4530: 	$ctr++;
                   4531:     }
1.700     bisitz   4532:     $select.= '</select>';
1.68      ng       4533: 
1.700     bisitz   4534:     $result.=
                   4535:         &Apache::lonhtmlcommon::row_title(&mt('Problems from'))
                   4536:        .$select
                   4537:        .&Apache::lonhtmlcommon::row_closure();
                   4538: 
                   4539:     $result.=
                   4540:         &Apache::lonhtmlcommon::row_title(&mt('View Problem Text'))
                   4541:        .'<label><input type="radio" name="vProb" value="no"'
                   4542:            .' checked="checked" /> '.&mt('no').' </label>'."\n"
                   4543:        .'<label><input type="radio" name="vProb" value="yes" />'
                   4544:            .&mt('yes').'</label>'."\n"
                   4545:        .&Apache::lonhtmlcommon::row_closure();
                   4546: 
                   4547:     $result.=
                   4548:         &Apache::lonhtmlcommon::row_title(&mt('View Submissions'))
                   4549:        .'<label><input type="radio" name="lastSub" value="none" /> '
                   4550:            .&mt('none').' </label>'."\n"
                   4551:        .'<label><input type="radio" name="lastSub" value="datesub"'
                   4552:            .' checked="checked" /> '.&mt('all submissions').'</label>'."\n"
                   4553:        .'<label><input type="radio" name="lastSub" value="all" /> '
                   4554:            .&mt('all submissions with details').' </label>'
                   4555:        .&Apache::lonhtmlcommon::row_closure();
1.432     banghart 4556:     
1.700     bisitz   4557:     $result.=
                   4558:         &Apache::lonhtmlcommon::row_title(&mt('Use CODE'))
                   4559:        .'<input type="text" name="CODE" value="" />'
                   4560:        .&Apache::lonhtmlcommon::row_closure(1)
                   4561:        .&Apache::lonhtmlcommon::end_pick_box();
1.382     albertel 4562: 
1.700     bisitz   4563:     # Show list of students to select for grading
                   4564:     $result.='<br /><input type="button" '.
1.589     bisitz   4565:              'onclick="javascript:checkPickOne(this.form);" value="'.&mt('Next').' &rarr;" /><br />'."\n";
1.72      ng       4566: 
1.68      ng       4567:     $request->print($result);
                   4568: 
1.485     albertel 4569:     my $studentTable.='&nbsp;<b>'.&mt('Select a student you wish to grade and then click on the Next button.').'</b><br />'.
1.484     albertel 4570: 	&Apache::loncommon::start_data_table().
                   4571: 	&Apache::loncommon::start_data_table_header_row().
1.485     albertel 4572: 	'<th align="right">&nbsp;'.&mt('No.').'</th>'.
1.484     albertel 4573: 	'<th>'.&nameUserString('header').'</th>'.
1.485     albertel 4574: 	'<th align="right">&nbsp;'.&mt('No.').'</th>'.
1.484     albertel 4575: 	'<th>'.&nameUserString('header').'</th>'.
                   4576: 	&Apache::loncommon::end_data_table_header_row();
1.68      ng       4577:  
1.76      ng       4578:     my (undef,undef,$fullname) = &getclasslist($getsec,'1');
1.68      ng       4579:     my $ptr = 1;
1.294     albertel 4580:     foreach my $student (sort 
                   4581: 			 {
                   4582: 			     if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                   4583: 				 return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                   4584: 			     }
                   4585: 			     return $a cmp $b;
                   4586: 			 } (keys(%$fullname))) {
1.68      ng       4587: 	my ($uname,$udom) = split(/:/,$student);
1.484     albertel 4588: 	$studentTable.=($ptr%2==1 ? &Apache::loncommon::start_data_table_row()
                   4589:                                   : '</td>');
1.126     ng       4590: 	$studentTable.='<td align="right">'.$ptr.'&nbsp;</td>';
1.288     albertel 4591: 	$studentTable.='<td>&nbsp;<label><input type="radio" name="student" value="'.$student.'" /> '
                   4592: 	    .&nameUserString(undef,$$fullname{$student},$uname,$udom)."</label>\n";
1.484     albertel 4593: 	$studentTable.=
                   4594: 	    ($ptr%2 == 0 ? '</td>'.&Apache::loncommon::end_data_table_row() 
                   4595:                          : '');
1.68      ng       4596: 	$ptr++;
                   4597:     }
1.484     albertel 4598:     if ($ptr%2 == 0) {
                   4599: 	$studentTable.='</td><td>&nbsp;</td><td>&nbsp;</td>'.
                   4600: 	    &Apache::loncommon::end_data_table_row();
                   4601:     }
                   4602:     $studentTable.=&Apache::loncommon::end_data_table()."\n";
1.126     ng       4603:     $studentTable.='<input type="button" '.
1.589     bisitz   4604:                    'onclick="javascript:checkPickOne(this.form);" value="'.&mt('Next').' &rarr;" /></form>'."\n";
1.68      ng       4605: 
                   4606:     $request->print($studentTable);
                   4607: 
                   4608:     return '';
                   4609: }
                   4610: 
                   4611: sub getSymbMap {
1.582     raeburn  4612:     my ($map_error) = @_;
1.132     bowersj2 4613:     my $navmap = Apache::lonnavmaps::navmap->new();
1.582     raeburn  4614:     unless (ref($navmap)) {
                   4615:         if (ref($map_error)) {
                   4616:             $$map_error = 'navmap';
                   4617:         }
                   4618:         return;
                   4619:     }
1.68      ng       4620:     my %symbx = ();
                   4621:     my @titles = ();
1.117     bowersj2 4622:     my $minder = 0;
                   4623: 
                   4624:     # Gather every sequence that has problems.
1.240     albertel 4625:     my @sequences = $navmap->retrieveResources(undef, sub { shift->is_map(); },
                   4626: 					       1,0,1);
1.117     bowersj2 4627:     for my $sequence ($navmap->getById('0.0'), @sequences) {
1.241     albertel 4628: 	if ($navmap->hasResource($sequence, sub { shift->is_problem(); }, 0) ) {
1.381     albertel 4629: 	    my $title = $minder.'.'.
                   4630: 		&HTML::Entities::encode($sequence->compTitle(),'"\'&');
                   4631: 	    push(@titles, $title); # minder in case two titles are identical
                   4632: 	    $symbx{$title} = &HTML::Entities::encode($sequence->symb(),'"\'&');
1.117     bowersj2 4633: 	    $minder++;
1.241     albertel 4634: 	}
1.68      ng       4635:     }
                   4636:     return \@titles,\%symbx;
                   4637: }
                   4638: 
1.72      ng       4639: #
                   4640: #--- Displays a page/sequence w/wo problems, w/wo submissions
1.68      ng       4641: sub displayPage {
1.608     www      4642:     my ($request,$symb) = @_;
1.257     albertel 4643:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
                   4644:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
                   4645:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
                   4646:     my $pageTitle = $env{'form.page'};
1.103     albertel 4647:     my ($classlist,undef,$fullname) = &getclasslist($getsec,'1');
1.257     albertel 4648:     my ($uname,$udom) = split(/:/,$env{'form.student'});
                   4649:     my $usec=$classlist->{$env{'form.student'}}[5];
1.168     albertel 4650: 
                   4651:     #need to make sure we have the correct data for later EXT calls, 
                   4652:     #thus invalidate the cache
                   4653:     &Apache::lonnet::devalidatecourseresdata(
1.257     albertel 4654:                  $env{'course.'.$env{'request.course.id'}.'.num'},
                   4655:                  $env{'course.'.$env{'request.course.id'}.'.domain'});
1.168     albertel 4656:     &Apache::lonnet::clear_EXT_cache_status();
                   4657: 
1.103     albertel 4658:     if (!&canview($usec)) {
1.712     bisitz   4659:         $request->print(
                   4660:             '<span class="LC_warning">'.
                   4661:             &mt('Unable to view requested student. ([_1])',
                   4662:                     $env{'form.student'}).
                   4663:             '</span>');
                   4664:         return;
1.103     albertel 4665:     }
1.398     albertel 4666:     my $result='<h3><span class="LC_info">&nbsp;'.$env{'form.title'}.'</span></h3>';
1.485     albertel 4667:     $result.='<h3>&nbsp;'.&mt('Student: [_1]',&nameUserString(undef,$$fullname{$env{'form.student'}},$uname,$udom)).
1.129     ng       4668: 	'</h3>'."\n";
1.500     albertel 4669:     $env{'form.CODE'} = uc($env{'form.CODE'});
1.501     foxr     4670:     if (&Apache::lonnet::validCODE(uc($env{'form.CODE'}))) {
1.485     albertel 4671: 	$result.='<h3>&nbsp;'.&mt('CODE: [_1]',$env{'form.CODE'}).'</h3>'."\n";
1.382     albertel 4672:     } else {
                   4673: 	delete($env{'form.CODE'});
                   4674:     }
1.71      ng       4675:     &sub_page_js($request);
                   4676:     $request->print($result);
                   4677: 
1.132     bowersj2 4678:     my $navmap = Apache::lonnavmaps::navmap->new();
1.582     raeburn  4679:     unless (ref($navmap)) {
                   4680:         $request->print(&navmap_errormsg());
                   4681:         return;
                   4682:     }
1.257     albertel 4683:     my ($mapUrl, $id, $resUrl)=&Apache::lonnet::decode_symb($env{'form.page'});
1.68      ng       4684:     my $map = $navmap->getResourceByUrl($resUrl); # add to navmaps
1.288     albertel 4685:     if (!$map) {
1.485     albertel 4686: 	$request->print('<span class="LC_warning">'.&mt('Unable to view requested sequence. ([_1])',$resUrl).'</span>');
1.288     albertel 4687: 	return; 
                   4688:     }
1.68      ng       4689:     my $iterator = $navmap->getIterator($map->map_start(),
                   4690: 					$map->map_finish());
                   4691: 
1.71      ng       4692:     my $studentTable='<form action="/adm/grades" method="post" name="gradePage">'."\n".
1.72      ng       4693: 	'<input type="hidden" name="command" value="gradeByPage" />'."\n".
1.257     albertel 4694: 	'<input type="hidden" name="fullname" value="'.$$fullname{$env{'form.student'}}.'" />'."\n".
                   4695: 	'<input type="hidden" name="student" value="'.$env{'form.student'}.'" />'."\n".
1.72      ng       4696: 	'<input type="hidden" name="page"    value="'.$pageTitle.'" />'."\n".
1.257     albertel 4697: 	'<input type="hidden" name="title"   value="'.$env{'form.title'}.'" />'."\n".
1.418     albertel 4698: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.613     www      4699: 	'<input type="hidden" name="overRideScore" value="no" />'."\n";
1.71      ng       4700: 
1.382     albertel 4701:     if (defined($env{'form.CODE'})) {
                   4702: 	$studentTable.=
                   4703: 	    '<input type="hidden" name="CODE" value="'.$env{'form.CODE'}.'" />'."\n";
                   4704:     }
1.381     albertel 4705:     my $checkIcon = '<img alt="'.&mt('Check Mark').
1.485     albertel 4706: 	'" src="'.&Apache::loncommon::lonhttpdurl($request->dir_config('lonIconsURL').'/check.gif').'" height="16" border="0" />';
1.71      ng       4707: 
1.594     bisitz   4708:     $studentTable.='&nbsp;<span class="LC_info">'.
                   4709:         &mt('Problems graded correct by the computer are marked with a [_1] symbol.',$checkIcon).
                   4710:         '</span>'."\n".
1.484     albertel 4711: 	&Apache::loncommon::start_data_table().
                   4712: 	&Apache::loncommon::start_data_table_header_row().
1.700     bisitz   4713: 	'<th>'.&mt('Prob.').'</th>'.
1.485     albertel 4714: 	'<th>&nbsp;'.($env{'form.vProb'} eq 'no' ? &mt('Title') : &mt('Problem Text')).'/'.&mt('Grade').'</th>'.
1.484     albertel 4715: 	&Apache::loncommon::end_data_table_header_row();
1.71      ng       4716: 
1.329     albertel 4717:     &Apache::lonxml::clear_problem_counter();
1.196     albertel 4718:     my ($depth,$question,$prob) = (1,1,1);
1.68      ng       4719:     $iterator->next(); # skip the first BEGIN_MAP
                   4720:     my $curRes = $iterator->next(); # for "current resource"
1.101     albertel 4721:     while ($depth > 0) {
1.68      ng       4722:         if($curRes == $iterator->BEGIN_MAP) { $depth++; }
1.100     bowersj2 4723:         if($curRes == $iterator->END_MAP) { $depth--; }
1.68      ng       4724: 
1.385     albertel 4725:         if (ref($curRes) && $curRes->is_problem()) {
1.91      albertel 4726: 	    my $parts = $curRes->parts();
1.68      ng       4727:             my $title = $curRes->compTitle();
1.71      ng       4728: 	    my $symbx = $curRes->symb();
1.484     albertel 4729: 	    $studentTable.=
                   4730: 		&Apache::loncommon::start_data_table_row().
                   4731: 		'<td align="center" valign="top" >'.$prob.
1.485     albertel 4732: 		(scalar(@{$parts}) == 1 ? '' 
1.681     raeburn  4733: 		                        : '<br />('.&mt('[_1]parts',
                   4734: 							scalar(@{$parts}).'&nbsp;').')'
1.485     albertel 4735: 		 ).
                   4736: 		 '</td>';
1.71      ng       4737: 	    $studentTable.='<td valign="top">';
1.382     albertel 4738: 	    my %form = ('CODE' => $env{'form.CODE'},);
1.257     albertel 4739: 	    if ($env{'form.vProb'} eq 'yes' ) {
1.144     albertel 4740: 		$studentTable.=&show_problem($request,$symbx,$uname,$udom,1,
1.383     albertel 4741: 					     undef,'both',\%form);
1.71      ng       4742: 	    } else {
1.382     albertel 4743: 		my $companswer = &Apache::loncommon::get_student_answers($symbx,$uname,$udom,$env{'request.course.id'},%form);
1.80      ng       4744: 		$companswer =~ s|<form(.*?)>||g;
                   4745: 		$companswer =~ s|</form>||g;
1.71      ng       4746: #		while ($companswer =~ /(<a href\=\"javascript:newWindow.*?Script Vars<\/a>)/s) { #<a href="javascript:newWindow</a>
1.116     ng       4747: #		    $companswer =~ s/$1/ /ms;
1.326     albertel 4748: #		    $request->print('match='.$1."<br />\n");
1.71      ng       4749: #		}
1.116     ng       4750: #		$companswer =~ s|<table border=\"1\">|<table border=\"0\">|g;
1.539     riegler  4751: 		$studentTable.='&nbsp;<b>'.$title.'</b>&nbsp;<br />&nbsp;<b>'.&mt('Correct answer').':</b><br />'.$companswer;
1.71      ng       4752: 	    }
                   4753: 
1.257     albertel 4754: 	    my %record = &Apache::lonnet::restore($symbx,$env{'request.course.id'},$udom,$uname);
1.125     ng       4755: 
1.257     albertel 4756: 	    if ($env{'form.lastSub'} eq 'datesub') {
1.71      ng       4757: 		if ($record{'version'} eq '') {
1.485     albertel 4758: 		    $studentTable.='<br />&nbsp;<span class="LC_warning">'.&mt('No recorded submission for this problem.').'</span><br />';
1.71      ng       4759: 		} else {
1.116     ng       4760: 		    my %responseType = ();
                   4761: 		    foreach my $partid (@{$parts}) {
1.147     albertel 4762: 			my @responseIds =$curRes->responseIds($partid);
                   4763: 			my @responseType =$curRes->responseType($partid);
                   4764: 			my %responseIds;
                   4765: 			for (my $i=0;$i<=$#responseIds;$i++) {
                   4766: 			    $responseIds{$responseIds[$i]}=$responseType[$i];
                   4767: 			}
                   4768: 			$responseType{$partid} = \%responseIds;
1.116     ng       4769: 		    }
1.148     albertel 4770: 		    $studentTable.= &displaySubByDates($symbx,\%record,$parts,\%responseType,$checkIcon,$uname,$udom);
1.147     albertel 4771: 
1.71      ng       4772: 		}
1.257     albertel 4773: 	    } elsif ($env{'form.lastSub'} eq 'all') {
                   4774: 		my $last = ($env{'form.lastSub'} eq 'last' ? 'last' : '');
1.71      ng       4775: 		$studentTable.=&Apache::loncommon::get_previous_attempt($symbx,$uname,$udom,
1.257     albertel 4776: 									$env{'request.course.id'},
1.71      ng       4777: 									'','.submission');
                   4778:  
                   4779: 	    }
1.103     albertel 4780: 	    if (&canmodify($usec)) {
1.585     bisitz   4781:             $studentTable.=&gradeBox_start();
1.103     albertel 4782: 		foreach my $partid (@{$parts}) {
                   4783: 		    $studentTable.=&gradeBox($request,$symbx,$uname,$udom,$question,$partid,\%record);
                   4784: 		    $studentTable.='<input type="hidden" name="q_'.$question.'" value="'.$partid.'" />'."\n";
                   4785: 		    $question++;
                   4786: 		}
1.585     bisitz   4787:             $studentTable.=&gradeBox_end();
1.196     albertel 4788: 		$prob++;
1.71      ng       4789: 	    }
                   4790: 	    $studentTable.='</td></tr>';
1.68      ng       4791: 
1.103     albertel 4792: 	}
1.68      ng       4793:         $curRes = $iterator->next();
                   4794:     }
                   4795: 
1.589     bisitz   4796:     $studentTable.=
                   4797:         '</table>'."\n".
                   4798:         '<input type="button" value="'.&mt('Save').'" '.
                   4799:         'onclick="javascript:checkSubmitPage(this.form,'.$question.');" />'.
                   4800:         '</form>'."\n";
1.71      ng       4801:     $request->print($studentTable);
                   4802: 
                   4803:     return '';
1.119     ng       4804: }
                   4805: 
                   4806: sub displaySubByDates {
1.148     albertel 4807:     my ($symb,$record,$parts,$responseType,$checkIcon,$uname,$udom) = @_;
1.224     albertel 4808:     my $isCODE=0;
1.335     albertel 4809:     my $isTask = ($symb =~/\.task$/);
1.224     albertel 4810:     if (exists($record->{'resource.CODE'})) { $isCODE=1; }
1.467     albertel 4811:     my $studentTable=&Apache::loncommon::start_data_table().
                   4812: 	&Apache::loncommon::start_data_table_header_row().
                   4813: 	'<th>'.&mt('Date/Time').'</th>'.
                   4814: 	($isCODE?'<th>'.&mt('CODE').'</th>':'').
1.671     raeburn  4815:         ($isTask?'<th>'.&mt('Version').'</th>':'').
1.467     albertel 4816: 	'<th>'.&mt('Submission').'</th>'.
                   4817: 	'<th>'.&mt('Status').'</th>'.
                   4818: 	&Apache::loncommon::end_data_table_header_row();
1.119     ng       4819:     my ($version);
                   4820:     my %mark;
1.148     albertel 4821:     my %orders;
1.119     ng       4822:     $mark{'correct_by_student'} = $checkIcon;
1.147     albertel 4823:     if (!exists($$record{'1:timestamp'})) {
1.539     riegler  4824: 	return '<br />&nbsp;<span class="LC_warning">'.&mt('Nothing submitted - no attempts.').'</span><br />';
1.147     albertel 4825:     }
1.335     albertel 4826: 
                   4827:     my $interaction;
1.525     raeburn  4828:     my $no_increment = 1;
1.640     raeburn  4829:     my %lastrndseed;
1.119     ng       4830:     for ($version=1;$version<=$$record{'version'};$version++) {
1.467     albertel 4831: 	my $timestamp = 
                   4832: 	    &Apache::lonlocal::locallocaltime($$record{$version.':timestamp'});
1.335     albertel 4833: 	if (exists($$record{$version.':resource.0.version'})) {
                   4834: 	    $interaction = $$record{$version.':resource.0.version'};
                   4835: 	}
1.671     raeburn  4836:         if ($isTask && $env{'form.previousversion'}) {
                   4837:             next unless ($interaction == $env{'form.previousversion'});
                   4838:         }
1.335     albertel 4839: 	my $where = ($isTask ? "$version:resource.$interaction"
                   4840: 		             : "$version:resource");
1.467     albertel 4841: 	$studentTable.=&Apache::loncommon::start_data_table_row().
                   4842: 	    '<td>'.$timestamp.'</td>';
1.224     albertel 4843: 	if ($isCODE) {
                   4844: 	    $studentTable.='<td>'.$record->{$version.':resource.CODE'}.'</td>';
                   4845: 	}
1.671     raeburn  4846:         if ($isTask) {
                   4847:             $studentTable.='<td>'.$interaction.'</td>';
                   4848:         }
1.119     ng       4849: 	my @versionKeys = split(/\:/,$$record{$version.':keys'});
                   4850: 	my @displaySub = ();
                   4851: 	foreach my $partid (@{$parts}) {
1.640     raeburn  4852:             my ($hidden,$type);
                   4853:             $type = $$record{$version.':resource.'.$partid.'.type'};
                   4854:             if (($type eq 'anonsurvey') || ($type eq 'anonsurveycred')) {
1.596     raeburn  4855:                 $hidden = 1;
                   4856:             }
1.335     albertel 4857: 	    my @matchKey = ($isTask ? sort(grep /^resource\.\d+\.\Q$partid\E\.award$/,@versionKeys)
                   4858: 			            : sort(grep /^resource\.\Q$partid\E\..*?\.submission$/,@versionKeys));
                   4859: 	    
1.122     ng       4860: #	    next if ($$record{"$version:resource.$partid.solved"} eq '');
1.324     albertel 4861: 	    my $display_part=&get_display_part($partid,$symb);
1.147     albertel 4862: 	    foreach my $matchKey (@matchKey) {
1.198     albertel 4863: 		if (exists($$record{$version.':'.$matchKey}) &&
                   4864: 		    $$record{$version.':'.$matchKey} ne '') {
1.596     raeburn  4865:                     
1.335     albertel 4866: 		    my ($responseId)= ($isTask ? ($matchKey=~ /^resource\.(.*?)\.\Q$partid\E\.award$/)
                   4867: 				               : ($matchKey=~ /^resource\.\Q$partid\E\.(.*?)\.submission$/));
1.670     raeburn  4868:                     $displaySub[0].='<span class="LC_nobreak">';
1.577     bisitz   4869:                     $displaySub[0].='<b>'.&mt('Part: [_1]',$display_part).'</b>'
                   4870:                                    .' <span class="LC_internal_info">'
1.625     www      4871:                                    .'('.&mt('Response ID: [_1]',$responseId).')'
1.577     bisitz   4872:                                    .'</span>'
                   4873:                                    .' <b>';
1.596     raeburn  4874:                     if ($hidden) {
                   4875:                         $displaySub[0].= &mt('Anonymous Survey').'</b>';
                   4876:                     } else {
1.640     raeburn  4877:                         my ($trial,$rndseed,$newvariation);
                   4878:                         if ($type eq 'randomizetry') {
                   4879:                             $trial = $$record{"$where.$partid.tries"};
                   4880:                             $rndseed = $$record{"$where.$partid.rndseed"};
                   4881:                         }
1.596     raeburn  4882: 		        if ($$record{"$where.$partid.tries"} eq '') {
                   4883: 			    $displaySub[0].=&mt('Trial not counted');
                   4884: 		        } else {
                   4885: 			    $displaySub[0].=&mt('Trial: [_1]',
1.467     albertel 4886: 					    $$record{"$where.$partid.tries"});
1.640     raeburn  4887:                             if ($rndseed || $lastrndseed{$partid}) {
                   4888:                                 if ($rndseed ne $lastrndseed{$partid}) {
                   4889:                                     $newvariation = '&nbsp;('.&mt('New variation this try').')';
                   4890:                                 }
                   4891:                             }
                   4892:                             $lastrndseed{$partid} = $rndseed;
1.596     raeburn  4893: 		        }
                   4894: 		        my $responseType=($isTask ? 'Task'
1.335     albertel 4895:                                               : $responseType->{$partid}->{$responseId});
1.596     raeburn  4896: 		        if (!exists($orders{$partid})) { $orders{$partid}={}; }
1.640     raeburn  4897: 		        if ((!exists($orders{$partid}->{$responseId})) || ($trial)) {
1.596     raeburn  4898: 			    $orders{$partid}->{$responseId}=
                   4899: 			        &get_order($partid,$responseId,$symb,$uname,$udom,
1.640     raeburn  4900:                                            $no_increment,$type,$trial,$rndseed);
1.596     raeburn  4901: 		        }
1.640     raeburn  4902: 		        $displaySub[0].='</b>'.$newvariation.'</span>'; # /nobreak
1.596     raeburn  4903: 		        $displaySub[0].='&nbsp; '.
1.640     raeburn  4904: 			    &cleanRecord($$record{$version.':'.$matchKey},$responseType,$symb,$partid,$responseId,$record,$orders{$partid}->{$responseId},"$version:",$uname,$udom,$type,$trial,$rndseed).'<br />';
1.596     raeburn  4905:                     }
1.147     albertel 4906: 		}
                   4907: 	    }
1.335     albertel 4908: 	    if (exists($$record{"$where.$partid.checkedin"})) {
1.485     albertel 4909: 		$displaySub[1].=&mt('Checked in by [_1] into slot [_2]',
                   4910: 				    $$record{"$where.$partid.checkedin"},
                   4911: 				    $$record{"$where.$partid.checkedin.slot"}).
                   4912: 					'<br />';
1.335     albertel 4913: 	    }
                   4914: 	    if (exists $$record{"$where.$partid.award"}) {
1.485     albertel 4915: 		$displaySub[1].='<b>'.&mt('Part:').'</b>&nbsp;'.$display_part.' &nbsp;'.
1.335     albertel 4916: 		    lc($$record{"$where.$partid.award"}).' '.
                   4917: 		    $mark{$$record{"$where.$partid.solved"}}.
1.147     albertel 4918: 		    '<br />';
                   4919: 	    }
1.335     albertel 4920: 	    if (exists $$record{"$where.$partid.regrader"}) {
                   4921: 		$displaySub[2].=$$record{"$where.$partid.regrader"}.
                   4922: 		    ' (<b>'.&mt('Part').':</b> '.$display_part.')';
                   4923: 	    } elsif ($$record{"$version:resource.$partid.regrader"} =~ /\S/) {
                   4924: 		$displaySub[2].=
                   4925: 		    $$record{"$version:resource.$partid.regrader"}.
1.207     albertel 4926: 		    ' (<b>'.&mt('Part').':</b> '.$display_part.')';
1.147     albertel 4927: 	    }
                   4928: 	}
                   4929: 	# needed because old essay regrader has not parts info
                   4930: 	if (exists $$record{"$version:resource.regrader"}) {
                   4931: 	    $displaySub[2].=$$record{"$version:resource.regrader"};
                   4932: 	}
                   4933: 	$studentTable.='<td>'.$displaySub[0].'&nbsp;</td><td>'.$displaySub[1];
                   4934: 	if ($displaySub[2]) {
1.467     albertel 4935: 	    $studentTable.=&mt('Manually graded by [_1]',$displaySub[2]);
1.147     albertel 4936: 	}
1.467     albertel 4937: 	$studentTable.='&nbsp;</td>'.
                   4938: 	    &Apache::loncommon::end_data_table_row();
1.119     ng       4939:     }
1.467     albertel 4940:     $studentTable.=&Apache::loncommon::end_data_table();
1.119     ng       4941:     return $studentTable;
1.71      ng       4942: }
                   4943: 
                   4944: sub updateGradeByPage {
1.608     www      4945:     my ($request,$symb) = @_;
1.71      ng       4946: 
1.257     albertel 4947:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
                   4948:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
                   4949:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
                   4950:     my $pageTitle = $env{'form.page'};
1.103     albertel 4951:     my ($classlist,undef,$fullname) = &getclasslist($getsec,'1');
1.257     albertel 4952:     my ($uname,$udom) = split(/:/,$env{'form.student'});
                   4953:     my $usec=$classlist->{$env{'form.student'}}[5];
1.103     albertel 4954:     if (!&canmodify($usec)) {
1.526     raeburn  4955: 	$request->print('<span class="LC_warning">'.&mt('Unable to modify requested student ([_1])',$env{'form.student'}).'</span>');
1.103     albertel 4956: 	return;
                   4957:     }
1.398     albertel 4958:     my $result='<h3><span class="LC_info">&nbsp;'.$env{'form.title'}.'</span></h3>';
1.526     raeburn  4959:     $result.='<h3>&nbsp;'.&mt('Student: ').&nameUserString(undef,$env{'form.fullname'},$uname,$udom).
1.129     ng       4960: 	'</h3>'."\n";
1.70      ng       4961: 
1.68      ng       4962:     $request->print($result);
                   4963: 
1.582     raeburn  4964: 
1.132     bowersj2 4965:     my $navmap = Apache::lonnavmaps::navmap->new();
1.582     raeburn  4966:     unless (ref($navmap)) {
                   4967:         $request->print(&navmap_errormsg());
                   4968:         return;
                   4969:     }
1.257     albertel 4970:     my ($mapUrl, $id, $resUrl) = &Apache::lonnet::decode_symb( $env{'form.page'});
1.71      ng       4971:     my $map = $navmap->getResourceByUrl($resUrl); # add to navmaps
1.288     albertel 4972:     if (!$map) {
1.527     raeburn  4973: 	$request->print('<span class="LC_warning">'.&mt('Unable to grade requested sequence ([_1]).',$resUrl).'</span>');
1.288     albertel 4974: 	return; 
                   4975:     }
1.71      ng       4976:     my $iterator = $navmap->getIterator($map->map_start(),
                   4977: 					$map->map_finish());
1.70      ng       4978: 
1.484     albertel 4979:     my $studentTable=
                   4980: 	&Apache::loncommon::start_data_table().
                   4981: 	&Apache::loncommon::start_data_table_header_row().
1.485     albertel 4982: 	'<th align="center">&nbsp;'.&mt('Prob.').'&nbsp;</th>'.
                   4983: 	'<th>&nbsp;'.&mt('Title').'&nbsp;</th>'.
                   4984: 	'<th>&nbsp;'.&mt('Previous Score').'&nbsp;</th>'.
                   4985: 	'<th>&nbsp;'.&mt('New Score').'&nbsp;</th>'.
1.484     albertel 4986: 	&Apache::loncommon::end_data_table_header_row();
1.71      ng       4987: 
                   4988:     $iterator->next(); # skip the first BEGIN_MAP
                   4989:     my $curRes = $iterator->next(); # for "current resource"
1.196     albertel 4990:     my ($depth,$question,$prob,$changeflag)= (1,1,1,0);
1.101     albertel 4991:     while ($depth > 0) {
1.71      ng       4992:         if($curRes == $iterator->BEGIN_MAP) { $depth++; }
1.100     bowersj2 4993:         if($curRes == $iterator->END_MAP) { $depth--; }
1.71      ng       4994: 
1.385     albertel 4995:         if (ref($curRes) && $curRes->is_problem()) {
1.91      albertel 4996: 	    my $parts = $curRes->parts();
1.71      ng       4997:             my $title = $curRes->compTitle();
                   4998: 	    my $symbx = $curRes->symb();
1.484     albertel 4999: 	    $studentTable.=
                   5000: 		&Apache::loncommon::start_data_table_row().
                   5001: 		'<td align="center" valign="top" >'.$prob.
1.485     albertel 5002: 		(scalar(@{$parts}) == 1 ? '' 
1.640     raeburn  5003:                                         : '<br />('.&mt('[quant,_1,part]',scalar(@{$parts}))
1.526     raeburn  5004: 		.')').'</td>';
1.71      ng       5005: 	    $studentTable.='<td valign="top">&nbsp;<b>'.$title.'</b>&nbsp;</td>';
                   5006: 
                   5007: 	    my %newrecord=();
                   5008: 	    my @displayPts=();
1.269     raeburn  5009:             my %aggregate = ();
                   5010:             my $aggregateflag = 0;
1.71      ng       5011: 	    foreach my $partid (@{$parts}) {
1.257     albertel 5012: 		my $newpts = $env{'form.GD_BOX'.$question.'_'.$partid};
                   5013: 		my $oldpts = $env{'form.oldpts'.$question.'_'.$partid};
1.71      ng       5014: 
1.257     albertel 5015: 		my $wgt = $env{'form.WGT'.$question.'_'.$partid} != 0 ? 
                   5016: 		    $env{'form.WGT'.$question.'_'.$partid} : 1;
1.71      ng       5017: 		my $partial = $newpts/$wgt;
                   5018: 		my $score;
                   5019: 		if ($partial > 0) {
                   5020: 		    $score = 'correct_by_override';
1.125     ng       5021: 		} elsif ($newpts ne '') { #empty is taken as 0
1.71      ng       5022: 		    $score = 'incorrect_by_override';
                   5023: 		}
1.257     albertel 5024: 		my $dropMenu = $env{'form.GD_SEL'.$question.'_'.$partid};
1.125     ng       5025: 		if ($dropMenu eq 'excused') {
1.71      ng       5026: 		    $partial = '';
                   5027: 		    $score = 'excused';
1.125     ng       5028: 		} elsif ($dropMenu eq 'reset status'
1.257     albertel 5029: 			 && $env{'form.solved'.$question.'_'.$partid} ne '') { #update only if previous record exists
1.125     ng       5030: 		    $newrecord{'resource.'.$partid.'.tries'} = 0;
                   5031: 		    $newrecord{'resource.'.$partid.'.solved'} = '';
                   5032: 		    $newrecord{'resource.'.$partid.'.award'} = '';
                   5033: 		    $newrecord{'resource.'.$partid.'.awarded'} = 0;
1.257     albertel 5034: 		    $newrecord{'resource.'.$partid.'.regrader'} = "$env{'user.name'}:$env{'user.domain'}";
1.125     ng       5035: 		    $changeflag++;
                   5036: 		    $newpts = '';
1.269     raeburn  5037:                     
                   5038:                     my $aggtries =  $env{'form.aggtries'.$question.'_'.$partid};
                   5039:                     my $totaltries = $env{'form.totaltries'.$question.'_'.$partid};
                   5040:                     my $solvedstatus = $env{'form.solved'.$question.'_'.$partid};
                   5041:                     if ($aggtries > 0) {
                   5042:                         &decrement_aggs($symbx,$partid,\%aggregate,$aggtries,$totaltries,$solvedstatus);
                   5043:                         $aggregateflag = 1;
                   5044:                     }
1.71      ng       5045: 		}
1.324     albertel 5046: 		my $display_part=&get_display_part($partid,$curRes->symb());
1.257     albertel 5047: 		my $oldstatus = $env{'form.solved'.$question.'_'.$partid};
1.526     raeburn  5048: 		$displayPts[0].='&nbsp;<b>'.&mt('Part').':</b> '.$display_part.' = '.
1.71      ng       5049: 		    (($oldstatus eq 'excused') ? 'excused' : $oldpts).
1.326     albertel 5050: 		    '&nbsp;<br />';
1.526     raeburn  5051: 		$displayPts[1].='&nbsp;<b>'.&mt('Part').':</b> '.$display_part.' = '.
1.125     ng       5052: 		     (($score eq 'excused') ? 'excused' : $newpts).
1.326     albertel 5053: 		    '&nbsp;<br />';
1.71      ng       5054: 		$question++;
1.380     albertel 5055: 		next if ($dropMenu eq 'reset status' || ($newpts eq $oldpts && $score ne 'excused'));
1.125     ng       5056: 
1.71      ng       5057: 		$newrecord{'resource.'.$partid.'.awarded'}  = $partial if $partial ne '';
1.125     ng       5058: 		$newrecord{'resource.'.$partid.'.solved'}   = $score if $score ne '';
1.257     albertel 5059: 		$newrecord{'resource.'.$partid.'.regrader'} = "$env{'user.name'}:$env{'user.domain'}"
1.125     ng       5060: 		    if (scalar(keys(%newrecord)) > 0);
1.71      ng       5061: 
                   5062: 		$changeflag++;
                   5063: 	    }
                   5064: 	    if (scalar(keys(%newrecord)) > 0) {
1.382     albertel 5065: 		my %record = 
                   5066: 		    &Apache::lonnet::restore($symbx,$env{'request.course.id'},
                   5067: 					     $udom,$uname);
                   5068: 
                   5069: 		if (&Apache::lonnet::validCODE($env{'form.CODE'})) {
                   5070: 		    $newrecord{'resource.CODE'} = $env{'form.CODE'};
                   5071: 		} elsif (&Apache::lonnet::validCODE($record{'resource.CODE'})) {
                   5072: 		    $newrecord{'resource.CODE'} = '';
                   5073: 		}
1.257     albertel 5074: 		&Apache::lonnet::cstore(\%newrecord,$symbx,$env{'request.course.id'},
1.71      ng       5075: 					$udom,$uname);
1.382     albertel 5076: 		%record = &Apache::lonnet::restore($symbx,
                   5077: 						   $env{'request.course.id'},
                   5078: 						   $udom,$uname);
1.380     albertel 5079: 		&check_and_remove_from_queue($parts,\%record,undef,$symbx,
                   5080: 					     $cdom,$cnum,$udom,$uname);
1.71      ng       5081: 	    }
1.380     albertel 5082: 	    
1.269     raeburn  5083:             if ($aggregateflag) {
                   5084:                 &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
                   5085:                       $env{'course.'.$env{'request.course.id'}.'.domain'},
                   5086:                       $env{'course.'.$env{'request.course.id'}.'.num'});
                   5087:             }
1.125     ng       5088: 
1.71      ng       5089: 	    $studentTable.='<td valign="top">'.$displayPts[0].'</td>'.
                   5090: 		'<td valign="top">'.$displayPts[1].'</td>'.
1.484     albertel 5091: 		&Apache::loncommon::end_data_table_row();
1.68      ng       5092: 
1.196     albertel 5093: 	    $prob++;
1.68      ng       5094: 	}
1.71      ng       5095:         $curRes = $iterator->next();
1.68      ng       5096:     }
1.98      albertel 5097: 
1.484     albertel 5098:     $studentTable.=&Apache::loncommon::end_data_table();
1.526     raeburn  5099:     my $grademsg=($changeflag == 0 ? &mt('No score was changed or updated.') :
                   5100: 		  &mt('The scores were changed for [quant,_1,problem].',
                   5101: 		  $changeflag));
1.76      ng       5102:     $request->print($grademsg.$studentTable);
1.68      ng       5103: 
1.70      ng       5104:     return '';
                   5105: }
                   5106: 
1.72      ng       5107: #-------- end of section for handling grading by page/sequence ---------
                   5108: #
                   5109: #-------------------------------------------------------------------
                   5110: 
1.581     www      5111: #-------------------- Bubblesheet (Scantron) Grading -------------------
1.75      albertel 5112: #
                   5113: #------ start of section for handling grading by page/sequence ---------
                   5114: 
1.423     albertel 5115: =pod
                   5116: 
                   5117: =head1 Bubble sheet grading routines
                   5118: 
1.424     albertel 5119:   For this documentation:
                   5120: 
                   5121:    'scanline' refers to the full line of characters
                   5122:    from the file that we are parsing that represents one entire sheet
                   5123: 
                   5124:    'bubble line' refers to the data
1.659     raeburn  5125:    representing the line of bubbles that are on the physical bubblesheet
1.424     albertel 5126: 
                   5127: 
1.659     raeburn  5128: The overall process is that a scanned in bubblesheet data is uploaded
1.424     albertel 5129: into a course. When a user wants to grade, they select a
1.659     raeburn  5130: sequence/folder of resources, a file of bubblesheet info, and pick
1.424     albertel 5131: one of the predefined configurations for what each scanline looks
                   5132: like.
                   5133: 
                   5134: Next each scanline is checked for any errors of either 'missing
1.435     foxr     5135: bubbles' (it's an error because it may have been mis-scanned
1.424     albertel 5136: because too light bubbling), 'double bubble' (each bubble line should
1.703     bisitz   5137: have no more than one letter picked), invalid or duplicated CODE,
1.556     weissno  5138: invalid student/employee ID
1.424     albertel 5139: 
                   5140: If the CODE option is used that determines the randomization of the
1.556     weissno  5141: homework problems, either way the student/employee ID is looked up into a
1.424     albertel 5142: username:domain.
                   5143: 
                   5144: During the validation phase the instructor can choose to skip scanlines. 
                   5145: 
1.659     raeburn  5146: After the validation phase, there are now 3 bubblesheet files
1.424     albertel 5147: 
                   5148:   scantron_original_filename (unmodified original file)
                   5149:   scantron_corrected_filename (file where the corrected information has replaced the original information)
                   5150:   scantron_skipped_filename (contains the exact text of scanlines that where skipped)
                   5151: 
                   5152: Also there is a separate hash nohist_scantrondata that contains extra
1.659     raeburn  5153: correction information that isn't representable in the bubblesheet
1.424     albertel 5154: file (see &scantron_getfile() for more information)
                   5155: 
                   5156: After all scanlines are either valid, marked as valid or skipped, then
                   5157: foreach line foreach problem in the picked sequence, an ssi request is
                   5158: made that simulates a user submitting their selected letter(s) against
                   5159: the homework problem.
1.423     albertel 5160: 
                   5161: =over 4
                   5162: 
                   5163: 
                   5164: 
                   5165: =item defaultFormData
                   5166: 
                   5167:   Returns html hidden inputs used to hold context/default values.
                   5168: 
                   5169:  Arguments:
                   5170:   $symb - $symb of the current resource 
                   5171: 
                   5172: =cut
1.422     foxr     5173: 
1.81      albertel 5174: sub defaultFormData {
1.324     albertel 5175:     my ($symb)=@_;
1.613     www      5176:     return '<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />';
1.81      albertel 5177: }
                   5178: 
1.447     foxr     5179: 
1.423     albertel 5180: =pod 
                   5181: 
                   5182: =item getSequenceDropDown
                   5183: 
                   5184:    Return html dropdown of possible sequences to grade
                   5185:  
                   5186:  Arguments:
1.582     raeburn  5187:    $symb - $symb of the current resource
                   5188:    $map_error - ref to scalar which will container error if
                   5189:                 $navmap object is unavailable in &getSymbMap().
1.423     albertel 5190: 
                   5191: =cut
1.422     foxr     5192: 
1.75      albertel 5193: sub getSequenceDropDown {
1.582     raeburn  5194:     my ($symb,$map_error)=@_;
1.75      albertel 5195:     my $result='<select name="selectpage">'."\n";
1.582     raeburn  5196:     my ($titles,$symbx) = &getSymbMap($map_error);
                   5197:     if (ref($map_error)) {
                   5198:         return if ($$map_error);
                   5199:     }
1.137     albertel 5200:     my ($curpage)=&Apache::lonnet::decode_symb($symb); 
1.75      albertel 5201:     my $ctr=0;
                   5202:     foreach (@$titles) {
                   5203: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
                   5204: 	$result.='<option value="'.$$symbx{$_}.'" '.
1.401     albertel 5205: 	    ($$symbx{$_} =~ /$curpage$/ ? 'selected="selected"' : '').
1.75      albertel 5206: 	    '>'.$showtitle.'</option>'."\n";
                   5207: 	$ctr++;
                   5208:     }
                   5209:     $result.= '</select>';
                   5210:     return $result;
                   5211: }
                   5212: 
1.495     albertel 5213: my %bubble_lines_per_response;     # no. bubble lines for each response.
1.554     raeburn  5214:                                    # key is zero-based index - 0, 1, 2 ...
1.495     albertel 5215: 
                   5216: my %first_bubble_line;             # First bubble line no. for each bubble.
                   5217: 
1.509     raeburn  5218: my %subdivided_bubble_lines;       # no. bubble lines for optionresponse, 
                   5219:                                    # matchresponse or rankresponse, where 
                   5220:                                    # an individual response can have multiple 
                   5221:                                    # lines
1.503     raeburn  5222: 
                   5223: my %responsetype_per_response;     # responsetype for each response
                   5224: 
1.691     raeburn  5225: my %masterseq_id_responsenum;      # src_id (e.g., 12.3_0.11 etc.) for each
                   5226:                                    # numbered response. Needed when randomorder
                   5227:                                    # or randompick are in use. Key is ID, value 
                   5228:                                    # is response number.
                   5229: 
1.495     albertel 5230: # Save and restore the bubble lines array to the form env.
                   5231: 
                   5232: 
                   5233: sub save_bubble_lines {
                   5234:     foreach my $line (keys(%bubble_lines_per_response)) {
                   5235: 	$env{"form.scantron.bubblelines.$line"}  = $bubble_lines_per_response{$line};
                   5236: 	$env{"form.scantron.first_bubble_line.$line"} =
                   5237: 	    $first_bubble_line{$line};
1.503     raeburn  5238:         $env{"form.scantron.sub_bubblelines.$line"} = 
                   5239:             $subdivided_bubble_lines{$line};
                   5240:         $env{"form.scantron.responsetype.$line"} =
                   5241:             $responsetype_per_response{$line};
1.495     albertel 5242:     }
1.691     raeburn  5243:     foreach my $resid (keys(%masterseq_id_responsenum)) {
                   5244:         my $line = $masterseq_id_responsenum{$resid};
                   5245:         $env{"form.scantron.residpart.$line"} = $resid;
                   5246:     }
1.495     albertel 5247: }
                   5248: 
                   5249: 
                   5250: sub restore_bubble_lines {
                   5251:     my $line = 0;
                   5252:     %bubble_lines_per_response = ();
1.691     raeburn  5253:     %masterseq_id_responsenum = ();
1.495     albertel 5254:     while ($env{"form.scantron.bubblelines.$line"}) {
                   5255: 	my $value = $env{"form.scantron.bubblelines.$line"};
                   5256: 	$bubble_lines_per_response{$line} = $value;
                   5257: 	$first_bubble_line{$line}  =
                   5258: 	    $env{"form.scantron.first_bubble_line.$line"};
1.503     raeburn  5259:         $subdivided_bubble_lines{$line} =
                   5260:             $env{"form.scantron.sub_bubblelines.$line"};
                   5261:         $responsetype_per_response{$line} =
                   5262:             $env{"form.scantron.responsetype.$line"};
1.691     raeburn  5263:         my $id = $env{"form.scantron.residpart.$line"};
                   5264:         $masterseq_id_responsenum{$id} = $line;
1.495     albertel 5265: 	$line++;
                   5266:     }
                   5267: }
                   5268: 
1.423     albertel 5269: =pod 
                   5270: 
                   5271: =item scantron_filenames
                   5272: 
                   5273:    Returns a list of the scantron files in the current course 
                   5274: 
                   5275: =cut
1.422     foxr     5276: 
1.202     albertel 5277: sub scantron_filenames {
1.257     albertel 5278:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   5279:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
1.517     raeburn  5280:     my $getpropath = 1;
1.662     raeburn  5281:     my ($dirlist,$listerror) = &Apache::lonnet::dirlist('userfiles',$cdom,
                   5282:                                                         $cname,$getpropath);
1.202     albertel 5283:     my @possiblenames;
1.662     raeburn  5284:     if (ref($dirlist) eq 'ARRAY') {
                   5285:         foreach my $filename (sort(@{$dirlist})) {
                   5286: 	    ($filename)=split(/&/,$filename);
                   5287: 	    if ($filename!~/^scantron_orig_/) { next ; }
                   5288: 	    $filename=~s/^scantron_orig_//;
                   5289: 	    push(@possiblenames,$filename);
                   5290:         }
1.202     albertel 5291:     }
                   5292:     return @possiblenames;
                   5293: }
                   5294: 
1.423     albertel 5295: =pod 
                   5296: 
                   5297: =item scantron_uploads
                   5298: 
                   5299:    Returns  html drop-down list of scantron files in current course.
                   5300: 
                   5301:  Arguments:
                   5302:    $file2grade - filename to set as selected in the dropdown
                   5303: 
                   5304: =cut
1.422     foxr     5305: 
1.202     albertel 5306: sub scantron_uploads {
1.209     ng       5307:     my ($file2grade) = @_;
1.202     albertel 5308:     my $result=	'<select name="scantron_selectfile">';
                   5309:     $result.="<option></option>";
                   5310:     foreach my $filename (sort(&scantron_filenames())) {
1.401     albertel 5311: 	$result.="<option".($filename eq $file2grade ? ' selected="selected"':'').">$filename</option>\n";
1.81      albertel 5312:     }
                   5313:     $result.="</select>";
                   5314:     return $result;
                   5315: }
                   5316: 
1.423     albertel 5317: =pod 
                   5318: 
                   5319: =item scantron_scantab
                   5320: 
                   5321:   Returns html drop down of the scantron formats in the scantronformat.tab
                   5322:   file.
                   5323: 
                   5324: =cut
1.422     foxr     5325: 
1.82      albertel 5326: sub scantron_scantab {
                   5327:     my $result='<select name="scantron_format">'."\n";
1.191     albertel 5328:     $result.='<option></option>'."\n";
1.518     raeburn  5329:     my @lines = &get_scantronformat_file();
                   5330:     if (@lines > 0) {
                   5331:         foreach my $line (@lines) {
                   5332:             next if (($line =~ /^\#/) || ($line eq ''));
                   5333: 	    my ($name,$descrip)=split(/:/,$line);
                   5334: 	    $result.='<option value="'.$name.'">'.$descrip.'</option>'."\n";
                   5335:         }
1.82      albertel 5336:     }
                   5337:     $result.='</select>'."\n";
1.518     raeburn  5338:     return $result;
                   5339: }
                   5340: 
                   5341: =pod
                   5342: 
                   5343: =item get_scantronformat_file
                   5344: 
                   5345:   Returns an array containing lines from the scantron format file for
                   5346:   the domain of the course.
                   5347: 
                   5348:   If a url for a custom.tab file is listed in domain's configuration.db, 
                   5349:   lines are from this file.
                   5350: 
                   5351:   Otherwise, if a default.tab has been published in RES space by the 
                   5352:   domainconfig user, lines are from this file.
                   5353: 
                   5354:   Otherwise, fall back to getting lines from the legacy file on the
1.519     raeburn  5355:   local server:  /home/httpd/lonTabs/default_scantronformat.tab    
1.82      albertel 5356: 
1.518     raeburn  5357: =cut
                   5358: 
                   5359: sub get_scantronformat_file {
                   5360:     my $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
                   5361:     my %domconfig = &Apache::lonnet::get_dom('configuration',['scantron'],$cdom);
                   5362:     my $gottab = 0;
                   5363:     my @lines;
                   5364:     if (ref($domconfig{'scantron'}) eq 'HASH') {
                   5365:         if ($domconfig{'scantron'}{'scantronformat'} ne '') {
                   5366:             my $formatfile = &Apache::lonnet::getfile($Apache::lonnet::perlvar{'lonDocRoot'}.$domconfig{'scantron'}{'scantronformat'});
                   5367:             if ($formatfile ne '-1') {
                   5368:                 @lines = split("\n",$formatfile,-1);
                   5369:                 $gottab = 1;
                   5370:             }
                   5371:         }
                   5372:     }
                   5373:     if (!$gottab) {
                   5374:         my $confname = $cdom.'-domainconfig';
                   5375:         my $default = $Apache::lonnet::perlvar{'lonDocRoot'}.'/res/'.$cdom.'/'.$confname.'/default.tab';
                   5376:         my $formatfile =  &Apache::lonnet::getfile($default);
                   5377:         if ($formatfile ne '-1') {
                   5378:             @lines = split("\n",$formatfile,-1);
                   5379:             $gottab = 1;
                   5380:         }
                   5381:     }
                   5382:     if (!$gottab) {
1.519     raeburn  5383:         my @domains = &Apache::lonnet::current_machine_domains();
                   5384:         if (grep(/^\Q$cdom\E$/,@domains)) {
                   5385:             my $fh=Apache::File->new($Apache::lonnet::perlvar{'lonTabDir'}.'/scantronformat.tab');
                   5386:             @lines = <$fh>;
                   5387:             close($fh);
                   5388:         } else {
                   5389:             my $fh=Apache::File->new($Apache::lonnet::perlvar{'lonTabDir'}.'/default_scantronformat.tab');
                   5390:             @lines = <$fh>;
                   5391:             close($fh);
                   5392:         }
1.518     raeburn  5393:     }
                   5394:     return @lines;
1.82      albertel 5395: }
                   5396: 
1.423     albertel 5397: =pod 
                   5398: 
                   5399: =item scantron_CODElist
                   5400: 
                   5401:   Returns html drop down of the saved CODE lists from current course,
                   5402:   generated from earlier printings.
                   5403: 
                   5404: =cut
1.422     foxr     5405: 
1.186     albertel 5406: sub scantron_CODElist {
1.257     albertel 5407:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   5408:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
1.186     albertel 5409:     my @names=&Apache::lonnet::getkeys('CODEs',$cdom,$cnum);
                   5410:     my $namechoice='<option></option>';
1.225     albertel 5411:     foreach my $name (sort {uc($a) cmp uc($b)} @names) {
1.191     albertel 5412: 	if ($name =~ /^error: 2 /) { next; }
1.278     albertel 5413: 	if ($name =~ /^type\0/) { next; }
1.186     albertel 5414: 	$namechoice.='<option value="'.$name.'">'.$name.'</option>';
                   5415:     }
                   5416:     $namechoice='<select name="scantron_CODElist">'.$namechoice.'</select>';
                   5417:     return $namechoice;
                   5418: }
                   5419: 
1.423     albertel 5420: =pod 
                   5421: 
                   5422: =item scantron_CODEunique
                   5423: 
                   5424:   Returns the html for "Each CODE to be used once" radio.
                   5425: 
                   5426: =cut
1.422     foxr     5427: 
1.186     albertel 5428: sub scantron_CODEunique {
1.532     bisitz   5429:     my $result='<span class="LC_nobreak">
1.272     albertel 5430:                  <label><input type="radio" name="scantron_CODEunique"
1.423     albertel 5431:                         value="yes" checked="checked" />'.&mt('Yes').' </label>
1.381     albertel 5432:                 </span>
1.532     bisitz   5433:                 <span class="LC_nobreak">
1.272     albertel 5434:                  <label><input type="radio" name="scantron_CODEunique"
1.423     albertel 5435:                         value="no" />'.&mt('No').' </label>
1.381     albertel 5436:                 </span>';
1.186     albertel 5437:     return $result;
                   5438: }
1.423     albertel 5439: 
                   5440: =pod 
                   5441: 
                   5442: =item scantron_selectphase
                   5443: 
1.659     raeburn  5444:   Generates the initial screen to start the bubblesheet process.
1.423     albertel 5445:   Allows for - starting a grading run.
1.424     albertel 5446:              - downloading existing scan data (original, corrected
1.423     albertel 5447:                                                 or skipped info)
                   5448: 
                   5449:              - uploading new scan data
                   5450: 
                   5451:  Arguments:
                   5452:   $r          - The Apache request object
                   5453:   $file2grade - name of the file that contain the scanned data to score
                   5454: 
                   5455: =cut
1.186     albertel 5456: 
1.75      albertel 5457: sub scantron_selectphase {
1.608     www      5458:     my ($r,$file2grade,$symb) = @_;
1.75      albertel 5459:     if (!$symb) {return '';}
1.582     raeburn  5460:     my $map_error;
                   5461:     my $sequence_selector=&getSequenceDropDown($symb,\$map_error);
                   5462:     if ($map_error) {
                   5463:         $r->print('<br />'.&navmap_errormsg().'<br />');
                   5464:         return;
                   5465:     }
1.324     albertel 5466:     my $default_form_data=&defaultFormData($symb);
1.209     ng       5467:     my $file_selector=&scantron_uploads($file2grade);
1.82      albertel 5468:     my $format_selector=&scantron_scantab();
1.186     albertel 5469:     my $CODE_selector=&scantron_CODElist();
                   5470:     my $CODE_unique=&scantron_CODEunique();
1.75      albertel 5471:     my $result;
1.422     foxr     5472: 
1.513     foxr     5473:     $ssi_error = 0;
                   5474: 
1.606     wenzelju 5475:     if (&Apache::lonnet::allowed('usc',$env{'request.role.domain'}) ||
                   5476:         &Apache::lonnet::allowed('usc',$env{'request.course.id'})) {
                   5477: 
                   5478: 	# Chunk of form to prompt for a scantron file upload.
                   5479: 
                   5480:         $r->print('
                   5481:     <br />
                   5482:     '.&Apache::loncommon::start_data_table('LC_scantron_action').'
                   5483:        '.&Apache::loncommon::start_data_table_header_row().'
                   5484:             <th>
                   5485:               &nbsp;'.&mt('Specify a bubblesheet data file to upload.').'
                   5486:             </th>
                   5487:        '.&Apache::loncommon::end_data_table_header_row().'
                   5488:        '.&Apache::loncommon::start_data_table_row().'
                   5489:             <td>
                   5490: ');
1.608     www      5491:     my $default_form_data=&defaultFormData($symb);
1.606     wenzelju 5492:     my $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
                   5493:     my $cnum= $env{'course.'.$env{'request.course.id'}.'.num'};
                   5494:     $r->print(&Apache::lonhtmlcommon::scripttag('
                   5495:     function checkUpload(formname) {
                   5496: 	if (formname.upfile.value == "") {
                   5497: 	    alert("'.&mt('Please use the browse button to select a file from your local directory.').'");
                   5498: 	    return false;
                   5499: 	}
                   5500: 	formname.submit();
                   5501:     }'));
                   5502:     $r->print('
                   5503:               <form enctype="multipart/form-data" action="/adm/grades" name="rules" method="post">
                   5504:                 '.$default_form_data.'
                   5505:                 <input name="courseid" type="hidden" value="'.$cnum.'" />
                   5506:                 <input name="domainid" type="hidden" value="'.$cdom.'" />
                   5507:                 <input name="command" value="scantronupload_save" type="hidden" />
                   5508:                 '.&mt('File to upload: [_1]','<input type="file" name="upfile" size="50" />').'
                   5509:                 <br />
                   5510:                 <input type="button" onclick="javascript:checkUpload(this.form);" value="'.&mt('Upload Bubblesheet Data').'" />
                   5511:               </form>
                   5512: ');
                   5513: 
                   5514:         $r->print('
                   5515:             </td>
                   5516:        '.&Apache::loncommon::end_data_table_row().'
                   5517:        '.&Apache::loncommon::end_data_table().'
                   5518: ');
                   5519:     }
                   5520: 
1.422     foxr     5521:     # Chunk of form to prompt for a file to grade and how:
                   5522: 
1.489     albertel 5523:     $result.= '
                   5524:     <br />
                   5525:     <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantron_process">
                   5526:     <input type="hidden" name="command" value="scantron_warning" />
                   5527:     '.$default_form_data.'
                   5528:     '.&Apache::loncommon::start_data_table('LC_scantron_action').'
                   5529:        '.&Apache::loncommon::start_data_table_header_row().'
                   5530:             <th colspan="2">
1.492     albertel 5531:               &nbsp;'.&mt('Specify file and which Folder/Sequence to grade').'
1.489     albertel 5532:             </th>
                   5533:        '.&Apache::loncommon::end_data_table_header_row().'
                   5534:        '.&Apache::loncommon::start_data_table_row().'
1.492     albertel 5535:             <td> '.&mt('Sequence to grade:').' </td><td> '.$sequence_selector.' </td>
1.489     albertel 5536:        '.&Apache::loncommon::end_data_table_row().'
                   5537:        '.&Apache::loncommon::start_data_table_row().'
1.572     www      5538:             <td> '.&mt('Filename of bubblesheet data file:').' </td><td> '.$file_selector.' </td>
1.489     albertel 5539:        '.&Apache::loncommon::end_data_table_row().'
                   5540:        '.&Apache::loncommon::start_data_table_row().'
1.572     www      5541:             <td> '.&mt('Format of bubblesheet data file:').' </td><td> '.$format_selector.' </td>
1.489     albertel 5542:        '.&Apache::loncommon::end_data_table_row().'
                   5543:        '.&Apache::loncommon::start_data_table_row().'
1.492     albertel 5544:             <td> '.&mt('Saved CODEs to validate against:').' </td><td> '.$CODE_selector.' </td>
1.489     albertel 5545:        '.&Apache::loncommon::end_data_table_row().'
                   5546:        '.&Apache::loncommon::start_data_table_row().'
1.492     albertel 5547:             <td> '.&mt('Each CODE is only to be used once:').'</td><td> '.$CODE_unique.' </td>
1.489     albertel 5548:        '.&Apache::loncommon::end_data_table_row().'
                   5549:        '.&Apache::loncommon::start_data_table_row().'
1.492     albertel 5550: 	    <td> '.&mt('Options:').' </td>
1.187     albertel 5551:             <td>
1.492     albertel 5552: 	       <label><input type="checkbox" name="scantron_options_redo" value="redo_skipped"/> '.&mt('Do only previously skipped records').'</label> <br />
                   5553:                <label><input type="checkbox" name="scantron_options_ignore" value="ignore_corrections"/> '.&mt('Remove all existing corrections').'</label> <br />
                   5554:                <label><input type="checkbox" name="scantron_options_hidden" value="ignore_hidden"/> '.&mt('Skip hidden resources when grading').'</label>
1.187     albertel 5555: 	    </td>
1.489     albertel 5556:        '.&Apache::loncommon::end_data_table_row().'
                   5557:        '.&Apache::loncommon::start_data_table_row().'
1.174     albertel 5558:             <td colspan="2">
1.572     www      5559:               <input type="submit" value="'.&mt('Grading: Validate Bubblesheet Records').'" />
1.162     albertel 5560:             </td>
1.489     albertel 5561:        '.&Apache::loncommon::end_data_table_row().'
                   5562:     '.&Apache::loncommon::end_data_table().'
                   5563:     </form>
                   5564: ';
1.162     albertel 5565:    
                   5566:     $r->print($result);
                   5567: 
1.422     foxr     5568: 
                   5569: 
                   5570:     # Chunk of the form that prompts to view a scoring office file,
                   5571:     # corrected file, skipped records in a file.
                   5572: 
1.489     albertel 5573:     $r->print('
                   5574:    <br />
                   5575:    <form action="/adm/grades" name="scantron_download">
                   5576:      '.$default_form_data.'
                   5577:      <input type="hidden" name="command" value="scantron_download" />
                   5578:      '.&Apache::loncommon::start_data_table('LC_scantron_action').'
                   5579:        '.&Apache::loncommon::start_data_table_header_row().'
                   5580:               <th>
1.492     albertel 5581:                 &nbsp;'.&mt('Download a scoring office file').'
1.489     albertel 5582:               </th>
                   5583:        '.&Apache::loncommon::end_data_table_header_row().'
                   5584:        '.&Apache::loncommon::start_data_table_row().'
1.492     albertel 5585:               <td> '.&mt('Filename of scoring office file: [_1]',$file_selector).' 
1.489     albertel 5586:                 <br />
1.492     albertel 5587:                 <input type="submit" value="'.&mt('Download: Show List of Associated Files').'" />
1.489     albertel 5588:        '.&Apache::loncommon::end_data_table_row().'
                   5589:      '.&Apache::loncommon::end_data_table().'
                   5590:    </form>
                   5591:    <br />
                   5592: ');
1.162     albertel 5593: 
1.457     banghart 5594:     &Apache::lonpickcode::code_list($r,2);
1.523     raeburn  5595: 
1.694     bisitz   5596:     $r->print('<br /><form method="post" name="checkscantron" action="">'.
1.523     raeburn  5597:              $default_form_data."\n".
                   5598:              &Apache::loncommon::start_data_table('LC_scantron_action')."\n".
                   5599:              &Apache::loncommon::start_data_table_header_row()."\n".
                   5600:              '<th colspan="2">
1.572     www      5601:               &nbsp;'.&mt('Review bubblesheet data and submissions for a previously graded folder/sequence')."\n".
1.523     raeburn  5602:              '</th>'."\n".
                   5603:               &Apache::loncommon::end_data_table_header_row()."\n".
                   5604:               &Apache::loncommon::start_data_table_row()."\n".
                   5605:               '<td> '.&mt('Graded folder/sequence:').' </td>'."\n".
                   5606:               '<td> '.$sequence_selector.' </td>'.
                   5607:               &Apache::loncommon::end_data_table_row()."\n".
                   5608:               &Apache::loncommon::start_data_table_row()."\n".
                   5609:               '<td> '.&mt('Filename of scoring office file:').' </td>'."\n".
                   5610:               '<td> '.$file_selector.' </td>'."\n".
                   5611:               &Apache::loncommon::end_data_table_row()."\n".
                   5612:               &Apache::loncommon::start_data_table_row()."\n".
                   5613:               '<td> '.&mt('Format of data file:').' </td>'."\n".
                   5614:               '<td> '.$format_selector.' </td>'."\n".
                   5615:               &Apache::loncommon::end_data_table_row()."\n".
                   5616:               &Apache::loncommon::start_data_table_row()."\n".
1.557     raeburn  5617:               '<td> '.&mt('Options').' </td>'."\n".
                   5618:               '<td> <label><input type="checkbox" name="scantron_options_hidden" value="ignore_hidden"/> '.&mt('Skip hidden resources').'</label></td>'.
                   5619:               &Apache::loncommon::end_data_table_row()."\n".
                   5620:               &Apache::loncommon::start_data_table_row()."\n".
1.523     raeburn  5621:               '<td colspan="2">'."\n".
                   5622:               '<input type="hidden" name="command" value="checksubmissions" />'."\n".
1.575     www      5623:               '<input type="submit" value="'.&mt('Review Bubblesheet Data and Submission Records').'" />'."\n".
1.523     raeburn  5624:               '</td>'."\n".
                   5625:               &Apache::loncommon::end_data_table_row()."\n".
                   5626:               &Apache::loncommon::end_data_table()."\n".
                   5627:               '</form><br />');
                   5628:     return;
1.75      albertel 5629: }
                   5630: 
1.423     albertel 5631: =pod
                   5632: 
                   5633: =item get_scantron_config
                   5634: 
1.711     bisitz   5635:    Parse and return the bubblesheet configuration line selected as a
1.423     albertel 5636:    hash of configuration file fields.
                   5637: 
                   5638:  Arguments:
                   5639:     which - the name of the configuration to parse from the file.
                   5640: 
                   5641: 
                   5642:  Returns:
                   5643:             If the named configuration is not in the file, an empty
                   5644:             hash is returned.
                   5645:     a hash with the fields
                   5646:       name         - internal name for the this configuration setup
                   5647:       description  - text to display to operator that describes this config
                   5648:       CODElocation - if 0 or the string 'none'
                   5649:                           - no CODE exists for this config
                   5650:                      if -1 || the string 'letter'
                   5651:                           - a CODE exists for this config and is
                   5652:                             a string of letters
                   5653:                      Unsupported value (but planned for future support)
                   5654:                           if a positive integer
                   5655:                                - The CODE exists as the first n items from
                   5656:                                  the question section of the form
                   5657:                           if the string 'number'
                   5658:                                - The CODE exists for this config and is
                   5659:                                  a string of numbers
                   5660:       CODEstart   - (only matter if a CODE exists) column in the line where
                   5661:                      the CODE starts
                   5662:       CODElength  - length of the CODE
1.573     bisitz   5663:       IDstart     - column where the student/employee ID starts
1.556     weissno  5664:       IDlength    - length of the student/employee ID info
1.423     albertel 5665:       Qstart      - column where the information from the bubbled
                   5666:                     'questions' start
                   5667:       Qlength     - number of columns comprising a single bubble line from
                   5668:                     the sheet. (usually either 1 or 10)
1.424     albertel 5669:       Qon         - either a single character representing the character used
1.423     albertel 5670:                     to signal a bubble was chosen in the positional setup, or
                   5671:                     the string 'letter' if the letter of the chosen bubble is
                   5672:                     in the final, or 'number' if a number representing the
                   5673:                     chosen bubble is in the file (1->A 0->J)
1.424     albertel 5674:       Qoff        - the character used to represent that a bubble was
                   5675:                     left blank
1.423     albertel 5676:       PaperID     - if the scanning process generates a unique number for each
                   5677:                     sheet scanned the column that this ID number starts in
                   5678:       PaperIDlength - number of columns that comprise the unique ID number
                   5679:                       for the sheet of paper
1.424     albertel 5680:       FirstName   - column that the first name starts in
1.423     albertel 5681:       FirstNameLength - number of columns that the first name spans
                   5682:  
                   5683:       LastName    - column that the last name starts in
                   5684:       LastNameLength - number of columns that the last name spans
1.649     raeburn  5685:       BubblesPerRow - number of bubbles available in each row used to 
                   5686:                       bubble an answer. (If not specified, 10 assumed).
1.671     raeburn  5687: 
1.423     albertel 5688: =cut
1.422     foxr     5689: 
1.82      albertel 5690: sub get_scantron_config {
                   5691:     my ($which) = @_;
1.518     raeburn  5692:     my @lines = &get_scantronformat_file();
1.82      albertel 5693:     my %config;
1.157     albertel 5694:     #FIXME probably should move to XML it has already gotten a bit much now
1.518     raeburn  5695:     foreach my $line (@lines) {
1.82      albertel 5696: 	my ($name,$descrip)=split(/:/,$line);
                   5697: 	if ($name ne $which ) { next; }
                   5698: 	chomp($line);
                   5699: 	my @config=split(/:/,$line);
                   5700: 	$config{'name'}=$config[0];
                   5701: 	$config{'description'}=$config[1];
                   5702: 	$config{'CODElocation'}=$config[2];
                   5703: 	$config{'CODEstart'}=$config[3];
                   5704: 	$config{'CODElength'}=$config[4];
                   5705: 	$config{'IDstart'}=$config[5];
                   5706: 	$config{'IDlength'}=$config[6];
                   5707: 	$config{'Qstart'}=$config[7];
1.497     foxr     5708:  	$config{'Qlength'}=$config[8];
1.82      albertel 5709: 	$config{'Qoff'}=$config[9];
                   5710: 	$config{'Qon'}=$config[10];
1.157     albertel 5711: 	$config{'PaperID'}=$config[11];
                   5712: 	$config{'PaperIDlength'}=$config[12];
                   5713: 	$config{'FirstName'}=$config[13];
                   5714: 	$config{'FirstNamelength'}=$config[14];
                   5715: 	$config{'LastName'}=$config[15];
                   5716: 	$config{'LastNamelength'}=$config[16];
1.649     raeburn  5717:         $config{'BubblesPerRow'}=$config[17];
1.82      albertel 5718: 	last;
                   5719:     }
                   5720:     return %config;
                   5721: }
                   5722: 
1.423     albertel 5723: =pod 
                   5724: 
                   5725: =item username_to_idmap
                   5726: 
1.556     weissno  5727:     creates a hash keyed by student/employee ID with values of the corresponding
1.423     albertel 5728:     student username:domain.
                   5729: 
                   5730:   Arguments:
                   5731: 
                   5732:     $classlist - reference to the class list hash. This is a hash
                   5733:                  keyed by student name:domain  whose elements are references
1.424     albertel 5734:                  to arrays containing various chunks of information
1.423     albertel 5735:                  about the student. (See loncoursedata for more info).
                   5736: 
                   5737:   Returns
                   5738:     %idmap - the constructed hash
                   5739: 
                   5740: =cut
                   5741: 
1.82      albertel 5742: sub username_to_idmap {
                   5743:     my ($classlist)= @_;
                   5744:     my %idmap;
                   5745:     foreach my $student (keys(%$classlist)) {
                   5746: 	$idmap{$classlist->{$student}->[&Apache::loncoursedata::CL_ID]}=
                   5747: 	    $student;
                   5748:     }
                   5749:     return %idmap;
                   5750: }
1.423     albertel 5751: 
                   5752: =pod
                   5753: 
1.424     albertel 5754: =item scantron_fixup_scanline
1.423     albertel 5755: 
                   5756:    Process a requested correction to a scanline.
                   5757: 
                   5758:   Arguments:
                   5759:     $scantron_config   - hash from &get_scantron_config()
                   5760:     $scan_data         - hash of correction information 
                   5761:                           (see &scantron_getfile())
                   5762:     $line              - existing scanline
                   5763:     $whichline         - line number of the passed in scanline
                   5764:     $field             - type of change to process 
                   5765:                          (either 
1.573     bisitz   5766:                           'ID'     -> correct the student/employee ID
1.423     albertel 5767:                           'CODE'   -> correct the CODE
                   5768:                           'answer' -> fixup the submitted answers)
                   5769:     
                   5770:    $args               - hash of additional info,
                   5771:                           - 'ID' 
                   5772:                                'newid' -> studentID to use in replacement
1.424     albertel 5773:                                           of existing one
1.423     albertel 5774:                           - 'CODE' 
                   5775:                                'CODE_ignore_dup' - set to true if duplicates
                   5776:                                                    should be ignored.
                   5777: 	                       'CODE' - is new code or 'use_unfound'
1.424     albertel 5778:                                         if the existing unfound code should
1.423     albertel 5779:                                         be used as is
                   5780:                           - 'answer'
                   5781:                                'response' - new answer or 'none' if blank
                   5782:                                'question' - the bubble line to change
1.503     raeburn  5783:                                'questionnum' - the question identifier,
                   5784:                                                may include subquestion. 
1.423     albertel 5785: 
                   5786:   Returns:
                   5787:     $line - the modified scanline
                   5788: 
                   5789:   Side effects: 
                   5790:     $scan_data - may be updated
                   5791: 
                   5792: =cut
                   5793: 
1.82      albertel 5794: 
1.157     albertel 5795: sub scantron_fixup_scanline {
                   5796:     my ($scantron_config,$scan_data,$line,$whichline,$field,$args)=@_;
                   5797:     if ($field eq 'ID') {
                   5798: 	if (length($args->{'newid'}) > $$scantron_config{'IDlength'}) {
1.186     albertel 5799: 	    return ($line,1,'New value too large');
1.157     albertel 5800: 	}
                   5801: 	if (length($args->{'newid'}) < $$scantron_config{'IDlength'}) {
                   5802: 	    $args->{'newid'}=sprintf('%-'.$$scantron_config{'IDlength'}.'s',
                   5803: 				     $args->{'newid'});
                   5804: 	}
                   5805: 	substr($line,$$scantron_config{'IDstart'}-1,
                   5806: 	       $$scantron_config{'IDlength'})=$args->{'newid'};
                   5807: 	if ($args->{'newid'}=~/^\s*$/) {
                   5808: 	    &scan_data($scan_data,"$whichline.user",
                   5809: 		       $args->{'username'}.':'.$args->{'domain'});
                   5810: 	}
1.186     albertel 5811:     } elsif ($field eq 'CODE') {
1.192     albertel 5812: 	if ($args->{'CODE_ignore_dup'}) {
                   5813: 	    &scan_data($scan_data,"$whichline.CODE_ignore_dup",'1');
                   5814: 	}
                   5815: 	&scan_data($scan_data,"$whichline.useCODE",'1');
                   5816: 	if ($args->{'CODE'} ne 'use_unfound') {
1.191     albertel 5817: 	    if (length($args->{'CODE'}) > $$scantron_config{'CODElength'}) {
                   5818: 		return ($line,1,'New CODE value too large');
                   5819: 	    }
                   5820: 	    if (length($args->{'CODE'}) < $$scantron_config{'CODElength'}) {
                   5821: 		$args->{'CODE'}=sprintf('%-'.$$scantron_config{'CODElength'}.'s',$args->{'CODE'});
                   5822: 	    }
                   5823: 	    substr($line,$$scantron_config{'CODEstart'}-1,
                   5824: 		   $$scantron_config{'CODElength'})=$args->{'CODE'};
1.186     albertel 5825: 	}
1.157     albertel 5826:     } elsif ($field eq 'answer') {
1.497     foxr     5827: 	my $length=$scantron_config->{'Qlength'};
1.157     albertel 5828: 	my $off=$scantron_config->{'Qoff'};
                   5829: 	my $on=$scantron_config->{'Qon'};
1.497     foxr     5830: 	my $answer=${off}x$length;
                   5831: 	if ($args->{'response'} eq 'none') {
                   5832: 	    &scan_data($scan_data,
1.503     raeburn  5833: 		       "$whichline.no_bubble.".$args->{'questionnum'},'1');
1.497     foxr     5834: 	} else {
                   5835: 	    if ($on eq 'letter') {
                   5836: 		my @alphabet=('A'..'Z');
                   5837: 		$answer=$alphabet[$args->{'response'}];
                   5838: 	    } elsif ($on eq 'number') {
                   5839: 		$answer=$args->{'response'}+1;
                   5840: 		if ($answer == 10) { $answer = '0'; }
1.274     albertel 5841: 	    } else {
1.497     foxr     5842: 		substr($answer,$args->{'response'},1)=$on;
1.274     albertel 5843: 	    }
1.497     foxr     5844: 	    &scan_data($scan_data,
1.503     raeburn  5845: 		       "$whichline.no_bubble.".$args->{'questionnum'},undef,'1');
1.157     albertel 5846: 	}
1.497     foxr     5847: 	my $where=$length*($args->{'question'}-1)+$scantron_config->{'Qstart'};
                   5848: 	substr($line,$where-1,$length)=$answer;
1.157     albertel 5849:     }
                   5850:     return $line;
                   5851: }
1.423     albertel 5852: 
                   5853: =pod
                   5854: 
                   5855: =item scan_data
                   5856: 
                   5857:     Edit or look up  an item in the scan_data hash.
                   5858: 
                   5859:   Arguments:
                   5860:     $scan_data  - The hash (see scantron_getfile)
                   5861:     $key        - shorthand of the key to edit (actual key is
1.424     albertel 5862:                   scantronfilename_key).
1.423     albertel 5863:     $data        - New value of the hash entry.
                   5864:     $delete      - If true, the entry is removed from the hash.
                   5865: 
                   5866:   Returns:
                   5867:     The new value of the hash table field (undefined if deleted).
                   5868: 
                   5869: =cut
                   5870: 
                   5871: 
1.157     albertel 5872: sub scan_data {
                   5873:     my ($scan_data,$key,$value,$delete)=@_;
1.257     albertel 5874:     my $filename=$env{'form.scantron_selectfile'};
1.157     albertel 5875:     if (defined($value)) {
                   5876: 	$scan_data->{$filename.'_'.$key} = $value;
                   5877:     }
                   5878:     if ($delete) { delete($scan_data->{$filename.'_'.$key}); }
                   5879:     return $scan_data->{$filename.'_'.$key};
                   5880: }
1.423     albertel 5881: 
1.495     albertel 5882: # ----- These first few routines are general use routines.----
                   5883: 
                   5884: # Return the number of occurences of a pattern in a string.
                   5885: 
                   5886: sub occurence_count {
                   5887:     my ($string, $pattern) = @_;
                   5888: 
                   5889:     my @matches = ($string =~ /$pattern/g);
                   5890: 
                   5891:     return scalar(@matches);
                   5892: }
                   5893: 
                   5894: 
                   5895: # Take a string known to have digits and convert all the
                   5896: # digits into letters in the range J,A..I.
                   5897: 
                   5898: sub digits_to_letters {
                   5899:     my ($input) = @_;
                   5900: 
                   5901:     my @alphabet = ('J', 'A'..'I');
                   5902: 
                   5903:     my @input    = split(//, $input);
                   5904:     my $output ='';
                   5905:     for (my $i = 0; $i < scalar(@input); $i++) {
                   5906: 	if ($input[$i] =~ /\d/) {
                   5907: 	    $output .= $alphabet[$input[$i]];
                   5908: 	} else {
                   5909: 	    $output .= $input[$i];
                   5910: 	}
                   5911:     }
                   5912:     return $output;
                   5913: }
                   5914: 
1.423     albertel 5915: =pod 
                   5916: 
                   5917: =item scantron_parse_scanline
                   5918: 
1.711     bisitz   5919:   Decodes a scanline from the selected bubblesheet file
1.423     albertel 5920: 
                   5921:  Arguments:
1.711     bisitz   5922:     line             - The text of the bubblesheet file line to process
1.423     albertel 5923:     whichline        - Line number
1.711     bisitz   5924:     scantron_config  - Hash describing the format of the bubblesheet lines.
1.423     albertel 5925:     scan_data        - Hash of extra information about the scanline
                   5926:                        (see scantron_getfile for more information)
                   5927:     just_header      - True if should not process question answers but only
                   5928:                        the stuff to the left of the answers.
1.691     raeburn  5929:     randomorder      - True if randomorder in use
                   5930:     randompick       - True if randompick in use
                   5931:     sequence         - Exam folder URL
                   5932:     master_seq       - Ref to array containing symbs in exam folder
                   5933:     symb_to_resource - Ref to hash of symbs for resources in exam folder
                   5934:                        (corresponding values are resource objects)
                   5935:     partids_by_symb  - Ref to hash of symb -> array ref of partIDs
                   5936:     orderedforcode   - Ref to hash of arrays. keys are CODEs and values
                   5937:                        are refs to an array of resource objects, ordered
                   5938:                        according to order used for CODE, when randomorder
                   5939:                        and or randompick are in use.
                   5940:     respnumlookup    - Ref to hash mapping question numbers in bubble lines
                   5941:                        for current line to question number used for same question
                   5942:                         in "Master Sequence" (as seen by Course Coordinator).
                   5943:     startline        - Ref to hash where key is question number (0 is first)
                   5944:                        and value is number of first bubble line for current 
                   5945:                        student or code-based randompick and/or randomorder.
                   5946:     totalref         - Ref of scalar used to score total number of bubble
                   5947:                        lines needed for responses in a scan line (used when
                   5948:                        randompick in use. 
                   5949:     
1.423     albertel 5950:  Returns:
                   5951:    Hash containing the result of parsing the scanline
                   5952: 
                   5953:    Keys are all proceeded by the string 'scantron.'
                   5954: 
                   5955:        CODE    - the CODE in use for this scanline
                   5956:        useCODE - 1 if the CODE is invalid but it usage has been forced
                   5957:                  by the operator
                   5958:        CODE_ignore_dup - 1 if the CODE is a duplicated use when unique
                   5959:                             CODEs were selected, but the usage has been
                   5960:                             forced by the operator
1.556     weissno  5961:        ID  - student/employee ID
1.423     albertel 5962:        PaperID - if used, the ID number printed on the sheet when the 
                   5963:                  paper was scanned
                   5964:        FirstName - first name from the sheet
                   5965:        LastName  - last name from the sheet
                   5966: 
                   5967:      if just_header was not true these key may also exist
                   5968: 
1.447     foxr     5969:        missingerror - a list of bubble ranges that are considered to be answers
                   5970:                       to a single question that don't have any bubbles filled in.
                   5971:                       Of the form questionnumber:firstbubblenumber:count.
                   5972:        doubleerror  - a list of bubble ranges that are considered to be answers
                   5973:                       to a single question that have more than one bubble filled in.
                   5974:                       Of the form questionnumber::firstbubblenumber:count
                   5975:    
                   5976:                 In the above, count is the number of bubble responses in the
                   5977:                 input line needed to represent the possible answers to the question.
                   5978:                 e.g. a radioresponse with 15 choices in an answer sheet with 10 choices
                   5979:                 per line would have count = 2.
                   5980: 
1.423     albertel 5981:        maxquest     - the number of the last bubble line that was parsed
                   5982: 
                   5983:        (<number> starts at 1)
                   5984:        <number>.answer - zero or more letters representing the selected
                   5985:                          letters from the scanline for the bubble line 
                   5986:                          <number>.
                   5987:                          if blank there was either no bubble or there where
                   5988:                          multiple bubbles, (consult the keys missingerror and
                   5989:                          doubleerror if this is an error condition)
                   5990: 
                   5991: =cut
                   5992: 
1.82      albertel 5993: sub scantron_parse_scanline {
1.691     raeburn  5994:     my ($line,$whichline,$scantron_config,$scan_data,$just_header,$idmap,
                   5995:         $randomorder,$randompick,$sequence,$master_seq,$symb_to_resource,
                   5996:         $partids_by_symb,$orderedforcode,$respnumlookup,$startline,$totalref)=@_;
1.470     foxr     5997: 
1.82      albertel 5998:     my %record;
1.691     raeburn  5999:     my $data=substr($line,0,$$scantron_config{'Qstart'}-1); # stuff before answers
1.278     albertel 6000:     if (!($$scantron_config{'CODElocation'} eq 0 ||
                   6001: 	  $$scantron_config{'CODElocation'} eq 'none')) {
                   6002: 	if ($$scantron_config{'CODElocation'} < 0 ||
                   6003: 	    $$scantron_config{'CODElocation'} eq 'letter' ||
                   6004: 	    $$scantron_config{'CODElocation'} eq 'number') {
1.191     albertel 6005: 	    $record{'scantron.CODE'}=substr($data,
                   6006: 					    $$scantron_config{'CODEstart'}-1,
1.83      albertel 6007: 					    $$scantron_config{'CODElength'});
1.191     albertel 6008: 	    if (&scan_data($scan_data,"$whichline.useCODE")) {
                   6009: 		$record{'scantron.useCODE'}=1;
                   6010: 	    }
1.192     albertel 6011: 	    if (&scan_data($scan_data,"$whichline.CODE_ignore_dup")) {
                   6012: 		$record{'scantron.CODE_ignore_dup'}=1;
                   6013: 	    }
1.82      albertel 6014: 	} else {
                   6015: 	    #FIXME interpret first N questions
                   6016: 	}
                   6017:     }
1.83      albertel 6018:     $record{'scantron.ID'}=substr($data,$$scantron_config{'IDstart'}-1,
                   6019: 				  $$scantron_config{'IDlength'});
1.157     albertel 6020:     $record{'scantron.PaperID'}=
                   6021: 	substr($data,$$scantron_config{'PaperID'}-1,
                   6022: 	       $$scantron_config{'PaperIDlength'});
                   6023:     $record{'scantron.FirstName'}=
                   6024: 	substr($data,$$scantron_config{'FirstName'}-1,
                   6025: 	       $$scantron_config{'FirstNamelength'});
                   6026:     $record{'scantron.LastName'}=
                   6027: 	substr($data,$$scantron_config{'LastName'}-1,
                   6028: 	       $$scantron_config{'LastNamelength'});
1.423     albertel 6029:     if ($just_header) { return \%record; }
1.194     albertel 6030: 
1.82      albertel 6031:     my @alphabet=('A'..'Z');
                   6032:     my $questnum=0;
1.447     foxr     6033:     my $ansnum  =1;		# Multiple 'answer lines'/question.
                   6034: 
1.691     raeburn  6035:     my $lastpos = $env{'form.scantron_maxbubble'}*$$scantron_config{'Qlength'};
                   6036:     if ($randompick || $randomorder) {
                   6037:         my $total = &get_respnum_lookups($sequence,$scan_data,$idmap,$line,\%record,
                   6038:                                          $master_seq,$symb_to_resource,
                   6039:                                          $partids_by_symb,$orderedforcode,
                   6040:                                          $respnumlookup,$startline);
                   6041:         if ($total) {
                   6042:             $lastpos = $total*$$scantron_config{'Qlength'}; 
                   6043:         }
                   6044:         if (ref($totalref)) {
                   6045:             $$totalref = $total;
                   6046:         }
                   6047:     }
                   6048:     my $questions=substr($line,$$scantron_config{'Qstart'}-1,$lastpos);  # Answers
1.470     foxr     6049:     chomp($questions);		# Get rid of any trailing \n.
                   6050:     $questions =~ s/\r$//;      # Get rid of trailing \r too (MAC or Win uploads).
                   6051:     while (length($questions)) {
1.691     raeburn  6052:         my $answers_needed;
                   6053:         if (($randompick || $randomorder) && (ref($respnumlookup) eq 'HASH')) {
                   6054:             $answers_needed = $bubble_lines_per_response{$respnumlookup->{$questnum}};
                   6055:         } else {
                   6056: 	    $answers_needed = $bubble_lines_per_response{$questnum};
                   6057:         }
1.503     raeburn  6058:         my $answer_length  = ($$scantron_config{'Qlength'} * $answers_needed)
                   6059:                              || 1;
                   6060:         $questnum++;
                   6061:         my $quest_id = $questnum;
                   6062:         my $currentquest = substr($questions,0,$answer_length);
                   6063:         $questions       = substr($questions,$answer_length);
                   6064:         if (length($currentquest) < $answer_length) { next; }
                   6065: 
1.691     raeburn  6066:         my $subdivided;
                   6067:         if (($randompick || $randomorder) && (ref($respnumlookup) eq 'HASH')) {
                   6068:             $subdivided = $subdivided_bubble_lines{$respnumlookup->{$questnum-1}};
                   6069:         } else {
                   6070:             $subdivided = $subdivided_bubble_lines{$questnum-1};
                   6071:         }
                   6072:         if ($subdivided =~ /,/) {
1.503     raeburn  6073:             my $subquestnum = 1;
                   6074:             my $subquestions = $currentquest;
1.691     raeburn  6075:             my @subanswers_needed = split(/,/,$subdivided);
1.503     raeburn  6076:             foreach my $subans (@subanswers_needed) {
                   6077:                 my $subans_length =
                   6078:                     ($$scantron_config{'Qlength'} * $subans)  || 1;
                   6079:                 my $currsubquest = substr($subquestions,0,$subans_length);
                   6080:                 $subquestions   = substr($subquestions,$subans_length);
                   6081:                 $quest_id = "$questnum.$subquestnum";
                   6082:                 if (($$scantron_config{'Qon'} eq 'letter') ||
                   6083:                     ($$scantron_config{'Qon'} eq 'number')) {
                   6084:                     $ansnum = &scantron_validator_lettnum($ansnum, 
                   6085:                         $questnum,$quest_id,$subans,$currsubquest,$whichline,
1.691     raeburn  6086:                         \@alphabet,\%record,$scantron_config,$scan_data,
                   6087:                         $randomorder,$randompick,$respnumlookup);
1.503     raeburn  6088:                 } else {
                   6089:                     $ansnum = &scantron_validator_positional($ansnum,
1.691     raeburn  6090:                         $questnum,$quest_id,$subans,$currsubquest,$whichline,
                   6091:                         \@alphabet,\%record,$scantron_config,$scan_data,
                   6092:                         $randomorder,$randompick,$respnumlookup);
1.503     raeburn  6093:                 }
                   6094:                 $subquestnum ++;
                   6095:             }
                   6096:         } else {
                   6097:             if (($$scantron_config{'Qon'} eq 'letter') ||
                   6098:                 ($$scantron_config{'Qon'} eq 'number')) {
                   6099:                 $ansnum = &scantron_validator_lettnum($ansnum,$questnum,
                   6100:                     $quest_id,$answers_needed,$currentquest,$whichline,
1.691     raeburn  6101:                     \@alphabet,\%record,$scantron_config,$scan_data,
                   6102:                     $randomorder,$randompick,$respnumlookup);
1.503     raeburn  6103:             } else {
                   6104:                 $ansnum = &scantron_validator_positional($ansnum,$questnum,
                   6105:                     $quest_id,$answers_needed,$currentquest,$whichline,
1.691     raeburn  6106:                     \@alphabet,\%record,$scantron_config,$scan_data,
                   6107:                     $randomorder,$randompick,$respnumlookup);
1.503     raeburn  6108:             }
                   6109:         }
                   6110:     }
                   6111:     $record{'scantron.maxquest'}=$questnum;
                   6112:     return \%record;
                   6113: }
1.447     foxr     6114: 
1.691     raeburn  6115: sub get_master_seq {
                   6116:     my ($resources,$master_seq,$symb_to_resource) = @_;
                   6117:     return unless ((ref($resources) eq 'ARRAY') && (ref($master_seq) eq 'ARRAY') && 
                   6118:                    (ref($symb_to_resource) eq 'HASH'));
                   6119:     my $resource_error;
                   6120:     foreach my $resource (@{$resources}) {
                   6121:         my $ressymb;
                   6122:         if (ref($resource)) {
                   6123:             $ressymb = $resource->symb();
                   6124:             push(@{$master_seq},$ressymb);
                   6125:             $symb_to_resource->{$ressymb} = $resource;
                   6126:         } else {
                   6127:             $resource_error = 1;
                   6128:             last;
                   6129:         }
                   6130:     }
                   6131:     return $resource_error;
                   6132: }
                   6133: 
                   6134: sub get_respnum_lookups {
                   6135:     my ($sequence,$scan_data,$idmap,$line,$record,$master_seq,$symb_to_resource,
                   6136:         $partids_by_symb,$orderedforcode,$respnumlookup,$startline) = @_;
                   6137:     return unless ((ref($record) eq 'HASH') && (ref($master_seq) eq 'ARRAY') &&
                   6138:                    (ref($symb_to_resource) eq 'HASH') && (ref($partids_by_symb) eq 'HASH') &&
                   6139:                    (ref($orderedforcode) eq 'HASH') && (ref($respnumlookup) eq 'HASH') &&
                   6140:                    (ref($startline) eq 'HASH'));
                   6141:     my ($user,$scancode);
                   6142:     if ((exists($record->{'scantron.CODE'})) &&
                   6143:         (&Apache::lonnet::validCODE($record->{'scantron.CODE'}))) {
                   6144:         $scancode = $record->{'scantron.CODE'};
                   6145:     } else {
                   6146:         $user = &scantron_find_student($record,$scan_data,$idmap,$line);
                   6147:     }
                   6148:     my @mapresources =
                   6149:         &users_order($user,$scancode,$sequence,$master_seq,$symb_to_resource,
                   6150:                      $orderedforcode);
                   6151:     my $total = 0;
                   6152:     my $count = 0;
                   6153:     foreach my $resource (@mapresources) {
                   6154:         my $id = $resource->id();
                   6155:         my $symb = $resource->symb();
                   6156:         if (ref($partids_by_symb->{$symb}) eq 'ARRAY') {
                   6157:             foreach my $partid (@{$partids_by_symb->{$symb}}) {
                   6158:                 my $respnum = $masterseq_id_responsenum{$id.'_'.$partid};
                   6159:                 if ($respnum ne '') {
                   6160:                     $respnumlookup->{$count} = $respnum;
                   6161:                     $startline->{$count} = $total;
                   6162:                     $total += $bubble_lines_per_response{$respnum};
                   6163:                     $count ++;
                   6164:                 }
                   6165:             }
                   6166:         }
                   6167:     }
                   6168:     return $total;
                   6169: }
                   6170: 
1.503     raeburn  6171: sub scantron_validator_lettnum {
                   6172:     my ($ansnum,$questnum,$quest_id,$answers_needed,$currquest,$whichline,
1.691     raeburn  6173:         $alphabet,$record,$scantron_config,$scan_data,$randomorder,
                   6174:         $randompick,$respnumlookup) = @_;
1.503     raeburn  6175: 
                   6176:     # Qon 'letter' implies for each slot in currquest we have:
                   6177:     #    ? or * for doubles, a letter in A-Z for a bubble, and
                   6178:     #    about anything else (esp. a value of Qoff) for missing
                   6179:     #    bubbles.
                   6180:     #
                   6181:     # Qon 'number' implies each slot gives a digit that indexes the
                   6182:     #    bubbles filled, or Qoff, or a non-number for unbubbled lines,
                   6183:     #    and * or ? for double bubbles on a single line.
                   6184:     #
1.447     foxr     6185: 
1.503     raeburn  6186:     my $matchon;
                   6187:     if ($$scantron_config{'Qon'} eq 'letter') {
                   6188:         $matchon = '[A-Z]';
                   6189:     } elsif ($$scantron_config{'Qon'} eq 'number') {
                   6190:         $matchon = '\d';
                   6191:     }
                   6192:     my $occurrences = 0;
1.691     raeburn  6193:     my $responsenum = $questnum-1;
                   6194:     if (($randompick || $randomorder) && (ref($respnumlookup) eq 'HASH')) {
                   6195:        $responsenum = $respnumlookup->{$questnum-1} 
                   6196:     }
                   6197:     if (($responsetype_per_response{$responsenum} eq 'essayresponse') ||
                   6198:         ($responsetype_per_response{$responsenum} eq 'formularesponse') ||
                   6199:         ($responsetype_per_response{$responsenum} eq 'stringresponse') ||
                   6200:         ($responsetype_per_response{$responsenum} eq 'imageresponse') ||
                   6201:         ($responsetype_per_response{$responsenum} eq 'reactionresponse') ||
                   6202:         ($responsetype_per_response{$responsenum} eq 'organicresponse')) {
1.503     raeburn  6203:         my @singlelines = split('',$currquest);
                   6204:         foreach my $entry (@singlelines) {
                   6205:             $occurrences = &occurence_count($entry,$matchon);
                   6206:             if ($occurrences > 1) {
                   6207:                 last;
                   6208:             }
1.691     raeburn  6209:         }
1.503     raeburn  6210:     } else {
                   6211:         $occurrences = &occurence_count($currquest,$matchon); 
                   6212:     }
                   6213:     if (($currquest =~ /\?/ || $currquest =~ /\*/) || ($occurrences > 1)) {
                   6214:         push(@{$record->{'scantron.doubleerror'}},$quest_id);
                   6215:         for (my $ans=0; $ans<$answers_needed; $ans++) {
                   6216:             my $bubble = substr($currquest,$ans,1);
                   6217:             if ($bubble =~ /$matchon/ ) {
                   6218:                 if ($$scantron_config{'Qon'} eq 'number') {
                   6219:                     if ($bubble == 0) {
                   6220:                         $bubble = 10; 
                   6221:                     }
                   6222:                     $record->{"scantron.$ansnum.answer"} = 
                   6223:                         $alphabet->[$bubble-1];
                   6224:                 } else {
                   6225:                     $record->{"scantron.$ansnum.answer"} = $bubble;
                   6226:                 }
                   6227:             } else {
                   6228:                 $record->{"scantron.$ansnum.answer"}='';
                   6229:             }
                   6230:             $ansnum++;
                   6231:         }
                   6232:     } elsif (!defined($currquest)
                   6233:             || (&occurence_count($currquest, $$scantron_config{'Qoff'}) == length($currquest))
                   6234:             || (&occurence_count($currquest,$matchon) == 0)) {
                   6235:         for (my $ans=0; $ans<$answers_needed; $ans++ ) {
                   6236:             $record->{"scantron.$ansnum.answer"}='';
                   6237:             $ansnum++;
                   6238:         }
                   6239:         if (!&scan_data($scan_data,"$whichline.no_bubble.$quest_id")) {
                   6240:             push(@{$record->{'scantron.missingerror'}},$quest_id);
                   6241:         }
                   6242:     } else {
                   6243:         if ($$scantron_config{'Qon'} eq 'number') {
                   6244:             $currquest = &digits_to_letters($currquest);            
                   6245:         }
                   6246:         for (my $ans=0; $ans<$answers_needed; $ans++) {
                   6247:             my $bubble = substr($currquest,$ans,1);
                   6248:             $record->{"scantron.$ansnum.answer"} = $bubble;
                   6249:             $ansnum++;
                   6250:         }
                   6251:     }
                   6252:     return $ansnum;
                   6253: }
1.447     foxr     6254: 
1.503     raeburn  6255: sub scantron_validator_positional {
                   6256:     my ($ansnum,$questnum,$quest_id,$answers_needed,$currquest,
1.691     raeburn  6257:         $whichline,$alphabet,$record,$scantron_config,$scan_data,
                   6258:         $randomorder,$randompick,$respnumlookup) = @_;
1.447     foxr     6259: 
1.503     raeburn  6260:     # Otherwise there's a positional notation;
                   6261:     # each bubble line requires Qlength items, and there are filled in
                   6262:     # bubbles for each case where there 'Qon' characters.
                   6263:     #
1.447     foxr     6264: 
1.503     raeburn  6265:     my @array=split($$scantron_config{'Qon'},$currquest,-1);
1.447     foxr     6266: 
1.503     raeburn  6267:     # If the split only gives us one element.. the full length of the
                   6268:     # answer string, no bubbles are filled in:
1.447     foxr     6269: 
1.507     raeburn  6270:     if ($answers_needed eq '') {
                   6271:         return;
                   6272:     }
                   6273: 
1.503     raeburn  6274:     if (length($array[0]) eq $$scantron_config{'Qlength'}*$answers_needed) {
                   6275:         for (my $ans=0; $ans<$answers_needed; $ans++ ) {
                   6276:             $record->{"scantron.$ansnum.answer"}='';
                   6277:             $ansnum++;
                   6278:         }
                   6279:         if (!&scan_data($scan_data,"$whichline.no_bubble.$quest_id")) {
                   6280:             push(@{$record->{"scantron.missingerror"}},$quest_id);
                   6281:         }
                   6282:     } elsif (scalar(@array) == 2) {
                   6283:         my $location = length($array[0]);
                   6284:         my $line_num = int($location / $$scantron_config{'Qlength'});
                   6285:         my $bubble   = $alphabet->[$location % $$scantron_config{'Qlength'}];
                   6286:         for (my $ans=0; $ans<$answers_needed; $ans++) {
                   6287:             if ($ans eq $line_num) {
                   6288:                 $record->{"scantron.$ansnum.answer"} = $bubble;
                   6289:             } else {
                   6290:                 $record->{"scantron.$ansnum.answer"} = ' ';
                   6291:             }
                   6292:             $ansnum++;
                   6293:          }
                   6294:     } else {
                   6295:         #  If there's more than one instance of a bubble character
                   6296:         #  That's a double bubble; with positional notation we can
                   6297:         #  record all the bubbles filled in as well as the
                   6298:         #  fact this response consists of multiple bubbles.
                   6299:         #
1.691     raeburn  6300:         my $responsenum = $questnum-1;
                   6301:         if (($randompick || $randomorder) && (ref($respnumlookup) eq 'HASH')) {
                   6302:             $responsenum = $respnumlookup->{$questnum-1}
                   6303:         }
                   6304:         if (($responsetype_per_response{$responsenum} eq 'essayresponse') ||
                   6305:             ($responsetype_per_response{$responsenum} eq 'formularesponse') ||
                   6306:             ($responsetype_per_response{$responsenum} eq 'stringresponse') ||
                   6307:             ($responsetype_per_response{$responsenum} eq 'imageresponse') ||
                   6308:             ($responsetype_per_response{$responsenum} eq 'reactionresponse') ||
                   6309:             ($responsetype_per_response{$responsenum} eq 'organicresponse')) {
1.503     raeburn  6310:             my $doubleerror = 0;
                   6311:             while (($currquest >= $$scantron_config{'Qlength'}) && 
                   6312:                    (!$doubleerror)) {
                   6313:                my $currline = substr($currquest,0,$$scantron_config{'Qlength'});
                   6314:                $currquest = substr($currquest,$$scantron_config{'Qlength'});
                   6315:                my @currarray = split($$scantron_config{'Qon'},$currline,-1);
                   6316:                if (length(@currarray) > 2) {
                   6317:                    $doubleerror = 1;
                   6318:                } 
                   6319:             }
                   6320:             if ($doubleerror) {
                   6321:                 push(@{$record->{'scantron.doubleerror'}},$quest_id);
                   6322:             }
                   6323:         } else {
                   6324:             push(@{$record->{'scantron.doubleerror'}},$quest_id);
                   6325:         }
                   6326:         my $item = $ansnum;
                   6327:         for (my $ans=0; $ans<$answers_needed; $ans++) {
                   6328:             $record->{"scantron.$item.answer"} = '';
                   6329:             $item ++;
                   6330:         }
1.447     foxr     6331: 
1.503     raeburn  6332:         my @ans=@array;
                   6333:         my $i=0;
                   6334:         my $increment = 0;
                   6335:         while ($#ans) {
                   6336:             $i+=length($ans[0]) + $increment;
                   6337:             my $line   = int($i/$$scantron_config{'Qlength'} + $ansnum);
                   6338:             my $bubble = $i%$$scantron_config{'Qlength'};
                   6339:             $record->{"scantron.$line.answer"}.=$alphabet->[$bubble];
                   6340:             shift(@ans);
                   6341:             $increment = 1;
                   6342:         }
                   6343:         $ansnum += $answers_needed;
1.82      albertel 6344:     }
1.503     raeburn  6345:     return $ansnum;
1.82      albertel 6346: }
                   6347: 
1.423     albertel 6348: =pod
                   6349: 
                   6350: =item scantron_add_delay
                   6351: 
                   6352:    Adds an error message that occurred during the grading phase to a
                   6353:    queue of messages to be shown after grading pass is complete
                   6354: 
                   6355:  Arguments:
1.424     albertel 6356:    $delayqueue  - arrary ref of hash ref of error messages
1.423     albertel 6357:    $scanline    - the scanline that caused the error
                   6358:    $errormesage - the error message
                   6359:    $errorcode   - a numeric code for the error
                   6360: 
                   6361:  Side Effects:
1.424     albertel 6362:    updates the $delayqueue to have a new hash ref of the error
1.423     albertel 6363: 
                   6364: =cut
                   6365: 
1.82      albertel 6366: sub scantron_add_delay {
1.140     albertel 6367:     my ($delayqueue,$scanline,$errormessage,$errorcode)=@_;
                   6368:     push(@$delayqueue,
                   6369: 	 {'line' => $scanline, 'emsg' => $errormessage,
                   6370: 	  'ecode' => $errorcode }
                   6371: 	 );
1.82      albertel 6372: }
                   6373: 
1.423     albertel 6374: =pod
                   6375: 
                   6376: =item scantron_find_student
                   6377: 
1.424     albertel 6378:    Finds the username for the current scanline
                   6379: 
                   6380:   Arguments:
                   6381:    $scantron_record - hash result from scantron_parse_scanline
                   6382:    $scan_data       - hash of correction information 
                   6383:                       (see &scantron_getfile() form more information)
                   6384:    $idmap           - hash from &username_to_idmap()
                   6385:    $line            - number of current scanline
                   6386:  
                   6387:   Returns:
                   6388:    Either 'username:domain' or undef if unknown
                   6389: 
1.423     albertel 6390: =cut
                   6391: 
1.82      albertel 6392: sub scantron_find_student {
1.157     albertel 6393:     my ($scantron_record,$scan_data,$idmap,$line)=@_;
1.83      albertel 6394:     my $scanID=$$scantron_record{'scantron.ID'};
1.157     albertel 6395:     if ($scanID =~ /^\s*$/) {
                   6396:  	return &scan_data($scan_data,"$line.user");
                   6397:     }
1.83      albertel 6398:     foreach my $id (keys(%$idmap)) {
1.157     albertel 6399:  	if (lc($id) eq lc($scanID)) {
                   6400:  	    return $$idmap{$id};
                   6401:  	}
1.83      albertel 6402:     }
                   6403:     return undef;
                   6404: }
                   6405: 
1.423     albertel 6406: =pod
                   6407: 
                   6408: =item scantron_filter
                   6409: 
1.424     albertel 6410:    Filter sub for lonnavmaps, filters out hidden resources if ignore
                   6411:    hidden resources was selected
                   6412: 
1.423     albertel 6413: =cut
                   6414: 
1.83      albertel 6415: sub scantron_filter {
                   6416:     my ($curres)=@_;
1.331     albertel 6417: 
                   6418:     if (ref($curres) && $curres->is_problem()) {
                   6419: 	# if the user has asked to not have either hidden
                   6420: 	# or 'randomout' controlled resources to be graded
                   6421: 	# don't include them
                   6422: 	if ($env{'form.scantron_options_hidden'} eq 'ignore_hidden'
                   6423: 	    && $curres->randomout) {
                   6424: 	    return 0;
                   6425: 	}
1.83      albertel 6426: 	return 1;
                   6427:     }
                   6428:     return 0;
1.82      albertel 6429: }
                   6430: 
1.423     albertel 6431: =pod
                   6432: 
                   6433: =item scantron_process_corrections
                   6434: 
1.424     albertel 6435:    Gets correction information out of submitted form data and corrects
                   6436:    the scanline
                   6437: 
1.423     albertel 6438: =cut
                   6439: 
1.157     albertel 6440: sub scantron_process_corrections {
                   6441:     my ($r) = @_;
1.257     albertel 6442:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.157     albertel 6443:     my ($scanlines,$scan_data)=&scantron_getfile();
                   6444:     my $classlist=&Apache::loncoursedata::get_classlist();
1.257     albertel 6445:     my $which=$env{'form.scantron_line'};
1.200     albertel 6446:     my $line=&scantron_get_line($scanlines,$scan_data,$which);
1.157     albertel 6447:     my ($skip,$err,$errmsg);
1.257     albertel 6448:     if ($env{'form.scantron_skip_record'}) {
1.157     albertel 6449: 	$skip=1;
1.257     albertel 6450:     } elsif ($env{'form.scantron_corrections'} =~ /^(duplicate|incorrect)ID$/) {
                   6451: 	my $newstudent=$env{'form.scantron_username'}.':'.
                   6452: 	    $env{'form.scantron_domain'};
1.157     albertel 6453: 	my $newid=$classlist->{$newstudent}->[&Apache::loncoursedata::CL_ID];
                   6454: 	($line,$err,$errmsg)=
                   6455: 	    &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,$which,
                   6456: 				     'ID',{'newid'=>$newid,
1.257     albertel 6457: 				    'username'=>$env{'form.scantron_username'},
                   6458: 				    'domain'=>$env{'form.scantron_domain'}});
                   6459:     } elsif ($env{'form.scantron_corrections'} =~ /^(duplicate|incorrect)CODE$/) {
                   6460: 	my $resolution=$env{'form.scantron_CODE_resolution'};
1.190     albertel 6461: 	my $newCODE;
1.192     albertel 6462: 	my %args;
1.190     albertel 6463: 	if      ($resolution eq 'use_unfound') {
1.191     albertel 6464: 	    $newCODE='use_unfound';
1.190     albertel 6465: 	} elsif ($resolution eq 'use_found') {
1.257     albertel 6466: 	    $newCODE=$env{'form.scantron_CODE_selectedvalue'};
1.190     albertel 6467: 	} elsif ($resolution eq 'use_typed') {
1.257     albertel 6468: 	    $newCODE=$env{'form.scantron_CODE_newvalue'};
1.194     albertel 6469: 	} elsif ($resolution =~ /^use_closest_(\d+)/) {
1.257     albertel 6470: 	    $newCODE=$env{"form.scantron_CODE_closest_$1"};
1.190     albertel 6471: 	}
1.257     albertel 6472: 	if ($env{'form.scantron_corrections'} eq 'duplicateCODE') {
1.192     albertel 6473: 	    $args{'CODE_ignore_dup'}=1;
                   6474: 	}
                   6475: 	$args{'CODE'}=$newCODE;
1.186     albertel 6476: 	($line,$err,$errmsg)=
                   6477: 	    &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,$which,
1.192     albertel 6478: 				     'CODE',\%args);
1.257     albertel 6479:     } elsif ($env{'form.scantron_corrections'} =~ /^(missing|double)bubble$/) {
                   6480: 	foreach my $question (split(',',$env{'form.scantron_questions'})) {
1.157     albertel 6481: 	    ($line,$err,$errmsg)=
                   6482: 		&scantron_fixup_scanline(\%scantron_config,$scan_data,$line,
                   6483: 					 $which,'answer',
                   6484: 					 { 'question'=>$question,
1.503     raeburn  6485: 		      		   'response'=>$env{"form.scantron_correct_Q_$question"},
                   6486:                                    'questionnum'=>$env{"form.scantron_questionnum_Q_$question"}});
1.157     albertel 6487: 	    if ($err) { last; }
                   6488: 	}
                   6489:     }
                   6490:     if ($err) {
1.703     bisitz   6491:         $r->print(
                   6492:             '<p class="LC_error">'
                   6493:            .&mt('Unable to accept last correction, an error occurred: [_1]',
                   6494:                 $errmsg)
1.704     raeburn  6495:            .'</p>');
1.157     albertel 6496:     } else {
1.200     albertel 6497: 	&scantron_put_line($scanlines,$scan_data,$which,$line,$skip);
1.157     albertel 6498: 	&scantron_putfile($scanlines,$scan_data);
                   6499:     }
                   6500: }
                   6501: 
1.423     albertel 6502: =pod
                   6503: 
                   6504: =item reset_skipping_status
                   6505: 
1.424     albertel 6506:    Forgets the current set of remember skipped scanlines (and thus
                   6507:    reverts back to considering all lines in the
                   6508:    scantron_skipped_<filename> file)
                   6509: 
1.423     albertel 6510: =cut
                   6511: 
1.200     albertel 6512: sub reset_skipping_status {
                   6513:     my ($scanlines,$scan_data)=&scantron_getfile();
                   6514:     &scan_data($scan_data,'remember_skipping',undef,1);
                   6515:     &scantron_putfile(undef,$scan_data);
                   6516: }
                   6517: 
1.423     albertel 6518: =pod
                   6519: 
                   6520: =item start_skipping
                   6521: 
1.424     albertel 6522:    Marks a scanline to be skipped. 
                   6523: 
1.423     albertel 6524: =cut
                   6525: 
1.376     albertel 6526: sub start_skipping {
1.200     albertel 6527:     my ($scan_data,$i)=@_;
                   6528:     my %remembered=split(':',&scan_data($scan_data,'remember_skipping'));
1.376     albertel 6529:     if ($env{'form.scantron_options_redo'} =~ /^redo_/) {
                   6530: 	$remembered{$i}=2;
                   6531:     } else {
                   6532: 	$remembered{$i}=1;
                   6533:     }
1.200     albertel 6534:     &scan_data($scan_data,'remember_skipping',join(':',%remembered));
                   6535: }
                   6536: 
1.423     albertel 6537: =pod
                   6538: 
                   6539: =item should_be_skipped
                   6540: 
1.424     albertel 6541:    Checks whether a scanline should be skipped.
                   6542: 
1.423     albertel 6543: =cut
                   6544: 
1.200     albertel 6545: sub should_be_skipped {
1.376     albertel 6546:     my ($scanlines,$scan_data,$i)=@_;
1.257     albertel 6547:     if ($env{'form.scantron_options_redo'} !~ /^redo_/) {
1.200     albertel 6548: 	# not redoing old skips
1.376     albertel 6549: 	if ($scanlines->{'skipped'}[$i]) { return 1; }
1.200     albertel 6550: 	return 0;
                   6551:     }
                   6552:     my %remembered=split(':',&scan_data($scan_data,'remember_skipping'));
1.376     albertel 6553: 
                   6554:     if (exists($remembered{$i}) && $remembered{$i} != 2 ) {
                   6555: 	return 0;
                   6556:     }
1.200     albertel 6557:     return 1;
                   6558: }
                   6559: 
1.423     albertel 6560: =pod
                   6561: 
                   6562: =item remember_current_skipped
                   6563: 
1.424     albertel 6564:    Discovers what scanlines are in the scantron_skipped_<filename>
                   6565:    file and remembers them into scan_data for later use.
                   6566: 
1.423     albertel 6567: =cut
                   6568: 
1.200     albertel 6569: sub remember_current_skipped {
                   6570:     my ($scanlines,$scan_data)=&scantron_getfile();
                   6571:     my %to_remember;
                   6572:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
                   6573: 	if ($scanlines->{'skipped'}[$i]) {
                   6574: 	    $to_remember{$i}=1;
                   6575: 	}
                   6576:     }
1.376     albertel 6577: 
1.200     albertel 6578:     &scan_data($scan_data,'remember_skipping',join(':',%to_remember));
                   6579:     &scantron_putfile(undef,$scan_data);
                   6580: }
                   6581: 
1.423     albertel 6582: =pod
                   6583: 
                   6584: =item check_for_error
                   6585: 
1.424     albertel 6586:     Checks if there was an error when attempting to remove a specific
1.659     raeburn  6587:     scantron_.. bubblesheet data file. Prints out an error if
1.424     albertel 6588:     something went wrong.
                   6589: 
1.423     albertel 6590: =cut
                   6591: 
1.200     albertel 6592: sub check_for_error {
                   6593:     my ($r,$result)=@_;
                   6594:     if ($result ne 'ok' && $result ne 'not_found' ) {
1.492     albertel 6595: 	$r->print(&mt("An error occurred ([_1]) when trying to remove the existing corrections.",$result));
1.200     albertel 6596:     }
                   6597: }
1.157     albertel 6598: 
1.423     albertel 6599: =pod
                   6600: 
                   6601: =item scantron_warning_screen
                   6602: 
1.424     albertel 6603:    Interstitial screen to make sure the operator has selected the
                   6604:    correct options before we start the validation phase.
                   6605: 
1.423     albertel 6606: =cut
                   6607: 
1.203     albertel 6608: sub scantron_warning_screen {
1.650     raeburn  6609:     my ($button_text,$symb)=@_;
1.257     albertel 6610:     my $title=&Apache::lonnet::gettitle($env{'form.selectpage'});
1.284     albertel 6611:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.373     albertel 6612:     my $CODElist;
1.284     albertel 6613:     if ($scantron_config{'CODElocation'} &&
                   6614: 	$scantron_config{'CODEstart'} &&
                   6615: 	$scantron_config{'CODElength'}) {
                   6616: 	$CODElist=$env{'form.scantron_CODElist'};
1.398     albertel 6617: 	if ($env{'form.scantron_CODElist'} eq '') { $CODElist='<span class="LC_warning">None</span>'; }
1.284     albertel 6618: 	$CODElist=
1.492     albertel 6619: 	    '<tr><td><b>'.&mt('List of CODES to validate against:').'</b></td><td><tt>'.
1.373     albertel 6620: 	    $env{'form.scantron_CODElist'}.'</tt></td></tr>';
1.284     albertel 6621:     }
1.663     raeburn  6622:     my $lastbubblepoints;
                   6623:     if ($env{'form.scantron_lastbubblepoints'} ne '') {
                   6624:         $lastbubblepoints =
                   6625:             '<tr><td><b>'.&mt('Hand-graded items: points from last bubble in row').'</b></td><td><tt>'.
                   6626:             $env{'form.scantron_lastbubblepoints'}.'</tt></td></tr>';
                   6627:     }
1.492     albertel 6628:     return ('
1.203     albertel 6629: <p>
1.492     albertel 6630: <span class="LC_warning">
1.705     raeburn  6631: '.&mt("Please double check the information below before clicking on '[_1]'",&mt($button_text)).'</span>
1.203     albertel 6632: </p>
                   6633: <table>
1.492     albertel 6634: <tr><td><b>'.&mt('Sequence to be Graded:').'</b></td><td>'.$title.'</td></tr>
                   6635: <tr><td><b>'.&mt('Data File that will be used:').'</b></td><td><tt>'.$env{'form.scantron_selectfile'}.'</tt></td></tr>
1.663     raeburn  6636: '.$CODElist.$lastbubblepoints.'
1.203     albertel 6637: </table>
1.680     raeburn  6638: <p> '.&mt("If this information is correct, please click on '[_1]'.",&mt($button_text)).'<br />
1.650     raeburn  6639: '.&mt('If something is incorrect, please return to [_1]Grade/Manage/Review Bubblesheets[_2] to start over.','<a href="/adm/grades?symb='.$symb.'&command=scantron_selectphase" class="LC_info">','</a>').'</p>
1.203     albertel 6640: 
                   6641: <br />
1.492     albertel 6642: ');
1.203     albertel 6643: }
                   6644: 
1.423     albertel 6645: =pod
                   6646: 
                   6647: =item scantron_do_warning
                   6648: 
1.424     albertel 6649:    Check if the operator has picked something for all required
                   6650:    fields. Error out if something is missing.
                   6651: 
1.423     albertel 6652: =cut
                   6653: 
1.203     albertel 6654: sub scantron_do_warning {
1.608     www      6655:     my ($r,$symb)=@_;
1.203     albertel 6656:     if (!$symb) {return '';}
1.324     albertel 6657:     my $default_form_data=&defaultFormData($symb);
1.203     albertel 6658:     $r->print(&scantron_form_start().$default_form_data);
1.257     albertel 6659:     if ( $env{'form.selectpage'} eq '' ||
                   6660: 	 $env{'form.scantron_selectfile'} eq '' ||
                   6661: 	 $env{'form.scantron_format'} eq '' ) {
1.642     raeburn  6662: 	$r->print("<p>".&mt('You have forgotten to specify some information. Please go Back and try again.')."</p>");
1.257     albertel 6663: 	if ( $env{'form.selectpage'} eq '') {
1.492     albertel 6664: 	    $r->print('<p><span class="LC_error">'.&mt('You have not selected a Sequence to grade').'</span></p>');
1.237     albertel 6665: 	} 
1.257     albertel 6666: 	if ( $env{'form.scantron_selectfile'} eq '') {
1.642     raeburn  6667: 	    $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 6668: 	} 
1.257     albertel 6669: 	if ( $env{'form.scantron_format'} eq '') {
1.642     raeburn  6670: 	    $r->print('<p><span class="LC_error">'.&mt("You have not selected the format of the student's response data.").'</span></p>');
1.237     albertel 6671: 	} 
                   6672:     } else {
1.650     raeburn  6673: 	my $warning=&scantron_warning_screen('Grading: Validate Records',$symb);
1.663     raeburn  6674:         my $bubbledbyhand=&hand_bubble_option();
1.492     albertel 6675: 	$r->print('
1.663     raeburn  6676: '.$warning.$bubbledbyhand.'
1.492     albertel 6677: <input type="submit" name="submit" value="'.&mt('Grading: Validate Records').'" />
1.203     albertel 6678: <input type="hidden" name="command" value="scantron_validate" />
1.492     albertel 6679: ');
1.237     albertel 6680:     }
1.614     www      6681:     $r->print("</form><br />");
1.203     albertel 6682:     return '';
                   6683: }
                   6684: 
1.423     albertel 6685: =pod
                   6686: 
                   6687: =item scantron_form_start
                   6688: 
1.424     albertel 6689:     html hidden input for remembering all selected grading options
                   6690: 
1.423     albertel 6691: =cut
                   6692: 
1.203     albertel 6693: sub scantron_form_start {
                   6694:     my ($max_bubble)=@_;
                   6695:     my $result= <<SCANTRONFORM;
                   6696: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantronupload">
1.257     albertel 6697:   <input type="hidden" name="selectpage" value="$env{'form.selectpage'}" />
                   6698:   <input type="hidden" name="scantron_format" value="$env{'form.scantron_format'}" />
                   6699:   <input type="hidden" name="scantron_selectfile" value="$env{'form.scantron_selectfile'}" />
1.218     albertel 6700:   <input type="hidden" name="scantron_maxbubble" value="$max_bubble" />
1.257     albertel 6701:   <input type="hidden" name="scantron_CODElist" value="$env{'form.scantron_CODElist'}" />
                   6702:   <input type="hidden" name="scantron_CODEunique" value="$env{'form.scantron_CODEunique'}" />
                   6703:   <input type="hidden" name="scantron_options_redo" value="$env{'form.scantron_options_redo'}" />
                   6704:   <input type="hidden" name="scantron_options_ignore" value="$env{'form.scantron_options_ignore'}" />
1.331     albertel 6705:   <input type="hidden" name="scantron_options_hidden" value="$env{'form.scantron_options_hidden'}" />
1.203     albertel 6706: SCANTRONFORM
1.447     foxr     6707: 
                   6708:   my $line = 0;
                   6709:     while (defined($env{"form.scantron.bubblelines.$line"})) {
                   6710:        my $chunk =
                   6711: 	   '<input type="hidden" name="scantron.bubblelines.'.$line.'" value="'.$env{"form.scantron.bubblelines.$line"}.'" />'."\n";
1.448     foxr     6712:        $chunk .=
                   6713: 	   '<input type="hidden" name="scantron.first_bubble_line.'.$line.'" value="'.$env{"form.scantron.first_bubble_line.$line"}.'" />'."\n";
1.503     raeburn  6714:        $chunk .= 
                   6715:            '<input type="hidden" name="scantron.sub_bubblelines.'.$line.'" value="'.$env{"form.scantron.sub_bubblelines.$line"}.'" />'."\n";
1.504     raeburn  6716:        $chunk .=
                   6717:            '<input type="hidden" name="scantron.responsetype.'.$line.'" value="'.$env{"form.scantron.responsetype.$line"}.'" />'."\n";
1.691     raeburn  6718:        $chunk .=
                   6719:            '<input type="hidden" name="scantron.residpart.'.$line.'" value="'.$env{"form.scantron.residpart.$line"}.'" />'."\n";
1.447     foxr     6720:        $result .= $chunk;
                   6721:        $line++;
1.691     raeburn  6722:     }
1.203     albertel 6723:     return $result;
                   6724: }
                   6725: 
1.423     albertel 6726: =pod
                   6727: 
                   6728: =item scantron_validate_file
                   6729: 
1.659     raeburn  6730:     Dispatch routine for doing validation of a bubblesheet data file.
1.424     albertel 6731: 
                   6732:     Also processes any necessary information resets that need to
                   6733:     occur before validation begins (ignore previous corrections,
                   6734:     restarting the skipped records processing)
                   6735: 
1.423     albertel 6736: =cut
                   6737: 
1.157     albertel 6738: sub scantron_validate_file {
1.608     www      6739:     my ($r,$symb) = @_;
1.157     albertel 6740:     if (!$symb) {return '';}
1.324     albertel 6741:     my $default_form_data=&defaultFormData($symb);
1.200     albertel 6742:     
1.703     bisitz   6743:     # do the detection of only doing skipped records first before we delete
1.424     albertel 6744:     # them when doing the corrections reset
1.257     albertel 6745:     if ($env{'form.scantron_options_redo'} ne 'redo_skipped_ready') {
1.200     albertel 6746: 	&reset_skipping_status();
                   6747:     }
1.257     albertel 6748:     if ($env{'form.scantron_options_redo'} eq 'redo_skipped') {
1.200     albertel 6749: 	&remember_current_skipped();
1.257     albertel 6750: 	$env{'form.scantron_options_redo'}='redo_skipped_ready';
1.200     albertel 6751:     }
                   6752: 
1.257     albertel 6753:     if ($env{'form.scantron_options_ignore'} eq 'ignore_corrections') {
1.200     albertel 6754: 	&check_for_error($r,&scantron_remove_file('corrected'));
                   6755: 	&check_for_error($r,&scantron_remove_file('skipped'));
                   6756: 	&check_for_error($r,&scantron_remove_scan_data());
1.257     albertel 6757: 	$env{'form.scantron_options_ignore'}='done';
1.192     albertel 6758:     }
1.200     albertel 6759: 
1.257     albertel 6760:     if ($env{'form.scantron_corrections'}) {
1.157     albertel 6761: 	&scantron_process_corrections($r);
                   6762:     }
1.503     raeburn  6763:     $r->print('<p>'.&mt('Gathering necessary information.').'</p>');$r->rflush();
1.157     albertel 6764:     #get the student pick code ready
                   6765:     $r->print(&Apache::loncommon::studentbrowser_javascript());
1.582     raeburn  6766:     my $nav_error;
1.649     raeburn  6767:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
                   6768:     my $max_bubble=&scantron_get_maxbubble(\$nav_error,\%scantron_config);
1.582     raeburn  6769:     if ($nav_error) {
                   6770:         $r->print(&navmap_errormsg());
                   6771:         return '';
                   6772:     }
1.203     albertel 6773:     my $result=&scantron_form_start($max_bubble).$default_form_data;
1.663     raeburn  6774:     if ($env{'form.scantron_lastbubblepoints'} ne '') {
                   6775:         $result .= '<input type="hidden" name="scantron_lastbubblepoints" value="'.$env{'form.scantron_lastbubblepoints'}.'" />';
                   6776:     }
1.157     albertel 6777:     $r->print($result);
                   6778:     
1.334     albertel 6779:     my @validate_phases=( 'sequence',
                   6780: 			  'ID',
1.157     albertel 6781: 			  'CODE',
                   6782: 			  'doublebubble',
                   6783: 			  'missingbubbles');
1.257     albertel 6784:     if (!$env{'form.validatepass'}) {
                   6785: 	$env{'form.validatepass'} = 0;
1.157     albertel 6786:     }
1.257     albertel 6787:     my $currentphase=$env{'form.validatepass'};
1.157     albertel 6788: 
1.448     foxr     6789: 
1.157     albertel 6790:     my $stop=0;
                   6791:     while (!$stop && $currentphase < scalar(@validate_phases)) {
1.503     raeburn  6792: 	$r->print(&mt('Validating '.$validate_phases[$currentphase]).'<br />');
1.157     albertel 6793: 	$r->rflush();
1.691     raeburn  6794:      
1.157     albertel 6795: 	my $which="scantron_validate_".$validate_phases[$currentphase];
                   6796: 	{
                   6797: 	    no strict 'refs';
                   6798: 	    ($stop,$currentphase)=&$which($r,$currentphase);
                   6799: 	}
                   6800:     }
                   6801:     if (!$stop) {
1.650     raeburn  6802: 	my $warning=&scantron_warning_screen('Start Grading',$symb);
1.542     raeburn  6803: 	$r->print(&mt('Validation process complete.').'<br />'.
                   6804:                   $warning.
                   6805:                   &mt('Perform verification for each student after storage of submissions?').
                   6806:                   '&nbsp;<span class="LC_nobreak"><label>'.
                   6807:                   '<input type="radio" name="verifyrecord" value="1" />'.&mt('Yes').'</label>'.
                   6808:                   ('&nbsp;'x3).'<label>'.
                   6809:                   '<input type="radio" name="verifyrecord" value="0" checked="checked" />'.&mt('No').
                   6810:                   '</label></span><br />'.
                   6811:                   &mt('Grading will take longer if you use verification.').'<br />'.
1.650     raeburn  6812:                   &mt('Otherwise, Grade/Manage/Review Bubblesheets [_1] Review bubblesheet data can be used once grading is complete.','&raquo;').'<br /><br />'.
1.542     raeburn  6813:                   '<input type="submit" name="submit" value="'.&mt('Start Grading').'" />'.
                   6814:                   '<input type="hidden" name="command" value="scantron_process" />'."\n");
1.157     albertel 6815:     } else {
                   6816: 	$r->print('<input type="hidden" name="command" value="scantron_validate" />');
                   6817: 	$r->print("<input type='hidden' name='validatepass' value='".$currentphase."' />");
                   6818:     }
                   6819:     if ($stop) {
1.334     albertel 6820: 	if ($validate_phases[$currentphase] eq 'sequence') {
1.539     riegler  6821: 	    $r->print('<input type="submit" name="submit" value="'.&mt('Ignore').' &rarr; " />');
1.492     albertel 6822: 	    $r->print(' '.&mt('this error').' <br />');
1.334     albertel 6823: 
1.650     raeburn  6824: 	    $r->print('<p>'.&mt('Or return to [_1]Grade/Manage/Review Bubblesheets[_2] to start over.','<a href="/adm/grades?symb='.$symb.'&command=scantron_selectphase" class="LC_info">','</a>').'</p>');
1.334     albertel 6825: 	} else {
1.503     raeburn  6826:             if ($validate_phases[$currentphase] eq 'doublebubble' || $validate_phases[$currentphase] eq 'missingbubbles') {
1.539     riegler  6827: 	        $r->print('<input type="button" name="submitbutton" value="'.&mt('Continue').' &rarr;" onclick="javascript:verify_bubble_radio(this.form)" />');
1.503     raeburn  6828:             } else {
1.539     riegler  6829:                 $r->print('<input type="submit" name="submit" value="'.&mt('Continue').' &rarr;" />');
1.503     raeburn  6830:             }
1.492     albertel 6831: 	    $r->print(' '.&mt('using corrected info').' <br />');
                   6832: 	    $r->print("<input type='submit' value='".&mt("Skip")."' name='scantron_skip_record' />");
                   6833: 	    $r->print(" ".&mt("this scanline saving it for later."));
1.334     albertel 6834: 	}
1.157     albertel 6835:     }
1.614     www      6836:     $r->print(" </form><br />");
1.157     albertel 6837:     return '';
                   6838: }
                   6839: 
1.423     albertel 6840: 
                   6841: =pod
                   6842: 
                   6843: =item scantron_remove_file
                   6844: 
1.659     raeburn  6845:    Removes the requested bubblesheet data file, makes sure that
1.424     albertel 6846:    scantron_original_<filename> is never removed
                   6847: 
                   6848: 
1.423     albertel 6849: =cut
                   6850: 
1.200     albertel 6851: sub scantron_remove_file {
1.192     albertel 6852:     my ($which)=@_;
1.257     albertel 6853:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   6854:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.192     albertel 6855:     my $file='scantron_';
1.200     albertel 6856:     if ($which eq 'corrected' || $which eq 'skipped') {
                   6857: 	$file.=$which.'_';
1.192     albertel 6858:     } else {
                   6859: 	return 'refused';
                   6860:     }
1.257     albertel 6861:     $file.=$env{'form.scantron_selectfile'};
1.200     albertel 6862:     return &Apache::lonnet::removeuserfile($cname,$cdom,$file);
                   6863: }
                   6864: 
1.423     albertel 6865: 
                   6866: =pod
                   6867: 
                   6868: =item scantron_remove_scan_data
                   6869: 
1.659     raeburn  6870:    Removes all scan_data correction for the requested bubblesheet
1.424     albertel 6871:    data file.  (In the case that both the are doing skipped records we need
                   6872:    to remember the old skipped lines for the time being so that element
                   6873:    persists for a while.)
                   6874: 
1.423     albertel 6875: =cut
                   6876: 
1.200     albertel 6877: sub scantron_remove_scan_data {
1.257     albertel 6878:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   6879:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.192     albertel 6880:     my @keys=&Apache::lonnet::getkeys('nohist_scantrondata',$cdom,$cname);
                   6881:     my @todelete;
1.257     albertel 6882:     my $filename=$env{'form.scantron_selectfile'};
1.192     albertel 6883:     foreach my $key (@keys) {
                   6884: 	if ($key=~/^\Q$filename\E_/) {
1.257     albertel 6885: 	    if ($env{'form.scantron_options_redo'} eq 'redo_skipped_ready' &&
1.200     albertel 6886: 		$key=~/remember_skipping/) {
                   6887: 		next;
                   6888: 	    }
1.192     albertel 6889: 	    push(@todelete,$key);
                   6890: 	}
                   6891:     }
1.200     albertel 6892:     my $result;
1.192     albertel 6893:     if (@todelete) {
1.491     albertel 6894: 	$result = &Apache::lonnet::del('nohist_scantrondata',
                   6895: 				       \@todelete,$cdom,$cname);
                   6896:     } else {
                   6897: 	$result = 'ok';
1.192     albertel 6898:     }
                   6899:     return $result;
                   6900: }
                   6901: 
1.423     albertel 6902: 
                   6903: =pod
                   6904: 
                   6905: =item scantron_getfile
                   6906: 
1.659     raeburn  6907:     Fetches the requested bubblesheet data file (all 3 versions), and
1.424     albertel 6908:     the scan_data hash
                   6909:   
                   6910:   Arguments:
                   6911:     None
                   6912: 
                   6913:   Returns:
                   6914:     2 hash references
                   6915: 
                   6916:      - first one has 
                   6917:          orig      -
                   6918:          corrected -
                   6919:          skipped   -  each of which points to an array ref of the specified
                   6920:                       file broken up into individual lines
                   6921:          count     - number of scanlines
                   6922:  
                   6923:      - second is the scan_data hash possible keys are
1.425     albertel 6924:        ($number refers to scanline numbered $number and thus the key affects
                   6925:         only that scanline
                   6926:         $bubline refers to the specific bubble line element and the aspects
                   6927:         refers to that specific bubble line element)
                   6928: 
                   6929:        $number.user - username:domain to use
                   6930:        $number.CODE_ignore_dup 
                   6931:                     - ignore the duplicate CODE error 
                   6932:        $number.useCODE
                   6933:                     - use the CODE in the scanline as is
                   6934:        $number.no_bubble.$bubline
                   6935:                     - it is valid that there is no bubbled in bubble
                   6936:                       at $number $bubline
                   6937:        remember_skipping
                   6938:                     - a frozen hash containing keys of $number and values
                   6939:                       of either 
                   6940:                         1 - we are on a 'do skipped records pass' and plan
                   6941:                             on processing this line
                   6942:                         2 - we are on a 'do skipped records pass' and this
                   6943:                             scanline has been marked to skip yet again
1.424     albertel 6944: 
1.423     albertel 6945: =cut
                   6946: 
1.157     albertel 6947: sub scantron_getfile {
1.200     albertel 6948:     #FIXME really would prefer a scantron directory
1.257     albertel 6949:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   6950:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.157     albertel 6951:     my $lines;
                   6952:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
1.257     albertel 6953: 		       'scantron_orig_'.$env{'form.scantron_selectfile'});
1.157     albertel 6954:     my %scanlines;
                   6955:     $scanlines{'orig'}=[(split("\n",$lines,-1))];
                   6956:     my $temp=$scanlines{'orig'};
                   6957:     $scanlines{'count'}=$#$temp;
                   6958: 
                   6959:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
1.257     albertel 6960: 		       'scantron_corrected_'.$env{'form.scantron_selectfile'});
1.157     albertel 6961:     if ($lines eq '-1') {
                   6962: 	$scanlines{'corrected'}=[];
                   6963:     } else {
                   6964: 	$scanlines{'corrected'}=[(split("\n",$lines,-1))];
                   6965:     }
                   6966:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
1.257     albertel 6967: 		       'scantron_skipped_'.$env{'form.scantron_selectfile'});
1.157     albertel 6968:     if ($lines eq '-1') {
                   6969: 	$scanlines{'skipped'}=[];
                   6970:     } else {
                   6971: 	$scanlines{'skipped'}=[(split("\n",$lines,-1))];
                   6972:     }
1.175     albertel 6973:     my @tmp=&Apache::lonnet::dump('nohist_scantrondata',$cdom,$cname);
1.157     albertel 6974:     if ($tmp[0] =~ /^(error:|no_such_host)/) { @tmp=(); }
                   6975:     my %scan_data = @tmp;
                   6976:     return (\%scanlines,\%scan_data);
                   6977: }
                   6978: 
1.423     albertel 6979: =pod
                   6980: 
                   6981: =item lonnet_putfile
                   6982: 
1.424     albertel 6983:    Wrapper routine to call &Apache::lonnet::finishuserfileupload
                   6984: 
                   6985:  Arguments:
                   6986:    $contents - data to store
                   6987:    $filename - filename to store $contents into
                   6988: 
                   6989:  Returns:
                   6990:    result value from &Apache::lonnet::finishuserfileupload
                   6991: 
1.423     albertel 6992: =cut
                   6993: 
1.157     albertel 6994: sub lonnet_putfile {
                   6995:     my ($contents,$filename)=@_;
1.257     albertel 6996:     my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   6997:     my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   6998:     $env{'form.sillywaytopassafilearound'}=$contents;
1.275     albertel 6999:     &Apache::lonnet::finishuserfileupload($docuname,$docudom,'sillywaytopassafilearound',$filename);
1.157     albertel 7000: 
                   7001: }
                   7002: 
1.423     albertel 7003: =pod
                   7004: 
                   7005: =item scantron_putfile
                   7006: 
1.659     raeburn  7007:     Stores the current version of the bubblesheet data files, and the
1.424     albertel 7008:     scan_data hash. (Does not modify the original version only the
                   7009:     corrected and skipped versions.
                   7010: 
                   7011:  Arguments:
                   7012:     $scanlines - hash ref that looks like the first return value from
                   7013:                  &scantron_getfile()
                   7014:     $scan_data - hash ref that looks like the second return value from
                   7015:                  &scantron_getfile()
                   7016: 
1.423     albertel 7017: =cut
                   7018: 
1.157     albertel 7019: sub scantron_putfile {
                   7020:     my ($scanlines,$scan_data) = @_;
1.200     albertel 7021:     #FIXME really would prefer a scantron directory
1.257     albertel 7022:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   7023:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.200     albertel 7024:     if ($scanlines) {
                   7025: 	my $prefix='scantron_';
1.157     albertel 7026: # no need to update orig, shouldn't change
                   7027: #   &lonnet_putfile(join("\n",@{$scanlines->{'orig'}}),$prefix.'orig_'.
1.257     albertel 7028: #		    $env{'form.scantron_selectfile'});
1.200     albertel 7029: 	&lonnet_putfile(join("\n",@{$scanlines->{'corrected'}}),
                   7030: 			$prefix.'corrected_'.
1.257     albertel 7031: 			$env{'form.scantron_selectfile'});
1.200     albertel 7032: 	&lonnet_putfile(join("\n",@{$scanlines->{'skipped'}}),
                   7033: 			$prefix.'skipped_'.
1.257     albertel 7034: 			$env{'form.scantron_selectfile'});
1.200     albertel 7035:     }
1.175     albertel 7036:     &Apache::lonnet::put('nohist_scantrondata',$scan_data,$cdom,$cname);
1.157     albertel 7037: }
                   7038: 
1.423     albertel 7039: =pod
                   7040: 
                   7041: =item scantron_get_line
                   7042: 
1.424     albertel 7043:    Returns the correct version of the scanline
                   7044: 
                   7045:  Arguments:
                   7046:     $scanlines - hash ref that looks like the first return value from
                   7047:                  &scantron_getfile()
                   7048:     $scan_data - hash ref that looks like the second return value from
                   7049:                  &scantron_getfile()
                   7050:     $i         - number of the requested line (starts at 0)
                   7051: 
                   7052:  Returns:
                   7053:    A scanline, (either the original or the corrected one if it
                   7054:    exists), or undef if the requested scanline should be
                   7055:    skipped. (Either because it's an skipped scanline, or it's an
                   7056:    unskipped scanline and we are not doing a 'do skipped scanlines'
                   7057:    pass.
                   7058: 
1.423     albertel 7059: =cut
                   7060: 
1.157     albertel 7061: sub scantron_get_line {
1.200     albertel 7062:     my ($scanlines,$scan_data,$i)=@_;
1.376     albertel 7063:     if (&should_be_skipped($scanlines,$scan_data,$i)) { return undef; }
                   7064:     #if ($scanlines->{'skipped'}[$i]) { return undef; }
1.157     albertel 7065:     if ($scanlines->{'corrected'}[$i]) {return $scanlines->{'corrected'}[$i];}
                   7066:     return $scanlines->{'orig'}[$i]; 
                   7067: }
                   7068: 
1.423     albertel 7069: =pod
                   7070: 
                   7071: =item scantron_todo_count
                   7072: 
1.424     albertel 7073:     Counts the number of scanlines that need processing.
                   7074: 
                   7075:  Arguments:
                   7076:     $scanlines - hash ref that looks like the first return value from
                   7077:                  &scantron_getfile()
                   7078:     $scan_data - hash ref that looks like the second return value from
                   7079:                  &scantron_getfile()
                   7080: 
                   7081:  Returns:
                   7082:     $count - number of scanlines to process
                   7083: 
1.423     albertel 7084: =cut
                   7085: 
1.200     albertel 7086: sub get_todo_count {
                   7087:     my ($scanlines,$scan_data)=@_;
                   7088:     my $count=0;
                   7089:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
                   7090: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
                   7091: 	if ($line=~/^[\s\cz]*$/) { next; }
                   7092: 	$count++;
                   7093:     }
                   7094:     return $count;
                   7095: }
                   7096: 
1.423     albertel 7097: =pod
                   7098: 
                   7099: =item scantron_put_line
                   7100: 
1.659     raeburn  7101:     Updates the 'corrected' or 'skipped' versions of the bubblesheet
1.424     albertel 7102:     data file.
                   7103: 
                   7104:  Arguments:
                   7105:     $scanlines - hash ref that looks like the first return value from
                   7106:                  &scantron_getfile()
                   7107:     $scan_data - hash ref that looks like the second return value from
                   7108:                  &scantron_getfile()
                   7109:     $i         - line number to update
                   7110:     $newline   - contents of the updated scanline
                   7111:     $skip      - if true make the line for skipping and update the
                   7112:                  'skipped' file
                   7113: 
1.423     albertel 7114: =cut
                   7115: 
1.157     albertel 7116: sub scantron_put_line {
1.200     albertel 7117:     my ($scanlines,$scan_data,$i,$newline,$skip)=@_;
1.157     albertel 7118:     if ($skip) {
                   7119: 	$scanlines->{'skipped'}[$i]=$newline;
1.376     albertel 7120: 	&start_skipping($scan_data,$i);
1.157     albertel 7121: 	return;
                   7122:     }
                   7123:     $scanlines->{'corrected'}[$i]=$newline;
                   7124: }
                   7125: 
1.423     albertel 7126: =pod
                   7127: 
                   7128: =item scantron_clear_skip
                   7129: 
1.424     albertel 7130:    Remove a line from the 'skipped' file
                   7131: 
                   7132:  Arguments:
                   7133:     $scanlines - hash ref that looks like the first return value from
                   7134:                  &scantron_getfile()
                   7135:     $scan_data - hash ref that looks like the second return value from
                   7136:                  &scantron_getfile()
                   7137:     $i         - line number to update
                   7138: 
1.423     albertel 7139: =cut
                   7140: 
1.376     albertel 7141: sub scantron_clear_skip {
                   7142:     my ($scanlines,$scan_data,$i)=@_;
                   7143:     if (exists($scanlines->{'skipped'}[$i])) {
                   7144: 	undef($scanlines->{'skipped'}[$i]);
                   7145: 	return 1;
                   7146:     }
                   7147:     return 0;
                   7148: }
                   7149: 
1.423     albertel 7150: =pod
                   7151: 
                   7152: =item scantron_filter_not_exam
                   7153: 
1.424     albertel 7154:    Filter routine used by &Apache::lonnavmaps::retrieveResources(), to
                   7155:    filter out resources that are not marked as 'exam' mode
                   7156: 
1.423     albertel 7157: =cut
                   7158: 
1.334     albertel 7159: sub scantron_filter_not_exam {
                   7160:     my ($curres)=@_;
                   7161:     
                   7162:     if (ref($curres) && $curres->is_problem() && !$curres->is_exam()) {
                   7163: 	# if the user has asked to not have either hidden
                   7164: 	# or 'randomout' controlled resources to be graded
                   7165: 	# don't include them
                   7166: 	if ($env{'form.scantron_options_hidden'} eq 'ignore_hidden'
                   7167: 	    && $curres->randomout) {
                   7168: 	    return 0;
                   7169: 	}
                   7170: 	return 1;
                   7171:     }
                   7172:     return 0;
                   7173: }
                   7174: 
1.423     albertel 7175: =pod
                   7176: 
                   7177: =item scantron_validate_sequence
                   7178: 
1.424     albertel 7179:     Validates the selected sequence, checking for resource that are
                   7180:     not set to exam mode.
                   7181: 
1.423     albertel 7182: =cut
                   7183: 
1.334     albertel 7184: sub scantron_validate_sequence {
                   7185:     my ($r,$currentphase) = @_;
                   7186: 
                   7187:     my $navmap=Apache::lonnavmaps::navmap->new();
1.582     raeburn  7188:     unless (ref($navmap)) {
                   7189:         $r->print(&navmap_errormsg());
                   7190:         return (1,$currentphase);
                   7191:     }
1.334     albertel 7192:     my (undef,undef,$sequence)=
                   7193: 	&Apache::lonnet::decode_symb($env{'form.selectpage'});
                   7194: 
                   7195:     my $map=$navmap->getResourceByUrl($sequence);
                   7196: 
                   7197:     $r->print('<input type="hidden" name="validate_sequence_exam"
                   7198:                                     value="ignore" />');
                   7199:     if ($env{'form.validate_sequence_exam'} ne 'ignore') {
                   7200: 	my @resources=
                   7201: 	    $navmap->retrieveResources($map,\&scantron_filter_not_exam,1,0);
                   7202: 	if (@resources) {
1.675     bisitz   7203: 	    $r->print(
                   7204:                 '<p class="LC_warning">'
                   7205:                .&mt('Some resources in the sequence currently are not set to'
1.684     bisitz   7206:                    .' bubblesheet exam mode. Grading these resources currently may not'
1.675     bisitz   7207:                    .' work correctly.')
                   7208:                .'</p>'
                   7209:             );
1.334     albertel 7210: 	    return (1,$currentphase);
                   7211: 	}
                   7212:     }
                   7213: 
                   7214:     return (0,$currentphase+1);
                   7215: }
                   7216: 
1.423     albertel 7217: 
                   7218: 
1.157     albertel 7219: sub scantron_validate_ID {
                   7220:     my ($r,$currentphase) = @_;
                   7221:     
                   7222:     #get student info
                   7223:     my $classlist=&Apache::loncoursedata::get_classlist();
                   7224:     my %idmap=&username_to_idmap($classlist);
                   7225: 
                   7226:     #get scantron line setup
1.257     albertel 7227:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.157     albertel 7228:     my ($scanlines,$scan_data)=&scantron_getfile();
1.582     raeburn  7229: 
                   7230:     my $nav_error;
1.649     raeburn  7231:     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # parse needs the bubble_lines.. array.
1.582     raeburn  7232:     if ($nav_error) {
                   7233:         $r->print(&navmap_errormsg());
                   7234:         return(1,$currentphase);
                   7235:     }
1.157     albertel 7236: 
                   7237:     my %found=('ids'=>{},'usernames'=>{});
                   7238:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
1.200     albertel 7239: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.157     albertel 7240: 	if ($line=~/^[\s\cz]*$/) { next; }
                   7241: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
                   7242: 						 $scan_data);
                   7243: 	my $id=$$scan_record{'scantron.ID'};
                   7244: 	my $found;
                   7245: 	foreach my $checkid (keys(%idmap)) {
                   7246: 	    if (lc($checkid) eq lc($id)) { $found=$checkid;last; }
                   7247: 	}
                   7248: 	if ($found) {
                   7249: 	    my $username=$idmap{$found};
                   7250: 	    if ($found{'ids'}{$found}) {
                   7251: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
                   7252: 					 $line,'duplicateID',$found);
1.194     albertel 7253: 		return(1,$currentphase);
1.157     albertel 7254: 	    } elsif ($found{'usernames'}{$username}) {
                   7255: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
                   7256: 					 $line,'duplicateID',$username);
1.194     albertel 7257: 		return(1,$currentphase);
1.157     albertel 7258: 	    }
1.186     albertel 7259: 	    #FIXME store away line we previously saw the ID on to use above
1.157     albertel 7260: 	    $found{'ids'}{$found}++;
                   7261: 	    $found{'usernames'}{$username}++;
                   7262: 	} else {
                   7263: 	    if ($id =~ /^\s*$/) {
1.158     albertel 7264: 		my $username=&scan_data($scan_data,"$i.user");
1.157     albertel 7265: 		if (defined($username) && $found{'usernames'}{$username}) {
                   7266: 		    &scantron_get_correction($r,$i,$scan_record,
                   7267: 					     \%scantron_config,
                   7268: 					     $line,'duplicateID',$username);
1.194     albertel 7269: 		    return(1,$currentphase);
1.157     albertel 7270: 		} elsif (!defined($username)) {
                   7271: 		    &scantron_get_correction($r,$i,$scan_record,
                   7272: 					     \%scantron_config,
                   7273: 					     $line,'incorrectID');
1.194     albertel 7274: 		    return(1,$currentphase);
1.157     albertel 7275: 		}
                   7276: 		$found{'usernames'}{$username}++;
                   7277: 	    } else {
                   7278: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
                   7279: 					 $line,'incorrectID');
1.194     albertel 7280: 		return(1,$currentphase);
1.157     albertel 7281: 	    }
                   7282: 	}
                   7283:     }
                   7284: 
                   7285:     return (0,$currentphase+1);
                   7286: }
                   7287: 
1.423     albertel 7288: 
1.157     albertel 7289: sub scantron_get_correction {
1.691     raeburn  7290:     my ($r,$i,$scan_record,$scan_config,$line,$error,$arg,
                   7291:         $randomorder,$randompick,$respnumlookup,$startline)=@_;
1.454     banghart 7292: #FIXME in the case of a duplicated ID the previous line, probably need
1.157     albertel 7293: #to show both the current line and the previous one and allow skipping
                   7294: #the previous one or the current one
                   7295: 
1.333     albertel 7296:     if ( $$scan_record{'scantron.PaperID'} =~ /\S/) {
1.658     bisitz   7297:         $r->print(
                   7298:             '<p class="LC_warning">'
                   7299:            .&mt('An error was detected ([_1]) for PaperID [_2]',
                   7300:                 "<b>$error</b>",
                   7301:                 '<tt>'.$$scan_record{'scantron.PaperID'}.'</tt>')
                   7302:            ."</p> \n");
1.157     albertel 7303:     } else {
1.658     bisitz   7304:         $r->print(
                   7305:             '<p class="LC_warning">'
                   7306:            .&mt('An error was detected ([_1]) in scanline [_2] [_3]',
                   7307:                 "<b>$error</b>", $i, "<pre>$line</pre>")
                   7308:            ."</p> \n");
                   7309:     }
                   7310:     my $message =
                   7311:         '<p>'
                   7312:        .&mt('The ID on the form is [_1]',
                   7313:             "<tt>$$scan_record{'scantron.ID'}</tt>")
                   7314:        .'<br />'
1.665     raeburn  7315:        .&mt('The name on the paper is [_1], [_2]',
1.658     bisitz   7316:             $$scan_record{'scantron.LastName'},
                   7317:             $$scan_record{'scantron.FirstName'})
                   7318:        .'</p>';
1.242     albertel 7319: 
1.157     albertel 7320:     $r->print('<input type="hidden" name="scantron_corrections" value="'.$error.'" />'."\n");
                   7321:     $r->print('<input type="hidden" name="scantron_line" value="'.$i.'" />'."\n");
1.503     raeburn  7322:                            # Array populated for doublebubble or
                   7323:     my @lines_to_correct;  # missingbubble errors to build javascript
                   7324:                            # to validate radio button checking   
                   7325: 
1.157     albertel 7326:     if ($error =~ /ID$/) {
1.186     albertel 7327: 	if ($error eq 'incorrectID') {
1.658     bisitz   7328:             $r->print('<p class="LC_warning">'.&mt("The encoded ID is not in the classlist").
1.492     albertel 7329: 		      "</p>\n");
1.157     albertel 7330: 	} elsif ($error eq 'duplicateID') {
1.658     bisitz   7331:             $r->print('<p class="LC_warning">'.&mt("The encoded ID has also been used by a previous paper [_1]",$arg)."</p>\n");
1.157     albertel 7332: 	}
1.242     albertel 7333: 	$r->print($message);
1.492     albertel 7334: 	$r->print("<p>".&mt("How should I handle this?")." <br /> \n");
1.157     albertel 7335: 	$r->print("\n<ul><li> ");
                   7336: 	#FIXME it would be nice if this sent back the user ID and
                   7337: 	#could do partial userID matches
                   7338: 	$r->print(&Apache::loncommon::selectstudent_link('scantronupload',
                   7339: 				       'scantron_username','scantron_domain'));
                   7340: 	$r->print(": <input type='text' name='scantron_username' value='' />");
1.685     bisitz   7341: 	$r->print("\n:\n".
1.257     albertel 7342: 		 &Apache::loncommon::select_dom_form($env{'request.role.domain'},'scantron_domain'));
1.157     albertel 7343: 
                   7344: 	$r->print('</li>');
1.186     albertel 7345:     } elsif ($error =~ /CODE$/) {
                   7346: 	if ($error eq 'incorrectCODE') {
1.658     bisitz   7347: 	    $r->print('<p class="LC_warning">'.&mt("The encoded CODE is not in the list of possible CODEs.")."</p>\n");
1.186     albertel 7348: 	} elsif ($error eq 'duplicateCODE') {
1.658     bisitz   7349: 	    $r->print('<p class="LC_warning">'.&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 7350: 	}
1.658     bisitz   7351: 	$r->print("<p>".&mt('The CODE on the form is [_1]',
                   7352: 			    "<tt>'$$scan_record{'scantron.CODE'}'</tt>")
                   7353:                  ."</p>\n");
1.242     albertel 7354: 	$r->print($message);
1.658     bisitz   7355: 	$r->print("<p>".&mt("How should I handle this?")."</p>\n");
1.187     albertel 7356: 	$r->print("\n<br /> ");
1.194     albertel 7357: 	my $i=0;
1.273     albertel 7358: 	if ($error eq 'incorrectCODE' 
                   7359: 	    && $$scan_record{'scantron.CODE'}=~/\S/ ) {
1.194     albertel 7360: 	    my ($max,$closest)=&scantron_get_closely_matching_CODEs($arg,$$scan_record{'scantron.CODE'});
1.278     albertel 7361: 	    if ($closest > 0) {
                   7362: 		foreach my $testcode (@{$closest}) {
                   7363: 		    my $checked='';
1.569     bisitz   7364: 		    if (!$i) { $checked=' checked="checked"'; }
1.492     albertel 7365: 		    $r->print("
                   7366:    <label>
1.569     bisitz   7367:        <input type='radio' name='scantron_CODE_resolution' value='use_closest_$i'$checked />
1.492     albertel 7368:        ".&mt("Use the similar CODE [_1] instead.",
                   7369: 	    "<b><tt>".$testcode."</tt></b>")."
                   7370:     </label>
                   7371:     <input type='hidden' name='scantron_CODE_closest_$i' value='$testcode' />");
1.278     albertel 7372: 		    $r->print("\n<br />");
                   7373: 		    $i++;
                   7374: 		}
1.194     albertel 7375: 	    }
                   7376: 	}
1.273     albertel 7377: 	if ($$scan_record{'scantron.CODE'}=~/\S/ ) {
1.569     bisitz   7378: 	    my $checked; if (!$i) { $checked=' checked="checked"'; }
1.492     albertel 7379: 	    $r->print("
                   7380:     <label>
1.569     bisitz   7381:         <input type='radio' name='scantron_CODE_resolution' value='use_unfound'$checked />
1.659     raeburn  7382:        ".&mt("Use the CODE [_1] that was on the paper, ignoring the error.",
1.492     albertel 7383: 	     "<b><tt>".$$scan_record{'scantron.CODE'}."</tt></b>")."
                   7384:     </label>");
1.273     albertel 7385: 	    $r->print("\n<br />");
                   7386: 	}
1.194     albertel 7387: 
1.597     wenzelju 7388: 	$r->print(&Apache::lonhtmlcommon::scripttag(<<ENDSCRIPT));
1.188     albertel 7389: function change_radio(field) {
1.190     albertel 7390:     var slct=document.scantronupload.scantron_CODE_resolution;
1.188     albertel 7391:     var i;
                   7392:     for (i=0;i<slct.length;i++) {
                   7393:         if (slct[i].value==field) { slct[i].checked=true; }
                   7394:     }
                   7395: }
                   7396: ENDSCRIPT
1.187     albertel 7397: 	my $href="/adm/pickcode?".
1.359     www      7398: 	   "form=".&escape("scantronupload").
                   7399: 	   "&scantron_format=".&escape($env{'form.scantron_format'}).
                   7400: 	   "&scantron_CODElist=".&escape($env{'form.scantron_CODElist'}).
                   7401: 	   "&curCODE=".&escape($$scan_record{'scantron.CODE'}).
                   7402: 	   "&scantron_selectfile=".&escape($env{'form.scantron_selectfile'});
1.332     albertel 7403: 	if ($env{'form.scantron_CODElist'} =~ /\S/) { 
1.492     albertel 7404: 	    $r->print("
                   7405:     <label>
                   7406:        <input type='radio' name='scantron_CODE_resolution' value='use_found' />
                   7407:        ".&mt("[_1]Select[_2] a CODE from the list of all CODEs and use it.",
                   7408: 	     "<a target='_blank' href='$href'>","</a>")."
                   7409:     </label> 
1.558     bisitz   7410:     ".&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 7411: 	    $r->print("\n<br />");
                   7412: 	}
1.492     albertel 7413: 	$r->print("
                   7414:     <label>
                   7415:        <input type='radio' name='scantron_CODE_resolution' value='use_typed' />
                   7416:        ".&mt("Use [_1] as the CODE.",
                   7417: 	     "</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 7418: 	$r->print("\n<br /><br />");
1.157     albertel 7419:     } elsif ($error eq 'doublebubble') {
1.658     bisitz   7420: 	$r->print('<p class="LC_warning">'.&mt("There have been multiple bubbles scanned for some question(s)")."</p>\n");
1.497     foxr     7421: 
                   7422: 	# The form field scantron_questions is acutally a list of line numbers.
                   7423: 	# represented by this form so:
                   7424: 
1.691     raeburn  7425: 	my $line_list = &questions_to_line_list($arg,$randomorder,$randompick,
                   7426:                                                 $respnumlookup,$startline);
1.497     foxr     7427: 
1.157     albertel 7428: 	$r->print('<input type="hidden" name="scantron_questions" value="'.
1.497     foxr     7429: 		  $line_list.'" />');
1.242     albertel 7430: 	$r->print($message);
1.492     albertel 7431: 	$r->print("<p>".&mt("Please indicate which bubble should be used for grading")."</p>");
1.157     albertel 7432: 	foreach my $question (@{$arg}) {
1.503     raeburn  7433: 	    my @linenums = &prompt_for_corrections($r,$question,$scan_config,
1.691     raeburn  7434:                                                    $scan_record, $error,
                   7435:                                                    $randomorder,$randompick,
                   7436:                                                    $respnumlookup,$startline);
1.524     raeburn  7437:             push(@lines_to_correct,@linenums);
1.157     albertel 7438: 	}
1.503     raeburn  7439:         $r->print(&verify_bubbles_checked(@lines_to_correct));
1.157     albertel 7440:     } elsif ($error eq 'missingbubble') {
1.658     bisitz   7441: 	$r->print('<p class="LC_warning">'.&mt("There have been [_1]no[_2] bubbles scanned for some question(s)",'<b>','</b>')."</p>\n");
1.242     albertel 7442: 	$r->print($message);
1.492     albertel 7443: 	$r->print("<p>".&mt("Please indicate which bubble should be used for grading.")."</p>");
1.503     raeburn  7444: 	$r->print(&mt("Some questions have no scanned bubbles.")."\n");
1.497     foxr     7445: 
1.503     raeburn  7446: 	# The form field scantron_questions is actually a list of line numbers not
1.497     foxr     7447: 	# a list of question numbers. Therefore:
                   7448: 	#
1.691     raeburn  7449: 
                   7450: 	my $line_list = &questions_to_line_list($arg,$randomorder,$randompick,
                   7451:                                                 $respnumlookup,$startline);
1.497     foxr     7452: 
1.157     albertel 7453: 	$r->print('<input type="hidden" name="scantron_questions" value="'.
1.497     foxr     7454: 		  $line_list.'" />');
1.157     albertel 7455: 	foreach my $question (@{$arg}) {
1.503     raeburn  7456: 	    my @linenums = &prompt_for_corrections($r,$question,$scan_config,
1.691     raeburn  7457:                                                    $scan_record, $error,
                   7458:                                                    $randomorder,$randompick,
                   7459:                                                    $respnumlookup,$startline);
1.524     raeburn  7460:             push(@lines_to_correct,@linenums);
1.157     albertel 7461: 	}
1.503     raeburn  7462:         $r->print(&verify_bubbles_checked(@lines_to_correct));
1.157     albertel 7463:     } else {
                   7464: 	$r->print("\n<ul>");
                   7465:     }
                   7466:     $r->print("\n</li></ul>");
1.497     foxr     7467: }
                   7468: 
1.503     raeburn  7469: sub verify_bubbles_checked {
                   7470:     my (@ansnums) = @_;
                   7471:     my $ansnumstr = join('","',@ansnums);
                   7472:     my $warning = &mt("A bubble or 'No bubble' selection has not been made for one or more lines.");
1.597     wenzelju 7473:     my $output = &Apache::lonhtmlcommon::scripttag((<<ENDSCRIPT));
1.503     raeburn  7474: function verify_bubble_radio(form) {
                   7475:     var ansnumArray = new Array ("$ansnumstr");
                   7476:     var need_bubble_count = 0;
                   7477:     for (var i=0; i<ansnumArray.length; i++) {
                   7478:         if (form.elements["scantron_correct_Q_"+ansnumArray[i]].length > 1) {
                   7479:             var bubble_picked = 0; 
                   7480:             for (var j=0; j<form.elements["scantron_correct_Q_"+ansnumArray[i]].length; j++) {
                   7481:                 if (form.elements["scantron_correct_Q_"+ansnumArray[i]][j].checked == true) {
                   7482:                     bubble_picked = 1;
                   7483:                 }
                   7484:             }
                   7485:             if (bubble_picked == 0) {
                   7486:                 need_bubble_count ++;
                   7487:             }
                   7488:         }
                   7489:     }
                   7490:     if (need_bubble_count) {
                   7491:         alert("$warning");
                   7492:         return;
                   7493:     }
                   7494:     form.submit(); 
                   7495: }
                   7496: ENDSCRIPT
                   7497:     return $output;
                   7498: }
                   7499: 
1.497     foxr     7500: =pod
                   7501: 
                   7502: =item  questions_to_line_list
1.157     albertel 7503: 
1.497     foxr     7504: Converts a list of questions into a string of comma separated
                   7505: line numbers in the answer sheet used by the questions.  This is
                   7506: used to fill in the scantron_questions form field.
                   7507: 
                   7508:   Arguments:
                   7509:      questions    - Reference to an array of questions.
1.691     raeburn  7510:      randomorder  - True if randomorder in use.
                   7511:      randompick   - True if randompick in use.
                   7512:      respnumlookup - Reference to HASH mapping question numbers in bubble lines
                   7513:                      for current line to question number used for same question
                   7514:                      in "Master Seqence" (as seen by Course Coordinator).
                   7515:      startline    - Reference to hash where key is question number (0 is first)
                   7516:                     and key is number of first bubble line for current student
                   7517:                     or code-based randompick and/or randomorder.
1.693     raeburn  7518: 
1.497     foxr     7519: =cut
                   7520: 
                   7521: 
                   7522: sub questions_to_line_list {
1.691     raeburn  7523:     my ($questions,$randomorder,$randompick,$respnumlookup,$startline) = @_;
1.497     foxr     7524:     my @lines;
                   7525: 
1.503     raeburn  7526:     foreach my $item (@{$questions}) {
                   7527:         my $question = $item;
                   7528:         my ($first,$count,$last);
                   7529:         if ($item =~ /^(\d+)\.(\d+)$/) {
                   7530:             $question = $1;
                   7531:             my $subquestion = $2;
1.691     raeburn  7532:             my $responsenum = $question-1;
                   7533:             if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH')) {
                   7534:                 $responsenum = $respnumlookup->{$question-1};
                   7535:                 if (ref($startline) eq 'HASH') {
                   7536:                     $first = $startline->{$question-1} + 1;
                   7537:                 }
                   7538:             } else {
                   7539:                 $first = $first_bubble_line{$responsenum} + 1;
                   7540:             }
                   7541:             my @subans = split(/,/,$subdivided_bubble_lines{$responsenum});
1.503     raeburn  7542:             my $subcount = 1;
                   7543:             while ($subcount<$subquestion) {
                   7544:                 $first += $subans[$subcount-1];
                   7545:                 $subcount ++;
                   7546:             }
                   7547:             $count = $subans[$subquestion-1];
                   7548:         } else {
1.691     raeburn  7549:             my $responsenum = $question-1;
                   7550:             if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH')) {
                   7551:                 $responsenum = $respnumlookup->{$question-1};
                   7552:                 if (ref($startline) eq 'HASH') {
                   7553:                     $first = $startline->{$question-1} + 1;
                   7554:                 }
                   7555:             } else {
                   7556:                 $first = $first_bubble_line{$responsenum} + 1;
                   7557:             }
                   7558: 	    $count   = $bubble_lines_per_response{$responsenum};
1.503     raeburn  7559:         }
1.506     raeburn  7560:         $last = $first+$count-1;
1.503     raeburn  7561:         push(@lines, ($first..$last));
1.497     foxr     7562:     }
                   7563:     return join(',', @lines);
                   7564: }
                   7565: 
                   7566: =pod 
                   7567: 
                   7568: =item prompt_for_corrections
                   7569: 
                   7570: Prompts for a potentially multiline correction to the
                   7571: user's bubbling (factors out common code from scantron_get_correction
                   7572: for multi and missing bubble cases).
                   7573: 
                   7574:  Arguments:
                   7575:    $r           - Apache request object.
                   7576:    $question    - The question number to prompt for.
                   7577:    $scan_config - The scantron file configuration hash.
                   7578:    $scan_record - Reference to the hash that has the the parsed scanlines.
1.503     raeburn  7579:    $error       - Type of error
1.691     raeburn  7580:    $randomorder - True if randomorder in use.
                   7581:    $randompick  - True if randompick in use.
                   7582:    $respnumlookup - Reference to HASH mapping question numbers in bubble lines
                   7583:                     for current line to question number used for same question
                   7584:                     in "Master Seqence" (as seen by Course Coordinator).
                   7585:    $startline   - Reference to hash where key is question number (0 is first)
                   7586:                   and value is number of first bubble line for current student
                   7587:                   or code-based randompick and/or randomorder.
                   7588: 
1.497     foxr     7589: 
                   7590:  Implicit inputs:
                   7591:    %bubble_lines_per_response   - Starting line numbers for each question.
                   7592:                                   Numbered from 0 (but question numbers are from
                   7593:                                   1.
                   7594:    %first_bubble_line           - Starting bubble line for each question.
1.509     raeburn  7595:    %subdivided_bubble_lines     - optionresponse, matchresponse and rankresponse 
                   7596:                                   type problems render as separate sub-questions, 
1.503     raeburn  7597:                                   in exam mode. This hash contains a 
                   7598:                                   comma-separated list of the lines per 
                   7599:                                   sub-question.
1.510     raeburn  7600:    %responsetype_per_response   - essayresponse, formularesponse,
                   7601:                                   stringresponse, imageresponse, reactionresponse,
                   7602:                                   and organicresponse type problem parts can have
1.503     raeburn  7603:                                   multiple lines per response if the weight
                   7604:                                   assigned exceeds 10.  In this case, only
                   7605:                                   one bubble per line is permitted, but more 
                   7606:                                   than one line might contain bubbles, e.g.
                   7607:                                   bubbling of: line 1 - J, line 2 - J, 
                   7608:                                   line 3 - B would assign 22 points.  
1.497     foxr     7609: 
                   7610: =cut
                   7611: 
                   7612: sub prompt_for_corrections {
1.691     raeburn  7613:     my ($r, $question, $scan_config, $scan_record, $error, $randomorder,
                   7614:         $randompick, $respnumlookup, $startline) = @_;
1.503     raeburn  7615:     my ($current_line,$lines);
                   7616:     my @linenums;
                   7617:     my $questionnum = $question;
1.691     raeburn  7618:     my ($first,$responsenum);
1.503     raeburn  7619:     if ($question =~ /^(\d+)\.(\d+)$/) {
                   7620:         $question = $1;
                   7621:         my $subquestion = $2;
1.691     raeburn  7622:         if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH')) {
                   7623:             $responsenum = $respnumlookup->{$question-1};
                   7624:             if (ref($startline) eq 'HASH') {
                   7625:                 $first = $startline->{$question-1};
                   7626:             }
                   7627:         } else {
                   7628:             $responsenum = $question-1;
1.714     raeburn  7629:             $first = $first_bubble_line{$responsenum};
1.691     raeburn  7630:         }
                   7631:         $current_line = $first + 1 ;
                   7632:         my @subans = split(/,/,$subdivided_bubble_lines{$responsenum});
1.503     raeburn  7633:         my $subcount = 1;
                   7634:         while ($subcount<$subquestion) {
                   7635:             $current_line += $subans[$subcount-1];
                   7636:             $subcount ++;
                   7637:         }
                   7638:         $lines = $subans[$subquestion-1];
                   7639:     } else {
1.691     raeburn  7640:         if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH')) {
                   7641:             $responsenum = $respnumlookup->{$question-1};
                   7642:             if (ref($startline) eq 'HASH') { 
                   7643:                 $first = $startline->{$question-1};
                   7644:             }
                   7645:         } else {
                   7646:             $responsenum = $question-1;
                   7647:             $first = $first_bubble_line{$responsenum};
                   7648:         }
                   7649:         $current_line = $first + 1;
                   7650:         $lines        = $bubble_lines_per_response{$responsenum};
1.503     raeburn  7651:     }
1.497     foxr     7652:     if ($lines > 1) {
1.503     raeburn  7653:         $r->print(&mt('The group of bubble lines below responds to a single question.').'<br />');
1.691     raeburn  7654:         if (($responsetype_per_response{$responsenum} eq 'essayresponse') ||
                   7655:             ($responsetype_per_response{$responsenum} eq 'formularesponse') ||
                   7656:             ($responsetype_per_response{$responsenum} eq 'stringresponse') ||
                   7657:             ($responsetype_per_response{$responsenum} eq 'imageresponse') ||
                   7658:             ($responsetype_per_response{$responsenum} eq 'reactionresponse') ||
                   7659:             ($responsetype_per_response{$responsenum} eq 'organicresponse')) {
1.684     bisitz   7660:             $r->print(
                   7661:                 &mt("Although this particular question type requires handgrading, the instructions for this question in the bubblesheet exam directed students to leave [quant,_1,line] blank on their bubblesheets.",$lines)
                   7662:                .'<br /><br />'
                   7663:                .&mt('A non-zero score can be assigned to the student during bubblesheet grading by selecting a bubble in at least one line.')
                   7664:                .'<br />'
                   7665:                .&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.')
                   7666:                .'<br />'
                   7667:                .&mt("To assign a score of zero for this question, mark all lines as 'No bubble'.")
                   7668:                .'<br /><br />'
                   7669:             );
1.503     raeburn  7670:         } else {
                   7671:             $r->print(&mt("Select at most one bubble in a single line and select 'No Bubble' in all the other lines. ")."<br />");
                   7672:         }
1.497     foxr     7673:     }
                   7674:     for (my $i =0; $i < $lines; $i++) {
1.503     raeburn  7675:         my $selected = $$scan_record{"scantron.$current_line.answer"};
1.691     raeburn  7676: 	&scantron_bubble_selector($r,$scan_config,$current_line,
1.503     raeburn  7677: 	        		  $questionnum,$error,split('', $selected));
1.524     raeburn  7678:         push(@linenums,$current_line);
1.497     foxr     7679: 	$current_line++;
                   7680:     }
                   7681:     if ($lines > 1) {
                   7682: 	$r->print("<hr /><br />");
                   7683:     }
1.503     raeburn  7684:     return @linenums;
1.157     albertel 7685: }
1.423     albertel 7686: 
                   7687: =pod
                   7688: 
                   7689: =item scantron_bubble_selector
                   7690:   
                   7691:    Generates the html radiobuttons to correct a single bubble line
1.424     albertel 7692:    possibly showing the existing the selected bubbles if known
1.423     albertel 7693: 
                   7694:  Arguments:
                   7695:     $r           - Apache request object
                   7696:     $scan_config - hash from &get_scantron_config()
1.497     foxr     7697:     $line        - Number of the line being displayed.
1.503     raeburn  7698:     $questionnum - Question number (may include subquestion)
                   7699:     $error       - Type of error.
1.497     foxr     7700:     @selected    - Array of bubbles picked on this line.
1.423     albertel 7701: 
                   7702: =cut
                   7703: 
1.157     albertel 7704: sub scantron_bubble_selector {
1.503     raeburn  7705:     my ($r,$scan_config,$line,$questionnum,$error,@selected)=@_;
1.157     albertel 7706:     my $max=$$scan_config{'Qlength'};
1.274     albertel 7707: 
                   7708:     my $scmode=$$scan_config{'Qon'};
1.649     raeburn  7709:     if ($scmode eq 'number' || $scmode eq 'letter') { 
                   7710:         if (($$scan_config{'BubblesPerRow'} =~ /^\d+$/) &&
                   7711:             ($$scan_config{'BubblesPerRow'} > 0)) {
                   7712:             $max=$$scan_config{'BubblesPerRow'};
                   7713:             if (($scmode eq 'number') && ($max > 10)) {
                   7714:                 $max = 10;
                   7715:             } elsif (($scmode eq 'letter') && $max > 26) {
                   7716:                 $max = 26;
                   7717:             }
                   7718:         } else {
                   7719:             $max = 10;
                   7720:         }
                   7721:     }
1.274     albertel 7722: 
1.157     albertel 7723:     my @alphabet=('A'..'Z');
1.503     raeburn  7724:     $r->print(&Apache::loncommon::start_data_table().
                   7725:               &Apache::loncommon::start_data_table_row());
                   7726:     $r->print('<td rowspan="2" class="LC_leftcol_header">'.$line.'</td>');
1.497     foxr     7727:     for (my $i=0;$i<$max+1;$i++) {
                   7728: 	$r->print("\n".'<td align="center">');
                   7729: 	if ($selected[0] eq $alphabet[$i]) { $r->print('X'); shift(@selected) }
                   7730: 	else { $r->print('&nbsp;'); }
                   7731: 	$r->print('</td>');
                   7732:     }
1.503     raeburn  7733:     $r->print(&Apache::loncommon::end_data_table_row().
                   7734:               &Apache::loncommon::start_data_table_row());
1.497     foxr     7735:     for (my $i=0;$i<$max;$i++) {
                   7736: 	$r->print("\n".
                   7737: 		  '<td><label><input type="radio" name="scantron_correct_Q_'.
                   7738: 		  $line.'" value="'.$i.'" />'.$alphabet[$i]."</label></td>");
                   7739:     }
1.503     raeburn  7740:     my $nobub_checked = ' ';
                   7741:     if ($error eq 'missingbubble') {
                   7742:         $nobub_checked = ' checked = "checked" ';
                   7743:     }
                   7744:     $r->print("\n".'<td><label><input type="radio" name="scantron_correct_Q_'.
                   7745: 	      $line.'" value="none"'.$nobub_checked.'/>'.&mt('No bubble').
                   7746:               '</label>'."\n".'<input type="hidden" name="scantron_questionnum_Q_'.
                   7747:               $line.'" value="'.$questionnum.'" /></td>');
                   7748:     $r->print(&Apache::loncommon::end_data_table_row().
                   7749:               &Apache::loncommon::end_data_table());
1.157     albertel 7750: }
                   7751: 
1.423     albertel 7752: =pod
                   7753: 
                   7754: =item num_matches
                   7755: 
1.424     albertel 7756:    Counts the number of characters that are the same between the two arguments.
                   7757: 
                   7758:  Arguments:
                   7759:    $orig - CODE from the scanline
                   7760:    $code - CODE to match against
                   7761: 
                   7762:  Returns:
                   7763:    $count - integer count of the number of same characters between the
                   7764:             two arguments
                   7765: 
1.423     albertel 7766: =cut
                   7767: 
1.194     albertel 7768: sub num_matches {
                   7769:     my ($orig,$code) = @_;
                   7770:     my @code=split(//,$code);
                   7771:     my @orig=split(//,$orig);
                   7772:     my $same=0;
                   7773:     for (my $i=0;$i<scalar(@code);$i++) {
                   7774: 	if ($code[$i] eq $orig[$i]) { $same++; }
                   7775:     }
                   7776:     return $same;
                   7777: }
                   7778: 
1.423     albertel 7779: =pod
                   7780: 
                   7781: =item scantron_get_closely_matching_CODEs
                   7782: 
1.424     albertel 7783:    Cycles through all CODEs and finds the set that has the greatest
                   7784:    number of same characters as the provided CODE
                   7785: 
                   7786:  Arguments:
                   7787:    $allcodes - hash ref returned by &get_codes()
                   7788:    $CODE     - CODE from the current scanline
                   7789: 
                   7790:  Returns:
                   7791:    2 element list
                   7792:     - first elements is number of how closely matching the best fit is 
                   7793:       (5 means best set has 5 matching characters)
                   7794:     - second element is an arrary ref containing the set of valid CODEs
                   7795:       that best fit the passed in CODE
                   7796: 
1.423     albertel 7797: =cut
                   7798: 
1.194     albertel 7799: sub scantron_get_closely_matching_CODEs {
                   7800:     my ($allcodes,$CODE)=@_;
                   7801:     my @CODEs;
                   7802:     foreach my $testcode (sort(keys(%{$allcodes}))) {
                   7803: 	push(@{$CODEs[&num_matches($CODE,$testcode)]},$testcode);
                   7804:     }
                   7805: 
                   7806:     return ($#CODEs,$CODEs[-1]);
                   7807: }
                   7808: 
1.423     albertel 7809: =pod
                   7810: 
                   7811: =item get_codes
                   7812: 
1.424     albertel 7813:    Builds a hash which has keys of all of the valid CODEs from the selected
                   7814:    set of remembered CODEs.
                   7815: 
                   7816:  Arguments:
                   7817:   $old_name - name of the set of remembered CODEs
                   7818:   $cdom     - domain of the course
                   7819:   $cnum     - internal course name
                   7820: 
                   7821:  Returns:
                   7822:   %allcodes - keys are the valid CODEs, values are all 1
                   7823: 
1.423     albertel 7824: =cut
                   7825: 
1.194     albertel 7826: sub get_codes {
1.280     foxr     7827:     my ($old_name, $cdom, $cnum) = @_;
                   7828:     if (!$old_name) {
                   7829: 	$old_name=$env{'form.scantron_CODElist'};
                   7830:     }
                   7831:     if (!$cdom) {
                   7832: 	$cdom =$env{'course.'.$env{'request.course.id'}.'.domain'};
                   7833:     }
                   7834:     if (!$cnum) {
                   7835: 	$cnum =$env{'course.'.$env{'request.course.id'}.'.num'};
                   7836:     }
1.278     albertel 7837:     my %result=&Apache::lonnet::get('CODEs',[$old_name,"type\0$old_name"],
                   7838: 				    $cdom,$cnum);
                   7839:     my %allcodes;
                   7840:     if ($result{"type\0$old_name"} eq 'number') {
                   7841: 	%allcodes=map {($_,1)} split(',',$result{$old_name});
                   7842:     } else {
                   7843: 	%allcodes=map {(&Apache::lonprintout::num_to_letters($_),1)} split(',',$result{$old_name});
                   7844:     }
1.194     albertel 7845:     return %allcodes;
                   7846: }
                   7847: 
1.423     albertel 7848: =pod
                   7849: 
                   7850: =item scantron_validate_CODE
                   7851: 
1.424     albertel 7852:    Validates all scanlines in the selected file to not have any
                   7853:    invalid or underspecified CODEs and that none of the codes are
                   7854:    duplicated if this was requested.
                   7855: 
1.423     albertel 7856: =cut
                   7857: 
1.157     albertel 7858: sub scantron_validate_CODE {
                   7859:     my ($r,$currentphase) = @_;
1.257     albertel 7860:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.186     albertel 7861:     if ($scantron_config{'CODElocation'} &&
                   7862: 	$scantron_config{'CODEstart'} &&
                   7863: 	$scantron_config{'CODElength'}) {
1.257     albertel 7864: 	if (!defined($env{'form.scantron_CODElist'})) {
1.186     albertel 7865: 	    &FIXME_blow_up()
                   7866: 	}
                   7867:     } else {
                   7868: 	return (0,$currentphase+1);
                   7869:     }
                   7870:     
                   7871:     my %usedCODEs;
                   7872: 
1.194     albertel 7873:     my %allcodes=&get_codes();
1.186     albertel 7874: 
1.582     raeburn  7875:     my $nav_error;
1.649     raeburn  7876:     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # parse needs the lines per response array.
1.582     raeburn  7877:     if ($nav_error) {
                   7878:         $r->print(&navmap_errormsg());
                   7879:         return(1,$currentphase);
                   7880:     }
1.447     foxr     7881: 
1.186     albertel 7882:     my ($scanlines,$scan_data)=&scantron_getfile();
                   7883:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
1.200     albertel 7884: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.186     albertel 7885: 	if ($line=~/^[\s\cz]*$/) { next; }
                   7886: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
                   7887: 						 $scan_data);
                   7888: 	my $CODE=$$scan_record{'scantron.CODE'};
                   7889: 	my $error=0;
1.224     albertel 7890: 	if (!&Apache::lonnet::validCODE($CODE)) {
                   7891: 	    &scantron_get_correction($r,$i,$scan_record,
                   7892: 				     \%scantron_config,
                   7893: 				     $line,'incorrectCODE',\%allcodes);
                   7894: 	    return(1,$currentphase);
                   7895: 	}
1.221     albertel 7896: 	if (%allcodes && !exists($allcodes{$CODE}) 
                   7897: 	    && !$$scan_record{'scantron.useCODE'}) {
1.186     albertel 7898: 	    &scantron_get_correction($r,$i,$scan_record,
                   7899: 				     \%scantron_config,
1.194     albertel 7900: 				     $line,'incorrectCODE',\%allcodes);
                   7901: 	    return(1,$currentphase);
1.186     albertel 7902: 	}
1.214     albertel 7903: 	if (exists($usedCODEs{$CODE}) 
1.257     albertel 7904: 	    && $env{'form.scantron_CODEunique'} eq 'yes'
1.192     albertel 7905: 	    && !$$scan_record{'scantron.CODE_ignore_dup'}) {
1.186     albertel 7906: 	    &scantron_get_correction($r,$i,$scan_record,
                   7907: 				     \%scantron_config,
1.194     albertel 7908: 				     $line,'duplicateCODE',$usedCODEs{$CODE});
                   7909: 	    return(1,$currentphase);
1.186     albertel 7910: 	}
1.524     raeburn  7911: 	push(@{$usedCODEs{$CODE}},$$scan_record{'scantron.PaperID'});
1.186     albertel 7912:     }
1.157     albertel 7913:     return (0,$currentphase+1);
                   7914: }
                   7915: 
1.423     albertel 7916: =pod
                   7917: 
                   7918: =item scantron_validate_doublebubble
                   7919: 
1.424     albertel 7920:    Validates all scanlines in the selected file to not have any
                   7921:    bubble lines with multiple bubbles marked.
                   7922: 
1.423     albertel 7923: =cut
                   7924: 
1.157     albertel 7925: sub scantron_validate_doublebubble {
                   7926:     my ($r,$currentphase) = @_;
                   7927:     #get student info
                   7928:     my $classlist=&Apache::loncoursedata::get_classlist();
                   7929:     my %idmap=&username_to_idmap($classlist);
1.691     raeburn  7930:     my (undef,undef,$sequence)=
                   7931:         &Apache::lonnet::decode_symb($env{'form.selectpage'});
1.157     albertel 7932: 
                   7933:     #get scantron line setup
1.257     albertel 7934:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.157     albertel 7935:     my ($scanlines,$scan_data)=&scantron_getfile();
1.691     raeburn  7936: 
                   7937:     my $navmap = Apache::lonnavmaps::navmap->new();
                   7938:     unless (ref($navmap)) {
                   7939:         $r->print(&navmap_errormsg());
                   7940:         return(1,$currentphase);
                   7941:     }
                   7942:     my $map=$navmap->getResourceByUrl($sequence);
                   7943:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
                   7944:     my ($randomorder,$randompick,@master_seq,%symb_to_resource,%grader_partids_by_symb,
                   7945:         %grader_randomlists_by_symb,%orderedforcode,%respnumlookup,%startline);
                   7946:     my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config);
                   7947: 
1.583     raeburn  7948:     my $nav_error;
1.691     raeburn  7949:     if (ref($map)) {
                   7950:         $randomorder = $map->randomorder();
                   7951:         $randompick = $map->randompick();
                   7952:         if ($randomorder || $randompick) {
                   7953:             $nav_error = &get_master_seq(\@resources,\@master_seq,\%symb_to_resource);
                   7954:             if ($nav_error) {
                   7955:                 $r->print(&navmap_errormsg());
                   7956:                 return(1,$currentphase);
                   7957:             }
                   7958:             &graders_resources_pass(\@resources,\%grader_partids_by_symb,
                   7959:                                     \%grader_randomlists_by_symb,$bubbles_per_row);
                   7960:         }
                   7961:     } else {
                   7962:         $r->print(&navmap_errormsg());
                   7963:         return(1,$currentphase);
                   7964:     }
                   7965: 
1.649     raeburn  7966:     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # parse needs the bubble line array.
1.583     raeburn  7967:     if ($nav_error) {
                   7968:         $r->print(&navmap_errormsg());
                   7969:         return(1,$currentphase);
                   7970:     }
1.447     foxr     7971: 
1.157     albertel 7972:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
1.200     albertel 7973: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.157     albertel 7974: 	if ($line=~/^[\s\cz]*$/) { next; }
                   7975: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
1.691     raeburn  7976: 						 $scan_data,undef,\%idmap,$randomorder,
                   7977:                                                  $randompick,$sequence,\@master_seq,
                   7978:                                                  \%symb_to_resource,\%grader_partids_by_symb,
                   7979:                                                  \%orderedforcode,\%respnumlookup,\%startline);
1.157     albertel 7980: 	if (!defined($$scan_record{'scantron.doubleerror'})) { next; }
                   7981: 	&scantron_get_correction($r,$i,$scan_record,\%scantron_config,$line,
                   7982: 				 'doublebubble',
1.691     raeburn  7983: 				 $$scan_record{'scantron.doubleerror'},
                   7984:                                  $randomorder,$randompick,\%respnumlookup,\%startline);
1.157     albertel 7985:     	return (1,$currentphase);
                   7986:     }
                   7987:     return (0,$currentphase+1);
                   7988: }
                   7989: 
1.423     albertel 7990: 
1.503     raeburn  7991: sub scantron_get_maxbubble {
1.649     raeburn  7992:     my ($nav_error,$scantron_config) = @_;
1.257     albertel 7993:     if (defined($env{'form.scantron_maxbubble'}) &&
                   7994: 	$env{'form.scantron_maxbubble'}) {
1.447     foxr     7995: 	&restore_bubble_lines();
1.257     albertel 7996: 	return $env{'form.scantron_maxbubble'};
1.191     albertel 7997:     }
1.330     albertel 7998: 
1.447     foxr     7999:     my (undef, undef, $sequence) =
1.257     albertel 8000: 	&Apache::lonnet::decode_symb($env{'form.selectpage'});
1.330     albertel 8001: 
1.447     foxr     8002:     my $navmap=Apache::lonnavmaps::navmap->new();
1.582     raeburn  8003:     unless (ref($navmap)) {
                   8004:         if (ref($nav_error)) {
                   8005:             $$nav_error = 1;
                   8006:         }
1.591     raeburn  8007:         return;
1.582     raeburn  8008:     }
1.191     albertel 8009:     my $map=$navmap->getResourceByUrl($sequence);
                   8010:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
1.649     raeburn  8011:     my $bubbles_per_row = &bubblesheet_bubbles_per_row($scantron_config);
1.330     albertel 8012: 
                   8013:     &Apache::lonxml::clear_problem_counter();
                   8014: 
1.557     raeburn  8015:     my $uname       = $env{'user.name'};
                   8016:     my $udom        = $env{'user.domain'};
1.435     foxr     8017:     my $cid         = $env{'request.course.id'};
                   8018:     my $total_lines = 0;
                   8019:     %bubble_lines_per_response = ();
1.447     foxr     8020:     %first_bubble_line         = ();
1.503     raeburn  8021:     %subdivided_bubble_lines   = ();
                   8022:     %responsetype_per_response = ();
1.691     raeburn  8023:     %masterseq_id_responsenum  = ();
1.554     raeburn  8024: 
1.447     foxr     8025:     my $response_number = 0;
                   8026:     my $bubble_line     = 0;
1.191     albertel 8027:     foreach my $resource (@resources) {
1.691     raeburn  8028:         my $resid = $resource->id(); 
1.672     raeburn  8029:         my ($analysis,$parts) = &scantron_partids_tograde($resource,$cid,$uname,
                   8030:                                                           $udom,undef,$bubbles_per_row);
1.542     raeburn  8031:         if ((ref($analysis) eq 'HASH') && (ref($parts) eq 'ARRAY')) {
                   8032: 	    foreach my $part_id (@{$parts}) {
                   8033:                 my $lines;
                   8034: 
                   8035: 	        # TODO - make this a persistent hash not an array.
                   8036: 
                   8037:                 # optionresponse, matchresponse and rankresponse type items 
                   8038:                 # render as separate sub-questions in exam mode.
                   8039:                 if (($analysis->{$part_id.'.type'} eq 'optionresponse') ||
                   8040:                     ($analysis->{$part_id.'.type'} eq 'matchresponse') ||
                   8041:                     ($analysis->{$part_id.'.type'} eq 'rankresponse')) {
                   8042:                     my ($numbub,$numshown);
                   8043:                     if ($analysis->{$part_id.'.type'} eq 'optionresponse') {
                   8044:                         if (ref($analysis->{$part_id.'.options'}) eq 'ARRAY') {
                   8045:                             $numbub = scalar(@{$analysis->{$part_id.'.options'}});
                   8046:                         }
                   8047:                     } elsif ($analysis->{$part_id.'.type'} eq 'matchresponse') {
                   8048:                         if (ref($analysis->{$part_id.'.items'}) eq 'ARRAY') {
                   8049:                             $numbub = scalar(@{$analysis->{$part_id.'.items'}});
                   8050:                         }
                   8051:                     } elsif ($analysis->{$part_id.'.type'} eq 'rankresponse') {
                   8052:                         if (ref($analysis->{$part_id.'.foils'}) eq 'ARRAY') {
                   8053:                             $numbub = scalar(@{$analysis->{$part_id.'.foils'}});
                   8054:                         }
                   8055:                     }
                   8056:                     if (ref($analysis->{$part_id.'.shown'}) eq 'ARRAY') {
                   8057:                         $numshown = scalar(@{$analysis->{$part_id.'.shown'}});
                   8058:                     }
1.649     raeburn  8059:                     my $bubbles_per_row =
                   8060:                         &bubblesheet_bubbles_per_row($scantron_config);
                   8061:                     my $inner_bubble_lines = int($numbub/$bubbles_per_row);
                   8062:                     if (($numbub % $bubbles_per_row) != 0) {
1.542     raeburn  8063:                         $inner_bubble_lines++;
                   8064:                     }
                   8065:                     for (my $i=0; $i<$numshown; $i++) {
                   8066:                         $subdivided_bubble_lines{$response_number} .= 
                   8067:                             $inner_bubble_lines.',';
                   8068:                     }
                   8069:                     $subdivided_bubble_lines{$response_number} =~ s/,$//;
                   8070:                     $lines = $numshown * $inner_bubble_lines;
                   8071:                 } else {
                   8072:                     $lines = $analysis->{"$part_id.bubble_lines"};
1.649     raeburn  8073:                 }
1.542     raeburn  8074: 
                   8075:                 $first_bubble_line{$response_number} = $bubble_line;
                   8076: 	        $bubble_lines_per_response{$response_number} = $lines;
                   8077:                 $responsetype_per_response{$response_number} = 
                   8078:                     $analysis->{$part_id.'.type'};
1.691     raeburn  8079:                 $masterseq_id_responsenum{$resid.'_'.$part_id} = $response_number;  
1.542     raeburn  8080: 	        $response_number++;
                   8081: 
                   8082: 	        $bubble_line +=  $lines;
                   8083: 	        $total_lines +=  $lines;
                   8084: 	    }
                   8085:         }
                   8086:     }
1.552     raeburn  8087:     &Apache::lonnet::delenv('scantron.');
1.542     raeburn  8088: 
                   8089:     &save_bubble_lines();
                   8090:     $env{'form.scantron_maxbubble'} =
                   8091: 	$total_lines;
                   8092:     return $env{'form.scantron_maxbubble'};
                   8093: }
1.523     raeburn  8094: 
1.649     raeburn  8095: sub bubblesheet_bubbles_per_row {
                   8096:     my ($scantron_config) = @_;
                   8097:     my $bubbles_per_row;
                   8098:     if (ref($scantron_config) eq 'HASH') {
                   8099:         $bubbles_per_row = $scantron_config->{'BubblesPerRow'};
                   8100:     }
                   8101:     if ((!$bubbles_per_row) || ($bubbles_per_row < 1)) {
                   8102:         $bubbles_per_row = 10;
                   8103:     }
                   8104:     return $bubbles_per_row;
                   8105: }
                   8106: 
1.157     albertel 8107: sub scantron_validate_missingbubbles {
                   8108:     my ($r,$currentphase) = @_;
                   8109:     #get student info
                   8110:     my $classlist=&Apache::loncoursedata::get_classlist();
                   8111:     my %idmap=&username_to_idmap($classlist);
1.691     raeburn  8112:     my (undef,undef,$sequence)=
                   8113:         &Apache::lonnet::decode_symb($env{'form.selectpage'});
1.157     albertel 8114: 
                   8115:     #get scantron line setup
1.257     albertel 8116:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.157     albertel 8117:     my ($scanlines,$scan_data)=&scantron_getfile();
1.691     raeburn  8118: 
                   8119:     my $navmap = Apache::lonnavmaps::navmap->new();
                   8120:     unless (ref($navmap)) {
                   8121:         $r->print(&navmap_errormsg());
                   8122:         return(1,$currentphase);
                   8123:     }
                   8124: 
                   8125:     my $map=$navmap->getResourceByUrl($sequence);
                   8126:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
                   8127:     my ($randomorder,$randompick,@master_seq,%symb_to_resource,%grader_partids_by_symb,
                   8128:         %grader_randomlists_by_symb,%orderedforcode,%respnumlookup,%startline);
                   8129:     my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config);
                   8130: 
1.582     raeburn  8131:     my $nav_error;
1.691     raeburn  8132:     if (ref($map)) {
                   8133:         $randomorder = $map->randomorder();
                   8134:         $randompick = $map->randompick();
                   8135:         if ($randomorder || $randompick) {
                   8136:             $nav_error = &get_master_seq(\@resources,\@master_seq,\%symb_to_resource);
                   8137:             if ($nav_error) {
                   8138:                 $r->print(&navmap_errormsg());
                   8139:                 return(1,$currentphase);
                   8140:             }
                   8141:             &graders_resources_pass(\@resources,\%grader_partids_by_symb,
                   8142:                                     \%grader_randomlists_by_symb,$bubbles_per_row);
                   8143:         }
                   8144:     } else {
                   8145:         $r->print(&navmap_errormsg());
                   8146:         return(1,$currentphase);
                   8147:     }
                   8148: 
                   8149: 
1.649     raeburn  8150:     my $max_bubble=&scantron_get_maxbubble(\$nav_error,\%scantron_config);
1.582     raeburn  8151:     if ($nav_error) {
1.691     raeburn  8152:         $r->print(&navmap_errormsg());
1.693     raeburn  8153:         return(1,$currentphase);
1.582     raeburn  8154:     }
1.691     raeburn  8155: 
1.157     albertel 8156:     if (!$max_bubble) { $max_bubble=2**31; }
                   8157:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
1.200     albertel 8158: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.157     albertel 8159: 	if ($line=~/^[\s\cz]*$/) { next; }
1.691     raeburn  8160: 	my $scan_record =
                   8161:             &scantron_parse_scanline($line,$i,\%scantron_config,$scan_data,undef,\%idmap,
                   8162: 				     $randomorder,$randompick,$sequence,\@master_seq,
                   8163:                                      \%symb_to_resource,\%grader_partids_by_symb,
                   8164:                                      \%orderedforcode,\%respnumlookup,\%startline);
1.157     albertel 8165: 	if (!defined($$scan_record{'scantron.missingerror'})) { next; }
                   8166: 	my @to_correct;
1.470     foxr     8167: 	
                   8168: 	# Probably here's where the error is...
                   8169: 
1.157     albertel 8170: 	foreach my $missing (@{$$scan_record{'scantron.missingerror'}}) {
1.505     raeburn  8171:             my $lastbubble;
                   8172:             if ($missing =~ /^(\d+)\.(\d+)$/) {
                   8173:                my $question = $1;
                   8174:                my $subquestion = $2;
1.691     raeburn  8175:                my ($first,$responsenum);
                   8176:                if ($randomorder || $randompick) {
                   8177:                    $responsenum = $respnumlookup{$question-1};
                   8178:                    $first = $startline{$question-1};
                   8179:                } else {
                   8180:                    $responsenum = $question-1; 
                   8181:                    $first = $first_bubble_line{$responsenum};
                   8182:                }
                   8183:                if (!defined($first)) { next; }
                   8184:                my @subans = split(/,/,$subdivided_bubble_lines{$responsenum});
1.505     raeburn  8185:                my $subcount = 1;
                   8186:                while ($subcount<$subquestion) {
                   8187:                    $first += $subans[$subcount-1];
                   8188:                    $subcount ++;
                   8189:                }
                   8190:                my $count = $subans[$subquestion-1];
                   8191:                $lastbubble = $first + $count;
                   8192:             } else {
1.691     raeburn  8193:                my ($first,$responsenum);
                   8194:                if ($randomorder || $randompick) {
                   8195:                    $responsenum = $respnumlookup{$missing-1};
                   8196:                    $first = $startline{$missing-1};
                   8197:                } else {
                   8198:                    $responsenum = $missing-1;
                   8199:                    $first = $first_bubble_line{$responsenum};
                   8200:                }
                   8201:                if (!defined($first)) { next; }
                   8202:                $lastbubble = $first + $bubble_lines_per_response{$responsenum};
1.505     raeburn  8203:             }
                   8204:             if ($lastbubble > $max_bubble) { next; }
1.157     albertel 8205: 	    push(@to_correct,$missing);
                   8206: 	}
                   8207: 	if (@to_correct) {
                   8208: 	    &scantron_get_correction($r,$i,$scan_record,\%scantron_config,
1.691     raeburn  8209: 				     $line,'missingbubble',\@to_correct,
                   8210:                                      $randomorder,$randompick,\%respnumlookup,
                   8211:                                      \%startline);
1.157     albertel 8212: 	    return (1,$currentphase);
                   8213: 	}
                   8214: 
                   8215:     }
                   8216:     return (0,$currentphase+1);
                   8217: }
                   8218: 
1.663     raeburn  8219: sub hand_bubble_option {
                   8220:     my (undef, undef, $sequence) =
                   8221:         &Apache::lonnet::decode_symb($env{'form.selectpage'});
                   8222:     return if ($sequence eq '');
                   8223:     my $navmap = Apache::lonnavmaps::navmap->new();
                   8224:     unless (ref($navmap)) {
                   8225:         return;
                   8226:     }
                   8227:     my $needs_hand_bubbles;
                   8228:     my $map=$navmap->getResourceByUrl($sequence);
                   8229:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
                   8230:     foreach my $res (@resources) {
                   8231:         if (ref($res)) {
                   8232:             if ($res->is_problem()) {
                   8233:                 my $partlist = $res->parts();
                   8234:                 foreach my $part (@{ $partlist }) {
                   8235:                     my @types = $res->responseType($part);
                   8236:                     if (grep(/^(chem|essay|image|formula|math|string|functionplot)$/,@types)) {
                   8237:                         $needs_hand_bubbles = 1;
                   8238:                         last;
                   8239:                     }
                   8240:                 }
                   8241:             }
                   8242:         }
                   8243:     }
                   8244:     if ($needs_hand_bubbles) {
                   8245:         my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
                   8246:         my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config);
                   8247:         return &mt('The sequence to be graded contains response types which are handgraded.').'<p>'.
                   8248:                &mt('If you have already graded these by bubbling sheets to indicate points awarded, [_1]what point value is assigned to a filled last bubble in each row?','<br />').
                   8249:                '<label><input type="radio" name="scantron_lastbubblepoints" value="'.$bubbles_per_row.'" checked="checked" />'.&mt('[quant,_1,point]',$bubbles_per_row).'</label>&nbsp;'.&mt('or').'&nbsp;'.
                   8250:                '<label><input type="radio" name="scantron_lastbubblepoints" value="0"/>0 points</label></p>';
                   8251:     }
                   8252:     return;
                   8253: }
1.423     albertel 8254: 
1.82      albertel 8255: sub scantron_process_students {
1.608     www      8256:     my ($r,$symb) = @_;
1.513     foxr     8257: 
1.257     albertel 8258:     my (undef,undef,$sequence)=&Apache::lonnet::decode_symb($env{'form.selectpage'});
1.513     foxr     8259:     if (!$symb) {
                   8260: 	return '';
                   8261:     }
1.324     albertel 8262:     my $default_form_data=&defaultFormData($symb);
1.82      albertel 8263: 
1.257     albertel 8264:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.691     raeburn  8265:     my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config); 
1.157     albertel 8266:     my ($scanlines,$scan_data)=&scantron_getfile();
1.82      albertel 8267:     my $classlist=&Apache::loncoursedata::get_classlist();
                   8268:     my %idmap=&username_to_idmap($classlist);
1.132     bowersj2 8269:     my $navmap=Apache::lonnavmaps::navmap->new();
1.582     raeburn  8270:     unless (ref($navmap)) {
                   8271:         $r->print(&navmap_errormsg());
                   8272:         return '';
1.691     raeburn  8273:     }
1.83      albertel 8274:     my $map=$navmap->getResourceByUrl($sequence);
1.691     raeburn  8275:     my ($randomorder,$randompick,@master_seq,%symb_to_resource,%grader_partids_by_symb,
1.693     raeburn  8276:         %grader_randomlists_by_symb);
1.677     raeburn  8277:     if (ref($map)) {
                   8278:         $randomorder = $map->randomorder();
1.689     raeburn  8279:         $randompick = $map->randompick();
1.691     raeburn  8280:     } else {
                   8281:         $r->print(&navmap_errormsg());
                   8282:         return '';
1.677     raeburn  8283:     }
1.691     raeburn  8284:     my $nav_error;
1.83      albertel 8285:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
1.691     raeburn  8286:     if ($randomorder || $randompick) {
                   8287:         $nav_error = &get_master_seq(\@resources,\@master_seq,\%symb_to_resource);
                   8288:         if ($nav_error) {
                   8289:             $r->print(&navmap_errormsg());
                   8290:             return '';
                   8291:         }
                   8292:     }
1.557     raeburn  8293:     &graders_resources_pass(\@resources,\%grader_partids_by_symb,
1.649     raeburn  8294:                             \%grader_randomlists_by_symb,$bubbles_per_row);
1.557     raeburn  8295: 
1.554     raeburn  8296:     my ($uname,$udom);
1.82      albertel 8297:     my $result= <<SCANTRONFORM;
1.81      albertel 8298: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantronupload">
                   8299:   <input type="hidden" name="command" value="scantron_configphase" />
                   8300:   $default_form_data
                   8301: SCANTRONFORM
1.82      albertel 8302:     $r->print($result);
                   8303: 
                   8304:     my @delayqueue;
1.542     raeburn  8305:     my (%completedstudents,%scandata);
1.140     albertel 8306:     
1.520     www      8307:     my $lock=&Apache::lonnet::set_lock(&mt('Grading bubblesheet exam'));
1.200     albertel 8308:     my $count=&get_todo_count($scanlines,$scan_data);
1.667     www      8309:     my %prog_state=&Apache::lonhtmlcommon::Create_PrgWin($r,$count);
                   8310:     &Apache::lonhtmlcommon::Update_PrgWin($r,\%prog_state,'Processing first student');
1.542     raeburn  8311:     $r->print('<br />');
1.140     albertel 8312:     my $start=&Time::HiRes::time();
1.158     albertel 8313:     my $i=-1;
1.542     raeburn  8314:     my $started;
1.447     foxr     8315: 
1.649     raeburn  8316:     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # Need the bubble lines array to parse.
1.582     raeburn  8317:     if ($nav_error) {
                   8318:         $r->print(&navmap_errormsg());
                   8319:         return '';
                   8320:     }
                   8321: 
1.513     foxr     8322:     # If an ssi failed in scantron_get_maxbubble, put an error message out to
                   8323:     # the user and return.
                   8324: 
                   8325:     if ($ssi_error) {
                   8326: 	$r->print("</form>");
                   8327: 	&ssi_print_error($r);
1.520     www      8328:         &Apache::lonnet::remove_lock($lock);
1.513     foxr     8329: 	return '';		# Dunno why the other returns return '' rather than just returning.
                   8330:     }
1.447     foxr     8331: 
1.542     raeburn  8332:     my %lettdig = &letter_to_digits();
                   8333:     my $numletts = scalar(keys(%lettdig));
1.691     raeburn  8334:     my %orderedforcode;
1.542     raeburn  8335: 
1.157     albertel 8336:     while ($i<$scanlines->{'count'}) {
                   8337:  	($uname,$udom)=('','');
                   8338:  	$i++;
1.200     albertel 8339:  	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.157     albertel 8340:  	if ($line=~/^[\s\cz]*$/) { next; }
1.200     albertel 8341: 	if ($started) {
1.667     www      8342: 	    &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state,'last student');
1.200     albertel 8343: 	}
                   8344: 	$started=1;
1.691     raeburn  8345:         my %respnumlookup = ();
                   8346:         my %startline = ();
                   8347:         my $total;
1.157     albertel 8348:  	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
1.691     raeburn  8349:                                                  $scan_data,undef,\%idmap,$randomorder,
                   8350:                                                  $randompick,$sequence,\@master_seq,
                   8351:                                                  \%symb_to_resource,\%grader_partids_by_symb,
                   8352:                                                  \%orderedforcode,\%respnumlookup,\%startline,
                   8353:                                                  \$total);
1.157     albertel 8354:  	unless ($uname=&scantron_find_student($scan_record,$scan_data,
                   8355:  					      \%idmap,$i)) {
                   8356:   	    &scantron_add_delay(\@delayqueue,$line,
                   8357:  				'Unable to find a student that matches',1);
                   8358:  	    next;
                   8359:   	}
                   8360:  	if (exists $completedstudents{$uname}) {
                   8361:  	    &scantron_add_delay(\@delayqueue,$line,
                   8362:  				'Student '.$uname.' has multiple sheets',2);
                   8363:  	    next;
                   8364:  	}
1.677     raeburn  8365:         my $usec = $classlist->{$uname}->[&Apache::loncoursedata::CL_SECTION];
                   8366:         my $user = $uname.':'.$usec;
1.157     albertel 8367:   	($uname,$udom)=split(/:/,$uname);
1.330     albertel 8368: 
1.677     raeburn  8369:         my $scancode;
                   8370:         if ((exists($scan_record->{'scantron.CODE'})) &&
                   8371:             (&Apache::lonnet::validCODE($scan_record->{'scantron.CODE'}))) {
                   8372:             $scancode = $scan_record->{'scantron.CODE'};
                   8373:         } else {
                   8374:             $scancode = '';
                   8375:         }
                   8376: 
                   8377:         my @mapresources = @resources;
1.689     raeburn  8378:         if ($randomorder || $randompick) {
1.678     raeburn  8379:             @mapresources = 
1.691     raeburn  8380:                 &users_order($user,$scancode,$sequence,\@master_seq,\%symb_to_resource,
                   8381:                              \%orderedforcode);
1.677     raeburn  8382:         }
1.586     raeburn  8383:         my (%partids_by_symb,$res_error);
1.677     raeburn  8384:         foreach my $resource (@mapresources) {
1.586     raeburn  8385:             my $ressymb;
                   8386:             if (ref($resource)) {
                   8387:                 $ressymb = $resource->symb();
                   8388:             } else {
                   8389:                 $res_error = 1;
                   8390:                 last;
                   8391:             }
1.557     raeburn  8392:             if ((exists($grader_randomlists_by_symb{$ressymb})) ||
                   8393:                 (ref($grader_partids_by_symb{$ressymb}) ne 'ARRAY')) {
                   8394:                 my ($analysis,$parts) =
1.672     raeburn  8395:                     &scantron_partids_tograde($resource,$env{'request.course.id'},
                   8396:                                               $uname,$udom,undef,$bubbles_per_row);
1.557     raeburn  8397:                 $partids_by_symb{$ressymb} = $parts;
                   8398:             } else {
                   8399:                 $partids_by_symb{$ressymb} = $grader_partids_by_symb{$ressymb};
                   8400:             }
1.554     raeburn  8401:         }
                   8402: 
1.586     raeburn  8403:         if ($res_error) {
                   8404:             &scantron_add_delay(\@delayqueue,$line,
                   8405:                                 'An error occurred while grading student '.$uname,2);
                   8406:             next;
                   8407:         }
                   8408: 
1.330     albertel 8409: 	&Apache::lonxml::clear_problem_counter();
1.514     raeburn  8410:   	&Apache::lonnet::appenv($scan_record);
1.376     albertel 8411: 
                   8412: 	if (&scantron_clear_skip($scanlines,$scan_data,$i)) {
                   8413: 	    &scantron_putfile($scanlines,$scan_data);
                   8414: 	}
1.161     albertel 8415: 	
1.542     raeburn  8416:         if (&grade_student_bubbles($r,$uname,$udom,$scan_record,$scancode,
1.677     raeburn  8417:                                    \@mapresources,\%partids_by_symb,
1.691     raeburn  8418:                                    $bubbles_per_row,$randomorder,$randompick,
                   8419:                                    \%respnumlookup,\%startline) 
                   8420:             eq 'ssi_error') {
1.542     raeburn  8421:             $ssi_error = 0; # So end of handler error message does not trigger.
                   8422:             $r->print("</form>");
                   8423:             &ssi_print_error($r);
                   8424:             &Apache::lonnet::remove_lock($lock);
                   8425:             return '';      # Why return ''?  Beats me.
                   8426:         }
1.513     foxr     8427: 
1.692     raeburn  8428:         if (($scancode) && ($randomorder || $randompick)) {
                   8429:             my $parmresult =
                   8430:                 &Apache::lonparmset::storeparm_by_symb($symb,
                   8431:                                                        '0_examcode',2,$scancode,
                   8432:                                                        'string_examcode',$uname,
                   8433:                                                        $udom);
                   8434:         }
1.140     albertel 8435: 	$completedstudents{$uname}={'line'=>$line};
1.542     raeburn  8436:         if ($env{'form.verifyrecord'}) {
                   8437:             my $lastpos = $env{'form.scantron_maxbubble'}*$scantron_config{'Qlength'};
1.691     raeburn  8438:             if ($randompick) {
                   8439:                 if ($total) {
                   8440:                     $lastpos = $total*$scantron_config{'Qlength'};
                   8441:                 }
                   8442:             }
                   8443: 
1.542     raeburn  8444:             my $studentdata = substr($line,$scantron_config{'Qstart'}-1,$lastpos);
                   8445:             chomp($studentdata);
                   8446:             $studentdata =~ s/\r$//;
                   8447:             my $studentrecord = '';
                   8448:             my $counter = -1;
1.677     raeburn  8449:             foreach my $resource (@mapresources) {
1.554     raeburn  8450:                 my $ressymb = $resource->symb();
1.542     raeburn  8451:                 ($counter,my $recording) =
                   8452:                     &verify_scantron_grading($resource,$udom,$uname,$env{'request.course.id'},
1.554     raeburn  8453:                                              $counter,$studentdata,$partids_by_symb{$ressymb},
1.691     raeburn  8454:                                              \%scantron_config,\%lettdig,$numletts,$randomorder,
                   8455:                                              $randompick,\%respnumlookup,\%startline);
1.542     raeburn  8456:                 $studentrecord .= $recording;
                   8457:             }
                   8458:             if ($studentrecord ne $studentdata) {
1.554     raeburn  8459:                 &Apache::lonxml::clear_problem_counter();
                   8460:                 if (&grade_student_bubbles($r,$uname,$udom,$scan_record,$scancode,
1.677     raeburn  8461:                                            \@mapresources,\%partids_by_symb,
1.691     raeburn  8462:                                            $bubbles_per_row,$randomorder,$randompick,
                   8463:                                            \%respnumlookup,\%startline) 
                   8464:                     eq 'ssi_error') {
1.554     raeburn  8465:                     $ssi_error = 0; # So end of handler error message does not trigger.
                   8466:                     $r->print("</form>");
                   8467:                     &ssi_print_error($r);
                   8468:                     &Apache::lonnet::remove_lock($lock);
                   8469:                     delete($completedstudents{$uname});
                   8470:                     return '';
                   8471:                 }
1.542     raeburn  8472:                 $counter = -1;
                   8473:                 $studentrecord = '';
1.677     raeburn  8474:                 foreach my $resource (@mapresources) {
1.554     raeburn  8475:                     my $ressymb = $resource->symb();
1.542     raeburn  8476:                     ($counter,my $recording) =
                   8477:                         &verify_scantron_grading($resource,$udom,$uname,$env{'request.course.id'},
1.554     raeburn  8478:                                                  $counter,$studentdata,$partids_by_symb{$ressymb},
1.691     raeburn  8479:                                                  \%scantron_config,\%lettdig,$numletts,
                   8480:                                                  $randomorder,$randompick,\%respnumlookup,
                   8481:                                                  \%startline);
1.542     raeburn  8482:                     $studentrecord .= $recording;
                   8483:                 }
                   8484:                 if ($studentrecord ne $studentdata) {
1.658     bisitz   8485:                     $r->print('<p><span class="LC_warning">');
1.542     raeburn  8486:                     if ($scancode eq '') {
1.658     bisitz   8487:                         $r->print(&mt('Mismatch grading bubblesheet for user: [_1] with ID: [_2].',
1.542     raeburn  8488:                                   $uname.':'.$udom,$scan_record->{'scantron.ID'}));
                   8489:                     } else {
1.658     bisitz   8490:                         $r->print(&mt('Mismatch grading bubblesheet for user: [_1] with ID: [_2] and CODE: [_3].',
1.542     raeburn  8491:                                   $uname.':'.$udom,$scan_record->{'scantron.ID'},$scancode));
                   8492:                     }
                   8493:                     $r->print('</span><br />'.&Apache::loncommon::start_data_table()."\n".
                   8494:                               &Apache::loncommon::start_data_table_header_row()."\n".
                   8495:                               '<th>'.&mt('Source').'</th><th>'.&mt('Bubbled responses').'</th>'.
                   8496:                               &Apache::loncommon::end_data_table_header_row()."\n".
                   8497:                               &Apache::loncommon::start_data_table_row().
1.658     bisitz   8498:                               '<td>'.&mt('Bubblesheet').'</td>'.
1.707     bisitz   8499:                               '<td><span class="LC_nobreak" style="white-space: pre;"><tt>'.$studentdata.'</tt></span></td>'.
1.542     raeburn  8500:                               &Apache::loncommon::end_data_table_row().
                   8501:                               &Apache::loncommon::start_data_table_row().
1.658     bisitz   8502:                               '<td>'.&mt('Stored submissions').'</td>'.
1.707     bisitz   8503:                               '<td><span class="LC_nobreak" style="white-space: pre;"><tt>'.$studentrecord.'</tt></span></td>'."\n".
1.542     raeburn  8504:                               &Apache::loncommon::end_data_table_row().
                   8505:                               &Apache::loncommon::end_data_table().'</p>');
                   8506:                 } else {
                   8507:                     $r->print('<br /><span class="LC_warning">'.
                   8508:                              &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 />'.
                   8509:                              &mt("As a consequence, this user's submission history records two tries.").
                   8510:                                  '</span><br />');
                   8511:                 }
                   8512:             }
                   8513:         }
1.543     raeburn  8514:         if (&Apache::loncommon::connection_aborted($r)) { last; }
1.140     albertel 8515:     } continue {
1.330     albertel 8516: 	&Apache::lonxml::clear_problem_counter();
1.552     raeburn  8517: 	&Apache::lonnet::delenv('scantron.');
1.82      albertel 8518:     }
1.140     albertel 8519:     &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
1.520     www      8520:     &Apache::lonnet::remove_lock($lock);
1.172     albertel 8521: #    my $lasttime = &Time::HiRes::time()-$start;
                   8522: #    $r->print("<p>took $lasttime</p>");
1.140     albertel 8523: 
1.200     albertel 8524:     $r->print("</form>");
1.157     albertel 8525:     return '';
1.75      albertel 8526: }
1.157     albertel 8527: 
1.557     raeburn  8528: sub graders_resources_pass {
1.649     raeburn  8529:     my ($resources,$grader_partids_by_symb,$grader_randomlists_by_symb,
                   8530:         $bubbles_per_row) = @_;
1.557     raeburn  8531:     if ((ref($resources) eq 'ARRAY') && (ref($grader_partids_by_symb)) && 
                   8532:         (ref($grader_randomlists_by_symb) eq 'HASH')) {
                   8533:         foreach my $resource (@{$resources}) {
                   8534:             my $ressymb = $resource->symb();
                   8535:             my ($analysis,$parts) =
                   8536:                 &scantron_partids_tograde($resource,$env{'request.course.id'},
1.672     raeburn  8537:                                           $env{'user.name'},$env{'user.domain'},
                   8538:                                           1,$bubbles_per_row);
1.557     raeburn  8539:             $grader_partids_by_symb->{$ressymb} = $parts;
                   8540:             if (ref($analysis) eq 'HASH') {
                   8541:                 if (ref($analysis->{'parts_withrandomlist'}) eq 'ARRAY') {
                   8542:                     $grader_randomlists_by_symb->{$ressymb} =
                   8543:                         $analysis->{'parts_withrandomlist'};
                   8544:                 }
                   8545:             }
                   8546:         }
                   8547:     }
                   8548:     return;
                   8549: }
                   8550: 
1.678     raeburn  8551: =pod
                   8552: 
                   8553: =item users_order
                   8554: 
                   8555:   Returns array of resources in current map, ordered based on either CODE,
                   8556:   if this is a CODEd exam, or based on student's identity if this is a 
                   8557:   "NAMEd" exam.
                   8558: 
1.691     raeburn  8559:   Should be used when randomorder and/or randompick applied when the 
                   8560:   corresponding exam was printed, prior to students completing bubblesheets 
                   8561:   for the version of the exam the student received.
1.678     raeburn  8562: 
                   8563: =cut
                   8564: 
                   8565: sub users_order  {
1.691     raeburn  8566:     my ($user,$scancode,$mapurl,$master_seq,$symb_to_resource,$orderedforcode) = @_;
1.678     raeburn  8567:     my @mapresources;
1.691     raeburn  8568:     unless ((ref($master_seq) eq 'ARRAY') && (ref($symb_to_resource) eq 'HASH')) {
1.678     raeburn  8569:         return @mapresources;
1.691     raeburn  8570:     }
                   8571:     if ($scancode) {
                   8572:         if ((ref($orderedforcode) eq 'HASH') && (ref($orderedforcode->{$scancode}) eq 'ARRAY')) {
                   8573:             @mapresources = @{$orderedforcode->{$scancode}};
                   8574:         } else {
                   8575:             $env{'form.CODE'} = $scancode;
                   8576:             my $actual_seq =
                   8577:                 &Apache::lonprintout::master_seq_to_person_seq($mapurl,
                   8578:                                                                $master_seq,
                   8579:                                                                $user,$scancode,1);
                   8580:             if (ref($actual_seq) eq 'ARRAY') {
                   8581:                 @mapresources = map { $symb_to_resource->{$_}; } @{$actual_seq};
                   8582:                 if (ref($orderedforcode) eq 'HASH') {
                   8583:                     if (@mapresources > 0) { 
                   8584:                         $orderedforcode->{$scancode} = \@mapresources;
                   8585:                     }
                   8586:                 }
                   8587:             }
                   8588:             delete($env{'form.CODE'});
1.678     raeburn  8589:         }
                   8590:     } else {
                   8591:         my $actual_seq =
                   8592:             &Apache::lonprintout::master_seq_to_person_seq($mapurl,
                   8593:                                                            $master_seq,
1.688     raeburn  8594:                                                            $user,undef,1);
1.678     raeburn  8595:         if (ref($actual_seq) eq 'ARRAY') {
                   8596:             @mapresources = 
                   8597:                 map { $symb_to_resource->{$_}; } @{$actual_seq};
                   8598:         }
1.691     raeburn  8599:     }
                   8600:     return @mapresources;
1.678     raeburn  8601: }
                   8602: 
1.542     raeburn  8603: sub grade_student_bubbles {
1.691     raeburn  8604:     my ($r,$uname,$udom,$scan_record,$scancode,$resources,$parts,$bubbles_per_row,
                   8605:         $randomorder,$randompick,$respnumlookup,$startline) = @_;
                   8606:     my $uselookup = 0;
                   8607:     if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH') &&
                   8608:         (ref($startline) eq 'HASH')) {
                   8609:         $uselookup = 1;
                   8610:     }
                   8611: 
1.554     raeburn  8612:     if (ref($resources) eq 'ARRAY') {
                   8613:         my $count = 0;
                   8614:         foreach my $resource (@{$resources}) {
                   8615:             my $ressymb = $resource->symb();
                   8616:             my %form = ('submitted'      => 'scantron',
                   8617:                         'grade_target'   => 'grade',
                   8618:                         'grade_username' => $uname,
                   8619:                         'grade_domain'   => $udom,
                   8620:                         'grade_courseid' => $env{'request.course.id'},
                   8621:                         'grade_symb'     => $ressymb,
                   8622:                         'CODE'           => $scancode
                   8623:                        );
1.649     raeburn  8624:             if ($bubbles_per_row ne '') {
                   8625:                 $form{'bubbles_per_row'} = $bubbles_per_row;
                   8626:             }
1.663     raeburn  8627:             if ($env{'form.scantron_lastbubblepoints'} ne '') {
                   8628:                 $form{'scantron_lastbubblepoints'} = $env{'form.scantron_lastbubblepoints'};
                   8629:             }
1.554     raeburn  8630:             if (ref($parts) eq 'HASH') {
                   8631:                 if (ref($parts->{$ressymb}) eq 'ARRAY') {
                   8632:                     foreach my $part (@{$parts->{$ressymb}}) {
1.691     raeburn  8633:                         if ($uselookup) {
                   8634:                             $form{'scantron_questnum_start.'.$part} = $startline->{$count} + 1;
                   8635:                         } else {
                   8636:                             $form{'scantron_questnum_start.'.$part} =
                   8637:                                 1+$env{'form.scantron.first_bubble_line.'.$count};
                   8638:                         }
1.554     raeburn  8639:                         $count++;
                   8640:                     }
                   8641:                 }
                   8642:             }
                   8643:             my $result=&ssi_with_retries($resource->src(),$ssi_retries,%form);
                   8644:             return 'ssi_error' if ($ssi_error);
                   8645:             last if (&Apache::loncommon::connection_aborted($r));
                   8646:         }
1.542     raeburn  8647:     }
                   8648:     return;
                   8649: }
                   8650: 
1.157     albertel 8651: sub scantron_upload_scantron_data {
1.608     www      8652:     my ($r,$symb)=@_;
1.565     raeburn  8653:     my $dom = $env{'request.role.domain'};
                   8654:     my $domdesc = &Apache::lonnet::domain($dom,'description');
                   8655:     $r->print(&Apache::loncommon::coursebrowser_javascript($dom));
1.157     albertel 8656:     my $select_link=&Apache::loncommon::selectcourse_link('rules','courseid',
1.181     albertel 8657: 							  'domainid',
1.565     raeburn  8658: 							  'coursename',$dom);
                   8659:     my $syllabuslink = '<a href="javascript:ToSyllabus();">'.&mt('Syllabus').'</a>'.
                   8660:                        ('&nbsp'x2).&mt('(shows course personnel)'); 
1.608     www      8661:     my $default_form_data=&defaultFormData($symb);
1.579     raeburn  8662:     my $nofile_alert = &mt('Please use the browse button to select a file from your local directory.');
                   8663:     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 8664:     $r->print(&Apache::lonhtmlcommon::scripttag('
1.157     albertel 8665:     function checkUpload(formname) {
                   8666: 	if (formname.upfile.value == "") {
1.579     raeburn  8667: 	    alert("'.$nofile_alert.'");
1.157     albertel 8668: 	    return false;
                   8669: 	}
1.565     raeburn  8670:         if (formname.courseid.value == "") {
1.579     raeburn  8671:             alert("'.$nocourseid_alert.'");
1.565     raeburn  8672:             return false;
                   8673:         }
1.157     albertel 8674: 	formname.submit();
                   8675:     }
1.565     raeburn  8676: 
                   8677:     function ToSyllabus() {
                   8678:         var cdom = '."'$dom'".';
                   8679:         var cnum = document.rules.courseid.value;
                   8680:         if (cdom == "" || cdom == null) {
                   8681:             return;
                   8682:         }
                   8683:         if (cnum == "" || cnum == null) {
                   8684:            return;
                   8685:         }
                   8686:         syllwin=window.open("/public/"+cdom+"/"+cnum+"/syllabus","LONCAPASyllabus",
                   8687:                             "height=350,width=350,scrollbars=yes,menubar=no");
                   8688:         return;
                   8689:     }
                   8690: 
1.597     wenzelju 8691: '));
                   8692:     $r->print('
1.648     bisitz   8693: <h3>'.&mt('Send bubblesheet data to a course').'</h3>
1.566     raeburn  8694: 
1.492     albertel 8695: <form enctype="multipart/form-data" action="/adm/grades" name="rules" method="post">
1.565     raeburn  8696: '.$default_form_data.
                   8697:   &Apache::lonhtmlcommon::start_pick_box().
                   8698:   &Apache::lonhtmlcommon::row_title(&mt('Course ID')).
                   8699:   '<input name="courseid" type="text" size="30" />'.$select_link.
                   8700:   &Apache::lonhtmlcommon::row_closure().
                   8701:   &Apache::lonhtmlcommon::row_title(&mt('Course Name')).
                   8702:   '<input name="coursename" type="text" size="30" />'.$syllabuslink.
                   8703:   &Apache::lonhtmlcommon::row_closure().
                   8704:   &Apache::lonhtmlcommon::row_title(&mt('Domain')).
                   8705:   '<input name="domainid" type="hidden" />'.$domdesc.
                   8706:   &Apache::lonhtmlcommon::row_closure().
                   8707:   &Apache::lonhtmlcommon::row_title(&mt('File to upload')).
                   8708:   '<input type="file" name="upfile" size="50" />'.
                   8709:   &Apache::lonhtmlcommon::row_closure(1).
                   8710:   &Apache::lonhtmlcommon::end_pick_box().'<br />
                   8711: 
1.492     albertel 8712: <input name="command" value="scantronupload_save" type="hidden" />
1.589     bisitz   8713: <input type="button" onclick="javascript:checkUpload(this.form);" value="'.&mt('Upload Bubblesheet Data').'" />
1.157     albertel 8714: </form>
1.492     albertel 8715: ');
1.157     albertel 8716:     return '';
                   8717: }
                   8718: 
1.423     albertel 8719: 
1.157     albertel 8720: sub scantron_upload_scantron_data_save {
1.608     www      8721:     my($r,$symb)=@_;
1.182     albertel 8722:     my $doanotherupload=
                   8723: 	'<br /><form action="/adm/grades" method="post">'."\n".
                   8724: 	'<input type="hidden" name="command" value="scantronupload" />'."\n".
1.492     albertel 8725: 	'<input type="submit" name="submit" value="'.&mt('Do Another Upload').'" />'."\n".
1.182     albertel 8726: 	'</form>'."\n";
1.257     albertel 8727:     if (!&Apache::lonnet::allowed('usc',$env{'form.domainid'}) &&
1.162     albertel 8728: 	!&Apache::lonnet::allowed('usc',
1.257     albertel 8729: 			    $env{'form.domainid'}.'_'.$env{'form.courseid'})) {
1.575     www      8730: 	$r->print(&mt("You are not allowed to upload bubblesheet data to the requested course.")."<br />");
1.614     www      8731: 	unless ($symb) {
1.182     albertel 8732: 	    $r->print($doanotherupload);
                   8733: 	}
1.162     albertel 8734: 	return '';
                   8735:     }
1.257     albertel 8736:     my %coursedata=&Apache::lonnet::coursedescription($env{'form.domainid'}.'_'.$env{'form.courseid'});
1.568     raeburn  8737:     my $uploadedfile;
1.710     bisitz   8738:     $r->print('<p>'.&mt('Uploading file to [_1]','"'.$coursedata{'description'}.'"').'</p>');
1.257     albertel 8739:     if (length($env{'form.upfile'}) < 2) {
1.710     bisitz   8740:         $r->print(
                   8741:             &Apache::lonhtmlcommon::confirm_success(
                   8742:                 &mt('The file: [_1] you attempted to upload contained no information. Please check that you entered the correct filename.',
                   8743:                         '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>'),1));
1.183     albertel 8744:     } else {
1.568     raeburn  8745:         my $result = 
                   8746:             &Apache::lonnet::userfileupload('upfile','','scantron','','','',
                   8747:                                             $env{'form.courseid'},$env{'form.domainid'});
1.710     bisitz   8748:         if ($result =~ m{^/uploaded/}) {
                   8749:             $r->print(
                   8750:                 &Apache::lonhtmlcommon::confirm_success(&mt('Upload successful')).'<br />'.
                   8751:                 &mt('Uploaded [_1] bytes of data into location: [_2]',
                   8752:                         (length($env{'form.upfile'})-1),
                   8753:                         '<span class="LC_filename">'.$result.'</span>'));
1.568     raeburn  8754:             ($uploadedfile) = ($result =~ m{/([^/]+)$});
1.567     raeburn  8755:             $r->print(&validate_uploaded_scantron_file($env{'form.domainid'},
1.568     raeburn  8756:                                                        $env{'form.courseid'},$uploadedfile));
1.710     bisitz   8757:         } else {
                   8758:             $r->print(
                   8759:                 &Apache::lonhtmlcommon::confirm_success(&mt('Upload failed'),1).'<br />'.
                   8760:                     &mt('An error ([_1]) occurred when attempting to upload the file: [_2]',
                   8761:                           $result,
1.568     raeburn  8762: 			  '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>'));
1.183     albertel 8763: 	}
                   8764:     }
1.174     albertel 8765:     if ($symb) {
1.612     www      8766: 	$r->print(&scantron_selectphase($r,$uploadedfile,$symb));
1.174     albertel 8767:     } else {
1.182     albertel 8768: 	$r->print($doanotherupload);
1.174     albertel 8769:     }
1.157     albertel 8770:     return '';
                   8771: }
                   8772: 
1.567     raeburn  8773: sub validate_uploaded_scantron_file {
                   8774:     my ($cdom,$cname,$fname) = @_;
                   8775:     my $scanlines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.$fname);
                   8776:     my @lines;
                   8777:     if ($scanlines ne '-1') {
                   8778:         @lines=split("\n",$scanlines,-1);
                   8779:     }
                   8780:     my $output;
                   8781:     if (@lines) {
                   8782:         my (%counts,$max_match_format);
1.710     bisitz   8783:         my ($found_match_count,$max_match_count,$max_match_pct) = (0,0,0);
1.567     raeburn  8784:         my $classlist = &Apache::loncoursedata::get_classlist($cdom,$cname);
                   8785:         my %idmap = &username_to_idmap($classlist);
                   8786:         foreach my $key (keys(%idmap)) {
                   8787:             my $lckey = lc($key);
                   8788:             $idmap{$lckey} = $idmap{$key};
                   8789:         }
                   8790:         my %unique_formats;
                   8791:         my @formatlines = &get_scantronformat_file();
                   8792:         foreach my $line (@formatlines) {
                   8793:             chomp($line);
                   8794:             my @config = split(/:/,$line);
                   8795:             my $idstart = $config[5];
                   8796:             my $idlength = $config[6];
                   8797:             if (($idstart ne '') && ($idlength > 0)) {
                   8798:                 if (ref($unique_formats{$idstart.':'.$idlength}) eq 'ARRAY') {
                   8799:                     push(@{$unique_formats{$idstart.':'.$idlength}},$config[0].':'.$config[1]); 
                   8800:                 } else {
                   8801:                     $unique_formats{$idstart.':'.$idlength} = [$config[0].':'.$config[1]];
                   8802:                 }
                   8803:             }
                   8804:         }
                   8805:         foreach my $key (keys(%unique_formats)) {
                   8806:             my ($idstart,$idlength) = split(':',$key);
                   8807:             %{$counts{$key}} = (
                   8808:                                'found'   => 0,
                   8809:                                'total'   => 0,
                   8810:                               );
                   8811:             foreach my $line (@lines) {
                   8812:                 next if ($line =~ /^#/);
                   8813:                 next if ($line =~ /^[\s\cz]*$/);
                   8814:                 my $id = substr($line,$idstart-1,$idlength);
                   8815:                 $id = lc($id);
                   8816:                 if (exists($idmap{$id})) {
                   8817:                     $counts{$key}{'found'} ++;
                   8818:                 }
                   8819:                 $counts{$key}{'total'} ++;
                   8820:             }
                   8821:             if ($counts{$key}{'total'}) {
                   8822:                 my $percent_match = (100*$counts{$key}{'found'})/($counts{$key}{'total'});
                   8823:                 if (($max_match_format eq '') || ($percent_match > $max_match_pct)) {
                   8824:                     $max_match_pct = $percent_match;
                   8825:                     $max_match_format = $key;
1.710     bisitz   8826:                     $found_match_count = $counts{$key}{'found'};
1.567     raeburn  8827:                     $max_match_count = $counts{$key}{'total'};
                   8828:                 }
                   8829:             }
                   8830:         }
                   8831:         if (ref($unique_formats{$max_match_format}) eq 'ARRAY') {
                   8832:             my $format_descs;
                   8833:             my $numwithformat = @{$unique_formats{$max_match_format}};
                   8834:             for (my $i=0; $i<$numwithformat; $i++) {
                   8835:                 my ($name,$desc) = split(':',$unique_formats{$max_match_format}[$i]);
                   8836:                 if ($i<$numwithformat-2) {
                   8837:                     $format_descs .= '"<i>'.$desc.'</i>", ';
                   8838:                 } elsif ($i==$numwithformat-2) {
                   8839:                     $format_descs .= '"<i>'.$desc.'</i>" '.&mt('and').' ';
                   8840:                 } elsif ($i==$numwithformat-1) {
                   8841:                     $format_descs .= '"<i>'.$desc.'</i>"';
                   8842:                 }
                   8843:             }
                   8844:             my $showpct = sprintf("%.0f",$max_match_pct).'%';
1.710     bisitz   8845:             $output .= '<br />';
                   8846:             if ($found_match_count == $max_match_count) {
                   8847:                 # 100% matching entries
                   8848:                 $output .= &Apache::lonhtmlcommon::confirm_success(
                   8849:                      &mt('Comparison of student IDs: [_1] matching ([quant,_2,entry,entries])',
                   8850:                             '<b>'.$showpct.'</b>',$found_match_count)).'<br />'.
                   8851:                 &mt('Comparison of student IDs in the uploaded file with'.
                   8852:                     ' the course roster found matches for [_1] of the [_2] entries'.
                   8853:                     ' in the file (for the format defined for [_3]).',
                   8854:                         '<b>'.$showpct.'</b>','<b>'.$max_match_count.'</b>',$format_descs);
                   8855:             } else {
                   8856:                 # Not all entries matching? -> Show warning and additional info
                   8857:                 $output .=
                   8858:                     &Apache::lonhtmlcommon::confirm_success(
                   8859:                         &mt('Comparison of student IDs: [_1] matching ([_2]/[quant,_3,entry,entries])',
                   8860:                                 '<b>'.$showpct.'</b>',$found_match_count,$max_match_count).'<br />'.
                   8861:                         &mt('Not all entries could be matched!'),1).'<br />'.
                   8862:                     &mt('Comparison of student IDs in the uploaded file with'.
                   8863:                         ' the course roster found matches for [_1] of the [_2] entries'.
                   8864:                         ' in the file (for the format defined for [_3]).',
                   8865:                             '<b>'.$showpct.'</b>','<b>'.$max_match_count.'</b>',$format_descs).
                   8866:                     '<p class="LC_info">'.
                   8867:                     &mt('A low percentage of matches results from one of the following:').
                   8868:                     '</p><ul>'.
                   8869:                     '<li>'.&mt('The file was uploaded to the wrong course.').'</li>'.
                   8870:                     '<li>'.&mt('The data is not in the format expected for the domain: [_1]',
                   8871:                                '<i>'.$cdom.'</i>').'</li>'.
                   8872:                     '<li>'.&mt('Students did not bubble their IDs, or mis-bubbled them').'</li>'.
                   8873:                     '<li>'.&mt('The course roster is not up to date.').'</li>'.
                   8874:                     '</ul>';
                   8875:             }
1.567     raeburn  8876:         }
                   8877:     } else {
1.710     bisitz   8878:         $output = '<p class="LC_warning">'.&mt('Uploaded file contained no data').'</p>';
1.567     raeburn  8879:     }
                   8880:     return $output;
                   8881: }
                   8882: 
1.202     albertel 8883: sub valid_file {
                   8884:     my ($requested_file)=@_;
                   8885:     foreach my $filename (sort(&scantron_filenames())) {
                   8886: 	if ($requested_file eq $filename) { return 1; }
                   8887:     }
                   8888:     return 0;
                   8889: }
                   8890: 
                   8891: sub scantron_download_scantron_data {
1.608     www      8892:     my ($r,$symb)=@_;
                   8893:     my $default_form_data=&defaultFormData($symb);
1.257     albertel 8894:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   8895:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   8896:     my $file=$env{'form.scantron_selectfile'};
1.202     albertel 8897:     if (! &valid_file($file)) {
1.492     albertel 8898: 	$r->print('
1.202     albertel 8899: 	<p>
1.686     bisitz   8900: 	    '.&mt('The requested filename was invalid.').'
1.202     albertel 8901:         </p>
1.492     albertel 8902: ');
1.202     albertel 8903: 	return;
                   8904:     }
                   8905:     my $orig='/uploaded/'.$cdom.'/'.$cname.'/scantron_orig_'.$file;
                   8906:     my $corrected='/uploaded/'.$cdom.'/'.$cname.'/scantron_corrected_'.$file;
                   8907:     my $skipped='/uploaded/'.$cdom.'/'.$cname.'/scantron_skipped_'.$file;
                   8908:     &Apache::lonnet::allowuploaded('/adm/grades',$orig);
                   8909:     &Apache::lonnet::allowuploaded('/adm/grades',$corrected);
                   8910:     &Apache::lonnet::allowuploaded('/adm/grades',$skipped);
1.492     albertel 8911:     $r->print('
1.202     albertel 8912:     <p>
1.711     bisitz   8913: 	'.&mt('[_1]Original[_2] file as uploaded by the bubblesheet office.',
1.492     albertel 8914: 	      '<a href="'.$orig.'">','</a>').'
1.202     albertel 8915:     </p>
                   8916:     <p>
1.492     albertel 8917: 	'.&mt('[_1]Corrections[_2], a file of corrected records that were used in grading.',
                   8918: 	      '<a href="'.$corrected.'">','</a>').'
1.202     albertel 8919:     </p>
                   8920:     <p>
1.492     albertel 8921: 	'.&mt('[_1]Skipped[_2], a file of records that were skipped.',
                   8922: 	      '<a href="'.$skipped.'">','</a>').'
1.202     albertel 8923:     </p>
1.492     albertel 8924: ');
1.202     albertel 8925:     return '';
                   8926: }
1.157     albertel 8927: 
1.523     raeburn  8928: sub checkscantron_results {
1.608     www      8929:     my ($r,$symb) = @_;
1.523     raeburn  8930:     if (!$symb) {return '';}
                   8931:     my $cid = $env{'request.course.id'};
1.542     raeburn  8932:     my %lettdig = &letter_to_digits();
1.523     raeburn  8933:     my $numletts = scalar(keys(%lettdig));
                   8934:     my $cnum = $env{'course.'.$cid.'.num'};
                   8935:     my $cdom = $env{'course.'.$cid.'.domain'};
                   8936:     my (undef, undef, $sequence) = &Apache::lonnet::decode_symb($env{'form.selectpage'});
                   8937:     my %record;
                   8938:     my %scantron_config =
                   8939:         &Apache::grades::get_scantron_config($env{'form.scantron_format'});
1.649     raeburn  8940:     my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config);
1.523     raeburn  8941:     my ($scanlines,$scan_data)=&Apache::grades::scantron_getfile();
                   8942:     my $classlist=&Apache::loncoursedata::get_classlist();
                   8943:     my %idmap=&Apache::grades::username_to_idmap($classlist);
                   8944:     my $navmap=Apache::lonnavmaps::navmap->new();
1.582     raeburn  8945:     unless (ref($navmap)) {
                   8946:         $r->print(&navmap_errormsg());
                   8947:         return '';
                   8948:     }
1.523     raeburn  8949:     my $map=$navmap->getResourceByUrl($sequence);
1.691     raeburn  8950:     my ($randomorder,$randompick,@master_seq,%symb_to_resource,%grader_partids_by_symb,
                   8951:         %grader_randomlists_by_symb,%orderedforcode);
1.677     raeburn  8952:     if (ref($map)) { 
                   8953:         $randomorder=$map->randomorder();
1.689     raeburn  8954:         $randompick=$map->randompick();
1.677     raeburn  8955:     }
1.557     raeburn  8956:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
1.691     raeburn  8957:     my $nav_error = &get_master_seq(\@resources,\@master_seq,\%symb_to_resource);
                   8958:     if ($nav_error) {
                   8959:         $r->print(&navmap_errormsg());
                   8960:         return '';
1.678     raeburn  8961:     }
1.673     raeburn  8962:     &graders_resources_pass(\@resources,\%grader_partids_by_symb,
                   8963:                             \%grader_randomlists_by_symb,$bubbles_per_row);
1.554     raeburn  8964:     my ($uname,$udom);
1.523     raeburn  8965:     my (%scandata,%lastname,%bylast);
                   8966:     $r->print('
                   8967: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="checkscantron">'."\n");
                   8968: 
                   8969:     my @delayqueue;
                   8970:     my %completedstudents;
                   8971: 
1.691     raeburn  8972:     my $count=&get_todo_count($scanlines,$scan_data);
1.667     www      8973:     my %prog_state=&Apache::lonhtmlcommon::Create_PrgWin($r,$count);
1.706     raeburn  8974:     my ($username,$domain,$started);
1.649     raeburn  8975:     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # Need the bubble lines array to parse.
1.582     raeburn  8976:     if ($nav_error) {
                   8977:         $r->print(&navmap_errormsg());
                   8978:         return '';
                   8979:     }
1.523     raeburn  8980: 
1.667     www      8981:     &Apache::lonhtmlcommon::Update_PrgWin($r,\%prog_state,'Processing first student');
1.523     raeburn  8982:     my $start=&Time::HiRes::time();
                   8983:     my $i=-1;
                   8984: 
                   8985:     while ($i<$scanlines->{'count'}) {
                   8986:         ($username,$domain,$uname)=('','','');
                   8987:         $i++;
                   8988:         my $line=&Apache::grades::scantron_get_line($scanlines,$scan_data,$i);
                   8989:         if ($line=~/^[\s\cz]*$/) { next; }
                   8990:         if ($started) {
1.667     www      8991:             &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state,'last student');
1.523     raeburn  8992:         }
                   8993:         $started=1;
                   8994:         my $scan_record=
                   8995:             &Apache::grades::scantron_parse_scanline($line,$i,\%scantron_config,
                   8996:                                                      $scan_data);
1.693     raeburn  8997:         unless ($uname=&scantron_find_student($scan_record,$scan_data,
                   8998:                                               \%idmap,$i)) {
1.523     raeburn  8999:             &Apache::grades::scantron_add_delay(\@delayqueue,$line,
                   9000:                                 'Unable to find a student that matches',1);
                   9001:             next;
                   9002:         }
                   9003:         if (exists $completedstudents{$uname}) {
                   9004:             &Apache::grades::scantron_add_delay(\@delayqueue,$line,
                   9005:                                 'Student '.$uname.' has multiple sheets',2);
                   9006:             next;
                   9007:         }
                   9008:         my $pid = $scan_record->{'scantron.ID'};
                   9009:         $lastname{$pid} = $scan_record->{'scantron.LastName'};
                   9010:         push(@{$bylast{$lastname{$pid}}},$pid);
1.678     raeburn  9011:         my $usec = $classlist->{$uname}->[&Apache::loncoursedata::CL_SECTION];
                   9012:         my $user = $uname.':'.$usec;
1.523     raeburn  9013:         ($username,$domain)=split(/:/,$uname);
1.677     raeburn  9014: 
1.678     raeburn  9015:         my $scancode;
1.677     raeburn  9016:         if ((exists($scan_record->{'scantron.CODE'})) &&
                   9017:             (&Apache::lonnet::validCODE($scan_record->{'scantron.CODE'}))) {
                   9018:             $scancode = $scan_record->{'scantron.CODE'};
                   9019:         } else {
                   9020:             $scancode = '';
                   9021:         }
                   9022: 
                   9023:         my @mapresources = @resources;
1.691     raeburn  9024:         my $lastpos = $env{'form.scantron_maxbubble'}*$scantron_config{'Qlength'};
                   9025:         my %respnumlookup=();
                   9026:         my %startline=();
1.689     raeburn  9027:         if ($randomorder || $randompick) {
1.678     raeburn  9028:             @mapresources =
1.691     raeburn  9029:                 &users_order($user,$scancode,$sequence,\@master_seq,\%symb_to_resource,
                   9030:                              \%orderedforcode);
                   9031:             my $total = &get_respnum_lookups($sequence,$scan_data,\%idmap,$line,
                   9032:                                              $scan_record,\@master_seq,\%symb_to_resource,
                   9033:                                              \%grader_partids_by_symb,\%orderedforcode,
                   9034:                                              \%respnumlookup,\%startline);
                   9035:             if ($randompick && $total) {
                   9036:                 $lastpos = $total*$scantron_config{'Qlength'};
                   9037:             }
1.677     raeburn  9038:         }
1.691     raeburn  9039:         $scandata{$pid} = substr($line,$scantron_config{'Qstart'}-1,$lastpos);
                   9040:         chomp($scandata{$pid});
                   9041:         $scandata{$pid} =~ s/\r$//;
                   9042: 
1.523     raeburn  9043:         my $counter = -1;
1.677     raeburn  9044:         foreach my $resource (@mapresources) {
1.557     raeburn  9045:             my $parts;
1.554     raeburn  9046:             my $ressymb = $resource->symb();
1.557     raeburn  9047:             if ((exists($grader_randomlists_by_symb{$ressymb})) ||
                   9048:                 (ref($grader_partids_by_symb{$ressymb}) ne 'ARRAY')) {
                   9049:                 (my $analysis,$parts) =
1.672     raeburn  9050:                     &scantron_partids_tograde($resource,$env{'request.course.id'},
                   9051:                                               $username,$domain,undef,
                   9052:                                               $bubbles_per_row);
1.557     raeburn  9053:             } else {
                   9054:                 $parts = $grader_partids_by_symb{$ressymb};
                   9055:             }
1.542     raeburn  9056:             ($counter,my $recording) =
                   9057:                 &verify_scantron_grading($resource,$domain,$username,$cid,$counter,
1.554     raeburn  9058:                                          $scandata{$pid},$parts,
1.691     raeburn  9059:                                          \%scantron_config,\%lettdig,$numletts,
                   9060:                                          $randomorder,$randompick,
                   9061:                                          \%respnumlookup,\%startline);
1.542     raeburn  9062:             $record{$pid} .= $recording;
1.523     raeburn  9063:         }
                   9064:     }
                   9065:     &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
                   9066:     $r->print('<br />');
                   9067:     my ($okstudents,$badstudents,$numstudents,$passed,$failed);
                   9068:     $passed = 0;
                   9069:     $failed = 0;
                   9070:     $numstudents = 0;
                   9071:     foreach my $last (sort(keys(%bylast))) {
                   9072:         if (ref($bylast{$last}) eq 'ARRAY') {
                   9073:             foreach my $pid (sort(@{$bylast{$last}})) {
                   9074:                 my $showscandata = $scandata{$pid};
                   9075:                 my $showrecord = $record{$pid};
                   9076:                 $showscandata =~ s/\s/&nbsp;/g;
                   9077:                 $showrecord =~ s/\s/&nbsp;/g;
                   9078:                 if ($scandata{$pid} eq $record{$pid}) {
                   9079:                     my $css_class = ($passed % 2)?'LC_odd_row':'LC_even_row';
                   9080:                     $okstudents .= '<tr class="'.$css_class.'">'.
1.581     www      9081: '<td>'.&mt('Bubblesheet').'</td><td>'.$showscandata.'</td><td rowspan="2">'.$last.'</td><td rowspan="2">'.$pid.'</td>'."\n".
1.523     raeburn  9082: '</tr>'."\n".
                   9083: '<tr class="'.$css_class.'">'."\n".
                   9084: '<td>Submissions</td><td>'.$showrecord.'</td></tr>'."\n";
                   9085:                     $passed ++;
                   9086:                 } else {
                   9087:                     my $css_class = ($failed % 2)?'LC_odd_row':'LC_even_row';
1.581     www      9088:                     $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  9089: '</tr>'."\n".
                   9090: '<tr class="'.$css_class.'">'."\n".
                   9091: '<td>Submissions</td><td><span class="LC_nobreak">'.$record{$pid}.'</span></td>'."\n".
                   9092: '</tr>'."\n";
                   9093:                     $failed ++;
                   9094:                 }
                   9095:                 $numstudents ++;
                   9096:             }
                   9097:         }
                   9098:     }
1.648     bisitz   9099:     $r->print(
                   9100:         '<p>'
                   9101:        .&mt('Comparison of bubblesheet data (including corrections) with corresponding submission records (most recent submission) for [_1][quant,_2,student][_3] ([quant,_4,bubblesheet line] per student).',
                   9102:             '<b>',
                   9103:             $numstudents,
                   9104:             '</b>',
                   9105:             $env{'form.scantron_maxbubble'})
                   9106:        .'</p>'
                   9107:     );
1.682     raeburn  9108:     $r->print('<p>'
1.683     raeburn  9109:              .&mt('Exact matches for [_1][quant,_2,student][_3].','<b>',$passed,'</b>')
1.682     raeburn  9110:              .'<br />'
                   9111:              .&mt('Discrepancies detected for [_1][quant,_2,student][_3].','<b>',$failed,'</b>')
                   9112:              .'</p>'
                   9113:     );
1.523     raeburn  9114:     if ($passed) {
1.572     www      9115:         $r->print(&mt('Students with exact correspondence between bubblesheet data and submissions are as follows:').'<br /><br />');
1.523     raeburn  9116:         $r->print(&Apache::loncommon::start_data_table()."\n".
                   9117:                  &Apache::loncommon::start_data_table_header_row()."\n".
                   9118:                  '<th>'.&mt('Source').'</th><th>'.&mt('Bubble records').'</th><th>'.&mt('Name').'</th><th>'.&mt('ID').'</th>'.
                   9119:                  &Apache::loncommon::end_data_table_header_row()."\n".
                   9120:                  $okstudents."\n".
                   9121:                  &Apache::loncommon::end_data_table().'<br />');
                   9122:     }
                   9123:     if ($failed) {
1.572     www      9124:         $r->print(&mt('Students with differences between bubblesheet data and submissions are as follows:').'<br /><br />');
1.523     raeburn  9125:         $r->print(&Apache::loncommon::start_data_table()."\n".
                   9126:                  &Apache::loncommon::start_data_table_header_row()."\n".
                   9127:                  '<th>'.&mt('Source').'</th><th>'.&mt('Bubble records').'</th><th>'.&mt('Name').'</th><th>'.&mt('ID').'</th>'.
                   9128:                  &Apache::loncommon::end_data_table_header_row()."\n".
                   9129:                  $badstudents."\n".
                   9130:                  &Apache::loncommon::end_data_table()).'<br />'.
1.572     www      9131:                  &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  9132:     }
1.614     www      9133:     $r->print('</form><br />');
1.523     raeburn  9134:     return;
                   9135: }
                   9136: 
1.542     raeburn  9137: sub verify_scantron_grading {
1.554     raeburn  9138:     my ($resource,$domain,$username,$cid,$counter,$scandata,$partids,
1.691     raeburn  9139:         $scantron_config,$lettdig,$numletts,$randomorder,$randompick,
                   9140:         $respnumlookup,$startline) = @_;
1.542     raeburn  9141:     my ($record,%expected,%startpos);
                   9142:     return ($counter,$record) if (!ref($resource));
                   9143:     return ($counter,$record) if (!$resource->is_problem());
                   9144:     my $symb = $resource->symb();
1.554     raeburn  9145:     return ($counter,$record) if (ref($partids) ne 'ARRAY');
                   9146:     foreach my $part_id (@{$partids}) {
1.542     raeburn  9147:         $counter ++;
                   9148:         $expected{$part_id} = 0;
1.691     raeburn  9149:         my $respnum = $counter;
                   9150:         if ($randomorder || $randompick) {
                   9151:             $respnum = $respnumlookup->{$counter};
                   9152:             $startpos{$part_id} = $startline->{$counter} + 1;
                   9153:         } else {
                   9154:             $startpos{$part_id} = $env{"form.scantron.first_bubble_line.$counter"};
                   9155:         }
                   9156:         if ($env{"form.scantron.sub_bubblelines.$respnum"}) {
                   9157:             my @sub_lines = split(/,/,$env{"form.scantron.sub_bubblelines.$respnum"});
1.542     raeburn  9158:             foreach my $item (@sub_lines) {
                   9159:                 $expected{$part_id} += $item;
                   9160:             }
                   9161:         } else {
1.691     raeburn  9162:             $expected{$part_id} = $env{"form.scantron.bubblelines.$respnum"};
1.542     raeburn  9163:         }
                   9164:     }
                   9165:     if ($symb) {
                   9166:         my %recorded;
                   9167:         my (%returnhash) = &Apache::lonnet::restore($symb,$cid,$domain,$username);
                   9168:         if ($returnhash{'version'}) {
                   9169:             my %lasthash=();
                   9170:             my $version;
                   9171:             for ($version=1;$version<=$returnhash{'version'};$version++) {
                   9172:                 foreach my $key (sort(split(/\:/,$returnhash{$version.':keys'}))) {
                   9173:                     $lasthash{$key}=$returnhash{$version.':'.$key};
                   9174:                 }
                   9175:             }
                   9176:             foreach my $key (keys(%lasthash)) {
                   9177:                 if ($key =~ /\.scantron$/) {
                   9178:                     my $value = &unescape($lasthash{$key});
                   9179:                     my ($part_id) = ($key =~ /^resource\.(.+)\.scantron$/);
                   9180:                     if ($value eq '') {
                   9181:                         for (my $i=0; $i<$expected{$part_id}; $i++) {
                   9182:                             for (my $j=0; $j<$scantron_config->{'length'}; $j++) {
                   9183:                                 $recorded{$part_id} .= $scantron_config->{'Qoff'};
                   9184:                             }
                   9185:                         }
                   9186:                     } else {
                   9187:                         my @tocheck;
                   9188:                         my @items = split(//,$value);
                   9189:                         if (($scantron_config->{'Qon'} eq 'letter') ||
                   9190:                             ($scantron_config->{'Qon'} eq 'number')) {
                   9191:                             if (@items < $expected{$part_id}) {
                   9192:                                 my $fragment = substr($scandata,$startpos{$part_id},$expected{$part_id});
                   9193:                                 my @singles = split(//,$fragment);
                   9194:                                 foreach my $pos (@singles) {
                   9195:                                     if ($pos eq ' ') {
                   9196:                                         push(@tocheck,$pos);
                   9197:                                     } else {
                   9198:                                         my $next = shift(@items);
                   9199:                                         push(@tocheck,$next);
                   9200:                                     }
                   9201:                                 }
                   9202:                             } else {
                   9203:                                 @tocheck = @items;
                   9204:                             }
                   9205:                             foreach my $letter (@tocheck) {
                   9206:                                 if ($scantron_config->{'Qon'} eq 'letter') {
                   9207:                                     if ($letter !~ /^[A-J]$/) {
                   9208:                                         $letter = $scantron_config->{'Qoff'};
                   9209:                                     }
                   9210:                                     $recorded{$part_id} .= $letter;
                   9211:                                 } elsif ($scantron_config->{'Qon'} eq 'number') {
                   9212:                                     my $digit;
                   9213:                                     if ($letter !~ /^[A-J]$/) {
                   9214:                                         $digit = $scantron_config->{'Qoff'};
                   9215:                                     } else {
                   9216:                                         $digit = $lettdig->{$letter};
                   9217:                                     }
                   9218:                                     $recorded{$part_id} .= $digit;
                   9219:                                 }
                   9220:                             }
                   9221:                         } else {
                   9222:                             @tocheck = @items;
                   9223:                             for (my $i=0; $i<$expected{$part_id}; $i++) {
                   9224:                                 my $curr_sub = shift(@tocheck);
                   9225:                                 my $digit;
                   9226:                                 if ($curr_sub =~ /^[A-J]$/) {
                   9227:                                     $digit = $lettdig->{$curr_sub}-1;
                   9228:                                 }
                   9229:                                 if ($curr_sub eq 'J') {
                   9230:                                     $digit += scalar($numletts);
                   9231:                                 }
                   9232:                                 for (my $j=0; $j<$scantron_config->{'Qlength'}; $j++) {
                   9233:                                     if ($j == $digit) {
                   9234:                                         $recorded{$part_id} .= $scantron_config->{'Qon'};
                   9235:                                     } else {
                   9236:                                         $recorded{$part_id} .= $scantron_config->{'Qoff'};
                   9237:                                     }
                   9238:                                 }
                   9239:                             }
                   9240:                         }
                   9241:                     }
                   9242:                 }
                   9243:             }
                   9244:         }
1.554     raeburn  9245:         foreach my $part_id (@{$partids}) {
1.542     raeburn  9246:             if ($recorded{$part_id} eq '') {
                   9247:                 for (my $i=0; $i<$expected{$part_id}; $i++) {
                   9248:                     for (my $j=0; $j<$scantron_config->{'Qlength'}; $j++) {
                   9249:                         $recorded{$part_id} .= $scantron_config->{'Qoff'};
                   9250:                     }
                   9251:                 }
                   9252:             }
                   9253:             $record .= $recorded{$part_id};
                   9254:         }
                   9255:     }
                   9256:     return ($counter,$record);
                   9257: }
                   9258: 
1.691     raeburn  9259: sub letter_to_digits {
1.542     raeburn  9260:     my %lettdig = (
                   9261:                     A => 1,
                   9262:                     B => 2,
                   9263:                     C => 3,
                   9264:                     D => 4,
                   9265:                     E => 5,
                   9266:                     F => 6,
                   9267:                     G => 7,
                   9268:                     H => 8,
                   9269:                     I => 9,
                   9270:                     J => 0,
                   9271:                   );
                   9272:     return %lettdig;
                   9273: }
                   9274: 
1.423     albertel 9275: 
1.75      albertel 9276: #-------- end of section for handling grading scantron forms -------
                   9277: #
                   9278: #-------------------------------------------------------------------
                   9279: 
1.72      ng       9280: #-------------------------- Menu interface -------------------------
                   9281: #
1.614     www      9282: #--- Href with symb and command ---
                   9283: 
                   9284: sub href_symb_cmd {
                   9285:     my ($symb,$cmd)=@_;
1.669     raeburn  9286:     return '/adm/grades?symb='.&HTML::Entities::encode(&Apache::lonenc::check_encrypt($symb),'<>&"').'&amp;command='.$cmd;
1.72      ng       9287: }
                   9288: 
1.443     banghart 9289: sub grading_menu {
1.608     www      9290:     my ($request,$symb) = @_;
1.443     banghart 9291:     if (!$symb) {return '';}
                   9292: 
                   9293:     my %fields = ('symb'=>&Apache::lonenc::check_encrypt($symb),
1.618     www      9294:                   'command'=>'individual');
1.538     schulted 9295:     
1.598     www      9296:     my $url1a = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   9297: 
                   9298:     $fields{'command'}='ungraded';
                   9299:     my $url1b=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   9300: 
                   9301:     $fields{'command'}='table';
                   9302:     my $url1c=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   9303: 
                   9304:     $fields{'command'}='all_for_one';
                   9305:     my $url1d=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   9306: 
1.621     www      9307:     $fields{'command'}='downloadfilesselect';
                   9308:     my $url1e=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   9309: 
1.443     banghart 9310:     $fields{'command'} = 'csvform';
1.538     schulted 9311:     my $url2 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   9312:     
1.443     banghart 9313:     $fields{'command'} = 'processclicker';
1.538     schulted 9314:     my $url3 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   9315:     
1.443     banghart 9316:     $fields{'command'} = 'scantron_selectphase';
1.538     schulted 9317:     my $url4 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
1.602     www      9318: 
                   9319:     $fields{'command'} = 'initialverifyreceipt';
                   9320:     my $url5 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
1.538     schulted 9321:     
1.598     www      9322:     my @menu = ({	categorytitle=>'Hand Grading',
1.538     schulted 9323:             items =>[
1.598     www      9324:                         {	linktext => 'Select individual students to grade',
                   9325:                     		url => $url1a,
1.538     schulted 9326:                     		permission => 'F',
1.636     wenzelju 9327:                     		icon => 'grade_students.png',
1.598     www      9328:                     		linktitle => 'Grade current resource for a selection of students.'
                   9329:                         }, 
                   9330:                         {       linktext => 'Grade ungraded submissions.',
                   9331:                                 url => $url1b,
                   9332:                                 permission => 'F',
1.636     wenzelju 9333:                                 icon => 'ungrade_sub.png',
1.598     www      9334:                                 linktitle => 'Grade all submissions that have not been graded yet.'
1.538     schulted 9335:                         },
1.598     www      9336: 
                   9337:                         {       linktext => 'Grading table',
                   9338:                                 url => $url1c,
                   9339:                                 permission => 'F',
1.636     wenzelju 9340:                                 icon => 'grading_table.png',
1.598     www      9341:                                 linktitle => 'Grade current resource for all students.'
                   9342:                         },
1.615     www      9343:                         {       linktext => 'Grade page/folder for one student',
1.598     www      9344:                                 url => $url1d,
                   9345:                                 permission => 'F',
1.636     wenzelju 9346:                                 icon => 'grade_PageFolder.png',
1.598     www      9347:                                 linktitle => 'Grade all resources in current page/sequence/folder for one student.'
1.621     www      9348:                         },
                   9349:                         {       linktext => 'Download submissions',
                   9350:                                 url => $url1e,
                   9351:                                 permission => 'F',
1.636     wenzelju 9352:                                 icon => 'download_sub.png',
1.621     www      9353:                                 linktitle => 'Download all students submissions.'
1.598     www      9354:                         }]},
                   9355:                          { categorytitle=>'Automated Grading',
                   9356:                items =>[
                   9357: 
1.538     schulted 9358:                 	    {	linktext => 'Upload Scores',
                   9359:                     		url => $url2,
                   9360:                     		permission => 'F',
                   9361:                     		icon => 'uploadscores.png',
                   9362:                     		linktitle => 'Specify a file containing the class scores for current resource.'
                   9363:                 	    },
                   9364:                 	    {	linktext => 'Process Clicker',
                   9365:                     		url => $url3,
                   9366:                     		permission => 'F',
                   9367:                     		icon => 'addClickerInfoFile.png',
                   9368:                     		linktitle => 'Specify a file containing the clicker information for this resource.'
                   9369:                 	    },
1.587     raeburn  9370:                 	    {	linktext => 'Grade/Manage/Review Bubblesheets',
1.538     schulted 9371:                     		url => $url4,
                   9372:                     		permission => 'F',
1.636     wenzelju 9373:                     		icon => 'bubblesheet.png',
1.648     bisitz   9374:                     		linktitle => 'Grade bubblesheet exams, upload/download bubblesheet data files, and review previously graded bubblesheet exams.'
1.602     www      9375:                 	    },
1.616     www      9376:                             {   linktext => 'Verify Receipt Number',
1.602     www      9377:                                 url => $url5,
                   9378:                                 permission => 'F',
1.636     wenzelju 9379:                                 icon => 'receipt_number.png',
1.602     www      9380:                                 linktitle => 'Verify a system-generated receipt number for correct problem solution.'
                   9381:                             }
                   9382: 
1.538     schulted 9383:                     ]
                   9384:             });
                   9385: 
1.443     banghart 9386:     # Create the menu
                   9387:     my $Str;
1.445     banghart 9388:     $Str .= '<form method="post" action="" name="gradingMenu">';
                   9389:     $Str .= '<input type="hidden" name="command" value="" />'.
1.618     www      9390:     	'<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
1.445     banghart 9391: 
1.602     www      9392:     $Str .= &Apache::lonhtmlcommon::generate_menu(@menu);
1.443     banghart 9393:     return $Str;    
                   9394: }
                   9395: 
1.598     www      9396: 
                   9397: sub ungraded {
                   9398:     my ($request)=@_;
                   9399:     &submit_options($request);
                   9400: }
                   9401: 
1.599     www      9402: sub submit_options_sequence {
1.608     www      9403:     my ($request,$symb) = @_;
1.599     www      9404:     if (!$symb) {return '';}
1.600     www      9405:     &commonJSfunctions($request);
                   9406:     my $result;
1.599     www      9407: 
1.600     www      9408:     $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
1.618     www      9409:         '<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
1.632     www      9410:     $result.=&selectfield(0).
1.601     www      9411:             '<input type="hidden" name="command" value="pickStudentPage" />
1.600     www      9412:             <div>
                   9413:               <input type="submit" value="'.&mt('Next').' &rarr;" />
                   9414:             </div>
                   9415:         </div>
                   9416:   </form>';
                   9417:     return $result;
                   9418: }
                   9419: 
                   9420: sub submit_options_table {
1.608     www      9421:     my ($request,$symb) = @_;
1.600     www      9422:     if (!$symb) {return '';}
1.599     www      9423:     &commonJSfunctions($request);
                   9424:     my $result;
                   9425: 
                   9426:     $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
1.618     www      9427:         '<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
1.599     www      9428: 
1.632     www      9429:     $result.=&selectfield(0).
1.601     www      9430:             '<input type="hidden" name="command" value="viewgrades" />
1.599     www      9431:             <div>
                   9432:               <input type="submit" value="'.&mt('Next').' &rarr;" />
                   9433:             </div>
                   9434:         </div>
                   9435:   </form>';
                   9436:     return $result;
                   9437: }
1.443     banghart 9438: 
1.621     www      9439: sub submit_options_download {
                   9440:     my ($request,$symb) = @_;
                   9441:     if (!$symb) {return '';}
                   9442: 
                   9443:     &commonJSfunctions($request);
                   9444: 
                   9445:     my $result='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
                   9446:         '<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
                   9447:     $result.='
                   9448: <h2>
                   9449:   '.&mt('Select Students for Which to Download Submissions').'
                   9450: </h2>'.&selectfield(1).'
                   9451:                 <input type="hidden" name="command" value="downloadfileslink" /> 
                   9452:               <input type="submit" value="'.&mt('Next').' &rarr;" />
                   9453:             </div>
                   9454:           </div>
1.600     www      9455: 
                   9456: 
1.621     www      9457:   </form>';
                   9458:     return $result;
                   9459: }
                   9460: 
1.443     banghart 9461: #--- Displays the submissions first page -------
                   9462: sub submit_options {
1.608     www      9463:     my ($request,$symb) = @_;
1.72      ng       9464:     if (!$symb) {return '';}
                   9465: 
1.118     ng       9466:     &commonJSfunctions($request);
1.473     albertel 9467:     my $result;
1.533     bisitz   9468: 
1.72      ng       9469:     $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
1.618     www      9470: 	'<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
1.632     www      9471:     $result.=&selectfield(1).'
1.601     www      9472:                 <input type="hidden" name="command" value="submission" /> 
                   9473: 	      <input type="submit" value="'.&mt('Next').' &rarr;" />
                   9474:             </div>
                   9475:           </div>
                   9476: 
                   9477: 
                   9478:   </form>';
                   9479:     return $result;
                   9480: }
1.533     bisitz   9481: 
1.601     www      9482: sub selectfield {
                   9483:    my ($full)=@_;
1.635     raeburn  9484:    my %options = 
                   9485:           (&Apache::lonlocal::texthash(
                   9486:              'yes'       => 'with submissions',
                   9487:              'queued'    => 'in grading queue',
                   9488:              'graded'    => 'with ungraded submissions',
                   9489:              'incorrect' => 'with incorrect submissions',
                   9490:              'all'       => 'with any status'),
                   9491:              'select_form_order' => ['yes','queued','graded','incorrect','all']);
1.601     www      9492:    my $result='<div class="LC_columnSection">
1.537     harmsja  9493:   
1.533     bisitz   9494:     <fieldset>
                   9495:       <legend>
                   9496:        '.&mt('Sections').'
                   9497:       </legend>
1.601     www      9498:       '.&Apache::lonstatistics::SectionSelect('section','multiple',5).'
1.533     bisitz   9499:     </fieldset>
1.537     harmsja  9500:   
1.533     bisitz   9501:     <fieldset>
                   9502:       <legend>
                   9503:         '.&mt('Groups').'
                   9504:       </legend>
                   9505:       '.&Apache::lonstatistics::GroupSelect('group','multiple',5).'
                   9506:     </fieldset>
1.537     harmsja  9507:   
1.533     bisitz   9508:     <fieldset>
                   9509:       <legend>
                   9510:         '.&mt('Access Status').'
                   9511:       </legend>
1.601     www      9512:       '.&Apache::lonhtmlcommon::StatusOptions(undef,undef,5,undef,'mult').'
                   9513:     </fieldset>';
                   9514:     if ($full) {
                   9515:        $result.='
1.533     bisitz   9516:     <fieldset>
                   9517:       <legend>
                   9518:         '.&mt('Submission Status').'
1.601     www      9519:       </legend>'.
1.635     raeburn  9520:        &Apache::loncommon::select_form('all','submitonly',\%options).
1.601     www      9521:    '</fieldset>';
                   9522:     }
                   9523:     $result.='</div><br />';
1.44      ng       9524:     return $result;
1.2       albertel 9525: }
                   9526: 
1.285     albertel 9527: sub reset_perm {
                   9528:     undef(%perm);
                   9529: }
                   9530: 
                   9531: sub init_perm {
                   9532:     &reset_perm();
1.300     albertel 9533:     foreach my $test_perm ('vgr','mgr','opa') {
                   9534: 
                   9535: 	my $scope = $env{'request.course.id'};
                   9536: 	if (!($perm{$test_perm}=&Apache::lonnet::allowed($test_perm,$scope))) {
                   9537: 
                   9538: 	    $scope .= '/'.$env{'request.course.sec'};
                   9539: 	    if ( $perm{$test_perm}=
                   9540: 		 &Apache::lonnet::allowed($test_perm,$scope)) {
                   9541: 		$perm{$test_perm.'_section'}=$env{'request.course.sec'};
                   9542: 	    } else {
                   9543: 		delete($perm{$test_perm});
                   9544: 	    }
1.285     albertel 9545: 	}
                   9546:     }
                   9547: }
                   9548: 
1.674     raeburn  9549: sub init_old_essays {
                   9550:     my ($symb,$apath,$adom,$aname) = @_;
                   9551:     if ($symb ne '') {
                   9552:         my %essays = &Apache::lonnet::dump('nohist_essay_'.$apath,$adom,$aname);
                   9553:         if (keys(%essays) > 0) {
                   9554:             $old_essays{$symb} = \%essays;
                   9555:         }
                   9556:     }
                   9557:     return;
                   9558: }
                   9559: 
                   9560: sub reset_old_essays {
                   9561:     undef(%old_essays);
                   9562: }
                   9563: 
1.400     www      9564: sub gather_clicker_ids {
1.408     albertel 9565:     my %clicker_ids;
1.400     www      9566: 
                   9567:     my $classlist = &Apache::loncoursedata::get_classlist();
                   9568: 
                   9569:     # Set up a couple variables.
1.407     albertel 9570:     my $username_idx = &Apache::loncoursedata::CL_SNAME();
                   9571:     my $domain_idx   = &Apache::loncoursedata::CL_SDOM();
1.438     www      9572:     my $status_idx   = &Apache::loncoursedata::CL_STATUS();
1.400     www      9573: 
1.407     albertel 9574:     foreach my $student (keys(%$classlist)) {
1.438     www      9575:         if ($classlist->{$student}->[$status_idx] ne 'Active') { next; }
1.407     albertel 9576:         my $username = $classlist->{$student}->[$username_idx];
                   9577:         my $domain   = $classlist->{$student}->[$domain_idx];
1.400     www      9578:         my $clickers =
1.408     albertel 9579: 	    (&Apache::lonnet::userenvironment($domain,$username,'clickers'))[1];
1.400     www      9580:         foreach my $id (split(/\,/,$clickers)) {
1.414     www      9581:             $id=~s/^[\#0]+//;
1.421     www      9582:             $id=~s/[\-\:]//g;
1.407     albertel 9583:             if (exists($clicker_ids{$id})) {
1.408     albertel 9584: 		$clicker_ids{$id}.=','.$username.':'.$domain;
1.400     www      9585:             } else {
1.408     albertel 9586: 		$clicker_ids{$id}=$username.':'.$domain;
1.400     www      9587:             }
                   9588:         }
                   9589:     }
1.407     albertel 9590:     return %clicker_ids;
1.400     www      9591: }
                   9592: 
1.402     www      9593: sub gather_adv_clicker_ids {
1.408     albertel 9594:     my %clicker_ids;
1.402     www      9595:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
                   9596:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   9597:     my %coursepersonnel=&Apache::lonnet::get_course_adv_roles($cdom.'/'.$cnum);
1.409     albertel 9598:     foreach my $element (sort(keys(%coursepersonnel))) {
1.402     www      9599:         foreach my $person (split(/\,/,$coursepersonnel{$element})) {
                   9600:             my ($puname,$pudom)=split(/\:/,$person);
                   9601:             my $clickers =
1.408     albertel 9602: 		(&Apache::lonnet::userenvironment($pudom,$puname,'clickers'))[1];
1.405     www      9603:             foreach my $id (split(/\,/,$clickers)) {
1.414     www      9604: 		$id=~s/^[\#0]+//;
1.421     www      9605:                 $id=~s/[\-\:]//g;
1.408     albertel 9606: 		if (exists($clicker_ids{$id})) {
                   9607: 		    $clicker_ids{$id}.=','.$puname.':'.$pudom;
                   9608: 		} else {
                   9609: 		    $clicker_ids{$id}=$puname.':'.$pudom;
                   9610: 		}
1.405     www      9611:             }
1.402     www      9612:         }
                   9613:     }
1.407     albertel 9614:     return %clicker_ids;
1.402     www      9615: }
                   9616: 
1.413     www      9617: sub clicker_grading_parameters {
                   9618:     return ('gradingmechanism' => 'scalar',
                   9619:             'upfiletype' => 'scalar',
                   9620:             'specificid' => 'scalar',
                   9621:             'pcorrect' => 'scalar',
                   9622:             'pincorrect' => 'scalar');
                   9623: }
                   9624: 
1.400     www      9625: sub process_clicker {
1.608     www      9626:     my ($r,$symb)=@_;
1.400     www      9627:     if (!$symb) {return '';}
                   9628:     my $result=&checkforfile_js();
1.632     www      9629:     $result.=&Apache::loncommon::start_data_table().
                   9630:              &Apache::loncommon::start_data_table_header_row().
                   9631:              '<th>'.&mt('Specify a file containing clicker information and set grading options.').'</th>'.
                   9632:              &Apache::loncommon::end_data_table_header_row().
                   9633:              &Apache::loncommon::start_data_table_row()."<td>\n";
1.413     www      9634: # Attempt to restore parameters from last session, set defaults if not present
                   9635:     my %Saveable_Parameters=&clicker_grading_parameters();
                   9636:     &Apache::loncommon::restore_course_settings('grades_clicker',
                   9637:                                                  \%Saveable_Parameters);
                   9638:     if (!$env{'form.pcorrect'}) { $env{'form.pcorrect'}=100; }
                   9639:     if (!$env{'form.pincorrect'}) { $env{'form.pincorrect'}=100; }
                   9640:     if (!$env{'form.gradingmechanism'}) { $env{'form.gradingmechanism'}='attendance'; }
                   9641:     if (!$env{'form.upfiletype'}) { $env{'form.upfiletype'}='iclicker'; }
                   9642: 
                   9643:     my %checked;
1.521     www      9644:     foreach my $gradingmechanism ('attendance','personnel','specific','given') {
1.413     www      9645:        if ($env{'form.gradingmechanism'} eq $gradingmechanism) {
1.569     bisitz   9646:           $checked{$gradingmechanism}=' checked="checked"';
1.413     www      9647:        }
                   9648:     }
                   9649: 
1.632     www      9650:     my $upload=&mt("Evaluate File");
1.400     www      9651:     my $type=&mt("Type");
1.402     www      9652:     my $attendance=&mt("Award points just for participation");
                   9653:     my $personnel=&mt("Correctness determined from response by course personnel");
1.414     www      9654:     my $specific=&mt("Correctness determined from response with clicker ID(s)"); 
1.521     www      9655:     my $given=&mt("Correctness determined from given list of answers").' '.
                   9656:               '<font size="-2"><tt>('.&mt("Provide comma-separated list. Use '*' for any answer correct, '-' for skip").')</tt></font>';
1.402     www      9657:     my $pcorrect=&mt("Percentage points for correct solution");
                   9658:     my $pincorrect=&mt("Percentage points for incorrect solution");
1.413     www      9659:     my $selectform=&Apache::loncommon::select_form($env{'form.upfiletype'},'upfiletype',
1.635     raeburn  9660: 						   {'iclicker' => 'i>clicker',
1.666     www      9661:                                                     'interwrite' => 'interwrite PRS',
                   9662:                                                     'turning' => 'Turning Technologies'});
1.418     albertel 9663:     $symb = &Apache::lonenc::check_encrypt($symb);
1.597     wenzelju 9664:     $result.= &Apache::lonhtmlcommon::scripttag(<<ENDUPFORM);
1.402     www      9665: function sanitycheck() {
                   9666: // Accept only integer percentages
                   9667:    document.forms.gradesupload.pcorrect.value=Math.round(document.forms.gradesupload.pcorrect.value);
                   9668:    document.forms.gradesupload.pincorrect.value=Math.round(document.forms.gradesupload.pincorrect.value);
                   9669: // Find out grading choice
                   9670:    for (i=0; i<document.forms.gradesupload.gradingmechanism.length; i++) {
                   9671:       if (document.forms.gradesupload.gradingmechanism[i].checked) {
                   9672:          gradingchoice=document.forms.gradesupload.gradingmechanism[i].value;
                   9673:       }
                   9674:    }
                   9675: // By default, new choice equals user selection
                   9676:    newgradingchoice=gradingchoice;
                   9677: // Not good to give more points for false answers than correct ones
                   9678:    if (Math.round(document.forms.gradesupload.pcorrect.value)<Math.round(document.forms.gradesupload.pincorrect.value)) {
                   9679:       document.forms.gradesupload.pcorrect.value=document.forms.gradesupload.pincorrect.value;
                   9680:    }
                   9681: // If new choice is attendance only, and old choice was correctness-based, restore defaults
                   9682:    if ((gradingchoice=='attendance') && (document.forms.gradesupload.waschecked.value!='attendance')) {
                   9683:       document.forms.gradesupload.pcorrect.value=100;
                   9684:       document.forms.gradesupload.pincorrect.value=100;
                   9685:    }
                   9686: // If the values are different, cannot be attendance only
                   9687:    if ((Math.round(document.forms.gradesupload.pcorrect.value)!=Math.round(document.forms.gradesupload.pincorrect.value)) &&
                   9688:        (gradingchoice=='attendance')) {
                   9689:        newgradingchoice='personnel';
                   9690:    }
                   9691: // Change grading choice to new one
                   9692:    for (i=0; i<document.forms.gradesupload.gradingmechanism.length; i++) {
                   9693:       if (document.forms.gradesupload.gradingmechanism[i].value==newgradingchoice) {
                   9694:          document.forms.gradesupload.gradingmechanism[i].checked=true;
                   9695:       } else {
                   9696:          document.forms.gradesupload.gradingmechanism[i].checked=false;
                   9697:       }
                   9698:    }
                   9699: // Remember the old state
                   9700:    document.forms.gradesupload.waschecked.value=newgradingchoice;
                   9701: }
1.597     wenzelju 9702: ENDUPFORM
                   9703:     $result.= <<ENDUPFORM;
1.400     www      9704: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
                   9705: <input type="hidden" name="symb" value="$symb" />
                   9706: <input type="hidden" name="command" value="processclickerfile" />
                   9707: <input type="file" name="upfile" size="50" />
                   9708: <br /><label>$type: $selectform</label>
1.632     www      9709: ENDUPFORM
                   9710:     $result.='</td>'.&Apache::loncommon::end_data_table_row().
                   9711:                      &Apache::loncommon::start_data_table_row().'<td>'.(<<ENDGRADINGFORM);
                   9712:       <label><input type="radio" name="gradingmechanism" value="attendance"$checked{'attendance'} onclick="sanitycheck()" />$attendance </label>
1.589     bisitz   9713: <br /><label><input type="radio" name="gradingmechanism" value="personnel"$checked{'personnel'} onclick="sanitycheck()" />$personnel</label>
                   9714: <br /><label><input type="radio" name="gradingmechanism" value="specific"$checked{'specific'} onclick="sanitycheck()" />$specific </label>
1.414     www      9715: <input type="text" name="specificid" value="$env{'form.specificid'}" size="20" />
1.589     bisitz   9716: <br /><label><input type="radio" name="gradingmechanism" value="given"$checked{'given'} onclick="sanitycheck()" />$given </label>
1.521     www      9717: <br />&nbsp;&nbsp;&nbsp;
                   9718: <input type="text" name="givenanswer" size="50" />
1.413     www      9719: <input type="hidden" name="waschecked" value="$env{'form.gradingmechanism'}" />
1.632     www      9720: ENDGRADINGFORM
                   9721:          $result.='</td>'.&Apache::loncommon::end_data_table_row().
                   9722:                      &Apache::loncommon::start_data_table_row().'<td>'.(<<ENDPERCFORM);
                   9723:       <label>$pcorrect: <input type="text" name="pcorrect" size="4" value="$env{'form.pcorrect'}" onchange="sanitycheck()" /></label>
1.589     bisitz   9724: <br /><label>$pincorrect: <input type="text" name="pincorrect" size="4" value="$env{'form.pincorrect'}" onchange="sanitycheck()" /></label>
                   9725: <br /><input type="button" onclick="javascript:checkUpload(this.form);" value="$upload" />
1.597     wenzelju 9726: </form>'
1.632     www      9727: ENDPERCFORM
                   9728:     $result.='</td>'.
                   9729:              &Apache::loncommon::end_data_table_row().
                   9730:              &Apache::loncommon::end_data_table();
1.400     www      9731:     return $result;
                   9732: }
                   9733: 
                   9734: sub process_clicker_file {
1.608     www      9735:     my ($r,$symb)=@_;
1.400     www      9736:     if (!$symb) {return '';}
1.413     www      9737: 
                   9738:     my %Saveable_Parameters=&clicker_grading_parameters();
                   9739:     &Apache::loncommon::store_course_settings('grades_clicker',
                   9740:                                               \%Saveable_Parameters);
1.598     www      9741:     my $result='';
1.404     www      9742:     if (($env{'form.gradingmechanism'} eq 'specific') && ($env{'form.specificid'}!~/\w/)) {
1.408     albertel 9743: 	$result.='<span class="LC_error">'.&mt('You need to specify a clicker ID for the correct answer').'</span>';
1.614     www      9744: 	return $result;
1.404     www      9745:     }
1.522     www      9746:     if (($env{'form.gradingmechanism'} eq 'given') && ($env{'form.givenanswer'}!~/\S/)) {
1.521     www      9747:         $result.='<span class="LC_error">'.&mt('You need to specify the correct answer').'</span>';
1.614     www      9748:         return $result;
1.521     www      9749:     }
1.522     www      9750:     my $foundgiven=0;
1.521     www      9751:     if ($env{'form.gradingmechanism'} eq 'given') {
                   9752:         $env{'form.givenanswer'}=~s/^\s*//gs;
                   9753:         $env{'form.givenanswer'}=~s/\s*$//gs;
1.644     www      9754:         $env{'form.givenanswer'}=~s/[^a-zA-Z0-9\.\*\-\+]+/\,/g;
1.521     www      9755:         $env{'form.givenanswer'}=uc($env{'form.givenanswer'});
1.522     www      9756:         my @answers=split(/\,/,$env{'form.givenanswer'});
                   9757:         $foundgiven=$#answers+1;
1.521     www      9758:     }
1.407     albertel 9759:     my %clicker_ids=&gather_clicker_ids();
1.408     albertel 9760:     my %correct_ids;
1.404     www      9761:     if ($env{'form.gradingmechanism'} eq 'personnel') {
1.408     albertel 9762: 	%correct_ids=&gather_adv_clicker_ids();
1.404     www      9763:     }
                   9764:     if ($env{'form.gradingmechanism'} eq 'specific') {
1.414     www      9765: 	foreach my $correct_id (split(/[\s\,]/,$env{'form.specificid'})) {;
                   9766: 	   $correct_id=~tr/a-z/A-Z/;
                   9767: 	   $correct_id=~s/\s//gs;
                   9768: 	   $correct_id=~s/^[\#0]+//;
1.421     www      9769:            $correct_id=~s/[\-\:]//g;
1.414     www      9770:            if ($correct_id) {
                   9771: 	      $correct_ids{$correct_id}='specified';
                   9772:            }
                   9773:         }
1.400     www      9774:     }
1.404     www      9775:     if ($env{'form.gradingmechanism'} eq 'attendance') {
1.408     albertel 9776: 	$result.=&mt('Score based on attendance only');
1.521     www      9777:     } elsif ($env{'form.gradingmechanism'} eq 'given') {
1.522     www      9778:         $result.=&mt('Score based on [_1] ([_2] answers)','<tt>'.$env{'form.givenanswer'}.'</tt>',$foundgiven);
1.404     www      9779:     } else {
1.408     albertel 9780: 	my $number=0;
1.411     www      9781: 	$result.='<p><b>'.&mt('Correctness determined by the following IDs').'</b>';
1.408     albertel 9782: 	foreach my $id (sort(keys(%correct_ids))) {
1.411     www      9783: 	    $result.='<br /><tt>'.$id.'</tt> - ';
1.408     albertel 9784: 	    if ($correct_ids{$id} eq 'specified') {
                   9785: 		$result.=&mt('specified');
                   9786: 	    } else {
                   9787: 		my ($uname,$udom)=split(/\:/,$correct_ids{$id});
                   9788: 		$result.=&Apache::loncommon::plainname($uname,$udom);
                   9789: 	    }
                   9790: 	    $number++;
                   9791: 	}
1.411     www      9792:         $result.="</p>\n";
1.710     bisitz   9793:         if ($number==0) {
                   9794:             $result .=
                   9795:                  &Apache::lonhtmlcommon::confirm_success(
                   9796:                      &mt('No IDs found to determine correct answer'),1);
                   9797:             return $result;
                   9798:         }
1.404     www      9799:     }
1.405     www      9800:     if (length($env{'form.upfile'}) < 2) {
1.710     bisitz   9801:         $result .=
                   9802:             &Apache::lonhtmlcommon::confirm_success(
                   9803:                 &mt('The file: [_1] you attempted to upload contained no information. Please check that you entered the correct filename.',
                   9804:                         '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>'),1);
1.614     www      9805:         return $result;
1.405     www      9806:     }
1.410     www      9807: 
                   9808: # Were able to get all the info needed, now analyze the file
                   9809: 
1.411     www      9810:     $result.=&Apache::loncommon::studentbrowser_javascript();
1.418     albertel 9811:     $symb = &Apache::lonenc::check_encrypt($symb);
1.632     www      9812:     $result.=&Apache::loncommon::start_data_table().
                   9813:              &Apache::loncommon::start_data_table_header_row().
                   9814:              '<th>'.&mt('Evaluate clicker file').'</th>'.
                   9815:              &Apache::loncommon::end_data_table_header_row().
                   9816:              &Apache::loncommon::start_data_table_row().(<<ENDHEADER);
                   9817: <td>
1.410     www      9818: <form method="post" action="/adm/grades" name="clickeranalysis">
                   9819: <input type="hidden" name="symb" value="$symb" />
                   9820: <input type="hidden" name="command" value="assignclickergrades" />
1.411     www      9821: <input type="hidden" name="gradingmechanism" value="$env{'form.gradingmechanism'}" />
                   9822: <input type="hidden" name="pcorrect" value="$env{'form.pcorrect'}" />
                   9823: <input type="hidden" name="pincorrect" value="$env{'form.pincorrect'}" />
1.410     www      9824: ENDHEADER
1.522     www      9825:     if ($env{'form.gradingmechanism'} eq 'given') {
                   9826:        $result.='<input type="hidden" name="correct:given" value="'.$env{'form.givenanswer'}.'" />';
                   9827:     } 
1.408     albertel 9828:     my %responses;
                   9829:     my @questiontitles;
1.405     www      9830:     my $errormsg='';
                   9831:     my $number=0;
                   9832:     if ($env{'form.upfiletype'} eq 'iclicker') {
1.408     albertel 9833: 	($errormsg,$number)=&iclicker_eval(\@questiontitles,\%responses);
1.406     www      9834:     }
1.419     www      9835:     if ($env{'form.upfiletype'} eq 'interwrite') {
                   9836:         ($errormsg,$number)=&interwrite_eval(\@questiontitles,\%responses);
                   9837:     }
1.666     www      9838:     if ($env{'form.upfiletype'} eq 'turning') {
                   9839:         ($errormsg,$number)=&turning_eval(\@questiontitles,\%responses);
                   9840:     }
1.411     www      9841:     $result.='<br />'.&mt('Found [_1] question(s)',$number).'<br />'.
                   9842:              '<input type="hidden" name="number" value="'.$number.'" />'.
                   9843:              &mt('Awarding [_1] percent for correct and [_2] percent for incorrect responses',
                   9844:                  $env{'form.pcorrect'},$env{'form.pincorrect'}).
                   9845:              '<br />';
1.522     www      9846:     if (($env{'form.gradingmechanism'} eq 'given') && ($number!=$foundgiven)) {
                   9847:        $result.='<span class="LC_error">'.&mt('Number of given answers does not agree with number of questions in file.').'</span>';
1.614     www      9848:        return $result;
1.522     www      9849:     } 
1.414     www      9850: # Remember Question Titles
                   9851: # FIXME: Possibly need delimiter other than ":"
                   9852:     for (my $i=0;$i<$number;$i++) {
                   9853:         $result.='<input type="hidden" name="question:'.$i.'" value="'.
                   9854:                  &HTML::Entities::encode($questiontitles[$i],'"&<>').'" />';
                   9855:     }
1.411     www      9856:     my $correct_count=0;
                   9857:     my $student_count=0;
                   9858:     my $unknown_count=0;
1.414     www      9859: # Match answers with usernames
                   9860: # FIXME: Possibly need delimiter other than ":"
1.409     albertel 9861:     foreach my $id (keys(%responses)) {
1.410     www      9862:        if ($correct_ids{$id}) {
1.414     www      9863:           $result.="\n".'<input type="hidden" name="correct:'.$correct_count.':'.$correct_ids{$id}.'" value="'.$responses{$id}.'" />';
1.411     www      9864:           $correct_count++;
1.410     www      9865:        } elsif ($clicker_ids{$id}) {
1.437     www      9866:           if ($clicker_ids{$id}=~/\,/) {
                   9867: # More than one user with the same clicker!
1.632     www      9868:              $result.="</td>".&Apache::loncommon::end_data_table_row().
                   9869:                            &Apache::loncommon::start_data_table_row()."<td>".
                   9870:                        &mt('Clicker registered more than once').": <tt>".$id."</tt><br />";
1.437     www      9871:              $result.="\n".'<input type="hidden" name="unknown:'.$id.'" value="'.$responses{$id}.'" />'.
                   9872:                            "<select name='multi".$id."'>";
                   9873:              foreach my $reguser (sort(split(/\,/,$clicker_ids{$id}))) {
                   9874:                  $result.="<option value='".$reguser."'>".&Apache::loncommon::plainname(split(/\:/,$reguser)).' ('.$reguser.')</option>';
                   9875:              }
                   9876:              $result.='</select>';
                   9877:              $unknown_count++;
                   9878:           } else {
                   9879: # Good: found one and only one user with the right clicker
                   9880:              $result.="\n".'<input type="hidden" name="student:'.$clicker_ids{$id}.'" value="'.$responses{$id}.'" />';
                   9881:              $student_count++;
                   9882:           }
1.410     www      9883:        } else {
1.632     www      9884:           $result.="</td>".&Apache::loncommon::end_data_table_row().
                   9885:                            &Apache::loncommon::start_data_table_row()."<td>".
                   9886:                     &mt('Unregistered Clicker')." <tt>".$id."</tt><br />";
1.411     www      9887:           $result.="\n".'<input type="hidden" name="unknown:'.$id.'" value="'.$responses{$id}.'" />'.
                   9888:                    "\n".&mt("Username").": <input type='text' name='uname".$id."' />&nbsp;".
                   9889:                    "\n".&mt("Domain").": ".
                   9890:                    &Apache::loncommon::select_dom_form($env{'course.'.$env{'request.course.id'}.'.domain'},'udom'.$id).'&nbsp;'.
1.643     www      9891:                    &Apache::loncommon::selectstudent_link('clickeranalysis','uname'.$id,'udom'.$id,0,$id);
1.411     www      9892:           $unknown_count++;
1.410     www      9893:        }
1.405     www      9894:     }
1.412     www      9895:     $result.='<hr />'.
                   9896:              &mt('Found [_1] registered and [_2] unregistered clickers.',$student_count,$unknown_count);
1.521     www      9897:     if (($env{'form.gradingmechanism'} ne 'attendance') && ($env{'form.gradingmechanism'} ne 'given')) {
1.412     www      9898:        if ($correct_count==0) {
1.696     bisitz   9899:           $errormsg.="Found no correct answers for grading!";
1.412     www      9900:        } elsif ($correct_count>1) {
1.414     www      9901:           $result.='<br /><span class="LC_warning">'.&mt("Found [_1] entries for grading!",$correct_count).'</span>';
1.412     www      9902:        }
                   9903:     }
1.428     www      9904:     if ($number<1) {
                   9905:        $errormsg.="Found no questions.";
                   9906:     }
1.412     www      9907:     if ($errormsg) {
                   9908:        $result.='<br /><span class="LC_error">'.&mt($errormsg).'</span>';
                   9909:     } else {
                   9910:        $result.='<br /><input type="submit" name="finalize" value="'.&mt('Finalize Grading').'" />';
                   9911:     }
1.632     www      9912:     $result.='</form></td>'.
                   9913:              &Apache::loncommon::end_data_table_row().
                   9914:              &Apache::loncommon::end_data_table();
1.614     www      9915:     return $result;
1.400     www      9916: }
                   9917: 
1.405     www      9918: sub iclicker_eval {
1.406     www      9919:     my ($questiontitles,$responses)=@_;
1.405     www      9920:     my $number=0;
                   9921:     my $errormsg='';
                   9922:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
1.410     www      9923:         my %components=&Apache::loncommon::record_sep($line);
                   9924:         my @entries=map {$components{$_}} (sort(keys(%components)));
1.408     albertel 9925: 	if ($entries[0] eq 'Question') {
                   9926: 	    for (my $i=3;$i<$#entries;$i+=6) {
                   9927: 		$$questiontitles[$number]=$entries[$i];
                   9928: 		$number++;
                   9929: 	    }
                   9930: 	}
                   9931: 	if ($entries[0]=~/^\#/) {
                   9932: 	    my $id=$entries[0];
                   9933: 	    my @idresponses;
                   9934: 	    $id=~s/^[\#0]+//;
                   9935: 	    for (my $i=0;$i<$number;$i++) {
                   9936: 		my $idx=3+$i*6;
1.644     www      9937:                 $entries[$idx]=~s/[^a-zA-Z0-9\.\*\-\+]+//g;
1.408     albertel 9938: 		push(@idresponses,$entries[$idx]);
                   9939: 	    }
                   9940: 	    $$responses{$id}=join(',',@idresponses);
                   9941: 	}
1.405     www      9942:     }
                   9943:     return ($errormsg,$number);
                   9944: }
                   9945: 
1.419     www      9946: sub interwrite_eval {
                   9947:     my ($questiontitles,$responses)=@_;
                   9948:     my $number=0;
                   9949:     my $errormsg='';
1.420     www      9950:     my $skipline=1;
                   9951:     my $questionnumber=0;
                   9952:     my %idresponses=();
1.419     www      9953:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
                   9954:         my %components=&Apache::loncommon::record_sep($line);
                   9955:         my @entries=map {$components{$_}} (sort(keys(%components)));
1.420     www      9956:         if ($entries[1] eq 'Time') { $skipline=0; next; }
                   9957:         if ($entries[1] eq 'Response') { $skipline=1; }
                   9958:         next if $skipline;
                   9959:         if ($entries[0]!=$questionnumber) {
                   9960:            $questionnumber=$entries[0];
                   9961:            $$questiontitles[$number]=&mt('Question [_1]',$questionnumber);
                   9962:            $number++;
1.419     www      9963:         }
1.420     www      9964:         my $id=$entries[4];
                   9965:         $id=~s/^[\#0]+//;
1.421     www      9966:         $id=~s/^v\d*\://i;
                   9967:         $id=~s/[\-\:]//g;
1.420     www      9968:         $idresponses{$id}[$number]=$entries[6];
                   9969:     }
1.524     raeburn  9970:     foreach my $id (keys(%idresponses)) {
1.420     www      9971:        $$responses{$id}=join(',',@{$idresponses{$id}});
                   9972:        $$responses{$id}=~s/^\s*\,//;
1.419     www      9973:     }
                   9974:     return ($errormsg,$number);
                   9975: }
                   9976: 
1.666     www      9977: sub turning_eval {
                   9978:     my ($questiontitles,$responses)=@_;
                   9979:     my $number=0;
                   9980:     my $errormsg='';
                   9981:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
                   9982:         my %components=&Apache::loncommon::record_sep($line);
                   9983:         my @entries=map {$components{$_}} (sort(keys(%components)));
                   9984:         if ($#entries>$number) { $number=$#entries; }
                   9985:         my $id=$entries[0];
                   9986:         my @idresponses;
                   9987:         $id=~s/^[\#0]+//;
                   9988:         unless ($id) { next; }
                   9989:         for (my $idx=1;$idx<=$#entries;$idx++) {
                   9990:             $entries[$idx]=~s/\,/\;/g;
                   9991:             $entries[$idx]=~s/[^a-zA-Z0-9\.\*\-\+\;]+//g;
                   9992:             push(@idresponses,$entries[$idx]);
                   9993:         }
                   9994:         $$responses{$id}=join(',',@idresponses);
                   9995:     }
                   9996:     for (my $i=1; $i<=$number; $i++) {
                   9997:         $$questiontitles[$i]=&mt('Question [_1]',$i);
                   9998:     }
                   9999:     return ($errormsg,$number);
                   10000: }
                   10001: 
                   10002: 
1.414     www      10003: sub assign_clicker_grades {
1.608     www      10004:     my ($r,$symb)=@_;
1.414     www      10005:     if (!$symb) {return '';}
1.416     www      10006: # See which part we are saving to
1.582     raeburn  10007:     my $res_error;
                   10008:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
                   10009:     if ($res_error) {
                   10010:         return &navmap_errormsg();
                   10011:     }
1.416     www      10012: # FIXME: This should probably look for the first handgradeable part
                   10013:     my $part=$$partlist[0];
                   10014: # Start screen output
1.632     www      10015:     my $result=&Apache::loncommon::start_data_table().
                   10016:              &Apache::loncommon::start_data_table_header_row().
                   10017:              '<th>'.&mt('Assigning grades based on clicker file').'</th>'.
                   10018:              &Apache::loncommon::end_data_table_header_row().
                   10019:              &Apache::loncommon::start_data_table_row().'<td>';
1.414     www      10020: # Get correct result
                   10021: # FIXME: Possibly need delimiter other than ":"
                   10022:     my @correct=();
1.415     www      10023:     my $gradingmechanism=$env{'form.gradingmechanism'};
                   10024:     my $number=$env{'form.number'};
                   10025:     if ($gradingmechanism ne 'attendance') {
1.414     www      10026:        foreach my $key (keys(%env)) {
                   10027:           if ($key=~/^form\.correct\:/) {
                   10028:              my @input=split(/\,/,$env{$key});
                   10029:              for (my $i=0;$i<=$#input;$i++) {
                   10030:                  if (($correct[$i]) && ($input[$i]) &&
                   10031:                      ($correct[$i] ne $input[$i])) {
                   10032:                     $result.='<br /><span class="LC_warning">'.
                   10033:                              &mt('More than one correct result given for question "[_1]": [_2] versus [_3].',
                   10034:                                  $env{'form.question:'.$i},$correct[$i],$input[$i]).'</span>';
1.644     www      10035:                  } elsif (($input[$i]) || ($input[$i] eq '0')) {
1.414     www      10036:                     $correct[$i]=$input[$i];
                   10037:                  }
                   10038:              }
                   10039:           }
                   10040:        }
1.415     www      10041:        for (my $i=0;$i<$number;$i++) {
1.644     www      10042:           if ((!$correct[$i]) && ($correct[$i] ne '0')) {
1.414     www      10043:              $result.='<br /><span class="LC_error">'.
                   10044:                       &mt('No correct result given for question "[_1]"!',
                   10045:                           $env{'form.question:'.$i}).'</span>';
                   10046:           }
                   10047:        }
1.644     www      10048:        $result.='<br />'.&mt("Correct answer: [_1]",join(', ',map { ((($_) || ($_ eq '0'))?$_:'-') } @correct));
1.414     www      10049:     }
                   10050: # Start grading
1.415     www      10051:     my $pcorrect=$env{'form.pcorrect'};
                   10052:     my $pincorrect=$env{'form.pincorrect'};
1.416     www      10053:     my $storecount=0;
1.632     www      10054:     my %users=();
1.415     www      10055:     foreach my $key (keys(%env)) {
1.420     www      10056:        my $user='';
1.415     www      10057:        if ($key=~/^form\.student\:(.*)$/) {
1.420     www      10058:           $user=$1;
                   10059:        }
                   10060:        if ($key=~/^form\.unknown\:(.*)$/) {
                   10061:           my $id=$1;
                   10062:           if (($env{'form.uname'.$id}) && ($env{'form.udom'.$id})) {
                   10063:              $user=$env{'form.uname'.$id}.':'.$env{'form.udom'.$id};
1.437     www      10064:           } elsif ($env{'form.multi'.$id}) {
                   10065:              $user=$env{'form.multi'.$id};
1.420     www      10066:           }
                   10067:        }
1.632     www      10068:        if ($user) {
                   10069:           if ($users{$user}) {
                   10070:              $result.='<br /><span class="LC_warning">'.
1.696     bisitz   10071:                       &mt('More than one entry found for [_1]!','<tt>'.$user.'</tt>').
1.632     www      10072:                       '</span><br />';
                   10073:           }
                   10074:           $users{$user}=1; 
1.415     www      10075:           my @answer=split(/\,/,$env{$key});
                   10076:           my $sum=0;
1.522     www      10077:           my $realnumber=$number;
1.415     www      10078:           for (my $i=0;$i<$number;$i++) {
1.576     www      10079:              if  ($correct[$i] eq '-') {
                   10080:                 $realnumber--;
1.644     www      10081:              } elsif (($answer[$i]) || ($answer[$i]=~/^[0\.]+$/))  {
1.415     www      10082:                 if ($gradingmechanism eq 'attendance') {
                   10083:                    $sum+=$pcorrect;
1.576     www      10084:                 } elsif ($correct[$i] eq '*') {
1.522     www      10085:                    $sum+=$pcorrect;
1.415     www      10086:                 } else {
1.644     www      10087: # We actually grade if correct or not
                   10088:                    my $increment=$pincorrect;
                   10089: # Special case: numerical answer "0"
                   10090:                    if ($correct[$i] eq '0') {
                   10091:                       if ($answer[$i]=~/^[0\.]+$/) {
                   10092:                          $increment=$pcorrect;
                   10093:                       }
                   10094: # General numerical answer, both evaluate to something non-zero
                   10095:                    } elsif ((1.0*$correct[$i]!=0) && (1.0*$answer[$i]!=0)) {
                   10096:                       if (1.0*$correct[$i]==1.0*$answer[$i]) {
                   10097:                          $increment=$pcorrect;
                   10098:                       }
                   10099: # Must be just alphanumeric
                   10100:                    } elsif ($answer[$i] eq $correct[$i]) {
                   10101:                       $increment=$pcorrect;
1.415     www      10102:                    }
1.644     www      10103:                    $sum+=$increment;
1.415     www      10104:                 }
                   10105:              }
                   10106:           }
1.522     www      10107:           my $ave=$sum/(100*$realnumber);
1.416     www      10108: # Store
                   10109:           my ($username,$domain)=split(/\:/,$user);
                   10110:           my %grades=();
                   10111:           $grades{"resource.$part.solved"}='correct_by_override';
                   10112:           $grades{"resource.$part.awarded"}=$ave;
                   10113:           $grades{"resource.regrader"}="$env{'user.name'}:$env{'user.domain'}";
                   10114:           my $returncode=&Apache::lonnet::cstore(\%grades,$symb,
                   10115:                                                  $env{'request.course.id'},
                   10116:                                                  $domain,$username);
                   10117:           if ($returncode ne 'ok') {
                   10118:              $result.="<br /><span class=\"LC_error\">Failed to save student $username:$domain. Message when trying to save was ($returncode)</span>";
                   10119:           } else {
                   10120:              $storecount++;
                   10121:           }
1.415     www      10122:        }
                   10123:     }
                   10124: # We are done
1.549     hauer    10125:     $result.='<br />'.&mt('Successfully stored grades for [quant,_1,student].',$storecount).
1.632     www      10126:              '</td>'.
                   10127:              &Apache::loncommon::end_data_table_row().
                   10128:              &Apache::loncommon::end_data_table();
1.614     www      10129:     return $result;
1.414     www      10130: }
                   10131: 
1.582     raeburn  10132: sub navmap_errormsg {
                   10133:     return '<div class="LC_error">'.
                   10134:            &mt('An error occurred retrieving information about resources in the course.').'<br />'.
1.595     raeburn  10135:            &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  10136:            '</div>';
                   10137: }
1.607     droeschl 10138: 
1.609     www      10139: sub startpage {
1.671     raeburn  10140:     my ($r,$symb,$crumbs,$onlyfolderflag,$nodisplayflag,$stuvcurrent,$stuvdisp,$nomenu,$js) = @_;
                   10141:     if ($nomenu) {
                   10142:         $r->print(&Apache::loncommon::start_page("Student's Version",$js,{'only_body' => '1'}));
                   10143:     } else {
                   10144:         unshift(@$crumbs,{href=>&href_symb_cmd($symb,'gradingmenu'),text=>"Grading"});
                   10145:         $r->print(&Apache::loncommon::start_page('Grading',$js,
                   10146:                                                  {'bread_crumbs' => $crumbs}));
                   10147:         &Apache::lonquickgrades::startGradeScreen($r,($env{'form.symb'}?'probgrading':'grading'));
                   10148:     }
1.613     www      10149:     unless ($nodisplayflag) {
1.671     raeburn  10150:        $r->print(&Apache::lonhtmlcommon::resource_info_box($symb,$onlyfolderflag,$stuvcurrent,$stuvdisp));
1.613     www      10151:     }
1.607     droeschl 10152: }
1.582     raeburn  10153: 
1.622     www      10154: sub select_problem {
                   10155:     my ($r)=@_;
1.632     www      10156:     $r->print('<h3>'.&mt('Select the problem or one of the problems you want to grade').'</h3><form action="/adm/grades">');
1.622     www      10157:     $r->print(&Apache::lonstathelpers::problem_selector('.',undef,1));
                   10158:     $r->print('<input type="hidden" name="command" value="gradingmenu" />');
                   10159:     $r->print('<input type="submit" value="'.&mt('Next').' &rarr;" /></form>');
                   10160: }
                   10161: 
1.1       albertel 10162: sub handler {
1.41      ng       10163:     my $request=$_[0];
1.434     albertel 10164:     &reset_caches();
1.646     raeburn  10165:     if ($request->header_only) {
                   10166:         &Apache::loncommon::content_type($request,'text/html');
                   10167:         $request->send_http_header;
                   10168:         return OK;
                   10169:     }
                   10170:     &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'});
                   10171: 
1.664     raeburn  10172: # see what command we need to execute
                   10173: 
                   10174:     my @commands=&Apache::loncommon::get_env_multiple('form.command');
                   10175:     my $command=$commands[0];
                   10176: 
1.646     raeburn  10177:     &init_perm();
                   10178:     if (!$env{'request.course.id'}) {
1.664     raeburn  10179:         unless ((&Apache::lonnet::allowed('usc',$env{'request.role.domain'})) &&
                   10180:                 ($command =~ /^scantronupload/)) {
                   10181:             # Not in a course.
                   10182:             $env{'user.error.msg'}="/adm/grades::vgr:0:0:Cannot display grades page outside course context";
                   10183:             return HTTP_NOT_ACCEPTABLE;
                   10184:         }
1.646     raeburn  10185:     } elsif (!%perm) {
                   10186:         $request->internal_redirect('/adm/quickgrades');
1.687     raeburn  10187:         return OK;
1.41      ng       10188:     }
1.646     raeburn  10189:     &Apache::loncommon::content_type($request,'text/html');
1.41      ng       10190:     $request->send_http_header;
1.646     raeburn  10191: 
1.160     albertel 10192:     if ($#commands > 0) {
                   10193: 	&Apache::lonnet::logthis("grades got multiple commands ".join(':',@commands));
                   10194:     }
1.608     www      10195: 
                   10196: # see what the symb is
                   10197: 
                   10198:     my $symb=$env{'form.symb'};
                   10199:     unless ($symb) {
                   10200:        (my $url=$env{'form.url'}) =~ s-^https*://($ENV{'SERVER_NAME'}|$ENV{'HTTP_HOST'})--;
                   10201:        $symb=&Apache::lonnet::symbread($url);
                   10202:     }
1.646     raeburn  10203:     &Apache::lonenc::check_decrypt(\$symb);
1.608     www      10204: 
1.513     foxr     10205:     $ssi_error = 0;
1.637     www      10206:     if (($symb eq '' || $command eq '') && ($env{'request.course.id'})) {
1.601     www      10207: #
1.637     www      10208: # Not called from a resource, but inside a course
1.601     www      10209: #    
1.622     www      10210:         &startpage($request,undef,[],1,1);
                   10211:         &select_problem($request);
1.41      ng       10212:     } else {
1.104     albertel 10213: 	if ($command eq 'submission' && $perm{'vgr'}) {
1.671     raeburn  10214:             my ($stuvcurrent,$stuvdisp,$versionform,$js);
                   10215:             if (($env{'form.student'} ne '') && ($env{'form.userdom'} ne '')) {
                   10216:                 ($stuvcurrent,$stuvdisp,$versionform,$js) =
                   10217:                     &choose_task_version_form($symb,$env{'form.student'},
                   10218:                                               $env{'form.userdom'});
                   10219:             }
                   10220:             &startpage($request,$symb,[{href=>"", text=>"Student Submissions"}],undef,undef,$stuvcurrent,$stuvdisp,undef,$js);
                   10221:             if ($versionform) {
                   10222:                 $request->print($versionform);
                   10223:             }
                   10224:             $request->print('<br clear="all" />');
1.611     www      10225: 	    ($env{'form.student'} eq '' ? &listStudents($request,$symb) : &submission($request,0,0,$symb));
1.671     raeburn  10226:         } elsif ($command eq 'versionsub' && $perm{'vgr'}) {
                   10227:             my ($stuvcurrent,$stuvdisp,$versionform,$js) =
                   10228:                 &choose_task_version_form($symb,$env{'form.student'},
                   10229:                                           $env{'form.userdom'},
                   10230:                                           $env{'form.inhibitmenu'});
                   10231:             &startpage($request,$symb,[{href=>"", text=>"Previous Student Version"}],undef,undef,$stuvcurrent,$stuvdisp,$env{'form.inhibitmenu'},$js);
                   10232:             if ($versionform) {
                   10233:                 $request->print($versionform);
                   10234:             }
                   10235:             $request->print('<br clear="all" />');
                   10236:             $request->print(&show_previous_task_version($request,$symb));
1.103     albertel 10237: 	} elsif ($command eq 'pickStudentPage' && $perm{'vgr'}) {
1.615     www      10238:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,'all_for_one'),text=>'Grade page/folder for one student'},
                   10239:                                        {href=>'',text=>'Select student'}],1,1);
1.608     www      10240: 	    &pickStudentPage($request,$symb);
1.103     albertel 10241: 	} elsif ($command eq 'displayPage' && $perm{'vgr'}) {
1.615     www      10242:             &startpage($request,$symb,
                   10243:                                       [{href=>&href_symb_cmd($symb,'all_for_one'),text=>'Grade page/folder for one student'},
                   10244:                                        {href=>'',text=>'Select student'},
                   10245:                                        {href=>'',text=>'Grade student'}],1,1);
1.608     www      10246: 	    &displayPage($request,$symb);
1.104     albertel 10247: 	} elsif ($command eq 'gradeByPage' && $perm{'mgr'}) {
1.616     www      10248:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,'all_for_one'),text=>'Grade page/folder for one student'},
                   10249:                                        {href=>'',text=>'Select student'},
                   10250:                                        {href=>'',text=>'Grade student'},
                   10251:                                        {href=>'',text=>'Store grades'}],1,1);
1.608     www      10252: 	    &updateGradeByPage($request,$symb);
1.104     albertel 10253: 	} elsif ($command eq 'processGroup' && $perm{'vgr'}) {
1.619     www      10254:             &startpage($request,$symb,[{href=>'',text=>'...'},
                   10255:                                        {href=>'',text=>'Modify grades'}]);
1.608     www      10256: 	    &processGroup($request,$symb);
1.104     albertel 10257: 	} elsif ($command eq 'gradingmenu' && $perm{'vgr'}) {
1.608     www      10258:             &startpage($request,$symb);
                   10259: 	    $request->print(&grading_menu($request,$symb));
1.598     www      10260: 	} elsif ($command eq 'individual' && $perm{'vgr'}) {
1.617     www      10261:             &startpage($request,$symb,[{href=>'',text=>'Select individual students to grade'}]);
1.608     www      10262: 	    $request->print(&submit_options($request,$symb));
1.598     www      10263:         } elsif ($command eq 'ungraded' && $perm{'vgr'}) {
1.617     www      10264:             &startpage($request,$symb,[{href=>'',text=>'Grade ungraded submissions'}]);
                   10265:             $request->print(&listStudents($request,$symb,'graded'));
1.598     www      10266:         } elsif ($command eq 'table' && $perm{'vgr'}) {
1.614     www      10267:             &startpage($request,$symb,[{href=>"", text=>"Grading table"}]);
1.611     www      10268:             $request->print(&submit_options_table($request,$symb));
1.598     www      10269:         } elsif ($command eq 'all_for_one' && $perm{'vgr'}) {
1.615     www      10270:             &startpage($request,$symb,[{href=>'',text=>'Grade page/folder for one student'}],1,1);
1.608     www      10271:             $request->print(&submit_options_sequence($request,$symb));
1.104     albertel 10272: 	} elsif ($command eq 'viewgrades' && $perm{'vgr'}) {
1.614     www      10273:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,"table"), text=>"Grading table"},{href=>'', text=>"Modify grades"}]);
1.608     www      10274: 	    $request->print(&viewgrades($request,$symb));
1.104     albertel 10275: 	} elsif ($command eq 'handgrade' && $perm{'mgr'}) {
1.620     www      10276:             &startpage($request,$symb,[{href=>'',text=>'...'},
                   10277:                                        {href=>'',text=>'Store grades'}]);
1.608     www      10278: 	    $request->print(&processHandGrade($request,$symb));
1.106     albertel 10279: 	} elsif ($command eq 'editgrades' && $perm{'mgr'}) {
1.614     www      10280:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,"table"), text=>"Grading table"},
                   10281:                                        {href=>&href_symb_cmd($symb,'viewgrades').'&group=all&section=all&Status=Active',
                   10282:                                                                              text=>"Modify grades"},
                   10283:                                        {href=>'', text=>"Store grades"}]);
1.608     www      10284: 	    $request->print(&editgrades($request,$symb));
1.602     www      10285:         } elsif ($command eq 'initialverifyreceipt' && $perm{'vgr'}) {
1.616     www      10286:             &startpage($request,$symb,[{href=>'',text=>'Verify Receipt Number'}]);
1.611     www      10287:             $request->print(&initialverifyreceipt($request,$symb));
1.106     albertel 10288: 	} elsif ($command eq 'verify' && $perm{'vgr'}) {
1.616     www      10289:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,"initialverifyreceipt"),text=>'Verify Receipt Number'},
                   10290:                                        {href=>'',text=>'Verification Result'}]);
1.608     www      10291: 	    $request->print(&verifyreceipt($request,$symb));
1.400     www      10292:         } elsif ($command eq 'processclicker' && $perm{'mgr'}) {
1.615     www      10293:             &startpage($request,$symb,[{href=>'', text=>'Process clicker'}]);
1.608     www      10294:             $request->print(&process_clicker($request,$symb));
1.400     www      10295:         } elsif ($command eq 'processclickerfile' && $perm{'mgr'}) {
1.615     www      10296:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,'processclicker'), text=>'Process clicker'},
                   10297:                                        {href=>'', text=>'Process clicker file'}]);
1.608     www      10298:             $request->print(&process_clicker_file($request,$symb));
1.414     www      10299:         } elsif ($command eq 'assignclickergrades' && $perm{'mgr'}) {
1.615     www      10300:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,'processclicker'), text=>'Process clicker'},
                   10301:                                        {href=>'', text=>'Process clicker file'},
                   10302:                                        {href=>'', text=>'Store grades'}]);
1.608     www      10303:             $request->print(&assign_clicker_grades($request,$symb));
1.106     albertel 10304: 	} elsif ($command eq 'csvform' && $perm{'mgr'}) {
1.627     www      10305:             &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
1.608     www      10306: 	    $request->print(&upcsvScores_form($request,$symb));
1.106     albertel 10307: 	} elsif ($command eq 'csvupload' && $perm{'mgr'}) {
1.627     www      10308:             &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
1.608     www      10309: 	    $request->print(&csvupload($request,$symb));
1.106     albertel 10310: 	} elsif ($command eq 'csvuploadmap' && $perm{'mgr'} ) {
1.627     www      10311:             &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
1.608     www      10312: 	    $request->print(&csvuploadmap($request,$symb));
1.246     albertel 10313: 	} elsif ($command eq 'csvuploadoptions' && $perm{'mgr'}) {
1.257     albertel 10314: 	    if ($env{'form.associate'} ne 'Reverse Association') {
1.627     www      10315:                 &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
1.608     www      10316: 		$request->print(&csvuploadoptions($request,$symb));
1.41      ng       10317: 	    } else {
1.257     albertel 10318: 		if ( $env{'form.upfile_associate'} ne 'reverse' ) {
                   10319: 		    $env{'form.upfile_associate'} = 'reverse';
1.41      ng       10320: 		} else {
1.257     albertel 10321: 		    $env{'form.upfile_associate'} = 'forward';
1.41      ng       10322: 		}
1.627     www      10323:                 &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
1.608     www      10324: 		$request->print(&csvuploadmap($request,$symb));
1.41      ng       10325: 	    }
1.246     albertel 10326: 	} elsif ($command eq 'csvuploadassign' && $perm{'mgr'} ) {
1.627     www      10327:             &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
1.608     www      10328: 	    $request->print(&csvuploadassign($request,$symb));
1.106     albertel 10329: 	} elsif ($command eq 'scantron_selectphase' && $perm{'mgr'}) {
1.616     www      10330:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
1.612     www      10331: 	    $request->print(&scantron_selectphase($request,undef,$symb));
1.203     albertel 10332:  	} elsif ($command eq 'scantron_warning' && $perm{'mgr'}) {
1.616     www      10333:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
1.608     www      10334:  	    $request->print(&scantron_do_warning($request,$symb));
1.142     albertel 10335: 	} elsif ($command eq 'scantron_validate' && $perm{'mgr'}) {
1.616     www      10336:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
1.608     www      10337: 	    $request->print(&scantron_validate_file($request,$symb));
1.106     albertel 10338: 	} elsif ($command eq 'scantron_process' && $perm{'mgr'}) {
1.616     www      10339:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
1.608     www      10340: 	    $request->print(&scantron_process_students($request,$symb));
1.157     albertel 10341:  	} elsif ($command eq 'scantronupload' && 
1.257     albertel 10342:  		 (&Apache::lonnet::allowed('usc',$env{'request.role.domain'})||
                   10343: 		  &Apache::lonnet::allowed('usc',$env{'request.course.id'}))) {
1.616     www      10344:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
1.608     www      10345:  	    $request->print(&scantron_upload_scantron_data($request,$symb)); 
1.157     albertel 10346:  	} elsif ($command eq 'scantronupload_save' &&
1.257     albertel 10347:  		 (&Apache::lonnet::allowed('usc',$env{'request.role.domain'})||
                   10348: 		  &Apache::lonnet::allowed('usc',$env{'request.course.id'}))) {
1.616     www      10349:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
1.608     www      10350:  	    $request->print(&scantron_upload_scantron_data_save($request,$symb));
1.202     albertel 10351:  	} elsif ($command eq 'scantron_download' &&
1.257     albertel 10352: 		 &Apache::lonnet::allowed('usc',$env{'request.course.id'})) {
1.616     www      10353:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
1.608     www      10354:  	    $request->print(&scantron_download_scantron_data($request,$symb));
1.523     raeburn  10355:         } elsif ($command eq 'checksubmissions' && $perm{'vgr'}) {
1.616     www      10356:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
1.621     www      10357:             $request->print(&checkscantron_results($request,$symb));
                   10358:         } elsif ($command eq 'downloadfilesselect' && $perm{'vgr'}) {
                   10359:             &startpage($request,$symb,[{href=>'', text=>'Select which submissions to download'}]);
                   10360:             $request->print(&submit_options_download($request,$symb));
                   10361:          } elsif ($command eq 'downloadfileslink' && $perm{'vgr'}) {
                   10362:             &startpage($request,$symb,
                   10363:    [{href=>&href_symb_cmd($symb,'downloadfilesselect'), text=>'Select which submissions to download'},
                   10364:     {href=>'', text=>'Download submissions'}]);
                   10365:             &submit_download_link($request,$symb);
1.106     albertel 10366: 	} elsif ($command) {
1.620     www      10367:             &startpage($request,$symb,[{href=>'', text=>'Access denied'}]);
1.562     bisitz   10368: 	    $request->print('<p class="LC_error">'.&mt('Access Denied ([_1])',$command).'</p>');
1.26      albertel 10369: 	}
1.2       albertel 10370:     }
1.513     foxr     10371:     if ($ssi_error) {
                   10372: 	&ssi_print_error($request);
                   10373:     }
1.671     raeburn  10374:     if ($env{'form.inhibitmenu'}) {
                   10375:         $request->print(&Apache::loncommon::end_page());
                   10376:     } else {
                   10377:         &Apache::lonquickgrades::endGradeScreen($request);
                   10378:     }
1.434     albertel 10379:     &reset_caches();
1.646     raeburn  10380:     return OK;
1.44      ng       10381: }
                   10382: 
1.1       albertel 10383: 1;
                   10384: 
1.13      albertel 10385: __END__;
1.531     jms      10386: 
                   10387: 
                   10388: =head1 NAME
                   10389: 
                   10390: Apache::grades
                   10391: 
                   10392: =head1 SYNOPSIS
                   10393: 
                   10394: Handles the viewing of grades.
                   10395: 
                   10396: This is part of the LearningOnline Network with CAPA project
                   10397: described at http://www.lon-capa.org.
                   10398: 
                   10399: =head1 OVERVIEW
                   10400: 
                   10401: Do an ssi with retries:
1.715     bisitz   10402: While I'd love to factor out this with the version in lonprintout,
1.531     jms      10403: 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
                   10404: I'm not quite ready to invent (e.g. an ssi_with_retry object).
                   10405: 
                   10406: At least the logic that drives this has been pulled out into loncommon.
                   10407: 
                   10408: 
                   10409: 
                   10410: ssi_with_retries - Does the server side include of a resource.
                   10411:                      if the ssi call returns an error we'll retry it up to
                   10412:                      the number of times requested by the caller.
1.715     bisitz   10413:                      If we still have a problem, no text is appended to the
1.531     jms      10414:                      output and we set some global variables.
                   10415:                      to indicate to the caller an SSI error occurred.  
                   10416:                      All of this is supposed to deal with the issues described
1.715     bisitz   10417:                      in LON-CAPA BZ 5631 see:
1.531     jms      10418:                      http://bugs.lon-capa.org/show_bug.cgi?id=5631
                   10419:                      by informing the user that this happened.
                   10420: 
                   10421: Parameters:
                   10422:   resource   - The resource to include.  This is passed directly, without
                   10423:                interpretation to lonnet::ssi.
                   10424:   form       - The form hash parameters that guide the interpretation of the resource
                   10425:                
                   10426:   retries    - Number of retries allowed before giving up completely.
                   10427: Returns:
                   10428:   On success, returns the rendered resource identified by the resource parameter.
                   10429: Side Effects:
                   10430:   The following global variables can be set:
                   10431:    ssi_error                - If an unrecoverable error occurred this becomes true.
                   10432:                               It is up to the caller to initialize this to false
                   10433:                               if desired.
                   10434:    ssi_error_resource  - If an unrecoverable error occurred, this is the value
                   10435:                               of the resource that could not be rendered by the ssi
                   10436:                               call.
                   10437:    ssi_error_message   - The error string fetched from the ssi response
                   10438:                               in the event of an error.
                   10439: 
                   10440: 
                   10441: =head1 HANDLER SUBROUTINE
                   10442: 
                   10443: ssi_with_retries()
                   10444: 
                   10445: =head1 SUBROUTINES
                   10446: 
                   10447: =over
                   10448: 
1.671     raeburn  10449: =head1 Routines to display previous version of a Task for a specific student
                   10450: 
                   10451: Tasks are graded pass/fail. Students who have yet to pass a particular Task
                   10452: can receive another opportunity. Access to tasks is slot-based. If a slot
                   10453: requires a proctor to check-in the student, a new version of the Task will
                   10454: be created when the student is checked in to the new opportunity.
                   10455: 
                   10456: If a particular student has tried two or more versions of a particular task,
                   10457: the submission screen provides a user with vgr privileges (e.g., a Course
                   10458: Coordinator) the ability to display a previous version worked on by the
                   10459: student.  By default, the current version is displayed. If a previous version
                   10460: has been selected for display, submission data are only shown that pertain
                   10461: to that particular version, and the interface to submit grades is not shown.
                   10462: 
                   10463: =over 4
                   10464: 
                   10465: =item show_previous_task_version()
                   10466: 
                   10467: Displays a specified version of a student's Task, as the student sees it.
                   10468: 
                   10469: Inputs: 2
                   10470:         request - request object
                   10471:         symb    - unique symb for current instance of resource
                   10472: 
                   10473: Output: None.
                   10474: 
                   10475: Side Effects: calls &show_problem() to print version of Task, with
                   10476:               version contained in form item: $env{'form.previousversion'}
                   10477: 
                   10478: =item choose_task_version_form()
                   10479: 
                   10480: Displays a web form used to select which version of a student's view of a
                   10481: Task should be displayed.  Either launches a pop-up window, or replaces
                   10482: content in existing pop-up, or replaces page in main window.
                   10483: 
                   10484: Inputs: 4
                   10485:         symb    - unique symb for current instance of resource
                   10486:         uname   - username of student
                   10487:         udom    - domain of student
                   10488:         nomenu  - 1 if display is in a pop-up window, and hence no menu
                   10489:                   breadcrumbs etc., are displayed
                   10490: 
                   10491: Output: 4
                   10492:         current   - student's current version
                   10493:         displayed - student's version being displayed
                   10494:         result    - scalar containing HTML for web form used to switch to
                   10495:                     a different version (or a link to close window, if pop-up).
                   10496:         js        - javascript for processing selection in versions web form
                   10497: 
                   10498: Side Effects: None.
                   10499: 
                   10500: =item previous_display_javascript()
                   10501: 
                   10502: Inputs: 2
                   10503:         nomenu  - 1 if display is in a pop-up window, and hence no menu
                   10504:                   breadcrumbs etc., are displayed.
                   10505:         current - student's current version number.
                   10506: 
                   10507: Output: 1
                   10508:         js      - javascript for processing selection in versions web form.
                   10509: 
                   10510: Side Effects: None.
                   10511: 
                   10512: =back
                   10513: 
                   10514: =head1 Routines to process bubblesheet data.
                   10515: 
                   10516: =over 4
                   10517: 
1.531     jms      10518: =item scantron_get_correction() : 
                   10519: 
                   10520:    Builds the interface screen to interact with the operator to fix a
                   10521:    specific error condition in a specific scanline
                   10522: 
                   10523:  Arguments:
                   10524:     $r           - Apache request object
                   10525:     $i           - number of the current scanline
                   10526:     $scan_record - hash ref as returned from &scantron_parse_scanline()
                   10527:     $scan_config - hash ref as returned from &get_scantron_config()
                   10528:     $line        - full contents of the current scanline
                   10529:     $error       - error condition, valid values are
                   10530:                    'incorrectCODE', 'duplicateCODE',
                   10531:                    'doublebubble', 'missingbubble',
                   10532:                    'duplicateID', 'incorrectID'
                   10533:     $arg         - extra information needed
                   10534:        For errors:
                   10535:          - duplicateID   - paper number that this studentID was seen before on
                   10536:          - duplicateCODE - array ref of the paper numbers this CODE was
                   10537:                            seen on before
                   10538:          - incorrectCODE - current incorrect CODE 
                   10539:          - doublebubble  - array ref of the bubble lines that have double
                   10540:                            bubble errors
                   10541:          - missingbubble - array ref of the bubble lines that have missing
                   10542:                            bubble errors
                   10543: 
1.691     raeburn  10544:    $randomorder - True if exam folder has randomorder set
                   10545:    $randompick  - True if exam folder has randompick set
                   10546:    $respnumlookup - Reference to HASH mapping question numbers in bubble lines
                   10547:                      for current line to question number used for same question
                   10548:                      in "Master Seqence" (as seen by Course Coordinator).
                   10549:    $startline   - Reference to hash where key is question number (0 is first)
                   10550:                   and value is number of first bubble line for current student
                   10551:                   or code-based randompick and/or randomorder.
                   10552: 
                   10553: 
                   10554: 
1.531     jms      10555: =item  scantron_get_maxbubble() : 
                   10556: 
1.582     raeburn  10557:    Arguments:
                   10558:        $nav_error  - Reference to scalar which is a flag to indicate a
                   10559:                       failure to retrieve a navmap object.
                   10560:        if $nav_error is set to 1 by scantron_get_maxbubble(), the 
                   10561:        calling routine should trap the error condition and display the warning
                   10562:        found in &navmap_errormsg().
                   10563: 
1.649     raeburn  10564:        $scantron_config - Reference to bubblesheet format configuration hash.
                   10565: 
1.531     jms      10566:    Returns the maximum number of bubble lines that are expected to
                   10567:    occur. Does this by walking the selected sequence rendering the
                   10568:    resource and then checking &Apache::lonxml::get_problem_counter()
                   10569:    for what the current value of the problem counter is.
                   10570: 
                   10571:    Caches the results to $env{'form.scantron_maxbubble'},
                   10572:    $env{'form.scantron.bubble_lines.n'}, 
                   10573:    $env{'form.scantron.first_bubble_line.n'} and
                   10574:    $env{"form.scantron.sub_bubblelines.n"}
1.691     raeburn  10575:    which are the total number of bubble lines, the number of bubble
1.531     jms      10576:    lines for response n and number of the first bubble line for response n,
                   10577:    and a comma separated list of numbers of bubble lines for sub-questions
                   10578:    (for optionresponse, matchresponse, and rankresponse items), for response n.  
                   10579: 
                   10580: 
                   10581: =item  scantron_validate_missingbubbles() : 
                   10582: 
                   10583:    Validates all scanlines in the selected file to not have any
                   10584:     answers that don't have bubbles that have not been verified
                   10585:     to be bubble free.
                   10586: 
                   10587: =item  scantron_process_students() : 
                   10588: 
1.659     raeburn  10589:    Routine that does the actual grading of the bubblesheet information.
1.531     jms      10590: 
                   10591:    The parsed scanline hash is added to %env 
                   10592: 
                   10593:    Then foreach unskipped scanline it does an &Apache::lonnet::ssi()
                   10594:    foreach resource , with the form data of
                   10595: 
                   10596: 	'submitted'     =>'scantron' 
                   10597: 	'grade_target'  =>'grade',
                   10598: 	'grade_username'=> username of student
                   10599: 	'grade_domain'  => domain of student
                   10600: 	'grade_courseid'=> of course
                   10601: 	'grade_symb'    => symb of resource to grade
                   10602: 
                   10603:     This triggers a grading pass. The problem grading code takes care
                   10604:     of converting the bubbled letter information (now in %env) into a
                   10605:     valid submission.
                   10606: 
                   10607: =item  scantron_upload_scantron_data() :
                   10608: 
1.659     raeburn  10609:     Creates the screen for adding a new bubblesheet data file to a course.
1.531     jms      10610: 
                   10611: =item  scantron_upload_scantron_data_save() : 
                   10612: 
                   10613:    Adds a provided bubble information data file to the course if user
                   10614:    has the correct privileges to do so. 
                   10615: 
                   10616: =item  valid_file() :
                   10617: 
                   10618:    Validates that the requested bubble data file exists in the course.
                   10619: 
                   10620: =item  scantron_download_scantron_data() : 
                   10621: 
                   10622:    Shows a list of the three internal files (original, corrected,
1.659     raeburn  10623:    skipped) for a specific bubblesheet data file that exists in the
1.531     jms      10624:    course.
                   10625: 
                   10626: =item  scantron_validate_ID() : 
                   10627: 
                   10628:    Validates all scanlines in the selected file to not have any
1.556     weissno  10629:    invalid or underspecified student/employee IDs
1.531     jms      10630: 
1.582     raeburn  10631: =item navmap_errormsg() :
                   10632: 
                   10633:    Returns HTML mark-up inside a <div></div> with a link to re-initialize the course.
1.671     raeburn  10634:    Should be called whenever the request to instantiate a navmap object fails.
                   10635: 
                   10636: =back
1.582     raeburn  10637: 
1.531     jms      10638: =back
                   10639: 
                   10640: =cut

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