[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.116, Thu Feb 5 06:40:13 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 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 TraceDump
516    
517        TraceDump($title, $object);
518    
519    Dump an object to the trace log. This method simply calls the C<Dumper>
520    function, but routes the output to the trace log instead of returning it
521    as a string. The output is arranged so that it comes out monospaced when
522    it appears in an HTML trace dump.
523    
524    =over 4
525    
526    =item title
527    
528    Title to give to the object being dumped.
529    
530    =item object
531    
532    Reference to a list, hash, or object to dump.
533    
534    =back
535    
536    =cut
537    
538    sub TraceDump {
539        # Get the parameters.
540        my ($title, $object) = @_;
541        # Trace the object.
542        Trace("Object dump for $title:\n" . Dumper($object));
543    }
544    
545  =head3 T  =head3 T
546    
547      my $switch = T($category, $traceLevel);      my $switch = T($category, $traceLevel);
# Line 553  Line 600 
600          $LastLevel = $traceLevel;          $LastLevel = $traceLevel;
601          # Convert it to lower case before we hash it.          # Convert it to lower case before we hash it.
602          $category = lc $category;          $category = lc $category;
603          # Use the category and tracelevel to compute the result.          # Validate the trace level.
604          if (ref $traceLevel) {          if (ref $traceLevel) {
605              Confess("Bad trace level.");              Confess("Bad trace level.");
606          } elsif (ref $TraceLevel) {          } elsif (ref $TraceLevel) {
607              Confess("Bad trace config.");              Confess("Bad trace config.");
608          }          }
609          $retVal = ($traceLevel <= $TraceLevel && ($AllTrace || exists $Categories{$category}));          # Make the check. Note that level 0 shows even if the category is turned off.
610            $retVal = ($traceLevel <= $TraceLevel && ($traceLevel == 0 || $AllTrace || exists $Categories{$category}));
611      }      }
612      # Return the computed result.      # Return the computed result.
613      return $retVal;      return $retVal;
# Line 636  Line 684 
684      # Set up the category and level.      # Set up the category and level.
685      $LastCategory = "(confess)";      $LastCategory = "(confess)";
686      $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.");  
             }  
         }  
     }  
