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