[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.98, Thu May 1 07:52:10 2008 UTC revision 1.118, Thu May 21 18:56:28 2009 UTC
# Line 18  Line 18 
18    
19  package Tracer;  package Tracer;
20    
     require Exporter;  
     @ISA = ('Exporter');  
     @EXPORT = qw(Trace T TSetup QTrace Confess Cluck Min Max Assert Open OpenDir TICK StandardSetup EmergencyKey ETracing Constrain Insure ChDir Emergency);  
     @EXPORT_OK = qw(GetFile GetOptions Merge MergeOptions ParseCommand ParseRecord UnEscape Escape PrintLine PutLine);  
21      use strict;      use strict;
22        use base qw(Exporter);
23        use vars qw(@EXPORT @EXPORT_OK);
24        @EXPORT = qw(Trace T TSetup QTrace Confess MemTrace Cluck Min Max Assert Open OpenDir TICK StandardSetup EmergencyKey ETracing Constrain Insure ChDir Emergency Warn TraceDump IDHASH);
25        @EXPORT_OK = qw(GetFile GetOptions Merge MergeOptions ParseCommand ParseRecord UnEscape Escape PrintLine PutLine);
26      use Carp qw(longmess croak carp);      use Carp qw(longmess croak carp);
27      use CGI;      use CGI;
28      use Cwd;      use Cwd;
# Line 36  Line 36 
36      use Time::HiRes 'gettimeofday';      use Time::HiRes 'gettimeofday';
37      use URI::Escape;      use URI::Escape;
38      use Time::Local;      use Time::Local;
39        use POSIX qw(strftime);
40        use Time::Zone;
41        use Fcntl qw(:DEFAULT :flock);
42        use Data::Dumper;
43    
44    
45  =head1 Tracing and Debugging Helpers  =head1 Tracing and Debugging Helpers
46    
# Line 204  Line 209 
209  my $LastLevel = 0;          # level of the last test call  my $LastLevel = 0;          # level of the last test call
210  my $SetupCount = 0;         # number of times TSetup called  my $SetupCount = 0;         # number of times TSetup called
211  my $AllTrace = 0;           # TRUE if we are tracing all categories.  my $AllTrace = 0;           # TRUE if we are tracing all categories.
212    my $SavedCGI;               # CGI object passed to ETracing
213    my $CommandLine;            # Command line passed to StandardSetup
214    umask 2;                    # Fix the damn umask so everything is group-writable.
215    
216  =head2 Tracing Methods  =head2 Tracing Methods
217    
# Line 480  Line 488 
488          # Push the message into the queue.          # Push the message into the queue.
489          push @Queue, "$formatted";          push @Queue, "$formatted";
490      } elsif ($Destination eq "HTML") {      } elsif ($Destination eq "HTML") {
491          # Convert the message to HTML and write it to the standard output.          # Convert the message to HTML.
492          my $escapedMessage = CGI::escapeHTML($stripped);          my $escapedMessage = CGI::escapeHTML($stripped);
493          print "<p>$timeStamp $LastCategory $LastLevel: $escapedMessage</p>\n";          # The stuff after the first line feed should be pre-formatted.
494            my @lines = split /\s*\n/, $escapedMessage;
495            # Get the normal portion.
496            my $line1 = shift @lines;
497            print "<p>$timeStamp $LastCategory $LastLevel: $line1</p>\n";
498            if (@lines) {
499                print "<pre>" . join("\n", @lines, "<pre>");
500            }
501      } elsif ($Destination =~ m/^>>/) {      } elsif ($Destination =~ m/^>>/) {
502          # Write the trace message to an output file.          # Write the trace message to an output file.
503          open(TRACING, $Destination) || die "Tracing open for \"$Destination\" failed: $!";          open(TRACING, $Destination) || die "Tracing open for \"$Destination\" failed: $!";
504            # Lock the file.
505            flock TRACING, LOCK_EX;
506          print TRACING "$formatted\n";          print TRACING "$formatted\n";
507          close TRACING;          close TRACING;
508          # If the Tee flag is on, echo it to the standard output.          # If the Tee flag is on, echo it to the standard output.
# Line 495  Line 512 
512      }      }
513  }  }
514    
515    =head3 MemTrace
516    
517        MemTrace($message);
518    
519    Output a trace message that includes memory size information.
520    
521    =over 4
522    
523    =item message
524    
525    Message to display. The message will be followed by a sentence about the memory size.
526    
527    =back
528    
529    =cut
530    
531    sub MemTrace {
532        # Get the parameters.
533        my ($message) = @_;
534        my $memory = GetMemorySize();
535        Trace("$message $memory in use.");
536    }
537    
538    
539    =head3 TraceDump
540    
541        TraceDump($title, $object);
542    
543    Dump an object to the trace log. This method simply calls the C<Dumper>
544    function, but routes the output to the trace log instead of returning it
545    as a string. The output is arranged so that it comes out monospaced when
546    it appears in an HTML trace dump.
547    
548    =over 4
549    
550    =item title
551    
552    Title to give to the object being dumped.
553    
554    =item object
555    
556    Reference to a list, hash, or object to dump.
557    
558    =back
559    
560    =cut
561    
562    sub TraceDump {
563        # Get the parameters.
564        my ($title, $object) = @_;
565        # Trace the object.
566        Trace("Object dump for $title:\n" . Dumper($object));
567    }
568    
569  =head3 T  =head3 T
570    
571      my $switch = T($category, $traceLevel);      my $switch = T($category, $traceLevel);
# Line 553  Line 624 
624          $LastLevel = $traceLevel;          $LastLevel = $traceLevel;
625          # Convert it to lower case before we hash it.          # Convert it to lower case before we hash it.
626          $category = lc $category;          $category = lc $category;
627          # Use the category and tracelevel to compute the result.          # Validate the trace level.
628          if (ref $traceLevel) {          if (ref $traceLevel) {
629              Confess("Bad trace level.");              Confess("Bad trace level.");
630          } elsif (ref $TraceLevel) {          } elsif (ref $TraceLevel) {
631              Confess("Bad trace config.");              Confess("Bad trace config.");
632          }          }
633          $retVal = ($traceLevel <= $TraceLevel && ($AllTrace || exists $Categories{$category}));          # Make the check. Note that level 0 shows even if the category is turned off.
634            $retVal = ($traceLevel <= $TraceLevel && ($traceLevel == 0 || $AllTrace || exists $Categories{$category}));
635      }      }
636      # Return the computed result.      # Return the computed result.
637      return $retVal;      return $retVal;
# Line 636  Line 708 
708      # Set up the category and level.      # Set up the category and level.
709      $LastCategory = "(confess)";      $LastCategory = "(confess)";
710      $LastLevel = 0;      $LastLevel = 0;
     if (! defined($FIG_Config::no_tool_hdr)) {  
         # Here we have a tool header. Display its length so that the user can adjust the line numbers.  
         my $toolHeaderFile = "$FIG_Config::fig_disk/dist/releases/current/$FIG_Config::arch/tool_hdr";  
         # Only proceed if the tool header file is actually present.  
         if (-f $toolHeaderFile) {  
             my $fh;  
             if (open $fh, "<$toolHeaderFile") {  
                 my @lines = <$fh>;  
                 Trace("Tool header has " . scalar(@lines) . " lines.");  
             }  
         }  
     }  
