Commit | Line | Data |
c20db8ca |
1 | package Catalyst::Context; |
2 | |
3 | use Moose; |
4 | use bytes; |
5 | use B::Hooks::EndOfScope (); |
48603b30 |
6 | use Catalyst; |
c20db8ca |
7 | use Catalyst::Exception::Detach; |
8 | use Catalyst::Exception::Go; |
9 | use Catalyst::Request; |
10 | use Catalyst::Request::Upload; |
11 | use Catalyst::Response; |
12 | use Catalyst::Utils; |
13 | use File::stat; |
14 | use Text::SimpleTable (); |
15 | use URI (); |
16 | use URI::http; |
17 | use URI::https; |
18 | use utf8; |
19 | use Carp qw/croak carp shortmess/; |
20 | |
21 | has stack => (is => 'ro', default => sub { [] }); |
22 | has stash => (is => 'rw', default => sub { {} }); |
23 | has state => (is => 'rw', default => 0); |
24 | has stats => (is => 'rw'); |
25 | has action => (is => 'rw'); |
26 | has counter => (is => 'rw', default => sub { {} }); |
27 | has request => (is => 'rw', default => sub { $_[0]->request_class->new({}) }, required => 1, lazy => 1); |
28 | has response => (is => 'rw', default => sub { $_[0]->response_class->new({}) }, required => 1, lazy => 1); |
29 | has namespace => (is => 'rw'); |
30 | |
31 | |
32 | has 'application' => ( |
33 | isa => 'Catalyst', |
34 | is => 'ro', |
35 | handles => [ |
36 | qw/ |
37 | controllers |
38 | models |
39 | views |
40 | component |
41 | config |
42 | log |
43 | debug |
44 | dispatcher_class |
45 | request_class |
48603b30 |
46 | response_class |
c20db8ca |
47 | dispatcher |
48 | prepare |
49 | engine_class |
50 | engine |
51 | path_to |
52 | plugin |
53 | setup_finalize |
54 | welcome_message |
55 | components |
48603b30 |
56 | context_class |
57 | setup_actions |
c20db8ca |
58 | search_extra |
59 | root |
60 | parse_on_demand |
61 | name |
62 | ignore_frontend_proxy |
63 | home |
64 | default_model |
65 | default_view |
66 | version |
67 | use_stats |
68 | stats_class |
69 | set_action |
70 | |
71 | ran_setup |
72 | _comp_search_prefixes |
73 | _filter_component |
74 | / |
75 | ], |
76 | ); |
77 | |
78 | sub depth { scalar @{ shift->stack || [] }; } |
79 | |
80 | sub req { |
81 | my $self = shift; return $self->request(@_); |
82 | } |
83 | sub res { |
84 | my $self = shift; return $self->response(@_); |
85 | } |
86 | |
87 | # For backwards compatibility |
88 | sub finalize_output { shift->finalize_body(@_) }; |
89 | |
90 | # For statistics |
91 | our $RECURSION = 1000; |
c20db8ca |
92 | |
93 | =head1 METHODS |
94 | |
95 | =head2 INFORMATION ABOUT THE CURRENT REQUEST |
96 | |
97 | =head2 $c->action |
98 | |
99 | Returns a L<Catalyst::Action> object for the current action, which |
100 | stringifies to the action name. See L<Catalyst::Action>. |
101 | |
102 | =head2 $c->namespace |
103 | |
104 | Returns the namespace of the current action, i.e., the URI prefix |
105 | corresponding to the controller of the current action. For example: |
106 | |
107 | # in Controller::Foo::Bar |
108 | $c->namespace; # returns 'foo/bar'; |
109 | |
110 | =head2 $c->request |
111 | |
112 | =head2 $c->req |
113 | |
114 | Returns the current L<Catalyst::Request> object, giving access to |
115 | information about the current client request (including parameters, |
116 | cookies, HTTP headers, etc.). See L<Catalyst::Request>. |
117 | |
118 | =head2 REQUEST FLOW HANDLING |
119 | |
120 | =head2 $c->forward( $action [, \@arguments ] ) |
121 | |
122 | =head2 $c->forward( $class, $method, [, \@arguments ] ) |
123 | |
124 | Forwards processing to another action, by its private name. If you give a |
125 | class name but no method, C<process()> is called. You may also optionally |
126 | pass arguments in an arrayref. The action will receive the arguments in |
127 | C<@_> and C<< $c->req->args >>. Upon returning from the function, |
128 | C<< $c->req->args >> will be restored to the previous values. |
129 | |
130 | Any data C<return>ed from the action forwarded to, will be returned by the |
131 | call to forward. |
132 | |
133 | my $foodata = $c->forward('/foo'); |
134 | $c->forward('index'); |
135 | $c->forward(qw/MyApp::Model::DBIC::Foo do_stuff/); |
136 | $c->forward('MyApp::View::TT'); |
137 | |
138 | Note that L<< forward|/"$c->forward( $action [, \@arguments ] )" >> implies |
139 | an C<< eval { } >> around the call (actually |
140 | L<< execute|/"$c->execute( $class, $coderef )" >> does), thus de-fatalizing |
141 | all 'dies' within the called action. If you want C<die> to propagate you |
142 | need to do something like: |
143 | |
144 | $c->forward('foo'); |
145 | die $c->error if $c->error; |
146 | |
147 | Or make sure to always return true values from your actions and write |
148 | your code like this: |
149 | |
150 | $c->forward('foo') || return; |
151 | |
152 | Another note is that C<< $c->forward >> always returns a scalar because it |
153 | actually returns $c->state which operates in a scalar context. |
154 | Thus, something like: |
155 | |
156 | return @array; |
157 | |
158 | in an action that is forwarded to is going to return a scalar, |
159 | i.e. how many items are in that array, which is probably not what you want. |
160 | If you need to return an array then return a reference to it, |
161 | or stash it like so: |
162 | |
163 | $c->stash->{array} = \@array; |
164 | |
165 | and access it from the stash. |
166 | |
167 | =cut |
168 | |
169 | sub forward { my $c = shift; no warnings 'recursion'; $c->dispatcher->forward( $c, @_ ) } |
170 | |
171 | =head2 $c->detach( $action [, \@arguments ] ) |
172 | |
173 | =head2 $c->detach( $class, $method, [, \@arguments ] ) |
174 | |
175 | =head2 $c->detach() |
176 | |
177 | The same as L<< forward|/"$c->forward( $action [, \@arguments ] )" >>, but |
178 | doesn't return to the previous action when processing is finished. |
179 | |
180 | When called with no arguments it escapes the processing chain entirely. |
181 | |
182 | =cut |
183 | |
184 | sub detach { my $c = shift; $c->dispatcher->detach( $c, @_ ) } |
185 | |
186 | =head2 $c->visit( $action [, \@captures, \@arguments ] ) |
187 | |
188 | =head2 $c->visit( $class, $method, [, \@captures, \@arguments ] ) |
189 | |
190 | Almost the same as L<< forward|/"$c->forward( $action [, \@arguments ] )" >>, |
191 | but does a full dispatch, instead of just calling the new C<$action> / |
192 | C<< $class->$method >>. This means that C<begin>, C<auto> and the method |
193 | you go to are called, just like a new request. |
194 | |
195 | In addition both C<< $c->action >> and C<< $c->namespace >> are localized. |
196 | This means, for example, that C<< $c->action >> methods such as |
197 | L<name|Catalyst::Action/name>, L<class|Catalyst::Action/class> and |
198 | L<reverse|Catalyst::Action/reverse> return information for the visited action |
199 | when they are invoked within the visited action. This is different from the |
200 | behavior of L<< forward|/"$c->forward( $action [, \@arguments ] )" >>, which |
201 | continues to use the $c->action object from the caller action even when |
202 | invoked from the callee. |
203 | |
204 | C<< $c->stash >> is kept unchanged. |
205 | |
206 | In effect, L<< visit|/"$c->visit( $action [, \@captures, \@arguments ] )" >> |
207 | allows you to "wrap" another action, just as it would have been called by |
208 | dispatching from a URL, while the analogous |
209 | L<< go|/"$c->go( $action [, \@captures, \@arguments ] )" >> allows you to |
210 | transfer control to another action as if it had been reached directly from a URL. |
211 | |
212 | =cut |
213 | |
214 | sub visit { my $c = shift; $c->dispatcher->visit( $c, @_ ) } |
215 | |
216 | =head2 $c->go( $action [, \@captures, \@arguments ] ) |
217 | |
218 | =head2 $c->go( $class, $method, [, \@captures, \@arguments ] ) |
219 | |
220 | The relationship between C<go> and |
221 | L<< visit|/"$c->visit( $action [, \@captures, \@arguments ] )" >> is the same as |
222 | the relationship between |
223 | L<< forward|/"$c->forward( $class, $method, [, \@arguments ] )" >> and |
224 | L<< detach|/"$c->detach( $action [, \@arguments ] )" >>. Like C<< $c->visit >>, |
225 | C<< $c->go >> will perform a full dispatch on the specified action or method, |
226 | with localized C<< $c->action >> and C<< $c->namespace >>. Like C<detach>, |
227 | C<go> escapes the processing of the current request chain on completion, and |
228 | does not return to its caller. |
229 | |
230 | =cut |
231 | |
232 | sub go { my $c = shift; $c->dispatcher->go( $c, @_ ) } |
233 | |
234 | =head2 $c->response |
235 | |
236 | =head2 $c->res |
237 | |
238 | Returns the current L<Catalyst::Response> object, see there for details. |
239 | |
240 | =head2 $c->stash |
241 | |
242 | Returns a hashref to the stash, which may be used to store data and pass |
243 | it between components during a request. You can also set hash keys by |
244 | passing arguments. The stash is automatically sent to the view. The |
245 | stash is cleared at the end of a request; it cannot be used for |
246 | persistent storage (for this you must use a session; see |
247 | L<Catalyst::Plugin::Session> for a complete system integrated with |
248 | Catalyst). |
249 | |
250 | $c->stash->{foo} = $bar; |
251 | $c->stash( { moose => 'majestic', qux => 0 } ); |
252 | $c->stash( bar => 1, gorch => 2 ); # equivalent to passing a hashref |
253 | |
254 | # stash is automatically passed to the view for use in a template |
255 | $c->forward( 'MyApp::View::TT' ); |
256 | |
257 | =cut |
258 | |
259 | around stash => sub { |
260 | my $orig = shift; |
261 | my $c = shift; |
262 | my $stash = $orig->($c); |
263 | if (@_) { |
264 | my $new_stash = @_ > 1 ? {@_} : $_[0]; |
265 | croak('stash takes a hash or hashref') unless ref $new_stash; |
266 | foreach my $key ( keys %$new_stash ) { |
267 | $stash->{$key} = $new_stash->{$key}; |
268 | } |
269 | } |
270 | |
271 | return $stash; |
272 | }; |
273 | |
274 | |
275 | =head2 $c->error |
276 | |
277 | =head2 $c->error($error, ...) |
278 | |
279 | =head2 $c->error($arrayref) |
280 | |
281 | Returns an arrayref containing error messages. If Catalyst encounters an |
282 | error while processing a request, it stores the error in $c->error. This |
283 | method should only be used to store fatal error messages. |
284 | |
285 | my @error = @{ $c->error }; |
286 | |
287 | Add a new error. |
288 | |
289 | $c->error('Something bad happened'); |
290 | |
291 | =cut |
292 | |
293 | sub error { |
294 | my $c = shift; |
295 | if ( $_[0] ) { |
296 | my $error = ref $_[0] eq 'ARRAY' ? $_[0] : [@_]; |
297 | croak @$error unless ref $c; |
298 | push @{ $c->{error} }, @$error; |
299 | } |
300 | elsif ( defined $_[0] ) { $c->{error} = undef } |
301 | return $c->{error} || []; |
302 | } |
303 | |
304 | |
305 | =head2 $c->state |
306 | |
307 | Contains the return value of the last executed action. |
308 | Note that << $c->state >> operates in a scalar context which means that all |
309 | values it returns are scalar. |
310 | |
311 | =head2 $c->clear_errors |
312 | |
313 | Clear errors. You probably don't want to clear the errors unless you are |
314 | implementing a custom error screen. |
315 | |
316 | This is equivalent to running |
317 | |
318 | $c->error(0); |
319 | |
320 | =cut |
321 | |
322 | sub clear_errors { |
323 | my $c = shift; |
324 | $c->error(0); |
325 | } |
326 | |
327 | |
328 | =head2 COMPONENT ACCESSORS |
329 | |
330 | =head2 $c->controller($name) |
331 | |
332 | Gets a L<Catalyst::Controller> instance by name. |
333 | |
334 | $c->controller('Foo')->do_stuff; |
335 | |
336 | If the name is omitted, will return the controller for the dispatched |
337 | action. |
338 | |
339 | If you want to search for controllers, pass in a regexp as the argument. |
340 | |
341 | # find all controllers that start with Foo |
342 | my @foo_controllers = $c->controller(qr{^Foo}); |
343 | |
344 | |
345 | =cut |
346 | |
347 | sub controller { |
348 | my ( $c, $name, @args ) = @_; |
349 | |
350 | if( $name ) { |
351 | my @result = $c->_comp_search_prefixes( $name, qw/Controller C/ ); |
352 | return map { $c->_filter_component( $_, @args ) } @result if ref $name; |
353 | return $c->_filter_component( $result[ 0 ], @args ); |
354 | } |
355 | |
356 | return $c->component( $c->action->class ); |
357 | } |
358 | |
359 | =head2 $c->model($name) |
360 | |
361 | Gets a L<Catalyst::Model> instance by name. |
362 | |
363 | $c->model('Foo')->do_stuff; |
364 | |
365 | Any extra arguments are directly passed to ACCEPT_CONTEXT. |
366 | |
367 | If the name is omitted, it will look for |
368 | - a model object in $c->stash->{current_model_instance}, then |
369 | - a model name in $c->stash->{current_model}, then |
370 | - a config setting 'default_model', or |
371 | - check if there is only one model, and return it if that's the case. |
372 | |
373 | If you want to search for models, pass in a regexp as the argument. |
374 | |
375 | # find all models that start with Foo |
376 | my @foo_models = $c->model(qr{^Foo}); |
377 | |
378 | =cut |
379 | |
380 | sub model { |
381 | my ( $c, $name, @args ) = @_; |
382 | my $appclass = ref($c) || $c; |
383 | if( $name ) { |
384 | my @result = $c->_comp_search_prefixes( $name, qw/Model M/ ); |
385 | return map { $c->_filter_component( $_, @args ) } @result if ref $name; |
386 | return $c->_filter_component( $result[ 0 ], @args ); |
387 | } |
388 | |
389 | if (ref $c) { |
390 | return $c->stash->{current_model_instance} |
391 | if $c->stash->{current_model_instance}; |
392 | return $c->model( $c->stash->{current_model} ) |
393 | if $c->stash->{current_model}; |
394 | } |
395 | return $c->model( $appclass->config->{default_model} ) |
396 | if $appclass->config->{default_model}; |
397 | |
398 | my( $comp, $rest ) = $c->_comp_search_prefixes( undef, qw/Model M/); |
399 | |
400 | if( $rest ) { |
401 | $c->log->warn( Carp::shortmess('Calling $c->model() will return a random model unless you specify one of:') ); |
402 | $c->log->warn( '* $c->config(default_model => "the name of the default model to use")' ); |
403 | $c->log->warn( '* $c->stash->{current_model} # the name of the model to use for this request' ); |
404 | $c->log->warn( '* $c->stash->{current_model_instance} # the instance of the model to use for this request' ); |
405 | $c->log->warn( 'NB: in version 5.81, the "random" behavior will not work at all.' ); |
406 | } |
407 | |
408 | return $c->_filter_component( $comp ); |
409 | } |
410 | |
411 | |
412 | =head2 $c->view($name) |
413 | |
414 | Gets a L<Catalyst::View> instance by name. |
415 | |
416 | $c->view('Foo')->do_stuff; |
417 | |
418 | Any extra arguments are directly passed to ACCEPT_CONTEXT. |
419 | |
420 | If the name is omitted, it will look for |
421 | - a view object in $c->stash->{current_view_instance}, then |
422 | - a view name in $c->stash->{current_view}, then |
423 | - a config setting 'default_view', or |
424 | - check if there is only one view, and return it if that's the case. |
425 | |
426 | If you want to search for views, pass in a regexp as the argument. |
427 | |
428 | # find all views that start with Foo |
429 | my @foo_views = $c->view(qr{^Foo}); |
430 | |
431 | =cut |
432 | |
433 | sub view { |
434 | my ( $c, $name, @args ) = @_; |
435 | |
436 | my $appclass = ref($c) || $c; |
437 | if( $name ) { |
438 | my @result = $c->_comp_search_prefixes( $name, qw/View V/ ); |
439 | return map { $c->_filter_component( $_, @args ) } @result if ref $name; |
440 | return $c->_filter_component( $result[ 0 ], @args ); |
441 | } |
442 | |
443 | if (ref $c) { |
444 | return $c->stash->{current_view_instance} |
445 | if $c->stash->{current_view_instance}; |
446 | return $c->view( $c->stash->{current_view} ) |
447 | if $c->stash->{current_view}; |
448 | } |
449 | return $c->view( $appclass->config->{default_view} ) |
450 | if $appclass->config->{default_view}; |
451 | |
452 | my( $comp, $rest ) = $c->_comp_search_prefixes( undef, qw/View V/); |
453 | |
454 | if( $rest ) { |
455 | $c->log->warn( 'Calling $c->view() will return a random view unless you specify one of:' ); |
456 | $c->log->warn( '* $c->config(default_view => "the name of the default view to use")' ); |
457 | $c->log->warn( '* $c->stash->{current_view} # the name of the view to use for this request' ); |
458 | $c->log->warn( '* $c->stash->{current_view_instance} # the instance of the view to use for this request' ); |
459 | $c->log->warn( 'NB: in version 5.81, the "random" behavior will not work at all.' ); |
460 | } |
461 | |
462 | return $c->_filter_component( $comp ); |
463 | } |
464 | |
465 | =head2 UTILITY METHODS |
466 | |
467 | =head2 $c->uri_for( $path?, @args?, \%query_values? ) |
468 | |
469 | =head2 $c->uri_for( $action, \@captures?, @args?, \%query_values? ) |
470 | |
471 | Constructs an absolute L<URI> object based on the application root, the |
472 | provided path, and the additional arguments and query parameters provided. |
473 | When used as a string, provides a textual URI. |
474 | |
475 | If no arguments are provided, the URI for the current action is returned. |
476 | To return the current action and also provide @args, use |
477 | C<< $c->uri_for( $c->action, @args ) >>. |
478 | |
479 | If the first argument is a string, it is taken as a public URI path relative |
480 | to C<< $c->namespace >> (if it doesn't begin with a forward slash) or |
481 | relative to the application root (if it does). It is then merged with |
482 | C<< $c->request->base >>; any C<@args> are appended as additional path |
483 | components; and any C<%query_values> are appended as C<?foo=bar> parameters. |
484 | |
485 | If the first argument is a L<Catalyst::Action> it represents an action which |
486 | will have its path resolved using C<< $c->dispatcher->uri_for_action >>. The |
487 | optional C<\@captures> argument (an arrayref) allows passing the captured |
488 | variables that are needed to fill in the paths of Chained and Regex actions; |
489 | once the path is resolved, C<uri_for> continues as though a path was |
490 | provided, appending any arguments or parameters and creating an absolute |
491 | URI. |
492 | |
493 | The captures for the current request can be found in |
494 | C<< $c->request->captures >>, and actions can be resolved using |
495 | C<< Catalyst::Controller->action_for($name) >>. If you have a private action |
496 | path, use C<< $c->uri_for_action >> instead. |
497 | |
498 | # Equivalent to $c->req->uri |
499 | $c->uri_for($c->action, $c->req->captures, |
500 | @{ $c->req->args }, $c->req->params); |
501 | |
502 | # For the Foo action in the Bar controller |
503 | $c->uri_for($c->controller('Bar')->action_for('Foo')); |
504 | |
505 | # Path to a static resource |
506 | $c->uri_for('/static/images/logo.png'); |
507 | |
508 | =cut |
509 | |
510 | sub uri_for { |
511 | my ( $c, $path, @args ) = @_; |
512 | |
513 | if (blessed($path) && $path->isa('Catalyst::Controller')) { |
514 | $path = $path->path_prefix; |
515 | $path =~ s{/+\z}{}; |
516 | $path .= '/'; |
517 | } |
518 | |
519 | if ( blessed($path) ) { # action object |
520 | my $captures = [ map { s|/|%2F|; $_; } |
521 | ( scalar @args && ref $args[0] eq 'ARRAY' |
522 | ? @{ shift(@args) } |
523 | : ()) ]; |
524 | my $action = $path; |
525 | $path = $c->dispatcher->uri_for_action($action, $captures); |
526 | if (not defined $path) { |
527 | $c->log->debug(qq/Can't find uri_for action '$action' @$captures/) |
528 | if $c->debug; |
529 | return undef; |
530 | } |
531 | $path = '/' if $path eq ''; |
532 | } |
533 | |
534 | undef($path) if (defined $path && $path eq ''); |
535 | |
536 | my $params = |
537 | ( scalar @args && ref $args[$#args] eq 'HASH' ? pop @args : {} ); |
538 | |
539 | carp "uri_for called with undef argument" if grep { ! defined $_ } @args; |
540 | s/([^$URI::uric])/$URI::Escape::escapes{$1}/go for @args; |
541 | s|/|%2F| for @args; |
542 | |
543 | unshift(@args, $path); |
544 | |
545 | unless (defined $path && $path =~ s!^/!!) { # in-place strip |
546 | my $namespace = $c->namespace; |
547 | if (defined $path) { # cheesy hack to handle path '../foo' |
548 | $namespace =~ s{(?:^|/)[^/]+$}{} while $args[0] =~ s{^\.\./}{}; |
549 | } |
550 | unshift(@args, $namespace || ''); |
551 | } |
552 | |
553 | # join args with '/', or a blank string |
554 | my $args = join('/', grep { defined($_) } @args); |
555 | $args =~ s/\?/%3F/g; # STUPID STUPID SPECIAL CASE |
556 | $args =~ s!^/+!!; |
557 | my $base = $c->req->base; |
558 | my $class = ref($base); |
559 | $base =~ s{(?<!/)$}{/}; |
560 | |
561 | my $query = ''; |
562 | |
563 | if (my @keys = keys %$params) { |
564 | # somewhat lifted from URI::_query's query_form |
565 | $query = '?'.join('&', map { |
566 | my $val = $params->{$_}; |
567 | s/([;\/?:@&=+,\$\[\]%])/$URI::Escape::escapes{$1}/go; |
568 | s/ /+/g; |
569 | my $key = $_; |
570 | $val = '' unless defined $val; |
571 | (map { |
572 | my $param = "$_"; |
573 | utf8::encode( $param ) if utf8::is_utf8($param); |
574 | # using the URI::Escape pattern here so utf8 chars survive |
575 | $param =~ s/([^A-Za-z0-9\-_.!~*'() ])/$URI::Escape::escapes{$1}/go; |
576 | $param =~ s/ /+/g; |
577 | "${key}=$param"; } ( ref $val eq 'ARRAY' ? @$val : $val )); |
578 | } @keys); |
579 | } |
580 | |
581 | my $res = bless(\"${base}${args}${query}", $class); |
582 | $res; |
583 | } |
584 | |
585 | =head2 $c->uri_for_action( $path, \@captures?, @args?, \%query_values? ) |
586 | |
587 | =head2 $c->uri_for_action( $action, \@captures?, @args?, \%query_values? ) |
588 | |
589 | =over |
590 | |
591 | =item $path |
592 | |
593 | A private path to the Catalyst action you want to create a URI for. |
594 | |
595 | This is a shortcut for calling C<< $c->dispatcher->get_action_by_path($path) |
596 | >> and passing the resulting C<$action> and the remaining arguments to C<< |
597 | $c->uri_for >>. |
598 | |
599 | You can also pass in a Catalyst::Action object, in which case it is passed to |
600 | C<< $c->uri_for >>. |
601 | |
602 | =back |
603 | |
604 | =cut |
605 | |
606 | sub uri_for_action { |
607 | my ( $c, $path, @args ) = @_; |
608 | my $action = blessed($path) |
609 | ? $path |
610 | : $c->dispatcher->get_action_by_path($path); |
611 | unless (defined $action) { |
612 | croak "Can't find action for path '$path'"; |
613 | } |
614 | return $c->uri_for( $action, @args ); |
615 | } |
616 | |
617 | =head1 INTERNAL METHODS |
618 | |
619 | =head2 $c->counter |
620 | |
621 | Returns a hashref containing coderefs and execution counts (needed for |
622 | deep recursion detection). |
623 | |
624 | =head2 $c->depth |
625 | |
626 | Returns the number of actions on the current internal execution stack. |
627 | |
628 | =head2 $c->dispatch |
629 | |
630 | Dispatches a request to actions. |
631 | |
632 | =cut |
633 | |
634 | sub dispatch { my $c = shift; $c->dispatcher->dispatch( $c, @_ ) } |
635 | |
636 | =head2 $c->dump_these |
637 | |
638 | Returns a list of 2-element array references (name, structure) pairs |
639 | that will be dumped on the error page in debug mode. |
640 | |
641 | =cut |
642 | |
643 | sub dump_these { |
644 | my $c = shift; |
645 | [ Request => $c->req ], |
646 | [ Response => $c->res ], |
647 | [ Stash => $c->stash ], |
648 | [ Config => $c->config ]; |
649 | } |
650 | |
651 | =head2 $c->execute( $class, $coderef ) |
652 | |
653 | Execute a coderef in given class and catch exceptions. Errors are available |
654 | via $c->error. |
655 | |
656 | =cut |
657 | |
658 | sub execute { |
659 | my ( $c, $class, $code ) = @_; |
660 | $class = $c->component($class) || $class; |
661 | $c->state(0); |
662 | |
663 | if ( $c->depth >= $RECURSION ) { |
664 | my $action = $code->reverse(); |
665 | $action = "/$action" unless $action =~ /->/; |
666 | my $error = qq/Deep recursion detected calling "${action}"/; |
667 | $c->log->error($error); |
668 | $c->error($error); |
669 | $c->state(0); |
670 | return $c->state; |
671 | } |
672 | |
673 | my $stats_info = $c->_stats_start_execute( $code ) if $c->use_stats; |
674 | |
675 | push( @{ $c->stack }, $code ); |
676 | |
677 | no warnings 'recursion'; |
678 | eval { $c->state( $code->execute( $class, $c, @{ $c->req->args } ) || 0 ) }; |
679 | |
680 | $c->_stats_finish_execute( $stats_info ) if $c->use_stats and $stats_info; |
681 | |
682 | my $last = pop( @{ $c->stack } ); |
683 | |
684 | if ( my $error = $@ ) { |
685 | if ( blessed($error) and $error->isa('Catalyst::Exception::Detach') ) { |
686 | $error->rethrow if $c->depth > 1; |
687 | } |
688 | elsif ( blessed($error) and $error->isa('Catalyst::Exception::Go') ) { |
689 | $error->rethrow if $c->depth > 0; |
690 | } |
691 | else { |
692 | unless ( ref $error ) { |
693 | no warnings 'uninitialized'; |
694 | chomp $error; |
695 | my $class = $last->class; |
696 | my $name = $last->name; |
697 | $error = qq/Caught exception in $class->$name "$error"/; |
698 | } |
699 | $c->error($error); |
700 | $c->state(0); |
701 | } |
702 | } |
703 | return $c->state; |
704 | } |
705 | |
706 | sub _stats_start_execute { |
707 | my ( $c, $code ) = @_; |
c20db8ca |
708 | return if ( ( $code->name =~ /^_.*/ ) |
1a4f82a0 |
709 | && ( !$c->config->{show_internal_actions} ) ); |
c20db8ca |
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 | |