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