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