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