[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.103, Fri May 9 04:21:45 2008 UTC revision 1.129, Tue Jan 5 17:25:48 2010 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 Warn);  
     @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 38  Line 38 
38      use Time::Local;      use Time::Local;
39      use POSIX qw(strftime);      use POSIX qw(strftime);
40      use Time::Zone;      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
# Line 208  Line 210 
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  my $SavedCGI;               # CGI object passed to ETracing
213    my $CommandLine;            # Command line passed to StandardSetup
214    my $Confessions = 0;        # confession count
215  umask 2;                    # Fix the damn umask so everything is group-writable.  umask 2;                    # Fix the damn umask so everything is group-writable.
216    
217  =head2 Tracing Methods  =head2 Tracing Methods
# Line 485  Line 489 
489          # Push the message into the queue.          # Push the message into the queue.
490          push @Queue, "$formatted";          push @Queue, "$formatted";
491      } elsif ($Destination eq "HTML") {      } elsif ($Destination eq "HTML") {
492          # Convert the message to HTML and write it to the standard output.          # Convert the message to HTML.
493          my $escapedMessage = CGI::escapeHTML($stripped);          my $escapedMessage = CGI::escapeHTML($stripped);
494          print "<p>$timeStamp $LastCategory $LastLevel: $escapedMessage</p>\n";          # The stuff after the first line feed should be pre-formatted.
495            my @lines = split /\s*\n/, $escapedMessage;
496            # Get the normal portion.
497            my $line1 = shift @lines;
498            print "<p>$timeStamp $LastCategory $LastLevel: $line1</p>\n";
499            if (@lines) {
500                print "<pre>" . join("\n", @lines, "</pre>");
501            }
502      } elsif ($Destination =~ m/^>>/) {      } elsif ($Destination =~ m/^>>/) {
503          # Write the trace message to an output file.          # Write the trace message to an output file.
504          open(TRACING, $Destination) || die "Tracing open for \"$Destination\" failed: $!";          open(TRACING, $Destination) || die "Tracing open for \"$Destination\" failed: $!";
505            # Lock the file.
506            flock TRACING, LOCK_EX;
507          print TRACING "$formatted\n";          print TRACING "$formatted\n";
508          close TRACING;          close TRACING;
509          # 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 500  Line 513 
513      }      }
514  }  }
515    
516    =head3 MemTrace
517    
518        MemTrace($message);
519    
520    Output a trace message that includes memory size information.
521    
522    =over 4
523    
524    =item message
525    
526    Message to display. The message will be followed by a sentence about the memory size.
527    
528    =back
529    
530    =cut
531    
532    sub MemTrace {
533        # Get the parameters.
534        my ($message) = @_;
535        my $memory = GetMemorySize();
536        Trace("$message $memory in use.");
537    }
538    
539    
540    =head3 TraceDump
541    
542        TraceDump($title, $object);
543    
544    Dump an object to the trace log. This method simply calls the C<Dumper>
545    function, but routes the output to the trace log instead of returning it
546    as a string. The output is arranged so that it comes out monospaced when
547    it appears in an HTML trace dump.
548    
549    =over 4
550    
551    =item title
552    
553    Title to give to the object being dumped.
554    
555    =item object
556    
557    Reference to a list, hash, or object to dump.
558    
559    =back
560    
561    =cut
562    
563    sub TraceDump {
564        # Get the parameters.
565        my ($title, $object) = @_;
566        # Trace the object.
567        Trace("Object dump for $title:\n" . Dumper($object));
568    }
569    
570  =head3 T  =head3 T
571    
572      my $switch = T($category, $traceLevel);      my $switch = T($category, $traceLevel);
# Line 642  Line 709 
709      # Set up the category and level.      # Set up the category and level.
710      $LastCategory = "(confess)";      $LastCategory = "(confess)";
711      $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.");  
             }  
         }  
     }  
