controller method on application, this one is identical to that one in Context -...
[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         controller
39         models 
40         views 
41         component 
42         config
43         log
44         debug
45         dispatcher_class
46         request_class
47         response_class
48         dispatcher
49         prepare 
50         engine_class
51         engine
52         path_to 
53         plugin 
54         setup_finalize 
55         welcome_message 
56         components
57         context_class
58         setup_actions
59         search_extra
60         root
61         parse_on_demand
62         name
63         ignore_frontend_proxy
64         home
65         default_model
66         default_view
67         version
68         use_stats
69         stats_class
70         set_action
71         registered_plugins
72
73         ran_setup
74         _comp_search_prefixes
75         _filter_component
76        /
77    ],
78 );
79
80 sub depth { scalar @{ shift->stack || [] }; }
81
82 sub req {
83     my $self = shift; return $self->request(@_);
84 }
85 sub res {
86     my $self = shift; return $self->response(@_);
87 }
88
89 # For backwards compatibility
90 sub finalize_output { shift->finalize_body(@_) };
91
92 # For statistics
93 our $RECURSION = 1000;
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 =head2 $c->model($name)
350
351 Gets a L<Catalyst::Model> instance by name.
352
353     $c->model('Foo')->do_stuff;
354
355 Any extra arguments are directly passed to ACCEPT_CONTEXT.
356
357 If the name is omitted, it will look for
358  - a model object in $c->stash->{current_model_instance}, then
359  - a model name in $c->stash->{current_model}, then
360  - a config setting 'default_model', or
361  - check if there is only one model, and return it if that's the case.
362
363 If you want to search for models, pass in a regexp as the argument.
364
365     # find all models that start with Foo
366     my @foo_models = $c->model(qr{^Foo});
367
368 =cut
369
370 sub model {
371     my ( $c, $name, @args ) = @_;
372     my $appclass = ref($c) || $c;
373     if( $name ) {
374         my @result = $c->_comp_search_prefixes( $name, qw/Model M/ );
375         return map { $c->_filter_component( $_, @args ) } @result if ref $name;
376         return $c->_filter_component( $result[ 0 ], @args );
377     }
378
379     if (ref $c) {
380         return $c->stash->{current_model_instance}
381           if $c->stash->{current_model_instance};
382         return $c->model( $c->stash->{current_model} )
383           if $c->stash->{current_model};
384     }
385     return $c->model( $appclass->config->{default_model} )
386       if $appclass->config->{default_model};
387
388     my( $comp, $rest ) = $c->_comp_search_prefixes( undef, qw/Model M/);
389
390     if( $rest ) {
391         $c->log->warn( Carp::shortmess('Calling $c->model() will return a random model unless you specify one of:') );
392         $c->log->warn( '* $c->config(default_model => "the name of the default model to use")' );
393         $c->log->warn( '* $c->stash->{current_model} # the name of the model to use for this request' );
394         $c->log->warn( '* $c->stash->{current_model_instance} # the instance of the model to use for this request' );
395         $c->log->warn( 'NB: in version 5.81, the "random" behavior will not work at all.' );
396     }
397
398     return $c->_filter_component( $comp );
399 }
400
401
402 =head2 $c->view($name)
403
404 Gets a L<Catalyst::View> instance by name.
405
406     $c->view('Foo')->do_stuff;
407
408 Any extra arguments are directly passed to ACCEPT_CONTEXT.
409
410 If the name is omitted, it will look for
411  - a view object in $c->stash->{current_view_instance}, then
412  - a view name in $c->stash->{current_view}, then
413  - a config setting 'default_view', or
414  - check if there is only one view, and return it if that's the case.
415
416 If you want to search for views, pass in a regexp as the argument.
417
418     # find all views that start with Foo
419     my @foo_views = $c->view(qr{^Foo});
420
421 =cut
422
423 sub view {
424     my ( $c, $name, @args ) = @_;
425
426     if( $name ) {
427         my @result = $c->_comp_search_prefixes( $name, qw/View V/ );
428         return map { $c->_filter_component( $_, @args ) } @result if ref $name;
429         return $c->_filter_component( $result[ 0 ], @args );
430     }
431
432     if (ref $c) {
433         return $c->stash->{current_view_instance}
434           if $c->stash->{current_view_instance};
435         return $c->view( $c->stash->{current_view} )
436           if $c->stash->{current_view};
437     }
438     return $c->view( $c->config->{default_view} )
439       if $c->config->{default_view};
440     my( $comp, $rest ) = $c->_comp_search_prefixes( undef, qw/View V/);
441
442     if( $rest ) {
443         $c->log->warn( 'Calling $c->view() will return a random view unless you specify one of:' );
444         $c->log->warn( '* $c->config(default_view => "the name of the default view to use")' );
445         $c->log->warn( '* $c->stash->{current_view} # the name of the view to use for this request' );
446         $c->log->warn( '* $c->stash->{current_view_instance} # the instance of the view to use for this request' );
447         $c->log->warn( 'NB: in version 5.81, the "random" behavior will not work at all.' );
448     }
449
450     return $c->_filter_component( $comp );
451 }
452
453 =head2 UTILITY METHODS
454
455 =head2 $c->uri_for( $path?, @args?, \%query_values? )
456
457 =head2 $c->uri_for( $action, \@captures?, @args?, \%query_values? )
458
459 Constructs an absolute L<URI> object based on the application root, the
460 provided path, and the additional arguments and query parameters provided.
461 When used as a string, provides a textual URI.
462
463 If no arguments are provided, the URI for the current action is returned.
464 To return the current action and also provide @args, use
465 C<< $c->uri_for( $c->action, @args ) >>. 
466
467 If the first argument is a string, it is taken as a public URI path relative
468 to C<< $c->namespace >> (if it doesn't begin with a forward slash) or
469 relative to the application root (if it does). It is then merged with
470 C<< $c->request->base >>; any C<@args> are appended as additional path
471 components; and any C<%query_values> are appended as C<?foo=bar> parameters.
472
473 If the first argument is a L<Catalyst::Action> it represents an action which
474 will have its path resolved using C<< $c->dispatcher->uri_for_action >>. The
475 optional C<\@captures> argument (an arrayref) allows passing the captured
476 variables that are needed to fill in the paths of Chained and Regex actions;
477 once the path is resolved, C<uri_for> continues as though a path was
478 provided, appending any arguments or parameters and creating an absolute
479 URI.
480
481 The captures for the current request can be found in
482 C<< $c->request->captures >>, and actions can be resolved using
483 C<< Catalyst::Controller->action_for($name) >>. If you have a private action
484 path, use C<< $c->uri_for_action >> instead.
485
486   # Equivalent to $c->req->uri
487   $c->uri_for($c->action, $c->req->captures,
488       @{ $c->req->args }, $c->req->params);
489
490   # For the Foo action in the Bar controller
491   $c->uri_for($c->controller('Bar')->action_for('Foo'));
492
493   # Path to a static resource
494   $c->uri_for('/static/images/logo.png');
495
496 =cut
497
498 sub uri_for {
499     my ( $c, $path, @args ) = @_;
500
501     if (blessed($path) && $path->isa('Catalyst::Controller')) {
502         $path = $path->path_prefix;
503         $path =~ s{/+\z}{};
504         $path .= '/';
505     }
506
507     if ( blessed($path) ) { # action object
508         my $captures = [ map { s|/|%2F|; $_; }
509                         ( scalar @args && ref $args[0] eq 'ARRAY'
510                          ? @{ shift(@args) }
511                          : ()) ];
512         my $action = $path;
513         $path = $c->dispatcher->uri_for_action($action, $captures);
514         if (not defined $path) {
515             $c->log->debug(qq/Can't find uri_for action '$action' @$captures/)
516                 if $c->debug;
517             return undef;
518         }
519         $path = '/' if $path eq '';
520     }
521
522     undef($path) if (defined $path && $path eq '');
523
524     my $params =
525       ( scalar @args && ref $args[$#args] eq 'HASH' ? pop @args : {} );
526
527     carp "uri_for called with undef argument" if grep { ! defined $_ } @args;
528     s/([^$URI::uric])/$URI::Escape::escapes{$1}/go for @args;
529     s|/|%2F| for @args;
530
531     unshift(@args, $path);
532
533     unless (defined $path && $path =~ s!^/!!) { # in-place strip
534         my $namespace = $c->namespace;
535         if (defined $path) { # cheesy hack to handle path '../foo'
536            $namespace =~ s{(?:^|/)[^/]+$}{} while $args[0] =~ s{^\.\./}{};
537         }
538         unshift(@args, $namespace || '');
539     }
540
541     # join args with '/', or a blank string
542     my $args = join('/', grep { defined($_) } @args);
543     $args =~ s/\?/%3F/g; # STUPID STUPID SPECIAL CASE
544     $args =~ s!^/+!!;
545     my $base = $c->req->base;
546     my $class = ref($base);
547     $base =~ s{(?<!/)$}{/};
548
549     my $query = '';
550
551     if (my @keys = keys %$params) {
552       # somewhat lifted from URI::_query's query_form
553       $query = '?'.join('&', map {
554           my $val = $params->{$_};
555           s/([;\/?:@&=+,\$\[\]%])/$URI::Escape::escapes{$1}/go;
556           s/ /+/g;
557           my $key = $_;
558           $val = '' unless defined $val;
559           (map {
560               my $param = "$_";
561               utf8::encode( $param ) if utf8::is_utf8($param);
562               # using the URI::Escape pattern here so utf8 chars survive
563               $param =~ s/([^A-Za-z0-9\-_.!~*'() ])/$URI::Escape::escapes{$1}/go;
564               $param =~ s/ /+/g;
565               "${key}=$param"; } ( ref $val eq 'ARRAY' ? @$val : $val ));
566       } @keys);
567     }
568
569     my $res = bless(\"${base}${args}${query}", $class);
570     $res;
571 }
572
573 =head2 $c->uri_for_action( $path, \@captures?, @args?, \%query_values? )
574
575 =head2 $c->uri_for_action( $action, \@captures?, @args?, \%query_values? )
576
577 =over
578
579 =item $path
580
581 A private path to the Catalyst action you want to create a URI for.
582
583 This is a shortcut for calling C<< $c->dispatcher->get_action_by_path($path)
584 >> and passing the resulting C<$action> and the remaining arguments to C<<
585 $c->uri_for >>.
586
587 You can also pass in a Catalyst::Action object, in which case it is passed to
588 C<< $c->uri_for >>.
589
590 =back
591
592 =cut
593
594 sub uri_for_action {
595     my ( $c, $path, @args ) = @_;
596     my $action = blessed($path)
597       ? $path
598       : $c->dispatcher->get_action_by_path($path);
599     unless (defined $action) {
600       croak "Can't find action for path '$path'";
601     }
602     return $c->uri_for( $action, @args );
603 }
604
605 =head1 INTERNAL METHODS
606
607 =head2 $c->counter
608
609 Returns a hashref containing coderefs and execution counts (needed for
610 deep recursion detection).
611
612 =head2 $c->depth
613
614 Returns the number of actions on the current internal execution stack.
615
616 =head2 $c->dispatch
617
618 Dispatches a request to actions.
619
620 =cut
621
622 sub dispatch { my $c = shift; $c->dispatcher->dispatch( $c, @_ ) }
623
624 =head2 $c->dump_these
625
626 Returns a list of 2-element array references (name, structure) pairs
627 that will be dumped on the error page in debug mode.
628
629 =cut
630
631 sub dump_these {
632     my $c = shift;
633     [ Request => $c->req ],
634     [ Response => $c->res ],
635     [ Stash => $c->stash ],
636     [ Config => $c->config ];
637 }
638
639 =head2 $c->execute( $class, $coderef )
640
641 Execute a coderef in given class and catch exceptions. Errors are available
642 via $c->error.
643
644 =cut
645
646 sub execute {
647     my ( $c, $class, $code ) = @_;
648     $class = $c->component($class) || $class;
649     $c->state(0);
650
651     if ( $c->depth >= $RECURSION ) {
652         my $action = $code->reverse();
653         $action = "/$action" unless $action =~ /->/;
654         my $error = qq/Deep recursion detected calling "${action}"/;
655         $c->log->error($error);
656         $c->error($error);
657         $c->state(0);
658         return $c->state;
659     }
660
661     my $stats_info = $c->_stats_start_execute( $code ) if $c->use_stats;
662
663     push( @{ $c->stack }, $code );
664
665     no warnings 'recursion';
666     eval { $c->state( $code->execute( $class, $c, @{ $c->req->args } ) || 0 ) };
667
668     $c->_stats_finish_execute( $stats_info ) if $c->use_stats and $stats_info;
669
670     my $last = pop( @{ $c->stack } );
671
672     if ( my $error = $@ ) {
673         if ( blessed($error) and $error->isa('Catalyst::Exception::Detach') ) {
674             $error->rethrow if $c->depth > 1;
675         }
676         elsif ( blessed($error) and $error->isa('Catalyst::Exception::Go') ) {
677             $error->rethrow if $c->depth > 0;
678         }
679         else {
680             unless ( ref $error ) {
681                 no warnings 'uninitialized';
682                 chomp $error;
683                 my $class = $last->class;
684                 my $name  = $last->name;
685                 $error = qq/Caught exception in $class->$name "$error"/;
686             }
687             $c->error($error);
688             $c->state(0);
689         }
690     }
691     return $c->state;
692 }
693
694 sub _stats_start_execute {
695     my ( $c, $code ) = @_;
696     return if ( ( $code->name =~ /^_.*/ )
697         && ( !$c->config->{show_internal_actions} ) );
698
699     my $action_name = $code->reverse();
700     $c->counter->{$action_name}++;
701
702     my $action = $action_name;
703     $action = "/$action" unless $action =~ /->/;
704
705     # determine if the call was the result of a forward
706     # this is done by walking up the call stack and looking for a calling
707     # sub of Catalyst::forward before the eval
708     my $callsub = q{};
709     for my $index ( 2 .. 11 ) {
710         last
711         if ( ( caller($index) )[0] eq 'Catalyst'
712             && ( caller($index) )[3] eq '(eval)' );
713
714         if ( ( caller($index) )[3] =~ /forward$/ ) {
715             $callsub = ( caller($index) )[3];
716             $action  = "-> $action";
717             last;
718         }
719     }
720
721     my $uid = $action_name . $c->counter->{$action_name};
722
723     # is this a root-level call or a forwarded call?
724     if ( $callsub =~ /forward$/ ) {
725         my $parent = $c->stack->[-1];
726
727         # forward, locate the caller
728         if ( exists $c->counter->{"$parent"} ) {
729             $c->stats->profile(
730                 begin  => $action,
731                 parent => "$parent" . $c->counter->{"$parent"},
732                 uid    => $uid,
733             );
734         }
735         else {
736
737             # forward with no caller may come from a plugin
738             $c->stats->profile(
739                 begin => $action,
740                 uid   => $uid,
741             );
742         }
743     }
744     else {
745
746         # root-level call
747         $c->stats->profile(
748             begin => $action,
749             uid   => $uid,
750         );
751     }
752     return $action;
753
754 }
755
756 sub _stats_finish_execute {
757     my ( $c, $info ) = @_;
758     $c->stats->profile( end => $info );
759 }
760
761 =head2 $c->finalize
762
763 Finalizes the request.
764
765 =cut
766
767 sub finalize {
768     my $c = shift;
769
770     for my $error ( @{ $c->error } ) {
771         $c->log->error($error);
772     }
773
774     # Allow engine to handle finalize flow (for POE)
775     my $engine = $c->engine;
776     if ( my $code = $engine->can('finalize') ) {
777         $engine->$code($c);
778     }
779     else {
780
781         $c->finalize_uploads;
782
783         # Error
784         if ( $#{ $c->error } >= 0 ) {
785             $c->finalize_error;
786         }
787
788         $c->finalize_headers;
789
790         # HEAD request
791         if ( $c->request->method eq 'HEAD' ) {
792             $c->response->body('');
793         }
794
795         $c->finalize_body;
796     }
797
798     if ($c->use_stats) {
799         my $elapsed = sprintf '%f', $c->stats->elapsed;
800         my $av = $elapsed == 0 ? '??' : sprintf '%.3f', 1 / $elapsed;
801         $c->log->info(
802             "Request took ${elapsed}s ($av/s)\n" . $c->stats->report . "\n" );
803     }
804
805     return $c->response->status;
806 }
807
808 =head2 $c->finalize_body
809
810 Finalizes body.
811
812 =cut
813
814 sub finalize_body { my $c = shift; $c->engine->finalize_body( $c, @_ ) }
815
816 =head2 $c->finalize_cookies
817
818 Finalizes cookies.
819
820 =cut
821
822 sub finalize_cookies { my $c = shift; $c->engine->finalize_cookies( $c, @_ ) }
823
824 =head2 $c->finalize_error
825
826 Finalizes error.
827
828 =cut
829
830 sub finalize_error { my $c = shift; $c->engine->finalize_error( $c, @_ ) }
831
832 =head2 $c->finalize_headers
833
834 Finalizes headers.
835
836 =cut
837
838 sub finalize_headers {
839     my $c = shift;
840
841     my $response = $c->response; #accessor calls can add up?
842
843     # Check if we already finalized headers
844     return if $response->finalized_headers;
845
846     # Handle redirects
847     if ( my $location = $response->redirect ) {
848         $c->log->debug(qq/Redirecting to "$location"/) if $c->debug;
849         $response->header( Location => $location );
850
851         if ( !$response->has_body ) {
852             # Add a default body if none is already present
853             $response->body(
854                 qq{<html><body><p>This item has moved <a href="$location">here</a>.</p></body></html>}
855             );
856         }
857     }
858
859     # Content-Length
860     if ( $response->body && !$response->content_length ) {
861
862         # get the length from a filehandle
863         if ( blessed( $response->body ) && $response->body->can('read') )
864         {
865             my $stat = stat $response->body;
866             if ( $stat && $stat->size > 0 ) {
867                 $response->content_length( $stat->size );
868             }
869             else {
870                 $c->log->warn('Serving filehandle without a content-length');
871             }
872         }
873         else {
874             # everything should be bytes at this point, but just in case
875             $response->content_length( bytes::length( $response->body ) );
876         }
877     }
878
879     # Errors
880     if ( $response->status =~ /^(1\d\d|[23]04)$/ ) {
881         $response->headers->remove_header("Content-Length");
882         $response->body('');
883     }
884
885     $c->finalize_cookies;
886
887     $c->engine->finalize_headers( $c, @_ );
888
889     # Done
890     $response->finalized_headers(1);
891 }
892
893 =head2 $c->finalize_output
894
895 An alias for finalize_body.
896
897 =head2 $c->finalize_read
898
899 Finalizes the input after reading is complete.
900
901 =cut
902
903 sub finalize_read { my $c = shift; $c->engine->finalize_read( $c, @_ ) }
904
905 =head2 $c->finalize_uploads
906
907 Finalizes uploads. Cleans up any temporary files.
908
909 =cut
910
911 sub finalize_uploads { my $c = shift; $c->engine->finalize_uploads( $c, @_ ) }
912
913 =head2 $c->get_action( $action, $namespace )
914
915 Gets an action in a given namespace.
916
917 =cut
918
919 sub get_action { my $c = shift; $c->dispatcher->get_action(@_) }
920
921 =head2 $c->get_actions( $action, $namespace )
922
923 Gets all actions of a given name in a namespace and all parent
924 namespaces.
925
926 =cut
927
928 sub get_actions { my $c = shift; $c->dispatcher->get_actions( $c, @_ ) }
929
930 =head2 $c->prepare_action
931
932 Prepares action. See L<Catalyst::Dispatcher>.
933
934 =cut
935
936 sub prepare_action { my $c = shift; $c->dispatcher->prepare_action( $c, @_ ) }
937
938 =head2 $c->prepare_body
939
940 Prepares message body.
941
942 =cut
943
944 sub prepare_body {
945     my $c = shift;
946
947     return if $c->request->_has_body;
948
949     # Initialize on-demand data
950     $c->engine->prepare_body( $c, @_ );
951     $c->prepare_parameters;
952     $c->prepare_uploads;
953
954     if ( $c->debug && keys %{ $c->req->body_parameters } ) {
955         my $t = Text::SimpleTable->new( [ 35, 'Parameter' ], [ 36, 'Value' ] );
956         for my $key ( sort keys %{ $c->req->body_parameters } ) {
957             my $param = $c->req->body_parameters->{$key};
958             my $value = defined($param) ? $param : '';
959             $t->row( $key,
960                 ref $value eq 'ARRAY' ? ( join ', ', @$value ) : $value );
961         }
962         $c->log->debug( "Body Parameters are:\n" . $t->draw );
963     }
964 }
965
966 =head2 $c->prepare_body_chunk( $chunk )
967
968 Prepares a chunk of data before sending it to L<HTTP::Body>.
969
970 See L<Catalyst::Engine>.
971
972 =cut
973
974 sub prepare_body_chunk {
975     my $c = shift;
976     $c->engine->prepare_body_chunk( $c, @_ );
977 }
978
979 =head2 $c->prepare_body_parameters
980
981 Prepares body parameters.
982
983 =cut
984
985 sub prepare_body_parameters {
986     my $c = shift;
987     $c->engine->prepare_body_parameters( $c, @_ );
988 }
989
990 =head2 $c->prepare_connection
991
992 Prepares connection.
993
994 =cut
995
996 sub prepare_connection {
997     my $c = shift;
998     $c->engine->prepare_connection( $c, @_ );
999 }
1000
1001 =head2 $c->prepare_cookies
1002
1003 Prepares cookies.
1004
1005 =cut
1006
1007 sub prepare_cookies { my $c = shift; $c->engine->prepare_cookies( $c, @_ ) }
1008
1009 =head2 $c->prepare_headers
1010
1011 Prepares headers.
1012
1013 =cut
1014
1015 sub prepare_headers { my $c = shift; $c->engine->prepare_headers( $c, @_ ) }
1016
1017 =head2 $c->prepare_parameters
1018
1019 Prepares parameters.
1020
1021 =cut
1022
1023 sub prepare_parameters {
1024     my $c = shift;
1025     $c->prepare_body_parameters;
1026     $c->engine->prepare_parameters( $c, @_ );
1027 }
1028
1029 =head2 $c->prepare_path
1030
1031 Prepares path and base.
1032
1033 =cut
1034
1035 sub prepare_path { my $c = shift; $c->engine->prepare_path( $c, @_ ) }
1036
1037 =head2 $c->prepare_query_parameters
1038
1039 Prepares query parameters.
1040
1041 =cut
1042
1043 sub prepare_query_parameters {
1044     my $c = shift;
1045
1046     $c->engine->prepare_query_parameters( $c, @_ );
1047
1048     if ( $c->debug && keys %{ $c->request->query_parameters } ) {
1049         my $t = Text::SimpleTable->new( [ 35, 'Parameter' ], [ 36, 'Value' ] );
1050         for my $key ( sort keys %{ $c->req->query_parameters } ) {
1051             my $param = $c->req->query_parameters->{$key};
1052             my $value = defined($param) ? $param : '';
1053             $t->row( $key,
1054                 ref $value eq 'ARRAY' ? ( join ', ', @$value ) : $value );
1055         }
1056         $c->log->debug( "Query Parameters are:\n" . $t->draw );
1057     }
1058 }
1059
1060 =head2 $c->prepare_read
1061
1062 Prepares the input for reading.
1063
1064 =cut
1065
1066 sub prepare_read { my $c = shift; $c->engine->prepare_read( $c, @_ ) }
1067
1068 =head2 $c->prepare_request
1069
1070 Prepares the engine request.
1071
1072 =cut
1073
1074 sub prepare_request { my $c = shift; $c->engine->prepare_request( $c, @_ ) }
1075
1076 =head2 $c->prepare_uploads
1077
1078 Prepares uploads.
1079
1080 =cut
1081
1082 sub prepare_uploads {
1083     my $c = shift;
1084
1085     $c->engine->prepare_uploads( $c, @_ );
1086
1087     if ( $c->debug && keys %{ $c->request->uploads } ) {
1088         my $t = Text::SimpleTable->new(
1089             [ 12, 'Parameter' ],
1090             [ 26, 'Filename' ],
1091             [ 18, 'Type' ],
1092             [ 9,  'Size' ]
1093         );
1094         for my $key ( sort keys %{ $c->request->uploads } ) {
1095             my $upload = $c->request->uploads->{$key};
1096             for my $u ( ref $upload eq 'ARRAY' ? @{$upload} : ($upload) ) {
1097                 $t->row( $key, $u->filename, $u->type, $u->size );
1098             }
1099         }
1100         $c->log->debug( "File Uploads are:\n" . $t->draw );
1101     }
1102 }
1103
1104 =head2 $c->prepare_write
1105
1106 Prepares the output for writing.
1107
1108 =cut
1109
1110 sub prepare_write { my $c = shift; $c->engine->prepare_write( $c, @_ ) }
1111
1112 =head2 $c->read( [$maxlength] )
1113
1114 Reads a chunk of data from the request body. This method is designed to
1115 be used in a while loop, reading C<$maxlength> bytes on every call.
1116 C<$maxlength> defaults to the size of the request if not specified.
1117
1118 You have to set C<< MyApp->config(parse_on_demand => 1) >> to use this
1119 directly.
1120
1121 Warning: If you use read(), Catalyst will not process the body,
1122 so you will not be able to access POST parameters or file uploads via
1123 $c->request.  You must handle all body parsing yourself.
1124
1125 =cut
1126
1127 sub read { my $c = shift; return $c->engine->read( $c, @_ ) }
1128
1129 =head2 $c->stack
1130
1131 Returns an arrayref of the internal execution stack (actions that are
1132 currently executing).
1133
1134
1135 =head2 $c->write( $data )
1136
1137 Writes $data to the output stream. When using this method directly, you
1138 will need to manually set the C<Content-Length> header to the length of
1139 your output data, if known.
1140
1141 =cut
1142
1143 sub write {
1144     my $c = shift;
1145
1146     # Finalize headers if someone manually writes output
1147     $c->finalize_headers;
1148
1149     return $c->engine->write( $c, @_ );
1150 }
1151
1152 no Moose;
1153 __PACKAGE__->meta->make_immutable;
1154
1155 1;
1156
1157 __END__
1158
1159 =head1 NAME
1160
1161 Catalyst::Context - object for keeping request related state
1162
1163 =head1 ATTRIBUTES 
1164
1165 =head3 action
1166
1167 =head3 counter
1168
1169 =head3 namespace
1170
1171 =head3 request_class
1172
1173 =head3 request
1174
1175 =head3 response_class
1176
1177 =head3 response
1178
1179 =head3 stack
1180
1181 =head3 stash
1182
1183 =head3 state
1184
1185 =head3 stats
1186
1187 =head1 SEE ALSO
1188
1189 L<Catalyst>, L<Catalyst::Model>, L<Catalyst::View>, L<Catalyst::Controller>.
1190
1191 =head1 AUTHORS
1192
1193 Catalyst Contributors, see Catalyst.pm
1194
1195 =head1 COPYRIGHT
1196
1197 This library is free software. You can redistribute it and/or modify it under
1198 the same terms as Perl itself.
1199
1200 =cut
1201