[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.95, Fri Apr 18 18:06:12 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 ScriptSetup ScriptFinish Insure ChDir Emergency);  
     @EXPORT_OK = qw(GetFile GetOptions Merge MergeOptions ParseCommand ParseRecord UnEscape Escape);  
21      use strict;      use strict;
22      use Carp qw(longmess croak);      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);
27      use CGI;      use CGI;
28      use Cwd;      use Cwd;
29      use FIG_Config;      use FIG_Config;
# 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 160  Line 165 
165    
166  Sometimes, you need a way for tracing to happen automatically without putting parameters  Sometimes, you need a way for tracing to happen automatically without putting parameters
167  in a form or on the command line. Emergency tracing does this. You invoke emergency tracing  in a form or on the command line. Emergency tracing does this. You invoke emergency tracing
168  from the debug form, which is accessed from I<MySeedInstance>C</FIG/Html/SetPassword.html>.  from the debug form, which is accessed from the [[DebugConsole]]. Emergency tracing requires
169  Emergency tracing requires you specify a tracing key. For command-line tools, the key is  that you specify a tracing key. For command-line tools, the key is
170  taken from the C<TRACING> environment variable. For web services, the key is taken from  taken from the C<TRACING> environment variable. For web services, the key is taken from
171  a cookie. Either way, the key tells the tracing facility who you are, so that you control  a cookie. Either way, the key tells the tracing facility who you are, so that you control
172  the tracing in your environment without stepping on other users.  the tracing in your environment without stepping on other users.
# Line 184  Line 189 
189    
190  The web script will look for the tracing key in the cookies, and the command-line  The web script will look for the tracing key in the cookies, and the command-line
191  script will look for it in the C<TRACING> environment variable. If you are  script will look for it in the C<TRACING> environment variable. If you are
192  using the L</StandardScript> or L</StandardSetup> methods, emergency tracing  using the L</StandardSetup> method or a [[WebApplication]], emergency tracing
193  will be configured automatically.  will be configured automatically.
194    
 NOTE: to configure emergency tracing from the command line instead of the Debugging  
 Control Panel (see below), use the C<trace.pl> script.  
   
 =head3 Debugging Control Panel  
   
 The debugging control panel provides several tools to assist in development of  
 SEED and Sprout software. You access the debugging control panel from the URL  
 C</FIG/Html/SetPassword.html> in whichever seed instance you're using. (So,  
 for example, the panel access point for the development NMPDR system is  
 C<http://web-1.nmpdr.org/next/FIG/Html/SetPassword.html>. Contact Bruce to  
 find out what the password is. From this page, you can also specify a tracing  
 key. If you don't specify a key, one will be generated for you.  
   
 =head4 Emergency Tracing Form  
   
 At the bottom of the debugging control panel is a form that allows you to  
 specify a trace level and tracing categories. Special and common categories  
 are listed with check boxes. You can hold your mouse over a check box to see  
 what its category does. In general, however, a category name is the same as  
 the name of the package in which the trace message occurs.  
   
 Additional categories can be entered in an input box, delimited by spaces or commas.  
   
 The B<Activate> button turns on Emergency tracing at the level you specify with the  
 specified categories active. The B<Terminate> button turns tracing off. The  
 B<Show File> button displays the current contents of the trace file. The tracing  
 form at the bottom of the control panel is designed for emergency tracing, so it  
 will only affect programs that call L</ETracing>, L</StandardScript>,  
 or L</StandardSetup>.  
   
 =head4 Script Form  
   
 The top form of the debugging control panel allows you to enter a tiny script and  
 have the output generated in a formatted table. Certain object variables are  
 predefined in the script, including a FIG object (C<$fig>), a CGI object (C<$cgi>),  
 and-- if Sprout is active-- Sprout (C<$sprout>) and SFXlate (C<$sfx>) objects.  
   
 The last line of the script must be a scalar, but it can be a reference to a hash,  
 a list, a list of lists, and various other combinations. If you select the appropriate  
 data type in the dropdown box, the output will be formatted accordingly. The form  
 also has controls for specifying tracing. These controls override any emergency  
 tracing in effect.  
   
 =head4 Database Query Forms  
   
 The forms between the script form and the emergency tracing form allow you to  
 make queries against the database. The FIG query form allows simple queries against  
 a single FIG table. The Sprout query form uses the B<GetAll> method to do a  
 multi-table query against the Sprout database. B<GetAll> is located in the B<ERDB>  
 package, and it takes five parameters.  
   
     GetAll(\@objectNames, $filterClause, \@parameters, \@fields, $count);  
   
 Each of the five parameters corresponds to a text box on the query form:  
   
 =over 4  
   
 =item Objects  
   
 Comma-separated list containing the names of the entity and relationship objects to be retrieved.  
   
 =item Filter  
   
 WHERE/ORDER BY clause (without the WHERE) to be used to filter and sort the query. The WHERE clause can  
 be parameterized with parameter markers (C<?>). Each field used must be specified in the standard form  
 B<I<objectName>(I<fieldName>)> or B<$I<number>(I<fieldName>)> where I<fieldName> is the name of a  
 field, I<objectName> is the name of the entity or relationship object containing the field, and  
 I<number> is the 1-based position of the object in the object list. Any parameters  
 specified in the filter clause should be specified in the B<Params> field.  
 The fields in a filter clause can come from primary entity relations,  
 relationship relations, or secondary entity relations; however, all of the  
 entities and relationships involved must be included in the list of object names.  
   
 =item Params  
   
 List of the parameters to be substituted in for the parameters marks in the filter clause. This  
 is a comma-separated list without any quoting or escaping.  
   
 =item fields  
   
 Comma-separated list of the fields to be returned in each element of the list returned. Fields  
 are specified in the same manner as in the filter clause.  
   
 =item count  
   
 Maximum number of records to return. If omitted or 0, all available records will be returned.  
   
 =back  
   
 B<GetAll> automatically joins together the entities and relationships listed in the object  
 names. This simplifies the coding of the filter clause, but it means that some queries are  
 not possible, since they cannot be expressed in a linear sequence of joins. This is a limitation  
 that has yet to be addressed.  
   
