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