1 package Catalyst::Request;
3 use IO::Socket qw[AF_INET inet_aton];
13 use namespace::clean -except => 'meta';
15 with 'MooseX::Emulate::Class::Accessor::Fast';
17 has env => (is => 'ro', writer => '_set_env');
19 has _read_position => ( is => 'rw', default => 0 );
20 has _read_length => ( is => 'ro',
23 $self->header('Content-Length') || 0;
28 has action => (is => 'rw');
29 has address => (is => 'rw');
30 has arguments => (is => 'rw', default => sub { [] });
31 has cookies => (is => 'rw', default => sub { {} });
32 has query_keywords => (is => 'rw');
33 has match => (is => 'rw');
34 has method => (is => 'rw');
35 has protocol => (is => 'rw');
36 has query_parameters => (is => 'rw', default => sub { {} });
37 has secure => (is => 'rw', default => 0);
38 has captures => (is => 'rw', default => sub { [] });
39 has uri => (is => 'rw', predicate => 'has_uri');
40 has remote_user => (is => 'rw');
43 isa => 'HTTP::Headers',
44 handles => [qw(content_encoding content_length content_type header referer user_agent)],
45 default => sub { HTTP::Headers->new() },
53 handles => ['read'], # XXX FIXME!
54 clearer => '_clear_context',
59 return $self->env->{'psgi.input'}->read(@_);
62 has body_parameters => (
66 default => sub { {} },
72 default => sub { {} },
79 default => sub { {} },
83 # - Can we lose the before modifiers which just call prepare_body ?
84 # they are wasteful, slow us down and feel cluttery.
86 # Can we make _body an attribute, have the rest of
87 # these lazy build from there and kill all the direct hash access
88 # in Catalyst.pm and Engine.pm?
92 my $context = $self->_context || return;
93 $context->prepare_body;
94 } for qw/parameters body_parameters/;
96 around parameters => sub {
97 my ($orig, $self, $params) = @_;
100 $self->_context->log->warn(
101 "Attempt to retrieve '$params' with req->params(), " .
102 "you probably meant to call req->param('$params')"
106 return $self->$orig($params);
117 return $self->path if $self->has_uri;
122 is => 'rw', clearer => '_clear_body', predicate => '_has_body',
124 # Eugh, ugly. Should just be able to rename accessor methods to 'body'
125 # and provide a custom reader..
128 $self->_context->prepare_body();
129 croak 'body is a reader' if scalar @_;
130 return blessed $self->_body ? $self->_body->body : $self->_body;
139 gethostbyaddr( inet_aton( $self->address ), AF_INET ) || $self->address
143 has _path => ( is => 'rw', predicate => '_has_path', clearer => '_clear_path' );
145 # XXX: Deprecated in docs ages ago (2006), deprecated with warning in 5.8000 due
146 # to confusion between Engines and Plugin::Authentication. Remove in 5.8100?
147 has user => (is => 'rw');
149 sub args { shift->arguments(@_) }
150 sub body_params { shift->body_parameters(@_) }
151 sub input { shift->body(@_) }
152 sub params { shift->parameters(@_) }
153 sub query_params { shift->query_parameters(@_) }
154 sub path_info { shift->path(@_) }
155 sub snippets { shift->captures(@_) }
157 =for stopwords param params
161 Catalyst::Request - provides information about the current client request
172 $req->body_parameters;
173 $req->content_encoding;
174 $req->content_length;
182 $req->query_keywords;
190 $req->query_parameters;
194 $req->captures; # previously knows as snippets
201 See also L<Catalyst>, L<Catalyst::Request::Upload>.
205 This is the Catalyst Request class, which provides an interface to data for the
206 current client request. The request object is prepared by L<Catalyst::Engine>,
207 thus hiding the details of the particular engine implementation.
213 [DEPRECATED] Returns the name of the requested action.
216 Use C<< $c->action >> instead (which returns a
217 L<Catalyst::Action|Catalyst::Action> object).
221 Returns the IP address of the client.
223 =head2 $req->arguments
225 Returns a reference to an array containing the arguments.
227 print $c->request->arguments->[0];
229 For example, if your action was
231 package MyApp::Controller::Foo;
237 and the URI for the request was C<http://.../foo/moose/bah>, the string C<bah>
238 would be the first and only argument.
240 Arguments get automatically URI-unescaped for you.
244 Shortcut for L</arguments>.
248 Contains the URI base. This will always have a trailing slash. Note that the
249 URI scheme (e.g., http vs. https) must be determined through heuristics;
250 depending on your server configuration, it may be incorrect. See $req->secure
253 If your application was queried with the URI
254 C<http://localhost:3000/some/path> then C<base> is C<http://localhost:3000/>.
258 Returns the message body of the request, as returned by L<HTTP::Body>: a string,
259 unless Content-Type is C<application/x-www-form-urlencoded>, C<text/xml>, or
260 C<multipart/form-data>, in which case a L<File::Temp> object is returned.
262 =head2 $req->body_parameters
264 Returns a reference to a hash containing body (POST) parameters. Values can
265 be either a scalar or an arrayref containing scalars.
267 print $c->request->body_parameters->{field};
268 print $c->request->body_parameters->{field}->[0];
270 These are the parameters from the POST part of the request, if any.
272 =head2 $req->body_params
274 Shortcut for body_parameters.
276 =head2 $req->content_encoding
278 Shortcut for $req->headers->content_encoding.
280 =head2 $req->content_length
282 Shortcut for $req->headers->content_length.
284 =head2 $req->content_type
286 Shortcut for $req->headers->content_type.
290 A convenient method to access $req->cookies.
292 $cookie = $c->request->cookie('name');
293 @cookies = $c->request->cookie;
301 return keys %{ $self->cookies };
308 unless ( exists $self->cookies->{$name} ) {
312 return $self->cookies->{$name};
318 Returns a reference to a hash containing the cookies.
320 print $c->request->cookies->{mycookie}->value;
322 The cookies in the hash are indexed by name, and the values are L<CGI::Simple::Cookie>
327 Shortcut for $req->headers->header.
331 Returns an L<HTTP::Headers> object containing the headers for the current request.
333 print $c->request->headers->header('X-Catalyst');
335 =head2 $req->hostname
337 Returns the hostname of the client. Use C<< $req->uri->host >> to get the hostname of the server.
341 Alias for $req->body.
343 =head2 $req->query_keywords
345 Contains the keywords portion of a query string, when no '=' signs are
348 http://localhost/path?some+keywords
350 $c->request->query_keywords will contain 'some keywords'
354 This contains the matching part of a Regex action. Otherwise
355 it returns the same as 'action', except for default actions,
356 which return an empty string.
360 Contains the request method (C<GET>, C<POST>, C<HEAD>, etc).
364 Returns GET and POST parameters with a CGI.pm-compatible param method. This
365 is an alternative method for accessing parameters in $c->req->parameters.
367 $value = $c->request->param( 'foo' );
368 @values = $c->request->param( 'foo' );
369 @params = $c->request->param;
371 Like L<CGI>, and B<unlike> earlier versions of Catalyst, passing multiple
372 arguments to this method, like this:
374 $c->request->param( 'foo', 'bar', 'gorch', 'quxx' );
376 will set the parameter C<foo> to the multiple values C<bar>, C<gorch> and
377 C<quxx>. Previously this would have added C<bar> as another value to C<foo>
378 (creating it if it didn't exist before), and C<quxx> as another value for
381 B<NOTE> this is considered a legacy interface and care should be taken when
382 using it. C<< scalar $c->req->param( 'foo' ) >> will return only the first
383 C<foo> param even if multiple are present; C<< $c->req->param( 'foo' ) >> will
384 return a list of as many are present, which can have unexpected consequences
385 when writing code of the form:
389 baz => $c->req->param( 'baz' ),
392 If multiple C<baz> parameters are provided this code might corrupt data or
393 cause a hash initialization error. For a more straightforward interface see
394 C<< $c->req->parameters >>.
402 return keys %{ $self->parameters };
409 unless ( exists $self->parameters->{$param} ) {
410 return wantarray ? () : undef;
413 if ( ref $self->parameters->{$param} eq 'ARRAY' ) {
415 ? @{ $self->parameters->{$param} }
416 : $self->parameters->{$param}->[0];
420 ? ( $self->parameters->{$param} )
421 : $self->parameters->{$param};
426 $self->parameters->{$field} = [@_];
430 =head2 $req->parameters
432 Returns a reference to a hash containing GET and POST parameters. Values can
433 be either a scalar or an arrayref containing scalars.
435 print $c->request->parameters->{field};
436 print $c->request->parameters->{field}->[0];
438 This is the combination of C<query_parameters> and C<body_parameters>.
442 Shortcut for $req->parameters.
446 Returns the path, i.e. the part of the URI after $req->base, for the current request.
448 http://localhost/path/foo
450 $c->request->path will contain 'path/foo'
452 =head2 $req->path_info
454 Alias for path, added for compatibility with L<CGI>.
459 my ( $self, @params ) = @_;
462 $self->uri->path(@params);
465 elsif ( $self->_has_path ) {
469 my $path = $self->uri->path;
470 my $location = $self->base->path;
471 $path =~ s/^(\Q$location\E)?//;
479 =head2 $req->protocol
481 Returns the protocol (HTTP/1.0 or HTTP/1.1) used for the current request.
483 =head2 $req->query_parameters
485 =head2 $req->query_params
487 Returns a reference to a hash containing query string (GET) parameters. Values can
488 be either a scalar or an arrayref containing scalars.
490 print $c->request->query_parameters->{field};
491 print $c->request->query_parameters->{field}->[0];
493 =head2 $req->read( [$maxlength] )
495 Reads a chunk of data from the request body. This method is intended to be
496 used in a while loop, reading $maxlength bytes on every call. $maxlength
497 defaults to the size of the request if not specified.
499 =head2 $req->read_chunk(\$buff, $max)
503 You have to set MyApp->config(parse_on_demand => 1) to use this directly.
507 Shortcut for $req->headers->referer. Returns the referring page.
511 Returns true or false, indicating whether the connection is secure
512 (https). Note that the URI scheme (e.g., http vs. https) must be determined
513 through heuristics, and therefore the reliability of $req->secure will depend
514 on your server configuration. If you are serving secure pages on the standard
515 SSL port (443) and/or setting the HTTPS environment variable, $req->secure
518 =head2 $req->captures
520 Returns a reference to an array containing captured args from chained
521 actions or regex captures.
523 my @captures = @{ $c->request->captures };
525 =head2 $req->snippets
527 C<captures> used to be called snippets. This is still available for backwards
528 compatibility, but is considered deprecated.
532 A convenient method to access $req->uploads.
534 $upload = $c->request->upload('field');
535 @uploads = $c->request->upload('field');
536 @fields = $c->request->upload;
538 for my $upload ( $c->request->upload('field') ) {
539 print $upload->filename;
548 return keys %{ $self->uploads };
555 unless ( exists $self->uploads->{$upload} ) {
556 return wantarray ? () : undef;
559 if ( ref $self->uploads->{$upload} eq 'ARRAY' ) {
561 ? @{ $self->uploads->{$upload} }
562 : $self->uploads->{$upload}->[0];
566 ? ( $self->uploads->{$upload} )
567 : $self->uploads->{$upload};
573 while ( my ( $field, $upload ) = splice( @_, 0, 2 ) ) {
575 if ( exists $self->uploads->{$field} ) {
576 for ( $self->uploads->{$field} ) {
577 $_ = [$_] unless ref($_) eq "ARRAY";
578 push( @$_, $upload );
582 $self->uploads->{$field} = $upload;
590 Returns a reference to a hash containing uploads. Values can be either a
591 L<Catalyst::Request::Upload> object, or an arrayref of
592 L<Catalyst::Request::Upload> objects.
594 my $upload = $c->request->uploads->{field};
595 my $upload = $c->request->uploads->{field}->[0];
599 Returns a L<URI> object for the current request. Stringifies to the URI text.
601 =head2 $req->mangle_params( { key => 'value' }, $appendmode);
603 Returns a hashref of parameters stemming from the current request's params,
604 plus the ones supplied. Keys for which no current param exists will be
605 added, keys with undefined values will be removed and keys with existing
606 params will be replaced. Note that you can supply a true value as the final
607 argument to change behavior with regards to existing parameters, appending
608 values rather than replacing them.
612 # URI query params foo=1
613 my $hashref = $req->mangle_params({ foo => 2 });
614 # Result is query params of foo=2
618 # URI query params foo=1
619 my $hashref = $req->mangle_params({ foo => 2 }, 1);
620 # Result is query params of foo=1&foo=2
622 This is the code behind C<uri_with>.
627 my ($self, $args, $append) = @_;
629 carp('No arguments passed to mangle_params()') unless $args;
631 foreach my $value ( values %$args ) {
632 next unless defined $value;
633 for ( ref $value eq 'ARRAY' ? @$value : $value ) {
635 utf8::encode( $_ ) if utf8::is_utf8($_);
639 my %params = %{ $self->uri->query_form_hash };
640 foreach my $key (keys %{ $args }) {
641 my $val = $args->{$key};
644 if($append && exists($params{$key})) {
646 # This little bit of heaven handles appending a new value onto
647 # an existing one regardless if the existing value is an array
648 # or not, and regardless if the new value is an array or not
650 ref($params{$key}) eq 'ARRAY' ? @{ $params{$key} } : $params{$key},
651 ref($val) eq 'ARRAY' ? @{ $val } : $val
655 $params{$key} = $val;
659 # If the param wasn't defined then we delete it.
660 delete($params{$key});
668 =head2 $req->uri_with( { key => 'value' } );
670 Returns a rewritten URI object for the current request. Key/value pairs
671 passed in will override existing parameters. You can remove an existing
672 parameter by passing in an undef value. Unmodified pairs will be
675 You may also pass an optional second parameter that puts C<uri_with> into
678 $req->uri_with( { key => 'value' }, { mode => 'append' } );
680 See C<mangle_params> for an explanation of this behavior.
685 my( $self, $args, $behavior) = @_;
687 carp( 'No arguments passed to uri_with()' ) unless $args;
690 if((ref($behavior) eq 'HASH') && defined($behavior->{mode}) && ($behavior->{mode} eq 'append')) {
694 my $params = $self->mangle_params($args, $append);
696 my $uri = $self->uri->clone;
697 $uri->query_form($params);
702 =head2 $req->remote_user
704 Returns the value of the C<REMOTE_USER> environment variable.
706 =head2 $req->user_agent
708 Shortcut to $req->headers->user_agent. Returns the user agent (browser)
717 Catalyst Contributors, see Catalyst.pm
721 This library is free software. You can redistribute it and/or modify
722 it under the same terms as Perl itself.
726 __PACKAGE__->meta->make_immutable;