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