<html><head><meta name="color-scheme" content="light dark"></head><body><pre style="word-wrap: break-word; white-space: pre-wrap;">package Catalyst::Plugin::Static::Simple;

use Moose::Role;
use File::stat;
use File::Spec ();
use IO::File ();
use MIME::Types ();
use MooseX::Types::Moose qw/ArrayRef Str/;
use Catalyst::Utils;
use namespace::autoclean;

our $VERSION = '0.30';

has _static_file =&gt; ( is =&gt; 'rw' );
has _static_debug_message =&gt; ( is =&gt; 'rw', isa =&gt; ArrayRef[Str] );

before prepare_action =&gt; sub {
    my $c = shift;
    my $path = $c-&gt;req-&gt;path;
    my $config = $c-&gt;config-&gt;{'Plugin::Static::Simple'};

    $path =~ s/%([0-9A-Fa-f]{2})/chr(hex($1))/eg;

    # is the URI in a static-defined path?
    foreach my $dir ( @{ $config-&gt;{dirs} } ) {
        my $dir_re = quotemeta $dir;

        # strip trailing slashes, they'll be added in our regex
        $dir_re =~ s{/$}{};

        my $re;

        if ( $dir =~ m{^qr/}xms ) {
            $re = eval $dir;

            if ($@) {
                $c-&gt;error( "Error compiling static dir regex '$dir': $@" );
            }
        }
        else {
            $re = qr{^${dir_re}/};
        }

        if ( $path =~ $re ) {
            if ( $c-&gt;_locate_static_file( $path, 1 ) ) {
                $c-&gt;_debug_msg( 'from static directory' )
                    if $config-&gt;{debug};
            } else {
                $c-&gt;_debug_msg( "404: file not found: $path" )
                    if $config-&gt;{debug};
                $c-&gt;res-&gt;status( 404 );
                $c-&gt;res-&gt;content_type( 'text/html' );
            }
        }
    }

    # Does the path have an extension?
    if ( $path =~ /.*\.(\S{1,})$/xms ) {
        # and does it exist?
        $c-&gt;_locate_static_file( $path );
    }
};

around dispatch =&gt; sub {
    my $orig = shift;
    my $c = shift;

    return if ( $c-&gt;res-&gt;status != 200 );

    if ( $c-&gt;_static_file ) {
        if ( $c-&gt;config-&gt;{'Plugin::Static::Simple'}-&gt;{no_logs} &amp;&amp; $c-&gt;log-&gt;can('abort') ) {
           $c-&gt;log-&gt;abort( 1 );
        }
        return $c-&gt;_serve_static;
    }
    else {
        return $c-&gt;$orig(@_);
    }
};

before finalize =&gt; sub {
    my $c = shift;

    # display all log messages
    if ( $c-&gt;config-&gt;{'Plugin::Static::Simple'}-&gt;{debug} &amp;&amp; scalar @{$c-&gt;_debug_msg} ) {
        $c-&gt;log-&gt;debug( 'Static::Simple: ' . join q{ }, @{$c-&gt;_debug_msg} );
    }
};

before setup_finalize =&gt; sub {
    my $c = shift;

    $c-&gt;log-&gt;warn("Deprecated 'static' config key used, please use the key 'Plugin::Static::Simple' instead")
        if exists $c-&gt;config-&gt;{static};
    my $config
        = $c-&gt;config-&gt;{'Plugin::Static::Simple'}
        = $c-&gt;config-&gt;{'static'}
        = Catalyst::Utils::merge_hashes(
            $c-&gt;config-&gt;{'Plugin::Static::Simple'} || {},
            $c-&gt;config-&gt;{static} || {}
        );

    $config-&gt;{dirs} ||= [];
    $config-&gt;{include_path} ||= [ $c-&gt;config-&gt;{root} ];
    $config-&gt;{mime_types} ||= {};
    $config-&gt;{ignore_extensions} ||= [ qw/tmpl tt tt2 html xhtml/ ];
    $config-&gt;{ignore_dirs} ||= [];
    $config-&gt;{debug} ||= $c-&gt;debug;
    $config-&gt;{no_logs} = 1 unless defined $config-&gt;{no_logs};
    $config-&gt;{no_logs} = 0 if $config-&gt;{logging};

    # load up a MIME::Types object, only loading types with
    # at least 1 file extension
    $config-&gt;{mime_types_obj} = MIME::Types-&gt;new( only_complete =&gt; 1 );

    # preload the type index hash so it's not built on the first request
    $config-&gt;{mime_types_obj}-&gt;create_type_index;
};

