Static::Simple, pre-0.09
[catagits/Catalyst-Plugin-Static-Simple.git] / lib / Catalyst / Plugin / Static / Simple.pm
CommitLineData
d6d29b9b 1package Catalyst::Plugin::Static::Simple;
2
3use strict;
4use base qw/Class::Accessor::Fast Class::Data::Inheritable/;
5use File::Slurp;
6use File::stat;
7use MIME::Types;
8use NEXT;
9
fa43d6b5 10our $VERSION = '0.09';
d6d29b9b 11
2268e329 12__PACKAGE__->mk_classdata( qw/_static_mime_types/ );
b1d96e3e 13__PACKAGE__->mk_accessors( qw/_static_file
2268e329 14 _static_apache_mode
15 _static_debug_message/ );
d6d29b9b 16
b1d96e3e 17# prepare_action is used to first check if the request path is a static file.
18# If so, we skip all other prepare_action steps to improve performance.
19sub prepare_action {
d6d29b9b 20 my $c = shift;
d6d29b9b 21 my $path = $c->req->path;
b1d96e3e 22
d6d29b9b 23 # is the URI in a static-defined path?
24 foreach my $dir ( @{ $c->config->{static}->{dirs} } ) {
b1d96e3e 25 my $re = ( $dir =~ /^qr\//xms ) ? eval $dir : qr/^${dir}/;
26 if ($@) {
27 $c->error( "Error compiling static dir regex '$dir': $@" );
28 }
d6d29b9b 29 if ( $path =~ $re ) {
30 if ( $c->_locate_static_file ) {
31 $c->_debug_msg( "from static directory" )
32 if ( $c->config->{static}->{debug} );
b1d96e3e 33 return;
d6d29b9b 34 } else {
35 $c->_debug_msg( "404: file not found: $path" )
36 if ( $c->config->{static}->{debug} );
37 $c->res->status( 404 );
b1d96e3e 38 return;
d6d29b9b 39 }
40 }
41 }
42
43 # Does the path have an extension?
b1d96e3e 44 if ( $path =~ /.*\.(\S{1,})$/xms ) {
d6d29b9b 45 # and does it exist?
b1d96e3e 46 return if ( $c->_locate_static_file );
d6d29b9b 47 }
48
b1d96e3e 49 return $c->NEXT::prepare_action(@_);
d6d29b9b 50}
51
b1d96e3e 52# dispatch takes the file found during prepare_action and serves it
53sub dispatch {
54 my $c = shift;
55
2268e329 56 return if ( $c->res->status != 200 );
b1d96e3e 57
58 if ( $c->_static_file ) {
2de14076 59 if ( $c->config->{static}->{no_logs} ) {
60 if ( $c->log->can('abort') ) { $c->log->abort(1) ; }
61 }
b1d96e3e 62 return $c->_serve_static;
63 }
64 else {
65 return $c->NEXT::dispatch(@_);
66 }
67}
68
69# finalize serves up final header information
d6d29b9b 70sub finalize {
71 my $c = shift;
72
73 # display all log messages
74 if ( $c->config->{static}->{debug} && scalar @{$c->_debug_msg} ) {
2de14076 75 $c->log->debug( "Static::Simple: Serving " .
76 join( " ", @{$c->_debug_msg} ) );
d6d29b9b 77 }
78
79 # return DECLINED when under mod_perl
2268e329 80 if ( $c->config->{static}->{use_apache} && $c->_static_apache_mode ) {
81 my $engine = $c->_static_apache_mode;
d6d29b9b 82 no strict 'subs';
83 if ( $engine == 13 ) {
84 return Apache::Constants::DECLINED;
b1d96e3e 85 }
86 elsif ( $engine == 19 ) {
d6d29b9b 87 return Apache::Const::DECLINED;
b1d96e3e 88 }
89 elsif ( $engine == 20 ) {
d6d29b9b 90 return Apache2::Const::DECLINED;
91 }
92 }
93
b1d96e3e 94 if ( $c->res->status =~ /^(1\d\d|[23]04)$/xms ) {
d6d29b9b 95 $c->res->headers->remove_content_headers;
96 return $c->finalize_headers;
97 }
b1d96e3e 98
d6d29b9b 99 return $c->NEXT::finalize(@_);
100}
101
102sub setup {
103 my $c = shift;
104
105 $c->NEXT::setup(@_);
106
107 $c->config->{static}->{dirs} ||= [];
108 $c->config->{static}->{include_path} ||= [ $c->config->{root} ];
109 $c->config->{static}->{mime_types} ||= {};
110 $c->config->{static}->{use_apache} ||= 0;
111 $c->config->{static}->{debug} ||= $c->debug;
2de14076 112 $c->config->{static}->{no_logs} ||= 1;
d6d29b9b 113
114 # load up a MIME::Types object, only loading types with
115 # at least 1 file extension
2268e329 116 $c->_static_mime_types( MIME::Types->new( only_complete => 1 ) );
117
d6d29b9b 118 # preload the type index hash so it's not built on the first request
2268e329 119 $c->_static_mime_types->create_type_index;
d6d29b9b 120}
121
122# Search through all included directories for the static file
123# Based on Template Toolkit INCLUDE_PATH code
124sub _locate_static_file {
125 my $c = shift;
126
127 my $path = $c->req->path;
128
129 my @ipaths = @{ $c->config->{static}->{include_path} };
130 my $dpaths;
131 my $count = 64; # maximum number of directories to search
132
133 while ( @ipaths && --$count) {
134 my $dir = shift @ipaths || next;
135
136 if ( ref $dir eq 'CODE' ) {
137 eval { $dpaths = &$dir( $c ) };
138 if ($@) {
139 $c->log->error( "Static::Simple: include_path error: " . $@ );
140 } else {
141 unshift( @ipaths, @$dpaths );
142 next;
143 }
144 } else {
b1d96e3e 145 $dir =~ s/\/$//xms;
d6d29b9b 146 if ( -d $dir && -f $dir . '/' . $path ) {
147 $c->_debug_msg( $dir . "/" . $path )
148 if ( $c->config->{static}->{debug} );
149 return $c->_static_file( $dir . '/' . $path );
150 }
151 }
152 }
153
2268e329 154 return;
d6d29b9b 155}
156
d6d29b9b 157sub _serve_static {
158 my $c = shift;
159
160 my $path = $c->req->path;
161
162 # abort if running under mod_perl
163 # note that we do not use the Apache method if the user has defined
b1d96e3e 164 # custom MIME types or is using include paths, as Apache would not know
165 # about them
166 APACHE_CHECK:
167 {
168 if ( $c->config->{static}->{use_apache} ) {
169 # check engine version
170 last APACHE_CHECK unless $c->engine =~ /Apache::MP(\d{2})/xms;
171 my $engine = $1;
172
173 # skip if we have user-defined MIME types
174 last APACHE_CHECK if keys %{ $c->config->{static}->{mime_types} };
175
176 # skip if the file is in a user-defined include path
177 last APACHE_CHECK if $c->_static_file
178 ne $c->config->{root} . '/' . $path;
179
180 # check that Apache will serve the correct file
181 if ( $c->apache->document_root ne $c->config->{root} ) {
182 $c->log->warn( "Static::Simple: Your Apache DocumentRoot"
183 . " must be set to " . $c->config->{root}
184 . " to use the Apache feature. Yours is"
185 . " currently " . $c->apache->document_root
186 );
187 }
188 else {
189 $c->_debug_msg( "DECLINED to Apache" )
190 if ( $c->config->{static}->{debug} );
2268e329 191 $c->_static_apache_mode( $engine );
192 return;
b1d96e3e 193 }
d6d29b9b 194 }
195 }
196
197 my $type = $c->_ext_to_type;
198
b1d96e3e 199 my $full_path = $c->_static_file;
200 my $stat = stat( $full_path );
d6d29b9b 201
202 # the below code all from C::P::Static
203 if ( $c->req->headers->if_modified_since ) {
204 if ( $c->req->headers->if_modified_since == $stat->mtime ) {
205 $c->res->status( 304 ); # Not Modified
206 $c->res->headers->remove_content_headers;
207 return 1;
208 }
209 }
210
b1d96e3e 211 my $content = read_file( $full_path );
d6d29b9b 212 $c->res->headers->content_type( $type );
213 $c->res->headers->content_length( $stat->size );
214 $c->res->headers->last_modified( $stat->mtime );
215 $c->res->output( $content );
b1d96e3e 216 return 1;
217}
218
219# looks up the correct MIME type for the current file extension
220sub _ext_to_type {
221 my $c = shift;
b1d96e3e 222 my $path = $c->req->path;
b1d96e3e 223
224 if ( $path =~ /.*\.(\S{1,})$/xms ) {
225 my $ext = $1;
226 my $user_types = $c->config->{static}->{mime_types};
2268e329 227 my $type = $user_types->{$ext}
228 || $c->_static_mime_types->mimeTypeOf( $ext );
229 if ( $type ) {
b1d96e3e 230 $c->_debug_msg( "as $type" )
231 if ( $c->config->{static}->{debug} );
232 return $type;
233 }
234 else {
235 $c->_debug_msg( "as text/plain (unknown extension $ext)" )
236 if ( $c->config->{static}->{debug} );
237 return 'text/plain';
238 }
239 }
240 else {
241 $c->_debug_msg( 'as text/plain (no extension)' )
242 if ( $c->config->{static}->{debug} );
243 return 'text/plain';
244 }
d6d29b9b 245}
246
247sub _debug_msg {
248 my ( $c, $msg ) = @_;
249
2268e329 250 if ( !defined $c->_static_debug_message ) {
251 $c->_static_debug_message( [] );
b1d96e3e 252 }
d6d29b9b 253
b1d96e3e 254 if ( $msg ) {
2268e329 255 push @{ $c->_static_debug_message }, $msg;
b1d96e3e 256 }
d6d29b9b 257
2268e329 258 return $c->_static_debug_message;
d6d29b9b 259}
b1d96e3e 260
2611;
262__END__
263
264=head1 NAME
265
266Catalyst::Plugin::Static::Simple - Make serving static pages painless.
267
268=head1 SYNOPSIS
269
270 use Catalyst;
271 MyApp->setup( qw/Static::Simple/ );
272
273=head1 DESCRIPTION
274
275The Static::Simple plugin is designed to make serving static content in your
276application during development quick and easy, without requiring a single
277line of code from you.
278
279It will detect static files used in your application by looking for file
280extensions in the URI. By default, you can simply load this plugin and it
281will immediately begin serving your static files with the correct MIME type.
282The light-weight MIME::Types module is used to map file extensions to
283IANA-registered MIME types.
284
285Note that actions mapped to paths using periods (.) will still operate
286properly.
287
288You may further tweak the operation by adding configuration options, described
289below.
290
291=head1 ADVANCED CONFIGURATION
292
293Configuration is completely optional and is specified within
294MyApp->config->{static}. If you use any of these options, the module will
295probably feel less "simple" to you!
296
2de14076 297=head2 Aborting request logging
298
299With Catalyst 5.50, there has been added support for dropping logging for a
300request. We've turned this on by default, as static logging tends to clutter
301the Log API, however, if you want logging of static requests, you can easily
302turn it on by setting MyApp->config->{static}->{no_logs} to 0.
303
2268e329 304=head2 Forcing directories into static mode
b1d96e3e 305
306Define a list of top-level directories beneath your 'root' directory that
307should always be served in static mode. Regular expressions may be
308specified using qr//.
309
310 MyApp->config->{static}->{dirs} = [
311 'static',
312 qr/^(images|css)/,
313 ];
314
fa43d6b5 315=head2 Including additional directories
b1d96e3e 316
317You may specify a list of directories in which to search for your static
318files. The directories will be searched in order and will return the first
319file found. Note that your root directory is B<not> automatically added to
320the search path when you specify an include_path. You should use
321MyApp->config->{root} to add it.
322
323 MyApp->config->{static}->{include_path} = [
324 '/path/to/overlay',
325 \&incpath_generator,
326 MyApp->config->{root}
327 ];
328
329With the above setting, a request for the file /images/logo.jpg will search
330for the following files, returning the first one found:
331
332 /path/to/overlay/images/logo.jpg
333 /dynamic/path/images/logo.jpg
334 /your/app/home/root/images/logo.jpg
335
336The include path can contain a subroutine reference to dynamically return a
337list of available directories. This method will receive the $c object as a
338parameter and should return a reference to a list of directories. Errors can
339be reported using die(). This method will be called every time a file is
340requested that appears to be a static file (i.e. it has an extension).
341
342For example:
343
344 sub incpath_generator {
345 my $c = shift;
346
347 if ( $c->session->{customer_dir} ) {
348 return [ $c->session->{customer_dir} ];
349 } else {
350 die "No customer dir defined.";
351 }
352 }
353
2268e329 354=head2 Custom MIME types
b1d96e3e 355
356To override or add to the default MIME types set by the MIME::Types module,
357you may enter your own extension to MIME type mapping.
358
359 MyApp->config->{static}->{mime_types} = {
360 jpg => 'image/jpg',
361 png => 'image/png',
362 };
2268e329 363
364=head2 Apache integration and performance
b1d96e3e 365
366Optionally, when running under mod_perl, Static::Simple can return DECLINED
367on static files to allow Apache to serve the file. A check is first done to
368make sure that Apache's DocumentRoot matches your Catalyst root, and that you
369are not using any custom MIME types or multiple roots. To enable the Apache
370support, you can set the following option.
371
372 MyApp->config->{static}->{use_apache} = 1;
373
374By default this option is disabled because after several benchmarks it
375appears that just serving the file from Catalyst is the better option. On a
3763K file, Catalyst appears to be around 25% faster, and is 42% faster on a 10K
377file. My benchmarking was done using the following 'siege' command, so other
378benchmarks would be welcome!
379
380 siege -u http://server/static/css/10K.css -b -t 1M -c 1
381
382For best static performance, you should still serve your static files directly
383from Apache by defining a Location block similar to the following:
384
385 <Location /static>
386 SetHandler default-handler
387 </Location>
2268e329 388
389=head2 Bypassing other plugins
b1d96e3e 390
391This plugin checks for a static file in the prepare_action stage. If the
392request is for a static file, it will bypass all remaining prepare_action
393steps. This means that by placing Static::Simple before all other plugins,
394they will not execute when a static file is found. This can be helpful by
395skipping session cookie checks for example. Or, if you want some plugins
396to run even on static files, list them before Static::Simple.
397
398Currently, work done by plugins in any other prepare method will execute
399normally.
400
2268e329 401=head2 Debugging information
b1d96e3e 402
403Enable additional debugging information printed in the Catalyst log. This
404is automatically enabled when running Catalyst in -Debug mode.
405
406 MyApp->config->{static}->{debug} = 1;
407
d6d29b9b 408=head1 SEE ALSO
409
b1d96e3e 410L<Catalyst>, L<Catalyst::Plugin::Static>,
411L<http://www.iana.org/assignments/media-types/>
d6d29b9b 412
413=head1 AUTHOR
414
b1d96e3e 415Andy Grundman, <andy@hybridized.org>
d6d29b9b 416
fa43d6b5 417=head1 CONTRIBUTORS
418
419Marcus Ramberg, <mramberg@cpan.org>
420
d6d29b9b 421=head1 THANKS
422
423The authors of Catalyst::Plugin::Static:
424
425 Sebastian Riedel
426 Christian Hansen
427 Marcus Ramberg
428
429For the include_path code from Template Toolkit:
430
431 Andy Wardley
432
433=head1 COPYRIGHT
434
435This program is free software, you can redistribute it and/or modify it under
436the same terms as Perl itself.
437
438=cut