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

Diff of /FigKernelPackages/Tracer.pm

Parent Directory Parent Directory | Revision Log Revision Log | View Patch Patch

revision 1.2, Wed Jan 19 18:50:48 2005 UTC revision 1.79, Thu Nov 9 21:12:46 2006 UTC
# Line 1  Line 1 
1    #
2    # Copyright (c) 2003-2006 University of Chicago and Fellowship
3    # for Interpretations of Genomes. All Rights Reserved.
4    #
5    # This file is part of the SEED Toolkit.
6    #
7    # The SEED Toolkit is free software. You can redistribute
8    # it and/or modify it under the terms of the SEED Toolkit
9    # Public License.
10    #
11    # You should have received a copy of the SEED Toolkit Public License
12    # along with this program; if not write to the University of Chicago
13    # at info@ci.uchicago.edu or the Fellowship for Interpretation of
14    # Genomes at veronika@thefig.info or download a copy from
15    # http://www.theseed.org/LICENSE.TXT.
16    #
17    
18  package Tracer;  package Tracer;
19    
20          require Exporter;          require Exporter;
21          @ISA = ('Exporter');          @ISA = ('Exporter');
22          @EXPORT = qw(Trace T TSetup QTrace Confess Cluck);      @EXPORT = qw(Trace T TSetup QTrace Confess Cluck Min Max Assert Open OpenDir TICK StandardSetup EmergencyKey ETracing ScriptSetup ScriptFinish Insure ChDir Emergency);
23          @EXPORT_OK = qw(GetFile GetOptions Merge MergeOptions ParseCommand ParseRecord UnEscape);      @EXPORT_OK = qw(GetFile GetOptions Merge MergeOptions ParseCommand ParseRecord UnEscape Escape);
24          use strict;          use strict;
25          use Carp qw(longmess croak);          use Carp qw(longmess croak);
26          use CGI;          use CGI;
27        use Cwd;
28        use FIG_Config;
29        use PageBuilder;
30        use Digest::MD5;
31        use File::Basename;
32        use File::Path;
33        use File::stat;
34        use LWP::UserAgent;
35        use Time::HiRes 'gettimeofday';
36        use URI::Escape;
37        use Time::Local;
38    
39  =head1 Tracing and Debugging Helpers  =head1 Tracing and Debugging Helpers
40    
41  =head2 Introduction  =head2 Tracing
42    
43  This package provides simple tracing for debugging and reporting purposes. To use it simply call the  This package provides simple tracing for debugging and reporting purposes. To use it simply call the
44  L</TSetup> method to set the options and call L</Trace> to write out trace messages. Each trace  L</TSetup> or L</ETracing> method to set the options and call L</Trace> to write out trace messages.
45  message has a I<trace level> and I<category> associated with it. In addition, the tracing package itself  L</TSetup> and L</ETracing> both establish a I<trace level> and a list of I<categories>. Similarly,
46  has a list of categories and a single trace level set by the B<TSetup> method. Only messages whose trace  each trace message has a I<trace level> and I<category> associated with it. Only messages whose trace
47  level is less than or equal to this package's trace level and whose category is activated will  level is less than or equal to the setup trace level and whose category is activated will
48  be written. Thus, a higher trace level on a message indicates that the message  be written. Thus, a higher trace level on a message indicates that the message
49  is less likely to be seen. A higher trace level passed to B<Setup> means more trace messages will  is less likely to be seen, while a higher trace level passed to B<TSetup> means more trace messages will
50  appear. To generate a trace message, use the following syntax.  appear.
51    
52    =head3 Putting Trace Messages in Your Code
53    
54  C<< Trace($message) if T(errors => 4); >>  To generate a trace message, use the following syntax.
55    
56        Trace($message) if T(errors => 4);
57    
58  This statement will produce a trace message if the trace level is 4 or more and the C<errors>  This statement will produce a trace message if the trace level is 4 or more and the C<errors>
59  category is active. Note that the special category C<root> is always active, so  category is active. There is a special category C<main> that is always active, so
60    
61  C<< Trace($message) if T(root => 4); >>      Trace($message) if T(main => 4);
62    
63  will trace if the trace level is 4 or more.  will trace if the trace level is 4 or more.
64    
# Line 34  Line 66 
66  following call is made in the B<Sprout> package, it will appear if the C<Sprout> category is  following call is made in the B<Sprout> package, it will appear if the C<Sprout> category is
67  active and the trace level is 2 or more.  active and the trace level is 2 or more.
68    
69  C<< Trace($message) if T(2); >>      Trace($message) if T(2);
70    
71    In scripts, where no package name is available, the category defaults to C<main>.
72    
73  To set up tracing, you call the C</Setup> method. The method takes as input a trace level, a list  =head3 Custom Tracing
74  of category names, and a set of options. The trace level and list of category names are  
75    Many programs have customized tracing configured using the L</TSetup> method. This is no longer
76    the preferred method, but a knowledge of how custom tracing works can make the more modern
77    L</Emergency Tracing> easier to understand.
78    
79    To set up custom tracing, you call the L</TSetup> method. The method takes as input a trace level,
80    a list of category names, and a destination. The trace level and list of category names are
81  specified as a space-delimited string. Thus  specified as a space-delimited string. Thus
82    
83  C<< TSetup('3 errors Sprout ERDB', 'HTML'); >>      TSetup('3 errors Sprout ERDB', 'TEXT');
84    
85    sets the trace level to 3, activates the C<errors>, C<Sprout>, and C<ERDB> categories, and
86    specifies that messages should be sent to the standard output.
87    
88    To turn on tracing for ALL categories, use an asterisk. The call below sets every category to
89    level 3 and writes the output to the standard error output. This sort of thing might be
90    useful in a CGI environment.
91    
92  sets the trace level to 3, activated the C<errors>, C<Sprout>, and C<ERDB> categories, and      TSetup('3 *', 'WARN');
 specifies that messages should be output as HTML paragraphs. The idea is to make it easier to  
 input tracing configuration on a web form.  
93    
94  In addition to HTML and file output for trace messages, you can specify that the trace messages  In addition standard error and file output for trace messages, you can specify that the trace messages
95  be queued. The messages can then be retrieved by calling the L</QTrace> method. This approach  be queued. The messages can then be retrieved by calling the L</QTrace> method. This approach
96  is useful if you are building a web page. Instead of having the trace messages interspersed with  is useful if you are building a web page. Instead of having the trace messages interspersed with
97  the page output, they can be gathered together and displayed at the end of the page. This makes  the page output, they can be gathered together and displayed at the end of the page. This makes
98  it easier to debug page formatting problems.  it easier to debug page formatting problems.
99    
100    Finally, you can specify that all trace messages be emitted to a file, or the standard output and
101    a file at the same time. To trace to a file, specify the filename with an output character in front
102    of it.
103    
104        TSetup('4 SQL', ">$fileName");
105    
106    To trace to the standard output and a file at the same time, put a C<+> in front of the angle
107    bracket.
108    
109        TSetup('3 *', "+>$fileName");
110    
111  The flexibility of tracing makes it superior to simple use of directives like C<die> and C<warn>.  The flexibility of tracing makes it superior to simple use of directives like C<die> and C<warn>.
112  Tracer calls can be left in the code with minimal overhead and then turned on only when needed.  Tracer calls can be left in the code with minimal overhead and then turned on only when needed.
113  Thus, debugging information is available and easily retrieved even when the application is  Thus, debugging information is available and easily retrieved even when the application is
114  being used out in the field.  being used out in the field.
115    
116    =head3 Trace Levels
117    
118    There is no hard and fast rule on how to use trace levels. The following is therefore only
119    a suggestion.
120    
121    =over 4
122    
123    =item Error 0
124    
125    Message indicates an error that may lead to incorrect results or that has stopped the
126    application entirely.
127    
128    =item Warning 1
129    
130    Message indicates something that is unexpected but that probably did not interfere
131    with program execution.
132    
133    =item Notice 2
134    
135    Message indicates the beginning or end of a major task.
136    
137    =item Information 3
138    
139    Message indicates a subtask. In the FIG system, a subtask generally relates to a single
140    genome. This would be a big loop that is not expected to execute more than 500 times or so.
141    
142    =item Detail 4
143    
144    Message indicates a low-level loop iteration.
145    
146    =back
147    
148    The format of trace messages is important because some utilities analyze trace files.
149    There are three fields-- the time stamp, the category name, and the text.
150    The time stamp is between square brackets and the category name between angle brackets.
151    After the category name there is a colon (C<:>) followed by the message text.
152    If the square brackets or angle brackets are missing, then the trace management
153    utilities assume that they are encountering a set of pre-formatted lines.
154    
155    Note, however, that this formatting is done automatically by the tracing functions. You
156    only need to know about it if you want to parse a trace file.
157    
158    =head3 Emergency Tracing
159    
160    Sometimes, you need a way for tracing to happen automatically without putting parameters
161    in a form or on the command line. Emergency tracing does this. You invoke emergency tracing
162    from the debug form, which is accessed from I<MySeedInstance>C</FIG/Html/SetPassword.html>.
163    Emergency tracing requires you specify a tracing key. For command-line tools, the key is
164    taken from the C<TRACING> environment variable. For web services, the key is taken from
165    a cookie. Either way, the key tells the tracing facility who you are, so that you control
166    the tracing in your environment without stepping on other users.
167    
168    The key can be anything you want. If you don't have a key, the C<SetPassword> page will
169    generate one for you.
170    
171    You can activate and de-activate emergency tracing from the debugging control panel, as
172    well as display the trace file itself.
173    
174    To enable emergency tracing in your code, call
175    
176        ETracing($cgi)
177    
178    from a web script and
179    
180        ETracing()
181    
182    from a command-line script.
183    
184    The web script will look for the tracing key in the cookies, and the command-line
185    script will look for it in the C<TRACING> environment variable. If you are
186    using the L</StandardScript> or L</StandardSetup> methods, emergency tracing
187    will be configured automatically.
188    
189    =head3 Debugging Control Panel
190    
191    The debugging control panel provides several tools to assist in development of
192    SEED and Sprout software. You access the debugging control panel from the URL
193    C</FIG/Html/SetPassword.html> in whichever seed instance you're using. (So,
194    for example, the panel access point for the development NMPDR system is
195    C<http://web-1.nmpdr.org/next/FIG/Html/SetPassword.html>. Contact Bruce to
196    find out what the password is. From this page, you can also specify a tracing
197    key. If you don't specify a key, one will be generated for you.
198    
199    =head4 Emergency Tracing Form
200    
201    At the bottom of the debugging control panel is a form that allows you to
202    specify a trace level and tracing categories. Special and common categories
203    are listed with check boxes. You can hold your mouse over a check box to see
204    what its category does. In general, however, a category name is the same as
205    the name of the package in which the trace message occurs.
206    
207    Additional categories can be entered in an input box, delimited by spaces or commas.
208    
209    The B<Activate> button turns on Emergency tracing at the level you specify with the
210    specified categories active. The B<Terminate> button turns tracing off. The
211    B<Show File> button displays the current contents of the trace file. The tracing
212    form at the bottom of the control panel is designed for emergency tracing, so it
213    will only affect programs that call L</ETracing>, L</StandardScript>,
214    or L</StandardSetup>.
215    
216    =head4 Script Form
217    
218    The top form of the debugging control panel allows you to enter a tiny script and
219    have the output generated in a formatted table. Certain object variables are
220    predefined in the script, including a FIG object (C<$fig>), a CGI object (C<$cgi>),
221    and-- if Sprout is active-- Sprout (C<$sprout>) and SFXlate (C<$sfx>) objects.
222    
223    The last line of the script must be a scalar, but it can be a reference to a hash,
224    a list, a list of lists, and various other combinations. If you select the appropriate
225    data type in the dropdown box, the output will be formatted accordingly. The form
226    also has controls for specifying tracing. These controls override any emergency
227    tracing in effect.
228    
229    =head4 Database Query Forms
230    
231    The forms between the script form and the emergency tracing form allow you to
232    make queries against the database. The FIG query form allows simple queries against
233    a single FIG table. The Sprout query form uses the B<GetAll> method to do a
234    multi-table query against the Sprout database. B<GetAll> is located in the B<ERDB>
235    package, and it takes five parameters.
236    
237        GetAll(\@objectNames, $filterClause, \@parameters, \@fields, $count);
238    
239    Each of the five parameters corresponds to a text box on the query form:
240    
241    =over 4
242    
243    =item Objects
244    
245    Comma-separated list containing the names of the entity and relationship objects to be retrieved.
246    
247    =item Filter
248    
249    WHERE/ORDER BY clause (without the WHERE) to be used to filter and sort the query. The WHERE clause can
250    be parameterized with parameter markers (C<?>). Each field used must be specified in the standard form
251    B<I<objectName>(I<fieldName>)> or B<$I<number>(I<fieldName>)> where I<fieldName> is the name of a
252    field, I<objectName> is the name of the entity or relationship object containing the field, and
253    I<number> is the 1-based position of the object in the object list. Any parameters
254    specified in the filter clause should be specified in the B<Params> field.
255    The fields in a filter clause can come from primary entity relations,
256    relationship relations, or secondary entity relations; however, all of the
257    entities and relationships involved must be included in the list of object names.
258    
259    =item Params
260    
261    List of the parameters to be substituted in for the parameters marks in the filter clause. This
262    is a comma-separated list without any quoting or escaping.
263    
264    =item fields
265    
266    Comma-separated list of the fields to be returned in each element of the list returned. Fields
267    are specified in the same manner as in the filter clause.
268    
269    =item count
270    
271    Maximum number of records to return. If omitted or 0, all available records will be returned.
272    
273    =back
274    
275    B<GetAll> automatically joins together the entities and relationships listed in the object
276    names. This simplifies the coding of the filter clause, but it means that some queries are
277    not possible, since they cannot be expressed in a linear sequence of joins. This is a limitation
278    that has yet to be addressed.
279    
280  =cut  =cut
281    
282  # Declare the configuration variables.  # Declare the configuration variables.
283    
284  my $Destination = "NONE";       # Description of where to send the trace output.  my $Destination = "NONE";       # Description of where to send the trace output.
285  my %Categories = ( root => 1 );  my $TeeFlag = 0;            # TRUE if output is going to a file and to the
286                                # standard output
287    my %Categories = ( main => 1 );
288                                                          # hash of active category names                                                          # hash of active category names
289  my $TraceLevel = 0;                     # trace level; a higher trace level produces more  my $TraceLevel = 0;                     # trace level; a higher trace level produces more
290                                                          # messages                                                          # messages
291  my @Queue = ();                         # queued list of trace messages.  my @Queue = ();                         # queued list of trace messages.
292    my $LastCategory = "main";  # name of the last category interrogated
293    my $SetupCount = 0;         # number of times TSetup called
294    my $AllTrace = 0;           # TRUE if we are tracing all categories.
295    
296  =head2 Public Methods  =head2 Public Methods
297    
# Line 88  Line 313 
313    
314  The destination for the trace output. To send the trace output to a file, specify the file  The destination for the trace output. To send the trace output to a file, specify the file
315  name preceded by a ">" symbol. If a double symbol is used (">>"), then the data is appended  name preceded by a ">" symbol. If a double symbol is used (">>"), then the data is appended
316  to the file. Otherwise the file is cleared before tracing begins. In addition to sending  to the file. Otherwise the file is cleared before tracing begins. Precede the first ">"
317  the trace messages to a file, you can specify XX special destinations. C<HTML> will  symbol with a C<+> to echo output to a file AND to the standard output. In addition to
318    sending the trace messages to a file, you can specify a special destination. C<HTML> will
319  cause tracing to the standard output with each line formatted as an HTML paragraph. C<TEXT>  cause tracing to the standard output with each line formatted as an HTML paragraph. C<TEXT>
320  will cause tracing to the standard output as ordinary text. C<QUEUE> will cause trace messages  will cause tracing to the standard output as ordinary text. C<ERROR> will cause trace
321  to be stored in a queue for later retrieval by the L</QTrace> method. C<NONE> will cause  messages to be sent to the standard error output as ordinary text. C<QUEUE> will cause trace
322  tracing to be suppressed.  messages to be stored in a queue for later retrieval by the L</QTrace> method. C<WARN> will
323    cause trace messages to be emitted as warnings using the B<warn> directive.  C<NONE> will
324    cause tracing to be suppressed.
325    
326  =back  =back
327    
# Line 106  Line 334 
334          my @categoryData = split /\s+/, $categoryList;          my @categoryData = split /\s+/, $categoryList;
335          # Extract the trace level.          # Extract the trace level.
336          $TraceLevel = shift @categoryData;          $TraceLevel = shift @categoryData;
337          # Build the category hash.      # Presume category-based tracing until we learn otherwise.
338        $AllTrace = 0;
339        # Build the category hash. Note that if we find a "*", we turn on non-category
340        # tracing. We must also clear away any pre-existing data.
341        %Categories = ( main => 1 );
342          for my $category (@categoryData) {          for my $category (@categoryData) {
343                  $Categories{$category} = 1;          if ($category eq '*') {
344                $AllTrace = 1;
345            } else {
346                $Categories{lc $category} = 1;
347            }
348          }          }
349          # Now we need to process the destination information. The most important special          # Now we need to process the destination information. The most important special
350          # case is the single ">", which requires we clear the file first. After doing      # cases are the single ">", which requires we clear the file first, and the
351          # so, we tack on another ">" sign so that future trace messages are appended.      # "+" prefix which indicates a double echo.
352        if ($target =~ m/^\+?>>?/) {
353            if ($target =~ m/^\+/) {
354                $TeeFlag = 1;
355                $target = substr($target, 1);
356            }
357          if ($target =~ m/^>[^>]/) {          if ($target =~ m/^>[^>]/) {
358                  open TRACEFILE, $target;                  open TRACEFILE, $target;
359                  print TRACEFILE Now() . " Tracing initialized.\n";              print TRACEFILE "[" . Now() . "] <Tracer>: Tracing initialized.\n";
360                  close TRACEFILE;                  close TRACEFILE;
361                  $Destination = ">$target";                  $Destination = ">$target";
362          } else {          } else {
363                $Destination = $target;
364            }
365        } else {
366                  $Destination = uc($target);                  $Destination = uc($target);
367          }          }
368        # Increment the setup counter.
369        $SetupCount++;
370  }  }
371    
372  =head3 Now  =head3 StandardSetup
373    
374  C<< my $string = Tracer::Now(); >>  C<< my ($options, @parameters) = StandardSetup(\@categories, \%options, $parmHelp, @ARGV); >>
375    
376  Return a displayable time stamp containing the local time.  This method performs standard command-line parsing and tracing setup. The return
377    values are a hash of the command-line options and a list of the positional
378    parameters. Tracing is automatically set up and the command-line options are
379    validated.
380    
381  =cut  This is a complex method that does a lot of grunt work. The parameters can
382    be more easily understood, however, once they are examined individually.
383    
384  sub Now {  The I<categories> parameter is the most obtuse. It is a reference to a list of
385          my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = localtime(time);  special-purpose tracing categories. Most tracing categories are PERL package
386          my $retVal = _p2($mon+1) . "/" . _p2($mday) . "/" . ($year + 1900) . " " .  names. So, for example, if you wanted to turn on tracing inside the B<Sprout>,
387                                   _p2($hour) . ":" . _p2($min) . ":" . _p2($sec);  B<ERDB>, and B<SproutLoad> packages, you would specify the categories
         return $retVal;  
 }  