712      # Trace the call stack.      # Trace the call stack.
713      Cluck($message);      Cluck($message);
714        # Increment the confession count.
715        $Confessions++;
716      # Abort the program.      # Abort the program.
717      croak(">>> $message");      croak(">>> $message");
718  }  }
719    
720    =head3 Confessions
721    
722        my $count = Tracer::Confessions();
723    
724    Return the number of calls to L</Confess> by the current task.
725    
726    =cut
727    
728    sub Confessions {
729        return $Confessions;
730    }
731    
732    
733    =head3 SaveCGI
734    
735        Tracer::SaveCGI($cgi);
736    
737    This method saves the CGI object but does not activate emergency tracing.
738    It is used to allow L</Warn> to work in situations where emergency
739    tracing is contra-indicated (e.g. the wiki).
740    
741    =over 4
742    
743    =item cgi
744    
745    Active CGI query object.
746    
747    =back
748    
749    =cut
750    
751    sub SaveCGI {
752        $SavedCGI = $_[0];
753    }
754    
755  =head3 Warn  =head3 Warn
756    
757      Warn($message);      Warn($message, @options);
758    
759  This method traces an important message. If an RSS feed is configured  This method traces an important message. If an RSS feed is configured
760  (via I<FIG_Config::error_feed>) and the tracing destination is C<WARN>,  (via I<FIG_Config::error_feed>) and the tracing destination is C<WARN>,
# Line 685  Line 777 
777    
778  Message to be traced.  Message to be traced.
779    
780    =item options
781    
782    A list containing zero or more options.
783    
784    =back
785    
786    The permissible options are as follows.
787    
788    =over 4
789    
790    =item noStack
791    
792    If specified, then the stack trace is not included in the output.
793    
794  =back  =back
795    
796  =cut  =cut
797    
798  sub Warn {  sub Warn {
799      # Get the parameters.      # Get the parameters.
800      my ($message) = @_;      my $message = shift @_;
801        my %options = map { $_ => 1 } @_;
802        # Save $@;
803        my $savedError = $@;
804      # Trace the message.      # Trace the message.
805      Trace($message);      Trace($message);
806        # This will contain the lock handle. If it's defined, it means we need to unlock.
807        my $lock;
808      # Check for feed forcing.      # Check for feed forcing.
809      my $forceFeed = exists $Categories{feed};      my $forceFeed = exists $Categories{feed};
810      # An error here would be disastrous. Note, however, that we aren't too worried      # An error here would be disastrous. Note that if debug mode is specified,
811      # about losing events. The error log is always available for the occasions where      # we do this stuff even in a test environment.
     # we mess up. Note that if debug mode is specified, we do this stuff even in a  
     # test environment.  
812      eval {      eval {
813          # Do we need to put this in the RSS feed?          # Do we need to put this in the RSS feed?
814          if ($FIG_Config::error_feed && ($Destination eq 'WARN' || $forceFeed)) {          if ($FIG_Config::error_feed && ($Destination eq 'WARN' || $forceFeed)) {
815              # Yes. We now need to compute the date, the link, and the title.              # Probably. We need to check first, however, to see if it's from an
816                # ignored IP. For non-CGI situations, we default the IP to the self-referent.
817                my $key = "127.0.0.1";
818                if (defined $SavedCGI) {
819                    # Get the IP address.
820                    $key = $ENV{HTTP_X_FORWARDED_FOR} || $ENV{REMOTE_ADDR};
821                }
822                # Is the IP address in the ignore list?
823                my $found = scalar(grep { $_ eq $key } @FIG_Config::error_ignore_ips);
824                if (! $found) {
825                    # No. We're good. We now need to compute the date, the link, and the title.
826              # First, the date, in a very specific format.              # First, the date, in a very specific format.
827              my $date = strftime("%a, %02e %b %H:%M:%S %Y ", localtime) .              my $date = strftime("%a, %02e %b %H:%M:%S %Y ", localtime) .
828                  (tz_local_offset() / 30);                  (tz_local_offset() / 30);
# Line 727  Line 846 
846              if (defined $SavedCGI) {              if (defined $SavedCGI) {
847                  # We're in a web service. The environment is the user's IP, and the link                  # We're in a web service. The environment is the user's IP, and the link
848                  # is the URL that got us here.                  # is the URL that got us here.
849                  my $key = $ENV{HTTP_X_FORWARDED_FOR} || $ENV{REMOTE_ADDR};                      $environment .= "Event Reported at IP address $key process $$.";
850                  $environment .= "Event Reported at IP address $key.";                      my $url = $SavedCGI->self_url();
                 my $url = $SavedCGI->url(-full => 1, -query => 1);  
851                  # We need the user agent string and (if available) the referrer.                  # We need the user agent string and (if available) the referrer.
852                  # The referrer will be the link.                  # The referrer will be the link.
853                  $environment .= "User Agent $ENV{HTTP_USER_AGENT}";                  $environment .= "User Agent $ENV{HTTP_USER_AGENT}";
# Line 740  Line 858 
858                      $environment .= " referrer unknown.";                      $environment .= " referrer unknown.";
859                  }                  }
860                  # Close off the sentence with the original link.                  # Close off the sentence with the original link.
861                  $environment .= " URL of error is <a href=\"$url\">$url</a>.";                      $environment .= " URL of event is <a href=\"$url\">$url</a>.";
862              } else {              } else {
863                  # No CGI object, so we're a command-line tool. Use the tracing                  # No CGI object, so we're a command-line tool. Use the tracing
864                  # key and the PID as the user identifier, and add the command.                  # key and the PID as the user identifier, and add the command.
865                  my $key = EmergencyKey();                  my $key = EmergencyKey();
866                  $environment .= "Event Reported by $key Process $$. Command $ENV{_}.";                      $environment .= "Event Reported by $key process $$.";
867                        if ($CommandLine) {
868                            # We're in a StandardSetup script, so we have the real command line.
869                            $environment .= "\n<pre>" . CGI::escapeHTML($CommandLine) . "</pre>\n";
870                        } elsif ($ENV{_}) {
871                            # We're in a BASH script, so the command has been stored in the _ variable.
872                            $environment .= "  Command = " . CGI::escapeHTML($ENV{_}) . "\n";
873                        }
874              }              }
875              # Build a GUID. We use the current time, the title, and the process ID,              # Build a GUID. We use the current time, the title, and the process ID,
876              # then digest the result.              # then digest the result.
877              my $guid = Digest::MD5::md5_base64(gettimeofday(), $title, $$);              my $guid = Digest::MD5::md5_base64(gettimeofday(), $title, $$);
878              # Finally, the description. This is a stack trace plus various environmental stuff.              # Finally, the description. This is a stack trace plus various environmental stuff.
879              my $stackTrace = "";                  # The trace is optional.
880                    my $stackTrace;
881                    if ($options{noStack}) {
882                        $stackTrace = "";
883                    } else {
884              my @trace = LongMess();              my @trace = LongMess();
885              # Only proceed if we got something back.              # Only proceed if we got something back.
886              if (scalar(@trace) > 0) {              if (scalar(@trace) > 0) {
887                  $trace[0] =~ s/Tracer::Warn.+?called/Event occurred/;                  $trace[0] =~ s/Tracer::Warn.+?called/Event occurred/;
888                  $stackTrace = "Stack trace:<pre>" . join("\n", @trace, "</pre>");                  $stackTrace = "Stack trace:<pre>" . join("\n", @trace, "</pre>");
889              }              }
890                    }
891              # We got the stack trace. Now it's time to put it all together.              # We got the stack trace. Now it's time to put it all together.
892              # We have a goofy thing here in that we need to HTML-escape some sections of the description              # We have a goofy thing here in that we need to HTML-escape some sections of the description
893              # twice. They will be escaped once here, and then once when written by XML::Simple. They are              # twice. They will be escaped once here, and then once when written by XML::Simple. They are
# Line 779  Line 909 
909              my $rss;              my $rss;
910              # Get the name of the RSS file. It's in the FIG temporary directory.              # Get the name of the RSS file. It's in the FIG temporary directory.
911              my $fileName = "$FIG_Config::temp/$FIG_Config::error_feed";              my $fileName = "$FIG_Config::temp/$FIG_Config::error_feed";
912                    # Open the config file and lock it.
913                    $lock = Open(undef, "<$FIG_Config::fig_disk/config/FIG_Config.pm");
914                    flock $lock, LOCK_EX;
915              # Does it exist?              # Does it exist?
916              if (-s $fileName) {              if (-s $fileName) {
917                  # Slurp it in.                  # Slurp it in.
# Line 811  Line 944 
944              unshift @{$items}, $newItem;              unshift @{$items}, $newItem;
945              # Create the XML. Note we do not include the root or the declaration. XML Simple can't handle              # Create the XML. Note we do not include the root or the declaration. XML Simple can't handle
946              # the requirements for those.              # the requirements for those.
947              my $xml = XML::Simple::XMLout($rss, NoAttr => 1, RootName => undef, XmlDecl => '');                  my $xml = XML::Simple::XMLout($channel, NoAttr => 1, RootName => 'channel', XmlDecl => '');
948              # Here we put in the root and declaration. The problem is that the root has to have the version attribute              # Here we put in the root and declaration. The problem is that the root has to have the version attribute
949              # in it. So, we suppress the root and do it by hand, and that requires suppressing the declaration, too.              # in it. So, we suppress the root and do it by hand, and that requires suppressing the declaration, too.
950              $xml = "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<rss version=\"2.0\">$xml\n</rss>";              $xml = "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<rss version=\"2.0\">$xml\n</rss>";
# Line 821  Line 954 
954                  close XMLOUT;                  close XMLOUT;
955              }              }
956          }          }
957            }
958      };      };
959      if ($@) {      if ($@) {
960          # If the feed failed, we need to know why. The error will be traced, but this method will not be involved          # If the feed failed, we need to know why. The error will be traced, but this method will not be involved
# Line 828  Line 962 
962          my $error = $@;          my $error = $@;
963          Trace("Feed Error: $error") if T(Feed => 0);          Trace("Feed Error: $error") if T(Feed => 0);
964      }      }
965        # Be sure to unlock.
966        if ($lock) {
967            flock $lock, LOCK_UN;
968            undef $lock;
969        }
970        # Restore the error message.
971        $@ = $savedError;
972  }  }
973    
974    
975    
976    
977  =head3 Assert  =head3 Assert
978    
979      Assert($condition1, $condition2, ... $conditionN);      Assert($condition1, $condition2, ... $conditionN);
# Line 916  Line 1060 
1060      return @retVal;      return @retVal;
1061  }  }
1062    
 =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.  
   
 =item RETURN  
   
 Returns a two-element list consisting of a CGI query object and a variable hash for  
 the output page.  
   
 =back  
   
 =cut  
   
 sub ScriptSetup {  
     # Get the parameters.  
     my ($noTrace) = @_;  
     # Get the CGI query object.  
     my $cgi = CGI->new();  
     # Set up tracing if it's not suppressed.  
     ETracing($cgi) unless $noTrace;  
     # Create the variable hash.  
     my $varHash = { results => '' };  
     # Return the query object and variable hash.  
     return ($cgi, $varHash);  
 }  
   