# Search through all included directories for the static file
# Based on Template Toolkit INCLUDE_PATH code
sub _locate_static_file {
    my ( $c, $path, $in_static_dir ) = @_;

    $path = File::Spec-&gt;catdir(
        File::Spec-&gt;no_upwards( File::Spec-&gt;splitdir( $path ) )
    );

    my $config = $c-&gt;config-&gt;{'Plugin::Static::Simple'};
    my @ipaths = @{ $config-&gt;{include_path} };
    my $dpaths;
    my $count = 64; # maximum number of directories to search

    DIR_CHECK:
    while ( @ipaths &amp;&amp; --$count) {
        my $dir = shift @ipaths || next DIR_CHECK;

        if ( ref $dir eq 'CODE' ) {
            eval { $dpaths = &amp;$dir( $c ) };
            if ($@) {
                $c-&gt;log-&gt;error( 'Static::Simple: include_path error: ' . $@ );
            } else {
                unshift @ipaths, @$dpaths;
                next DIR_CHECK;
            }
        } else {
            $dir =~ s/(\/|\\)$//xms;
            if ( -d $dir &amp;&amp; -f $dir . '/' . $path ) {

                # Don't ignore any files in static dirs defined with 'dirs'
                unless ( $in_static_dir ) {
                    # do we need to ignore the file?
                    for my $ignore ( @{ $config-&gt;{ignore_dirs} } ) {
                        $ignore =~ s{(/|\\)$}{};
                        if ( $path =~ /^$ignore(\/|\\)/ ) {
                            $c-&gt;_debug_msg( "Ignoring directory `$ignore`" )
                                if $config-&gt;{debug};
                            next DIR_CHECK;
                        }
                    }

                    # do we need to ignore based on extension?
                    for my $ignore_ext ( @{ $config-&gt;{ignore_extensions} } ) {
                        if ( $path =~ /.*\.${ignore_ext}$/ixms ) {
                            $c-&gt;_debug_msg( "Ignoring extension `$ignore_ext`" )
                                if $config-&gt;{debug};
                            next DIR_CHECK;
                        }
                    }
                }

                $c-&gt;_debug_msg( 'Serving ' . $dir . '/' . $path )
                    if $config-&gt;{debug};
                return $c-&gt;_static_file( $dir . '/' . $path );
            }
        }
    }

    return;
}

sub _serve_static {
    my $c = shift;
    my $config = $c-&gt;config-&gt;{'Plugin::Static::Simple'};

    my $full_path = shift || $c-&gt;_static_file;
    my $type      = $c-&gt;_ext_to_type( $full_path );
    my $stat      = stat $full_path;

    $c-&gt;res-&gt;headers-&gt;content_type( $type );
    $c-&gt;res-&gt;headers-&gt;content_length( $stat-&gt;size );
    $c-&gt;res-&gt;headers-&gt;last_modified( $stat-&gt;mtime );
    # Tell Firefox &amp; friends its OK to cache, even over SSL:
    $c-&gt;res-&gt;headers-&gt;header('Cache-control' =&gt; 'public');
    # Optionally, set a fixed expiry time:
    if ($config-&gt;{expires}) {
        $c-&gt;res-&gt;headers-&gt;expires(time() + $config-&gt;{expires});
    }

    my $fh = IO::File-&gt;new( $full_path, 'r' );
    if ( defined $fh ) {
        binmode $fh;
        $c-&gt;res-&gt;body( $fh );
    }
    else {
        Catalyst::Exception-&gt;throw(
            message =&gt; "Unable to open $full_path for reading" );
    }

    return 1;
}

sub serve_static_file {
    my ( $c, $full_path ) = @_;

    my $config = $c-&gt;config-&gt;{'Plugin::Static::Simple'};

    if ( -e $full_path ) {
        $c-&gt;_debug_msg( "Serving static file: $full_path" )
            if $config-&gt;{debug};
    }
    else {
        $c-&gt;_debug_msg( "404: file not found: $full_path" )
            if $config-&gt;{debug};
        $c-&gt;res-&gt;status( 404 );
        $c-&gt;res-&gt;content_type( 'text/html' );
        return;
    }

    $c-&gt;_serve_static( $full_path );
}

