4bb64845130e94a336a8e7f5ca46dfe994be1a6d
[freeside.git] / rt / lib / RT / Interface / Web / Handler.pm
1 # BEGIN BPS TAGGED BLOCK {{{
2 #
3 # COPYRIGHT:
4 #
5 # This software is Copyright (c) 1996-2011 Best Practical Solutions, LLC
6 #                                          <sales@bestpractical.com>
7 #
8 # (Except where explicitly superseded by other copyright notices)
9 #
10 #
11 # LICENSE:
12 #
13 # This work is made available to you under the terms of Version 2 of
14 # the GNU General Public License. A copy of that license should have
15 # been provided with this software, but in any event can be snarfed
16 # from www.gnu.org.
17 #
18 # This work is distributed in the hope that it will be useful, but
19 # WITHOUT ANY WARRANTY; without even the implied warranty of
20 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
21 # General Public License for more details.
22 #
23 # You should have received a copy of the GNU General Public License
24 # along with this program; if not, write to the Free Software
25 # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
26 # 02110-1301 or visit their web page on the internet at
27 # http://www.gnu.org/licenses/old-licenses/gpl-2.0.html.
28 #
29 #
30 # CONTRIBUTION SUBMISSION POLICY:
31 #
32 # (The following paragraph is not intended to limit the rights granted
33 # to you to modify and distribute this software under the terms of
34 # the GNU General Public License and is only of importance to you if
35 # you choose to contribute your changes and enhancements to the
36 # community by submitting them to Best Practical Solutions, LLC.)
37 #
38 # By intentionally submitting any modifications, corrections or
39 # derivatives to this work, or any other work intended for use with
40 # Request Tracker, to Best Practical Solutions, LLC, you confirm that
41 # you are the copyright holder for those contributions and you grant
42 # Best Practical Solutions,  LLC a nonexclusive, worldwide, irrevocable,
43 # royalty-free, perpetual, license to use, copy, create derivative
44 # works based on those contributions, and sublicense and distribute
45 # those contributions and any derivatives thereof.
46 #
47 # END BPS TAGGED BLOCK }}}
48
49 package RT::Interface::Web::Handler;
50
51 use CGI qw/-private_tempfiles/;
52 use MIME::Entity;
53 use Text::Wrapper;
54 use CGI::Cookie;
55 use Time::ParseDate;
56 use Time::HiRes;
57 use HTML::Entities;
58 use HTML::Scrubber;
59 use RT::Interface::Web::Handler;
60 use RT::Interface::Web::Request;
61 use File::Path qw( rmtree );
62 use File::Glob qw( bsd_glob );
63 use File::Spec::Unix;
64
65 sub DefaultHandlerArgs  { (
66     comp_root => [
67         [ local    => $RT::MasonLocalComponentRoot ],
68         (map {[ "plugin-".$_->Name =>  $_->ComponentRoot ]} @{RT->Plugins}),
69         [ standard => $RT::MasonComponentRoot ]
70     ],
71     default_escape_flags => 'h',
72     data_dir             => "$RT::MasonDataDir",
73     allow_globals        => [qw(%session)],
74     # Turn off static source if we're in developer mode.
75     static_source        => (RT->Config->Get('DevelMode') ? '0' : '1'), 
76     use_object_files     => (RT->Config->Get('DevelMode') ? '0' : '1'), 
77     autoflush            => 0,
78     error_format         => (RT->Config->Get('DevelMode') ? 'html': 'brief'),
79     request_class        => 'RT::Interface::Web::Request',
80     named_component_subs => $INC{'Devel/Cover.pm'} ? 1 : 0,
81 ) };
82
83 # {{{ sub new 
84
85 =head2 new
86
87   Constructs a web handler of the appropriate class.
88   Takes options to pass to the constructor.
89
90 =cut
91
92 sub new {
93     my $class = shift;
94     $class->InitSessionDir;
95
96     if ( ($mod_perl::VERSION && $mod_perl::VERSION >= 1.9908) || $CGI::MOD_PERL) {
97         goto &NewApacheHandler;
98     }
99     else {
100         goto &NewCGIHandler;
101     }
102 }
103
104 sub InitSessionDir {
105     # Activate the following if running httpd as root (the normal case).
106     # Resets ownership of all files created by Mason at startup.
107     # Note that mysql uses DB for sessions, so there's no need to do this.
108     unless ( RT->Config->Get('DatabaseType') =~ /(?:mysql|Pg)/ ) {
109
110         # Clean up our umask to protect session files
111         umask(0077);
112
113         if ($CGI::MOD_PERL and $CGI::MOD_PERL < 1.9908 ) {
114
115             chown( Apache->server->uid, Apache->server->gid,
116                 $RT::MasonSessionDir )
117             if Apache->server->can('uid');
118         }
119
120         # Die if WebSessionDir doesn't exist or we can't write to it
121         stat($RT::MasonSessionDir);
122         die "Can't read and write $RT::MasonSessionDir"
123         unless ( ( -d _ ) and ( -r _ ) and ( -w _ ) );
124     }
125
126 }
127
128 # }}}
129
130 # {{{ sub NewApacheHandler 
131
132 =head2 NewApacheHandler
133
134   Takes extra options to pass to HTML::Mason::ApacheHandler->new
135   Returns a new Mason::ApacheHandler object
136
137 =cut
138
139 sub NewApacheHandler {
140     require HTML::Mason::ApacheHandler;
141     return NewHandler('HTML::Mason::ApacheHandler', args_method => "CGI", @_);
142 }
143
144 # }}}
145
146 # {{{ sub NewCGIHandler 
147
148 =head2 NewCGIHandler
149
150   Returns a new Mason::CGIHandler object
151
152 =cut
153
154 sub NewCGIHandler {
155     require HTML::Mason::CGIHandler;
156     return NewHandler(
157         'HTML::Mason::CGIHandler',
158         out_method => sub {
159             my $m = HTML::Mason::Request->instance;
160             my $r = $m->cgi_request;
161
162             # Send headers if they have not been sent by us or by user.
163             $r->send_http_header unless $r->http_header_sent;
164
165             # Set up a default
166             $r->content_type('text/html; charset=utf-8')
167                 unless $r->content_type;
168
169             if ( $r->content_type =~ /charset=([\w-]+)$/ ) {
170                 my $enc = $1;
171                 if ( lc $enc !~ /utf-?8$/ ) {
172                     for my $str (@_) {
173                         next unless $str;
174
175                         # only encode perl internal strings
176                         next unless utf8::is_utf8($str);
177                         $str = Encode::encode( $enc, $str );
178                     }
179                 }
180             }
181
182             # default to utf8 encoding
183             for my $str (@_) {
184                 next unless $str;
185                 next unless utf8::is_utf8($str);
186                 $str = Encode::encode( 'utf8', $str );
187             }
188
189             # We could perhaps install a new, faster out_method here that
190             # wouldn't have to keep checking whether headers have been
191             # sent and what the $r->method is.  That would require
192             # additions to the Request interface, though.
193             print STDOUT grep {defined} @_;
194         },
195         @_
196     );
197 }
198
199 sub NewHandler {
200     my $class = shift;
201     my $handler = $class->new(
202         DefaultHandlerArgs(),
203         @_
204     );
205   
206     $handler->interp->set_escape( h => \&RT::Interface::Web::EscapeUTF8 );
207     $handler->interp->set_escape( u => \&RT::Interface::Web::EscapeURI  );
208     return($handler);
209 }
210
211 =head2 CleanupRequest
212
213 Clean ups globals, caches and other things that could be still
214 there from previous requests:
215
216 =over 4
217
218 =item Rollback any uncommitted transaction(s)
219
220 =item Flush the ACL cache
221
222 =item Flush records cache of the L<DBIx::SearchBuilder> if
223 WebFlushDbCacheEveryRequest option is enabled, what is true by default
224 and is not recommended to change.
225
226 =item Clean up state of RT::Action::SendEmail using 'CleanSlate' method
227
228 =item Flush tmp GnuPG key preferences
229
230 =back
231
232 =cut
233
234 sub CleanupRequest {
235
236     if ( $RT::Handle && $RT::Handle->TransactionDepth ) {
237         $RT::Handle->ForceRollback;
238         $RT::Logger->crit(
239             "Transaction not committed. Usually indicates a software fault."
240             . "Data loss may have occurred" );
241     }
242
243     # Clean out the ACL cache. the performance impact should be marginal.
244     # Consistency is imprived, too.
245     RT::Principal->InvalidateACLCache();
246     DBIx::SearchBuilder::Record::Cachable->FlushCache
247       if ( RT->Config->Get('WebFlushDbCacheEveryRequest')
248         and UNIVERSAL::can(
249             'DBIx::SearchBuilder::Record::Cachable' => 'FlushCache' ) );
250
251     # cleanup global squelching of the mails
252     require RT::Action::SendEmail;
253     RT::Action::SendEmail->CleanSlate;
254     
255     if (RT->Config->Get('GnuPG')->{'Enable'}) {
256         require RT::Crypt::GnuPG;
257         RT::Crypt::GnuPG::UseKeyForEncryption();
258         RT::Crypt::GnuPG::UseKeyForSigning( undef );
259     }
260
261     %RT::Ticket::MERGE_CACHE = ( effective => {}, merged => {} );
262
263     # RT::System persists between requests, so its attributes cache has to be
264     # cleared manually. Without this, for example, subject tags across multiple
265     # processes will remain cached incorrectly
266     delete $RT::System->{attributes};
267
268     # Explicitly remove any tmpfiles that GPG opened, and close their
269     # filehandles.
270     File::Temp::cleanup;
271 }
272 # }}}
273
274 1;