Merge branch 'master' of git.freeside.biz:/home/git/freeside
[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 Carp;
7 use File::Slurp qw( slurp );
8 use HTML::Mason 1.27; #http://www.masonhq.com/?ApacheModPerl2Redirect
9 use HTML::Mason::Interp;
10 use HTML::Mason::Compiler::ToObject;
11
12 @ISA = qw( Exporter );
13 @EXPORT_OK = qw( mason_interps );
14
15 =head1 NAME
16
17 FS::Mason - Initialize the Mason environment
18
19 =head1 SYNOPSIS
20
21   use FS::Mason qw( mason_interps );
22
23   my( $fs_interp, $rt_interp ) = mason_interps('apache');
24
25   #OR
26
27   my( $fs_interp, $rt_interp ) = mason_interps('standalone'); #XXX name?
28
29 =head1 DESCRIPTION
30
31 Initializes the Mason environment, loads all Freeside and RT libraries, etc.
32
33 =cut
34
35 $addl_handler_use = '';
36 my $addl_handler_use_file = '%%%FREESIDE_CONF%%%/addl_handler_use.pl';
37 if ( -e $addl_handler_use_file ) {
38   $addl_handler_use = slurp( $addl_handler_use_file );
39 }
40
41 # List of modules that you want to use from components (see Admin
42 # manual for details)
43 {
44   package HTML::Mason::Commands;
45
46   use strict;
47   use vars qw( %session );
48   use CGI 3.39 qw(-private_tempfiles); #3.39 for cpan#37365
49
50   #use CGI::Carp qw(fatalsToBrowser);
51   use CGI::Cookie;
52   use List::Util qw( max min sum );
53   use List::MoreUtils qw( first_index uniq );
54   use Scalar::Util qw( blessed looks_like_number );
55   use Data::Dumper;
56   use Date::Format;
57   use Time::Local;
58   use Time::HiRes;
59   use Time::Duration;
60   use DateTime;
61   use DateTime::Format::Strptime;
62   use FS::Misc::DateTime qw( parse_datetime );
63   use FS::Misc::Geo qw( get_district );
64   use Lingua::EN::Inflect qw(PL);
65   Lingua::EN::Inflect::classical names=>0; #Categorys
66   use Tie::IxHash;
67   use URI;
68   use URI::Escape 3.31;
69   use HTML::Entities;
70   use HTML::TreeBuilder;
71   use HTML::TableExtract qw(tree);
72   use HTML::FormatText;
73   use HTML::Defang;
74   use Cpanel::JSON::XS;
75   use MIME::Base64;
76   use IO::Handle;
77   use IO::File;
78   use IO::Scalar;
79   use IO::String;
80   use File::Slurp qw( slurp );
81   #not actually using this yet anyway...# use IPC::Run3 0.036;
82   use Net::Whois::Raw qw(whois);
83   if ( $] < 5.006 ) {
84     eval "use Net::Whois::Raw 0.32 qw(whois)";
85     die $@ if $@;
86   }
87   use Text::CSV_XS;
88   use Spreadsheet::WriteExcel;
89   use Spreadsheet::WriteExcel::Utility;
90   use OLE::Storage_Lite;
91   use Excel::Writer::XLSX;
92   #use Excel::Writer::XLSX::Utility; #redundant with above
93
94   use Business::CreditCard 0.36; #for best-effort cardtype() (60xx as Discover)
95   use NetAddr::IP;
96   use Net::MAC::Vendor;
97   use Net::Ping;
98   use Net::Ping::External;
99   #if CPAN #7815 ever gets fixed# if ( $Net::Ping::External::VERSION <= 0.12 )
100   {
101     no warnings 'redefine';
102     eval 'sub Net::Ping::External::_ping_linux { 
103             my %args = @_;
104             my $command = "ping -s $args{size} -c $args{count} -w $args{timeout} $args{host}";
105             return Net::Ping::External::_ping_system($command, 0);
106           }
107          ';
108     die $@ if $@;
109   }
110   use String::Approx qw(amatch);
111   use Chart::LinesPoints;
112   use Chart::Mountain;
113   use Chart::Bars;
114   use Color::Scheme;
115   use HTML::Widgets::SelectLayers 0.07; #should go away in favor of
116                                         #selectlayers.html
117   use Locale::Country;
118   #use FS::geocode_Mixin; #for its code2country
119   use Locale::Currency;
120   use Locale::Currency::Format;
121   use Business::US::USPS::WebTools::AddressStandardization;
122   use Geo::GoogleEarth::Pluggable;
123   use LWP::UserAgent;
124   use Storable qw( nfreeze thaw );
125   use FS;
126   use FS::UID qw( dbh datasrc driver_name );
127   use FS::Record qw( qsearch qsearchs fields dbdef
128                     str2time_sql str2time_sql_closing
129                     midnight_sql regexp_sql
130                    );
131   use FS::Conf;
132   use FS::CGI qw(header menubar table itable ntable idiot
133                  eidiot myexit http_header);
134   use FS::UI::Web qw(svc_url random_id
135                   get_page_pref  set_page_pref);
136   use FS::UI::Web::small_custview qw(small_custview);
137   use FS::UI::bytecount;
138   use FS::UI::REST qw( rest_auth rest_uri_remain encode_rest );
139   use FS::Msgcat qw(gettext geterror);
140   use FS::Misc qw( send_email send_fax ocr_image
141                    states_hash counties cities state_label
142                    card_types
143                  );
144   use FS::Misc::eps2png qw( eps2png );
145   use FS::Report::FCC_477;
146   use FS::Report::Table;
147   use FS::Report::Table::Monthly;
148   use FS::Report::Table::Daily;
149   use FS::Report::Tax::ByName;
150   use FS::Report::Tax::All;
151   use FS::TicketSystem;
152   use FS::NetworkMonitoringSystem;
153   use FS::Tron qw( tron_lint );
154   use FS::Locales;
155   use FS::Maketext qw( mt emt js_mt );
156
157   use FS::Query;
158
159   use FS::agent;
160   use FS::agent_type;
161   use FS::domain_record;
162   use FS::cust_bill;
163   use FS::cust_bill_pay;
164   use FS::cust_credit;
165   use FS::cust_credit_bill;
166   use FS::cust_main;
167   use FS::h_cust_main;
168   use FS::cust_main::Search qw(smart_search);
169   use FS::cust_main::Import;
170   use FS::cust_main::Import_Charges;
171   use FS::cust_main_county;
172   use FS::cust_location;
173   use FS::cust_pay;
174   use FS::cust_pkg;
175   use FS::cust_pkg::Import;
176   use FS::part_pkg_taxclass;
177   use FS::cust_pkg_reason;
178   use FS::cust_refund;
179   use FS::cust_credit_refund;
180   use FS::cust_pay_refund;
181   use FS::cust_svc;
182   use FS::nas;
183   use FS::part_event;
184   use FS::part_event_condition;
185   use FS::part_pkg;
186   use FS::part_referral;
187   use FS::part_svc;
188   use FS::part_svc_router;
189   use FS::part_virtual_field;
190   use FS::pay_batch;
191   use FS::pkg_svc;
192   use FS::port;
193   use FS::queue qw(joblisting);
194   use FS::raddb;
195   use FS::session;
196   use FS::svc_acct;
197   use FS::svc_acct_pop qw(popselector);
198   use FS::acct_rt_transaction;
199   use FS::svc_domain;
200   use FS::svc_forward;
201   use FS::svc_www;
202   use FS::router;
203   use FS::addr_block;
204   use FS::svc_broadband;
205   use FS::svc_external;
206   use FS::type_pkgs;
207   use FS::part_export;
208   use FS::part_export_option;
209   use FS::export_svc;
210   use FS::export_device;
211   use FS::msgcat;
212   use FS::rate;
213   use FS::rate_region;
214   use FS::rate_prefix;
215   use FS::rate_detail;
216   use FS::usage_class;
217   use FS::payment_gateway;
218   use FS::agent_payment_gateway;
219   use FS::payby;
220   use FS::cdr;
221   use FS::cdr_batch;
222   use FS::inventory_class;
223   use FS::inventory_item;
224   use FS::pkg_category;
225   use FS::pkg_class;
226   use FS::access_user;
227   use FS::access_user_pref;
228   use FS::access_group;
229   use FS::access_usergroup;
230   use FS::access_groupagent;
231   use FS::access_right;
232   use FS::AccessRight;
233   use FS::svc_phone;
234   use FS::phone_device;
235   use FS::part_device;
236   use FS::reason_type;
237   use FS::reason;
238   use FS::cust_main_note;
239   use FS::tax_class;
240   use FS::cust_tax_location;
241   use FS::part_pkg_taxproduct;
242   use FS::part_pkg_taxoverride;
243   use FS::part_pkg_taxrate;
244   use FS::tax_rate;
245   use FS::part_pkg_report_option;
246   use FS::cust_attachment;
247   use FS::h_cust_pkg;
248   use FS::h_inventory_item;
249   use FS::h_svc_acct;
250   use FS::h_svc_broadband;
251   use FS::h_svc_domain;
252   #use FS::h_domain_record;
253   use FS::h_svc_external;
254   use FS::h_svc_forward;
255   use FS::h_svc_phone;
256   #use FS::h_phone_device;
257   use FS::h_svc_www;
258   use FS::cust_statement;
259   use FS::cust_class;
260   use FS::cust_category;
261   use FS::prospect_main;
262   use FS::contact;
263   use FS::phone_type;
264   use FS::svc_pbx;
265   use FS::discount;
266   use FS::cust_pkg_discount;
267   use FS::cust_bill_pkg_discount;
268   use FS::svc_mailinglist;
269   use FS::cgp_rule;
270   use FS::cgp_rule_condition;
271   use FS::cgp_rule_action;
272   use FS::bill_batch;
273   use FS::cust_bill_batch;
274   use FS::rate_time;
275   use FS::rate_time_interval;
276   use FS::msg_template;
277   use FS::part_tag;
278   use FS::acct_snarf;
279   use FS::part_pkg_discount;
280   use FS::svc_cert;
281   use FS::svc_dsl;
282   use FS::qual;
283   use FS::qual_option;
284   use FS::dsl_note;
285   use FS::part_pkg_vendor;
286   use FS::cust_note_class;
287   use FS::svc_port;
288   use FS::lata;
289   use FS::did_vendor;
290   use FS::did_order;
291   use FS::torrus_srvderive;
292   use FS::torrus_srvderive_component;
293   use FS::areacode;
294   use FS::svc_dish;
295   use FS::h_svc_dish;
296   use FS::svc_hardware;
297   use FS::h_svc_hardware;
298   use FS::hardware_class;
299   use FS::hardware_type;
300   use FS::hardware_status;
301   use FS::did_order_item;
302   use FS::msa;
303   use FS::rate_center;
304   use FS::cust_msg;
305   use FS::radius_group;
306   use FS::template_content;
307   use FS::dsl_device;
308   use FS::nas;
309   use FS::nas;
310   use FS::export_nas;
311   use FS::legacy_cust_bill;
312   use FS::rate_tier;
313   use FS::rate_tier_detail;
314   use FS::radius_attr;
315   use FS::discount_plan;
316   use FS::tower;
317   use FS::tower_sector;
318   use FS::sales;
319   use FS::contact_class;
320   use FS::part_svc_class;
321   use FS::upload_target;
322   use FS::quotation;
323   use FS::quotation_pkg;
324   use FS::quotation_pkg_discount;
325   use FS::cust_bill_void;
326   use FS::cust_bill_pkg_void;
327   use FS::cust_bill_pkg_detail_void;
328   use FS::cust_bill_pkg_display_void;
329   use FS::cust_bill_pkg_tax_location_void;
330   use FS::cust_bill_pkg_tax_rate_location_void;
331   use FS::cust_tax_exempt_pkg_void;
332   use FS::cust_bill_pkg_discount_void;
333   use FS::agent_pkg_class;
334   use FS::svc_export_machine;
335   use FS::GeocodeCache;
336   use FS::log;
337   use FS::log_context;
338   use FS::part_pkg_usage_class;
339   use FS::cust_pkg_usage;
340   use FS::part_pkg_usage_class;
341   use FS::part_pkg_usage;
342   use FS::cdr_cust_pkg_usage;
343   use FS::part_pkg_msgcat;
344   use FS::svc_cable;
345   use FS::agent_currency;
346   use FS::currency_exchange;
347   use FS::part_pkg_currency;
348   use FS::cust_payby;
349   use FS::vend_main;
350   use FS::vend_class;
351   use FS::vend_bill;
352   use FS::vend_pay;
353   use FS::vend_bill_pay;
354   use FS::sales_pkg_class;
355   use FS::svc_alarm;
356   use FS::cable_model;
357   use FS::invoice_mode;
358   use FS::invoice_conf;
359   use FS::cable_provider;
360   use FS::cust_credit_void;
361   use FS::discount_class;
362   use FS::alarm_system;
363   use FS::alarm_type;
364   use FS::alarm_station;
365   use FS::addr_range;
366   use FS::svc_conferencing;
367   use FS::conferencing_type;
368   use FS::conferencing_quality;
369   use FS::svc_video;
370   use FS::part_pkg_usageprice;
371   use FS::cust_pkg_usageprice;
372   use FS::pbx_extension;
373   use FS::pbx_device;
374   use FS::extension_device;
375   use FS::cust_main_credit_limit;
376   use FS::cust_event_fee;
377   use FS::part_fee;
378   use FS::cust_bill_pkg_fee;
379   use FS::part_fee_msgcat;
380   use FS::part_fee_usage;
381   use FS::sched_item;
382   use FS::sched_avail;
383   use FS::export_batch;
384   use FS::export_batch_item;
385   use FS::part_pkg_fcc_option;
386   use FS::state;
387   use FS::state;
388   use FS::queue_stat;
389   use FS::deploy_zone;
390   use FS::deploy_zone_block;
391   use FS::deploy_zone_vertex;
392   use FS::TaxEngine;
393   use FS::tax_status;
394   use FS::circuit_type;
395   use FS::circuit_provider;
396   use FS::circuit_termination;
397   use FS::svc_circuit;
398   use FS::cust_credit_source_bill_pkg;
399   use FS::prospect_contact;
400   use FS::cust_contact;
401   use FS::legacy_cust_history;
402   use FS::quotation_pkg_tax;
403   use FS::cust_pkg_reason_fee;
404   use FS::part_svc_link;
405   use FS::access_user_log;
406   use FS::report_batch;
407   use FS::report_batch;
408   use FS::report_batch;
409   use FS::report_batch;
410   use FS::password_history;
411   use FS::svc_fiber;
412   use FS::fiber_olt;
413   use FS::olt_site;
414   use FS::access_user_page_pref;
415   use FS::part_svc_msgcat;
416   use FS::commission_schedule;
417   use FS::commission_rate;
418   use FS::saved_search;
419   # Sammath Naur
420
421   if ( $FS::Mason::addl_handler_use ) {
422     eval $FS::Mason::addl_handler_use;
423     die $@ if $@;
424   }
425
426   if ( %%%RT_ENABLED%%% ) {
427     eval '
428       use lib ( "/opt/rt3/local/lib", "/opt/rt3/lib" );
429       use vars qw($Nobody $SystemUser);
430       use RT;
431       use RT::Util;
432       use RT::Tickets;
433       use RT::Transactions;
434       use RT::Users;
435       use RT::CurrentUser;
436       use RT::Templates;
437       use RT::Queues;
438       use RT::ScripActions;
439       use RT::ScripConditions;
440       use RT::Scrips;
441       use RT::Groups;
442       use RT::GroupMembers;
443       use RT::CustomFields;
444       use RT::CustomFieldValues;
445       use RT::ObjectCustomFieldValues;
446
447       use RT::Interface::Web::Handler;
448
449       #blah.  not even in RT::Interface::Web::Handler, just in 
450       #html/NoAuth/css/dhandler and rt-test-dependencies.  ask for it here
451       #to throw a real error instead of just a mysterious unstyled RT
452       use CSS::Squish 0.06;
453
454       #another undeclared web UI dep (for ticket links graph)
455       use IPC::Run::SafeHandles;
456
457       #slow, unreliable, segfaults and is optional
458       #see rt/html/Ticket/Elements/ShowTransactionAttachments
459       #use Text::Quoted;
460
461       #?#use File::Path qw( rmtree );
462       #?#use File::Glob qw( bsd_glob );
463       #?#use File::Spec::Unix;
464
465     ';
466     die $@ if $@;
467   }
468
469   no warnings 'redefine';
470   *CGI::redirect = sub {
471     my $self = shift;
472     my $cookie = '';
473     if ( $_[0] eq '-cookie' ) { #this isn't actually used at the moment
474       (my $x, $cookie) = (shift, shift);
475       $HTML::Mason::r->err_headers_out->add( 'Set-cookie' => $cookie );
476     }
477     my $location = shift;
478
479     use vars qw($m);
480
481     # false laziness w/below
482     if ( @DBIx::Profile::ISA ) {
483
484       if ( $FS::CurrentUser::CurrentUser->option('show_db_profile') ) {
485
486         #profiling redirect
487
488         my $page =
489           qq!<HTML><BODY>Redirect to <A HREF="$location">$location</A>!.
490           '<BR><BR><PRE>'.
491             ( UNIVERSAL::can(dbh, 'sprintProfile')
492                 ? encode_entities(dbh->sprintProfile())
493                 : 'DBIx::Profile missing sprintProfile method;'.
494                   'unpatched or too old?'                        ).
495           #"\n\n". &sprintAutoProfile().  '</PRE>'.
496           "\n\n".                         '</PRE>'.
497           '</BODY></HTML>';
498
499
500         dbh->{'private_profile'} = {};
501         return $page;
502
503       } else {
504
505         #clear db profile, but normal redirect
506         dbh->{'private_profile'} = {};
507         $m->redirect($location);
508         '';
509
510       }
511
512     } else { #normal redirect
513
514       $m->redirect($location);
515       '';
516
517     }
518
519   };
520   
521   sub include {
522     use vars qw($m);
523     #warn 'include deprecated; use an HTML::Mason <& &> style include (or $m->scomp) at '. $m->callers(0)->path. "\n";
524     $m->scomp(@_);
525   }
526
527   sub errorpage {
528     use vars qw($m);
529     $m->comp('/elements/errorpage.html', @_);
530   }
531
532   sub errorpage_popup {
533     use vars qw($m);
534     $m->comp('/elements/errorpage-popup.html', @_);
535   }
536
537   sub redirect {
538     my( $location ) = @_;
539     use vars qw($m);
540     $m->clear_buffer;
541     #false laziness w/above
542     if ( @DBIx::Profile::ISA ) {
543
544       if ( $FS::CurrentUser::CurrentUser->option('show_db_profile') ) {
545
546         #profiling redirect
547
548         $m->print(
549           qq!<HTML><BODY>Redirect to <A HREF="$location">$location</A>!.
550           '<BR><BR><PRE>'.
551             ( UNIVERSAL::can(dbh, 'sprintProfile')
552                 ? encode_entities(dbh->sprintProfile())
553                 : 'DBIx::Profile missing sprintProfile method;'.
554                   'unpatched or too old?'                        ).
555           #"\n\n". &sprintAutoProfile().  '</PRE>'.
556           "\n\n".                         '</PRE>'.
557           '</BODY></HTML>'
558         );
559
560         dbh->{'private_profile'} = {};
561
562       } else {
563
564         #clear db profile, but normal redirect
565         dbh->{'private_profile'} = {};
566         $m->redirect($location);
567
568       }
569
570     } else { #normal redirect
571
572       $m->redirect($location);
573
574     }
575
576   }
577
578 } # end package HTML::Mason::Commands;
579
580 =head1 SUBROUTINES
581
582 =over 4
583
584 =item mason_interps [ MODE [ OPTION => VALUE ... ] ]
585
586 Returns a list consisting of two HTML::Mason::Interp objects, the first for
587 Freeside pages, and the second for RT pages.
588
589 MODE can be 'apache' or 'standalone'.  If not specified, defaults to 'apache'.
590
591 Options and values can be passed following mode.  Currently available options
592 are:
593
594 I<outbuf> should be set to a scalar reference in standalone mode.
595
596 =cut
597
598 my %defang_opts = ( attribs_to_callback => ['src'], attribs_callback => sub { 1 });
599
600 sub mason_interps {
601   my $mode = shift || 'apache';
602   my %opt = @_;
603
604   #my $request_class = 'HTML::Mason::Request'.
605                       #( $mode eq 'apache' ? '::ApacheHandler' : '' );
606   my $request_class = $mode eq 'standalone' ? 'FS::Mason::StandaloneRequest'
607                                             : 'FS::Mason::Request';
608
609   #not entirely sure it belongs here, but what the hey
610   if ( %%%RT_ENABLED%%% && $mode ne 'standalone' ) {
611     RT::LoadConfig();
612   }
613
614   my $fs_comp_root = '%%%FREESIDE_DOCUMENT_ROOT%%%';
615
616   my %interp = (
617     request_class        => $request_class,
618     data_dir             => '%%%MASONDATA%%%',
619     error_mode           => 'output',
620     error_format         => 'html',
621     ignore_warnings_expr => '.',
622   );
623
624   $interp{out_method} = $opt{outbuf} if $mode eq 'standalone' && $opt{outbuf};
625
626   my $html_defang = new HTML::Defang (%defang_opts);
627
628   #false laziness w/ FS::Maketext js_mt
629   my $js_string_sub = sub {
630     #${$_[0]} =~ s/(['\\\n])/'\\'.($1 eq "\n" ? 'n' : $1)/ge;
631     ${$_[0]} =~ s/(['\\])/\\$1/g;
632     ${$_[0]} =~ s/\r/\\r/g;
633     ${$_[0]} =~ s/\n/\\n/g;
634     # prevent premature termination of the script
635     ${$_[0]} =~ s[</script>][<\\/script>]ig;
636     ${$_[0]} = "'". ${$_[0]}. "'";
637   };
638
639   my $defang_sub = sub {
640     ${$_[0]} = $html_defang->defang(${$_[0]});
641   };
642
643   my $fs_interp = new HTML::Mason::Interp (
644     %interp,
645     comp_root    => $fs_comp_root,
646     escape_flags => { 'js_string'   => $js_string_sub,
647                       'defang'      => $defang_sub,
648                     },
649     compiler     => HTML::Mason::Compiler::ToObject->new(
650                       allow_globals        => [qw(%session)],
651                     ),
652   );
653
654   my $rt_interp = new HTML::Mason::Interp (
655     %interp,
656     comp_root    => [
657                       [ 'rt'       => '%%%FREESIDE_DOCUMENT_ROOT%%%/rt' ],
658                       [ 'freeside' => '%%%FREESIDE_DOCUMENT_ROOT%%%'    ],
659                     ],
660     escape_flags => { 'h'         => \&RT::Interface::Web::EscapeHTML,
661                       #u and j aren't used anymore?  :/
662                       'u'         => \&RT::Interface::Web::EscapeURI,
663                       'j'         => \&RT::Interface::Web::EscapeJS,
664                       'js_string' => $js_string_sub,
665                     },
666     compiler     => HTML::Mason::Compiler::ToObject->new(
667                       default_escape_flags => 'h',
668                       allow_globals        => [qw(%session $DECODED_ARGS)],
669                     ),
670   );
671
672   ( $fs_interp, $rt_interp );
673
674 }
675
676 =item child_init
677
678 Per-process Apache child initialization code.
679
680 Calls srand() to re-seed Perl's PRNG so that multiple children do not generate
681 the same "random" numbers.
682
683 Works around a Net::SSLeay connection error by creating and deleting an SSL
684 context, so subsequent connections do not error out with a CTX_new (900 NET OR
685 SSL ERROR).  See http://bugs.debian.org/830152
686
687 =cut
688
689 sub child_init {
690   #my ($pool, $server) = @_; #the child process pool (APR::Pool) and the server object (Apache2::ServerRec).
691
692   srand();
693
694   #{
695     use Net::SSLeay;
696     package Net::SSLeay;
697     initialize();
698     my $bad_ctx = new_x_ctx();
699     while ( ERR_get_error() ) {}; #print_errs('CTX_new');
700     CTX_free($bad_ctx);
701   #}
702
703 }
704
705 =back
706
707 =head1 BUGS
708
709 Lurking in the darkness...
710
711 =head1 SEE ALSO
712
713 L<HTML::Mason>, L<FS>, L<RT>
714
715 =cut
716
717 1;