6f1848a4db3502333a02f5e0e66faea5cf8f423e
[catagits/Catalyst-Runtime.git] / lib / Catalyst.pm
1 package Catalyst;
2
3 use strict;
4 use base 'Catalyst::Component';
5 use bytes;
6 use Catalyst::Exception;
7 use Catalyst::Log;
8 use Catalyst::Request;
9 use Catalyst::Request::Upload;
10 use Catalyst::Response;
11 use Catalyst::Utils;
12 use Catalyst::Controller;
13 use Devel::InnerPackage ();
14 use File::stat;
15 use Module::Pluggable::Object ();
16 use NEXT;
17 use Text::SimpleTable ();
18 use Path::Class::Dir ();
19 use Path::Class::File ();
20 use Time::HiRes qw/gettimeofday tv_interval/;
21 use URI ();
22 use URI::http;
23 use URI::https;
24 use Scalar::Util qw/weaken blessed/;
25 use Tree::Simple qw/use_weak_refs/;
26 use Tree::Simple::Visitor::FindByUID;
27 use attributes;
28 use utf8;
29 use Carp qw/croak carp/;
30
31 BEGIN { require 5.008001; }
32
33 __PACKAGE__->mk_accessors(
34     qw/counter request response state action stack namespace stats/
35 );
36
37 attributes->import( __PACKAGE__, \&namespace, 'lvalue' );
38
39 sub depth { scalar @{ shift->stack || [] }; }
40
41 # Laziness++
42 *comp = \&component;
43 *req  = \&request;
44 *res  = \&response;
45
46 # For backwards compatibility
47 *finalize_output = \&finalize_body;
48
49 # For statistics
50 our $COUNT     = 1;
51 our $START     = time;
52 our $RECURSION = 1000;
53 our $DETACH    = "catalyst_detach\n";
54
55 __PACKAGE__->mk_classdata($_)
56   for qw/components arguments dispatcher engine log dispatcher_class
57   engine_class context_class request_class response_class setup_finished/;
58
59 __PACKAGE__->dispatcher_class('Catalyst::Dispatcher');
60 __PACKAGE__->engine_class('Catalyst::Engine::CGI');
61 __PACKAGE__->request_class('Catalyst::Request');
62 __PACKAGE__->response_class('Catalyst::Response');
63
64 # Remember to update this in Catalyst::Runtime as well!
65
66 our $VERSION = '5.7008';
67
68 sub import {
69     my ( $class, @arguments ) = @_;
70
71     # We have to limit $class to Catalyst to avoid pushing Catalyst upon every
72     # callers @ISA.
73     return unless $class eq 'Catalyst';
74
75     my $caller = caller(0);
76
77     unless ( $caller->isa('Catalyst') ) {
78         no strict 'refs';
79         push @{"$caller\::ISA"}, $class, 'Catalyst::Controller';
80     }
81
82     $caller->arguments( [@arguments] );
83     $caller->setup_home;
84 }
85
86 =head1 NAME
87
88 Catalyst - The Elegant MVC Web Application Framework
89
90 =head1 SYNOPSIS
91
92 See the L<Catalyst::Manual> distribution for comprehensive
93 documentation and tutorials.
94
95     # Install Catalyst::Devel for helpers and other development tools
96     # use the helper to create a new application
97     catalyst.pl MyApp
98
99     # add models, views, controllers
100     script/myapp_create.pl model MyDatabase DBIC::Schema create=dynamic dbi:SQLite:/path/to/db
101     script/myapp_create.pl view MyTemplate TT
102     script/myapp_create.pl controller Search
103
104     # built in testserver -- use -r to restart automatically on changes
105     # --help to see all available options
106     script/myapp_server.pl
107
108     # command line testing interface
109     script/myapp_test.pl /yada
110
111     ### in lib/MyApp.pm
112     use Catalyst qw/-Debug/; # include plugins here as well
113     
114     ### In lib/MyApp/Controller/Root.pm (autocreated)
115     sub foo : Global { # called for /foo, /foo/1, /foo/1/2, etc.
116         my ( $self, $c, @args ) = @_; # args are qw/1 2/ for /foo/1/2
117         $c->stash->{template} = 'foo.tt'; # set the template
118         # lookup something from db -- stash vars are passed to TT
119         $c->stash->{data} = 
120           $c->model('Database::Foo')->search( { country => $args[0] } );
121         if ( $c->req->params->{bar} ) { # access GET or POST parameters
122             $c->forward( 'bar' ); # process another action
123             # do something else after forward returns            
124         }
125     }
126     
127     # The foo.tt TT template can use the stash data from the database
128     [% WHILE (item = data.next) %]
129         [% item.foo %]
130     [% END %]
131     
132     # called for /bar/of/soap, /bar/of/soap/10, etc.
133     sub bar : Path('/bar/of/soap') { ... }
134
135     # called for all actions, from the top-most controller downwards
136     sub auto : Private { 
137         my ( $self, $c ) = @_;
138         if ( !$c->user_exists ) { # Catalyst::Plugin::Authentication
139             $c->res->redirect( '/login' ); # require login
140             return 0; # abort request and go immediately to end()
141         }
142         return 1; # success; carry on to next action
143     }
144     
145     # called after all actions are finished
146     sub end : Private { 
147         my ( $self, $c ) = @_;
148         if ( scalar @{ $c->error } ) { ... } # handle errors
149         return if $c->res->body; # already have a response
150         $c->forward( 'MyApp::View::TT' ); # render template
151     }
152
153     ### in MyApp/Controller/Foo.pm
154     # called for /foo/bar
155     sub bar : Local { ... }
156     
157     # called for /blargle
158     sub blargle : Global { ... }
159     
160     # an index action matches /foo, but not /foo/1, etc.
161     sub index : Private { ... }
162     
163     ### in MyApp/Controller/Foo/Bar.pm
164     # called for /foo/bar/baz
165     sub baz : Local { ... }
166     
167     # first Root auto is called, then Foo auto, then this
168     sub auto : Private { ... }
169     
170     # powerful regular expression paths are also possible
171     sub details : Regex('^product/(\w+)/details$') {
172         my ( $self, $c ) = @_;
173         # extract the (\w+) from the URI
174         my $product = $c->req->captures->[0];
175     }
176
177 See L<Catalyst::Manual::Intro> for additional information.
178
179 =head1 DESCRIPTION
180
181 Catalyst is a modern framework for making web applications without the
182 pain usually associated with this process. This document is a reference
183 to the main Catalyst application. If you are a new user, we suggest you
184 start with L<Catalyst::Manual::Tutorial> or L<Catalyst::Manual::Intro>.
185
186 See L<Catalyst::Manual> for more documentation.
187
188 Catalyst plugins can be loaded by naming them as arguments to the "use
189 Catalyst" statement. Omit the C<Catalyst::Plugin::> prefix from the
190 plugin name, i.e., C<Catalyst::Plugin::My::Module> becomes
191 C<My::Module>.
192
193     use Catalyst qw/My::Module/;
194
195 If your plugin starts with a name other than C<Catalyst::Plugin::>, you can
196 fully qualify the name by using a unary plus:
197
198     use Catalyst qw/
199         My::Module
200         +Fully::Qualified::Plugin::Name
201     /;
202
203 Special flags like C<-Debug> and C<-Engine> can also be specified as
204 arguments when Catalyst is loaded:
205
206     use Catalyst qw/-Debug My::Module/;
207
208 The position of plugins and flags in the chain is important, because
209 they are loaded in the order in which they appear.
210
211 The following flags are supported:
212
213 =head2 -Debug
214
215 Enables debug output. You can also force this setting from the system
216 environment with CATALYST_DEBUG or <MYAPP>_DEBUG. The environment
217 settings override the application, with <MYAPP>_DEBUG having the highest
218 priority.
219
220 =head2 -Engine
221
222 Forces Catalyst to use a specific engine. Omit the
223 C<Catalyst::Engine::> prefix of the engine name, i.e.:
224
225     use Catalyst qw/-Engine=CGI/;
226
227 =head2 -Home
228
229 Forces Catalyst to use a specific home directory, e.g.:
230
231     use Catalyst qw[-Home=/usr/mst];
232
233 This can also be done in the shell environment by setting either the
234 C<CATALYST_HOME> environment variable or C<MYAPP_HOME>; where C<MYAPP>
235 is replaced with the uppercased name of your application, any "::" in
236 the name will be replaced with underscores, e.g. MyApp::Web should use
237 MYAPP_WEB_HOME. If both variables are set, the MYAPP_HOME one will be used.
238
239 =head2 -Log
240
241 Specifies log level.
242
243 =head1 METHODS
244
245 =head2 INFORMATION ABOUT THE CURRENT REQUEST
246
247 =head2 $c->action
248
249 Returns a L<Catalyst::Action> object for the current action, which
250 stringifies to the action name. See L<Catalyst::Action>.
251
252 =head2 $c->namespace
253
254 Returns the namespace of the current action, i.e., the URI prefix
255 corresponding to the controller of the current action. For example:
256
257     # in Controller::Foo::Bar
258     $c->namespace; # returns 'foo/bar';
259
260 =head2 $c->request
261
262 =head2 $c->req
263
264 Returns the current L<Catalyst::Request> object, giving access to
265 information about the current client request (including parameters,
266 cookies, HTTP headers, etc.). See L<Catalyst::Request>.
267
268 =head2 REQUEST FLOW HANDLING
269
270 =head2 $c->forward( $action [, \@arguments ] )
271
272 =head2 $c->forward( $class, $method, [, \@arguments ] )
273
274 Forwards processing to another action, by its private name. If you give a
275 class name but no method, C<process()> is called. You may also optionally
276 pass arguments in an arrayref. The action will receive the arguments in
277 C<@_> and C<< $c->req->args >>. Upon returning from the function,
278 C<< $c->req->args >> will be restored to the previous values.
279
280 Any data C<return>ed from the action forwarded to, will be returned by the
281 call to forward.
282
283     my $foodata = $c->forward('/foo');
284     $c->forward('index');
285     $c->forward(qw/MyApp::Model::DBIC::Foo do_stuff/);
286     $c->forward('MyApp::View::TT');
287
288 Note that forward implies an C<<eval { }>> around the call (actually
289 C<execute> does), thus de-fatalizing all 'dies' within the called
290 action. If you want C<die> to propagate you need to do something like:
291
292     $c->forward('foo');
293     die $c->error if $c->error;
294
295 Or make sure to always return true values from your actions and write
296 your code like this:
297
298     $c->forward('foo') || return;
299
300 =cut
301
302 sub forward { my $c = shift; $c->dispatcher->forward( $c, @_ ) }
303
304 =head2 $c->detach( $action [, \@arguments ] )
305
306 =head2 $c->detach( $class, $method, [, \@arguments ] )
307
308 =head2 $c->detach()
309
310 The same as C<forward>, but doesn't return to the previous action when 
311 processing is finished. 
312
313 When called with no arguments it escapes the processing chain entirely.
314
315 =cut
316
317 sub detach { my $c = shift; $c->dispatcher->detach( $c, @_ ) }
318
319 =head2 $c->response
320
321 =head2 $c->res
322
323 Returns the current L<Catalyst::Response> object, see there for details.
324
325 =head2 $c->stash
326
327 Returns a hashref to the stash, which may be used to store data and pass
328 it between components during a request. You can also set hash keys by
329 passing arguments. The stash is automatically sent to the view. The
330 stash is cleared at the end of a request; it cannot be used for
331 persistent storage (for this you must use a session; see
332 L<Catalyst::Plugin::Session> for a complete system integrated with
333 Catalyst).
334
335     $c->stash->{foo} = $bar;
336     $c->stash( { moose => 'majestic', qux => 0 } );
337     $c->stash( bar => 1, gorch => 2 ); # equivalent to passing a hashref
338     
339     # stash is automatically passed to the view for use in a template
340     $c->forward( 'MyApp::View::TT' );
341
342 =cut
343
344 sub stash {
345     my $c = shift;
346     if (@_) {
347         my $stash = @_ > 1 ? {@_} : $_[0];
348         croak('stash takes a hash or hashref') unless ref $stash;
349         foreach my $key ( keys %$stash ) {
350             $c->{stash}->{$key} = $stash->{$key};
351         }
352     }
353     return $c->{stash};
354 }
355
356 =head2 $c->error
357
358 =head2 $c->error($error, ...)
359
360 =head2 $c->error($arrayref)
361
362 Returns an arrayref containing error messages.  If Catalyst encounters an
363 error while processing a request, it stores the error in $c->error.  This
364 method should only be used to store fatal error messages.
365
366     my @error = @{ $c->error };
367
368 Add a new error.
369
370     $c->error('Something bad happened');
371
372 =cut
373
374 sub error {
375     my $c = shift;
376     if ( $_[0] ) {
377         my $error = ref $_[0] eq 'ARRAY' ? $_[0] : [@_];
378         croak @$error unless ref $c;
379         push @{ $c->{error} }, @$error;
380     }
381     elsif ( defined $_[0] ) { $c->{error} = undef }
382     return $c->{error} || [];
383 }
384
385
386 =head2 $c->state
387
388 Contains the return value of the last executed action.
389
390 =head2 $c->clear_errors
391
392 Clear errors.  You probably don't want to clear the errors unless you are
393 implementing a custom error screen.
394
395 This is equivalent to running
396
397     $c->error(0);
398
399 =cut
400
401 sub clear_errors {
402     my $c = shift;
403     $c->error(0);
404 }
405
406
407 # search via regex
408 sub _comp_search {
409     my ( $c, @names ) = @_;
410
411     foreach my $name (@names) {
412         foreach my $component ( keys %{ $c->components } ) {
413             return $c->components->{$component} if $component =~ /$name/i;
414         }
415     }
416
417     return undef;
418 }
419
420 # try explicit component names
421 sub _comp_explicit {
422     my ( $c, @names ) = @_;
423
424     foreach my $try (@names) {
425         return $c->components->{$try} if ( exists $c->components->{$try} );
426     }
427
428     return undef;
429 }
430
431 # like component, but try just these prefixes before regex searching,
432 #  and do not try to return "sort keys %{ $c->components }"
433 sub _comp_prefixes {
434     my ( $c, $name, @prefixes ) = @_;
435
436     my $appclass = ref $c || $c;
437
438     my @names = map { "${appclass}::${_}::${name}" } @prefixes;
439
440     my $comp = $c->_comp_explicit(@names);
441     return $comp if defined($comp);
442     $comp = $c->_comp_search($name);
443     return $comp;
444 }
445
446 # Find possible names for a prefix 
447
448 sub _comp_names {
449     my ( $c, @prefixes ) = @_;
450
451     my $appclass = ref $c || $c;
452
453     my @pre = map { "${appclass}::${_}::" } @prefixes;
454
455     my @names;
456
457     COMPONENT: foreach my $comp ($c->component) {
458         foreach my $p (@pre) {
459             if ($comp =~ s/^$p//) {
460                 push(@names, $comp);
461                 next COMPONENT;
462             }
463         }
464     }
465
466     return @names;
467 }
468
469 # Return a component if only one matches.
470 sub _comp_singular {
471     my ( $c, @prefixes ) = @_;
472
473     my $appclass = ref $c || $c;
474
475     my ( $comp, $rest ) =
476       map { $c->_comp_search("^${appclass}::${_}::") } @prefixes;
477     return $comp unless $rest;
478 }
479
480 # Filter a component before returning by calling ACCEPT_CONTEXT if available
481 sub _filter_component {
482     my ( $c, $comp, @args ) = @_;
483     if ( eval { $comp->can('ACCEPT_CONTEXT'); } ) {
484         return $comp->ACCEPT_CONTEXT( $c, @args );
485     }
486     else { return $comp }
487 }
488
489 =head2 COMPONENT ACCESSORS
490
491 =head2 $c->controller($name)
492
493 Gets a L<Catalyst::Controller> instance by name.
494
495     $c->controller('Foo')->do_stuff;
496
497 If the name is omitted, will return the controller for the dispatched
498 action.
499
500 =cut
501
502 sub controller {
503     my ( $c, $name, @args ) = @_;
504     return $c->_filter_component( $c->_comp_prefixes( $name, qw/Controller C/ ),
505         @args )
506       if ($name);
507     return $c->component( $c->action->class );
508 }
509
510 =head2 $c->model($name)
511
512 Gets a L<Catalyst::Model> instance by name.
513
514     $c->model('Foo')->do_stuff;
515
516 Any extra arguments are directly passed to ACCEPT_CONTEXT.
517
518 If the name is omitted, it will look for 
519  - a model object in $c->stash{current_model_instance}, then
520  - a model name in $c->stash->{current_model}, then
521  - a config setting 'default_model', or
522  - check if there is only one model, and return it if that's the case.
523
524 =cut
525
526 sub model {
527     my ( $c, $name, @args ) = @_;
528     return $c->_filter_component( $c->_comp_prefixes( $name, qw/Model M/ ),
529         @args )
530       if $name;
531     if (ref $c) {
532         return $c->stash->{current_model_instance} 
533           if $c->stash->{current_model_instance};
534         return $c->model( $c->stash->{current_model} )
535           if $c->stash->{current_model};
536     }
537     return $c->model( $c->config->{default_model} )
538       if $c->config->{default_model};
539     return $c->_filter_component( $c->_comp_singular(qw/Model M/) );
540
541 }
542
543 =head2 $c->controllers
544
545 Returns the available names which can be passed to $c->controller
546
547 =cut
548
549 sub controllers {
550     my ( $c ) = @_;
551     return $c->_comp_names(qw/Controller C/);
552 }
553
554
555 =head2 $c->view($name)
556
557 Gets a L<Catalyst::View> instance by name.
558
559     $c->view('Foo')->do_stuff;
560
561 Any extra arguments are directly passed to ACCEPT_CONTEXT.
562
563 If the name is omitted, it will look for 
564  - a view object in $c->stash{current_view_instance}, then
565  - a view name in $c->stash->{current_view}, then
566  - a config setting 'default_view', or
567  - check if there is only one view, and return it if that's the case.
568
569 =cut
570
571 sub view {
572     my ( $c, $name, @args ) = @_;
573     return $c->_filter_component( $c->_comp_prefixes( $name, qw/View V/ ),
574         @args )
575       if $name;
576     if (ref $c) {
577         return $c->stash->{current_view_instance} 
578           if $c->stash->{current_view_instance};
579         return $c->view( $c->stash->{current_view} )
580           if $c->stash->{current_view};
581     }
582     return $c->view( $c->config->{default_view} )
583       if $c->config->{default_view};
584     return $c->_filter_component( $c->_comp_singular(qw/View V/) );
585 }
586
587 =head2 $c->models
588
589 Returns the available names which can be passed to $c->model
590
591 =cut
592
593 sub models {
594     my ( $c ) = @_;
595     return $c->_comp_names(qw/Model M/);
596 }
597
598
599 =head2 $c->views
600
601 Returns the available names which can be passed to $c->view
602
603 =cut
604
605 sub views {
606     my ( $c ) = @_;
607     return $c->_comp_names(qw/View V/);
608 }
609
610 =head2 $c->comp($name)
611
612 =head2 $c->component($name)
613
614 Gets a component object by name. This method is not recommended,
615 unless you want to get a specific component by full
616 class. C<< $c->controller >>, C<< $c->model >>, and C<< $c->view >>
617 should be used instead.
618
619 =cut
620
621 sub component {
622     my $c = shift;
623
624     if (@_) {
625
626         my $name = shift;
627
628         my $appclass = ref $c || $c;
629
630         my @names = (
631             $name, "${appclass}::${name}",
632             map { "${appclass}::${_}::${name}" }
633               qw/Model M Controller C View V/
634         );
635
636         my $comp = $c->_comp_explicit(@names);
637         return $c->_filter_component( $comp, @_ ) if defined($comp);
638
639         $comp = $c->_comp_search($name);
640         return $c->_filter_component( $comp, @_ ) if defined($comp);
641     }
642
643     return sort keys %{ $c->components };
644 }
645
646
647
648 =head2 CLASS DATA AND HELPER CLASSES
649
650 =head2 $c->config
651
652 Returns or takes a hashref containing the application's configuration.
653
654     __PACKAGE__->config( { db => 'dsn:SQLite:foo.db' } );
655
656 You can also use a C<YAML>, C<XML> or C<Config::General> config file
657 like myapp.yml in your applications home directory. See
658 L<Catalyst::Plugin::ConfigLoader>.
659
660     ---
661     db: dsn:SQLite:foo.db
662
663
664 =cut
665
666 sub config {
667     my $c = shift;
668
669     $c->log->warn("Setting config after setup has been run is not a good idea.")
670       if ( @_ and $c->setup_finished );
671
672     $c->NEXT::config(@_);
673 }
674
675 =head2 $c->log
676
677 Returns the logging object instance. Unless it is already set, Catalyst
678 sets this up with a L<Catalyst::Log> object. To use your own log class,
679 set the logger with the C<< __PACKAGE__->log >> method prior to calling
680 C<< __PACKAGE__->setup >>.
681
682  __PACKAGE__->log( MyLogger->new );
683  __PACKAGE__->setup;
684
685 And later:
686
687     $c->log->info( 'Now logging with my own logger!' );
688
689 Your log class should implement the methods described in
690 L<Catalyst::Log>.
691
692
693 =head2 $c->debug
694
695 Overload to enable debug messages (same as -Debug option).
696
697 Note that this is a static method, not an accessor and should be overloaded
698 by declaring "sub debug { 1 }" in your MyApp.pm, not by calling $c->debug(1).
699
700 =cut
701
702 sub debug { 0 }
703
704 =head2 $c->dispatcher
705
706 Returns the dispatcher instance. Stringifies to class name. See
707 L<Catalyst::Dispatcher>.
708
709 =head2 $c->engine
710
711 Returns the engine instance. Stringifies to the class name. See
712 L<Catalyst::Engine>.
713
714
715 =head2 UTILITY METHODS
716
717 =head2 $c->path_to(@path)
718
719 Merges C<@path> with C<< $c->config->{home} >> and returns a
720 L<Path::Class::Dir> object.
721
722 For example:
723
724     $c->path_to( 'db', 'sqlite.db' );
725
726 =cut
727
728 sub path_to {
729     my ( $c, @path ) = @_;
730     my $path = Path::Class::Dir->new( $c->config->{home}, @path );
731     if ( -d $path ) { return $path }
732     else { return Path::Class::File->new( $c->config->{home}, @path ) }
733 }
734
735 =head2 $c->plugin( $name, $class, @args )
736
737 Helper method for plugins. It creates a classdata accessor/mutator and
738 loads and instantiates the given class.
739
740     MyApp->plugin( 'prototype', 'HTML::Prototype' );
741
742     $c->prototype->define_javascript_functions;
743
744 =cut
745
746 sub plugin {
747     my ( $class, $name, $plugin, @args ) = @_;
748     $class->_register_plugin( $plugin, 1 );
749
750     eval { $plugin->import };
751     $class->mk_classdata($name);
752     my $obj;
753     eval { $obj = $plugin->new(@args) };
754
755     if ($@) {
756         Catalyst::Exception->throw( message =>
757               qq/Couldn't instantiate instant plugin "$plugin", "$@"/ );
758     }
759
760     $class->$name($obj);
761     $class->log->debug(qq/Initialized instant plugin "$plugin" as "$name"/)
762       if $class->debug;
763 }
764
765 =head2 MyApp->setup
766
767 Initializes the dispatcher and engine, loads any plugins, and loads the
768 model, view, and controller components. You may also specify an array
769 of plugins to load here, if you choose to not load them in the C<use
770 Catalyst> line.
771
772     MyApp->setup;
773     MyApp->setup( qw/-Debug/ );
774
775 =cut
776
777 sub setup {
778     my ( $class, @arguments ) = @_;
779
780     $class->log->warn("Running setup twice is not a good idea.")
781       if ( $class->setup_finished );
782
783     unless ( $class->isa('Catalyst') ) {
784
785         Catalyst::Exception->throw(
786             message => qq/'$class' does not inherit from Catalyst/ );
787     }
788
789     if ( $class->arguments ) {
790         @arguments = ( @arguments, @{ $class->arguments } );
791     }
792
793     # Process options
794     my $flags = {};
795
796     foreach (@arguments) {
797
798         if (/^-Debug$/) {
799             $flags->{log} =
800               ( $flags->{log} ) ? 'debug,' . $flags->{log} : 'debug';
801         }
802         elsif (/^-(\w+)=?(.*)$/) {
803             $flags->{ lc $1 } = $2;
804         }
805         else {
806             push @{ $flags->{plugins} }, $_;
807         }
808     }
809
810     $class->setup_home( delete $flags->{home} );
811
812     $class->setup_log( delete $flags->{log} );
813     $class->setup_plugins( delete $flags->{plugins} );
814     $class->setup_dispatcher( delete $flags->{dispatcher} );
815     $class->setup_engine( delete $flags->{engine} );
816
817     for my $flag ( sort keys %{$flags} ) {
818
819         if ( my $code = $class->can( 'setup_' . $flag ) ) {
820             &$code( $class, delete $flags->{$flag} );
821         }
822         else {
823             $class->log->warn(qq/Unknown flag "$flag"/);
824         }
825     }
826
827     eval { require Catalyst::Devel; };
828     if( !$@ && $ENV{CATALYST_SCRIPT_GEN} && ( $ENV{CATALYST_SCRIPT_GEN} < $Catalyst::Devel::CATALYST_SCRIPT_GEN ) ) {
829         $class->log->warn(<<"EOF");
830 You are running an old script!
831
832   Please update by running (this will overwrite existing files):
833     catalyst.pl -force -scripts $class
834
835   or (this will not overwrite existing files):
836     catalyst.pl -scripts $class
837
838 EOF
839     }
840     
841     if ( $class->debug ) {
842         my @plugins = map { "$_  " . ( $_->VERSION || '' ) } $class->registered_plugins;
843
844         if (@plugins) {
845             my $t = Text::SimpleTable->new(74);
846             $t->row($_) for @plugins;
847             $class->log->debug( "Loaded plugins:\n" . $t->draw . "\n" );
848         }
849
850         my $dispatcher = $class->dispatcher;
851         my $engine     = $class->engine;
852         my $home       = $class->config->{home};
853
854         $class->log->debug(qq/Loaded dispatcher "$dispatcher"/);
855         $class->log->debug(qq/Loaded engine "$engine"/);
856
857         $home
858           ? ( -d $home )
859           ? $class->log->debug(qq/Found home "$home"/)
860           : $class->log->debug(qq/Home "$home" doesn't exist/)
861           : $class->log->debug(q/Couldn't find home/);
862     }
863
864     # Call plugins setup
865     {
866         no warnings qw/redefine/;
867         local *setup = sub { };
868         $class->setup;
869     }
870
871     # Initialize our data structure
872     $class->components( {} );
873
874     $class->setup_components;
875
876     if ( $class->debug ) {
877         my $t = Text::SimpleTable->new( [ 63, 'Class' ], [ 8, 'Type' ] );
878         for my $comp ( sort keys %{ $class->components } ) {
879             my $type = ref $class->components->{$comp} ? 'instance' : 'class';
880             $t->row( $comp, $type );
881         }
882         $class->log->debug( "Loaded components:\n" . $t->draw . "\n" )
883           if ( keys %{ $class->components } );
884     }
885
886     # Add our self to components, since we are also a component
887     $class->components->{$class} = $class;
888
889     $class->setup_actions;
890
891     if ( $class->debug ) {
892         my $name = $class->config->{name} || 'Application';
893         $class->log->info("$name powered by Catalyst $Catalyst::VERSION");
894     }
895     $class->log->_flush() if $class->log->can('_flush');
896
897     $class->setup_finished(1);
898 }
899
900 =head2 $c->uri_for( $path, @args?, \%query_values? )
901
902 Merges path with C<< $c->request->base >> for absolute URIs and with
903 C<< $c->namespace >> for relative URIs, then returns a normalized L<URI>
904 object. If any args are passed, they are added at the end of the path.
905 If the last argument to C<uri_for> is a hash reference, it is assumed to
906 contain GET parameter key/value pairs, which will be appended to the URI
907 in standard fashion.
908
909 Instead of C<$path>, you can also optionally pass a C<$action> object
910 which will be resolved to a path using
911 C<< $c->dispatcher->uri_for_action >>; if the first element of
912 C<@args> is an arrayref it is treated as a list of captures to be passed
913 to C<uri_for_action>.
914
915 =cut
916
917 sub uri_for {
918     my ( $c, $path, @args ) = @_;
919
920     if ( Scalar::Util::blessed($path) ) { # action object
921         my $captures = ( scalar @args && ref $args[0] eq 'ARRAY'
922                          ? shift(@args)
923                          : [] );
924         $path = $c->dispatcher->uri_for_action($path, $captures);
925         return undef unless defined($path);
926         $path = '/' if $path eq '';
927     }
928
929     undef($path) if (defined $path && $path eq '');
930
931     my $params =
932       ( scalar @args && ref $args[$#args] eq 'HASH' ? pop @args : {} );
933
934     carp "uri_for called with undef argument" if grep { ! defined $_ } @args;
935     s/([^$URI::uric])/$URI::Escape::escapes{$1}/go for @args;
936
937     unshift(@args, $path);
938
939     unless (defined $path && $path =~ s!^/!!) { # in-place strip
940         my $namespace = $c->namespace;
941         if (defined $path) { # cheesy hack to handle path '../foo'
942            $namespace =~ s{(?:^|/)[^/]+$}{} while $args[0] =~ s{^\.\./}{};
943         }
944         unshift(@args, $namespace || '');
945     }
946     
947     # join args with '/', or a blank string
948     my $args = join('/', grep { defined($_) } @args);
949     $args =~ s/\?/%3F/g; # STUPID STUPID SPECIAL CASE
950     $args =~ s!^/!!;
951     my $base = $c->req->base;
952     my $class = ref($base);
953     $base =~ s{(?<!/)$}{/};
954
955     my $query = '';
956
957     if (my @keys = keys %$params) {
958       # somewhat lifted from URI::_query's query_form
959       $query = '?'.join('&', map {
960           s/([;\/?:@&=+,\$\[\]%])/$URI::Escape::escapes{$1}/go;
961           s/ /+/g;
962           my $key = $_;
963           my $val = $params->{$_};
964           $val = '' unless defined $val;
965           (map {
966               $_ = "$_";
967               utf8::encode( $_ );
968               # using the URI::Escape pattern here so utf8 chars survive
969               s/([^A-Za-z0-9\-_.!~*'() ])/$URI::Escape::escapes{$1}/go;
970               s/ /+/g;
971               "${key}=$_"; } ( ref $val eq 'ARRAY' ? @$val : $val ));
972       } @keys);
973     }
974
975     my $res = bless(\"${base}${args}${query}", $class);
976     $res;
977 }
978
979 =head2 $c->welcome_message
980
981 Returns the Catalyst welcome HTML page.
982
983 =cut
984
985 sub welcome_message {
986     my $c      = shift;
987     my $name   = $c->config->{name};
988     my $logo   = $c->uri_for('/static/images/catalyst_logo.png');
989     my $prefix = Catalyst::Utils::appprefix( ref $c );
990     $c->response->content_type('text/html; charset=utf-8');
991     return <<"EOF";
992 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
993     "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
994 <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
995     <head>
996     <meta http-equiv="Content-Language" content="en" />
997     <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
998         <title>$name on Catalyst $VERSION</title>
999         <style type="text/css">
1000             body {
1001                 color: #000;
1002                 background-color: #eee;
1003             }
1004             div#content {
1005                 width: 640px;
1006                 margin-left: auto;
1007                 margin-right: auto;
1008                 margin-top: 10px;
1009                 margin-bottom: 10px;
1010                 text-align: left;
1011                 background-color: #ccc;
1012                 border: 1px solid #aaa;
1013             }
1014             p, h1, h2 {
1015                 margin-left: 20px;
1016                 margin-right: 20px;
1017                 font-family: verdana, tahoma, sans-serif;
1018             }
1019             a {
1020                 font-family: verdana, tahoma, sans-serif;
1021             }
1022             :link, :visited {
1023                     text-decoration: none;
1024                     color: #b00;
1025                     border-bottom: 1px dotted #bbb;
1026             }
1027             :link:hover, :visited:hover {
1028                     color: #555;
1029             }
1030             div#topbar {
1031                 margin: 0px;
1032             }
1033             pre {
1034                 margin: 10px;
1035                 padding: 8px;
1036             }
1037             div#answers {
1038                 padding: 8px;
1039                 margin: 10px;
1040                 background-color: #fff;
1041                 border: 1px solid #aaa;
1042             }
1043             h1 {
1044                 font-size: 0.9em;
1045                 font-weight: normal;
1046                 text-align: center;
1047             }
1048             h2 {
1049                 font-size: 1.0em;
1050             }
1051             p {
1052                 font-size: 0.9em;
1053             }
1054             p img {
1055                 float: right;
1056                 margin-left: 10px;
1057             }
1058             span#appname {
1059                 font-weight: bold;
1060                 font-size: 1.6em;
1061             }
1062         </style>
1063     </head>
1064     <body>
1065         <div id="content">
1066             <div id="topbar">
1067                 <h1><span id="appname">$name</span> on <a href="http://catalyst.perl.org">Catalyst</a>
1068                     $VERSION</h1>
1069              </div>
1070              <div id="answers">
1071                  <p>
1072                  <img src="$logo" alt="Catalyst Logo" />
1073                  </p>
1074                  <p>Welcome to the  world of Catalyst.
1075                     This <a href="http://en.wikipedia.org/wiki/MVC">MVC</a>
1076                     framework will make web development something you had
1077                     never expected it to be: Fun, rewarding, and quick.</p>
1078                  <h2>What to do now?</h2>
1079                  <p>That really depends  on what <b>you</b> want to do.
1080                     We do, however, provide you with a few starting points.</p>
1081                  <p>If you want to jump right into web development with Catalyst
1082                     you might want want to start with a tutorial.</p>
1083 <pre>perldoc <a href="http://cpansearch.perl.org/dist/Catalyst-Manual/lib/Catalyst/Manual/Tutorial.pod">Catalyst::Manual::Tutorial</a></code>
1084 </pre>
1085 <p>Afterwards you can go on to check out a more complete look at our features.</p>
1086 <pre>
1087 <code>perldoc <a href="http://cpansearch.perl.org/dist/Catalyst-Manual/lib/Catalyst/Manual/Intro.pod">Catalyst::Manual::Intro</a>
1088 <!-- Something else should go here, but the Catalyst::Manual link seems unhelpful -->
1089 </code></pre>
1090                  <h2>What to do next?</h2>
1091                  <p>Next it's time to write an actual application. Use the
1092                     helper scripts to generate <a href="http://cpansearch.perl.org/search?query=Catalyst%3A%3AController%3A%3A&amp;mode=all">controllers</a>,
1093                     <a href="http://cpansearch.perl.org/search?query=Catalyst%3A%3AModel%3A%3A&amp;mode=all">models</a>, and
1094                     <a href="http://cpansearch.perl.org/search?query=Catalyst%3A%3AView%3A%3A&amp;mode=all">views</a>;
1095                     they can save you a lot of work.</p>
1096                     <pre><code>script/${prefix}_create.pl -help</code></pre>
1097                     <p>Also, be sure to check out the vast and growing
1098                     collection of <a href="http://cpansearch.perl.org/search?query=Catalyst%3A%3APlugin%3A%3A&amp;mode=all">plugins for Catalyst on CPAN</a>;
1099                     you are likely to find what you need there.
1100                     </p>
1101
1102                  <h2>Need help?</h2>
1103                  <p>Catalyst has a very active community. Here are the main places to
1104                     get in touch with us.</p>
1105                  <ul>
1106                      <li>
1107                          <a href="http://dev.catalyst.perl.org">Wiki</a>
1108                      </li>
1109                      <li>
1110                          <a href="http://lists.rawmode.org/mailman/listinfo/catalyst">Mailing-List</a>
1111                      </li>
1112                      <li>
1113                          <a href="irc://irc.perl.org/catalyst">IRC channel #catalyst on irc.perl.org</a>
1114                      </li>
1115                  </ul>
1116                  <h2>In conclusion</h2>
1117                  <p>The Catalyst team hopes you will enjoy using Catalyst as much 
1118                     as we enjoyed making it. Please contact us if you have ideas
1119                     for improvement or other feedback.</p>
1120              </div>
1121          </div>
1122     </body>
1123 </html>
1124 EOF
1125 }
1126
1127 =head1 INTERNAL METHODS
1128
1129 These methods are not meant to be used by end users.
1130
1131 =head2 $c->components
1132
1133 Returns a hash of components.
1134
1135 =head2 $c->context_class
1136
1137 Returns or sets the context class.
1138
1139 =head2 $c->counter
1140
1141 Returns a hashref containing coderefs and execution counts (needed for
1142 deep recursion detection).
1143
1144 =head2 $c->depth
1145
1146 Returns the number of actions on the current internal execution stack.
1147
1148 =head2 $c->dispatch
1149
1150 Dispatches a request to actions.
1151
1152 =cut
1153
1154 sub dispatch { my $c = shift; $c->dispatcher->dispatch( $c, @_ ) }
1155
1156 =head2 $c->dispatcher_class
1157
1158 Returns or sets the dispatcher class.
1159
1160 =head2 $c->dump_these
1161
1162 Returns a list of 2-element array references (name, structure) pairs
1163 that will be dumped on the error page in debug mode.
1164
1165 =cut
1166
1167 sub dump_these {
1168     my $c = shift;
1169     [ Request => $c->req ], 
1170     [ Response => $c->res ], 
1171     [ Stash => $c->stash ],
1172     [ Config => $c->config ];
1173 }
1174
1175 =head2 $c->engine_class
1176
1177 Returns or sets the engine class.
1178
1179 =head2 $c->execute( $class, $coderef )
1180
1181 Execute a coderef in given class and catch exceptions. Errors are available
1182 via $c->error.
1183
1184 =cut
1185
1186 sub execute {
1187     my ( $c, $class, $code ) = @_;
1188     $class = $c->component($class) || $class;
1189     $c->state(0);
1190
1191     if ( $c->depth >= $RECURSION ) {
1192         my $action = "$code";
1193         $action = "/$action" unless $action =~ /->/;
1194         my $error = qq/Deep recursion detected calling "$action"/;
1195         $c->log->error($error);
1196         $c->error($error);
1197         $c->state(0);
1198         return $c->state;
1199     }
1200
1201     my $stats_info = $c->_stats_start_execute( $code ) if $c->debug;
1202
1203     push( @{ $c->stack }, $code );
1204     
1205     eval { $c->state( &$code( $class, $c, @{ $c->req->args } ) || 0 ) };
1206
1207     $c->_stats_finish_execute( $stats_info ) if $c->debug and $stats_info;
1208     
1209     my $last = pop( @{ $c->stack } );
1210
1211     if ( my $error = $@ ) {
1212         if ( !ref($error) and $error eq $DETACH ) { die $DETACH if $c->depth > 1 }
1213         else {
1214             unless ( ref $error ) {
1215                 no warnings 'uninitialized';
1216                 chomp $error;
1217                 my $class = $last->class;
1218                 my $name  = $last->name;
1219                 $error = qq/Caught exception in $class->$name "$error"/;
1220             }
1221             $c->error($error);
1222             $c->state(0);
1223         }
1224     }
1225     return $c->state;
1226 }
1227
1228 sub _stats_start_execute {
1229     my ( $c, $code ) = @_;
1230
1231     return if ( ( $code->name =~ /^_.*/ )
1232         && ( !$c->config->{show_internal_actions} ) );
1233
1234     $c->counter->{"$code"}++;
1235
1236     my $action = "$code";
1237     $action = "/$action" unless $action =~ /->/;
1238
1239     # determine if the call was the result of a forward
1240     # this is done by walking up the call stack and looking for a calling
1241     # sub of Catalyst::forward before the eval
1242     my $callsub = q{};
1243     for my $index ( 2 .. 11 ) {
1244         last
1245         if ( ( caller($index) )[0] eq 'Catalyst'
1246             && ( caller($index) )[3] eq '(eval)' );
1247
1248         if ( ( caller($index) )[3] =~ /forward$/ ) {
1249             $callsub = ( caller($index) )[3];
1250             $action  = "-> $action";
1251             last;
1252         }
1253     }
1254
1255     my $node = Tree::Simple->new(
1256         {
1257             action  => $action,
1258             elapsed => undef,     # to be filled in later
1259             comment => "",
1260         }
1261     );
1262     $node->setUID( "$code" . $c->counter->{"$code"} );
1263
1264     # is this a root-level call or a forwarded call?
1265     if ( $callsub =~ /forward$/ ) {
1266
1267         # forward, locate the caller
1268         if ( my $parent = $c->stack->[-1] ) {
1269             my $visitor = Tree::Simple::Visitor::FindByUID->new;
1270             $visitor->searchForUID(
1271                 "$parent" . $c->counter->{"$parent"} );
1272             $c->stats->accept($visitor);
1273             if ( my $result = $visitor->getResult ) {
1274                 $result->addChild($node);
1275             }
1276         }
1277         else {
1278
1279             # forward with no caller may come from a plugin
1280             $c->stats->addChild($node);
1281         }
1282     }
1283     else {
1284
1285         # root-level call
1286         $c->stats->addChild($node);
1287     }
1288
1289     return {
1290         start   => [gettimeofday],
1291         node    => $node,
1292     };
1293 }
1294
1295 sub _stats_finish_execute {
1296     my ( $c, $info ) = @_;
1297     my $elapsed = tv_interval $info->{start};
1298     my $value = $info->{node}->getNodeValue;
1299     $value->{elapsed} = sprintf( '%fs', $elapsed );
1300 }
1301
1302 =head2 $c->_localize_fields( sub { }, \%keys );
1303
1304 =cut
1305
1306 sub _localize_fields {
1307     my ( $c, $localized, $code ) = ( @_ );
1308
1309     my $request = delete $localized->{request} || {};
1310     my $response = delete $localized->{response} || {};
1311     
1312     local @{ $c }{ keys %$localized } = values %$localized;
1313     local @{ $c->request }{ keys %$request } = values %$request;
1314     local @{ $c->response }{ keys %$response } = values %$response;
1315
1316     $code->();
1317 }
1318
1319 =head2 $c->finalize
1320
1321 Finalizes the request.
1322
1323 =cut
1324
1325 sub finalize {
1326     my $c = shift;
1327
1328     for my $error ( @{ $c->error } ) {
1329         $c->log->error($error);
1330     }
1331
1332     # Allow engine to handle finalize flow (for POE)
1333     if ( $c->engine->can('finalize') ) {
1334         $c->engine->finalize($c);
1335     }
1336     else {
1337
1338         $c->finalize_uploads;
1339
1340         # Error
1341         if ( $#{ $c->error } >= 0 ) {
1342             $c->finalize_error;
1343         }
1344
1345         $c->finalize_headers;
1346
1347         # HEAD request
1348         if ( $c->request->method eq 'HEAD' ) {
1349             $c->response->body('');
1350         }
1351
1352         $c->finalize_body;
1353     }
1354     
1355     if ($c->debug) {
1356         my $elapsed = sprintf '%f', tv_interval($c->stats->getNodeValue);
1357         my $av = $elapsed == 0 ? '??' : sprintf '%.3f', 1 / $elapsed;
1358         
1359         my $t = Text::SimpleTable->new( [ 62, 'Action' ], [ 9, 'Time' ] );
1360         $c->stats->traverse(
1361             sub {
1362                 my $action = shift;
1363                 my $stat   = $action->getNodeValue;
1364                 $t->row( ( q{ } x $action->getDepth ) . $stat->{action} . $stat->{comment},
1365                     $stat->{elapsed} || '??' );
1366             }
1367         );
1368
1369         $c->log->info(
1370             "Request took ${elapsed}s ($av/s)\n" . $t->draw . "\n" );        
1371     }
1372
1373     return $c->response->status;
1374 }
1375
1376 =head2 $c->finalize_body
1377
1378 Finalizes body.
1379
1380 =cut
1381
1382 sub finalize_body { my $c = shift; $c->engine->finalize_body( $c, @_ ) }
1383
1384 =head2 $c->finalize_cookies
1385
1386 Finalizes cookies.
1387
1388 =cut
1389
1390 sub finalize_cookies { my $c = shift; $c->engine->finalize_cookies( $c, @_ ) }
1391
1392 =head2 $c->finalize_error
1393
1394 Finalizes error.
1395
1396 =cut
1397
1398 sub finalize_error { my $c = shift; $c->engine->finalize_error( $c, @_ ) }
1399
1400 =head2 $c->finalize_headers
1401
1402 Finalizes headers.
1403
1404 =cut
1405
1406 sub finalize_headers {
1407     my $c = shift;
1408
1409     # Check if we already finalized headers
1410     return if $c->response->{_finalized_headers};
1411
1412     # Handle redirects
1413     if ( my $location = $c->response->redirect ) {
1414         $c->log->debug(qq/Redirecting to "$location"/) if $c->debug;
1415         $c->response->header( Location => $location );
1416         
1417         if ( !$c->response->body ) {
1418             # Add a default body if none is already present
1419             $c->response->body(
1420                 qq{<html><body><p>This item has moved <a href="$location">here</a>.</p></body></html>}
1421             );
1422         }
1423     }
1424
1425     # Content-Length
1426     if ( $c->response->body && !$c->response->content_length ) {
1427
1428         # get the length from a filehandle
1429         if ( blessed( $c->response->body ) && $c->response->body->can('read') )
1430         {
1431             my $stat = stat $c->response->body;
1432             if ( $stat && $stat->size > 0 ) {
1433                 $c->response->content_length( $stat->size );
1434             }
1435             else {
1436                 $c->log->warn('Serving filehandle without a content-length');
1437             }
1438         }
1439         else {
1440             $c->response->content_length( bytes::length( $c->response->body ) );
1441         }
1442     }
1443
1444     # Errors
1445     if ( $c->response->status =~ /^(1\d\d|[23]04)$/ ) {
1446         $c->response->headers->remove_header("Content-Length");
1447         $c->response->body('');
1448     }
1449
1450     $c->finalize_cookies;
1451
1452     $c->engine->finalize_headers( $c, @_ );
1453
1454     # Done
1455     $c->response->{_finalized_headers} = 1;
1456 }
1457
1458 =head2 $c->finalize_output
1459
1460 An alias for finalize_body.
1461
1462 =head2 $c->finalize_read
1463
1464 Finalizes the input after reading is complete.
1465
1466 =cut
1467
1468 sub finalize_read { my $c = shift; $c->engine->finalize_read( $c, @_ ) }
1469
1470 =head2 $c->finalize_uploads
1471
1472 Finalizes uploads. Cleans up any temporary files.
1473
1474 =cut
1475
1476 sub finalize_uploads { my $c = shift; $c->engine->finalize_uploads( $c, @_ ) }
1477
1478 =head2 $c->get_action( $action, $namespace )
1479
1480 Gets an action in a given namespace.
1481
1482 =cut
1483
1484 sub get_action { my $c = shift; $c->dispatcher->get_action(@_) }
1485
1486 =head2 $c->get_actions( $action, $namespace )
1487
1488 Gets all actions of a given name in a namespace and all parent
1489 namespaces.
1490
1491 =cut
1492
1493 sub get_actions { my $c = shift; $c->dispatcher->get_actions( $c, @_ ) }
1494
1495 =head2 $c->handle_request( $class, @arguments )
1496
1497 Called to handle each HTTP request.
1498
1499 =cut
1500
1501 sub handle_request {
1502     my ( $class, @arguments ) = @_;
1503
1504     # Always expect worst case!
1505     my $status = -1;
1506     eval {
1507         if ($class->debug) {
1508             my $secs = time - $START || 1;
1509             my $av = sprintf '%.3f', $COUNT / $secs;
1510             my $time = localtime time;
1511             $class->log->info("*** Request $COUNT ($av/s) [$$] [$time] ***");
1512         }
1513
1514         my $c = $class->prepare(@arguments);
1515         $c->dispatch;
1516         $status = $c->finalize;   
1517     };
1518
1519     if ( my $error = $@ ) {
1520         chomp $error;
1521         $class->log->error(qq/Caught exception in engine "$error"/);
1522     }
1523
1524     $COUNT++;
1525     $class->log->_flush() if $class->log->can('_flush');
1526     return $status;
1527 }
1528
1529 =head2 $c->prepare( @arguments )
1530
1531 Creates a Catalyst context from an engine-specific request (Apache, CGI,
1532 etc.).
1533
1534 =cut
1535
1536 sub prepare {
1537     my ( $class, @arguments ) = @_;
1538
1539     $class->context_class( ref $class || $class ) unless $class->context_class;
1540     my $c = $class->context_class->new(
1541         {
1542             counter => {},
1543             stack   => [],
1544             request => $class->request_class->new(
1545                 {
1546                     arguments        => [],
1547                     body_parameters  => {},
1548                     cookies          => {},
1549                     headers          => HTTP::Headers->new,
1550                     parameters       => {},
1551                     query_parameters => {},
1552                     secure           => 0,
1553                     captures         => [],
1554                     uploads          => {}
1555                 }
1556             ),
1557             response => $class->response_class->new(
1558                 {
1559                     body    => '',
1560                     cookies => {},
1561                     headers => HTTP::Headers->new(),
1562                     status  => 200
1563                 }
1564             ),
1565             stash => {},
1566             state => 0
1567         }
1568     );
1569
1570     if ( $c->debug ) {
1571         $c->stats(Tree::Simple->new([gettimeofday]));
1572         $c->res->headers->header( 'X-Catalyst' => $Catalyst::VERSION );            
1573     }
1574
1575     # For on-demand data
1576     $c->request->{_context}  = $c;
1577     $c->response->{_context} = $c;
1578     weaken( $c->request->{_context} );
1579     weaken( $c->response->{_context} );
1580
1581     # Allow engine to direct the prepare flow (for POE)
1582     if ( $c->engine->can('prepare') ) {
1583         $c->engine->prepare( $c, @arguments );
1584     }
1585     else {
1586         $c->prepare_request(@arguments);
1587         $c->prepare_connection;
1588         $c->prepare_query_parameters;
1589         $c->prepare_headers;
1590         $c->prepare_cookies;
1591         $c->prepare_path;
1592
1593         # On-demand parsing
1594         $c->prepare_body unless $c->config->{parse_on_demand};
1595     }
1596
1597     my $method  = $c->req->method  || '';
1598     my $path    = $c->req->path    || '/';
1599     my $address = $c->req->address || '';
1600
1601     $c->log->debug(qq/"$method" request for "$path" from "$address"/)
1602       if $c->debug;
1603
1604     $c->prepare_action;
1605
1606     return $c;
1607 }
1608
1609 =head2 $c->prepare_action
1610
1611 Prepares action. See L<Catalyst::Dispatcher>.
1612
1613 =cut
1614
1615 sub prepare_action { my $c = shift; $c->dispatcher->prepare_action( $c, @_ ) }
1616
1617 =head2 $c->prepare_body
1618
1619 Prepares message body.
1620
1621 =cut
1622
1623 sub prepare_body {
1624     my $c = shift;
1625
1626     # Do we run for the first time?
1627     return if defined $c->request->{_body};
1628
1629     # Initialize on-demand data
1630     $c->engine->prepare_body( $c, @_ );
1631     $c->prepare_parameters;
1632     $c->prepare_uploads;
1633
1634     if ( $c->debug && keys %{ $c->req->body_parameters } ) {
1635         my $t = Text::SimpleTable->new( [ 35, 'Parameter' ], [ 36, 'Value' ] );
1636         for my $key ( sort keys %{ $c->req->body_parameters } ) {
1637             my $param = $c->req->body_parameters->{$key};
1638             my $value = defined($param) ? $param : '';
1639             $t->row( $key,
1640                 ref $value eq 'ARRAY' ? ( join ', ', @$value ) : $value );
1641         }
1642         $c->log->debug( "Body Parameters are:\n" . $t->draw );
1643     }
1644 }
1645
1646 =head2 $c->prepare_body_chunk( $chunk )
1647
1648 Prepares a chunk of data before sending it to L<HTTP::Body>.
1649
1650 See L<Catalyst::Engine>.
1651
1652 =cut
1653
1654 sub prepare_body_chunk {
1655     my $c = shift;
1656     $c->engine->prepare_body_chunk( $c, @_ );
1657 }
1658
1659 =head2 $c->prepare_body_parameters
1660
1661 Prepares body parameters.
1662
1663 =cut
1664
1665 sub prepare_body_parameters {
1666     my $c = shift;
1667     $c->engine->prepare_body_parameters( $c, @_ );
1668 }
1669
1670 =head2 $c->prepare_connection
1671
1672 Prepares connection.
1673
1674 =cut
1675
1676 sub prepare_connection {
1677     my $c = shift;
1678     $c->engine->prepare_connection( $c, @_ );
1679 }
1680
1681 =head2 $c->prepare_cookies
1682
1683 Prepares cookies.
1684
1685 =cut
1686
1687 sub prepare_cookies { my $c = shift; $c->engine->prepare_cookies( $c, @_ ) }
1688
1689 =head2 $c->prepare_headers
1690
1691 Prepares headers.
1692
1693 =cut
1694
1695 sub prepare_headers { my $c = shift; $c->engine->prepare_headers( $c, @_ ) }
1696
1697 =head2 $c->prepare_parameters
1698
1699 Prepares parameters.
1700
1701 =cut
1702
1703 sub prepare_parameters {
1704     my $c = shift;
1705     $c->prepare_body_parameters;
1706     $c->engine->prepare_parameters( $c, @_ );
1707 }
1708
1709 =head2 $c->prepare_path
1710
1711 Prepares path and base.
1712
1713 =cut
1714
1715 sub prepare_path { my $c = shift; $c->engine->prepare_path( $c, @_ ) }
1716
1717 =head2 $c->prepare_query_parameters
1718
1719 Prepares query parameters.
1720
1721 =cut
1722
1723 sub prepare_query_parameters {
1724     my $c = shift;
1725
1726     $c->engine->prepare_query_parameters( $c, @_ );
1727
1728     if ( $c->debug && keys %{ $c->request->query_parameters } ) {
1729         my $t = Text::SimpleTable->new( [ 35, 'Parameter' ], [ 36, 'Value' ] );
1730         for my $key ( sort keys %{ $c->req->query_parameters } ) {
1731             my $param = $c->req->query_parameters->{$key};
1732             my $value = defined($param) ? $param : '';
1733             $t->row( $key,
1734                 ref $value eq 'ARRAY' ? ( join ', ', @$value ) : $value );
1735         }
1736         $c->log->debug( "Query Parameters are:\n" . $t->draw );
1737     }
1738 }
1739
1740 =head2 $c->prepare_read
1741
1742 Prepares the input for reading.
1743
1744 =cut
1745
1746 sub prepare_read { my $c = shift; $c->engine->prepare_read( $c, @_ ) }
1747
1748 =head2 $c->prepare_request
1749
1750 Prepares the engine request.
1751
1752 =cut
1753
1754 sub prepare_request { my $c = shift; $c->engine->prepare_request( $c, @_ ) }
1755
1756 =head2 $c->prepare_uploads
1757
1758 Prepares uploads.
1759
1760 =cut
1761
1762 sub prepare_uploads {
1763     my $c = shift;
1764
1765     $c->engine->prepare_uploads( $c, @_ );
1766
1767     if ( $c->debug && keys %{ $c->request->uploads } ) {
1768         my $t = Text::SimpleTable->new(
1769             [ 12, 'Parameter' ],
1770             [ 26, 'Filename' ],
1771             [ 18, 'Type' ],
1772             [ 9,  'Size' ]
1773         );
1774         for my $key ( sort keys %{ $c->request->uploads } ) {
1775             my $upload = $c->request->uploads->{$key};
1776             for my $u ( ref $upload eq 'ARRAY' ? @{$upload} : ($upload) ) {
1777                 $t->row( $key, $u->filename, $u->type, $u->size );
1778             }
1779         }
1780         $c->log->debug( "File Uploads are:\n" . $t->draw );
1781     }
1782 }
1783
1784 =head2 $c->prepare_write
1785
1786 Prepares the output for writing.
1787
1788 =cut
1789
1790 sub prepare_write { my $c = shift; $c->engine->prepare_write( $c, @_ ) }
1791
1792 =head2 $c->request_class
1793
1794 Returns or sets the request class.
1795
1796 =head2 $c->response_class
1797
1798 Returns or sets the response class.
1799
1800 =head2 $c->read( [$maxlength] )
1801
1802 Reads a chunk of data from the request body. This method is designed to
1803 be used in a while loop, reading C<$maxlength> bytes on every call.
1804 C<$maxlength> defaults to the size of the request if not specified.
1805
1806 You have to set C<< MyApp->config->{parse_on_demand} >> to use this
1807 directly.
1808
1809 =cut
1810
1811 sub read { my $c = shift; return $c->engine->read( $c, @_ ) }
1812
1813 =head2 $c->run
1814
1815 Starts the engine.
1816
1817 =cut
1818
1819 sub run { my $c = shift; return $c->engine->run( $c, @_ ) }
1820
1821 =head2 $c->set_action( $action, $code, $namespace, $attrs )
1822
1823 Sets an action in a given namespace.
1824
1825 =cut
1826
1827 sub set_action { my $c = shift; $c->dispatcher->set_action( $c, @_ ) }
1828
1829 =head2 $c->setup_actions($component)
1830
1831 Sets up actions for a component.
1832
1833 =cut
1834
1835 sub setup_actions { my $c = shift; $c->dispatcher->setup_actions( $c, @_ ) }
1836
1837 =head2 $c->setup_components
1838
1839 Sets up components. Specify a C<setup_components> config option to pass
1840 additional options directly to L<Module::Pluggable>. To add additional
1841 search paths, specify a key named C<search_extra> as an array
1842 reference. Items in the array beginning with C<::> will have the
1843 application class name prepended to them.
1844
1845 =cut
1846
1847 sub setup_components {
1848     my $class = shift;
1849
1850     my @paths   = qw( ::Controller ::C ::Model ::M ::View ::V );
1851     my $config  = $class->config->{ setup_components };
1852     my $extra   = delete $config->{ search_extra } || [];
1853     
1854     push @paths, @$extra;
1855         
1856     my $locator = Module::Pluggable::Object->new(
1857         search_path => [ map { s/^(?=::)/$class/; $_; } @paths ],
1858         %$config
1859     );
1860
1861     my @comps = sort { length $a <=> length $b } $locator->plugins;
1862     my %comps = map { $_ => 1 } @comps;
1863     
1864     for my $component ( @comps ) {
1865         Catalyst::Utils::ensure_class_loaded( $component, { ignore_loaded => 1 } );
1866
1867         my $module  = $class->setup_component( $component );
1868         my %modules = (
1869             $component => $module,
1870             map {
1871                 $_ => $class->setup_component( $_ )
1872             } grep { 
1873               not exists $comps{$_}
1874             } Devel::InnerPackage::list_packages( $component )
1875         );
1876         
1877         for my $key ( keys %modules ) {
1878             $class->components->{ $key } = $modules{ $key };
1879         }
1880     }
1881 }
1882
1883 =head2 $c->setup_component
1884
1885 =cut
1886
1887 sub setup_component {
1888     my( $class, $component ) = @_;
1889
1890     unless ( $component->can( 'COMPONENT' ) ) {
1891         return $component;
1892     }
1893
1894     my $suffix = Catalyst::Utils::class2classsuffix( $component );
1895     my $config = $class->config->{ $suffix } || {};
1896
1897     my $instance = eval { $component->COMPONENT( $class, $config ); };
1898
1899     if ( my $error = $@ ) {
1900         chomp $error;
1901         Catalyst::Exception->throw(
1902             message => qq/Couldn't instantiate component "$component", "$error"/
1903         );
1904     }
1905
1906     Catalyst::Exception->throw(
1907         message =>
1908         qq/Couldn't instantiate component "$component", "COMPONENT() didn't return an object-like value"/
1909     ) unless eval { $instance->can( 'can' ) };
1910
1911     return $instance;
1912 }
1913
1914 =head2 $c->setup_dispatcher
1915
1916 Sets up dispatcher.
1917
1918 =cut
1919
1920 sub setup_dispatcher {
1921     my ( $class, $dispatcher ) = @_;
1922
1923     if ($dispatcher) {
1924         $dispatcher = 'Catalyst::Dispatcher::' . $dispatcher;
1925     }
1926
1927     if ( my $env = Catalyst::Utils::env_value( $class, 'DISPATCHER' ) ) {
1928         $dispatcher = 'Catalyst::Dispatcher::' . $env;
1929     }
1930
1931     unless ($dispatcher) {
1932         $dispatcher = $class->dispatcher_class;
1933     }
1934
1935     unless (Class::Inspector->loaded($dispatcher)) {
1936         require Class::Inspector->filename($dispatcher);
1937     }
1938
1939     # dispatcher instance
1940     $class->dispatcher( $dispatcher->new );
1941 }
1942
1943 =head2 $c->setup_engine
1944
1945 Sets up engine.
1946
1947 =cut
1948
1949 sub setup_engine {
1950     my ( $class, $engine ) = @_;
1951
1952     if ($engine) {
1953         $engine = 'Catalyst::Engine::' . $engine;
1954     }
1955
1956     if ( my $env = Catalyst::Utils::env_value( $class, 'ENGINE' ) ) {
1957         $engine = 'Catalyst::Engine::' . $env;
1958     }
1959
1960     if ( $ENV{MOD_PERL} ) {
1961
1962         # create the apache method
1963         {
1964             no strict 'refs';
1965             *{"$class\::apache"} = sub { shift->engine->apache };
1966         }
1967
1968         my ( $software, $version ) =
1969           $ENV{MOD_PERL} =~ /^(\S+)\/(\d+(?:[\.\_]\d+)+)/;
1970
1971         $version =~ s/_//g;
1972         $version =~ s/(\.[^.]+)\./$1/g;
1973
1974         if ( $software eq 'mod_perl' ) {
1975
1976             if ( !$engine ) {
1977
1978                 if ( $version >= 1.99922 ) {
1979                     $engine = 'Catalyst::Engine::Apache2::MP20';
1980                 }
1981
1982                 elsif ( $version >= 1.9901 ) {
1983                     $engine = 'Catalyst::Engine::Apache2::MP19';
1984                 }
1985
1986                 elsif ( $version >= 1.24 ) {
1987                     $engine = 'Catalyst::Engine::Apache::MP13';
1988                 }
1989
1990                 else {
1991                     Catalyst::Exception->throw( message =>
1992                           qq/Unsupported mod_perl version: $ENV{MOD_PERL}/ );
1993                 }
1994
1995             }
1996
1997             # install the correct mod_perl handler
1998             if ( $version >= 1.9901 ) {
1999                 *handler = sub  : method {
2000                     shift->handle_request(@_);
2001                 };
2002             }
2003             else {
2004                 *handler = sub ($$) { shift->handle_request(@_) };
2005             }
2006
2007         }
2008
2009         elsif ( $software eq 'Zeus-Perl' ) {
2010             $engine = 'Catalyst::Engine::Zeus';
2011         }
2012
2013         else {
2014             Catalyst::Exception->throw(
2015                 message => qq/Unsupported mod_perl: $ENV{MOD_PERL}/ );
2016         }
2017     }
2018
2019     unless ($engine) {
2020         $engine = $class->engine_class;
2021     }
2022
2023     unless (Class::Inspector->loaded($engine)) {
2024         require Class::Inspector->filename($engine);
2025     }
2026
2027     # check for old engines that are no longer compatible
2028     my $old_engine;
2029     if ( $engine->isa('Catalyst::Engine::Apache')
2030         && !Catalyst::Engine::Apache->VERSION )
2031     {
2032         $old_engine = 1;
2033     }
2034
2035     elsif ( $engine->isa('Catalyst::Engine::Server::Base')
2036         && Catalyst::Engine::Server->VERSION le '0.02' )
2037     {
2038         $old_engine = 1;
2039     }
2040
2041     elsif ($engine->isa('Catalyst::Engine::HTTP::POE')
2042         && $engine->VERSION eq '0.01' )
2043     {
2044         $old_engine = 1;
2045     }
2046
2047     elsif ($engine->isa('Catalyst::Engine::Zeus')
2048         && $engine->VERSION eq '0.01' )
2049     {
2050         $old_engine = 1;
2051     }
2052
2053     if ($old_engine) {
2054         Catalyst::Exception->throw( message =>
2055               qq/Engine "$engine" is not supported by this version of Catalyst/
2056         );
2057     }
2058
2059     # engine instance
2060     $class->engine( $engine->new );
2061 }
2062
2063 =head2 $c->setup_home
2064
2065 Sets up the home directory.
2066
2067 =cut
2068
2069 sub setup_home {
2070     my ( $class, $home ) = @_;
2071
2072     if ( my $env = Catalyst::Utils::env_value( $class, 'HOME' ) ) {
2073         $home = $env;
2074     }
2075
2076     unless ($home) {
2077         $home = Catalyst::Utils::home($class);
2078     }
2079
2080     if ($home) {
2081         $class->config->{home} ||= $home;
2082         $class->config->{root} ||= Path::Class::Dir->new($home)->subdir('root');
2083     }
2084 }
2085
2086 =head2 $c->setup_log
2087
2088 Sets up log.
2089
2090 =cut
2091
2092 sub setup_log {
2093     my ( $class, $debug ) = @_;
2094
2095     unless ( $class->log ) {
2096         $class->log( Catalyst::Log->new );
2097     }
2098
2099     my $env_debug = Catalyst::Utils::env_value( $class, 'DEBUG' );
2100     if ( defined($env_debug) ? $env_debug : $debug ) {
2101         no strict 'refs';
2102         *{"$class\::debug"} = sub { 1 };
2103         $class->log->debug('Debug messages enabled');
2104     }
2105 }
2106
2107 =head2 $c->setup_plugins
2108
2109 Sets up plugins.
2110
2111 =cut
2112
2113 =head2 $c->registered_plugins 
2114
2115 Returns a sorted list of the plugins which have either been stated in the
2116 import list or which have been added via C<< MyApp->plugin(@args); >>.
2117
2118 If passed a given plugin name, it will report a boolean value indicating
2119 whether or not that plugin is loaded.  A fully qualified name is required if
2120 the plugin name does not begin with C<Catalyst::Plugin::>.
2121
2122  if ($c->registered_plugins('Some::Plugin')) {
2123      ...
2124  }
2125
2126 =cut
2127
2128 {
2129
2130     sub registered_plugins {
2131         my $proto = shift;
2132         return sort keys %{ $proto->_plugins } unless @_;
2133         my $plugin = shift;
2134         return 1 if exists $proto->_plugins->{$plugin};
2135         return exists $proto->_plugins->{"Catalyst::Plugin::$plugin"};
2136     }
2137
2138     sub _register_plugin {
2139         my ( $proto, $plugin, $instant ) = @_;
2140         my $class = ref $proto || $proto;
2141
2142         Catalyst::Utils::ensure_class_loaded( $plugin, { ignore_loaded => 1 } );
2143
2144         $proto->_plugins->{$plugin} = 1;
2145         unless ($instant) {
2146             no strict 'refs';
2147             unshift @{"$class\::ISA"}, $plugin;
2148         }
2149         return $class;
2150     }
2151
2152     sub setup_plugins {
2153         my ( $class, $plugins ) = @_;
2154
2155         $class->_plugins( {} ) unless $class->_plugins;
2156         $plugins ||= [];
2157         for my $plugin ( reverse @$plugins ) {
2158
2159             unless ( $plugin =~ s/\A\+// ) {
2160                 $plugin = "Catalyst::Plugin::$plugin";
2161             }
2162
2163             $class->_register_plugin($plugin);
2164         }
2165     }
2166 }
2167
2168 =head2 $c->stack
2169
2170 Returns an arrayref of the internal execution stack (actions that are
2171 currently executing).
2172
2173 =head2 $c->write( $data )
2174
2175 Writes $data to the output stream. When using this method directly, you
2176 will need to manually set the C<Content-Length> header to the length of
2177 your output data, if known.
2178
2179 =cut
2180
2181 sub write {
2182     my $c = shift;
2183
2184     # Finalize headers if someone manually writes output
2185     $c->finalize_headers;
2186
2187     return $c->engine->write( $c, @_ );
2188 }
2189
2190 =head2 version
2191
2192 Returns the Catalyst version number. Mostly useful for "powered by"
2193 messages in template systems.
2194
2195 =cut
2196
2197 sub version { return $Catalyst::VERSION }
2198
2199 =head1 INTERNAL ACTIONS
2200
2201 Catalyst uses internal actions like C<_DISPATCH>, C<_BEGIN>, C<_AUTO>,
2202 C<_ACTION>, and C<_END>. These are by default not shown in the private
2203 action table, but you can make them visible with a config parameter.
2204
2205     MyApp->config->{show_internal_actions} = 1;
2206
2207 =head1 CASE SENSITIVITY
2208
2209 By default Catalyst is not case sensitive, so C<MyApp::C::FOO::Bar> is
2210 mapped to C</foo/bar>. You can activate case sensitivity with a config
2211 parameter.
2212
2213     MyApp->config->{case_sensitive} = 1;
2214
2215 This causes C<MyApp::C::Foo::Bar> to map to C</Foo/Bar>.
2216
2217 =head1 ON-DEMAND PARSER
2218
2219 The request body is usually parsed at the beginning of a request,
2220 but if you want to handle input yourself or speed things up a bit,
2221 you can enable on-demand parsing with a config parameter.
2222
2223     MyApp->config->{parse_on_demand} = 1;
2224     
2225 =head1 PROXY SUPPORT
2226
2227 Many production servers operate using the common double-server approach,
2228 with a lightweight frontend web server passing requests to a larger
2229 backend server. An application running on the backend server must deal
2230 with two problems: the remote user always appears to be C<127.0.0.1> and
2231 the server's hostname will appear to be C<localhost> regardless of the
2232 virtual host that the user connected through.
2233
2234 Catalyst will automatically detect this situation when you are running
2235 the frontend and backend servers on the same machine. The following
2236 changes are made to the request.
2237
2238     $c->req->address is set to the user's real IP address, as read from 
2239     the HTTP X-Forwarded-For header.
2240     
2241     The host value for $c->req->base and $c->req->uri is set to the real
2242     host, as read from the HTTP X-Forwarded-Host header.
2243
2244 Obviously, your web server must support these headers for this to work.
2245
2246 In a more complex server farm environment where you may have your
2247 frontend proxy server(s) on different machines, you will need to set a
2248 configuration option to tell Catalyst to read the proxied data from the
2249 headers.
2250
2251     MyApp->config->{using_frontend_proxy} = 1;
2252     
2253 If you do not wish to use the proxy support at all, you may set:
2254
2255     MyApp->config->{ignore_frontend_proxy} = 1;
2256
2257 =head1 THREAD SAFETY
2258
2259 Catalyst has been tested under Apache 2's threading C<mpm_worker>,
2260 C<mpm_winnt>, and the standalone forking HTTP server on Windows. We
2261 believe the Catalyst core to be thread-safe.
2262
2263 If you plan to operate in a threaded environment, remember that all other
2264 modules you are using must also be thread-safe. Some modules, most notably
2265 L<DBD::SQLite>, are not thread-safe.
2266
2267 =head1 SUPPORT
2268
2269 IRC:
2270
2271     Join #catalyst on irc.perl.org.
2272
2273 Mailing Lists:
2274
2275     http://lists.rawmode.org/mailman/listinfo/catalyst
2276     http://lists.rawmode.org/mailman/listinfo/catalyst-dev
2277
2278 Web:
2279
2280     http://catalyst.perl.org
2281
2282 Wiki:
2283
2284     http://dev.catalyst.perl.org
2285
2286 =head1 SEE ALSO
2287
2288 =head2 L<Task::Catalyst> - All you need to start with Catalyst
2289
2290 =head2 L<Catalyst::Manual> - The Catalyst Manual
2291
2292 =head2 L<Catalyst::Component>, L<Catalyst::Base> - Base classes for components
2293
2294 =head2 L<Catalyst::Engine> - Core engine
2295
2296 =head2 L<Catalyst::Log> - Log class.
2297
2298 =head2 L<Catalyst::Request> - Request object
2299
2300 =head2 L<Catalyst::Response> - Response object
2301
2302 =head2 L<Catalyst::Test> - The test suite.
2303
2304 =head1 CREDITS
2305
2306 Andy Grundman
2307
2308 Andy Wardley
2309
2310 Andreas Marienborg
2311
2312 Andrew Bramble
2313
2314 Andrew Ford
2315
2316 Andrew Ruthven
2317
2318 Arthur Bergman
2319
2320 Autrijus Tang
2321
2322 Brian Cassidy
2323
2324 Carl Franks
2325
2326 Christian Hansen
2327
2328 Christopher Hicks
2329
2330 Dan Sully
2331
2332 Danijel Milicevic
2333
2334 David Kamholz
2335
2336 David Naughton
2337
2338 Drew Taylor
2339
2340 Gary Ashton Jones
2341
2342 Geoff Richards
2343
2344 Jesse Sheidlower
2345
2346 Jesse Vincent
2347
2348 Jody Belka
2349
2350 Johan Lindstrom
2351
2352 Juan Camacho
2353
2354 Leon Brocard
2355
2356 Marcus Ramberg
2357
2358 Matt S Trout
2359
2360 Robert Sedlacek
2361
2362 Sam Vilain
2363
2364 Sascha Kiefer
2365
2366 Tatsuhiko Miyagawa
2367
2368 Ulf Edvinsson
2369
2370 Yuval Kogman
2371
2372 =head1 AUTHOR
2373
2374 Sebastian Riedel, C<sri@oook.de>
2375
2376 =head1 LICENSE
2377
2378 This library is free software, you can redistribute it and/or modify it under
2379 the same terms as Perl itself.
2380
2381 =cut
2382
2383 1;