[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.92, Thu Dec 6 13:59:04 2007 UTC revision 1.93, Tue Feb 5 02:17:29 2008 UTC
# Line 296  Line 296 
296  my $SetupCount = 0;         # number of times TSetup called  my $SetupCount = 0;         # number of times TSetup called
297  my $AllTrace = 0;           # TRUE if we are tracing all categories.  my $AllTrace = 0;           # TRUE if we are tracing all categories.
298    
299  =head2 Public Methods  =head2 Tracing Methods
300    
301    =head3 Setups
302    
303        my $count = Tracer::Setups();
304    
305    Return the number of times L</TSetup> has been called.
306    
307    This method allows for the creation of conditional tracing setups where, for example, we
308    may want to set up tracing if nobody else has done it before us.
309    
310    =cut
311    
312    sub Setups {
313        return $SetupCount;
314    }
315    
316  =head3 TSetup  =head3 TSetup
317    
# Line 372  Line 387 
387      $SetupCount++;      $SetupCount++;
388  }  }
389    
390  =head3 StandardSetup  =head3 SetLevel
391    
392      my ($options, @parameters) = StandardSetup(\@categories, \%options, $parmHelp, @ARGV);      Tracer::SetLevel($newLevel);
393    
394  This method performs standard command-line parsing and tracing setup. The return  Modify the trace level. A higher trace level will cause more messages to appear.
 values are a hash of the command-line options and a list of the positional  
 parameters. Tracing is automatically set up and the command-line options are  
 validated.  
395    
396  This is a complex method that does a lot of grunt work. The parameters can  =over 4
 be more easily understood, however, once they are examined individually.  
397    
398  The I<categories> parameter is the most obtuse. It is a reference to a list of  =item newLevel
 special-purpose tracing categories. Most tracing categories are PERL package  
 names. So, for example, if you wanted to turn on tracing inside the B<Sprout>,  
 B<ERDB>, and B<SproutLoad> packages, you would specify the categories  
399    
400      ["Sprout", "SproutLoad", "ERDB"]  Proposed new trace level.
401    
402  This would cause trace messages in the specified three packages to appear in  =back
 the output. There are two special tracing categories that are automatically  
 handled by this method. In other words, if you used L</TSetup> you would need  
 to include these categories manually, but if you use this method they are turned  
 on automatically.  
403    
404  =over 4  =cut
405    
406  =item SQL  sub SetLevel {
407        $TraceLevel = $_[0];
408    }
409    
410  Traces SQL commands and activity.  =head3 ParseTraceDate
411    
412  =item Tracer      my $time = Tracer::ParseTraceDate($dateString);
413    
414  Traces error messages and call stacks.  Convert a date from the trace file into a PERL timestamp.
415    
416  =back  =over 4
417    
418  C<SQL> is only turned on if the C<-sql> option is specified in the command line.  =item dateString
 The trace level is specified using the C<-trace> command-line option. For example,  
 the following command line for C<TransactFeatures> turns on SQL tracing and runs  
 all tracing at level 3.  
419    
420      TransactFeatures -trace=3 -sql register ../xacts IDs.tbl  The date string from the trace file. The format of the string is determined by the
421    L</Now> method.
422    
423  Standard tracing is output to the standard output and echoed to the file  =item RETURN
 C<trace>I<$$>C<.log> in the FIG temporary directory, where I<$$> is the  
 process ID. You can also specify the C<user> parameter to put a user ID  
 instead of a process ID in the trace file name. So, for example  
424    
425  The default trace level is 2. To get all messages, specify a trace level of 4.  Returns a PERL time, that is, a number of seconds since the epoch, or C<undef> if
426  For a genome-by-genome update, use 3.  the time string is invalid.
427    
428      TransactFeatures -trace=3 -sql -user=Bruce register ../xacts IDs.tbl  =back
429    
430  would send the trace output to C<traceBruce.log> in the temporary directory.  =cut
431    
432  The I<options> parameter is a reference to a hash containing the command-line  sub ParseTraceDate {
433  options, their default values, and an explanation of what they mean. Command-line      # Get the parameters.
434  options may be in the form of switches or keywords. In the case of a switch, the      my ($dateString) = @_;
435  option value is 1 if it is specified and 0 if it is not specified. In the case      # Declare the return variable.
436  of a keyword, the value is separated from the option name by an equal sign. You      my $retVal;
437  can see this last in the command-line example above.      # Parse the date.
438        if ($dateString =~ m#(\d+)/(\d+)/(\d+)\s+(\d+):(\d+):(\d+)#) {
439            # Create a time object. Note we need to convert the day, month,
440            # and year to a different base. Years count from 1900, and
441            # the internal month value is relocated to January = 0.
442            $retVal = timelocal($6, $5, $4, $2, $1 - 1, $3 - 1900);
443        }
444        # Return the result.
445        return $retVal;
446    }
447    
448  You can specify a different default trace level by setting C<$options->{trace}>  =head3 LogErrors
 prior to calling this method.  
449    
450  An example at this point would help. Consider, for example, the command-line utility      Tracer::LogErrors($fileName);
 C<TransactFeatures>. It accepts a list of positional parameters plus the options  
 C<safe>, C<noAlias>, C<start>, and C<tblFiles>. To start up this command, we execute  
 the following code.  
451    
452      my ($options, @parameters) = Tracer::StandardSetup(["DocUtils"],  Route the standard error output to a log file.
                         { safe => [0, "use database transactions"],  
                           noAlias => [0, "do not expect aliases in CHANGE transactions"],  
                           start => [' ', "start with this genome"],  
                           tblFiles => [0, "output TBL files containing the corrected IDs"] },  
                         "<command> <transactionDirectory> <IDfile>",  
                       @ARGV);  
453    
454    =over 4
455    
456  The call to C<ParseCommand> specifies the default values for the options and  =item fileName
 stores the actual options in a hash that is returned as C<$options>. The  
 positional parameters are returned in C<@parameters>.  
457    
458  The following is a sample command line for C<TransactFeatures>.  Name of the file to receive the error output.
459    
460      TransactFeatures -trace=2 -noAlias register ../xacts IDs.tbl  =back
461    
462  Single and double hyphens are equivalent. So, you could also code the  =cut
 above command as  
463    
464      TransactFeatures --trace=2 --noAlias register ../xacts IDs.tbl  sub LogErrors {
465        # Get the file name.
466        my ($fileName) = @_;
467        # Open the file as the standard error output.
468        open STDERR, '>', $fileName;
469    }
470    
471  In this case, C<register>, C<../xacts>, and C<IDs.tbl> are the positional  =head3 Trace
 parameters, and would find themselves in I<@parameters> after executing the  
 above code fragment. The tracing would be set to level 2, and the categories  
 would be C<Tracer>, and <DocUtils>. C<Tracer> is standard,  
 and C<DocUtils> was included because it came in within the first parameter  
 to this method. The I<$options> hash would be  
472    
473      { trace => 2, sql => 0, safe => 0,      Trace($message);
       noAlias => 1, start => ' ', tblFiles => 0 }  
474    
475  Use of C<StandardSetup> in this way provides a simple way of performing  Write a trace message to the target location specified in L</TSetup>. If there has not been
476  standard tracing setup and command-line parsing. Note that the caller is  any prior call to B<TSetup>.
 not even aware of the command-line switches C<-trace> and C<-sql>, which  
 are used by this method to control the tracing. If additional tracing features  
 need to be added in the future, they can be processed by this method without  
 upsetting the command-line utilities.  
477    
478  If the C<background> option is specified on the command line, then the  =over 4
 standard and error outputs will be directed to files in the temporary  
 directory, using the same suffix as the trace file. So, if the command  
 line specified  
479    
480      -user=Bruce -background  =item message
481    
482  then the trace output would go to C<traceBruce.log>, the standard output to  Message to write.
 C<outBruce.log>, and the error output to C<errBruce.log>. This is designed to  
 simplify starting a command in the background.  
483    
484  The user name is also used as the tracing key for L</Emergency Tracing>.  =back
 Specifying a value of C<E> for the trace level causes emergency tracing to  
 be used instead of custom tracing. If the user name is not specified,  
 the tracing key is taken from the C<Tracing> environment variable. If there  
 is no value for that variable, the tracing key will be computed from the PID.  
485    
486  Finally, if the special option C<-help> is specified, the option  =cut
 names will be traced at level 0 and the program will exit without processing.  
 This provides a limited help capability. For example, if the user enters  
487    
488      TransactFeatures -help  sub Trace {
489        # Get the parameters.
490        my ($message) = @_;
491        # Get the timestamp.
492        my $timeStamp = Now();
493        # Format the message. Note we strip off any line terminators at the end.
494        my $prefix = "[$timeStamp] <$LastCategory>: ";
495        my $formatted = $prefix . Strip($message);
496        # Process according to the destination.
497        if ($Destination eq "TEXT") {
498            # Write the message to the standard output.
499            print "$formatted\n";
500        } elsif ($Destination eq "ERROR") {
501            # Write the message to the error output.
502            print STDERR "$formatted\n";
503        } elsif ($Destination eq "QUEUE") {
504            # Push the message into the queue.
505            push @Queue, "$formatted";
506        } elsif ($Destination eq "HTML") {
507            # Convert the message to HTML and write it to the standard output.
508            my $escapedMessage = CGI::escapeHTML($message);
509            print "<p>$timeStamp $LastCategory: $escapedMessage</p>\n";
510        } elsif ($Destination eq "WARN") {
511           # Emit the message as a warning.
512           warn $message;
513        } elsif ($Destination =~ m/^>>/) {
514            # Write the trace message to an output file.
515            (open TRACING, $Destination) || die "Tracing open for \"$Destination\" failed: $!";
516            print TRACING "$formatted\n";
517            close TRACING;
518            # If the Tee flag is on, echo it to the standard output.
519            if ($TeeFlag) {
520                print "$formatted\n";
521            }
522        }
523    }
524    
525  he would see the following output.  =head3 T
526    
527      TransactFeatures [options] <command> <transactionDirectory> <IDfile>      my $switch = T($category, $traceLevel);
         -trace    tracing level (default E)  
         -sql      trace SQL commands  
         -safe     use database transactions  
         -noAlias  do not expect aliases in CHANGE transactions  
         -start    start with this genome  
         -tblFiles output TBL files containing the corrected IDs  
528    
529  The caller has the option of modifying the tracing scheme by placing a value      or
 for C<trace> in the incoming options hash. The default value can be overridden,  
 or the tracing to the standard output can be turned off by suffixing a minus  
 sign to the trace level. So, for example,  
