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