per-user preference for turning on profiling display when DBIx::Profile is loaded...
[freeside.git] / FS / FS / Mason.pm
1 package FS::Mason;
2
3 use strict;
4 use vars qw( @ISA @EXPORT_OK );
5 use Exporter;
6 use HTML::Mason 1.27; #http://www.masonhq.com/?ApacheModPerl2Redirect
7 use HTML::Mason::Interp;
8 use HTML::Mason::Compiler::ToObject;
9
10 @ISA = qw( Exporter );
11 @EXPORT_OK = qw( mason_interps );
12
13 =head1 NAME
14
15 FS::Mason - Initialize the Mason environment
16
17 =head1 SYNOPSIS
18
19   use FS::Mason qw( mason_interps );
20
21   my( $fs_interp, $rt_interp ) = mason_interps('apache');
22
23   #OR
24
25   my( $fs_interp, $rt_interp ) = mason_interps('standalone'); #XXX name?
26
27 =head1 DESCRIPTION
28
29 Initializes the Mason environment, loads all Freeside and RT libraries, etc.
30
31 =cut
32
33 # List of modules that you want to use from components (see Admin
34 # manual for details)
35 {
36   package HTML::Mason::Commands;
37
38   use strict;
39   use vars qw( %session );
40   use CGI 3.29 qw(-private_tempfiles); #3.29 to fix RT attachment problems
41   #use CGI::Carp qw(fatalsToBrowser);
42   use CGI::Cookie;
43   use List::Util qw( max min );
44   use Data::Dumper;
45   use Date::Format;
46   use Date::Parse;
47   use Time::Local;
48   use Time::Duration;
49   use DateTime;
50   use DateTime::Format::Strptime;
51   use Lingua::EN::Inflect qw(PL);
52   use Tie::IxHash;
53   use URI::URL;
54   use URI::Escape;
55   use HTML::Entities;
56   use HTML::TreeBuilder;
57   use HTML::FormatText;
58   use JSON;
59   use MIME::Base64;
60   use IO::Handle;
61   use IO::File;
62   use IO::Scalar;
63   #not actually using this yet anyway...# use IPC::Run3 0.036;
64   use Net::Whois::Raw qw(whois);
65   if ( $] < 5.006 ) {
66     eval "use Net::Whois::Raw 0.32 qw(whois)";
67     die $@ if $@;
68   }
69   use Text::CSV_XS;
70   use Spreadsheet::WriteExcel;
71   use Business::CreditCard 0.30; #for mask-aware cardtype()
72   use NetAddr::IP;
73   use String::Approx qw(amatch);
74   use Chart::LinesPoints;
75   use Chart::Mountain;
76   use Color::Scheme;
77   use HTML::Widgets::SelectLayers 0.07; #should go away in favor of
78                                         #selectlayers.html
79   use Locale::Country;
80   use Business::US::USPS::WebTools::AddressStandardization;
81   use FS;
82   use FS::UID qw( getotaker dbh datasrc driver_name );
83   use FS::Record qw( qsearch qsearchs fields dbdef
84                     str2time_sql str2time_sql_closing
85                    );
86   use FS::Conf;
87   use FS::CGI qw(header menubar table itable ntable idiot
88                  eidiot myexit http_header);
89   use FS::UI::Web qw(svc_url);
90   use FS::UI::Web::small_custview qw(small_custview);
91   use FS::UI::bytecount;
92   use FS::Msgcat qw(gettext geterror);
93   use FS::Misc qw( send_email send_fax states_hash counties state_label );
94   use FS::Report::Table::Monthly;
95   use FS::TicketSystem;
96   use FS::Tron qw( tron_lint );
97
98   use FS::agent;
99   use FS::agent_type;
100   use FS::domain_record;
101   use FS::cust_bill;
102   use FS::cust_bill_pay;
103   use FS::cust_credit;
104   use FS::cust_credit_bill;
105   use FS::cust_main qw(smart_search);
106   use FS::cust_main::Import;
107   use FS::cust_main_county;
108   use FS::cust_location;
109   use FS::cust_pay;
110   use FS::cust_pkg;
111   use FS::part_pkg_taxclass;
112   use FS::cust_pkg_reason;
113   use FS::cust_refund;
114   use FS::cust_credit_refund;
115   use FS::cust_pay_refund;
116   use FS::cust_svc;
117   use FS::nas;
118   use FS::part_bill_event;
119   use FS::part_event;
120   use FS::part_event_condition;
121   use FS::part_pkg;
122   use FS::part_referral;
123   use FS::part_svc;
124   use FS::part_svc_router;
125   use FS::part_virtual_field;
126   use FS::pay_batch;
127   use FS::pkg_svc;
128   use FS::port;
129   use FS::queue qw(joblisting);
130   use FS::raddb;
131   use FS::session;
132   use FS::svc_acct;
133   use FS::svc_acct_pop qw(popselector);
134   use FS::acct_rt_transaction;
135   use FS::svc_domain;
136   use FS::svc_forward;
137   use FS::svc_www;
138   use FS::router;
139   use FS::addr_block;
140   use FS::svc_broadband;
141   use FS::svc_external;
142   use FS::type_pkgs;
143   use FS::part_export;
144   use FS::part_export_option;
145   use FS::export_svc;
146   use FS::msgcat;
147   use FS::rate;
148   use FS::rate_region;
149   use FS::rate_prefix;
150   use FS::rate_detail;
151   use FS::usage_class;
152   use FS::payment_gateway;
153   use FS::agent_payment_gateway;
154   use FS::XMLRPC;
155   use FS::payby;
156   use FS::cdr;
157   use FS::inventory_class;
158   use FS::inventory_item;
159   use FS::pkg_category;
160   use FS::pkg_class;
161   use FS::access_user;
162   use FS::access_user_pref;
163   use FS::access_group;
164   use FS::access_usergroup;
165   use FS::access_groupagent;
166   use FS::access_right;
167   use FS::AccessRight;
168   use FS::svc_phone;
169   use FS::reason_type;
170   use FS::reason;
171   use FS::cust_main_note;
172   use FS::tax_class;
173   use FS::cust_tax_location;
174   use FS::part_pkg_taxproduct;
175   use FS::part_pkg_taxoverride;
176   use FS::part_pkg_taxrate;
177   use FS::tax_rate;
178
179   if ( %%%RT_ENABLED%%% ) {
180     eval '
181       use lib ( "/opt/rt3/local/lib", "/opt/rt3/lib" );
182       use vars qw($Nobody $SystemUser);
183       use RT;
184       use RT::Tickets;
185       use RT::Transactions;
186       use RT::Users;
187       use RT::CurrentUser;
188       use RT::Templates;
189       use RT::Queues;
190       use RT::ScripActions;
191       use RT::ScripConditions;
192       use RT::Scrips;
193       use RT::Groups;
194       use RT::GroupMembers;
195       use RT::CustomFields;
196       use RT::CustomFieldValues;
197       use RT::ObjectCustomFieldValues;
198
199       #blah.  manually updated from RT::Interface::Web::Handler
200       use RT::Interface::Web;
201       use MIME::Entity;
202       use Text::Wrapper;
203       use Time::ParseDate;
204       use Time::HiRes;
205       use HTML::Scrubber;
206
207       #blah.  not even in RT::Interface::Web::Handler, just in 
208       #html/NoAuth/css/dhandler and rt-test-dependencies.  ask for it here
209       #to throw a real error instead of just a mysterious unstyled RT
210       use CSS::Squish 0.06;
211
212       #slow, unreliable, segfaults and is optional
213       #see rt/html/Ticket/Elements/ShowTransactionAttachments
214       #use Text::Quoted;
215
216       #?#use File::Path qw( rmtree );
217       #?#use File::Glob qw( bsd_glob );
218       #?#use File::Spec::Unix;
219
220     ';
221     die $@ if $@;
222   }
223
224   *CGI::redirect = sub {
225     my $self = shift;
226     my $cookie = '';
227     if ( $_[0] eq '-cookie' ) { #this isn't actually used at the moment
228       (my $x, $cookie) = (shift, shift);
229       $HTML::Mason::r->err_headers_out->add( 'Set-cookie' => $cookie );
230     }
231     my $location = shift;
232
233     use vars qw($m);
234
235     # false laziness w/below
236     if ( defined(@DBIx::Profile::ISA) ) {
237
238       if ( $FS::CurrentUser::CurrentUser->option('show_db_profile') ) {
239
240         #profiling redirect
241
242         my $page =
243           qq!<HTML><BODY>Redirect to <A HREF="$location">$location</A>!.
244           '<BR><BR><PRE>'.
245             ( UNIVERSAL::can(dbh, 'sprintProfile')
246                 ? encode_entities(dbh->sprintProfile())
247                 : 'DBIx::Profile missing sprintProfile method;'.
248                   'unpatched or too old?'                        ).
249           #"\n\n". &sprintAutoProfile().  '</PRE>'.
250           "\n\n".                         '</PRE>'.
251           '</BODY></HTML>';
252
253
254         dbh->{'private_profile'} = {};
255         return $page;
256
257       } else {
258
259         #clear db profile, but normal redirect
260         dbh->{'private_profile'} = {};
261         $m->redirect($location);
262         '';
263
264       }
265
266     } else { #normal redirect
267
268       $m->redirect($location);
269       '';
270
271     }
272
273   };
274   
275   sub include {
276     use vars qw($m);
277     $m->scomp(@_);
278   }
279
280   sub errorpage {
281     use vars qw($m);
282     $m->comp('/elements/errorpage.html', @_);
283   }
284
285   sub redirect {
286     my( $location ) = @_;
287     use vars qw($m);
288     $m->clear_buffer;
289     #false laziness w/above
290     if ( defined(@DBIx::Profile::ISA) ) {
291
292       if ( $FS::CurrentUser::CurrentUser->option('show_db_profile') ) {
293
294         #profiling redirect
295
296         $m->print(
297           qq!<HTML><BODY>Redirect to <A HREF="$location">$location</A>!.
298           '<BR><BR><PRE>'.
299             ( UNIVERSAL::can(dbh, 'sprintProfile')
300                 ? encode_entities(dbh->sprintProfile())
301                 : 'DBIx::Profile missing sprintProfile method;'.
302                   'unpatched or too old?'                        ).
303           #"\n\n". &sprintAutoProfile().  '</PRE>'.
304           "\n\n".                         '</PRE>'.
305           '</BODY></HTML>'
306         );
307
308         dbh->{'private_profile'} = {};
309
310       } else {
311
312         #clear db profile, but normal redirect
313         dbh->{'private_profile'} = {};
314         $m->redirect($location);
315
316       }
317
318     } else { #normal redirect
319
320       $m->redirect($location);
321
322     }
323
324   }
325
326 } # end package HTML::Mason::Commands;
327
328 =head1 SUBROUTINE
329
330 =over 4
331
332 =item mason_interps [ MODE ]
333
334 Returns a list consisting of two HTML::Mason::Interp objects, the first for
335 Freeside pages, and the second for RT pages.
336
337 #MODE can be 'apache' or 'standalone'.  If not specified, defaults to 'apache'.
338
339 =cut
340
341 sub mason_interps {
342   my $mode = shift || 'apache';
343   my %opt = @_;
344
345   #my $request_class = 'HTML::Mason::Request'.
346                       #( $mode eq 'apache' ? '::ApacheHandler' : '' );
347   my $request_class = 'FS::Mason::Request';
348
349   #not entirely sure it belongs here, but what the hey
350   if ( %%%RT_ENABLED%%% ) {
351     RT::LoadConfig();
352   }
353
354   my %interp = (
355     request_class        => $request_class,
356     data_dir             => '%%%MASONDATA%%%',
357     error_mode           => 'output',
358     error_format         => 'html',
359     ignore_warnings_expr => '.',
360     comp_root            => [
361                               [ 'freeside'=>'%%%FREESIDE_DOCUMENT_ROOT%%%'    ],
362                               [ 'rt'      =>'%%%FREESIDE_DOCUMENT_ROOT%%%/rt' ],
363                             ],
364   );
365
366   $interp{out_method} = $opt{outbuf} if $mode eq 'standalone' && $opt{outbuf};
367
368   my $fs_interp = new HTML::Mason::Interp (
369     %interp,
370     escape_flags => { 'js_string' => sub {
371                         #${$_[0]} =~ s/(['\\\n])/'\\'.($1 eq "\n" ? 'n' : $1)/ge;
372                         ${$_[0]} =~ s/(['\\])/\\$1/g;
373                         ${$_[0]} =~ s/\n/\\n/g;
374                         ${$_[0]} = "'". ${$_[0]}. "'";
375                       }
376                     },
377   );
378
379   my $rt_interp = new HTML::Mason::Interp (
380     %interp,
381     escape_flags => { 'h' => \&RT::Interface::Web::EscapeUTF8 },
382     compiler     => HTML::Mason::Compiler::ToObject->new(
383                       default_escape_flags => 'h',
384                       allow_globals        => [qw(%session)],
385                     ),
386   );
387
388   ( $fs_interp, $rt_interp );
389
390 }
391
392 =back
393
394 =head1 BUGS
395
396 Lurking in the darkness...
397
398 =head1 SEE ALSO
399
400 L<HTML::Mason>, L<FS>, L<RT>
401
402 =cut
403
404 1;