make JSON::MaybeXS only load if it is asked for
[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
6802c884 13use namespace::clean -except => 'meta';
14
b99ff5d8 15with 'MooseX::Emulate::Class::Accessor::Fast';
16
faa02805 17has env => (is => 'ro', writer => '_set_env');
47b9d68e 18# XXX Deprecated crap here - warn?
19has action => (is => 'rw');
20# XXX: Deprecated in docs ages ago (2006), deprecated with warning in 5.8000 due
21# to confusion between Engines and Plugin::Authentication. Remove in 5.8100?
22has user => (is => 'rw');
23sub snippets { shift->captures(@_) }
faa02805 24
47b9d68e 25has _read_position => (
26fc3c5f 26 # FIXME: work around Moose bug RT#75367
27 # init_arg => undef,
47b9d68e 28 is => 'ro',
29 writer => '_set_read_position',
30 default => 0,
31);
32has _read_length => (
26fc3c5f 33 # FIXME: work around Moose bug RT#75367
34 # init_arg => undef,
47b9d68e 35 is => 'ro',
faa02805 36 default => sub {
37 my $self = shift;
38 $self->header('Content-Length') || 0;
39 },
40 lazy => 1,
41);
42
5fb12dbb 43has address => (is => 'rw');
44has arguments => (is => 'rw', default => sub { [] });
d5f4b434 45has cookies => (is => 'ro', builder => 'prepare_cookies', lazy => 1);
46
d5f4b434 47sub prepare_cookies {
48 my ( $self ) = @_;
49
50 if ( my $header = $self->header('Cookie') ) {
51 return { CGI::Simple::Cookie->parse($header) };
52 }
53 {};
54}
55
5fb12dbb 56has query_keywords => (is => 'rw');
57has match => (is => 'rw');
58has method => (is => 'rw');
59has protocol => (is => 'rw');
059c085b 60has query_parameters => (is => 'rw', default => sub { {} });
5fb12dbb 61has secure => (is => 'rw', default => 0);
62has captures => (is => 'rw', default => sub { [] });
6cb9e383 63has uri => (is => 'rw', predicate => 'has_uri');
8026359e 64has remote_user => (is => 'rw');
5fb12dbb 65has headers => (
e5ecd5bc 66 is => 'rw',
059c085b 67 isa => 'HTTP::Headers',
68 handles => [qw(content_encoding content_length content_type header referer user_agent)],
d5f4b434 69 builder => 'prepare_headers',
6680c772 70 lazy => 1,
059c085b 71);
72
d5f4b434 73sub prepare_headers {
74 my ($self) = @_;
75
76 my $env = $self->env;
77 my $headers = HTTP::Headers->new();
78
79 for my $header (keys %{ $env }) {
80 next unless $header =~ /^(HTTP|CONTENT|COOKIE)/i;
81 (my $field = $header) =~ s/^HTTPS?_//;
82 $field =~ tr/_/-/;
83 $headers->header($field => $env->{$header});
84 }
85 return $headers;
86}
87
7c1c4dc6 88has _log => (
89 is => 'ro',
90 weak_ref => 1,
91 required => 1,
059c085b 92);
93
eb1f4b49 94has io_fh => (
b87d834e 95 is=>'ro',
96 predicate=>'has_io_fh',
97 lazy=>1,
98 builder=>'_build_io_fh');
eb1f4b49 99
ade3da0a 100sub _build_io_fh {
eb1f4b49 101 my $self = shift;
102 return $self->env->{'psgix.io'}
103 || die "Your Server does not support psgix.io";
ade3da0a 104};
eb1f4b49 105
b87d834e 106has data_handlers => ( is=>'ro', isa=>'HashRef', default=>sub { +{} } );
ade3da0a 107
b87d834e 108has body_data => (
109 is=>'ro',
110 lazy=>1,
111 builder=>'_build_body_data');
112
113sub _build_body_data {
114 my ($self) = @_;
115 my $content_type = $self->content_type;
116 my ($match) = grep { $content_type =~/$_/i }
117 keys(%{$self->data_handlers});
118
119 if($match) {
120 my $fh = $self->body;
121 local $_ = $fh;
122 return $self->data_handlers->{$match}->($fh, $self);
123 } else {
124 return undef;
125 }
126}
eb1f4b49 127
f083854e 128# Amount of data to read from input on each pass
129our $CHUNKSIZE = 64 * 1024;
130
131sub read {
132 my ($self, $maxlength) = @_;
133 my $remaining = $self->_read_length - $self->_read_position;
134 $maxlength ||= $CHUNKSIZE;
135
136 # Are we done reading?
137 if ( $remaining <= 0 ) {
138 return;
139 }
140
141 my $readlen = ( $remaining > $maxlength ) ? $maxlength : $remaining;
142 my $rc = $self->read_chunk( my $buffer, $readlen );
143 if ( defined $rc ) {
144 if (0 == $rc) { # Nothing more to read even though Content-Length
145 # said there should be.
146 return;
147 }
47b9d68e 148 $self->_set_read_position( $self->_read_position + $rc );
f083854e 149 return $buffer;
150 }
151 else {
152 Catalyst::Exception->throw(
153 message => "Unknown error reading input: $!" );
154 }
155}
156
87f50436 157sub read_chunk {
158 my $self = shift;
159 return $self->env->{'psgi.input'}->read(@_);
160}
161
059c085b 162has body_parameters => (
5fb12dbb 163 is => 'rw',
164 required => 1,
165 lazy => 1,
d003ff83 166 builder => 'prepare_body_parameters',
fc7ec1d9 167);
168
059c085b 169has uploads => (
5fb12dbb 170 is => 'rw',
171 required => 1,
5fb12dbb 172 default => sub { {} },
059c085b 173);
174
059c085b 175has parameters => (
1cbdfa9b 176 is => 'rw',
177 lazy => 1,
11e7af55 178 builder => '_build_parameters',
179 clearer => '_clear_parameters',
059c085b 180);
181
341620d5 182# TODO:
183# - Can we lose the before modifiers which just call prepare_body ?
184# they are wasteful, slow us down and feel cluttery.
185
186# Can we make _body an attribute, have the rest of
187# these lazy build from there and kill all the direct hash access
188# in Catalyst.pm and Engine.pm?
189
1cbdfa9b 190sub prepare_parameters {
191 my ( $self ) = @_;
11e7af55 192 $self->_clear_parameters;
193 return $self->parameters;
194}
195
11e7af55 196sub _build_parameters {
197 my ( $self ) = @_;
1cbdfa9b 198 my $parameters = {};
199 my $body_parameters = $self->body_parameters;
200 my $query_parameters = $self->query_parameters;
201 # We copy, no references
202 foreach my $name (keys %$query_parameters) {
203 my $param = $query_parameters->{$name};
204 $parameters->{$name} = ref $param eq 'ARRAY' ? [ @$param ] : $param;
205 }
206
207 # Merge query and body parameters
208 foreach my $name (keys %$body_parameters) {
209 my $param = $body_parameters->{$name};
210 my @values = ref $param eq 'ARRAY' ? @$param : ($param);
211 if ( my $existing = $parameters->{$name} ) {
212 unshift(@values, (ref $existing eq 'ARRAY' ? @$existing : $existing));
213 }
214 $parameters->{$name} = @values > 1 ? \@values : $values[0];
215 }
216 $parameters;
217}
218
398f13db 219has _uploadtmp => (
220 is => 'ro',
221 predicate => '_has_uploadtmp',
222);
223
224sub prepare_body {
225 my ( $self ) = @_;
226
227 if ( my $length = $self->_read_length ) {
228 unless ( $self->_body ) {
229 my $type = $self->header('Content-Type');
230 $self->_body(HTTP::Body->new( $type, $length ));
231 $self->_body->cleanup(1); # Make extra sure!
232 $self->_body->tmpdir( $self->_uploadtmp )
233 if $self->_has_uploadtmp;
234 }
235
236 # Check for definedness as you could read '0'
237 while ( defined ( my $buffer = $self->read() ) ) {
238 $self->prepare_body_chunk($buffer);
239 }
240
241 # paranoia against wrong Content-Length header
242 my $remaining = $length - $self->_read_position;
243 if ( $remaining > 0 ) {
244 Catalyst::Exception->throw(
245 "Wrong Content-Length value: $length" );
246 }
247 }
248 else {
249 # Defined but will cause all body code to be skipped
250 $self->_body(0);
251 }
252}
253
398f13db 254sub prepare_body_chunk {
255 my ( $self, $chunk ) = @_;
256
257 $self->_body->add($chunk);
258}
259
398f13db 260sub prepare_body_parameters {
261 my ( $self ) = @_;
262
d003ff83 263 $self->prepare_body if ! $self->_has_body;
a7d2a530 264 return {} unless $self->_body;
398f13db 265
d003ff83 266 return $self->_body->param;
398f13db 267}
341620d5 268
2f498a7e 269sub prepare_connection {
270 my ($self) = @_;
271
272 my $env = $self->env;
273
274 $self->address( $env->{REMOTE_ADDR} );
275 $self->hostname( $env->{REMOTE_HOST} )
276 if exists $env->{REMOTE_HOST};
277 $self->protocol( $env->{SERVER_PROTOCOL} );
278 $self->remote_user( $env->{REMOTE_USER} );
279 $self->method( $env->{REQUEST_METHOD} );
280 $self->secure( $env->{'psgi.url_scheme'} eq 'https' ? 1 : 0 );
281}
282
283# XXX - FIXME - method is here now, move this crap...
e99ec2dc 284around parameters => sub {
285 my ($orig, $self, $params) = @_;
286 if ($params) {
287 if ( !ref $params ) {
7c1c4dc6 288 $self->_log->warn(
e99ec2dc 289 "Attempt to retrieve '$params' with req->params(), " .
290 "you probably meant to call req->param('$params')"
291 );
292 $params = undef;
293 }
294 return $self->$orig($params);
295 }
296 $self->$orig();
059c085b 297};
298
299has base => (
5fb12dbb 300 is => 'rw',
301 required => 1,
302 lazy => 1,
303 default => sub {
059c085b 304 my $self = shift;
6cb9e383 305 return $self->path if $self->has_uri;
059c085b 306 },
307);
308
069355da 309has _body => (
0f56bbcf 310 is => 'rw', clearer => '_clear_body', predicate => '_has_body',
059c085b 311);
610bc6ec 312# Eugh, ugly. Should just be able to rename accessor methods to 'body'
b0ad47c1 313# and provide a custom reader..
610bc6ec 314sub body {
315 my $self = shift;
d003ff83 316 $self->prepare_body unless ! $self->_has_body;
14c057aa 317 croak 'body is a reader' if scalar @_;
610bc6ec 318 return blessed $self->_body ? $self->_body->body : $self->_body;
319}
059c085b 320
321has hostname => (
322 is => 'rw',
323 required => 1,
324 lazy => 1,
325 default => sub {
326 my ($self) = @_;
9fb936e5 327 gethostbyaddr( inet_aton( $self->address ), AF_INET ) || $self->address
059c085b 328 },
329);
330
02570318 331has _path => ( is => 'rw', predicate => '_has_path', clearer => '_clear_path' );
332
059c085b 333sub args { shift->arguments(@_) }
334sub body_params { shift->body_parameters(@_) }
335sub input { shift->body(@_) }
336sub params { shift->parameters(@_) }
337sub query_params { shift->query_parameters(@_) }
338sub path_info { shift->path(@_) }
f7e4e231 339
8738b8fe 340=for stopwords param params
965f3e35 341
fc7ec1d9 342=head1 NAME
343
3e19f4f6 344Catalyst::Request - provides information about the current client request
fc7ec1d9 345
346=head1 SYNOPSIS
347
b22c6668 348 $req = $c->request;
767480fd 349 $req->address eq "127.0.0.1";
b22c6668 350 $req->arguments;
3e19f4f6 351 $req->args;
b22c6668 352 $req->base;
06e1b616 353 $req->body;
fbcc39ad 354 $req->body_parameters;
b5176d9e 355 $req->content_encoding;
356 $req->content_length;
357 $req->content_type;
b77e7869 358 $req->cookie;
b22c6668 359 $req->cookies;
b5176d9e 360 $req->header;
b22c6668 361 $req->headers;
362 $req->hostname;
61bacdcc 363 $req->input;
3b4d1251 364 $req->query_keywords;
b22c6668 365 $req->match;
366 $req->method;
e7c0c583 367 $req->param;
e7c0c583 368 $req->parameters;
3e19f4f6 369 $req->params;
b22c6668 370 $req->path;
bfde09a2 371 $req->protocol;
fbcc39ad 372 $req->query_parameters;
373 $req->read;
b5176d9e 374 $req->referer;
bfde09a2 375 $req->secure;
47b9d68e 376 $req->captures;
e7c0c583 377 $req->upload;
b22c6668 378 $req->uploads;
77d12cae 379 $req->uri;
7ce7ca2e 380 $req->user;
66294129 381 $req->user_agent;
b22c6668 382
3e22baa5 383See also L<Catalyst>, L<Catalyst::Request::Upload>.
fc7ec1d9 384
385=head1 DESCRIPTION
386
3e19f4f6 387This is the Catalyst Request class, which provides an interface to data for the
388current client request. The request object is prepared by L<Catalyst::Engine>,
389thus hiding the details of the particular engine implementation.
b22c6668 390
391=head1 METHODS
fc7ec1d9 392
b5ecfcf0 393=head2 $req->address
0556eb49 394
3e19f4f6 395Returns the IP address of the client.
61b1e958 396
b5ecfcf0 397=head2 $req->arguments
61b1e958 398
b22c6668 399Returns a reference to an array containing the arguments.
fc7ec1d9 400
401 print $c->request->arguments->[0];
402
c436c1e8 403For example, if your action was
404
7d7519a4 405 package MyApp::Controller::Foo;
85d9fce6 406
407 sub moose : Local {
408 ...
409 }
c436c1e8 410
3e19f4f6 411and the URI for the request was C<http://.../foo/moose/bah>, the string C<bah>
c436c1e8 412would be the first and only argument.
413
6d920953 414Arguments get automatically URI-unescaped for you.
8f58057d 415
b5ecfcf0 416=head2 $req->args
3e19f4f6 417
01011731 418Shortcut for L</arguments>.
3e19f4f6 419
b5ecfcf0 420=head2 $req->base
fc7ec1d9 421
328f225e 422Contains the URI base. This will always have a trailing slash. Note that the
f4dda4a8 423URI scheme (e.g., http vs. https) must be determined through heuristics;
328f225e 424depending on your server configuration, it may be incorrect. See $req->secure
425for more info.
c436c1e8 426
3e19f4f6 427If your application was queried with the URI
428C<http://localhost:3000/some/path> then C<base> is C<http://localhost:3000/>.
fc7ec1d9 429
b5ecfcf0 430=head2 $req->body
06e1b616 431
843871cf 432Returns the message body of the request, as returned by L<HTTP::Body>: a string,
433unless Content-Type is C<application/x-www-form-urlencoded>, C<text/xml>, or
434C<multipart/form-data>, in which case a L<File::Temp> object is returned.
e060fe05 435
b5ecfcf0 436=head2 $req->body_parameters
fbcc39ad 437
3e19f4f6 438Returns a reference to a hash containing body (POST) parameters. Values can
fbcc39ad 439be either a scalar or an arrayref containing scalars.
440
441 print $c->request->body_parameters->{field};
442 print $c->request->body_parameters->{field}->[0];
c436c1e8 443
d631b5f9 444These are the parameters from the POST part of the request, if any.
e5ecd5bc 445
b5ecfcf0 446=head2 $req->body_params
fbcc39ad 447
3e19f4f6 448Shortcut for body_parameters.
fbcc39ad 449
b5ecfcf0 450=head2 $req->content_encoding
b5176d9e 451
3e19f4f6 452Shortcut for $req->headers->content_encoding.
b5176d9e 453
b5ecfcf0 454=head2 $req->content_length
b5176d9e 455
3e19f4f6 456Shortcut for $req->headers->content_length.
b5176d9e 457
b5ecfcf0 458=head2 $req->content_type
b5176d9e 459
3e19f4f6 460Shortcut for $req->headers->content_type.
b5176d9e 461
b5ecfcf0 462=head2 $req->cookie
3ad654e0 463
3e19f4f6 464A convenient method to access $req->cookies.
3ad654e0 465
466 $cookie = $c->request->cookie('name');
467 @cookies = $c->request->cookie;
468
469=cut
470
471sub cookie {
472 my $self = shift;
473
474 if ( @_ == 0 ) {
b77e7869 475 return keys %{ $self->cookies };
3ad654e0 476 }
477
478 if ( @_ == 1 ) {
479
480 my $name = shift;
481
b77e7869 482 unless ( exists $self->cookies->{$name} ) {
3ad654e0 483 return undef;
484 }
fbcc39ad 485
b77e7869 486 return $self->cookies->{$name};
3ad654e0 487 }
488}
489
b5ecfcf0 490=head2 $req->cookies
fc7ec1d9 491
b22c6668 492Returns a reference to a hash containing the cookies.
fc7ec1d9 493
494 print $c->request->cookies->{mycookie}->value;
495
7e743798 496The cookies in the hash are indexed by name, and the values are L<CGI::Simple::Cookie>
c436c1e8 497objects.
498
b5ecfcf0 499=head2 $req->header
b5176d9e 500
3e19f4f6 501Shortcut for $req->headers->header.
b5176d9e 502
b5ecfcf0 503=head2 $req->headers
fc7ec1d9 504
3e19f4f6 505Returns an L<HTTP::Headers> object containing the headers for the current request.
fc7ec1d9 506
507 print $c->request->headers->header('X-Catalyst');
508
b5ecfcf0 509=head2 $req->hostname
0556eb49 510
178dca5f 511Returns the hostname of the client. Use C<< $req->uri->host >> to get the hostname of the server.
e5ecd5bc 512
b5ecfcf0 513=head2 $req->input
61bacdcc 514
3e19f4f6 515Alias for $req->body.
61bacdcc 516
3b4d1251 517=head2 $req->query_keywords
518
519Contains the keywords portion of a query string, when no '=' signs are
520present.
521
522 http://localhost/path?some+keywords
b0ad47c1 523
3b4d1251 524 $c->request->query_keywords will contain 'some keywords'
525
b5ecfcf0 526=head2 $req->match
fc7ec1d9 527
3e19f4f6 528This contains the matching part of a Regex action. Otherwise
2c83fd5a 529it returns the same as 'action', except for default actions,
530which return an empty string.
fc7ec1d9 531
b5ecfcf0 532=head2 $req->method
b5176d9e 533
534Contains the request method (C<GET>, C<POST>, C<HEAD>, etc).
535
b5ecfcf0 536=head2 $req->param
e7c0c583 537
b0ad47c1 538Returns GET and POST parameters with a CGI.pm-compatible param method. This
3e19f4f6 539is an alternative method for accessing parameters in $c->req->parameters.
e7c0c583 540
a82c2894 541 $value = $c->request->param( 'foo' );
542 @values = $c->request->param( 'foo' );
e7c0c583 543 @params = $c->request->param;
544
3e705254 545Like L<CGI>, and B<unlike> earlier versions of Catalyst, passing multiple
a82c2894 546arguments to this method, like this:
547
85d9fce6 548 $c->request->param( 'foo', 'bar', 'gorch', 'quxx' );
a82c2894 549
550will set the parameter C<foo> to the multiple values C<bar>, C<gorch> and
551C<quxx>. Previously this would have added C<bar> as another value to C<foo>
3e19f4f6 552(creating it if it didn't exist before), and C<quxx> as another value for
553C<gorch>.
a82c2894 554
83312afd 555B<NOTE> this is considered a legacy interface and care should be taken when
556using it. C<< scalar $c->req->param( 'foo' ) >> will return only the first
557C<foo> param even if multiple are present; C<< $c->req->param( 'foo' ) >> will
558return a list of as many are present, which can have unexpected consequences
559when writing code of the form:
560
561 $foo->bar(
562 a => 'b',
563 baz => $c->req->param( 'baz' ),
564 );
565
566If multiple C<baz> parameters are provided this code might corrupt data or
567cause a hash initialization error. For a more straightforward interface see
568C<< $c->req->parameters >>.
569
e7c0c583 570=cut
571
572sub param {
573 my $self = shift;
574
575 if ( @_ == 0 ) {
576 return keys %{ $self->parameters };
577 }
578
bfde09a2 579 if ( @_ == 1 ) {
e7c0c583 580
bfde09a2 581 my $param = shift;
6bd2b72c 582
bfde09a2 583 unless ( exists $self->parameters->{$param} ) {
584 return wantarray ? () : undef;
585 }
586
587 if ( ref $self->parameters->{$param} eq 'ARRAY' ) {
588 return (wantarray)
589 ? @{ $self->parameters->{$param} }
590 : $self->parameters->{$param}->[0];
591 }
592 else {
593 return (wantarray)
594 ? ( $self->parameters->{$param} )
595 : $self->parameters->{$param};
596 }
d7945f32 597 }
a82c2894 598 elsif ( @_ > 1 ) {
599 my $field = shift;
600 $self->parameters->{$field} = [@_];
d7945f32 601 }
e7c0c583 602}
b5176d9e 603
b5ecfcf0 604=head2 $req->parameters
61b1e958 605
3e19f4f6 606Returns a reference to a hash containing GET and POST parameters. Values can
d08ced28 607be either a scalar or an arrayref containing scalars.
fc7ec1d9 608
e7c0c583 609 print $c->request->parameters->{field};
610 print $c->request->parameters->{field}->[0];
fc7ec1d9 611
c436c1e8 612This is the combination of C<query_parameters> and C<body_parameters>.
613
b5ecfcf0 614=head2 $req->params
3e19f4f6 615
616Shortcut for $req->parameters.
617
b5ecfcf0 618=head2 $req->path
fc7ec1d9 619
3e19f4f6 620Returns the path, i.e. the part of the URI after $req->base, for the current request.
fc7ec1d9 621
be6801fa 622 http://localhost/path/foo
623
624 $c->request->path will contain 'path/foo'
625
b5ecfcf0 626=head2 $req->path_info
fbcc39ad 627
10011c19 628Alias for path, added for compatibility with L<CGI>.
fbcc39ad 629
630=cut
631
632sub path {
02fb5d78 633 my ( $self, @params ) = @_;
4f5ebacd 634
02fb5d78 635 if (@params) {
636 $self->uri->path(@params);
02570318 637 $self->_clear_path;
fbcc39ad 638 }
02570318 639 elsif ( $self->_has_path ) {
640 return $self->_path;
e561386f 641 }
02fb5d78 642 else {
643 my $path = $self->uri->path;
644 my $location = $self->base->path;
645 $path =~ s/^(\Q$location\E)?//;
646 $path =~ s/^\///;
02570318 647 $self->_path($path);
fbcc39ad 648
02fb5d78 649 return $path;
650 }
fbcc39ad 651}
652
b5ecfcf0 653=head2 $req->protocol
bfde09a2 654
3e19f4f6 655Returns the protocol (HTTP/1.0 or HTTP/1.1) used for the current request.
bfde09a2 656
b5ecfcf0 657=head2 $req->query_parameters
fbcc39ad 658
def54ce2 659=head2 $req->query_params
660
3e19f4f6 661Returns a reference to a hash containing query string (GET) parameters. Values can
fbcc39ad 662be either a scalar or an arrayref containing scalars.
663
664 print $c->request->query_parameters->{field};
665 print $c->request->query_parameters->{field}->[0];
b0ad47c1 666
b5ecfcf0 667=head2 $req->read( [$maxlength] )
fbcc39ad 668
3e19f4f6 669Reads a chunk of data from the request body. This method is intended to be
670used in a while loop, reading $maxlength bytes on every call. $maxlength
fbcc39ad 671defaults to the size of the request if not specified.
672
87f50436 673=head2 $req->read_chunk(\$buff, $max)
674
d7f18923 675Reads a chunk.
87f50436 676
9779c885 677You have to set MyApp->config(parse_on_demand => 1) to use this directly.
fbcc39ad 678
b5ecfcf0 679=head2 $req->referer
fc7ec1d9 680
3e19f4f6 681Shortcut for $req->headers->referer. Returns the referring page.
fc7ec1d9 682
b5ecfcf0 683=head2 $req->secure
bfde09a2 684
328f225e 685Returns true or false, indicating whether the connection is secure
d7f18923 686(https). The reliability of $req->secure may depend on your server
687configuration; Catalyst relies on PSGI to determine whether or not a
688request is secure (Catalyst looks at psgi.url_scheme), and different
689PSGI servers may make this determination in different ways (as by
690directly passing along information from the server, interpreting any of
691several HTTP headers, or using heuristics of their own).
bfde09a2 692
2982e768 693=head2 $req->captures
694
5c6a56e0 695Returns a reference to an array containing captured args from chained
696actions or regex captures.
fc7ec1d9 697
2982e768 698 my @captures = @{ $c->request->captures };
699
b5ecfcf0 700=head2 $req->upload
e7c0c583 701
3e19f4f6 702A convenient method to access $req->uploads.
e7c0c583 703
704 $upload = $c->request->upload('field');
705 @uploads = $c->request->upload('field');
706 @fields = $c->request->upload;
bfde09a2 707
e7c0c583 708 for my $upload ( $c->request->upload('field') ) {
146554c5 709 print $upload->filename;
e7c0c583 710 }
711
712=cut
713
714sub upload {
715 my $self = shift;
716
717 if ( @_ == 0 ) {
718 return keys %{ $self->uploads };
719 }
720
bfde09a2 721 if ( @_ == 1 ) {
e7c0c583 722
bfde09a2 723 my $upload = shift;
724
725 unless ( exists $self->uploads->{$upload} ) {
726 return wantarray ? () : undef;
727 }
6bd2b72c 728
bfde09a2 729 if ( ref $self->uploads->{$upload} eq 'ARRAY' ) {
730 return (wantarray)
731 ? @{ $self->uploads->{$upload} }
732 : $self->uploads->{$upload}->[0];
733 }
734 else {
735 return (wantarray)
fbcc39ad 736 ? ( $self->uploads->{$upload} )
737 : $self->uploads->{$upload};
bfde09a2 738 }
d7945f32 739 }
bfde09a2 740
a4f5c51e 741 if ( @_ > 1 ) {
bfde09a2 742
743 while ( my ( $field, $upload ) = splice( @_, 0, 2 ) ) {
744
745 if ( exists $self->uploads->{$field} ) {
746 for ( $self->uploads->{$field} ) {
747 $_ = [$_] unless ref($_) eq "ARRAY";
748 push( @$_, $upload );
749 }
750 }
751 else {
752 $self->uploads->{$field} = $upload;
753 }
754 }
e7c0c583 755 }
756}
757
b5ecfcf0 758=head2 $req->uploads
fc7ec1d9 759
bfde09a2 760Returns a reference to a hash containing uploads. Values can be either a
b0ad47c1 761L<Catalyst::Request::Upload> object, or an arrayref of
84e7aa89 762L<Catalyst::Request::Upload> objects.
e7c0c583 763
764 my $upload = $c->request->uploads->{field};
765 my $upload = $c->request->uploads->{field}->[0];
766
b5ecfcf0 767=head2 $req->uri
fbcc39ad 768
d26ee0d0 769Returns a L<URI> object for the current request. Stringifies to the URI text.
fbcc39ad 770
a375a206 771=head2 $req->mangle_params( { key => 'value' }, $appendmode);
bd917b94 772
a375a206 773Returns a hashref of parameters stemming from the current request's params,
774plus the ones supplied. Keys for which no current param exists will be
775added, keys with undefined values will be removed and keys with existing
776params will be replaced. Note that you can supply a true value as the final
777argument to change behavior with regards to existing parameters, appending
778values rather than replacing them.
779
780A quick example:
781
782 # URI query params foo=1
783 my $hashref = $req->mangle_params({ foo => 2 });
784 # Result is query params of foo=2
785
786versus append mode:
787
788 # URI query params foo=1
789 my $hashref = $req->mangle_params({ foo => 2 }, 1);
790 # Result is query params of foo=1&foo=2
791
792This is the code behind C<uri_with>.
bd917b94 793
794=cut
795
a375a206 796sub mangle_params {
797 my ($self, $args, $append) = @_;
b0ad47c1 798
a375a206 799 carp('No arguments passed to mangle_params()') unless $args;
fbb513f7 800
2f381252 801 foreach my $value ( values %$args ) {
d0f0fcf6 802 next unless defined $value;
fbb513f7 803 for ( ref $value eq 'ARRAY' ? @$value : $value ) {
804 $_ = "$_";
7066a4d5 805 utf8::encode( $_ ) if utf8::is_utf8($_);
fc42a730 806 }
fc42a730 807 };
b0ad47c1 808
a375a206 809 my %params = %{ $self->uri->query_form_hash };
810 foreach my $key (keys %{ $args }) {
811 my $val = $args->{$key};
812 if(defined($val)) {
813
814 if($append && exists($params{$key})) {
815
816 # This little bit of heaven handles appending a new value onto
817 # an existing one regardless if the existing value is an array
818 # or not, and regardless if the new value is an array or not
819 $params{$key} = [
820 ref($params{$key}) eq 'ARRAY' ? @{ $params{$key} } : $params{$key},
821 ref($val) eq 'ARRAY' ? @{ $val } : $val
822 ];
823
824 } else {
825 $params{$key} = $val;
826 }
827 } else {
828
829 # If the param wasn't defined then we delete it.
830 delete($params{$key});
831 }
832 }
833
834
835 return \%params;
836}
837
838=head2 $req->uri_with( { key => 'value' } );
839
840Returns a rewritten URI object for the current request. Key/value pairs
841passed in will override existing parameters. You can remove an existing
842parameter by passing in an undef value. Unmodified pairs will be
843preserved.
844
845You may also pass an optional second parameter that puts C<uri_with> into
846append mode:
847
848 $req->uri_with( { key => 'value' }, { mode => 'append' } );
9779c885 849
a375a206 850See C<mangle_params> for an explanation of this behavior.
851
852=cut
853
854sub uri_with {
855 my( $self, $args, $behavior) = @_;
856
857 carp( 'No arguments passed to uri_with()' ) unless $args;
858
859 my $append = 0;
860 if((ref($behavior) eq 'HASH') && defined($behavior->{mode}) && ($behavior->{mode} eq 'append')) {
861 $append = 1;
862 }
863
864 my $params = $self->mangle_params($args, $append);
865
866 my $uri = $self->uri->clone;
867 $uri->query_form($params);
2f381252 868
bd917b94 869 return $uri;
870}
871
8026359e 872=head2 $req->remote_user
873
874Returns the value of the C<REMOTE_USER> environment variable.
7ce7ca2e 875
b5ecfcf0 876=head2 $req->user_agent
b5176d9e 877
3e19f4f6 878Shortcut to $req->headers->user_agent. Returns the user agent (browser)
879version string.
b5176d9e 880
eb1f4b49 881=head2 $req->io_fh
882
883Returns a psgix.io bidirectional socket, if your server supports one. Used for
884when you want to jailbreak out of PSGI and handle bidirectional client server
885communication manually, such as when you are using cometd or websockets.
886
47b9d68e 887=head1 SETUP METHODS
888
889You should never need to call these yourself in application code,
890however they are useful if extending Catalyst by applying a request role.
891
892=head2 $self->prepare_headers()
893
894Sets up the C<< $res->headers >> accessor.
895
896=head2 $self->prepare_body()
897
898Sets up the body using L<HTTP::Body>
899
900=head2 $self->prepare_body_chunk()
901
902Add a chunk to the request body.
903
904=head2 $self->prepare_body_parameters()
905
906Sets up parameters from body.
907
8738b8fe 908=head2 $self->prepare_cookies()
47b9d68e 909
910Parse cookies from header. Sets up a L<CGI::Simple::Cookie> object.
911
8738b8fe 912=head2 $self->prepare_connection()
913
914Sets up various fields in the request like the local and remote addresses,
f59eeb09 915request method, hostname requested etc.
8738b8fe 916
917=head2 $self->prepare_parameters()
918
919Ensures that the body has been parsed, then builds the parameters, which are
920combined from those in the request and those in the body.
921
11e7af55 922If parameters have already been set will clear the parameters and build them again.
923
8738b8fe 924
059c085b 925=head2 meta
926
927Provided by Moose
928
3e19f4f6 929=head1 AUTHORS
fc7ec1d9 930
2f381252 931Catalyst Contributors, see Catalyst.pm
fc7ec1d9 932
933=head1 COPYRIGHT
934
536bee89 935This library is free software. You can redistribute it and/or modify
61b1e958 936it under the same terms as Perl itself.
fc7ec1d9 937
938=cut
939
e5ecd5bc 940__PACKAGE__->meta->make_immutable;
941
fc7ec1d9 9421;