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