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