711      # Trace the call stack.      # Trace the call stack.
712      Cluck($message);      Cluck($message);
713      # Abort the program.      # Abort the program.
714      croak(">>> $message");      croak(">>> $message");
715  }  }
716    
717    =head3 SaveCGI
718    
719        Tracer::SaveCGI($cgi);
720    
721    This method saves the CGI object but does not activate emergency tracing.
722    It is used to allow L</Warn> to work in situations where emergency
723    tracing is contra-indicated (e.g. the wiki).
724    
725    =over 4
726    
727    =item cgi
728    
729    Active CGI query object.
730    
731    =back
732    
733    =cut
734    
735    sub SaveCGI {
736        $SavedCGI = $_[0];
737    }
738    
739    =head3 Warn
740    
741        Warn($message, @options);
742    
743    This method traces an important message. If an RSS feed is configured
744    (via I<FIG_Config::error_feed>) and the tracing destination is C<WARN>,
745    then the message will be echoed to the feed. In general, a tracing
746    destination of C<WARN> indicates that the caller is running as a web
747    service in a production environment; however, this is not a requirement.
748    
749    To force warnings into the RSS feed even when the tracing destination
750    is not C<WARN>, simply specify the C<Feed> tracing module. This can be
751    configured automatically when L</StandardSetup> is used.
752    
753    The L</Cluck> method calls this one for its final message. Since
754    L</Confess> calls L</Cluck>, this means that any error which is caught
755    and confessed will put something in the feed. This insures that someone
756    will be alerted relatively quickly when a failure occurs.
757    
758    =over 4
759    
760    =item message
761    
762    Message to be traced.
763    
764    =item options
765    
766    A list containing zero or more options.
767    
768    =back
769    
770    The permissible options are as follows.
771    
772    =over 4
773    
774    =item noStack
775    
776    If specified, then the stack trace is not included in the output.
777    
778    =back
779    
780    =cut
781    
782    sub Warn {
783        # Get the parameters.
784        my $message = shift @_;
785        my %options = map { $_ => 1 } @_;
786        # Save $@;
787        my $savedError = $@;
788        # Trace the message.
789        Trace($message);
790        # This will contain the lock handle. If it's defined, it means we need to unlock.
791        my $lock;
792        # Check for feed forcing.
793        my $forceFeed = exists $Categories{feed};
794        # An error here would be disastrous. Note that if debug mode is specified,
795        # we do this stuff even in a test environment.
796        eval {
797            # Do we need to put this in the RSS feed?
798            if ($FIG_Config::error_feed && ($Destination eq 'WARN' || $forceFeed)) {
799                # Probably. We need to check first, however, to see if it's from an
800                # ignored IP. For non-CGI situations, we default the IP to the self-referent.
801                my $key = "127.0.0.1";
802                if (defined $SavedCGI) {
803                    # Get the IP address.
804                    $key = $ENV{HTTP_X_FORWARDED_FOR} || $ENV{REMOTE_ADDR};
805                }
806                # Is the IP address in the ignore list?
807                my $found = scalar(grep { $_ eq $key } @FIG_Config::error_ignore_ips);
808                if (! $found) {
809                    # No. We're good. We now need to compute the date, the link, and the title.
810                    # First, the date, in a very specific format.
811                    my $date = strftime("%a, %02e %b %H:%M:%S %Y ", localtime) .
812                        (tz_local_offset() / 30);
813                    # Environment data goes in here. We start with the date.
814                    my $environment = "$date.  ";
815                    # If we need to recap the message (because it's too long to be a title), we'll
816                    # put it in here.
817                    my $recap;
818                    # Copy the message and remove excess space.
819                    my $title = $message;
820                    $title =~ s/\s+/ /gs;
821                    # If it's too long, we have to split it up.
822                    if (length $title > 60) {
823                        # Put the full message in the environment string.
824                        $recap = $title;
825                        # Excerpt it as the title.
826                        $title = substr($title, 0, 50) . "...";
827                    }
828                    # If we have a CGI object, then this is a web error. Otherwise, it's
829                    # command-line.
830                    if (defined $SavedCGI) {
831                        # We're in a web service. The environment is the user's IP, and the link
832                        # is the URL that got us here.
833                        $environment .= "Event Reported at IP address $key process $$.";
834                        my $url = $SavedCGI->self_url();
835                        # We need the user agent string and (if available) the referrer.
836                        # The referrer will be the link.
837                        $environment .= " User Agent $ENV{HTTP_USER_AGENT}";
838                        if ($ENV{HTTP_REFERER}) {
839                            my $link = $ENV{HTTP_REFERER};
840                            $environment .= " referred from <a href=\"$link\">$link</a>.";
841                        } else {
842                            $environment .= " referrer unknown.";
843                        }
844                        # Close off the sentence with the original link.
845                        $environment .= " URL of event is <a href=\"$url\">$url</a>.";
846                    } else {
847                        # No CGI object, so we're a command-line tool. Use the tracing
848                        # key and the PID as the user identifier, and add the command.
849                        my $key = EmergencyKey();
850                        $environment .= "Event Reported by $key process $$.";
851                        if ($CommandLine) {
852                            # We're in a StandardSetup script, so we have the real command line.
853                            $environment .= "\n<pre>" . CGI::escapeHTML($CommandLine) . "</pre>\n";
854                        } elsif ($ENV{_}) {
855                            # We're in a BASH script, so the command has been stored in the _ variable.
856                            $environment .= "  Command = " . CGI::escapeHTML($ENV{_}) . "\n";
857                        }
858                    }
859                    # Build a GUID. We use the current time, the title, and the process ID,
860                    # then digest the result.
861                    my $guid = Digest::MD5::md5_base64(gettimeofday(), $title, $$);
862                    # Finally, the description. This is a stack trace plus various environmental stuff.
863                    # The trace is optional.
864                    my $stackTrace;
865                    if ($options{noStack}) {
866                        $stackTrace = "";
867                    } else {
868                        my @trace = LongMess();
869                        # Only proceed if we got something back.
870                        if (scalar(@trace) > 0) {
871                            $trace[0] =~ s/Tracer::Warn.+?called/Event occurred/;
872                            $stackTrace = "Stack trace:<pre>" . join("\n", @trace, "</pre>");
873                        }
874                    }
875                    # We got the stack trace. Now it's time to put it all together.
876                    # We have a goofy thing here in that we need to HTML-escape some sections of the description
877                    # twice. They will be escaped once here, and then once when written by XML::Simple. They are
878                    # unescaped once when processed by the RSS reader, and stuff in the description is treated as
879                    # HTML. So, anything escaped here is treated as a literal when viewed in the RSS reader, but
880                    # our <br>s and <pre>s are used to format the description.
881                    $recap = (defined $recap ? "<em>" . CGI::escapeHTML($recap) . "</em><br /><br />" : "");
882                    my $description = "$recap$environment  $stackTrace";
883                    # Okay, we have all the pieces. Create a hash of the new event.
884                    my $newItem = { title => $title,
885                                    description => $description,
886                                    category => $LastCategory,
887                                    pubDate => $date,
888                                    guid => $guid,
889                                  };
890                    # We need XML capability for this.
891                    require XML::Simple;
892                    # The RSS document goes in here.
893                    my $rss;
894                    # Get the name of the RSS file. It's in the FIG temporary directory.
895                    my $fileName = "$FIG_Config::temp/$FIG_Config::error_feed";
896                    # Open the config file and lock it.
897                    $lock = Open(undef, "<$FIG_Config::fig_disk/config/FIG_Config.pm");
898                    flock $lock, LOCK_EX;
899                    # Does it exist?
900                    if (-s $fileName) {
901                        # Slurp it in.
902                        $rss = XML::Simple::XMLin($fileName, ForceArray => ['item']);
903                    } else {
904                        my $size = -s $fileName;
905                        # Create an empty channel.
906                        $rss = {
907                            channel => {
908                                title => 'NMPDR Warning Feed',
909                                link => "$FIG_Config::temp_url/$FIG_Config::error_feed",
910                                description => "Important messages regarding the status of the NMPDR.",
911                                generator => "NMPDR Trace Facility",
912                                docs => "http://blogs.law.harvard.edu/tech/rss",
913                                item => []
914                            },
915                        };
916                    }
917                    # Get the channel object.
918                    my $channel = $rss->{channel};
919                    # Update the last-build date.
920                    $channel->{lastBuildDate} = $date;
921                    # Get the item array.
922                    my $items = $channel->{item};
923                    # Insure it has only 100 entries.
924                    while (scalar @{$items} > 100) {
925                        pop @{$items};
926                    }
927                    # Add our new item at the front.
928                    unshift @{$items}, $newItem;
929                    # Create the XML. Note we do not include the root or the declaration. XML Simple can't handle
930                    # the requirements for those.
931                    my $xml = XML::Simple::XMLout($channel, NoAttr => 1, RootName => 'channel', XmlDecl => '');
932                    # Here we put in the root and declaration. The problem is that the root has to have the version attribute
933                    # in it. So, we suppress the root and do it by hand, and that requires suppressing the declaration, too.
934                    $xml = "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<rss version=\"2.0\">$xml\n</rss>";
935                    # We don't use Open here because we can't afford an error.
936                    if (open XMLOUT, ">$fileName") {
937                        print XMLOUT $xml;
938                        close XMLOUT;
939                    }
940                }
941            }
942        };
943        if ($@) {
944            # If the feed failed, we need to know why. The error will be traced, but this method will not be involved
945            # (which is a good thing).
946            my $error = $@;
947            Trace("Feed Error: $error") if T(Feed => 0);
948        }
949        # Be sure to unlock.
950        if ($lock) {
951            flock $lock, LOCK_UN;
952            undef $lock;
953        }
954        # Restore the error message.
955        $@ = $savedError;
956    }
957    
958    
959    
960    
961  =head3 Assert  =head3 Assert
962    
963      Assert($condition1, $condition2, ... $conditionN);      Assert($condition1, $condition2, ... $conditionN);
# Line 704  Line 1008 
1008      my ($message) = @_;      my ($message) = @_;
1009      # Trace what's happening.      # Trace what's happening.
1010      Trace("Stack trace for event: $message");      Trace("Stack trace for event: $message");
1011      my $confession = longmess($message);      # Get the stack trace.
1012      # Convert the confession to a series of trace messages.      my @trace = LongMess();
1013      for my $line (split /\s*\n/, $confession) {      # Convert the trace to a series of messages.
1014          # Only proceed if this call trace is for a method outside Tracer itself.      for my $line (@trace) {
1015          if ($line !~ /Tracer\.pm/) {          # Replace the tab at the beginning with spaces.
1016              # Replace the leading tab with a series of spaces.          $line =~ s/^\t/    /;
             $line =~ s/\t/    /;  
1017              # Trace the line.              # Trace the line.
1018              Trace($line);              Trace($line);
1019          }          }
1020        # Issue a warning. This displays the event message and inserts it into the RSS error feed.
1021        Warn($message);
1022      }      }
 }  
   
 =head3 ScriptSetup (deprecated)  
   
     my ($cgi, $varHash) = ScriptSetup($noTrace);  
   
 Perform standard tracing and debugging setup for scripts. The value returned is  
 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.  
   
 This method calls L</ETracing> to configure tracing, which allows the tracing  
 to be configured via the emergency tracing form on the debugging control panel.  
 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>.  
   
 =over 4  
   
 =item noTrace (optional)  
   
 If specified, tracing will be suppressed. This is useful if the script wants to set up  
 tracing manually.  
