useful stuff for webdemo & profiling
[freeside.git] / htetc / handler.pl
1 #!/usr/bin/perl
2
3 package HTML::Mason;
4
5 use strict;
6 use vars qw($r);
7 use HTML::Mason 1.27; #http://www.masonhq.com/?ApacheModPerl2Redirect
8 use HTML::Mason::Interp;
9 use HTML::Mason::Compiler::ToObject;
10
11 # Bring in ApacheHandler, necessary for mod_perl integration.
12 # Uncomment the second line (and comment the first) to use
13 # Apache::Request instead of CGI.pm to parse arguments.
14 use HTML::Mason::ApacheHandler;
15 # use HTML::Mason::ApacheHandler (args_method=>'mod_perl');
16
17 ###use Module::Refresh;###
18
19 # List of modules that you want to use from components (see Admin
20 # manual for details)
21 #{  package HTML::Mason::Commands;
22 #   use CGI;
23 #}
24
25 if ( %%%RT_ENABLED%%% ) {
26  eval '
27    use lib ( "/opt/rt3/local/lib", "/opt/rt3/lib" );
28    use RT;
29    use vars qw($Nobody $SystemUser);
30    RT::LoadConfig();
31  ';
32  die $@ if $@;
33 }
34
35 # Create Mason objects
36
37 my %interp = (
38   request_class        => 'HTML::Mason::Request::ApacheHandler',
39   data_dir             => '%%%MASONDATA%%%',
40   error_mode           => 'output',
41   error_format         => 'html',
42   ignore_warnings_expr => '.',
43   comp_root            => [
44                             [ 'freeside' => '%%%FREESIDE_DOCUMENT_ROOT%%%'    ],
45                             [ 'rt'       => '%%%FREESIDE_DOCUMENT_ROOT%%%/rt' ],
46                           ],
47 );
48
49 my $fs_interp = new HTML::Mason::Interp (
50   %interp,
51   escape_flags => { 'js_string' => sub {
52                       #${$_[0]} =~ s/(['\\\n])/'\\'.($1 eq "\n" ? 'n' : $1)/ge;
53                       ${$_[0]} =~ s/(['\\])/\\$1/g;
54                       ${$_[0]} =~ s/\n/\\n/g;
55                       ${$_[0]} = "'". ${$_[0]}. "'";
56                     }
57                   },
58 );
59
60 my $rt_interp = new HTML::Mason::Interp (
61   %interp,
62   escape_flags => { 'h' => \&RT::Interface::Web::EscapeUTF8 },
63   compiler     => HTML::Mason::Compiler::ToObject->new(
64                     default_escape_flags => 'h',
65                     allow_globals        => [qw(%session)],
66                   ),
67 );
68
69 my $ah = new HTML::Mason::ApacheHandler (
70   interp      => $fs_interp,
71   args_method => 'CGI', #(and FS too)
72 );
73
74 # Activate the following if running httpd as root (the normal case).
75 # Resets ownership of all files created by Mason at startup.
76 #
77 #chown (Apache->server->uid, Apache->server->gid, $interp->files_written);
78
79 sub handler
80 {
81     ($r) = @_;
82
83     # If you plan to intermix images in the same directory as
84     # components, activate the following to prevent Mason from
85     # evaluating image files as components.
86     #
87     #return -1 if $r->content_type && $r->content_type !~ m|^text/|i;
88
89     #rar
90     { package HTML::Mason::Commands;
91       use strict;
92       use vars qw( $cgi $p $fsurl);
93       use vars qw( %session );
94       use CGI 3.29 qw(-private_tempfiles); #3.29 to fix RT attachment problems
95
96       #breaks quick payment entry
97       #http://rt.cpan.org/Public/Bug/Display.html?id=37365
98       die "CGI.pm v3.38 is broken, use any other version >= 3.29".
99           " (Debian 5.0?  aptitude remove libcgi-pm-perl)"
100         if $CGI::VERSION == 3.38;
101
102       #use CGI::Carp qw(fatalsToBrowser);
103       use List::Util qw( max min );
104       use Date::Format;
105       use Date::Parse;
106       use Time::Local;
107       use Time::Duration;
108       use DateTime;
109       use DateTime::Format::Strptime;
110       use Lingua::EN::Inflect qw(PL);
111       use Tie::IxHash;
112       use URI::URL;
113       use URI::Escape;
114       use HTML::Entities;
115       use HTML::TreeBuilder;
116       use HTML::FormatText;
117       use JSON;
118       use IO::Handle;
119       use IO::File;
120       use IO::Scalar;
121       use Net::Whois::Raw qw(whois);
122       if ( $] < 5.006 ) {
123         eval "use Net::Whois::Raw 0.32 qw(whois)";
124         die $@ if $@;
125       }
126       use Text::CSV_XS;
127       use Spreadsheet::WriteExcel;
128       use Business::CreditCard 0.30; #for mask-aware cardtype()
129       use NetAddr::IP;
130       use String::Approx qw(amatch);
131       use Chart::LinesPoints;
132       use Chart::Mountain;
133       use Color::Scheme;
134       use HTML::Widgets::SelectLayers 0.07;
135       use Locale::Country;
136       use FS;
137       use FS::UID qw( adminsuidsetup cgisuidsetup getotaker
138                       dbh datasrc driver_name
139                     );
140       use FS::Record qw( qsearch qsearchs fields dbdef
141                         str2time_sql str2time_sql_closing
142                        );
143       use FS::Conf;
144       use FS::CGI qw(header menubar popurl rooturl table itable ntable idiot
145                      eidiot myexit http_header);
146       use FS::UI::Web qw(svc_url);
147       use FS::UI::Web::small_custview qw(small_custview);
148       use FS::UI::bytecount;
149       use FS::Msgcat qw(gettext geterror);
150       use FS::Misc qw( send_email send_fax states_hash counties state_label );
151       use FS::Report::Table::Monthly;
152       use FS::TicketSystem;
153
154       use FS::agent;
155       use FS::agent_type;
156       use FS::domain_record;
157       use FS::cust_bill;
158       use FS::cust_bill_pay;
159       use FS::cust_credit;
160       use FS::cust_credit_bill;
161       use FS::cust_main qw(smart_search);
162       use FS::cust_main_county;
163       use FS::part_pkg_taxclass;
164       use FS::cust_pay;
165       use FS::cust_pkg;
166       use FS::cust_pkg_reason;
167       use FS::cust_refund;
168       use FS::cust_credit_refund;
169       use FS::cust_pay_refund;
170       use FS::cust_svc;
171       use FS::nas;
172       use FS::part_bill_event;
173       use FS::part_pkg;
174       use FS::part_referral;
175       use FS::part_svc;
176       use FS::part_svc_router;
177       use FS::part_virtual_field;
178       use FS::pay_batch;
179       use FS::pkg_svc;
180       use FS::port;
181       use FS::queue qw(joblisting);
182       use FS::raddb;
183       use FS::session;
184       use FS::svc_acct;
185       use FS::svc_acct_pop qw(popselector);
186       use FS::svc_domain;
187       use FS::svc_forward;
188       use FS::svc_www;
189       use FS::router;
190       use FS::addr_block;
191       use FS::svc_broadband;
192       use FS::svc_external;
193       use FS::type_pkgs;
194       use FS::part_export;
195       use FS::part_export_option;
196       use FS::export_svc;
197       use FS::msgcat;
198       use FS::rate;
199       use FS::rate_region;
200       use FS::rate_prefix;
201       use FS::payment_gateway;
202       use FS::agent_payment_gateway;
203       use FS::XMLRPC;
204       use FS::payby;
205       use FS::cdr;
206       use FS::inventory_class;
207       use FS::inventory_item;
208       use FS::pkg_class;
209       use FS::access_user;
210       use FS::access_group;
211       use FS::access_usergroup;
212       use FS::access_groupagent;
213       use FS::access_right;
214       use FS::AccessRight;
215       use FS::svc_phone;
216       use FS::reason_type;
217       use FS::reason;
218       use FS::cust_main_note;
219
220       if ( %%%RT_ENABLED%%% ) {
221         eval '
222           use RT::Tickets;
223           use RT::Transactions;
224           use RT::Users;
225           use RT::CurrentUser;
226           use RT::Templates;
227           use RT::Queues;
228           use RT::ScripActions;
229           use RT::ScripConditions;
230           use RT::Scrips;
231           use RT::Groups;
232           use RT::GroupMembers;
233           use RT::CustomFields;
234           use RT::CustomFieldValues;
235           use RT::ObjectCustomFieldValues;
236
237           use RT::Interface::Web;
238           use MIME::Entity;
239           use Text::Wrapper;
240           use CGI::Cookie;
241           use Time::ParseDate;
242           use HTML::Scrubber;
243           #use Text::Quoted; #slow, unreliable, segfaults and is optional
244           use Time::HiRes;
245         ';
246         die $@ if $@;
247       }
248
249       *CGI::redirect = sub {
250         my( $self, $location ) = @_;
251         use vars qw($m);
252
253         # false laziness w/below
254         if ( defined(@DBIx::Profile::ISA) ) { #profiling redirect
255
256           my $page =
257             qq!<HTML><BODY>Redirect to <A HREF="$location">$location</A>!.
258             '<BR><BR><PRE>'.
259               ( UNIVERSAL::can(dbh, 'sprintProfile')
260                   ? encode_entities(dbh->sprintProfile())
261                   : 'DBIx::Profile missing sprintProfile method;'.
262                     'unpatched or too old?'                        ).
263             #"\n\n". &sprintAutoProfile().  '</PRE>'.
264             "\n\n".                         '</PRE>'.
265             '</BODY></HTML>';
266           dbh->{'private_profile'} = {};
267           return $page;
268
269         } else { #normal redirect
270
271           $m->redirect($location);
272           '';
273
274         }
275
276       };
277       
278       if ( $HTML::Mason::r->filename !~ /\/rt\/.*NoAuth/ ) { #not RT images/JS
279
280         $cgi = new CGI;
281         &cgisuidsetup($cgi);
282         #&cgisuidsetup($r);
283         $p = popurl(2);
284         $fsurl = rooturl();
285
286       } elsif ( $HTML::Mason::r->filename =~ /\/rt\/REST\/.*NoAuth/ ) {
287
288         #need to log somebody in for the mail gw
289
290         ##old installs w/fs_selfs or selfserv??
291         #&adminsuidsetup('fs_selfservice');
292
293         &adminsuidsetup('fs_queue');
294
295       }
296
297       sub include {
298         use vars qw($m);
299         $m->scomp(@_);
300       }
301
302       sub errorpage {
303         use vars qw($m);
304         $m->comp('/elements/errorpage.html', @_);
305       }
306
307       sub redirect {
308         my( $location ) = @_;
309         use vars qw($m);
310         $m->clear_buffer;
311         #false laziness w/above
312         if ( defined(@DBIx::Profile::ISA) ) { #profiling redirect
313
314           $m->print(
315             qq!<HTML><BODY>Redirect to <A HREF="$location">$location</A>!.
316             '<BR><BR><PRE>'.
317               ( UNIVERSAL::can(dbh, 'sprintProfile')
318                   ? encode_entities(dbh->sprintProfile())
319                   : 'DBIx::Profile missing sprintProfile method;'.
320                     'unpatched or too old?'                        ).
321             #"\n\n". &sprintAutoProfile().  '</PRE>'.
322             "\n\n".                         '</PRE>'.
323             '</BODY></HTML>'
324           );
325           dbh->{'private_profile'} = {};
326
327           #whew.  removing this is all that's needed to fix the annoying
328           #blank-page-instead-of-profiling-redirect-when-called-from-an-include
329           #bug triggered by mason 1.32
330           #my $rv = $m->abort(200);
331
332         } else { #normal redirect
333
334           $m->redirect($location);
335
336         }
337
338       }
339
340     } # end package HTML::Mason::Commands;
341
342     ###Module::Refresh->refresh;###
343
344     #$r->content_type('text/html; charset=utf-8');
345     $r->content_type('text/html; charset=iso-8859-1');
346     #eorar
347
348     my $headers = $r->headers_out;
349     $headers->{'Cache-control'} = 'no-cache';
350     #$r->no_cache(1);
351     $headers->{'Expires'} = '0';
352
353 #    $r->send_http_header;
354
355     if ( $r->filename =~ /\/rt\// ) { #RT
356
357       $ah->interp($rt_interp);
358
359       local $SIG{__WARN__};
360       local $SIG{__DIE__};
361
362       RT::Init();
363
364       # We don't need to handle non-text, non-xml items
365       return -1 if defined( $r->content_type )
366                 && $r->content_type !~ m!(^text/|\bxml\b)!io;
367
368     } else {
369
370       $ah->interp($fs_interp);
371
372     }
373
374     my %session;
375     my $status;
376     eval { $status = $ah->handle_request($r); };
377 #!!
378 #    if ( $@ ) {
379 #       $RT::Logger->crit($@);
380 #    }
381     warn $@ if $@;
382
383     undef %session;
384
385 #!!
386 #    if ($RT::Handle->TransactionDepth) {
387 #       $RT::Handle->ForceRollback;
388 #       $RT::Logger->crit(
389 #"Transaction not committed. Usually indicates a software fault. Data loss may have occurred"
390 #       );
391 #    }
392
393     $status;
394 }
395
396 1;