195  =cut  =cut
196    
197  # Declare the configuration variables.  # Declare the configuration variables.
# Line 290  Line 201 
201                              # standard output                              # standard output
202  my %Categories = ( main => 1 );  my %Categories = ( main => 1 );
203                              # hash of active category names                              # hash of active category names
204    my @LevelNames = qw(error warn notice info detail);
205  my $TraceLevel = 0;         # trace level; a higher trace level produces more  my $TraceLevel = 0;         # trace level; a higher trace level produces more
206                              # messages                              # messages
207  my @Queue = ();             # queued list of trace messages.  my @Queue = ();             # queued list of trace messages.
208  my $LastCategory = "main";  # name of the last category interrogated  my $LastCategory = "main";  # name of the last category interrogated
209    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 366  Line 282 
282          }          }
283      }      }
284      # Now we need to process the destination information. The most important special      # Now we need to process the destination information. The most important special
285      # cases are the single ">", which requires we clear the file first, and the      # case is when we're writing to a file. This is indicated by ">" (overwrite) and
286      # "+" prefix which indicates a double echo.      # ">>" (append). A leading "+" for either indicates that we are also writing to
287        # the standard output (tee mode).
288      if ($target =~ m/^\+?>>?/) {      if ($target =~ m/^\+?>>?/) {
289          if ($target =~ m/^\+/) {          if ($target =~ m/^\+/) {
290              $TeeFlag = 1;              $TeeFlag = 1;
291              $target = substr($target, 1);              $target = substr($target, 1);
292          }          }
293          if ($target =~ m/^>[^>]/) {          if ($target =~ m/^>[^>]/) {
294                # We need to initialize the file (which clears it).
295              open TRACEFILE, $target;              open TRACEFILE, $target;
296              print TRACEFILE "[" . Now() . "] <Tracer>: Tracing initialized.\n";              print TRACEFILE "[" . Now() . "] [notice] [Tracer] Tracing initialized.\n";
297              close TRACEFILE;              close TRACEFILE;
298                # Set to append mode now that the file has been cleared.
299              $Destination = ">$target";              $Destination = ">$target";
300          } else {          } else {
301              $Destination = $target;              $Destination = $target;
# Line 408  Line 327 
327      $TraceLevel = $_[0];      $TraceLevel = $_[0];
328  }  }
329    
330  =head3 ParseTraceDate  =head3 ParseDate
331    
332        my $time = Tracer::ParseDate($dateString);
333    
334      my $time = Tracer::ParseTraceDate($dateString);  Convert a date into a PERL time number. This method expects a date-like string
335    and parses it into a number. The string must be vaguely date-like or it will
336    return an undefined value. Our requirement is that a month and day be
337    present and that three pieces of the date string (time of day, month and day,
338    year) be separated by likely delimiters, such as spaces, commas, and such-like.
339    
340  Convert a date from the trace file into a PERL timestamp.  If a time of day is present, it must be in military time with two digits for
341    everything but the hour.
342    
343    The year must be exactly four digits.
344    
345    Additional stuff can be in the string. We presume it's time zones or weekdays or something
346    equally innocuous. This means, however, that a sufficiently long sentence with date-like
347    parts in it may be interpreted as a date. Hopefully this will not be a problem.
348    
349    It should be guaranteed that this method will parse the output of the L</Now> function.
350    
351    The parameters are as follows.
352    
353  =over 4  =over 4
354    
355  =item dateString  =item dateString
356    
357  The date string from the trace file. The format of the string is determined by the  The date string to convert.
 L</Now> method.  
358    
359  =item RETURN  =item RETURN
360    
361  Returns a PERL time, that is, a number of seconds since the epoch, or C<undef> if  Returns a PERL time, that is, a number of seconds since the epoch, or C<undef> if
362  the time string is invalid.  the date string is invalid. A valid date string must contain a month and day.
363    
364  =back  =back
365    
366  =cut  =cut
367    
368  sub ParseTraceDate {  # Universal month conversion table.
369    use constant MONTHS => {    Jan =>  0, January   =>  0, '01' =>  0,  '1' =>  0,
370                                Feb =>  1, February  =>  1, '02' =>  1,  '2' =>  1,
371                                Mar =>  2, March     =>  2, '03' =>  2,  '3' =>  2,
372                                Apr =>  3, April     =>  3, '04' =>  3,  '4' =>  3,
373                                May =>  4, May       =>  4, '05' =>  4,  '5' =>  4,
374                                Jun =>  5, June      =>  5, '06' =>  5,  '6' =>  5,
375                                Jul =>  6, July      =>  6, '07' =>  6,  '7' =>  6,
376                                Aug =>  7, August    =>  7, '08' =>  7,  '8' =>  7,
377                                Sep =>  8, September =>  8, '09' =>  8,  '9' =>  8,
378                                Oct =>  9, October  =>   9, '10' =>  9,
379                                Nov => 10, November =>  10, '11' => 10,
380                                Dec => 11, December =>  11, '12' => 11
381                            };
382    
383    sub ParseDate {
384      # Get the parameters.      # Get the parameters.
385      my ($dateString) = @_;      my ($dateString) = @_;
386      # Declare the return variable.      # Declare the return variable.
387      my $retVal;      my $retVal;
388      # Parse the date.      # Find the month and day of month. There are two ways that can happen. We check for the
389      if ($dateString =~ m#(\d+)/(\d+)/(\d+)\s+(\d+):(\d+):(\d+)#) {      # numeric style first. That way, if the user's done something like "Sun 12/22", then we
390          # Create a time object. Note we need to convert the day, month,      # won't be fooled into thinking the month is Sunday.
391          # and year to a different base. Years count from 1900, and      if ($dateString =~ m#\b(\d{1,2})/(\d{1,2})\b# || $dateString =~ m#\b(\w+)\s(\d{1,2})\b#) {
392          # the internal month value is relocated to January = 0.          my ($mon, $mday) = (MONTHS->{$1}, $2);
393          $retVal = timelocal($6, $5, $4, $2, $1 - 1, $3 - 1900);          # Insist that the month and day are valid.
394            if (defined($mon) && $2 >= 1 && $2 <= 31) {
395                # Find the time.
396                my ($hour, $min, $sec) = (0, 0, 0);
397                if ($dateString =~ /\b(\d{1,2}):(\d{2}):(\d{2})\b/) {
398                    ($hour, $min, $sec) = ($1, $2, $3);
399                }
400                # Find the year.
401                my $year;
402                if ($dateString =~ /\b(\d{4})\b/) {
403                    $year = $1;
404                } else {
405                    # Get the default year, which is this one. Note we must convert it to
406                    # the four-digit value expected by "timelocal".
407                    (undef, undef, undef, undef, undef, $year) = localtime();
408                    $year += 1900;
409                }
410                $retVal = timelocal($sec, $min, $hour, $mday, $mon, $year);
411            }
412      }      }
413      # Return the result.      # Return the result.
414      return $retVal;      return $retVal;
# Line 489  Line 457 
457  sub Trace {  sub Trace {
458      # Get the parameters.      # Get the parameters.
459      my ($message) = @_;      my ($message) = @_;
460        # Strip off any line terminators at the end of the message. We will add
461        # new-line stuff ourselves.
462        my $stripped = Strip($message);
463        # Compute the caller information.
464        my ($callPackage, $callFile, $callLine) = caller();
465        my $callFileTitle = basename($callFile);
466        # Check the caller.
467        my $callerInfo = ($callFileTitle ne "Tracer.pm" ? " [$callFileTitle $callLine]" : "");
468      # Get the timestamp.      # Get the timestamp.
469      my $timeStamp = Now();      my $timeStamp = Now();
470      # Format the message. Note we strip off any line terminators at the end.      # Build the prefix.
471      my $prefix = "[$timeStamp] <$LastCategory>: ";      my $level = $LevelNames[$LastLevel] || "($LastLevel)";
472      my $formatted = $prefix . Strip($message);      my $prefix = "[$timeStamp] [$level] [$LastCategory]$callerInfo";
473        # Format the message.
474        my $formatted = "$prefix $stripped";
475      # Process according to the destination.      # Process according to the destination.
476      if ($Destination eq "TEXT") {      if ($Destination eq "TEXT") {
477          # Write the message to the standard output.          # Write the message to the standard output.
478          print "$formatted\n";          print "$formatted\n";
479      } elsif ($Destination eq "ERROR") {      } elsif ($Destination eq "ERROR") {
480          # Write the message to the error output.          # Write the message to the error output. Here, we want our prefix fields.
481          print STDERR "$formatted\n";          print STDERR "$formatted\n";
482        } elsif ($Destination eq "WARN") {
483            # Emit the message to the standard error output. It is presumed that the
484            # error logger will add its own prefix fields, the notable exception being
485            # the caller info.
486            print STDERR "$callerInfo$stripped\n";
487      } elsif ($Destination eq "QUEUE") {      } elsif ($Destination eq "QUEUE") {
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($message);          my $escapedMessage = CGI::escapeHTML($stripped);
493          print "<p>$timeStamp $LastCategory: $escapedMessage</p>\n";          # The stuff after the first line feed should be pre-formatted.
494      } elsif ($Destination eq "WARN") {          my @lines = split /\s*\n/, $escapedMessage;
495         # Emit the message as a warning.          # Get the normal portion.
496         carp $message;          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 523  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 576  Line 595 
595                  $category = $cats[$#cats];                  $category = $cats[$#cats];
596              }              }
597          }          }
598          # Save the category name.          # Save the category name and level.
599          $LastCategory = $category;          $LastCategory = $category;
600            $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 660  Line 681 
681  sub Confess {  sub Confess {
682      # Get the parameters.      # Get the parameters.
683      my ($message) = @_;      my ($message) = @_;
684      if (! defined($FIG_Config::no_tool_hdr)) {      # Set up the category and level.
685          # Here we have a tool header. Display its length so that the user can adjust the line numbers.      $LastCategory = "(confess)";
686          my $toolHeaderFile = "$FIG_Config::fig_disk/dist/releases/current/$FIG_Config::arch/tool_hdr";      $LastLevel = 0;
         # Only proceed if the tool header file is actually present.  
         if (-f $toolHeaderFile) {  
             my @lines = GetFile($toolHeaderFile);  
             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 725  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. Note we skip any      my @trace = LongMess();
989      # messages relating to calls into Tracer.      # Convert the trace to a series of messages.
990      for my $line (split /\s*\n/, $confession) {      for my $line (@trace) {
991          Trace($line) if ($line !~ /Tracer\.pm/);          # Replace the tab at the beginning with spaces.
992            $line =~ s/^\t/    /;
993            # Trace the line.
994            Trace($line);
995      }      }
996        # Issue a warning. This displays the event message and inserts it into the RSS error feed.
997        Warn($message);
998  }  }
999    
1000  =head3 ScriptSetup  =head3 LongMess
   
     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  
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 806  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 839  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 958  Line 1207 
1207          $retVal = ">>" . EmergencyFileTarget($tkey);          $retVal = ">>" . EmergencyFileTarget($tkey);
1208      } elsif ($myDest eq 'DUAL') {      } elsif ($myDest eq 'DUAL') {
1209          $retVal = "+>" . EmergencyFileTarget($tkey);          $retVal = "+>" . EmergencyFileTarget($tkey);
1210        } elsif ($myDest eq 'WARN') {
1211            $retVal = "WARN";
1212      }      }
1213      # Return the result.      # Return the result.
1214      return $retVal;      return $retVal;
# Line 1042  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 1085  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 1095  Line 1356 
1356              # Note we skip the Trace parameters, which are for our use only.              # Note we skip the Trace parameters, which are for our use only.
1357              if ($parmName ne 'Trace' && $parmName ne 'TF') {              if ($parmName ne 'Trace' && $parmName ne 'TF') {
1358                  my @values = $cgi->param($parmName);                  my @values = $cgi->param($parmName);
1359                  Trace("CGI: $parmName = " . join(", ", @values));                  Trace("[CGI] $parmName = " . join(", ", @values));
1360              }              }
1361          }          }
1362          # Display the request method.          # Display the request method.
# Line 1105  Line 1366 
1366      if (T(CGI => 4)) {      if (T(CGI => 4)) {
1367          # Here we want the environment data too.          # Here we want the environment data too.
1368          for my $envName (sort keys %ENV) {          for my $envName (sort keys %ENV) {
1369              Trace("ENV: $envName = $ENV{$envName}");              Trace("[ENV] $envName = $ENV{$envName}");
1370          }          }
1371      }      }
1372  }  }
# Line 1161  Line 1422 
1422      }      }
1423  }  }
1424    
1425    =head2 Command-Line Utility Methods
1426    
1427  =head3 ScriptFinish  =head3 SendSMS
   
     ScriptFinish($webData, $varHash);  
