home *** CD-ROM | disk | FTP | other *** search
/ PC Professionell 2004 December / PCpro_2004_12.ISO / files / webserver / tsw / TSW_3.4.0.exe / Apache2 / perl / Interp.pm < prev    next >
Encoding:
Perl POD Document  |  2003-12-12  |  33.5 KB  |  1,130 lines

  1. # Copyright (c) 1998-2003 by Jonathan Swartz. All rights reserved.
  2. # This program is free software; you can redistribute it and/or modify it
  3. # under the same terms as Perl itself.
  4.  
  5. package HTML::Mason::Interp;
  6.  
  7. use strict;
  8.  
  9. use Config;
  10. use File::Basename;
  11. use File::Path;
  12. use File::Spec;
  13. use HTML::Mason;
  14. use HTML::Mason::Escapes;
  15. use HTML::Mason::Request;
  16. use HTML::Mason::Resolver::File;
  17. use HTML::Mason::Tools qw(make_fh read_file taint_is_on load_pkg);
  18.  
  19. use HTML::Mason::Exceptions( abbr => [qw(param_error system_error wrong_compiler_error compilation_error error)] );
  20.  
  21. use Params::Validate qw(:all);
  22. Params::Validate::validation_options( on_fail => sub { param_error join '', @_  } );
  23.  
  24. use Class::Container;
  25. use base qw(Class::Container);
  26.  
  27. BEGIN
  28. {
  29.     # Fields that can be set in new method, with defaults
  30.     __PACKAGE__->valid_params
  31.     (
  32.      autohandler_name =>
  33.          { parse => 'string',  default => 'autohandler', type => SCALAR,
  34.            descr => "The filename to use for Mason's 'autohandler' capability" },
  35.  
  36.      code_cache_max_size =>
  37.          { parse => 'string',  default => 10*1024*1024, type => SCALAR,  # 10M
  38.            descr => "The maximum size of the component code cache, in bytes" },
  39.  
  40.      compiler =>
  41.          { isa => 'HTML::Mason::Compiler',
  42.            descr => "A Compiler object for compiling components" },
  43.  
  44.      current_time =>
  45.          { parse => 'string', default => 'real', optional => 1,
  46.            type => SCALAR, descr => "Current time (deprecated)" },
  47.  
  48.      data_dir =>
  49.          { parse => 'string', optional => 1, type => SCALAR,
  50.            descr => "A directory for storing cache files and other state information" },
  51.  
  52.          escape_flags =>
  53.          { parse => 'hash_list', optional => 1, type => HASHREF,
  54.            descr => "A list of escape flags to set (as if calling the set_escape() method" },
  55.  
  56.      static_source =>
  57.          { parse => 'boolean', default => 0, type => BOOLEAN,
  58.            descr => "When true, we only compile source files once" },
  59.  
  60.      # OBJECT cause qr// returns an object
  61.      ignore_warnings_expr =>
  62.          { parse => 'string',  type => SCALAR|OBJECT, default => qr/Subroutine .* redefined/i,
  63.            descr => "A regular expression describing Perl warning messages to ignore" },
  64.  
  65.      preloads =>
  66.          { parse => 'list', optional => 1, type => ARRAYREF,
  67.            descr => "A list of components to load immediately when creating the Interpreter" },
  68.  
  69.      resolver =>
  70.          { isa => 'HTML::Mason::Resolver',
  71.            descr => "A Resolver object for fetching components from storage" },
  72.  
  73.      use_object_files =>
  74.          { parse => 'boolean', default => 1, type => BOOLEAN,
  75.            descr => "Whether to cache component objects on disk" },
  76.     );
  77.  
  78.     __PACKAGE__->contained_objects
  79.     (
  80.      resolver => { class => 'HTML::Mason::Resolver::File',
  81.                descr => "This class is expected to return component information based on a component path" },
  82.      compiler => { class => 'HTML::Mason::Compiler::ToObject',
  83.                descr => "This class is used to translate component source into code" },
  84.      request  => { class => 'HTML::Mason::Request',
  85.                delayed => 1,
  86.                descr => "Objects returned by make_request are members of this class" },
  87.     );
  88. }
  89.  
  90. use HTML::Mason::MethodMaker
  91.     ( read_only => [ qw( autohandler_name
  92.                          code_cache
  93.                          compiler
  94.              data_dir
  95.              preloads
  96.                          static_source
  97.                          resolver
  98.                          source_cache
  99.              use_object_files
  100.                         ) ],
  101.  
  102.       read_write => [ map { [ $_ => __PACKAGE__->validation_spec->{$_} ] }
  103.               qw( code_cache_max_size
  104.               ignore_warnings_expr
  105.                          )
  106.             ],
  107.  
  108.       read_write_contained => { request =>
  109.                 [ [ autoflush => { type => BOOLEAN } ],
  110.                   [ data_cache_api => { type => SCALAR } ],
  111.                   [ data_cache_defaults => { type => HASHREF } ],
  112.                   [ dhandler_name => { type => SCALAR } ],
  113.                   [ error_format => { type => SCALAR } ],
  114.                   [ error_mode => { type => SCALAR } ],
  115.                   [ max_recurse => { type => SCALAR } ],
  116.                   [ out_method => { type => SCALARREF | CODEREF } ],
  117.                 ]
  118.                   },
  119.       );
  120.  
  121. sub new
  122. {
  123.     my $class = shift;
  124.     my $self = $class->SUPER::new(@_);
  125.  
  126.     $self->_initialize;
  127.     return $self;
  128. }
  129.  
  130. sub _initialize
  131. {
  132.     my ($self) = shift;
  133.     $self->{code_cache} = {};
  134.     $self->{code_cache_current_size} = 0;
  135.     $self->{files_written} = [];
  136.  
  137.     #
  138.     # Check that data_dir is absolute.
  139.     #
  140.     if ($self->{data_dir}) {
  141.         $self->{data_dir} = File::Spec->canonpath( $self->{data_dir} );
  142.         param_error "data_dir '$self->{data_dir}' must be an absolute directory"
  143.             unless File::Spec->file_name_is_absolute( $self->{data_dir} );
  144.     }
  145.  
  146.     #
  147.     # Create data subdirectories if necessary. mkpath will die on error.
  148.     #
  149.     if ($self->data_dir) {
  150.     foreach my $subdir ( qw(obj cache) ) {
  151.         my @newdirs = mkpath( File::Spec->catdir( $self->data_dir, $subdir ) , 0, 0775 );
  152.         $self->push_files_written(@newdirs);
  153.     }
  154.     } else {
  155.     $self->{use_object_files} = 0;
  156.     }
  157.  
  158.     #
  159.     # Preloads
  160.     #
  161.     if ($self->preloads) {
  162.     foreach my $pattern (@{$self->preloads}) {
  163.         error "preload pattern '$pattern' must be an absolute path"
  164.         unless File::Spec->file_name_is_absolute($pattern);
  165.         my @paths = $self->resolver->glob_path($pattern)
  166.         or warn "Didn't find any components for preload pattern '$pattern'";
  167.         foreach (@paths)
  168.             {
  169.                 $self->load($_)
  170.                     or error "Cannot preload component $_, found via pattern $pattern";
  171.             }
  172.     }
  173.     }
  174.  
  175.     #
  176.     # Add the escape flags (including defaults)
  177.     #
  178.     foreach ( [ h => \&HTML::Mason::Escapes::html_entities_escape ],
  179.               [ u => \&HTML::Mason::Escapes::url_escape ],
  180.             )
  181.     {
  182.         $self->set_escape(@$_);
  183.     }
  184.  
  185.     if ( my $e = delete $self->{escape_flags} )
  186.     {
  187.         while ( my ($flag, $code) = each %$e )
  188.         {
  189.             $self->set_escape( $flag => $code );
  190.         }
  191.     }
  192. }
  193.  
  194. #
  195. # Shorthand for various data subdirectories and files.
  196. #
  197. sub object_dir { my $self = shift; return $self->data_dir ? File::Spec->catdir( $self->data_dir, 'obj' ) : ''; }
  198. sub cache_dir  { my $self = shift; return $self->data_dir ? File::Spec->catdir( $self->data_dir, 'cache' ) : ''; }
  199.  
  200. #
  201. # exec is the initial entry point for executing a component
  202. # in a new request.
  203. #
  204. sub exec {
  205.     my $self = shift;
  206.     my $comp = shift;
  207.     $self->make_request(comp=>$comp, args=>\@_)->exec;
  208. }
  209.  
  210. sub make_request {
  211.     my $self = shift;
  212.  
  213.     return $self->create_delayed_object( 'request', interp => $self, @_ );
  214. }
  215.  
  216. sub comp_exists {
  217.     my ($self, $path) = @_;
  218.     return $self->resolver->get_info($path);
  219. }
  220.  
  221. #
  222. # Load <$path> into a component, possibly parsing the source and/or
  223. # caching the code. Returns a component object or undef if the
  224. # component was not found.
  225. #
  226. sub load {
  227.     my ($self, $path) = @_;
  228.     my ($maxfilemod, $objfile, $objfilemod);
  229.     my $code_cache = $self->code_cache;
  230.     my $resolver = $self->{resolver};
  231.  
  232.     #
  233.     # Path must be absolute.
  234.     #
  235.     unless (substr($path, 0, 1) eq '/') {
  236.     error "Component path given to Interp->load must be absolute (was given $path)";
  237.     }
  238.  
  239.     #
  240.     # Get source info from resolver. Cache the results in static_source mode.
  241.     #
  242.     my $source;
  243.     if ($self->static_source) {
  244.     unless (exists($self->{source_cache}{$path})) {
  245.         $self->{source_cache}{$path} = $resolver->get_info($path);
  246.     }
  247.     $source = $self->{source_cache}{$path};
  248.     } else {
  249.     $source = $resolver->get_info($path);
  250.     }
  251.  
  252.     # No component matches this path.
  253.     return unless defined $source;
  254.  
  255.     # comp_id is the unique name for the component, used for cache key
  256.     # and object file name.
  257.     my $comp_id = $source->comp_id;
  258.  
  259.     #
  260.     # Get last modified time of source.
  261.     #
  262.     my $srcmod = $source->last_modified;
  263.  
  264.     #
  265.     # If code cache contains an up to date entry for this path, use
  266.     # the cached comp.  Always use the cached comp in static_source
  267.     # mode.
  268.     #
  269.     if ( exists $code_cache->{$comp_id} &&
  270.          ( $self->static_source || $code_cache->{$comp_id}->{lastmod} >= $srcmod )
  271.        ) {
  272.         return $code_cache->{$comp_id}->{comp};
  273.     }
  274.  
  275.     if ($self->{use_object_files}) {
  276.     $objfile = $self->comp_id_to_objfile($comp_id);
  277.  
  278.     my @stat = stat $objfile;
  279.     if ( @stat && ! -f _ ) {
  280.         error "The object file '$objfile' exists but it is not a file!";
  281.     }
  282.  
  283.     if ($self->static_source) {
  284.         # No entry in the code cache so if the object file exists,
  285.         # we will use it, otherwise we must create it.  These
  286.         # values make that happen.
  287.         $objfilemod = @stat ? $srcmod : 0;
  288.     } else {
  289.         # If the object file exists, get its modification time.
  290.         # Otherwise (it doesn't exist or it is a directory) we
  291.         # must create it.
  292.         $objfilemod = @stat ? $stat[9] : 0;
  293.     }
  294.     }
  295.  
  296.     my $comp;
  297.     if ($objfile) {
  298.     #
  299.     # We are using object files.  Update object file if necessary
  300.     # and load component from there.
  301.     #
  302.     my $tries = 0;
  303.     do
  304.     {
  305.         if ($tries++ == 3) {
  306.         $self->_compilation_error( $source->friendly_name, "Could not load or recreate object file after 3 tries" );
  307.         }
  308.         if ($objfilemod < $srcmod) {
  309.         $self->compiler->compile_to_file( file => $objfile, source => $source);
  310.         }
  311.         $comp = eval { $self->eval_object_code( object_file => $objfile ) };
  312.  
  313.         if ($@) {
  314.         if (isa_mason_exception($@, 'Compilation::IncompatibleCompiler')) {
  315.             $objfilemod = 0;
  316.         } else {
  317.             $self->_compilation_error( $source->friendly_name, $@ );
  318.         }
  319.         }
  320.     } until ($comp);
  321.     } else {
  322.     #
  323.     # Not using object files. Load component directly into memory.
  324.     #
  325.     my $object_code = $source->object_code( compiler => $self->compiler );
  326.     $comp = eval { $self->eval_object_code( object_code => $object_code ) };
  327.     $self->_compilation_error( $source->friendly_name, $@ ) if $@;
  328.     }
  329.     $comp->assign_runtime_properties($self, $source);
  330.  
  331.     #
  332.     # Delete any stale cached version of this component, then
  333.     # cache it if it's small enough.
  334.     #
  335.     $self->delete_from_code_cache($comp_id);
  336.  
  337.     if ($comp->object_size <= $self->code_cache_max_elem) {
  338.     $code_cache->{$comp_id} = { lastmod => $srcmod, comp => $comp };
  339.     $self->{code_cache_current_size} += $comp->object_size;
  340.     }
  341.     return $comp;
  342. }
  343.  
  344. sub delete_from_code_cache {
  345.     my ($self, $comp) = @_;
  346.     return unless exists $self->{code_cache}{$comp};
  347.  
  348.     $self->{code_cache_current_size} -= $self->{code_cache}{$comp}{comp}->object_size;
  349.     delete $self->{code_cache}{$comp};
  350.     return;
  351. }
  352.  
  353.  
  354. sub comp_id_to_objfile {
  355.     my ($self, $comp_id) = @_;
  356.  
  357.     return File::Spec->catfile( $self->object_dir, split /\//, $comp_id );
  358. }
  359.  
  360. # User method for emptying code cache - useful for preventing memory leak
  361. sub flush_code_cache {
  362.     my $self = shift;
  363.  
  364.     $self->{code_cache} = {};
  365.     $self->{code_cache_current_size} = 0;
  366. }
  367.  
  368. #
  369. # If code cache has exceeded maximum, remove least frequently used
  370. # elements from cache until size falls below minimum.
  371. #
  372. sub purge_code_cache {
  373.     my ($self) = @_;
  374.  
  375.     if ($self->{code_cache_current_size} > $self->code_cache_max_size) {
  376.     my $code_cache = $self->{code_cache};
  377.     my $min_size = $self->code_cache_min_size;
  378.     my $decay_factor = $self->code_cache_decay_factor;
  379.  
  380.     my @elems;
  381.     while (my ($path,$href) = each(%{$code_cache})) {
  382.         push(@elems,[$path,$href->{comp}->mfu_count,$href->{comp}]);
  383.     }
  384.     @elems = sort { $a->[1] <=> $b->[1] } @elems;
  385.     while (($self->{code_cache_current_size} > $min_size) and @elems) {
  386.         $self->delete_from_code_cache(shift(@elems)->[0]);
  387.     }
  388.  
  389.     #
  390.     # Multiply each remaining cache item's count by a decay factor,
  391.     # to gradually reduce impact of old information.
  392.     #
  393.     foreach my $elem (@elems) {
  394.         $elem->[2]->mfu_count( $elem->[2]->mfu_count * $decay_factor );
  395.     }
  396.     }
  397. }
  398.  
  399. #
  400. # Construct a component on the fly.  Virtual if 'path' parameter is
  401. # given, otherwise anonymous.
  402. #
  403. sub make_component {
  404.     my $self = shift;
  405.  
  406.     my %p = validate(@_, { comp_source => { type => SCALAR, optional => 1 },
  407.                comp_file   => { type => SCALAR, optional => 1 },
  408.                name        => { type => SCALAR, optional => 1 } });
  409.  
  410.     $p{comp_source} = read_file(delete $p{comp_file}) if exists $p{comp_file};
  411.     param_error "Must specify either 'comp_source' or 'comp_file' parameter to 'make_component()'"
  412.     unless defined $p{comp_source};
  413.  
  414.     $p{name} ||= '<anonymous component>';
  415.  
  416.     my $source = HTML::Mason::ComponentSource->new( friendly_name => $p{name},
  417.                             comp_path => $p{name},
  418.                             comp_id => undef,
  419.                             last_modified => time,
  420.                             comp_class => 'HTML::Mason::Component',
  421.                             source_callback => sub { $p{comp_source} },
  422.                           );
  423.  
  424.     my $object_code = $source->object_code( compiler => $self->compiler);
  425.  
  426.     my $comp = eval { $self->eval_object_code( object_code => $object_code ) };
  427.     $self->_compilation_error( $p{name}, $@ ) if $@;
  428.  
  429.     $comp->assign_runtime_properties($self, $source);
  430.  
  431.     return $comp;
  432. }
  433.  
  434. sub set_global
  435. {
  436.     my ($self, $decl, @values) = @_;
  437.     param_error "Interp->set_global: expects a variable name and one or more values"
  438.     unless @values;
  439.     my ($prefix, $name) = ($decl =~ s/^([\$@%])//) ? ($1, $decl) : ('$', $decl);
  440.  
  441.     my $varname = sprintf("%s::%s",$self->compiler->in_package,$name);
  442.     no strict 'refs';
  443.     if ($prefix eq '$') {
  444.     $$varname = $values[0];
  445.     } elsif ($prefix eq '@') {
  446.     @$varname = @values;
  447.     } else {
  448.     %$varname = @values;
  449.     }
  450. }
  451.  
  452. sub comp_root { shift->resolver->comp_root(@_) }
  453.  
  454. sub files_written
  455. {
  456.     my $self = shift;
  457.     return @{$self->{files_written}};
  458. }
  459.  
  460. #
  461. # Push onto list of written files.
  462. #
  463. sub push_files_written
  464. {
  465.     my $self = shift;
  466.     my $fref = $self->{'files_written'};
  467.     push(@$fref,@_);
  468. }
  469.  
  470. #
  471. # Look for component <$name> starting in <$startpath> and moving upwards
  472. # to the root. Return component object or undef.
  473. #
  474. sub find_comp_upwards
  475. {
  476.     my ($self, $startpath, $name) = @_;
  477.     $startpath =~ s{/+$}{};
  478.  
  479.     # Don't use File::Spec here, this is a URL path.
  480.     do {
  481.       my $comp = $self->load("$startpath/$name");
  482.       return $comp if $comp;
  483.     } while $startpath =~ s{/+[^/]*$}{};
  484.  
  485.     return;  # Nothing found
  486. }
  487.  
  488. # Code cache parameter methods
  489.  
  490. sub code_cache_min_size { shift->code_cache_max_size * 0.75 }
  491. sub code_cache_max_elem { shift->code_cache_max_size * 0.20 }
  492. sub code_cache_decay_factor { 0.75 }
  493.  
  494.  
  495. ###################################################################
  496. # The eval_object_code & write_object_file methods used to be in
  497. # Parser.pm.  This is a temporary home only.  They need to be moved
  498. # again at some point in the future (during some sort of interp
  499. # re-architecting).
  500. ###################################################################
  501.  
  502. #
  503. # eval_object_code
  504. #   (object_code, object_file, error)
  505. # Evaluate an object file or object text.  Return a component object
  506. # or undef if error.
  507. #
  508. # I think this belongs in the resolver (or comp loader) - Dave
  509. #
  510. sub eval_object_code
  511. {
  512.     my ($self, %p) = @_;
  513.  
  514.     $self->compiler->assert_creatorship(\%p);
  515.  
  516.     #
  517.     # Evaluate object file or text with warnings on, unless
  518.     # ignore_warnings_expr is '.'.
  519.     #
  520.     my $ignore_expr = $self->ignore_warnings_expr;
  521.     my ($comp, $err);
  522.     my $warnstr = '';
  523.  
  524.     {
  525.     local $^W = $ignore_expr eq '.' ? 0 : 1;
  526.     local $SIG{__WARN__} =
  527.         ( $ignore_expr ?
  528.               ( $ignore_expr eq '.' ?
  529.                 sub { } :
  530.                 sub { $warnstr .= $_[0] if $_[0] !~ /$ignore_expr/ }
  531.               ) :
  532.           sub { $warnstr .= $_[0] } );
  533.     
  534.     $comp = $self->_do_or_eval(\%p);
  535.     }
  536.  
  537.     $err = $warnstr . $@;
  538.  
  539.     unless ($err) {
  540.     # Yes, I know I always freak out when people start poking
  541.     # around in object internals but since there is no longer a
  542.     # parser_version method in Component.pm there is no other way.
  543.     # Only pre-1.10 components have parser_version set.
  544.     wrong_compiler_error 'This object file was created by a pre-1.10 parser.  Please remove the component files in your object directory.'
  545.         if ref $comp && exists $comp->{parser_version};
  546.  
  547.     wrong_compiler_error 'This object file was created by an incompatible Compiler or Lexer.  Please remove the component files in your object directory.'
  548.         if UNIVERSAL::can( $comp, 'compiler_id' ) && $comp->compiler_id ne $self->compiler->object_id;
  549.     }
  550.  
  551.     #
  552.     # Return component or error
  553.     #
  554.     if ($err) {
  555.     # attempt to stem very long eval errors
  556.     $err =~ s/has too many errors\..+/has too many errors./s;
  557.     compilation_error $err;
  558.     } else {
  559.     return $comp;
  560.     }
  561. }
  562.  
  563. sub _do_or_eval
  564. {
  565.     my ($self, $p) = @_;
  566.  
  567.     if ($p->{object_file}) {
  568.     return do $p->{object_file};
  569.     } else {
  570.     # If in taint mode, untaint the object text
  571.     (${$p->{object_code}}) = ${$p->{object_code}} =~ /^(.*)/s if taint_is_on;
  572.  
  573.     return eval ${$p->{object_code}};
  574.     }
  575. }
  576.  
  577. sub _compilation_error {
  578.     my ($self, $filename, $err) = @_;
  579.  
  580.     HTML::Mason::Exception::Compilation->throw(error=>$err, filename=>$filename);
  581. }
  582.  
  583.  
  584. sub object_file {
  585.     my ($self, $comp) = @_;
  586.     return $comp->persistent ?
  587.     $self->comp_id_to_objfile($comp->comp_id) :
  588.     undef;
  589. }
  590.  
  591. sub use_autohandlers
  592. {
  593.     my $self = shift;
  594.     return defined $self->{autohandler_name} and length $self->{autohandler_name};
  595. }
  596.  
  597. # Generate HTML that describes Interp's current status.
  598. # This is used in things like Apache::Status reports.  Currently shows:
  599. # -- Interp properties
  600. # -- loaded (cached) components
  601. #
  602. # Note that Apache::Status has an extremely narrow URL API, and I
  603. # think the only way to pass info to another request is through
  604. # PATH_INFO.  That's why the expiration stuff is awkward.
  605. sub status_as_html {
  606.     my ($self, %p) = @_;
  607.  
  608.     # Should I be scared about this?  =)
  609.  
  610.     my $comp_source = <<'EOF';
  611. <h3>Interpreter properties:</h3>
  612. <blockquote>
  613.  <h4>Startup options:</h4>
  614.  <tt>
  615. <table width="100%">
  616. <%perl>
  617. foreach my $property (sort keys %$interp) {
  618.     my $val = $interp->{$property};
  619.  
  620.     my $default = ( defined $val && defined $valid{$property}{default} && $val eq $valid{$property}{default} ) || ( ! defined $val && exists $valid{$property}{default} && ! defined $valid{$property}{default} );
  621.  
  622.     my $display = $val;
  623.     if (ref $val) {
  624.         $display = '<font color="darkred">';
  625.         # only object can ->can, others die
  626.         my $is_object = eval { $val->can('anything'); 1 };
  627.         if ($is_object) {
  628.             $display .= ref $val . ' object';
  629.         } else {
  630.             if (UNIVERSAL::isa($val, 'ARRAY')) {
  631.                 $display .= 'ARRAY reference - [ ';
  632.                 $display .= join ', ', @$val;
  633.                 $display .= '] ';
  634.             } elsif (UNIVERSAL::isa($val, 'HASH')) {
  635.                 $display .= 'HASH reference - { ';
  636.                 my @pairs;
  637.                 while (my ($k, $v) = each %$val) {
  638.                    push @pairs, "$k => $v";
  639.                 }
  640.                 $display .= join ', ', @pairs;
  641.                 $display .= ' }';
  642.             } else {
  643.                 $display = ref $val . ' reference';
  644.             }
  645.         }
  646.         $display .= '</font>';
  647.     }
  648.  
  649.     defined $display && $display =~ s,([\x00-\x1F]),'<font color="purple">control-' . chr( ord('A') + ord($1) - 1 ) . '</font>',eg; # does this work for non-ASCII?
  650. </%perl>
  651.  <tr valign="top" cellspacing="10">
  652.   <td>
  653.     <% $property | h %>
  654.   </td>
  655.   <td>
  656.    <% defined $display ? $display : '<i>undef</i>' %>
  657.    <% $default ? '<font color=green>(default)</font>' : '' %>
  658.   </td>
  659.  </tr>
  660. % }
  661. </table>
  662.   </tt>
  663.  
  664.  <h4>Components in memory cache:</h4>
  665.  <tt>
  666. % my $cache;
  667. % if ($cache = $interp->code_cache and %$cache) {
  668. %   foreach my $key (sort keys %$cache) {
  669.       <% $key |h%> (modified <% scalar localtime $cache->{$key}->{lastmod} %>)
  670.       <br>
  671. %   }
  672. % } else {
  673.     <I>None</I>
  674. % }
  675.   </tt>
  676. </blockquote>
  677.  
  678. <%args>
  679.  $interp   # The interpreter we'll elucidate
  680.  %valid    # Default values for interp member data
  681. </%args>
  682. EOF
  683.  
  684.     my $comp = $self->make_component(comp_source => $comp_source);
  685.     my $out;
  686.  
  687.     my $args = [interp => $self, valid => $self->validation_spec];
  688.     $self->make_request(comp=>$comp, args=>$args, out_method=>\$out, %p)->exec;
  689.  
  690.     return $out;
  691. }
  692.  
  693. sub set_escape
  694. {
  695.     my $self = shift;
  696.     my %p = @_;
  697.  
  698.     while ( my ($name, $sub) = each %p )
  699.     {
  700.         my $flag_regex = $self->compiler->lexer->escape_flag_regex;
  701.  
  702.         param_error "Invalid escape name ($name)"
  703.             if $name !~ /^$flag_regex$/ || $name =~ /^n$/;
  704.  
  705.         my $coderef;
  706.         if ( ref $sub )
  707.         {
  708.             $coderef = $sub;
  709.         }
  710.         else
  711.         {
  712.             if ( $sub =~ /^\w+$/ )
  713.             {
  714.                 no strict 'refs';
  715.                 unless ( defined &{"HTML::Mason::Escapes::$sub"} )
  716.                 {
  717.                     param_error "Invalid escape: $sub (no matching subroutine in HTML::Mason::Escapes";
  718.                 }
  719.  
  720.                 $coderef = \&{"HTML::Mason::Escapes::$sub"};
  721.             }
  722.             else
  723.             {
  724.                 $coderef = eval $sub;
  725.                 param_error "Invalid escape: $sub ($@)" if $@;
  726.             }
  727.         }
  728.  
  729.         $self->{escapes}{$name} = $coderef;
  730.     }
  731. }
  732.  
  733. sub remove_escape
  734. {
  735.     my $self = shift;
  736.  
  737.     delete $self->{escapes}{ shift() };
  738. }
  739.  
  740. sub apply_escapes
  741. {
  742.     my $self = shift;
  743.     my $text = shift;
  744.  
  745.     foreach my $flag (@_)
  746.     {
  747.         param_error "Invalid escape flag: $flag"
  748.             unless exists $self->{escapes}{$flag};
  749.  
  750.         $self->{escapes}{$flag}->(\$text);
  751.     }
  752.  
  753.     return $text;
  754. }
  755.  
  756. #
  757. # Set or fetch the current time value (deprecated in 1.1x).
  758. #
  759. sub current_time {
  760.     my $self = shift;
  761.     if (@_) {
  762.     my $newtime = shift;
  763.     param_error "Interp::current_time: invalid value '$newtime' - must be 'real' or a numeric time value" if $newtime ne 'real' && $newtime !~ /^[0-9]+$/;
  764.     return $self->{current_time} = $newtime;
  765.     } else {
  766.     return $self->{current_time};
  767.     }
  768. }
  769.  
  770. 1;
  771.  
  772. __END__
  773.  
  774. =head1 NAME
  775.  
  776. HTML::Mason::Interp - Mason Component Interpreter
  777.  
  778. =head1 SYNOPSIS
  779.  
  780.     my $i = HTML::Mason::Interp->new (data_dir=>'/usr/local/mason',
  781.                                      comp_root=>'/usr/local/www/htdocs/',
  782.                                      ...other params...);
  783.  
  784. =head1 DESCRIPTION
  785.  
  786. Interp is the Mason workhorse, executing components and routing their
  787. output and errors to all the right places. In a mod_perl environment,
  788. Interp objects are handed off immediately to an ApacheHandler object
  789. which internally calls the Interp implementation methods. In that case
  790. the only user method is the new() constructor.
  791.  
  792. =head1 PARAMETERS TO THE new() CONSTRUCTOR
  793.  
  794. =over
  795.  
  796. =item autohandler_name
  797.  
  798. File name used for
  799. L<autohandlers|HTML::Mason::Devel/autohandlers>. Default is
  800. "autohandler".  If this is set to an empty string ("") then
  801. autohandlers are turned off entirely.
  802.  
  803. =item code_cache_max_size
  804.  
  805. Specifies the maximum size, in bytes, of the in-memory code cache
  806. where components are stored. Default is 10 MB. See the L<code cache|HTML::Mason::Admin/code cache> section of the administrator's manual
  807. for further details.
  808.  
  809. =item compiler
  810.  
  811. The Compiler object to associate with this Interpreter.  By default a
  812. new object of class L<compiler_class|HTML::Mason::Params/compiler_class> will be created.
  813.  
  814. =item compiler_class
  815.  
  816. The class to use when creating a compiler. Defaults to
  817. L<HTML::Mason::Compiler|HTML::Mason::Compiler>.
  818.  
  819. =item current_time
  820.  
  821. Interpreter's notion of the current time (deprecated).
  822.  
  823. =item data_dir
  824.  
  825. The data directory is a writable directory that Mason uses for various
  826. features and optimizations: for example, component object files and
  827. data cache files. Mason will create the directory on startup, if necessary, and set its
  828. permissions according to the web server User/Group.
  829.  
  830. Under L<Apache|HTML::Mason::ApacheHandler>, data_dir defaults to a
  831. directory called "mason" under the Apache server root. You will
  832. need to change this on certain systems that assign a high-level
  833. server root such as F</usr>!
  834.  
  835. In non-Apache environments, data_dir has no default. If it is left
  836. unspecified, Mason will not use L<object files|HTML::Mason::Admin/object files>, and the default
  837. L<data cache class|HTML::Mason::Request/item_cache> will be
  838. C<MemoryCache> instead of C<FileCache>.
  839.  
  840. =item escape_flags
  841.  
  842. A hash reference of escape flags to set for this object.  See the
  843. section on the L<set_escape
  844. method|HTML::Mason::Interp/item_set_escape> for more details.
  845.  
  846. =item ignore_warnings_expr
  847.  
  848. Regular expression indicating which warnings to ignore when loading
  849. components. Any warning that is not ignored will prevent the
  850. component from being loaded and executed. For example:
  851.  
  852.     ignore_warnings_expr =>
  853.         'Global symbol.*requires explicit package'
  854.  
  855. If set to undef, all warnings are heeded. If set to '.', warnings
  856. are turned off completely as a specially optimized case.
  857.  
  858. By default, this is set to 'Subroutine .* redefined'.  This allows you
  859. to declare global subroutines inside <%once> sections and not receive
  860. an error when the component is reloaded.
  861.  
  862. =item preloads
  863.  
  864. A list of component paths, optionally with glob wildcards, to load
  865. when the interpreter initializes. e.g.
  866.  
  867.     preloads => ['/foo/index.html','/bar/*.pl']
  868.  
  869. Default is the empty list.  For maximum performance, this should only
  870. be used for components that are frequently viewed and rarely updated.
  871. See the L<preloading components|HTML::Mason::Admin/preloading components> section of the administrator's manual for further details.
  872.  
  873. As mentioned in the developer's manual, a component's C<< <%once> >>
  874. section is executed when it is loaded.  For preloaded components, this
  875. means that this section will be executed before a Mason or Apache
  876. request exist, so preloading a component that uses C<$m> or C<$r> in a
  877. C<< <%once> >> section will fail.
  878.  
  879. =item request_class
  880.  
  881. The class to use when creating requests. Defaults to
  882. L<HTML::Mason::Request|HTML::Mason::Request>.
  883.  
  884. =item resolver
  885.  
  886. The Resolver object to associate with this Compiler. By default a new
  887. object of class L<resolver_class|HTML::Mason::Params/resolver_class> will be created.
  888.  
  889. =item resolver_class
  890.  
  891. The class to use when creating a resolver. Defaults to
  892. L<HTML::Mason::Resolver::File|HTML::Mason::Resolver::File>.
  893.  
  894. =item static_source
  895.  
  896. True or false, default is false. When false, Mason checks the
  897. timestamp of the component source file each time the component is used
  898. to see if it has changed. This provides the instant feedback for
  899. source changes that is expected for development.  However it does
  900. entail a file stat for each component executed.
  901.  
  902. When true, Mason assumes that the component source tree is unchanging:
  903. it will not check component source files to determine if the memory
  904. cache or object file has expired.  This can save many file stats per
  905. request. However, in order to get Mason to recognize a component
  906. source change, you must remove object files and restart the server (so
  907. as to clear the memory cache).
  908.  
  909. Use this feature for live sites where performance is crucial and
  910. where updates are infrequent and well-controlled.
  911.  
  912. =item use_object_files
  913.  
  914. True or false, default is true.  Specifies whether Mason creates
  915. object files to save the results of component parsing. You may want to
  916. turn off object files for disk space reasons, but otherwise this
  917. should be left alone.
  918.  
  919. =back
  920.  
  921. =head1 ACCESSOR METHODS
  922.  
  923. All of the above properties have standard accessor methods of the same
  924. name. In general, no arguments retrieves the value, and one argument
  925. sets and returns the value.  For example:
  926.  
  927.     my $interp = HTML::Mason::Interp->new (...);
  928.     my $c = $interp->compiler;
  929.     $interp->code_cache_max_size(20 * 1024 * 1024);
  930.  
  931. The following properties can be queried but not modified: data_dir,
  932. preloads.
  933.  
  934. =head1 ESCAPE FLAG METHODS
  935.  
  936. =over
  937.  
  938. =for html <a name="item_apply_escapes"></a>
  939.  
  940. =item apply_escapes ($text, $flags, [more flags...])
  941.  
  942. This method applies a one or more escapes to a piece of text.  The
  943. escapes are specified by giving their flag.  Each escape is applied to
  944. the text in turn, after which the now-modified text is returned.
  945.  
  946. =for html <a name="item_remove_escape"></a>
  947.  
  948. =item remove_escape ($name)
  949.  
  950. Given an escape name, this removes that escape from the interpreter's
  951. known escapes.  If the name is not recognized, it is simply ignored.
  952.  
  953. =for html <a name="item_set_escape"></a>
  954.  
  955. =item set_escape ($name => see below])
  956.  
  957. This method is called to add an escape flag to the list of known
  958. escapes for the interpreter.  The flag may only consist of the
  959. characters matching C<\w> and the dash (-).  It must start with an
  960. alpha character or an underscore (_).
  961.  
  962. The right hand side may be one of several things.  It can be a
  963. subroutine reference.  It can also be a string match C</^\w+$/>, in
  964. which case it is assumed to be the name of a subroutine in the
  965. C<HTML::Mason::Escapes> module.  Finally, if it is a string that does
  966. not match the above regex, then it is assumed to be C<eval>able code,
  967. which will return a subroutine reference.
  968.  
  969. When setting these with C<PerlSetVar> directives in an Apache
  970. configuration file, you can set them like this:
  971.  
  972.   PerlSetVar  MasonEscapeFlags  "h => \&HTML::Mason::Escapes::basic_html_escape"
  973.   PerlSetVar  MasonEscapeFlags  "flag  => \&subroutine"
  974.   PerlSetVar  MasonEscapeFlags  "uc    => sub { ${$_[0]} = uc ${$_[0]}; }"
  975.   PerlAddVar  MasonEscapeFlags  "thing => other_thing"
  976.  
  977. =back
  978.  
  979. =head1 OTHER METHODS
  980.  
  981. =over
  982.  
  983. =for html <a name="item_comp_exists"></a>
  984.  
  985. =item comp_exists (path)
  986.  
  987. Given an I<absolute> component path, this method returns a boolean
  988. value indicating whether or not a component exists for that path.
  989.  
  990. =for html <a name="item_comp_root"></a>
  991.  
  992. =item comp_root (comp_root)
  993.  
  994. This is a convenience method which simply calls the C<comp_root>
  995. method in the resolver object, which by default is in the
  996. HTML::Mason::Resolver::File class.
  997.  
  998. Obviously, if you are using a custom resolver class which does not
  999. have a C<comp_root> method, then this convenience method will not
  1000. work.
  1001.  
  1002. =for html <a name="item_exec"></a>
  1003.  
  1004. =item exec (comp, args...)
  1005.  
  1006. Creates a new HTML::Mason::Request object for the given I<comp> and
  1007. I<args>, and executes it. The return value is the return value of
  1008. I<comp>, if any.
  1009.  
  1010. This is useful for running Mason outside of a web environment.
  1011. See L<HTML::Mason::Admin/using Mason from a standalone script>
  1012. for examples.
  1013.  
  1014. This method isn't generally useful in a mod_perl environment; see
  1015. L<subrequests|HTML::Mason::Devel/Subrequests> instead.
  1016.  
  1017. =for html <a name="flush_code_cache"></a>
  1018.  
  1019. =item flush_code_cache
  1020.  
  1021. Empties the component cache. When using Perl 5.00503 or earlier, you
  1022. should call this when finished with an interpreter, in order to remove
  1023. circular references that would prevent the interpreter from being
  1024. destroyed.
  1025.  
  1026. =for html <a name="item_load"></a>
  1027.  
  1028. =item load (path)
  1029.  
  1030. Returns the component object corresponding to an absolute component
  1031. C<path>, or undef if none exists.
  1032.  
  1033. =for html <a name="item_make_component"></a>
  1034.  
  1035. =item make_component (comp_source => ... )
  1036.  
  1037. =item make_component (comp_file => ... )
  1038.  
  1039. This method compiles Mason component source code and returns a
  1040. Component object.  The source may be passed in as a string in C<comp_source>,
  1041. or as a filename in C<comp_file>.  When using C<comp_file>, the
  1042. filename is specified as a path on the file system, not as a path
  1043. relative to Mason's component root (see 
  1044. L<$m-E<gt>fetch_comp|HTML::Mason::Request/item_fetch_comp> for that).
  1045.  
  1046. If Mason encounters an error during processing, an exception will be thrown.
  1047.  
  1048. Example of usage:
  1049.  
  1050.     # Make an anonymous component
  1051.     my $anon_comp =
  1052.       eval { $interp->make_component
  1053.                ( comp_source => '<%perl>my $name = "World";</%perl>Hello <% $name %>!' ) };
  1054.     die $@ if $@;
  1055.  
  1056.     $m->comp($anon_comp);
  1057.  
  1058. =for html <a name="item_make_request"></a>
  1059.  
  1060. =item make_request (@request_params)
  1061.  
  1062. This method creates a Mason request object. The arguments to be passed
  1063. are the same as those for the C<< HTML::Mason::Request->new >>
  1064. constructor or its relevant subclass. This method will likely only be
  1065. of interest to those attempting to write new handlers or to subclass
  1066. C<HTML::Mason::Interp>.  If you want to create a I<subrequest>, see
  1067. L<subrequests|HTML::Mason::Devel/Subrequests> instead.
  1068.  
  1069. =for html <a name="purge_code_cache"></a>
  1070.  
  1071. =item purge_code_cache ()
  1072.  
  1073. Called during request execution in order to clear out the code
  1074. cache. Mainly useful to subclasses that may want to take some custom
  1075. action upon clearing the cache.
  1076.  
  1077. =for html <a name="item_set_global"></a>
  1078.  
  1079. =item set_global ($varname, [values...])
  1080.  
  1081. This method sets a global to be used in components. C<varname> is a
  1082. variable name, optionally preceded with a prefix (C<$>, C<@>, or
  1083. C<%>); if the prefix is omitted then C<$> is assumed. C<varname> is
  1084. followed by a value, in the case of a scalar, or by one or more values
  1085. in the case of a list or hash.  For example:
  1086.  
  1087.     # Set a global variable $dbh containing the database handle
  1088.     $interp->set_global(dbh => DBI->connect(...));
  1089.  
  1090.     # Set a global hash %session from a local hash
  1091.     $interp->set_global('%session', %s);
  1092.  
  1093. The global is set in the package that components run in: usually
  1094. C<HTML::Mason::Commands>, although this can be overridden via the
  1095. L<in_package|HTML::Mason::Params/in_package> parameter.
  1096. The lines above, for example, are equivalent to:
  1097.  
  1098.     $HTML::Mason::Commands::dbh = DBI->connect(...);
  1099.     %HTML::Mason::Commands::session = %s;
  1100.  
  1101. assuming that L<in_package|HTML::Mason::Params/in_package> has not been changed.
  1102.  
  1103. Any global that you set should also be registered with the
  1104. L<allow_globals|HTML::Mason::Params/allow_globals> parameter; otherwise you'll get warnings from
  1105. C<strict>.
  1106.  
  1107. =back
  1108.  
  1109. =head1 MEMORY LEAK WARNING
  1110.  
  1111. When using Perl 5.00503 or earlier, using the code cache creates a
  1112. circular reference between Interp and component objects.  This means
  1113. that Interp objects will not be destroyed unless you call
  1114. L<flush_code_cache|HTML::Mason::Interp/flush_code_cache>.  If you are
  1115. using Perl 5.6.0 or greater, and you have the XS version of
  1116. Scalar::Util installed, Mason uses weak references to prevent this
  1117. problem.
  1118.  
  1119. Win32 users should note that as of this writing, ActiveState's PPD for
  1120. Scalar-List-Utils only includes the pure Perl version of these
  1121. modules, which don't include the weak references functionality.
  1122.  
  1123. =head1 SEE ALSO
  1124.  
  1125. L<HTML::Mason|HTML::Mason>,
  1126. L<HTML::Mason::Admin|HTML::Mason::Admin>,
  1127. L<HTML::Mason::ApacheHandler|HTML::Mason::ApacheHandler>
  1128.  
  1129. =cut
  1130.