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