# looks up the correct MIME type for the current file extension
sub _ext_to_type {
    my ( $c, $full_path ) = @_;

    my $config = $c-&gt;config-&gt;{'Plugin::Static::Simple'};

    if ( $full_path =~ /.*\.(\S{1,})$/xms ) {
        my $ext = $1;
        my $type = $config-&gt;{mime_types}{$ext}
            || $config-&gt;{mime_types_obj}-&gt;mimeTypeOf( $ext );
        if ( $type ) {
            $c-&gt;_debug_msg( "as $type" ) if $config-&gt;{debug};
            return ( ref $type ) ? $type-&gt;type : $type;
        }
        else {
            $c-&gt;_debug_msg( "as text/plain (unknown extension $ext)" )
                if $config-&gt;{debug};
            return 'text/plain';
        }
    }
    else {
        $c-&gt;_debug_msg( 'as text/plain (no extension)' )
            if $config-&gt;{debug};
        return 'text/plain';
    }
}

sub _debug_msg {
    my ( $c, $msg ) = @_;

    if ( !defined $c-&gt;_static_debug_message ) {
        $c-&gt;_static_debug_message( [] );
    }

    if ( $msg ) {
        push @{ $c-&gt;_static_debug_message }, $msg;
    }

    return $c-&gt;_static_debug_message;
}

1;
__END__

=head1 NAME

Catalyst::Plugin::Static::Simple - Make serving static pages painless.

=head1 SYNOPSIS

    package MyApp;
    use Catalyst qw/ Static::Simple /;
    MyApp-&gt;setup;
    # that's it; static content is automatically served by Catalyst
    # from the application's root directory, though you can configure
    # things or bypass Catalyst entirely in a production environment
    #
    # one caveat: the files must be served from an absolute path
    # (i.e. /images/foo.png)

=head1 DESCRIPTION

The Static::Simple plugin is designed to make serving static content in
your application during development quick and easy, without requiring a
single line of code from you.

This plugin detects static files by looking at the file extension in the
URL (such as B&lt;.css&gt; or B&lt;.png&gt; or B&lt;.js&gt;). The plugin uses the
lightweight L&lt;MIME::Types&gt; module to map file extensions to
IANA-registered MIME types, and will serve your static files with the
correct MIME type directly to the browser, without being processed
through Catalyst.

Note that actions mapped to paths using periods (.) will still operate
properly.

If the plugin can not find the file, the request is dispatched to your
application instead. This means you are responsible for generating a
C&lt;404&gt; error if your applicaton can not process the request:

   # handled by static::simple, not dispatched to your application
   /images/exists.png

   # static::simple will not find the file and let your application
   # handle the request. You are responsible for generating a file
   # or returning a 404 error
   /images/does_not_exist.png

Though Static::Simple is designed to work out-of-the-box, you can tweak
the operation by adding various configuration options. In a production
environment, you will probably want to use your webserver to deliver
static content; for an example see L&lt;USING WITH APACHE&gt;, below.

=head1 DEFAULT BEHAVIOUR

By default, Static::Simple will deliver all files having extensions
(that is, bits of text following a period (C&lt;.&gt;)), I&lt;except&gt; files
having the extensions C&lt;tmpl&gt;, C&lt;tt&gt;, C&lt;tt2&gt;, C&lt;html&gt;, and
C&lt;xhtml&gt;. These files, and all files without extensions, will be
processed through Catalyst. If L&lt;MIME::Types&gt; doesn't recognize an
extension, it will be served as C&lt;text/plain&gt;.

To restate: files having the extensions C&lt;tmpl&gt;, C&lt;tt&gt;, C&lt;tt2&gt;, C&lt;html&gt;,
and C&lt;xhtml&gt; I&lt;will not&gt; be served statically by default, they will be
processed by Catalyst. Thus if you want to use C&lt;.html&gt; files from
within a Catalyst app as static files, you need to change the
configuration of Static::Simple. Note also that files having any other
extension I&lt;will&gt; be served statically, so if you're using any other
extension for template files, you should also change the configuration.

Logging of static files is turned off by default.

=head1 ADVANCED CONFIGURATION

Configuration is completely optional and is specified within
C&lt;MyApp-E&lt;gt&gt;config-E&lt;gt&gt;{static}&gt;.  If you use any of these options,
this module will probably feel less "simple" to you!

=head2 Enabling request logging