1023    
1024  =item RETURN  =head3 LongMess
1025    
1026  Returns a two-element list consisting of a CGI query object and a variable hash for      my @lines = Tracer::LongMess();
 the output page.  
1027    
1028  =back  Return a stack trace with all tracing methods removed. The return will be in the form of a list
1029    of message strings.
1030    
1031  =cut  =cut
1032    
1033  sub ScriptSetup {  sub LongMess {
1034      # Get the parameters.      # Declare the return variable.
1035      my ($noTrace) = @_;      my @retVal = ();
1036      # Get the CGI query object.      my $confession = longmess("");
1037      my $cgi = CGI->new();      for my $line (split /\s*\n/, $confession) {
1038      # Set up tracing if it's not suppressed.          unless ($line =~ /Tracer\.pm/) {
1039      ETracing($cgi) unless $noTrace;              # Here we have a line worth keeping. Push it onto the result list.
1040      # Create the variable hash.              push @retVal, $line;
1041      my $varHash = { results => '' };          }
1042      # Return the query object and variable hash.      }
1043      return ($cgi, $varHash);      # Return the result.
1044        return @retVal;
1045  }  }
1046    
1047  =head3 ETracing  =head3 ETracing
# Line 790  Line 1075 
1075      # Get the parameter.      # Get the parameter.
1076      my ($parameter) = @_;      my ($parameter) = @_;
1077      # Check for CGI mode.      # Check for CGI mode.
1078      my $cgi = (ref $parameter eq 'CGI' ? $parameter : undef);      if (defined $parameter && ref $parameter eq 'CGI') {
1079            $SavedCGI = $parameter;
1080        } else {
1081            $SavedCGI = undef;
1082        }
1083      # Default to no tracing except errors.      # Default to no tracing except errors.
1084      my ($tracing, $dest) = ("0", "WARN");      my ($tracing, $dest) = ("0", "WARN");
1085      # Check for emergency tracing.      # Check for emergency tracing.
# Line 823  Line 1112 
1112              # Set the trace parameter.              # Set the trace parameter.
1113              $tracing = join(" ", $level, sort keys %moduleHash);              $tracing = join(" ", $level, sort keys %moduleHash);
1114          }          }
1115      } elsif (defined $cgi) {      } elsif (defined $SavedCGI) {
1116          # There's no emergency tracing, but we have a CGI object, so check          # There's no emergency tracing, but we have a CGI object, so check
1117          # for tracing from the form parameters.          # for tracing from the form parameters.
1118          if ($cgi->param('Trace')) {          if ($SavedCGI->param('Trace')) {
1119              # Here the user has requested tracing via a form.              # Here the user has requested tracing via a form.
1120              $dest = ($cgi->param('TF') ? ">$FIG_Config::temp/Trace$$.log" : "QUEUE");              $dest = ($SavedCGI->param('TF') ? ">$FIG_Config::temp/Trace$$.log" : "QUEUE");
1121              $tracing = $cgi->param('Trace') . " Tracer";              $tracing = $SavedCGI->param('Trace') . " Tracer";
1122          }          }
1123      }      }
1124      # Setup the tracing we've determined from all the stuff above.      # Setup the tracing we've determined from all the stuff above.
1125      TSetup($tracing, $dest);      TSetup($tracing, $dest);
1126      # Check to see if we're a web script.      # Check to see if we're a web script.
1127      if (defined $cgi) {      if (defined $SavedCGI) {
1128          # Yes we are. Trace the form and environment data.          # Yes we are. Trace the form and environment data.
1129          TraceParms($cgi);          TraceParms($SavedCGI);
1130          # Check for RAW mode. In raw mode, we print a fake header so that we see everything          # Check for RAW mode. In raw mode, we print a fake header so that we see everything
1131          # emitted by the script in its raw form.          # emitted by the script in its raw form.
1132          if (T(Raw => 3)) {          if (T(Raw => 3)) {
# Line 1028  Line 1317 
1317      # Declare the return variable.      # Declare the return variable.
1318      my $retVal;      my $retVal;
1319      # Determine the parameter type.      # Determine the parameter type.
1320      if (! defined $parameter) {      if (! defined $parameter || defined($ENV{TRACING})) {
1321          # Here we're supposed to check the environment.          # Here we're supposed to check the environment. If that fails, we
1322          $retVal = $ENV{TRACING};          # get the effective login ID.
1323            $retVal = $ENV{TRACING} || scalar getpwuid($<);
1324      } else {      } else {
1325          my $ptype = ref $parameter;          my $ptype = ref $parameter;
1326          if ($ptype eq 'CGI') {          if ($ptype eq 'CGI') {
# Line 1071  Line 1361 
1361      # Get the parameters.      # Get the parameters.
1362      my ($cgi) = @_;      my ($cgi) = @_;
1363      if (T(CGI => 2)) {      if (T(CGI => 2)) {
1364          # Here we trace the GET-style URL for the script.          # Here we trace the GET-style URL for the script, but only if it's
1365          Trace("[URL] " . $cgi->url(-relative => 1, -query => 1));          # relatively small.
1366            my $url = $cgi->url(-relative => 1, -query => 1);
1367            my $len = length($url);
1368            if ($len < 500) {
1369                Trace("[URL] $url");
1370            } elsif ($len > 2048) {
1371                Trace("[URL] URL is too long to use with GET ($len characters).");
1372            } else {
1373                Trace("[URL] URL length is $len characters.");
1374            }
1375      }      }
1376      if (T(CGI => 3)) {      if (T(CGI => 3)) {
1377          # Here we want to trace the parameter data.          # Here we want to trace the parameter data.
# Line 1147  Line 1446 
1446      }      }
1447  }  }
1448    
   
 =head3 ScriptFinish (deprecated)  
   
     ScriptFinish($webData, $varHash);  
   
 Output a web page at the end of a script. Either the string to be output or the  
 name of a template file can be specified. If the second parameter is omitted,  
 it is assumed we have a string to be output; otherwise, it is assumed we have the  
 name of a template file. The template should have the variable C<DebugData>  
 specified in any form that invokes a standard script. If debugging mode is turned  
 on, a form field will be put in that allows the user to enter tracing data.  
 Trace messages will be placed immediately before the terminal C<BODY> tag in  
 the output, formatted as a list.  
   
 A typical standard script would loook like the following.  
   
     BEGIN {  
         # Print the HTML header.  
         print "CONTENT-TYPE: text/html\n\n";  
     }  
     use Tracer;  
     use CGI;  
     use FIG;  
     # ... more uses ...  
   
     my ($cgi, $varHash) = ScriptSetup();  
     eval {  
         # ... get data from $cgi, put it in $varHash ...  
     };  
     if ($@) {  
         Trace("Script Error: $@") if T(0);  
     }  
     ScriptFinish("Html/MyTemplate.html", $varHash);  
   
 The idea here is that even if the script fails, you'll see trace messages and  
 useful output.  
   
 =over 4  
   
 =item webData  
   
 A string containing either the full web page to be written to the output or the  
 name of a template file from which the page is to be constructed. If the name  
 of a template file is specified, then the second parameter must be present;  
 otherwise, it must be absent.  
   
 =item varHash (optional)  
   
 If specified, then a reference to a hash mapping variable names for a template  
 to their values. The template file will be read into memory, and variable markers  
 will be replaced by data in this hash reference.  
   
 =back  
   
 =cut  
   
 sub ScriptFinish {  
     # Get the parameters.  
     my ($webData, $varHash) = @_;  
     # Check for a template file situation.  
     my $outputString;  
     if (defined $varHash) {  
         # Here we have a template file. We need to determine the template type.  
         my $template;  
         if ($FIG_Config::template_url && $webData =~ /\.php$/) {  
             $template = "$FIG_Config::template_url/$webData";  
         } else {  
             $template = "<<$webData";  
         }  
         $outputString = PageBuilder::Build($template, $varHash, "Html");  
     } else {  
         # Here the user gave us a raw string.  
         $outputString = $webData;  
     }  
     # Check for trace messages.  
     if ($Destination ne "NONE" && $TraceLevel > 0) {  
         # 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;  
         }  
         # If the trace messages were queued, we unroll them. Otherwise, we display the  
         # destination.  
         my $traceHtml;  
         if ($Destination eq "QUEUE") {  
             $traceHtml = QTrace('Html');  
         } elsif ($Destination =~ /^>>(.+)$/) {  
             # Here the tracing output it to a file. We code it as a hyperlink so the user  
             # can copy the file name into the clipboard easily.  
             my $actualDest = $1;  
             $traceHtml = "<p>Tracing output to $actualDest.</p>\n";  
         } else {  
             # Here we have one of the special destinations.  
             $traceHtml = "<P>Tracing output type is $Destination.</p>\n";  
         }  
         substr $outputString, $pos, 0, $traceHtml;  
     }  
     # Write the output string.  
     print $outputString;  
 }  
   
1449  =head2 Command-Line Utility Methods  =head2 Command-Line Utility Methods
1450    
1451  =head3 SendSMS  =head3 SendSMS
# Line 1454  Line 1650 
1650  Specifying a value of C<E> for the trace level causes emergency tracing to  Specifying a value of C<E> for the trace level causes emergency tracing to
1651  be used instead of custom tracing. If the user name is not specified,  be used instead of custom tracing. If the user name is not specified,
1652  the tracing key is taken from the C<Tracing> environment variable. If there  the tracing key is taken from the C<Tracing> environment variable. If there
1653  is no value for that variable, the tracing key will be computed from the PID.  is no value for that variable, the tracing key will be computed from the active
1654    login ID.
1655    
1656    Since the default situation in StandardSetup is to trace to the standard
1657    output, errors that occur in command-line scripts will not generate
1658    RSS events. To force the events, use the C<warn> option.
1659    
1660        TransactFeatures -background -warn register ../xacts IDs.tbl
1661    
1662  Finally, if the special option C<-help> is specified, the option  Finally, if the special option C<-help> is specified, the option
1663  names will be traced at level 0 and the program will exit without processing.  names will be traced at level 0 and the program will exit without processing.
# Line 1471  Line 1674 
1674          -noAlias  do not expect aliases in CHANGE transactions          -noAlias  do not expect aliases in CHANGE transactions
1675          -start    start with this genome          -start    start with this genome
1676          -tblFiles output TBL files containing the corrected IDs          -tblFiles output TBL files containing the corrected IDs
1677            -forked   do not erase the trace file before tracing
1678    
1679  The caller has the option of modifying the tracing scheme by placing a value  The caller has the option of modifying the tracing scheme by placing a value
1680  for C<trace> in the incoming options hash. The default value can be overridden,  for C<trace> in the incoming options hash. The default value can be overridden,
# Line 1534  Line 1738 
1738      my ($categories, $options, $parmHelp, @argv) = @_;      my ($categories, $options, $parmHelp, @argv) = @_;
1739      # Get the default tracing key.      # Get the default tracing key.
1740      my $tkey = EmergencyKey();      my $tkey = EmergencyKey();
1741        # Save the command line.
1742        $CommandLine = join(" ", $0, map { $_ =~ /\s/ ? "\"$_\"" : $_ } @argv);
1743      # Add the tracing options.      # Add the tracing options.
1744      if (! exists $options->{trace}) {      if (! exists $options->{trace}) {
1745          $options->{trace} = ['2', "tracing level (E for emergency tracing)"];          $options->{trace} = ['2', "tracing level (E for emergency tracing)"];
1746      }      }
1747        if (! exists $options->{forked}) {
1748            $options->{forked} = [0, "keep old trace file"];
1749        }
1750      $options->{sql} = [0, "turn on SQL tracing"];      $options->{sql} = [0, "turn on SQL tracing"];
1751      $options->{help} = [0, "display command-line options"];      $options->{help} = [0, "display command-line options"];
1752      $options->{user} = [$tkey, "tracing key"];      $options->{user} = [$tkey, "tracing key"];
1753      $options->{background} = [0, "spool standard and error output"];      $options->{background} = [0, "spool standard and error output"];
1754        $options->{warn} = [0, "send errors to RSS feed"];
1755        $options->{moreTracing} = ["", "comma-delimited list of additional trace modules for debugging"];
1756      # Create a parsing hash from the options hash. The parsing hash      # Create a parsing hash from the options hash. The parsing hash
1757      # contains the default values rather than the default value      # contains the default values rather than the default value
1758      # and the description. While we're at it, we'll memorize the      # and the description. While we're at it, we'll memorize the
# Line 1558  Line 1769 
1769      my ($retOptions, @retParameters) = ParseCommand(\%parseOptions, @argv);      my ($retOptions, @retParameters) = ParseCommand(\%parseOptions, @argv);
1770      # Get the logfile suffix.      # Get the logfile suffix.
1771      my $suffix = $retOptions->{user};      my $suffix = $retOptions->{user};
1772      # Check for background mode.      # We'll put the trace file name in here. We need it later if background
1773      if ($retOptions->{background}) {      # mode is on.
1774          my $outFileName = "$FIG_Config::temp/out$suffix.log";      my $traceFileName;
         my $errFileName = "$FIG_Config::temp/err$suffix.log";  
         open STDOUT, ">$outFileName";  
         open STDERR, ">$errFileName";  
         # Check for phone support. If we have phone support and a phone number,  
         # we want to turn it on.  
         if ($ENV{PHONE} && defined($FIG_Config::phone)) {  
             $retOptions->{phone} = $ENV{PHONE};  
         }  
     }  
1775      # Now we want to set up tracing. First, we need to know if the user      # Now we want to set up tracing. First, we need to know if the user
1776      # wants emergency tracing.      # wants emergency tracing.
1777      if ($retOptions->{trace} eq 'E') {      if ($retOptions->{trace} eq 'E') {
# Line 1580  Line 1782 
1782          if ($retOptions->{sql}) {          if ($retOptions->{sql}) {
1783              push @cats, "SQL";              push @cats, "SQL";
1784          }          }
1785            if ($retOptions->{warn}) {
1786                push @cats, "Feed";
1787            }
1788          # Add the default categories.          # Add the default categories.
1789          push @cats, "Tracer";          push @cats, "Tracer";
1790            # Check for more tracing groups.
1791            if ($retOptions->{moreTracing}) {
1792                push @cats, split /,/, $retOptions->{moreTracing};
1793            }
1794          # Next, we create the category string by joining the categories.          # Next, we create the category string by joining the categories.
1795          my $cats = join(" ", @cats);          my $cats = join(" ", @cats);
1796          # Check to determine whether or not the caller wants to turn off tracing          # Check to determine whether or not the caller wants to turn off tracing
# Line 1596  Line 1805 
1805          my $traceMode;          my $traceMode;
1806          # Verify that we can open a file in the FIG temporary directory.          # Verify that we can open a file in the FIG temporary directory.
1807          my $traceFileName = "$FIG_Config::temp/trace$suffix.log";          my $traceFileName = "$FIG_Config::temp/trace$suffix.log";
1808          if (open TESTTRACE, ">$traceFileName") {          my $traceFileSpec = ($retOptions->{forked} ? ">>$traceFileName" : ">$traceFileName");
1809            if (open TESTTRACE, "$traceFileSpec") {
1810              # Here we can trace to a file.              # Here we can trace to a file.
1811              $traceMode = ">$traceFileName";              $traceMode = ">>$traceFileName";
1812              if ($textOKFlag) {              if ($textOKFlag) {
1813                  # Echo to standard output if the text-OK flag is set.                  # Echo to standard output if the text-OK flag is set.
1814                  $traceMode = "+$traceMode";                  $traceMode = "+$traceMode";
# Line 1619  Line 1829 
1829          # Now set up the tracing.          # Now set up the tracing.
1830          TSetup("$traceLevel $cats", $traceMode);          TSetup("$traceLevel $cats", $traceMode);
1831      }      }
1832        # Check for background mode.
1833        if ($retOptions->{background}) {
1834            my $outFileName = "$FIG_Config::temp/out$suffix$$.log";
1835            my $errFileName = "$FIG_Config::temp/err$suffix$$.log";
1836            # Spool the output.
1837            open STDOUT, ">$outFileName";
1838            # If we have a trace file, trace the errors to the log. Otherwise,
1839            # spool the errors.
1840            if (defined $traceFileName) {
1841                open STDERR, "| Tracer $traceFileName";
1842            } else {
1843                open STDERR, ">$errFileName";
1844            }
1845            # Check for phone support. If we have phone support and a phone number,
1846            # we want to turn it on.
1847            if ($ENV{PHONE} && defined($FIG_Config::phone)) {
1848                $retOptions->{phone} = $ENV{PHONE};
1849            }
1850        }
1851      # Check for the "help" option. If it is specified, dump the command-line      # Check for the "help" option. If it is specified, dump the command-line
1852      # options and exit the program.      # options and exit the program.
1853      if ($retOptions->{help}) {      if ($retOptions->{help}) {
# Line 1799  Line 2028 
2028      }      }
2029  }  }
2030    
2031    =head3 UnparseOptions
2032    
2033        my $optionString = Tracer::UnparseOptions(\%options);
2034    
2035    Convert an option hash into a command-line string. This will not
2036    necessarily be the same text that came in, but it will nonetheless
2037    produce the same ultimate result when parsed by L</StandardSetup>.
2038    
2039    =over 4
2040    
2041    =item options
2042    
2043    Reference to a hash of options to convert into an option string.
2044    
2045    =item RETURN
2046    
2047    Returns a string that will parse to the same set of options when
2048    parsed by L</StandardSetup>.
2049    
2050    =back
2051    
2052    =cut
2053    
2054    sub UnparseOptions {
2055        # Get the parameters.
2056        my ($options) = @_;
2057        # The option segments will be put in here.
2058        my @retVal = ();
2059        # Loop through the options.
2060        for my $key (keys %$options) {
2061            # Get the option value.
2062            my $value = $options->{$key};
2063            # Only use it if it's nonempty.
2064            if (defined $value && $value ne "") {
2065                my $segment = "--$key=$value";
2066                # Quote it if necessary.
2067                if ($segment =~ /[ |<>*]/) {
2068                    $segment = '"' . $segment . '"';
2069                }
2070                # Add it to the return list.
2071                push @retVal, $segment;
2072            }
2073        }
2074        # Return the result.
2075        return join(" ", @retVal);
2076    }
2077    
2078  =head3 ParseCommand  =head3 ParseCommand
2079    
2080      my ($options, @arguments) = Tracer::ParseCommand(\%optionTable, @inputList);      my ($options, @arguments) = Tracer::ParseCommand(\%optionTable, @inputList);
# Line 2271  Line 2547 
2547          } else {          } else {
2548              @retVal = readdir $dirHandle;              @retVal = readdir $dirHandle;
2549          }          }
2550            closedir $dirHandle;
2551      } elsif (! $flag) {      } elsif (! $flag) {
2552          # Here the directory would not open and it's considered an error.          # Here the directory would not open and it's considered an error.
2553          Confess("Could not open directory $dirName.");          Confess("Could not open directory $dirName.");
# Line 2377  Line 2654 
2654  Map of search patterns to permission masks. If a directory name matches  Map of search patterns to permission masks. If a directory name matches
2655  one of the patterns, that directory and all its members and subdirectories  one of the patterns, that directory and all its members and subdirectories
2656  will be assigned the new pattern. For example, the following would  will be assigned the new pattern. For example, the following would
2657  assign 01664 to most files, but would use 01777 for directories named C<tmp>.  assign 0664 to most files, but would use 0777 for directories named C<tmp>.
2658    
2659      Tracer::SetPermissions($dirName, 'fig', 01664, '^tmp$' => 01777);      Tracer::SetPermissions($dirName, 'fig', 01664, '^tmp$' => 01777);
2660    
# Line 2430  Line 2707 
2707                      $match = 1;                      $match = 1;
2708                  }                  }
2709              }              }
2710              # Check for a match. Note we use $i-1 because the loop added 2              # Find out if we have a match. Note we use $i-1 because the loop added 2
2711              # before terminating due to the match.              # before terminating due to the match.
2712              if ($match && $otherMasks[$i-1] != $mask) {              if ($match && $otherMasks[$i-1] != $mask) {
2713                  # This directory matches one of the incoming patterns, and it's                  # This directory matches one of the incoming patterns, and it's
# Line 2598  Line 2875 
2875    
2876  =head2 Other Useful Methods  =head2 Other Useful Methods
2877    
2878    =head3 IDHASH
2879    
2880        my $hash = SHTargetSearch::IDHASH(@keys);
2881    
2882    This is a dinky little method that converts a list of values to a reference
2883    to hash of values to labels. The values and labels are the same.
2884    
2885    =cut
2886    
2887    sub IDHASH {
2888        my %retVal = map { $_ => $_ } @_;
2889        return \%retVal;
2890    }
2891    
2892    =head3 Pluralize
2893    
2894        my $plural = Tracer::Pluralize($word);
2895    
2896    This is a very simple pluralization utility. It adds an C<s> at the end
2897    of the input word unless it already ends in an C<s>, in which case it
2898    adds C<es>.
2899    
2900    =over 4
2901    
2902    =item word
2903    
2904    Singular word to pluralize.
2905    
2906    =item RETURN
2907    
2908    Returns the probable plural form of the word.
2909    
2910    =back
2911    
2912    =cut
2913    
2914    sub Pluralize {
2915        # Get the parameters.
2916        my ($word) = @_;
2917        # Declare the return variable.
2918        my $retVal;
2919        if ($word =~ /s$/) {
2920            $retVal = $word . 'es';
2921        } else {
2922            $retVal = $word . 's';
2923        }
2924        # Return the result.
2925        return $retVal;
2926    }
2927    
2928    =head3 Numeric
2929    
2930        my $okFlag = Tracer::Numeric($string);
2931    
2932    Return the value of the specified string if it is numeric, or an undefined value
2933    if it is not numeric.
2934    
2935    =over 4
2936    
2937    =item string
2938    
2939    String to check.
2940    
2941    =item RETURN
2942    
2943    Returns the numeric value of the string if successful, or C<undef> if the string
2944    is not numeric.
2945    
2946    =back
2947    
2948    =cut
2949    
2950    sub Numeric {
2951        # Get the parameters.
2952        my ($string) = @_;
2953        # We'll put the value in here if we succeed.
2954        my $retVal;
2955        # Get a working copy of the string.
2956        my $copy = $string;
2957        # Trim leading and trailing spaces.
2958        $copy =~ s/^\s+//;
2959        $copy =~ s/\s+$//;
2960        # Check the result.
2961        if ($copy =~ /^[+-]?\d+$/) {
2962            $retVal = $copy;
2963        } elsif ($copy =~ /^([+-]\d+|\d*)[eE][+-]?\d+$/) {
2964            $retVal = $copy;
2965        } elsif ($copy =~ /^([+-]\d+|\d*)\.\d*([eE][+-]?\d+)?$/) {
2966            $retVal = $copy;
2967        }
2968        # Return the result.
2969        return $retVal;
2970    }
2971    
2972    
2973  =head3 ParseParm  =head3 ParseParm
2974    
2975      my $listValue = Tracer::ParseParm($string);      my $listValue = Tracer::ParseParm($string);
# Line 2840  Line 3212 
3212      return $retVal;      return $retVal;
3213  }  }
3214    
3215    =head3 In
3216    
3217        my $flag = Tracer::In($value, $min, $max);
3218    
3219    Return TRUE if the value is between the minimum and the maximum, else FALSE.
3220    
3221    =cut
3222    
3223    sub In {
3224        return ($_[0] <= $_[2] && $_[0] >= $_[1]);
3225    }
3226    
3227    
3228  =head3 Constrain  =head3 Constrain
3229    
3230      my $constrained = Constrain($value, $min, $max);      my $constrained = Constrain($value, $min, $max);
# Line 2951  Line 3336 
3336      return $retVal;      return $retVal;
3337  }  }
3338    
   
