mro compat stuff
[catagits/Catalyst-Runtime.git] / lib / Catalyst / Request.pm
1 package Catalyst::Request;
2
3 use MRO::Compat;
4 use mro 'c3';
5 use IO::Socket qw[AF_INET inet_aton];
6 use Carp;
7 use utf8;
8 use URI::http;
9 use URI::https;
10 use URI::QueryParam;
11 use HTTP::Headers;
12
13 use Moose;
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');
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 and have the rest of these lazy build from there?
42
43 has _context => (
44   is => 'rw',
45   weak_ref => 1,
46   handles => ['read'],
47 );
48
49 has body_parameters => (
50   is => 'rw',
51   required => 1,
52   lazy => 1,
53   default => sub { {} },
54 );
55
56 before body_parameters => sub {
57   my ($self) = @_;
58   $self->_context->prepare_body();
59 };
60
61 has uploads => (
62   is => 'rw',
63   required => 1,
64   lazy => 1,
65   default => sub { {} },
66 );
67
68 # modifier was a noop (groditi)
69 # before uploads => sub {
70 #   my ($self) = @_;
71 #   #$self->_context->prepare_body;
72 # };
73
74 has parameters => (
75   is => 'rw',
76   required => 1,
77   lazy => 1,
78   default => sub { {} },
79 );
80
81 before parameters => sub {
82   my ($self, $params) = @_;
83   #$self->_context->prepare_body();
84   if ( $params && !ref $params ) {
85     $self->_context->log->warn(
86         "Attempt to retrieve '$params' with req->params(), " .
87         "you probably meant to call req->param('$params')" );
88     $params = undef;
89   }
90
91 };
92
93 has base => (
94   is => 'rw',
95   required => 1,
96   lazy => 1,
97   default => sub {
98     my $self = shift;
99     return $self->path if $self->uri;
100   },
101 );
102
103 has body => (
104   is => 'rw'
105 );
106
107 before body => sub {
108   my ($self) = @_;
109   $self->_context->prepare_body();
110 };
111
112 has hostname => (
113   is        => 'rw',
114   required  => 1,
115   lazy      => 1,
116   default   => sub {
117     my ($self) = @_;
118     gethostbyaddr( inet_aton( $self->address ), AF_INET )
119   },
120 );
121
122 no Moose;
123
124 sub args            { shift->arguments(@_) }
125 sub body_params     { shift->body_parameters(@_) }
126 sub input           { shift->body(@_) }
127 sub params          { shift->parameters(@_) }
128 sub query_params    { shift->query_parameters(@_) }
129 sub path_info       { shift->path(@_) }
130 sub snippets        { shift->captures(@_) }
131
132 =head1 NAME
133
134 Catalyst::Request - provides information about the current client request
135
136 =head1 SYNOPSIS
137
138     $req = $c->request;
139     $req->action;
140     $req->address;
141     $req->arguments;
142     $req->args;
143     $req->base;
144     $req->body;
145     $req->body_parameters;
146     $req->content_encoding;
147     $req->content_length;
148     $req->content_type;
149     $req->cookie;
150     $req->cookies;
151     $req->header;
152     $req->headers;
153     $req->hostname;
154     $req->input;
155     $req->query_keywords;
156     $req->match;
157     $req->method;
158     $req->param;
159     $req->parameters;
160     $req->params;
161     $req->path;
162     $req->protocol;
163     $req->query_parameters;
164     $req->read;
165     $req->referer;
166     $req->secure;
167     $req->captures; # previously knows as snippets
168     $req->upload;
169     $req->uploads;
170     $req->uri;
171     $req->user;
172     $req->user_agent;
173
174 See also L<Catalyst>, L<Catalyst::Request::Upload>.
175
176 =head1 DESCRIPTION
177
178 This is the Catalyst Request class, which provides an interface to data for the
179 current client request. The request object is prepared by L<Catalyst::Engine>,
180 thus hiding the details of the particular engine implementation.
181
182 =head1 METHODS
183
184 =head2 $req->action
185
186 [DEPRECATED] Returns the name of the requested action.
187
188
189 Use C<< $c->action >> instead (which returns a
190 L<Catalyst::Action|Catalyst::Action> object).
191
192 =head2 $req->address
193
194 Returns the IP address of the client.
195
196 =head2 $req->arguments
197
198 Returns a reference to an array containing the arguments.
199
200     print $c->request->arguments->[0];
201
202 For example, if your action was
203
204     package MyApp::C::Foo;
205
206     sub moose : Local {
207         ...
208     }
209
210 and the URI for the request was C<http://.../foo/moose/bah>, the string C<bah>
211 would be the first and only argument.
212
213 =head2 $req->args
214
215 Shortcut for arguments.
216
217 =head2 $req->base
218
219 Contains the URI base. This will always have a trailing slash.
220
221 If your application was queried with the URI
222 C<http://localhost:3000/some/path> then C<base> is C<http://localhost:3000/>.
223
224 =head2 $req->body
225
226 Returns the message body of the request, unless Content-Type is
227 C<application/x-www-form-urlencoded> or C<multipart/form-data>.
228
229 =head2 $req->body_parameters
230
231 Returns a reference to a hash containing body (POST) parameters. Values can
232 be either a scalar or an arrayref containing scalars.
233
234     print $c->request->body_parameters->{field};
235     print $c->request->body_parameters->{field}->[0];
236
237 These are the parameters from the POST part of the request, if any.
238
239 =head2 $req->body_params
240
241 Shortcut for body_parameters.
242
243 =head2 $req->content_encoding
244
245 Shortcut for $req->headers->content_encoding.
246
247 =head2 $req->content_length
248
249 Shortcut for $req->headers->content_length.
250
251 =head2 $req->content_type
252
253 Shortcut for $req->headers->content_type.
254
255 =head2 $req->cookie
256
257 A convenient method to access $req->cookies.
258
259     $cookie  = $c->request->cookie('name');
260     @cookies = $c->request->cookie;
261
262 =cut
263
264 sub cookie {
265     my $self = shift;
266
267     if ( @_ == 0 ) {
268         return keys %{ $self->cookies };
269     }
270
271     if ( @_ == 1 ) {
272
273         my $name = shift;
274
275         unless ( exists $self->cookies->{$name} ) {
276             return undef;
277         }
278
279         return $self->cookies->{$name};
280     }
281 }
282
283 =head2 $req->cookies
284
285 Returns a reference to a hash containing the cookies.
286
287     print $c->request->cookies->{mycookie}->value;
288
289 The cookies in the hash are indexed by name, and the values are L<CGI::Cookie>
290 objects.
291
292 =head2 $req->header
293
294 Shortcut for $req->headers->header.
295
296 =head2 $req->headers
297
298 Returns an L<HTTP::Headers> object containing the headers for the current request.
299
300     print $c->request->headers->header('X-Catalyst');
301
302 =head2 $req->hostname
303
304 Returns the hostname of the client.
305
306 =head2 $req->input
307
308 Alias for $req->body.
309
310 =head2 $req->query_keywords
311
312 Contains the keywords portion of a query string, when no '=' signs are
313 present.
314
315     http://localhost/path?some+keywords
316     
317     $c->request->query_keywords will contain 'some keywords'
318
319 =head2 $req->match
320
321 This contains the matching part of a Regex action. Otherwise
322 it returns the same as 'action', except for default actions,
323 which return an empty string.
324
325 =head2 $req->method
326
327 Contains the request method (C<GET>, C<POST>, C<HEAD>, etc).
328
329 =head2 $req->param
330
331 Returns GET and POST parameters with a CGI.pm-compatible param method. This 
332 is an alternative method for accessing parameters in $c->req->parameters.
333
334     $value  = $c->request->param( 'foo' );
335     @values = $c->request->param( 'foo' );
336     @params = $c->request->param;
337
338 Like L<CGI>, and B<unlike> earlier versions of Catalyst, passing multiple
339 arguments to this method, like this:
340
341     $c->request->param( 'foo', 'bar', 'gorch', 'quxx' );
342
343 will set the parameter C<foo> to the multiple values C<bar>, C<gorch> and
344 C<quxx>. Previously this would have added C<bar> as another value to C<foo>
345 (creating it if it didn't exist before), and C<quxx> as another value for
346 C<gorch>.
347
348 =cut
349
350 sub param {
351     my $self = shift;
352
353     if ( @_ == 0 ) {
354         return keys %{ $self->parameters };
355     }
356
357     if ( @_ == 1 ) {
358
359         my $param = shift;
360
361         unless ( exists $self->parameters->{$param} ) {
362             return wantarray ? () : undef;
363         }
364
365         if ( ref $self->parameters->{$param} eq 'ARRAY' ) {
366             return (wantarray)
367               ? @{ $self->parameters->{$param} }
368               : $self->parameters->{$param}->[0];
369         }
370         else {
371             return (wantarray)
372               ? ( $self->parameters->{$param} )
373               : $self->parameters->{$param};
374         }
375     }
376     elsif ( @_ > 1 ) {
377         my $field = shift;
378         $self->parameters->{$field} = [@_];
379     }
380 }
381
382 =head2 $req->parameters
383
384 Returns a reference to a hash containing GET and POST parameters. Values can
385 be either a scalar or an arrayref containing scalars.
386
387     print $c->request->parameters->{field};
388     print $c->request->parameters->{field}->[0];
389
390 This is the combination of C<query_parameters> and C<body_parameters>.
391
392 =head2 $req->params
393
394 Shortcut for $req->parameters.
395
396 =head2 $req->path
397
398 Returns the path, i.e. the part of the URI after $req->base, for the current request.
399
400 =head2 $req->path_info
401
402 Alias for path, added for compability with L<CGI>.
403
404 =cut
405
406 sub path {
407     my ( $self, @params ) = @_;
408
409     if (@params) {
410         $self->uri->path(@params);
411         undef $self->{path};
412     }
413     elsif ( defined( my $path = $self->{path} ) ) {
414         return $path;
415     }
416     else {
417         my $path     = $self->uri->path;
418         my $location = $self->base->path;
419         $path =~ s/^(\Q$location\E)?//;
420         $path =~ s/^\///;
421         $self->{path} = $path;
422
423         return $path;
424     }
425 }
426
427 =head2 $req->protocol
428
429 Returns the protocol (HTTP/1.0 or HTTP/1.1) used for the current request.
430
431 =head2 $req->query_parameters
432
433 =head2 $req->query_params
434
435 Returns a reference to a hash containing query string (GET) parameters. Values can
436 be either a scalar or an arrayref containing scalars.
437
438     print $c->request->query_parameters->{field};
439     print $c->request->query_parameters->{field}->[0];
440     
441 =head2 $req->read( [$maxlength] )
442
443 Reads a chunk of data from the request body. This method is intended to be
444 used in a while loop, reading $maxlength bytes on every call. $maxlength
445 defaults to the size of the request if not specified.
446
447 You have to set MyApp->config->{parse_on_demand} to use this directly.
448
449 =head2 $req->referer
450
451 Shortcut for $req->headers->referer. Returns the referring page.
452
453 =head2 $req->secure
454
455 Returns true or false, indicating whether the connection is secure (https).
456
457 =head2 $req->captures
458
459 Returns a reference to an array containing 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. Unmodified pairs will be
543 preserved.
544
545 =cut
546
547 sub uri_with {
548     my( $self, $args ) = @_;
549     
550     carp( 'No arguments passed to uri_with()' ) unless $args;
551
552     for my $value ( values %$args ) {
553         next unless defined $value;
554         for ( ref $value eq 'ARRAY' ? @$value : $value ) {
555             $_ = "$_";
556             utf8::encode( $_ ) if utf8::is_utf8($_);
557         }
558     };
559     
560     my $uri = $self->uri->clone;
561     
562     $uri->query_form( {
563         %{ $uri->query_form_hash },
564         %$args
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 Sebastian Riedel, C<sri@cpan.org>
586
587 Marcus Ramberg, C<mramberg@cpan.org>
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;