687      # Trace the call stack.      # Trace the call stack.
688      Cluck($message);      Cluck($message);
689      # Abort the program.      # Abort the program.
690      croak(">>> $message");      croak(">>> $message");
691  }  }
692    
693    =head3 SaveCGI
694    
695        Tracer::SaveCGI($cgi);
696    
697    This method saves the CGI object but does not activate emergency tracing.
698    It is used to allow L</Warn> to work in situations where emergency
699    tracing is contra-indicated (e.g. the wiki).
700    
701    =over 4
702    
703    =item cgi
704    
705    Active CGI query object.
706    
707    =back
708    
709    =cut
710    
711    sub SaveCGI {
712        $SavedCGI = $_[0];
713    }
714    
715    =head3 Warn
716    
717        Warn($message, @options);
718    
719    This method traces an important message. If an RSS feed is configured
720    (via I<FIG_Config::error_feed>) and the tracing destination is C<WARN>,
721    then the message will be echoed to the feed. In general, a tracing
722    destination of C<WARN> indicates that the caller is running as a web
723    service in a production environment; however, this is not a requirement.
724    
725    To force warnings into the RSS feed even when the tracing destination
726    is not C<WARN>, simply specify the C<Feed> tracing module. This can be
727    configured automatically when L</StandardSetup> is used.
728    
729    The L</Cluck> method calls this one for its final message. Since
730    L</Confess> calls L</Cluck>, this means that any error which is caught
731    and confessed will put something in the feed. This insures that someone
732    will be alerted relatively quickly when a failure occurs.
733    
734    =over 4
735    
736    =item message
737    
738    Message to be traced.
739    
740    =item options
741    
742    A list containing zero or more options.
743    
744    =back
745    
746    The permissible options are as follows.
747    
748    =over 4
749    
750    =item noStack
751    
752    If specified, then the stack trace is not included in the output.
753    
754    =back
755    
756    =cut
757    
758    sub Warn {
759        # Get the parameters.
760        my $message = shift @_;
761        my %options = map { $_ => 1 } @_;
762        # Save $@;
763        my $savedError = $@;
764        # Trace the message.
765        Trace($message);
766        # This will contain the lock handle. If it's defined, it means we need to unlock.
767        my $lock;
768        # Check for feed forcing.
769        my $forceFeed = exists $Categories{feed};
770        # An error here would be disastrous. Note that if debug mode is specified,
771        # we do this stuff even in a test environment.
772        eval {
773            # Do we need to put this in the RSS feed?
774            if ($FIG_Config::error_feed && ($Destination eq 'WARN' || $forceFeed)) {
775                # Probably. We need to check first, however, to see if it's from an
776                # ignored IP. For non-CGI situations, we default the IP to the self-referent.
777                my $key = "127.0.0.1";
778                if (defined $SavedCGI) {
779                    # Get the IP address.
780                    $key = $ENV{HTTP_X_FORWARDED_FOR} || $ENV{REMOTE_ADDR};
781                }
782                # Is the IP address in the ignore list?
783                my $found = scalar(grep { $_ eq $key } @FIG_Config::error_ignore_ips);
784                if (! $found) {
785                    # No. We're good. We now need to compute the date, the link, and the title.
786                    # First, the date, in a very specific format.
787                    my $date = strftime("%a, %02e %b %H:%M:%S %Y ", localtime) .
788                        (tz_local_offset() / 30);
789                    # Environment data goes in here. We start with the date.
790                    my $environment = "$date.  ";
791                    # If we need to recap the message (because it's too long to be a title), we'll
792                    # put it in here.
793                    my $recap;
794                    # Copy the message and remove excess space.
795                    my $title = $message;
796                    $title =~ s/\s+/ /gs;
797                    # If it's too long, we have to split it up.
798                    if (length $title > 60) {
799                        # Put the full message in the environment string.
800                        $recap = $title;
801                        # Excerpt it as the title.
802                        $title = substr($title, 0, 50) . "...";
803                    }
804                    # If we have a CGI object, then this is a web error. Otherwise, it's
805                    # command-line.
806                    if (defined $SavedCGI) {
807                        # We're in a web service. The environment is the user's IP, and the link
808                        # is the URL that got us here.
809                        $environment .= "Event Reported at IP address $key process $$.";
810                        my $url = $SavedCGI->self_url();
811                        # We need the user agent string and (if available) the referrer.
812                        # The referrer will be the link.
813                        $environment .= " User Agent $ENV{HTTP_USER_AGENT}";
814                        if ($ENV{HTTP_REFERER}) {
815                            my $link = $ENV{HTTP_REFERER};
816                            $environment .= " referred from <a href=\"$link\">$link</a>.";
817                        } else {
818                            $environment .= " referrer unknown.";
819                        }
820                        # Close off the sentence with the original link.
821                        $environment .= " URL of event is <a href=\"$url\">$url</a>.";
822                    } else {
823                        # No CGI object, so we're a command-line tool. Use the tracing
824                        # key and the PID as the user identifier, and add the command.
825                        my $key = EmergencyKey();
826                        $environment .= "Event Reported by $key process $$.";
827                        if ($CommandLine) {
828                            # We're in a StandardSetup script, so we have the real command line.
829                            $environment .= "\n<pre>" . CGI::escapeHTML($CommandLine) . "</pre>\n";
830                        } elsif ($ENV{_}) {
831                            # We're in a BASH script, so the command has been stored in the _ variable.
832                            $environment .= "  Command = " . CGI::escapeHTML($ENV{_}) . "\n";
833                        }
834                    }
835                    # Build a GUID. We use the current time, the title, and the process ID,
836                    # then digest the result.
837                    my $guid = Digest::MD5::md5_base64(gettimeofday(), $title, $$);
838                    # Finally, the description. This is a stack trace plus various environmental stuff.
839                    # The trace is optional.
840                    my $stackTrace;
841                    if ($options{noStack}) {
842                        $stackTrace = "";
843                    } else {
844                        my @trace = LongMess();
845                        # Only proceed if we got something back.
846                        if (scalar(@trace) > 0) {
847                            $trace[0] =~ s/Tracer::Warn.+?called/Event occurred/;
848                            $stackTrace = "Stack trace:<pre>" . join("\n", @trace, "</pre>");
849                        }
850                    }
851                    # We got the stack trace. Now it's time to put it all together.
852                    # We have a goofy thing here in that we need to HTML-escape some sections of the description
853                    # twice. They will be escaped once here, and then once when written by XML::Simple. They are
854                    # unescaped once when processed by the RSS reader, and stuff in the description is treated as
855                    # HTML. So, anything escaped here is treated as a literal when viewed in the RSS reader, but
856                    # our <br>s and <pre>s are used to format the description.
857                    $recap = (defined $recap ? "<em>" . CGI::escapeHTML($recap) . "</em><br /><br />" : "");
858                    my $description = "$recap$environment  $stackTrace";
859                    # Okay, we have all the pieces. Create a hash of the new event.
860                    my $newItem = { title => $title,
861                                    description => $description,
862                                    category => $LastCategory,
863                                    pubDate => $date,
864                                    guid => $guid,
865                                  };
866                    # We need XML capability for this.
867                    require XML::Simple;
868                    # The RSS document goes in here.
869                    my $rss;
870                    # Get the name of the RSS file. It's in the FIG temporary directory.
871                    my $fileName = "$FIG_Config::temp/$FIG_Config::error_feed";
872                    # Open the config file and lock it.
873                    $lock = Open(undef, "<$FIG_Config::fig_disk/config/FIG_Config.pm");
874                    flock $lock, LOCK_EX;
875                    # Does it exist?
876                    if (-s $fileName) {
877                        # Slurp it in.
878                        $rss = XML::Simple::XMLin($fileName, ForceArray => ['item']);
879                    } else {
880                        my $size = -s $fileName;
881                        # Create an empty channel.
882                        $rss = {
883                            channel => {
884                                title => 'NMPDR Warning Feed',
885                                link => "$FIG_Config::temp_url/$FIG_Config::error_feed",
886                                description => "Important messages regarding the status of the NMPDR.",
887                                generator => "NMPDR Trace Facility",
888                                docs => "http://blogs.law.harvard.edu/tech/rss",
889                                item => []
890                            },
891                        };
892                    }
893                    # Get the channel object.
894                    my $channel = $rss->{channel};
895                    # Update the last-build date.
896                    $channel->{lastBuildDate} = $date;
897                    # Get the item array.
898                    my $items = $channel->{item};
899                    # Insure it has only 100 entries.
900                    while (scalar @{$items} > 100) {
901                        pop @{$items};
902                    }
903                    # Add our new item at the front.
904                    unshift @{$items}, $newItem;
905                    # Create the XML. Note we do not include the root or the declaration. XML Simple can't handle
906                    # the requirements for those.
907                    my $xml = XML::Simple::XMLout($channel, NoAttr => 1, RootName => 'channel', XmlDecl => '');
908                    # Here we put in the root and declaration. The problem is that the root has to have the version attribute
909                    # in it. So, we suppress the root and do it by hand, and that requires suppressing the declaration, too.
910                    $xml = "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<rss version=\"2.0\">$xml\n</rss>";
911                    # We don't use Open here because we can't afford an error.
912                    if (open XMLOUT, ">$fileName") {
913                        print XMLOUT $xml;
914                        close XMLOUT;
915                    }
916                }
917            }
918        };
919        if ($@) {
920            # If the feed failed, we need to know why. The error will be traced, but this method will not be involved
921            # (which is a good thing).
922            my $error = $@;
923            Trace("Feed Error: $error") if T(Feed => 0);
924        }
925        # Be sure to unlock.
926        if ($lock) {
927            flock $lock, LOCK_UN;
928            undef $lock;
929        }
930        # Restore the error message.
931        $@ = $savedError;
932    }
933    
934    
935    
936    
937  =head3 Assert  =head3 Assert
938    
939      Assert($condition1, $condition2, ... $conditionN);      Assert($condition1, $condition2, ... $conditionN);
# Line 704  Line 984 
984      my ($message) = @_;      my ($message) = @_;
985      # Trace what's happening.      # Trace what's happening.
986      Trace("Stack trace for event: $message");      Trace("Stack trace for event: $message");
987      my $confession = longmess($message);      # Get the stack trace.
988      # Convert the confession to a series of trace messages.      my @trace = LongMess();
989      for my $line (split /\s*\n/, $confession) {      # Convert the trace to a series of messages.
990          # Only proceed if this call trace is for a method outside Tracer itself.      for my $line (@trace) {
991          if ($line !~ /Tracer\.pm/) {          # Replace the tab at the beginning with spaces.
992              # Replace the leading tab with a series of spaces.          $line =~ s/^\t/    /;
             $line =~ s/\t/    /;  
993              # Trace the line.              # Trace the line.
994              Trace($line);              Trace($line);
995          }          }
996        # Issue a warning. This displays the event message and inserts it into the RSS error feed.
997        Warn($message);
998      }      }
 }  
   
 =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.  