3339  =head3 Strip  =head3 Strip
3340    
3341      my $string = Tracer::Strip($line);      my $string = Tracer::Strip($line);
# Line 2984  Line 3368 
3368      return $retVal;      return $retVal;
3369  }  }
3370    
3371    =head3 Trim
3372    
3373        my $string = Tracer::Trim($line);
3374    
3375    Trim all spaces from the beginning and ending of a string.
3376    
3377    =over 4
3378    
3379    =item line
3380    
3381    Line of text to be trimmed.
3382    
3383    =item RETURN
3384    
3385    The same line of text with all whitespace chopped off either end.
3386    
3387    =back
3388    
3389    =cut
3390    
3391    sub Trim {
3392        # Get a copy of the parameter string.
3393        my ($string) = @_;
3394        my $retVal = (defined $string ? $string : "");
3395        # Strip the front spaces.
3396        $retVal =~ s/^\s+//;
3397        # Strip the back spaces.
3398        $retVal =~ s/\s+$//;
3399        # Return the result.
3400        return $retVal;
3401    }
3402    
3403  =head3 Pad  =head3 Pad
3404    
3405      my $paddedString = Tracer::Pad($string, $len, $left, $padChar);      my $paddedString = Tracer::Pad($string, $len, $left, $padChar);
# Line 3045  Line 3461 
3461      return $retVal;      return $retVal;
3462  }  }
3463    
3464    =head3 Quoted
3465    
3466        my $string = Tracer::Quoted($var);
3467    
3468    Convert the specified value to a string and enclose it in single quotes.
3469    If it's undefined, the string C<undef> in angle brackets will be used
3470    instead.
3471    
3472    =over 4
3473    
3474    =item var
3475    
3476    Value to quote.
3477    
3478    =item RETURN
3479    
3480    Returns a string enclosed in quotes, or an indication the value is undefined.
3481    
3482    =back
3483    
3484    =cut
3485    
3486    sub Quoted {
3487        # Get the parameters.
3488        my ($var) = @_;
3489        # Declare the return variable.
3490        my $retVal;
3491        # Are we undefined?
3492        if (! defined $var) {
3493            $retVal = "<undef>";
3494        } else {
3495            # No, so convert to a string and enclose in quotes.
3496            $retVal = $var;
3497            $retVal =~ s/'/\\'/;
3498            $retVal = "'$retVal'";
3499        }
3500        # Return the result.
3501        return $retVal;
3502    }
3503    
3504  =head3 EOF  =head3 EOF
3505    
3506  This is a constant that is lexically greater than any useful string.  This is a constant that is lexically greater than any useful string.
# Line 3134  Line 3590 
3590  }  }
3591    
3592    
3593    =head3 GetMemorySize
3594    
3595        my $string = Tracer::GetMemorySize();
3596    
3597    Return a memory size string for the current process. The string will be
3598    in comma format, with a size indicator (K, M, G) at the end.
3599    
3600    =cut
3601    
3602    sub GetMemorySize {
3603        # Get the memory size from Unix.
3604        my ($retVal) = `ps h -o vsz $$`;
3605        # Remove the ending new-line.
3606        chomp $retVal;
3607        # Format and return the result.
3608        return CommaFormat($retVal) . "K";
3609    }
3610    
3611  =head3 CompareLists  =head3 CompareLists
3612    
3613      my ($inserted, $deleted) = Tracer::CompareLists(\@newList, \@oldList, $keyIndex);      my ($inserted, $deleted) = Tracer::CompareLists(\@newList, \@oldList, $keyIndex);
# Line 3201  Line 3675 
3675      return ($inserted, $deleted);      return ($inserted, $deleted);
3676  }  }
3677    
3678    =head3 Cmp
3679    
3680        my $cmp = Tracer::Cmp($a, $b);
3681    
3682    This method performs a universal sort comparison. Each value coming in is
3683    separated into a leading text part and a trailing number part. The text
3684    part is string compared, and if both parts are equal, then the number
3685    parts are compared numerically. A stream of just numbers or a stream of
3686    just strings will sort correctly, and a mixed stream will sort with the
3687    numbers first. Strings with a label and a number will sort in the
3688    expected manner instead of lexically.
3689    
3690    =over 4
3691    
3692    =item a
3693    
3694    First item to compare.
3695    
3696    =item b
3697    
3698    Second item to compare.
3699    
3700    =item RETURN
3701    
3702    Returns a negative number if the first item should sort first (is less), a positive
3703    number if the first item should sort second (is greater), and a zero if the items are
3704    equal.
3705    
3706    =back
3707    
3708    =cut
3709    
3710    sub Cmp {
3711        # Get the parameters.
3712        my ($a, $b) = @_;
3713        # Declare the return value.
3714        my $retVal;
3715        # Check for nulls.
3716        if (! defined($a)) {
3717            $retVal = (! defined($b) ? 0 : -1);
3718        } elsif (! defined($b)) {
3719            $retVal = 1;
3720        } else {
3721            # Here we have two real values. Parse the two strings.
3722            my $aParsed = _Parse($a);
3723            my $bParsed = _Parse($b);
3724            # Compare the string parts insensitively.
3725            $retVal = (lc $aParsed->[0] cmp lc $bParsed->[0]);
3726            # If they're equal, compare them sensitively.
3727            if (! $retVal) {
3728                $retVal = ($aParsed->[0] cmp $bParsed->[0]);
3729            }
3730            # If they're STILL equal, compare the number parts.
3731            if (! $retVal) {
3732                $retVal = $aParsed->[1] <=> $bParsed->[1];
3733            }
3734        }
3735        # Return the result.
3736        return $retVal;
3737    }
3738    
3739    # This method parses an input string into a string part and a number part.
3740    sub _Parse {
3741        my ($string) = @_;
3742        my ($alpha, $num);
3743        if ($string =~ /^(.*?)(\d+(?:\.\d+)?)$/) {
3744            $alpha = $1;
3745            $num = $2;
3746        } else {
3747            $alpha = $string;
3748            $num = 0;
3749        }
3750        return [$alpha, $num];
3751    }
3752    
3753    =head3 ListEQ
3754    
3755        my $flag = Tracer::ListEQ(\@a, \@b);
3756    
3757    Return TRUE if the specified lists contain the same strings in the same
3758    order, else FALSE.
3759    
3760    =over 4
3761    
3762    =item a
3763    
3764    Reference to the first list.
3765    
3766    =item b
3767    
3768    Reference to the second list.
3769    
3770    =item RETURN
3771    
3772    Returns TRUE if the two parameters are identical string lists, else FALSE.
3773    
3774    =back
3775    
3776    =cut
3777    
3778    sub ListEQ {
3779        # Get the parameters.
3780        my ($a, $b) = @_;
3781        # Declare the return variable. Start by checking the lengths.
3782        my $n = scalar(@$a);
3783        my $retVal = ($n == scalar(@$b));
3784        # Now compare the list elements.
3785        for (my $i = 0; $retVal && $i < $n; $i++) {
3786            $retVal = ($a->[$i] eq $b->[$i]);
3787        }
3788        # Return the result.
3789        return $retVal;
3790    }
3791    
3792    =head2 CGI Script Utilities
3793    
3794    =head3 ScriptSetup (deprecated)
3795    
3796        my ($cgi, $varHash) = ScriptSetup($noTrace);
3797    
3798    Perform standard tracing and debugging setup for scripts. The value returned is
3799    the CGI object followed by a pre-built variable hash. At the end of the script,
3800    the client should call L</ScriptFinish> to output the web page.
3801    
3802    This method calls L</ETracing> to configure tracing, which allows the tracing
3803    to be configured via the emergency tracing form on the debugging control panel.
3804    Tracing will then be turned on automatically for all programs that use the L</ETracing>
3805    method, which includes every program that uses this method or L</StandardSetup>.
3806    
3807    =over 4
3808    
3809    =item noTrace (optional)
3810    
3811    If specified, tracing will be suppressed. This is useful if the script wants to set up
3812    tracing manually.
3813    
3814    =item RETURN
3815    
3816    Returns a two-element list consisting of a CGI query object and a variable hash for
3817    the output page.
3818    
3819    =back
3820    
3821    =cut
3822    
3823    sub ScriptSetup {
3824        # Get the parameters.
3825        my ($noTrace) = @_;
3826        # Get the CGI query object.
3827        my $cgi = CGI->new();
3828        # Set up tracing if it's not suppressed.
3829        ETracing($cgi) unless $noTrace;
3830        # Create the variable hash.
3831        my $varHash = { results => '' };
3832        # Return the query object and variable hash.
3833        return ($cgi, $varHash);
3834    }
3835    
3836    =head3 ScriptFinish (deprecated)
3837    
3838        ScriptFinish($webData, $varHash);
3839    
3840    Output a web page at the end of a script. Either the string to be output or the
3841    name of a template file can be specified. If the second parameter is omitted,
3842    it is assumed we have a string to be output; otherwise, it is assumed we have the
3843    name of a template file. The template should have the variable C<DebugData>
3844    specified in any form that invokes a standard script. If debugging mode is turned
3845    on, a form field will be put in that allows the user to enter tracing data.
3846    Trace messages will be placed immediately before the terminal C<BODY> tag in
3847    the output, formatted as a list.
3848    
3849    A typical standard script would loook like the following.
3850    
3851        BEGIN {
3852            # Print the HTML header.
3853            print "CONTENT-TYPE: text/html\n\n";
3854        }
3855        use Tracer;
3856        use CGI;
3857        use FIG;
3858        # ... more uses ...
3859    
3860        my ($cgi, $varHash) = ScriptSetup();
3861        eval {
3862            # ... get data from $cgi, put it in $varHash ...
3863        };
3864        if ($@) {
3865            Trace("Script Error: $@") if T(0);
3866        }
3867        ScriptFinish("Html/MyTemplate.html", $varHash);
3868    
3869    The idea here is that even if the script fails, you'll see trace messages and
3870    useful output.
3871    
3872    =over 4
3873    
3874    =item webData
3875    
3876    A string containing either the full web page to be written to the output or the
3877    name of a template file from which the page is to be constructed. If the name
3878    of a template file is specified, then the second parameter must be present;
3879    otherwise, it must be absent.
3880    
3881    =item varHash (optional)
3882    
3883    If specified, then a reference to a hash mapping variable names for a template
3884    to their values. The template file will be read into memory, and variable markers
3885    will be replaced by data in this hash reference.
3886    
3887    =back
3888    
3889    =cut
3890    
3891    sub ScriptFinish {
3892        # Get the parameters.
3893        my ($webData, $varHash) = @_;
3894        # Check for a template file situation.
3895        my $outputString;
3896        if (defined $varHash) {
3897            # Here we have a template file. We need to determine the template type.
3898            my $template;
3899            if ($FIG_Config::template_url && $webData =~ /\.php$/) {
3900                $template = "$FIG_Config::template_url/$webData";
3901            } else {
3902                $template = "<<$webData";
3903            }
3904            $outputString = PageBuilder::Build($template, $varHash, "Html");
3905        } else {
3906            # Here the user gave us a raw string.
3907            $outputString = $webData;
3908        }
3909        # Check for trace messages.
3910        if ($Destination ne "NONE" && $TraceLevel > 0) {
3911            # We have trace messages, so we want to put them at the end of the body. This
3912            # is either at the end of the whole string or at the beginning of the BODY
3913            # end-tag.
3914            my $pos = length $outputString;
3915            if ($outputString =~ m#</body>#gi) {
3916                $pos = (pos $outputString) - 7;
3917            }
3918            # If the trace messages were queued, we unroll them. Otherwise, we display the
3919            # destination.
3920            my $traceHtml;
3921            if ($Destination eq "QUEUE") {
3922                $traceHtml = QTrace('Html');
3923            } elsif ($Destination =~ /^>>(.+)$/) {
3924                # Here the tracing output it to a file. We code it as a hyperlink so the user
3925                # can copy the file name into the clipboard easily.
3926                my $actualDest = $1;
3927                $traceHtml = "<p>Tracing output to $actualDest.</p>\n";
3928            } else {
3929                # Here we have one of the special destinations.
3930                $traceHtml = "<P>Tracing output type is $Destination.</p>\n";
3931            }
3932            substr $outputString, $pos, 0, $traceHtml;
3933        }
3934        # Write the output string.
3935        print $outputString;
3936    }
3937    
3938  =head3 GenerateURL  =head3 GenerateURL
3939    
3940      my $queryUrl = Tracer::GenerateURL($page, %parameters);      my $queryUrl = Tracer::GenerateURL($page, %parameters);
# Line 3335  Line 4069 
4069      return $retVal;      return $retVal;
4070  }  }
4071    
 =head3 Cmp  
   
     my $cmp = Tracer::Cmp($a, $b);  
   
 This method performs a universal sort comparison. Each value coming in is  
 separated into a leading text part and a trailing number part. The text  
 part is string compared, and if both parts are equal, then the number  
 parts are compared numerically. A stream of just numbers or a stream of  
 just strings will sort correctly, and a mixed stream will sort with the  
 numbers first. Strings with a label and a number will sort in the  
 expected manner instead of lexically.  
   
 =over 4  
   
 =item a  
   
 First item to compare.  
   
 =item b  
   
 Second item to compare.  
   
 =item RETURN  
   
 Returns a negative number if the first item should sort first (is less), a positive  
 number if the first item should sort second (is greater), and a zero if the items are  
 equal.  
   
 =back  
   
 =cut  
   
 sub Cmp {  
     # Get the parameters.  
     my ($a, $b) = @_;  
     # Declare the return value.  
     my $retVal;  
     # Check for nulls.  
     if (! defined($a)) {  
         $retVal = (! defined($b) ? 0 : -1);  
     } elsif (! defined($b)) {  
         $retVal = 1;  
     } else {  
         # Here we have two real values. Parse the two strings.  
         $a =~ /^(\D*)(\d*)$/;  
         my $aParsed = [$1, $2];  
         $b =~ /^(\D*)(\d*)$/;  
         my $bParsed = [$1, $2];  
         # Compare the string parts.  
         $retVal = $aParsed->[0] cmp $bParsed->[0];  
         if (! $retVal) {  
             $retVal = $aParsed->[1] <=> $bParsed->[1];  
         }  
     }  
     # Return the result.  
     return $retVal;  
 }  
   
   