530    
531      { trace => [0, "tracing level (default 0)"],      my $switch = T($traceLevel);
        ...  
532    
533  would set the default trace level to 0 instead of E, while  Return TRUE if the trace level is at or above a specified value and the specified category
534    is active, else FALSE. If no category is specified, the caller's package name is used.
535    
536      { trace => ["2-", "tracing level (default 2)"],  =over 4
        ...  
537    
538  would set the default to 2, but trace only to the log file, not to the  =item category
 standard output.  
539    
540  The parameters to this method are as follows.  Category to which the message belongs. If not specified, the caller's package name is
541    used.
542    
543  =over 4  =item traceLevel
544    
545  =item categories  Relevant tracing level.
546    
547  Reference to a list of tracing category names. These should be names of  =item RETURN
 packages whose internal workings will need to be debugged to get the  
 command working.  
548    
549  =item options  TRUE if a message at the specified trace level would appear in the trace, else FALSE.
550    
551  Reference to a hash containing the legal options for the current command mapped  =back
 to their default values and descriptions. The user can override the defaults  
 by specifying the options as command-line switches prefixed by a hyphen.  
 Tracing-related options may be added to this hash. If the C<-h> option is  
 specified on the command line, the option descriptions will be used to  
 explain the options. To turn off tracing to the standard output, add a  
 minus sign to the value for C<trace> (see above).  
   
 =item parmHelp  
   
 A string that vaguely describes the positional parameters. This is used  
 if the user specifies the C<-h> option.  
   
 =item argv  
   
 List of command line parameters, including the option switches, which must  
 precede the positional parameters and be prefixed by a hyphen.  
   
 =item RETURN  
   
 Returns a list. The first element of the list is the reference to a hash that  
 maps the command-line option switches to their values. These will either be the  
 default values or overrides specified on the command line. The remaining  
 elements of the list are the position parameters, in order.  
   
 =back  
552    
553  =cut  =cut
554    
555  sub StandardSetup {  sub T {
556        # Declare the return variable.
557        my $retVal = 0;
558        # Only proceed if tracing is turned on.
559        if ($Destination ne "NONE") {
560      # Get the parameters.      # Get the parameters.
561      my ($categories, $options, $parmHelp, @argv) = @_;          my ($category, $traceLevel) = @_;
562      # Get the default tracing key.          if (!defined $traceLevel) {
563      my $tkey = EmergencyKey();              # Here we have no category, so we need to get the calling package.
564      # Add the tracing options.              # The calling package is normally the first parameter. If it is
565      if (! exists $options->{trace}) {              # omitted, the first parameter will be the tracelevel. So, the
566          $options->{trace} = ['2', "tracing level (E for emergency tracing)"];              # first thing we do is shift the so-called category into the
567      }              # $traceLevel variable where it belongs.
568      $options->{sql} = [0, "turn on SQL tracing"];              $traceLevel = $category;
569      $options->{help} = [0, "display command-line options"];              my ($package, $fileName, $line) = caller;
570      $options->{user} = [$tkey, "tracing key"];              # If there is no calling package, we default to "main".
571      $options->{background} = [0, "spool standard and error output"];              if (!$package) {
572      # Create a parsing hash from the options hash. The parsing hash                  $category = "main";
     # contains the default values rather than the default value  
     # and the description. While we're at it, we'll memorize the  
     # length of the longest option name.  
     my $longestName = 0;  
     my %parseOptions = ();  
     for my $key (keys %{$options}) {  
         if (length $key > $longestName) {  
             $longestName = length $key;  
         }  
         $parseOptions{$key} = $options->{$key}->[0];  
     }  
     # Parse the command line.  
     my ($retOptions, @retParameters) = ParseCommand(\%parseOptions, @argv);  
     # Get the logfile suffix.  
     my $suffix = $retOptions->{user};  
     # Check for background mode.  
     if ($retOptions->{background}) {  
         my $outFileName = "$FIG_Config::temp/out$suffix.log";  
         my $errFileName = "$FIG_Config::temp/err$suffix.log";  
         open STDOUT, ">$outFileName";  
         open STDERR, ">$errFileName";  
         # Check for phone support. If we have phone support and a phone number,  
         # we want to turn it on.  
         if ($ENV{PHONE} && defined($FIG_Config::phone)) {  
             $retOptions->{phone} = $ENV{PHONE};  
         }  
     }  
     # Now we want to set up tracing. First, we need to know if the user  
     # wants emergency tracing.  
     if ($retOptions->{trace} eq 'E') {  
         ETracing($retOptions->{user});  
     } else {  
         # Here the tracing is controlled from the command line.  
         my @cats = @{$categories};  
         if ($retOptions->{sql}) {  
             push @cats, "SQL";  
         }  
         # Add the default categories.  
         push @cats, "Tracer";  
         # Next, we create the category string by joining the categories.  
         my $cats = join(" ", @cats);  
         # Check to determine whether or not the caller wants to turn off tracing  
         # to the standard output.  
         my $traceLevel = $retOptions->{trace};  
         my $textOKFlag = 1;  
         if ($traceLevel =~ /^(.)-/) {  
             $traceLevel = $1;  
             $textOKFlag = 0;  
         }  
         # Now we set up the trace mode.  
         my $traceMode;  
         # Verify that we can open a file in the FIG temporary directory.  
         my $traceFileName = "$FIG_Config::temp/trace$suffix.log";  
         if (open TESTTRACE, ">$traceFileName") {  
             # Here we can trace to a file.  
             $traceMode = ">$traceFileName";  
             if ($textOKFlag) {  
                 # Echo to standard output if the text-OK flag is set.  
                 $traceMode = "+$traceMode";  
             }  
             # Close the test file.  
             close TESTTRACE;  
         } else {  
             # Here we can't trace to a file. We trace to the standard output if it's  
             # okay, and the error log otherwise.  
             if ($textOKFlag) {  
                 $traceMode = "TEXT";  
573              } else {              } else {
574                  $traceMode = "WARN";                  my @cats = split /::/, $package;
575              }                  $category = $cats[$#cats];
         }  
         # Now set up the tracing.  
         TSetup("$traceLevel $cats", $traceMode);  
     }  
     # Check for the "help" option. If it is specified, dump the command-line  
     # options and exit the program.  
     if ($retOptions->{help}) {  
         $0 =~ m#[/\\](\w+)(\.pl)?$#i;  
         print "$1 [options] $parmHelp\n";  
         for my $key (sort keys %{$options}) {  
             my $name = Pad($key, $longestName, 0, ' ');  
             my $desc = $options->{$key}->[1];  
             if ($options->{$key}->[0]) {  
                 $desc .= " (default " . $options->{$key}->[0] . ")";  
576              }              }
             print "  $name $desc\n";  
577          }          }
578          exit(0);          # Save the category name.
579            $LastCategory = $category;
580            # Convert it to lower case before we hash it.
581            $category = lc $category;
582            # Use the category and tracelevel to compute the result.
583            if (ref $traceLevel) {
584                Confess("Bad trace level.");
585            } elsif (ref $TraceLevel) {
586                Confess("Bad trace config.");
587      }      }
588      # Trace the options, if applicable.          $retVal = ($traceLevel <= $TraceLevel && ($AllTrace || exists $Categories{$category}));
     if (T(3)) {  
         my @parms = grep { $retOptions->{$_} } keys %{$retOptions};  
         Trace("Selected options: " . join(", ", sort @parms) . ".");  
589      }      }
590      # Return the parsed parameters.      # Return the computed result.
591      return ($retOptions, @retParameters);      return $retVal;
592  }  }
593    
594  =head3 Setups  =head3 QTrace
595    
596      my $count = Tracer::Setups();      my $data = QTrace($format);
597    
598  Return the number of times L</TSetup> has been called.  Return the queued trace data in the specified format.
599    
600  This method allows for the creation of conditional tracing setups where, for example, we  =over 4
601  may want to set up tracing if nobody else has done it before us.  
602    =item format
603    
604    C<html> to format the data as an HTML list, C<text> to format it as straight text.
605    
606    =back
607    
608  =cut  =cut
609    
610  sub Setups {  sub QTrace {
611      return $SetupCount;      # Get the parameter.
612        my ($format) = @_;
613        # Create the return variable.
614        my $retVal = "";
615        # Only proceed if there is an actual queue.
616        if (@Queue) {
617            # Process according to the format.
618            if ($format =~ m/^HTML$/i) {
619                # Convert the queue into an HTML list.
620                $retVal = "<ul>\n";
621                for my $line (@Queue) {
622                    my $escapedLine = CGI::escapeHTML($line);
623                    $retVal .= "<li>$escapedLine</li>\n";
624                }
625                $retVal .= "</ul>\n";
626            } elsif ($format =~ m/^TEXT$/i) {
627                # Convert the queue into a list of text lines.
628                $retVal = join("\n", @Queue) . "\n";
629            }
630            # Clear the queue.
631            @Queue = ();
632        }
633        # Return the formatted list.
634        return $retVal;
635  }  }
636    
637  =head3 Open  =head3 Confess
638    
639      my $handle = Open($fileHandle, $fileSpec, $message);      Confess($message);
640    
641  Open a file.  Trace the call stack and abort the program with the specified message. When used with
642    the OR operator and the L</Assert> method, B<Confess> can function as a debugging assert.
643    So, for example
644    
645  The I<$fileSpec> is essentially the second argument of the PERL C<open>      Assert($recNum >= 0) || Confess("Invalid record number $recNum.");
 function. The mode is specified using Unix-like shell information. So, for  
 example,  
646    
647      Open(\*LOGFILE, '>>/usr/spool/news/twitlog', "Could not open twit log.");  Will abort the program with a stack trace if the value of C<$recNum> is negative.
648    
649  would open for output appended to the specified file, and  =over 4
650    
651      Open(\*DATASTREAM, "| sort -u >$outputFile", "Could not open $outputFile.");  =item message
652    
653  would open a pipe that sorts the records written and removes duplicates. Note  Message to include in the trace.
 the use of file handle syntax in the Open call. To use anonymous file handles,  
 code as follows.  
654    
655      my $logFile = Open(undef, '>>/usr/spool/news/twitlog', "Could not open twit log.");  =back
656    
657  The I<$message> parameter is used if the open fails. If it is set to C<0>, then  =cut
 the open returns TRUE if successful and FALSE if an error occurred. Otherwise, a  
 failed open will throw an exception and the third parameter will be used to construct  
 an error message. If the parameter is omitted, a standard message is constructed  
 using the file spec.  
658    
659      Could not open "/usr/spool/news/twitlog"  sub Confess {
660        # Get the parameters.
661        my ($message) = @_;
662        if (! defined($FIG_Config::no_tool_hdr)) {
663            # Here we have a tool header. Display its length so that the user can adjust the line numbers.
664            my $toolHeaderFile = "$FIG_Config::fig_disk/dist/releases/current/$FIG_Config::arch/tool_hdr";
665            # Only proceed if the tool header file is actually present.
666            if (-f $toolHeaderFile) {
667                my @lines = GetFile($toolHeaderFile);
668                Trace("Tool header has " . scalar(@lines) . " lines.");
669            }
670        }
671        # Trace the call stack.
672        Cluck($message);
673        # Abort the program.
674        croak(">>> $message");
675    }
676    
677  Note that the mode characters are automatically cleaned from the file name.  =head3 Assert
 The actual error message from the file system will be captured and appended to the  
 message in any case.  
678    
679      Could not open "/usr/spool/news/twitlog": file not found.      Assert($condition1, $condition2, ... $conditionN);
680    
681  In some versions of PERL the only error message we get is a number, which  Return TRUE if all the conditions are true. This method can be used in conjunction with
682  corresponds to the C++ C<errno> value.  the OR operator and the L</Confess> method as a debugging assert.
683    So, for example
684    
685      Could not open "/usr/spool/news/twitlog": 6.      Assert($recNum >= 0) || Confess("Invalid record number $recNum.");
686    
687  =over 4  Will abort the program with a stack trace if the value of C<$recNum> is negative.
688    
689  =item fileHandle  =cut
690    sub Assert {
691        my $retVal = 1;
692        LOOP: for my $condition (@_) {
693            if (! $condition) {
694                $retVal = 0;
695                last LOOP;
696            }
697        }
698        return $retVal;
699    }
700    
701  File handle. If this parameter is C<undef>, a file handle will be generated  =head3 Cluck
 and returned as the value of this method.  
702    
703  =item fileSpec      Cluck($message);
704    
705  File name and mode, as per the PERL C<open> function.  Trace the call stack. Note that for best results, you should qualify the call with a
706    trace condition. For example,
707    
708  =item message (optional)      Cluck("Starting record parse.") if T(3);
709    
710  Error message to use if the open fails. If omitted, a standard error message  will only trace the stack if the trace level for the package is 3 or more.
 will be generated. In either case, the error information from the file system  
 is appended to the message. To specify a conditional open that does not throw  
 an error if it fails, use C<0>.  
711    
712  =item RETURN  =over 4
713    
714  Returns the name of the file handle assigned to the file, or C<undef> if the  =item message
715  open failed.  
716    Message to include in the trace.
717    
718  =back  =back
719    
720  =cut  =cut
721    
722  sub Open {  sub Cluck {
723      # Get the parameters.      # Get the parameters.
724      my ($fileHandle, $fileSpec, $message) = @_;      my ($message) = @_;
725      # Attempt to open the file.      # Trace what's happening.
726      my $rv = open $fileHandle, $fileSpec;      Trace("Stack trace for event: $message");
727      # If the open failed, generate an error message.      my $confession = longmess($message);
728      if (! $rv) {      # Convert the confession to a series of trace messages. Note we skip any
729          # Save the system error message.      # messages relating to calls into Tracer.
730          my $sysMessage = $!;      for my $line (split /\s*\n/, $confession) {
731          # See if we need a default message.          Trace($line) if ($line !~ /Tracer\.pm/);
         if (!$message) {  
             # Clean any obvious mode characters and leading spaces from the  
             # filename.  
             my ($fileName) = FindNamePart($fileSpec);  
             $message = "Could not open \"$fileName\"";  
         }  
         # Terminate with an error using the supplied message and the  
         # error message from the file system.  
         Confess("$message: $!");  
732      }      }
     # Return the file handle.  
     return $fileHandle;  
733  }  }
734    
735  =head3 FindNamePart  =head3 ScriptSetup
   
     my ($fileName, $start, $len) = Tracer::FindNamePart($fileSpec);  
   
 Extract the portion of a file specification that contains the file name.  
736    
737  A file specification is the string passed to an C<open> call. It specifies the file      my ($cgi, $varHash) = ScriptSetup($noTrace);
 mode and name. In a truly complex situation, it can specify a pipe sequence. This  
 method assumes that the file name is whatever follows the first angle bracket  
 sequence.  So, for example, in the following strings the file name is  
 C</usr/fig/myfile.txt>.  
738    
739      >>/usr/fig/myfile.txt  Perform standard tracing and debugging setup for scripts. The value returned is
740      </usr/fig/myfile.txt  the CGI object followed by a pre-built variable hash. At the end of the script,
741      | sort -u > /usr/fig/myfile.txt  the client should call L</ScriptFinish> to output the web page.
742    
743  If the method cannot find a file name using its normal methods, it will return the  This method calls L</ETracing> to configure tracing, which allows the tracing
744  whole incoming string.  to be configured via the emergency tracing form on the debugging control panel.
745    Tracing will then be turned on automatically for all programs that use the L</ETracing>
746    method, which includes every program that uses this method or L</StandardSetup>.
747    
748  =over 4  =over 4
749    
750  =item fileSpec  =item noTrace (optional)
751    
752  File specification string from which the file name is to be extracted.  If specified, tracing will be suppressed. This is useful if the script wants to set up
753    tracing manually.
754    
755  =item RETURN  =item RETURN
756    
757  Returns a three-element list. The first element contains the file name portion of  Returns a two-element list consisting of a CGI query object and a variable hash for
758  the specified string, or the whole string if a file name cannot be found via normal  the output page.
 methods. The second element contains the start position of the file name portion and  
 the third element contains the length.  
759    
760  =back  =back
761    
762  =cut  =cut
763  #: Return Type $;  
764  sub FindNamePart {  sub ScriptSetup {
765      # Get the parameters.      # Get the parameters.
766      my ($fileSpec) = @_;      my ($noTrace) = @_;
767      # Default to the whole input string.      # Get the CGI query object.
768      my ($retVal, $pos, $len) = ($fileSpec, 0, length $fileSpec);      my $cgi = CGI->new();
769      # Parse out the file name if we can.      # Set up tracing if it's not suppressed.
770      if ($fileSpec =~ m/(<|>>?)(.+?)(\s*)$/) {      ETracing($cgi) unless $noTrace;
771          $retVal = $2;      # Create the variable hash.
772          $len = length $retVal;      my $varHash = { results => '' };
773          $pos = (length $fileSpec) - (length $3) - $len;      # Return the query object and variable hash.
774      }      return ($cgi, $varHash);
     # Return the result.  
     return ($retVal, $pos, $len);  
775  }  }
776    
777  =head3 OpenDir  =head3 ETracing
778    
779      my @files = OpenDir($dirName, $filtered, $flag);      ETracing($parameter);
780    
781  Open a directory and return all the file names. This function essentially performs  Set up emergency tracing. Emergency tracing is tracing that is turned
782  the functions of an C<opendir> and C<readdir>. If the I<$filtered> parameter is  on automatically for any program that calls this method. The emergency
783  set to TRUE, all filenames beginning with a period (C<.>), dollar sign (C<$>),  tracing parameters are stored in a a file identified by a tracing key.
784  or pound sign (C<#>) and all filenames ending with a tilde C<~>) will be  If this method is called with a CGI object, then the tracing key is
785  filtered out of the return list. If the directory does not open and I<$flag> is not  taken from a cookie. If it is called with no parameters, then the tracing
786  set, an exception is thrown. So, for example,  key is taken from an environment variable. If it is called with a string,
787    the tracing key is that string.
788    
789      my @files = OpenDir("/Volumes/fig/contigs", 1);  =over 4
790    
791  is effectively the same as  =item parameter
792    
793      opendir(TMP, "/Volumes/fig/contigs") || Confess("Could not open /Volumes/fig/contigs.");  A parameter from which the tracing key is computed. If it is a scalar,
794      my @files = grep { $_ !~ /^[\.\$\#]/ && $_ !~ /~$/ } readdir(TMP);  that scalar is used as the tracing key. If it is a CGI object, the
795    tracing key is taken from the C<IP> cookie. If it is omitted, the
796    tracing key is taken from the C<TRACING> environment variable. If it
797    is a CGI object and emergency tracing is not on, the C<Trace> and
798    C<TF> parameters will be used to determine the type of tracing.
799    
800    =back
801    
802    =cut
803    
804    sub ETracing {
805        # Get the parameter.
806        my ($parameter) = @_;
807        # Check for CGI mode.
808        my $cgi = (ref $parameter eq 'CGI' ? $parameter : undef);
809        # Default to no tracing except errors.
810        my ($tracing, $dest) = ("0", "WARN");
811        # Check for emergency tracing.
812        my $tkey = EmergencyKey($parameter);
813        my $emergencyFile = EmergencyFileName($tkey);
814        if (-e $emergencyFile) {
815            # We have the file. Read in the data.
816            my @tracing = GetFile($emergencyFile);
817            # Pull off the time limit.
818            my $expire = shift @tracing;
819            # Convert it to seconds.
820            $expire *= 3600;
821            # Check the file data.
822            my $stat = stat($emergencyFile);
823            my ($now) = gettimeofday;
824            if ($now - $stat->mtime > $expire) {
825                # Delete the expired file.
826                unlink $emergencyFile;
827            } else {
828                # Emergency tracing is on. Pull off the destination and
829                # the trace level;
830                $dest = shift @tracing;
831                my $level = shift @tracing;
832                # Convert the destination to a real tracing destination.
833                # temp directory.
834                $dest = EmergencyTracingDest($tkey, $dest);
835                # Insure Tracer is specified.
836                my %moduleHash = map { $_ => 1 } @tracing;
837                $moduleHash{Tracer} = 1;
838                # Set the trace parameter.
839                $tracing = join(" ", $level, sort keys %moduleHash);
840            }
841        } elsif (defined $cgi) {
842            # There's no emergency tracing, but we have a CGI object, so check
843            # for tracing from the form parameters.
844            if ($cgi->param('Trace')) {
845                # Here the user has requested tracing via a form.
846                $dest = ($cgi->param('TF') ? ">$FIG_Config::temp/Trace$$.log" : "QUEUE");
847                $tracing = $cgi->param('Trace') . " Tracer";
848            }
849        }
850        # Setup the tracing we've determined from all the stuff above.
851        TSetup($tracing, $dest);
852        # If we're a web script, trace the parameter and environment data.
853        if (defined $cgi) {
854            TraceParms($cgi);
855        }
856    }
857    
858  Similarly, the following code  =head3 EmergencyFileName
859    
860      my @files = grep { $_ =~ /^\d/ } OpenDir("/Volumes/fig/orgs", 0, 1);      my $fileName = Tracer::EmergencyFileName($tkey);
861    
862  Returns the names of all files in C</Volumes/fig/orgs> that begin with digits and  Return the emergency tracing file name. This is the file that specifies
863  automatically returns an empty list if the directory fails to open.  the tracing information.
864    
865  =over 4  =over 4
866    
867  =item dirName  =item tkey
   
 Name of the directory to open.  
   
 =item filtered  
868    
869  TRUE if files whose names begin with a period (C<.>) should be automatically removed  Tracing key for the current program.
 from the list, else FALSE.  
870    
871  =item flag  =item RETURN
872    
873  TRUE if a failure to open is okay, else FALSE  Returns the name of the file to contain the emergency tracing information.
874    
875  =back  =back
876    
877  =cut  =cut
878  #: Return Type @;  
879  sub OpenDir {  sub EmergencyFileName {
880      # Get the parameters.      # Get the parameters.
881      my ($dirName, $filtered, $flag) = @_;      my ($tkey) = @_;
882      # Declare the return variable.      # Compute the emergency tracing file name.
883      my @retVal = ();      return "$FIG_Config::temp/Emergency$tkey.txt";
     # Open the directory.  
     if (opendir(my $dirHandle, $dirName)) {  
         # The directory opened successfully. Get the appropriate list according to the  
         # strictures of the filter parameter.  
         if ($filtered) {  
             @retVal = grep { $_ !~ /^[\.\$\#]/ && $_ !~ /~$/ } readdir $dirHandle;  
         } else {  
             @retVal = readdir $dirHandle;  
         }  
     } elsif (! $flag) {  
         # Here the directory would not open and it's considered an error.  
         Confess("Could not open directory $dirName.");  
     }  
     # Return the result.  
     return @retVal;  
884  }  }
885    
886  =head3 SetLevel  =head3 EmergencyFileTarget
887    
888      Tracer::SetLevel($newLevel);      my $fileName = Tracer::EmergencyFileTarget($tkey);
889    
890  Modify the trace level. A higher trace level will cause more messages to appear.  Return the emergency tracing target file name. This is the file that receives
891    the tracing output for file-based tracing.
892    
893  =over 4  =over 4
894    
895  =item newLevel  =item tkey
   
 Proposed new trace level.  
   
 =back  
   
 =cut  
896    
897  sub SetLevel {  Tracing key for the current program.
     $TraceLevel = $_[0];  
 }  
898    
899  =head3 Now  =item RETURN
900    
901      my $string = Tracer::Now();  Returns the name of the file to contain the trace output.
902    
903  Return a displayable time stamp containing the local time.  =back
904    
905  =cut  =cut
906    
907  sub Now {  sub EmergencyFileTarget {
908      my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = localtime(time);      # Get the parameters.
909      my $retVal = _p2($mon+1) . "/" . _p2($mday) . "/" . ($year + 1900) . " " .      my ($tkey) = @_;
910                   _p2($hour) . ":" . _p2($min) . ":" . _p2($sec);      # Compute the emergency tracing file name.
911      return $retVal;      return "$FIG_Config::temp/trace$tkey.log";
 }  
   
 # Pad a number to 2 digits.  
 sub _p2 {  
     my ($value) = @_;  
     $value = "0$value" if ($value < 10);  
     return $value;  
912  }  }
913    
914  =head3 ParseTraceDate  =head3 EmergencyTracingDest
915    
916      my $time = Tracer::ParseTraceDate($dateString);      my $dest = Tracer::EmergencyTracingDest($tkey, $myDest);
917    
918  Convert a date from the trace file into a PERL timestamp.  This method converts an emergency tracing destination to a real
919    tracing destination. The main difference is that if the
920    destination is C<FILE> or C<APPEND>, we convert it to file
921    output. If the destination is C<DUAL>, we convert it to file
922    and standard output.
923    
924  =over 4  =over 4
925    
926  =item dateString  =item tkey
927    
928  The date string from the trace file. The format of the string is determined by the  Tracing key for this environment.
929  L</Now> method.  
930    =item myDest
931    
932    Destination from the emergency tracing file.
933    
934  =item RETURN  =item RETURN
935    
936  Returns a PERL time, that is, a number of seconds since the epoch, or C<undef> if  Returns a destination that can be passed into L</TSetup>.
 the time string is invalid.  
937    
938  =back  =back
939    
940  =cut  =cut
941    
942  sub ParseTraceDate {  sub EmergencyTracingDest {
943      # Get the parameters.      # Get the parameters.
944      my ($dateString) = @_;      my ($tkey, $myDest) = @_;
945      # Declare the return variable.      # Declare the return variable.
946      my $retVal;      my $retVal = $myDest;
947      # Parse the date.      # Process according to the destination value.
948      if ($dateString =~ m#(\d+)/(\d+)/(\d+)\s+(\d+):(\d+):(\d+)#) {      if ($myDest eq 'FILE') {
949          # Create a time object. Note we need to convert the day, month,          $retVal = ">" . EmergencyFileTarget($tkey);
950          # and year to a different base. Years count from 1900, and      } elsif ($myDest eq 'APPEND') {
951          # the internal month value is relocated to January = 0.          $retVal = ">>" . EmergencyFileTarget($tkey);
952          $retVal = timelocal($6, $5, $4, $2, $1 - 1, $3 - 1900);      } elsif ($myDest eq 'DUAL') {
953            $retVal = "+>" . EmergencyFileTarget($tkey);
954      }      }
955      # Return the result.      # Return the result.
956      return $retVal;      return $retVal;
957  }  }
958    
959  =head3 LogErrors  =head3 Emergency
960    
961      Tracer::LogErrors($fileName);      Emergency($key, $hours, $dest, $level, @modules);
962    
963  Route the standard error output to a log file.  Turn on emergency tracing. This method is normally invoked over the web from
964    a debugging console, but it can also be called by the C<trace.pl> script.
965    The caller specifies the duration of the emergency in hours, the desired tracing
966    destination, the trace level, and a list of the trace modules to activate.
967    For the length of the duration, when a program in an environment with the
968    specified tracing key active invokes a Sprout CGI script, tracing will be
969    turned on automatically. See L</TSetup> for more about tracing setup and
970    L</ETracing> for more about emergency tracing.
971    
972  =over 4  =over 4
973    
974  =item fileName  =item tkey
975    
976  Name of the file to receive the error output.  The tracing key. This is used to identify the control file and the trace file.
977    
978    =item hours
979    
980    Number of hours to keep emergency tracing alive.
981    
982    =item dest
983    
984    Tracing destination. If no path information is specified for a file
985    destination, it is put in the FIG temporary directory.
986    
987    =item level
988    
989    Tracing level. A higher level means more trace messages.
990    
991    =item modules
992    
993    A list of the tracing modules to activate.
994    
995  =back  =back
996    
997  =cut  =cut
998    
999  sub LogErrors {  sub Emergency {
1000      # Get the file name.      # Get the parameters.
1001      my ($fileName) = @_;      my ($tkey, $hours, $dest, $level, @modules) = @_;
1002      # Open the file as the standard error output.      # Create the emergency file.
1003      open STDERR, '>', $fileName;      my $specFile = EmergencyFileName($tkey);
1004        my $outHandle = Open(undef, ">$specFile");
1005        print $outHandle join("\n", $hours, $dest, $level, @modules, "");
1006  }  }
1007    
1008  =head3 ReadOptions  =head3 EmergencyKey
   
     my %options = Tracer::ReadOptions($fileName);  
   
 Read a set of options from a file. Each option is encoded in a line of text that has the  
 format  
1009    
1010  I<optionName>C<=>I<optionValue>C<; >I<comment>      my $tkey = EmergencyKey($parameter);
1011    
1012  The option name must consist entirely of letters, digits, and the punctuation characters  Return the Key to be used for emergency tracing. This could be an IP address,
1013  C<.> and C<_>, and is case sensitive. Blank lines and lines in which the first nonblank   a session ID, or a user name, depending on the environment.
 character is a semi-colon will be ignored. The return hash will map each option name to  
 the corresponding option value.  
1014    
1015  =over 4  =over 4
1016    
1017  =item fileName  =item parameter
1018    
1019  Name of the file containing the option data.  Parameter defining the method for finding the tracing key. If it is a scalar,
1020    then it is presumed to be the tracing key itself. If it is a CGI object, then
1021    the tracing key is taken from the C<IP> cookie. Otherwise, the tracing key is
1022    taken from the C<TRACING> environment variable.
1023    
1024  =item RETURN  =item RETURN
1025    
1026  Returns a hash mapping the option names specified in the file to their corresponding option  Returns the key to be used for labels in emergency tracing.
 value.  
1027    
1028  =back  =back
1029    
1030  =cut  =cut
1031    
1032  sub ReadOptions {  sub EmergencyKey {
1033      # Get the parameters.      # Get the parameters.
1034      my ($fileName) = @_;      my ($parameter) = @_;
1035      # Open the file.      # Declare the return variable.
1036      (open CONFIGFILE, "<$fileName") || Confess("Could not open option file $fileName.");      my $retVal;
1037      # Count the number of records read.      # Determine the parameter type.
1038      my ($records, $comments) = 0;      if (! defined $parameter) {
1039      # Create the return hash.          # Here we're supposed to check the environment.
1040      my %retVal = ();          $retVal = $ENV{TRACING};
     # Loop through the file, accumulating key-value pairs.  
     while (my $line = <CONFIGFILE>) {  
         # Denote we've read a line.  
         $records++;  
         # Determine the line type.  
         if ($line =~ /^\s*[\n\r]/) {  
             # A blank line is a comment.  
             $comments++;  
         } elsif ($line =~ /^\s*([A-Za-z0-9_\.]+)=([^;]*);/) {  
             # Here we have an option assignment.  
             retVal{$1} = $2;  
         } elsif ($line =~ /^\s*;/) {  
             # Here we have a text comment.  
             $comments++;  
1041          } else {          } else {
1042              # Here we have an invalid line.          my $ptype = ref $parameter;
1043              Trace("Invalid option statement in record $records.") if T(0);          if ($ptype eq 'CGI') {
1044          }              # Here we were invoked from a web page. Look for a cookie.
1045                $retVal = $parameter->cookie('IP');
1046            } elsif (! $ptype) {
1047                # Here the key was passed in.
1048                $retVal = $parameter;
1049      }      }
1050      # Return the hash created.      }
1051      return %retVal;      # If no luck finding a key, use the PID.
1052        if (! defined $retVal) {
1053            $retVal = $$;
1054        }
1055        # Return the result.
1056        return $retVal;
1057  }  }
1058    
 =head3 GetOptions  
   
     Tracer::GetOptions(\%defaults, \%options);  
   
 Merge a specified set of options into a table of defaults. This method takes two hash references  
 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.  
   
 Consider the following example.  
   
     my $optionTable = GetOptions({ dbType => 'mySQL', trace => 0 }, $options);  
1059    
1060  In this example, the variable B<$options> is expected to contain at most two options-- B<dbType> and  =head3 TraceParms
 B<trace>. The default database type is C<mySQL> and the default trace level is C<0>. If the value of  
 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  
1061    
1062      {databaseType => 'Oracle'}      Tracer::TraceParms($cgi);
1063    
1064  an error will occur because the B<databaseType> option does not exist.  Trace the CGI parameters at trace level CGI => 3 and the environment variables
1065    at level CGI => 4.
1066    
1067  =over 4  =over 4
1068    
1069  =item defaults  =item cgi
   
 Table of default option values.  
   
 =item options  
   
 Table of overrides, if any.  
   
 =item RETURN  
1070    
1071  Returns a reference to the default table passed in as the first parameter.  CGI query object containing the parameters to trace.
1072    
1073  =back  =back
1074    
1075  =cut  =cut
1076    
1077  sub GetOptions {  sub TraceParms {
1078      # Get the parameters.      # Get the parameters.
1079      my ($defaults, $options) = @_;      my ($cgi) = @_;
1080      # Check for overrides.      if (T(CGI => 3)) {
1081      if ($options) {          # Here we want to trace the parameter data.
1082          # Loop through the overrides.          my @names = $cgi->param;
1083          while (my ($option, $setting) = each %{$options}) {          for my $parmName (sort @names) {
1084              # Insure this override exists.              # Note we skip the Trace parameters, which are for our use only.
1085              if (!exists $defaults->{$option}) {              if ($parmName ne 'Trace' && $parmName ne 'TF') {
1086                  croak "Unrecognized option $option encountered.";                  my @values = $cgi->param($parmName);
1087              } else {                  Trace("CGI: $parmName = " . join(", ", @values));
                 # Apply the override.  
                 $defaults->{$option} = $setting;  
1088              }              }
1089          }          }
1090            # Display the request method.
1091            my $method = $cgi->request_method();
1092            Trace("Method: $method");
1093        }
1094        if (T(CGI => 4)) {
1095            # Here we want the environment data too.
1096            for my $envName (sort keys %ENV) {
1097                Trace("ENV: $envName = $ENV{$envName}");
1098            }
1099      }      }
     # Return the merged table.  
     return $defaults;  
1100  }  }
1101    
1102  =head3 MergeOptions  =head3 ScriptFinish
1103    
1104      Tracer::MergeOptions(\%table, \%defaults);      ScriptFinish($webData, $varHash);
1105    
1106  Merge default values into a hash table. This method looks at the key-value pairs in the  Output a web page at the end of a script. Either the string to be output or the
1107  second (default) hash, and if a matching key is not found in the first hash, the default  name of a template file can be specified. If the second parameter is omitted,
1108  pair is copied in. The process is similar to L</GetOptions>, but there is no error-  it is assumed we have a string to be output; otherwise, it is assumed we have the
1109  checking and no return value.  name of a template file. The template should have the variable C<DebugData>
1110    specified in any form that invokes a standard script. If debugging mode is turned
1111    on, a form field will be put in that allows the user to enter tracing data.
1112    Trace messages will be placed immediately before the terminal C<BODY> tag in
1113    the output, formatted as a list.
1114    
1115    A typical standard script would loook like the following.
1116    
1117        BEGIN {
1118            # Print the HTML header.
1119            print "CONTENT-TYPE: text/html\n\n";
1120        }
1121        use Tracer;
1122        use CGI;
1123        use FIG;
1124        # ... more uses ...
1125    
1126        my ($cgi, $varHash) = ScriptSetup();
1127        eval {
1128            # ... get data from $cgi, put it in $varHash ...
1129        };
1130        if ($@) {
1131            Trace("Script Error: $@") if T(0);
1132        }
1133        ScriptFinish("Html/MyTemplate.html", $varHash);
1134    
1135    The idea here is that even if the script fails, you'll see trace messages and
1136    useful output.
1137    
1138  =over 4  =over 4
1139    
1140  =item table  =item webData
1141    
1142  Hash table to be updated with the default values.  A string containing either the full web page to be written to the output or the
1143    name of a template file from which the page is to be constructed. If the name
1144    of a template file is specified, then the second parameter must be present;
1145    otherwise, it must be absent.
1146    
1147  =item defaults  =item varHash (optional)
1148    
1149  Default values to be merged into the first hash table if they are not already present.  If specified, then a reference to a hash mapping variable names for a template
1150    to their values. The template file will be read into memory, and variable markers
1151    will be replaced by data in this hash reference.
1152    
1153  =back  =back
1154    
1155  =cut  =cut
1156    
1157  sub MergeOptions {  sub ScriptFinish {
1158      # Get the parameters.      # Get the parameters.
1159      my ($table, $defaults) = @_;      my ($webData, $varHash) = @_;
1160      # Loop through the defaults.      # Check for a template file situation.
1161      while (my ($key, $value) = each %{$defaults}) {      my $outputString;
1162          if (!exists $table->{$key}) {      if (defined $varHash) {
1163              $table->{$key} = $value;          # Here we have a template file. We need to determine the template type.
1164            my $template;
1165            if ($FIG_Config::template_url && $webData =~ /\.php$/) {
1166                $template = "$FIG_Config::template_url/$webData";
1167            } else {
1168                $template = "<<$webData";
1169            }
1170            $outputString = PageBuilder::Build($template, $varHash, "Html");
1171        } else {
1172            # Here the user gave us a raw string.
1173            $outputString = $webData;
1174        }
1175        # Check for trace messages.
1176        if ($Destination ne "NONE" && $TraceLevel > 0) {
1177            # We have trace messages, so we want to put them at the end of the body. This
1178            # is either at the end of the whole string or at the beginning of the BODY
1179            # end-tag.
1180            my $pos = length $outputString;
1181            if ($outputString =~ m#</body>#gi) {
1182                $pos = (pos $outputString) - 7;
1183          }          }
1184            # If the trace messages were queued, we unroll them. Otherwise, we display the
1185            # destination.
1186            my $traceHtml;
1187            if ($Destination eq "QUEUE") {
1188                $traceHtml = QTrace('Html');
1189            } elsif ($Destination =~ /^>>(.+)$/) {
1190                # Here the tracing output it to a file. We code it as a hyperlink so the user
1191                # can copy the file name into the clipboard easily.
1192                my $actualDest = $1;
1193                $traceHtml = "<p>Tracing output to $actualDest.</p>\n";
1194            } else {
1195                # Here we have one of the special destinations.
1196                $traceHtml = "<P>Tracing output type is $Destination.</p>\n";
1197            }
1198            substr $outputString, $pos, 0, $traceHtml;
1199      }      }
1200        # Write the output string.
1201        print $outputString;
1202  }  }
1203    
1204  =head3 Trace  =head2 Command-Line Utility Methods
1205    
1206      Trace($message);  =head3 SendSMS
1207    
1208  Write a trace message to the target location specified in L</TSetup>. If there has not been      my $msgID = Tracer::SendSMS($phoneNumber, $msg);
1209  any prior call to B<TSetup>.  
1210    Send a text message to a phone number using Clickatell. The FIG_Config file must contain the
1211    user name, password, and API ID for the relevant account in the hash reference variable
1212    I<$FIG_Config::phone>, using the keys C<user>, C<password>, and C<api_id>. For
1213    example, if the user name is C<BruceTheHumanPet>, the password is C<silly>, and the API ID
1214    is C<2561022>, then the FIG_Config file must contain
1215    
1216        $phone =  { user => 'BruceTheHumanPet',
1217                    password => 'silly',
1218                    api_id => '2561022' };
1219    
1220    The original purpose of this method was to insure Bruce would be notified immediately when the
1221    Sprout Load terminates. Care should be taken if you do not wish Bruce to be notified immediately
1222    when you call this method.
1223    
1224    The message ID will be returned if successful, and C<undef> if an error occurs.
1225    
1226  =over 4  =over 4
1227    
1228  =item message  =item phoneNumber
1229    
1230  Message to write.  Phone number to receive the message, in international format. A United States phone number
1231    would be prefixed by "1". A British phone number would be prefixed by "44".
1232    
1233    =item msg
1234    
1235    Message to send to the specified phone.
1236    
1237    =item RETURN
1238    
1239    Returns the message ID if successful, and C<undef> if the message could not be sent.
1240    
1241  =back  =back
1242    
1243  =cut  =cut
1244    
1245  sub Trace {  sub SendSMS {
1246      # Get the parameters.      # Get the parameters.
1247      my ($message) = @_;      my ($phoneNumber, $msg) = @_;
1248      # Get the timestamp.      # Declare the return variable. If we do not change it, C<undef> will be returned.
1249      my $timeStamp = Now();      my $retVal;
1250      # Format the message. Note we strip off any line terminators at the end.      # Only proceed if we have phone support.
1251      my $prefix = "[$timeStamp] <$LastCategory>: ";      if (! defined $FIG_Config::phone) {
1252      my $formatted = $prefix . Strip($message);          Trace("Phone support not present in FIG_Config.") if T(1);
1253      # Process according to the destination.      } else {
1254      if ($Destination eq "TEXT") {          # Get the phone data.
1255          # Write the message to the standard output.          my $parms = $FIG_Config::phone;
1256          print "$formatted\n";          # Get the Clickatell URL.
1257      } elsif ($Destination eq "ERROR") {          my $url = "http://api.clickatell.com/http/";
1258          # Write the message to the error output.          # Create the user agent.
1259          print STDERR "$formatted\n";          my $ua = LWP::UserAgent->new;
1260      } elsif ($Destination eq "QUEUE") {          # Request a Clickatell session.
1261          # Push the message into the queue.          my $resp = $ua->post("$url/sendmsg", { user => $parms->{user},
1262          push @Queue, "$formatted";                                       password => $parms->{password},
1263      } elsif ($Destination eq "HTML") {                                       api_id => $parms->{api_id},
1264          # Convert the message to HTML and write it to the standard output.                                       to => $phoneNumber,
1265          my $escapedMessage = CGI::escapeHTML($message);                                       text => $msg});
1266          print "<p>$timeStamp $LastCategory: $escapedMessage</p>\n";          # Check for an error.
1267      } elsif ($Destination eq "WARN") {          if (! $resp->is_success) {
1268         # Emit the message as a warning.              Trace("Alert failed.") if T(1);
1269         warn $message;          } else {
1270      } elsif ($Destination =~ m/^>>/) {              # Get the message ID.
1271          # Write the trace message to an output file.              my $rstring = $resp->content;
1272          (open TRACING, $Destination) || die "Tracing open for \"$Destination\" failed: $!";              if ($rstring =~ /^ID:\s+(.*)$/) {
1273          print TRACING "$formatted\n";                  $retVal = $1;
1274          close TRACING;              } else {
1275          # If the Tee flag is on, echo it to the standard output.                  Trace("Phone attempt failed with $rstring") if T(1);
         if ($TeeFlag) {  
             print "$formatted\n";  
1276          }          }
1277      }      }
1278  }  }
1279        # Return the result.
1280        return $retVal;
1281    }
1282    
1283  =head3 T  =head3 StandardSetup
1284    
1285      my $switch = T($category, $traceLevel);      my ($options, @parameters) = StandardSetup(\@categories, \%options, $parmHelp, @ARGV);
1286    
1287      or  This method performs standard command-line parsing and tracing setup. The return
1288    values are a hash of the command-line options and a list of the positional
1289    parameters. Tracing is automatically set up and the command-line options are
1290    validated.
1291    
1292      my $switch = T($traceLevel);  This is a complex method that does a lot of grunt work. The parameters can
1293    be more easily understood, however, once they are examined individually.
1294    
1295  Return TRUE if the trace level is at or above a specified value and the specified category  The I<categories> parameter is the most obtuse. It is a reference to a list of
1296  is active, else FALSE. If no category is specified, the caller's package name is used.  special-purpose tracing categories. Most tracing categories are PERL package
1297    names. So, for example, if you wanted to turn on tracing inside the B<Sprout>,
1298    B<ERDB>, and B<SproutLoad> packages, you would specify the categories
1299    
1300  =over 4      ["Sprout", "SproutLoad", "ERDB"]
1301    
1302  =item category  This would cause trace messages in the specified three packages to appear in
1303    the output. There are two special tracing categories that are automatically
1304    handled by this method. In other words, if you used L</TSetup> you would need
1305    to include these categories manually, but if you use this method they are turned
1306    on automatically.
1307    
1308  Category to which the message belongs. If not specified, the caller's package name is  =over 4
 used.  
1309    
1310  =item traceLevel  =item SQL
1311    
1312  Relevant tracing level.  Traces SQL commands and activity.
1313    
1314  =item RETURN  =item Tracer
1315    
1316  TRUE if a message at the specified trace level would appear in the trace, else FALSE.  Traces error messages and call stacks.
1317    
1318  =back  =back
1319    
1320  =cut  C<SQL> is only turned on if the C<-sql> option is specified in the command line.
1321    The trace level is specified using the C<-trace> command-line option. For example,
1322    the following command line for C<TransactFeatures> turns on SQL tracing and runs
1323    all tracing at level 3.
1324    
1325  sub T {      TransactFeatures -trace=3 -sql register ../xacts IDs.tbl
     # Declare the return variable.  
     my $retVal = 0;  
     # Only proceed if tracing is turned on.  
     if ($Destination ne "NONE") {  
         # Get the parameters.  
         my ($category, $traceLevel) = @_;  
         if (!defined $traceLevel) {  
             # Here we have no category, so we need to get the calling package.  
             # The calling package is normally the first parameter. If it is  
             # omitted, the first parameter will be the tracelevel. So, the  
             # first thing we do is shift the so-called category into the  
             # $traceLevel variable where it belongs.  
             $traceLevel = $category;  
             my ($package, $fileName, $line) = caller;  
             # If there is no calling package, we default to "main".  
             if (!$package) {  
                 $category = "main";  
             } else {  
                 my @cats = split /::/, $package;  
                 $category = $cats[$#cats];  
             }  
         }  
         # Save the category name.  
         $LastCategory = $category;  
         # Convert it to lower case before we hash it.  
         $category = lc $category;  
         # Use the category and tracelevel to compute the result.  
         if (ref $traceLevel) {  
             Confess("Bad trace level.");  
         } elsif (ref $TraceLevel) {  
             Confess("Bad trace config.");  
         }  
         $retVal = ($traceLevel <= $TraceLevel && ($AllTrace || exists $Categories{$category}));  
     }  
     # Return the computed result.  
     return $retVal;  
 }  
1326    
1327  =head3 ParseCommand  Standard tracing is output to the standard output and echoed to the file
1328    C<trace>I<$$>C<.log> in the FIG temporary directory, where I<$$> is the
1329    process ID. You can also specify the C<user> parameter to put a user ID
1330    instead of a process ID in the trace file name. So, for example
1331    
1332      my ($options, @arguments) = Tracer::ParseCommand(\%optionTable, @inputList);  The default trace level is 2. To get all messages, specify a trace level of 4.
1333    For a genome-by-genome update, use 3.
1334    
1335  Parse a command line consisting of a list of parameters. The initial parameters may be option      TransactFeatures -trace=3 -sql -user=Bruce register ../xacts IDs.tbl
 specifiers of the form C<->I<option> or C<->I<option>C<=>I<value>. The options are stripped  
 off and merged into a table of default options. The remainder of the command line is  
 returned as a list of positional arguments. For example, consider the following invocation.  
1336    
1337      my ($options, @arguments) = ParseCommand({ errors => 0, logFile => 'trace.log'}, @words);  would send the trace output to C<traceBruce.log> in the temporary directory.
1338    
1339  In this case, the list @words will be treated as a command line and there are two options available,  The I<options> parameter is a reference to a hash containing the command-line
1340  B<errors> and B<logFile>. If @words has the following format  options, their default values, and an explanation of what they mean. Command-line
1341    options may be in the form of switches or keywords. In the case of a switch, the
1342    option value is 1 if it is specified and 0 if it is not specified. In the case
1343    of a keyword, the value is separated from the option name by an equal sign. You
1344    can see this last in the command-line example above.
1345    
1346      -logFile=error.log apple orange rutabaga  You can specify a different default trace level by setting C<$options->{trace}>
1347    prior to calling this method.
1348    
1349  then at the end of the invocation, C<$options> will be  An example at this point would help. Consider, for example, the command-line utility
1350    C<TransactFeatures>. It accepts a list of positional parameters plus the options
1351    C<safe>, C<noAlias>, C<start>, and C<tblFiles>. To start up this command, we execute
1352    the following code.
1353    
1354      { errors => 0, logFile => 'error.log' }      my ($options, @parameters) = Tracer::StandardSetup(["DocUtils"],
1355                            { safe => [0, "use database transactions"],
1356                              noAlias => [0, "do not expect aliases in CHANGE transactions"],
1357                              start => [' ', "start with this genome"],
1358                              tblFiles => [0, "output TBL files containing the corrected IDs"] },
1359                            "<command> <transactionDirectory> <IDfile>",
1360                          @ARGV);
1361    
 and C<@arguments> will contain  
1362    
1363      apple orange rutabaga  The call to C<ParseCommand> specifies the default values for the options and
1364    stores the actual options in a hash that is returned as C<$options>. The
1365    positional parameters are returned in C<@parameters>.
1366    
1367  The parser allows for some escape sequences. See L</UnEscape> for a description. There is no  The following is a sample command line for C<TransactFeatures>.
 support for quote characters. Options can be specified with single or double hyphens.  
1368    
1369  =over 4      TransactFeatures -trace=2 -noAlias register ../xacts IDs.tbl
1370    
1371  =item optionTable  Single and double hyphens are equivalent. So, you could also code the
1372    above command as
1373    
1374  Table of default options.      TransactFeatures --trace=2 --noAlias register ../xacts IDs.tbl
1375    
1376  =item inputList  In this case, C<register>, C<../xacts>, and C<IDs.tbl> are the positional
1377    parameters, and would find themselves in I<@parameters> after executing the
1378    above code fragment. The tracing would be set to level 2, and the categories
1379    would be C<Tracer>, and <DocUtils>. C<Tracer> is standard,
1380    and C<DocUtils> was included because it came in within the first parameter
1381    to this method. The I<$options> hash would be
1382    
1383  List of words on the command line.      { trace => 2, sql => 0, safe => 0,
1384          noAlias => 1, start => ' ', tblFiles => 0 }
1385    
1386  =item RETURN  Use of C<StandardSetup> in this way provides a simple way of performing
1387    standard tracing setup and command-line parsing. Note that the caller is
1388    not even aware of the command-line switches C<-trace> and C<-sql>, which
1389    are used by this method to control the tracing. If additional tracing features
1390    need to be added in the future, they can be processed by this method without
1391    upsetting the command-line utilities.
1392    
1393  Returns a reference to the option table and a list of the positional arguments.  If the C<background> option is specified on the command line, then the
1394    standard and error outputs will be directed to files in the temporary
1395    directory, using the same suffix as the trace file. So, if the command
1396    line specified
1397    
1398  =back      -user=Bruce -background
1399    
1400  =cut  then the trace output would go to C<traceBruce.log>, the standard output to
1401    C<outBruce.log>, and the error output to C<errBruce.log>. This is designed to
1402    simplify starting a command in the background.
1403    
1404  sub ParseCommand {  The user name is also used as the tracing key for L</Emergency Tracing>.
1405      # Get the parameters.  Specifying a value of C<E> for the trace level causes emergency tracing to
1406      my ($optionTable, @inputList) = @_;  be used instead of custom tracing. If the user name is not specified,
1407      # Process any options in the input list.  the tracing key is taken from the C<Tracing> environment variable. If there
1408      my %overrides = ();  is no value for that variable, the tracing key will be computed from the PID.
     while ((@inputList > 0) && ($inputList[0] =~ /^--?/)) {  
         # Get the current option.  
         my $arg = shift @inputList;  
         # 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);  
         } else {  
             # Here there is no value, so we use 1.  
             $overrides{$name} = 1;  
         }  
     }  
     # Merge the options into the defaults.  
     GetOptions($optionTable, \%overrides);  
     # Translate the remaining parameters.  
     my @retVal = ();  
     for my $inputParm (@inputList) {  
         push @retVal, UnEscape($inputParm);  
     }  
     # Return the results.  
     return ($optionTable, @retVal);  
 }  
1409    
1410  =head3 Escape  Finally, if the special option C<-help> is specified, the option
1411    names will be traced at level 0 and the program will exit without processing.
1412    This provides a limited help capability. For example, if the user enters
1413    
1414      my $codedString = Tracer::Escape($realString);      TransactFeatures -help
1415    
1416  Escape a string for use in a command length. Tabs will be replaced by C<\t>, new-lines  he would see the following output.
1417  replaced by C<\n>, carriage returns will be deleted, and backslashes will be doubled. The  
1418  result is to reverse the effect of L</UnEscape>.      TransactFeatures [options] <command> <transactionDirectory> <IDfile>
1419            -trace    tracing level (default E)
1420            -sql      trace SQL commands
1421            -safe     use database transactions
1422            -noAlias  do not expect aliases in CHANGE transactions
1423            -start    start with this genome
1424            -tblFiles output TBL files containing the corrected IDs
1425    
1426    The caller has the option of modifying the tracing scheme by placing a value
1427    for C<trace> in the incoming options hash. The default value can be overridden,
1428    or the tracing to the standard output can be turned off by suffixing a minus
1429    sign to the trace level. So, for example,
1430    
1431        { trace => [0, "tracing level (default 0)"],
1432           ...
1433    
1434    would set the default trace level to 0 instead of E, while
1435    
1436        { trace => ["2-", "tracing level (default 2)"],
1437           ...
1438    
1439    would set the default to 2, but trace only to the log file, not to the
1440    standard output.
1441    
1442    The parameters to this method are as follows.
1443    
1444    =over 4
1445    
1446    =item categories
1447    
1448    Reference to a list of tracing category names. These should be names of
1449    packages whose internal workings will need to be debugged to get the
1450    command working.
1451    
1452    =item options
1453    
1454    Reference to a hash containing the legal options for the current command mapped
1455    to their default values and descriptions. The user can override the defaults
1456    by specifying the options as command-line switches prefixed by a hyphen.
1457    Tracing-related options may be added to this hash. If the C<-h> option is
1458    specified on the command line, the option descriptions will be used to
1459    explain the options. To turn off tracing to the standard output, add a
1460    minus sign to the value for C<trace> (see above).
1461    
1462  =over 4  =item parmHelp
1463    
1464  =item realString  A string that vaguely describes the positional parameters. This is used
1465    if the user specifies the C<-h> option.
1466    
1467  String to escape.  =item argv
1468    
1469    List of command line parameters, including the option switches, which must
1470    precede the positional parameters and be prefixed by a hyphen.
1471    
1472  =item RETURN  =item RETURN
1473    
1474  Escaped equivalent of the real string.  Returns a list. The first element of the list is the reference to a hash that
1475    maps the command-line option switches to their values. These will either be the
1476    default values or overrides specified on the command line. The remaining
1477    elements of the list are the position parameters, in order.
1478    
1479  =back  =back
1480    
1481  =cut  =cut
1482    
1483  sub Escape {  sub StandardSetup {
1484      # Get the parameter.      # Get the parameters.
1485      my ($realString) = @_;      my ($categories, $options, $parmHelp, @argv) = @_;
1486      # Initialize the return variable.      # Get the default tracing key.
1487      my $retVal = "";      my $tkey = EmergencyKey();
1488      # Loop through the parameter string, looking for sequences to escape.      # Add the tracing options.
1489      while (length $realString > 0) {      if (! exists $options->{trace}) {
1490          # Look for the first sequence to escape.          $options->{trace} = ['2', "tracing level (E for emergency tracing)"];
1491          if ($realString =~ /^(.*?)([\n\t\r\\])/) {      }
1492              # Here we found it. The text preceding the sequence is in $1. The sequence      $options->{sql} = [0, "turn on SQL tracing"];
1493              # itself is in $2. First, move the clear text to the return variable.      $options->{help} = [0, "display command-line options"];
1494              $retVal .= $1;      $options->{user} = [$tkey, "tracing key"];
1495              # Strip the processed section off the real string.      $options->{background} = [0, "spool standard and error output"];
1496              $realString = substr $realString, (length $2) + (length $1);      # Create a parsing hash from the options hash. The parsing hash
1497              # Get the matched character.      # contains the default values rather than the default value
1498              my $char = $2;      # and the description. While we're at it, we'll memorize the
1499              # If we have a CR, we are done.      # length of the longest option name.
1500              if ($char ne "\r") {      my $longestName = 0;
1501                  # It's not a CR, so encode the escape sequence.      my %parseOptions = ();
1502                  $char =~ tr/\t\n/tn/;      for my $key (keys %{$options}) {
1503                  $retVal .= "\\" . $char;          if (length $key > $longestName) {
1504                $longestName = length $key;
1505            }
1506            $parseOptions{$key} = $options->{$key}->[0];
1507        }
1508        # Parse the command line.
1509        my ($retOptions, @retParameters) = ParseCommand(\%parseOptions, @argv);
1510        # Get the logfile suffix.
1511        my $suffix = $retOptions->{user};
1512        # Check for background mode.
1513        if ($retOptions->{background}) {
1514            my $outFileName = "$FIG_Config::temp/out$suffix.log";
1515            my $errFileName = "$FIG_Config::temp/err$suffix.log";
1516            open STDOUT, ">$outFileName";
1517            open STDERR, ">$errFileName";
1518            # Check for phone support. If we have phone support and a phone number,
1519            # we want to turn it on.
1520            if ($ENV{PHONE} && defined($FIG_Config::phone)) {
1521                $retOptions->{phone} = $ENV{PHONE};
1522            }
1523              }              }
1524        # Now we want to set up tracing. First, we need to know if the user
1525        # wants emergency tracing.
1526        if ($retOptions->{trace} eq 'E') {
1527            ETracing($retOptions->{user});
1528          } else {          } else {
1529              # Here there are no more escape sequences. The rest of the string is          # Here the tracing is controlled from the command line.
1530              # transferred unmodified.          my @cats = @{$categories};
1531              $retVal .= $realString;          if ($retOptions->{sql}) {
1532              $realString = "";              push @cats, "SQL";
1533            }
1534            # Add the default categories.
1535            push @cats, "Tracer";
1536            # Next, we create the category string by joining the categories.
1537            my $cats = join(" ", @cats);
1538            # Check to determine whether or not the caller wants to turn off tracing
1539            # to the standard output.
1540            my $traceLevel = $retOptions->{trace};
1541            my $textOKFlag = 1;
1542            if ($traceLevel =~ /^(.)-/) {
1543                $traceLevel = $1;
1544                $textOKFlag = 0;
1545          }          }
1546            # Now we set up the trace mode.
1547            my $traceMode;
1548            # Verify that we can open a file in the FIG temporary directory.
1549            my $traceFileName = "$FIG_Config::temp/trace$suffix.log";
1550            if (open TESTTRACE, ">$traceFileName") {
1551                # Here we can trace to a file.
1552                $traceMode = ">$traceFileName";
1553                if ($textOKFlag) {
1554                    # Echo to standard output if the text-OK flag is set.
1555                    $traceMode = "+$traceMode";
1556      }      }
1557      # Return the result.              # Close the test file.
1558      return $retVal;              close TESTTRACE;
1559            } else {
1560                # Here we can't trace to a file. We trace to the standard output if it's
1561                # okay, and the error log otherwise.
1562                if ($textOKFlag) {
1563                    $traceMode = "TEXT";
1564                } else {
1565                    $traceMode = "WARN";
1566                }
1567            }
1568            # Now set up the tracing.
1569            TSetup("$traceLevel $cats", $traceMode);
1570        }
1571        # Check for the "help" option. If it is specified, dump the command-line
1572        # options and exit the program.
1573        if ($retOptions->{help}) {
1574            $0 =~ m#[/\\](\w+)(\.pl)?$#i;
1575            print "$1 [options] $parmHelp\n";
1576            for my $key (sort keys %{$options}) {
1577                my $name = Pad($key, $longestName, 0, ' ');
1578                my $desc = $options->{$key}->[1];
1579                if ($options->{$key}->[0]) {
1580                    $desc .= " (default " . $options->{$key}->[0] . ")";
1581                }
1582                print "  $name $desc\n";
1583            }
1584            exit(0);
1585        }
1586        # Trace the options, if applicable.
1587        if (T(3)) {
1588            my @parms = grep { $retOptions->{$_} } keys %{$retOptions};
1589            Trace("Selected options: " . join(", ", sort @parms) . ".");
1590        }
1591        # Return the parsed parameters.
1592        return ($retOptions, @retParameters);
1593  }  }
1594    
1595  =head3 UnEscape  =head3 ReadOptions
1596    
1597      my $realString = Tracer::UnEscape($codedString);      my %options = Tracer::ReadOptions($fileName);
1598    
1599  Replace escape sequences with their actual equivalents. C<\t> will be replaced by  Read a set of options from a file. Each option is encoded in a line of text that has the
1600  a tab, C<\n> by a new-line character, and C<\\> by a backslash. C<\r> codes will  format
1601  be deleted.  
1602    I<optionName>C<=>I<optionValue>C<; >I<comment>
1603    
1604    The option name must consist entirely of letters, digits, and the punctuation characters
1605    C<.> and C<_>, and is case sensitive. Blank lines and lines in which the first nonblank
1606    character is a semi-colon will be ignored. The return hash will map each option name to
1607    the corresponding option value.
1608    
1609  =over 4  =over 4
1610    
1611  =item codedString  =item fileName
1612    
1613  String to un-escape.  Name of the file containing the option data.
1614    
1615  =item RETURN  =item RETURN
1616    
1617  Returns a copy of the original string with the escape sequences converted to their actual  Returns a hash mapping the option names specified in the file to their corresponding option
1618  values.  value.
1619    
1620  =back  =back
1621    
1622  =cut  =cut
1623    
1624  sub UnEscape {  sub ReadOptions {
1625      # Get the parameter.      # Get the parameters.
1626      my ($codedString) = @_;      my ($fileName) = @_;
1627      # Initialize the return variable.      # Open the file.
1628      my $retVal = "";      (open CONFIGFILE, "<$fileName") || Confess("Could not open option file $fileName.");
1629      # Only proceed if the incoming string is nonempty.      # Count the number of records read.
1630      if (defined $codedString) {      my ($records, $comments) = 0;
1631          # Loop through the parameter string, looking for escape sequences. We can't do      # Create the return hash.
1632          # translating because it causes problems with the escaped slash. ("\\t" becomes      my %retVal = ();
1633          # "\<tab>" no matter what we do.)      # Loop through the file, accumulating key-value pairs.
1634          while (length $codedString > 0) {      while (my $line = <CONFIGFILE>) {
1635              # Look for the first escape sequence.          # Denote we've read a line.
1636              if ($codedString =~ /^(.*?)\\(\\|n|t|r)/) {          $records++;
1637                  # Here we found it. The text preceding the sequence is in $1. The sequence          # Determine the line type.
1638                  # itself is in $2. First, move the clear text to the return variable.          if ($line =~ /^\s*[\n\r]/) {
1639                  $retVal .= $1;              # A blank line is a comment.
1640                  $codedString = substr $codedString, (2 + length $1);              $comments++;
1641                  # Get the escape value.          } elsif ($line =~ /^\s*([A-Za-z0-9_\.]+)=([^;]*);/) {
1642                  my $char = $2;              # Here we have an option assignment.
1643                  # If we have a "\r", we are done.              retVal{$1} = $2;
1644                  if ($char ne 'r') {          } elsif ($line =~ /^\s*;/) {
1645                      # Here it's not an 'r', so we convert it.              # Here we have a text comment.
1646                      $char =~ tr/\\tn/\\\t\n/;              $comments++;
                     $retVal .= $char;  
                 }  
1647              } else {              } else {
1648                  # Here there are no more escape sequences. The rest of the string is              # Here we have an invalid line.
1649                  # transferred unmodified.              Trace("Invalid option statement in record $records.") if T(0);
                 $retVal .= $codedString;  
                 $codedString = "";  
             }  
1650          }          }
1651      }      }
1652      # Return the result.      # Return the hash created.
1653      return $retVal;      return %retVal;
1654  }  }
1655    
1656  =head3 ParseRecord  =head3 GetOptions
1657    
1658      my @fields = Tracer::ParseRecord($line);      Tracer::GetOptions(\%defaults, \%options);
1659    
1660  Parse a tab-delimited data line. The data line is split into field values. Embedded tab  Merge a specified set of options into a table of defaults. This method takes two hash references
1661  and new-line characters in the data line must be represented as C<\t> and C<\n>, respectively.  as input and uses the data from the second to update the first. If the second does not exist,
1662  These will automatically be converted.  there will be no effect. An error will be thrown if one of the entries in the second hash does not
1663    exist in the first.
1664    
1665    Consider the following example.
1666    
1667        my $optionTable = GetOptions({ dbType => 'mySQL', trace => 0 }, $options);
1668    
1669    In this example, the variable B<$options> is expected to contain at most two options-- B<dbType> and
1670    B<trace>. The default database type is C<mySQL> and the default trace level is C<0>. If the value of
1671    B<$options> is C<< {dbType => 'Oracle'} >>, then the database type will be changed to C<Oracle> and
1672    the trace level will remain at 0. If B<$options> is undefined, then the database type and trace level
1673    will remain C<mySQL> and C<0>. If, on the other hand, B<$options> is defined as
1674    
1675        {databaseType => 'Oracle'}
1676    
1677    an error will occur because the B<databaseType> option does not exist.
1678    
1679  =over 4  =over 4
1680    
1681  =item line  =item defaults
1682    
1683  Line of data containing the tab-delimited fields.  Table of default option values.
1684    
1685    =item options
1686    
1687    Table of overrides, if any.
1688    
1689  =item RETURN  =item RETURN
1690    
1691  Returns a list of the fields found in the data line.  Returns a reference to the default table passed in as the first parameter.
1692    
1693  =back  =back
1694    
1695  =cut  =cut
1696    
1697  sub ParseRecord {  sub GetOptions {
1698      # Get the parameter.      # Get the parameters.
1699      my ($line) = @_;      my ($defaults, $options) = @_;
1700      # Remove the trailing new-line, if any.      # Check for overrides.
1701      chomp $line;      if ($options) {
1702      # Split the line read into pieces using the tab character.          # Loop through the overrides.
1703      my @retVal = split /\t/, $line;          while (my ($option, $setting) = each %{$options}) {
1704      # Trim and fix the escapes in each piece.              # Insure this override exists.
1705      for my $value (@retVal) {              if (!exists $defaults->{$option}) {
1706          # Trim leading whitespace.                  croak "Unrecognized option $option encountered.";
1707          $value =~ s/^\s+//;              } else {
1708          # Trim trailing whitespace.                  # Apply the override.
1709          $value =~ s/\s+$//;                  $defaults->{$option} = $setting;
1710          # Delete the carriage returns.              }
         $value =~ s/\r//g;  
         # Convert the escapes into their real values.  
         $value =~ s/\\t/"\t"/ge;  
         $value =~ s/\\n/"\n"/ge;  
1711      }      }
1712      # Return the result.      }
1713      return @retVal;      # Return the merged table.
1714        return $defaults;
1715  }  }
1716    
1717  =head3 Merge  =head3 MergeOptions
1718    
1719      my @mergedList = Tracer::Merge(@inputList);      Tracer::MergeOptions(\%table, \%defaults);
1720    
1721  Sort a list of strings and remove duplicates.  Merge default values into a hash table. This method looks at the key-value pairs in the
1722    second (default) hash, and if a matching key is not found in the first hash, the default
1723    pair is copied in. The process is similar to L</GetOptions>, but there is no error-
1724    checking and no return value.
1725    
1726  =over 4  =over 4
1727    
1728  =item inputList  =item table
1729    
1730  List of scalars to sort and merge.  Hash table to be updated with the default values.
1731    
1732  =item RETURN  =item defaults
1733    
1734  Returns a list containing the same elements sorted in ascending order with duplicates  Default values to be merged into the first hash table if they are not already present.
 removed.  
1735    
1736  =back  =back
1737    
1738  =cut  =cut
1739    
1740  sub Merge {  sub MergeOptions {
1741      # Get the input list in sort order.      # Get the parameters.
1742      my @inputList = sort @_;      my ($table, $defaults) = @_;
1743      # Only proceed if the list has at least two elements.      # Loop through the defaults.
1744      if (@inputList > 1) {      while (my ($key, $value) = each %{$defaults}) {
1745          # Now we want to move through the list splicing out duplicates.          if (!exists $table->{$key}) {
1746          my $i = 0;              $table->{$key} = $value;
         while ($i < @inputList) {  
             # Get the current entry.  
             my $thisEntry = $inputList[$i];  
             # Find out how many elements duplicate the current entry.  
             my $j = $i + 1;  
             my $dup1 = $i + 1;  
             while ($j < @inputList && $inputList[$j] eq $thisEntry) { $j++; };  
             # If the number is nonzero, splice out the duplicates found.  
             if ($j > $dup1) {  
                 splice @inputList, $dup1, $j - $dup1;  
             }  
             # Now the element at position $dup1 is different from the element before it  
             # at position $i. We push $i forward one position and start again.  
             $i++;  
1747          }          }
1748      }      }
     # Return the merged list.  
     return @inputList;  
1749  }  }
1750    
1751  =head3 Percent  =head3 ParseCommand
1752    
1753      my $percent = Tracer::Percent($number, $base);      my ($options, @arguments) = Tracer::ParseCommand(\%optionTable, @inputList);
1754    
1755  Returns the percent of the base represented by the given number. If the base  Parse a command line consisting of a list of parameters. The initial parameters may be option
1756  is zero, returns zero.  specifiers of the form C<->I<option> or C<->I<option>C<=>I<value>. The options are stripped
1757    off and merged into a table of default options. The remainder of the command line is
1758    returned as a list of positional arguments. For example, consider the following invocation.
1759    
1760        my ($options, @arguments) = ParseCommand({ errors => 0, logFile => 'trace.log'}, @words);
1761    
1762    In this case, the list @words will be treated as a command line and there are two options available,
1763    B<errors> and B<logFile>. If @words has the following format
1764    
1765        -logFile=error.log apple orange rutabaga
1766    
1767    then at the end of the invocation, C<$options> will be
1768    
1769        { errors => 0, logFile => 'error.log' }
1770    
1771    and C<@arguments> will contain
1772    
1773        apple orange rutabaga
1774    
1775    The parser allows for some escape sequences. See L</UnEscape> for a description. There is no
1776    support for quote characters. Options can be specified with single or double hyphens.
1777    
1778  =over 4  =over 4
1779    
1780  =item number  =item optionTable
1781    
1782  Percent numerator.  Table of default options.
1783    
1784  =item base  =item inputList
1785    
1786  Percent base.  List of words on the command line.
1787    
1788  =item RETURN  =item RETURN
1789    
1790  Returns the percentage of the base represented by the numerator.  Returns a reference to the option table and a list of the positional arguments.
1791    
1792  =back  =back
1793    
1794  =cut  =cut
1795    
1796  sub Percent {  sub ParseCommand {
1797      # Get the parameters.      # Get the parameters.
1798      my ($number, $base) = @_;      my ($optionTable, @inputList) = @_;
1799      # Declare the return variable.      # Process any options in the input list.
1800      my $retVal = 0;      my %overrides = ();
1801      # Compute the percent.      while ((@inputList > 0) && ($inputList[0] =~ /^--?/)) {
1802      if ($base != 0) {          # Get the current option.
1803          $retVal = $number * 100 / $base;          my $arg = shift @inputList;
1804            # Pull out the option name.
1805            $arg =~ /^--?([^=]*)/g;
1806            my $name = $1;
1807            # Check for an option value.
1808            if ($arg =~ /\G=(.*)$/g) {
1809                # Here we have a value for the option.
1810                $overrides{$name} = UnEscape($1);
1811            } else {
1812                # Here there is no value, so we use 1.
1813                $overrides{$name} = 1;
1814      }      }
     # Return the result.  
     return $retVal;  
1815  }  }
1816        # Merge the options into the defaults.
1817        GetOptions($optionTable, \%overrides);
1818        # Translate the remaining parameters.
1819        my @retVal = ();
1820        for my $inputParm (@inputList) {
1821            push @retVal, UnEscape($inputParm);
1822        }
1823        # Return the results.
1824        return ($optionTable, @retVal);
1825    }
1826    
1827    
1828    =head2 File Utility Methods
1829    
1830  =head3 GetFile  =head3 GetFile
1831    
# Line 1711  Line 1926 
1926      close $handle;      close $handle;
1927  }  }
1928    
1929  =head3 QTrace  =head3 ParseRecord
1930    
1931      my $data = QTrace($format);      my @fields = Tracer::ParseRecord($line);
1932    
1933  Return the queued trace data in the specified format.  Parse a tab-delimited data line. The data line is split into field values. Embedded tab
1934    and new-line characters in the data line must be represented as C<\t> and C<\n>, respectively.
1935    These will automatically be converted.
1936    
1937  =over 4  =over 4
1938    
1939  =item format  =item line
1940    
1941  C<html> to format the data as an HTML list, C<text> to format it as straight text.  Line of data containing the tab-delimited fields.
1942    
1943    =item RETURN
1944    
1945    Returns a list of the fields found in the data line.
1946    
1947  =back  =back
1948    
1949  =cut  =cut
1950    
1951  sub QTrace {  sub ParseRecord {
1952      # Get the parameter.      # Get the parameter.
1953      my ($format) = @_;      my ($line) = @_;
1954      # Create the return variable.      # Remove the trailing new-line, if any.
1955      my $retVal = "";      chomp $line;
1956      # Only proceed if there is an actual queue.      # Split the line read into pieces using the tab character.
1957      if (@Queue) {      my @retVal = split /\t/, $line;
1958          # Process according to the format.      # Trim and fix the escapes in each piece.
1959          if ($format =~ m/^HTML$/i) {      for my $value (@retVal) {
1960              # Convert the queue into an HTML list.          # Trim leading whitespace.
1961              $retVal = "<ul>\n";          $value =~ s/^\s+//;
1962              for my $line (@Queue) {          # Trim trailing whitespace.
1963                  my $escapedLine = CGI::escapeHTML($line);          $value =~ s/\s+$//;
1964                  $retVal .= "<li>$escapedLine</li>\n";          # Delete the carriage returns.
1965            $value =~ s/\r//g;
1966            # Convert the escapes into their real values.
1967            $value =~ s/\\t/"\t"/ge;
1968            $value =~ s/\\n/"\n"/ge;
1969        }
1970        # Return the result.
1971        return @retVal;
1972    }
1973    
1974    =head3 Merge
1975    
1976        my @mergedList = Tracer::Merge(@inputList);
1977    
1978    Sort a list of strings and remove duplicates.
1979    
1980    =over 4
1981    
1982    =item inputList
1983    
1984    List of scalars to sort and merge.
1985    
1986    =item RETURN
1987    
1988    Returns a list containing the same elements sorted in ascending order with duplicates
1989    removed.
1990    
1991    =back
1992    
1993    =cut
1994    
1995    sub Merge {
1996        # Get the input list in sort order.
1997        my @inputList = sort @_;
1998        # Only proceed if the list has at least two elements.
1999        if (@inputList > 1) {
2000            # Now we want to move through the list splicing out duplicates.
2001            my $i = 0;
2002            while ($i < @inputList) {
2003                # Get the current entry.
2004                my $thisEntry = $inputList[$i];
2005                # Find out how many elements duplicate the current entry.
2006                my $j = $i + 1;
2007                my $dup1 = $i + 1;
2008                while ($j < @inputList && $inputList[$j] eq $thisEntry) { $j++; };
2009                # If the number is nonzero, splice out the duplicates found.
2010                if ($j > $dup1) {
2011                    splice @inputList, $dup1, $j - $dup1;
2012              }              }
2013              $retVal .= "</ul>\n";              # Now the element at position $dup1 is different from the element before it
2014          } elsif ($format =~ m/^TEXT$/i) {              # at position $i. We push $i forward one position and start again.
2015              # Convert the queue into a list of text lines.              $i++;
             $retVal = join("\n", @Queue) . "\n";  
2016          }          }
         # Clear the queue.  
         @Queue = ();  
2017      }      }
2018      # Return the formatted list.      # Return the merged list.
2019      return $retVal;      return @inputList;
2020  }  }
2021    
2022  =head3 Confess  =head3 Open
   
     Confess($message);  
2023    
2024  Trace the call stack and abort the program with the specified message. When used with      my $handle = Open($fileHandle, $fileSpec, $message);
 the OR operator and the L</Assert> method, B<Confess> can function as a debugging assert.  
 So, for example  
2025    
2026      Assert($recNum >= 0) || Confess("Invalid record number $recNum.");  Open a file.
2027    
2028  Will abort the program with a stack trace if the value of C<$recNum> is negative.  The I<$fileSpec> is essentially the second argument of the PERL C<open>
2029    function. The mode is specified using Unix-like shell information. So, for
2030    example,
2031    
2032  =over 4      Open(\*LOGFILE, '>>/usr/spool/news/twitlog', "Could not open twit log.");
2033    
2034  =item message  would open for output appended to the specified file, and
2035    
2036  Message to include in the trace.      Open(\*DATASTREAM, "| sort -u >$outputFile", "Could not open $outputFile.");
2037    
2038  =back  would open a pipe that sorts the records written and removes duplicates. Note
2039    the use of file handle syntax in the Open call. To use anonymous file handles,
2040    code as follows.
2041    
2042  =cut      my $logFile = Open(undef, '>>/usr/spool/news/twitlog', "Could not open twit log.");
2043    
2044  sub Confess {  The I<$message> parameter is used if the open fails. If it is set to C<0>, then
2045      # Get the parameters.  the open returns TRUE if successful and FALSE if an error occurred. Otherwise, a
2046      my ($message) = @_;  failed open will throw an exception and the third parameter will be used to construct
2047      if (! defined($FIG_Config::no_tool_hdr)) {  an error message. If the parameter is omitted, a standard message is constructed
2048          # Here we have a tool header. Display its length so that the user can adjust the line numbers.  using the file spec.
         my $toolHeaderFile = "$FIG_Config::fig_disk/dist/releases/current/$FIG_Config::arch/tool_hdr";  
         # Only proceed if the tool header file is actually present.  
         if (-f $toolHeaderFile) {  
             my @lines = GetFile($toolHeaderFile);  
             Trace("Tool header has " . scalar(@lines) . " lines.");  
         }  
     }  
     # Trace the call stack.  
     Cluck($message);  
     # Abort the program.  
     croak(">>> $message");  
 }  
2049    
2050  =head3 Assert      Could not open "/usr/spool/news/twitlog"
2051    
2052      Assert($condition1, $condition2, ... $conditionN);  Note that the mode characters are automatically cleaned from the file name.
2053    The actual error message from the file system will be captured and appended to the
2054    message in any case.
2055    
2056  Return TRUE if all the conditions are true. This method can be used in conjunction with      Could not open "/usr/spool/news/twitlog": file not found.
 the OR operator and the L</Confess> method as a debugging assert.  
 So, for example  
2057    
2058      Assert($recNum >= 0) || Confess("Invalid record number $recNum.");  In some versions of PERL the only error message we get is a number, which
2059    corresponds to the C++ C<errno> value.
2060    
2061  Will abort the program with a stack trace if the value of C<$recNum> is negative.      Could not open "/usr/spool/news/twitlog": 6.
2062    
2063  =cut  =over 4
 sub Assert {  
     my $retVal = 1;  
     LOOP: for my $condition (@_) {  
         if (! $condition) {  
             $retVal = 0;  
             last LOOP;  
         }  
     }  
     return $retVal;  
 }  
2064    
2065  =head3 Cluck  =item fileHandle
2066    
2067      Cluck($message);  File handle. If this parameter is C<undef>, a file handle will be generated
2068    and returned as the value of this method.
2069    
2070  Trace the call stack. Note that for best results, you should qualify the call with a  =item fileSpec
 trace condition. For example,  
2071    
2072      Cluck("Starting record parse.") if T(3);  File name and mode, as per the PERL C<open> function.
2073    
2074  will only trace the stack if the trace level for the package is 3 or more.  =item message (optional)
2075    
2076  =over 4  Error message to use if the open fails. If omitted, a standard error message
2077    will be generated. In either case, the error information from the file system
2078    is appended to the message. To specify a conditional open that does not throw
2079    an error if it fails, use C<0>.
2080    
2081  =item message  =item RETURN
2082    
2083  Message to include in the trace.  Returns the name of the file handle assigned to the file, or C<undef> if the
2084    open failed.
2085    
2086  =back  =back
2087    
2088  =cut  =cut
2089    
2090  sub Cluck {  sub Open {
2091      # Get the parameters.      # Get the parameters.
2092      my ($message) = @_;      my ($fileHandle, $fileSpec, $message) = @_;
2093      # Trace what's happening.      # Attempt to open the file.
2094      Trace("Stack trace for event: $message");      my $rv = open $fileHandle, $fileSpec;
2095      my $confession = longmess($message);      # If the open failed, generate an error message.
2096      # Convert the confession to a series of trace messages. Note we skip any      if (! $rv) {
2097      # messages relating to calls into Tracer.          # Save the system error message.
2098      for my $line (split /\s*\n/, $confession) {          my $sysMessage = $!;
2099          Trace($line) if ($line !~ /Tracer\.pm/);          # See if we need a default message.
2100            if (!$message) {
2101                # Clean any obvious mode characters and leading spaces from the
2102                # filename.
2103                my ($fileName) = FindNamePart($fileSpec);
2104                $message = "Could not open \"$fileName\"";
2105            }
2106            # Terminate with an error using the supplied message and the
2107            # error message from the file system.
2108            Confess("$message: $!");
2109      }      }
2110        # Return the file handle.
2111        return $fileHandle;
2112  }  }
2113    
2114  =head3 Min  =head3 FindNamePart
2115    
2116      my $min = Min($value1, $value2, ... $valueN);      my ($fileName, $start, $len) = Tracer::FindNamePart($fileSpec);
2117    
2118  Return the minimum argument. The arguments are treated as numbers.  Extract the portion of a file specification that contains the file name.
2119    
2120    A file specification is the string passed to an C<open> call. It specifies the file
2121    mode and name. In a truly complex situation, it can specify a pipe sequence. This
2122    method assumes that the file name is whatever follows the first angle bracket
2123    sequence.  So, for example, in the following strings the file name is
2124    C</usr/fig/myfile.txt>.
2125    
2126        >>/usr/fig/myfile.txt
2127        </usr/fig/myfile.txt
2128        | sort -u > /usr/fig/myfile.txt
2129    
2130    If the method cannot find a file name using its normal methods, it will return the
2131    whole incoming string.
2132    
2133  =over 4  =over 4
2134    
2135  =item $value1, $value2, ... $valueN  =item fileSpec
2136    
2137  List of numbers to compare.  File specification string from which the file name is to be extracted.
2138    
2139  =item RETURN  =item RETURN
2140    
2141  Returns the lowest number in the list.  Returns a three-element list. The first element contains the file name portion of
2142    the specified string, or the whole string if a file name cannot be found via normal
2143    methods. The second element contains the start position of the file name portion and
2144    the third element contains the length.
2145    
2146  =back  =back
2147    
2148  =cut  =cut
2149    #: Return Type $;
2150  sub Min {  sub FindNamePart {
2151      # Get the parameters. Note that we prime the return value with the first parameter.      # Get the parameters.
2152      my ($retVal, @values) = @_;      my ($fileSpec) = @_;
2153      # Loop through the remaining parameters, looking for the lowest.      # Default to the whole input string.
2154      for my $value (@values) {      my ($retVal, $pos, $len) = ($fileSpec, 0, length $fileSpec);
2155          if ($value < $retVal) {      # Parse out the file name if we can.
2156              $retVal = $value;      if ($fileSpec =~ m/(<|>>?)(.+?)(\s*)$/) {
2157          }          $retVal = $2;
2158            $len = length $retVal;
2159            $pos = (length $fileSpec) - (length $3) - $len;
2160      }      }
2161      # Return the minimum found.      # Return the result.
2162      return $retVal;      return ($retVal, $pos, $len);
2163  }  }
2164    
2165  =head3 Max  =head3 OpenDir
2166    
2167      my $max = Max($value1, $value2, ... $valueN);      my @files = OpenDir($dirName, $filtered, $flag);
2168    
2169  Return the maximum argument. The arguments are treated as numbers.  Open a directory and return all the file names. This function essentially performs
2170    the functions of an C<opendir> and C<readdir>. If the I<$filtered> parameter is
2171    set to TRUE, all filenames beginning with a period (C<.>), dollar sign (C<$>),
2172    or pound sign (C<#>) and all filenames ending with a tilde C<~>) will be
2173    filtered out of the return list. If the directory does not open and I<$flag> is not
2174    set, an exception is thrown. So, for example,
2175    
2176        my @files = OpenDir("/Volumes/fig/contigs", 1);
2177    
2178    is effectively the same as
2179    
2180        opendir(TMP, "/Volumes/fig/contigs") || Confess("Could not open /Volumes/fig/contigs.");
2181        my @files = grep { $_ !~ /^[\.\$\#]/ && $_ !~ /~$/ } readdir(TMP);
2182    
2183    Similarly, the following code
2184    
2185        my @files = grep { $_ =~ /^\d/ } OpenDir("/Volumes/fig/orgs", 0, 1);
2186    
2187    Returns the names of all files in C</Volumes/fig/orgs> that begin with digits and
2188    automatically returns an empty list if the directory fails to open.
2189    
2190  =over 4  =over 4
2191    
2192  =item $value1, $value2, ... $valueN  =item dirName
2193    
2194  List of numbers to compare.  Name of the directory to open.
2195    
2196  =item RETURN  =item filtered
2197    
2198  Returns the highest number in the list.  TRUE if files whose names begin with a period (C<.>) should be automatically removed
2199    from the list, else FALSE.
2200    
2201    =item flag
2202    
2203    TRUE if a failure to open is okay, else FALSE
2204    
2205  =back  =back
2206    
2207  =cut  =cut
2208    #: Return Type @;
2209  sub Max {  sub OpenDir {
2210      # Get the parameters. Note that we prime the return value with the first parameter.      # Get the parameters.
2211      my ($retVal, @values) = @_;      my ($dirName, $filtered, $flag) = @_;
2212      # Loop through the remaining parameters, looking for the highest.      # Declare the return variable.
2213      for my $value (@values) {      my @retVal = ();
2214          if ($value > $retVal) {      # Open the directory.
2215              $retVal = $value;      if (opendir(my $dirHandle, $dirName)) {
2216            # The directory opened successfully. Get the appropriate list according to the
2217            # strictures of the filter parameter.
2218            if ($filtered) {
2219                @retVal = grep { $_ !~ /^[\.\$\#]/ && $_ !~ /~$/ } readdir $dirHandle;
2220            } else {
2221                @retVal = readdir $dirHandle;
2222          }          }
2223        } elsif (! $flag) {
2224            # Here the directory would not open and it's considered an error.
2225            Confess("Could not open directory $dirName.");
2226      }      }
2227      # Return the maximum found.      # Return the result.
2228      return $retVal;      return @retVal;
2229  }  }
2230    
 =head3 AddToListMap  
2231    
2232      Tracer::AddToListMap(\%hash, $key, $value1, $value2, ... valueN);  =head3 Insure
   
 Add a key-value pair to a hash of lists. If no value exists for the key, a singleton list  
 is created for the key. Otherwise, the new value is pushed onto the list.  
2233    
2234  =over 4      Insure($dirName, $chmod);
2235    
2236  =item hash  Insure a directory is present.
2237    
2238  Reference to the target hash.  =over 4
2239    
2240  =item key  =item dirName
2241    
2242  Key for which the value is to be added.  Name of the directory to check. If it does not exist, it will be created.
2243    
2244  =item value1, value2, ... valueN  =item chmod (optional)
2245    
2246  List of values to add to the key's value list.  Security privileges to be given to the directory if it is created.
2247    
2248  =back  =back
2249    
2250  =cut  =cut
2251    
2252  sub AddToListMap {  sub Insure {
2253      # Get the parameters.      my ($dirName, $chmod) = @_;
2254      my ($hash, $key, @values) = @_;      if (! -d $dirName) {
2255      # Process according to whether or not the key already has a value.          Trace("Creating $dirName directory.") if T(2);
2256      if (! exists $hash->{$key}) {          eval {
2257          $hash->{$key} = [@values];              mkpath $dirName;
2258      } else {              # If we have permissions specified, set them here.
2259          push @{$hash->{$key}}, @values;              if (defined($chmod)) {
2260                    chmod $chmod, $dirName;
2261      }      }
2262            };
2263            if ($@) {
2264                Confess("Error creating $dirName: $@");
2265  }  }
   
 =head3 DebugMode  
   
     if (Tracer::DebugMode) { ...code... }  
   
 Return TRUE if debug mode has been turned on, else abort.  
   
 Certain CGI scripts are too dangerous to exist in the production  
 environment. This method provides a simple way to prevent them  
 from working unless they are explicitly turned on by creating a password  
 cookie via the B<SetPassword> script.  If debugging mode  
 is not turned on, an error will occur.  
   
 =cut  
   
 sub DebugMode {  
     # Declare the return variable.  
     my $retVal = 0;  
     # Check the debug configuration.  
     my $password = CGI::cookie("DebugMode");  
     my $encrypted = Digest::MD5::md5_hex($password);  
     if ($encrypted eq "252dec43280e0c0d6a75ffcec486e61d") {  
         $retVal = 1;  
     } else {  
         # Here debug mode is off, so we generate an error.  
         Confess("Cannot use this facility without logging in.");  
2266      }      }
     # Return the determination indicator.  
     return $retVal;  
2267  }  }
2268    
2269  =head3 Strip  =head3 ChDir
2270    
2271      my $string = Tracer::Strip($line);      ChDir($dirName);
2272    
2273  Strip all line terminators off a string. This is necessary when dealing with files  Change to the specified directory.
 that may have been transferred back and forth several times among different  
 operating environments.  
2274    
2275  =over 4  =over 4
2276    
2277  =item line  =item dirName
   
 Line of text to be stripped.  
   
 =item RETURN  
2278    
2279  The same line of text with all the line-ending characters chopped from the end.  Name of the directory to which we want to change.
2280    
2281  =back  =back
2282    
2283  =cut  =cut
2284    
2285  sub Strip {  sub ChDir {
2286      # Get a copy of the parameter string.      my ($dirName) = @_;
2287      my ($string) = @_;      if (! -d $dirName) {
2288      my $retVal = (defined $string ? $string : "");          Confess("Cannot change to directory $dirName: no such directory.");
2289      # Strip the line terminator characters.      } else {
2290      $retVal =~ s/(\r|\n)+$//g;          Trace("Changing to directory $dirName.") if T(File => 4);
2291      # Return the result.          my $okFlag = chdir $dirName;
2292      return $retVal;          if (! $okFlag) {
2293                Confess("Error switching to directory $dirName.");
2294            }
2295        }
2296  }  }
2297    
2298  =head3 Pad  =head3 SetPermissions
2299    
2300      my $paddedString = Tracer::Pad($string, $len, $left, $padChar);      Tracer::SetPermissions($dirName, $group, $mask, %otherMasks);
2301    
2302  Pad a string to a specified length. The pad character will be a  Set the permissions for a directory and all the files and folders inside it.
2303  space, and the padding will be on the right side unless specified  In addition, the group ownership will be changed to the specified value.
2304  in the third parameter.  
2305    This method is more vulnerable than most to permission and compatability
2306    problems, so it does internal error recovery.
2307    
2308  =over 4  =over 4
2309    
2310  =item string  =item dirName
2311    
2312  String to be padded.  Name of the directory to process.
2313    
2314  =item len  =item group
2315    
2316  Desired length of the padded string.  Name of the group to be assigned.
2317    
2318  =item left (optional)  =item mask
2319    
2320  TRUE if the string is to be left-padded; otherwise it will be padded on the right.  Permission mask. Bits that are C<1> in this mask will be ORed into the
2321    permission bits of any file or directory that does not already have them
2322    set to 1.
2323    
2324  =item padChar (optional)  =item otherMasks
2325    
2326  Character to use for padding. The default is a space.  Map of search patterns to permission masks. If a directory name matches
2327    one of the patterns, that directory and all its members and subdirectories
2328    will be assigned the new pattern. For example, the following would
2329    assign 01664 to most files, but would use 01777 for directories named C<tmp>.
2330    
2331  =item RETURN      Tracer::SetPermissions($dirName, 'fig', 01664, '^tmp$' => 01777);
2332    
2333  Returns a copy of the original string with the pad character added to the  The list is ordered, so the following would use 0777 for C<tmp1> and
2334  specified end so that it achieves the desired length.  0666 for C<tmp>, C<tmp2>, or C<tmp3>.
2335    
2336        Tracer::SetPermissions($dirName, 'fig', 01664, '^tmp1' => 0777,
2337                                                       '^tmp' => 0666);
2338    
2339    Note that the pattern matches are all case-insensitive, and only directory
2340    names are matched, not file names.
2341    
2342  =back  =back
2343    
2344  =cut  =cut
2345    
2346  sub Pad {  sub SetPermissions {
2347      # Get the parameters.      # Get the parameters.
2348      my ($string, $len, $left, $padChar) = @_;      my ($dirName, $group, $mask, @otherMasks) = @_;
2349      # Compute the padding character.      # Set up for error recovery.
2350      if (! defined $padChar) {      eval {
2351          $padChar = " ";          # Switch to the specified directory.
2352            ChDir($dirName);
2353            # Get the group ID.
2354            my $gid = getgrnam($group);
2355            # Get the mask for tracing.
2356            my $traceMask = sprintf("%04o", $mask) . "($mask)";
2357            Trace("Fixing permissions for directory $dirName using group $group($gid) and mask $traceMask.") if T(File => 2);
2358            my $fixCount = 0;
2359            my $lookCount = 0;
2360            # @dirs will be a stack of directories to be processed.
2361            my @dirs = (getcwd());
2362            while (scalar(@dirs) > 0) {
2363                # Get the current directory.
2364                my $dir = pop @dirs;
2365                # Check for a match to one of the specified directory names. To do
2366                # that, we need to pull the individual part of the name off of the
2367                # whole path.
2368                my $simpleName = $dir;
2369                if ($dir =~ m!/([^/]+)$!) {
2370                    $simpleName = $1;
2371      }      }
2372      # Compute the number of spaces needed.              Trace("Simple directory name for $dir is $simpleName.") if T(File => 4);
2373      my $needed = $len - length $string;              # Search for a match.
2374      # Copy the string into the return variable.              my $match = 0;
2375      my $retVal = $string;              my $i;
2376      # Only proceed if padding is needed.              for ($i = 0; $i < $#otherMasks && ! $match; $i += 2) {
2377      if ($needed > 0) {                  my $pattern = $otherMasks[$i];
2378          # Create the pad string.                  if ($simpleName =~ /$pattern/i) {
2379          my $pad = $padChar x $needed;                      $match = 1;
2380          # Affix it to the return value.                  }
2381          if ($left) {              }
2382              $retVal = $pad . $retVal;              # Check for a match. Note we use $i-1 because the loop added 2
2383                # before terminating due to the match.
2384                if ($match && $otherMasks[$i-1] != $mask) {
2385                    # This directory matches one of the incoming patterns, and it's
2386                    # a different mask, so we process it recursively with that mask.
2387                    SetPermissions($dir, $group, $otherMasks[$i-1], @otherMasks);
2388          } else {          } else {
2389              $retVal .= $pad;                  # Here we can process normally. Get all of the non-hidden members.
2390                    my @submems = OpenDir($dir, 1);
2391                    for my $submem (@submems) {
2392                        # Get the full name.
2393                        my $thisMem = "$dir/$submem";
2394                        Trace("Checking member $thisMem.") if T(4);
2395                        $lookCount++;
2396                        if ($lookCount % 1000 == 0) {
2397                            Trace("$lookCount members examined. Current is $thisMem. Mask is $traceMask") if T(File => 3);
2398          }          }
2399                        # Fix the group.
2400                        chown -1, $gid, $thisMem;
2401                        # Insure this member is not a symlink.
2402                        if (! -l $thisMem) {
2403                            # Get its info.
2404                            my $fileInfo = stat $thisMem;
2405                            # Only proceed if we got the info. Otherwise, it's a hard link
2406                            # and we want to skip it anyway.
2407                            if ($fileInfo) {
2408                                my $fileMode = $fileInfo->mode;
2409                                if (($fileMode & $mask) != $mask) {
2410                                    # Fix this member.
2411                                    $fileMode |= $mask;
2412                                    chmod $fileMode, $thisMem;
2413                                    $fixCount++;
2414      }      }
2415      # Return the result.                              # If it's a subdirectory, stack it.
2416      return $retVal;                              if (-d $thisMem) {
2417                                    push @dirs, $thisMem;
2418                                }
2419                            }
2420                        }
2421                    }
2422                }
2423            }
2424            Trace("$lookCount files and directories processed, $fixCount fixed.") if T(File => 2);
2425        };
2426        # Check for an error.
2427        if ($@) {
2428            Confess("SetPermissions error: $@");
2429  }  }
   
 =head3 EOF  
   
 This is a constant that is lexically greater than any useful string.  
   
 =cut  
   
 sub EOF {  
     return "\xFF\xFF\xFF\xFF\xFF";  
2430  }  }
2431    
2432  =head3 TICK  =head3 GetLine
   
     my @results = TICK($commandString);  
   
 Perform a back-tick operation on a command. If this is a Windows environment, any leading  
 dot-slash (C<./> will be removed. So, for example, if you were doing  
   
     `./protein.cgi`  
   
 from inside a CGI script, it would work fine in Unix, but would issue an error message  
 in Windows complaining that C<'.'> is not a valid command. If instead you code  
2433    
2434      TICK("./protein.cgi")      my @data = Tracer::GetLine($handle);
2435    
2436  it will work correctly in both environments.  Read a line of data from a tab-delimited file.
2437    
2438  =over 4  =over 4
2439    
2440  =item commandString  =item handle
2441    
2442  The command string to pass to the system.  Open file handle from which to read.
2443    
2444  =item RETURN  =item RETURN
2445    
2446  Returns the standard output from the specified command, as a list.  Returns a list of the fields in the record read. The fields are presumed to be
2447    tab-delimited. If we are at the end of the file, then an empty list will be
2448    returned. If an empty line is read, a single list item consisting of a null
2449    string will be returned.
2450    
2451  =back  =back
2452    
2453  =cut  =cut
2454  #: Return Type @;  
2455  sub TICK {  sub GetLine {
2456      # Get the parameters.      # Get the parameters.
2457      my ($commandString) = @_;      my ($handle) = @_;
2458      # Chop off the dot-slash if this is Windows.      # Declare the return variable.
2459      if ($FIG_Config::win_mode) {      my @retVal = ();
2460          $commandString =~ s!^\./!!;      Trace("File position is " . tell($handle) . ". EOF flag is " . eof($handle) . ".") if T(File => 4);
2461        # Read from the file.
2462        my $line = <$handle>;
2463        # Only proceed if we found something.
2464        if (defined $line) {
2465            # Remove the new-line. We are a bit over-cautious here because the file may be coming in via an
2466            # upload control and have a nonstandard EOL combination.
2467            $line =~ s/(\r|\n)+$//;
2468            # Here we do some fancy tracing to help in debugging complicated EOL marks.
2469            if (T(File => 4)) {
2470                my $escapedLine = $line;
2471                $escapedLine =~ s/\n/\\n/g;
2472                $escapedLine =~ s/\r/\\r/g;
2473                $escapedLine =~ s/\t/\\t/g;
2474                Trace("Line read: -->$escapedLine<--");
2475      }      }
2476      # Activate the command and return the result.          # If the line is empty, return a single empty string; otherwise, parse
2477      return `$commandString`;          # it into fields.
2478            if ($line eq "") {
2479                push @retVal, "";
2480            } else {
2481                push @retVal, split /\t/,$line;
2482            }
2483        } else {
2484            # Trace the reason the read failed.
2485            Trace("End of file: $!") if T(File => 3);
2486        }
2487        # Return the result.
2488        return @retVal;
2489  }  }
2490    
2491  =head3 ScriptSetup  =head3 PutLine
   
     my ($cgi, $varHash) = ScriptSetup($noTrace);  
2492    
2493  Perform standard tracing and debugging setup for scripts. The value returned is      Tracer::PutLine($handle, \@fields, $eol);
 the CGI object followed by a pre-built variable hash. At the end of the script,  
 the client should call L</ScriptFinish> to output the web page.  
2494    
2495  This method calls L</ETracing> to configure tracing, which allows the tracing  Write a line of data to a tab-delimited file. The specified field values will be
2496  to be configured via the emergency tracing form on the debugging control panel.  output in tab-separated form, with a trailing new-line.
 Tracing will then be turned on automatically for all programs that use the L</ETracing>  
 method, which includes every program that uses this method or L</StandardSetup>.  
2497    
2498  =over 4  =over 4
2499    
2500  =item noTrace (optional)  =item handle
2501    
2502  If specified, tracing will be suppressed. This is useful if the script wants to set up  Output file handle.
 tracing manually.  
2503    
2504  =item RETURN  =item fields
2505    
2506  Returns a two-element list consisting of a CGI query object and a variable hash for  List of field values.
2507  the output page.  
2508    =item eol (optional)
2509    
2510    End-of-line character (default is "\n").
2511    
2512  =back  =back
2513    
2514  =cut  =cut
2515    
2516  sub ScriptSetup {  sub PutLine {
2517      # Get the parameters.      # Get the parameters.
2518      my ($noTrace) = @_;      my ($handle, $fields, $eol) = @_;
2519      # Get the CGI query object.      # Write the data.
2520      my $cgi = CGI->new();      print $handle join("\t", @{$fields}) . ($eol || "\n");
     # Set up tracing if it's not suppressed.  
     ETracing($cgi) unless $noTrace;  
     # Create the variable hash.  
     my $varHash = { results => '' };  
     # Return the query object and variable hash.  
     return ($cgi, $varHash);  
2521  }  }
2522    
 =head3 ETracing  
2523    
     ETracing($parameter);  
2524    
2525  Set up emergency tracing. Emergency tracing is tracing that is turned  =head2 Other Useful Methods
2526  on automatically for any program that calls this method. The emergency  
2527  tracing parameters are stored in a a file identified by a tracing key.  =head3 ParseParm
2528  If this method is called with a CGI object, then the tracing key is  
2529  taken from a cookie. If it is called with no parameters, then the tracing      my $listValue = Tracer::ParseParm($string);
2530  key is taken from an environment variable. If it is called with a string,  
2531  the tracing key is that string.  Convert a parameter into a list reference. If the parameter is undefined,
2532    an undefined value will be returned. Otherwise, it will be parsed as a
2533    comma-separated list of values.
2534    
2535  =over 4  =over 4
2536    
2537  =item parameter  =item string
2538    
2539  A parameter from which the tracing key is computed. If it is a scalar,  Incoming string.
2540  that scalar is used as the tracing key. If it is a CGI object, the  
2541  tracing key is taken from the C<IP> cookie. If it is omitted, the  =item RETURN
2542  tracing key is taken from the C<TRACING> environment variable. If it  
2543  is a CGI object and emergency tracing is not on, the C<Trace> and  Returns a reference to a list of values, or C<undef> if the incoming value
2544  C<TF> parameters will be used to determine the type of tracing.  was undefined.
2545    
2546  =back  =back
2547    
2548  =cut  =cut
2549    
2550  sub ETracing {  sub ParseParm {
2551      # Get the parameter.      # Get the parameters.
2552      my ($parameter) = @_;      my ($string) = @_;
2553      # Check for CGI mode.      # Declare the return variable.
2554      my $cgi = (ref $parameter eq 'CGI' ? $parameter : undef);      my $retVal;
2555      # Default to no tracing except errors.      # Check for data.
2556      my ($tracing, $dest) = ("0", "WARN");      if (defined $string) {
2557      # Check for emergency tracing.          # We have some, so split it into a list.
2558      my $tkey = EmergencyKey($parameter);          $retVal = [ split /\s*,\s*/, $string];
     my $emergencyFile = EmergencyFileName($tkey);  
     if (-e $emergencyFile) {  
         # We have the file. Read in the data.  
         my @tracing = GetFile($emergencyFile);  
         # Pull off the time limit.  
         my $expire = shift @tracing;  
         # Convert it to seconds.  
         $expire *= 3600;  
         # Check the file data.  
         my $stat = stat($emergencyFile);  
         my ($now) = gettimeofday;  
         if ($now - $stat->mtime > $expire) {  
             # Delete the expired file.  
             unlink $emergencyFile;  
         } else {  
             # Emergency tracing is on. Pull off the destination and  
             # the trace level;  
             $dest = shift @tracing;  
             my $level = shift @tracing;  
             # Convert the destination to a real tracing destination.  
             # temp directory.  
             $dest = EmergencyTracingDest($tkey, $dest);  
             # Insure Tracer is specified.  
             my %moduleHash = map { $_ => 1 } @tracing;  
             $moduleHash{Tracer} = 1;  
             # Set the trace parameter.  
             $tracing = join(" ", $level, sort keys %moduleHash);  
         }  
     } elsif (defined $cgi) {  
         # There's no emergency tracing, but we have a CGI object, so check  
         # for tracing from the form parameters.  
         if ($cgi->param('Trace')) {  
             # Here the user has requested tracing via a form.  
             $dest = ($cgi->param('TF') ? ">$FIG_Config::temp/Trace$$.log" : "QUEUE");  
             $tracing = $cgi->param('Trace') . " Tracer";  
         }  
     }  
     # Setup the tracing we've determined from all the stuff above.  
     TSetup($tracing, $dest);  
     # If we're a web script, trace the parameter and environment data.  
     if (defined $cgi) {  
         TraceParms($cgi);  
2559      }      }
2560        # Return the result.
2561        return $retVal;
2562  }  }
2563    
 =head3 EmergencyFileName  
   
     my $fileName = Tracer::EmergencyFileName($tkey);  
   
 Return the emergency tracing file name. This is the file that specifies  
 the tracing information.  
   
 =over 4  
2564    
 =item tkey  
2565    
 Tracing key for the current program.  
2566    
2567  =item RETURN  =head3 Now
2568    
2569  Returns the name of the file to contain the emergency tracing information.      my $string = Tracer::Now();
2570    
2571  =back  Return a displayable time stamp containing the local time.
2572    
2573  =cut  =cut
2574    
2575  sub EmergencyFileName {  sub Now {
2576      # Get the parameters.      my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = localtime(time);
2577      my ($tkey) = @_;      my $retVal = _p2($mon+1) . "/" . _p2($mday) . "/" . ($year + 1900) . " " .
2578      # Compute the emergency tracing file name.                   _p2($hour) . ":" . _p2($min) . ":" . _p2($sec);
2579      return "$FIG_Config::temp/Emergency$tkey.txt";      return $retVal;
2580  }  }
2581    
2582  =head3 EmergencyFileTarget  # Pad a number to 2 digits.
2583    sub _p2 {
2584        my ($value) = @_;
2585        $value = "0$value" if ($value < 10);
2586        return $value;
2587    }
2588    
2589      my $fileName = Tracer::EmergencyFileTarget($tkey);  =head3 Escape
2590    
2591  Return the emergency tracing target file name. This is the file that receives      my $codedString = Tracer::Escape($realString);
2592  the tracing output for file-based tracing.  
2593    Escape a string for use in a command. Tabs will be replaced by C<\t>, new-lines
2594    replaced by C<\n>, carriage returns will be deleted, and backslashes will be doubled. The
2595    result is to reverse the effect of L</UnEscape>.
2596    
2597  =over 4  =over 4
2598    
2599  =item tkey  =item realString
2600    
2601  Tracing key for the current program.  String to escape.
2602    
2603  =item RETURN  =item RETURN
2604    
2605  Returns the name of the file to contain the trace output.  Escaped equivalent of the real string.
2606    
2607  =back  =back
2608    
2609  =cut  =cut
2610    
2611  sub EmergencyFileTarget {  sub Escape {
2612      # Get the parameters.      # Get the parameter.
2613      my ($tkey) = @_;      my ($realString) = @_;
2614      # Compute the emergency tracing file name.      # Initialize the return variable.
2615      return "$FIG_Config::temp/trace$tkey.log";      my $retVal = "";
2616        # Loop through the parameter string, looking for sequences to escape.
2617        while (length $realString > 0) {
2618            # Look for the first sequence to escape.
2619            if ($realString =~ /^(.*?)([\n\t\r\\])/) {
2620                # Here we found it. The text preceding the sequence is in $1. The sequence
2621                # itself is in $2. First, move the clear text to the return variable.
2622                $retVal .= $1;
2623                # Strip the processed section off the real string.
2624                $realString = substr $realString, (length $2) + (length $1);
2625                # Get the matched character.
2626                my $char = $2;
2627                # If we have a CR, we are done.
2628                if ($char ne "\r") {
2629                    # It's not a CR, so encode the escape sequence.
2630                    $char =~ tr/\t\n/tn/;
2631                    $retVal .= "\\" . $char;
2632                }
2633            } else {
2634                # Here there are no more escape sequences. The rest of the string is
2635                # transferred unmodified.
2636                $retVal .= $realString;
2637                $realString = "";
2638            }
2639        }
2640        # Return the result.
2641        return $retVal;
2642  }  }
2643    
2644  =head3 EmergencyTracingDest  =head3 UnEscape
2645    
2646      my $dest = Tracer::EmergencyTracingDest($tkey, $myDest);      my $realString = Tracer::UnEscape($codedString);
2647    
2648  This method converts an emergency tracing destination to a real  Replace escape sequences with their actual equivalents. C<\t> will be replaced by
2649  tracing destination. The main difference is that if the  a tab, C<\n> by a new-line character, and C<\\> by a backslash. C<\r> codes will
2650  destination is C<FILE> or C<APPEND>, we convert it to file  be deleted.
 output. If the destination is C<DUAL>, we convert it to file  
 and standard output.  
2651    
2652  =over 4  =over 4
2653    
2654  =item tkey  =item codedString
   
 Tracing key for this environment.  
   
 =item myDest  
2655    
2656  Destination from the emergency tracing file.  String to un-escape.
2657    
2658  =item RETURN  =item RETURN
2659    
2660  Returns a destination that can be passed into L</TSetup>.  Returns a copy of the original string with the escape sequences converted to their actual
2661    values.
2662    
2663  =back  =back
2664    
2665  =cut  =cut
2666    
2667  sub EmergencyTracingDest {  sub UnEscape {
2668      # Get the parameters.      # Get the parameter.
2669      my ($tkey, $myDest) = @_;      my ($codedString) = @_;
2670      # Declare the return variable.      # Initialize the return variable.
2671      my $retVal = $myDest;      my $retVal = "";
2672      # Process according to the destination value.      # Only proceed if the incoming string is nonempty.
2673      if ($myDest eq 'FILE') {      if (defined $codedString) {
2674          $retVal = ">" . EmergencyFileTarget($tkey);          # Loop through the parameter string, looking for escape sequences. We can't do
2675      } elsif ($myDest eq 'APPEND') {          # translating because it causes problems with the escaped slash. ("\\t" becomes
2676          $retVal = ">>" . EmergencyFileTarget($tkey);          # "\<tab>" no matter what we do.)
2677      } elsif ($myDest eq 'DUAL') {          while (length $codedString > 0) {
2678          $retVal = "+>" . EmergencyFileTarget($tkey);              # Look for the first escape sequence.
2679                if ($codedString =~ /^(.*?)\\(\\|n|t|r)/) {
2680                    # Here we found it. The text preceding the sequence is in $1. The sequence
2681                    # itself is in $2. First, move the clear text to the return variable.
2682                    $retVal .= $1;
2683                    $codedString = substr $codedString, (2 + length $1);
2684                    # Get the escape value.
2685                    my $char = $2;
2686                    # If we have a "\r", we are done.
2687                    if ($char ne 'r') {
2688                        # Here it's not an 'r', so we convert it.
2689                        $char =~ tr/\\tn/\\\t\n/;
2690                        $retVal .= $char;
2691                    }
2692                } else {
2693                    # Here there are no more escape sequences. The rest of the string is
2694                    # transferred unmodified.
2695                    $retVal .= $codedString;
2696                    $codedString = "";
2697                }
2698            }
2699      }      }
2700      # Return the result.      # Return the result.
2701      return $retVal;      return $retVal;
2702  }  }
2703    
2704  =head3 Emergency  =head3 Percent
2705    
2706      Emergency($key, $hours, $dest, $level, @modules);      my $percent = Tracer::Percent($number, $base);
2707    
2708  Turn on emergency tracing. This method is normally invoked over the web from  Returns the percent of the base represented by the given number. If the base
2709  a debugging console, but it can also be called by the C<trace.pl> script.  is zero, returns zero.
 The caller specifies the duration of the emergency in hours, the desired tracing  
 destination, the trace level, and a list of the trace modules to activate.  
 For the length of the duration, when a program in an environment with the  
 specified tracing key active invokes a Sprout CGI script, tracing will be  
 turned on automatically. See L</TSetup> for more about tracing setup and  
 L</ETracing> for more about emergency tracing.  
2710    
2711  =over 4  =over 4
2712    
2713  =item tkey  =item number
   
 The tracing key. This is used to identify the control file and the trace file.  
   
 =item hours  
   
 Number of hours to keep emergency tracing alive.  
   
 =item dest  
   
 Tracing destination. If no path information is specified for a file  
 destination, it is put in the FIG temporary directory.  
   
 =item level  
   
 Tracing level. A higher level means more trace messages.  
   
 =item modules  
   
 A list of the tracing modules to activate.  
   
 =back  
   
 =cut  
   
 sub Emergency {  
     # Get the parameters.  
     my ($tkey, $hours, $dest, $level, @modules) = @_;  
     # Create the emergency file.  
     my $specFile = EmergencyFileName($tkey);  
     my $outHandle = Open(undef, ">$specFile");  
     print $outHandle join("\n", $hours, $dest, $level, @modules, "");  
 }  
   
 =head3 EmergencyKey  
   
     my $tkey = EmergencyKey($parameter);  
   
 Return the Key to be used for emergency tracing. This could be an IP address,  
  a session ID, or a user name, depending on the environment.  
2714    
2715  =over 4  Percent numerator.
2716    
2717  =item parameter  =item base
2718    
2719  Parameter defining the method for finding the tracing key. If it is a scalar,  Percent base.
 then it is presumed to be the tracing key itself. If it is a CGI object, then  
 the tracing key is taken from the C<IP> cookie. Otherwise, the tracing key is  
 taken from the C<TRACING> environment variable.  
2720    
2721  =item RETURN  =item RETURN
2722    
2723  Returns the key to be used for labels in emergency tracing.  Returns the percentage of the base represented by the numerator.
2724    
2725  =back  =back
2726    
2727  =cut  =cut
2728    
2729  sub EmergencyKey {  sub Percent {
2730      # Get the parameters.      # Get the parameters.
2731      my ($parameter) = @_;      my ($number, $base) = @_;
2732      # Declare the return variable.      # Declare the return variable.
2733      my $retVal;      my $retVal = 0;
2734      # Determine the parameter type.      # Compute the percent.
2735      if (! defined $parameter) {      if ($base != 0) {
2736          # Here we're supposed to check the environment.          $retVal = $number * 100 / $base;
         $retVal = $ENV{TRACING};  
     } else {  
         my $ptype = ref $parameter;  
         if ($ptype eq 'CGI') {  
             # Here we were invoked from a web page. Look for a cookie.  
             $retVal = $parameter->cookie('IP');  
         } elsif (! $ptype) {  
             # Here the key was passed in.  
             $retVal = $parameter;  
         }  
     }  
     # If no luck finding a key, use the PID.  
     if (! defined $retVal) {  
         $retVal = $$;  
2737      }      }
2738      # Return the result.      # Return the result.
2739      return $retVal;      return $retVal;
2740  }  }
2741    
2742    =head3 Min
2743    
2744  =head3 TraceParms      my $min = Min($value1, $value2, ... $valueN);
   
     Tracer::TraceParms($cgi);  
2745    
2746  Trace the CGI parameters at trace level CGI => 3 and the environment variables  Return the minimum argument. The arguments are treated as numbers.
 at level CGI => 4.  
2747    
2748  =over 4  =over 4
2749    
2750  =item cgi  =item $value1, $value2, ... $valueN
2751    
2752  CGI query object containing the parameters to trace.  List of numbers to compare.
2753    
2754    =item RETURN
2755    
2756    Returns the lowest number in the list.
2757    
2758  =back  =back
2759    
2760  =cut  =cut
2761    
2762  sub TraceParms {  sub Min {
2763      # Get the parameters.      # Get the parameters. Note that we prime the return value with the first parameter.
2764      my ($cgi) = @_;      my ($retVal, @values) = @_;
2765      if (T(CGI => 3)) {      # Loop through the remaining parameters, looking for the lowest.
2766          # Here we want to trace the parameter data.      for my $value (@values) {
2767          my @names = $cgi->param;          if ($value < $retVal) {
2768          for my $parmName (sort @names) {              $retVal = $value;
             # Note we skip the Trace parameters, which are for our use only.  
             if ($parmName ne 'Trace' && $parmName ne 'TF') {  
                 my @values = $cgi->param($parmName);  
                 Trace("CGI: $parmName = " . join(", ", @values));  
             }  
         }  
         # Display the request method.  
         my $method = $cgi->request_method();  
         Trace("Method: $method");  
     }  
     if (T(CGI => 4)) {  
         # Here we want the environment data too.  
         for my $envName (sort keys %ENV) {  
             Trace("ENV: $envName = $ENV{$envName}");  
2769          }          }
2770      }      }
2771        # Return the minimum found.
2772        return $retVal;
2773  }  }
2774    
2775  =head3 ScriptFinish  =head3 Max
   
     ScriptFinish($webData, $varHash);  
   
 Output a web page at the end of a script. Either the string to be output or the  
 name of a template file can be specified. If the second parameter is omitted,  
 it is assumed we have a string to be output; otherwise, it is assumed we have the  
 name of a template file. The template should have the variable C<DebugData>  
 specified in any form that invokes a standard script. If debugging mode is turned  
 on, a form field will be put in that allows the user to enter tracing data.  
 Trace messages will be placed immediately before the terminal C<BODY> tag in  
 the output, formatted as a list.  
   
 A typical standard script would loook like the following.  
   
     BEGIN {  
         # Print the HTML header.  
         print "CONTENT-TYPE: text/html\n\n";  
     }  
     use Tracer;  
     use CGI;  
     use FIG;  
     # ... more uses ...  
2776    
2777      my ($cgi, $varHash) = ScriptSetup();      my $max = Max($value1, $value2, ... $valueN);
     eval {  
         # ... get data from $cgi, put it in $varHash ...  
     };  
     if ($@) {  
         Trace("Script Error: $@") if T(0);  
     }  
     ScriptFinish("Html/MyTemplate.html", $varHash);  
2778    
2779  The idea here is that even if the script fails, you'll see trace messages and  Return the maximum argument. The arguments are treated as numbers.
 useful output.  
2780    
2781  =over 4  =over 4
2782    
2783  =item webData  =item $value1, $value2, ... $valueN
   
 A string containing either the full web page to be written to the output or the  
 name of a template file from which the page is to be constructed. If the name  
 of a template file is specified, then the second parameter must be present;  
 otherwise, it must be absent.  
2784    
2785  =item varHash (optional)  List of numbers to compare.
2786    
2787  If specified, then a reference to a hash mapping variable names for a template  =item RETURN
2788  to their values. The template file will be read into memory, and variable markers  
2789  will be replaced by data in this hash reference.  Returns the highest number in the list.
2790    
2791  =back  =back
2792    
2793  =cut  =cut
2794    
2795  sub ScriptFinish {  sub Max {
2796      # Get the parameters.      # Get the parameters. Note that we prime the return value with the first parameter.
2797      my ($webData, $varHash) = @_;      my ($retVal, @values) = @_;
2798      # Check for a template file situation.      # Loop through the remaining parameters, looking for the highest.
2799      my $outputString;      for my $value (@values) {
2800      if (defined $varHash) {          if ($value > $retVal) {
2801          # Here we have a template file. We need to determine the template type.              $retVal = $value;
         my $template;  
         if ($FIG_Config::template_url && $webData =~ /\.php$/) {  
             $template = "$FIG_Config::template_url/$webData";  
         } else {  
             $template = "<<$webData";  
2802          }          }
         $outputString = PageBuilder::Build($template, $varHash, "Html");  
     } else {  
         # Here the user gave us a raw string.  
         $outputString = $webData;  
2803      }      }
2804      # Check for trace messages.      # Return the maximum found.
2805      if ($Destination ne "NONE" && $TraceLevel > 0) {      return $retVal;
         # We have trace messages, so we want to put them at the end of the body. This  
         # is either at the end of the whole string or at the beginning of the BODY  
         # end-tag.  
         my $pos = length $outputString;  
         if ($outputString =~ m#</body>#gi) {  
             $pos = (pos $outputString) - 7;  
2806          }          }
2807          # If the trace messages were queued, we unroll them. Otherwise, we display the  
2808          # destination.  =head3 DebugMode
2809          my $traceHtml;  
2810          if ($Destination eq "QUEUE") {      if (Tracer::DebugMode) { ...code... }
2811              $traceHtml = QTrace('Html');  
2812          } elsif ($Destination =~ /^>>(.+)$/) {  Return TRUE if debug mode has been turned on, else abort.
2813              # Here the tracing output it to a file. We code it as a hyperlink so the user  
2814              # can copy the file name into the clipboard easily.  Certain CGI scripts are too dangerous to exist in the production
2815              my $actualDest = $1;  environment. This method provides a simple way to prevent them
2816              $traceHtml = "<p>Tracing output to $actualDest.</p>\n";  from working unless they are explicitly turned on by creating a password
2817    cookie via the B<SetPassword> script.  If debugging mode
2818    is not turned on, an error will occur.
2819    
2820    =cut
2821    
2822    sub DebugMode {
2823        # Declare the return variable.
2824        my $retVal = 0;
2825        # Check the debug configuration.
2826        my $password = CGI::cookie("DebugMode");
2827        my $encrypted = Digest::MD5::md5_hex($password);
2828        if ($encrypted eq "252dec43280e0c0d6a75ffcec486e61d") {
2829            $retVal = 1;
2830          } else {          } else {
2831              # Here we have one of the special destinations.          # Here debug mode is off, so we generate an error.
2832              $traceHtml = "<P>Tracing output type is $Destination.</p>\n";          Confess("Cannot use this facility without logging in.");
         }  
         substr $outputString, $pos, 0, $traceHtml;  
2833      }      }
2834      # Write the output string.      # Return the determination indicator.
2835      print $outputString;      return $retVal;
2836  }  }
2837    
2838  =head3 Insure  =head3 Strip
2839    
2840      Insure($dirName, $chmod);      my $string = Tracer::Strip($line);
2841    
2842  Insure a directory is present.  Strip all line terminators off a string. This is necessary when dealing with files
2843    that may have been transferred back and forth several times among different
2844    operating environments.
2845    
2846  =over 4  =over 4
2847    
2848  =item dirName  =item line
2849    
2850  Name of the directory to check. If it does not exist, it will be created.  Line of text to be stripped.
2851    
2852  =item chmod (optional)  =item RETURN
2853    
2854  Security privileges to be given to the directory if it is created.  The same line of text with all the line-ending characters chopped from the end.
2855    
2856  =back  =back
2857    
2858  =cut  =cut
2859    
2860  sub Insure {  sub Strip {
2861      my ($dirName, $chmod) = @_;      # Get a copy of the parameter string.
2862      if (! -d $dirName) {      my ($string) = @_;
2863          Trace("Creating $dirName directory.") if T(2);      my $retVal = (defined $string ? $string : "");
2864          eval {      # Strip the line terminator characters.
2865              mkpath $dirName;      $retVal =~ s/(\r|\n)+$//g;
2866              # If we have permissions specified, set them here.      # Return the result.
2867              if (defined($chmod)) {      return $retVal;
                 chmod $chmod, $dirName;  
             }  
         };  
         if ($@) {  
             Confess("Error creating $dirName: $@");  
         }  
     }  
2868  }  }
2869    
2870  =head3 ChDir  =head3 Pad
2871    
2872      ChDir($dirName);      my $paddedString = Tracer::Pad($string, $len, $left, $padChar);
2873    
2874  Change to the specified directory.  Pad a string to a specified length. The pad character will be a
2875    space, and the padding will be on the right side unless specified
2876    in the third parameter.
2877    
2878  =over 4  =over 4
2879    
2880  =item dirName  =item string
2881    
2882  Name of the directory to which we want to change.  String to be padded.
2883    
2884    =item len
2885    
2886    Desired length of the padded string.
2887    
2888    =item left (optional)
2889    
2890    TRUE if the string is to be left-padded; otherwise it will be padded on the right.
2891    
2892    =item padChar (optional)
2893    
2894    Character to use for padding. The default is a space.
2895    
2896    =item RETURN
2897    
2898    Returns a copy of the original string with the pad character added to the
2899    specified end so that it achieves the desired length.
2900    
2901  =back  =back
2902    
2903  =cut  =cut
2904    
2905  sub ChDir {  sub Pad {
2906      my ($dirName) = @_;      # Get the parameters.
2907      if (! -d $dirName) {      my ($string, $len, $left, $padChar) = @_;
2908          Confess("Cannot change to directory $dirName: no such directory.");      # Compute the padding character.
2909        if (! defined $padChar) {
2910            $padChar = " ";
2911        }
2912        # Compute the number of spaces needed.
2913        my $needed = $len - length $string;
2914        # Copy the string into the return variable.
2915        my $retVal = $string;
2916        # Only proceed if padding is needed.
2917        if ($needed > 0) {
2918            # Create the pad string.
2919            my $pad = $padChar x $needed;
2920            # Affix it to the return value.
2921            if ($left) {
2922                $retVal = $pad . $retVal;
2923      } else {      } else {
2924          Trace("Changing to directory $dirName.") if T(File => 4);              $retVal .= $pad;
         my $okFlag = chdir $dirName;  
         if (! $okFlag) {  
             Confess("Error switching to directory $dirName.");  
2925          }          }
2926      }      }
2927        # Return the result.
2928        return $retVal;
2929  }  }
2930    
2931  =head3 SendSMS  =head3 EOF
2932    
2933      my $msgID = Tracer::SendSMS($phoneNumber, $msg);  This is a constant that is lexically greater than any useful string.
2934    
2935  Send a text message to a phone number using Clickatell. The FIG_Config file must contain the  =cut
 user name, password, and API ID for the relevant account in the hash reference variable  
 I<$FIG_Config::phone>, using the keys C<user>, C<password>, and C<api_id>. For  
 example, if the user name is C<BruceTheHumanPet>, the password is C<silly>, and the API ID  
 is C<2561022>, then the FIG_Config file must contain  
2936    
2937      $phone =  { user => 'BruceTheHumanPet',  sub EOF {
2938                  password => 'silly',      return "\xFF\xFF\xFF\xFF\xFF";
2939                  api_id => '2561022' };  }
2940    
2941  The original purpose of this method was to insure Bruce would be notified immediately when the  =head3 TICK
 Sprout Load terminates. Care should be taken if you do not wish Bruce to be notified immediately  
 when you call this method.  
2942    
2943  The message ID will be returned if successful, and C<undef> if an error occurs.      my @results = TICK($commandString);
2944    
2945  =over 4  Perform a back-tick operation on a command. If this is a Windows environment, any leading
2946    dot-slash (C<./> will be removed. So, for example, if you were doing
2947    
2948  =item phoneNumber      `./protein.cgi`
2949    
2950  Phone number to receive the message, in international format. A United States phone number  from inside a CGI script, it would work fine in Unix, but would issue an error message
2951  would be prefixed by "1". A British phone number would be prefixed by "44".  in Windows complaining that C<'.'> is not a valid command. If instead you code
2952    
2953  =item msg      TICK("./protein.cgi")
2954    
2955  Message to send to the specified phone.  it will work correctly in both environments.
2956    
2957    =over 4
2958    
2959    =item commandString
2960    
2961    The command string to pass to the system.
2962    
2963  =item RETURN  =item RETURN
2964    
2965  Returns the message ID if successful, and C<undef> if the message could not be sent.  Returns the standard output from the specified command, as a list.
2966    
2967  =back  =back
2968    
2969  =cut  =cut
2970    #: Return Type @;
2971  sub SendSMS {  sub TICK {
2972      # Get the parameters.      # Get the parameters.
2973      my ($phoneNumber, $msg) = @_;      my ($commandString) = @_;
2974      # Declare the return variable. If we do not change it, C<undef> will be returned.      # Chop off the dot-slash if this is Windows.
2975      my $retVal;      if ($FIG_Config::win_mode) {
2976      # Only proceed if we have phone support.          $commandString =~ s!^\./!!;
     if (! defined $FIG_Config::phone) {  
         Trace("Phone support not present in FIG_Config.") if T(1);  
     } else {  
         # Get the phone data.  
         my $parms = $FIG_Config::phone;  
         # Get the Clickatell URL.  
         my $url = "http://api.clickatell.com/http/";  
         # Create the user agent.  
         my $ua = LWP::UserAgent->new;  
         # Request a Clickatell session.  
         my $resp = $ua->post("$url/sendmsg", { user => $parms->{user},  
                                      password => $parms->{password},  
                                      api_id => $parms->{api_id},  
                                      to => $phoneNumber,  
                                      text => $msg});  
         # Check for an error.  
         if (! $resp->is_success) {  
             Trace("Alert failed.") if T(1);  
         } else {  
             # Get the message ID.  
             my $rstring = $resp->content;  
             if ($rstring =~ /^ID:\s+(.*)$/) {  
                 $retVal = $1;  
             } else {  
                 Trace("Phone attempt failed with $rstring") if T(1);  
             }  
         }  
2977      }      }
2978      # Return the result.      # Activate the command and return the result.
2979      return $retVal;      return `$commandString`;
2980  }  }
2981    
2982    
2983  =head3 CommaFormat  =head3 CommaFormat
2984    
2985      my $formatted = Tracer::CommaFormat($number);      my $formatted = Tracer::CommaFormat($number);
# Line 2775  Line 3015 
3015      # Return the result.      # Return the result.
3016      return $retVal;      return $retVal;
3017  }  }
 =head3 SetPermissions  
   
     Tracer::SetPermissions($dirName, $group, $mask, %otherMasks);  
   
 Set the permissions for a directory and all the files and folders inside it.  
 In addition, the group ownership will be changed to the specified value.  
   
 This method is more vulnerable than most to permission and compatability  
 problems, so it does internal error recovery.  
   
 =over 4  
   
 =item dirName  
   
 Name of the directory to process.  
   
 =item group  
   
 Name of the group to be assigned.  
   
 =item mask  
   
 Permission mask. Bits that are C<1> in this mask will be ORed into the  
 permission bits of any file or directory that does not already have them  
 set to 1.  
3018    
 =item otherMasks  
   
 Map of search patterns to permission masks. If a directory name matches  
 one of the patterns, that directory and all its members and subdirectories  
 will be assigned the new pattern. For example, the following would  
 assign 01664 to most files, but would use 01777 for directories named C<tmp>.  
   
     Tracer::SetPermissions($dirName, 'fig', 01664, '^tmp$' => 01777);  
   
 The list is ordered, so the following would use 0777 for C<tmp1> and  
 0666 for C<tmp>, C<tmp2>, or C<tmp3>.  
   
     Tracer::SetPermissions($dirName, 'fig', 01664, '^tmp1' => 0777,  
                                                    '^tmp' => 0666);  
   
 Note that the pattern matches are all case-insensitive, and only directory  
 names are matched, not file names.  
   
 =back  
   
 =cut  
   
 sub SetPermissions {  
     # Get the parameters.  
     my ($dirName, $group, $mask, @otherMasks) = @_;  
     # Set up for error recovery.  
     eval {  
         # Switch to the specified directory.  
         ChDir($dirName);  
         # Get the group ID.  
         my $gid = getgrnam($group);  
         # Get the mask for tracing.  
         my $traceMask = sprintf("%04o", $mask) . "($mask)";  
         Trace("Fixing permissions for directory $dirName using group $group($gid) and mask $traceMask.") if T(File => 2);  
         my $fixCount = 0;  
         my $lookCount = 0;  
         # @dirs will be a stack of directories to be processed.  
         my @dirs = (getcwd());  
         while (scalar(@dirs) > 0) {  
             # Get the current directory.  
             my $dir = pop @dirs;  
             # Check for a match to one of the specified directory names. To do  
             # that, we need to pull the individual part of the name off of the  
             # whole path.  
             my $simpleName = $dir;  
             if ($dir =~ m!/([^/]+)$!) {  
                 $simpleName = $1;  
             }  
             Trace("Simple directory name for $dir is $simpleName.") if T(File => 4);  
             # Search for a match.  
             my $match = 0;  
             my $i;  
             for ($i = 0; $i < $#otherMasks && ! $match; $i += 2) {  
                 my $pattern = $otherMasks[$i];  
                 if ($simpleName =~ /$pattern/i) {  
                     $match = 1;  
                 }  
             }  
             # Check for a match. Note we use $i-1 because the loop added 2  
             # before terminating due to the match.  
             if ($match && $otherMasks[$i-1] != $mask) {  
                 # This directory matches one of the incoming patterns, and it's  
                 # a different mask, so we process it recursively with that mask.  
                 SetPermissions($dir, $group, $otherMasks[$i-1], @otherMasks);  
             } else {  
                 # Here we can process normally. Get all of the non-hidden members.  
                 my @submems = OpenDir($dir, 1);  
                 for my $submem (@submems) {  
                     # Get the full name.  
                     my $thisMem = "$dir/$submem";  
                     Trace("Checking member $thisMem.") if T(4);  
                     $lookCount++;  
                     if ($lookCount % 1000 == 0) {  
                         Trace("$lookCount members examined. Current is $thisMem. Mask is $traceMask") if T(File => 3);  
                     }  
                     # Fix the group.  
                     chown -1, $gid, $thisMem;  
                     # Insure this member is not a symlink.  
                     if (! -l $thisMem) {  
                         # Get its info.  
                         my $fileInfo = stat $thisMem;  
                         # Only proceed if we got the info. Otherwise, it's a hard link  
                         # and we want to skip it anyway.  
                         if ($fileInfo) {  
                             my $fileMode = $fileInfo->mode;  
                             if (($fileMode & $mask) != $mask) {  
                                 # Fix this member.  
                                 $fileMode |= $mask;  
                                 chmod $fileMode, $thisMem;  
                                 $fixCount++;  
                             }  
                             # If it's a subdirectory, stack it.  
                             if (-d $thisMem) {  
                                 push @dirs, $thisMem;  
                             }  
                         }  
                     }  
                 }  
             }  
         }  
         Trace("$lookCount files and directories processed, $fixCount fixed.") if T(File => 2);  
     };  
     # Check for an error.  
     if ($@) {  
         Confess("SetPermissions error: $@");  
     }  
 }  
3019    
3020  =head3 CompareLists  =head3 CompareLists
3021    
# Line 2976  Line 3084 
3084      return ($inserted, $deleted);      return ($inserted, $deleted);
3085  }  }
3086    
 =head3 GetLine  
   
     my @data = Tracer::GetLine($handle);  
   
 Read a line of data from a tab-delimited file.  
   
 =over 4  
   
 =item handle  
   
 Open file handle from which to read.  
   
 =item RETURN  
   
 Returns a list of the fields in the record read. The fields are presumed to be  
 tab-delimited. If we are at the end of the file, then an empty list will be  
 returned. If an empty line is read, a single list item consisting of a null  
 string will be returned.  
   
 =back  
   
 =cut  
   
 sub GetLine {  
     # Get the parameters.  
     my ($handle) = @_;  
     # Declare the return variable.  
     my @retVal = ();  
     Trace("File position is " . tell($handle) . ". EOF flag is " . eof($handle) . ".") if T(File => 4);  
     # Read from the file.  
     my $line = <$handle>;  
     # Only proceed if we found something.  
     if (defined $line) {  
         # Remove the new-line. We are a bit over-cautious here because the file may be coming in via an  
         # upload control and have a nonstandard EOL combination.  
         $line =~ s/(\r|\n)+$//;  
         # Here we do some fancy tracing to help in debugging complicated EOL marks.  
         if (T(File => 4)) {  
             my $escapedLine = $line;  
             $escapedLine =~ s/\n/\\n/g;  
             $escapedLine =~ s/\r/\\r/g;  
             $escapedLine =~ s/\t/\\t/g;  
             Trace("Line read: -->$escapedLine<--");  
         }  
         # If the line is empty, return a single empty string; otherwise, parse  
         # it into fields.  
         if ($line eq "") {  
             push @retVal, "";  
         } else {  
             push @retVal, split /\t/,$line;  
         }  
     } else {  
         # Trace the reason the read failed.  
         Trace("End of file: $!") if T(File => 3);  
     }  
     # Return the result.  
     return @retVal;  
 }  
   
 =head3 PutLine  
   
     Tracer::PutLine($handle, \@fields, $eol);  
   
 Write a line of data to a tab-delimited file. The specified field values will be  
 output in tab-separated form, with a trailing new-line.  
   
 =over 4  
   
 =item handle  
   
 Output file handle.  
   
 =item fields  
   
 List of field values.  
   
 =item eol (optional)  
   
 End-of-line character (default is "\n").  
   
 =back  
   
 =cut  
   
 sub PutLine {  
     # Get the parameters.  
     my ($handle, $fields, $eol) = @_;  
     # Write the data.  
     print $handle join("\t", @{$fields}) . ($eol || "\n");  
 }  
   
3087  =head3 GenerateURL  =head3 GenerateURL
3088    
3089      my $queryUrl = Tracer::GenerateURL($page, %parameters);      my $queryUrl = Tracer::GenerateURL($page, %parameters);
# Line 3201  Line 3218 
3218      return $retVal;      return $retVal;
3219  }  }
3220    
3221    =head3 Cmp
3222    
3223        my $cmp = Tracer::Cmp($a, $b);
3224    
3225    This method performs a universal sort comparison. Each value coming in is
3226    separated into a leading text part and a trailing number part. The text
3227    part is string compared, and if both parts are equal, then the number
3228    parts are compared numerically. A stream of just numbers or a stream of
3229    just strings will sort correctly, and a mixed stream will sort with the
3230    numbers first. Strings with a label and a number will sort in the
3231    expected manner instead of lexically.
3232    
3233    =over 4
3234    
3235    =item a
3236    
3237    First item to compare.
3238    
3239    =item b
3240    
3241    Second item to compare.
3242    
3243    =item RETURN
3244    
3245    Returns a negative number if the first item should sort first (is less), a positive
3246    number if the first item should sort second (is greater), and a zero if the items are
3247    equal.
3248    
3249    =back
3250    
3251    =cut
3252    
3253    sub Cmp {
3254        # Get the parameters.
3255        my ($a, $b) = @_;
3256        # Declare the return value.
3257        my $retVal;
3258        # Check for nulls.
3259        if (! defined($a)) {
3260            $retVal = (! defined($b) ? 0 : -1);
3261        } elsif (! defined($b)) {
3262            $retVal = 1;
3263        } else {
3264            # Here we have two real values. Parse the two strings.
3265            $a =~ /^(\D*)(\d*)$/;
3266            my $aParsed = [$1, $2];
3267            $b =~ /^(\D*)(\d*)$/;
3268            my $bParsed = [$1, $2];
3269            # Compare the string parts.
3270            $retVal = $aParsed->[0] cmp $bParsed->[0];
3271            if (! $retVal) {
3272                $retVal = $aParsed->[1] <=> $bParsed->[1];
3273            }
3274        }
3275        # Return the result.
3276        return $retVal;
3277    }
3278    
3279    
3280  1;  1;

Legend:
Removed from v.1.92  
changed lines
  Added in v.1.93

MCS Webmaster
ViewVC Help
Powered by ViewVC 1.0.3