21a26bffe3a5d53a43fa49f8138a6cb6d8474210
[catagits/Catalyst-Runtime.git] / lib / Catalyst / Request.pm
1 package Catalyst::Request;
2
3 use Class::C3;
4 use IO::Socket qw[AF_INET inet_aton];
5 use Carp;
6 use utf8;
7 use URI::http;
8 use URI::https;
9 use URI::QueryParam;
10 use HTTP::Headers;
11
12 use Moose;
13
14 has action => (is => 'rw');
15 has address => (is => 'rw');
16 has arguments => (is => 'rw', default => sub { [] });
17 has cookies => (is => 'rw', default => sub { {} });
18 has query_keywords => (is => 'rw');
19 has match => (is => 'rw');
20 has method => (is => 'rw');
21 has protocol => (is => 'rw');
22 has query_parameters  => (is => 'rw', default => sub { {} });
23 has secure => (is => 'rw', default => 0);
24 has captures => (is => 'rw', default => sub { [] });
25 has uri => (is => 'rw');
26 has user => (is => 'rw');
27 has headers => (
28   is      => 'rw',
29   isa     => 'HTTP::Headers',
30   handles => [qw(content_encoding content_length content_type header referer user_agent)],
31   default => sub { HTTP::Headers->new() },
32   required => 1,
33   lazy => 1,
34 );
35
36 #Moose ToDo:
37 #can we lose the before modifiers which just call prepare_body ?
38 #they are wasteful, slow us down and feel cluttery.
39 # Can we call prepare_body at BUILD time?
40 # Can we make _body an attribute and have the rest of these lazy build from there?
41
42 has _context => (
43   is => 'rw',
44   weak_ref => 1,
45   handles => ['read'],
46 );
47
48 has body_parameters => (
49   is => 'rw',
50   required => 1,
51   lazy => 1,
52   default => sub { {} },
53 );
54
55 before body_parameters => sub {
56   my ($self) = @_;
57   $self->_context->prepare_body();
58 };
59
60 has uploads => (
61   is => 'rw',
62   required => 1,
63   lazy => 1,
64   default => sub { {} },
65 );
66
67 # modifier was a noop (groditi)
68 # before uploads => sub {
69 #   my ($self) = @_;
70 #   #$self->_context->prepare_body;
71 # };
72
73 has parameters => (
74   is => 'rw',
75   required => 1,
76   lazy => 1,
77   default => sub { {} },
78 );
79
80 before parameters => sub {
81   my ($self, $params) = @_;
82   #$self->_context->prepare_body();
83   if ( $params && !ref $params ) {
84     $self->_context->log->warn(
85         "Attempt to retrieve '$params' with req->params(), " .
86         "you probably meant to call req->param('$params')" );
87     $params = undef;
88   }
89
90 };
91
92 has base => (
93   is => 'rw',
94   required => 1,
95   lazy => 1,
96   default => sub {
97     my $self = shift;
98     return $self->path if $self->uri;
99   },
100 );
101
102 has body => (
103   is => 'rw'
104 );
105
106 before body => sub {
107   my ($self) = @_;
108   $self->_context->prepare_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 )
118   },
119 );
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         undef $self->{path};
411     }
412     elsif ( defined( my $path = $self->{path} ) ) {
413         return $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 regex captures.
459
460     my @captures = @{ $c->request->captures };
461
462 =head2 $req->snippets
463
464 C<captures> used to be called snippets. This is still available for backwoards
465 compatibility, but is considered deprecated.
466
467 =head2 $req->upload
468
469 A convenient method to access $req->uploads.
470
471     $upload  = $c->request->upload('field');
472     @uploads = $c->request->upload('field');
473     @fields  = $c->request->upload;
474
475     for my $upload ( $c->request->upload('field') ) {
476         print $upload->filename;
477     }
478
479 =cut
480
481 sub upload {
482     my $self = shift;
483
484     if ( @_ == 0 ) {
485         return keys %{ $self->uploads };
486     }
487
488     if ( @_ == 1 ) {
489
490         my $upload = shift;
491
492         unless ( exists $self->uploads->{$upload} ) {
493             return wantarray ? () : undef;
494         }
495
496         if ( ref $self->uploads->{$upload} eq 'ARRAY' ) {
497             return (wantarray)
498               ? @{ $self->uploads->{$upload} }
499               : $self->uploads->{$upload}->[0];
500         }
501         else {
502             return (wantarray)
503               ? ( $self->uploads->{$upload} )
504               : $self->uploads->{$upload};
505         }
506     }
507
508     if ( @_ > 1 ) {
509
510         while ( my ( $field, $upload ) = splice( @_, 0, 2 ) ) {
511
512             if ( exists $self->uploads->{$field} ) {
513                 for ( $self->uploads->{$field} ) {
514                     $_ = [$_] unless ref($_) eq "ARRAY";
515                     push( @$_, $upload );
516                 }
517             }
518             else {
519                 $self->uploads->{$field} = $upload;
520             }
521         }
522     }
523 }
524
525 =head2 $req->uploads
526
527 Returns a reference to a hash containing uploads. Values can be either a
528 L<Catalyst::Request::Upload> object, or an arrayref of 
529 L<Catalyst::Request::Upload> objects.
530
531     my $upload = $c->request->uploads->{field};
532     my $upload = $c->request->uploads->{field}->[0];
533
534 =head2 $req->uri
535
536 Returns a URI object for the current request. Stringifies to the URI text.
537
538 =head2 $req->uri_with( { key => 'value' } );
539
540 Returns a rewritten URI object for the current request. Key/value pairs
541 passed in will override existing parameters. 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     for 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     
561     $uri->query_form( {
562         %{ $uri->query_form_hash },
563         %$args
564     } );
565     return $uri;
566 }
567
568 =head2 $req->user
569
570 Returns the currently logged in user. Deprecated. The method recommended for
571 newer plugins is $c->user.
572
573 =head2 $req->user_agent
574
575 Shortcut to $req->headers->user_agent. Returns the user agent (browser)
576 version string.
577
578 =head2 meta
579
580 Provided by Moose
581
582 =head1 AUTHORS
583
584 Sebastian Riedel, C<sri@cpan.org>
585
586 Marcus Ramberg, C<mramberg@cpan.org>
587
588 =head1 COPYRIGHT
589
590 This program is free software, you can redistribute it and/or modify
591 it under the same terms as Perl itself.
592
593 =cut
594
595 __PACKAGE__->meta->make_immutable;
596
597 1;