[Bio] / FigKernelPackages / Tracer.pm Repository:
ViewVC logotype

Annotation of /FigKernelPackages/Tracer.pm

Parent Directory Parent Directory | Revision Log Revision Log


Revision 1.137 - (view) (download) (as text)

1 : gdpusch 1.95 # -*- perl -*-
2 :     ########################################################################
3 : olson 1.30 # Copyright (c) 2003-2006 University of Chicago and Fellowship
4 :     # for Interpretations of Genomes. All Rights Reserved.
5 :     #
6 :     # This file is part of the SEED Toolkit.
7 : parrello 1.61 #
8 : olson 1.30 # The SEED Toolkit is free software. You can redistribute
9 :     # it and/or modify it under the terms of the SEED Toolkit
10 : parrello 1.61 # Public License.
11 : olson 1.30 #
12 :     # You should have received a copy of the SEED Toolkit Public License
13 :     # along with this program; if not write to the University of Chicago
14 :     # at info@ci.uchicago.edu or the Fellowship for Interpretation of
15 :     # Genomes at veronika@thefig.info or download a copy from
16 :     # http://www.theseed.org/LICENSE.TXT.
17 : gdpusch 1.95 ########################################################################
18 : olson 1.30
19 : olson 1.133 #
20 :     # This is a SAS component.
21 :     #
22 :    
23 : olson 1.1 package Tracer;
24 :    
25 : parrello 1.115 use strict;
26 :     use base qw(Exporter);
27 :     use vars qw(@EXPORT @EXPORT_OK);
28 : parrello 1.117 @EXPORT = qw(Trace T TSetup QTrace Confess MemTrace Cluck Min Max Assert Open OpenDir TICK StandardSetup EmergencyKey ETracing Constrain Insure ChDir Emergency Warn TraceDump IDHASH);
29 : parrello 1.97 @EXPORT_OK = qw(GetFile GetOptions Merge MergeOptions ParseCommand ParseRecord UnEscape Escape PrintLine PutLine);
30 : parrello 1.131 use Carp qw(longmess croak carp confess);
31 : parrello 1.12 use CGI;
32 : parrello 1.47 use Cwd;
33 : parrello 1.9 use PageBuilder;
34 : parrello 1.21 use Digest::MD5;
35 : parrello 1.36 use File::Basename;
36 : parrello 1.37 use File::Path;
37 : parrello 1.48 use File::stat;
38 : parrello 1.59 use LWP::UserAgent;
39 : parrello 1.64 use Time::HiRes 'gettimeofday';
40 : parrello 1.65 use URI::Escape;
41 : parrello 1.74 use Time::Local;
42 : parrello 1.99 use POSIX qw(strftime);
43 :     use Time::Zone;
44 : parrello 1.115 use Fcntl qw(:DEFAULT :flock);
45 :     use Data::Dumper;
46 : parrello 1.99
47 : olson 1.137 our $tracer_tmp = "/tmp";
48 : olson 1.1
49 : olson 1.133 #
50 :     # These are made optional in order to facilitate the SAS release
51 :     # that might need Tracer.
52 :     #
53 :     BEGIN {
54 :     eval {
55 :     require FIG_Config;
56 : olson 1.137 $tracer_tmp = $FIG_Config::temp;
57 : olson 1.133 };
58 :     }
59 :    
60 : olson 1.1 =head1 Tracing and Debugging Helpers
61 :    
62 : parrello 1.72 =head2 Tracing
63 : olson 1.1
64 :     This package provides simple tracing for debugging and reporting purposes. To use it simply call the
65 : parrello 1.72 L</TSetup> or L</ETracing> method to set the options and call L</Trace> to write out trace messages.
66 :     L</TSetup> and L</ETracing> both establish a I<trace level> and a list of I<categories>. Similarly,
67 :     each trace message has a I<trace level> and I<category> associated with it. Only messages whose trace
68 :     level is less than or equal to the setup trace level and whose category is activated will
69 : parrello 1.2 be written. Thus, a higher trace level on a message indicates that the message
70 : parrello 1.72 is less likely to be seen, while a higher trace level passed to B<TSetup> means more trace messages will
71 :     appear.
72 : olson 1.1
73 : parrello 1.72 =head3 Putting Trace Messages in Your Code
74 :    
75 :     To generate a trace message, use the following syntax.
76 :    
77 :     Trace($message) if T(errors => 4);
78 : olson 1.1
79 : parrello 1.2 This statement will produce a trace message if the trace level is 4 or more and the C<errors>
80 : parrello 1.72 category is active. There is a special category C<main> that is always active, so
81 : olson 1.1
82 : parrello 1.72 Trace($message) if T(main => 4);
83 : olson 1.1
84 :     will trace if the trace level is 4 or more.
85 :    
86 :     If the category name is the same as the package name, all you need is the number. So, if the
87 :     following call is made in the B<Sprout> package, it will appear if the C<Sprout> category is
88 :     active and the trace level is 2 or more.
89 :    
90 : parrello 1.72 Trace($message) if T(2);
91 :    
92 :     In scripts, where no package name is available, the category defaults to C<main>.
93 :    
94 :     =head3 Custom Tracing
95 :    
96 :     Many programs have customized tracing configured using the L</TSetup> method. This is no longer
97 :     the preferred method, but a knowledge of how custom tracing works can make the more modern
98 :     L</Emergency Tracing> easier to understand.
99 : olson 1.1
100 : parrello 1.72 To set up custom tracing, you call the L</TSetup> method. The method takes as input a trace level,
101 :     a list of category names, and a destination. The trace level and list of category names are
102 : olson 1.1 specified as a space-delimited string. Thus
103 :    
104 : parrello 1.72 TSetup('3 errors Sprout ERDB', 'TEXT');
105 : olson 1.1
106 : parrello 1.7 sets the trace level to 3, activates the C<errors>, C<Sprout>, and C<ERDB> categories, and
107 : parrello 1.72 specifies that messages should be sent to the standard output.
108 : parrello 1.12
109 :     To turn on tracing for ALL categories, use an asterisk. The call below sets every category to
110 :     level 3 and writes the output to the standard error output. This sort of thing might be
111 :     useful in a CGI environment.
112 :    
113 : parrello 1.72 TSetup('3 *', 'WARN');
114 : olson 1.1
115 : parrello 1.72 In addition standard error and file output for trace messages, you can specify that the trace messages
116 : olson 1.1 be queued. The messages can then be retrieved by calling the L</QTrace> method. This approach
117 :     is useful if you are building a web page. Instead of having the trace messages interspersed with
118 :     the page output, they can be gathered together and displayed at the end of the page. This makes
119 :     it easier to debug page formatting problems.
120 :    
121 : parrello 1.72 Finally, you can specify that all trace messages be emitted to a file, or the standard output and
122 :     a file at the same time. To trace to a file, specify the filename with an output character in front
123 :     of it.
124 :    
125 :     TSetup('4 SQL', ">$fileName");
126 :    
127 :     To trace to the standard output and a file at the same time, put a C<+> in front of the angle
128 :     bracket.
129 :    
130 :     TSetup('3 *', "+>$fileName");
131 : parrello 1.4
132 : olson 1.1 The flexibility of tracing makes it superior to simple use of directives like C<die> and C<warn>.
133 :     Tracer calls can be left in the code with minimal overhead and then turned on only when needed.
134 :     Thus, debugging information is available and easily retrieved even when the application is
135 :     being used out in the field.
136 :    
137 : parrello 1.72 =head3 Trace Levels
138 :    
139 : parrello 1.10 There is no hard and fast rule on how to use trace levels. The following is therefore only
140 :     a suggestion.
141 :    
142 :     =over 4
143 :    
144 : parrello 1.32 =item Error 0
145 : parrello 1.10
146 :     Message indicates an error that may lead to incorrect results or that has stopped the
147 :     application entirely.
148 :    
149 : parrello 1.32 =item Warning 1
150 : parrello 1.10
151 :     Message indicates something that is unexpected but that probably did not interfere
152 :     with program execution.
153 :    
154 : parrello 1.32 =item Notice 2
155 : parrello 1.10
156 :     Message indicates the beginning or end of a major task.
157 :    
158 : parrello 1.32 =item Information 3
159 : parrello 1.10
160 :     Message indicates a subtask. In the FIG system, a subtask generally relates to a single
161 :     genome. This would be a big loop that is not expected to execute more than 500 times or so.
162 :    
163 : parrello 1.32 =item Detail 4
164 : parrello 1.10
165 :     Message indicates a low-level loop iteration.
166 :    
167 :     =back
168 :    
169 : parrello 1.69 The format of trace messages is important because some utilities analyze trace files.
170 : parrello 1.72 There are three fields-- the time stamp, the category name, and the text.
171 :     The time stamp is between square brackets and the category name between angle brackets.
172 :     After the category name there is a colon (C<:>) followed by the message text.
173 :     If the square brackets or angle brackets are missing, then the trace management
174 :     utilities assume that they are encountering a set of pre-formatted lines.
175 :    
176 :     Note, however, that this formatting is done automatically by the tracing functions. You
177 :     only need to know about it if you want to parse a trace file.
178 :    
179 :     =head3 Emergency Tracing
180 :    
181 :     Sometimes, you need a way for tracing to happen automatically without putting parameters
182 :     in a form or on the command line. Emergency tracing does this. You invoke emergency tracing
183 : parrello 1.97 from the debug form, which is accessed from the [[DebugConsole]]. Emergency tracing requires
184 :     that you specify a tracing key. For command-line tools, the key is
185 : parrello 1.72 taken from the C<TRACING> environment variable. For web services, the key is taken from
186 :     a cookie. Either way, the key tells the tracing facility who you are, so that you control
187 :     the tracing in your environment without stepping on other users.
188 :    
189 :     The key can be anything you want. If you don't have a key, the C<SetPassword> page will
190 :     generate one for you.
191 :    
192 :     You can activate and de-activate emergency tracing from the debugging control panel, as
193 :     well as display the trace file itself.
194 :    
195 :     To enable emergency tracing in your code, call
196 :    
197 :     ETracing($cgi)
198 :    
199 :     from a web script and
200 :    
201 :     ETracing()
202 :    
203 :     from a command-line script.
204 :    
205 :     The web script will look for the tracing key in the cookies, and the command-line
206 :     script will look for it in the C<TRACING> environment variable. If you are
207 : parrello 1.97 using the L</StandardSetup> method or a [[WebApplication]], emergency tracing
208 : parrello 1.72 will be configured automatically.
209 :    
210 : olson 1.1 =cut
211 : parrello 1.2
212 : olson 1.1 # Declare the configuration variables.
213 :    
214 : parrello 1.94 my $Destination = "WARN"; # Description of where to send the trace output.
215 : parrello 1.12 my $TeeFlag = 0; # TRUE if output is going to a file and to the
216 :     # standard output
217 : parrello 1.3 my %Categories = ( main => 1 );
218 : parrello 1.12 # hash of active category names
219 : parrello 1.97 my @LevelNames = qw(error warn notice info detail);
220 : parrello 1.12 my $TraceLevel = 0; # trace level; a higher trace level produces more
221 :     # messages
222 :     my @Queue = (); # queued list of trace messages.
223 : parrello 1.7 my $LastCategory = "main"; # name of the last category interrogated
224 : parrello 1.97 my $LastLevel = 0; # level of the last test call
225 : parrello 1.11 my $SetupCount = 0; # number of times TSetup called
226 : parrello 1.12 my $AllTrace = 0; # TRUE if we are tracing all categories.
227 : parrello 1.99 my $SavedCGI; # CGI object passed to ETracing
228 : parrello 1.104 my $CommandLine; # Command line passed to StandardSetup
229 : parrello 1.119 my $Confessions = 0; # confession count
230 : parrello 1.99 umask 2; # Fix the damn umask so everything is group-writable.
231 : olson 1.1
232 : parrello 1.93 =head2 Tracing Methods
233 :    
234 :     =head3 Setups
235 :    
236 :     my $count = Tracer::Setups();
237 :    
238 :     Return the number of times L</TSetup> has been called.
239 :    
240 :     This method allows for the creation of conditional tracing setups where, for example, we
241 :     may want to set up tracing if nobody else has done it before us.
242 :    
243 :     =cut
244 :    
245 :     sub Setups {
246 :     return $SetupCount;
247 :     }
248 : olson 1.1
249 :     =head3 TSetup
250 :    
251 : parrello 1.92 TSetup($categoryList, $target);
252 : olson 1.1
253 :     This method is used to specify the trace options. The options are stored as package data
254 :     and interrogated by the L</Trace> and L</T> methods.
255 :    
256 :     =over 4
257 :    
258 :     =item categoryList
259 :    
260 :     A string specifying the trace level and the categories to be traced, separated by spaces.
261 :     The trace level must come first.
262 :    
263 :     =item target
264 :    
265 :     The destination for the trace output. To send the trace output to a file, specify the file
266 :     name preceded by a ">" symbol. If a double symbol is used (">>"), then the data is appended
267 : parrello 1.10 to the file. Otherwise the file is cleared before tracing begins. Precede the first ">"
268 :     symbol with a C<+> to echo output to a file AND to the standard output. In addition to
269 :     sending the trace messages to a file, you can specify a special destination. C<HTML> will
270 :     cause tracing to the standard output with each line formatted as an HTML paragraph. C<TEXT>
271 : parrello 1.5 will cause tracing to the standard output as ordinary text. C<ERROR> will cause trace
272 : parrello 1.9 messages to be sent to the standard error output as ordinary text. C<QUEUE> will cause trace
273 : parrello 1.6 messages to be stored in a queue for later retrieval by the L</QTrace> method. C<WARN> will
274 : parrello 1.9 cause trace messages to be emitted as warnings using the B<warn> directive. C<NONE> will
275 : parrello 1.6 cause tracing to be suppressed.
276 : olson 1.1
277 :     =back
278 :    
279 :     =cut
280 :    
281 :     sub TSetup {
282 : parrello 1.12 # Get the parameters.
283 :     my ($categoryList, $target) = @_;
284 :     # Parse the category list.
285 : parrello 1.136 my @categoryData = split m/\s+/, $categoryList;
286 : parrello 1.12 # Extract the trace level.
287 :     $TraceLevel = shift @categoryData;
288 :     # Presume category-based tracing until we learn otherwise.
289 :     $AllTrace = 0;
290 :     # Build the category hash. Note that if we find a "*", we turn on non-category
291 : parrello 1.33 # tracing. We must also clear away any pre-existing data.
292 : parrello 1.34 %Categories = ( main => 1 );
293 : parrello 1.12 for my $category (@categoryData) {
294 :     if ($category eq '*') {
295 :     $AllTrace = 1;
296 :     } else {
297 : parrello 1.13 $Categories{lc $category} = 1;
298 : parrello 1.12 }
299 :     }
300 :     # Now we need to process the destination information. The most important special
301 : parrello 1.98 # case is when we're writing to a file. This is indicated by ">" (overwrite) and
302 :     # ">>" (append). A leading "+" for either indicates that we are also writing to
303 :     # the standard output (tee mode).
304 : parrello 1.12 if ($target =~ m/^\+?>>?/) {
305 :     if ($target =~ m/^\+/) {
306 :     $TeeFlag = 1;
307 :     $target = substr($target, 1);
308 :     }
309 :     if ($target =~ m/^>[^>]/) {
310 : parrello 1.98 # We need to initialize the file (which clears it).
311 : parrello 1.12 open TRACEFILE, $target;
312 : parrello 1.98 print TRACEFILE "[" . Now() . "] [notice] [Tracer] Tracing initialized.\n";
313 : parrello 1.12 close TRACEFILE;
314 : parrello 1.98 # Set to append mode now that the file has been cleared.
315 : parrello 1.12 $Destination = ">$target";
316 :     } else {
317 :     $Destination = $target;
318 :     }
319 :     } else {
320 :     $Destination = uc($target);
321 :     }
322 :     # Increment the setup counter.
323 :     $SetupCount++;
324 : parrello 1.11 }
325 :    
326 : parrello 1.93 =head3 SetLevel
327 : parrello 1.31
328 : parrello 1.93 Tracer::SetLevel($newLevel);
329 : parrello 1.31
330 : parrello 1.93 Modify the trace level. A higher trace level will cause more messages to appear.
331 : parrello 1.31
332 : parrello 1.93 =over 4
333 : parrello 1.31
334 : parrello 1.93 =item newLevel
335 : parrello 1.31
336 : parrello 1.93 Proposed new trace level.
337 : parrello 1.31
338 : parrello 1.93 =back
339 : parrello 1.31
340 : parrello 1.93 =cut
341 : parrello 1.31
342 : parrello 1.93 sub SetLevel {
343 :     $TraceLevel = $_[0];
344 :     }
345 : parrello 1.31
346 : parrello 1.97 =head3 ParseDate
347 :    
348 :     my $time = Tracer::ParseDate($dateString);
349 :    
350 :     Convert a date into a PERL time number. This method expects a date-like string
351 :     and parses it into a number. The string must be vaguely date-like or it will
352 :     return an undefined value. Our requirement is that a month and day be
353 :     present and that three pieces of the date string (time of day, month and day,
354 :     year) be separated by likely delimiters, such as spaces, commas, and such-like.
355 :    
356 :     If a time of day is present, it must be in military time with two digits for
357 :     everything but the hour.
358 : parrello 1.31
359 : parrello 1.97 The year must be exactly four digits.
360 : parrello 1.31
361 : parrello 1.97 Additional stuff can be in the string. We presume it's time zones or weekdays or something
362 :     equally innocuous. This means, however, that a sufficiently long sentence with date-like
363 :     parts in it may be interpreted as a date. Hopefully this will not be a problem.
364 :    
365 :     It should be guaranteed that this method will parse the output of the L</Now> function.
366 :    
367 :     The parameters are as follows.
368 : parrello 1.31
369 : parrello 1.93 =over 4
370 : parrello 1.31
371 : parrello 1.93 =item dateString
372 : parrello 1.31
373 : parrello 1.97 The date string to convert.
374 : parrello 1.31
375 : parrello 1.93 =item RETURN
376 : parrello 1.31
377 : parrello 1.93 Returns a PERL time, that is, a number of seconds since the epoch, or C<undef> if
378 : parrello 1.97 the date string is invalid. A valid date string must contain a month and day.
379 : parrello 1.31
380 : parrello 1.93 =back
381 : parrello 1.38
382 : parrello 1.93 =cut
383 : parrello 1.38
384 : parrello 1.97 # Universal month conversion table.
385 :     use constant MONTHS => { Jan => 0, January => 0, '01' => 0, '1' => 0,
386 :     Feb => 1, February => 1, '02' => 1, '2' => 1,
387 :     Mar => 2, March => 2, '03' => 2, '3' => 2,
388 :     Apr => 3, April => 3, '04' => 3, '4' => 3,
389 :     May => 4, May => 4, '05' => 4, '5' => 4,
390 :     Jun => 5, June => 5, '06' => 5, '6' => 5,
391 :     Jul => 6, July => 6, '07' => 6, '7' => 6,
392 :     Aug => 7, August => 7, '08' => 7, '8' => 7,
393 :     Sep => 8, September => 8, '09' => 8, '9' => 8,
394 :     Oct => 9, October => 9, '10' => 9,
395 :     Nov => 10, November => 10, '11' => 10,
396 :     Dec => 11, December => 11, '12' => 11
397 :     };
398 :    
399 :     sub ParseDate {
400 : parrello 1.93 # Get the parameters.
401 :     my ($dateString) = @_;
402 :     # Declare the return variable.
403 :     my $retVal;
404 : parrello 1.97 # Find the month and day of month. There are two ways that can happen. We check for the
405 :     # numeric style first. That way, if the user's done something like "Sun 12/22", then we
406 :     # won't be fooled into thinking the month is Sunday.
407 :     if ($dateString =~ m#\b(\d{1,2})/(\d{1,2})\b# || $dateString =~ m#\b(\w+)\s(\d{1,2})\b#) {
408 :     my ($mon, $mday) = (MONTHS->{$1}, $2);
409 :     # Insist that the month and day are valid.
410 :     if (defined($mon) && $2 >= 1 && $2 <= 31) {
411 :     # Find the time.
412 :     my ($hour, $min, $sec) = (0, 0, 0);
413 :     if ($dateString =~ /\b(\d{1,2}):(\d{2}):(\d{2})\b/) {
414 :     ($hour, $min, $sec) = ($1, $2, $3);
415 :     }
416 :     # Find the year.
417 :     my $year;
418 :     if ($dateString =~ /\b(\d{4})\b/) {
419 :     $year = $1;
420 :     } else {
421 :     # Get the default year, which is this one. Note we must convert it to
422 :     # the four-digit value expected by "timelocal".
423 :     (undef, undef, undef, undef, undef, $year) = localtime();
424 :     $year += 1900;
425 :     }
426 :     $retVal = timelocal($sec, $min, $hour, $mday, $mon, $year);
427 :     }
428 : parrello 1.93 }
429 :     # Return the result.
430 :     return $retVal;
431 :     }
432 : parrello 1.31
433 : parrello 1.93 =head3 LogErrors
434 : parrello 1.42
435 : parrello 1.93 Tracer::LogErrors($fileName);
436 : parrello 1.31
437 : parrello 1.93 Route the standard error output to a log file.
438 : parrello 1.31
439 : parrello 1.93 =over 4
440 : parrello 1.31
441 : parrello 1.93 =item fileName
442 : parrello 1.31
443 : parrello 1.93 Name of the file to receive the error output.
444 : parrello 1.31
445 : parrello 1.93 =back
446 : parrello 1.31
447 : parrello 1.93 =cut
448 : parrello 1.84
449 : parrello 1.93 sub LogErrors {
450 :     # Get the file name.
451 :     my ($fileName) = @_;
452 :     # Open the file as the standard error output.
453 :     open STDERR, '>', $fileName;
454 :     }
455 : parrello 1.84
456 : parrello 1.93 =head3 Trace
457 : parrello 1.31
458 : parrello 1.93 Trace($message);
459 : parrello 1.31
460 : parrello 1.93 Write a trace message to the target location specified in L</TSetup>. If there has not been
461 :     any prior call to B<TSetup>.
462 : parrello 1.31
463 : parrello 1.93 =over 4
464 : parrello 1.42
465 : parrello 1.93 =item message
466 : parrello 1.42
467 : parrello 1.93 Message to write.
468 : parrello 1.42
469 : parrello 1.93 =back
470 : parrello 1.72
471 : parrello 1.93 =cut
472 : parrello 1.36
473 : parrello 1.93 sub Trace {
474 :     # Get the parameters.
475 :     my ($message) = @_;
476 : parrello 1.97 # Strip off any line terminators at the end of the message. We will add
477 :     # new-line stuff ourselves.
478 :     my $stripped = Strip($message);
479 :     # Compute the caller information.
480 :     my ($callPackage, $callFile, $callLine) = caller();
481 :     my $callFileTitle = basename($callFile);
482 :     # Check the caller.
483 : parrello 1.98 my $callerInfo = ($callFileTitle ne "Tracer.pm" ? " [$callFileTitle $callLine]" : "");
484 : parrello 1.93 # Get the timestamp.
485 :     my $timeStamp = Now();
486 : parrello 1.97 # Build the prefix.
487 :     my $level = $LevelNames[$LastLevel] || "($LastLevel)";
488 : parrello 1.98 my $prefix = "[$timeStamp] [$level] [$LastCategory]$callerInfo";
489 : parrello 1.97 # Format the message.
490 :     my $formatted = "$prefix $stripped";
491 : parrello 1.93 # Process according to the destination.
492 :     if ($Destination eq "TEXT") {
493 :     # Write the message to the standard output.
494 :     print "$formatted\n";
495 :     } elsif ($Destination eq "ERROR") {
496 : parrello 1.97 # Write the message to the error output. Here, we want our prefix fields.
497 : parrello 1.93 print STDERR "$formatted\n";
498 : parrello 1.97 } elsif ($Destination eq "WARN") {
499 :     # Emit the message to the standard error output. It is presumed that the
500 : parrello 1.98 # error logger will add its own prefix fields, the notable exception being
501 :     # the caller info.
502 :     print STDERR "$callerInfo$stripped\n";
503 : parrello 1.93 } elsif ($Destination eq "QUEUE") {
504 :     # Push the message into the queue.
505 :     push @Queue, "$formatted";
506 :     } elsif ($Destination eq "HTML") {
507 : parrello 1.116 # Convert the message to HTML.
508 : parrello 1.97 my $escapedMessage = CGI::escapeHTML($stripped);
509 : parrello 1.116 # The stuff after the first line feed should be pre-formatted.
510 : parrello 1.135 my @lines = split m/\s*\n/, $escapedMessage;
511 : parrello 1.116 # Get the normal portion.
512 :     my $line1 = shift @lines;
513 :     print "<p>$timeStamp $LastCategory $LastLevel: $line1</p>\n";
514 :     if (@lines) {
515 : parrello 1.120 print "<pre>" . join("\n", @lines, "</pre>");
516 : parrello 1.116 }
517 : parrello 1.93 } elsif ($Destination =~ m/^>>/) {
518 :     # Write the trace message to an output file.
519 : parrello 1.131 open(TRACING, $Destination) || confess("Tracing open for \"$Destination\" failed: $!");
520 : parrello 1.111 # Lock the file.
521 :     flock TRACING, LOCK_EX;
522 : parrello 1.93 print TRACING "$formatted\n";
523 :     close TRACING;
524 :     # If the Tee flag is on, echo it to the standard output.
525 :     if ($TeeFlag) {
526 :     print "$formatted\n";
527 :     }
528 :     }
529 :     }
530 : parrello 1.36
531 : parrello 1.117 =head3 MemTrace
532 :    
533 :     MemTrace($message);
534 :    
535 :     Output a trace message that includes memory size information.
536 :    
537 :     =over 4
538 :    
539 :     =item message
540 :    
541 :     Message to display. The message will be followed by a sentence about the memory size.
542 :    
543 :     =back
544 :    
545 :     =cut
546 :    
547 :     sub MemTrace {
548 :     # Get the parameters.
549 :     my ($message) = @_;
550 :     my $memory = GetMemorySize();
551 :     Trace("$message $memory in use.");
552 :     }
553 :    
554 :    
555 : parrello 1.115 =head3 TraceDump
556 :    
557 :     TraceDump($title, $object);
558 :    
559 :     Dump an object to the trace log. This method simply calls the C<Dumper>
560 :     function, but routes the output to the trace log instead of returning it
561 :     as a string. The output is arranged so that it comes out monospaced when
562 :     it appears in an HTML trace dump.
563 :    
564 :     =over 4
565 :    
566 :     =item title
567 :    
568 :     Title to give to the object being dumped.
569 :    
570 :     =item object
571 :    
572 :     Reference to a list, hash, or object to dump.
573 :    
574 :     =back
575 :    
576 :     =cut
577 :    
578 :     sub TraceDump {
579 :     # Get the parameters.
580 :     my ($title, $object) = @_;
581 :     # Trace the object.
582 :     Trace("Object dump for $title:\n" . Dumper($object));
583 :     }
584 :    
585 : parrello 1.93 =head3 T
586 : parrello 1.36
587 : parrello 1.93 my $switch = T($category, $traceLevel);
588 : parrello 1.36
589 : parrello 1.93 or
590 : parrello 1.44
591 : parrello 1.93 my $switch = T($traceLevel);
592 : parrello 1.44
593 : parrello 1.93 Return TRUE if the trace level is at or above a specified value and the specified category
594 :     is active, else FALSE. If no category is specified, the caller's package name is used.
595 : parrello 1.44
596 : parrello 1.93 =over 4
597 : parrello 1.44
598 : parrello 1.93 =item category
599 : parrello 1.44
600 : parrello 1.93 Category to which the message belongs. If not specified, the caller's package name is
601 :     used.
602 : parrello 1.31
603 : parrello 1.93 =item traceLevel
604 : parrello 1.31
605 : parrello 1.93 Relevant tracing level.
606 : parrello 1.31
607 : parrello 1.93 =item RETURN
608 : parrello 1.31
609 : parrello 1.93 TRUE if a message at the specified trace level would appear in the trace, else FALSE.
610 : parrello 1.31
611 : parrello 1.93 =back
612 : parrello 1.36
613 : parrello 1.93 =cut
614 :    
615 :     sub T {
616 :     # Declare the return variable.
617 :     my $retVal = 0;
618 :     # Only proceed if tracing is turned on.
619 :     if ($Destination ne "NONE") {
620 :     # Get the parameters.
621 :     my ($category, $traceLevel) = @_;
622 :     if (!defined $traceLevel) {
623 :     # Here we have no category, so we need to get the calling package.
624 :     # The calling package is normally the first parameter. If it is
625 :     # omitted, the first parameter will be the tracelevel. So, the
626 :     # first thing we do is shift the so-called category into the
627 :     # $traceLevel variable where it belongs.
628 :     $traceLevel = $category;
629 :     my ($package, $fileName, $line) = caller;
630 :     # If there is no calling package, we default to "main".
631 :     if (!$package) {
632 :     $category = "main";
633 :     } else {
634 :     my @cats = split /::/, $package;
635 :     $category = $cats[$#cats];
636 :     }
637 :     }
638 : parrello 1.97 # Save the category name and level.
639 : parrello 1.93 $LastCategory = $category;
640 : parrello 1.97 $LastLevel = $traceLevel;
641 : parrello 1.93 # Convert it to lower case before we hash it.
642 :     $category = lc $category;
643 : parrello 1.100 # Validate the trace level.
644 : parrello 1.93 if (ref $traceLevel) {
645 :     Confess("Bad trace level.");
646 :     } elsif (ref $TraceLevel) {
647 :     Confess("Bad trace config.");
648 :     }
649 : parrello 1.100 # Make the check. Note that level 0 shows even if the category is turned off.
650 :     $retVal = ($traceLevel <= $TraceLevel && ($traceLevel == 0 || $AllTrace || exists $Categories{$category}));
651 : parrello 1.93 }
652 :     # Return the computed result.
653 :     return $retVal;
654 :     }
655 :    
656 :     =head3 QTrace
657 :    
658 :     my $data = QTrace($format);
659 :    
660 :     Return the queued trace data in the specified format.
661 :    
662 :     =over 4
663 :    
664 :     =item format
665 :    
666 :     C<html> to format the data as an HTML list, C<text> to format it as straight text.
667 :    
668 :     =back
669 :    
670 :     =cut
671 :    
672 :     sub QTrace {
673 :     # Get the parameter.
674 :     my ($format) = @_;
675 :     # Create the return variable.
676 :     my $retVal = "";
677 :     # Only proceed if there is an actual queue.
678 :     if (@Queue) {
679 :     # Process according to the format.
680 :     if ($format =~ m/^HTML$/i) {
681 :     # Convert the queue into an HTML list.
682 :     $retVal = "<ul>\n";
683 :     for my $line (@Queue) {
684 :     my $escapedLine = CGI::escapeHTML($line);
685 :     $retVal .= "<li>$escapedLine</li>\n";
686 :     }
687 :     $retVal .= "</ul>\n";
688 :     } elsif ($format =~ m/^TEXT$/i) {
689 :     # Convert the queue into a list of text lines.
690 :     $retVal = join("\n", @Queue) . "\n";
691 :     }
692 :     # Clear the queue.
693 :     @Queue = ();
694 :     }
695 :     # Return the formatted list.
696 :     return $retVal;
697 :     }
698 :    
699 :     =head3 Confess
700 :    
701 :     Confess($message);
702 :    
703 :     Trace the call stack and abort the program with the specified message. When used with
704 :     the OR operator and the L</Assert> method, B<Confess> can function as a debugging assert.
705 :     So, for example
706 :    
707 :     Assert($recNum >= 0) || Confess("Invalid record number $recNum.");
708 :    
709 :     Will abort the program with a stack trace if the value of C<$recNum> is negative.
710 :    
711 :     =over 4
712 :    
713 :     =item message
714 :    
715 :     Message to include in the trace.
716 :    
717 :     =back
718 :    
719 :     =cut
720 :    
721 :     sub Confess {
722 :     # Get the parameters.
723 :     my ($message) = @_;
724 : parrello 1.97 # Set up the category and level.
725 :     $LastCategory = "(confess)";
726 :     $LastLevel = 0;
727 : parrello 1.93 # Trace the call stack.
728 :     Cluck($message);
729 : parrello 1.119 # Increment the confession count.
730 :     $Confessions++;
731 : parrello 1.93 # Abort the program.
732 :     croak(">>> $message");
733 :     }
734 :    
735 : parrello 1.119 =head3 Confessions
736 :    
737 :     my $count = Tracer::Confessions();
738 :    
739 :     Return the number of calls to L</Confess> by the current task.
740 :    
741 :     =cut
742 :    
743 :     sub Confessions {
744 :     return $Confessions;
745 :     }
746 :    
747 :    
748 : parrello 1.106 =head3 SaveCGI
749 :    
750 :     Tracer::SaveCGI($cgi);
751 :    
752 :     This method saves the CGI object but does not activate emergency tracing.
753 :     It is used to allow L</Warn> to work in situations where emergency
754 :     tracing is contra-indicated (e.g. the wiki).
755 :    
756 :     =over 4
757 :    
758 :     =item cgi
759 :    
760 :     Active CGI query object.
761 :    
762 :     =back
763 :    
764 :     =cut
765 :    
766 :     sub SaveCGI {
767 :     $SavedCGI = $_[0];
768 :     }
769 :    
770 : parrello 1.99 =head3 Warn
771 :    
772 : parrello 1.106 Warn($message, @options);
773 : parrello 1.99
774 :     This method traces an important message. If an RSS feed is configured
775 :     (via I<FIG_Config::error_feed>) and the tracing destination is C<WARN>,
776 :     then the message will be echoed to the feed. In general, a tracing
777 :     destination of C<WARN> indicates that the caller is running as a web
778 :     service in a production environment; however, this is not a requirement.
779 :    
780 : parrello 1.103 To force warnings into the RSS feed even when the tracing destination
781 :     is not C<WARN>, simply specify the C<Feed> tracing module. This can be
782 :     configured automatically when L</StandardSetup> is used.
783 :    
784 : parrello 1.99 The L</Cluck> method calls this one for its final message. Since
785 :     L</Confess> calls L</Cluck>, this means that any error which is caught
786 :     and confessed will put something in the feed. This insures that someone
787 :     will be alerted relatively quickly when a failure occurs.
788 :    
789 :     =over 4
790 :    
791 :     =item message
792 :    
793 :     Message to be traced.
794 :    
795 : parrello 1.106 =item options
796 :    
797 :     A list containing zero or more options.
798 :    
799 :     =back
800 :    
801 :     The permissible options are as follows.
802 :    
803 :     =over 4
804 :    
805 :     =item noStack
806 :    
807 :     If specified, then the stack trace is not included in the output.
808 :    
809 : parrello 1.99 =back
810 :    
811 :     =cut
812 :    
813 :     sub Warn {
814 :     # Get the parameters.
815 : parrello 1.106 my $message = shift @_;
816 :     my %options = map { $_ => 1 } @_;
817 : parrello 1.107 # Save $@;
818 :     my $savedError = $@;
819 : parrello 1.99 # Trace the message.
820 :     Trace($message);
821 : parrello 1.106 # This will contain the lock handle. If it's defined, it means we need to unlock.
822 :     my $lock;
823 : parrello 1.103 # Check for feed forcing.
824 :     my $forceFeed = exists $Categories{feed};
825 : parrello 1.106 # An error here would be disastrous. Note that if debug mode is specified,
826 :     # we do this stuff even in a test environment.
827 : parrello 1.99 eval {
828 :     # Do we need to put this in the RSS feed?
829 : parrello 1.103 if ($FIG_Config::error_feed && ($Destination eq 'WARN' || $forceFeed)) {
830 : parrello 1.109 # Probably. We need to check first, however, to see if it's from an
831 :     # ignored IP. For non-CGI situations, we default the IP to the self-referent.
832 :     my $key = "127.0.0.1";
833 :     if (defined $SavedCGI) {
834 :     # Get the IP address.
835 :     $key = $ENV{HTTP_X_FORWARDED_FOR} || $ENV{REMOTE_ADDR};
836 : parrello 1.101 }
837 : parrello 1.109 # Is the IP address in the ignore list?
838 :     my $found = scalar(grep { $_ eq $key } @FIG_Config::error_ignore_ips);
839 :     if (! $found) {
840 :     # No. We're good. We now need to compute the date, the link, and the title.
841 :     # First, the date, in a very specific format.
842 :     my $date = strftime("%a, %02e %b %H:%M:%S %Y ", localtime) .
843 :     (tz_local_offset() / 30);
844 :     # Environment data goes in here. We start with the date.
845 :     my $environment = "$date. ";
846 :     # If we need to recap the message (because it's too long to be a title), we'll
847 :     # put it in here.
848 :     my $recap;
849 :     # Copy the message and remove excess space.
850 :     my $title = $message;
851 :     $title =~ s/\s+/ /gs;
852 :     # If it's too long, we have to split it up.
853 :     if (length $title > 60) {
854 :     # Put the full message in the environment string.
855 :     $recap = $title;
856 :     # Excerpt it as the title.
857 :     $title = substr($title, 0, 50) . "...";
858 :     }
859 :     # If we have a CGI object, then this is a web error. Otherwise, it's
860 :     # command-line.
861 :     if (defined $SavedCGI) {
862 :     # We're in a web service. The environment is the user's IP, and the link
863 :     # is the URL that got us here.
864 :     $environment .= "Event Reported at IP address $key process $$.";
865 :     my $url = $SavedCGI->self_url();
866 :     # We need the user agent string and (if available) the referrer.
867 :     # The referrer will be the link.
868 :     $environment .= " User Agent $ENV{HTTP_USER_AGENT}";
869 :     if ($ENV{HTTP_REFERER}) {
870 :     my $link = $ENV{HTTP_REFERER};
871 :     $environment .= " referred from <a href=\"$link\">$link</a>.";
872 :     } else {
873 :     $environment .= " referrer unknown.";
874 :     }
875 :     # Close off the sentence with the original link.
876 :     $environment .= " URL of event is <a href=\"$url\">$url</a>.";
877 :     } else {
878 :     # No CGI object, so we're a command-line tool. Use the tracing
879 :     # key and the PID as the user identifier, and add the command.
880 :     my $key = EmergencyKey();
881 :     $environment .= "Event Reported by $key process $$.";
882 :     if ($CommandLine) {
883 :     # We're in a StandardSetup script, so we have the real command line.
884 :     $environment .= "\n<pre>" . CGI::escapeHTML($CommandLine) . "</pre>\n";
885 :     } elsif ($ENV{_}) {
886 :     # We're in a BASH script, so the command has been stored in the _ variable.
887 :     $environment .= " Command = " . CGI::escapeHTML($ENV{_}) . "\n";
888 :     }
889 :     }
890 :     # Build a GUID. We use the current time, the title, and the process ID,
891 :     # then digest the result.
892 :     my $guid = Digest::MD5::md5_base64(gettimeofday(), $title, $$);
893 :     # Finally, the description. This is a stack trace plus various environmental stuff.
894 :     # The trace is optional.
895 :     my $stackTrace;
896 :     if ($options{noStack}) {
897 :     $stackTrace = "";
898 :     } else {
899 :     my @trace = LongMess();
900 :     # Only proceed if we got something back.
901 :     if (scalar(@trace) > 0) {
902 :     $trace[0] =~ s/Tracer::Warn.+?called/Event occurred/;
903 :     $stackTrace = "Stack trace:<pre>" . join("\n", @trace, "</pre>");
904 :     }
905 :     }
906 :     # We got the stack trace. Now it's time to put it all together.
907 :     # We have a goofy thing here in that we need to HTML-escape some sections of the description
908 :     # twice. They will be escaped once here, and then once when written by XML::Simple. They are
909 :     # unescaped once when processed by the RSS reader, and stuff in the description is treated as
910 :     # HTML. So, anything escaped here is treated as a literal when viewed in the RSS reader, but
911 :     # our <br>s and <pre>s are used to format the description.
912 :     $recap = (defined $recap ? "<em>" . CGI::escapeHTML($recap) . "</em><br /><br />" : "");
913 :     my $description = "$recap$environment $stackTrace";
914 :     # Okay, we have all the pieces. Create a hash of the new event.
915 :     my $newItem = { title => $title,
916 :     description => $description,
917 :     category => $LastCategory,
918 :     pubDate => $date,
919 :     guid => $guid,
920 :     };
921 :     # We need XML capability for this.
922 :     require XML::Simple;
923 :     # The RSS document goes in here.
924 :     my $rss;
925 :     # Get the name of the RSS file. It's in the FIG temporary directory.
926 : olson 1.137 my $fileName = "$tracer_tmp/$FIG_Config::error_feed";
927 : parrello 1.109 # Open the config file and lock it.
928 :     $lock = Open(undef, "<$FIG_Config::fig_disk/config/FIG_Config.pm");
929 :     flock $lock, LOCK_EX;
930 :     # Does it exist?
931 :     if (-s $fileName) {
932 :     # Slurp it in.
933 :     $rss = XML::Simple::XMLin($fileName, ForceArray => ['item']);
934 : parrello 1.102 } else {
935 : parrello 1.109 my $size = -s $fileName;
936 :     # Create an empty channel.
937 :     $rss = {
938 :     channel => {
939 :     title => 'NMPDR Warning Feed',
940 :     link => "$FIG_Config::temp_url/$FIG_Config::error_feed",
941 :     description => "Important messages regarding the status of the NMPDR.",
942 :     generator => "NMPDR Trace Facility",
943 :     docs => "http://blogs.law.harvard.edu/tech/rss",
944 :     item => []
945 :     },
946 :     };
947 : parrello 1.100 }
948 : parrello 1.109 # Get the channel object.
949 :     my $channel = $rss->{channel};
950 :     # Update the last-build date.
951 :     $channel->{lastBuildDate} = $date;
952 :     # Get the item array.
953 :     my $items = $channel->{item};
954 :     # Insure it has only 100 entries.
955 :     while (scalar @{$items} > 100) {
956 :     pop @{$items};
957 : parrello 1.104 }
958 : parrello 1.109 # Add our new item at the front.
959 :     unshift @{$items}, $newItem;
960 :     # Create the XML. Note we do not include the root or the declaration. XML Simple can't handle
961 :     # the requirements for those.
962 :     my $xml = XML::Simple::XMLout($channel, NoAttr => 1, RootName => 'channel', XmlDecl => '');
963 :     # Here we put in the root and declaration. The problem is that the root has to have the version attribute
964 :     # in it. So, we suppress the root and do it by hand, and that requires suppressing the declaration, too.
965 :     $xml = "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<rss version=\"2.0\">$xml\n</rss>";
966 :     # We don't use Open here because we can't afford an error.
967 :     if (open XMLOUT, ">$fileName") {
968 :     print XMLOUT $xml;
969 :     close XMLOUT;
970 : parrello 1.106 }
971 : parrello 1.101 }
972 : parrello 1.99 }
973 :     };
974 : parrello 1.103 if ($@) {
975 :     # If the feed failed, we need to know why. The error will be traced, but this method will not be involved
976 :     # (which is a good thing).
977 : parrello 1.102 my $error = $@;
978 : parrello 1.103 Trace("Feed Error: $error") if T(Feed => 0);
979 : parrello 1.102 }
980 : parrello 1.106 # Be sure to unlock.
981 :     if ($lock) {
982 :     flock $lock, LOCK_UN;
983 :     undef $lock;
984 :     }
985 : parrello 1.107 # Restore the error message.
986 :     $@ = $savedError;
987 : parrello 1.99 }
988 :    
989 : parrello 1.106
990 :    
991 :    
992 : parrello 1.93 =head3 Assert
993 :    
994 :     Assert($condition1, $condition2, ... $conditionN);
995 :    
996 :     Return TRUE if all the conditions are true. This method can be used in conjunction with
997 :     the OR operator and the L</Confess> method as a debugging assert.
998 :     So, for example
999 :    
1000 :     Assert($recNum >= 0) || Confess("Invalid record number $recNum.");
1001 :    
1002 :     Will abort the program with a stack trace if the value of C<$recNum> is negative.
1003 :    
1004 :     =cut
1005 :     sub Assert {
1006 :     my $retVal = 1;
1007 :     LOOP: for my $condition (@_) {
1008 :     if (! $condition) {
1009 :     $retVal = 0;
1010 :     last LOOP;
1011 :     }
1012 :     }
1013 :     return $retVal;
1014 :     }
1015 :    
1016 :     =head3 Cluck
1017 :    
1018 :     Cluck($message);
1019 :    
1020 :     Trace the call stack. Note that for best results, you should qualify the call with a
1021 :     trace condition. For example,
1022 :    
1023 :     Cluck("Starting record parse.") if T(3);
1024 :    
1025 :     will only trace the stack if the trace level for the package is 3 or more.
1026 :    
1027 :     =over 4
1028 :    
1029 :     =item message
1030 :    
1031 :     Message to include in the trace.
1032 :    
1033 :     =back
1034 :    
1035 :     =cut
1036 :    
1037 :     sub Cluck {
1038 :     # Get the parameters.
1039 :     my ($message) = @_;
1040 :     # Trace what's happening.
1041 :     Trace("Stack trace for event: $message");
1042 : parrello 1.99 # Get the stack trace.
1043 :     my @trace = LongMess();
1044 :     # Convert the trace to a series of messages.
1045 :     for my $line (@trace) {
1046 :     # Replace the tab at the beginning with spaces.
1047 :     $line =~ s/^\t/ /;
1048 :     # Trace the line.
1049 :     Trace($line);
1050 :     }
1051 :     # Issue a warning. This displays the event message and inserts it into the RSS error feed.
1052 :     Warn($message);
1053 :     }
1054 :    
1055 :     =head3 LongMess
1056 :    
1057 :     my @lines = Tracer::LongMess();
1058 :    
1059 :     Return a stack trace with all tracing methods removed. The return will be in the form of a list
1060 :     of message strings.
1061 :    
1062 :     =cut
1063 :    
1064 :     sub LongMess {
1065 :     # Declare the return variable.
1066 :     my @retVal = ();
1067 :     my $confession = longmess("");
1068 : parrello 1.135 for my $line (split m/\s*\n/, $confession) {
1069 : parrello 1.99 unless ($line =~ /Tracer\.pm/) {
1070 :     # Here we have a line worth keeping. Push it onto the result list.
1071 :     push @retVal, $line;
1072 : parrello 1.97 }
1073 : parrello 1.93 }
1074 : parrello 1.99 # Return the result.
1075 :     return @retVal;
1076 : parrello 1.93 }
1077 :    
1078 :     =head3 ETracing
1079 :    
1080 : parrello 1.125 ETracing($parameter, %options);
1081 : parrello 1.93
1082 :     Set up emergency tracing. Emergency tracing is tracing that is turned
1083 :     on automatically for any program that calls this method. The emergency
1084 :     tracing parameters are stored in a a file identified by a tracing key.
1085 :     If this method is called with a CGI object, then the tracing key is
1086 :     taken from a cookie. If it is called with no parameters, then the tracing
1087 :     key is taken from an environment variable. If it is called with a string,
1088 :     the tracing key is that string.
1089 :    
1090 :     =over 4
1091 :    
1092 :     =item parameter
1093 :    
1094 :     A parameter from which the tracing key is computed. If it is a scalar,
1095 :     that scalar is used as the tracing key. If it is a CGI object, the
1096 :     tracing key is taken from the C<IP> cookie. If it is omitted, the
1097 :     tracing key is taken from the C<TRACING> environment variable. If it
1098 :     is a CGI object and emergency tracing is not on, the C<Trace> and
1099 :     C<TF> parameters will be used to determine the type of tracing.
1100 :    
1101 : parrello 1.125 =item options
1102 :    
1103 :     Hash of options. The permissible options are given below.
1104 :    
1105 :     =over 8
1106 :    
1107 :     =item destType
1108 :    
1109 :     Emergency tracing destination type to use if no tracing file is found. The
1110 :     default is C<WARN>.
1111 :    
1112 : parrello 1.124 =item noParms
1113 :    
1114 : parrello 1.125 If TRUE, then display of the saved CGI parms is suppressed. The default is FALSE.
1115 :    
1116 :     =item level
1117 :    
1118 :     The trace level to use if no tracing file is found. The default is C<0>.
1119 : parrello 1.124
1120 : parrello 1.93 =back
1121 :    
1122 : parrello 1.130 =back
1123 :    
1124 : parrello 1.93 =cut
1125 :    
1126 :     sub ETracing {
1127 :     # Get the parameter.
1128 : parrello 1.125 my ($parameter, %options) = @_;
1129 : parrello 1.93 # Check for CGI mode.
1130 : parrello 1.99 if (defined $parameter && ref $parameter eq 'CGI') {
1131 :     $SavedCGI = $parameter;
1132 :     } else {
1133 :     $SavedCGI = undef;
1134 :     }
1135 : parrello 1.125 # Check for the noParms option.
1136 :     my $noParms = $options{noParms} || 0;
1137 :     # Get the default tracing information.
1138 :     my $tracing = $options{level} || 0;
1139 :     my $dest = $options{destType} || "WARN";
1140 : parrello 1.93 # Check for emergency tracing.
1141 :     my $tkey = EmergencyKey($parameter);
1142 :     my $emergencyFile = EmergencyFileName($tkey);
1143 : parrello 1.129 if (-e $emergencyFile && (my $stat = stat($emergencyFile))) {
1144 : parrello 1.93 # We have the file. Read in the data.
1145 :     my @tracing = GetFile($emergencyFile);
1146 :     # Pull off the time limit.
1147 :     my $expire = shift @tracing;
1148 :     # Convert it to seconds.
1149 :     $expire *= 3600;
1150 :     # Check the file data.
1151 :     my ($now) = gettimeofday;
1152 : parrello 1.129 if ($now - $stat->mtime <= $expire) {
1153 : parrello 1.93 # Emergency tracing is on. Pull off the destination and
1154 :     # the trace level;
1155 :     $dest = shift @tracing;
1156 :     my $level = shift @tracing;
1157 :     # Insure Tracer is specified.
1158 :     my %moduleHash = map { $_ => 1 } @tracing;
1159 :     $moduleHash{Tracer} = 1;
1160 :     # Set the trace parameter.
1161 :     $tracing = join(" ", $level, sort keys %moduleHash);
1162 : parrello 1.44 }
1163 : parrello 1.36 }
1164 : parrello 1.125 # Convert the destination to a real tracing destination.
1165 :     $dest = EmergencyTracingDest($tkey, $dest);
1166 : parrello 1.93 # Setup the tracing we've determined from all the stuff above.
1167 :     TSetup($tracing, $dest);
1168 : parrello 1.94 # Check to see if we're a web script.
1169 : parrello 1.125 if (defined $SavedCGI) {
1170 :     # Yes we are. Trace the form and environment data if it's not suppressed.
1171 :     if (! $noParms) {
1172 :     TraceParms($SavedCGI);
1173 :     }
1174 : parrello 1.94 # Check for RAW mode. In raw mode, we print a fake header so that we see everything
1175 :     # emitted by the script in its raw form.
1176 :     if (T(Raw => 3)) {
1177 :     print CGI::header(-type => 'text/plain', -tracing => 'Raw');
1178 :     }
1179 : parrello 1.83 }
1180 : parrello 1.31 }
1181 :    
1182 : parrello 1.93 =head3 EmergencyFileName
1183 :    
1184 :     my $fileName = Tracer::EmergencyFileName($tkey);
1185 :    
1186 :     Return the emergency tracing file name. This is the file that specifies
1187 :     the tracing information.
1188 :    
1189 :     =over 4
1190 :    
1191 :     =item tkey
1192 :    
1193 :     Tracing key for the current program.
1194 : parrello 1.11
1195 : parrello 1.93 =item RETURN
1196 : parrello 1.11
1197 : parrello 1.93 Returns the name of the file to contain the emergency tracing information.
1198 : parrello 1.11
1199 : parrello 1.93 =back
1200 : parrello 1.11
1201 :     =cut
1202 :    
1203 : parrello 1.93 sub EmergencyFileName {
1204 :     # Get the parameters.
1205 :     my ($tkey) = @_;
1206 :     # Compute the emergency tracing file name.
1207 : olson 1.137 return "$tracer_tmp/Emergency$tkey.txt";
1208 : olson 1.1 }
1209 :    
1210 : parrello 1.93 =head3 EmergencyFileTarget
1211 : parrello 1.10
1212 : parrello 1.93 my $fileName = Tracer::EmergencyFileTarget($tkey);
1213 : parrello 1.10
1214 : parrello 1.93 Return the emergency tracing target file name. This is the file that receives
1215 :     the tracing output for file-based tracing.
1216 : parrello 1.10
1217 : parrello 1.93 =over 4
1218 : parrello 1.10
1219 : parrello 1.93 =item tkey
1220 : parrello 1.10
1221 : parrello 1.93 Tracing key for the current program.
1222 : parrello 1.10
1223 : parrello 1.93 =item RETURN
1224 : parrello 1.10
1225 : parrello 1.93 Returns the name of the file to contain the trace output.
1226 : parrello 1.10
1227 : parrello 1.93 =back
1228 : parrello 1.10
1229 : parrello 1.93 =cut
1230 : parrello 1.10
1231 : parrello 1.93 sub EmergencyFileTarget {
1232 :     # Get the parameters.
1233 :     my ($tkey) = @_;
1234 :     # Compute the emergency tracing file name.
1235 : olson 1.137 return "$tracer_tmp/trace$tkey.log";
1236 : parrello 1.93 }
1237 : parrello 1.10
1238 : parrello 1.93 =head3 EmergencyTracingDest
1239 : parrello 1.10
1240 : parrello 1.93 my $dest = Tracer::EmergencyTracingDest($tkey, $myDest);
1241 : parrello 1.10
1242 : parrello 1.93 This method converts an emergency tracing destination to a real
1243 :     tracing destination. The main difference is that if the
1244 :     destination is C<FILE> or C<APPEND>, we convert it to file
1245 :     output. If the destination is C<DUAL>, we convert it to file
1246 :     and standard output.
1247 : parrello 1.10
1248 :     =over 4
1249 :    
1250 : parrello 1.93 =item tkey
1251 : parrello 1.10
1252 : parrello 1.93 Tracing key for this environment.
1253 : parrello 1.10
1254 : parrello 1.93 =item myDest
1255 : parrello 1.10
1256 : parrello 1.93 Destination from the emergency tracing file.
1257 : parrello 1.10
1258 :     =item RETURN
1259 :    
1260 : parrello 1.93 Returns a destination that can be passed into L</TSetup>.
1261 : parrello 1.10
1262 :     =back
1263 :    
1264 :     =cut
1265 :    
1266 : parrello 1.93 sub EmergencyTracingDest {
1267 : parrello 1.12 # Get the parameters.
1268 : parrello 1.93 my ($tkey, $myDest) = @_;
1269 :     # Declare the return variable.
1270 :     my $retVal = $myDest;
1271 :     # Process according to the destination value.
1272 :     if ($myDest eq 'FILE') {
1273 :     $retVal = ">" . EmergencyFileTarget($tkey);
1274 :     } elsif ($myDest eq 'APPEND') {
1275 :     $retVal = ">>" . EmergencyFileTarget($tkey);
1276 :     } elsif ($myDest eq 'DUAL') {
1277 :     $retVal = "+>" . EmergencyFileTarget($tkey);
1278 : parrello 1.97 } elsif ($myDest eq 'WARN') {
1279 :     $retVal = "WARN";
1280 : parrello 1.12 }
1281 : parrello 1.93 # Return the result.
1282 :     return $retVal;
1283 : parrello 1.10 }
1284 :    
1285 : parrello 1.93 =head3 Emergency
1286 :    
1287 :     Emergency($key, $hours, $dest, $level, @modules);
1288 :    
1289 :     Turn on emergency tracing. This method is normally invoked over the web from
1290 :     a debugging console, but it can also be called by the C<trace.pl> script.
1291 :     The caller specifies the duration of the emergency in hours, the desired tracing
1292 :     destination, the trace level, and a list of the trace modules to activate.
1293 :     For the length of the duration, when a program in an environment with the
1294 :     specified tracing key active invokes a Sprout CGI script, tracing will be
1295 :     turned on automatically. See L</TSetup> for more about tracing setup and
1296 :     L</ETracing> for more about emergency tracing.
1297 :    
1298 :     =over 4
1299 : parrello 1.11
1300 : parrello 1.93 =item tkey
1301 : parrello 1.11
1302 : parrello 1.93 The tracing key. This is used to identify the control file and the trace file.
1303 : parrello 1.11
1304 : parrello 1.93 =item hours
1305 : parrello 1.11
1306 : parrello 1.93 Number of hours to keep emergency tracing alive.
1307 : parrello 1.11
1308 : parrello 1.93 =item dest
1309 : parrello 1.11
1310 : parrello 1.93 Tracing destination. If no path information is specified for a file
1311 :     destination, it is put in the FIG temporary directory.
1312 : parrello 1.11
1313 : parrello 1.93 =item level
1314 : parrello 1.11
1315 : parrello 1.93 Tracing level. A higher level means more trace messages.
1316 : parrello 1.11
1317 : parrello 1.93 =item modules
1318 : parrello 1.11
1319 : parrello 1.93 A list of the tracing modules to activate.
1320 : parrello 1.11
1321 :     =back
1322 :    
1323 :     =cut
1324 : parrello 1.93
1325 :     sub Emergency {
1326 : parrello 1.11 # Get the parameters.
1327 : parrello 1.93 my ($tkey, $hours, $dest, $level, @modules) = @_;
1328 :     # Create the emergency file.
1329 :     my $specFile = EmergencyFileName($tkey);
1330 :     my $outHandle = Open(undef, ">$specFile");
1331 :     print $outHandle join("\n", $hours, $dest, $level, @modules, "");
1332 : parrello 1.11 }
1333 :    
1334 : parrello 1.93 =head3 EmergencyKey
1335 :    
1336 :     my $tkey = EmergencyKey($parameter);
1337 :    
1338 :     Return the Key to be used for emergency tracing. This could be an IP address,
1339 :     a session ID, or a user name, depending on the environment.
1340 : parrello 1.11
1341 : parrello 1.93 =over 4
1342 : parrello 1.11
1343 : parrello 1.93 =item parameter
1344 : parrello 1.11
1345 : parrello 1.93 Parameter defining the method for finding the tracing key. If it is a scalar,
1346 :     then it is presumed to be the tracing key itself. If it is a CGI object, then
1347 :     the tracing key is taken from the C<IP> cookie. Otherwise, the tracing key is
1348 :     taken from the C<TRACING> environment variable.
1349 : parrello 1.29
1350 : parrello 1.93 =item RETURN
1351 : parrello 1.11
1352 : parrello 1.93 Returns the key to be used for labels in emergency tracing.
1353 : parrello 1.11
1354 : parrello 1.93 =back
1355 : parrello 1.11
1356 : parrello 1.93 =cut
1357 : parrello 1.29
1358 : parrello 1.93 sub EmergencyKey {
1359 :     # Get the parameters.
1360 :     my ($parameter) = @_;
1361 :     # Declare the return variable.
1362 :     my $retVal;
1363 :     # Determine the parameter type.
1364 : parrello 1.128 if (! defined $parameter) {
1365 : parrello 1.99 # Here we're supposed to check the environment. If that fails, we
1366 :     # get the effective login ID.
1367 : olson 1.134 $retVal = $ENV{TRACING} || eval { scalar getpwuid($<) } || 100;
1368 : parrello 1.93 } else {
1369 :     my $ptype = ref $parameter;
1370 :     if ($ptype eq 'CGI') {
1371 :     # Here we were invoked from a web page. Look for a cookie.
1372 :     $retVal = $parameter->cookie('IP');
1373 :     } elsif (! $ptype) {
1374 :     # Here the key was passed in.
1375 :     $retVal = $parameter;
1376 :     }
1377 :     }
1378 :     # If no luck finding a key, use the PID.
1379 :     if (! defined $retVal) {
1380 :     $retVal = $$;
1381 :     }
1382 :     # Return the result.
1383 :     return $retVal;
1384 :     }
1385 : parrello 1.11
1386 :    
1387 : parrello 1.93 =head3 TraceParms
1388 : parrello 1.11
1389 : parrello 1.93 Tracer::TraceParms($cgi);
1390 : parrello 1.11
1391 : parrello 1.93 Trace the CGI parameters at trace level CGI => 3 and the environment variables
1392 : parrello 1.94 at level CGI => 4. A self-referencing URL is traced at level CGI => 2.
1393 : parrello 1.11
1394 : parrello 1.93 =over 4
1395 : parrello 1.11
1396 : parrello 1.93 =item cgi
1397 : parrello 1.31
1398 : parrello 1.93 CGI query object containing the parameters to trace.
1399 : parrello 1.31
1400 : parrello 1.11 =back
1401 :    
1402 :     =cut
1403 : parrello 1.93
1404 :     sub TraceParms {
1405 : parrello 1.11 # Get the parameters.
1406 : parrello 1.93 my ($cgi) = @_;
1407 : parrello 1.94 if (T(CGI => 2)) {
1408 : parrello 1.115 # Here we trace the GET-style URL for the script, but only if it's
1409 :     # relatively small.
1410 :     my $url = $cgi->url(-relative => 1, -query => 1);
1411 :     my $len = length($url);
1412 :     if ($len < 500) {
1413 :     Trace("[URL] $url");
1414 :     } elsif ($len > 2048) {
1415 :     Trace("[URL] URL is too long to use with GET ($len characters).");
1416 :     } else {
1417 :     Trace("[URL] URL length is $len characters.");
1418 :     }
1419 : parrello 1.94 }
1420 : parrello 1.93 if (T(CGI => 3)) {
1421 :     # Here we want to trace the parameter data.
1422 :     my @names = $cgi->param;
1423 :     for my $parmName (sort @names) {
1424 :     # Note we skip the Trace parameters, which are for our use only.
1425 :     if ($parmName ne 'Trace' && $parmName ne 'TF') {
1426 :     my @values = $cgi->param($parmName);
1427 : parrello 1.97 Trace("[CGI] $parmName = " . join(", ", @values));
1428 : parrello 1.93 }
1429 :     }
1430 :     # Display the request method.
1431 :     my $method = $cgi->request_method();
1432 :     Trace("Method: $method");
1433 :     }
1434 :     if (T(CGI => 4)) {
1435 :     # Here we want the environment data too.
1436 :     for my $envName (sort keys %ENV) {
1437 : parrello 1.97 Trace("[ENV] $envName = $ENV{$envName}");
1438 : parrello 1.12 }
1439 :     }
1440 : parrello 1.11 }
1441 :    
1442 : parrello 1.94 =head3 TraceImages
1443 :    
1444 :     Tracer::TraceImages($htmlString);
1445 :    
1446 :     Trace information about all of an html document's images. The tracing
1447 :     will be for type "IMG" at level 3. The image's source string
1448 :     will be displayed. This is generally either the URL of the image or
1449 :     raw data for the image itself. If the source is too long, only the first 300
1450 :     characters will be shown at trace level 3. The entire source will be shown,
1451 :     however, at trace level 4. This method is not very smart, and might catch
1452 :     Javascript code, but it is still useful when debugging the arcane
1453 :     behavior of images in multiple browser environments.
1454 :    
1455 :     =over 4
1456 :    
1457 :     =item htmlString
1458 :    
1459 :     HTML text for an outgoing web page.
1460 :    
1461 :     =back
1462 :    
1463 :     =cut
1464 :    
1465 :     sub TraceImages {
1466 :     # Only proceed if we're at the proper trace level.
1467 :     if (T(IMG => 3)) {
1468 :     # For performance reasons we're manipulating $_[0] instead of retrieving the string
1469 :     # into a variable called "$htmlString". This is because we expect html strings to be
1470 :     # long, and don't want to copy them any more than we have to.
1471 :     Trace(length($_[0]) . " characters in web page.");
1472 :     # Loop through the HTML, culling image tags.
1473 :     while ($_[0] =~ /<img\s+[^>]+?src="([^"]+)"/sgi) {
1474 :     # Extract the source string and determine whether or not it's too long.
1475 :     my $srcString = $1;
1476 :     my $pos = pos($_[0]) - length($srcString);
1477 :     my $excess = length($srcString) - 300;
1478 :     # We'll put the display string in here.
1479 :     my $srcDisplay = $srcString;
1480 :     # If it's a data string, split it at the comma.
1481 :     $srcDisplay =~ s/^(data[^,]+,)/$1\n/;
1482 :     # If there's no excess or we're at trace level 4, we're done. At level 3 with
1483 :     # a long string, however, we only show the first 300 characters.
1484 :     if ($excess > 0 && ! T(IMG => 4)) {
1485 :     $srcDisplay = substr($srcDisplay,0,300) . "\nplus $excess characters.";
1486 :     }
1487 :     # Output the trace message.
1488 :     Trace("Image tag at position $pos:\n$srcDisplay");
1489 :     }
1490 :     }
1491 :     }
1492 :    
1493 : parrello 1.93 =head2 Command-Line Utility Methods
1494 : olson 1.1
1495 : parrello 1.93 =head3 SendSMS
1496 : olson 1.1
1497 : parrello 1.93 my $msgID = Tracer::SendSMS($phoneNumber, $msg);
1498 : olson 1.1
1499 : parrello 1.93 Send a text message to a phone number using Clickatell. The FIG_Config file must contain the
1500 :     user name, password, and API ID for the relevant account in the hash reference variable
1501 :     I<$FIG_Config::phone>, using the keys C<user>, C<password>, and C<api_id>. For
1502 :     example, if the user name is C<BruceTheHumanPet>, the password is C<silly>, and the API ID
1503 :     is C<2561022>, then the FIG_Config file must contain
1504 : olson 1.1
1505 : parrello 1.93 $phone = { user => 'BruceTheHumanPet',
1506 :     password => 'silly',
1507 :     api_id => '2561022' };
1508 : olson 1.1
1509 : parrello 1.93 The original purpose of this method was to insure Bruce would be notified immediately when the
1510 :     Sprout Load terminates. Care should be taken if you do not wish Bruce to be notified immediately
1511 :     when you call this method.
1512 : olson 1.1
1513 : parrello 1.93 The message ID will be returned if successful, and C<undef> if an error occurs.
1514 : parrello 1.74
1515 : parrello 1.93 =over 4
1516 : parrello 1.74
1517 : parrello 1.93 =item phoneNumber
1518 : parrello 1.74
1519 : parrello 1.93 Phone number to receive the message, in international format. A United States phone number
1520 :     would be prefixed by "1". A British phone number would be prefixed by "44".
1521 : parrello 1.74
1522 : parrello 1.93 =item msg
1523 : parrello 1.74
1524 : parrello 1.93 Message to send to the specified phone.
1525 : parrello 1.74
1526 :     =item RETURN
1527 :    
1528 : parrello 1.93 Returns the message ID if successful, and C<undef> if the message could not be sent.
1529 : parrello 1.74
1530 : parrello 1.78 =back
1531 :    
1532 : parrello 1.74 =cut
1533 :    
1534 : parrello 1.93 sub SendSMS {
1535 : parrello 1.74 # Get the parameters.
1536 : parrello 1.93 my ($phoneNumber, $msg) = @_;
1537 :     # Declare the return variable. If we do not change it, C<undef> will be returned.
1538 : parrello 1.74 my $retVal;
1539 : parrello 1.93 # Only proceed if we have phone support.
1540 :     if (! defined $FIG_Config::phone) {
1541 :     Trace("Phone support not present in FIG_Config.") if T(1);
1542 :     } else {
1543 :     # Get the phone data.
1544 :     my $parms = $FIG_Config::phone;
1545 :     # Get the Clickatell URL.
1546 :     my $url = "http://api.clickatell.com/http/";
1547 :     # Create the user agent.
1548 :     my $ua = LWP::UserAgent->new;
1549 :     # Request a Clickatell session.
1550 :     my $resp = $ua->post("$url/sendmsg", { user => $parms->{user},
1551 :     password => $parms->{password},
1552 :     api_id => $parms->{api_id},
1553 :     to => $phoneNumber,
1554 :     text => $msg});
1555 :     # Check for an error.
1556 :     if (! $resp->is_success) {
1557 :     Trace("Alert failed.") if T(1);
1558 :     } else {
1559 :     # Get the message ID.
1560 :     my $rstring = $resp->content;
1561 :     if ($rstring =~ /^ID:\s+(.*)$/) {
1562 :     $retVal = $1;
1563 :     } else {
1564 :     Trace("Phone attempt failed with $rstring") if T(1);
1565 :     }
1566 :     }
1567 : parrello 1.74 }
1568 :     # Return the result.
1569 :     return $retVal;
1570 :     }
1571 :    
1572 : parrello 1.93 =head3 StandardSetup
1573 : olson 1.1
1574 : parrello 1.93 my ($options, @parameters) = StandardSetup(\@categories, \%options, $parmHelp, @ARGV);
1575 : olson 1.1
1576 : parrello 1.93 This method performs standard command-line parsing and tracing setup. The return
1577 :     values are a hash of the command-line options and a list of the positional
1578 :     parameters. Tracing is automatically set up and the command-line options are
1579 :     validated.
1580 : olson 1.1
1581 : parrello 1.93 This is a complex method that does a lot of grunt work. The parameters can
1582 :     be more easily understood, however, once they are examined individually.
1583 : olson 1.1
1584 : parrello 1.93 The I<categories> parameter is the most obtuse. It is a reference to a list of
1585 :     special-purpose tracing categories. Most tracing categories are PERL package
1586 :     names. So, for example, if you wanted to turn on tracing inside the B<Sprout>,
1587 :     B<ERDB>, and B<SproutLoad> packages, you would specify the categories
1588 : olson 1.1
1589 : parrello 1.93 ["Sprout", "SproutLoad", "ERDB"]
1590 : olson 1.1
1591 : parrello 1.93 This would cause trace messages in the specified three packages to appear in
1592 :     the output. There are two special tracing categories that are automatically
1593 :     handled by this method. In other words, if you used L</TSetup> you would need
1594 :     to include these categories manually, but if you use this method they are turned
1595 :     on automatically.
1596 : parrello 1.5
1597 :     =over 4
1598 :    
1599 : parrello 1.93 =item SQL
1600 : parrello 1.5
1601 : parrello 1.93 Traces SQL commands and activity.
1602 : parrello 1.5
1603 : parrello 1.93 =item Tracer
1604 : parrello 1.5
1605 : parrello 1.93 Traces error messages and call stacks.
1606 : parrello 1.5
1607 :     =back
1608 :    
1609 : parrello 1.93 C<SQL> is only turned on if the C<-sql> option is specified in the command line.
1610 :     The trace level is specified using the C<-trace> command-line option. For example,
1611 :     the following command line for C<TransactFeatures> turns on SQL tracing and runs
1612 :     all tracing at level 3.
1613 : parrello 1.5
1614 : parrello 1.93 TransactFeatures -trace=3 -sql register ../xacts IDs.tbl
1615 : parrello 1.5
1616 : parrello 1.93 Standard tracing is output to the standard output and echoed to the file
1617 :     C<trace>I<$$>C<.log> in the FIG temporary directory, where I<$$> is the
1618 :     process ID. You can also specify the C<user> parameter to put a user ID
1619 :     instead of a process ID in the trace file name. So, for example
1620 : olson 1.1
1621 : parrello 1.93 The default trace level is 2. To get all messages, specify a trace level of 4.
1622 :     For a genome-by-genome update, use 3.
1623 : olson 1.1
1624 : parrello 1.93 TransactFeatures -trace=3 -sql -user=Bruce register ../xacts IDs.tbl
1625 : olson 1.1
1626 : parrello 1.93 would send the trace output to C<traceBruce.log> in the temporary directory.
1627 : olson 1.1
1628 : parrello 1.93 The I<options> parameter is a reference to a hash containing the command-line
1629 :     options, their default values, and an explanation of what they mean. Command-line
1630 :     options may be in the form of switches or keywords. In the case of a switch, the
1631 :     option value is 1 if it is specified and 0 if it is not specified. In the case
1632 :     of a keyword, the value is separated from the option name by an equal sign. You
1633 :     can see this last in the command-line example above.
1634 : olson 1.1
1635 : parrello 1.93 You can specify a different default trace level by setting C<$options->{trace}>
1636 :     prior to calling this method.
1637 : olson 1.1
1638 : parrello 1.93 An example at this point would help. Consider, for example, the command-line utility
1639 :     C<TransactFeatures>. It accepts a list of positional parameters plus the options
1640 :     C<safe>, C<noAlias>, C<start>, and C<tblFiles>. To start up this command, we execute
1641 :     the following code.
1642 : olson 1.1
1643 : parrello 1.93 my ($options, @parameters) = Tracer::StandardSetup(["DocUtils"],
1644 :     { safe => [0, "use database transactions"],
1645 :     noAlias => [0, "do not expect aliases in CHANGE transactions"],
1646 :     start => [' ', "start with this genome"],
1647 :     tblFiles => [0, "output TBL files containing the corrected IDs"] },
1648 :     "<command> <transactionDirectory> <IDfile>",
1649 :     @ARGV);
1650 : olson 1.1
1651 :    
1652 : parrello 1.93 The call to C<ParseCommand> specifies the default values for the options and
1653 :     stores the actual options in a hash that is returned as C<$options>. The
1654 :     positional parameters are returned in C<@parameters>.
1655 : olson 1.1
1656 : parrello 1.93 The following is a sample command line for C<TransactFeatures>.
1657 : olson 1.1
1658 : parrello 1.93 TransactFeatures -trace=2 -noAlias register ../xacts IDs.tbl
1659 : olson 1.1
1660 : parrello 1.93 Single and double hyphens are equivalent. So, you could also code the
1661 :     above command as
1662 : olson 1.1
1663 : parrello 1.93 TransactFeatures --trace=2 --noAlias register ../xacts IDs.tbl
1664 : olson 1.1
1665 : parrello 1.93 In this case, C<register>, C<../xacts>, and C<IDs.tbl> are the positional
1666 :     parameters, and would find themselves in I<@parameters> after executing the
1667 :     above code fragment. The tracing would be set to level 2, and the categories
1668 :     would be C<Tracer>, and <DocUtils>. C<Tracer> is standard,
1669 :     and C<DocUtils> was included because it came in within the first parameter
1670 :     to this method. The I<$options> hash would be
1671 : olson 1.1
1672 : parrello 1.93 { trace => 2, sql => 0, safe => 0,
1673 :     noAlias => 1, start => ' ', tblFiles => 0 }
1674 : olson 1.1
1675 : parrello 1.93 Use of C<StandardSetup> in this way provides a simple way of performing
1676 :     standard tracing setup and command-line parsing. Note that the caller is
1677 :     not even aware of the command-line switches C<-trace> and C<-sql>, which
1678 :     are used by this method to control the tracing. If additional tracing features
1679 :     need to be added in the future, they can be processed by this method without
1680 :     upsetting the command-line utilities.
1681 : olson 1.1
1682 : parrello 1.93 If the C<background> option is specified on the command line, then the
1683 :     standard and error outputs will be directed to files in the temporary
1684 :     directory, using the same suffix as the trace file. So, if the command
1685 :     line specified
1686 : olson 1.1
1687 : parrello 1.93 -user=Bruce -background
1688 : olson 1.1
1689 : parrello 1.93 then the trace output would go to C<traceBruce.log>, the standard output to
1690 :     C<outBruce.log>, and the error output to C<errBruce.log>. This is designed to
1691 :     simplify starting a command in the background.
1692 : olson 1.1
1693 : parrello 1.93 The user name is also used as the tracing key for L</Emergency Tracing>.
1694 :     Specifying a value of C<E> for the trace level causes emergency tracing to
1695 :     be used instead of custom tracing. If the user name is not specified,
1696 :     the tracing key is taken from the C<Tracing> environment variable. If there
1697 : parrello 1.103 is no value for that variable, the tracing key will be computed from the active
1698 :     login ID.
1699 :    
1700 :     Since the default situation in StandardSetup is to trace to the standard
1701 :     output, errors that occur in command-line scripts will not generate
1702 :     RSS events. To force the events, use the C<warn> option.
1703 :    
1704 :     TransactFeatures -background -warn register ../xacts IDs.tbl
1705 : olson 1.1
1706 : parrello 1.93 Finally, if the special option C<-help> is specified, the option
1707 :     names will be traced at level 0 and the program will exit without processing.
1708 :     This provides a limited help capability. For example, if the user enters
1709 : olson 1.1
1710 : parrello 1.93 TransactFeatures -help
1711 : olson 1.1
1712 : parrello 1.93 he would see the following output.
1713 : olson 1.1
1714 : parrello 1.93 TransactFeatures [options] <command> <transactionDirectory> <IDfile>
1715 :     -trace tracing level (default E)
1716 :     -sql trace SQL commands
1717 :     -safe use database transactions
1718 :     -noAlias do not expect aliases in CHANGE transactions
1719 :     -start start with this genome
1720 :     -tblFiles output TBL files containing the corrected IDs
1721 : parrello 1.111 -forked do not erase the trace file before tracing
1722 : olson 1.1
1723 : parrello 1.93 The caller has the option of modifying the tracing scheme by placing a value
1724 :     for C<trace> in the incoming options hash. The default value can be overridden,
1725 :     or the tracing to the standard output can be turned off by suffixing a minus
1726 :     sign to the trace level. So, for example,
1727 : olson 1.1
1728 : parrello 1.93 { trace => [0, "tracing level (default 0)"],
1729 :     ...
1730 : olson 1.1
1731 : parrello 1.93 would set the default trace level to 0 instead of E, while
1732 : olson 1.1
1733 : parrello 1.93 { trace => ["2-", "tracing level (default 2)"],
1734 :     ...
1735 : olson 1.1
1736 : parrello 1.93 would set the default to 2, but trace only to the log file, not to the
1737 :     standard output.
1738 : olson 1.1
1739 : parrello 1.93 The parameters to this method are as follows.
1740 : olson 1.1
1741 : parrello 1.93 =over 4
1742 : olson 1.1
1743 : parrello 1.93 =item categories
1744 : parrello 1.2
1745 : parrello 1.93 Reference to a list of tracing category names. These should be names of
1746 :     packages whose internal workings will need to be debugged to get the
1747 :     command working.
1748 : olson 1.1
1749 : parrello 1.93 =item options
1750 : olson 1.1
1751 : parrello 1.93 Reference to a hash containing the legal options for the current command mapped
1752 :     to their default values and descriptions. The user can override the defaults
1753 :     by specifying the options as command-line switches prefixed by a hyphen.
1754 :     Tracing-related options may be added to this hash. If the C<-h> option is
1755 :     specified on the command line, the option descriptions will be used to
1756 :     explain the options. To turn off tracing to the standard output, add a
1757 :     minus sign to the value for C<trace> (see above).
1758 : olson 1.1
1759 : parrello 1.93 =item parmHelp
1760 : olson 1.1
1761 : parrello 1.93 A string that vaguely describes the positional parameters. This is used
1762 :     if the user specifies the C<-h> option.
1763 : olson 1.1
1764 : parrello 1.93 =item argv
1765 : olson 1.1
1766 : parrello 1.93 List of command line parameters, including the option switches, which must
1767 :     precede the positional parameters and be prefixed by a hyphen.
1768 : olson 1.1
1769 :     =item RETURN
1770 :    
1771 : parrello 1.93 Returns a list. The first element of the list is the reference to a hash that
1772 :     maps the command-line option switches to their values. These will either be the
1773 :     default values or overrides specified on the command line. The remaining
1774 :     elements of the list are the position parameters, in order.
1775 : olson 1.1
1776 :     =back
1777 :    
1778 :     =cut
1779 :    
1780 : parrello 1.93 sub StandardSetup {
1781 :     # Get the parameters.
1782 :     my ($categories, $options, $parmHelp, @argv) = @_;
1783 :     # Get the default tracing key.
1784 :     my $tkey = EmergencyKey();
1785 : parrello 1.104 # Save the command line.
1786 :     $CommandLine = join(" ", $0, map { $_ =~ /\s/ ? "\"$_\"" : $_ } @argv);
1787 : parrello 1.93 # Add the tracing options.
1788 :     if (! exists $options->{trace}) {
1789 :     $options->{trace} = ['2', "tracing level (E for emergency tracing)"];
1790 :     }
1791 : parrello 1.112 if (! exists $options->{forked}) {
1792 :     $options->{forked} = [0, "keep old trace file"];
1793 :     }
1794 : parrello 1.93 $options->{sql} = [0, "turn on SQL tracing"];
1795 :     $options->{help} = [0, "display command-line options"];
1796 :     $options->{user} = [$tkey, "tracing key"];
1797 :     $options->{background} = [0, "spool standard and error output"];
1798 : parrello 1.103 $options->{warn} = [0, "send errors to RSS feed"];
1799 : parrello 1.113 $options->{moreTracing} = ["", "comma-delimited list of additional trace modules for debugging"];
1800 : parrello 1.132 $options->{config} = ["", "display configuration data"];
1801 : parrello 1.93 # Create a parsing hash from the options hash. The parsing hash
1802 :     # contains the default values rather than the default value
1803 :     # and the description. While we're at it, we'll memorize the
1804 :     # length of the longest option name.
1805 :     my $longestName = 0;
1806 :     my %parseOptions = ();
1807 :     for my $key (keys %{$options}) {
1808 :     if (length $key > $longestName) {
1809 :     $longestName = length $key;
1810 :     }
1811 :     $parseOptions{$key} = $options->{$key}->[0];
1812 :     }
1813 :     # Parse the command line.
1814 :     my ($retOptions, @retParameters) = ParseCommand(\%parseOptions, @argv);
1815 :     # Get the logfile suffix.
1816 :     my $suffix = $retOptions->{user};
1817 : parrello 1.113 # We'll put the trace file name in here. We need it later if background
1818 :     # mode is on.
1819 :     my $traceFileName;
1820 : parrello 1.93 # Now we want to set up tracing. First, we need to know if the user
1821 :     # wants emergency tracing.
1822 :     if ($retOptions->{trace} eq 'E') {
1823 :     ETracing($retOptions->{user});
1824 :     } else {
1825 :     # Here the tracing is controlled from the command line.
1826 :     my @cats = @{$categories};
1827 :     if ($retOptions->{sql}) {
1828 :     push @cats, "SQL";
1829 :     }
1830 : parrello 1.103 if ($retOptions->{warn}) {
1831 :     push @cats, "Feed";
1832 :     }
1833 : parrello 1.93 # Add the default categories.
1834 :     push @cats, "Tracer";
1835 : parrello 1.113 # Check for more tracing groups.
1836 :     if ($retOptions->{moreTracing}) {
1837 : parrello 1.136 push @cats, split m/,/, $retOptions->{moreTracing};
1838 : parrello 1.113 }
1839 : parrello 1.93 # Next, we create the category string by joining the categories.
1840 :     my $cats = join(" ", @cats);
1841 :     # Check to determine whether or not the caller wants to turn off tracing
1842 :     # to the standard output.
1843 :     my $traceLevel = $retOptions->{trace};
1844 :     my $textOKFlag = 1;
1845 :     if ($traceLevel =~ /^(.)-/) {
1846 :     $traceLevel = $1;
1847 :     $textOKFlag = 0;
1848 :     }
1849 :     # Now we set up the trace mode.
1850 :     my $traceMode;
1851 :     # Verify that we can open a file in the FIG temporary directory.
1852 : olson 1.137 my $traceFileName = "$tracer_tmp/trace$suffix.log";
1853 : parrello 1.111 my $traceFileSpec = ($retOptions->{forked} ? ">>$traceFileName" : ">$traceFileName");
1854 :     if (open TESTTRACE, "$traceFileSpec") {
1855 : parrello 1.93 # Here we can trace to a file.
1856 : parrello 1.111 $traceMode = ">>$traceFileName";
1857 : parrello 1.93 if ($textOKFlag) {
1858 :     # Echo to standard output if the text-OK flag is set.
1859 :     $traceMode = "+$traceMode";
1860 :     }
1861 :     # Close the test file.
1862 :     close TESTTRACE;
1863 :     } else {
1864 : parrello 1.98 # Here we can't trace to a file. Complain about this.
1865 :     warn "Could not open trace file $traceFileName: $!\n";
1866 :     # We trace to the standard output if it's
1867 :     # okay, and the error log otherwise.
1868 : parrello 1.93 if ($textOKFlag) {
1869 :     $traceMode = "TEXT";
1870 : parrello 1.12 } else {
1871 : parrello 1.93 $traceMode = "WARN";
1872 : parrello 1.12 }
1873 :     }
1874 : parrello 1.93 # Now set up the tracing.
1875 :     TSetup("$traceLevel $cats", $traceMode);
1876 :     }
1877 : parrello 1.113 # Check for background mode.
1878 :     if ($retOptions->{background}) {
1879 : olson 1.137 my $outFileName = "$tracer_tmp/out$suffix$$.log";
1880 :     my $errFileName = "$tracer_tmp/err$suffix$$.log";
1881 : parrello 1.113 # Spool the output.
1882 :     open STDOUT, ">$outFileName";
1883 :     # If we have a trace file, trace the errors to the log. Otherwise,
1884 :     # spool the errors.
1885 :     if (defined $traceFileName) {
1886 :     open STDERR, "| Tracer $traceFileName";
1887 :     } else {
1888 :     open STDERR, ">$errFileName";
1889 :     }
1890 :     # Check for phone support. If we have phone support and a phone number,
1891 :     # we want to turn it on.
1892 :     if ($ENV{PHONE} && defined($FIG_Config::phone)) {
1893 :     $retOptions->{phone} = $ENV{PHONE};
1894 :     }
1895 :     }
1896 : parrello 1.93 # Check for the "help" option. If it is specified, dump the command-line
1897 :     # options and exit the program.
1898 :     if ($retOptions->{help}) {
1899 :     $0 =~ m#[/\\](\w+)(\.pl)?$#i;
1900 :     print "$1 [options] $parmHelp\n";
1901 :     for my $key (sort keys %{$options}) {
1902 :     my $name = Pad($key, $longestName, 0, ' ');
1903 :     my $desc = $options->{$key}->[1];
1904 :     if ($options->{$key}->[0]) {
1905 :     $desc .= " (default " . $options->{$key}->[0] . ")";
1906 :     }
1907 :     print " $name $desc\n";
1908 : parrello 1.36 }
1909 : parrello 1.93 exit(0);
1910 : parrello 1.132 } elsif ($retOptions->{config}) {
1911 :     # Here we want to dump some useful config information and exit.
1912 :     print "Command is $0.\n";
1913 : olson 1.137 print "Temp directory is $tracer_tmp.\n";
1914 : parrello 1.132 exit(0);
1915 : parrello 1.93 }
1916 :     # Trace the options, if applicable.
1917 :     if (T(3)) {
1918 :     my @parms = grep { $retOptions->{$_} } keys %{$retOptions};
1919 :     Trace("Selected options: " . join(", ", sort @parms) . ".");
1920 : parrello 1.3 }
1921 : parrello 1.93 # Return the parsed parameters.
1922 :     return ($retOptions, @retParameters);
1923 : olson 1.1 }
1924 :    
1925 : parrello 1.93 =head3 ReadOptions
1926 : olson 1.1
1927 : parrello 1.93 my %options = Tracer::ReadOptions($fileName);
1928 : olson 1.1
1929 : parrello 1.93 Read a set of options from a file. Each option is encoded in a line of text that has the
1930 :     format
1931 : olson 1.1
1932 : parrello 1.93 I<optionName>C<=>I<optionValue>C<; >I<comment>
1933 : olson 1.1
1934 : parrello 1.93 The option name must consist entirely of letters, digits, and the punctuation characters
1935 :     C<.> and C<_>, and is case sensitive. Blank lines and lines in which the first nonblank
1936 :     character is a semi-colon will be ignored. The return hash will map each option name to
1937 :     the corresponding option value.
1938 : olson 1.1
1939 :     =over 4
1940 :    
1941 : parrello 1.93 =item fileName
1942 : olson 1.1
1943 : parrello 1.93 Name of the file containing the option data.
1944 : olson 1.1
1945 :     =item RETURN
1946 :    
1947 : parrello 1.93 Returns a hash mapping the option names specified in the file to their corresponding option
1948 :     value.
1949 : olson 1.1
1950 :     =back
1951 :    
1952 :     =cut
1953 :    
1954 : parrello 1.93 sub ReadOptions {
1955 : parrello 1.12 # Get the parameters.
1956 : parrello 1.93 my ($fileName) = @_;
1957 :     # Open the file.
1958 :     (open CONFIGFILE, "<$fileName") || Confess("Could not open option file $fileName.");
1959 :     # Count the number of records read.
1960 :     my ($records, $comments) = 0;
1961 :     # Create the return hash.
1962 :     my %retVal = ();
1963 :     # Loop through the file, accumulating key-value pairs.
1964 :     while (my $line = <CONFIGFILE>) {
1965 :     # Denote we've read a line.
1966 :     $records++;
1967 :     # Determine the line type.
1968 :     if ($line =~ /^\s*[\n\r]/) {
1969 :     # A blank line is a comment.
1970 :     $comments++;
1971 :     } elsif ($line =~ /^\s*([A-Za-z0-9_\.]+)=([^;]*);/) {
1972 :     # Here we have an option assignment.
1973 :     retVal{$1} = $2;
1974 :     } elsif ($line =~ /^\s*;/) {
1975 :     # Here we have a text comment.
1976 :     $comments++;
1977 : parrello 1.12 } else {
1978 : parrello 1.93 # Here we have an invalid line.
1979 :     Trace("Invalid option statement in record $records.") if T(0);
1980 : parrello 1.12 }
1981 :     }
1982 : parrello 1.93 # Return the hash created.
1983 :     return %retVal;
1984 : olson 1.1 }
1985 :    
1986 : parrello 1.93 =head3 GetOptions
1987 : parrello 1.9
1988 : parrello 1.93 Tracer::GetOptions(\%defaults, \%options);
1989 : parrello 1.9
1990 : parrello 1.93 Merge a specified set of options into a table of defaults. This method takes two hash references
1991 :     as input and uses the data from the second to update the first. If the second does not exist,
1992 :     there will be no effect. An error will be thrown if one of the entries in the second hash does not
1993 :     exist in the first.
1994 : parrello 1.9
1995 : parrello 1.93 Consider the following example.
1996 : parrello 1.9
1997 : parrello 1.93 my $optionTable = GetOptions({ dbType => 'mySQL', trace => 0 }, $options);
1998 : parrello 1.9
1999 : parrello 1.93 In this example, the variable B<$options> is expected to contain at most two options-- B<dbType> and
2000 :     B<trace>. The default database type is C<mySQL> and the default trace level is C<0>. If the value of
2001 :     B<$options> is C<< {dbType => 'Oracle'} >>, then the database type will be changed to C<Oracle> and
2002 :     the trace level will remain at 0. If B<$options> is undefined, then the database type and trace level
2003 :     will remain C<mySQL> and C<0>. If, on the other hand, B<$options> is defined as
2004 : parrello 1.9
2005 : parrello 1.93 {databaseType => 'Oracle'}
2006 : parrello 1.9
2007 : parrello 1.93 an error will occur because the B<databaseType> option does not exist.
2008 : parrello 1.9
2009 : parrello 1.93 =over 4
2010 : parrello 1.9
2011 : parrello 1.93 =item defaults
2012 : parrello 1.9
2013 : parrello 1.93 Table of default option values.
2014 : parrello 1.9
2015 : parrello 1.93 =item options
2016 : olson 1.1
2017 : parrello 1.93 Table of overrides, if any.
2018 : olson 1.1
2019 :     =item RETURN
2020 :    
2021 : parrello 1.93 Returns a reference to the default table passed in as the first parameter.
2022 : olson 1.1
2023 :     =back
2024 :    
2025 :     =cut
2026 :    
2027 : parrello 1.93 sub GetOptions {
2028 :     # Get the parameters.
2029 :     my ($defaults, $options) = @_;
2030 :     # Check for overrides.
2031 :     if ($options) {
2032 :     # Loop through the overrides.
2033 :     while (my ($option, $setting) = each %{$options}) {
2034 :     # Insure this override exists.
2035 :     if (!exists $defaults->{$option}) {
2036 :     croak "Unrecognized option $option encountered.";
2037 : parrello 1.12 } else {
2038 : parrello 1.93 # Apply the override.
2039 :     $defaults->{$option} = $setting;
2040 : parrello 1.12 }
2041 :     }
2042 :     }
2043 : parrello 1.93 # Return the merged table.
2044 :     return $defaults;
2045 : olson 1.1 }
2046 :    
2047 : parrello 1.93 =head3 MergeOptions
2048 : olson 1.1
2049 : parrello 1.93 Tracer::MergeOptions(\%table, \%defaults);
2050 : olson 1.1
2051 : parrello 1.93 Merge default values into a hash table. This method looks at the key-value pairs in the
2052 :     second (default) hash, and if a matching key is not found in the first hash, the default
2053 :     pair is copied in. The process is similar to L</GetOptions>, but there is no error-
2054 :     checking and no return value.
2055 : olson 1.1
2056 :     =over 4
2057 :    
2058 : parrello 1.93 =item table
2059 : olson 1.1
2060 : parrello 1.93 Hash table to be updated with the default values.
2061 : olson 1.1
2062 : parrello 1.93 =item defaults
2063 : olson 1.1
2064 : parrello 1.93 Default values to be merged into the first hash table if they are not already present.
2065 : olson 1.1
2066 :     =back
2067 :    
2068 :     =cut
2069 :    
2070 : parrello 1.93 sub MergeOptions {
2071 :     # Get the parameters.
2072 :     my ($table, $defaults) = @_;
2073 :     # Loop through the defaults.
2074 :     while (my ($key, $value) = each %{$defaults}) {
2075 :     if (!exists $table->{$key}) {
2076 :     $table->{$key} = $value;
2077 :     }
2078 : parrello 1.12 }
2079 : olson 1.1 }
2080 :    
2081 : parrello 1.111 =head3 UnparseOptions
2082 :    
2083 :     my $optionString = Tracer::UnparseOptions(\%options);
2084 :    
2085 :     Convert an option hash into a command-line string. This will not
2086 :     necessarily be the same text that came in, but it will nonetheless
2087 :     produce the same ultimate result when parsed by L</StandardSetup>.
2088 :    
2089 :     =over 4
2090 :    
2091 :     =item options
2092 :    
2093 :     Reference to a hash of options to convert into an option string.
2094 :    
2095 :     =item RETURN
2096 :    
2097 :     Returns a string that will parse to the same set of options when
2098 :     parsed by L</StandardSetup>.
2099 :    
2100 :     =back
2101 :    
2102 :     =cut
2103 :    
2104 :     sub UnparseOptions {
2105 :     # Get the parameters.
2106 :     my ($options) = @_;
2107 :     # The option segments will be put in here.
2108 :     my @retVal = ();
2109 :     # Loop through the options.
2110 :     for my $key (keys %$options) {
2111 :     # Get the option value.
2112 :     my $value = $options->{$key};
2113 :     # Only use it if it's nonempty.
2114 :     if (defined $value && $value ne "") {
2115 :     my $segment = "--$key=$value";
2116 :     # Quote it if necessary.
2117 :     if ($segment =~ /[ |<>*]/) {
2118 :     $segment = '"' . $segment . '"';
2119 :     }
2120 :     # Add it to the return list.
2121 :     push @retVal, $segment;
2122 :     }
2123 :     }
2124 :     # Return the result.
2125 :     return join(" ", @retVal);
2126 :     }
2127 :    
2128 : parrello 1.93 =head3 ParseCommand
2129 : olson 1.1
2130 : parrello 1.93 my ($options, @arguments) = Tracer::ParseCommand(\%optionTable, @inputList);
2131 : olson 1.1
2132 : parrello 1.93 Parse a command line consisting of a list of parameters. The initial parameters may be option
2133 :     specifiers of the form C<->I<option> or C<->I<option>C<=>I<value>. The options are stripped
2134 :     off and merged into a table of default options. The remainder of the command line is
2135 :     returned as a list of positional arguments. For example, consider the following invocation.
2136 : olson 1.1
2137 : parrello 1.93 my ($options, @arguments) = ParseCommand({ errors => 0, logFile => 'trace.log'}, @words);
2138 : olson 1.1
2139 : parrello 1.93 In this case, the list @words will be treated as a command line and there are two options available,
2140 :     B<errors> and B<logFile>. If @words has the following format
2141 : olson 1.1
2142 : parrello 1.93 -logFile=error.log apple orange rutabaga
2143 : olson 1.1
2144 : parrello 1.93 then at the end of the invocation, C<$options> will be
2145 : olson 1.1
2146 : parrello 1.93 { errors => 0, logFile => 'error.log' }
2147 : olson 1.1
2148 : parrello 1.93 and C<@arguments> will contain
2149 : olson 1.1
2150 : parrello 1.93 apple orange rutabaga
2151 : olson 1.1
2152 : parrello 1.93 The parser allows for some escape sequences. See L</UnEscape> for a description. There is no
2153 :     support for quote characters. Options can be specified with single or double hyphens.
2154 : parrello 1.54
2155 :     =over 4
2156 :    
2157 : parrello 1.93 =item optionTable
2158 : parrello 1.54
2159 : parrello 1.93 Table of default options.
2160 : parrello 1.54
2161 : parrello 1.93 =item inputList
2162 : parrello 1.54
2163 : parrello 1.93 List of words on the command line.
2164 : parrello 1.54
2165 :     =item RETURN
2166 :    
2167 : parrello 1.93 Returns a reference to the option table and a list of the positional arguments.
2168 : parrello 1.54
2169 :     =back
2170 :    
2171 :     =cut
2172 :    
2173 : parrello 1.93 sub ParseCommand {
2174 : parrello 1.54 # Get the parameters.
2175 : parrello 1.93 my ($optionTable, @inputList) = @_;
2176 :     # Process any options in the input list.
2177 :     my %overrides = ();
2178 :     while ((@inputList > 0) && ($inputList[0] =~ /^--?/)) {
2179 :     # Get the current option.
2180 :     my $arg = shift @inputList;
2181 :     # Pull out the option name.
2182 :     $arg =~ /^--?([^=]*)/g;
2183 :     my $name = $1;
2184 :     # Check for an option value.
2185 :     if ($arg =~ /\G=(.*)$/g) {
2186 :     # Here we have a value for the option.
2187 :     $overrides{$name} = UnEscape($1);
2188 :     } else {
2189 :     # Here there is no value, so we use 1.
2190 :     $overrides{$name} = 1;
2191 :     }
2192 :     }
2193 :     # Merge the options into the defaults.
2194 :     GetOptions($optionTable, \%overrides);
2195 :     # Translate the remaining parameters.
2196 :     my @retVal = ();
2197 :     for my $inputParm (@inputList) {
2198 :     push @retVal, UnEscape($inputParm);
2199 : parrello 1.54 }
2200 : parrello 1.93 # Return the results.
2201 :     return ($optionTable, @retVal);
2202 : parrello 1.54 }
2203 :    
2204 : parrello 1.93
2205 :     =head2 File Utility Methods
2206 :    
2207 : olson 1.1 =head3 GetFile
2208 :    
2209 : parrello 1.92 my @fileContents = Tracer::GetFile($fileName);
2210 : olson 1.1
2211 : parrello 1.35 or
2212 :    
2213 : parrello 1.92 my $fileContents = Tracer::GetFile($fileName);
2214 : parrello 1.35
2215 :     Return the entire contents of a file. In list context, line-ends are removed and
2216 :     each line is a list element. In scalar context, line-ends are replaced by C<\n>.
2217 : olson 1.1
2218 :     =over 4
2219 :    
2220 :     =item fileName
2221 :    
2222 :     Name of the file to read.
2223 :    
2224 :     =item RETURN
2225 :    
2226 : parrello 1.6 In a list context, returns the entire file as a list with the line terminators removed.
2227 : parrello 1.39 In a scalar context, returns the entire file as a string. If an error occurs opening
2228 :     the file, an empty list will be returned.
2229 : olson 1.1
2230 :     =back
2231 :    
2232 :     =cut
2233 :    
2234 :     sub GetFile {
2235 : parrello 1.12 # Get the parameters.
2236 :     my ($fileName) = @_;
2237 :     # Declare the return variable.
2238 :     my @retVal = ();
2239 :     # Open the file for input.
2240 : parrello 1.60 my $handle = Open(undef, "<$fileName");
2241 :     # Read the whole file into the return variable, stripping off any terminator
2242 :     # characters.
2243 :     my $lineCount = 0;
2244 :     while (my $line = <$handle>) {
2245 :     $lineCount++;
2246 :     $line = Strip($line);
2247 :     push @retVal, $line;
2248 :     }
2249 :     # Close it.
2250 :     close $handle;
2251 :     my $actualLines = @retVal;
2252 : parrello 1.77 Trace("$actualLines lines read from file $fileName.") if T(File => 2);
2253 : parrello 1.12 # Return the file's contents in the desired format.
2254 : parrello 1.9 if (wantarray) {
2255 : parrello 1.12 return @retVal;
2256 : parrello 1.6 } else {
2257 :     return join "\n", @retVal;
2258 :     }
2259 : olson 1.1 }
2260 :    
2261 : parrello 1.60 =head3 PutFile
2262 :    
2263 : parrello 1.92 Tracer::PutFile($fileName, \@lines);
2264 : parrello 1.60
2265 :     Write out a file from a list of lines of text.
2266 :    
2267 :     =over 4
2268 :    
2269 :     =item fileName
2270 :    
2271 :     Name of the output file.
2272 :    
2273 :     =item lines
2274 :    
2275 :     Reference to a list of text lines. The lines will be written to the file in order, with trailing
2276 : parrello 1.66 new-line characters. Alternatively, may be a string, in which case the string will be written without
2277 :     modification.
2278 : parrello 1.60
2279 :     =back
2280 :    
2281 :     =cut
2282 :    
2283 :     sub PutFile {
2284 :     # Get the parameters.
2285 :     my ($fileName, $lines) = @_;
2286 :     # Open the output file.
2287 :     my $handle = Open(undef, ">$fileName");
2288 : parrello 1.77 # Count the lines written.
2289 : parrello 1.66 if (ref $lines ne 'ARRAY') {
2290 :     # Here we have a scalar, so we write it raw.
2291 :     print $handle $lines;
2292 : parrello 1.77 Trace("Scalar put to file $fileName.") if T(File => 3);
2293 : parrello 1.66 } else {
2294 :     # Write the lines one at a time.
2295 : parrello 1.77 my $count = 0;
2296 : parrello 1.66 for my $line (@{$lines}) {
2297 :     print $handle "$line\n";
2298 : parrello 1.77 $count++;
2299 : parrello 1.66 }
2300 : parrello 1.77 Trace("$count lines put to file $fileName.") if T(File => 3);
2301 : parrello 1.60 }
2302 :     # Close the output file.
2303 :     close $handle;
2304 :     }
2305 :    
2306 : parrello 1.93 =head3 ParseRecord
2307 : olson 1.1
2308 : parrello 1.93 my @fields = Tracer::ParseRecord($line);
2309 : olson 1.1
2310 : parrello 1.93 Parse a tab-delimited data line. The data line is split into field values. Embedded tab
2311 :     and new-line characters in the data line must be represented as C<\t> and C<\n>, respectively.
2312 :     These will automatically be converted.
2313 : olson 1.1
2314 :     =over 4
2315 :    
2316 : parrello 1.93 =item line
2317 :    
2318 :     Line of data containing the tab-delimited fields.
2319 :    
2320 :     =item RETURN
2321 : olson 1.1
2322 : parrello 1.93 Returns a list of the fields found in the data line.
2323 : olson 1.1
2324 :     =back
2325 :    
2326 :     =cut
2327 :    
2328 : parrello 1.93 sub ParseRecord {
2329 : parrello 1.12 # Get the parameter.
2330 : parrello 1.93 my ($line) = @_;
2331 :     # Remove the trailing new-line, if any.
2332 :     chomp $line;
2333 :     # Split the line read into pieces using the tab character.
2334 :     my @retVal = split /\t/, $line;
2335 :     # Trim and fix the escapes in each piece.
2336 :     for my $value (@retVal) {
2337 :     # Trim leading whitespace.
2338 :     $value =~ s/^\s+//;
2339 :     # Trim trailing whitespace.
2340 :     $value =~ s/\s+$//;
2341 :     # Delete the carriage returns.
2342 :     $value =~ s/\r//g;
2343 :     # Convert the escapes into their real values.
2344 :     $value =~ s/\\t/"\t"/ge;
2345 :     $value =~ s/\\n/"\n"/ge;
2346 :     }
2347 :     # Return the result.
2348 :     return @retVal;
2349 :     }
2350 :    
2351 :     =head3 Merge
2352 :    
2353 :     my @mergedList = Tracer::Merge(@inputList);
2354 :    
2355 :     Sort a list of strings and remove duplicates.
2356 :    
2357 :     =over 4
2358 :    
2359 :     =item inputList
2360 :    
2361 :     List of scalars to sort and merge.
2362 :    
2363 :     =item RETURN
2364 :    
2365 :     Returns a list containing the same elements sorted in ascending order with duplicates
2366 :     removed.
2367 :    
2368 :     =back
2369 :    
2370 :     =cut
2371 :    
2372 :     sub Merge {
2373 :     # Get the input list in sort order.
2374 :     my @inputList = sort @_;
2375 :     # Only proceed if the list has at least two elements.
2376 :     if (@inputList > 1) {
2377 :     # Now we want to move through the list splicing out duplicates.
2378 :     my $i = 0;
2379 :     while ($i < @inputList) {
2380 :     # Get the current entry.
2381 :     my $thisEntry = $inputList[$i];
2382 :     # Find out how many elements duplicate the current entry.
2383 :     my $j = $i + 1;
2384 :     my $dup1 = $i + 1;
2385 :     while ($j < @inputList && $inputList[$j] eq $thisEntry) { $j++; };
2386 :     # If the number is nonzero, splice out the duplicates found.
2387 :     if ($j > $dup1) {
2388 :     splice @inputList, $dup1, $j - $dup1;
2389 : parrello 1.14 }
2390 : parrello 1.93 # Now the element at position $dup1 is different from the element before it
2391 :     # at position $i. We push $i forward one position and start again.
2392 :     $i++;
2393 : parrello 1.14 }
2394 : parrello 1.12 }
2395 : parrello 1.93 # Return the merged list.
2396 :     return @inputList;
2397 : olson 1.1 }
2398 :    
2399 : parrello 1.93 =head3 Open
2400 : olson 1.1
2401 : parrello 1.93 my $handle = Open($fileHandle, $fileSpec, $message);
2402 : olson 1.1
2403 : parrello 1.93 Open a file.
2404 : olson 1.1
2405 : parrello 1.93 The I<$fileSpec> is essentially the second argument of the PERL C<open>
2406 :     function. The mode is specified using Unix-like shell information. So, for
2407 :     example,
2408 : olson 1.1
2409 : parrello 1.93 Open(\*LOGFILE, '>>/usr/spool/news/twitlog', "Could not open twit log.");
2410 : olson 1.1
2411 : parrello 1.93 would open for output appended to the specified file, and
2412 : olson 1.1
2413 : parrello 1.93 Open(\*DATASTREAM, "| sort -u >$outputFile", "Could not open $outputFile.");
2414 : olson 1.1
2415 : parrello 1.93 would open a pipe that sorts the records written and removes duplicates. Note
2416 :     the use of file handle syntax in the Open call. To use anonymous file handles,
2417 :     code as follows.
2418 : olson 1.1
2419 : parrello 1.93 my $logFile = Open(undef, '>>/usr/spool/news/twitlog', "Could not open twit log.");
2420 : olson 1.1
2421 : parrello 1.93 The I<$message> parameter is used if the open fails. If it is set to C<0>, then
2422 :     the open returns TRUE if successful and FALSE if an error occurred. Otherwise, a
2423 :     failed open will throw an exception and the third parameter will be used to construct
2424 :     an error message. If the parameter is omitted, a standard message is constructed
2425 :     using the file spec.
2426 : olson 1.1
2427 : parrello 1.93 Could not open "/usr/spool/news/twitlog"
2428 : olson 1.1
2429 : parrello 1.93 Note that the mode characters are automatically cleaned from the file name.
2430 :     The actual error message from the file system will be captured and appended to the
2431 :     message in any case.
2432 : parrello 1.6
2433 : parrello 1.93 Could not open "/usr/spool/news/twitlog": file not found.
2434 : parrello 1.6
2435 : parrello 1.93 In some versions of PERL the only error message we get is a number, which
2436 :     corresponds to the C++ C<errno> value.
2437 : parrello 1.6
2438 : parrello 1.93 Could not open "/usr/spool/news/twitlog": 6.
2439 : parrello 1.6
2440 : parrello 1.93 =over 4
2441 : parrello 1.6
2442 : parrello 1.93 =item fileHandle
2443 : parrello 1.6
2444 : parrello 1.93 File handle. If this parameter is C<undef>, a file handle will be generated
2445 :     and returned as the value of this method.
2446 : olson 1.1
2447 : parrello 1.93 =item fileSpec
2448 : olson 1.1
2449 : parrello 1.93 File name and mode, as per the PERL C<open> function.
2450 : olson 1.1
2451 : parrello 1.93 =item message (optional)
2452 : olson 1.1
2453 : parrello 1.93 Error message to use if the open fails. If omitted, a standard error message
2454 :     will be generated. In either case, the error information from the file system
2455 :     is appended to the message. To specify a conditional open that does not throw
2456 :     an error if it fails, use C<0>.
2457 : olson 1.1
2458 : parrello 1.93 =item RETURN
2459 : olson 1.1
2460 : parrello 1.93 Returns the name of the file handle assigned to the file, or C<undef> if the
2461 :     open failed.
2462 : olson 1.1
2463 :     =back
2464 :    
2465 :     =cut
2466 :    
2467 : parrello 1.93 sub Open {
2468 : parrello 1.12 # Get the parameters.
2469 : parrello 1.93 my ($fileHandle, $fileSpec, $message) = @_;
2470 :     # Attempt to open the file.
2471 :     my $rv = open $fileHandle, $fileSpec;
2472 :     # If the open failed, generate an error message.
2473 :     if (! $rv) {
2474 :     # Save the system error message.
2475 :     my $sysMessage = $!;
2476 :     # See if we need a default message.
2477 :     if (!$message) {
2478 :     # Clean any obvious mode characters and leading spaces from the
2479 :     # filename.
2480 :     my ($fileName) = FindNamePart($fileSpec);
2481 :     $message = "Could not open \"$fileName\"";
2482 :     }
2483 :     # Terminate with an error using the supplied message and the
2484 :     # error message from the file system.
2485 :     Confess("$message: $!");
2486 : parrello 1.12 }
2487 : parrello 1.93 # Return the file handle.
2488 :     return $fileHandle;
2489 : olson 1.1 }
2490 :    
2491 : parrello 1.93 =head3 FindNamePart
2492 :    
2493 :     my ($fileName, $start, $len) = Tracer::FindNamePart($fileSpec);
2494 :    
2495 :     Extract the portion of a file specification that contains the file name.
2496 :    
2497 :     A file specification is the string passed to an C<open> call. It specifies the file
2498 :     mode and name. In a truly complex situation, it can specify a pipe sequence. This
2499 :     method assumes that the file name is whatever follows the first angle bracket
2500 :     sequence. So, for example, in the following strings the file name is
2501 :     C</usr/fig/myfile.txt>.
2502 : parrello 1.5
2503 : parrello 1.93 >>/usr/fig/myfile.txt
2504 :     </usr/fig/myfile.txt
2505 :     | sort -u > /usr/fig/myfile.txt
2506 : parrello 1.5
2507 : parrello 1.93 If the method cannot find a file name using its normal methods, it will return the
2508 :     whole incoming string.
2509 : parrello 1.5
2510 :     =over 4
2511 :    
2512 : parrello 1.93 =item fileSpec
2513 : parrello 1.5
2514 : parrello 1.93 File specification string from which the file name is to be extracted.
2515 : parrello 1.5
2516 :     =item RETURN
2517 :    
2518 : parrello 1.93 Returns a three-element list. The first element contains the file name portion of
2519 :     the specified string, or the whole string if a file name cannot be found via normal
2520 :     methods. The second element contains the start position of the file name portion and
2521 :     the third element contains the length.
2522 : parrello 1.5
2523 :     =back
2524 :    
2525 :     =cut
2526 : parrello 1.93 #: Return Type $;
2527 :     sub FindNamePart {
2528 :     # Get the parameters.
2529 :     my ($fileSpec) = @_;
2530 :     # Default to the whole input string.
2531 :     my ($retVal, $pos, $len) = ($fileSpec, 0, length $fileSpec);
2532 :     # Parse out the file name if we can.
2533 :     if ($fileSpec =~ m/(<|>>?)(.+?)(\s*)$/) {
2534 :     $retVal = $2;
2535 :     $len = length $retVal;
2536 :     $pos = (length $fileSpec) - (length $3) - $len;
2537 : parrello 1.12 }
2538 : parrello 1.93 # Return the result.
2539 :     return ($retVal, $pos, $len);
2540 : parrello 1.5 }
2541 :    
2542 : parrello 1.93 =head3 OpenDir
2543 : parrello 1.5
2544 : parrello 1.93 my @files = OpenDir($dirName, $filtered, $flag);
2545 : parrello 1.5
2546 : parrello 1.93 Open a directory and return all the file names. This function essentially performs
2547 :     the functions of an C<opendir> and C<readdir>. If the I<$filtered> parameter is
2548 :     set to TRUE, all filenames beginning with a period (C<.>), dollar sign (C<$>),
2549 :     or pound sign (C<#>) and all filenames ending with a tilde C<~>) will be
2550 :     filtered out of the return list. If the directory does not open and I<$flag> is not
2551 :     set, an exception is thrown. So, for example,
2552 : parrello 1.5
2553 : parrello 1.93 my @files = OpenDir("/Volumes/fig/contigs", 1);
2554 : parrello 1.5
2555 : parrello 1.93 is effectively the same as
2556 : parrello 1.5
2557 : parrello 1.93 opendir(TMP, "/Volumes/fig/contigs") || Confess("Could not open /Volumes/fig/contigs.");
2558 :     my @files = grep { $_ !~ /^[\.\$\#]/ && $_ !~ /~$/ } readdir(TMP);
2559 : parrello 1.5
2560 : parrello 1.93 Similarly, the following code
2561 : parrello 1.5
2562 : parrello 1.93 my @files = grep { $_ =~ /^\d/ } OpenDir("/Volumes/fig/orgs", 0, 1);
2563 : parrello 1.5
2564 : parrello 1.93 Returns the names of all files in C</Volumes/fig/orgs> that begin with digits and
2565 :     automatically returns an empty list if the directory fails to open.
2566 : parrello 1.5
2567 : parrello 1.93 =over 4
2568 : parrello 1.5
2569 : parrello 1.93 =item dirName
2570 : parrello 1.5
2571 : parrello 1.93 Name of the directory to open.
2572 : parrello 1.5
2573 : parrello 1.93 =item filtered
2574 : parrello 1.5
2575 : parrello 1.93 TRUE if files whose names begin with a period (C<.>) should be automatically removed
2576 :     from the list, else FALSE.
2577 : parrello 1.5
2578 : parrello 1.93 =item flag
2579 : parrello 1.5
2580 : parrello 1.93 TRUE if a failure to open is okay, else FALSE
2581 : parrello 1.5
2582 : parrello 1.93 =back
2583 : parrello 1.5
2584 : parrello 1.93 =cut
2585 :     #: Return Type @;
2586 :     sub OpenDir {
2587 :     # Get the parameters.
2588 :     my ($dirName, $filtered, $flag) = @_;
2589 :     # Declare the return variable.
2590 :     my @retVal = ();
2591 :     # Open the directory.
2592 :     if (opendir(my $dirHandle, $dirName)) {
2593 :     # The directory opened successfully. Get the appropriate list according to the
2594 :     # strictures of the filter parameter.
2595 :     if ($filtered) {
2596 :     @retVal = grep { $_ !~ /^[\.\$\#]/ && $_ !~ /~$/ } readdir $dirHandle;
2597 :     } else {
2598 :     @retVal = readdir $dirHandle;
2599 :     }
2600 : parrello 1.117 closedir $dirHandle;
2601 : parrello 1.93 } elsif (! $flag) {
2602 :     # Here the directory would not open and it's considered an error.
2603 :     Confess("Could not open directory $dirName.");
2604 :     }
2605 :     # Return the result.
2606 :     return @retVal;
2607 :     }
2608 : parrello 1.5
2609 :    
2610 : parrello 1.93 =head3 Insure
2611 : parrello 1.5
2612 : parrello 1.93 Insure($dirName, $chmod);
2613 : parrello 1.5
2614 : parrello 1.93 Insure a directory is present.
2615 : parrello 1.5
2616 : parrello 1.93 =over 4
2617 : parrello 1.5
2618 : parrello 1.93 =item dirName
2619 : olson 1.1
2620 : parrello 1.93 Name of the directory to check. If it does not exist, it will be created.
2621 : parrello 1.7
2622 : parrello 1.93 =item chmod (optional)
2623 : parrello 1.7
2624 : parrello 1.93 Security privileges to be given to the directory if it is created.
2625 : parrello 1.7
2626 : parrello 1.93 =back
2627 : parrello 1.7
2628 :     =cut
2629 :    
2630 : parrello 1.93 sub Insure {
2631 :     my ($dirName, $chmod) = @_;
2632 :     if (! -d $dirName) {
2633 :     Trace("Creating $dirName directory.") if T(2);
2634 :     eval {
2635 :     mkpath $dirName;
2636 :     # If we have permissions specified, set them here.
2637 :     if (defined($chmod)) {
2638 :     chmod $chmod, $dirName;
2639 :     }
2640 :     };
2641 :     if ($@) {
2642 :     Confess("Error creating $dirName: $@");
2643 :     }
2644 : parrello 1.12 }
2645 : parrello 1.9 }
2646 :    
2647 : parrello 1.93 =head3 ChDir
2648 : parrello 1.9
2649 : parrello 1.93 ChDir($dirName);
2650 : parrello 1.9
2651 : parrello 1.93 Change to the specified directory.
2652 : parrello 1.9
2653 :     =over 4
2654 :    
2655 : parrello 1.93 =item dirName
2656 : parrello 1.9
2657 : parrello 1.93 Name of the directory to which we want to change.
2658 : parrello 1.9
2659 :     =back
2660 :    
2661 :     =cut
2662 :    
2663 : parrello 1.93 sub ChDir {
2664 :     my ($dirName) = @_;
2665 :     if (! -d $dirName) {
2666 :     Confess("Cannot change to directory $dirName: no such directory.");
2667 :     } else {
2668 :     Trace("Changing to directory $dirName.") if T(File => 4);
2669 :     my $okFlag = chdir $dirName;
2670 :     if (! $okFlag) {
2671 :     Confess("Error switching to directory $dirName.");
2672 :     }
2673 :     }
2674 : parrello 1.9 }
2675 :    
2676 : parrello 1.93 =head3 SetPermissions
2677 :    
2678 :     Tracer::SetPermissions($dirName, $group, $mask, %otherMasks);
2679 : parrello 1.9
2680 : parrello 1.93 Set the permissions for a directory and all the files and folders inside it.
2681 :     In addition, the group ownership will be changed to the specified value.
2682 : parrello 1.9
2683 : parrello 1.93 This method is more vulnerable than most to permission and compatability
2684 :     problems, so it does internal error recovery.
2685 : parrello 1.9
2686 :     =over 4
2687 :    
2688 : parrello 1.93 =item dirName
2689 :    
2690 :     Name of the directory to process.
2691 :    
2692 :     =item group
2693 : parrello 1.9
2694 : parrello 1.93 Name of the group to be assigned.
2695 : parrello 1.9
2696 : parrello 1.93 =item mask
2697 : parrello 1.9
2698 : parrello 1.93 Permission mask. Bits that are C<1> in this mask will be ORed into the
2699 :     permission bits of any file or directory that does not already have them
2700 :     set to 1.
2701 : parrello 1.9
2702 : parrello 1.93 =item otherMasks
2703 : parrello 1.9
2704 : parrello 1.93 Map of search patterns to permission masks. If a directory name matches
2705 :     one of the patterns, that directory and all its members and subdirectories
2706 :     will be assigned the new pattern. For example, the following would
2707 : parrello 1.110 assign 0664 to most files, but would use 0777 for directories named C<tmp>.
2708 : parrello 1.9
2709 : parrello 1.93 Tracer::SetPermissions($dirName, 'fig', 01664, '^tmp$' => 01777);
2710 : parrello 1.9
2711 : parrello 1.93 The list is ordered, so the following would use 0777 for C<tmp1> and
2712 :     0666 for C<tmp>, C<tmp2>, or C<tmp3>.
2713 : parrello 1.22
2714 : parrello 1.93 Tracer::SetPermissions($dirName, 'fig', 01664, '^tmp1' => 0777,
2715 :     '^tmp' => 0666);
2716 : parrello 1.9
2717 : parrello 1.93 Note that the pattern matches are all case-insensitive, and only directory
2718 :     names are matched, not file names.
2719 : parrello 1.9
2720 :     =back
2721 :    
2722 :     =cut
2723 :    
2724 : parrello 1.93 sub SetPermissions {
2725 : parrello 1.12 # Get the parameters.
2726 : parrello 1.93 my ($dirName, $group, $mask, @otherMasks) = @_;
2727 :     # Set up for error recovery.
2728 :     eval {
2729 :     # Switch to the specified directory.
2730 :     ChDir($dirName);
2731 :     # Get the group ID.
2732 :     my $gid = getgrnam($group);
2733 :     # Get the mask for tracing.
2734 :     my $traceMask = sprintf("%04o", $mask) . "($mask)";
2735 :     Trace("Fixing permissions for directory $dirName using group $group($gid) and mask $traceMask.") if T(File => 2);
2736 :     my $fixCount = 0;
2737 :     my $lookCount = 0;
2738 :     # @dirs will be a stack of directories to be processed.
2739 :     my @dirs = (getcwd());
2740 :     while (scalar(@dirs) > 0) {
2741 :     # Get the current directory.
2742 :     my $dir = pop @dirs;
2743 :     # Check for a match to one of the specified directory names. To do
2744 :     # that, we need to pull the individual part of the name off of the
2745 :     # whole path.
2746 :     my $simpleName = $dir;
2747 :     if ($dir =~ m!/([^/]+)$!) {
2748 :     $simpleName = $1;
2749 :     }
2750 :     Trace("Simple directory name for $dir is $simpleName.") if T(File => 4);
2751 :     # Search for a match.
2752 :     my $match = 0;
2753 :     my $i;
2754 :     for ($i = 0; $i < $#otherMasks && ! $match; $i += 2) {
2755 :     my $pattern = $otherMasks[$i];
2756 :     if ($simpleName =~ /$pattern/i) {
2757 :     $match = 1;
2758 :     }
2759 :     }
2760 : parrello 1.110 # Find out if we have a match. Note we use $i-1 because the loop added 2
2761 : parrello 1.93 # before terminating due to the match.
2762 :     if ($match && $otherMasks[$i-1] != $mask) {
2763 :     # This directory matches one of the incoming patterns, and it's
2764 :     # a different mask, so we process it recursively with that mask.
2765 :     SetPermissions($dir, $group, $otherMasks[$i-1], @otherMasks);
2766 :     } else {
2767 :     # Here we can process normally. Get all of the non-hidden members.
2768 :     my @submems = OpenDir($dir, 1);
2769 :     for my $submem (@submems) {
2770 :     # Get the full name.
2771 :     my $thisMem = "$dir/$submem";
2772 :     Trace("Checking member $thisMem.") if T(4);
2773 :     $lookCount++;
2774 :     if ($lookCount % 1000 == 0) {
2775 :     Trace("$lookCount members examined. Current is $thisMem. Mask is $traceMask") if T(File => 3);
2776 :     }
2777 :     # Fix the group.
2778 :     chown -1, $gid, $thisMem;
2779 :     # Insure this member is not a symlink.
2780 :     if (! -l $thisMem) {
2781 :     # Get its info.
2782 :     my $fileInfo = stat $thisMem;
2783 :     # Only proceed if we got the info. Otherwise, it's a hard link
2784 :     # and we want to skip it anyway.
2785 :     if ($fileInfo) {
2786 :     my $fileMode = $fileInfo->mode;
2787 :     if (($fileMode & $mask) != $mask) {
2788 :     # Fix this member.
2789 :     $fileMode |= $mask;
2790 :     chmod $fileMode, $thisMem;
2791 :     $fixCount++;
2792 :     }
2793 :     # If it's a subdirectory, stack it.
2794 :     if (-d $thisMem) {
2795 :     push @dirs, $thisMem;
2796 :     }
2797 :     }
2798 :     }
2799 :     }
2800 :     }
2801 : parrello 1.12 }
2802 : parrello 1.93 Trace("$lookCount files and directories processed, $fixCount fixed.") if T(File => 2);
2803 :     };
2804 :     # Check for an error.
2805 :     if ($@) {
2806 :     Confess("SetPermissions error: $@");
2807 : parrello 1.12 }
2808 : parrello 1.7 }
2809 :    
2810 : parrello 1.93 =head3 GetLine
2811 : parrello 1.29
2812 : parrello 1.93 my @data = Tracer::GetLine($handle);
2813 : parrello 1.15
2814 : parrello 1.93 Read a line of data from a tab-delimited file.
2815 : parrello 1.15
2816 :     =over 4
2817 :    
2818 : parrello 1.93 =item handle
2819 : parrello 1.15
2820 : parrello 1.93 Open file handle from which to read.
2821 : parrello 1.15
2822 :     =item RETURN
2823 :    
2824 : parrello 1.93 Returns a list of the fields in the record read. The fields are presumed to be
2825 :     tab-delimited. If we are at the end of the file, then an empty list will be
2826 :     returned. If an empty line is read, a single list item consisting of a null
2827 :     string will be returned.
2828 : parrello 1.15
2829 :     =back
2830 :    
2831 :     =cut
2832 : parrello 1.93
2833 :     sub GetLine {
2834 : parrello 1.15 # Get the parameters.
2835 : parrello 1.93 my ($handle) = @_;
2836 :     # Declare the return variable.
2837 :     my @retVal = ();
2838 :     Trace("File position is " . tell($handle) . ". EOF flag is " . eof($handle) . ".") if T(File => 4);
2839 :     # Read from the file.
2840 :     my $line = <$handle>;
2841 :     # Only proceed if we found something.
2842 :     if (defined $line) {
2843 :     # Remove the new-line. We are a bit over-cautious here because the file may be coming in via an
2844 :     # upload control and have a nonstandard EOL combination.
2845 :     $line =~ s/(\r|\n)+$//;
2846 :     # Here we do some fancy tracing to help in debugging complicated EOL marks.
2847 :     if (T(File => 4)) {
2848 :     my $escapedLine = $line;
2849 :     $escapedLine =~ s/\n/\\n/g;
2850 :     $escapedLine =~ s/\r/\\r/g;
2851 :     $escapedLine =~ s/\t/\\t/g;
2852 :     Trace("Line read: -->$escapedLine<--");
2853 :     }
2854 :     # If the line is empty, return a single empty string; otherwise, parse
2855 :     # it into fields.
2856 :     if ($line eq "") {
2857 :     push @retVal, "";
2858 :     } else {
2859 :     push @retVal, split /\t/,$line;
2860 :     }
2861 :     } else {
2862 :     # Trace the reason the read failed.
2863 :     Trace("End of file: $!") if T(File => 3);
2864 : parrello 1.15 }
2865 : parrello 1.93 # Return the result.
2866 :     return @retVal;
2867 : parrello 1.15 }
2868 :    
2869 : parrello 1.93 =head3 PutLine
2870 :    
2871 :     Tracer::PutLine($handle, \@fields, $eol);
2872 : parrello 1.35
2873 : parrello 1.93 Write a line of data to a tab-delimited file. The specified field values will be
2874 :     output in tab-separated form, with a trailing new-line.
2875 : parrello 1.35
2876 : parrello 1.93 =over 4
2877 : parrello 1.35
2878 : parrello 1.93 =item handle
2879 : parrello 1.69
2880 : parrello 1.93 Output file handle.
2881 : parrello 1.69
2882 : parrello 1.93 =item fields
2883 : parrello 1.69
2884 : parrello 1.93 List of field values.
2885 : parrello 1.69
2886 : parrello 1.93 =item eol (optional)
2887 : parrello 1.69
2888 : parrello 1.93 End-of-line character (default is "\n").
2889 : parrello 1.69
2890 :     =back
2891 : parrello 1.35
2892 :     =cut
2893 :    
2894 : parrello 1.93 sub PutLine {
2895 : parrello 1.69 # Get the parameters.
2896 : parrello 1.93 my ($handle, $fields, $eol) = @_;
2897 :     # Write the data.
2898 :     print $handle join("\t", @{$fields}) . ($eol || "\n");
2899 : parrello 1.69 }
2900 :    
2901 :    
2902 : parrello 1.97 =head3 PrintLine
2903 :    
2904 :     Tracer::PrintLine($line);
2905 :    
2906 :     Print a line of text with a trailing new-line.
2907 :    
2908 :     =over 4
2909 :    
2910 :     =item line
2911 :    
2912 :     Line of text to print.
2913 :    
2914 :     =back
2915 :    
2916 :     =cut
2917 :    
2918 :     sub PrintLine {
2919 :     # Get the parameters.
2920 :     my ($line) = @_;
2921 :     # Print the line.
2922 :     print "$line\n";
2923 :     }
2924 :    
2925 : parrello 1.69
2926 : parrello 1.93 =head2 Other Useful Methods
2927 :    
2928 : parrello 1.115 =head3 IDHASH
2929 :    
2930 :     my $hash = SHTargetSearch::IDHASH(@keys);
2931 :    
2932 :     This is a dinky little method that converts a list of values to a reference
2933 :     to hash of values to labels. The values and labels are the same.
2934 :    
2935 :     =cut
2936 :    
2937 :     sub IDHASH {
2938 :     my %retVal = map { $_ => $_ } @_;
2939 :     return \%retVal;
2940 :     }
2941 :    
2942 :     =head3 Pluralize
2943 :    
2944 :     my $plural = Tracer::Pluralize($word);
2945 :    
2946 :     This is a very simple pluralization utility. It adds an C<s> at the end
2947 :     of the input word unless it already ends in an C<s>, in which case it
2948 :     adds C<es>.
2949 :    
2950 :     =over 4
2951 :    
2952 :     =item word
2953 :    
2954 :     Singular word to pluralize.
2955 :    
2956 :     =item RETURN
2957 :    
2958 :     Returns the probable plural form of the word.
2959 :    
2960 :     =back
2961 :    
2962 :     =cut
2963 :    
2964 :     sub Pluralize {
2965 :     # Get the parameters.
2966 :     my ($word) = @_;
2967 :     # Declare the return variable.
2968 :     my $retVal;
2969 :     if ($word =~ /s$/) {
2970 :     $retVal = $word . 'es';
2971 :     } else {
2972 :     $retVal = $word . 's';
2973 :     }
2974 :     # Return the result.
2975 :     return $retVal;
2976 :     }
2977 :    
2978 :     =head3 Numeric
2979 :    
2980 :     my $okFlag = Tracer::Numeric($string);
2981 :    
2982 :     Return the value of the specified string if it is numeric, or an undefined value
2983 :     if it is not numeric.
2984 :    
2985 :     =over 4
2986 :    
2987 :     =item string
2988 :    
2989 :     String to check.
2990 :    
2991 :     =item RETURN
2992 :    
2993 :     Returns the numeric value of the string if successful, or C<undef> if the string
2994 :     is not numeric.
2995 :    
2996 :     =back
2997 :    
2998 :     =cut
2999 :    
3000 :     sub Numeric {
3001 :     # Get the parameters.
3002 :     my ($string) = @_;
3003 :     # We'll put the value in here if we succeed.
3004 :     my $retVal;
3005 :     # Get a working copy of the string.
3006 :     my $copy = $string;
3007 :     # Trim leading and trailing spaces.
3008 :     $copy =~ s/^\s+//;
3009 :     $copy =~ s/\s+$//;
3010 :     # Check the result.
3011 :     if ($copy =~ /^[+-]?\d+$/) {
3012 :     $retVal = $copy;
3013 :     } elsif ($copy =~ /^([+-]\d+|\d*)[eE][+-]?\d+$/) {
3014 :     $retVal = $copy;
3015 :     } elsif ($copy =~ /^([+-]\d+|\d*)\.\d*([eE][+-]?\d+)?$/) {
3016 :     $retVal = $copy;
3017 :     }
3018 :     # Return the result.
3019 :     return $retVal;
3020 :     }
3021 :    
3022 :    
3023 : parrello 1.93 =head3 ParseParm
3024 :    
3025 :     my $listValue = Tracer::ParseParm($string);
3026 :    
3027 :     Convert a parameter into a list reference. If the parameter is undefined,
3028 :     an undefined value will be returned. Otherwise, it will be parsed as a
3029 :     comma-separated list of values.
3030 : parrello 1.69
3031 :     =over 4
3032 :    
3033 : parrello 1.93 =item string
3034 :    
3035 :     Incoming string.
3036 :    
3037 :     =item RETURN
3038 : parrello 1.69
3039 : parrello 1.93 Returns a reference to a list of values, or C<undef> if the incoming value
3040 :     was undefined.
3041 : parrello 1.69
3042 :     =back
3043 :    
3044 :     =cut
3045 :    
3046 : parrello 1.93 sub ParseParm {
3047 :     # Get the parameters.
3048 :     my ($string) = @_;
3049 :     # Declare the return variable.
3050 :     my $retVal;
3051 :     # Check for data.
3052 :     if (defined $string) {
3053 :     # We have some, so split it into a list.
3054 :     $retVal = [ split /\s*,\s*/, $string];
3055 : parrello 1.72 }
3056 : parrello 1.93 # Return the result.
3057 :     return $retVal;
3058 : parrello 1.69 }
3059 :    
3060 : parrello 1.97 =head3 Now
3061 :    
3062 :     my $string = Tracer::Now();
3063 :    
3064 :     Return a displayable time stamp containing the local time. Whatever format this
3065 :     method produces must be parseable by L</ParseDate>.
3066 :    
3067 :     =cut
3068 :    
3069 :     sub Now {
3070 :     return DisplayTime(time);
3071 :     }
3072 :    
3073 :     =head3 DisplayTime
3074 :    
3075 :     my $string = Tracer::DisplayTime($time);
3076 : parrello 1.69
3077 : parrello 1.97 Convert a time value to a displayable time stamp. Whatever format this
3078 :     method produces must be parseable by L</ParseDate>.
3079 :    
3080 :     =over 4
3081 : parrello 1.69
3082 : parrello 1.97 =item time
3083 : parrello 1.69
3084 : parrello 1.97 Time to display, in seconds since the epoch, or C<undef> if the time is unknown.
3085 :    
3086 :     =item RETURN
3087 : parrello 1.69
3088 : parrello 1.97 Returns a displayable time, or C<(n/a)> if the incoming time is undefined.
3089 : parrello 1.69
3090 : parrello 1.97 =back
3091 : parrello 1.69
3092 : parrello 1.93 =cut
3093 : parrello 1.69
3094 : parrello 1.97 sub DisplayTime {
3095 :     my ($time) = @_;
3096 :     my $retVal = "(n/a)";
3097 :     if (defined $time) {
3098 :     my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = localtime($time);
3099 :     $retVal = _p2($mon+1) . "/" . _p2($mday) . "/" . ($year + 1900) . " " .
3100 :     _p2($hour) . ":" . _p2($min) . ":" . _p2($sec);
3101 :     }
3102 : parrello 1.93 return $retVal;
3103 :     }
3104 : parrello 1.69
3105 : parrello 1.93 # Pad a number to 2 digits.
3106 :     sub _p2 {
3107 :     my ($value) = @_;
3108 :     $value = "0$value" if ($value < 10);
3109 :     return $value;
3110 : parrello 1.69 }
3111 :    
3112 : parrello 1.93 =head3 Escape
3113 : parrello 1.69
3114 : parrello 1.93 my $codedString = Tracer::Escape($realString);
3115 : parrello 1.69
3116 : parrello 1.93 Escape a string for use in a command. Tabs will be replaced by C<\t>, new-lines
3117 :     replaced by C<\n>, carriage returns will be deleted, and backslashes will be doubled. The
3118 :     result is to reverse the effect of L</UnEscape>.
3119 : parrello 1.69
3120 :     =over 4
3121 :    
3122 : parrello 1.93 =item realString
3123 : parrello 1.69
3124 : parrello 1.93 String to escape.
3125 : parrello 1.69
3126 :     =item RETURN
3127 :    
3128 : parrello 1.93 Escaped equivalent of the real string.
3129 :    
3130 :     =back
3131 :    
3132 :     =cut
3133 :    
3134 :     sub Escape {
3135 :     # Get the parameter.
3136 :     my ($realString) = @_;
3137 :     # Initialize the return variable.
3138 :     my $retVal = "";
3139 :     # Loop through the parameter string, looking for sequences to escape.
3140 :     while (length $realString > 0) {
3141 :     # Look for the first sequence to escape.
3142 :     if ($realString =~ /^(.*?)([\n\t\r\\])/) {
3143 :     # Here we found it. The text preceding the sequence is in $1. The sequence
3144 :     # itself is in $2. First, move the clear text to the return variable.
3145 :     $retVal .= $1;
3146 :     # Strip the processed section off the real string.
3147 :     $realString = substr $realString, (length $2) + (length $1);
3148 :     # Get the matched character.
3149 :     my $char = $2;
3150 :     # If we have a CR, we are done.
3151 :     if ($char ne "\r") {
3152 :     # It's not a CR, so encode the escape sequence.
3153 :     $char =~ tr/\t\n/tn/;
3154 :     $retVal .= "\\" . $char;
3155 :     }
3156 :     } else {
3157 :     # Here there are no more escape sequences. The rest of the string is
3158 :     # transferred unmodified.
3159 :     $retVal .= $realString;
3160 :     $realString = "";
3161 :     }
3162 :     }
3163 :     # Return the result.
3164 :     return $retVal;
3165 : parrello 1.69 }
3166 :    
3167 : parrello 1.93 =head3 UnEscape
3168 : parrello 1.69
3169 : parrello 1.93 my $realString = Tracer::UnEscape($codedString);
3170 : parrello 1.69
3171 : parrello 1.93 Replace escape sequences with their actual equivalents. C<\t> will be replaced by
3172 :     a tab, C<\n> by a new-line character, and C<\\> by a backslash. C<\r> codes will
3173 :     be deleted.
3174 : parrello 1.69
3175 :     =over 4
3176 :    
3177 : parrello 1.93 =item codedString
3178 : parrello 1.69
3179 : parrello 1.93 String to un-escape.
3180 : parrello 1.69
3181 :     =item RETURN
3182 :    
3183 : parrello 1.93 Returns a copy of the original string with the escape sequences converted to their actual
3184 :     values.
3185 : parrello 1.69
3186 :     =back
3187 :    
3188 :     =cut
3189 :    
3190 : parrello 1.93 sub UnEscape {
3191 :     # Get the parameter.
3192 :     my ($codedString) = @_;
3193 :     # Initialize the return variable.
3194 :     my $retVal = "";
3195 :     # Only proceed if the incoming string is nonempty.
3196 :     if (defined $codedString) {
3197 :     # Loop through the parameter string, looking for escape sequences. We can't do
3198 :     # translating because it causes problems with the escaped slash. ("\\t" becomes
3199 :     # "\<tab>" no matter what we do.)
3200 :     while (length $codedString > 0) {
3201 :     # Look for the first escape sequence.
3202 :     if ($codedString =~ /^(.*?)\\(\\|n|t|r)/) {
3203 :     # Here we found it. The text preceding the sequence is in $1. The sequence
3204 :     # itself is in $2. First, move the clear text to the return variable.
3205 :     $retVal .= $1;
3206 :     $codedString = substr $codedString, (2 + length $1);
3207 :     # Get the escape value.
3208 :     my $char = $2;
3209 :     # If we have a "\r", we are done.
3210 :     if ($char ne 'r') {
3211 :     # Here it's not an 'r', so we convert it.
3212 :     $char =~ tr/\\tn/\\\t\n/;
3213 :     $retVal .= $char;
3214 :     }
3215 :     } else {
3216 :     # Here there are no more escape sequences. The rest of the string is
3217 :     # transferred unmodified.
3218 :     $retVal .= $codedString;
3219 :     $codedString = "";
3220 :     }
3221 :     }
3222 : parrello 1.35 }
3223 : parrello 1.69 # Return the result.
3224 :     return $retVal;
3225 :     }
3226 :    
3227 : parrello 1.93 =head3 Percent
3228 : parrello 1.69
3229 : parrello 1.93 my $percent = Tracer::Percent($number, $base);
3230 : parrello 1.69
3231 : parrello 1.93 Returns the percent of the base represented by the given number. If the base
3232 :     is zero, returns zero.
3233 : parrello 1.69
3234 :     =over 4
3235 :    
3236 : parrello 1.93 =item number
3237 : parrello 1.69
3238 : parrello 1.93 Percent numerator.
3239 : parrello 1.69
3240 : parrello 1.93 =item base
3241 : parrello 1.69
3242 : parrello 1.93 Percent base.
3243 : parrello 1.69
3244 : parrello 1.93 =item RETURN
3245 : parrello 1.69
3246 : parrello 1.93 Returns the percentage of the base represented by the numerator.
3247 : parrello 1.69
3248 :     =back
3249 :    
3250 :     =cut
3251 :    
3252 : parrello 1.93 sub Percent {
3253 : parrello 1.69 # Get the parameters.
3254 : parrello 1.93 my ($number, $base) = @_;
3255 :     # Declare the return variable.
3256 :     my $retVal = 0;
3257 :     # Compute the percent.
3258 :     if ($base != 0) {
3259 :     $retVal = $number * 100 / $base;
3260 :     }
3261 :     # Return the result.
3262 :     return $retVal;
3263 : parrello 1.69 }
3264 :    
3265 : parrello 1.115 =head3 In
3266 :    
3267 :     my $flag = Tracer::In($value, $min, $max);
3268 :    
3269 :     Return TRUE if the value is between the minimum and the maximum, else FALSE.
3270 :    
3271 :     =cut
3272 :    
3273 :     sub In {
3274 :     return ($_[0] <= $_[2] && $_[0] >= $_[1]);
3275 :     }
3276 :    
3277 :    
3278 : parrello 1.97 =head3 Constrain
3279 :    
3280 :     my $constrained = Constrain($value, $min, $max);
3281 :    
3282 :     Modify a numeric value to bring it to a point in between a maximum and a minimum.
3283 :    
3284 :     =over 4
3285 :    
3286 :     =item value
3287 :    
3288 :     Value to constrain.
3289 :    
3290 :     =item min (optional)
3291 :    
3292 :     Minimum permissible value. If this parameter is undefined, no minimum constraint will be applied.
3293 :    
3294 :     =item max (optional)
3295 :    
3296 :     Maximum permissible value. If this parameter is undefined, no maximum constraint will be applied.
3297 :    
3298 :     =item RETURN
3299 :    
3300 :     Returns the incoming value, constrained according to the other parameters.
3301 :    
3302 :     =back
3303 :    
3304 :     =cut
3305 :    
3306 :     sub Constrain {
3307 :     # Get the parameters.
3308 :     my ($value, $min, $max) = @_;
3309 :     # Declare the return variable.
3310 :     my $retVal = $value;
3311 :     # Apply the minimum constraint.
3312 :     if (defined $min && $retVal < $min) {
3313 :     $retVal = $min;
3314 :     }
3315 :     # Apply the maximum constraint.
3316 :     if (defined $max && $retVal > $max) {
3317 :     $retVal = $max;
3318 :     }
3319 :     # Return the result.
3320 :     return $retVal;
3321 :     }
3322 :    
3323 : parrello 1.93 =head3 Min
3324 : parrello 1.69
3325 : parrello 1.93 my $min = Min($value1, $value2, ... $valueN);
3326 : parrello 1.69
3327 : parrello 1.93 Return the minimum argument. The arguments are treated as numbers.
3328 : parrello 1.69
3329 :     =over 4
3330 :    
3331 : parrello 1.93 =item $value1, $value2, ... $valueN
3332 : parrello 1.69
3333 : parrello 1.93 List of numbers to compare.
3334 : parrello 1.69
3335 :     =item RETURN
3336 :    
3337 : parrello 1.93 Returns the lowest number in the list.
3338 : parrello 1.69
3339 :     =back
3340 :    
3341 :     =cut
3342 :    
3343 : parrello 1.93 sub Min {
3344 :     # Get the parameters. Note that we prime the return value with the first parameter.
3345 :     my ($retVal, @values) = @_;
3346 :     # Loop through the remaining parameters, looking for the lowest.
3347 :     for my $value (@values) {
3348 :     if ($value < $retVal) {
3349 :     $retVal = $value;
3350 : parrello 1.72 }
3351 :     }
3352 : parrello 1.93 # Return the minimum found.
3353 : parrello 1.70 return $retVal;
3354 : parrello 1.35 }
3355 :    
3356 : parrello 1.93 =head3 Max
3357 :    
3358 :     my $max = Max($value1, $value2, ... $valueN);
3359 : parrello 1.69
3360 : parrello 1.93 Return the maximum argument. The arguments are treated as numbers.
3361 : parrello 1.65
3362 : parrello 1.93 =over 4
3363 : parrello 1.65
3364 : parrello 1.93 =item $value1, $value2, ... $valueN
3365 : parrello 1.65
3366 : parrello 1.93 List of numbers to compare.
3367 : parrello 1.65
3368 : parrello 1.93 =item RETURN
3369 : parrello 1.65
3370 : parrello 1.93 Returns the highest number in the list.
3371 : parrello 1.65
3372 :     =back
3373 :    
3374 :     =cut
3375 :    
3376 : parrello 1.93 sub Max {
3377 :     # Get the parameters. Note that we prime the return value with the first parameter.
3378 :     my ($retVal, @values) = @_;
3379 :     # Loop through the remaining parameters, looking for the highest.
3380 :     for my $value (@values) {
3381 :     if ($value > $retVal) {
3382 :     $retVal = $value;
3383 : parrello 1.65 }
3384 :     }
3385 : parrello 1.93 # Return the maximum found.
3386 :     return $retVal;
3387 : parrello 1.65 }
3388 :    
3389 : parrello 1.93 =head3 Strip
3390 : parrello 1.37
3391 : parrello 1.93 my $string = Tracer::Strip($line);
3392 : parrello 1.37
3393 : parrello 1.93 Strip all line terminators off a string. This is necessary when dealing with files
3394 :     that may have been transferred back and forth several times among different
3395 :     operating environments.
3396 : parrello 1.37
3397 :     =over 4
3398 :    
3399 : parrello 1.93 =item line
3400 : parrello 1.37
3401 : parrello 1.93 Line of text to be stripped.
3402 : parrello 1.37
3403 : parrello 1.93 =item RETURN
3404 : parrello 1.91
3405 : parrello 1.93 The same line of text with all the line-ending characters chopped from the end.
3406 : parrello 1.91
3407 : parrello 1.37 =back
3408 :    
3409 :     =cut
3410 :    
3411 : parrello 1.93 sub Strip {
3412 :     # Get a copy of the parameter string.
3413 :     my ($string) = @_;
3414 :     my $retVal = (defined $string ? $string : "");
3415 :     # Strip the line terminator characters.
3416 :     $retVal =~ s/(\r|\n)+$//g;
3417 :     # Return the result.
3418 :     return $retVal;
3419 : parrello 1.43 }
3420 :    
3421 : parrello 1.115 =head3 Trim
3422 :    
3423 :     my $string = Tracer::Trim($line);
3424 :    
3425 :     Trim all spaces from the beginning and ending of a string.
3426 :    
3427 :     =over 4
3428 :    
3429 :     =item line
3430 :    
3431 :     Line of text to be trimmed.
3432 :    
3433 :     =item RETURN
3434 :    
3435 :     The same line of text with all whitespace chopped off either end.
3436 :    
3437 :     =back
3438 :    
3439 :     =cut
3440 :    
3441 :     sub Trim {
3442 :     # Get a copy of the parameter string.
3443 :     my ($string) = @_;
3444 :     my $retVal = (defined $string ? $string : "");
3445 :     # Strip the front spaces.
3446 :     $retVal =~ s/^\s+//;
3447 :     # Strip the back spaces.
3448 :     $retVal =~ s/\s+$//;
3449 :     # Return the result.
3450 :     return $retVal;
3451 :     }
3452 :    
3453 : parrello 1.93 =head3 Pad
3454 : parrello 1.43
3455 : parrello 1.93 my $paddedString = Tracer::Pad($string, $len, $left, $padChar);
3456 : parrello 1.43
3457 : parrello 1.93 Pad a string to a specified length. The pad character will be a
3458 :     space, and the padding will be on the right side unless specified
3459 :     in the third parameter.
3460 : parrello 1.43
3461 :     =over 4
3462 :    
3463 : parrello 1.93 =item string
3464 :    
3465 :     String to be padded.
3466 :    
3467 :     =item len
3468 :    
3469 :     Desired length of the padded string.
3470 :    
3471 :     =item left (optional)
3472 :    
3473 :     TRUE if the string is to be left-padded; otherwise it will be padded on the right.
3474 :    
3475 :     =item padChar (optional)
3476 :    
3477 :     Character to use for padding. The default is a space.
3478 :    
3479 :     =item RETURN
3480 : parrello 1.43
3481 : parrello 1.93 Returns a copy of the original string with the pad character added to the
3482 :     specified end so that it achieves the desired length.
3483 : parrello 1.43
3484 :     =back
3485 :    
3486 :     =cut
3487 :    
3488 : parrello 1.93 sub Pad {
3489 :     # Get the parameters.
3490 :     my ($string, $len, $left, $padChar) = @_;
3491 :     # Compute the padding character.
3492 :     if (! defined $padChar) {
3493 :     $padChar = " ";
3494 :     }
3495 :     # Compute the number of spaces needed.
3496 :     my $needed = $len - length $string;
3497 :     # Copy the string into the return variable.
3498 :     my $retVal = $string;
3499 :     # Only proceed if padding is needed.
3500 :     if ($needed > 0) {
3501 :     # Create the pad string.
3502 :     my $pad = $padChar x $needed;
3503 :     # Affix it to the return value.
3504 :     if ($left) {
3505 :     $retVal = $pad . $retVal;
3506 :     } else {
3507 :     $retVal .= $pad;
3508 : parrello 1.43 }
3509 : parrello 1.37 }
3510 : parrello 1.93 # Return the result.
3511 :     return $retVal;
3512 : parrello 1.37 }
3513 :    
3514 : parrello 1.118 =head3 Quoted
3515 :    
3516 :     my $string = Tracer::Quoted($var);
3517 :    
3518 :     Convert the specified value to a string and enclose it in single quotes.
3519 :     If it's undefined, the string C<undef> in angle brackets will be used
3520 :     instead.
3521 :    
3522 :     =over 4
3523 :    
3524 :     =item var
3525 :    
3526 :     Value to quote.
3527 :    
3528 :     =item RETURN
3529 :    
3530 :     Returns a string enclosed in quotes, or an indication the value is undefined.
3531 :    
3532 :     =back
3533 :    
3534 :     =cut
3535 :    
3536 :     sub Quoted {
3537 :     # Get the parameters.
3538 :     my ($var) = @_;
3539 :     # Declare the return variable.
3540 :     my $retVal;
3541 :     # Are we undefined?
3542 :     if (! defined $var) {
3543 :     $retVal = "<undef>";
3544 :     } else {
3545 :     # No, so convert to a string and enclose in quotes.
3546 :     $retVal = $var;
3547 :     $retVal =~ s/'/\\'/;
3548 :     $retVal = "'$retVal'";
3549 :     }
3550 :     # Return the result.
3551 :     return $retVal;
3552 :     }
3553 :    
3554 : parrello 1.93 =head3 EOF
3555 :    
3556 :     This is a constant that is lexically greater than any useful string.
3557 :    
3558 :     =cut
3559 :    
3560 :     sub EOF {
3561 :     return "\xFF\xFF\xFF\xFF\xFF";
3562 :     }
3563 : parrello 1.59
3564 : parrello 1.93 =head3 TICK
3565 : parrello 1.59
3566 : parrello 1.93 my @results = TICK($commandString);
3567 : parrello 1.59
3568 : parrello 1.93 Perform a back-tick operation on a command. If this is a Windows environment, any leading
3569 :     dot-slash (C<./> will be removed. So, for example, if you were doing
3570 : parrello 1.59
3571 : parrello 1.93 `./protein.cgi`
3572 : parrello 1.59
3573 : parrello 1.93 from inside a CGI script, it would work fine in Unix, but would issue an error message
3574 :     in Windows complaining that C<'.'> is not a valid command. If instead you code
3575 : parrello 1.59
3576 : parrello 1.93 TICK("./protein.cgi")
3577 : parrello 1.59
3578 : parrello 1.93 it will work correctly in both environments.
3579 : parrello 1.59
3580 : parrello 1.93 =over 4
3581 : parrello 1.59
3582 : parrello 1.93 =item commandString
3583 : parrello 1.59
3584 : parrello 1.93 The command string to pass to the system.
3585 : parrello 1.59
3586 :     =item RETURN
3587 :    
3588 : parrello 1.93 Returns the standard output from the specified command, as a list.
3589 : parrello 1.59
3590 :     =back
3591 :    
3592 :     =cut
3593 : parrello 1.93 #: Return Type @;
3594 :     sub TICK {
3595 : parrello 1.59 # Get the parameters.
3596 : parrello 1.93 my ($commandString) = @_;
3597 :     # Chop off the dot-slash if this is Windows.
3598 :     if ($FIG_Config::win_mode) {
3599 :     $commandString =~ s!^\./!!;
3600 : parrello 1.59 }
3601 : parrello 1.93 # Activate the command and return the result.
3602 :     return `$commandString`;
3603 : parrello 1.59 }
3604 :    
3605 : parrello 1.93
3606 : parrello 1.55 =head3 CommaFormat
3607 :    
3608 : parrello 1.92 my $formatted = Tracer::CommaFormat($number);
3609 : parrello 1.55
3610 :     Insert commas into a number.
3611 :    
3612 :     =over 4
3613 :    
3614 :     =item number
3615 :    
3616 :     A sequence of digits.
3617 :    
3618 :     =item RETURN
3619 :    
3620 :     Returns the same digits with commas strategically inserted.
3621 :    
3622 :     =back
3623 :    
3624 :     =cut
3625 :    
3626 :     sub CommaFormat {
3627 :     # Get the parameters.
3628 :     my ($number) = @_;
3629 :     # Pad the length up to a multiple of three.
3630 :     my $padded = "$number";
3631 :     $padded = " " . $padded while length($padded) % 3 != 0;
3632 :     # This is a fancy PERL trick. The parentheses in the SPLIT pattern
3633 :     # cause the delimiters to be included in the output stream. The
3634 :     # GREP removes the empty strings in between the delimiters.
3635 :     my $retVal = join(",", grep { $_ ne '' } split(/(...)/, $padded));
3636 :     # Clean out the spaces.
3637 :     $retVal =~ s/ //g;
3638 :     # Return the result.
3639 :     return $retVal;
3640 :     }
3641 : parrello 1.46
3642 :    
3643 : parrello 1.117 =head3 GetMemorySize
3644 :    
3645 :     my $string = Tracer::GetMemorySize();
3646 :    
3647 :     Return a memory size string for the current process. The string will be
3648 :     in comma format, with a size indicator (K, M, G) at the end.
3649 :    
3650 :     =cut
3651 :    
3652 :     sub GetMemorySize {
3653 :     # Get the memory size from Unix.
3654 :     my ($retVal) = `ps h -o vsz $$`;
3655 :     # Remove the ending new-line.
3656 :     chomp $retVal;
3657 :     # Format and return the result.
3658 :     return CommaFormat($retVal) . "K";
3659 :     }
3660 :    
3661 : parrello 1.62 =head3 CompareLists
3662 :    
3663 : parrello 1.92 my ($inserted, $deleted) = Tracer::CompareLists(\@newList, \@oldList, $keyIndex);
3664 : parrello 1.62
3665 :     Compare two lists of tuples, and return a hash analyzing the differences. The lists
3666 :     are presumed to be sorted alphabetically by the value in the $keyIndex column.
3667 :     The return value contains a list of items that are only in the new list
3668 :     (inserted) and only in the old list (deleted).
3669 :    
3670 :     =over 4
3671 :    
3672 :     =item newList
3673 :    
3674 :     Reference to a list of new tuples.
3675 :    
3676 :     =item oldList
3677 :    
3678 :     Reference to a list of old tuples.
3679 :    
3680 :     =item keyIndex (optional)
3681 :    
3682 :     Index into each tuple of its key field. The default is 0.
3683 :    
3684 :     =item RETURN
3685 :    
3686 :     Returns a 2-tuple consisting of a reference to the list of items that are only in the new
3687 :     list (inserted) followed by a reference to the list of items that are only in the old
3688 :     list (deleted).
3689 :    
3690 :     =back
3691 :    
3692 :     =cut
3693 :    
3694 :     sub CompareLists {
3695 :     # Get the parameters.
3696 :     my ($newList, $oldList, $keyIndex) = @_;
3697 :     if (! defined $keyIndex) {
3698 :     $keyIndex = 0;
3699 :     }
3700 :     # Declare the return variables.
3701 :     my ($inserted, $deleted) = ([], []);
3702 :     # Loop through the two lists simultaneously.
3703 :     my ($newI, $oldI) = (0, 0);
3704 :     my ($newN, $oldN) = (scalar @{$newList}, scalar @{$oldList});
3705 :     while ($newI < $newN || $oldI < $oldN) {
3706 :     # Get the current object in each list. Note that if one
3707 :     # of the lists is past the end, we'll get undef.
3708 :     my $newItem = $newList->[$newI];
3709 :     my $oldItem = $oldList->[$oldI];
3710 : parrello 1.63 if (! defined($newItem) || defined($oldItem) && $newItem->[$keyIndex] gt $oldItem->[$keyIndex]) {
3711 : parrello 1.62 # The old item is not in the new list, so mark it deleted.
3712 :     push @{$deleted}, $oldItem;
3713 :     $oldI++;
3714 :     } elsif (! defined($oldItem) || $oldItem->[$keyIndex] gt $newItem->[$keyIndex]) {
3715 :     # The new item is not in the old list, so mark it inserted.
3716 :     push @{$inserted}, $newItem;
3717 :     $newI++;
3718 :     } else {
3719 :     # The item is in both lists, so push forward.
3720 :     $oldI++;
3721 :     $newI++;
3722 :     }
3723 :     }
3724 :     # Return the result.
3725 :     return ($inserted, $deleted);
3726 :     }
3727 :    
3728 : parrello 1.105 =head3 Cmp
3729 :    
3730 :     my $cmp = Tracer::Cmp($a, $b);
3731 :    
3732 :     This method performs a universal sort comparison. Each value coming in is
3733 : parrello 1.121 separated into a text parts and number parts. The text
3734 : parrello 1.105 part is string compared, and if both parts are equal, then the number
3735 :     parts are compared numerically. A stream of just numbers or a stream of
3736 :     just strings will sort correctly, and a mixed stream will sort with the
3737 :     numbers first. Strings with a label and a number will sort in the
3738 : parrello 1.121 expected manner instead of lexically. Undefined values sort last.
3739 : parrello 1.105
3740 :     =over 4
3741 :    
3742 :     =item a
3743 :    
3744 :     First item to compare.
3745 :    
3746 :     =item b
3747 :    
3748 :     Second item to compare.
3749 :    
3750 :     =item RETURN
3751 :    
3752 :     Returns a negative number if the first item should sort first (is less), a positive
3753 :     number if the first item should sort second (is greater), and a zero if the items are
3754 :     equal.
3755 :    
3756 :     =back
3757 :    
3758 :     =cut
3759 :    
3760 :     sub Cmp {
3761 :     # Get the parameters.
3762 :     my ($a, $b) = @_;
3763 :     # Declare the return value.
3764 :     my $retVal;
3765 :     # Check for nulls.
3766 :     if (! defined($a)) {
3767 :     $retVal = (! defined($b) ? 0 : -1);
3768 :     } elsif (! defined($b)) {
3769 :     $retVal = 1;
3770 :     } else {
3771 :     # Here we have two real values. Parse the two strings.
3772 : parrello 1.121 my @aParsed = _Parse($a);
3773 :     my @bParsed = _Parse($b);
3774 :     # Loop through the first string.
3775 :     while (! $retVal && @aParsed) {
3776 :     # Extract the string parts.
3777 :     my $aPiece = shift(@aParsed);
3778 :     my $bPiece = shift(@bParsed) || '';
3779 :     # Extract the number parts.
3780 :     my $aNum = shift(@aParsed);
3781 :     my $bNum = shift(@bParsed) || 0;
3782 :     # Compare the string parts insensitively.
3783 :     $retVal = (lc($aPiece) cmp lc($bPiece));
3784 :     # If they're equal, compare them sensitively.
3785 :     if (! $retVal) {
3786 :     $retVal = ($aPiece cmp $bPiece);
3787 :     # If they're STILL equal, compare the number parts.
3788 :     if (! $retVal) {
3789 :     $retVal = $aNum <=> $bNum;
3790 :     }
3791 :     }
3792 : parrello 1.105 }
3793 :     }
3794 :     # Return the result.
3795 :     return $retVal;
3796 :     }
3797 :    
3798 : parrello 1.121 # This method parses an input string into a string parts alternating with
3799 :     # number parts.
3800 : parrello 1.115 sub _Parse {
3801 : parrello 1.121 # Get the incoming string.
3802 : parrello 1.115 my ($string) = @_;
3803 : parrello 1.121 # The pieces will be put in here.
3804 :     my @retVal;
3805 :     # Loop through as many alpha/num sets as we can.
3806 :     while ($string =~ /^(\D*)(\d+)(.*)/) {
3807 :     # Push the alpha and number parts into the return string.
3808 :     push @retVal, $1, $2;
3809 :     # Save the residual.
3810 :     $string = $3;
3811 :     }
3812 :     # If there's still stuff left, add it to the end with a trailing
3813 :     # zero.
3814 :     if ($string) {
3815 :     push @retVal, $string, 0;
3816 : parrello 1.115 }
3817 : parrello 1.121 # Return the list.
3818 :     return @retVal;
3819 : parrello 1.115 }
3820 :    
3821 : parrello 1.108 =head3 ListEQ
3822 :    
3823 :     my $flag = Tracer::ListEQ(\@a, \@b);
3824 :    
3825 :     Return TRUE if the specified lists contain the same strings in the same
3826 :     order, else FALSE.
3827 :    
3828 :     =over 4
3829 :    
3830 :     =item a
3831 :    
3832 :     Reference to the first list.
3833 :    
3834 :     =item b
3835 :    
3836 :     Reference to the second list.
3837 :    
3838 :     =item RETURN
3839 :    
3840 :     Returns TRUE if the two parameters are identical string lists, else FALSE.
3841 :    
3842 :     =back
3843 :    
3844 :     =cut
3845 :    
3846 :     sub ListEQ {
3847 :     # Get the parameters.
3848 :     my ($a, $b) = @_;
3849 :     # Declare the return variable. Start by checking the lengths.
3850 :     my $n = scalar(@$a);
3851 :     my $retVal = ($n == scalar(@$b));
3852 :     # Now compare the list elements.
3853 :     for (my $i = 0; $retVal && $i < $n; $i++) {
3854 :     $retVal = ($a->[$i] eq $b->[$i]);
3855 :     }
3856 :     # Return the result.
3857 :     return $retVal;
3858 :     }
3859 :    
3860 : parrello 1.105 =head2 CGI Script Utilities
3861 :    
3862 :     =head3 ScriptSetup (deprecated)
3863 :    
3864 :     my ($cgi, $varHash) = ScriptSetup($noTrace);
3865 :    
3866 :     Perform standard tracing and debugging setup for scripts. The value returned is
3867 :     the CGI object followed by a pre-built variable hash. At the end of the script,
3868 :     the client should call L</ScriptFinish> to output the web page.
3869 :    
3870 :     This method calls L</ETracing> to configure tracing, which allows the tracing
3871 :     to be configured via the emergency tracing form on the debugging control panel.
3872 :     Tracing will then be turned on automatically for all programs that use the L</ETracing>
3873 :     method, which includes every program that uses this method or L</StandardSetup>.
3874 :    
3875 :     =over 4
3876 :    
3877 :     =item noTrace (optional)
3878 :    
3879 :     If specified, tracing will be suppressed. This is useful if the script wants to set up
3880 :     tracing manually.
3881 :    
3882 :     =item RETURN
3883 :    
3884 :     Returns a two-element list consisting of a CGI query object and a variable hash for
3885 :     the output page.
3886 :    
3887 :     =back
3888 :    
3889 :     =cut
3890 :    
3891 :     sub ScriptSetup {
3892 :     # Get the parameters.
3893 :     my ($noTrace) = @_;
3894 :     # Get the CGI query object.
3895 :     my $cgi = CGI->new();
3896 :     # Set up tracing if it's not suppressed.
3897 :     ETracing($cgi) unless $noTrace;
3898 :     # Create the variable hash.
3899 :     my $varHash = { results => '' };
3900 :     # Return the query object and variable hash.
3901 :     return ($cgi, $varHash);
3902 :     }
3903 :    
3904 :     =head3 ScriptFinish (deprecated)
3905 :    
3906 :     ScriptFinish($webData, $varHash);
3907 :    
3908 :     Output a web page at the end of a script. Either the string to be output or the
3909 :     name of a template file can be specified. If the second parameter is omitted,
3910 :     it is assumed we have a string to be output; otherwise, it is assumed we have the
3911 :     name of a template file. The template should have the variable C<DebugData>
3912 :     specified in any form that invokes a standard script. If debugging mode is turned
3913 :     on, a form field will be put in that allows the user to enter tracing data.
3914 :     Trace messages will be placed immediately before the terminal C<BODY> tag in
3915 :     the output, formatted as a list.
3916 :    
3917 :     A typical standard script would loook like the following.
3918 :    
3919 :     BEGIN {
3920 :     # Print the HTML header.
3921 :     print "CONTENT-TYPE: text/html\n\n";
3922 :     }
3923 :     use Tracer;
3924 :     use CGI;
3925 :     use FIG;
3926 :     # ... more uses ...
3927 :    
3928 :     my ($cgi, $varHash) = ScriptSetup();
3929 :     eval {
3930 :     # ... get data from $cgi, put it in $varHash ...
3931 :     };
3932 :     if ($@) {
3933 :     Trace("Script Error: $@") if T(0);
3934 :     }
3935 :     ScriptFinish("Html/MyTemplate.html", $varHash);
3936 :    
3937 :     The idea here is that even if the script fails, you'll see trace messages and
3938 :     useful output.
3939 :    
3940 :     =over 4
3941 :    
3942 :     =item webData
3943 :    
3944 :     A string containing either the full web page to be written to the output or the
3945 :     name of a template file from which the page is to be constructed. If the name
3946 :     of a template file is specified, then the second parameter must be present;
3947 :     otherwise, it must be absent.
3948 :    
3949 :     =item varHash (optional)
3950 :    
3951 :     If specified, then a reference to a hash mapping variable names for a template
3952 :     to their values. The template file will be read into memory, and variable markers
3953 :     will be replaced by data in this hash reference.
3954 :    
3955 :     =back
3956 :    
3957 :     =cut
3958 :    
3959 :     sub ScriptFinish {
3960 :     # Get the parameters.
3961 :     my ($webData, $varHash) = @_;
3962 :     # Check for a template file situation.
3963 :     my $outputString;
3964 :     if (defined $varHash) {
3965 :     # Here we have a template file. We need to determine the template type.
3966 :     my $template;
3967 :     if ($FIG_Config::template_url && $webData =~ /\.php$/) {
3968 :     $template = "$FIG_Config::template_url/$webData";
3969 :     } else {
3970 :     $template = "<<$webData";
3971 :     }
3972 :     $outputString = PageBuilder::Build($template, $varHash, "Html");
3973 :     } else {
3974 :     # Here the user gave us a raw string.
3975 :     $outputString = $webData;
3976 :     }
3977 :     # Check for trace messages.
3978 :     if ($Destination ne "NONE" && $TraceLevel > 0) {
3979 :     # We have trace messages, so we want to put them at the end of the body. This
3980 :     # is either at the end of the whole string or at the beginning of the BODY
3981 :     # end-tag.
3982 :     my $pos = length $outputString;
3983 :     if ($outputString =~ m#</body>#gi) {
3984 :     $pos = (pos $outputString) - 7;
3985 :     }
3986 :     # If the trace messages were queued, we unroll them. Otherwise, we display the
3987 :     # destination.
3988 :     my $traceHtml;
3989 :     if ($Destination eq "QUEUE") {
3990 :     $traceHtml = QTrace('Html');
3991 :     } elsif ($Destination =~ /^>>(.+)$/) {
3992 :     # Here the tracing output it to a file. We code it as a hyperlink so the user
3993 :     # can copy the file name into the clipboard easily.
3994 :     my $actualDest = $1;
3995 :     $traceHtml = "<p>Tracing output to $actualDest.</p>\n";
3996 :     } else {
3997 :     # Here we have one of the special destinations.
3998 :     $traceHtml = "<P>Tracing output type is $Destination.</p>\n";
3999 :     }
4000 :     substr $outputString, $pos, 0, $traceHtml;
4001 :     }
4002 :     # Write the output string.
4003 :     print $outputString;
4004 :     }
4005 :    
4006 : parrello 1.65 =head3 GenerateURL
4007 :    
4008 : parrello 1.92 my $queryUrl = Tracer::GenerateURL($page, %parameters);
4009 : parrello 1.65
4010 :     Generate a GET-style URL for the specified page with the specified parameter
4011 :     names and values. The values will be URL-escaped automatically. So, for
4012 :     example
4013 :    
4014 :     Tracer::GenerateURL("form.cgi", type => 1, string => "\"high pass\" or highway")
4015 :    
4016 :     would return
4017 :    
4018 : parrello 1.79 form.cgi?type=1;string=%22high%20pass%22%20or%20highway
4019 : parrello 1.65
4020 :     =over 4
4021 :    
4022 :     =item page
4023 :    
4024 :     Page URL.
4025 :    
4026 :     =item parameters
4027 :    
4028 :     Hash mapping parameter names to parameter values.
4029 :    
4030 :     =item RETURN
4031 :    
4032 :     Returns a GET-style URL that goes to the specified page and passes in the
4033 :     specified parameters and values.
4034 :    
4035 :     =back
4036 :    
4037 :     =cut
4038 :    
4039 :     sub GenerateURL {
4040 :     # Get the parameters.
4041 :     my ($page, %parameters) = @_;
4042 :     # Prime the return variable with the page URL.
4043 :     my $retVal = $page;
4044 :     # Loop through the parameters, creating parameter elements in a list.
4045 :     my @parmList = map { "$_=" . uri_escape($parameters{$_}) } keys %parameters;
4046 :     # If the list is nonempty, tack it on.
4047 :     if (@parmList) {
4048 : parrello 1.79 $retVal .= "?" . join(";", @parmList);
4049 : parrello 1.65 }
4050 :     # Return the result.
4051 :     return $retVal;
4052 :     }
4053 :    
4054 : parrello 1.78 =head3 ApplyURL
4055 :    
4056 : parrello 1.92 Tracer::ApplyURL($table, $target, $url);
4057 : parrello 1.78
4058 :     Run through a two-dimensional table (or more accurately, a list of lists), converting the
4059 :     I<$target> column to HTML text having a hyperlink to a URL in the I<$url> column. The
4060 :     URL column will be deleted by this process and the target column will be HTML-escaped.
4061 :    
4062 :     This provides a simple way to process the results of a database query into something
4063 :     displayable by combining a URL with text.
4064 :    
4065 :     =over 4
4066 :    
4067 :     =item table
4068 :    
4069 :     Reference to a list of lists. The elements in the containing list will be updated by
4070 :     this method.
4071 :    
4072 :     =item target
4073 :    
4074 :     The index of the column to be converted into HTML.
4075 :    
4076 :     =item url
4077 :    
4078 :     The index of the column containing the URL. Note that the URL must have a recognizable
4079 :     C<http:> at the beginning.
4080 :    
4081 :     =back
4082 :    
4083 :     =cut
4084 :    
4085 :     sub ApplyURL {
4086 :     # Get the parameters.
4087 :     my ($table, $target, $url) = @_;
4088 :     # Loop through the table.
4089 :     for my $row (@{$table}) {
4090 :     # Apply the URL to the target cell.
4091 :     $row->[$target] = CombineURL($row->[$target], $row->[$url]);
4092 :     # Delete the URL from the row.
4093 :     delete $row->[$url];
4094 :     }
4095 :     }
4096 :    
4097 :     =head3 CombineURL
4098 :    
4099 : parrello 1.92 my $combinedHtml = Tracer::CombineURL($text, $url);
4100 : parrello 1.78
4101 :     This method will convert the specified text into HTML hyperlinked to the specified
4102 :     URL. The hyperlinking will only take place if the URL looks legitimate: that is, it
4103 :     is defined and begins with an C<http:> header.
4104 :    
4105 :     =over 4
4106 :    
4107 :     =item text
4108 :    
4109 :     Text to return. This will be HTML-escaped automatically.
4110 :    
4111 :     =item url
4112 :    
4113 :     A URL to be hyperlinked to the text. If it does not look like a URL, then the text
4114 :     will be returned without any hyperlinking.
4115 :    
4116 :     =item RETURN
4117 :    
4118 :     Returns the original text, HTML-escaped, with the URL hyperlinked to it. If the URL
4119 :     doesn't look right, the HTML-escaped text will be returned without any further
4120 :     modification.
4121 :    
4122 :     =back
4123 :    
4124 :     =cut
4125 :    
4126 :     sub CombineURL {
4127 :     # Get the parameters.
4128 :     my ($text, $url) = @_;
4129 :     # Declare the return variable.
4130 :     my $retVal = CGI::escapeHTML($text);
4131 :     # Verify the URL.
4132 :     if (defined($url) && $url =~ m!http://!i) {
4133 :     # It's good, so we apply it to the text.
4134 :     $retVal = "<a href=\"$url\">$retVal</a>";
4135 :     }
4136 :     # Return the result.
4137 :     return $retVal;
4138 :     }
4139 :    
4140 : parrello 1.97 =head3 TrackingCode
4141 :    
4142 :     my $html = Tracer::TrackingCode();
4143 :    
4144 :     Returns the HTML code for doing web page traffic monitoring. If the
4145 :     current environment is a test system, then it returns a null string;
4146 :     otherwise, it returns a bunch of javascript containing code for turning
4147 :     on SiteMeter and Google Analytics.
4148 :    
4149 :     =cut
4150 :    
4151 :     sub TrackingCode {
4152 :     # Declare the return variable.
4153 :     my $retVal = "<!-- tracking off -->";
4154 :     # Determine if we're in production.
4155 :     if ($FIG_Config::site_meter) {
4156 :     $retVal = <<END_HTML
4157 :     <!-- Site Meter -->
4158 :     <script type="text/javascript" src="http://s20.sitemeter.com/js/counter.js?site=s20nmpdr">
4159 :     </script>
4160 :     <noscript>
4161 :     <a href="http://s20.sitemeter.com/stats.asp?site=s20nmpdr" target="_top">
4162 :     <img src="http://s20.sitemeter.com/meter.asp?site=s20nmpdr" alt="Site Meter" border="0"/></a>
4163 :     </noscript>
4164 :     <!-- Copyright (c)2006 Site Meter -->
4165 :     END_HTML
4166 :     }
4167 :     return $retVal;
4168 :     }
4169 :    
4170 : parrello 1.105 =head3 Clean
4171 :