Since Catalyst 5.50, logging of static requests is turned off by
default; static requests tend to clutter the log output and rarely
reveal anything useful. However, if you want to enable logging of static
requests, you can do so by setting
C&lt;MyApp-E&lt;gt&gt;config-E&lt;gt&gt;{static}-E&lt;gt&gt;{logging}&gt; to 1.

=head2 Forcing directories into static mode

Define a list of top-level directories beneath your 'root' directory
that should always be served in static mode.  Regular expressions may be
specified using C&lt;qr//&gt;.

    MyApp-&gt;config(
        static =&gt; {
            dirs =&gt; [
                'static',
                qr/^(images|css)/,
            ],
        }
    );

=head2 Including additional directories

You may specify a list of directories in which to search for your static
files. The directories will be searched in order and will return the
first file found. Note that your root directory is B&lt;not&gt; automatically
added to the search path when you specify an C&lt;include_path&gt;. You should
use C&lt;MyApp-E&lt;gt&gt;config-E&lt;gt&gt;{root}&gt; to add it.

    MyApp-&gt;config(
        static =&gt; {
            include_path =&gt; [
                '/path/to/overlay',
                \&amp;incpath_generator,
                MyApp-&gt;config-&gt;{root},
            ],
        },
    );

With the above setting, a request for the file C&lt;/images/logo.jpg&gt; will search
for the following files, returning the first one found:

    /path/to/overlay/images/logo.jpg
    /dynamic/path/images/logo.jpg
    /your/app/home/root/images/logo.jpg

The include path can contain a subroutine reference to dynamically return a
list of available directories.  This method will receive the C&lt;$c&gt; object as a
parameter and should return a reference to a list of directories.  Errors can
be reported using C&lt;die()&gt;.  This method will be called every time a file is
requested that appears to be a static file (i.e. it has an extension).

For example:

    sub incpath_generator {
        my $c = shift;

        if ( $c-&gt;session-&gt;{customer_dir} ) {
            return [ $c-&gt;session-&gt;{customer_dir} ];
        } else {
            die "No customer dir defined.";
        }
    }

=head2 Ignoring certain types of files

There are some file types you may not wish to serve as static files.
Most important in this category are your raw template files.  By
default, files with the extensions C&lt;tmpl&gt;, C&lt;tt&gt;, C&lt;tt2&gt;, C&lt;html&gt;, and
C&lt;xhtml&gt; will be ignored by Static::Simple in the interest of security.
If you wish to define your own extensions to ignore, use the
C&lt;ignore_extensions&gt; option:

    MyApp-&gt;config(
        static =&gt; {
            ignore_extensions =&gt; [ qw/html asp php/ ],
        },
    );

=head2 Ignoring entire directories

To prevent an entire directory from being served statically, you can use
the C&lt;ignore_dirs&gt; option.  This option contains a list of relative
directory paths to ignore.  If using C&lt;include_path&gt;, the path will be
checked against every included path.

    MyApp-&gt;config(
        static =&gt; {
            ignore_dirs =&gt; [ qw/tmpl css/ ],
        },
    );

For example, if combined with the above C&lt;include_path&gt; setting, this
C&lt;ignore_dirs&gt; value will ignore the following directories if they exist:

    /path/to/overlay/tmpl
    /path/to/overlay/css
    /dynamic/path/tmpl
    /dynamic/path/css
    /your/app/home/root/tmpl
    /your/app/home/root/css

=head2 Custom MIME types

To override or add to the default MIME types set by the L&lt;MIME::Types&gt;
module, you may enter your own extension to MIME type mapping.

    MyApp-&gt;config(
        static =&gt; {
            mime_types =&gt; {
                jpg =&gt; 'image/jpg',
                png =&gt; 'image/png',
            },
        },
    );

=head2 Controlling caching with Expires header

The files served by Static::Simple will have a Last-Modified header set,
which allows some browsers to cache them for a while. However if you want
to explicitly set an Expires header, such as to allow proxies to cache your
static content, then you can do so by setting the "expires" config option.

The value indicates the number of seconds after access time to allow caching.
So a value of zero really means "don't cache at all", and any higher values
will keep the file around for that long.

    MyApp-&gt;config(
        static =&gt; {
            expires =&gt; 3600, # Caching allowed for one hour.
        },
    );

=head2 Compatibility with other plugins

Since version 0.12, Static::Simple plays nice with other plugins.  It no
longer short-circuits the C&lt;prepare_action&gt; stage as it was causing too
many compatibility issues with other plugins.

