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

Legend:
Removed from v.1.87  
changed lines
  Added in v.1.95

MCS Webmaster
ViewVC Help
Powered by ViewVC 1.0.3