4d7ce68489ad2cb5b16c58540353a84c5fcb7e9a
[catagits/Catalyst-Plugin-Static-Simple.git] / lib / Catalyst / Plugin / Static / Simple.pm
1 package Catalyst::Plugin::Static::Simple;
2
3 use strict;
4 use base qw/Class::Accessor::Fast Class::Data::Inheritable/;
5 use File::Slurp;
6 use File::stat;
7 use MIME::Types;
8 use NEXT;
9
10 our $VERSION = '0.08';
11
12 __PACKAGE__->mk_classdata( qw/_static_mime_types/ );
13 __PACKAGE__->mk_accessors( qw/_static_file
14                               _static_apache_mode
15                               _static_debug_message/ );
16
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.
19 sub prepare_action {
20     my $c = shift;
21     my $path = $c->req->path;
22
23     # is the URI in a static-defined path?
24     foreach my $dir ( @{ $c->config->{static}->{dirs} } ) {
25         my $re = ( $dir =~ /^qr\//xms ) ? eval $dir : qr/^${dir}/;
26         if ($@) {
27             $c->error( "Error compiling static dir regex '$dir': $@" );
28         }
29         if ( $path =~ $re ) {
30             if ( $c->_locate_static_file ) {
31                 $c->_debug_msg( "from static directory" )
32                     if ( $c->config->{static}->{debug} );
33                 return;
34             } else {
35                 $c->_debug_msg( "404: file not found: $path" )
36                     if ( $c->config->{static}->{debug} );
37                 $c->res->status( 404 );
38                 return;
39             }
40         }
41     }
42     
43     # Does the path have an extension?
44     if ( $path =~ /.*\.(\S{1,})$/xms ) {
45         # and does it exist?
46         return if ( $c->_locate_static_file );
47     }
48     
49     return $c->NEXT::prepare_action(@_);
50 }
51
52 # dispatch takes the file found during prepare_action and serves it
53 sub dispatch {
54     my $c = shift;
55     
56     return if ( $c->res->status != 200 );
57     
58     if ( $c->_static_file ) {
59         if ( $c->config->{static}->{no_logs} ) {
60            if ( $c->log->can('abort') ) { $c->log->abort(1) ; }
61         }
62         return $c->_serve_static;
63     }
64     else {
65         return $c->NEXT::dispatch(@_);
66     }
67 }
68
69 # finalize serves up final header information
70 sub finalize {
71     my $c = shift;
72     
73     # display all log messages
74     if ( $c->config->{static}->{debug} && scalar @{$c->_debug_msg} ) {
75         $c->log->debug( "Static::Simple: Serving " .
76             join( " ", @{$c->_debug_msg} ) );
77     }
78     
79     # return DECLINED when under mod_perl
80     if ( $c->config->{static}->{use_apache} && $c->_static_apache_mode ) {
81         my $engine = $c->_static_apache_mode;
82         no strict 'subs';
83         if ( $engine == 13 ) {
84             return Apache::Constants::DECLINED;
85         }
86         elsif ( $engine == 19 ) {
87             return Apache::Const::DECLINED;
88         }
89         elsif ( $engine == 20 ) {
90             return Apache2::Const::DECLINED;
91         }
92     }
93     
94     if ( $c->res->status =~ /^(1\d\d|[23]04)$/xms ) {
95         $c->res->headers->remove_content_headers;
96         return $c->finalize_headers;
97     }
98     
99     return $c->NEXT::finalize(@_);
100 }
101
102 sub 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;
112     $c->config->{static}->{no_logs} ||= 1;
113     
114     # load up a MIME::Types object, only loading types with
115     # at least 1 file extension
116     $c->_static_mime_types( MIME::Types->new( only_complete => 1 ) );
117     
118     # preload the type index hash so it's not built on the first request
119     $c->_static_mime_types->create_type_index;
120 }
121
122 # Search through all included directories for the static file
123 # Based on Template Toolkit INCLUDE_PATH code
124 sub _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 {
145             $dir =~ s/\/$//xms;
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     
154     return;
155 }
156
157 sub _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
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} );          
191                  $c->_static_apache_mode( $engine );
192                  return;
193              }
194         }
195     }
196     
197     my $type = $c->_ext_to_type;
198     
199     my $full_path = $c->_static_file;
200     my $stat = stat( $full_path );
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
211     my $content = read_file( $full_path );
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 );
216     return 1;
217 }
218
219 # looks up the correct MIME type for the current file extension
220 sub _ext_to_type {
221     my $c = shift;
222     my $path = $c->req->path;
223     
224     if ( $path =~ /.*\.(\S{1,})$/xms ) {
225         my $ext = $1;
226         my $user_types = $c->config->{static}->{mime_types};
227         my $type = $user_types->{$ext} 
228                 || $c->_static_mime_types->mimeTypeOf( $ext );
229         if ( $type ) {
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     }
245 }
246
247 sub _debug_msg {
248     my ( $c, $msg ) = @_;
249     
250     if ( !defined $c->_static_debug_message ) {
251         $c->_static_debug_message( [] );
252     }
253     
254     if ( $msg ) {
255         push @{ $c->_static_debug_message }, $msg;
256     }
257     
258     return $c->_static_debug_message;
259 }
260
261 1;
262 __END__
263
264 =head1 NAME
265
266 Catalyst::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
275 The Static::Simple plugin is designed to make serving static content in your
276 application during development quick and easy, without requiring a single
277 line of code from you.
278
279 It will detect static files used in your application by looking for file
280 extensions in the URI.  By default, you can simply load this plugin and it
281 will immediately begin serving your static files with the correct MIME type.
282 The light-weight MIME::Types module is used to map file extensions to
283 IANA-registered MIME types.
284
285 Note that actions mapped to paths using periods (.) will still operate
286 properly.
287
288 You may further tweak the operation by adding configuration options, described
289 below.
290
291 =head1 ADVANCED CONFIGURATION
292
293 Configuration is completely optional and is specified within 
294 MyApp->config->{static}.  If you use any of these options, the module will
295 probably feel less "simple" to you!
296
297 =head2 Aborting request logging
298
299 With Catalyst 5.50, there has been added support for dropping logging for a 
300 request. We've turned this on by default, as static logging tends to clutter
301 the Log API, however, if you want logging of static requests, you can easily
302 turn it on by setting MyApp->config->{static}->{no_logs} to 0.
303
304 =head2 Forcing directories into static mode
305
306 Define a list of top-level directories beneath your 'root' directory that
307 should always be served in static mode.  Regular expressions may be
308 specified using qr//.
309
310     MyApp->config->{static}->{dirs} = [
311         'static',
312         qr/^(images|css)/,
313     ];
314
315 =head2 Including additional directories (experimental!)
316
317 You may specify a list of directories in which to search for your static
318 files.  The directories will be searched in order and will return the first
319 file found.  Note that your root directory is B<not> automatically added to
320 the search path when you specify an include_path.  You should use
321 MyApp->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     
329 With the above setting, a request for the file /images/logo.jpg will search
330 for 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     
336 The include path can contain a subroutine reference to dynamically return a
337 list of available directories.  This method will receive the $c object as a
338 parameter and should return a reference to a list of directories.  Errors can
339 be reported using die().  This method will be called every time a file is
340 requested that appears to be a static file (i.e. it has an extension).
341
342 For 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
354 =head2 Custom MIME types
355
356 To override or add to the default MIME types set by the MIME::Types module,
357 you 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     };
363
364 =head2 Apache integration and performance
365
366 Optionally, when running under mod_perl, Static::Simple can return DECLINED
367 on static files to allow Apache to serve the file.  A check is first done to
368 make sure that Apache's DocumentRoot matches your Catalyst root, and that you
369 are not using any custom MIME types or multiple roots.  To enable the Apache
370 support, you can set the following option.
371
372     MyApp->config->{static}->{use_apache} = 1;
373     
374 By default this option is disabled because after several benchmarks it
375 appears that just serving the file from Catalyst is the better option.  On a
376 3K file, Catalyst appears to be around 25% faster, and is 42% faster on a 10K
377 file.  My benchmarking was done using the following 'siege' command, so other
378 benchmarks would be welcome!
379
380     siege -u http://server/static/css/10K.css -b -t 1M -c 1
381
382 For best static performance, you should still serve your static files directly
383 from Apache by defining a Location block similar to the following:
384
385     <Location /static>
386         SetHandler default-handler
387     </Location>
388
389 =head2 Bypassing other plugins
390
391 This plugin checks for a static file in the prepare_action stage.  If the
392 request is for a static file, it will bypass all remaining prepare_action
393 steps.  This means that by placing Static::Simple before all other plugins,
394 they will not execute when a static file is found.  This can be helpful by
395 skipping session cookie checks for example.  Or, if you want some plugins
396 to run even on static files, list them before Static::Simple.
397
398 Currently, work done by plugins in any other prepare method will execute
399 normally.
400
401 =head2 Debugging information
402
403 Enable additional debugging information printed in the Catalyst log.  This
404 is automatically enabled when running Catalyst in -Debug mode.
405
406     MyApp->config->{static}->{debug} = 1;
407
408 =head1 SEE ALSO
409
410 L<Catalyst>, L<Catalyst::Plugin::Static>, 
411 L<http://www.iana.org/assignments/media-types/>
412
413 =head1 AUTHOR
414
415 Andy Grundman, <andy@hybridized.org>
416
417 =head1 THANKS
418
419 The authors of Catalyst::Plugin::Static:
420
421     Sebastian Riedel
422     Christian Hansen
423     Marcus Ramberg
424
425 For the include_path code from Template Toolkit:
426
427     Andy Wardley
428
429 =head1 COPYRIGHT
430
431 This program is free software, you can redistribute it and/or modify it under
432 the same terms as Perl itself.
433
434 =cut