=head2 Debugging information

Enable additional debugging information printed in the Catalyst log.  This
is automatically enabled when running Catalyst in -Debug mode.

    MyApp-&gt;config(
        static =&gt; {
            debug =&gt; 1,
        },
    );

=head1 USING WITH APACHE

While Static::Simple will work just fine serving files through Catalyst
in mod_perl, for increased performance you may wish to have Apache
handle the serving of your static files directly. To do this, simply use
a dedicated directory for your static files and configure an Apache
Location block for that directory  This approach is recommended for
production installations.

    &lt;Location /myapp/static&gt;
        SetHandler default-handler
    &lt;/Location&gt;

Using this approach Apache will bypass any handling of these directories
through Catalyst. You can leave Static::Simple as part of your
application, and it will continue to function on a development server,
or using Catalyst's built-in server.

In practice, your Catalyst application is probably (i.e. should be)
structured in the recommended way (i.e., that generated by bootstrapping
the application with the C&lt;catalyst.pl&gt; script, with a main directory
under which is a C&lt;lib/&gt; directory for module files and a C&lt;root/&gt;
directory for templates and static files). Thus, unless you break up
this structure when deploying your app by moving the static files to a
different location in your filesystem, you will need to use an Alias
directive in Apache to point to the right place. You will then need to
add a Directory block to give permission for Apache to serve these
files. The final configuration will look something like this:

    Alias /myapp/static /filesystem/path/to/MyApp/root/static
    &lt;Directory /filesystem/path/to/MyApp/root/static&gt;
        allow from all
    &lt;/Directory&gt;
    &lt;Location /myapp/static&gt;
        SetHandler default-handler
    &lt;/Location&gt;

If you are running in a VirtualHost, you can just set the DocumentRoot
location to the location of your root directory; see
L&lt;Catalyst::Engine::Apache2::MP20&gt;.

=head1 PUBLIC METHODS

=head2 serve_static_file $file_path

Will serve the file located in $file_path statically. This is useful when
you need to  autogenerate them if they don't exist, or they are stored in a model.

    package MyApp::Controller::User;

    sub curr_user_thumb : PathPart("my_thumbnail.png") {
        my ( $self, $c ) = @_;
        my $file_path = $c-&gt;user-&gt;picture_thumbnail_path;
        $c-&gt;serve_static_file($file_path);
    }

=head1 INTERNAL EXTENDED METHODS

Static::Simple extends the following steps in the Catalyst process.

=head2 prepare_action

C&lt;prepare_action&gt; is used to first check if the request path is a static
file.  If so, we skip all other C&lt;prepare_action&gt; steps to improve
performance.

=head2 dispatch

C&lt;dispatch&gt; takes the file found during C&lt;prepare_action&gt; and writes it
to the output.

=head2 finalize

C&lt;finalize&gt; serves up final header information and displays any log
messages.

=head2 setup

C&lt;setup&gt; initializes all default values.

=head1 SEE ALSO

L&lt;Catalyst&gt;, L&lt;Catalyst::Plugin::Static&gt;,
L&lt;http://www.iana.org/assignments/media-types/&gt;

=head1 AUTHOR

Andy Grundman, &lt;andy@hybridized.org&gt;

=head1 CONTRIBUTORS

Marcus Ramberg, &lt;mramberg@cpan.org&gt;

Jesse Sheidlower, &lt;jester@panix.com&gt;

Guillermo Roditi, &lt;groditi@cpan.org&gt;

Florian Ragwitz, &lt;rafl@debian.org&gt;

Tomas Doran, &lt;bobtfish@bobtfish.net&gt;

Justin Wheeler (dnm)

Matt S Trout, &lt;mst@shadowcat.co.uk&gt;

Toby Corkindale, &lt;tjc@wintrmute.net&gt;

=head1 THANKS

The authors of Catalyst::Plugin::Static:

    Sebastian Riedel
    Christian Hansen
    Marcus Ramberg

For the include_path code from Template Toolkit:

    Andy Wardley

=head1 COPYRIGHT

Copyright (c) 2005 - 2011
the Catalyst::Plugin::Static::Simple L&lt;/AUTHOR&gt; and L&lt;/CONTRIBUTORS&gt;
as listed above.

=head1 LICENSE

This program is free software, you can redistribute it and/or modify it under
the same terms as Perl itself.

=cut
</pre></body></html>