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() },
54 clearer => '_clear_context',
57 has body_parameters => (
61 default => sub { {} },
67 default => sub { {} },
74 default => sub { {} },
78 # - Can we lose the before modifiers which just call prepare_body ?
79 # they are wasteful, slow us down and feel cluttery.
81 # Can we make _body an attribute, have the rest of
82 # these lazy build from there and kill all the direct hash access
83 # in Catalyst.pm and Engine.pm?
87 my $context = $self->_context || return;
88 $context->prepare_body;
89 } for qw/parameters body_parameters/;
91 around parameters => sub {
92 my ($orig, $self, $params) = @_;
95 $self->_context->log->warn(
96 "Attempt to retrieve '$params' with req->params(), " .
97 "you probably meant to call req->param('$params')"
101 return $self->$orig($params);
112 return $self->path if $self->has_uri;
117 is => 'rw', clearer => '_clear_body', predicate => '_has_body',
119 # Eugh, ugly. Should just be able to rename accessor methods to 'body'
120 # and provide a custom reader..
123 $self->_context->prepare_body();
124 croak 'body is a reader' if scalar @_;
125 return blessed $self->_body ? $self->_body->body : $self->_body;
134 gethostbyaddr( inet_aton( $self->address ), AF_INET ) || $self->address
138 has _path => ( is => 'rw', predicate => '_has_path', clearer => '_clear_path' );
140 # XXX: Deprecated in docs ages ago (2006), deprecated with warning in 5.8000 due
141 # to confusion between Engines and Plugin::Authentication. Remove in 5.8100?
142 has user => (is => 'rw');
144 sub args { shift->arguments(@_) }
145 sub body_params { shift->body_parameters(@_) }
146 sub input { shift->body(@_) }
147 sub params { shift->parameters(@_) }
148 sub query_params { shift->query_parameters(@_) }
149 sub path_info { shift->path(@_) }
150 sub snippets { shift->captures(@_) }
152 =for stopwords param params
156 Catalyst::Request - provides information about the current client request
167 $req->body_parameters;
168 $req->content_encoding;
169 $req->content_length;
177 $req->query_keywords;
185 $req->query_parameters;
189 $req->captures; # previously knows as snippets
196 See also L<Catalyst>, L<Catalyst::Request::Upload>.
200 This is the Catalyst Request class, which provides an interface to data for the
201 current client request. The request object is prepared by L<Catalyst::Engine>,
202 thus hiding the details of the particular engine implementation.
208 [DEPRECATED] Returns the name of the requested action.
211 Use C<< $c->action >> instead (which returns a
212 L<Catalyst::Action|Catalyst::Action> object).
216 Returns the IP address of the client.
218 =head2 $req->arguments
220 Returns a reference to an array containing the arguments.
222 print $c->request->arguments->[0];
224 For example, if your action was
226 package MyApp::Controller::Foo;
232 and the URI for the request was C<http://.../foo/moose/bah>, the string C<bah>
233 would be the first and only argument.
235 Arguments get automatically URI-unescaped for you.
239 Shortcut for L</arguments>.
243 Contains the URI base. This will always have a trailing slash. Note that the
244 URI scheme (e.g., http vs. https) must be determined through heuristics;
245 depending on your server configuration, it may be incorrect. See $req->secure
248 If your application was queried with the URI
249 C<http://localhost:3000/some/path> then C<base> is C<http://localhost:3000/>.
253 Returns the message body of the request, as returned by L<HTTP::Body>: a string,
254 unless Content-Type is C<application/x-www-form-urlencoded>, C<text/xml>, or
255 C<multipart/form-data>, in which case a L<File::Temp> object is returned.
257 =head2 $req->body_parameters
259 Returns a reference to a hash containing body (POST) parameters. Values can
260 be either a scalar or an arrayref containing scalars.
262 print $c->request->body_parameters->{field};
263 print $c->request->body_parameters->{field}->[0];
265 These are the parameters from the POST part of the request, if any.
267 =head2 $req->body_params
269 Shortcut for body_parameters.
271 =head2 $req->content_encoding
273 Shortcut for $req->headers->content_encoding.
275 =head2 $req->content_length
277 Shortcut for $req->headers->content_length.
279 =head2 $req->content_type
281 Shortcut for $req->headers->content_type.
285 A convenient method to access $req->cookies.
287 $cookie = $c->request->cookie('name');
288 @cookies = $c->request->cookie;
296 return keys %{ $self->cookies };
303 unless ( exists $self->cookies->{$name} ) {
307 return $self->cookies->{$name};
313 Returns a reference to a hash containing the cookies.
315 print $c->request->cookies->{mycookie}->value;
317 The cookies in the hash are indexed by name, and the values are L<CGI::Simple::Cookie>
322 Shortcut for $req->headers->header.
326 Returns an L<HTTP::Headers> object containing the headers for the current request.
328 print $c->request->headers->header('X-Catalyst');
330 =head2 $req->hostname
332 Returns the hostname of the client. Use C<< $req->uri->host >> to get the hostname of the server.
336 Alias for $req->body.
338 =head2 $req->query_keywords
340 Contains the keywords portion of a query string, when no '=' signs are
343 http://localhost/path?some+keywords
345 $c->request->query_keywords will contain 'some keywords'
349 This contains the matching part of a Regex action. Otherwise
350 it returns the same as 'action', except for default actions,
351 which return an empty string.
355 Contains the request method (C<GET>, C<POST>, C<HEAD>, etc).
359 Returns GET and POST parameters with a CGI.pm-compatible param method. This
360 is an alternative method for accessing parameters in $c->req->parameters.
362 $value = $c->request->param( 'foo' );
363 @values = $c->request->param( 'foo' );
364 @params = $c->request->param;
366 Like L<CGI>, and B<unlike> earlier versions of Catalyst, passing multiple
367 arguments to this method, like this:
369 $c->request->param( 'foo', 'bar', 'gorch', 'quxx' );
371 will set the parameter C<foo> to the multiple values C<bar>, C<gorch> and
372 C<quxx>. Previously this would have added C<bar> as another value to C<foo>
373 (creating it if it didn't exist before), and C<quxx> as another value for
376 B<NOTE> this is considered a legacy interface and care should be taken when
377 using it. C<< scalar $c->req->param( 'foo' ) >> will return only the first
378 C<foo> param even if multiple are present; C<< $c->req->param( 'foo' ) >> will
379 return a list of as many are present, which can have unexpected consequences
380 when writing code of the form:
384 baz => $c->req->param( 'baz' ),
387 If multiple C<baz> parameters are provided this code might corrupt data or
388 cause a hash initialization error. For a more straightforward interface see
389 C<< $c->req->parameters >>.
397 return keys %{ $self->parameters };
404 unless ( exists $self->parameters->{$param} ) {
405 return wantarray ? () : undef;
408 if ( ref $self->parameters->{$param} eq 'ARRAY' ) {
410 ? @{ $self->parameters->{$param} }
411 : $self->parameters->{$param}->[0];
415 ? ( $self->parameters->{$param} )
416 : $self->parameters->{$param};
421 $self->parameters->{$field} = [@_];
425 =head2 $req->parameters
427 Returns a reference to a hash containing GET and POST parameters. Values can
428 be either a scalar or an arrayref containing scalars.
430 print $c->request->parameters->{field};
431 print $c->request->parameters->{field}->[0];
433 This is the combination of C<query_parameters> and C<body_parameters>.
437 Shortcut for $req->parameters.
441 Returns the path, i.e. the part of the URI after $req->base, for the current request.
443 http://localhost/path/foo
445 $c->request->path will contain 'path/foo'
447 =head2 $req->path_info
449 Alias for path, added for compatibility with L<CGI>.
454 my ( $self, @params ) = @_;
457 $self->uri->path(@params);
460 elsif ( $self->_has_path ) {
464 my $path = $self->uri->path;
465 my $location = $self->base->path;
466 $path =~ s/^(\Q$location\E)?//;
474 =head2 $req->protocol
476 Returns the protocol (HTTP/1.0 or HTTP/1.1) used for the current request.
478 =head2 $req->query_parameters
480 =head2 $req->query_params
482 Returns a reference to a hash containing query string (GET) parameters. Values can
483 be either a scalar or an arrayref containing scalars.
485 print $c->request->query_parameters->{field};
486 print $c->request->query_parameters->{field}->[0];
488 =head2 $req->read( [$maxlength] )
490 Reads a chunk of data from the request body. This method is intended to be
491 used in a while loop, reading $maxlength bytes on every call. $maxlength
492 defaults to the size of the request if not specified.
494 You have to set MyApp->config(parse_on_demand => 1) to use this directly.
498 Shortcut for $req->headers->referer. Returns the referring page.
502 Returns true or false, indicating whether the connection is secure
503 (https). Note that the URI scheme (e.g., http vs. https) must be determined
504 through heuristics, and therefore the reliability of $req->secure will depend
505 on your server configuration. If you are serving secure pages on the standard
506 SSL port (443) and/or setting the HTTPS environment variable, $req->secure
509 =head2 $req->captures
511 Returns a reference to an array containing captured args from chained
512 actions or regex captures.
514 my @captures = @{ $c->request->captures };
516 =head2 $req->snippets
518 C<captures> used to be called snippets. This is still available for backwards
519 compatibility, but is considered deprecated.
523 A convenient method to access $req->uploads.
525 $upload = $c->request->upload('field');
526 @uploads = $c->request->upload('field');
527 @fields = $c->request->upload;
529 for my $upload ( $c->request->upload('field') ) {
530 print $upload->filename;
539 return keys %{ $self->uploads };
546 unless ( exists $self->uploads->{$upload} ) {
547 return wantarray ? () : undef;
550 if ( ref $self->uploads->{$upload} eq 'ARRAY' ) {
552 ? @{ $self->uploads->{$upload} }
553 : $self->uploads->{$upload}->[0];
557 ? ( $self->uploads->{$upload} )
558 : $self->uploads->{$upload};
564 while ( my ( $field, $upload ) = splice( @_, 0, 2 ) ) {
566 if ( exists $self->uploads->{$field} ) {
567 for ( $self->uploads->{$field} ) {
568 $_ = [$_] unless ref($_) eq "ARRAY";
569 push( @$_, $upload );
573 $self->uploads->{$field} = $upload;
581 Returns a reference to a hash containing uploads. Values can be either a
582 L<Catalyst::Request::Upload> object, or an arrayref of
583 L<Catalyst::Request::Upload> objects.
585 my $upload = $c->request->uploads->{field};
586 my $upload = $c->request->uploads->{field}->[0];
590 Returns a L<URI> object for the current request. Stringifies to the URI text.
592 =head2 $req->mangle_params( { key => 'value' }, $appendmode);
594 Returns a hashref of parameters stemming from the current request's params,
595 plus the ones supplied. Keys for which no current param exists will be
596 added, keys with undefined values will be removed and keys with existing
597 params will be replaced. Note that you can supply a true value as the final
598 argument to change behavior with regards to existing parameters, appending
599 values rather than replacing them.
603 # URI query params foo=1
604 my $hashref = $req->mangle_params({ foo => 2 });
605 # Result is query params of foo=2
609 # URI query params foo=1
610 my $hashref = $req->mangle_params({ foo => 2 }, 1);
611 # Result is query params of foo=1&foo=2
613 This is the code behind C<uri_with>.
618 my ($self, $args, $append) = @_;
620 carp('No arguments passed to mangle_params()') unless $args;
622 foreach my $value ( values %$args ) {
623 next unless defined $value;
624 for ( ref $value eq 'ARRAY' ? @$value : $value ) {
626 utf8::encode( $_ ) if utf8::is_utf8($_);
630 my %params = %{ $self->uri->query_form_hash };
631 foreach my $key (keys %{ $args }) {
632 my $val = $args->{$key};
635 if($append && exists($params{$key})) {
637 # This little bit of heaven handles appending a new value onto
638 # an existing one regardless if the existing value is an array
639 # or not, and regardless if the new value is an array or not
641 ref($params{$key}) eq 'ARRAY' ? @{ $params{$key} } : $params{$key},
642 ref($val) eq 'ARRAY' ? @{ $val } : $val
646 $params{$key} = $val;
650 # If the param wasn't defined then we delete it.
651 delete($params{$key});
659 =head2 $req->uri_with( { key => 'value' } );
661 Returns a rewritten URI object for the current request. Key/value pairs
662 passed in will override existing parameters. You can remove an existing
663 parameter by passing in an undef value. Unmodified pairs will be
666 You may also pass an optional second parameter that puts C<uri_with> into
669 $req->uri_with( { key => 'value' }, { mode => 'append' } );
671 See C<mangle_params> for an explanation of this behavior.
676 my( $self, $args, $behavior) = @_;
678 carp( 'No arguments passed to uri_with()' ) unless $args;
681 if((ref($behavior) eq 'HASH') && defined($behavior->{mode}) && ($behavior->{mode} eq 'append')) {
685 my $params = $self->mangle_params($args, $append);
687 my $uri = $self->uri->clone;
688 $uri->query_form($params);
693 =head2 $req->remote_user
695 Returns the value of the C<REMOTE_USER> environment variable.
697 =head2 $req->user_agent
699 Shortcut to $req->headers->user_agent. Returns the user agent (browser)
708 Catalyst Contributors, see Catalyst.pm
712 This library is free software. You can redistribute it and/or modify
713 it under the same terms as Perl itself.
717 __PACKAGE__->meta->make_immutable;