calling config on app object instead of context class (fix for t/live_stats.t )
[catagits/Catalyst-Runtime.git] / lib / Catalyst / Context.pm
1 package Catalyst::Context;
2
3 use Moose;
4 use bytes;
5 use B::Hooks::EndOfScope ();
6 use Catalyst;
7 use Catalyst::Exception::Detach;
8 use Catalyst::Exception::Go;
9 use Catalyst::Request;
10 use Catalyst::Request::Upload;
11 use Catalyst::Response;
12 use Catalyst::Utils;
13 use File::stat;
14 use Text::SimpleTable ();
15 use URI ();
16 use URI::http;
17 use URI::https;
18 use utf8;
19 use Carp qw/croak carp shortmess/;
20
21 has stack => (is => 'ro', default => sub { [] });
22 has stash => (is => 'rw', default => sub { {} });
23 has state => (is => 'rw', default => 0);
24 has stats => (is => 'rw');
25 has action => (is => 'rw');
26 has counter => (is => 'rw', default => sub { {} });
27 has request => (is => 'rw', default => sub { $_[0]->request_class->new({}) }, required => 1, lazy => 1);
28 has response => (is => 'rw', default => sub { $_[0]->response_class->new({}) }, required => 1, lazy => 1);
29 has namespace => (is => 'rw');
30
31
32 has 'application' => (
33     isa       => 'Catalyst',
34     is        => 'ro',
35     handles   => [
36         qw/
37         controllers 
38         models 
39         views 
40         component 
41         config
42         log
43         debug
44         dispatcher_class
45         request_class
46         response_class
47         dispatcher
48         prepare 
49         engine_class
50         engine
51         path_to 
52         plugin 
53         setup_finalize 
54         welcome_message 
55         components
56         context_class
57         setup_actions
58         search_extra
59         root
60         parse_on_demand
61         name
62         ignore_frontend_proxy
63         home
64         default_model
65         default_view
66         version
67         use_stats
68         stats_class
69         set_action
70
71         ran_setup
72         _comp_search_prefixes
73         _filter_component
74        /
75    ],
76 );
77
78 sub depth { scalar @{ shift->stack || [] }; }
79
80 sub req {
81     my $self = shift; return $self->request(@_);
82 }
83 sub res {
84     my $self = shift; return $self->response(@_);
85 }
86
87 # For backwards compatibility
88 sub finalize_output { shift->finalize_body(@_) };
89
90 # For statistics
91 our $RECURSION = 1000;
92 our $DETACH    = Catalyst::Exception::Detach->new;
93 our $GO        = Catalyst::Exception::Go->new;
94
95 =head1 METHODS
96
97 =head2 INFORMATION ABOUT THE CURRENT REQUEST
98
99 =head2 $c->action
100
101 Returns a L<Catalyst::Action> object for the current action, which
102 stringifies to the action name. See L<Catalyst::Action>.
103
104 =head2 $c->namespace
105
106 Returns the namespace of the current action, i.e., the URI prefix
107 corresponding to the controller of the current action. For example:
108
109     # in Controller::Foo::Bar
110     $c->namespace; # returns 'foo/bar';
111
112 =head2 $c->request
113
114 =head2 $c->req
115
116 Returns the current L<Catalyst::Request> object, giving access to
117 information about the current client request (including parameters,
118 cookies, HTTP headers, etc.). See L<Catalyst::Request>.
119
120 =head2 REQUEST FLOW HANDLING
121
122 =head2 $c->forward( $action [, \@arguments ] )
123
124 =head2 $c->forward( $class, $method, [, \@arguments ] )
125
126 Forwards processing to another action, by its private name. If you give a
127 class name but no method, C<process()> is called. You may also optionally
128 pass arguments in an arrayref. The action will receive the arguments in
129 C<@_> and C<< $c->req->args >>. Upon returning from the function,
130 C<< $c->req->args >> will be restored to the previous values.
131
132 Any data C<return>ed from the action forwarded to, will be returned by the
133 call to forward.
134
135     my $foodata = $c->forward('/foo');
136     $c->forward('index');
137     $c->forward(qw/MyApp::Model::DBIC::Foo do_stuff/);
138     $c->forward('MyApp::View::TT');
139
140 Note that L<< forward|/"$c->forward( $action [, \@arguments ] )" >> implies
141 an C<< eval { } >> around the call (actually
142 L<< execute|/"$c->execute( $class, $coderef )" >> does), thus de-fatalizing
143 all 'dies' within the called action. If you want C<die> to propagate you
144 need to do something like:
145
146     $c->forward('foo');
147     die $c->error if $c->error;
148
149 Or make sure to always return true values from your actions and write
150 your code like this:
151
152     $c->forward('foo') || return;
153     
154 Another note is that C<< $c->forward >> always returns a scalar because it
155 actually returns $c->state which operates in a scalar context.
156 Thus, something like:
157
158     return @array;
159     
160 in an action that is forwarded to is going to return a scalar, 
161 i.e. how many items are in that array, which is probably not what you want.
162 If you need to return an array then return a reference to it, 
163 or stash it like so:
164
165     $c->stash->{array} = \@array;
166
167 and access it from the stash.
168
169 =cut
170
171 sub forward { my $c = shift; no warnings 'recursion'; $c->dispatcher->forward( $c, @_ ) }
172
173 =head2 $c->detach( $action [, \@arguments ] )
174
175 =head2 $c->detach( $class, $method, [, \@arguments ] )
176
177 =head2 $c->detach()
178
179 The same as L<< forward|/"$c->forward( $action [, \@arguments ] )" >>, but
180 doesn't return to the previous action when processing is finished.
181
182 When called with no arguments it escapes the processing chain entirely.
183
184 =cut
185
186 sub detach { my $c = shift; $c->dispatcher->detach( $c, @_ ) }
187
188 =head2 $c->visit( $action [, \@captures, \@arguments ] )
189
190 =head2 $c->visit( $class, $method, [, \@captures, \@arguments ] )
191
192 Almost the same as L<< forward|/"$c->forward( $action [, \@arguments ] )" >>,
193 but does a full dispatch, instead of just calling the new C<$action> /
194 C<< $class->$method >>. This means that C<begin>, C<auto> and the method
195 you go to are called, just like a new request.
196
197 In addition both C<< $c->action >> and C<< $c->namespace >> are localized.
198 This means, for example, that C<< $c->action >> methods such as
199 L<name|Catalyst::Action/name>, L<class|Catalyst::Action/class> and
200 L<reverse|Catalyst::Action/reverse> return information for the visited action
201 when they are invoked within the visited action.  This is different from the
202 behavior of L<< forward|/"$c->forward( $action [, \@arguments ] )" >>, which
203 continues to use the $c->action object from the caller action even when
204 invoked from the callee.
205
206 C<< $c->stash >> is kept unchanged.
207
208 In effect, L<< visit|/"$c->visit( $action [, \@captures, \@arguments ] )" >>
209 allows you to "wrap" another action, just as it would have been called by
210 dispatching from a URL, while the analogous
211 L<< go|/"$c->go( $action [, \@captures, \@arguments ] )" >> allows you to
212 transfer control to another action as if it had been reached directly from a URL.
213
214 =cut
215
216 sub visit { my $c = shift; $c->dispatcher->visit( $c, @_ ) }
217
218 =head2 $c->go( $action [, \@captures, \@arguments ] )
219
220 =head2 $c->go( $class, $method, [, \@captures, \@arguments ] )
221
222 The relationship between C<go> and 
223 L<< visit|/"$c->visit( $action [, \@captures, \@arguments ] )" >> is the same as
224 the relationship between 
225 L<< forward|/"$c->forward( $class, $method, [, \@arguments ] )" >> and
226 L<< detach|/"$c->detach( $action [, \@arguments ] )" >>. Like C<< $c->visit >>,
227 C<< $c->go >> will perform a full dispatch on the specified action or method,
228 with localized C<< $c->action >> and C<< $c->namespace >>. Like C<detach>,
229 C<go> escapes the processing of the current request chain on completion, and
230 does not return to its caller.
231
232 =cut
233
234 sub go { my $c = shift; $c->dispatcher->go( $c, @_ ) }
235
236 =head2 $c->response
237
238 =head2 $c->res
239
240 Returns the current L<Catalyst::Response> object, see there for details.
241
242 =head2 $c->stash
243
244 Returns a hashref to the stash, which may be used to store data and pass
245 it between components during a request. You can also set hash keys by
246 passing arguments. The stash is automatically sent to the view. The
247 stash is cleared at the end of a request; it cannot be used for
248 persistent storage (for this you must use a session; see
249 L<Catalyst::Plugin::Session> for a complete system integrated with
250 Catalyst).
251
252     $c->stash->{foo} = $bar;
253     $c->stash( { moose => 'majestic', qux => 0 } );
254     $c->stash( bar => 1, gorch => 2 ); # equivalent to passing a hashref
255
256     # stash is automatically passed to the view for use in a template
257     $c->forward( 'MyApp::View::TT' );
258
259 =cut
260
261 around stash => sub {
262     my $orig = shift;
263     my $c = shift;
264     my $stash = $orig->($c);
265     if (@_) {
266         my $new_stash = @_ > 1 ? {@_} : $_[0];
267         croak('stash takes a hash or hashref') unless ref $new_stash;
268         foreach my $key ( keys %$new_stash ) {
269           $stash->{$key} = $new_stash->{$key};
270         }
271     }
272
273     return $stash;
274 };
275
276
277 =head2 $c->error
278
279 =head2 $c->error($error, ...)
280
281 =head2 $c->error($arrayref)
282
283 Returns an arrayref containing error messages.  If Catalyst encounters an
284 error while processing a request, it stores the error in $c->error.  This
285 method should only be used to store fatal error messages.
286
287     my @error = @{ $c->error };
288
289 Add a new error.
290
291     $c->error('Something bad happened');
292
293 =cut
294
295 sub error {
296     my $c = shift;
297     if ( $_[0] ) {
298         my $error = ref $_[0] eq 'ARRAY' ? $_[0] : [@_];
299         croak @$error unless ref $c;
300         push @{ $c->{error} }, @$error;
301     }
302     elsif ( defined $_[0] ) { $c->{error} = undef }
303     return $c->{error} || [];
304 }
305
306
307 =head2 $c->state
308
309 Contains the return value of the last executed action.   
310 Note that << $c->state >> operates in a scalar context which means that all
311 values it returns are scalar.
312
313 =head2 $c->clear_errors
314
315 Clear errors.  You probably don't want to clear the errors unless you are
316 implementing a custom error screen.
317
318 This is equivalent to running
319
320     $c->error(0);
321
322 =cut
323
324 sub clear_errors {
325     my $c = shift;
326     $c->error(0);
327 }
328
329
330 =head2 COMPONENT ACCESSORS
331
332 =head2 $c->controller($name)
333
334 Gets a L<Catalyst::Controller> instance by name.
335
336     $c->controller('Foo')->do_stuff;
337
338 If the name is omitted, will return the controller for the dispatched
339 action.
340
341 If you want to search for controllers, pass in a regexp as the argument.
342
343     # find all controllers that start with Foo
344     my @foo_controllers = $c->controller(qr{^Foo});
345
346
347 =cut
348
349 sub controller {
350     my ( $c, $name, @args ) = @_;
351
352     if( $name ) {
353         my @result = $c->_comp_search_prefixes( $name, qw/Controller C/ );
354         return map { $c->_filter_component( $_, @args ) } @result if ref $name;
355         return $c->_filter_component( $result[ 0 ], @args );
356     }
357
358     return $c->component( $c->action->class );
359 }
360
361 =head2 $c->model($name)
362
363 Gets a L<Catalyst::Model> instance by name.
364
365     $c->model('Foo')->do_stuff;
366
367 Any extra arguments are directly passed to ACCEPT_CONTEXT.
368
369 If the name is omitted, it will look for
370  - a model object in $c->stash->{current_model_instance}, then
371  - a model name in $c->stash->{current_model}, then
372  - a config setting 'default_model', or
373  - check if there is only one model, and return it if that's the case.
374
375 If you want to search for models, pass in a regexp as the argument.
376
377     # find all models that start with Foo
378     my @foo_models = $c->model(qr{^Foo});
379
380 =cut
381
382 sub model {
383     my ( $c, $name, @args ) = @_;
384     my $appclass = ref($c) || $c;
385     if( $name ) {
386         my @result = $c->_comp_search_prefixes( $name, qw/Model M/ );
387         return map { $c->_filter_component( $_, @args ) } @result if ref $name;
388         return $c->_filter_component( $result[ 0 ], @args );
389     }
390
391     if (ref $c) {
392         return $c->stash->{current_model_instance}
393           if $c->stash->{current_model_instance};
394         return $c->model( $c->stash->{current_model} )
395           if $c->stash->{current_model};
396     }
397     return $c->model( $appclass->config->{default_model} )
398       if $appclass->config->{default_model};
399
400     my( $comp, $rest ) = $c->_comp_search_prefixes( undef, qw/Model M/);
401
402     if( $rest ) {
403         $c->log->warn( Carp::shortmess('Calling $c->model() will return a random model unless you specify one of:') );
404         $c->log->warn( '* $c->config(default_model => "the name of the default model to use")' );
405         $c->log->warn( '* $c->stash->{current_model} # the name of the model to use for this request' );
406         $c->log->warn( '* $c->stash->{current_model_instance} # the instance of the model to use for this request' );
407         $c->log->warn( 'NB: in version 5.81, the "random" behavior will not work at all.' );
408     }
409
410     return $c->_filter_component( $comp );
411 }
412
413
414 =head2 $c->view($name)
415
416 Gets a L<Catalyst::View> instance by name.
417
418     $c->view('Foo')->do_stuff;
419
420 Any extra arguments are directly passed to ACCEPT_CONTEXT.
421
422 If the name is omitted, it will look for
423  - a view object in $c->stash->{current_view_instance}, then
424  - a view name in $c->stash->{current_view}, then
425  - a config setting 'default_view', or
426  - check if there is only one view, and return it if that's the case.
427
428 If you want to search for views, pass in a regexp as the argument.
429
430     # find all views that start with Foo
431     my @foo_views = $c->view(qr{^Foo});
432
433 =cut
434
435 sub view {
436     my ( $c, $name, @args ) = @_;
437
438     my $appclass = ref($c) || $c;
439     if( $name ) {
440         my @result = $c->_comp_search_prefixes( $name, qw/View V/ );
441         return map { $c->_filter_component( $_, @args ) } @result if ref $name;
442         return $c->_filter_component( $result[ 0 ], @args );
443     }
444
445     if (ref $c) {
446         return $c->stash->{current_view_instance}
447           if $c->stash->{current_view_instance};
448         return $c->view( $c->stash->{current_view} )
449           if $c->stash->{current_view};
450     }
451     return $c->view( $appclass->config->{default_view} )
452       if $appclass->config->{default_view};
453
454     my( $comp, $rest ) = $c->_comp_search_prefixes( undef, qw/View V/);
455
456     if( $rest ) {
457         $c->log->warn( 'Calling $c->view() will return a random view unless you specify one of:' );
458         $c->log->warn( '* $c->config(default_view => "the name of the default view to use")' );
459         $c->log->warn( '* $c->stash->{current_view} # the name of the view to use for this request' );
460         $c->log->warn( '* $c->stash->{current_view_instance} # the instance of the view to use for this request' );
461         $c->log->warn( 'NB: in version 5.81, the "random" behavior will not work at all.' );
462     }
463
464     return $c->_filter_component( $comp );
465 }
466
467 =head2 UTILITY METHODS
468
469 =head2 $c->uri_for( $path?, @args?, \%query_values? )
470
471 =head2 $c->uri_for( $action, \@captures?, @args?, \%query_values? )
472
473 Constructs an absolute L<URI> object based on the application root, the
474 provided path, and the additional arguments and query parameters provided.
475 When used as a string, provides a textual URI.
476
477 If no arguments are provided, the URI for the current action is returned.
478 To return the current action and also provide @args, use
479 C<< $c->uri_for( $c->action, @args ) >>. 
480
481 If the first argument is a string, it is taken as a public URI path relative
482 to C<< $c->namespace >> (if it doesn't begin with a forward slash) or
483 relative to the application root (if it does). It is then merged with
484 C<< $c->request->base >>; any C<@args> are appended as additional path
485 components; and any C<%query_values> are appended as C<?foo=bar> parameters.
486
487 If the first argument is a L<Catalyst::Action> it represents an action which
488 will have its path resolved using C<< $c->dispatcher->uri_for_action >>. The
489 optional C<\@captures> argument (an arrayref) allows passing the captured
490 variables that are needed to fill in the paths of Chained and Regex actions;
491 once the path is resolved, C<uri_for> continues as though a path was
492 provided, appending any arguments or parameters and creating an absolute
493 URI.
494
495 The captures for the current request can be found in
496 C<< $c->request->captures >>, and actions can be resolved using
497 C<< Catalyst::Controller->action_for($name) >>. If you have a private action
498 path, use C<< $c->uri_for_action >> instead.
499
500   # Equivalent to $c->req->uri
501   $c->uri_for($c->action, $c->req->captures,
502       @{ $c->req->args }, $c->req->params);
503
504   # For the Foo action in the Bar controller
505   $c->uri_for($c->controller('Bar')->action_for('Foo'));
506
507   # Path to a static resource
508   $c->uri_for('/static/images/logo.png');
509
510 =cut
511
512 sub uri_for {
513     my ( $c, $path, @args ) = @_;
514
515     if (blessed($path) && $path->isa('Catalyst::Controller')) {
516         $path = $path->path_prefix;
517         $path =~ s{/+\z}{};
518         $path .= '/';
519     }
520
521     if ( blessed($path) ) { # action object
522         my $captures = [ map { s|/|%2F|; $_; }
523                         ( scalar @args && ref $args[0] eq 'ARRAY'
524                          ? @{ shift(@args) }
525                          : ()) ];
526         my $action = $path;
527         $path = $c->dispatcher->uri_for_action($action, $captures);
528         if (not defined $path) {
529             $c->log->debug(qq/Can't find uri_for action '$action' @$captures/)
530                 if $c->debug;
531             return undef;
532         }
533         $path = '/' if $path eq '';
534     }
535
536     undef($path) if (defined $path && $path eq '');
537
538     my $params =
539       ( scalar @args && ref $args[$#args] eq 'HASH' ? pop @args : {} );
540
541     carp "uri_for called with undef argument" if grep { ! defined $_ } @args;
542     s/([^$URI::uric])/$URI::Escape::escapes{$1}/go for @args;
543     s|/|%2F| for @args;
544
545     unshift(@args, $path);
546
547     unless (defined $path && $path =~ s!^/!!) { # in-place strip
548         my $namespace = $c->namespace;
549         if (defined $path) { # cheesy hack to handle path '../foo'
550            $namespace =~ s{(?:^|/)[^/]+$}{} while $args[0] =~ s{^\.\./}{};
551         }
552         unshift(@args, $namespace || '');
553     }
554
555     # join args with '/', or a blank string
556     my $args = join('/', grep { defined($_) } @args);
557     $args =~ s/\?/%3F/g; # STUPID STUPID SPECIAL CASE
558     $args =~ s!^/+!!;
559     my $base = $c->req->base;
560     my $class = ref($base);
561     $base =~ s{(?<!/)$}{/};
562
563     my $query = '';
564
565     if (my @keys = keys %$params) {
566       # somewhat lifted from URI::_query's query_form
567       $query = '?'.join('&', map {
568           my $val = $params->{$_};
569           s/([;\/?:@&=+,\$\[\]%])/$URI::Escape::escapes{$1}/go;
570           s/ /+/g;
571           my $key = $_;
572           $val = '' unless defined $val;
573           (map {
574               my $param = "$_";
575               utf8::encode( $param ) if utf8::is_utf8($param);
576               # using the URI::Escape pattern here so utf8 chars survive
577               $param =~ s/([^A-Za-z0-9\-_.!~*'() ])/$URI::Escape::escapes{$1}/go;
578               $param =~ s/ /+/g;
579               "${key}=$param"; } ( ref $val eq 'ARRAY' ? @$val : $val ));
580       } @keys);
581     }
582
583     my $res = bless(\"${base}${args}${query}", $class);
584     $res;
585 }
586
587 =head2 $c->uri_for_action( $path, \@captures?, @args?, \%query_values? )
588
589 =head2 $c->uri_for_action( $action, \@captures?, @args?, \%query_values? )
590
591 =over
592
593 =item $path
594
595 A private path to the Catalyst action you want to create a URI for.
596
597 This is a shortcut for calling C<< $c->dispatcher->get_action_by_path($path)
598 >> and passing the resulting C<$action> and the remaining arguments to C<<
599 $c->uri_for >>.
600
601 You can also pass in a Catalyst::Action object, in which case it is passed to
602 C<< $c->uri_for >>.
603
604 =back
605
606 =cut
607
608 sub uri_for_action {
609     my ( $c, $path, @args ) = @_;
610     my $action = blessed($path)
611       ? $path
612       : $c->dispatcher->get_action_by_path($path);
613     unless (defined $action) {
614       croak "Can't find action for path '$path'";
615     }
616     return $c->uri_for( $action, @args );
617 }
618
619 =head1 INTERNAL METHODS
620
621 =head2 $c->counter
622
623 Returns a hashref containing coderefs and execution counts (needed for
624 deep recursion detection).
625
626 =head2 $c->depth
627
628 Returns the number of actions on the current internal execution stack.
629
630 =head2 $c->dispatch
631
632 Dispatches a request to actions.
633
634 =cut
635
636 sub dispatch { my $c = shift; $c->dispatcher->dispatch( $c, @_ ) }
637
638 =head2 $c->dump_these
639
640 Returns a list of 2-element array references (name, structure) pairs
641 that will be dumped on the error page in debug mode.
642
643 =cut
644
645 sub dump_these {
646     my $c = shift;
647     [ Request => $c->req ],
648     [ Response => $c->res ],
649     [ Stash => $c->stash ],
650     [ Config => $c->config ];
651 }
652
653 =head2 $c->execute( $class, $coderef )
654
655 Execute a coderef in given class and catch exceptions. Errors are available
656 via $c->error.
657
658 =cut
659
660 sub execute {
661     my ( $c, $class, $code ) = @_;
662     $class = $c->component($class) || $class;
663     $c->state(0);
664
665     if ( $c->depth >= $RECURSION ) {
666         my $action = $code->reverse();
667         $action = "/$action" unless $action =~ /->/;
668         my $error = qq/Deep recursion detected calling "${action}"/;
669         $c->log->error($error);
670         $c->error($error);
671         $c->state(0);
672         return $c->state;
673     }
674
675     my $stats_info = $c->_stats_start_execute( $code ) if $c->use_stats;
676
677     push( @{ $c->stack }, $code );
678
679     no warnings 'recursion';
680     eval { $c->state( $code->execute( $class, $c, @{ $c->req->args } ) || 0 ) };
681
682     $c->_stats_finish_execute( $stats_info ) if $c->use_stats and $stats_info;
683
684     my $last = pop( @{ $c->stack } );
685
686     if ( my $error = $@ ) {
687         if ( blessed($error) and $error->isa('Catalyst::Exception::Detach') ) {
688             $error->rethrow if $c->depth > 1;
689         }
690         elsif ( blessed($error) and $error->isa('Catalyst::Exception::Go') ) {
691             $error->rethrow if $c->depth > 0;
692         }
693         else {
694             unless ( ref $error ) {
695                 no warnings 'uninitialized';
696                 chomp $error;
697                 my $class = $last->class;
698                 my $name  = $last->name;
699                 $error = qq/Caught exception in $class->$name "$error"/;
700             }
701             $c->error($error);
702             $c->state(0);
703         }
704     }
705     return $c->state;
706 }
707
708 sub _stats_start_execute {
709     my ( $c, $code ) = @_;
710     return if ( ( $code->name =~ /^_.*/ )
711         && ( !$c->config->{show_internal_actions} ) );
712
713     my $action_name = $code->reverse();
714     $c->counter->{$action_name}++;
715
716     my $action = $action_name;
717     $action = "/$action" unless $action =~ /->/;
718
719     # determine if the call was the result of a forward
720     # this is done by walking up the call stack and looking for a calling
721     # sub of Catalyst::forward before the eval
722     my $callsub = q{};
723     for my $index ( 2 .. 11 ) {
724         last
725         if ( ( caller($index) )[0] eq 'Catalyst'
726             && ( caller($index) )[3] eq '(eval)' );
727
728         if ( ( caller($index) )[3] =~ /forward$/ ) {
729             $callsub = ( caller($index) )[3];
730             $action  = "-> $action";
731             last;
732         }
733     }
734
735     my $uid = $action_name . $c->counter->{$action_name};
736
737     # is this a root-level call or a forwarded call?
738     if ( $callsub =~ /forward$/ ) {
739         my $parent = $c->stack->[-1];
740
741         # forward, locate the caller
742         if ( exists $c->counter->{"$parent"} ) {
743             $c->stats->profile(
744                 begin  => $action,
745                 parent => "$parent" . $c->counter->{"$parent"},
746                 uid    => $uid,
747             );
748         }
749         else {
750
751             # forward with no caller may come from a plugin
752             $c->stats->profile(
753                 begin => $action,
754                 uid   => $uid,
755             );
756         }
757     }
758     else {
759
760         # root-level call
761         $c->stats->profile(
762             begin => $action,
763             uid   => $uid,
764         );
765     }
766     return $action;
767
768 }
769
770 sub _stats_finish_execute {
771     my ( $c, $info ) = @_;
772     $c->stats->profile( end => $info );
773 }
774
775 =head2 $c->finalize
776
777 Finalizes the request.
778
779 =cut
780
781 sub finalize {
782     my $c = shift;
783
784     for my $error ( @{ $c->error } ) {
785         $c->log->error($error);
786     }
787
788     # Allow engine to handle finalize flow (for POE)
789     my $engine = $c->engine;
790     if ( my $code = $engine->can('finalize') ) {
791         $engine->$code($c);
792     }
793     else {
794
795         $c->finalize_uploads;
796
797         # Error
798         if ( $#{ $c->error } >= 0 ) {
799             $c->finalize_error;
800         }
801
802         $c->finalize_headers;
803
804         # HEAD request
805         if ( $c->request->method eq 'HEAD' ) {
806             $c->response->body('');
807         }
808
809         $c->finalize_body;
810     }
811
812     if ($c->use_stats) {
813         my $elapsed = sprintf '%f', $c->stats->elapsed;
814         my $av = $elapsed == 0 ? '??' : sprintf '%.3f', 1 / $elapsed;
815         $c->log->info(
816             "Request took ${elapsed}s ($av/s)\n" . $c->stats->report . "\n" );
817     }
818
819     return $c->response->status;
820 }
821
822 =head2 $c->finalize_body
823
824 Finalizes body.
825
826 =cut
827
828 sub finalize_body { my $c = shift; $c->engine->finalize_body( $c, @_ ) }
829
830 =head2 $c->finalize_cookies
831
832 Finalizes cookies.
833
834 =cut
835
836 sub finalize_cookies { my $c = shift; $c->engine->finalize_cookies( $c, @_ ) }
837
838 =head2 $c->finalize_error
839
840 Finalizes error.
841
842 =cut
843
844 sub finalize_error { my $c = shift; $c->engine->finalize_error( $c, @_ ) }
845
846 =head2 $c->finalize_headers
847
848 Finalizes headers.
849
850 =cut
851
852 sub finalize_headers {
853     my $c = shift;
854
855     my $response = $c->response; #accessor calls can add up?
856
857     # Check if we already finalized headers
858     return if $response->finalized_headers;
859
860     # Handle redirects
861     if ( my $location = $response->redirect ) {
862         $c->log->debug(qq/Redirecting to "$location"/) if $c->debug;
863         $response->header( Location => $location );
864
865         if ( !$response->has_body ) {
866             # Add a default body if none is already present
867             $response->body(
868                 qq{<html><body><p>This item has moved <a href="$location">here</a>.</p></body></html>}
869             );
870         }
871     }
872
873     # Content-Length
874     if ( $response->body && !$response->content_length ) {
875
876         # get the length from a filehandle
877         if ( blessed( $response->body ) && $response->body->can('read') )
878         {
879             my $stat = stat $response->body;
880             if ( $stat && $stat->size > 0 ) {
881                 $response->content_length( $stat->size );
882             }
883             else {
884                 $c->log->warn('Serving filehandle without a content-length');
885             }
886         }
887         else {
888             # everything should be bytes at this point, but just in case
889             $response->content_length( bytes::length( $response->body ) );
890         }
891     }
892
893     # Errors
894     if ( $response->status =~ /^(1\d\d|[23]04)$/ ) {
895         $response->headers->remove_header("Content-Length");
896         $response->body('');
897     }
898
899     $c->finalize_cookies;
900
901     $c->engine->finalize_headers( $c, @_ );
902
903     # Done
904     $response->finalized_headers(1);
905 }
906
907 =head2 $c->finalize_output
908
909 An alias for finalize_body.
910
911 =head2 $c->finalize_read
912
913 Finalizes the input after reading is complete.
914
915 =cut
916
917 sub finalize_read { my $c = shift; $c->engine->finalize_read( $c, @_ ) }
918
919 =head2 $c->finalize_uploads
920
921 Finalizes uploads. Cleans up any temporary files.
922
923 =cut
924
925 sub finalize_uploads { my $c = shift; $c->engine->finalize_uploads( $c, @_ ) }
926
927 =head2 $c->get_action( $action, $namespace )
928
929 Gets an action in a given namespace.
930
931 =cut
932
933 sub get_action { my $c = shift; $c->dispatcher->get_action(@_) }
934
935 =head2 $c->get_actions( $action, $namespace )
936
937 Gets all actions of a given name in a namespace and all parent
938 namespaces.
939
940 =cut
941
942 sub get_actions { my $c = shift; $c->dispatcher->get_actions( $c, @_ ) }
943
944 =head2 $c->prepare_action
945
946 Prepares action. See L<Catalyst::Dispatcher>.
947
948 =cut
949
950 sub prepare_action { my $c = shift; $c->dispatcher->prepare_action( $c, @_ ) }
951
952 =head2 $c->prepare_body
953
954 Prepares message body.
955
956 =cut
957
958 sub prepare_body {
959     my $c = shift;
960
961     return if $c->request->_has_body;
962
963     # Initialize on-demand data
964     $c->engine->prepare_body( $c, @_ );
965     $c->prepare_parameters;
966     $c->prepare_uploads;
967
968     if ( $c->debug && keys %{ $c->req->body_parameters } ) {
969         my $t = Text::SimpleTable->new( [ 35, 'Parameter' ], [ 36, 'Value' ] );
970         for my $key ( sort keys %{ $c->req->body_parameters } ) {
971             my $param = $c->req->body_parameters->{$key};
972             my $value = defined($param) ? $param : '';
973             $t->row( $key,
974                 ref $value eq 'ARRAY' ? ( join ', ', @$value ) : $value );
975         }
976         $c->log->debug( "Body Parameters are:\n" . $t->draw );
977     }
978 }
979
980 =head2 $c->prepare_body_chunk( $chunk )
981
982 Prepares a chunk of data before sending it to L<HTTP::Body>.
983
984 See L<Catalyst::Engine>.
985
986 =cut
987
988 sub prepare_body_chunk {
989     my $c = shift;
990     $c->engine->prepare_body_chunk( $c, @_ );
991 }
992
993 =head2 $c->prepare_body_parameters
994
995 Prepares body parameters.
996
997 =cut
998
999 sub prepare_body_parameters {
1000     my $c = shift;
1001     $c->engine->prepare_body_parameters( $c, @_ );
1002 }
1003
1004 =head2 $c->prepare_connection
1005
1006 Prepares connection.
1007
1008 =cut
1009
1010 sub prepare_connection {
1011     my $c = shift;
1012     $c->engine->prepare_connection( $c, @_ );
1013 }
1014
1015 =head2 $c->prepare_cookies
1016
1017 Prepares cookies.
1018
1019 =cut
1020
1021 sub prepare_cookies { my $c = shift; $c->engine->prepare_cookies( $c, @_ ) }
1022
1023 =head2 $c->prepare_headers
1024
1025 Prepares headers.
1026
1027 =cut
1028
1029 sub prepare_headers { my $c = shift; $c->engine->prepare_headers( $c, @_ ) }
1030
1031 =head2 $c->prepare_parameters
1032
1033 Prepares parameters.
1034
1035 =cut
1036
1037 sub prepare_parameters {
1038     my $c = shift;
1039     $c->prepare_body_parameters;
1040     $c->engine->prepare_parameters( $c, @_ );
1041 }
1042
1043 =head2 $c->prepare_path
1044
1045 Prepares path and base.
1046
1047 =cut
1048
1049 sub prepare_path { my $c = shift; $c->engine->prepare_path( $c, @_ ) }
1050
1051 =head2 $c->prepare_query_parameters
1052
1053 Prepares query parameters.
1054
1055 =cut
1056
1057 sub prepare_query_parameters {
1058     my $c = shift;
1059
1060     $c->engine->prepare_query_parameters( $c, @_ );
1061
1062     if ( $c->debug && keys %{ $c->request->query_parameters } ) {
1063         my $t = Text::SimpleTable->new( [ 35, 'Parameter' ], [ 36, 'Value' ] );
1064         for my $key ( sort keys %{ $c->req->query_parameters } ) {
1065             my $param = $c->req->query_parameters->{$key};
1066             my $value = defined($param) ? $param : '';
1067             $t->row( $key,
1068                 ref $value eq 'ARRAY' ? ( join ', ', @$value ) : $value );
1069         }
1070         $c->log->debug( "Query Parameters are:\n" . $t->draw );
1071     }
1072 }
1073
1074 =head2 $c->prepare_read
1075
1076 Prepares the input for reading.
1077
1078 =cut
1079
1080 sub prepare_read { my $c = shift; $c->engine->prepare_read( $c, @_ ) }
1081
1082 =head2 $c->prepare_request
1083
1084 Prepares the engine request.
1085
1086 =cut
1087
1088 sub prepare_request { my $c = shift; $c->engine->prepare_request( $c, @_ ) }
1089
1090 =head2 $c->prepare_uploads
1091
1092 Prepares uploads.
1093
1094 =cut
1095
1096 sub prepare_uploads {
1097     my $c = shift;
1098
1099     $c->engine->prepare_uploads( $c, @_ );
1100
1101     if ( $c->debug && keys %{ $c->request->uploads } ) {
1102         my $t = Text::SimpleTable->new(
1103             [ 12, 'Parameter' ],
1104             [ 26, 'Filename' ],
1105             [ 18, 'Type' ],
1106             [ 9,  'Size' ]
1107         );
1108         for my $key ( sort keys %{ $c->request->uploads } ) {
1109             my $upload = $c->request->uploads->{$key};
1110             for my $u ( ref $upload eq 'ARRAY' ? @{$upload} : ($upload) ) {
1111                 $t->row( $key, $u->filename, $u->type, $u->size );
1112             }
1113         }
1114         $c->log->debug( "File Uploads are:\n" . $t->draw );
1115     }
1116 }
1117
1118 =head2 $c->prepare_write
1119
1120 Prepares the output for writing.
1121
1122 =cut
1123
1124 sub prepare_write { my $c = shift; $c->engine->prepare_write( $c, @_ ) }
1125
1126 =head2 $c->read( [$maxlength] )
1127
1128 Reads a chunk of data from the request body. This method is designed to
1129 be used in a while loop, reading C<$maxlength> bytes on every call.
1130 C<$maxlength> defaults to the size of the request if not specified.
1131
1132 You have to set C<< MyApp->config(parse_on_demand => 1) >> to use this
1133 directly.
1134
1135 Warning: If you use read(), Catalyst will not process the body,
1136 so you will not be able to access POST parameters or file uploads via
1137 $c->request.  You must handle all body parsing yourself.
1138
1139 =cut
1140
1141 sub read { my $c = shift; return $c->engine->read( $c, @_ ) }
1142
1143 =head2 $c->stack
1144
1145 Returns an arrayref of the internal execution stack (actions that are
1146 currently executing).
1147
1148
1149 =head2 $c->write( $data )
1150
1151 Writes $data to the output stream. When using this method directly, you
1152 will need to manually set the C<Content-Length> header to the length of
1153 your output data, if known.
1154
1155 =cut
1156
1157 sub write {
1158     my $c = shift;
1159
1160     # Finalize headers if someone manually writes output
1161     $c->finalize_headers;
1162
1163     return $c->engine->write( $c, @_ );
1164 }
1165
1166 no Moose;
1167 __PACKAGE__->meta->make_immutable;
1168
1169 1;
1170
1171 __END__
1172
1173 =head1 NAME
1174
1175 Catalyst::Context - object for keeping request related state
1176
1177 =head1 ATTRIBUTES 
1178
1179 =head3 action
1180
1181 =head3 counter
1182
1183 =head3 namespace
1184
1185 =head3 request_class
1186
1187 =head3 request
1188
1189 =head3 response_class
1190
1191 =head3 response
1192
1193 =head3 stack
1194
1195 =head3 stash
1196
1197 =head3 state
1198
1199 =head3 stats
1200
1201 =head1 SEE ALSO
1202
1203 L<Catalyst>, L<Catalyst::Model>, L<Catalyst::View>, L<Catalyst::Controller>.
1204
1205 =head1 AUTHORS
1206
1207 Catalyst Contributors, see Catalyst.pm
1208
1209 =head1 COPYRIGHT
1210
1211 This library is free software. You can redistribute it and/or modify it under
1212 the same terms as Perl itself.
1213
1214 =cut
1215