1428    
1429  Output a web page at the end of a script. Either the string to be output or the      my $msgID = Tracer::SendSMS($phoneNumber, $msg);
 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.  
1430    
1431  A typical standard script would loook like the following.  Send a text message to a phone number using Clickatell. The FIG_Config file must contain the
1432    user name, password, and API ID for the relevant account in the hash reference variable
1433    I<$FIG_Config::phone>, using the keys C<user>, C<password>, and C<api_id>. For
1434    example, if the user name is C<BruceTheHumanPet>, the password is C<silly>, and the API ID
1435    is C<2561022>, then the FIG_Config file must contain
1436    
1437      BEGIN {      $phone =  { user => 'BruceTheHumanPet',
1438          # Print the HTML header.                  password => 'silly',
1439          print "CONTENT-TYPE: text/html\n\n";                  api_id => '2561022' };
     }  
     use Tracer;  
     use CGI;  
     use FIG;  
     # ... more uses ...  
1440    
1441      my ($cgi, $varHash) = ScriptSetup();  The original purpose of this method was to insure Bruce would be notified immediately when the
1442      eval {  Sprout Load terminates. Care should be taken if you do not wish Bruce to be notified immediately
1443          # ... get data from $cgi, put it in $varHash ...  when you call this method.
     };  
     if ($@) {  
         Trace("Script Error: $@") if T(0);  
     }  
     ScriptFinish("Html/MyTemplate.html", $varHash);  