1063  =head3 ETracing  =head3 ETracing
1064    
1065      ETracing($parameter);      ETracing($parameter, %options);
1066    
1067  Set up emergency tracing. Emergency tracing is tracing that is turned  Set up emergency tracing. Emergency tracing is tracing that is turned
1068  on automatically for any program that calls this method. The emergency  on automatically for any program that calls this method. The emergency
# Line 981  Line 1083 
1083  is a CGI object and emergency tracing is not on, the C<Trace> and  is a CGI object and emergency tracing is not on, the C<Trace> and
1084  C<TF> parameters will be used to determine the type of tracing.  C<TF> parameters will be used to determine the type of tracing.
1085    
1086    =item options
1087    
1088    Hash of options. The permissible options are given below.
1089    
1090    =over 8
1091    
1092    =item destType
1093    
1094    Emergency tracing destination type to use if no tracing file is found. The
1095    default is C<WARN>.
1096    
1097    =item noParms
1098    
1099    If TRUE, then display of the saved CGI parms is suppressed. The default is FALSE.
1100    
1101    =item level
1102    
1103    The trace level to use if no tracing file is found. The default is C<0>.
1104    
1105  =back  =back
1106    
1107  =cut  =cut
1108    
1109  sub ETracing {  sub ETracing {
1110      # Get the parameter.      # Get the parameter.
1111      my ($parameter) = @_;      my ($parameter, %options) = @_;
1112      # Check for CGI mode.      # Check for CGI mode.
1113      if (defined $parameter && ref $parameter eq 'CGI') {      if (defined $parameter && ref $parameter eq 'CGI') {
1114          $SavedCGI = $parameter;          $SavedCGI = $parameter;
1115      } else {      } else {
1116          $SavedCGI = undef;          $SavedCGI = undef;
1117      }      }
1118      # Default to no tracing except errors.      # Check for the noParms option.
1119      my ($tracing, $dest) = ("0", "WARN");      my $noParms = $options{noParms} || 0;
1120        # Get the default tracing information.
1121        my $tracing = $options{level} || 0;
1122        my $dest = $options{destType} || "WARN";
1123      # Check for emergency tracing.      # Check for emergency tracing.
1124      my $tkey = EmergencyKey($parameter);      my $tkey = EmergencyKey($parameter);
1125      my $emergencyFile = EmergencyFileName($tkey);      my $emergencyFile = EmergencyFileName($tkey);
1126      if (-e $emergencyFile) {      if (-e $emergencyFile && (my $stat = stat($emergencyFile))) {
1127          # We have the file. Read in the data.          # We have the file. Read in the data.
1128          my @tracing = GetFile($emergencyFile);          my @tracing = GetFile($emergencyFile);
1129          # Pull off the time limit.          # Pull off the time limit.
# Line 1007  Line 1131 
1131          # Convert it to seconds.          # Convert it to seconds.
1132          $expire *= 3600;          $expire *= 3600;
1133          # Check the file data.          # Check the file data.
         my $stat = stat($emergencyFile);  
1134          my ($now) = gettimeofday;          my ($now) = gettimeofday;
1135          if ($now - $stat->mtime > $expire) {          if ($now - $stat->mtime <= $expire) {
             # Delete the expired file.  
             unlink $emergencyFile;  
         } else {  
1136              # Emergency tracing is on. Pull off the destination and              # Emergency tracing is on. Pull off the destination and
1137              # the trace level;              # the trace level;
1138              $dest = shift @tracing;              $dest = shift @tracing;
1139              my $level = shift @tracing;              my $level = shift @tracing;
             # Convert the destination to a real tracing destination.  
             # temp directory.  
             $dest = EmergencyTracingDest($tkey, $dest);  
1140              # Insure Tracer is specified.              # Insure Tracer is specified.
1141              my %moduleHash = map { $_ => 1 } @tracing;              my %moduleHash = map { $_ => 1 } @tracing;
1142              $moduleHash{Tracer} = 1;              $moduleHash{Tracer} = 1;
1143              # Set the trace parameter.              # Set the trace parameter.
1144              $tracing = join(" ", $level, sort keys %moduleHash);              $tracing = join(" ", $level, sort keys %moduleHash);
1145          }          }
     } elsif (defined $SavedCGI) {  
         # There's no emergency tracing, but we have a CGI object, so check  
         # for tracing from the form parameters.  
         if ($SavedCGI->param('Trace')) {  
             # Here the user has requested tracing via a form.  
             $dest = ($SavedCGI->param('TF') ? ">$FIG_Config::temp/Trace$$.log" : "QUEUE");  
             $tracing = $SavedCGI->param('Trace') . " Tracer";  
         }  
1146      }      }
1147        # Convert the destination to a real tracing destination.
1148        $dest = EmergencyTracingDest($tkey, $dest);
1149      # Setup the tracing we've determined from all the stuff above.      # Setup the tracing we've determined from all the stuff above.
1150      TSetup($tracing, $dest);      TSetup($tracing, $dest);
1151      # Check to see if we're a web script.      # Check to see if we're a web script.
1152      if (defined $SavedCGI) {      if (defined $SavedCGI) {
1153          # Yes we are. Trace the form and environment data.          # Yes we are. Trace the form and environment data if it's not suppressed.
1154            if (! $noParms) {
1155          TraceParms($SavedCGI);          TraceParms($SavedCGI);
1156            }
1157          # 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
1158          # emitted by the script in its raw form.          # emitted by the script in its raw form.
1159          if (T(Raw => 3)) {          if (T(Raw => 3)) {
# Line 1275  Line 1388 
1388      # Get the parameters.      # Get the parameters.
1389      my ($cgi) = @_;      my ($cgi) = @_;
1390      if (T(CGI => 2)) {      if (T(CGI => 2)) {
1391          # 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
1392          Trace("[URL] " . $cgi->url(-relative => 1, -query => 1));          # relatively small.
1393            my $url = $cgi->url(-relative => 1, -query => 1);
1394            my $len = length($url);
1395            if ($len < 500) {
1396                Trace("[URL] $url");
1397            } elsif ($len > 2048) {
1398                Trace("[URL] URL is too long to use with GET ($len characters).");
1399            } else {
1400                Trace("[URL] URL length is $len characters.");
1401            }
1402      }      }
1403      if (T(CGI => 3)) {      if (T(CGI => 3)) {
1404          # Here we want to trace the parameter data.          # Here we want to trace the parameter data.
# Line 1351  Line 1473 
1473      }      }
1474  }  }
1475    
   
 =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;  
 }  
   
1476  =head2 Command-Line Utility Methods  =head2 Command-Line Utility Methods
1477    
1478  =head3 SendSMS  =head3 SendSMS
# Line 1682  Line 1701 
1701          -noAlias  do not expect aliases in CHANGE transactions          -noAlias  do not expect aliases in CHANGE transactions
1702          -start    start with this genome          -start    start with this genome
1703          -tblFiles output TBL files containing the corrected IDs          -tblFiles output TBL files containing the corrected IDs
1704            -forked   do not erase the trace file before tracing
1705    
1706  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
1707  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 1745  Line 1765 
1765      my ($categories, $options, $parmHelp, @argv) = @_;      my ($categories, $options, $parmHelp, @argv) = @_;
1766      # Get the default tracing key.      # Get the default tracing key.
1767      my $tkey = EmergencyKey();      my $tkey = EmergencyKey();
1768        # Save the command line.
1769        $CommandLine = join(" ", $0, map { $_ =~ /\s/ ? "\"$_\"" : $_ } @argv);
1770      # Add the tracing options.      # Add the tracing options.
1771      if (! exists $options->{trace}) {      if (! exists $options->{trace}) {
1772          $options->{trace} = ['2', "tracing level (E for emergency tracing)"];          $options->{trace} = ['2', "tracing level (E for emergency tracing)"];
1773      }      }
1774        if (! exists $options->{forked}) {
1775            $options->{forked} = [0, "keep old trace file"];
1776        }
1777      $options->{sql} = [0, "turn on SQL tracing"];      $options->{sql} = [0, "turn on SQL tracing"];
1778      $options->{help} = [0, "display command-line options"];      $options->{help} = [0, "display command-line options"];
1779      $options->{user} = [$tkey, "tracing key"];      $options->{user} = [$tkey, "tracing key"];
1780      $options->{background} = [0, "spool standard and error output"];      $options->{background} = [0, "spool standard and error output"];
1781      $options->{warn} = [0, "send errors to RSS feed"];      $options->{warn} = [0, "send errors to RSS feed"];
1782        $options->{moreTracing} = ["", "comma-delimited list of additional trace modules for debugging"];
1783      # Create a parsing hash from the options hash. The parsing hash      # Create a parsing hash from the options hash. The parsing hash
1784      # contains the default values rather than the default value      # contains the default values rather than the default value
1785      # 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 1770  Line 1796 
1796      my ($retOptions, @retParameters) = ParseCommand(\%parseOptions, @argv);      my ($retOptions, @retParameters) = ParseCommand(\%parseOptions, @argv);
1797      # Get the logfile suffix.      # Get the logfile suffix.
1798      my $suffix = $retOptions->{user};      my $suffix = $retOptions->{user};
1799      # Check for background mode.      # We'll put the trace file name in here. We need it later if background
1800      if ($retOptions->{background}) {      # mode is on.
1801          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};  
         }  
     }  
1802      # 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
1803      # wants emergency tracing.      # wants emergency tracing.
1804      if ($retOptions->{trace} eq 'E') {      if ($retOptions->{trace} eq 'E') {
# Line 1797  Line 1814 
1814          }          }
1815          # Add the default categories.          # Add the default categories.
1816          push @cats, "Tracer";          push @cats, "Tracer";
1817            # Check for more tracing groups.
1818            if ($retOptions->{moreTracing}) {
1819                push @cats, split /,/, $retOptions->{moreTracing};
1820            }
1821          # Next, we create the category string by joining the categories.          # Next, we create the category string by joining the categories.
1822          my $cats = join(" ", @cats);          my $cats = join(" ", @cats);
1823          # 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 1811  Line 1832 
1832          my $traceMode;          my $traceMode;
1833          # Verify that we can open a file in the FIG temporary directory.          # Verify that we can open a file in the FIG temporary directory.
1834          my $traceFileName = "$FIG_Config::temp/trace$suffix.log";          my $traceFileName = "$FIG_Config::temp/trace$suffix.log";
1835          if (open TESTTRACE, ">$traceFileName") {          my $traceFileSpec = ($retOptions->{forked} ? ">>$traceFileName" : ">$traceFileName");
1836            if (open TESTTRACE, "$traceFileSpec") {
1837              # Here we can trace to a file.              # Here we can trace to a file.
1838              $traceMode = ">$traceFileName";              $traceMode = ">>$traceFileName";
1839              if ($textOKFlag) {              if ($textOKFlag) {
1840                  # Echo to standard output if the text-OK flag is set.                  # Echo to standard output if the text-OK flag is set.
1841                  $traceMode = "+$traceMode";                  $traceMode = "+$traceMode";
# Line 1834  Line 1856 
1856          # Now set up the tracing.          # Now set up the tracing.
1857          TSetup("$traceLevel $cats", $traceMode);          TSetup("$traceLevel $cats", $traceMode);
1858      }      }
1859        # Check for background mode.
1860        if ($retOptions->{background}) {
1861            my $outFileName = "$FIG_Config::temp/out$suffix$$.log";
1862            my $errFileName = "$FIG_Config::temp/err$suffix$$.log";
1863            # Spool the output.
1864            open STDOUT, ">$outFileName";
1865            # If we have a trace file, trace the errors to the log. Otherwise,
1866            # spool the errors.
1867            if (defined $traceFileName) {
1868                open STDERR, "| Tracer $traceFileName";
1869            } else {
1870                open STDERR, ">$errFileName";
1871            }
1872            # Check for phone support. If we have phone support and a phone number,
1873            # we want to turn it on.
1874            if ($ENV{PHONE} && defined($FIG_Config::phone)) {
1875                $retOptions->{phone} = $ENV{PHONE};
1876            }
1877        }
1878      # 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
1879      # options and exit the program.      # options and exit the program.
1880      if ($retOptions->{help}) {      if ($retOptions->{help}) {
# Line 2014  Line 2055 
2055      }      }
2056  }  }
2057    
2058    =head3 UnparseOptions
2059    
2060        my $optionString = Tracer::UnparseOptions(\%options);
2061    
2062    Convert an option hash into a command-line string. This will not
2063    necessarily be the same text that came in, but it will nonetheless
2064    produce the same ultimate result when parsed by L</StandardSetup>.
2065    
2066    =over 4
2067    
2068    =item options
2069    
2070    Reference to a hash of options to convert into an option string.
2071    
2072    =item RETURN
2073    
2074    Returns a string that will parse to the same set of options when
2075    parsed by L</StandardSetup>.
2076    
2077    =back
2078    
2079    =cut
2080    
2081    sub UnparseOptions {
2082        # Get the parameters.
2083        my ($options) = @_;
2084        # The option segments will be put in here.
2085        my @retVal = ();
2086        # Loop through the options.
2087        for my $key (keys %$options) {
2088            # Get the option value.
2089            my $value = $options->{$key};
2090            # Only use it if it's nonempty.
2091            if (defined $value && $value ne "") {
2092                my $segment = "--$key=$value";
2093                # Quote it if necessary.
2094                if ($segment =~ /[ |<>*]/) {
2095                    $segment = '"' . $segment . '"';
2096                }
2097                # Add it to the return list.
2098                push @retVal, $segment;
2099            }
2100        }
2101        # Return the result.
2102        return join(" ", @retVal);
2103    }
2104    
2105  =head3 ParseCommand  =head3 ParseCommand
2106    
2107      my ($options, @arguments) = Tracer::ParseCommand(\%optionTable, @inputList);      my ($options, @arguments) = Tracer::ParseCommand(\%optionTable, @inputList);
# Line 2486  Line 2574 
2574          } else {          } else {
2575              @retVal = readdir $dirHandle;              @retVal = readdir $dirHandle;
2576          }          }
2577            closedir $dirHandle;
2578      } elsif (! $flag) {      } elsif (! $flag) {
2579          # Here the directory would not open and it's considered an error.          # Here the directory would not open and it's considered an error.
2580          Confess("Could not open directory $dirName.");          Confess("Could not open directory $dirName.");
# Line 2592  Line 2681 
2681  Map of search patterns to permission masks. If a directory name matches  Map of search patterns to permission masks. If a directory name matches
2682  one of the patterns, that directory and all its members and subdirectories  one of the patterns, that directory and all its members and subdirectories
2683  will be assigned the new pattern. For example, the following would  will be assigned the new pattern. For example, the following would
2684  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>.
2685    
2686      Tracer::SetPermissions($dirName, 'fig', 01664, '^tmp$' => 01777);      Tracer::SetPermissions($dirName, 'fig', 01664, '^tmp$' => 01777);
2687    
# Line 2645  Line 2734 
2734                      $match = 1;                      $match = 1;
2735                  }                  }
2736              }              }
2737              # 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
2738              # before terminating due to the match.              # before terminating due to the match.
2739              if ($match && $otherMasks[$i-1] != $mask) {              if ($match && $otherMasks[$i-1] != $mask) {
2740                  # This directory matches one of the incoming patterns, and it's                  # This directory matches one of the incoming patterns, and it's
# Line 2813  Line 2902 
2902    
2903  =head2 Other Useful Methods  =head2 Other Useful Methods
2904    
2905    =head3 IDHASH
2906    
2907        my $hash = SHTargetSearch::IDHASH(@keys);
2908    
2909    This is a dinky little method that converts a list of values to a reference
2910    to hash of values to labels. The values and labels are the same.
2911    
2912    =cut
2913    
2914    sub IDHASH {
2915        my %retVal = map { $_ => $_ } @_;
2916        return \%retVal;
2917    }
2918    
2919    =head3 Pluralize
2920    
2921        my $plural = Tracer::Pluralize($word);
2922    
2923    This is a very simple pluralization utility. It adds an C<s> at the end
2924    of the input word unless it already ends in an C<s>, in which case it
2925    adds C<es>.
2926    
2927    =over 4
2928    
2929    =item word
2930    
2931    Singular word to pluralize.
2932    
2933    =item RETURN
2934    
2935    Returns the probable plural form of the word.
2936    
2937    =back
2938    
2939    =cut
2940    
2941    sub Pluralize {
2942        # Get the parameters.
2943        my ($word) = @_;
2944        # Declare the return variable.
2945        my $retVal;
2946        if ($word =~ /s$/) {
2947            $retVal = $word . 'es';
2948        } else {
2949            $retVal = $word . 's';
2950        }
2951        # Return the result.
2952        return $retVal;
2953    }
2954    
2955    =head3 Numeric
2956    
2957        my $okFlag = Tracer::Numeric($string);
2958    
2959    Return the value of the specified string if it is numeric, or an undefined value
2960    if it is not numeric.
2961    
2962    =over 4
2963    
2964    =item string
2965    
2966    String to check.
2967    
2968    =item RETURN
2969    
2970    Returns the numeric value of the string if successful, or C<undef> if the string
2971    is not numeric.
2972    
2973    =back
2974    
2975    =cut
2976    
2977    sub Numeric {
2978        # Get the parameters.
2979        my ($string) = @_;
2980        # We'll put the value in here if we succeed.
2981        my $retVal;
2982        # Get a working copy of the string.
2983        my $copy = $string;
2984        # Trim leading and trailing spaces.
2985        $copy =~ s/^\s+//;
2986        $copy =~ s/\s+$//;
2987        # Check the result.
2988        if ($copy =~ /^[+-]?\d+$/) {
2989            $retVal = $copy;
2990        } elsif ($copy =~ /^([+-]\d+|\d*)[eE][+-]?\d+$/) {
2991            $retVal = $copy;
2992        } elsif ($copy =~ /^([+-]\d+|\d*)\.\d*([eE][+-]?\d+)?$/) {
2993            $retVal = $copy;
2994        }
2995        # Return the result.
2996        return $retVal;
2997    }
2998    
2999    
3000  =head3 ParseParm  =head3 ParseParm
3001    
3002      my $listValue = Tracer::ParseParm($string);      my $listValue = Tracer::ParseParm($string);
# Line 3055  Line 3239 
3239      return $retVal;      return $retVal;
3240  }  }
3241    
3242    =head3 In
3243    
3244        my $flag = Tracer::In($value, $min, $max);
3245    
3246    Return TRUE if the value is between the minimum and the maximum, else FALSE.
3247    
3248    =cut
3249    
3250    sub In {
3251        return ($_[0] <= $_[2] && $_[0] >= $_[1]);
3252    }
3253    
3254    
3255  =head3 Constrain  =head3 Constrain
3256    
3257      my $constrained = Constrain($value, $min, $max);      my $constrained = Constrain($value, $min, $max);
# Line 3166  Line 3363 
3363      return $retVal;      return $retVal;
3364  }  }
3365    
   