999    
1000  =item RETURN  =head3 LongMess
1001    
1002  Returns a two-element list consisting of a CGI query object and a variable hash for      my @lines = Tracer::LongMess();
 the output page.  
1003    
1004  =back  Return a stack trace with all tracing methods removed. The return will be in the form of a list
1005    of message strings.
1006    
1007  =cut  =cut
1008    
1009  sub ScriptSetup {  sub LongMess {
1010      # Get the parameters.      # Declare the return variable.
1011      my ($noTrace) = @_;      my @retVal = ();
1012      # Get the CGI query object.      my $confession = longmess("");
1013      my $cgi = CGI->new();      for my $line (split /\s*\n/, $confession) {
1014      # Set up tracing if it's not suppressed.          unless ($line =~ /Tracer\.pm/) {
1015      ETracing($cgi) unless $noTrace;              # Here we have a line worth keeping. Push it onto the result list.
1016      # Create the variable hash.              push @retVal, $line;
1017      my $varHash = { results => '' };          }
1018      # Return the query object and variable hash.      }
1019      return ($cgi, $varHash);      # Return the result.
1020        return @retVal;
1021  }  }
1022    
1023  =head3 ETracing  =head3 ETracing
# Line 790  Line 1051 
1051      # Get the parameter.      # Get the parameter.
1052      my ($parameter) = @_;      my ($parameter) = @_;
1053      # Check for CGI mode.      # Check for CGI mode.
1054      my $cgi = (ref $parameter eq 'CGI' ? $parameter : undef);      if (defined $parameter && ref $parameter eq 'CGI') {
1055            $SavedCGI = $parameter;
1056        } else {
1057            $SavedCGI = undef;
1058        }
1059      # Default to no tracing except errors.      # Default to no tracing except errors.
1060      my ($tracing, $dest) = ("0", "WARN");      my ($tracing, $dest) = ("0", "WARN");
1061      # Check for emergency tracing.      # Check for emergency tracing.
# Line 823  Line 1088 
1088              # Set the trace parameter.              # Set the trace parameter.
1089              $tracing = join(" ", $level, sort keys %moduleHash);              $tracing = join(" ", $level, sort keys %moduleHash);
1090          }          }
1091      } elsif (defined $cgi) {      } elsif (defined $SavedCGI) {
1092          # 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
1093          # for tracing from the form parameters.          # for tracing from the form parameters.
1094          if ($cgi->param('Trace')) {          if ($SavedCGI->param('Trace')) {
1095              # Here the user has requested tracing via a form.              # Here the user has requested tracing via a form.
1096              $dest = ($cgi->param('TF') ? ">$FIG_Config::temp/Trace$$.log" : "QUEUE");              $dest = ($SavedCGI->param('TF') ? ">$FIG_Config::temp/Trace$$.log" : "QUEUE");
1097              $tracing = $cgi->param('Trace') . " Tracer";              $tracing = $SavedCGI->param('Trace') . " Tracer";
1098          }          }
1099      }      }
1100      # Setup the tracing we've determined from all the stuff above.      # Setup the tracing we've determined from all the stuff above.
1101      TSetup($tracing, $dest);      TSetup($tracing, $dest);
1102      # Check to see if we're a web script.      # Check to see if we're a web script.
1103      if (defined $cgi) {      if (defined $SavedCGI) {
1104          # Yes we are. Trace the form and environment data.          # Yes we are. Trace the form and environment data.
1105          TraceParms($cgi);          TraceParms($SavedCGI);
1106          # 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
1107          # emitted by the script in its raw form.          # emitted by the script in its raw form.
1108          if (T(Raw => 3)) {          if (T(Raw => 3)) {
# Line 1028  Line 1293 
1293      # Declare the return variable.      # Declare the return variable.
1294      my $retVal;      my $retVal;
1295      # Determine the parameter type.      # Determine the parameter type.
1296      if (! defined $parameter) {      if (! defined $parameter || defined($ENV{TRACING})) {
1297          # Here we're supposed to check the environment.          # Here we're supposed to check the environment. If that fails, we
1298          $retVal = $ENV{TRACING};          # get the effective login ID.
1299            $retVal = $ENV{TRACING} || scalar getpwuid($<);
1300      } else {      } else {
1301          my $ptype = ref $parameter;          my $ptype = ref $parameter;
1302          if ($ptype eq 'CGI') {          if ($ptype eq 'CGI') {
# Line 1071  Line 1337 
1337      # Get the parameters.      # Get the parameters.
1338      my ($cgi) = @_;      my ($cgi) = @_;
1339      if (T(CGI => 2)) {      if (T(CGI => 2)) {
1340          # 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
1341          Trace("[URL] " . $cgi->url(-relative => 1, -query => 1));          # relatively small.
1342            my $url = $cgi->url(-relative => 1, -query => 1);
1343            my $len = length($url);
1344            if ($len < 500) {
1345                Trace("[URL] $url");
1346            } elsif ($len > 2048) {
1347                Trace("[URL] URL is too long to use with GET ($len characters).");
1348            } else {
1349                Trace("[URL] URL length is $len characters.");
1350            }
1351      }      }
1352      if (T(CGI => 3)) {      if (T(CGI => 3)) {
1353          # Here we want to trace the parameter data.          # Here we want to trace the parameter data.
# Line 1147  Line 1422 
1422      }      }
1423  }  }
1424    
   
 =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;  
 }  
   
1425  =head2 Command-Line Utility Methods  =head2 Command-Line Utility Methods
1426    
1427  =head3 SendSMS  =head3 SendSMS
# Line 1454  Line 1626 
1626  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
1627  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,
1628  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
1629  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
1630    login ID.
1631    
1632    Since the default situation in StandardSetup is to trace to the standard
1633    output, errors that occur in command-line scripts will not generate
1634    RSS events. To force the events, use the C<warn> option.
1635    
1636        TransactFeatures -background -warn register ../xacts IDs.tbl
1637    
1638  Finally, if the special option C<-help> is specified, the option  Finally, if the special option C<-help> is specified, the option
1639  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 1650 
1650          -noAlias  do not expect aliases in CHANGE transactions          -noAlias  do not expect aliases in CHANGE transactions
1651          -start    start with this genome          -start    start with this genome
1652          -tblFiles output TBL files containing the corrected IDs          -tblFiles output TBL files containing the corrected IDs
1653            -forked   do not erase the trace file before tracing
1654    
1655  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
1656  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 1714 
1714      my ($categories, $options, $parmHelp, @argv) = @_;      my ($categories, $options, $parmHelp, @argv) = @_;
1715      # Get the default tracing key.      # Get the default tracing key.
1716      my $tkey = EmergencyKey();      my $tkey = EmergencyKey();
1717        # Save the command line.
1718        $CommandLine = join(" ", $0, map { $_ =~ /\s/ ? "\"$_\"" : $_ } @argv);
1719      # Add the tracing options.      # Add the tracing options.
1720      if (! exists $options->{trace}) {      if (! exists $options->{trace}) {
1721          $options->{trace} = ['2', "tracing level (E for emergency tracing)"];          $options->{trace} = ['2', "tracing level (E for emergency tracing)"];
1722      }      }
1723        if (! exists $options->{forked}) {
1724            $options->{forked} = [0, "keep old trace file"];
1725        }
1726      $options->{sql} = [0, "turn on SQL tracing"];      $options->{sql} = [0, "turn on SQL tracing"];
1727      $options->{help} = [0, "display command-line options"];      $options->{help} = [0, "display command-line options"];
1728      $options->{user} = [$tkey, "tracing key"];      $options->{user} = [$tkey, "tracing key"];
1729      $options->{background} = [0, "spool standard and error output"];      $options->{background} = [0, "spool standard and error output"];
1730        $options->{warn} = [0, "send errors to RSS feed"];
1731        $options->{moreTracing} = ["", "comma-delimited list of additional trace modules for debugging"];
1732      # Create a parsing hash from the options hash. The parsing hash      # Create a parsing hash from the options hash. The parsing hash
1733      # contains the default values rather than the default value      # contains the default values rather than the default value
1734      # 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 1745 
1745      my ($retOptions, @retParameters) = ParseCommand(\%parseOptions, @argv);      my ($retOptions, @retParameters) = ParseCommand(\%parseOptions, @argv);
1746      # Get the logfile suffix.      # Get the logfile suffix.
1747      my $suffix = $retOptions->{user};      my $suffix = $retOptions->{user};
1748      # Check for background mode.      # We'll put the trace file name in here. We need it later if background
1749      if ($retOptions->{background}) {      # mode is on.
1750          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};  
         }  
     }  
1751      # 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
1752      # wants emergency tracing.      # wants emergency tracing.
1753      if ($retOptions->{trace} eq 'E') {      if ($retOptions->{trace} eq 'E') {
# Line 1580  Line 1758 
1758          if ($retOptions->{sql}) {          if ($retOptions->{sql}) {
1759              push @cats, "SQL";              push @cats, "SQL";
1760          }          }
1761            if ($retOptions->{warn}) {
1762                push @cats, "Feed";
1763            }
1764          # Add the default categories.          # Add the default categories.
1765          push @cats, "Tracer";          push @cats, "Tracer";
1766            # Check for more tracing groups.
1767            if ($retOptions->{moreTracing}) {
1768                push @cats, split /,/, $retOptions->{moreTracing};
1769            }
1770          # Next, we create the category string by joining the categories.          # Next, we create the category string by joining the categories.
1771          my $cats = join(" ", @cats);          my $cats = join(" ", @cats);
1772          # 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 1781 
1781          my $traceMode;          my $traceMode;
1782          # Verify that we can open a file in the FIG temporary directory.          # Verify that we can open a file in the FIG temporary directory.
1783          my $traceFileName = "$FIG_Config::temp/trace$suffix.log";          my $traceFileName = "$FIG_Config::temp/trace$suffix.log";
1784          if (open TESTTRACE, ">$traceFileName") {          my $traceFileSpec = ($retOptions->{forked} ? ">>$traceFileName" : ">$traceFileName");
1785            if (open TESTTRACE, "$traceFileSpec") {
1786              # Here we can trace to a file.              # Here we can trace to a file.
1787              $traceMode = ">$traceFileName";              $traceMode = ">>$traceFileName";
1788              if ($textOKFlag) {              if ($textOKFlag) {
1789                  # Echo to standard output if the text-OK flag is set.                  # Echo to standard output if the text-OK flag is set.
1790                  $traceMode = "+$traceMode";                  $traceMode = "+$traceMode";
# Line 1619  Line 1805 
1805          # Now set up the tracing.          # Now set up the tracing.
1806          TSetup("$traceLevel $cats", $traceMode);          TSetup("$traceLevel $cats", $traceMode);
1807      }      }
1808      # Check for the "help" option. If it is specified, dump the command-line      # Check for background mode.
1809      # options and exit the program.      if ($retOptions->{background}) {
1810      if ($retOptions->{help}) {          my $outFileName = "$FIG_Config::temp/out$suffix$$.log";
1811          $0 =~ m#[/\\](\w+)(\.pl)?$#i;          my $errFileName = "$FIG_Config::temp/err$suffix$$.log";
1812          print "$1 [options] $parmHelp\n";          # Spool the output.
1813          for my $key (sort keys %{$options}) {          open STDOUT, ">$outFileName";
1814            # If we have a trace file, trace the errors to the log. Otherwise,
1815            # spool the errors.
1816            if (defined $traceFileName) {
1817                open STDERR, "| Tracer $traceFileName";
1818            } else {
1819                open STDERR, ">$errFileName";
1820            }
1821            # Check for phone support. If we have phone support and a phone number,
1822            # we want to turn it on.
1823            if ($ENV{PHONE} && defined($FIG_Config::phone)) {
1824                $retOptions->{phone} = $ENV{PHONE};
1825            }
1826        }
1827        # Check for the "help" option. If it is specified, dump the command-line
1828        # options and exit the program.
1829        if ($retOptions->{help}) {
1830            $0 =~ m#[/\\](\w+)(\.pl)?$#i;
1831            print "$1 [options] $parmHelp\n";
1832            for my $key (sort keys %{$options}) {
1833              my $name = Pad($key, $longestName, 0, ' ');              my $name = Pad($key, $longestName, 0, ' ');
1834              my $desc = $options->{$key}->[1];              my $desc = $options->{$key}->[1];
1835              if ($options->{$key}->[0]) {              if ($options->{$key}->[0]) {
# Line 1799  Line 2004 
2004      }      }
2005  }  }
2006    
2007    =head3 UnparseOptions
2008    
2009        my $optionString = Tracer::UnparseOptions(\%options);
2010    
2011    Convert an option hash into a command-line string. This will not
2012    necessarily be the same text that came in, but it will nonetheless
2013    produce the same ultimate result when parsed by L</StandardSetup>.
2014    
2015    =over 4
2016    
2017    =item options
2018    
2019    Reference to a hash of options to convert into an option string.
2020    
2021    =item RETURN
2022    
2023    Returns a string that will parse to the same set of options when
2024    parsed by L</StandardSetup>.
2025    
2026    =back
2027    
2028    =cut
2029    
2030    sub UnparseOptions {
2031        # Get the parameters.
2032        my ($options) = @_;
2033        # The option segments will be put in here.
2034        my @retVal = ();
2035        # Loop through the options.
2036        for my $key (keys %$options) {
2037            # Get the option value.
2038            my $value = $options->{$key};
2039            # Only use it if it's nonempty.
2040            if (defined $value && $value ne "") {
2041                my $segment = "--$key=$value";
2042                # Quote it if necessary.
2043                if ($segment =~ /[ |<>*]/) {
2044                    $segment = '"' . $segment . '"';
2045                }
2046                # Add it to the return list.
2047                push @retVal, $segment;
2048            }
2049        }
2050        # Return the result.
2051        return join(" ", @retVal);
2052    }
2053    
2054  =head3 ParseCommand  =head3 ParseCommand
2055    
2056      my ($options, @arguments) = Tracer::ParseCommand(\%optionTable, @inputList);      my ($options, @arguments) = Tracer::ParseCommand(\%optionTable, @inputList);
# Line 2377  Line 2629 
2629  Map of search patterns to permission masks. If a directory name matches  Map of search patterns to permission masks. If a directory name matches
2630  one of the patterns, that directory and all its members and subdirectories  one of the patterns, that directory and all its members and subdirectories
2631  will be assigned the new pattern. For example, the following would  will be assigned the new pattern. For example, the following would
2632  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>.
2633    
2634      Tracer::SetPermissions($dirName, 'fig', 01664, '^tmp$' => 01777);      Tracer::SetPermissions($dirName, 'fig', 01664, '^tmp$' => 01777);
2635    
# Line 2430  Line 2682 
2682                      $match = 1;                      $match = 1;
2683                  }                  }
2684              }              }
2685              # 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
2686              # before terminating due to the match.              # before terminating due to the match.
2687              if ($match && $otherMasks[$i-1] != $mask) {              if ($match && $otherMasks[$i-1] != $mask) {
2688                  # 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 2850 
2850    
2851  =head2 Other Useful Methods  =head2 Other Useful Methods
2852    
2853    =head3 IDHASH
2854    
2855        my $hash = SHTargetSearch::IDHASH(@keys);
2856    
2857    This is a dinky little method that converts a list of values to a reference
2858    to hash of values to labels. The values and labels are the same.
2859    
2860    =cut
2861    
2862    sub IDHASH {
2863        my %retVal = map { $_ => $_ } @_;
2864        return \%retVal;
2865    }
2866    
2867    =head3 Pluralize
2868    
2869        my $plural = Tracer::Pluralize($word);
2870    
2871    This is a very simple pluralization utility. It adds an C<s> at the end
2872    of the input word unless it already ends in an C<s>, in which case it
2873    adds C<es>.
2874    
2875    =over 4
2876    
2877    =item word
2878    
2879    Singular word to pluralize.
2880    
2881    =item RETURN
2882    
2883    Returns the probable plural form of the word.
2884    
2885    =back
2886    
2887    =cut
2888    
2889    sub Pluralize {
2890        # Get the parameters.
2891        my ($word) = @_;
2892        # Declare the return variable.
2893        my $retVal;
2894        if ($word =~ /s$/) {
2895            $retVal = $word . 'es';
2896        } else {
2897            $retVal = $word . 's';
2898        }
2899        # Return the result.
2900        return $retVal;
2901    }
2902    
2903    =head3 Numeric
2904    
2905        my $okFlag = Tracer::Numeric($string);
2906    
2907    Return the value of the specified string if it is numeric, or an undefined value
2908    if it is not numeric.
2909    
2910    =over 4
2911    
2912    =item string
2913    
2914    String to check.
2915    
2916    =item RETURN
2917    
2918    Returns the numeric value of the string if successful, or C<undef> if the string
2919    is not numeric.
2920    
2921    =back
2922    
2923    =cut
2924    
2925    sub Numeric {
2926        # Get the parameters.
2927        my ($string) = @_;
2928        # We'll put the value in here if we succeed.
2929        my $retVal;
2930        # Get a working copy of the string.
2931        my $copy = $string;
2932        # Trim leading and trailing spaces.
2933        $copy =~ s/^\s+//;
2934        $copy =~ s/\s+$//;
2935        # Check the result.
2936        if ($copy =~ /^[+-]?\d+$/) {
2937            $retVal = $copy;
2938        } elsif ($copy =~ /^([+-]\d+|\d*)[eE][+-]?\d+$/) {
2939            $retVal = $copy;
2940        } elsif ($copy =~ /^([+-]\d+|\d*)\.\d*([eE][+-]?\d+)?$/) {
2941            $retVal = $copy;
2942        }
2943        # Return the result.
2944        return $retVal;
2945    }
2946    
2947    
2948  =head3 ParseParm  =head3 ParseParm
2949    
2950      my $listValue = Tracer::ParseParm($string);      my $listValue = Tracer::ParseParm($string);
# Line 2840  Line 3187 
3187      return $retVal;      return $retVal;
3188  }  }
3189    
3190    =head3 In
3191    
3192        my $flag = Tracer::In($value, $min, $max);
3193    
3194    Return TRUE if the value is between the minimum and the maximum, else FALSE.
3195    
3196    =cut
3197    
3198    sub In {
3199        return ($_[0] <= $_[2] && $_[0] >= $_[1]);
3200    }
3201    
3202    
3203  =head3 Constrain  =head3 Constrain
3204    
3205      my $constrained = Constrain($value, $min, $max);      my $constrained = Constrain($value, $min, $max);
# Line 2951  Line 3311 
3311      return $retVal;      return $retVal;
3312  }  }
3313    
   
3314  =head3 Strip  =head3 Strip
3315    
3316      my $string = Tracer::Strip($line);      my $string = Tracer::Strip($line);
# Line 2984  Line 3343 
3343      return $retVal;      return $retVal;
3344  }  }
3345    
3346    =head3 Trim
3347    
3348        my $string = Tracer::Trim($line);
3349    
3350    Trim all spaces from the beginning and ending of a string.
3351    
3352    =over 4
3353    
3354    =item line
3355    
3356    Line of text to be trimmed.
3357    
3358    =item RETURN
3359    
3360    The same line of text with all whitespace chopped off either end.
3361    
3362    =back
3363    
3364    =cut
3365    
3366    sub Trim {
3367        # Get a copy of the parameter string.
3368        my ($string) = @_;
3369        my $retVal = (defined $string ? $string : "");
3370        # Strip the front spaces.
3371        $retVal =~ s/^\s+//;
3372        # Strip the back spaces.
3373        $retVal =~ s/\s+$//;
3374        # Return the result.
3375        return $retVal;
3376    }
3377    
3378  =head3 Pad  =head3 Pad
3379    
3380      my $paddedString = Tracer::Pad($string, $len, $left, $padChar);      my $paddedString = Tracer::Pad($string, $len, $left, $padChar);
# Line 3201  Line 3592 
3592      return ($inserted, $deleted);      return ($inserted, $deleted);
3593  }  }
3594    
3595    =head3 Cmp
3596    
3597        my $cmp = Tracer::Cmp($a, $b);
3598    
3599    This method performs a universal sort comparison. Each value coming in is
3600    separated into a leading text part and a trailing number part. The text
3601    part is string compared, and if both parts are equal, then the number
3602    parts are compared numerically. A stream of just numbers or a stream of
3603    just strings will sort correctly, and a mixed stream will sort with the
3604    numbers first. Strings with a label and a number will sort in the
3605    expected manner instead of lexically.
3606    
3607    =over 4
3608    
3609    =item a
3610    
3611    First item to compare.
3612    
3613    =item b
3614    
3615    Second item to compare.
3616    
3617    =item RETURN
3618    
3619    Returns a negative number if the first item should sort first (is less), a positive
3620    number if the first item should sort second (is greater), and a zero if the items are
3621    equal.
3622    
3623    =back
3624    
3625    =cut
3626    
3627    sub Cmp {
3628        # Get the parameters.
3629        my ($a, $b) = @_;
3630        # Declare the return value.
3631        my $retVal;
3632        # Check for nulls.
3633        if (! defined($a)) {
3634            $retVal = (! defined($b) ? 0 : -1);
3635        } elsif (! defined($b)) {
3636            $retVal = 1;
3637        } else {
3638            # Here we have two real values. Parse the two strings.
3639            my $aParsed = _Parse($a);
3640            my $bParsed = _Parse($b);
3641            # Compare the string parts insensitively.
3642            $retVal = (lc $aParsed->[0] cmp lc $bParsed->[0]);
3643            # If they're equal, compare them sensitively.
3644            if (! $retVal) {
3645                $retVal = ($aParsed->[0] cmp $bParsed->[0]);
3646            }
3647            # If they're STILL equal, compare the number parts.
3648            if (! $retVal) {
3649                $retVal = $aParsed->[1] <=> $bParsed->[1];
3650            }
3651        }
3652        # Return the result.
3653        return $retVal;
3654    }
3655    
3656    # This method parses an input string into a string part and a number part.
3657    sub _Parse {
3658        my ($string) = @_;
3659        my ($alpha, $num);
3660        if ($string =~ /^(.*?)(\d+(?:\.\d+)?)$/) {
3661            $alpha = $1;
3662            $num = $2;
3663        } else {
3664            $alpha = $string;
3665            $num = 0;
3666        }
3667        return [$alpha, $num];
3668    }
3669    
3670    =head3 ListEQ
3671    
3672        my $flag = Tracer::ListEQ(\@a, \@b);
3673    
3674    Return TRUE if the specified lists contain the same strings in the same
3675    order, else FALSE.
3676    
3677    =over 4
3678    
3679    =item a
3680    
3681    Reference to the first list.
3682    
3683    =item b
3684    
3685    Reference to the second list.
3686    
3687    =item RETURN
3688    
3689    Returns TRUE if the two parameters are identical string lists, else FALSE.
3690    
3691    =back
3692    
3693    =cut
3694    
3695    sub ListEQ {
3696        # Get the parameters.
3697        my ($a, $b) = @_;
3698        # Declare the return variable. Start by checking the lengths.
3699        my $n = scalar(@$a);
3700        my $retVal = ($n == scalar(@$b));
3701        # Now compare the list elements.
3702        for (my $i = 0; $retVal && $i < $n; $i++) {
3703            $retVal = ($a->[$i] eq $b->[$i]);
3704        }
3705        # Return the result.
3706        return $retVal;
3707    }
3708    
3709    =head2 CGI Script Utilities
3710    
3711    =head3 ScriptSetup (deprecated)
3712    
3713        my ($cgi, $varHash) = ScriptSetup($noTrace);
3714    
3715    Perform standard tracing and debugging setup for scripts. The value returned is
3716    the CGI object followed by a pre-built variable hash. At the end of the script,
3717    the client should call L</ScriptFinish> to output the web page.
3718    
3719    This method calls L</ETracing> to configure tracing, which allows the tracing
3720    to be configured via the emergency tracing form on the debugging control panel.
3721    Tracing will then be turned on automatically for all programs that use the L</ETracing>
3722    method, which includes every program that uses this method or L</StandardSetup>.
3723    
3724    =over 4
3725    
3726    =item noTrace (optional)
3727    
3728    If specified, tracing will be suppressed. This is useful if the script wants to set up
3729    tracing manually.
3730    
3731    =item RETURN
3732    
3733    Returns a two-element list consisting of a CGI query object and a variable hash for
3734    the output page.
3735    
3736    =back
3737    
3738    =cut
3739    
3740    sub ScriptSetup {
3741        # Get the parameters.
3742        my ($noTrace) = @_;
3743        # Get the CGI query object.
3744        my $cgi = CGI->new();
3745        # Set up tracing if it's not suppressed.
3746        ETracing($cgi) unless $noTrace;
3747        # Create the variable hash.
3748        my $varHash = { results => '' };
3749        # Return the query object and variable hash.
3750        return ($cgi, $varHash);
3751    }
3752    
3753    =head3 ScriptFinish (deprecated)
3754    
3755        ScriptFinish($webData, $varHash);
3756    
3757    Output a web page at the end of a script. Either the string to be output or the
3758    name of a template file can be specified. If the second parameter is omitted,
3759    it is assumed we have a string to be output; otherwise, it is assumed we have the
3760    name of a template file. The template should have the variable C<DebugData>
3761    specified in any form that invokes a standard script. If debugging mode is turned
3762    on, a form field will be put in that allows the user to enter tracing data.
3763    Trace messages will be placed immediately before the terminal C<BODY> tag in
3764    the output, formatted as a list.
3765    
3766    A typical standard script would loook like the following.
3767    
3768        BEGIN {
3769            # Print the HTML header.
3770            print "CONTENT-TYPE: text/html\n\n";
3771        }
3772        use Tracer;
3773        use CGI;
3774        use FIG;
3775        # ... more uses ...
3776    
3777        my ($cgi, $varHash) = ScriptSetup();
3778        eval {
3779            # ... get data from $cgi, put it in $varHash ...
3780        };
3781        if ($@) {
3782            Trace("Script Error: $@") if T(0);
3783        }
3784        ScriptFinish("Html/MyTemplate.html", $varHash);
3785    
3786    The idea here is that even if the script fails, you'll see trace messages and
3787    useful output.
3788    
3789    =over 4
3790    
3791    =item webData
3792    
3793    A string containing either the full web page to be written to the output or the
3794    name of a template file from which the page is to be constructed. If the name
3795    of a template file is specified, then the second parameter must be present;
3796    otherwise, it must be absent.
3797    
3798    =item varHash (optional)
3799    
3800    If specified, then a reference to a hash mapping variable names for a template
3801    to their values. The template file will be read into memory, and variable markers
3802    will be replaced by data in this hash reference.
3803    
3804    =back
3805    
3806    =cut
3807    
3808    sub ScriptFinish {
3809        # Get the parameters.
3810        my ($webData, $varHash) = @_;
3811        # Check for a template file situation.
3812        my $outputString;
3813        if (defined $varHash) {
3814            # Here we have a template file. We need to determine the template type.
3815            my $template;
3816            if ($FIG_Config::template_url && $webData =~ /\.php$/) {
3817                $template = "$FIG_Config::template_url/$webData";
3818            } else {
3819                $template = "<<$webData";
3820            }
3821            $outputString = PageBuilder::Build($template, $varHash, "Html");
3822        } else {
3823            # Here the user gave us a raw string.
3824            $outputString = $webData;
3825        }
3826        # Check for trace messages.
3827        if ($Destination ne "NONE" && $TraceLevel > 0) {
3828            # We have trace messages, so we want to put them at the end of the body. This
3829            # is either at the end of the whole string or at the beginning of the BODY
3830            # end-tag.
3831            my $pos = length $outputString;
3832            if ($outputString =~ m#</body>#gi) {
3833                $pos = (pos $outputString) - 7;
3834            }
3835            # If the trace messages were queued, we unroll them. Otherwise, we display the
3836            # destination.
3837            my $traceHtml;
3838            if ($Destination eq "QUEUE") {
3839                $traceHtml = QTrace('Html');
3840            } elsif ($Destination =~ /^>>(.+)$/) {
3841                # Here the tracing output it to a file. We code it as a hyperlink so the user
3842                # can copy the file name into the clipboard easily.
3843                my $actualDest = $1;
3844                $traceHtml = "<p>Tracing output to $actualDest.</p>\n";
3845            } else {
3846                # Here we have one of the special destinations.
3847                $traceHtml = "<P>Tracing output type is $Destination.</p>\n";
3848            }
3849            substr $outputString, $pos, 0, $traceHtml;
3850        }
3851        # Write the output string.
3852        print $outputString;
3853    }
3854    
3855  =head3 GenerateURL  =head3 GenerateURL
3856    
3857      my $queryUrl = Tracer::GenerateURL($page, %parameters);      my $queryUrl = Tracer::GenerateURL($page, %parameters);
# Line 3335  Line 3986 
3986      return $retVal;      return $retVal;
3987  }  }
3988    
 =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;  
 }  
   
   
