add an explicit use for RT's not-well-declared dependency on CSS::Squish 0.06
[freeside.git] / htetc / handler.pl
1 #!/usr/bin/perl
2
3 package HTML::Mason;
4
5 use strict;
6 use vars qw($r);
7 use HTML::Mason 1.27; #http://www.masonhq.com/?ApacheModPerl2Redirect
8 use HTML::Mason::Interp;
9 use HTML::Mason::Compiler::ToObject;
10
11 # Bring in ApacheHandler, necessary for mod_perl integration.
12 # Uncomment the second line (and comment the first) to use
13 # Apache::Request instead of CGI.pm to parse arguments.
14 use HTML::Mason::ApacheHandler;
15 # use HTML::Mason::ApacheHandler (args_method=>'mod_perl');
16
17 ###use Module::Refresh;###
18
19 # List of modules that you want to use from components (see Admin
20 # manual for details)
21 #{  package HTML::Mason::Commands;
22 #   use CGI;
23 #}
24
25 if ( %%%RT_ENABLED%%% ) {
26  eval '
27    use lib ( "/opt/rt3/local/lib", "/opt/rt3/lib" );
28    use RT;
29    use vars qw($Nobody $SystemUser);
30    RT::LoadConfig();
31  ';
32  die $@ if $@;
33 }
34
35 # Create Mason objects
36
37 my %interp = (
38   request_class        => 'HTML::Mason::Request::ApacheHandler',
39   data_dir             => '%%%MASONDATA%%%',
40   error_mode           => 'output',
41   error_format         => 'html',
42   ignore_warnings_expr => '.',
43   comp_root            => [
44                             [ 'freeside' => '%%%FREESIDE_DOCUMENT_ROOT%%%'    ],
45                             [ 'rt'       => '%%%FREESIDE_DOCUMENT_ROOT%%%/rt' ],
46                           ],
47 );
48
49 my $fs_interp = new HTML::Mason::Interp (
50   %interp,
51   escape_flags => { 'js_string' => sub {
52                       #${$_[0]} =~ s/(['\\\n])/'\\'.($1 eq "\n" ? 'n' : $1)/ge;
53                       ${$_[0]} =~ s/(['\\])/\\$1/g;
54                       ${$_[0]} =~ s/\n/\\n/g;
55                       ${$_[0]} = "'". ${$_[0]}. "'";
56                     }
57                   },
58 );
59
60 my $rt_interp = new HTML::Mason::Interp (
61   %interp,
62   escape_flags => { 'h' => \&RT::Interface::Web::EscapeUTF8 },
63   compiler     => HTML::Mason::Compiler::ToObject->new(
64                     default_escape_flags => 'h',
65                     allow_globals        => [qw(%session)],
66                   ),
67 );
68
69 my $ah = new HTML::Mason::ApacheHandler (
70   interp      => $fs_interp,
71   args_method => 'CGI', #(and FS too)
72 );
73
74 # Activate the following if running httpd as root (the normal case).
75 # Resets ownership of all files created by Mason at startup.
76 #
77 #chown (Apache->server->uid, Apache->server->gid, $interp->files_written);
78
79 sub handler
80 {
81     ($r) = @_;
82
83     # If you plan to intermix images in the same directory as
84     # components, activate the following to prevent Mason from
85     # evaluating image files as components.
86     #
87     #return -1 if $r->content_type && $r->content_type !~ m|^text/|i;
88
89     #rar
90     { package HTML::Mason::Commands;
91       use strict;
92       use vars qw( $cgi $p $fsurl);
93       use vars qw( %session );
94       use CGI 2.47 qw(-private_tempfiles);
95       #use CGI::Carp qw(fatalsToBrowser);
96       use CGI::Cookie;
97       use List::Util qw( max min );
98       use Data::Dumper;
99       use Date::Format;
100       use Date::Parse;
101       use Time::Local;
102       use Time::Duration;
103       use DateTime;
104       use DateTime::Format::Strptime;
105       use Lingua::EN::Inflect qw(PL);
106       use Tie::IxHash;
107       use URI::Escape;
108       use HTML::Entities;
109       use JSON;
110       use MIME::Base64;
111       use IO::Handle;
112       use IO::File;
113       use IO::Scalar;
114       #not actually using this yet anyway...# use IPC::Run3 0.036;
115       use Net::Whois::Raw qw(whois);
116       if ( $] < 5.006 ) {
117         eval "use Net::Whois::Raw 0.32 qw(whois)";
118         die $@ if $@;
119       }
120       use Text::CSV_XS;
121       use Spreadsheet::WriteExcel;
122       use Business::CreditCard 0.30; #for mask-aware cardtype()
123       use NetAddr::IP;
124       use String::Approx qw(amatch);
125       use Chart::LinesPoints;
126       use Chart::Mountain;
127       use Color::Scheme;
128       use HTML::Widgets::SelectLayers 0.07; #should go away in favor of
129                                             #selectlayers.html
130       use Locale::Country;
131       use Business::US::USPS::WebTools::AddressStandardization;
132       use FS;
133       use FS::UID qw( adminsuidsetup cgisuidsetup getotaker
134                       dbh datasrc driver_name
135                     );
136       use FS::Record qw(qsearch qsearchs fields dbdef str2time_sql);
137       use FS::Conf;
138       use FS::CGI qw(header menubar popurl rooturl table itable ntable idiot
139                      eidiot small_custview myexit http_header);
140       use FS::UI::Web qw(svc_url);
141       use FS::UI::bytecount;
142       use FS::Msgcat qw(gettext geterror);
143       use FS::Misc qw( send_email send_fax states_hash counties state_label );
144       use FS::Report::Table::Monthly;
145       use FS::TicketSystem;
146
147       use FS::agent;
148       use FS::agent_type;
149       use FS::domain_record;
150       use FS::cust_bill;
151       use FS::cust_bill_pay;
152       use FS::cust_credit;
153       use FS::cust_credit_bill;
154       use FS::cust_main qw(smart_search);
155       use FS::cust_main_county;
156       use FS::cust_pay;
157       use FS::cust_pkg;
158       use FS::part_pkg_taxclass;
159       use FS::cust_pkg_reason;
160       use FS::cust_refund;
161       use FS::cust_svc;
162       use FS::nas;
163       use FS::part_bill_event;
164       use FS::part_event;
165       use FS::part_event_condition;
166       use FS::part_pkg;
167       use FS::part_referral;
168       use FS::part_svc;
169       use FS::part_svc_router;
170       use FS::part_virtual_field;
171       use FS::pay_batch;
172       use FS::pkg_svc;
173       use FS::port;
174       use FS::queue qw(joblisting);
175       use FS::raddb;
176       use FS::session;
177       use FS::svc_acct;
178       use FS::svc_acct_pop qw(popselector);
179       use FS::acct_rt_transaction;
180       use FS::svc_domain;
181       use FS::svc_forward;
182       use FS::svc_www;
183       use FS::router;
184       use FS::addr_block;
185       use FS::svc_broadband;
186       use FS::svc_external;
187       use FS::type_pkgs;
188       use FS::part_export;
189       use FS::part_export_option;
190       use FS::export_svc;
191       use FS::msgcat;
192       use FS::rate;
193       use FS::rate_region;
194       use FS::rate_prefix;
195       use FS::payment_gateway;
196       use FS::agent_payment_gateway;
197       use FS::XMLRPC;
198       use FS::payby;
199       use FS::cdr;
200       use FS::inventory_class;
201       use FS::inventory_item;
202       use FS::pkg_class;
203       use FS::access_user;
204       use FS::access_user_pref;
205       use FS::access_group;
206       use FS::access_usergroup;
207       use FS::access_groupagent;
208       use FS::access_right;
209       use FS::AccessRight;
210       use FS::svc_phone;
211       use FS::reason_type;
212       use FS::reason;
213       use FS::cust_main_note;
214       use FS::tax_class;
215       use FS::cust_tax_location;
216       use FS::part_pkg_taxproduct;
217       use FS::part_pkg_taxoverride;
218       use FS::part_pkg_taxrate;
219       use FS::tax_rate;
220
221       if ( %%%RT_ENABLED%%% ) {
222         eval '
223           use RT::Tickets;
224           use RT::Transactions;
225           use RT::Users;
226           use RT::CurrentUser;
227           use RT::Templates;
228           use RT::Queues;
229           use RT::ScripActions;
230           use RT::ScripConditions;
231           use RT::Scrips;
232           use RT::Groups;
233           use RT::GroupMembers;
234           use RT::CustomFields;
235           use RT::CustomFieldValues;
236           use RT::ObjectCustomFieldValues;
237
238           #blah.  manually updated from RT::Interface::Web::Handler
239           use RT::Interface::Web;
240           use MIME::Entity;
241           use Text::Wrapper;
242           use Time::ParseDate;
243           use Time::HiRes;
244           use HTML::Scrubber;
245
246           #blah.  not even in RT::Interface::Web::Handler, just in 
247           #html/NoAuth/css/dhandler and rt-test-dependencies.  ask for it here
248           #to throw a real error instead of just a mysterious unstyled RT
249           use CSS::Squish 0.06;
250
251           #slow, unreliable, segfaults and is optional
252           #see rt/html/Ticket/Elements/ShowTransactionAttachments
253           #use Text::Quoted;
254
255           #?#use File::Path qw( rmtree );
256           #?#use File::Glob qw( bsd_glob );
257           #?#use File::Spec::Unix;
258
259         ';
260         die $@ if $@;
261       }
262
263       *CGI::redirect = sub {
264         my $self = shift;
265         my $cookie = '';
266         if ( $_[0] eq '-cookie' ) { #this isn't actually used at the moment
267           (my $x, $cookie) = (shift, shift);
268           $HTML::Mason::r->err_headers_out->add( 'Set-cookie' => $cookie );
269         }
270         my $location = shift;
271
272         use vars qw($m);
273
274         # false laziness w/below
275         if ( defined(@DBIx::Profile::ISA) ) { #profiling redirect
276
277           my $page =
278             qq!<HTML><BODY>Redirect to <A HREF="$location">$location</A>!.
279             '<BR><BR><PRE>'.
280               ( UNIVERSAL::can(dbh, 'sprintProfile')
281                   ? encode_entities(dbh->sprintProfile())
282                   : 'DBIx::Profile missing sprintProfile method;'.
283                     'unpatched or too old?'                        ).
284             #"\n\n". &sprintAutoProfile().  '</PRE>'.
285             "\n\n".                         '</PRE>'.
286             '</BODY></HTML>';
287           dbh->{'private_profile'} = {};
288           return $page;
289
290         } else { #normal redirect
291
292           $m->redirect($location);
293           '';
294
295         }
296
297       };
298       
299       if ( $HTML::Mason::r->filename !~ /\/rt\/.*NoAuth/ ) { #not RT images/JS
300
301         $cgi = new CGI;
302         &cgisuidsetup($cgi);
303         #&cgisuidsetup($r);
304         $p = popurl(2);
305         $fsurl = rooturl();
306
307       } elsif ( $HTML::Mason::r->filename =~ /\/rt\/REST\/.*NoAuth/ ) {
308
309         #need to log somebody in for the mail gw
310
311         ##old installs w/fs_selfs or selfserv??
312         #&adminsuidsetup('fs_selfservice');
313
314         &adminsuidsetup('fs_queue');
315
316       }
317
318       sub include {
319         use vars qw($m);
320         $m->scomp(@_);
321       }
322
323       sub errorpage {
324         use vars qw($m);
325         $m->comp('/elements/errorpage.html', @_);
326       }
327
328       sub redirect {
329         my( $location ) = @_;
330         use vars qw($m);
331         $m->clear_buffer;
332         #false laziness w/above
333         if ( defined(@DBIx::Profile::ISA) ) { #profiling redirect
334
335           $m->print(
336             qq!<HTML><BODY>Redirect to <A HREF="$location">$location</A>!.
337             '<BR><BR><PRE>'.
338               ( UNIVERSAL::can(dbh, 'sprintProfile')
339                   ? encode_entities(dbh->sprintProfile())
340                   : 'DBIx::Profile missing sprintProfile method;'.
341                     'unpatched or too old?'                        ).
342             #"\n\n". &sprintAutoProfile().  '</PRE>'.
343             "\n\n".                         '</PRE>'.
344             '</BODY></HTML>'
345           );
346           dbh->{'private_profile'} = {};
347
348           #whew.  removing this is all that's needed to fix the annoying
349           #blank-page-instead-of-profiling-redirect-when-called-from-an-include
350           #bug triggered by mason 1.32
351           #my $rv = $m->abort(200);
352
353         } else { #normal redirect
354
355           $m->redirect($location);
356
357         }
358
359       }
360
361     } # end package HTML::Mason::Commands;
362
363     ###Module::Refresh->refresh;###
364
365     $r->content_type('text/html');
366     #eorar
367
368     my $headers = $r->headers_out;
369     $headers->{'Cache-control'} = 'no-cache';
370     #$r->no_cache(1);
371     $headers->{'Expires'} = '0';
372
373 #    $r->send_http_header;
374
375     if ( $r->filename =~ /\/rt\// ) { #RT
376
377       $ah->interp($rt_interp);
378
379       local $SIG{__WARN__};
380       local $SIG{__DIE__};
381
382       RT::Init();
383
384       # We don't need to handle non-text, non-xml items
385       return -1 if defined( $r->content_type )
386                 && $r->content_type !~ m!(^text/|\bxml\b)!io;
387
388     } else {
389
390       $ah->interp($fs_interp);
391
392     }
393
394     my %session;
395     my $status;
396     eval { $status = $ah->handle_request($r); };
397 #!!
398 #    if ( $@ ) {
399 #       $RT::Logger->crit($@);
400 #    }
401     warn $@ if $@;
402
403     undef %session;
404
405 #!!
406 #    if ($RT::Handle->TransactionDepth) {
407 #       $RT::Handle->ForceRollback;
408 #       $RT::Logger->crit(
409 #"Transaction not committed. Usually indicates a software fault. Data loss may have occurred"
410 #       );
411 #    }
412
413     $status;
414 }
415
416 1;