broadband_snmp export: better MIB selection
[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 Scalar::Util qw( blessed );
60   use Data::Dumper;
61   use Date::Format;
62   use Time::Local;
63   use Time::HiRes;
64   use Time::Duration;
65   use DateTime;
66   use DateTime::Format::Strptime;
67   use FS::Misc::DateTime qw( parse_datetime );
68   use FS::Misc::Geo qw( get_district );
69   use Lingua::EN::Inflect qw(PL);
70   Lingua::EN::Inflect::classical names=>0; #Categorys
71   use Tie::IxHash;
72   use URI;
73   use URI::Escape 3.31;
74   use HTML::Entities;
75   use HTML::TreeBuilder;
76   use HTML::TableExtract qw(tree);
77   use HTML::FormatText;
78   use HTML::Defang;
79   use JSON;
80 #  use XMLRPC::Transport::HTTP;
81 #  use XMLRPC::Lite; # for XMLRPC::Serializer
82   use MIME::Base64;
83   use IO::Handle;
84   use IO::File;
85   use IO::Scalar;
86   #not actually using this yet anyway...# use IPC::Run3 0.036;
87   use Net::Whois::Raw qw(whois);
88   if ( $] < 5.006 ) {
89     eval "use Net::Whois::Raw 0.32 qw(whois)";
90     die $@ if $@;
91   }
92   use Text::CSV_XS;
93   use Spreadsheet::WriteExcel;
94   use Spreadsheet::WriteExcel::Utility;
95   use OLE::Storage_Lite;
96   use Excel::Writer::XLSX;
97   #use Excel::Writer::XLSX::Utility; #redundant with above
98
99   use Business::CreditCard 0.30; #for mask-aware cardtype()
100   use NetAddr::IP;
101   use Net::Ping;
102   use Net::Ping::External;
103   #if CPAN #7815 ever gets fixed# if ( $Net::Ping::External::VERSION <= 0.12 )
104   {
105     no warnings 'redefine';
106     eval 'sub Net::Ping::External::_ping_linux { 
107             my %args = @_;
108             my $command = "ping -s $args{size} -c $args{count} -w $args{timeout} $args{host}";
109             return Net::Ping::External::_ping_system($command, 0);
110           }
111          ';
112     die $@ if $@;
113   }
114   use String::Approx qw(amatch);
115   use Chart::LinesPoints;
116   use Chart::Mountain;
117   use Chart::Bars;
118   use Color::Scheme;
119   use HTML::Widgets::SelectLayers 0.07; #should go away in favor of
120                                         #selectlayers.html
121   use Locale::Country;
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( getotaker dbh datasrc driver_name );
128   use FS::Record qw( qsearch qsearchs fields dbdef
129                     str2time_sql str2time_sql_closing
130                     midnight_sql
131                    );
132   use FS::Conf;
133   use FS::CGI qw(header menubar table itable ntable idiot
134                  eidiot myexit http_header);
135   use FS::UI::Web qw(svc_url);
136   use FS::UI::Web::small_custview qw(small_custview);
137   use FS::UI::bytecount;
138   use FS::Msgcat qw(gettext geterror);
139   use FS::Misc qw( send_email send_fax ocr_image
140                    states_hash counties cities state_label
141                  );
142   use FS::Misc::eps2png qw( eps2png );
143   use FS::Report::FCC_477;
144   use FS::Report::Table;
145   use FS::Report::Table::Monthly;
146   use FS::Report::Table::Daily;
147   use FS::TicketSystem;
148   use FS::NetworkMonitoringSystem;
149   use FS::Tron qw( tron_lint );
150   use FS::Locales;
151   use FS::Maketext qw( mt emt js_mt );
152
153   use FS::agent;
154   use FS::agent_type;
155   use FS::domain_record;
156   use FS::cust_bill;
157   use FS::cust_bill_pay;
158   use FS::cust_credit;
159   use FS::cust_credit_bill;
160   use FS::cust_main;
161   use FS::cust_main::Search qw(smart_search);
162   use FS::cust_main::Import;
163   use FS::cust_main_county;
164   use FS::cust_location;
165   use FS::cust_pay;
166   use FS::cust_pkg;
167   use FS::cust_pkg::Import;
168   use FS::part_pkg_taxclass;
169   use FS::cust_pkg_reason;
170   use FS::cust_refund;
171   use FS::cust_credit_refund;
172   use FS::cust_pay_refund;
173   use FS::cust_svc;
174   use FS::nas;
175   use FS::part_bill_event;
176   use FS::part_event;
177   use FS::part_event_condition;
178   use FS::part_pkg;
179   use FS::part_referral;
180   use FS::part_svc;
181   use FS::part_svc_router;
182   use FS::part_virtual_field;
183   use FS::pay_batch;
184   use FS::pkg_svc;
185   use FS::port;
186   use FS::queue qw(joblisting);
187   use FS::raddb;
188   use FS::session;
189   use FS::svc_acct;
190   use FS::svc_acct_pop qw(popselector);
191   use FS::acct_rt_transaction;
192   use FS::svc_domain;
193   use FS::svc_forward;
194   use FS::svc_www;
195   use FS::router;
196   use FS::addr_block;
197   use FS::svc_broadband;
198   use FS::svc_external;
199   use FS::type_pkgs;
200   use FS::part_export;
201   use FS::part_export_option;
202   use FS::export_svc;
203   use FS::export_device;
204   use FS::msgcat;
205   use FS::rate;
206   use FS::rate_region;
207   use FS::rate_prefix;
208   use FS::rate_detail;
209   use FS::usage_class;
210   use FS::payment_gateway;
211   use FS::agent_payment_gateway;
212   use FS::XMLRPC;
213   use FS::payby;
214   use FS::cdr;
215   use FS::cdr_batch;
216   use FS::inventory_class;
217   use FS::inventory_item;
218   use FS::pkg_category;
219   use FS::pkg_class;
220   use FS::access_user;
221   use FS::access_user_pref;
222   use FS::access_group;
223   use FS::access_usergroup;
224   use FS::access_groupagent;
225   use FS::access_right;
226   use FS::AccessRight;
227   use FS::svc_phone;
228   use FS::phone_device;
229   use FS::part_device;
230   use FS::reason_type;
231   use FS::reason;
232   use FS::cust_main_note;
233   use FS::tax_class;
234   use FS::cust_tax_location;
235   use FS::part_pkg_taxproduct;
236   use FS::part_pkg_taxoverride;
237   use FS::part_pkg_taxrate;
238   use FS::tax_rate;
239   use FS::part_pkg_report_option;
240   use FS::cust_attachment;
241   use FS::h_cust_pkg;
242   use FS::h_inventory_item;
243   use FS::h_svc_acct;
244   use FS::h_svc_broadband;
245   use FS::h_svc_domain;
246   #use FS::h_domain_record;
247   use FS::h_svc_external;
248   use FS::h_svc_forward;
249   use FS::h_svc_phone;
250   #use FS::h_phone_device;
251   use FS::h_svc_www;
252   use FS::cust_statement;
253   use FS::cust_class;
254   use FS::cust_category;
255   use FS::prospect_main;
256   use FS::contact;
257   use FS::phone_type;
258   use FS::svc_pbx;
259   use FS::discount;
260   use FS::cust_pkg_discount;
261   use FS::cust_bill_pkg_discount;
262   use FS::svc_mailinglist;
263   use FS::cgp_rule;
264   use FS::cgp_rule_condition;
265   use FS::cgp_rule_action;
266   use FS::bill_batch;
267   use FS::cust_bill_batch;
268   use FS::rate_time;
269   use FS::rate_time_interval;
270   use FS::msg_template;
271   use FS::part_tag;
272   use FS::acct_snarf;
273   use FS::part_pkg_discount;
274   use FS::svc_cert;
275   use FS::svc_dsl;
276   use FS::qual;
277   use FS::qual_option;
278   use FS::dsl_note;
279   use FS::part_pkg_vendor;
280   use FS::cust_note_class;
281   use FS::svc_port;
282   use FS::lata;
283   use FS::did_vendor;
284   use FS::did_order;
285   use FS::torrus_srvderive;
286   use FS::torrus_srvderive_component;
287   use FS::areacode;
288   use FS::svc_dish;
289   use FS::h_svc_dish;
290   use FS::svc_hardware;
291   use FS::h_svc_hardware;
292   use FS::hardware_class;
293   use FS::hardware_type;
294   use FS::hardware_status;
295   use FS::did_order_item;
296   use FS::msa;
297   use FS::rate_center;
298   use FS::cust_msg;
299   use FS::radius_group;
300   use FS::template_content;
301   use FS::dsl_device;
302   use FS::nas;
303   use FS::nas;
304   use FS::export_nas;
305   use FS::legacy_cust_bill;
306   use FS::rate_tier;
307   use FS::rate_tier_detail;
308   use FS::radius_attr;
309   use FS::discount_plan;
310   use FS::tower;
311   use FS::tower_sector;
312   use FS::sales;
313   use FS::access_groupsales;
314   use FS::contact_class;
315   use FS::part_svc_class;
316   use FS::upload_target;
317   use FS::quotation;
318   use FS::quotation_pkg;
319   use FS::quotation_pkg_discount;
320   use FS::cust_bill_void;
321   use FS::cust_bill_pkg_void;
322   use FS::cust_bill_pkg_detail_void;
323   use FS::cust_bill_pkg_display_void;
324   use FS::cust_bill_pkg_tax_location_void;
325   use FS::cust_bill_pkg_tax_rate_location_void;
326   use FS::cust_tax_exempt_pkg_void;
327   use FS::cust_bill_pkg_discount_void;
328   use FS::agent_pkg_class;
329   use FS::svc_export_machine;
330   use FS::GeocodeCache;
331   # Sammath Naur
332
333   if ( $FS::Mason::addl_handler_use ) {
334     eval $FS::Mason::addl_handler_use;
335     die $@ if $@;
336   }
337
338   if ( %%%RT_ENABLED%%% ) {
339     eval '
340       use lib ( "/opt/rt3/local/lib", "/opt/rt3/lib" );
341       use vars qw($Nobody $SystemUser);
342       use RT;
343       use RT::Util;
344       use RT::Tickets;
345       use RT::Transactions;
346       use RT::Users;
347       use RT::CurrentUser;
348       use RT::Templates;
349       use RT::Queues;
350       use RT::ScripActions;
351       use RT::ScripConditions;
352       use RT::Scrips;
353       use RT::Groups;
354       use RT::GroupMembers;
355       use RT::CustomFields;
356       use RT::CustomFieldValues;
357       use RT::ObjectCustomFieldValues;
358
359       #blah.  manually updated from RT::Interface::Web::Handler
360       use RT::Interface::Web;
361       use MIME::Entity;
362       use Text::Wrapper;
363       use Time::ParseDate;
364       use Time::HiRes;
365       use HTML::Scrubber;
366
367       #blah.  not even in RT::Interface::Web::Handler, just in 
368       #html/NoAuth/css/dhandler and rt-test-dependencies.  ask for it here
369       #to throw a real error instead of just a mysterious unstyled RT
370       use CSS::Squish 0.06;
371
372       use RT::Interface::Web::Request;
373
374       #another undeclared web UI dep (for ticket links graph)
375       use IPC::Run::SafeHandles;
376
377       #slow, unreliable, segfaults and is optional
378       #see rt/html/Ticket/Elements/ShowTransactionAttachments
379       #use Text::Quoted;
380
381       #?#use File::Path qw( rmtree );
382       #?#use File::Glob qw( bsd_glob );
383       #?#use File::Spec::Unix;
384
385     ';
386     die $@ if $@;
387   }
388
389   *CGI::redirect = sub {
390     my $self = shift;
391     my $cookie = '';
392     if ( $_[0] eq '-cookie' ) { #this isn't actually used at the moment
393       (my $x, $cookie) = (shift, shift);
394       $HTML::Mason::r->err_headers_out->add( 'Set-cookie' => $cookie );
395     }
396     my $location = shift;
397
398     use vars qw($m);
399
400     # false laziness w/below
401     if ( defined(@DBIx::Profile::ISA) ) {
402
403       if ( $FS::CurrentUser::CurrentUser->option('show_db_profile') ) {
404
405         #profiling redirect
406
407         my $page =
408           qq!<HTML><BODY>Redirect to <A HREF="$location">$location</A>!.
409           '<BR><BR><PRE>'.
410             ( UNIVERSAL::can(dbh, 'sprintProfile')
411                 ? encode_entities(dbh->sprintProfile())
412                 : 'DBIx::Profile missing sprintProfile method;'.
413                   'unpatched or too old?'                        ).
414           #"\n\n". &sprintAutoProfile().  '</PRE>'.
415           "\n\n".                         '</PRE>'.
416           '</BODY></HTML>';
417
418
419         dbh->{'private_profile'} = {};
420         return $page;
421
422       } else {
423
424         #clear db profile, but normal redirect
425         dbh->{'private_profile'} = {};
426         $m->redirect($location);
427         '';
428
429       }
430
431     } else { #normal redirect
432
433       $m->redirect($location);
434       '';
435
436     }
437
438   };
439   
440   sub include {
441     use vars qw($m);
442     #carp #should just switch to <& &> syntax
443     $m->scomp(@_);
444   }
445
446   sub errorpage {
447     use vars qw($m);
448     $m->comp('/elements/errorpage.html', @_);
449   }
450
451   sub errorpage_popup {
452     use vars qw($m);
453     $m->comp('/elements/errorpage-popup.html', @_);
454   }
455
456   sub redirect {
457     my( $location ) = @_;
458     use vars qw($m);
459     $m->clear_buffer;
460     #false laziness w/above
461     if ( defined(@DBIx::Profile::ISA) ) {
462
463       if ( $FS::CurrentUser::CurrentUser->option('show_db_profile') ) {
464
465         #profiling redirect
466
467         $m->print(
468           qq!<HTML><BODY>Redirect to <A HREF="$location">$location</A>!.
469           '<BR><BR><PRE>'.
470             ( UNIVERSAL::can(dbh, 'sprintProfile')
471                 ? encode_entities(dbh->sprintProfile())
472                 : 'DBIx::Profile missing sprintProfile method;'.
473                   'unpatched or too old?'                        ).
474           #"\n\n". &sprintAutoProfile().  '</PRE>'.
475           "\n\n".                         '</PRE>'.
476           '</BODY></HTML>'
477         );
478
479         dbh->{'private_profile'} = {};
480
481       } else {
482
483         #clear db profile, but normal redirect
484         dbh->{'private_profile'} = {};
485         $m->redirect($location);
486
487       }
488
489     } else { #normal redirect
490
491       $m->redirect($location);
492
493     }
494
495   }
496
497 } # end package HTML::Mason::Commands;
498
499 =head1 SUBROUTINE
500
501 =over 4
502
503 =item mason_interps [ MODE [ OPTION => VALUE ... ] ]
504
505 Returns a list consisting of two HTML::Mason::Interp objects, the first for
506 Freeside pages, and the second for RT pages.
507
508 MODE can be 'apache' or 'standalone'.  If not specified, defaults to 'apache'.
509
510 Options and values can be passed following mode.  Currently available options
511 are:
512
513 I<outbuf> should be set to a scalar reference in standalone mode.
514
515 =cut
516
517 my %defang_opts = ( attribs_to_callback => ['src'], attribs_callback => sub { 1 });
518
519 sub mason_interps {
520   my $mode = shift || 'apache';
521   my %opt = @_;
522
523   #my $request_class = 'HTML::Mason::Request'.
524                       #( $mode eq 'apache' ? '::ApacheHandler' : '' );
525   my $request_class = $mode eq 'standalone' ? 'FS::Mason::StandaloneRequest'
526                                             : 'FS::Mason::Request';
527
528   #not entirely sure it belongs here, but what the hey
529   if ( %%%RT_ENABLED%%% && $mode ne 'standalone' ) {
530     RT::LoadConfig();
531   }
532
533   my $fs_comp_root = '%%%FREESIDE_DOCUMENT_ROOT%%%';
534
535   my %interp = (
536     request_class        => $request_class,
537     data_dir             => '%%%MASONDATA%%%',
538     error_mode           => 'output',
539     error_format         => 'html',
540     ignore_warnings_expr => '.',
541   );
542
543   $interp{out_method} = $opt{outbuf} if $mode eq 'standalone' && $opt{outbuf};
544
545   my $html_defang = new HTML::Defang (%defang_opts);
546
547   #false laziness w/ FS::Maketext js_mt
548   my $js_string_sub = sub {
549     #${$_[0]} =~ s/(['\\\n])/'\\'.($1 eq "\n" ? 'n' : $1)/ge;
550     ${$_[0]} =~ s/(['\\])/\\$1/g;
551     ${$_[0]} =~ s/\r/\\r/g;
552     ${$_[0]} =~ s/\n/\\n/g;
553     # prevent premature termination of the script
554     ${$_[0]} =~ s[</script>][<\\/script>]ig;
555     ${$_[0]} = "'". ${$_[0]}. "'";
556   };
557
558   my $defang_sub = sub {
559     ${$_[0]} = $html_defang->defang(${$_[0]});
560   };
561
562   my $fs_interp = new HTML::Mason::Interp (
563     %interp,
564     comp_root    => $fs_comp_root,
565     escape_flags => { 'js_string'   => $js_string_sub,
566                       'defang'      => $defang_sub,
567                     },
568     compiler     => HTML::Mason::Compiler::ToObject->new(
569                       allow_globals        => [qw(%session)],
570                     ),
571   );
572
573   my $rt_interp = new HTML::Mason::Interp (
574     %interp,
575     comp_root    => [
576                       [ 'rt'       => '%%%FREESIDE_DOCUMENT_ROOT%%%/rt' ],
577                       [ 'freeside' => '%%%FREESIDE_DOCUMENT_ROOT%%%'    ],
578                     ],
579     escape_flags => { 'h'         => \&RT::Interface::Web::EscapeUTF8,
580                       'u'         => \&RT::Interface::Web::EscapeURI,
581                       'j'         => \&RT::Interface::Web::EscapeJS,
582                       'js_string' => $js_string_sub,
583                     },
584     compiler     => HTML::Mason::Compiler::ToObject->new(
585                       default_escape_flags => 'h',
586                       allow_globals        => [qw(%session $DECODED_ARGS)],
587                     ),
588   );
589
590   ( $fs_interp, $rt_interp );
591
592 }
593
594 =back
595
596 =head1 BUGS
597
598 Lurking in the darkness...
599
600 =head1 SEE ALSO
601
602 L<HTML::Mason>, L<FS>, L<RT>
603
604 =cut
605
606 1;