WrapCGI: fix missing dep on namespace::clean
[catagits/Catalyst-Controller-WrapCGI.git] / lib / Catalyst / Controller / WrapCGI.pm
1 package Catalyst::Controller::WrapCGI;
2
3 use strict;
4 use warnings;
5 use parent 'Catalyst::Controller';
6
7 use HTTP::Request::AsCGI;
8 use HTTP::Request;
9 use URI;
10 use Catalyst::Exception ();
11
12 =head1 NAME
13
14 Catalyst::Controller::WrapCGI - Run CGIs in Catalyst
15
16 =head1 VERSION
17
18 Version 0.0026
19
20 =cut
21
22 our $VERSION = '0.0026';
23
24 =head1 SYNOPSIS
25
26     package MyApp::Controller::Foo;
27
28     use parent qw/Catalyst::Controller::WrapCGI/;
29     use CGI ();
30
31     sub hello : Path('cgi-bin/hello.cgi') {
32         my ($self, $c) = @_;
33
34         $self->cgi_to_response($c, sub {
35             my $q = CGI->new;
36             print $q->header, $q->start_html('Hello'),
37                 $q->h1('Catalyst Rocks!'),
38                 $q->end_html;
39         });
40     }
41
42 In your .conf, configure which environment variables to pass:
43
44     <Controller::Foo>
45         <CGI>
46             username_field username # used for REMOTE_USER env var
47             pass_env PERL5LIB
48             pass_env PATH
49             pass_env /^MYAPP_/
50         </CGI>
51     </Controller::Foo>
52
53 =head1 DESCRIPTION
54
55 Allows you to run Perl code in a CGI environment derived from your L<Catalyst>
56 context.
57
58 B<*WARNING*>: do not export L<CGI> functions into a Controller, it will break
59 with L<Catalyst> 5.8 onward.
60
61 If you just want to run CGIs from files, see L<Catalyst::Controller::CGIBin>.
62
63 =head1 CONFIGURATION
64
65 C<$your_controller->{CGI}{pass_env}> should be an array of environment variables
66 or regular expressions to pass through to your CGIs. Entries surrounded by C</>
67 characters are considered regular expressions.
68
69 Default is to pass the whole of C<%ENV>.
70
71 C<{CGI}{username_field}> should be the field for your user's name, which will be
72 read from C<$c->user->obj>. Defaults to 'username'.
73
74 See L</SYNOPSIS> for an example.
75
76 =cut
77
78 # Hack-around because Catalyst::Engine::HTTP goes and changes
79 # them to be the remote socket, and FCGI.pm does even dumber things.
80
81 open my $REAL_STDIN, "<&=".fileno(*STDIN);
82 open my $REAL_STDOUT, ">>&=".fileno(*STDOUT);
83
84 =head1 METHODS
85
86 =head2 $self->cgi_to_response($c, $coderef)
87
88 Does the magic of running $coderef in a CGI environment, and populating the
89 appropriate parts of your Catalyst context with the results.
90
91 Calls wrap_cgi (below.)
92
93 =cut
94
95 sub cgi_to_response {
96   my ($self, $c, $script) = @_;
97   my $res = $self->wrap_cgi($c, $script);
98
99   # if the CGI doesn't set the response code but sets location they were
100   # probably trying to redirect so set 302 for them
101
102   my $location = $res->headers->header('Location');
103
104   if (defined $location && length $location && $res->code == 200) {
105     $c->res->status(302);
106   } else { 
107     $c->res->status($res->code);
108   }
109   $c->res->body($res->content);
110   $c->res->headers($res->headers);
111 }
112
113 =head2 $self->wrap_cgi($c, $coderef)
114
115 Runs $coderef in a CGI environment using L<HTTP::Request::AsCGI>, returns an
116 L<HTTP::Response>.
117
118 The CGI environment is set up based on $c.
119
120 The environment variables to pass on are taken from the configuration for your
121 Controller, see L</SYNOPSIS> for an example. If you don't supply a list of
122 environment variables to pass, the whole of %ENV is used.
123
124 Used by cgi_to_response (above), which is probably what you want to use as well.
125
126 =cut
127
128 sub wrap_cgi {
129   my ($self, $c, $call) = @_;
130   my $req = HTTP::Request->new(
131     map { $c->req->$_ } qw/method uri headers/
132   );
133   my $body = $c->req->body;
134   my $body_content = '';
135
136   $req->content_type($c->req->content_type); # set this now so we can override
137
138   if ($body) { # Slurp from body filehandle
139     local $/; $body_content = <$body>;
140   } else {
141     my $body_params = $c->req->body_parameters;
142     if (%$body_params) {
143       my $encoder = URI->new;
144       $encoder->query_form(%$body_params);
145       $body_content = $encoder->query;
146       $req->content_type('application/x-www-form-urlencoded');
147     }
148   }
149
150   my @env;
151
152   my $pass_env = $self->{CGI}{pass_env};
153   $pass_env = []            if not defined $pass_env;
154   $pass_env = [ $pass_env ] unless ref $pass_env;
155
156   for (@$pass_env) {
157     if (m!^/(.*)/\z!) {
158       my $re = qr/$1/;
159       push @env, grep /$re/, keys %ENV;
160     } else {
161       push @env, $_;
162     }
163   }
164
165   @env = keys %ENV unless @env;
166
167   $req->content($body_content);
168   $req->content_length(length($body_content));
169
170   my $username_field = $self->{CGI}{username_field} || 'username';
171
172   my $username = (($c->can('user_exists') && $c->user_exists)
173                ? eval { $c->user->obj->$username_field }
174                 : '');
175   my $env = HTTP::Request::AsCGI->new(
176               $req,
177               ($username ? (REMOTE_USER => $username) : ()),
178               map { ($_, $ENV{$_}) } @env
179             );
180
181   {
182     local *STDIN = $REAL_STDIN;   # restore the real ones so the filenos
183     local *STDOUT = $REAL_STDOUT; # are 0 and 1 for the env setup
184
185     my $old = select($REAL_STDOUT); # in case somebody just calls 'print'
186
187     my $saved_error;
188
189     $env->setup;
190     eval { $call->() };
191     $saved_error = $@;
192     $env->restore;
193
194     select($old);
195
196     Catalyst::Exception->throw(
197         message => "CGI invocation failed: $saved_error"
198     ) if $saved_error;
199   }
200
201   return $env->response;
202 }
203
204 =head1 ACKNOWLEDGEMENTS
205
206 Original development sponsored by L<http://www.altinity.com/>
207
208 =head1 SEE ALSO
209
210 L<Catalyst::Controller::CGIBin>, L<CatalystX::GlobalContext>,
211 L<Catalyst::Controller>, L<CGI>, L<Catalyst>
212
213 =head1 AUTHOR
214
215 Matt S. Trout, C<< <mst at shadowcat.co.uk> >>
216
217 =head1 BUGS
218
219 Please report any bugs or feature requests to C<bug-catalyst-controller-wrapcgi
220 at rt.cpan.org>, or through the web interface at
221 L<http://rt.cpan.org/NoAuth/ReportBug.html?Queue=Catalyst-Controller-WrapCGI>.
222 I will be notified, and then you'll automatically be notified of progress on
223 your bug as I make changes.
224
225 =head1 SUPPORT
226
227 More information at:
228
229 =over 4
230
231 =item * RT: CPAN's request tracker
232
233 L<http://rt.cpan.org/NoAuth/Bugs.html?Dist=Catalyst-Controller-WrapCGI>
234
235 =item * AnnoCPAN: Annotated CPAN documentation
236
237 L<http://annocpan.org/dist/Catalyst-Controller-WrapCGI>
238
239 =item * CPAN Ratings
240
241 L<http://cpanratings.perl.org/d/Catalyst-Controller-WrapCGI>
242
243 =item * Search CPAN
244
245 L<http://search.cpan.org/dist/Catalyst-Controller-WrapCGI>
246
247 =back
248
249 =head1 COPYRIGHT & LICENSE
250
251 Copyright (c) 2008 Matt S. Trout
252
253 This program is free software; you can redistribute it and/or modify it
254 under the same terms as Perl itself.
255
256 =cut
257
258 1; # End of Catalyst::Controller::WrapCGI
259
260 # vim: expandtab shiftwidth=2 ts=2 tw=80: