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