388    
389  # Pad a number to 2 digits.      ["Sprout", "SproutLoad", "ERDB"]
 sub _p2 {  
         my ($value) = @_;  
         $value = "0$value" if ($value < 10);  
         return $value;  
 }  
390    
391  =head3 LogErrors  This would cause trace messages in the specified three packages to appear in
392    the output. There are two special tracing categories that are automatically
393    handled by this method. In other words, if you used L</TSetup> you would need
394    to include these categories manually, but if you use this method they are turned
395    on automatically.
396    
397  C<< Tracer::LogErrors($fileName); >>  =over 4
398    
399  Route the standard error output to a log file.  =item SQL
400    
401  =over 4  Traces SQL commands and activity.
402    
403  =item fileName  =item Tracer
404    
405  Name of the file to receive the error output.  Traces error messages and call stacks.
406    
407  =back  =back
408    
409  =cut  C<SQL> is only turned on if the C<-sql> option is specified in the command line.
410    The trace level is specified using the C<-trace> command-line option. For example,
411    the following command line for C<TransactFeatures> turns on SQL tracing and runs
412    all tracing at level 3.
413    
414  sub LogErrors {      TransactFeatures -trace=3 -sql register ../xacts IDs.tbl
         # Get the file name.  
         my ($fileName) = @_;  
         # Open the file as the standard error output.  
         open STDERR, '>', $fileName;  
 }  
415    
416  =head3 GetOptions  Standard tracing is output to the standard output and echoed to the file
417    C<trace>I<$$>C<.log> in the FIG temporary directory, where I<$$> is the
418    process ID. You can also specify the C<user> parameter to put a user ID
419    instead of a process ID in the trace file name. So, for example
420    
421  C<< Tracer::GetOptions(\%defaults, \%options); >>  The default trace level is 2. To get all messages, specify a trace level of 4.
422    For a genome-by-genome update, use 3.
423    
424  Merge a specified set of options into a table of defaults. This method takes two hash references      TransactFeatures -trace=3 -sql -user=Bruce register ../xacts IDs.tbl
 as input and uses the data from the second to update the first. If the second does not exist,  
 there will be no effect. An error will be thrown if one of the entries in the second hash does not  
 exist in the first.  
425    
426  Consider the following example.  would send the trace output to C<traceBruce.log> in the temporary directory.
427    
428  C<< my $optionTable = GetOptions({ dbType => 'mySQL', trace => 0 }, $options); >>  The I<options> parameter is a reference to a hash containing the command-line
429    options, their default values, and an explanation of what they mean. Command-line
430    options may be in the form of switches or keywords. In the case of a switch, the
431    option value is 1 if it is specified and 0 if it is not specified. In the case
432    of a keyword, the value is separated from the option name by an equal sign. You
433    can see this last in the command-line example above.
434    
435  In this example, the variable B<$options> is expected to contain at most two options-- B<dbType> and  You can specify a different default trace level by setting C<$options->{trace}>
436  B<trace>. The default database type is C<mySQL> and the default trace level is C<0>. If the value of  prior to calling this method.
 B<$options> is C<< {dbType => 'Oracle'} >>, then the database type will be changed to C<Oracle> and  
 the trace level will remain at 0. If B<$options> is undefined, then the database type and trace level  
 will remain C<mySQL> and C<0>. If, on the other hand, B<$options> is defined as  
437    
438  C<< {databaseType => 'Oracle'} >>  An example at this point would help. Consider, for example, the command-line utility
439    C<TransactFeatures>. It accepts a list of positional parameters plus the options
440    C<safe>, C<noAlias>, C<start>, and C<tblFiles>. To start up this command, we execute
441    the following code.
442    
443  an error will occur because the B<databaseType> option does not exist.      my ($options, @parameters) = Tracer::StandardSetup(["DocUtils"],
444                            { safe => [0, "use database transactions"],
445                              noAlias => [0, "do not expect aliases in CHANGE transactions"],
446                              start => [' ', "start with this genome"],
447                              tblFiles => [0, "output TBL files containing the corrected IDs"] },
448                            "command transactionDirectory IDfile",
449                          @ARGV);
450    
451    
452    The call to C<ParseCommand> specifies the default values for the options and
453    stores the actual options in a hash that is returned as C<$options>. The
454    positional parameters are returned in C<@parameters>.
455    
456    The following is a sample command line for C<TransactFeatures>.
457    
458        TransactFeatures -trace=2 -noAlias register ../xacts IDs.tbl
459    
460    In this case, C<register>, C<../xacts>, and C<IDs.tbl> are the positional
461    parameters, and would find themselves in I<@parameters> after executing the
462    above code fragment. The tracing would be set to level 2, and the categories
463    would be C<Tracer>, and <DocUtils>. C<Tracer> is standard,
464    and C<DocUtils> was included because it came in within the first parameter
465    to this method. The I<$options> hash would be
466    
467        { trace => 2, sql => 0, safe => 0,
468          noAlias => 1, start => ' ', tblFiles => 0 }
469    
470    Use of C<StandardSetup> in this way provides a simple way of performing
471    standard tracing setup and command-line parsing. Note that the caller is
472    not even aware of the command-line switches C<-trace> and C<-sql>, which
473    are used by this method to control the tracing. If additional tracing features
474    need to be added in the future, they can be processed by this method without
475    upsetting the command-line utilities.
476    
477    If the C<background> option is specified on the command line, then the
478    standard and error outputs will be directed to files in the temporary
479    directory, using the same suffix as the trace file. So, if the command
480    line specified
481    
482        -user=Bruce -background
483    
484    then the trace output would go to C<traceBruce.log>, the standard output to
485    C<outBruce.log>, and the error output to C<errBruce.log>. This is designed to
486    simplify starting a command in the background.
487    
488    The user name is also used as the tracing key for L</Emergency Tracing>.
489    Specifying a value of C<E> for the trace level causes emergency tracing to
490    be used instead of custom tracing. If the user name is not specified,
491    the tracing key is taken from the C<Tracing> environment variable. If there
492    is no value for that variable, the tracing key will be computed from the PID.
493    
494    Finally, if the special option C<-h> is specified, the option names will
495    be traced at level 0 and the program will exit without processing.
496    This provides a limited help capability. For example, if the user enters
497    
498        TransactFeatures -h
499    
500    he would see the following output.
501    
502        TransactFeatures [options] command transactionDirectory IDfile
503            -trace    tracing level (default E)
504            -sql      trace SQL commands
505            -safe     use database transactions
506            -noAlias  do not expect aliases in CHANGE transactions
507            -start    start with this genome
508            -tblFiles output TBL files containing the corrected IDs
509    
510    The caller has the option of modifying the tracing scheme by placing a value
511    for C<trace> in the incoming options hash. The default value can be overridden,
512    or the tracing to the standard output can be turned off by suffixing a minus
513    sign to the trace level. So, for example,
514    
515        { trace => [0, "tracing level (default 0)"],
516           ...
517    
518    would set the default trace level to 0 instead of E, while
519    
520        { trace => ["2-", "tracing level (default 2)"],
521           ...
522    
523    would set the default to 2, but trace only to the log file, not to the
524    standard output.
525    
526    The parameters to this method are as follows.
527    
528  =over 4  =over 4
529    
530  =item defaults  =item categories
531    
532  Table of default option values.  Reference to a list of tracing category names. These should be names of
533    packages whose internal workings will need to be debugged to get the
534    command working.
535    
536  =item options  =item options
537    
538  Table of overrides, if any.  Reference to a hash containing the legal options for the current command mapped
539    to their default values and descriptions. The user can override the defaults
540    by specifying the options as command-line switches prefixed by a hyphen.
541    Tracing-related options may be added to this hash. If the C<-h> option is
542    specified on the command line, the option descriptions will be used to
543    explain the options. To turn off tracing to the standard output, add a
544    minus sign to the value for C<trace> (see above).
545    
546    =item parmHelp
547    
548    A string that vaguely describes the positional parameters. This is used
549    if the user specifies the C<-h> option.
550    
551    =item argv
552    
553    List of command line parameters, including the option switches, which must
554    precede the positional parameters and be prefixed by a hyphen.
555    
556  =item RETURN  =item RETURN
557    
558  Returns a reference to the default table passed in as the first parameter.  Returns a list. The first element of the list is the reference to a hash that
559    maps the command-line option switches to their values. These will either be the
560    default values or overrides specified on the command line. The remaining
561    elements of the list are the position parameters, in order.
562    
563  =back  =back
564    
565  =cut  =cut
566    
567  sub GetOptions {  sub StandardSetup {
568          # Get the parameters.          # Get the parameters.
569          my ($defaults, $options) = @_;      my ($categories, $options, $parmHelp, @argv) = @_;
570          # Check for overrides.      # Get the default tracing key.
571          if ($options) {      my $tkey = EmergencyKey();
572                  # Loop through the overrides.      # Add the tracing options.
573                  while (my ($option, $setting) = each %{$options}) {      if (! exists $options->{trace}) {
574                          # Insure this override exists.          $options->{trace} = ['E', "tracing level (E for emergency tracing)"];
575                          if (!exists $defaults->{$option}) {      }
576                                  croak "Unrecognized option $option encountered.";      $options->{sql} = [0, "turn on SQL tracing"];
577        $options->{h} = [0, "display command-line options"];
578        $options->{user} = [$tkey, "tracing key"];
579        $options->{background} = [0, "spool standard and error output"];
580        # Create a parsing hash from the options hash. The parsing hash
581        # contains the default values rather than the default value
582        # and the description. While we're at it, we'll memorize the
583        # length of the longest option name.
584        my $longestName = 0;
585        my %parseOptions = ();
586        for my $key (keys %{$options}) {
587            if (length $key > $longestName) {
588                $longestName = length $key;
589            }
590            $parseOptions{$key} = $options->{$key}->[0];
591        }
592        # Parse the command line.
593        my ($retOptions, @retParameters) = ParseCommand(\%parseOptions, @argv);
594        # Get the logfile suffix.
595        my $suffix = $retOptions->{user};
596        # Check for background mode.
597        if ($retOptions->{background}) {
598            my $outFileName = "$FIG_Config::temp/out$suffix.log";
599            my $errFileName = "$FIG_Config::temp/err$suffix.log";
600            open STDOUT, ">$outFileName";
601            open STDERR, ">$errFileName";
602        }
603        # Now we want to set up tracing. First, we need to know if the user
604        # wants emergency tracing.
605        if ($retOptions->{trace} eq 'E') {
606            ETracing($retOptions->{user});
607                          } else {                          } else {
608                                  # Apply the override.          # Here the tracing is controlled from the command line.
609                                  $defaults->{$option} = $setting;          my @cats = @{$categories};
610            if ($retOptions->{sql}) {
611                push @cats, "SQL";
612            }
613            # Add the default categories.
614            push @cats, "Tracer";
615            # Next, we create the category string by joining the categories.
616            my $cats = join(" ", @cats);
617            # Check to determine whether or not the caller wants to turn off tracing
618            # to the standard output.
619            my $traceLevel = $retOptions->{trace};
620            my $textOKFlag = 1;
621            if ($traceLevel =~ /^(.)-/) {
622                $traceLevel = $1;
623                $textOKFlag = 0;
624            }
625            # Now we set up the trace mode.
626            my $traceMode;
627            # Verify that we can open a file in the FIG temporary directory.
628            my $traceFileName = "$FIG_Config::temp/trace$suffix.log";
629            if (open TESTTRACE, ">$traceFileName") {
630                # Here we can trace to a file.
631                $traceMode = ">$traceFileName";
632                if ($textOKFlag) {
633                    # Echo to standard output if the text-OK flag is set.
634                    $traceMode = "+$traceMode";
635                          }                          }
636                # Close the test file.
637                close TESTTRACE;
638            } else {
639                # Here we can't trace to a file. We trace to the standard output if it's
640                # okay, and the error log otherwise.
641                if ($textOKFlag) {
642                    $traceMode = "TEXT";
643                } else {
644                    $traceMode = "WARN";
645                  }                  }
646          }          }
647          # Return the merged table.          # Now set up the tracing.
648          return $defaults;          TSetup("$traceLevel $cats", $traceMode);
649        }
650        # Check for the "h" option. If it is specified, dump the command-line
651        # options and exit the program.
652        if ($retOptions->{h}) {
653            $0 =~ m#[/\\](\w+)(\.pl)?$#i;
654            print "$1 [options] $parmHelp\n";
655            for my $key (sort keys %{$options}) {
656                my $name = Pad($key, $longestName, 0, ' ');
657                my $desc = $options->{$key}->[1];
658                if ($options->{$key}->[0]) {
659                    $desc .= " (default " . $options->{$key}->[0] . ")";
660                }
661                print "  $name $desc\n";
662            }
663            exit(0);
664        }
665        # Return the parsed parameters.
666        return ($retOptions, @retParameters);
667  }  }
668    
669  =head3 MergeOptions  =head3 Setups
670    
671  C<< Tracer::MergeOptions(\%table, \%defaults); >>  C<< my $count = Tracer::Setups(); >>
672    
673  Merge default values into a hash table. This method looks at the key-value pairs in the  Return the number of times L</TSetup> has been called.
674  second (default) hash, and if a matching key is not found in the first hash, the default  
675  pair is copied in. The process is similar to L</GetOptions>, but there is no error-  This method allows for the creation of conditional tracing setups where, for example, we
676  checking and no return value.  may want to set up tracing if nobody else has done it before us.
677    
678    =cut
679    
680    sub Setups {
681        return $SetupCount;
682    }
683    
684    =head3 Open
685    
686    C<< my $handle = Open($fileHandle, $fileSpec, $message); >>
687    
688    Open a file.
689    
690    The I<$fileSpec> is essentially the second argument of the PERL C<open>
691    function. The mode is specified using Unix-like shell information. So, for
692    example,
693    
694        Open(\*LOGFILE, '>>/usr/spool/news/twitlog', "Could not open twit log.");
695    
696    would open for output appended to the specified file, and
697    
698        Open(\*DATASTREAM, "| sort -u >$outputFile", "Could not open $outputFile.");
699    
700    would open a pipe that sorts the records written and removes duplicates. Note
701    the use of file handle syntax in the Open call. To use anonymous file handles,
702    code as follows.
703    
704        my $logFile = Open(undef, '>>/usr/spool/news/twitlog', "Could not open twit log.");
705    
706    The I<$message> parameter is used if the open fails. If it is set to C<0>, then
707    the open returns TRUE if successful and FALSE if an error occurred. Otherwise, a
708    failed open will throw an exception and the third parameter will be used to construct
709    an error message. If the parameter is omitted, a standard message is constructed
710    using the file spec.
711    
712        Could not open "/usr/spool/news/twitlog"
713    
714    Note that the mode characters are automatically cleaned from the file name.
715    The actual error message from the file system will be captured and appended to the
716    message in any case.
717    
718        Could not open "/usr/spool/news/twitlog": file not found.
719    
720    In some versions of PERL the only error message we get is a number, which
721    corresponds to the C++ C<errno> value.
722    
723        Could not open "/usr/spool/news/twitlog": 6.
724    
725  =over 4  =over 4
726    
727  =item table  =item fileHandle
728    
729  Hash table to be updated with the default values.  File handle. If this parameter is C<undef>, a file handle will be generated
730    and returned as the value of this method.
731    
732  =item defaults  =item fileSpec
733    
734  Default values to be merged into the first hash table if they are not already present.  File name and mode, as per the PERL C<open> function.
735    
736    =item message (optional)
737    
738    Error message to use if the open fails. If omitted, a standard error message
739    will be generated. In either case, the error information from the file system
740    is appended to the message. To specify a conditional open that does not throw
741    an error if it fails, use C<0>.
742    
743    =item RETURN
744    
745    Returns the name of the file handle assigned to the file, or C<undef> if the
746    open failed.
747    
748  =back  =back
749    
750  =cut  =cut
751    
752  sub MergeOptions {  sub Open {
753          # Get the parameters.          # Get the parameters.
754          my ($table, $defaults) = @_;      my ($fileHandle, $fileSpec, $message) = @_;
755          # Loop through the defaults.      # Attempt to open the file.
756          while (my ($key, $value) = each %{$defaults}) {      my $rv = open $fileHandle, $fileSpec;
757                  if (!exists $table->{$key}) {      # If the open failed, generate an error message.
758                          $table->{$key} = $value;      if (! $rv) {
759                  }          # Save the system error message.
760          }          my $sysMessage = $!;
761  }          # See if we need a default message.
762            if (!$message) {
763                # Clean any obvious mode characters and leading spaces from the
764                # filename.
765                my ($fileName) = FindNamePart($fileSpec);
766                $message = "Could not open \"$fileName\"";
767            }
768            # Terminate with an error using the supplied message and the
769            # error message from the file system.
770            Confess("$message: $!");
771        }
772        # Return the file handle.
773        return $fileHandle;
774    }
775    
776    =head3 FindNamePart
777    
778    C<< my ($fileName, $start, $len) = Tracer::FindNamePart($fileSpec); >>
779    
780    Extract the portion of a file specification that contains the file name.
781    
782    A file specification is the string passed to an C<open> call. It specifies the file
783    mode and name. In a truly complex situation, it can specify a pipe sequence. This
784    method assumes that the file name is whatever follows the first angle bracket
785    sequence.  So, for example, in the following strings the file name is
786    C</usr/fig/myfile.txt>.
787    
788        >>/usr/fig/myfile.txt
789        </usr/fig/myfile.txt
790        | sort -u > /usr/fig/myfile.txt
791    
792  =head3 Trace  If the method cannot find a file name using its normal methods, it will return the
793    whole incoming string.
794    
795  C<< Trace($message); >>  =over 4
796    
797  Write a trace message to the target location specified in L</TSetup>. If there has not been  =item fileSpec
 any prior call to B<TSetup>.  
798    
799  =over 4  File specification string from which the file name is to be extracted.
800    
801  =item message  =item RETURN
802    
803  Message to write.  Returns a three-element list. The first element contains the file name portion of
804    the specified string, or the whole string if a file name cannot be found via normal
805    methods. The second element contains the start position of the file name portion and
806    the third element contains the length.
807    
808  =back  =back
809    
810  =cut  =cut
811    #: Return Type $;
812  sub Trace {  sub FindNamePart {
813          # Get the parameters.          # Get the parameters.
814          my ($message) = @_;      my ($fileSpec) = @_;
815          # Get the timestamp.      # Default to the whole input string.
816          my $timeStamp = Now();      my ($retVal, $pos, $len) = ($fileSpec, 0, length $fileSpec);
817          # Process according to the destination.      # Parse out the file name if we can.
818          if ($Destination eq "TEXT") {      if ($fileSpec =~ m/(<|>>?)(.+?)(\s*)$/) {
819                  # Write the message to the standard output.          $retVal = $2;
820                  print "$timeStamp $message\n";          $len = length $retVal;
821          } elsif ($Destination eq "QUEUE") {          $pos = (length $fileSpec) - (length $3) - $len;
                 # Push the message into the queue.  
                 push @Queue, "$timeStamp $message";  
         } elsif ($Destination eq "HTML") {  
                 # Convert the message to HTML and write it to the standard output.  
                 my $escapedMessage = CGI::escapeHTML($message);  
                 print "<p>$timeStamp $message</p>\n";  
         } elsif ($Destination =~ m/^>>/) {  
                 # Write the trace message to an output file.  
                 open TRACING, $Destination;  
                 print TRACING "$timeStamp $message\n";  
                 close TRACING;  
822          }          }
823        # Return the result.
824        return ($retVal, $pos, $len);
825  }  }
826    
827  =head3 T  =head3 OpenDir
828    
829  C<< my $switch = T($category, $traceLevel); >>  C<< my @files = OpenDir($dirName, $filtered, $flag); >>
830    
831          or  Open a directory and return all the file names. This function essentially performs
832    the functions of an C<opendir> and C<readdir>. If the I<$filtered> parameter is
833    set to TRUE, all filenames beginning with a period (C<.>), dollar sign (C<$>),
834    or pound sign (C<#>) and all filenames ending with a tilde C<~>) will be
835    filtered out of the return list. If the directory does not open and I<$flag> is not
836    set, an exception is thrown. So, for example,
837    
838  C<< my $switch = T($traceLevel); >>      my @files = OpenDir("/Volumes/fig/contigs", 1);
839    
840  Return TRUE if the trace level is at or above a specified value and the specified category  is effectively the same as
841  is active, else FALSE. If no category is specified, the caller's package name is used.  
842        opendir(TMP, "/Volumes/fig/contigs") || Confess("Could not open /Volumes/fig/contigs.");
843        my @files = grep { $_ !~ /^[\.\$\#]/ && $_ !~ /~$/ } readdir(TMP);
844    
845    Similarly, the following code
846    
847        my @files = grep { $_ =~ /^\d/ } OpenDir("/Volumes/fig/orgs", 0, 1);
848    
849    Returns the names of all files in C</Volumes/fig/orgs> that begin with digits and
850    automatically returns an empty list if the directory fails to open.
851    
852  =over 4  =over 4
853    
854  =item category  =item dirName
855    
856  Category to which the message belongs. If not specified, the caller's package name is  Name of the directory to open.
 used.  
857    
858  =item traceLevel  =item filtered
859    
860  Relevant tracing level.  TRUE if files whose names begin with a period (C<.>) should be automatically removed
861    from the list, else FALSE.
862    
863  =item RETURN  =item flag
864    
865  TRUE if a message at the specified trace level would appear in the trace, else FALSE.  TRUE if a failure to open is okay, else FALSE
866    
867  =back  =back
868    
869  =cut  =cut
870    #: Return Type @;
871  sub T {  sub OpenDir {
872        # Get the parameters.
873        my ($dirName, $filtered, $flag) = @_;
874          # Declare the return variable.          # Declare the return variable.
875          my $retVal = 0;      my @retVal = ();
876        # Open the directory.
877        if (opendir(my $dirHandle, $dirName)) {
878            # The directory opened successfully. Get the appropriate list according to the
879            # strictures of the filter parameter.
880            if ($filtered) {
881                @retVal = grep { $_ !~ /^[\.\$\#]/ && $_ !~ /~$/ } readdir $dirHandle;
882            } else {
883                @retVal = readdir $dirHandle;
884            }
885        } elsif (! $flag) {
886            # Here the directory would not open and it's considered an error.
887            Confess("Could not open directory $dirName.");
888        }
889        # Return the result.
890        return @retVal;
891    }
892    
893    =head3 SetLevel
894    
895    C<< Tracer::SetLevel($newLevel); >>
896    
897    Modify the trace level. A higher trace level will cause more messages to appear.
898    
899    =over 4
900    
901    =item newLevel
902    
903    Proposed new trace level.
904    
905    =back
906    
907    =cut
908    
909    sub SetLevel {
910        $TraceLevel = $_[0];
911    }
912    
913    =head3 Now
914    
915    C<< my $string = Tracer::Now(); >>
916    
917    Return a displayable time stamp containing the local time.
918    
919    =cut
920    
921    sub Now {
922        my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = localtime(time);
923        my $retVal = _p2($mon+1) . "/" . _p2($mday) . "/" . ($year + 1900) . " " .
924                     _p2($hour) . ":" . _p2($min) . ":" . _p2($sec);
925        return $retVal;
926    }
927    
928    # Pad a number to 2 digits.
929    sub _p2 {
930        my ($value) = @_;
931        $value = "0$value" if ($value < 10);
932        return $value;
933    }
934    
935    =head3 ParseTraceDate
936    
937    C<< my $time = Tracer::ParseTraceDate($dateString); >>
938    
939    Convert a date from the trace file into a PERL timestamp.
940    
941    =over 4
942    
943    =item dateString
944    
945    The date string from the trace file. The format of the string is determined by the
946    L</Now> method.
947    
948    =item RETURN
949    
950    Returns a PERL time, that is, a number of seconds since the epoch, or C<undef> if
951    the time string is invalid.
952    
953    =back
954    
955    =cut
956    
957    sub ParseTraceDate {
958        # Get the parameters.
959        my ($dateString) = @_;
960        # Declare the return variable.
961        my $retVal;
962        # Parse the date.
963        if ($dateString =~ m#(\d+)/(\d+)/(\d+)\s+(\d+):(\d+):(\d+)#) {
964            # Create a time object. Note we need to convert the day, month,
965            # and year to a different base. Years count from 1900, and
966            # the internal month value is relocated to January = 0.
967            $retVal = timelocal($6, $5, $4, $2, $1 - 1, $3 - 1900);
968        }
969        # Return the result.
970        return $retVal;
971    }
972    
973    =head3 LogErrors
974    
975    C<< Tracer::LogErrors($fileName); >>
976    
977    Route the standard error output to a log file.
978    
979    =over 4
980    
981    =item fileName
982    
983    Name of the file to receive the error output.
984    
985    =back
986    
987    =cut
988    
989    sub LogErrors {
990        # Get the file name.
991        my ($fileName) = @_;
992        # Open the file as the standard error output.
993        open STDERR, '>', $fileName;
994    }
995    
996    =head3 ReadOptions
997    
998    C<< my %options = Tracer::ReadOptions($fileName); >>
999    
1000    Read a set of options from a file. Each option is encoded in a line of text that has the
1001    format
1002    
1003    I<optionName>C<=>I<optionValue>C<; >I<comment>
1004    
1005    The option name must consist entirely of letters, digits, and the punctuation characters
1006    C<.> and C<_>, and is case sensitive. Blank lines and lines in which the first nonblank
1007    character is a semi-colon will be ignored. The return hash will map each option name to
1008    the corresponding option value.
1009    
1010    =over 4
1011    
1012    =item fileName
1013    
1014    Name of the file containing the option data.
1015    
1016    =item RETURN
1017    
1018    Returns a hash mapping the option names specified in the file to their corresponding option
1019    value.
1020    
1021    =back
1022    
1023    =cut
1024    
1025    sub ReadOptions {
1026        # Get the parameters.
1027        my ($fileName) = @_;
1028        # Open the file.
1029        (open CONFIGFILE, "<$fileName") || Confess("Could not open option file $fileName.");
1030        # Count the number of records read.
1031        my ($records, $comments) = 0;
1032        # Create the return hash.
1033        my %retVal = ();
1034        # Loop through the file, accumulating key-value pairs.
1035        while (my $line = <CONFIGFILE>) {
1036            # Denote we've read a line.
1037            $records++;
1038            # Determine the line type.
1039            if ($line =~ /^\s*[\n\r]/) {
1040                # A blank line is a comment.
1041                $comments++;
1042            } elsif ($line =~ /^\s*([A-Za-z0-9_\.]+)=([^;]*);/) {
1043                # Here we have an option assignment.
1044                retVal{$1} = $2;
1045            } elsif ($line =~ /^\s*;/) {
1046                # Here we have a text comment.
1047                $comments++;
1048            } else {
1049                # Here we have an invalid line.
1050                Trace("Invalid option statement in record $records.") if T(0);
1051            }
1052        }
1053        # Return the hash created.
1054        return %retVal;
1055    }
1056    
1057    =head3 GetOptions
1058    
1059    C<< Tracer::GetOptions(\%defaults, \%options); >>
1060    
1061    Merge a specified set of options into a table of defaults. This method takes two hash references
1062    as input and uses the data from the second to update the first. If the second does not exist,
1063    there will be no effect. An error will be thrown if one of the entries in the second hash does not
1064    exist in the first.
1065    
1066    Consider the following example.
1067    
1068    C<< my $optionTable = GetOptions({ dbType => 'mySQL', trace => 0 }, $options); >>
1069    
1070    In this example, the variable B<$options> is expected to contain at most two options-- B<dbType> and
1071    B<trace>. The default database type is C<mySQL> and the default trace level is C<0>. If the value of
1072    B<$options> is C<< {dbType => 'Oracle'} >>, then the database type will be changed to C<Oracle> and
1073    the trace level will remain at 0. If B<$options> is undefined, then the database type and trace level
1074    will remain C<mySQL> and C<0>. If, on the other hand, B<$options> is defined as
1075    
1076    C<< {databaseType => 'Oracle'} >>
1077    
1078    an error will occur because the B<databaseType> option does not exist.
1079    
1080    =over 4
1081    
1082    =item defaults
1083    
1084    Table of default option values.
1085    
1086    =item options
1087    
1088    Table of overrides, if any.
1089    
1090    =item RETURN
1091    
1092    Returns a reference to the default table passed in as the first parameter.
1093    
1094    =back
1095    
1096    =cut
1097    
1098    sub GetOptions {
1099        # Get the parameters.
1100        my ($defaults, $options) = @_;
1101        # Check for overrides.
1102        if ($options) {
1103            # Loop through the overrides.
1104            while (my ($option, $setting) = each %{$options}) {
1105                # Insure this override exists.
1106                if (!exists $defaults->{$option}) {
1107                    croak "Unrecognized option $option encountered.";
1108                } else {
1109                    # Apply the override.
1110                    $defaults->{$option} = $setting;
1111                }
1112            }
1113        }
1114        # Return the merged table.
1115        return $defaults;
1116    }
1117    
1118    =head3 MergeOptions
1119    
1120    C<< Tracer::MergeOptions(\%table, \%defaults); >>
1121    
1122    Merge default values into a hash table. This method looks at the key-value pairs in the
1123    second (default) hash, and if a matching key is not found in the first hash, the default
1124    pair is copied in. The process is similar to L</GetOptions>, but there is no error-
1125    checking and no return value.
1126    
1127    =over 4
1128    
1129    =item table
1130    
1131    Hash table to be updated with the default values.
1132    
1133    =item defaults
1134    
1135    Default values to be merged into the first hash table if they are not already present.
1136    
1137    =back
1138    
1139    =cut
1140    
1141    sub MergeOptions {
1142        # Get the parameters.
1143        my ($table, $defaults) = @_;
1144        # Loop through the defaults.
1145        while (my ($key, $value) = each %{$defaults}) {
1146            if (!exists $table->{$key}) {
1147                $table->{$key} = $value;
1148            }
1149        }
1150    }
1151    
1152    =head3 Trace
1153    
1154    C<< Trace($message); >>
1155    
1156    Write a trace message to the target location specified in L</TSetup>. If there has not been
1157    any prior call to B<TSetup>.
1158    
1159    =over 4
1160    
1161    =item message
1162    
1163    Message to write.
1164    
1165    =back
1166    
1167    =cut
1168    
1169    sub Trace {
1170        # Get the parameters.
1171        my ($message) = @_;
1172        # Get the timestamp.
1173        my $timeStamp = Now();
1174        # Format the message. Note we strip off any line terminators at the end.
1175        my $formatted = "[$timeStamp] <$LastCategory>: " . Strip($message);
1176        # Process according to the destination.
1177        if ($Destination eq "TEXT") {
1178            # Write the message to the standard output.
1179            print "$formatted\n";
1180        } elsif ($Destination eq "ERROR") {
1181            # Write the message to the error output.
1182            print STDERR "$formatted\n";
1183        } elsif ($Destination eq "QUEUE") {
1184            # Push the message into the queue.
1185            push @Queue, "$formatted";
1186        } elsif ($Destination eq "HTML") {
1187            # Convert the message to HTML and write it to the standard output.
1188            my $escapedMessage = CGI::escapeHTML($message);
1189            print "<p>$formatted</p>\n";
1190        } elsif ($Destination eq "WARN") {
1191           # Emit the message as a warning.
1192           warn $message;
1193        } elsif ($Destination =~ m/^>>/) {
1194            # Write the trace message to an output file.
1195            (open TRACING, $Destination) || die "Tracing open for \"$Destination\" failed: $!";
1196            print TRACING "$formatted\n";
1197            close TRACING;
1198            # If the Tee flag is on, echo it to the standard output.
1199            if ($TeeFlag) {
1200                print "$formatted\n";
1201            }
1202        }
1203    }
1204    
1205    =head3 T
1206    
1207    C<< my $switch = T($category, $traceLevel); >>
1208    
1209        or
1210    
1211    C<< my $switch = T($traceLevel); >>
1212    
1213    Return TRUE if the trace level is at or above a specified value and the specified category
1214    is active, else FALSE. If no category is specified, the caller's package name is used.
1215    
1216    =over 4
1217    
1218    =item category
1219    
1220    Category to which the message belongs. If not specified, the caller's package name is
1221    used.
1222    
1223    =item traceLevel
1224    
1225    Relevant tracing level.
1226    
1227    =item RETURN
1228    
1229    TRUE if a message at the specified trace level would appear in the trace, else FALSE.
1230    
1231    =back
1232    
1233    =cut
1234    
1235    sub T {
1236        # Declare the return variable.
1237        my $retVal = 0;
1238          # Only proceed if tracing is turned on.          # Only proceed if tracing is turned on.
1239          if ($Destination ne "NONE") {          if ($Destination ne "NONE") {
1240                  # Get the parameters.                  # Get the parameters.
1241                  my ($category, $traceLevel) = @_;          my ($category, $traceLevel) = @_;
1242                  if (!defined $traceLevel) {          if (!defined $traceLevel) {
1243                          # Here we have no category, so we need to get the calling package.              # Here we have no category, so we need to get the calling package.
1244                          $traceLevel = $category;              # The calling package is normally the first parameter. If it is
1245                          my ($package, $fileName, $line) = caller;              # omitted, the first parameter will be the tracelevel. So, the
1246                          # If there is no calling package, we default to "root".              # first thing we do is shift the so-called category into the
1247                          if (!$package) {              # $traceLevel variable where it belongs.
1248                                  $category = "root";              $traceLevel = $category;
1249                my ($package, $fileName, $line) = caller;
1250                # If there is no calling package, we default to "main".
1251                if (!$package) {
1252                    $category = "main";
1253                } else {
1254                    $category = $package;
1255                }
1256            }
1257            # Save the category name.
1258            $LastCategory = $category;
1259            # Convert it to lower case before we hash it.
1260            $category = lc $category;
1261            # Use the category and tracelevel to compute the result.
1262            if (ref $traceLevel) {
1263                Confess("Bad trace level.");
1264            } elsif (ref $TraceLevel) {
1265                Confess("Bad trace config.");
1266            }
1267            $retVal = ($traceLevel <= $TraceLevel && ($AllTrace || exists $Categories{$category}));
1268        }
1269        # Return the computed result.
1270        return $retVal;
1271    }
1272    
1273    =head3 ParseCommand
1274    
1275    C<< my ($options, @arguments) = Tracer::ParseCommand(\%optionTable, @inputList); >>
1276    
1277    Parse a command line consisting of a list of parameters. The initial parameters may be option
1278    specifiers of the form C<->I<option> or C<->I<option>C<=>I<value>. The options are stripped
1279    off and merged into a table of default options. The remainder of the command line is
1280    returned as a list of positional arguments. For example, consider the following invocation.
1281    
1282    C<< my ($options, @arguments) = ParseCommand({ errors => 0, logFile => 'trace.log'}, @words); >>
1283    
1284    In this case, the list @words will be treated as a command line. There are two options available,
1285    B<errors> and B<logFile>. If @words has the following format
1286    
1287    C<< -logFile=error.log apple orange rutabaga >>
1288    
1289    then at the end of the invocation, C<$options> will be
1290    
1291    C<< { errors => 0, logFile => 'error.log' } >>
1292    
1293    and C<@arguments> will contain
1294    
1295    C<< apple orange rutabaga >>
1296    
1297    The parser allows for some escape sequences. See L</UnEscape> for a description. There is no
1298    support for quote characters.
1299    
1300    =over 4
1301    
1302    =item optionTable
1303    
1304    Table of default options.
1305    
1306    =item inputList
1307    
1308    List of words on the command line.
1309    
1310    =item RETURN
1311    
1312    Returns a reference to the option table and a list of the positional arguments.
1313    
1314    =back
1315    
1316    =cut
1317    
1318    sub ParseCommand {
1319        # Get the parameters.
1320        my ($optionTable, @inputList) = @_;
1321        # Process any options in the input list.
1322        my %overrides = ();
1323        while ((@inputList > 0) && ($inputList[0] =~ /^-/)) {
1324            # Get the current option.
1325            my $arg = shift @inputList;
1326            # Pull out the option name.
1327            $arg =~ /^-([^=]*)/g;
1328            my $name = $1;
1329            # Check for an option value.
1330            if ($arg =~ /\G=(.*)$/g) {
1331                # Here we have a value for the option.
1332                $overrides{$name} = UnEscape($1);
1333            } else {
1334                # Here there is no value, so we use 1.
1335                $overrides{$name} = 1;
1336            }
1337        }
1338        # Merge the options into the defaults.
1339        GetOptions($optionTable, \%overrides);
1340        # Translate the remaining parameters.
1341        my @retVal = ();
1342        for my $inputParm (@inputList) {
1343            push @retVal, UnEscape($inputParm);
1344        }
1345        # Return the results.
1346        return ($optionTable, @retVal);
1347    }
1348    
1349    =head3 Escape
1350    
1351    C<< my $codedString = Tracer::Escape($realString); >>
1352    
1353    Escape a string for use in a command length. Tabs will be replaced by C<\t>, new-lines
1354    replaced by C<\n>, carriage returns will be deleted, and backslashes will be doubled. The
1355    result is to reverse the effect of L</UnEscape>.
1356    
1357    =over 4
1358    
1359    =item realString
1360    
1361    String to escape.
1362    
1363    =item RETURN
1364    
1365    Escaped equivalent of the real string.
1366    
1367    =back
1368    
1369    =cut
1370    
1371    sub Escape {
1372        # Get the parameter.
1373        my ($realString) = @_;
1374        # Initialize the return variable.
1375        my $retVal = "";
1376        # Loop through the parameter string, looking for sequences to escape.
1377        while (length $realString > 0) {
1378            # Look for the first sequence to escape.
1379            if ($realString =~ /^(.*?)([\n\t\r\\])/) {
1380                # Here we found it. The text preceding the sequence is in $1. The sequence
1381                # itself is in $2. First, move the clear text to the return variable.
1382                $retVal .= $1;
1383                # Strip the processed section off the real string.
1384                $realString = substr $realString, (length $2) + (length $1);
1385                # Get the matched character.
1386                my $char = $2;
1387                # If we have a CR, we are done.
1388                if ($char ne "\r") {
1389                    # It's not a CR, so encode the escape sequence.
1390                    $char =~ tr/\t\n/tn/;
1391                    $retVal .= "\\" . $char;
1392                }
1393            } else {
1394                # Here there are no more escape sequences. The rest of the string is
1395                # transferred unmodified.
1396                $retVal .= $realString;
1397                $realString = "";
1398            }
1399        }
1400        # Return the result.
1401        return $retVal;
1402    }
1403    
1404    =head3 UnEscape
1405    
1406    C<< my $realString = Tracer::UnEscape($codedString); >>
1407    
1408    Replace escape sequences with their actual equivalents. C<\t> will be replaced by
1409    a tab, C<\n> by a new-line character, and C<\\> by a backslash. C<\r> codes will
1410    be deleted.
1411    
1412    =over 4
1413    
1414    =item codedString
1415    
1416    String to un-escape.
1417    
1418    =item RETURN
1419    
1420    Returns a copy of the original string with the escape sequences converted to their actual
1421    values.
1422    
1423    =back
1424    
1425    =cut
1426    
1427    sub UnEscape {
1428        # Get the parameter.
1429        my ($codedString) = @_;
1430        # Initialize the return variable.
1431        my $retVal = "";
1432        # Only proceed if the incoming string is nonempty.
1433        if (defined $codedString) {
1434            # Loop through the parameter string, looking for escape sequences. We can't do
1435            # translating because it causes problems with the escaped slash. ("\\t" becomes
1436            # "\<tab>" no matter what we do.)
1437            while (length $codedString > 0) {
1438                # Look for the first escape sequence.
1439                if ($codedString =~ /^(.*?)\\(\\|n|t|r)/) {
1440                    # Here we found it. The text preceding the sequence is in $1. The sequence
1441                    # itself is in $2. First, move the clear text to the return variable.
1442                    $retVal .= $1;
1443                    $codedString = substr $codedString, (2 + length $1);
1444                    # Get the escape value.
1445                    my $char = $2;
1446                    # If we have a "\r", we are done.
1447                    if ($char ne 'r') {
1448                        # Here it's not an 'r', so we convert it.
1449                        $char =~ tr/\\tn/\\\t\n/;
1450                        $retVal .= $char;
1451                    }
1452                } else {
1453                    # Here there are no more escape sequences. The rest of the string is
1454                    # transferred unmodified.
1455                    $retVal .= $codedString;
1456                    $codedString = "";
1457                }
1458            }
1459        }
1460        # Return the result.
1461        return $retVal;
1462    }
1463    
1464    =head3 ParseRecord
1465    
1466    C<< my @fields = Tracer::ParseRecord($line); >>
1467    
1468    Parse a tab-delimited data line. The data line is split into field values. Embedded tab
1469    and new-line characters in the data line must be represented as C<\t> and C<\n>, respectively.
1470    These will automatically be converted.
1471    
1472    =over 4
1473    
1474    =item line
1475    
1476    Line of data containing the tab-delimited fields.
1477    
1478    =item RETURN
1479    
1480    Returns a list of the fields found in the data line.
1481    
1482    =back
1483    
1484    =cut
1485    
1486    sub ParseRecord {
1487        # Get the parameter.
1488        my ($line) = @_;
1489        # Remove the trailing new-line, if any.
1490        chomp $line;
1491        # Split the line read into pieces using the tab character.
1492        my @retVal = split /\t/, $line;
1493        # Trim and fix the escapes in each piece.
1494        for my $value (@retVal) {
1495            # Trim leading whitespace.
1496            $value =~ s/^\s+//;
1497            # Trim trailing whitespace.
1498            $value =~ s/\s+$//;
1499            # Delete the carriage returns.
1500            $value =~ s/\r//g;
1501            # Convert the escapes into their real values.
1502            $value =~ s/\\t/"\t"/ge;
1503            $value =~ s/\\n/"\n"/ge;
1504        }
1505        # Return the result.
1506        return @retVal;
1507    }
1508    
1509    =head3 Merge
1510    
1511    C<< my @mergedList = Tracer::Merge(@inputList); >>
1512    
1513    Sort a list of strings and remove duplicates.
1514    
1515    =over 4
1516    
1517    =item inputList
1518    
1519    List of scalars to sort and merge.
1520    
1521    =item RETURN
1522    
1523    Returns a list containing the same elements sorted in ascending order with duplicates
1524    removed.
1525    
1526    =back
1527    
1528    =cut
1529    
1530    sub Merge {
1531        # Get the input list in sort order.
1532        my @inputList = sort @_;
1533        # Only proceed if the list has at least two elements.
1534        if (@inputList > 1) {
1535            # Now we want to move through the list splicing out duplicates.
1536            my $i = 0;
1537            while ($i < @inputList) {
1538                # Get the current entry.
1539                my $thisEntry = $inputList[$i];
1540                # Find out how many elements duplicate the current entry.
1541                my $j = $i + 1;
1542                my $dup1 = $i + 1;
1543                while ($j < @inputList && $inputList[$j] eq $thisEntry) { $j++; };
1544                # If the number is nonzero, splice out the duplicates found.
1545                if ($j > $dup1) {
1546                    splice @inputList, $dup1, $j - $dup1;
1547                }
1548                # Now the element at position $dup1 is different from the element before it
1549                # at position $i. We push $i forward one position and start again.
1550                $i++;
1551            }
1552        }
1553        # Return the merged list.
1554        return @inputList;
1555    }
1556    
1557    =head3 Percent
1558    
1559    C<< my $percent = Tracer::Percent($number, $base); >>
1560    
1561    Returns the percent of the base represented by the given number. If the base
1562    is zero, returns zero.
1563    
1564    =over 4
1565    
1566    =item number
1567    
1568    Percent numerator.
1569    
1570    =item base
1571    
1572    Percent base.
1573    
1574    =item RETURN
1575    
1576    Returns the percentage of the base represented by the numerator.
1577    
1578    =back
1579    
1580    =cut
1581    
1582    sub Percent {
1583        # Get the parameters.
1584        my ($number, $base) = @_;
1585        # Declare the return variable.
1586        my $retVal = 0;
1587        # Compute the percent.
1588        if ($base != 0) {
1589            $retVal = $number * 100 / $base;
1590        }
1591        # Return the result.
1592        return $retVal;
1593    }
1594    
1595    =head3 GetFile
1596    
1597    C<< my @fileContents = Tracer::GetFile($fileName); >>
1598    
1599        or
1600    
1601    C<< my $fileContents = Tracer::GetFile($fileName); >>
1602    
1603    Return the entire contents of a file. In list context, line-ends are removed and
1604    each line is a list element. In scalar context, line-ends are replaced by C<\n>.
1605    
1606    =over 4
1607    
1608    =item fileName
1609    
1610    Name of the file to read.
1611    
1612    =item RETURN
1613    
1614    In a list context, returns the entire file as a list with the line terminators removed.
1615    In a scalar context, returns the entire file as a string. If an error occurs opening
1616    the file, an empty list will be returned.
1617    
1618    =back
1619    
1620    =cut
1621    
1622    sub GetFile {
1623        # Get the parameters.
1624        my ($fileName) = @_;
1625        # Declare the return variable.
1626        my @retVal = ();
1627        # Open the file for input.
1628        my $handle = Open(undef, "<$fileName");
1629        # Read the whole file into the return variable, stripping off any terminator
1630        # characters.
1631        my $lineCount = 0;
1632        while (my $line = <$handle>) {
1633            $lineCount++;
1634            $line = Strip($line);
1635            push @retVal, $line;
1636        }
1637        # Close it.
1638        close $handle;
1639        my $actualLines = @retVal;
1640        Trace("$actualLines lines read from file $fileName.") if T(File => 2);
1641        # Return the file's contents in the desired format.
1642        if (wantarray) {
1643            return @retVal;
1644        } else {
1645            return join "\n", @retVal;
1646        }
1647    }
1648    
1649    =head3 PutFile
1650    
1651    C<< Tracer::PutFile($fileName, \@lines); >>
1652    
1653    Write out a file from a list of lines of text.
1654    
1655    =over 4
1656    
1657    =item fileName
1658    
1659    Name of the output file.
1660    
1661    =item lines
1662    
1663    Reference to a list of text lines. The lines will be written to the file in order, with trailing
1664    new-line characters. Alternatively, may be a string, in which case the string will be written without
1665    modification.
1666    
1667    =back
1668    
1669    =cut
1670    
1671    sub PutFile {
1672        # Get the parameters.
1673        my ($fileName, $lines) = @_;
1674        # Open the output file.
1675        my $handle = Open(undef, ">$fileName");
1676        # Count the lines written.
1677        if (ref $lines ne 'ARRAY') {
1678            # Here we have a scalar, so we write it raw.
1679            print $handle $lines;
1680            Trace("Scalar put to file $fileName.") if T(File => 3);
1681        } else {
1682            # Write the lines one at a time.
1683            my $count = 0;
1684            for my $line (@{$lines}) {
1685                print $handle "$line\n";
1686                $count++;
1687            }
1688            Trace("$count lines put to file $fileName.") if T(File => 3);
1689        }
1690        # Close the output file.
1691        close $handle;
1692    }
1693    
1694    =head3 QTrace
1695    
1696    C<< my $data = QTrace($format); >>
1697    
1698    Return the queued trace data in the specified format.
1699    
1700    =over 4
1701    
1702    =item format
1703    
1704    C<html> to format the data as an HTML list, C<text> to format it as straight text.
1705    
1706    =back
1707    
1708    =cut
1709    
1710    sub QTrace {
1711        # Get the parameter.
1712        my ($format) = @_;
1713        # Create the return variable.
1714        my $retVal = "";
1715        # Only proceed if there is an actual queue.
1716        if (@Queue) {
1717            # Process according to the format.
1718            if ($format =~ m/^HTML$/i) {
1719                # Convert the queue into an HTML list.
1720                $retVal = "<ul>\n";
1721                for my $line (@Queue) {
1722                    my $escapedLine = CGI::escapeHTML($line);
1723                    $retVal .= "<li>$escapedLine</li>\n";
1724                }
1725                $retVal .= "</ul>\n";
1726            } elsif ($format =~ m/^TEXT$/i) {
1727                # Convert the queue into a list of text lines.
1728                $retVal = join("\n", @Queue) . "\n";
1729            }
1730            # Clear the queue.
1731            @Queue = ();
1732        }
1733        # Return the formatted list.
1734        return $retVal;
1735    }
1736    
1737    =head3 Confess
1738    
1739    C<< Confess($message); >>
1740    
1741    Trace the call stack and abort the program with the specified message. When used with
1742    the OR operator and the L</Assert> method, B<Confess> can function as a debugging assert.
1743    So, for example
1744    
1745    C<< Assert($recNum >= 0) || Confess("Invalid record number $recNum."); >>
1746    
1747    Will abort the program with a stack trace if the value of C<$recNum> is negative.
1748    
1749    =over 4
1750    
1751    =item message
1752    
1753    Message to include in the trace.
1754    
1755    =back
1756    
1757    =cut
1758    
1759    sub Confess {
1760        # Get the parameters.
1761        my ($message) = @_;
1762        # Trace the call stack.
1763        Cluck($message);
1764        # Abort the program.
1765        croak(">>> $message");
1766    }
1767    
1768    =head3 Assert
1769    
1770    C<< Assert($condition1, $condition2, ... $conditionN); >>
1771    
1772    Return TRUE if all the conditions are true. This method can be used in conjunction with
1773    the OR operator and the L</Confess> method as a debugging assert.
1774    So, for example
1775    
1776    C<< Assert($recNum >= 0) || Confess("Invalid record number $recNum."); >>
1777    
1778    Will abort the program with a stack trace if the value of C<$recNum> is negative.
1779    
1780    =cut
1781    sub Assert {
1782        my $retVal = 1;
1783        LOOP: for my $condition (@_) {
1784            if (! $condition) {
1785                $retVal = 0;
1786                last LOOP;
1787            }
1788        }
1789        return $retVal;
1790    }
1791    
1792    =head3 Cluck
1793    
1794    C<< Cluck($message); >>
1795    
1796    Trace the call stack. Note that for best results, you should qualify the call with a
1797    trace condition. For example,
1798    
1799    C<< Cluck("Starting record parse.") if T(3); >>
1800    
1801    will only trace the stack if the trace level for the package is 3 or more.
1802    
1803    =over 4
1804    
1805    =item message
1806    
1807    Message to include in the trace.
1808    
1809    =back
1810    
1811    =cut
1812    
1813    sub Cluck {
1814        # Get the parameters.
1815        my ($message) = @_;
1816        # Trace what's happening.
1817        Trace("Stack trace for event: $message");
1818        my $confession = longmess($message);
1819        # Convert the confession to a series of trace messages. Note we skip any
1820        # messages relating to calls into Tracer.
1821        for my $line (split /\s*\n/, $confession) {
1822            Trace($line) if ($line !~ /Tracer\.pm/);
1823        }
1824    }
1825    
1826    =head3 Min
1827    
1828    C<< my $min = Min($value1, $value2, ... $valueN); >>
1829    
1830    Return the minimum argument. The arguments are treated as numbers.
1831    
1832    =over 4
1833    
1834    =item $value1, $value2, ... $valueN
1835    
1836    List of numbers to compare.
1837    
1838    =item RETURN
1839    
1840    Returns the lowest number in the list.
1841    
1842    =back
1843    
1844    =cut
1845    
1846    sub Min {
1847        # Get the parameters. Note that we prime the return value with the first parameter.
1848        my ($retVal, @values) = @_;
1849        # Loop through the remaining parameters, looking for the lowest.
1850        for my $value (@values) {
1851            if ($value < $retVal) {
1852                $retVal = $value;
1853            }
1854        }
1855        # Return the minimum found.
1856        return $retVal;
1857    }
1858    
1859    =head3 Max
1860    
1861    C<< my $max = Max($value1, $value2, ... $valueN); >>
1862    
1863    Return the maximum argument. The arguments are treated as numbers.
1864    
1865    =over 4
1866    
1867    =item $value1, $value2, ... $valueN
1868    
1869    List of numbers to compare.
1870    
1871    =item RETURN
1872    
1873    Returns the highest number in the list.
1874    
1875    =back
1876    
1877    =cut
1878    
1879    sub Max {
1880        # Get the parameters. Note that we prime the return value with the first parameter.
1881        my ($retVal, @values) = @_;
1882        # Loop through the remaining parameters, looking for the highest.
1883        for my $value (@values) {
1884            if ($value > $retVal) {
1885                $retVal = $value;
1886            }
1887        }
1888        # Return the maximum found.
1889        return $retVal;
1890    }
1891    
1892    =head3 AddToListMap
1893    
1894    C<< Tracer::AddToListMap(\%hash, $key, $value1, $value2, ... valueN); >>
1895    
1896    Add a key-value pair to a hash of lists. If no value exists for the key, a singleton list
1897    is created for the key. Otherwise, the new value is pushed onto the list.
1898    
1899    =over 4
1900    
1901    =item hash
1902    
1903    Reference to the target hash.
1904    
1905    =item key
1906    
1907    Key for which the value is to be added.
1908    
1909    =item value1, value2, ... valueN
1910    
1911    List of values to add to the key's value list.
1912    
1913    =back
1914    
1915    =cut
1916    
1917    sub AddToListMap {
1918        # Get the parameters.
1919        my ($hash, $key, @values) = @_;
1920        # Process according to whether or not the key already has a value.
1921        if (! exists $hash->{$key}) {
1922            $hash->{$key} = [@values];
1923        } else {
1924            push @{$hash->{$key}}, @values;
1925        }
1926    }
1927    
1928    =head3 DebugMode
1929    
1930    C<< if (Tracer::DebugMode) { ...code... } >>
1931    
1932    Return TRUE if debug mode has been turned on, else abort.
1933    
1934    Certain CGI scripts are too dangerous to exist in the production
1935    environment. This method provides a simple way to prevent them
1936    from working unless they are explicitly turned on by creating a password
1937    cookie via the B<SetPassword> script.  If debugging mode
1938    is not turned on, an error will occur.
1939    
1940    =cut
1941    
1942    sub DebugMode {
1943        # Declare the return variable.
1944        my $retVal = 0;
1945        # Check the debug configuration.
1946        my $password = CGI::cookie("DebugMode");
1947        my $encrypted = Digest::MD5::md5_hex($password);
1948        if ($encrypted eq "252dec43280e0c0d6a75ffcec486e61d") {
1949            $retVal = 1;
1950        } else {
1951            # Here debug mode is off, so we generate an error.
1952            Confess("Cannot use this facility without logging in.");
1953        }
1954        # Return the determination indicator.
1955        return $retVal;
1956    }
1957    
1958    =head3 Strip
1959    
1960    C<< my $string = Tracer::Strip($line); >>
1961    
1962    Strip all line terminators off a string. This is necessary when dealing with files
1963    that may have been transferred back and forth several times among different
1964    operating environments.
1965    
1966    =over 4
1967    
1968    =item line
1969    
1970    Line of text to be stripped.
1971    
1972    =item RETURN
1973    
1974    The same line of text with all the line-ending characters chopped from the end.
1975    
1976    =back
1977    
1978    =cut
1979    
1980    sub Strip {
1981        # Get a copy of the parameter string.
1982        my ($string) = @_;
1983        my $retVal = (defined $string ? $string : "");
1984        # Strip the line terminator characters.
1985        $retVal =~ s/(\r|\n)+$//g;
1986        # Return the result.
1987        return $retVal;
1988    }
1989    
1990    =head3 Pad
1991    
1992    C<< my $paddedString = Tracer::Pad($string, $len, $left, $padChar); >>
1993    
1994    Pad a string to a specified length. The pad character will be a
1995    space, and the padding will be on the right side unless specified
1996    in the third parameter.
1997    
1998    =over 4
1999    
2000    =item string
2001    
2002    String to be padded.
2003    
2004    =item len
2005    
2006    Desired length of the padded string.
2007    
2008    =item left (optional)
2009    
2010    TRUE if the string is to be left-padded; otherwise it will be padded on the right.
2011    
2012    =item padChar (optional)
2013    
2014    Character to use for padding. The default is a space.
2015    
2016    =item RETURN
2017    
2018    Returns a copy of the original string with the pad character added to the
2019    specified end so that it achieves the desired length.
2020    
2021    =back
2022    
2023    =cut
2024    
2025    sub Pad {
2026        # Get the parameters.
2027        my ($string, $len, $left, $padChar) = @_;
2028        # Compute the padding character.
2029        if (! defined $padChar) {
2030            $padChar = " ";
2031        }
2032        # Compute the number of spaces needed.
2033        my $needed = $len - length $string;
2034        # Copy the string into the return variable.
2035        my $retVal = $string;
2036        # Only proceed if padding is needed.
2037        if ($needed > 0) {
2038            # Create the pad string.
2039            my $pad = $padChar x $needed;
2040            # Affix it to the return value.
2041            if ($left) {
2042                $retVal = $pad . $retVal;
2043                          } else {                          } else {
2044                                  $category = $package;              $retVal .= $pad;
2045                          }                          }
2046                  }                  }
2047                  # Use the package and tracelevel to compute the result.      # Return the result.
2048                  $retVal = ($traceLevel <= $TraceLevel && exists $Categories{$category});      return $retVal;
2049          }          }
2050          # Return the computed result.  
2051    =head3 EOF
2052    
2053    This is a constant that is lexically greater than any useful string.
2054    
2055    =cut
2056    
2057    sub EOF {
2058        return "\xFF\xFF\xFF\xFF\xFF";
2059    }
2060    
2061    =head3 TICK
2062    
2063    C<< my @results = TICK($commandString); >>
2064    
2065    Perform a back-tick operation on a command. If this is a Windows environment, any leading
2066    dot-slash (C<./> will be removed. So, for example, if you were doing
2067    
2068        `./protein.cgi`
2069    
2070    from inside a CGI script, it would work fine in Unix, but would issue an error message
2071    in Windows complaining that C<'.'> is not a valid command. If instead you code
2072    
2073        TICK("./protein.cgi")
2074    
2075    it will work correctly in both environments.
2076    
2077    =over 4
2078    
2079    =item commandString
2080    
2081    The command string to pass to the system.
2082    
2083    =item RETURN
2084    
2085    Returns the standard output from the specified command, as a list.
2086    
2087    =back
2088    
2089    =cut
2090    #: Return Type @;
2091    sub TICK {
2092        # Get the parameters.
2093        my ($commandString) = @_;
2094        # Chop off the dot-slash if this is Windows.
2095        if ($FIG_Config::win_mode) {
2096            $commandString =~ s!^\./!!;
2097        }
2098        # Activate the command and return the result.
2099        return `$commandString`;
2100    }
2101    
2102    =head3 ScriptSetup
2103    
2104    C<< my ($cgi, $varHash) = ScriptSetup($noTrace); >>
2105    
2106    Perform standard tracing and debugging setup for scripts. The value returned is
2107    the CGI object followed by a pre-built variable hash.
2108    
2109    The C<Trace> form parameter is used to determine whether or not tracing is active and
2110    which trace modules (other than C<Tracer> itself) should be turned on. Specifying
2111    the C<CGI> trace module will trace parameter and environment information. Parameters are
2112    traced at level 3 and environment variables at level 4. To trace to a file instead of to
2113    the web page, set C<TF> to 1. At the end of the script, the client should call
2114    L</ScriptFinish> to output the web page.
2115    
2116    In some situations, it is not practical to invoke tracing via form parameters. For this
2117    situation, you can turn on emergency tracing from the debugging control panel.
2118    Tracing will then be turned on automatically for all programs that use the L</ETracing>
2119    method, which includes every program that uses this method or L</StandardSetup>.
2120    
2121    =over 4
2122    
2123    =item noTrace (optional)
2124    
2125    If specified, tracing will be suppressed. This is useful if the script wants to set up
2126    tracing manually.
2127    
2128    =item RETURN
2129    
2130    Returns a two-element list consisting of a CGI query object and a variable hash for
2131    the output page.
2132    
2133    =back
2134    
2135    =cut
2136    
2137    sub ScriptSetup {
2138        # Get the parameters.
2139        my ($noTrace) = @_;
2140        # Get the CGI query object.
2141        my $cgi = CGI->new();
2142        # Set up tracing if it's not suppressed.
2143        ETracing($cgi) unless $noTrace;
2144        # Create the variable hash.
2145        my $varHash = { results => '' };
2146        # Return the query object and variable hash.
2147        return ($cgi, $varHash);
2148    }
2149    
2150    =head3 ETracing
2151    
2152    C<< ETracing($parameter); >>
2153    
2154    Set up emergency tracing. Emergency tracing is tracing that is turned
2155    on automatically for any program that calls this method. The emergency
2156    tracing parameters are stored in a a file identified by a tracing key.
2157    If this method is called with a CGI object, then the tracing key is
2158    taken from a cookie. If it is called with no parameters, then the tracing
2159    key is taken from an environment variable. If it is called with a string,
2160    the tracing key is that string.
2161    
2162    =over 4
2163    
2164    =item parameter
2165    
2166    A parameter from which the tracing key is computed. If it is a scalar,
2167    that scalar is used as the tracing key. If it is a CGI object, the
2168    tracing key is taken from the C<IP> cookie. If it is omitted, the
2169    tracing key is taken from the C<TRACING> environment variable. If it
2170    is a CGI object and emergency tracing is not on, the C<Trace> and
2171    C<TF> parameters will be used to determine the type of tracing.
2172    
2173    =back
2174    
2175    =cut
2176    
2177    sub ETracing {
2178        # Get the parameter.
2179        my ($parameter) = @_;
2180        # Check for CGI mode.
2181        my $cgi = (ref $parameter eq 'CGI' ? $parameter : undef);
2182        # Default to no tracing except errors.
2183        my ($tracing, $dest) = ("0", "WARN");
2184        # Check for emergency tracing.
2185        my $tkey = EmergencyKey($parameter);
2186        my $emergencyFile = EmergencyFileName($tkey);
2187        if (-e $emergencyFile) {
2188            # We have the file. Read in the data.
2189            my @tracing = GetFile($emergencyFile);
2190            # Pull off the time limit.
2191            my $expire = shift @tracing;
2192            # Convert it to seconds.
2193            $expire *= 3600;
2194            # Check the file data.
2195            my $stat = stat($emergencyFile);
2196            my ($now) = gettimeofday;
2197            if ($now - $stat->mtime > $expire) {
2198                # Delete the expired file.
2199                unlink $emergencyFile;
2200            } else {
2201                # Emergency tracing is on. Pull off the destination and
2202                # the trace level;
2203                $dest = shift @tracing;
2204                my $level = shift @tracing;
2205                # Convert the destination to a real tracing destination.
2206                # temp directory.
2207                $dest = EmergencyTracingDest($tkey, $dest);
2208                # Insure Tracer is specified.
2209                my %moduleHash = map { $_ => 1 } @tracing;
2210                $moduleHash{Tracer} = 1;
2211                # Set the trace parameter.
2212                $tracing = join(" ", $level, sort keys %moduleHash);
2213            }
2214        } elsif (defined $cgi) {
2215            # There's no emergency tracing, but we have a CGI object, so check
2216            # for tracing from the form parameters.
2217            if ($cgi->param('Trace')) {
2218                # Here the user has requested tracing via a form.
2219                $dest = ($cgi->param('TF') ? ">$FIG_Config::temp/Trace$$.log" : "QUEUE");
2220                $tracing = $cgi->param('Trace') . " Tracer";
2221            }
2222        }
2223        # Setup the tracing we've determined from all the stuff above.
2224        TSetup($tracing, $dest);
2225        # If we're a web script, trace the parameter and environment data.
2226        if (defined $cgi) {
2227            TraceParms($cgi);
2228        }
2229    }
2230    
2231    =head3 EmergencyFileName
2232    
2233    C<< my $fileName = Tracer::EmergencyFileName($tkey); >>
2234    
2235    Return the emergency tracing file name. This is the file that specifies
2236    the tracing information.
2237    
2238    =over 4
2239    
2240    =item tkey
2241    
2242    Tracing key for the current program.
2243    
2244    =item RETURN
2245    
2246    Returns the name of the file to contain the emergency tracing information.
2247    
2248    =back
2249    
2250    =cut
2251    
2252    sub EmergencyFileName {
2253        # Get the parameters.
2254        my ($tkey) = @_;
2255        # Compute the emergency tracing file name.
2256        return "$FIG_Config::temp/Emergency$tkey.txt";
2257    }
2258    
2259    =head3 EmergencyFileTarget
2260    
2261    C<< my $fileName = Tracer::EmergencyFileTarget($tkey); >>
2262    
2263    Return the emergency tracing target file name. This is the file that receives
2264    the tracing output for file-based tracing.
2265    
2266    =over 4
2267    
2268    =item tkey
2269    
2270    Tracing key for the current program.
2271    
2272    =item RETURN
2273    
2274    Returns the name of the file to contain the trace output.
2275    
2276    =back
2277    
2278    =cut
2279    
2280    sub EmergencyFileTarget {
2281        # Get the parameters.
2282        my ($tkey) = @_;
2283        # Compute the emergency tracing file name.
2284        return "$FIG_Config::temp/trace$tkey.log";
2285    }
2286    
2287    =head3 EmergencyTracingDest
2288    
2289    C<< my $dest = Tracer::EmergencyTracingDest($tkey, $myDest); >>
2290    
2291    This method converts an emergency tracing destination to a real
2292    tracing destination. The main difference is that if the
2293    destination is C<FILE> or C<APPEND>, we convert it to file
2294    output.
2295    
2296    =over 4
2297    
2298    =item tkey
2299    
2300    Tracing key for this environment.
2301    
2302    =item myDest
2303    
2304    Destination from the emergency tracing file.
2305    
2306    =item RETURN
2307    
2308    Returns a destination that can be passed into L</TSetup>.
2309    
2310    =back
2311    
2312    =cut
2313    
2314    sub EmergencyTracingDest {
2315        # Get the parameters.
2316        my ($tkey, $myDest) = @_;
2317        # Declare the return variable.
2318        my $retVal;
2319        # Process according to the destination value.
2320        if ($myDest eq 'FILE') {
2321            $retVal = ">" . EmergencyFileTarget($tkey);
2322        } elsif ($myDest eq 'APPEND') {
2323            $retVal = ">>" . EmergencyFileTarget($tkey);
2324        } else {
2325            $retVal = $myDest;
2326        }
2327        # Return the result.
2328          return $retVal;          return $retVal;
2329  }  }
2330    
2331  =head3 ParseCommand  =head3 Emergency
2332    
2333  C<< my ($options, @arguments) = Tracer::ParseCommand(\%optionTable, @inputList); >>  C<< Emergency($key, $hours, $dest, $level, @modules); >>
2334    
2335  Parse a command line consisting of a list of parameters. The initial parameters may be option  Turn on emergency tracing. This method can only be invoked over the web and is
2336  specifiers of the form C<->I<option> or C<->I<option>C<=>I<value>. The options are stripped  should not be called if debug mode is off. The caller specifies the duration of the
2337  off and merged into a table of default options. The remainder of the command line is  emergency in hours, the desired tracing destination, the trace level,
2338  returned as a list of positional arguments. For example, consider the following invocation.  and a list of the trace modules to activate. For the length of the duration, when a
2339    program in an environment with the specified tracing key active invokes a Sprout
2340    CGI script, tracing will be turned on automatically. See L</TSetup> for more
2341    about tracing setup and L</ETracing> for more about emergency tracing.
2342    
2343  C<< my ($options, @arguments) = ParseCommand({ errors => 0, logFile => 'trace.log'}, @words); >>  =over 4
2344    
2345  In this case, the list @words will be treated as a command line. There are two options available,  =item tkey
2346  B<errors> and B<logFile>. If @words has the following format  
2347    The tracing key. This is used to identify the control file and the trace file.
2348    
2349    =item hours
2350    
2351    Number of hours to keep emergency tracing alive.
2352    
2353    =item dest
2354    
2355    Tracing destination. If no path information is specified for a file
2356    destination, it is put in the FIG temporary directory.
2357    
2358    =item level
2359    
2360    Tracing level. A higher level means more trace messages.
2361    
2362    =item modules
2363    
2364    A list of the tracing modules to activate.
2365    
2366    =back
2367    
2368    =cut
2369    
2370    sub Emergency {
2371        # Get the parameters.
2372        my ($tkey, $hours, $dest, $level, @modules) = @_;
2373        # Create the emergency file.
2374        my $specFile = EmergencyFileName($tkey);
2375        my $outHandle = Open(undef, ">$specFile");
2376        print $outHandle join("\n", $hours, $dest, $level, @modules, "");
2377    }
2378    
2379    =head3 EmergencyKey
2380    
2381    C<< my $tkey = EmergencyKey($parameter); >>
2382    
2383    Return the Key to be used for emergency tracing. This could be an IP address,
2384     a session ID, or a user name, depending on the environment.
2385    
2386    =over 4
2387    
2388    =item parameter
2389    
2390    Parameter defining the method for finding the tracing key. If it is a scalar,
2391    then it is presumed to be the tracing key itself. If it is a CGI object, then
2392    the tracing key is taken from the C<IP> cookie. Otherwise, the tracing key is
2393    taken from the C<TRACING> environment variable.
2394    
2395    =item RETURN
2396    
2397    Returns the key to be used for labels in emergency tracing.
2398    
2399    =back
2400    
2401    =cut
2402    
2403    sub EmergencyKey {
2404        # Get the parameters.
2405        my ($parameter) = @_;
2406        # Declare the return variable.
2407        my $retVal;
2408        # Determine the parameter type.
2409        if (! defined $parameter) {
2410            # Here we're supposed to check the environment.
2411            $retVal = $ENV{TRACING};
2412        } else {
2413            my $ptype = ref $parameter;
2414            if ($ptype eq 'CGI') {
2415                # Here we were invoked from a web page. Look for a cookie.
2416                $retVal = $parameter->cookie('IP');
2417            } elsif (! $ptype) {
2418                # Here the key was passed in.
2419                $retVal = $parameter;
2420            }
2421        }
2422        # If no luck finding a key, use the PID.
2423        if (! defined $retVal) {
2424            $retVal = $$;
2425        }
2426        # Return the result.
2427        return $retVal;
2428    }
2429    
2430    
2431    =head3 TraceParms
2432    
2433    C<< Tracer::TraceParms($cgi); >>
2434    
2435    Trace the CGI parameters at trace level CGI => 3 and the environment variables
2436    at level CGI => 4.
2437    
2438    =over 4
2439    
2440    =item cgi
2441    
2442    CGI query object containing the parameters to trace.
2443    
2444    =back
2445    
2446    =cut
2447    
2448    sub TraceParms {
2449        # Get the parameters.
2450        my ($cgi) = @_;
2451        if (T(CGI => 3)) {
2452            # Here we want to trace the parameter data.
2453            my @names = $cgi->param;
2454            for my $parmName (sort @names) {
2455                # Note we skip the Trace parameters, which are for our use only.
2456                if ($parmName ne 'Trace' && $parmName ne 'TF') {
2457                    my @values = $cgi->param($parmName);
2458                    Trace("CGI: $parmName = " . join(", ", @values));
2459                }
2460            }
2461            # Display the request method.
2462            my $method = $cgi->request_method();
2463            Trace("Method: $method");
2464        }
2465        if (T(CGI => 4)) {
2466            # Here we want the environment data too.
2467            for my $envName (sort keys %ENV) {
2468                Trace("ENV: $envName = $ENV{$envName}");
2469            }
2470        }
2471    }
2472    
2473    =head3 ScriptFinish
2474    
2475    C<< ScriptFinish($webData, $varHash); >>
2476    
2477    Output a web page at the end of a script. Either the string to be output or the
2478    name of a template file can be specified. If the second parameter is omitted,
2479    it is assumed we have a string to be output; otherwise, it is assumed we have the
2480    name of a template file. The template should have the variable C<DebugData>
2481    specified in any form that invokes a standard script. If debugging mode is turned
2482    on, a form field will be put in that allows the user to enter tracing data.
2483    Trace messages will be placed immediately before the terminal C<BODY> tag in
2484    the output, formatted as a list.
2485    
2486    A typical standard script would loook like the following.
2487    
2488        BEGIN {
2489            # Print the HTML header.
2490            print "CONTENT-TYPE: text/html\n\n";
2491        }
2492        use Tracer;
2493        use CGI;
2494        use FIG;
2495        # ... more uses ...
2496    
2497        my ($cgi, $varHash) = ScriptSetup();
2498        eval {
2499            # ... get data from $cgi, put it in $varHash ...
2500        };
2501        if ($@) {
2502            Trace("Script Error: $@") if T(0);
2503        }
2504        ScriptFinish("Html/MyTemplate.html", $varHash);
2505    
2506    The idea here is that even if the script fails, you'll see trace messages and
2507    useful output.
2508    
2509    =over 4
2510    
2511    =item webData
2512    
2513    A string containing either the full web page to be written to the output or the
2514    name of a template file from which the page is to be constructed. If the name
2515    of a template file is specified, then the second parameter must be present;
2516    otherwise, it must be absent.
2517    
2518    =item varHash (optional)
2519    
2520    If specified, then a reference to a hash mapping variable names for a template
2521    to their values. The template file will be read into memory, and variable markers
2522    will be replaced by data in this hash reference.
2523    
2524    =back
2525    
2526    =cut
2527    
2528    sub ScriptFinish {
2529        # Get the parameters.
2530        my ($webData, $varHash) = @_;
2531        # Check for a template file situation.
2532        my $outputString;
2533        if (defined $varHash) {
2534            # Here we have a template file. We need to determine the template type.
2535            my $template;
2536            if ($FIG_Config::template_url && $webData =~ /\.php$/) {
2537                $template = "$FIG_Config::template_url/$webData";
2538            } else {
2539                $template = "<<$webData";
2540            }
2541            $outputString = PageBuilder::Build($template, $varHash, "Html");
2542        } else {
2543            # Here the user gave us a raw string.
2544            $outputString = $webData;
2545        }
2546        # Check for trace messages.
2547        if ($Destination ne "NONE" && $TraceLevel > 0) {
2548            # We have trace messages, so we want to put them at the end of the body. This
2549            # is either at the end of the whole string or at the beginning of the BODY
2550            # end-tag.
2551            my $pos = length $outputString;
2552            if ($outputString =~ m#</body>#gi) {
2553                $pos = (pos $outputString) - 7;
2554            }
2555            # If the trace messages were queued, we unroll them. Otherwise, we display the
2556            # destination.
2557            my $traceHtml;
2558            if ($Destination eq "QUEUE") {
2559                $traceHtml = QTrace('Html');
2560            } elsif ($Destination =~ /^>>(.+)$/) {
2561                # Here the tracing output it to a file. We code it as a hyperlink so the user
2562                # can copy the file name into the clipboard easily.
2563                my $actualDest = $1;
2564                $traceHtml = "<p>Tracing output to $actualDest.</p>\n";
2565            } else {
2566                # Here we have one of the special destinations.
2567                $traceHtml = "<P>Tracing output type is $Destination.</p>\n";
2568            }
2569            substr $outputString, $pos, 0, $traceHtml;
2570        }
2571        # Write the output string.
2572        print $outputString;
2573    }
2574    
2575    =head3 Insure
2576    
2577    C<< Insure($dirName); >>
2578    
2579    Insure a directory is present.
2580    
2581    =over 4
2582    
2583    =item dirName
2584    
2585    Name of the directory to check. If it does not exist, it will be created.
2586    
2587    =back
2588    
2589    =cut
2590    
2591    sub Insure {
2592        my ($dirName) = @_;
2593        if (! -d $dirName) {
2594            Trace("Creating $dirName directory.") if T(File => 2);
2595            eval { mkpath $dirName; };
2596            if ($@) {
2597                Confess("Error creating $dirName: $@");
2598            }
2599        }
2600    }
2601    
2602    =head3 ChDir
2603    
2604    C<< ChDir($dirName); >>
2605    
2606    Change to the specified directory.
2607    
2608    =over 4
2609    
2610    =item dirName
2611    
2612    Name of the directory to which we want to change.
2613    
2614    =back
2615    
2616    =cut
2617    
2618    sub ChDir {
2619        my ($dirName) = @_;
2620        if (! -d $dirName) {
2621            Confess("Cannot change to directory $dirName: no such directory.");
2622        } else {
2623            Trace("Changing to directory $dirName.") if T(File => 4);
2624            my $okFlag = chdir $dirName;
2625            if (! $okFlag) {
2626                Confess("Error switching to directory $dirName.");
2627            }
2628        }
2629    }
2630    
2631  C<< -logFile=error.log apple orange rutabaga >>  =head3 SendSMS
2632    
2633  then at the end of the invocation, C<$options> will be  C<< my $msgID = Tracer::SendSMS($phoneNumber, $msg); >>
2634    
2635  C<< { errors => 0, logFile => 'error.log' } >>  Send a text message to a phone number using Clickatell. The FIG_Config file must contain the
2636    user name, password, and API ID for the relevant account in the hash reference variable
2637    I<$FIG_Config::phone>, using the keys C<user>, C<password>, and C<api_id>. For
2638    example, if the user name is C<BruceTheHumanPet>, the password is C<silly>, and the API ID
2639    is C<2561022>, then the FIG_Config file must contain
2640    
2641  and C<@arguments> will contain      $phone =  { user => 'BruceTheHumanPet',
2642                    password => 'silly',
2643                    api_id => '2561022' };
2644    
2645  C<< apple orange rutabaga >>  The original purpose of this method was to insure Bruce would be notified immediately when the
2646    Sprout Load terminates. Care should be taken if you do not wish Bruce to be notified immediately
2647    when you call this method.
2648    
2649  The parser allows for some escape sequences. See L</UnEscape> for a description. There is no  The message ID will be returned if successful, and C<undef> if an error occurs.
 support for quote characters.  
2650    
2651  =over 4  =over 4
2652    
2653  =item optionTable  =item phoneNumber
2654    
2655  Table of default options.  Phone number to receive the message, in international format. A United States phone number
2656    would be prefixed by "1". A British phone number would be prefixed by "44".
2657    
2658  =item inputList  =item msg
2659    
2660  List of words on the command line.  Message to send to the specified phone.
2661    
2662  =item RETURN  =item RETURN
2663    
2664  Returns a reference to the option table and a list of the positional arguments.  Returns the message ID if successful, and C<undef> if the message could not be sent.
2665    
2666  =back  =back
2667    
2668  =cut  =cut
2669    
2670  sub ParseCommand {  sub SendSMS {
2671          # Get the parameters.          # Get the parameters.
2672          my ($optionTable, @inputList) = @_;      my ($phoneNumber, $msg) = @_;
2673          # Process any options in the input list.      # Declare the return variable. If we do not change it, C<undef> will be returned.
2674          my %overrides = ();      my $retVal;
2675          while ((@inputList > 0) && ($inputList[0] =~ /^-/)) {      # Only proceed if we have phone support.
2676                  # Get the current option.      if (! defined $FIG_Config::phone) {
2677                  my $arg = shift @inputList;          Trace("Phone support not present in FIG_Config.") if T(1);
                 # Pull out the option name.  
                 $arg =~ /^-([^=]*)/g;  
                 my $name = $1;  
                 # Check for an option value.  
                 if ($arg =~ /\G=(.*)$/g) {  
                         # Here we have a value for the option.  
                         $overrides{$name} = UnEscape($1);  
2678                  } else {                  } else {
2679                          # Here there is no value, so we use 1.          # Get the phone data.
2680                          $overrides{$name} = 1;          my $parms = $FIG_Config::phone;
2681            # Get the Clickatell URL.
2682            my $url = "http://api.clickatell.com/http/";
2683            # Create the user agent.
2684            my $ua = LWP::UserAgent->new;
2685            # Request a Clickatell session.
2686            my $resp = $ua->post("$url/sendmsg", { user => $parms->{user},
2687                                         password => $parms->{password},
2688                                         api_id => $parms->{api_id},
2689                                         to => $phoneNumber,
2690                                         text => $msg});
2691            # Check for an error.
2692            if (! $resp->is_success) {
2693                Trace("Alert failed.") if T(1);
2694            } else {
2695                # Get the message ID.
2696                my $rstring = $resp->content;
2697                if ($rstring =~ /^ID:\s+(.*)$/) {
2698                    $retVal = $1;
2699                } else {
2700                    Trace("Phone attempt failed with $rstring") if T(1);
2701                  }                  }
2702          }          }
         # Merge the options into the defaults.  
         GetOptions($optionTable, \%overrides);  
         # Translate the remaining parameters.  
         my @retVal = ();  
         for my $inputParm (@inputList) {  
                 push @retVal, UnEscape($inputParm);  
2703          }          }
2704          # Return the results.      # Return the result.
2705          return ($optionTable, @retVal);      return $retVal;
2706  }  }
2707    
2708  =head3 UnEscape  =head3 CommaFormat
2709    
2710  C<< my $realString = Tracer::UnEscape($codedString); >>  C<< my $formatted = Tracer::CommaFormat($number); >>
2711    
2712  Replace escape sequences with their actual equivalents. C<\b> will be replaced by a space,  Insert commas into a number.
 C<\t> by a tab, C<\n> by a new-line character, and C<\\> by a back-slash.  
2713    
2714  =over 4  =over 4
2715    
2716  =item codedString  =item number
2717    
2718  String to un-escape.  A sequence of digits.
2719    
2720  =item RETURN  =item RETURN
2721    
2722  Returns a copy of the original string with the escape sequences converted to their actual  Returns the same digits with commas strategically inserted.
 values.  
2723    
2724  =back  =back
2725    
2726  =cut  =cut
2727    
2728  sub UnEscape {  sub CommaFormat {
2729          # Get the parameter.      # Get the parameters.
2730          my ($codedString) = @_;      my ($number) = @_;
2731          # Initialize the return variable.      # Pad the length up to a multiple of three.
2732          my $retVal = "";      my $padded = "$number";
2733          # Loop through the parameter string, looking for escape sequences. We can't do      $padded = " " . $padded while length($padded) % 3 != 0;
2734          # translating because it causes problems with the escaped slash. ("\\b" becomes      # This is a fancy PERL trick. The parentheses in the SPLIT pattern
2735          # "\ " no matter what we do.)      # cause the delimiters to be included in the output stream. The
2736          while (length $codedString > 0) {      # GREP removes the empty strings in between the delimiters.
2737                  # Look for the first escape sequence.      my $retVal = join(",", grep { $_ ne '' } split(/(...)/, $padded));
2738                  if ($codedString =~ /^(.*?)\\(\\|b|n|t)/) {      # Clean out the spaces.
2739                          # Here we found it. The text preceding the sequence is in $1. The sequence      $retVal =~ s/ //g;
                         # itself is in $2. First, move the clear text to the return variable.  
                         $retVal .= $1;  
                         $codedString = substr $codedString, (2 + length $1);  
                         # Decode the escape sequence.  
                         my $char = $2;  
                         $char =~ tr/\\btn/\\ \t\n/;  
                         $retVal .= $char;  
                 } else {  
                         # Here there are no more escape sequences. The rest of the string is  
                         # transferred unmodified.  
                         $retVal .= $codedString;  
                         $codedString = "";  
                 }  
         }  
2740          # Return the result.          # Return the result.
2741          return $retVal;          return $retVal;
2742  }  }
2743    =head3 SetPermissions
2744    
2745  =head3 ParseRecord  C<< Tracer::SetPermissions($dirName, $group, $mask, %otherMasks); >>
2746    
2747  C<< my @fields = Tracer::ParseRecord($line); >>  Set the permissions for a directory and all the files and folders inside it.
2748    In addition, the group ownership will be changed to the specified value.
2749    
2750  Parse a tab-delimited data line. The data line is split into field values. Embedded tab  This method is more vulnerable than most to permission and compatability
2751  and new-line characters in the data line must be represented as C<\t> and C<\n>, respectively.  problems, so it does internal error recovery.
 These will automatically be converted.  
2752    
2753  =over 4  =over 4
2754    
2755  =item line  =item dirName
2756    
2757  Line of data containing the tab-delimited fields.  Name of the directory to process.
2758    
2759  =item RETURN  =item group
2760    
2761  Returns a list of the fields found in the data line.  Name of the group to be assigned.
2762    
2763    =item mask
2764    
2765    Permission mask. Bits that are C<1> in this mask will be ORed into the
2766    permission bits of any file or directory that does not already have them
2767    set to 1.
2768    
2769    =item otherMasks
2770    
2771    Map of search patterns to permission masks. If a directory name matches
2772    one of the patterns, that directory and all its members and subdirectories
2773    will be assigned the new pattern. For example, the following would
2774    assign 01664 to most files, but would use 01777 for directories named C<tmp>.
2775    
2776        Tracer::SetPermissions($dirName, 'fig', 01664, '^tmp$' => 01777);
2777    
2778    The list is ordered, so the following would use 0777 for C<tmp1> and
2779    0666 for C<tmp>, C<tmp2>, or C<tmp3>.
2780    
2781        Tracer::SetPermissions($dirName, 'fig', 01664, '^tmp1' => 0777,
2782                                                       '^tmp' => 0666);
2783    
2784    Note that the pattern matches are all case-insensitive, and only directory
2785    names are matched, not file names.
2786    
2787  =back  =back
2788    
2789  =cut  =cut
2790    
2791  sub ParseRecord {  sub SetPermissions {
2792          # Get the parameter.      # Get the parameters.
2793          my ($line) = @_;      my ($dirName, $group, $mask, @otherMasks) = @_;
2794          # Remove the trailing new-line, if any.      # Set up for error recovery.
2795          chomp $line;      eval {
2796          # Split the line read into pieces using the tab character.          # Switch to the specified directory.
2797          my @retVal = split /\t/, $line;          ChDir($dirName);
2798          # Trim and fix the escapes in each piece.          # Get the group ID.
2799          for my $value (@retVal) {          my $gid = getgrnam($group);
2800                  # Trim leading whitespace.          # Get the mask for tracing.
2801                  $value =~ s/^\s+//;          my $traceMask = sprintf("%04o", $mask) . "($mask)";
2802                  # Trim trailing whitespace.          Trace("Fixing permissions for directory $dirName using group $group($gid) and mask $traceMask.") if T(File => 2);
2803                  $value =~ s/\s+$//;          my $fixCount = 0;
2804                  # Delete the carriage returns.          my $lookCount = 0;
2805                  $value =~ s/\r//g;          # @dirs will be a stack of directories to be processed.
2806                  # Convert the escapes into their real values.          my @dirs = (getcwd());
2807                  $value =~ s/\\t/"\t"/ge;          while (scalar(@dirs) > 0) {
2808                  $value =~ s/\\n/"\n"/ge;              # Get the current directory.
2809                my $dir = pop @dirs;
2810                # Check for a match to one of the specified directory names. To do
2811                # that, we need to pull the individual part of the name off of the
2812                # whole path.
2813                my $simpleName = $dir;
2814                if ($dir =~ m!/([^/]+)$!) {
2815                    $simpleName = $1;
2816                }
2817                Trace("Simple directory name for $dir is $simpleName.") if T(File => 4);
2818                # Search for a match.
2819                my $match = 0;
2820                my $i;
2821                for ($i = 0; $i < $#otherMasks && ! $match; $i += 2) {
2822                    my $pattern = $otherMasks[$i];
2823                    if ($simpleName =~ /$pattern/i) {
2824                        $match = 1;
2825                    }
2826                }
2827                # Check for a match. Note we use $i-1 because the loop added 2
2828                # before terminating due to the match.
2829                if ($match && $otherMasks[$i-1] != $mask) {
2830                    # This directory matches one of the incoming patterns, and it's
2831                    # a different mask, so we process it recursively with that mask.
2832                    SetPermissions($dir, $group, $otherMasks[$i-1], @otherMasks);
2833                } else {
2834                    # Here we can process normally. Get all of the non-hidden members.
2835                    my @submems = OpenDir($dir, 1);
2836                    for my $submem (@submems) {
2837                        # Get the full name.
2838                        my $thisMem = "$dir/$submem";
2839                        Trace("Checking member $thisMem.") if T(4);
2840                        $lookCount++;
2841                        if ($lookCount % 1000 == 0) {
2842                            Trace("$lookCount members examined. Current is $thisMem. Mask is $traceMask") if T(File => 3);
2843                        }
2844                        # Fix the group.
2845                        chown -1, $gid, $thisMem;
2846                        # Insure this member is not a symlink.
2847                        if (! -l $thisMem) {
2848                            # Get its info.
2849                            my $fileInfo = stat $thisMem;
2850                            # Only proceed if we got the info. Otherwise, it's a hard link
2851                            # and we want to skip it anyway.
2852                            if ($fileInfo) {
2853                                my $fileMode = $fileInfo->mode;
2854                                if (($fileMode & $mask) != $mask) {
2855                                    # Fix this member.
2856                                    $fileMode |= $mask;
2857                                    chmod $fileMode, $thisMem;
2858                                    $fixCount++;
2859                                }
2860                                # If it's a subdirectory, stack it.
2861                                if (-d $thisMem) {
2862                                    push @dirs, $thisMem;
2863                                }
2864                            }
2865                        }
2866                    }
2867                }
2868            }
2869            Trace("$lookCount files and directories processed, $fixCount fixed.") if T(File => 2);
2870        };
2871        # Check for an error.
2872        if ($@) {
2873            Confess("SetPermissions error: $@");
2874          }          }
         # Return the result.  
         return @retVal;  
2875  }  }
2876    
2877  =head3 Merge  =head3 CompareLists
2878    
2879  C<< my @mergedList = Tracer::Merge(@inputList); >>  C<< my ($inserted, $deleted) = Tracer::CompareLists(\@newList, \@oldList, $keyIndex); >>
2880    
2881  Sort a list of strings and remove duplicates.  Compare two lists of tuples, and return a hash analyzing the differences. The lists
2882    are presumed to be sorted alphabetically by the value in the $keyIndex column.
2883    The return value contains a list of items that are only in the new list
2884    (inserted) and only in the old list (deleted).
2885    
2886  =over 4  =over 4
2887    
2888  =item inputList  =item newList
2889    
2890  List of scalars to sort and merge.  Reference to a list of new tuples.
2891    
2892    =item oldList
2893    
2894    Reference to a list of old tuples.
2895    
2896    =item keyIndex (optional)
2897    
2898    Index into each tuple of its key field. The default is 0.
2899    
2900  =item RETURN  =item RETURN
2901    
2902  Returns a list containing the same elements sorted in ascending order with duplicates  Returns a 2-tuple consisting of a reference to the list of items that are only in the new
2903  removed.  list (inserted) followed by a reference to the list of items that are only in the old
2904    list (deleted).
2905    
2906  =back  =back
2907    
2908  =cut  =cut
2909    
2910  sub Merge {  sub CompareLists {
2911          # Get the input list in sort order.      # Get the parameters.
2912          my @inputList = sort @_;      my ($newList, $oldList, $keyIndex) = @_;
2913          # Only proceed if the list has at least two elements.      if (! defined $keyIndex) {
2914          if (@inputList > 1) {          $keyIndex = 0;
2915                  # Now we want to move through the list splicing out duplicates.      }
2916                  my $i = 0;      # Declare the return variables.
2917                  while ($i < @inputList) {      my ($inserted, $deleted) = ([], []);
2918                          # Get the current entry.      # Loop through the two lists simultaneously.
2919                          my $thisEntry = $inputList[$i];      my ($newI, $oldI) = (0, 0);
2920                          # Find out how many elements duplicate the current entry.      my ($newN, $oldN) = (scalar @{$newList}, scalar @{$oldList});
2921                          my $j = $i + 1;      while ($newI < $newN || $oldI < $oldN) {
2922                          my $dup1 = $i + 1;          # Get the current object in each list. Note that if one
2923                          while ($j < @inputList && $inputList[$j] eq $thisEntry) { $j++; };          # of the lists is past the end, we'll get undef.
2924                          # If the number is nonzero, splice out the duplicates found.          my $newItem = $newList->[$newI];
2925                          if ($j > $dup1) {          my $oldItem = $oldList->[$oldI];
2926                                  splice @inputList, $dup1, $j - $dup1;          if (! defined($newItem) || defined($oldItem) && $newItem->[$keyIndex] gt $oldItem->[$keyIndex]) {
2927                          }              # The old item is not in the new list, so mark it deleted.
2928                          # Now the element at position $dup1 is different from the element before it              push @{$deleted}, $oldItem;
2929                          # at position $i. We push $i forward one position and start again.              $oldI++;
2930                          $i++;          } elsif (! defined($oldItem) || $oldItem->[$keyIndex] gt $newItem->[$keyIndex]) {
2931                # The new item is not in the old list, so mark it inserted.
2932                push @{$inserted}, $newItem;
2933                $newI++;
2934            } else {
2935                # The item is in both lists, so push forward.
2936                $oldI++;
2937                $newI++;
2938                  }                  }
2939          }          }
2940          # Return the merged list.      # Return the result.
2941          return @inputList;      return ($inserted, $deleted);
2942  }  }
2943    
2944  =head3 GetFile  =head3 GetLine
2945    
2946  C<< my $fileContents = Tracer::GetFile($fileName); >>  C<< my @data = Tracer::GetLine($handle); >>
2947    
2948  Return the entire contents of a file.  Read a line of data from a tab-delimited file.
2949    
2950  =over 4  =over 4
2951    
2952  =item fileName  =item handle
2953    
2954  Name of the file to read.  Open file handle from which to read.
2955    
2956  =item RETURN  =item RETURN
2957    
2958  Returns the entire file as a single string. If an error occurs, will return  Returns a list of the fields in the record read. The fields are presumed to be
2959  an empty string.  tab-delimited. If we are at the end of the file, then an empty list will be
2960    returned. If an empty line is read, a single list item consisting of a null
2961    string will be returned.
2962    
2963  =back  =back
2964    
2965  =cut  =cut
2966    
2967  sub GetFile {  sub GetLine {
2968          # Get the parameters.          # Get the parameters.
2969          my ($fileName) = @_;      my ($handle) = @_;
2970          # Declare the return variable.          # Declare the return variable.
2971          my $retVal = "";      my @retVal = ();
2972          # Open the file for input.      Trace("File position is " . tell($handle) . ". EOF flag is " . eof($handle) . ".") if T(File => 4);
2973          my $ok = open INPUTFILE, "<$fileName";      # Read from the file.
2974          if (!$ok) {      my $line = <$handle>;
2975                  # If we had an error, trace it. We will automatically return a null string.      # Only proceed if we found something.
2976                  Trace(0, "Could not open \"$fileName\" for input.");      if (defined $line) {
2977          } else {          # Remove the new-line.
2978                  # Read the whole file into the return variable.          chomp $line;
2979                  while (<INPUTFILE>) {          Trace("Line read: $line") if T(File => 4);
2980                          $retVal .= $_;          # If the line is empty, return a single empty string; otherwise, parse
2981            # it into fields.
2982            if ($line eq "") {
2983                push @retVal, "";
2984            } else {
2985                push @retVal, split /\t/,$line;
2986                  }                  }
2987                  # Close it.      } else {
2988                  close INPUTFILE;          # Trace the reason the read failed.
2989            Trace("End of file: $!") if T(File => 3);
2990          }          }
2991          # Return the file's contents.      # Return the result.
2992          return $retVal;      return @retVal;
2993  }  }
2994    
2995  =head3 QTrace  =head3 PutLine
2996    
2997  C<< my $data = QTrace($format); >>  C<< Tracer::PutLine($handle, \@fields); >>
2998    
2999  Return the queued trace data in the specified format.  Write a line of data to a tab-delimited file. The specified field values will be
3000    output in tab-separated form, with a trailing new-line.
3001    
3002  =over 4  =over 4
3003    
3004  =item format  =item handle
3005    
3006  C<html> to format the data as an HTML list, C<text> to format it as straight text.  Output file handle.
3007    
3008    =item fields
3009    
3010    List of field values.
3011    
3012  =back  =back
3013    
3014  =cut  =cut
3015    
3016  sub QTrace {  sub PutLine {
3017          # Get the parameter.      # Get the parameters.
3018          my ($format) = @_;      my ($handle, $fields) = @_;
3019          # Create the return variable.      # Write the data.
3020          my $retVal = "";      print $handle join("\t", @{$fields}) . "\n";
         # Process according to the format.  
         if ($format =~ m/^HTML$/i) {  
                 # Convert the queue into an HTML list.  
                 $retVal = "<ul>\n";  
                 for my $line (@Queue) {  
                         my $escapedLine = CGI::escapeHTML($line);  
                         $retVal .= "<li>$escapedLine</li>\n";  
3021                  }                  }
3022                  $retVal .= "</ul>\n";  
3023          } elsif ($format =~ m/^TEXT$/i) {  =head3 GenerateURL
3024                  # Convert the queue into a list of text lines.  
3025                  $retVal = join("\n", @Queue) . "\n";  C<< my $queryUrl = Tracer::GenerateURL($page, %parameters); >>
3026    
3027    Generate a GET-style URL for the specified page with the specified parameter
3028    names and values. The values will be URL-escaped automatically. So, for
3029    example
3030    
3031        Tracer::GenerateURL("form.cgi", type => 1, string => "\"high pass\" or highway")
3032    
3033    would return
3034    
3035        form.cgi?type=1;string=%22high%20pass%22%20or%20highway
3036    
3037    =over 4
3038    
3039    =item page
3040    
3041    Page URL.
3042    
3043    =item parameters
3044    
3045    Hash mapping parameter names to parameter values.
3046    
3047    =item RETURN
3048    
3049    Returns a GET-style URL that goes to the specified page and passes in the
3050    specified parameters and values.
3051    
3052    =back
3053    
3054    =cut
3055    
3056    sub GenerateURL {
3057        # Get the parameters.
3058        my ($page, %parameters) = @_;
3059        # Prime the return variable with the page URL.
3060        my $retVal = $page;
3061        # Loop through the parameters, creating parameter elements in a list.
3062        my @parmList = map { "$_=" . uri_escape($parameters{$_}) } keys %parameters;
3063        # If the list is nonempty, tack it on.
3064        if (@parmList) {
3065            $retVal .= "?" . join(";", @parmList);
3066          }          }
3067          # Clear the queue.      # Return the result.
         @Queue = ();  
         # Return the formatted list.  
3068          return $retVal;          return $retVal;
3069  }  }
3070    
3071  =head3 Confess  =head3 ApplyURL
   
 C<< Confess($message); >>  
3072    
3073  Trace the call stack and abort the program with the specified message. The stack  C<< Tracer::ApplyURL($table, $target, $url); >>
 trace will only appear if the trace level for this package is 1 or more. When used with  
 the OR operator, this method can function as a debugging assert. So, for example  
3074    
3075  C<< ($recNum >= 0) || Confess("Invalid record number $recNum."); >>  Run through a two-dimensional table (or more accurately, a list of lists), converting the
3076    I<$target> column to HTML text having a hyperlink to a URL in the I<$url> column. The
3077    URL column will be deleted by this process and the target column will be HTML-escaped.
3078    
3079  Will abort the program with a stack trace if the value of C<$recNum> is negative.  This provides a simple way to process the results of a database query into something
3080    displayable by combining a URL with text.
3081    
3082  =over 4  =over 4
3083    
3084  =item message  =item table
3085    
3086  Message to include in the trace.  Reference to a list of lists. The elements in the containing list will be updated by
3087    this method.
3088    
3089    =item target
3090    
3091    The index of the column to be converted into HTML.
3092    
3093    =item url
3094    
3095    The index of the column containing the URL. Note that the URL must have a recognizable
3096    C<http:> at the beginning.
3097    
3098  =back  =back
3099    
3100  =cut  =cut
3101    
3102  sub Confess {  sub ApplyURL {
3103          # Get the parameters.          # Get the parameters.
3104          my ($message) = @_;      my ($table, $target, $url) = @_;
3105          # Trace the call stack.      # Loop through the table.
3106          Cluck($message) if T(1);      for my $row (@{$table}) {
3107          # Abort the program.          # Apply the URL to the target cell.
3108          die $message;          $row->[$target] = CombineURL($row->[$target], $row->[$url]);
3109            # Delete the URL from the row.
3110            delete $row->[$url];
3111        }
3112  }  }
3113    
3114  =head3 Cluck  =head3 CombineURL
3115    
3116  C<< Cluck($message); >>  C<< my $combinedHtml = Tracer::CombineURL($text, $url); >>
3117    
3118  Trace the call stack. Note that for best results, you should qualify the call with a  This method will convert the specified text into HTML hyperlinked to the specified
3119  trace condition. For example,  URL. The hyperlinking will only take place if the URL looks legitimate: that is, it
3120    is defined and begins with an C<http:> header.
3121    
3122  C<< Cluck("Starting record parse.") if T(3); >>  =over 4
3123    
3124  will only trace the stack if the trace level for the package is 3 or more.  =item text
3125    
3126  =over 4  Text to return. This will be HTML-escaped automatically.
3127    
3128  =item message  =item url
3129    
3130  Message to include in the trace.  A URL to be hyperlinked to the text. If it does not look like a URL, then the text
3131    will be returned without any hyperlinking.
3132    
3133    =item RETURN
3134    
3135    Returns the original text, HTML-escaped, with the URL hyperlinked to it. If the URL
3136    doesn't look right, the HTML-escaped text will be returned without any further
3137    modification.
3138    
3139  =back  =back
3140    
3141  =cut  =cut
3142    
3143  sub Cluck {  sub CombineURL {
3144          # Get the parameters.          # Get the parameters.
3145          my ($message) = @_;      my ($text, $url) = @_;
3146          my $confession = longmess($message);      # Declare the return variable.
3147          # Convert the confession to a series of trace messages.      my $retVal = CGI::escapeHTML($text);
3148          for my $line (split /\s*\n/, $confession) {      # Verify the URL.
3149                  Trace($line);      if (defined($url) && $url =~ m!http://!i) {
3150            # It's good, so we apply it to the text.
3151            $retVal = "<a href=\"$url\">$retVal</a>";
3152          }          }
3153        # Return the result.
3154        return $retVal;
3155  }  }
3156    
   
3157  1;  1;

Legend:
Removed from v.1.2  
changed lines
  Added in v.1.79

MCS Webmaster
ViewVC Help
Powered by ViewVC 1.0.3