use more popular json parsers
[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;
974733c0 354 $req->body_data;
fbcc39ad 355 $req->body_parameters;
b5176d9e 356 $req->content_encoding;
357 $req->content_length;
358 $req->content_type;
b77e7869 359 $req->cookie;
b22c6668 360 $req->cookies;
b5176d9e 361 $req->header;
b22c6668 362 $req->headers;
363 $req->hostname;
61bacdcc 364 $req->input;
3b4d1251 365 $req->query_keywords;
b22c6668 366 $req->match;
367 $req->method;
e7c0c583 368 $req->param;
e7c0c583 369 $req->parameters;
3e19f4f6 370 $req->params;
b22c6668 371 $req->path;
bfde09a2 372 $req->protocol;
fbcc39ad 373 $req->query_parameters;
374 $req->read;
b5176d9e 375 $req->referer;
bfde09a2 376 $req->secure;
47b9d68e 377 $req->captures;
e7c0c583 378 $req->upload;
b22c6668 379 $req->uploads;
77d12cae 380 $req->uri;
7ce7ca2e 381 $req->user;
66294129 382 $req->user_agent;
b22c6668 383
3e22baa5 384See also L<Catalyst>, L<Catalyst::Request::Upload>.
fc7ec1d9 385
386=head1 DESCRIPTION
387
3e19f4f6 388This is the Catalyst Request class, which provides an interface to data for the
389current client request. The request object is prepared by L<Catalyst::Engine>,
390thus hiding the details of the particular engine implementation.
b22c6668 391
392=head1 METHODS
fc7ec1d9 393
b5ecfcf0 394=head2 $req->address
0556eb49 395
3e19f4f6 396Returns the IP address of the client.
61b1e958 397
b5ecfcf0 398=head2 $req->arguments
61b1e958 399
b22c6668 400Returns a reference to an array containing the arguments.
fc7ec1d9 401
402 print $c->request->arguments->[0];
403
c436c1e8 404For example, if your action was
405
7d7519a4 406 package MyApp::Controller::Foo;
85d9fce6 407
408 sub moose : Local {
409 ...
410 }
c436c1e8 411
3e19f4f6 412and the URI for the request was C<http://.../foo/moose/bah>, the string C<bah>
c436c1e8 413would be the first and only argument.
414
6d920953 415Arguments get automatically URI-unescaped for you.
8f58057d 416
b5ecfcf0 417=head2 $req->args
3e19f4f6 418
01011731 419Shortcut for L</arguments>.
3e19f4f6 420
b5ecfcf0 421=head2 $req->base
fc7ec1d9 422
328f225e 423Contains the URI base. This will always have a trailing slash. Note that the
f4dda4a8 424URI scheme (e.g., http vs. https) must be determined through heuristics;
328f225e 425depending on your server configuration, it may be incorrect. See $req->secure
426for more info.
c436c1e8 427
3e19f4f6 428If your application was queried with the URI
429C<http://localhost:3000/some/path> then C<base> is C<http://localhost:3000/>.
fc7ec1d9 430
b5ecfcf0 431=head2 $req->body
06e1b616 432
843871cf 433Returns the message body of the request, as returned by L<HTTP::Body>: a string,
434unless Content-Type is C<application/x-www-form-urlencoded>, C<text/xml>, or
435C<multipart/form-data>, in which case a L<File::Temp> object is returned.
e060fe05 436
974733c0 437=head2 $req->body_data
438
439Returns a Perl representation of POST/PUT body data that is not classic HTML
440form data, such as JSON, XML, etc. By default, Catalyst will parse incoming
441data of the type 'application/json' and return access to that data via this
442method. You may define addition data_handlers via a global configuration
443setting. See L<Catalyst\DATA HANDLERS> for more information.
444
b5ecfcf0 445=head2 $req->body_parameters
fbcc39ad 446
3e19f4f6 447Returns a reference to a hash containing body (POST) parameters. Values can
fbcc39ad 448be either a scalar or an arrayref containing scalars.
449
450 print $c->request->body_parameters->{field};
451 print $c->request->body_parameters->{field}->[0];
c436c1e8 452
d631b5f9 453These are the parameters from the POST part of the request, if any.
e5ecd5bc 454
b5ecfcf0 455=head2 $req->body_params
fbcc39ad 456
3e19f4f6 457Shortcut for body_parameters.
fbcc39ad 458
b5ecfcf0 459=head2 $req->content_encoding
b5176d9e 460
3e19f4f6 461Shortcut for $req->headers->content_encoding.
b5176d9e 462
b5ecfcf0 463=head2 $req->content_length
b5176d9e 464
3e19f4f6 465Shortcut for $req->headers->content_length.
b5176d9e 466
b5ecfcf0 467=head2 $req->content_type
b5176d9e 468
3e19f4f6 469Shortcut for $req->headers->content_type.
b5176d9e 470
b5ecfcf0 471=head2 $req->cookie
3ad654e0 472
3e19f4f6 473A convenient method to access $req->cookies.
3ad654e0 474
475 $cookie = $c->request->cookie('name');
476 @cookies = $c->request->cookie;
477
478=cut
479
480sub cookie {
481 my $self = shift;
482
483 if ( @_ == 0 ) {
b77e7869 484 return keys %{ $self->cookies };
3ad654e0 485 }
486
487 if ( @_ == 1 ) {
488
489 my $name = shift;
490
b77e7869 491 unless ( exists $self->cookies->{$name} ) {
3ad654e0 492 return undef;
493 }
fbcc39ad 494
b77e7869 495 return $self->cookies->{$name};
3ad654e0 496 }
497}
498
b5ecfcf0 499=head2 $req->cookies
fc7ec1d9 500
b22c6668 501Returns a reference to a hash containing the cookies.
fc7ec1d9 502
503 print $c->request->cookies->{mycookie}->value;
504
7e743798 505The cookies in the hash are indexed by name, and the values are L<CGI::Simple::Cookie>
c436c1e8 506objects.
507
b5ecfcf0 508=head2 $req->header
b5176d9e 509
3e19f4f6 510Shortcut for $req->headers->header.
b5176d9e 511
b5ecfcf0 512=head2 $req->headers
fc7ec1d9 513
3e19f4f6 514Returns an L<HTTP::Headers> object containing the headers for the current request.
fc7ec1d9 515
516 print $c->request->headers->header('X-Catalyst');
517
b5ecfcf0 518=head2 $req->hostname
0556eb49 519
178dca5f 520Returns the hostname of the client. Use C<< $req->uri->host >> to get the hostname of the server.
e5ecd5bc 521
b5ecfcf0 522=head2 $req->input
61bacdcc 523
3e19f4f6 524Alias for $req->body.
61bacdcc 525
3b4d1251 526=head2 $req->query_keywords
527
528Contains the keywords portion of a query string, when no '=' signs are
529present.
530
531 http://localhost/path?some+keywords
b0ad47c1 532
3b4d1251 533 $c->request->query_keywords will contain 'some keywords'
534
b5ecfcf0 535=head2 $req->match
fc7ec1d9 536
3e19f4f6 537This contains the matching part of a Regex action. Otherwise
2c83fd5a 538it returns the same as 'action', except for default actions,
539which return an empty string.
fc7ec1d9 540
b5ecfcf0 541=head2 $req->method
b5176d9e 542
543Contains the request method (C<GET>, C<POST>, C<HEAD>, etc).
544
b5ecfcf0 545=head2 $req->param
e7c0c583 546
b0ad47c1 547Returns GET and POST parameters with a CGI.pm-compatible param method. This
3e19f4f6 548is an alternative method for accessing parameters in $c->req->parameters.
e7c0c583 549
a82c2894 550 $value = $c->request->param( 'foo' );
551 @values = $c->request->param( 'foo' );
e7c0c583 552 @params = $c->request->param;
553
3e705254 554Like L<CGI>, and B<unlike> earlier versions of Catalyst, passing multiple
a82c2894 555arguments to this method, like this:
556
85d9fce6 557 $c->request->param( 'foo', 'bar', 'gorch', 'quxx' );
a82c2894 558
559will set the parameter C<foo> to the multiple values C<bar>, C<gorch> and
560C<quxx>. Previously this would have added C<bar> as another value to C<foo>
3e19f4f6 561(creating it if it didn't exist before), and C<quxx> as another value for
562C<gorch>.
a82c2894 563
83312afd 564B<NOTE> this is considered a legacy interface and care should be taken when
565using it. C<< scalar $c->req->param( 'foo' ) >> will return only the first
566C<foo> param even if multiple are present; C<< $c->req->param( 'foo' ) >> will
567return a list of as many are present, which can have unexpected consequences
568when writing code of the form:
569
570 $foo->bar(
571 a => 'b',
572 baz => $c->req->param( 'baz' ),
573 );
574
575If multiple C<baz> parameters are provided this code might corrupt data or
576cause a hash initialization error. For a more straightforward interface see
577C<< $c->req->parameters >>.
578
e7c0c583 579=cut
580
581sub param {
582 my $self = shift;
583
584 if ( @_ == 0 ) {
585 return keys %{ $self->parameters };
586 }
587
bfde09a2 588 if ( @_ == 1 ) {
e7c0c583 589
bfde09a2 590 my $param = shift;
6bd2b72c 591
bfde09a2 592 unless ( exists $self->parameters->{$param} ) {
593 return wantarray ? () : undef;
594 }
595
596 if ( ref $self->parameters->{$param} eq 'ARRAY' ) {
597 return (wantarray)
598 ? @{ $self->parameters->{$param} }
599 : $self->parameters->{$param}->[0];
600 }
601 else {
602 return (wantarray)
603 ? ( $self->parameters->{$param} )
604 : $self->parameters->{$param};
605 }
d7945f32 606 }
a82c2894 607 elsif ( @_ > 1 ) {
608 my $field = shift;
609 $self->parameters->{$field} = [@_];
d7945f32 610 }
e7c0c583 611}
b5176d9e 612
b5ecfcf0 613=head2 $req->parameters
61b1e958 614
3e19f4f6 615Returns a reference to a hash containing GET and POST parameters. Values can
d08ced28 616be either a scalar or an arrayref containing scalars.
fc7ec1d9 617
e7c0c583 618 print $c->request->parameters->{field};
619 print $c->request->parameters->{field}->[0];
fc7ec1d9 620
c436c1e8 621This is the combination of C<query_parameters> and C<body_parameters>.
622
b5ecfcf0 623=head2 $req->params
3e19f4f6 624
625Shortcut for $req->parameters.
626
b5ecfcf0 627=head2 $req->path
fc7ec1d9 628
3e19f4f6 629Returns the path, i.e. the part of the URI after $req->base, for the current request.
fc7ec1d9 630
be6801fa 631 http://localhost/path/foo
632
633 $c->request->path will contain 'path/foo'
634
b5ecfcf0 635=head2 $req->path_info
fbcc39ad 636
10011c19 637Alias for path, added for compatibility with L<CGI>.
fbcc39ad 638
639=cut
640
641sub path {
02fb5d78 642 my ( $self, @params ) = @_;
4f5ebacd 643
02fb5d78 644 if (@params) {
645 $self->uri->path(@params);
02570318 646 $self->_clear_path;
fbcc39ad 647 }
02570318 648 elsif ( $self->_has_path ) {
649 return $self->_path;
e561386f 650 }
02fb5d78 651 else {
652 my $path = $self->uri->path;
653 my $location = $self->base->path;
654 $path =~ s/^(\Q$location\E)?//;
655 $path =~ s/^\///;
02570318 656 $self->_path($path);
fbcc39ad 657
02fb5d78 658 return $path;
659 }
fbcc39ad 660}
661
b5ecfcf0 662=head2 $req->protocol
bfde09a2 663
3e19f4f6 664Returns the protocol (HTTP/1.0 or HTTP/1.1) used for the current request.
bfde09a2 665
b5ecfcf0 666=head2 $req->query_parameters
fbcc39ad 667
def54ce2 668=head2 $req->query_params
669
3e19f4f6 670Returns a reference to a hash containing query string (GET) parameters. Values can
fbcc39ad 671be either a scalar or an arrayref containing scalars.
672
673 print $c->request->query_parameters->{field};
674 print $c->request->query_parameters->{field}->[0];
b0ad47c1 675
b5ecfcf0 676=head2 $req->read( [$maxlength] )
fbcc39ad 677
3e19f4f6 678Reads a chunk of data from the request body. This method is intended to be
679used in a while loop, reading $maxlength bytes on every call. $maxlength
fbcc39ad 680defaults to the size of the request if not specified.
681
87f50436 682=head2 $req->read_chunk(\$buff, $max)
683
d7f18923 684Reads a chunk.
87f50436 685
9779c885 686You have to set MyApp->config(parse_on_demand => 1) to use this directly.
fbcc39ad 687
b5ecfcf0 688=head2 $req->referer
fc7ec1d9 689
3e19f4f6 690Shortcut for $req->headers->referer. Returns the referring page.
fc7ec1d9 691
b5ecfcf0 692=head2 $req->secure
bfde09a2 693
328f225e 694Returns true or false, indicating whether the connection is secure
d7f18923 695(https). The reliability of $req->secure may depend on your server
696configuration; Catalyst relies on PSGI to determine whether or not a
697request is secure (Catalyst looks at psgi.url_scheme), and different
698PSGI servers may make this determination in different ways (as by
699directly passing along information from the server, interpreting any of
700several HTTP headers, or using heuristics of their own).
bfde09a2 701
2982e768 702=head2 $req->captures
703
5c6a56e0 704Returns a reference to an array containing captured args from chained
705actions or regex captures.
fc7ec1d9 706
2982e768 707 my @captures = @{ $c->request->captures };
708
b5ecfcf0 709=head2 $req->upload
e7c0c583 710
3e19f4f6 711A convenient method to access $req->uploads.
e7c0c583 712
713 $upload = $c->request->upload('field');
714 @uploads = $c->request->upload('field');
715 @fields = $c->request->upload;
bfde09a2 716
e7c0c583 717 for my $upload ( $c->request->upload('field') ) {
146554c5 718 print $upload->filename;
e7c0c583 719 }
720
721=cut
722
723sub upload {
724 my $self = shift;
725
726 if ( @_ == 0 ) {
727 return keys %{ $self->uploads };
728 }
729
bfde09a2 730 if ( @_ == 1 ) {
e7c0c583 731
bfde09a2 732 my $upload = shift;
733
734 unless ( exists $self->uploads->{$upload} ) {
735 return wantarray ? () : undef;
736 }
6bd2b72c 737
bfde09a2 738 if ( ref $self->uploads->{$upload} eq 'ARRAY' ) {
739 return (wantarray)
740 ? @{ $self->uploads->{$upload} }
741 : $self->uploads->{$upload}->[0];
742 }
743 else {
744 return (wantarray)
fbcc39ad 745 ? ( $self->uploads->{$upload} )
746 : $self->uploads->{$upload};
bfde09a2 747 }
d7945f32 748 }
bfde09a2 749
a4f5c51e 750 if ( @_ > 1 ) {
bfde09a2 751
752 while ( my ( $field, $upload ) = splice( @_, 0, 2 ) ) {
753
754 if ( exists $self->uploads->{$field} ) {
755 for ( $self->uploads->{$field} ) {
756 $_ = [$_] unless ref($_) eq "ARRAY";
757 push( @$_, $upload );
758 }
759 }
760 else {
761 $self->uploads->{$field} = $upload;
762 }
763 }
e7c0c583 764 }
765}
766
b5ecfcf0 767=head2 $req->uploads
fc7ec1d9 768
bfde09a2 769Returns a reference to a hash containing uploads. Values can be either a
b0ad47c1 770L<Catalyst::Request::Upload> object, or an arrayref of
84e7aa89 771L<Catalyst::Request::Upload> objects.
e7c0c583 772
773 my $upload = $c->request->uploads->{field};
774 my $upload = $c->request->uploads->{field}->[0];
775
b5ecfcf0 776=head2 $req->uri
fbcc39ad 777
d26ee0d0 778Returns a L<URI> object for the current request. Stringifies to the URI text.
fbcc39ad 779
a375a206 780=head2 $req->mangle_params( { key => 'value' }, $appendmode);
bd917b94 781
a375a206 782Returns a hashref of parameters stemming from the current request's params,
783plus the ones supplied. Keys for which no current param exists will be
784added, keys with undefined values will be removed and keys with existing
785params will be replaced. Note that you can supply a true value as the final
786argument to change behavior with regards to existing parameters, appending
787values rather than replacing them.
788
789A quick example:
790
791 # URI query params foo=1
792 my $hashref = $req->mangle_params({ foo => 2 });
793 # Result is query params of foo=2
794
795versus append mode:
796
797 # URI query params foo=1
798 my $hashref = $req->mangle_params({ foo => 2 }, 1);
799 # Result is query params of foo=1&foo=2
800
801This is the code behind C<uri_with>.
bd917b94 802
803=cut
804
a375a206 805sub mangle_params {
806 my ($self, $args, $append) = @_;
b0ad47c1 807
a375a206 808 carp('No arguments passed to mangle_params()') unless $args;
fbb513f7 809
2f381252 810 foreach my $value ( values %$args ) {
d0f0fcf6 811 next unless defined $value;
fbb513f7 812 for ( ref $value eq 'ARRAY' ? @$value : $value ) {
813 $_ = "$_";
7066a4d5 814 utf8::encode( $_ ) if utf8::is_utf8($_);
fc42a730 815 }
fc42a730 816 };
b0ad47c1 817
a375a206 818 my %params = %{ $self->uri->query_form_hash };
819 foreach my $key (keys %{ $args }) {
820 my $val = $args->{$key};
821 if(defined($val)) {
822
823 if($append && exists($params{$key})) {
824
825 # This little bit of heaven handles appending a new value onto
826 # an existing one regardless if the existing value is an array
827 # or not, and regardless if the new value is an array or not
828 $params{$key} = [
829 ref($params{$key}) eq 'ARRAY' ? @{ $params{$key} } : $params{$key},
830 ref($val) eq 'ARRAY' ? @{ $val } : $val
831 ];
832
833 } else {
834 $params{$key} = $val;
835 }
836 } else {
837
838 # If the param wasn't defined then we delete it.
839 delete($params{$key});
840 }
841 }
842
843
844 return \%params;
845}
846
847=head2 $req->uri_with( { key => 'value' } );
848
849Returns a rewritten URI object for the current request. Key/value pairs
850passed in will override existing parameters. You can remove an existing
851parameter by passing in an undef value. Unmodified pairs will be
852preserved.
853
854You may also pass an optional second parameter that puts C<uri_with> into
855append mode:
856
857 $req->uri_with( { key => 'value' }, { mode => 'append' } );
9779c885 858
a375a206 859See C<mangle_params> for an explanation of this behavior.
860
861=cut
862
863sub uri_with {
864 my( $self, $args, $behavior) = @_;
865
866 carp( 'No arguments passed to uri_with()' ) unless $args;
867
868 my $append = 0;
869 if((ref($behavior) eq 'HASH') && defined($behavior->{mode}) && ($behavior->{mode} eq 'append')) {
870 $append = 1;
871 }
872
873 my $params = $self->mangle_params($args, $append);
874
875 my $uri = $self->uri->clone;
876 $uri->query_form($params);
2f381252 877
bd917b94 878 return $uri;
879}
880
8026359e 881=head2 $req->remote_user
882
883Returns the value of the C<REMOTE_USER> environment variable.
7ce7ca2e 884
b5ecfcf0 885=head2 $req->user_agent
b5176d9e 886
3e19f4f6 887Shortcut to $req->headers->user_agent. Returns the user agent (browser)
888version string.
b5176d9e 889
eb1f4b49 890=head2 $req->io_fh
891
892Returns a psgix.io bidirectional socket, if your server supports one. Used for
893when you want to jailbreak out of PSGI and handle bidirectional client server
894communication manually, such as when you are using cometd or websockets.
895
47b9d68e 896=head1 SETUP METHODS
897
898You should never need to call these yourself in application code,
899however they are useful if extending Catalyst by applying a request role.
900
901=head2 $self->prepare_headers()
902
903Sets up the C<< $res->headers >> accessor.
904
905=head2 $self->prepare_body()
906
907Sets up the body using L<HTTP::Body>
908
909=head2 $self->prepare_body_chunk()
910
911Add a chunk to the request body.
912
913=head2 $self->prepare_body_parameters()
914
915Sets up parameters from body.
916
8738b8fe 917=head2 $self->prepare_cookies()
47b9d68e 918
919Parse cookies from header. Sets up a L<CGI::Simple::Cookie> object.
920
8738b8fe 921=head2 $self->prepare_connection()
922
923Sets up various fields in the request like the local and remote addresses,
f59eeb09 924request method, hostname requested etc.
8738b8fe 925
926=head2 $self->prepare_parameters()
927
928Ensures that the body has been parsed, then builds the parameters, which are
929combined from those in the request and those in the body.
930
11e7af55 931If parameters have already been set will clear the parameters and build them again.
932
8738b8fe 933
059c085b 934=head2 meta
935
936Provided by Moose
937
3e19f4f6 938=head1 AUTHORS
fc7ec1d9 939
2f381252 940Catalyst Contributors, see Catalyst.pm
fc7ec1d9 941
942=head1 COPYRIGHT
943
536bee89 944This library is free software. You can redistribute it and/or modify
61b1e958 945it under the same terms as Perl itself.
fc7ec1d9 946
947=cut
948
e5ecd5bc 949__PACKAGE__->meta->make_immutable;
950
fc7ec1d9 9511;