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