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