3366  =head3 Strip  =head3 Strip
3367    
3368      my $string = Tracer::Strip($line);      my $string = Tracer::Strip($line);
# Line 3199  Line 3395 
3395      return $retVal;      return $retVal;
3396  }  }
3397    
3398    =head3 Trim
3399    
3400        my $string = Tracer::Trim($line);
3401    
3402    Trim all spaces from the beginning and ending of a string.
3403    
3404    =over 4
3405    
3406    =item line
3407    
3408    Line of text to be trimmed.
3409    
3410    =item RETURN
3411    
3412    The same line of text with all whitespace chopped off either end.
3413    
3414    =back
3415    
3416    =cut
3417    
3418    sub Trim {
3419        # Get a copy of the parameter string.
3420        my ($string) = @_;
3421        my $retVal = (defined $string ? $string : "");
3422        # Strip the front spaces.
3423        $retVal =~ s/^\s+//;
3424        # Strip the back spaces.
3425        $retVal =~ s/\s+$//;
3426        # Return the result.
3427        return $retVal;
3428    }
3429    
3430  =head3 Pad  =head3 Pad
3431    
3432      my $paddedString = Tracer::Pad($string, $len, $left, $padChar);      my $paddedString = Tracer::Pad($string, $len, $left, $padChar);
# Line 3260  Line 3488 
3488      return $retVal;      return $retVal;
3489  }  }
3490    
3491    =head3 Quoted
3492    
3493        my $string = Tracer::Quoted($var);
3494    
3495    Convert the specified value to a string and enclose it in single quotes.
3496    If it's undefined, the string C<undef> in angle brackets will be used
3497    instead.
3498    
3499    =over 4
3500    
3501    =item var
3502    
3503    Value to quote.
3504    
3505    =item RETURN
3506    
3507    Returns a string enclosed in quotes, or an indication the value is undefined.
3508    
3509    =back
3510    
3511    =cut
3512    
3513    sub Quoted {
3514        # Get the parameters.
3515        my ($var) = @_;
3516        # Declare the return variable.
3517        my $retVal;
3518        # Are we undefined?
3519        if (! defined $var) {
3520            $retVal = "<undef>";
3521        } else {
3522            # No, so convert to a string and enclose in quotes.
3523            $retVal = $var;
3524            $retVal =~ s/'/\\'/;
3525            $retVal = "'$retVal'";
3526        }
3527        # Return the result.
3528        return $retVal;
3529    }
3530    
3531  =head3 EOF  =head3 EOF
3532    
3533  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 3349  Line 3617 
3617  }  }
3618    
3619    
3620    =head3 GetMemorySize
3621    
3622        my $string = Tracer::GetMemorySize();
3623    
3624    Return a memory size string for the current process. The string will be
3625    in comma format, with a size indicator (K, M, G) at the end.
3626    
3627    =cut
3628    
3629    sub GetMemorySize {
3630        # Get the memory size from Unix.
3631        my ($retVal) = `ps h -o vsz $$`;
3632        # Remove the ending new-line.
3633        chomp $retVal;
3634        # Format and return the result.
3635        return CommaFormat($retVal) . "K";
3636    }
3637    
3638  =head3 CompareLists  =head3 CompareLists
3639    
3640      my ($inserted, $deleted) = Tracer::CompareLists(\@newList, \@oldList, $keyIndex);      my ($inserted, $deleted) = Tracer::CompareLists(\@newList, \@oldList, $keyIndex);
# Line 3416  Line 3702 
3702      return ($inserted, $deleted);      return ($inserted, $deleted);
3703  }  }
3704    
3705    =head3 Cmp
3706    
3707        my $cmp = Tracer::Cmp($a, $b);
3708    
3709    This method performs a universal sort comparison. Each value coming in is
3710    separated into a text parts and number parts. The text
3711    part is string compared, and if both parts are equal, then the number
3712    parts are compared numerically. A stream of just numbers or a stream of
3713    just strings will sort correctly, and a mixed stream will sort with the
3714    numbers first. Strings with a label and a number will sort in the
3715    expected manner instead of lexically. Undefined values sort last.
3716    
3717    =over 4
3718    
3719    =item a
3720    
3721    First item to compare.
3722    
3723    =item b
3724    
3725    Second item to compare.
3726    
3727    =item RETURN
3728    
3729    Returns a negative number if the first item should sort first (is less), a positive
3730    number if the first item should sort second (is greater), and a zero if the items are
3731    equal.
3732    
3733    =back
3734    
3735    =cut
3736    
3737    sub Cmp {
3738        # Get the parameters.
3739        my ($a, $b) = @_;
3740        # Declare the return value.
3741        my $retVal;
3742        # Check for nulls.
3743        if (! defined($a)) {
3744            $retVal = (! defined($b) ? 0 : -1);
3745        } elsif (! defined($b)) {
3746            $retVal = 1;
3747        } else {
3748            # Here we have two real values. Parse the two strings.
3749            my @aParsed = _Parse($a);
3750            my @bParsed = _Parse($b);
3751            # Loop through the first string.
3752            while (! $retVal && @aParsed) {
3753                # Extract the string parts.
3754                my $aPiece = shift(@aParsed);
3755                my $bPiece = shift(@bParsed) || '';
3756                # Extract the number parts.
3757                my $aNum = shift(@aParsed);
3758                my $bNum = shift(@bParsed) || 0;
3759                # Compare the string parts insensitively.
3760                $retVal = (lc($aPiece) cmp lc($bPiece));
3761                # If they're equal, compare them sensitively.
3762                if (! $retVal) {
3763                    $retVal = ($aPiece cmp $bPiece);
3764                    # If they're STILL equal, compare the number parts.
3765                    if (! $retVal) {
3766                        $retVal = $aNum <=> $bNum;
3767                    }
3768                }
3769            }
3770        }
3771        # Return the result.
3772        return $retVal;
3773    }
3774    
3775    # This method parses an input string into a string parts alternating with
3776    # number parts.
3777    sub _Parse {
3778        # Get the incoming string.
3779        my ($string) = @_;
3780        # The pieces will be put in here.
3781        my @retVal;
3782        # Loop through as many alpha/num sets as we can.
3783        while ($string =~ /^(\D*)(\d+)(.*)/) {
3784            # Push the alpha and number parts into the return string.
3785            push @retVal, $1, $2;
3786            # Save the residual.
3787            $string = $3;
3788        }
3789        # If there's still stuff left, add it to the end with a trailing
3790        # zero.
3791        if ($string) {
3792            push @retVal, $string, 0;
3793        }
3794        # Return the list.
3795        return @retVal;
3796    }
3797    
3798    =head3 ListEQ
3799    
3800        my $flag = Tracer::ListEQ(\@a, \@b);
3801    
3802    Return TRUE if the specified lists contain the same strings in the same
3803    order, else FALSE.
3804    
3805    =over 4
3806    
3807    =item a
3808    
3809    Reference to the first list.
3810    
3811    =item b
3812    
3813    Reference to the second list.
3814    
3815    =item RETURN
3816    
3817    Returns TRUE if the two parameters are identical string lists, else FALSE.
3818    
3819    =back
3820    
3821    =cut
3822    
3823    sub ListEQ {
3824        # Get the parameters.
3825        my ($a, $b) = @_;
3826        # Declare the return variable. Start by checking the lengths.
3827        my $n = scalar(@$a);
3828        my $retVal = ($n == scalar(@$b));
3829        # Now compare the list elements.
3830        for (my $i = 0; $retVal && $i < $n; $i++) {
3831            $retVal = ($a->[$i] eq $b->[$i]);
3832        }
3833        # Return the result.
3834        return $retVal;
3835    }
3836    
3837    =head2 CGI Script Utilities
3838    
3839    =head3 ScriptSetup (deprecated)
3840    
3841        my ($cgi, $varHash) = ScriptSetup($noTrace);
3842    
3843    Perform standard tracing and debugging setup for scripts. The value returned is
3844    the CGI object followed by a pre-built variable hash. At the end of the script,
3845    the client should call L</ScriptFinish> to output the web page.
3846    
3847    This method calls L</ETracing> to configure tracing, which allows the tracing
3848    to be configured via the emergency tracing form on the debugging control panel.
3849    Tracing will then be turned on automatically for all programs that use the L</ETracing>
3850    method, which includes every program that uses this method or L</StandardSetup>.
3851    
3852    =over 4
3853    
3854    =item noTrace (optional)
3855    
3856    If specified, tracing will be suppressed. This is useful if the script wants to set up
3857    tracing manually.
3858    
3859    =item RETURN
3860    
3861    Returns a two-element list consisting of a CGI query object and a variable hash for
3862    the output page.
3863    
3864    =back
3865    
3866    =cut
3867    
3868    sub ScriptSetup {
3869        # Get the parameters.
3870        my ($noTrace) = @_;
3871        # Get the CGI query object.
3872        my $cgi = CGI->new();
3873        # Set up tracing if it's not suppressed.
3874        ETracing($cgi) unless $noTrace;
3875        # Create the variable hash.
3876        my $varHash = { results => '' };
3877        # Return the query object and variable hash.
3878        return ($cgi, $varHash);
3879    }
3880    
3881    =head3 ScriptFinish (deprecated)
3882    
3883        ScriptFinish($webData, $varHash);
3884    
3885    Output a web page at the end of a script. Either the string to be output or the
3886    name of a template file can be specified. If the second parameter is omitted,
3887    it is assumed we have a string to be output; otherwise, it is assumed we have the
3888    name of a template file. The template should have the variable C<DebugData>
3889    specified in any form that invokes a standard script. If debugging mode is turned
3890    on, a form field will be put in that allows the user to enter tracing data.
3891    Trace messages will be placed immediately before the terminal C<BODY> tag in
3892    the output, formatted as a list.
3893    
3894    A typical standard script would loook like the following.
3895    
3896        BEGIN {
3897            # Print the HTML header.
3898            print "CONTENT-TYPE: text/html\n\n";
3899        }
3900        use Tracer;
3901        use CGI;
3902        use FIG;
3903        # ... more uses ...
3904    
3905        my ($cgi, $varHash) = ScriptSetup();
3906        eval {
3907            # ... get data from $cgi, put it in $varHash ...
3908        };
3909        if ($@) {
3910            Trace("Script Error: $@") if T(0);
3911        }
3912        ScriptFinish("Html/MyTemplate.html", $varHash);
3913    
3914    The idea here is that even if the script fails, you'll see trace messages and
3915    useful output.
3916    
3917    =over 4
3918    
3919    =item webData
3920    
3921    A string containing either the full web page to be written to the output or the
3922    name of a template file from which the page is to be constructed. If the name
3923    of a template file is specified, then the second parameter must be present;
3924    otherwise, it must be absent.
3925    
3926    =item varHash (optional)
3927    
3928    If specified, then a reference to a hash mapping variable names for a template
3929    to their values. The template file will be read into memory, and variable markers
3930    will be replaced by data in this hash reference.
3931    
3932    =back
3933    
3934    =cut
3935    
3936    sub ScriptFinish {
3937        # Get the parameters.
3938        my ($webData, $varHash) = @_;
3939        # Check for a template file situation.
3940        my $outputString;
3941        if (defined $varHash) {
3942            # Here we have a template file. We need to determine the template type.
3943            my $template;
3944            if ($FIG_Config::template_url && $webData =~ /\.php$/) {
3945                $template = "$FIG_Config::template_url/$webData";
3946            } else {
3947                $template = "<<$webData";
3948            }
3949            $outputString = PageBuilder::Build($template, $varHash, "Html");
3950        } else {
3951            # Here the user gave us a raw string.
3952            $outputString = $webData;
3953        }
3954        # Check for trace messages.
3955        if ($Destination ne "NONE" && $TraceLevel > 0) {
3956            # We have trace messages, so we want to put them at the end of the body. This
3957            # is either at the end of the whole string or at the beginning of the BODY
3958            # end-tag.
3959            my $pos = length $outputString;
3960            if ($outputString =~ m#</body>#gi) {
3961                $pos = (pos $outputString) - 7;
3962            }
3963            # If the trace messages were queued, we unroll them. Otherwise, we display the
3964            # destination.
3965            my $traceHtml;
3966            if ($Destination eq "QUEUE") {
3967                $traceHtml = QTrace('Html');
3968            } elsif ($Destination =~ /^>>(.+)$/) {
3969                # Here the tracing output it to a file. We code it as a hyperlink so the user
3970                # can copy the file name into the clipboard easily.
3971                my $actualDest = $1;
3972                $traceHtml = "<p>Tracing output to $actualDest.</p>\n";
3973            } else {
3974                # Here we have one of the special destinations.
3975                $traceHtml = "<P>Tracing output type is $Destination.</p>\n";
3976            }
3977            substr $outputString, $pos, 0, $traceHtml;
3978        }
3979        # Write the output string.
3980        print $outputString;
3981    }
3982    
3983  =head3 GenerateURL  =head3 GenerateURL
3984    
3985      my $queryUrl = Tracer::GenerateURL($page, %parameters);      my $queryUrl = Tracer::GenerateURL($page, %parameters);
# Line 3550  Line 4114 
4114      return $retVal;      return $retVal;
4115  }  }
4116    
 =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;  
 }  
   
   
