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