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