4117  =head3 TrackingCode  =head3 TrackingCode
4118    
4119      my $html = Tracer::TrackingCode();      my $html = Tracer::TrackingCode();
# Line 3639  Line 4144 
4144      return $retVal;      return $retVal;
4145  }  }
4146    
4147    =head3 Clean
4148    
4149        my $cleaned = Tracer::Clean($string);
4150    
4151    Clean up a string for HTML display. This not only converts special
4152    characters to HTML entity names, it also removes control characters.
4153    
4154    =over 4
4155    
4156    =item string
4157    
4158    String to convert.
4159    
4160    =item RETURN
4161    
4162    Returns the input string with anything that might disrupt an HTML literal removed. An
4163    undefined value will be converted to an empty string.
4164    
4165    =back
4166    
4167    =cut
4168    
4169    sub Clean {
4170        # Get the parameters.
4171        my ($string) = @_;
4172        # Declare the return variable.
4173        my $retVal = "";
4174        # Only proceed if the value exists.
4175        if (defined $string) {
4176            # Get the string.
4177            $retVal = $string;
4178            # Clean the control characters.
4179            $retVal =~ tr/\x00-\x1F/?/;
4180            # Escape the rest.
4181            $retVal = CGI::escapeHTML($retVal);
4182        }
4183        # Return the result.
4184        return $retVal;
4185    }
4186    
4187    =head3 SortByValue
4188    
4189        my @keys = Tracer::SortByValue(\%hash);
4190    
4191    Get a list of hash table keys sorted by hash table values.
4192    
4193    =over 4
4194    
4195    =item hash
4196    
4197    Hash reference whose keys are to be extracted.
4198    
4199    =item RETURN
4200    
4201    Returns a list of the hash keys, ordered so that the corresponding hash values
4202    are in alphabetical sequence.
4203    
4204    =back
4205    
4206    =cut
4207    
4208    sub SortByValue {
4209        # Get the parameters.
4210        my ($hash) = @_;
4211        # Sort the hash's keys using the values.
4212        my @retVal = sort { Cmp($hash->{$a}, $hash->{$b}) } keys %$hash;
4213        # Return the result.
4214        return @retVal;
4215    }
4216    
4217    =head3 GetSet
4218    
4219        my $value = Tracer::GetSet($object, $name => $newValue);
4220    
4221    Get or set the value of an object field. The object is treated as an
4222    ordinary hash reference. If a new value is specified, it is stored in the
4223    hash under the specified name and then returned. If no new value is
4224    specified, the current value is returned.
4225    
4226    =over 4
4227    
4228    =item object
4229    
4230    Reference to the hash that is to be interrogated or updated.
4231    
4232    =item name
4233    
4234    Name of the field. This is the hash key.
4235    
4236    =item newValue (optional)
4237    
4238    New value to be stored in the field. If no new value is specified, the current
4239    value of the field is returned.
4240    
4241    =item RETURN
4242    
4243    Returns the value of the named field in the specified hash.
4244    
4245    =back
4246    
4247    =cut
4248    
4249    sub GetSet {
4250        # Get the parameters.
4251        my ($object, $name, $newValue) = @_;
4252        # Is a new value specified?
4253        if (defined $newValue) {
4254            # Yes, so store it.
4255            $object->{$name} = $newValue;
4256        }
4257        # Return the result.
4258        return $object->{$name};
4259    }
4260    
4261  1;  1;

Legend:
Removed from v.1.103  
changed lines
  Added in v.1.129

MCS Webmaster
ViewVC Help
Powered by ViewVC 1.0.3