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