finish adding str2time_sql_closing
[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       #use CGI::Carp qw(fatalsToBrowser);
96       use CGI::Cookie;
97       use List::Util qw( max min );
98       use Data::Dumper;
99       use Date::Format;
100       use Date::Parse;
101       use Time::Local;
102       use Time::Duration;
103       use DateTime;
104       use DateTime::Format::Strptime;
105       use Lingua::EN::Inflect qw(PL);
106       use Tie::IxHash;
107       use URI::URL;
108       use URI::Escape;
109       use HTML::Entities;
110       use HTML::TreeBuilder;
111       use HTML::FormatText;
112       use JSON;
113       use MIME::Base64;
114       use IO::Handle;
115       use IO::File;
116       use IO::Scalar;
117       #not actually using this yet anyway...# use IPC::Run3 0.036;
118       use Net::Whois::Raw qw(whois);
119       if ( $] < 5.006 ) {
120         eval "use Net::Whois::Raw 0.32 qw(whois)";
121         die $@ if $@;
122       }
123       use Text::CSV_XS;
124       use Spreadsheet::WriteExcel;
125       use Business::CreditCard 0.30; #for mask-aware cardtype()
126       use NetAddr::IP;
127       use String::Approx qw(amatch);
128       use Chart::LinesPoints;
129       use Chart::Mountain;
130       use Color::Scheme;
131       use HTML::Widgets::SelectLayers 0.07; #should go away in favor of
132                                             #selectlayers.html
133       use Locale::Country;
134       use Business::US::USPS::WebTools::AddressStandardization;
135       use FS;
136       use FS::UID qw( adminsuidsetup cgisuidsetup getotaker
137                       dbh datasrc driver_name
138                     );
139       use FS::Record qw( qsearch qsearchs fields dbdef
140                         str2time_sql str2time_sql_closing
141                        );
142       use FS::Conf;
143       use FS::CGI qw(header menubar popurl rooturl table itable ntable idiot
144                      eidiot myexit http_header);
145       use FS::UI::Web qw(svc_url);
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 states_hash counties state_label );
150       use FS::Report::Table::Monthly;
151       use FS::TicketSystem;
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 qw(smart_search);
161       use FS::cust_main_county;
162       use FS::cust_pay;
163       use FS::cust_pkg;
164       use FS::part_pkg_taxclass;
165       use FS::cust_pkg_reason;
166       use FS::cust_refund;
167       use FS::cust_credit_refund;
168       use FS::cust_pay_refund;
169       use FS::cust_svc;
170       use FS::nas;
171       use FS::part_bill_event;
172       use FS::part_event;
173       use FS::part_event_condition;
174       use FS::part_pkg;
175       use FS::part_referral;
176       use FS::part_svc;
177       use FS::part_svc_router;
178       use FS::part_virtual_field;
179       use FS::pay_batch;
180       use FS::pkg_svc;
181       use FS::port;
182       use FS::queue qw(joblisting);
183       use FS::raddb;
184       use FS::session;
185       use FS::svc_acct;
186       use FS::svc_acct_pop qw(popselector);
187       use FS::acct_rt_transaction;
188       use FS::svc_domain;
189       use FS::svc_forward;
190       use FS::svc_www;
191       use FS::router;
192       use FS::addr_block;
193       use FS::svc_broadband;
194       use FS::svc_external;
195       use FS::type_pkgs;
196       use FS::part_export;
197       use FS::part_export_option;
198       use FS::export_svc;
199       use FS::msgcat;
200       use FS::rate;
201       use FS::rate_region;
202       use FS::rate_prefix;
203       use FS::payment_gateway;
204       use FS::agent_payment_gateway;
205       use FS::XMLRPC;
206       use FS::payby;
207       use FS::cdr;
208       use FS::inventory_class;
209       use FS::inventory_item;
210       use FS::pkg_category;
211       use FS::pkg_class;
212       use FS::access_user;
213       use FS::access_user_pref;
214       use FS::access_group;
215       use FS::access_usergroup;
216       use FS::access_groupagent;
217       use FS::access_right;
218       use FS::AccessRight;
219       use FS::svc_phone;
220       use FS::reason_type;
221       use FS::reason;
222       use FS::cust_main_note;
223       use FS::tax_class;
224       use FS::cust_tax_location;
225       use FS::part_pkg_taxproduct;
226       use FS::part_pkg_taxoverride;
227       use FS::part_pkg_taxrate;
228       use FS::tax_rate;
229
230       if ( %%%RT_ENABLED%%% ) {
231         eval '
232           use RT::Tickets;
233           use RT::Transactions;
234           use RT::Users;
235           use RT::CurrentUser;
236           use RT::Templates;
237           use RT::Queues;
238           use RT::ScripActions;
239           use RT::ScripConditions;
240           use RT::Scrips;
241           use RT::Groups;
242           use RT::GroupMembers;
243           use RT::CustomFields;
244           use RT::CustomFieldValues;
245           use RT::ObjectCustomFieldValues;
246
247           #blah.  manually updated from RT::Interface::Web::Handler
248           use RT::Interface::Web;
249           use MIME::Entity;
250           use Text::Wrapper;
251           use Time::ParseDate;
252           use Time::HiRes;
253           use HTML::Scrubber;
254
255           #blah.  not even in RT::Interface::Web::Handler, just in 
256           #html/NoAuth/css/dhandler and rt-test-dependencies.  ask for it here
257           #to throw a real error instead of just a mysterious unstyled RT
258           use CSS::Squish 0.06;
259
260           #slow, unreliable, segfaults and is optional
261           #see rt/html/Ticket/Elements/ShowTransactionAttachments
262           #use Text::Quoted;
263
264           #?#use File::Path qw( rmtree );
265           #?#use File::Glob qw( bsd_glob );
266           #?#use File::Spec::Unix;
267
268         ';
269         die $@ if $@;
270       }
271
272       *CGI::redirect = sub {
273         my $self = shift;
274         my $cookie = '';
275         if ( $_[0] eq '-cookie' ) { #this isn't actually used at the moment
276           (my $x, $cookie) = (shift, shift);
277           $HTML::Mason::r->err_headers_out->add( 'Set-cookie' => $cookie );
278         }
279         my $location = shift;
280
281         use vars qw($m);
282
283         # false laziness w/below
284         if ( defined(@DBIx::Profile::ISA) ) { #profiling redirect
285
286           my $page =
287             qq!<HTML><BODY>Redirect to <A HREF="$location">$location</A>!.
288             '<BR><BR><PRE>'.
289               ( UNIVERSAL::can(dbh, 'sprintProfile')
290                   ? encode_entities(dbh->sprintProfile())
291                   : 'DBIx::Profile missing sprintProfile method;'.
292                     'unpatched or too old?'                        ).
293             #"\n\n". &sprintAutoProfile().  '</PRE>'.
294             "\n\n".                         '</PRE>'.
295             '</BODY></HTML>';
296           dbh->{'private_profile'} = {};
297           return $page;
298
299         } else { #normal redirect
300
301           $m->redirect($location);
302           '';
303
304         }
305
306       };
307       
308       if ( $HTML::Mason::r->filename !~ /\/rt\/.*NoAuth/ ) { #not RT images/JS
309
310         $cgi = new CGI;
311         &cgisuidsetup($cgi);
312         #&cgisuidsetup($r);
313         $p = popurl(2);
314         $fsurl = rooturl();
315
316       } elsif ( $HTML::Mason::r->filename =~ /\/rt\/REST\/.*NoAuth/ ) {
317
318         #need to log somebody in for the mail gw
319
320         ##old installs w/fs_selfs or selfserv??
321         #&adminsuidsetup('fs_selfservice');
322
323         &adminsuidsetup('fs_queue');
324
325       }
326
327       sub include {
328         use vars qw($m);
329         $m->scomp(@_);
330       }
331
332       sub errorpage {
333         use vars qw($m);
334         $m->comp('/elements/errorpage.html', @_);
335       }
336
337       sub redirect {
338         my( $location ) = @_;
339         use vars qw($m);
340         $m->clear_buffer;
341         #false laziness w/above
342         if ( defined(@DBIx::Profile::ISA) ) { #profiling redirect
343
344           $m->print(
345             qq!<HTML><BODY>Redirect to <A HREF="$location">$location</A>!.
346             '<BR><BR><PRE>'.
347               ( UNIVERSAL::can(dbh, 'sprintProfile')
348                   ? encode_entities(dbh->sprintProfile())
349                   : 'DBIx::Profile missing sprintProfile method;'.
350                     'unpatched or too old?'                        ).
351             #"\n\n". &sprintAutoProfile().  '</PRE>'.
352             "\n\n".                         '</PRE>'.
353             '</BODY></HTML>'
354           );
355           dbh->{'private_profile'} = {};
356
357           #whew.  removing this is all that's needed to fix the annoying
358           #blank-page-instead-of-profiling-redirect-when-called-from-an-include
359           #bug triggered by mason 1.32
360           #my $rv = $m->abort(200);
361
362         } else { #normal redirect
363
364           $m->redirect($location);
365
366         }
367
368       }
369
370     } # end package HTML::Mason::Commands;
371
372     ###Module::Refresh->refresh;###
373
374     $r->content_type('text/html');
375     #eorar
376
377     my $headers = $r->headers_out;
378     $headers->{'Cache-control'} = 'no-cache';
379     #$r->no_cache(1);
380     $headers->{'Expires'} = '0';
381
382 #    $r->send_http_header;
383
384     if ( $r->filename =~ /\/rt\// ) { #RT
385
386       $ah->interp($rt_interp);
387
388       local $SIG{__WARN__};
389       local $SIG{__DIE__};
390
391       RT::Init();
392
393       # We don't need to handle non-text, non-xml items
394       return -1 if defined( $r->content_type )
395                 && $r->content_type !~ m!(^text/|\bxml\b)!io;
396
397     } else {
398
399       $ah->interp($fs_interp);
400
401     }
402
403     my %session;
404     my $status;
405     eval { $status = $ah->handle_request($r); };
406 #!!
407 #    if ( $@ ) {
408 #       $RT::Logger->crit($@);
409 #    }
410     warn $@ if $@;
411
412     undef %session;
413
414 #!!
415 #    if ($RT::Handle->TransactionDepth) {
416 #       $RT::Handle->ForceRollback;
417 #       $RT::Logger->crit(
418 #"Transaction not committed. Usually indicates a software fault. Data loss may have occurred"
419 #       );
420 #    }
421
422     $status;
423 }
424
425 1;