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