4072  =head3 TrackingCode  =head3 TrackingCode
4073    
4074      my $html = Tracer::TrackingCode();      my $html = Tracer::TrackingCode();
# Line 3424  Line 4099 
4099      return $retVal;      return $retVal;
4100  }  }
4101    
4102    =head3 Clean
4103    
4104        my $cleaned = Tracer::Clean($string);
4105    
4106    Clean up a string for HTML display. This not only converts special
4107    characters to HTML entity names, it also removes control characters.
4108    
4109    =over 4
4110    
4111    =item string
4112    
4113    String to convert.
4114    
4115    =item RETURN
4116    
4117    Returns the input string with anything that might disrupt an HTML literal removed. An
4118    undefined value will be converted to an empty string.
4119    
4120    =back
4121    
4122    =cut
4123    
4124    sub Clean {
4125        # Get the parameters.
4126        my ($string) = @_;
4127        # Declare the return variable.
4128        my $retVal = "";
4129        # Only proceed if the value exists.
4130        if (defined $string) {
4131            # Get the string.
4132            $retVal = $string;
4133            # Clean the control characters.
4134            $retVal =~ tr/\x00-\x1F/?/;
4135            # Escape the rest.
4136            $retVal = CGI::escapeHTML($retVal);
4137        }
4138        # Return the result.
4139        return $retVal;
4140    }
4141    
4142    =head3 SortByValue
4143    
4144        my @keys = Tracer::SortByValue(\%hash);
4145    
4146    Get a list of hash table keys sorted by hash table values.
4147    
4148    =over 4
4149    
4150    =item hash
4151    
4152    Hash reference whose keys are to be extracted.
4153    
4154    =item RETURN
4155    
4156    Returns a list of the hash keys, ordered so that the corresponding hash values
4157    are in alphabetical sequence.
4158    
4159    =back
4160    
4161    =cut
4162    
4163    sub SortByValue {
4164        # Get the parameters.
4165        my ($hash) = @_;
4166        # Sort the hash's keys using the values.
4167        my @retVal = sort { Cmp($hash->{$a}, $hash->{$b}) } keys %$hash;
4168        # Return the result.
4169        return @retVal;
4170    }
4171    
4172    =head3 GetSet
4173    
4174        my $value = Tracer::GetSet($object, $name => $newValue);
4175    
4176    Get or set the value of an object field. The object is treated as an
4177    ordinary hash reference. If a new value is specified, it is stored in the
4178    hash under the specified name and then returned. If no new value is
4179    specified, the current value is returned.
4180    
4181    =over 4
4182    
4183    =item object
4184    
4185    Reference to the hash that is to be interrogated or updated.
4186    
4187    =item name
4188    
4189    Name of the field. This is the hash key.
4190    
4191    =item newValue (optional)
4192    
4193    New value to be stored in the field. If no new value is specified, the current
4194    value of the field is returned.
4195    
4196    =item RETURN
4197    
4198    Returns the value of the named field in the specified hash.
4199    
4200    =back
4201    
4202    =cut
4203    
4204    sub GetSet {
4205        # Get the parameters.
4206        my ($object, $name, $newValue) = @_;
4207        # Is a new value specified?
4208        if (defined $newValue) {
4209            # Yes, so store it.
4210            $object->{$name} = $newValue;
4211        }
4212        # Return the result.
4213        return $object->{$name};
4214    }
4215    
4216  1;  1;

Legend:
Removed from v.1.98  
changed lines
  Added in v.1.118

MCS Webmaster
ViewVC Help
Powered by ViewVC 1.0.3