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 action => (is => 'rw');
18 has address => (is => 'rw');
19 has arguments => (is => 'rw', default => sub { [] });
20 has cookies => (is => 'rw', default => sub { {} });
21 has query_keywords => (is => 'rw');
22 has match => (is => 'rw');
23 has method => (is => 'rw');
24 has protocol => (is => 'rw');
25 has query_parameters => (is => 'rw', default => sub { {} });
26 has secure => (is => 'rw', default => 0);
27 has captures => (is => 'rw', default => sub { [] });
28 has uri => (is => 'rw', predicate => 'has_uri');
29 has remote_user => (is => 'rw');
32 isa => 'HTTP::Headers',
33 handles => [qw(content_encoding content_length content_type header referer user_agent)],
34 default => sub { HTTP::Headers->new() },
43 clearer => '_clear_context',
46 has body_parameters => (
50 default => sub { {} },
56 default => sub { {} },
63 default => sub { {} },
67 # - Can we lose the before modifiers which just call prepare_body ?
68 # they are wasteful, slow us down and feel cluttery.
70 # Can we make _body an attribute, have the rest of
71 # these lazy build from there and kill all the direct hash access
72 # in Catalyst.pm and Engine.pm?
76 my $context = $self->_context || return;
77 $context->prepare_body;
78 } for qw/parameters body_parameters/;
80 around parameters => sub {
81 my ($orig, $self, $params) = @_;
84 $self->_context->log->warn(
85 "Attempt to retrieve '$params' with req->params(), " .
86 "you probably meant to call req->param('$params')"
90 return $self->$orig($params);
101 return $self->path if $self->has_uri;
106 is => 'rw', clearer => '_clear_body', predicate => '_has_body',
108 # Eugh, ugly. Should just be able to rename accessor methods to 'body'
109 # and provide a custom reader..
112 $self->_context->prepare_body();
113 croak 'body is a reader' if scalar @_;
114 return blessed $self->_body ? $self->_body->body : $self->_body;
123 gethostbyaddr( inet_aton( $self->address ), AF_INET ) || $self->address
127 has _path => ( is => 'rw', predicate => '_has_path', clearer => '_clear_path' );
129 # XXX: Deprecated in docs ages ago (2006), deprecated with warning in 5.8000 due
130 # to confusion between Engines and Plugin::Authentication. Remove in 5.8100?
131 has user => (is => 'rw');
133 sub args { shift->arguments(@_) }
134 sub body_params { shift->body_parameters(@_) }
135 sub input { shift->body(@_) }
136 sub params { shift->parameters(@_) }
137 sub query_params { shift->query_parameters(@_) }
138 sub path_info { shift->path(@_) }
139 sub snippets { shift->captures(@_) }
143 Catalyst::Request - provides information about the current client request
154 $req->body_parameters;
155 $req->content_encoding;
156 $req->content_length;
164 $req->query_keywords;
172 $req->query_parameters;
176 $req->captures; # previously knows as snippets
183 See also L<Catalyst>, L<Catalyst::Request::Upload>.
187 This is the Catalyst Request class, which provides an interface to data for the
188 current client request. The request object is prepared by L<Catalyst::Engine>,
189 thus hiding the details of the particular engine implementation.
195 [DEPRECATED] Returns the name of the requested action.
198 Use C<< $c->action >> instead (which returns a
199 L<Catalyst::Action|Catalyst::Action> object).
203 Returns the IP address of the client.
205 =head2 $req->arguments
207 Returns a reference to an array containing the arguments.
209 print $c->request->arguments->[0];
211 For example, if your action was
213 package MyApp::Controller::Foo;
219 and the URI for the request was C<http://.../foo/moose/bah>, the string C<bah>
220 would be the first and only argument.
222 Arguments get automatically URI-unescaped for you.
226 Shortcut for L</arguments>.
230 Contains the URI base. This will always have a trailing slash. Note that the
231 URI scheme (eg., http vs. https) must be determined through heuristics;
232 depending on your server configuration, it may be incorrect. See $req->secure
235 If your application was queried with the URI
236 C<http://localhost:3000/some/path> then C<base> is C<http://localhost:3000/>.
240 Returns the message body of the request, as returned by L<HTTP::Body>: a string,
241 unless Content-Type is C<application/x-www-form-urlencoded>, C<text/xml>, or
242 C<multipart/form-data>, in which case a L<File::Temp> object is returned.
244 =head2 $req->body_parameters
246 Returns a reference to a hash containing body (POST) parameters. Values can
247 be either a scalar or an arrayref containing scalars.
249 print $c->request->body_parameters->{field};
250 print $c->request->body_parameters->{field}->[0];
252 These are the parameters from the POST part of the request, if any.
254 =head2 $req->body_params
256 Shortcut for body_parameters.
258 =head2 $req->content_encoding
260 Shortcut for $req->headers->content_encoding.
262 =head2 $req->content_length
264 Shortcut for $req->headers->content_length.
266 =head2 $req->content_type
268 Shortcut for $req->headers->content_type.
272 A convenient method to access $req->cookies.
274 $cookie = $c->request->cookie('name');
275 @cookies = $c->request->cookie;
283 return keys %{ $self->cookies };
290 unless ( exists $self->cookies->{$name} ) {
294 return $self->cookies->{$name};
300 Returns a reference to a hash containing the cookies.
302 print $c->request->cookies->{mycookie}->value;
304 The cookies in the hash are indexed by name, and the values are L<CGI::Simple::Cookie>
309 Shortcut for $req->headers->header.
313 Returns an L<HTTP::Headers> object containing the headers for the current request.
315 print $c->request->headers->header('X-Catalyst');
317 =head2 $req->hostname
319 Returns the hostname of the client.
323 Alias for $req->body.
325 =head2 $req->query_keywords
327 Contains the keywords portion of a query string, when no '=' signs are
330 http://localhost/path?some+keywords
332 $c->request->query_keywords will contain 'some keywords'
336 This contains the matching part of a Regex action. Otherwise
337 it returns the same as 'action', except for default actions,
338 which return an empty string.
342 Contains the request method (C<GET>, C<POST>, C<HEAD>, etc).
346 Returns GET and POST parameters with a CGI.pm-compatible param method. This
347 is an alternative method for accessing parameters in $c->req->parameters.
349 $value = $c->request->param( 'foo' );
350 @values = $c->request->param( 'foo' );
351 @params = $c->request->param;
353 Like L<CGI>, and B<unlike> earlier versions of Catalyst, passing multiple
354 arguments to this method, like this:
356 $c->request->param( 'foo', 'bar', 'gorch', 'quxx' );
358 will set the parameter C<foo> to the multiple values C<bar>, C<gorch> and
359 C<quxx>. Previously this would have added C<bar> as another value to C<foo>
360 (creating it if it didn't exist before), and C<quxx> as another value for
363 B<NOTE> this is considered a legacy interface and care should be taken when
364 using it. C<< scalar $c->req->param( 'foo' ) >> will return only the first
365 C<foo> param even if multiple are present; C<< $c->req->param( 'foo' ) >> will
366 return a list of as many are present, which can have unexpected consequences
367 when writing code of the form:
371 baz => $c->req->param( 'baz' ),
374 If multiple C<baz> parameters are provided this code might corrupt data or
375 cause a hash initialization error. For a more straightforward interface see
376 C<< $c->req->parameters >>.
384 return keys %{ $self->parameters };
391 unless ( exists $self->parameters->{$param} ) {
392 return wantarray ? () : undef;
395 if ( ref $self->parameters->{$param} eq 'ARRAY' ) {
397 ? @{ $self->parameters->{$param} }
398 : $self->parameters->{$param}->[0];
402 ? ( $self->parameters->{$param} )
403 : $self->parameters->{$param};
408 $self->parameters->{$field} = [@_];
412 =head2 $req->parameters
414 Returns a reference to a hash containing GET and POST parameters. Values can
415 be either a scalar or an arrayref containing scalars.
417 print $c->request->parameters->{field};
418 print $c->request->parameters->{field}->[0];
420 This is the combination of C<query_parameters> and C<body_parameters>.
424 Shortcut for $req->parameters.
428 Returns the path, i.e. the part of the URI after $req->base, for the current request.
430 http://localhost/path/foo
432 $c->request->path will contain 'path/foo'
434 =head2 $req->path_info
436 Alias for path, added for compatibility with L<CGI>.
441 my ( $self, @params ) = @_;
444 $self->uri->path(@params);
447 elsif ( $self->_has_path ) {
451 my $path = $self->uri->path;
452 my $location = $self->base->path;
453 $path =~ s/^(\Q$location\E)?//;
461 =head2 $req->protocol
463 Returns the protocol (HTTP/1.0 or HTTP/1.1) used for the current request.
465 =head2 $req->query_parameters
467 =head2 $req->query_params
469 Returns a reference to a hash containing query string (GET) parameters. Values can
470 be either a scalar or an arrayref containing scalars.
472 print $c->request->query_parameters->{field};
473 print $c->request->query_parameters->{field}->[0];
475 =head2 $req->read( [$maxlength] )
477 Reads a chunk of data from the request body. This method is intended to be
478 used in a while loop, reading $maxlength bytes on every call. $maxlength
479 defaults to the size of the request if not specified.
481 You have to set MyApp->config(parse_on_demand => 1) to use this directly.
485 Shortcut for $req->headers->referer. Returns the referring page.
489 Returns true or false, indicating whether the connection is secure
490 (https). Note that the URI scheme (eg., http vs. https) must be determined
491 through heuristics, and therefore the reliability of $req->secure will depend
492 on your server configuration. If you are serving secure pages on the standard
493 SSL port (443) and/or setting the HTTPS environment variable, $req->secure
496 =head2 $req->captures
498 Returns a reference to an array containing captured args from chained
499 actions or regex captures.
501 my @captures = @{ $c->request->captures };
503 =head2 $req->snippets
505 C<captures> used to be called snippets. This is still available for backwards
506 compatibility, but is considered deprecated.
510 A convenient method to access $req->uploads.
512 $upload = $c->request->upload('field');
513 @uploads = $c->request->upload('field');
514 @fields = $c->request->upload;
516 for my $upload ( $c->request->upload('field') ) {
517 print $upload->filename;
526 return keys %{ $self->uploads };
533 unless ( exists $self->uploads->{$upload} ) {
534 return wantarray ? () : undef;
537 if ( ref $self->uploads->{$upload} eq 'ARRAY' ) {
539 ? @{ $self->uploads->{$upload} }
540 : $self->uploads->{$upload}->[0];
544 ? ( $self->uploads->{$upload} )
545 : $self->uploads->{$upload};
551 while ( my ( $field, $upload ) = splice( @_, 0, 2 ) ) {
553 if ( exists $self->uploads->{$field} ) {
554 for ( $self->uploads->{$field} ) {
555 $_ = [$_] unless ref($_) eq "ARRAY";
556 push( @$_, $upload );
560 $self->uploads->{$field} = $upload;
568 Returns a reference to a hash containing uploads. Values can be either a
569 L<Catalyst::Request::Upload> object, or an arrayref of
570 L<Catalyst::Request::Upload> objects.
572 my $upload = $c->request->uploads->{field};
573 my $upload = $c->request->uploads->{field}->[0];
577 Returns a L<URI> object for the current request. Stringifies to the URI text.
579 =head2 $req->mangle_params( { key => 'value' }, $appendmode);
581 Returns a hashref of parameters stemming from the current request's params,
582 plus the ones supplied. Keys for which no current param exists will be
583 added, keys with undefined values will be removed and keys with existing
584 params will be replaced. Note that you can supply a true value as the final
585 argument to change behavior with regards to existing parameters, appending
586 values rather than replacing them.
590 # URI query params foo=1
591 my $hashref = $req->mangle_params({ foo => 2 });
592 # Result is query params of foo=2
596 # URI query params foo=1
597 my $hashref = $req->mangle_params({ foo => 2 }, 1);
598 # Result is query params of foo=1&foo=2
600 This is the code behind C<uri_with>.
605 my ($self, $args, $append) = @_;
607 carp('No arguments passed to mangle_params()') unless $args;
609 foreach my $value ( values %$args ) {
610 next unless defined $value;
611 for ( ref $value eq 'ARRAY' ? @$value : $value ) {
613 utf8::encode( $_ ) if utf8::is_utf8($_);
617 my %params = %{ $self->uri->query_form_hash };
618 foreach my $key (keys %{ $args }) {
619 my $val = $args->{$key};
622 if($append && exists($params{$key})) {
624 # This little bit of heaven handles appending a new value onto
625 # an existing one regardless if the existing value is an array
626 # or not, and regardless if the new value is an array or not
628 ref($params{$key}) eq 'ARRAY' ? @{ $params{$key} } : $params{$key},
629 ref($val) eq 'ARRAY' ? @{ $val } : $val
633 $params{$key} = $val;
637 # If the param wasn't defined then we delete it.
638 delete($params{$key});
646 =head2 $req->uri_with( { key => 'value' } );
648 Returns a rewritten URI object for the current request. Key/value pairs
649 passed in will override existing parameters. You can remove an existing
650 parameter by passing in an undef value. Unmodified pairs will be
653 You may also pass an optional second parameter that puts C<uri_with> into
656 $req->uri_with( { key => 'value' }, { mode => 'append' } );
658 See C<mangle_params> for an explanation of this behavior.
663 my( $self, $args, $behavior) = @_;
665 carp( 'No arguments passed to uri_with()' ) unless $args;
668 if((ref($behavior) eq 'HASH') && defined($behavior->{mode}) && ($behavior->{mode} eq 'append')) {
672 my $params = $self->mangle_params($args, $append);
674 my $uri = $self->uri->clone;
675 $uri->query_form($params);
680 =head2 $req->remote_user
682 Returns the value of the C<REMOTE_USER> environment variable.
684 =head2 $req->user_agent
686 Shortcut to $req->headers->user_agent. Returns the user agent (browser)
695 Catalyst Contributors, see Catalyst.pm
699 This library is free software. You can redistribute it and/or modify
700 it under the same terms as Perl itself.
704 __PACKAGE__->meta->make_immutable;