1444    
1445  The idea here is that even if the script fails, you'll see trace messages and  The message ID will be returned if successful, and C<undef> if an error occurs.
 useful output.  
1446    
1447  =over 4  =over 4
1448    
1449  =item webData  =item phoneNumber
1450    
1451  A string containing either the full web page to be written to the output or the  Phone number to receive the message, in international format. A United States phone number
1452  name of a template file from which the page is to be constructed. If the name  would be prefixed by "1". A British phone number would be prefixed by "44".
 of a template file is specified, then the second parameter must be present;  
 otherwise, it must be absent.  
1453    
1454  =item varHash (optional)  =item msg
1455    
1456  If specified, then a reference to a hash mapping variable names for a template  Message to send to the specified phone.
1457  to their values. The template file will be read into memory, and variable markers  
1458  will be replaced by data in this hash reference.  =item RETURN
1459    
1460    Returns the message ID if successful, and C<undef> if the message could not be sent.
1461    
1462  =back  =back
1463    
1464  =cut  =cut
1465    
1466  sub ScriptFinish {  sub SendSMS {
1467      # Get the parameters.      # Get the parameters.
1468      my ($webData, $varHash) = @_;      my ($phoneNumber, $msg) = @_;
1469      # Check for a template file situation.      # Declare the return variable. If we do not change it, C<undef> will be returned.
1470      my $outputString;      my $retVal;
1471      if (defined $varHash) {      # Only proceed if we have phone support.
1472          # Here we have a template file. We need to determine the template type.      if (! defined $FIG_Config::phone) {
1473          my $template;          Trace("Phone support not present in FIG_Config.") if T(1);
         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;  
 }  
   
 =head2 Command-Line Utility Methods  
   
 =head3 SendSMS  
   
     my $msgID = Tracer::SendSMS($phoneNumber, $msg);  
   
 Send a text message to a phone number using Clickatell. The FIG_Config file must contain the  
 user name, password, and API ID for the relevant account in the hash reference variable  
 I<$FIG_Config::phone>, using the keys C<user>, C<password>, and C<api_id>. For  
 example, if the user name is C<BruceTheHumanPet>, the password is C<silly>, and the API ID  
 is C<2561022>, then the FIG_Config file must contain  
   
     $phone =  { user => 'BruceTheHumanPet',  
                 password => 'silly',  
                 api_id => '2561022' };  
   
 The original purpose of this method was to insure Bruce would be notified immediately when the  
 Sprout Load terminates. Care should be taken if you do not wish Bruce to be notified immediately  
 when you call this method.  
   
 The message ID will be returned if successful, and C<undef> if an error occurs.  
   
 =over 4  
   
 =item phoneNumber  
   
 Phone number to receive the message, in international format. A United States phone number  
 would be prefixed by "1". A British phone number would be prefixed by "44".  
   
 =item msg  
   
 Message to send to the specified phone.  
   
 =item RETURN  
   
 Returns the message ID if successful, and C<undef> if the message could not be sent.  
   
 =back  
   
 =cut  
   
 sub SendSMS {  
     # Get the parameters.  
     my ($phoneNumber, $msg) = @_;  
     # Declare the return variable. If we do not change it, C<undef> will be returned.  
     my $retVal;  
     # Only proceed if we have phone support.  
     if (! defined $FIG_Config::phone) {  
         Trace("Phone support not present in FIG_Config.") if T(1);  
1474      } else {      } else {
1475          # Get the phone data.          # Get the phone data.
1476          my $parms = $FIG_Config::phone;          my $parms = $FIG_Config::phone;
# Line 1468  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 1485  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 1548  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 1572  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 1594  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 1610  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 1620  Line 1792 
1792              # Close the test file.              # Close the test file.
1793              close TESTTRACE;              close TESTTRACE;
1794          } else {          } else {
1795              # Here we can't trace to a file. We trace to the standard output if it's              # Here we can't trace to a file. Complain about this.
1796                warn "Could not open trace file $traceFileName: $!\n";
1797                # We trace to the standard output if it's
1798              # okay, and the error log otherwise.              # okay, and the error log otherwise.
1799              if ($textOKFlag) {              if ($textOKFlag) {
1800                  $traceMode = "TEXT";                  $traceMode = "TEXT";
# Line 1631  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 background mode.
1809        if ($retOptions->{background}) {
1810            my $outFileName = "$FIG_Config::temp/out$suffix$$.log";
1811            my $errFileName = "$FIG_Config::temp/err$suffix$$.log";
1812            # Spool the output.
1813            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      # Check for the "help" option. If it is specified, dump the command-line
1828      # options and exit the program.      # options and exit the program.
1829      if ($retOptions->{help}) {      if ($retOptions->{help}) {
# Line 1811  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 2389  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 2442  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 2584  Line 2824 
2824  }  }
2825    
2826    
2827    =head3 PrintLine
2828    
2829        Tracer::PrintLine($line);
2830    
2831    Print a line of text with a trailing new-line.
2832    
2833    =over 4
2834    
2835    =item line
2836    
2837    Line of text to print.
2838    
2839    =back
2840    
2841    =cut
2842    
2843    sub PrintLine {
2844        # Get the parameters.
2845        my ($line) = @_;
2846        # Print the line.
2847        print "$line\n";
2848    }
2849    
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 2624  Line 2982 
2982      return $retVal;      return $retVal;
2983  }  }
2984    
   
   
   
2985  =head3 Now  =head3 Now
2986    
2987      my $string = Tracer::Now();      my $string = Tracer::Now();
2988    
2989  Return a displayable time stamp containing the local time.  Return a displayable time stamp containing the local time. Whatever format this
2990    method produces must be parseable by L</ParseDate>.
2991    
2992  =cut  =cut
2993    
2994  sub Now {  sub Now {
2995      my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = localtime(time);      return DisplayTime(time);
2996      my $retVal = _p2($mon+1) . "/" . _p2($mday) . "/" . ($year + 1900) . " " .  }
2997    
2998    =head3 DisplayTime
2999    
3000        my $string = Tracer::DisplayTime($time);
3001    
3002    Convert a time value to a displayable time stamp. Whatever format this
3003    method produces must be parseable by L</ParseDate>.
3004    
3005    =over 4
3006    
3007    =item time
3008    
3009    Time to display, in seconds since the epoch, or C<undef> if the time is unknown.
3010    
3011    =item RETURN
3012    
3013    Returns a displayable time, or C<(n/a)> if the incoming time is undefined.
3014    
3015    =back
3016    
3017    =cut
3018    
3019    sub DisplayTime {
3020        my ($time) = @_;
3021        my $retVal = "(n/a)";
3022        if (defined $time) {
3023            my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = localtime($time);
3024            $retVal = _p2($mon+1) . "/" . _p2($mday) . "/" . ($year + 1900) . " " .
3025                   _p2($hour) . ":" . _p2($min) . ":" . _p2($sec);                   _p2($hour) . ":" . _p2($min) . ":" . _p2($sec);
3026        }
3027      return $retVal;      return $retVal;
3028  }  }
3029    
# Line 2802  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
3204    
3205        my $constrained = Constrain($value, $min, $max);
3206    
3207    Modify a numeric value to bring it to a point in between a maximum and a minimum.
3208    
3209    =over 4
3210    
3211    =item value
3212    
3213    Value to constrain.
3214    
3215    =item min (optional)
3216    
3217    Minimum permissible value. If this parameter is undefined, no minimum constraint will be applied.
3218    
3219    =item max (optional)
3220    
3221    Maximum permissible value. If this parameter is undefined, no maximum constraint will be applied.
3222    
3223    =item RETURN
3224    
3225    Returns the incoming value, constrained according to the other parameters.
3226    
3227    =back
3228    
3229    =cut
3230    
3231    sub Constrain {
3232        # Get the parameters.
3233        my ($value, $min, $max) = @_;
3234        # Declare the return variable.
3235        my $retVal = $value;
3236        # Apply the minimum constraint.
3237        if (defined $min && $retVal < $min) {
3238            $retVal = $min;
3239        }
3240        # Apply the maximum constraint.
3241        if (defined $max && $retVal > $max) {
3242            $retVal = $max;
3243        }
3244        # Return the result.
3245        return $retVal;
3246    }
3247    
3248  =head3 Min  =head3 Min
3249    
3250      my $min = Min($value1, $value2, ... $valueN);      my $min = Min($value1, $value2, ... $valueN);
# Line 2868  Line 3311 
3311      return $retVal;      return $retVal;
3312  }  }
3313    
3314  =head3 DebugMode  =head3 Strip
3315    
3316      if (Tracer::DebugMode) { ...code... }      my $string = Tracer::Strip($line);
3317    
3318  Return TRUE if debug mode has been turned on, else abort.  Strip all line terminators off a string. This is necessary when dealing with files
3319    that may have been transferred back and forth several times among different
3320    operating environments.
3321    
3322  Certain CGI scripts are too dangerous to exist in the production  =over 4
3323  environment. This method provides a simple way to prevent them  
3324  from working unless they are explicitly turned on by creating a password  =item line
3325  cookie via the B<SetPassword> script.  If debugging mode  
3326  is not turned on, an error will occur.  Line of text to be stripped.
3327    
3328    =item RETURN
3329    
3330    The same line of text with all the line-ending characters chopped from the end.
3331    
3332    =back
3333    
3334  =cut  =cut
3335    
3336  sub DebugMode {  sub Strip {
3337      # Declare the return variable.      # Get a copy of the parameter string.
3338      my $retVal = 0;      my ($string) = @_;
3339      # Check the debug configuration.      my $retVal = (defined $string ? $string : "");
3340      my $password = CGI::cookie("DebugMode");      # Strip the line terminator characters.
3341      my $encrypted = Digest::MD5::md5_hex($password);      $retVal =~ s/(\r|\n)+$//g;
3342      if ($encrypted eq "252dec43280e0c0d6a75ffcec486e61d") {      # Return the result.
         $retVal = 1;  
     } else {  
         # Here debug mode is off, so we generate an error.  
         Confess("Cannot use this facility without logging in.");  
     }  
     # Return the determination indicator.  
3343      return $retVal;      return $retVal;
3344  }  }
3345    
3346  =head3 Strip  =head3 Trim
3347    
3348      my $string = Tracer::Strip($line);      my $string = Tracer::Trim($line);
3349    
3350  Strip all line terminators off a string. This is necessary when dealing with files  Trim all spaces from the beginning and ending of a string.
 that may have been transferred back and forth several times among different  
 operating environments.  
3351    
3352  =over 4  =over 4
3353    
3354  =item line  =item line
3355    
3356  Line of text to be stripped.  Line of text to be trimmed.
3357    
3358  =item RETURN  =item RETURN
3359    
3360  The same line of text with all the line-ending characters chopped from the end.  The same line of text with all whitespace chopped off either end.
3361    
3362  =back  =back
3363    
3364  =cut  =cut
3365    
3366  sub Strip {  sub Trim {
3367      # Get a copy of the parameter string.      # Get a copy of the parameter string.
3368      my ($string) = @_;      my ($string) = @_;
3369      my $retVal = (defined $string ? $string : "");      my $retVal = (defined $string ? $string : "");
3370      # Strip the line terminator characters.      # Strip the front spaces.
3371      $retVal =~ s/(\r|\n)+$//g;      $retVal =~ s/^\s+//;
3372        # Strip the back spaces.
3373        $retVal =~ s/\s+$//;
3374      # Return the result.      # Return the result.
3375      return $retVal;      return $retVal;
3376  }  }
# Line 3147  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 3281  Line 3986 
3986      return $retVal;      return $retVal;
3987  }  }
3988    
3989  =head3 Cmp  =head3 TrackingCode
3990    
3991      my $cmp = Tracer::Cmp($a, $b);      my $html = Tracer::TrackingCode();
3992    
3993  This method performs a universal sort comparison. Each value coming in is  Returns the HTML code for doing web page traffic monitoring. If the
3994  separated into a leading text part and a trailing number part. The text  current environment is a test system, then it returns a null string;
3995  part is string compared, and if both parts are equal, then the number  otherwise, it returns a bunch of javascript containing code for turning
3996  parts are compared numerically. A stream of just numbers or a stream of  on SiteMeter and Google Analytics.
 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.  
3997    
3998  =over 4  =cut
3999    
4000  =item a  sub TrackingCode {
4001        # Declare the return variable.
4002        my $retVal = "<!-- tracking off -->";
4003        # Determine if we're in production.
4004        if ($FIG_Config::site_meter) {
4005            $retVal = <<END_HTML
4006            <!-- Site Meter -->
4007            <script type="text/javascript" src="http://s20.sitemeter.com/js/counter.js?site=s20nmpdr">
4008            </script>
4009            <noscript>
4010            <a href="http://s20.sitemeter.com/stats.asp?site=s20nmpdr" target="_top">
4011            <img src="http://s20.sitemeter.com/meter.asp?site=s20nmpdr" alt="Site Meter" border="0"/></a>
4012            </noscript>
4013            <!-- Copyright (c)2006 Site Meter -->
4014    END_HTML
4015        }
4016        return $retVal;
4017    }
4018    
4019  First item to compare.  =head3 Clean
4020    
4021  =item b      my $cleaned = Tracer::Clean($string);
4022    
4023  Second item to compare.  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  =item RETURN
4033    
4034  Returns a negative number if the first item should sort first (is less), a positive  Returns the input string with anything that might disrupt an HTML literal removed. An
4035  number if the first item should sort second (is greater), and a zero if the items are  undefined value will be converted to an empty string.
 equal.  
4036    
4037  =back  =back
4038    
4039  =cut  =cut
4040    
4041  sub Cmp {  sub Clean {
4042      # Get the parameters.      # Get the parameters.
4043      my ($a, $b) = @_;      my ($string) = @_;
4044      # Declare the return value.      # Declare the return variable.
4045      my $retVal;      my $retVal = "";
4046      # Check for nulls.      # Only proceed if the value exists.
4047      if (! defined($a)) {      if (defined $string) {
4048          $retVal = (! defined($b) ? 0 : -1);          # Get the string.
4049      } elsif (! defined($b)) {          $retVal = $string;
4050          $retVal = 1;          # Clean the control characters.
4051      } else {          $retVal =~ tr/\x00-\x1F/?/;
4052          # Here we have two real values. Parse the two strings.          # Escape the rest.
4053          $a =~ /^(\D*)(\d*)$/;          $retVal = CGI::escapeHTML($retVal);
         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];  
         }  
4054      }      }
4055      # Return the result.      # Return the result.
4056      return $retVal;      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.95  
changed lines
  Added in v.1.116

MCS Webmaster
ViewVC Help
Powered by ViewVC 1.0.3