RT#6226: security fix for customer notes
[freeside.git] / FS / FS / Mason.pm
1 package FS::Mason;
2
3 use strict;
4 use vars qw( @ISA @EXPORT_OK $addl_handler_use );
5 use Exporter;
6 use File::Slurp qw( slurp );
7 use HTML::Mason 1.27; #http://www.masonhq.com/?ApacheModPerl2Redirect
8 use HTML::Mason::Interp;
9 use HTML::Mason::Compiler::ToObject;
10
11 @ISA = qw( Exporter );
12 @EXPORT_OK = qw( mason_interps );
13
14 =head1 NAME
15
16 FS::Mason - Initialize the Mason environment
17
18 =head1 SYNOPSIS
19
20   use FS::Mason qw( mason_interps );
21
22   my( $fs_interp, $rt_interp ) = mason_interps('apache');
23
24   #OR
25
26   my( $fs_interp, $rt_interp ) = mason_interps('standalone'); #XXX name?
27
28 =head1 DESCRIPTION
29
30 Initializes the Mason environment, loads all Freeside and RT libraries, etc.
31
32 =cut
33
34 $addl_handler_use = '';
35 my $addl_handler_use_file = '%%%FREESIDE_CONF%%%/addl_handler_use.pl';
36 if ( -e $addl_handler_use_file ) {
37   $addl_handler_use = slurp( $addl_handler_use_file );
38 }
39
40 # List of modules that you want to use from components (see Admin
41 # manual for details)
42 {
43   package HTML::Mason::Commands;
44
45   use strict;
46   use vars qw( %session );
47   use CGI 3.29 qw(-private_tempfiles); #3.29 to fix RT attachment problems
48
49   #breaks quick payment entry
50   #http://rt.cpan.org/Public/Bug/Display.html?id=37365
51   die "CGI.pm v3.38 is broken, use any other version >= 3.29".
52       " (Debian 5.0?  aptitude remove libcgi-pm-perl)"
53     if $CGI::VERSION == 3.38;
54
55   #use CGI::Carp qw(fatalsToBrowser);
56   use CGI::Cookie;
57   use List::Util qw( max min );
58   use Data::Dumper;
59   use Date::Format;
60   use Date::Parse;
61   use Time::Local;
62   use Time::HiRes;
63   use Time::Duration;
64   use DateTime;
65   use DateTime::Format::Strptime;
66   use Lingua::EN::Inflect qw(PL);
67   use Tie::IxHash;
68   use URI;
69   use URI::Escape;
70   use HTML::Entities;
71   use HTML::TreeBuilder;
72   use HTML::FormatText;
73   use HTML::Defang;
74   use JSON;
75   use MIME::Base64;
76   use IO::Handle;
77   use IO::File;
78   use IO::Scalar;
79   #not actually using this yet anyway...# use IPC::Run3 0.036;
80   use Net::Whois::Raw qw(whois);
81   if ( $] < 5.006 ) {
82     eval "use Net::Whois::Raw 0.32 qw(whois)";
83     die $@ if $@;
84   }
85   use Text::CSV_XS;
86   use Spreadsheet::WriteExcel;
87   use Business::CreditCard 0.30; #for mask-aware cardtype()
88   use NetAddr::IP;
89   use Net::Ping;
90   use Net::Ping::External;
91   #if CPAN #7815 ever gets fixed# if ( $Net::Ping::External::VERSION <= 0.12 )
92   {
93     no warnings 'redefine';
94     eval 'sub Net::Ping::External::_ping_linux { 
95             my %args = @_;
96             my $command = "ping -s $args{size} -c $args{count} -w $args{timeout} $args{host}";
97             return Net::Ping::External::_ping_system($command, 0);
98           }
99          ';
100     die $@ if $@;
101   }
102   use String::Approx qw(amatch);
103   use Chart::LinesPoints;
104   use Chart::Mountain;
105   use Color::Scheme;
106   use HTML::Widgets::SelectLayers 0.07; #should go away in favor of
107                                         #selectlayers.html
108   use Locale::Country;
109   use Business::US::USPS::WebTools::AddressStandardization;
110   use FS;
111   use FS::UID qw( getotaker dbh datasrc driver_name );
112   use FS::Record qw( qsearch qsearchs fields dbdef
113                     str2time_sql str2time_sql_closing
114                    );
115   use FS::Conf;
116   use FS::CGI qw(header menubar table itable ntable idiot
117                  eidiot myexit http_header);
118   use FS::UI::Web qw(svc_url);
119   use FS::UI::Web::small_custview qw(small_custview);
120   use FS::UI::bytecount;
121   use FS::Msgcat qw(gettext geterror);
122   use FS::Misc qw( send_email send_fax
123                    states_hash counties cities state_label
124                  );
125   use FS::Misc::eps2png qw( eps2png );
126   use FS::Report::Table::Monthly;
127   use FS::TicketSystem;
128   use FS::Tron qw( tron_lint );
129
130   use FS::agent;
131   use FS::agent_type;
132   use FS::domain_record;
133   use FS::cust_bill;
134   use FS::cust_bill_pay;
135   use FS::cust_credit;
136   use FS::cust_credit_bill;
137   use FS::cust_main qw(smart_search);
138   use FS::cust_main::Import;
139   use FS::cust_main_county;
140   use FS::cust_location;
141   use FS::cust_pay;
142   use FS::cust_pkg;
143   use FS::part_pkg_taxclass;
144   use FS::cust_pkg_reason;
145   use FS::cust_refund;
146   use FS::cust_credit_refund;
147   use FS::cust_pay_refund;
148   use FS::cust_svc;
149   use FS::nas;
150   use FS::part_bill_event;
151   use FS::part_event;
152   use FS::part_event_condition;
153   use FS::part_pkg;
154   use FS::part_referral;
155   use FS::part_svc;
156   use FS::part_svc_router;
157   use FS::part_virtual_field;
158   use FS::pay_batch;
159   use FS::pkg_svc;
160   use FS::port;
161   use FS::queue qw(joblisting);
162   use FS::raddb;
163   use FS::session;
164   use FS::svc_acct;
165   use FS::svc_acct_pop qw(popselector);
166   use FS::acct_rt_transaction;
167   use FS::svc_domain;
168   use FS::svc_forward;
169   use FS::svc_www;
170   use FS::router;
171   use FS::addr_block;
172   use FS::svc_broadband;
173   use FS::svc_external;
174   use FS::type_pkgs;
175   use FS::part_export;
176   use FS::part_export_option;
177   use FS::export_svc;
178   use FS::export_device;
179   use FS::msgcat;
180   use FS::rate;
181   use FS::rate_region;
182   use FS::rate_prefix;
183   use FS::rate_detail;
184   use FS::usage_class;
185   use FS::payment_gateway;
186   use FS::agent_payment_gateway;
187   use FS::XMLRPC;
188   use FS::payby;
189   use FS::cdr;
190   use FS::cdr_batch;
191   use FS::inventory_class;
192   use FS::inventory_item;
193   use FS::pkg_category;
194   use FS::pkg_class;
195   use FS::access_user;
196   use FS::access_user_pref;
197   use FS::access_group;
198   use FS::access_usergroup;
199   use FS::access_groupagent;
200   use FS::access_right;
201   use FS::AccessRight;
202   use FS::svc_phone;
203   use FS::phone_device;
204   use FS::part_device;
205   use FS::reason_type;
206   use FS::reason;
207   use FS::cust_main_note;
208   use FS::tax_class;
209   use FS::cust_tax_location;
210   use FS::part_pkg_taxproduct;
211   use FS::part_pkg_taxoverride;
212   use FS::part_pkg_taxrate;
213   use FS::tax_rate;
214   use FS::part_pkg_report_option;
215   use FS::cust_attachment;
216   use FS::h_cust_pkg;
217   use FS::h_svc_acct;
218   use FS::h_svc_broadband;
219   use FS::h_svc_domain;
220   #use FS::h_domain_record;
221   use FS::h_svc_external;
222   use FS::h_svc_forward;
223   use FS::h_svc_phone;
224   #use FS::h_phone_device;
225   use FS::h_svc_www;
226   use FS::cust_statement;
227   use FS::cust_class;
228   use FS::cust_category;
229   use FS::prospect_main;
230   use FS::contact;
231   use FS::svc_pbx;
232   use FS::discount;
233   use FS::cust_pkg_discount;
234   use FS::cust_bill_pkg_discount;
235   use FS::svc_mailinglist;
236   # Sammath Naur
237
238   if ( $FS::Mason::addl_handler_use ) {
239     eval $FS::Mason::addl_handler_use;
240     die $@ if $@;
241   }
242
243   if ( %%%RT_ENABLED%%% ) {
244     eval '
245       use lib ( "/opt/rt3/local/lib", "/opt/rt3/lib" );
246       use vars qw($Nobody $SystemUser);
247       use RT;
248       use RT::Tickets;
249       use RT::Transactions;
250       use RT::Users;
251       use RT::CurrentUser;
252       use RT::Templates;
253       use RT::Queues;
254       use RT::ScripActions;
255       use RT::ScripConditions;
256       use RT::Scrips;
257       use RT::Groups;
258       use RT::GroupMembers;
259       use RT::CustomFields;
260       use RT::CustomFieldValues;
261       use RT::ObjectCustomFieldValues;
262
263       #blah.  manually updated from RT::Interface::Web::Handler
264       use RT::Interface::Web;
265       use MIME::Entity;
266       use Text::Wrapper;
267       use Time::ParseDate;
268       use Time::HiRes;
269       use HTML::Scrubber;
270
271       #blah.  not even in RT::Interface::Web::Handler, just in 
272       #html/NoAuth/css/dhandler and rt-test-dependencies.  ask for it here
273       #to throw a real error instead of just a mysterious unstyled RT
274       use CSS::Squish 0.06;
275
276       use RT::Interface::Web::Request;
277
278       #slow, unreliable, segfaults and is optional
279       #see rt/html/Ticket/Elements/ShowTransactionAttachments
280       #use Text::Quoted;
281
282       #?#use File::Path qw( rmtree );
283       #?#use File::Glob qw( bsd_glob );
284       #?#use File::Spec::Unix;
285
286     ';
287     die $@ if $@;
288   }
289
290   *CGI::redirect = sub {
291     my $self = shift;
292     my $cookie = '';
293     if ( $_[0] eq '-cookie' ) { #this isn't actually used at the moment
294       (my $x, $cookie) = (shift, shift);
295       $HTML::Mason::r->err_headers_out->add( 'Set-cookie' => $cookie );
296     }
297     my $location = shift;
298
299     use vars qw($m);
300
301     # false laziness w/below
302     if ( defined(@DBIx::Profile::ISA) ) {
303
304       if ( $FS::CurrentUser::CurrentUser->option('show_db_profile') ) {
305
306         #profiling redirect
307
308         my $page =
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         return $page;
322
323       } else {
324
325         #clear db profile, but normal redirect
326         dbh->{'private_profile'} = {};
327         $m->redirect($location);
328         '';
329
330       }
331
332     } else { #normal redirect
333
334       $m->redirect($location);
335       '';
336
337     }
338
339   };
340   
341   sub include {
342     use vars qw($m);
343     $m->scomp(@_);
344   }
345
346   sub errorpage {
347     use vars qw($m);
348     $m->comp('/elements/errorpage.html', @_);
349   }
350
351   sub redirect {
352     my( $location ) = @_;
353     use vars qw($m);
354     $m->clear_buffer;
355     #false laziness w/above
356     if ( defined(@DBIx::Profile::ISA) ) {
357
358       if ( $FS::CurrentUser::CurrentUser->option('show_db_profile') ) {
359
360         #profiling redirect
361
362         $m->print(
363           qq!<HTML><BODY>Redirect to <A HREF="$location">$location</A>!.
364           '<BR><BR><PRE>'.
365             ( UNIVERSAL::can(dbh, 'sprintProfile')
366                 ? encode_entities(dbh->sprintProfile())
367                 : 'DBIx::Profile missing sprintProfile method;'.
368                   'unpatched or too old?'                        ).
369           #"\n\n". &sprintAutoProfile().  '</PRE>'.
370           "\n\n".                         '</PRE>'.
371           '</BODY></HTML>'
372         );
373
374         dbh->{'private_profile'} = {};
375
376       } else {
377
378         #clear db profile, but normal redirect
379         dbh->{'private_profile'} = {};
380         $m->redirect($location);
381
382       }
383
384     } else { #normal redirect
385
386       $m->redirect($location);
387
388     }
389
390   }
391
392 } # end package HTML::Mason::Commands;
393
394 =head1 SUBROUTINE
395
396 =over 4
397
398 =item mason_interps [ MODE [ OPTION => VALUE ... ] ]
399
400 Returns a list consisting of two HTML::Mason::Interp objects, the first for
401 Freeside pages, and the second for RT pages.
402
403 MODE can be 'apache' or 'standalone'.  If not specified, defaults to 'apache'.
404
405 Options and values can be passed following mode.  Currently available options
406 are:
407
408 I<outbuf> should be set to a scalar reference in standalone mode.
409
410 =cut
411
412 my %defang_opts = ( attribs_to_callback => ['src'], attribs_callback => sub { 1 });
413
414 sub mason_interps {
415   my $mode = shift || 'apache';
416   my %opt = @_;
417
418   #my $request_class = 'HTML::Mason::Request'.
419                       #( $mode eq 'apache' ? '::ApacheHandler' : '' );
420   my $request_class = 'FS::Mason::Request';
421
422   #not entirely sure it belongs here, but what the hey
423   if ( %%%RT_ENABLED%%% && $mode ne 'standalone' ) {
424     RT::LoadConfig();
425   }
426
427   # A hook supporting strange legacy ways people have added stuff on
428
429   my @addl_comp_root = ();
430   my $addl_comp_root_file = '%%%FREESIDE_CONF%%%/addl_comp_root.pl';
431   if ( -e $addl_comp_root_file ) {
432     warn "reading $addl_comp_root_file\n";
433     my $text = slurp( $addl_comp_root_file );
434     my @addl = eval $text;
435     if ( @addl && ! $@ ) {
436       @addl_comp_root = @addl;
437     } elsif ($@) {
438       warn "error parsing $addl_comp_root_file: $@\n";
439     }
440   }
441
442   my %interp = (
443     request_class        => $request_class,
444     data_dir             => '%%%MASONDATA%%%',
445     error_mode           => 'output',
446     error_format         => 'html',
447     ignore_warnings_expr => '.',
448     comp_root            => [
449                               [ 'freeside'=>'%%%FREESIDE_DOCUMENT_ROOT%%%'    ],
450                               [ 'rt'      =>'%%%FREESIDE_DOCUMENT_ROOT%%%/rt' ],
451                               @addl_comp_root,
452                             ],
453   );
454
455   $interp{out_method} = $opt{outbuf} if $mode eq 'standalone' && $opt{outbuf};
456
457   my $html_defang = new HTML::Defang (%defang_opts);
458
459   my $fs_interp = new HTML::Mason::Interp (
460     %interp,
461     escape_flags => { 'js_string' => sub {
462                         #${$_[0]} =~ s/(['\\\n])/'\\'.($1 eq "\n" ? 'n' : $1)/ge;
463                         ${$_[0]} =~ s/(['\\])/\\$1/g;
464                         ${$_[0]} =~ s/\n/\\n/g;
465                         ${$_[0]} = "'". ${$_[0]}. "'";
466                       },
467                       'defang'    => sub {
468                         ${$_[0]} = $html_defang->defang(${$_[0]});
469                       },
470                     },
471     compiler     => HTML::Mason::Compiler::ToObject->new(
472                       allow_globals        => [qw(%session)],
473                     ),
474   );
475
476   my $rt_interp = new HTML::Mason::Interp (
477     %interp,
478     escape_flags => { 'h' => \&RT::Interface::Web::EscapeUTF8 },
479     compiler     => HTML::Mason::Compiler::ToObject->new(
480                       default_escape_flags => 'h',
481                       allow_globals        => [qw(%session)],
482                     ),
483   );
484
485   ( $fs_interp, $rt_interp );
486
487 }
488
489 =back
490
491 =head1 BUGS
492
493 Lurking in the darkness...
494
495 =head1 SEE ALSO
496
497 L<HTML::Mason>, L<FS>, L<RT>
498
499 =cut
500
501 1;