Fix C::Request disparity between _body and body accessors, TODO test now passes.
[catagits/Catalyst-Runtime.git] / lib / Catalyst / Request.pm
CommitLineData
fc7ec1d9 1package Catalyst::Request;
2
b4ca0ee8 3use IO::Socket qw[AF_INET inet_aton];
bd917b94 4use Carp;
fc42a730 5use utf8;
de19de2e 6use URI::http;
7use URI::https;
e669e88a 8use URI::QueryParam;
6680c772 9use HTTP::Headers;
b4ca0ee8 10
059c085b 11use Moose;
12
b99ff5d8 13with 'MooseX::Emulate::Class::Accessor::Fast';
14
5fb12dbb 15has action => (is => 'rw');
16has address => (is => 'rw');
17has arguments => (is => 'rw', default => sub { [] });
18has cookies => (is => 'rw', default => sub { {} });
19has query_keywords => (is => 'rw');
20has match => (is => 'rw');
21has method => (is => 'rw');
22has protocol => (is => 'rw');
059c085b 23has query_parameters => (is => 'rw', default => sub { {} });
5fb12dbb 24has secure => (is => 'rw', default => 0);
25has captures => (is => 'rw', default => sub { [] });
6cb9e383 26has uri => (is => 'rw', predicate => 'has_uri');
5fb12dbb 27has user => (is => 'rw');
28has headers => (
e5ecd5bc 29 is => 'rw',
059c085b 30 isa => 'HTTP::Headers',
31 handles => [qw(content_encoding content_length content_type header referer user_agent)],
6680c772 32 default => sub { HTTP::Headers->new() },
33 required => 1,
34 lazy => 1,
059c085b 35);
36
02570318 37# Moose TODO:
38# - Can we lose the before modifiers which just call prepare_body ?
39# they are wasteful, slow us down and feel cluttery.
0fc2d522 40# Can we call prepare_body at BUILD time?
02570318 41# Can we make _body an attribute, have the rest of
42# these lazy build from there and kill all the direct hash access
43# in Catalyst.pm and Engine.pm?
0fc2d522 44
059c085b 45has _context => (
46 is => 'rw',
47 weak_ref => 1,
0fc2d522 48 handles => ['read'],
02570318 49 clearer => '_clear_context',
059c085b 50);
51
52has body_parameters => (
5fb12dbb 53 is => 'rw',
54 required => 1,
55 lazy => 1,
56 default => sub { {} },
fc7ec1d9 57);
58
059c085b 59before body_parameters => sub {
60 my ($self) = @_;
61 $self->_context->prepare_body();
62};
63
64has uploads => (
5fb12dbb 65 is => 'rw',
66 required => 1,
67 lazy => 1,
68 default => sub { {} },
059c085b 69);
70
059c085b 71has parameters => (
72 is => 'rw',
73 required => 1,
74 lazy => 1,
75 default => sub { {} },
76);
77
78before parameters => sub {
79 my ($self, $params) = @_;
059c085b 80 if ( $params && !ref $params ) {
e5ecd5bc 81 $self->_context->log->warn(
059c085b 82 "Attempt to retrieve '$params' with req->params(), " .
83 "you probably meant to call req->param('$params')" );
84 $params = undef;
85 }
86
87};
88
89has base => (
5fb12dbb 90 is => 'rw',
91 required => 1,
92 lazy => 1,
93 default => sub {
059c085b 94 my $self = shift;
6cb9e383 95 return $self->path if $self->has_uri;
059c085b 96 },
97);
98
069355da 99has _body => (
100 is => 'rw',
101 accessor => 'body',
059c085b 102);
103
104before body => sub {
105 my ($self) = @_;
106 $self->_context->prepare_body();
107};
108
109has hostname => (
110 is => 'rw',
111 required => 1,
112 lazy => 1,
113 default => sub {
114 my ($self) = @_;
8fc0d39e 115 gethostbyaddr( inet_aton( $self->address ), AF_INET ) || 'localhost'
059c085b 116 },
117);
118
02570318 119has _path => ( is => 'rw', predicate => '_has_path', clearer => '_clear_path' );
120
059c085b 121no Moose;
122
123sub args { shift->arguments(@_) }
124sub body_params { shift->body_parameters(@_) }
125sub input { shift->body(@_) }
126sub params { shift->parameters(@_) }
127sub query_params { shift->query_parameters(@_) }
128sub path_info { shift->path(@_) }
129sub snippets { shift->captures(@_) }
f7e4e231 130
fc7ec1d9 131=head1 NAME
132
3e19f4f6 133Catalyst::Request - provides information about the current client request
fc7ec1d9 134
135=head1 SYNOPSIS
136
b22c6668 137 $req = $c->request;
138 $req->action;
139 $req->address;
b22c6668 140 $req->arguments;
3e19f4f6 141 $req->args;
b22c6668 142 $req->base;
06e1b616 143 $req->body;
fbcc39ad 144 $req->body_parameters;
b5176d9e 145 $req->content_encoding;
146 $req->content_length;
147 $req->content_type;
b77e7869 148 $req->cookie;
b22c6668 149 $req->cookies;
b5176d9e 150 $req->header;
b22c6668 151 $req->headers;
152 $req->hostname;
61bacdcc 153 $req->input;
3b4d1251 154 $req->query_keywords;
b22c6668 155 $req->match;
156 $req->method;
e7c0c583 157 $req->param;
e7c0c583 158 $req->parameters;
3e19f4f6 159 $req->params;
b22c6668 160 $req->path;
bfde09a2 161 $req->protocol;
fbcc39ad 162 $req->query_parameters;
163 $req->read;
b5176d9e 164 $req->referer;
bfde09a2 165 $req->secure;
2982e768 166 $req->captures; # previously knows as snippets
e7c0c583 167 $req->upload;
b22c6668 168 $req->uploads;
77d12cae 169 $req->uri;
7ce7ca2e 170 $req->user;
66294129 171 $req->user_agent;
b22c6668 172
3e22baa5 173See also L<Catalyst>, L<Catalyst::Request::Upload>.
fc7ec1d9 174
175=head1 DESCRIPTION
176
3e19f4f6 177This is the Catalyst Request class, which provides an interface to data for the
178current client request. The request object is prepared by L<Catalyst::Engine>,
179thus hiding the details of the particular engine implementation.
b22c6668 180
181=head1 METHODS
fc7ec1d9 182
b5ecfcf0 183=head2 $req->action
fc7ec1d9 184
aae8d418 185[DEPRECATED] Returns the name of the requested action.
186
187
188Use C<< $c->action >> instead (which returns a
189L<Catalyst::Action|Catalyst::Action> object).
fc7ec1d9 190
b5ecfcf0 191=head2 $req->address
0556eb49 192
3e19f4f6 193Returns the IP address of the client.
61b1e958 194
b5ecfcf0 195=head2 $req->arguments
61b1e958 196
b22c6668 197Returns a reference to an array containing the arguments.
fc7ec1d9 198
199 print $c->request->arguments->[0];
200
c436c1e8 201For example, if your action was
202
85d9fce6 203 package MyApp::C::Foo;
204
205 sub moose : Local {
206 ...
207 }
c436c1e8 208
3e19f4f6 209and the URI for the request was C<http://.../foo/moose/bah>, the string C<bah>
c436c1e8 210would be the first and only argument.
211
b5ecfcf0 212=head2 $req->args
3e19f4f6 213
214Shortcut for arguments.
215
b5ecfcf0 216=head2 $req->base
fc7ec1d9 217
c436c1e8 218Contains the URI base. This will always have a trailing slash.
219
3e19f4f6 220If your application was queried with the URI
221C<http://localhost:3000/some/path> then C<base> is C<http://localhost:3000/>.
fc7ec1d9 222
b5ecfcf0 223=head2 $req->body
06e1b616 224
3e19f4f6 225Returns the message body of the request, unless Content-Type is
e060fe05 226C<application/x-www-form-urlencoded> or C<multipart/form-data>.
227
b5ecfcf0 228=head2 $req->body_parameters
fbcc39ad 229
3e19f4f6 230Returns a reference to a hash containing body (POST) parameters. Values can
fbcc39ad 231be either a scalar or an arrayref containing scalars.
232
233 print $c->request->body_parameters->{field};
234 print $c->request->body_parameters->{field}->[0];
c436c1e8 235
d631b5f9 236These are the parameters from the POST part of the request, if any.
e5ecd5bc 237
b5ecfcf0 238=head2 $req->body_params
fbcc39ad 239
3e19f4f6 240Shortcut for body_parameters.
fbcc39ad 241
b5ecfcf0 242=head2 $req->content_encoding
b5176d9e 243
3e19f4f6 244Shortcut for $req->headers->content_encoding.
b5176d9e 245
b5ecfcf0 246=head2 $req->content_length
b5176d9e 247
3e19f4f6 248Shortcut for $req->headers->content_length.
b5176d9e 249
b5ecfcf0 250=head2 $req->content_type
b5176d9e 251
3e19f4f6 252Shortcut for $req->headers->content_type.
b5176d9e 253
b5ecfcf0 254=head2 $req->cookie
3ad654e0 255
3e19f4f6 256A convenient method to access $req->cookies.
3ad654e0 257
258 $cookie = $c->request->cookie('name');
259 @cookies = $c->request->cookie;
260
261=cut
262
263sub cookie {
264 my $self = shift;
265
266 if ( @_ == 0 ) {
b77e7869 267 return keys %{ $self->cookies };
3ad654e0 268 }
269
270 if ( @_ == 1 ) {
271
272 my $name = shift;
273
b77e7869 274 unless ( exists $self->cookies->{$name} ) {
3ad654e0 275 return undef;
276 }
fbcc39ad 277
b77e7869 278 return $self->cookies->{$name};
3ad654e0 279 }
280}
281
b5ecfcf0 282=head2 $req->cookies
fc7ec1d9 283
b22c6668 284Returns a reference to a hash containing the cookies.
fc7ec1d9 285
286 print $c->request->cookies->{mycookie}->value;
287
3e19f4f6 288The cookies in the hash are indexed by name, and the values are L<CGI::Cookie>
c436c1e8 289objects.
290
b5ecfcf0 291=head2 $req->header
b5176d9e 292
3e19f4f6 293Shortcut for $req->headers->header.
b5176d9e 294
b5ecfcf0 295=head2 $req->headers
fc7ec1d9 296
3e19f4f6 297Returns an L<HTTP::Headers> object containing the headers for the current request.
fc7ec1d9 298
299 print $c->request->headers->header('X-Catalyst');
300
b5ecfcf0 301=head2 $req->hostname
0556eb49 302
3e19f4f6 303Returns the hostname of the client.
e5ecd5bc 304
b5ecfcf0 305=head2 $req->input
61bacdcc 306
3e19f4f6 307Alias for $req->body.
61bacdcc 308
3b4d1251 309=head2 $req->query_keywords
310
311Contains the keywords portion of a query string, when no '=' signs are
312present.
313
314 http://localhost/path?some+keywords
ac5c933b 315
3b4d1251 316 $c->request->query_keywords will contain 'some keywords'
317
b5ecfcf0 318=head2 $req->match
fc7ec1d9 319
3e19f4f6 320This contains the matching part of a Regex action. Otherwise
2c83fd5a 321it returns the same as 'action', except for default actions,
322which return an empty string.
fc7ec1d9 323
b5ecfcf0 324=head2 $req->method
b5176d9e 325
326Contains the request method (C<GET>, C<POST>, C<HEAD>, etc).
327
b5ecfcf0 328=head2 $req->param
e7c0c583 329
ac5c933b 330Returns GET and POST parameters with a CGI.pm-compatible param method. This
3e19f4f6 331is an alternative method for accessing parameters in $c->req->parameters.
e7c0c583 332
a82c2894 333 $value = $c->request->param( 'foo' );
334 @values = $c->request->param( 'foo' );
e7c0c583 335 @params = $c->request->param;
336
3e705254 337Like L<CGI>, and B<unlike> earlier versions of Catalyst, passing multiple
a82c2894 338arguments to this method, like this:
339
85d9fce6 340 $c->request->param( 'foo', 'bar', 'gorch', 'quxx' );
a82c2894 341
342will set the parameter C<foo> to the multiple values C<bar>, C<gorch> and
343C<quxx>. Previously this would have added C<bar> as another value to C<foo>
3e19f4f6 344(creating it if it didn't exist before), and C<quxx> as another value for
345C<gorch>.
a82c2894 346
e7c0c583 347=cut
348
349sub param {
350 my $self = shift;
351
352 if ( @_ == 0 ) {
353 return keys %{ $self->parameters };
354 }
355
bfde09a2 356 if ( @_ == 1 ) {
e7c0c583 357
bfde09a2 358 my $param = shift;
6bd2b72c 359
bfde09a2 360 unless ( exists $self->parameters->{$param} ) {
361 return wantarray ? () : undef;
362 }
363
364 if ( ref $self->parameters->{$param} eq 'ARRAY' ) {
365 return (wantarray)
366 ? @{ $self->parameters->{$param} }
367 : $self->parameters->{$param}->[0];
368 }
369 else {
370 return (wantarray)
371 ? ( $self->parameters->{$param} )
372 : $self->parameters->{$param};
373 }
d7945f32 374 }
a82c2894 375 elsif ( @_ > 1 ) {
376 my $field = shift;
377 $self->parameters->{$field} = [@_];
d7945f32 378 }
e7c0c583 379}
b5176d9e 380
b5ecfcf0 381=head2 $req->parameters
61b1e958 382
3e19f4f6 383Returns a reference to a hash containing GET and POST parameters. Values can
d08ced28 384be either a scalar or an arrayref containing scalars.
fc7ec1d9 385
e7c0c583 386 print $c->request->parameters->{field};
387 print $c->request->parameters->{field}->[0];
fc7ec1d9 388
c436c1e8 389This is the combination of C<query_parameters> and C<body_parameters>.
390
b5ecfcf0 391=head2 $req->params
3e19f4f6 392
393Shortcut for $req->parameters.
394
b5ecfcf0 395=head2 $req->path
fc7ec1d9 396
3e19f4f6 397Returns the path, i.e. the part of the URI after $req->base, for the current request.
fc7ec1d9 398
b5ecfcf0 399=head2 $req->path_info
fbcc39ad 400
3e19f4f6 401Alias for path, added for compability with L<CGI>.
fbcc39ad 402
403=cut
404
405sub path {
02fb5d78 406 my ( $self, @params ) = @_;
4f5ebacd 407
02fb5d78 408 if (@params) {
409 $self->uri->path(@params);
02570318 410 $self->_clear_path;
fbcc39ad 411 }
02570318 412 elsif ( $self->_has_path ) {
413 return $self->_path;
e561386f 414 }
02fb5d78 415 else {
416 my $path = $self->uri->path;
417 my $location = $self->base->path;
418 $path =~ s/^(\Q$location\E)?//;
419 $path =~ s/^\///;
02570318 420 $self->_path($path);
fbcc39ad 421
02fb5d78 422 return $path;
423 }
fbcc39ad 424}
425
b5ecfcf0 426=head2 $req->protocol
bfde09a2 427
3e19f4f6 428Returns the protocol (HTTP/1.0 or HTTP/1.1) used for the current request.
bfde09a2 429
b5ecfcf0 430=head2 $req->query_parameters
fbcc39ad 431
def54ce2 432=head2 $req->query_params
433
3e19f4f6 434Returns a reference to a hash containing query string (GET) parameters. Values can
fbcc39ad 435be either a scalar or an arrayref containing scalars.
436
437 print $c->request->query_parameters->{field};
438 print $c->request->query_parameters->{field}->[0];
ac5c933b 439
b5ecfcf0 440=head2 $req->read( [$maxlength] )
fbcc39ad 441
3e19f4f6 442Reads a chunk of data from the request body. This method is intended to be
443used in a while loop, reading $maxlength bytes on every call. $maxlength
fbcc39ad 444defaults to the size of the request if not specified.
445
446You have to set MyApp->config->{parse_on_demand} to use this directly.
447
b5ecfcf0 448=head2 $req->referer
fc7ec1d9 449
3e19f4f6 450Shortcut for $req->headers->referer. Returns the referring page.
fc7ec1d9 451
b5ecfcf0 452=head2 $req->secure
bfde09a2 453
3e19f4f6 454Returns true or false, indicating whether the connection is secure (https).
bfde09a2 455
2982e768 456=head2 $req->captures
457
5c6a56e0 458Returns a reference to an array containing captured args from chained
459actions or regex captures.
fc7ec1d9 460
2982e768 461 my @captures = @{ $c->request->captures };
462
463=head2 $req->snippets
fc7ec1d9 464
2982e768 465C<captures> used to be called snippets. This is still available for backwoards
466compatibility, but is considered deprecated.
fc7ec1d9 467
b5ecfcf0 468=head2 $req->upload
e7c0c583 469
3e19f4f6 470A convenient method to access $req->uploads.
e7c0c583 471
472 $upload = $c->request->upload('field');
473 @uploads = $c->request->upload('field');
474 @fields = $c->request->upload;
bfde09a2 475
e7c0c583 476 for my $upload ( $c->request->upload('field') ) {
146554c5 477 print $upload->filename;
e7c0c583 478 }
479
480=cut
481
482sub upload {
483 my $self = shift;
484
485 if ( @_ == 0 ) {
486 return keys %{ $self->uploads };
487 }
488
bfde09a2 489 if ( @_ == 1 ) {
e7c0c583 490
bfde09a2 491 my $upload = shift;
492
493 unless ( exists $self->uploads->{$upload} ) {
494 return wantarray ? () : undef;
495 }
6bd2b72c 496
bfde09a2 497 if ( ref $self->uploads->{$upload} eq 'ARRAY' ) {
498 return (wantarray)
499 ? @{ $self->uploads->{$upload} }
500 : $self->uploads->{$upload}->[0];
501 }
502 else {
503 return (wantarray)
fbcc39ad 504 ? ( $self->uploads->{$upload} )
505 : $self->uploads->{$upload};
bfde09a2 506 }
d7945f32 507 }
bfde09a2 508
a4f5c51e 509 if ( @_ > 1 ) {
bfde09a2 510
511 while ( my ( $field, $upload ) = splice( @_, 0, 2 ) ) {
512
513 if ( exists $self->uploads->{$field} ) {
514 for ( $self->uploads->{$field} ) {
515 $_ = [$_] unless ref($_) eq "ARRAY";
516 push( @$_, $upload );
517 }
518 }
519 else {
520 $self->uploads->{$field} = $upload;
521 }
522 }
e7c0c583 523 }
524}
525
b5ecfcf0 526=head2 $req->uploads
fc7ec1d9 527
bfde09a2 528Returns a reference to a hash containing uploads. Values can be either a
ac5c933b 529L<Catalyst::Request::Upload> object, or an arrayref of
84e7aa89 530L<Catalyst::Request::Upload> objects.
e7c0c583 531
532 my $upload = $c->request->uploads->{field};
533 my $upload = $c->request->uploads->{field}->[0];
534
b5ecfcf0 535=head2 $req->uri
fbcc39ad 536
3e19f4f6 537Returns a URI object for the current request. Stringifies to the URI text.
fbcc39ad 538
bd917b94 539=head2 $req->uri_with( { key => 'value' } );
540
3338e8ce 541Returns a rewritten URI object for the current request. Key/value pairs
2f381252 542passed in will override existing parameters. You can remove an existing
543parameter by passing in an undef value. Unmodified pairs will be
3338e8ce 544preserved.
bd917b94 545
546=cut
547
548sub uri_with {
549 my( $self, $args ) = @_;
ac5c933b 550
bd917b94 551 carp( 'No arguments passed to uri_with()' ) unless $args;
fbb513f7 552
2f381252 553 foreach my $value ( values %$args ) {
d0f0fcf6 554 next unless defined $value;
fbb513f7 555 for ( ref $value eq 'ARRAY' ? @$value : $value ) {
556 $_ = "$_";
7066a4d5 557 utf8::encode( $_ ) if utf8::is_utf8($_);
fc42a730 558 }
fc42a730 559 };
ac5c933b 560
2f381252 561 my $uri = $self->uri->clone;
562 my %query = ( %{ $uri->query_form_hash }, %$args );
563
bd917b94 564 $uri->query_form( {
2f381252 565 # remove undef values
566 map { defined $query{ $_ } ? ( $_ => $query{ $_ } ) : () } keys %query
bd917b94 567 } );
568 return $uri;
569}
570
b5ecfcf0 571=head2 $req->user
7ce7ca2e 572
3e19f4f6 573Returns the currently logged in user. Deprecated. The method recommended for
574newer plugins is $c->user.
7ce7ca2e 575
b5ecfcf0 576=head2 $req->user_agent
b5176d9e 577
3e19f4f6 578Shortcut to $req->headers->user_agent. Returns the user agent (browser)
579version string.
b5176d9e 580
059c085b 581=head2 meta
582
583Provided by Moose
584
3e19f4f6 585=head1 AUTHORS
fc7ec1d9 586
2f381252 587Catalyst Contributors, see Catalyst.pm
fc7ec1d9 588
589=head1 COPYRIGHT
590
e7c0c583 591This program is free software, you can redistribute it and/or modify
61b1e958 592it under the same terms as Perl itself.
fc7ec1d9 593
594=cut
595
e5ecd5bc 596__PACKAGE__->meta->make_immutable;
597
fc7ec1d9 5981;