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