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