3989  =head3 TrackingCode  =head3 TrackingCode
3990    
3991      my $html = Tracer::TrackingCode();      my $html = Tracer::TrackingCode();
# Line 3424  Line 4016 
4016      return $retVal;      return $retVal;
4017  }  }
4018    
4019    =head3 Clean
4020    
4021        my $cleaned = Tracer::Clean($string);
4022    
4023    Clean up a string for HTML display. This not only converts special
4024    characters to HTML entity names, it also removes control characters.
4025    
4026    =over 4
4027    
4028    =item string
4029    
4030    String to convert.
4031    
4032    =item RETURN
4033    
4034    Returns the input string with anything that might disrupt an HTML literal removed. An
4035    undefined value will be converted to an empty string.
4036    
4037    =back
4038    
4039    =cut
4040    
4041    sub Clean {
4042        # Get the parameters.
4043        my ($string) = @_;
4044        # Declare the return variable.
4045        my $retVal = "";
4046        # Only proceed if the value exists.
4047        if (defined $string) {
4048            # Get the string.
4049            $retVal = $string;
4050            # Clean the control characters.
4051            $retVal =~ tr/\x00-\x1F/?/;
4052            # Escape the rest.
4053            $retVal = CGI::escapeHTML($retVal);
4054        }
4055        # Return the result.
4056        return $retVal;
4057    }
4058    
4059    =head3 SortByValue
4060    
4061        my @keys = Tracer::SortByValue(\%hash);
4062    
4063    Get a list of hash table keys sorted by hash table values.
4064    
4065    =over 4
4066    
4067    =item hash
4068    
4069    Hash reference whose keys are to be extracted.
4070    
4071    =item RETURN
4072    
4073    Returns a list of the hash keys, ordered so that the corresponding hash values
4074    are in alphabetical sequence.
4075    
4076    =back
4077    
4078    =cut
4079    
4080    sub SortByValue {
4081        # Get the parameters.
4082        my ($hash) = @_;
4083        # Sort the hash's keys using the values.
4084        my @retVal = sort { Cmp($hash->{$a}, $hash->{$b}) } keys %$hash;
4085        # Return the result.
4086        return @retVal;
4087    }
4088    
4089    =head3 GetSet
4090    
4091        my $value = Tracer::GetSet($object, $name => $newValue);
4092    
4093    Get or set the value of an object field. The object is treated as an
4094    ordinary hash reference. If a new value is specified, it is stored in the
4095    hash under the specified name and then returned. If no new value is
4096    specified, the current value is returned.
4097    
4098    =over 4
4099    
4100    =item object
4101    
4102    Reference to the hash that is to be interrogated or updated.
4103    
4104    =item name
4105    
4106    Name of the field. This is the hash key.
4107    
4108    =item newValue (optional)
4109    
4110    New value to be stored in the field. If no new value is specified, the current
4111    value of the field is returned.
4112    
4113    =item RETURN
4114    
4115    Returns the value of the named field in the specified hash.
4116    
4117    =back
4118    
4119    =cut
4120    
4121    sub GetSet {
4122        # Get the parameters.
4123        my ($object, $name, $newValue) = @_;
4124        # Is a new value specified?
4125        if (defined $newValue) {
4126            # Yes, so store it.
4127            $object->{$name} = $newValue;
4128        }
4129        # Return the result.
4130        return $object->{$name};
4131    }
4132    
4133  1;  1;

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

MCS Webmaster
ViewVC Help
Powered by ViewVC 1.0.3