WrapCGI - file uploads support
[catagits/Catalyst-Controller-WrapCGI.git] / lib / Catalyst / Controller / WrapCGI.pm
CommitLineData
71e6daf6 1package Catalyst::Controller::WrapCGI;
b2a17df2 2
9cd47364 3use Moose;
4use mro 'c3';
5
6extends 'Catalyst::Controller';
b2a17df2 7
0d83c5de 8use HTTP::Request::AsCGI ();
9use HTTP::Request ();
10use URI ();
21a20b7e 11use Catalyst::Exception ();
f410f043 12use URI::Escape;
16db0bfc 13use HTTP::Request::Common;
f410f043 14
15use namespace::clean -except => 'meta';
32b32c62 16
17=head1 NAME
18
19Catalyst::Controller::WrapCGI - Run CGIs in Catalyst
20
21=head1 VERSION
22
16db0bfc 23Version 0.0033
32b32c62 24
25=cut
26
16db0bfc 27our $VERSION = '0.0033';
32b32c62 28
29=head1 SYNOPSIS
30
31 package MyApp::Controller::Foo;
32
33 use parent qw/Catalyst::Controller::WrapCGI/;
12d29ebf 34 use CGI ();
32b32c62 35
36 sub hello : Path('cgi-bin/hello.cgi') {
37 my ($self, $c) = @_;
38
39 $self->cgi_to_response($c, sub {
12d29ebf 40 my $q = CGI->new;
41 print $q->header, $q->start_html('Hello'),
42 $q->h1('Catalyst Rocks!'),
43 $q->end_html;
32b32c62 44 });
45 }
46
457c1d76 47In your .conf, configure which environment variables to pass:
48
49 <Controller::Foo>
50 <CGI>
21a20b7e 51 username_field username # used for REMOTE_USER env var
457c1d76 52 pass_env PERL5LIB
53 pass_env PATH
21a20b7e 54 pass_env /^MYAPP_/
c212b57b 55 kill_env MOD_PERL
457c1d76 56 </CGI>
57 </Controller::Foo>
58
59=head1 DESCRIPTION
60
61Allows you to run Perl code in a CGI environment derived from your L<Catalyst>
62context.
63
12d29ebf 64B<*WARNING*>: do not export L<CGI> functions into a Controller, it will break
65with L<Catalyst> 5.8 onward.
66
21a20b7e 67If you just want to run CGIs from files, see L<Catalyst::Controller::CGIBin>.
68
69=head1 CONFIGURATION
70
c212b57b 71C<< $your_controller->{CGI}{pass_env} >> should be an array of environment variables
21a20b7e 72or regular expressions to pass through to your CGIs. Entries surrounded by C</>
73characters are considered regular expressions.
74
c212b57b 75C<< $your_controller->{CGI}{kill_env} >> should be an array of environment
76variables or regular expressions to remove from the environment before passing
77it to your CGIs. Entries surrounded by C</> characters are considered regular
78expressions.
21a20b7e 79
a032b7f8 80Default is to pass the whole of C<%ENV>, except for C<MOD_PERL> and
81C<CONTENT_TYPE> (that is, the default C<kill_env> is C<[ qw(MOD_PERL
82CONTENT_TYPE) ]>.
c212b57b 83
84C<< $your_controller->{CGI}{username_field} >> should be the field for your user's name, which will be
85read from C<< $c->user->obj >>. Defaults to 'username'.
21a20b7e 86
87See L</SYNOPSIS> for an example.
88
32b32c62 89=cut
b2a17df2 90
91# Hack-around because Catalyst::Engine::HTTP goes and changes
92# them to be the remote socket, and FCGI.pm does even dumber things.
93
32b32c62 94open my $REAL_STDIN, "<&=".fileno(*STDIN);
95open my $REAL_STDOUT, ">>&=".fileno(*STDOUT);
96
97=head1 METHODS
98
f410f043 99=head2 cgi_to_response
100
101C<<$self->cgi_to_response($c, $coderef)>>
32b32c62 102
103Does the magic of running $coderef in a CGI environment, and populating the
104appropriate parts of your Catalyst context with the results.
105
f410f043 106Calls L</wrap_cgi>.
457c1d76 107
32b32c62 108=cut
b2a17df2 109
110sub cgi_to_response {
111 my ($self, $c, $script) = @_;
0d83c5de 112
b2a17df2 113 my $res = $self->wrap_cgi($c, $script);
114
115 # if the CGI doesn't set the response code but sets location they were
116 # probably trying to redirect so set 302 for them
117
32b32c62 118 my $location = $res->headers->header('Location');
119
120 if (defined $location && length $location && $res->code == 200) {
b2a17df2 121 $c->res->status(302);
122 } else {
123 $c->res->status($res->code);
124 }
125 $c->res->body($res->content);
126 $c->res->headers($res->headers);
127}
128
f410f043 129=head2 wrap_cgi
130
131C<<$self->wrap_cgi($c, $coderef)>>
32b32c62 132
133Runs $coderef in a CGI environment using L<HTTP::Request::AsCGI>, returns an
134L<HTTP::Response>.
135
136The CGI environment is set up based on $c.
137
457c1d76 138The environment variables to pass on are taken from the configuration for your
139Controller, see L</SYNOPSIS> for an example. If you don't supply a list of
140environment variables to pass, the whole of %ENV is used.
141
f410f043 142Used by L</cgi_to_response>, which is probably what you want to use as well.
32b32c62 143
144=cut
145
b2a17df2 146sub wrap_cgi {
147 my ($self, $c, $call) = @_;
148 my $req = HTTP::Request->new(
149 map { $c->req->$_ } qw/method uri headers/
150 );
151 my $body = $c->req->body;
152 my $body_content = '';
153
154 $req->content_type($c->req->content_type); # set this now so we can override
155
156 if ($body) { # Slurp from body filehandle
157 local $/; $body_content = <$body>;
158 } else {
159 my $body_params = $c->req->body_parameters;
16db0bfc 160
161 if (my %uploads = %{ $c->req->uploads }) {
162 my $post = POST 'http://localhost/',
163 Content_Type => 'form-data',
164 Content => [
165 %$body_params,
166 map {
167 my $upl = $uploads{$_};
168 $_ => [
169 undef,
170 $upl->filename,
171 Content => $upl->slurp,
172 'Content-Type' => $upl->type || 'application/octet-stream',
173 map (
174 $_ => $upl->headers->header($_)
175 ), grep !/^Content-(?:Type|Disposition)$/,
176 $upl->headers->header_field_names
177 ]
178 } keys %uploads
179 ];
180 $body_content = $post->content;
181 $req->content_type($post->header('Content-Type'));
182 } elsif (%$body_params) {
32b32c62 183 my $encoder = URI->new;
184 $encoder->query_form(%$body_params);
185 $body_content = $encoder->query;
b2a17df2 186 $req->content_type('application/x-www-form-urlencoded');
187 }
188 }
189
c212b57b 190 my $filtered_env = $self->_filtered_env(\%ENV);
457c1d76 191
b2a17df2 192 $req->content($body_content);
193 $req->content_length(length($body_content));
21a20b7e 194
195 my $username_field = $self->{CGI}{username_field} || 'username';
196
197 my $username = (($c->can('user_exists') && $c->user_exists)
198 ? eval { $c->user->obj->$username_field }
b2a17df2 199 : '');
0d83c5de 200
f410f043 201 my $path_info = '/'.join '/' => map uri_escape_utf8($_), @{ $c->req->args };
0d83c5de 202
b2a17df2 203 my $env = HTTP::Request::AsCGI->new(
204 $req,
21a20b7e 205 ($username ? (REMOTE_USER => $username) : ()),
c212b57b 206 %$filtered_env,
f410f043 207 PATH_INFO => $path_info,
208 FILEPATH_INFO => '/'.$c->action.$path_info, # eww
209 SCRIPT_NAME => $c->uri_for($c->action)->path
b2a17df2 210 );
211
212 {
32b32c62 213 local *STDIN = $REAL_STDIN; # restore the real ones so the filenos
214 local *STDOUT = $REAL_STDOUT; # are 0 and 1 for the env setup
b2a17df2 215
32b32c62 216 my $old = select($REAL_STDOUT); # in case somebody just calls 'print'
b2a17df2 217
218 my $saved_error;
219
220 $env->setup;
221 eval { $call->() };
222 $saved_error = $@;
223 $env->restore;
224
225 select($old);
226
21a20b7e 227 Catalyst::Exception->throw(
228 message => "CGI invocation failed: $saved_error"
229 ) if $saved_error;
b2a17df2 230 }
231
232 return $env->response;
233}
234
0d83c5de 235sub _filtered_env {
236 my ($self, $env) = @_;
237 my @ok;
238
239 my $pass_env = $self->{CGI}{pass_env};
240 $pass_env = [] if not defined $pass_env;
241 $pass_env = [ $pass_env ] unless ref $pass_env;
242
243 my $kill_env = $self->{CGI}{kill_env};
a032b7f8 244 $kill_env = [ 'MOD_PERL', 'CONTENT_TYPE' ] unless defined $kill_env;
0d83c5de 245 $kill_env = [ $kill_env ] unless ref $kill_env;
246
247 if (@$pass_env) {
248 for (@$pass_env) {
249 if (m!^/(.*)/\z!) {
250 my $re = qr/$1/;
251 push @ok, grep /$re/, keys %$env;
252 } else {
253 push @ok, $_;
254 }
255 }
256 } else {
257 @ok = keys %$env;
258 }
259
260 for my $k (@$kill_env) {
261 if ($k =~ m!^/(.*)/\z!) {
262 my $re = qr/$1/;
263 @ok = grep { ! /$re/ } @ok;
264 } else {
265 @ok = grep { $_ ne $k } @ok;
266 }
267 }
268 return { map {; $_ => $env->{$_} } @ok };
269}
270
f410f043 271__PACKAGE__->meta->make_immutable;
0d83c5de 272
32b32c62 273=head1 ACKNOWLEDGEMENTS
274
275Original development sponsored by L<http://www.altinity.com/>
276
457c1d76 277=head1 SEE ALSO
278
21a20b7e 279L<Catalyst::Controller::CGIBin>, L<CatalystX::GlobalContext>,
457c1d76 280L<Catalyst::Controller>, L<CGI>, L<Catalyst>
281
0d83c5de 282=head1 AUTHORS
283
284Originally written by:
32b32c62 285
286Matt S. Trout, C<< <mst at shadowcat.co.uk> >>
287
0d83c5de 288Contributors:
289
290Rafael Kitover C<< <rkitover at cpan.org> >>
291
292Hans Dieter Pearcey C<< <hdp at cpan.org> >>
293
32b32c62 294=head1 BUGS
295
296Please report any bugs or feature requests to C<bug-catalyst-controller-wrapcgi
297at rt.cpan.org>, or through the web interface at
298L<http://rt.cpan.org/NoAuth/ReportBug.html?Queue=Catalyst-Controller-WrapCGI>.
299I will be notified, and then you'll automatically be notified of progress on
300your bug as I make changes.
301
302=head1 SUPPORT
303
304More information at:
305
306=over 4
307
308=item * RT: CPAN's request tracker
309
310L<http://rt.cpan.org/NoAuth/Bugs.html?Dist=Catalyst-Controller-WrapCGI>
311
312=item * AnnoCPAN: Annotated CPAN documentation
313
314L<http://annocpan.org/dist/Catalyst-Controller-WrapCGI>
315
316=item * CPAN Ratings
317
318L<http://cpanratings.perl.org/d/Catalyst-Controller-WrapCGI>
319
320=item * Search CPAN
321
322L<http://search.cpan.org/dist/Catalyst-Controller-WrapCGI>
323
324=back
325
326=head1 COPYRIGHT & LICENSE
327
328Copyright (c) 2008 Matt S. Trout
329
330This program is free software; you can redistribute it and/or modify it
331under the same terms as Perl itself.
332
333=cut
334
3351; # End of Catalyst::Controller::WrapCGI
336
21a20b7e 337# vim: expandtab shiftwidth=2 ts=2 tw=80: