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