]> git.evergreen-ils.org Git - working/Evergreen.git/blob - Open-ILS/src/perlmods/lib/OpenILS/WWW/EGWeb.pm
Bypass install_filter mem leak via direct insertion
[working/Evergreen.git] / Open-ILS / src / perlmods / lib / OpenILS / WWW / EGWeb.pm
1 package OpenILS::WWW::EGWeb;
2 use strict; use warnings;
3 use Template;
4 use XML::Simple;
5 use XML::LibXML;
6 use File::stat;
7 use Apache2::Const -compile => qw(OK DECLINED HTTP_INTERNAL_SERVER_ERROR);
8 use Apache2::Log;
9 use OpenSRF::EX qw(:try);
10 use OpenILS::Utils::CStoreEditor;
11
12 use constant OILS_HTTP_COOKIE_SKIN => 'eg_skin';
13 use constant OILS_HTTP_COOKIE_THEME => 'eg_theme';
14 use constant OILS_HTTP_COOKIE_LOCALE => 'eg_locale';
15
16 my $web_config;
17 my $web_config_file;
18 my $web_config_edit_time;
19 my %lh_cache; # locale handlers
20
21 sub import {
22     my $self = shift;
23     $web_config_file = shift || '';
24     unless(-r $web_config_file) {
25         warn "Invalid web config $web_config_file\n";
26         return;
27     }
28     check_web_config();
29 }
30
31
32 sub handler {
33     my $r = shift;
34     check_web_config($r); # option to disable this
35     my $ctx = load_context($r);
36     my $base = $ctx->{base_path};
37
38     $r->content_type('text/html; encoding=utf8');
39
40     my($template, $page_args, $as_xml) = find_template($r, $base, $ctx);
41     $ctx->{page_args} = $page_args;
42
43     my $stat = run_context_loader($r, $ctx);
44
45     return $stat unless $stat == Apache2::Const::OK;
46     return Apache2::Const::DECLINED unless $template;
47
48     $template = $ctx->{skin} . "/$template";
49
50     my $text_handler = set_text_handler($ctx, $r);
51
52     my $tt = Template->new({
53         OUTPUT => ($as_xml) ?  sub { parse_as_xml($r, $ctx, @_); } : $r,
54         INCLUDE_PATH => $ctx->{template_paths},
55         DEBUG => $ctx->{debug_template},
56         PLUGINS => {
57             EGI18N => 'OpenILS::WWW::EGWeb::I18NFilter',
58             CGI_utf8 => 'OpenILS::WWW::EGWeb::CGI_utf8'
59         },
60         FILTERS => {l => $text_handler}
61     });
62
63     unless($tt->process($template, {ctx => $ctx, ENV => \%ENV, l => $text_handler})) {
64         $r->log->warn('egweb: template error: ' . $tt->error);
65         return Apache2::Const::HTTP_INTERNAL_SERVER_ERROR;
66     }
67
68     return Apache2::Const::OK;
69 }
70
71 sub set_text_handler {
72     my $ctx = shift;
73     my $r = shift;
74
75     my $locale = $ctx->{locale};
76     $locale =~ s/-/_/g;
77
78     $r->log->debug("egweb: messages locale = $locale");
79
80     unless($lh_cache{$locale}) {
81         $r->log->info("egweb: Unsupported locale: $locale");
82         $lh_cache{$locale} = $lh_cache{'en_US'};
83     }
84
85     return sub { return $lh_cache{$locale}->maketext(@_); };
86 }
87
88
89
90 sub run_context_loader {
91     my $r = shift;
92     my $ctx = shift;
93
94     my $stat = Apache2::Const::OK;
95
96     my $loader = $r->dir_config('OILSWebContextLoader');
97     return $stat unless $loader;
98
99     eval {
100         $loader->use;
101         $stat = $loader->new($r, $ctx)->load;
102     };
103
104     if($@) {
105         $r->log->error("egweb: Context Loader error: $@");
106         return Apache2::Const::HTTP_INTERNAL_SERVER_ERROR;
107     }
108
109     $r->log->debug("egweb: context loader resulted in status $stat");
110     return $stat;
111 }
112
113 sub parse_as_xml {
114     my $r = shift;
115     my $ctx = shift;
116     my $data = shift;
117
118     my $success = 0;
119
120     try { 
121         my $doc = XML::LibXML->new->parse_string($data); 
122         $data = $doc->documentElement->toStringC14N;
123         $data = $ctx->{final_dtd} . "\n" . $data;
124         $success = 1;
125     } otherwise {
126             my $e = shift;
127         my $err = "Invalid XML: $e";
128         $r->log->error("egweb: $err");
129         $r->content_type('text/plain; encoding=utf8');
130         $r->print("\n$err\n\n$data");
131     };
132
133     $r->print($data) if ($success);
134 }
135
136
137 sub load_context {
138     my $r = shift;
139     my $cgi = CGI->new;
140     my $ctx = {}; # new context for each page load
141     $ctx->{$_} = $web_config->{base_ctx}->{$_} for keys %{$web_config->{base_ctx}};
142     $ctx->{hostname} = $r->hostname;
143     $ctx->{base_url} = $cgi->url(-base => 1);
144     $ctx->{skin} = $cgi->cookie(OILS_HTTP_COOKIE_SKIN) || 'default';
145     $ctx->{theme} = $cgi->cookie(OILS_HTTP_COOKIE_THEME) || 'default';
146
147     $ctx->{locale} = 
148         $cgi->cookie(OILS_HTTP_COOKIE_LOCALE) || 
149         parse_accept_lang($r->headers_in->get('Accept-Language')) || 'en-US';
150
151     my $mprefix = $ctx->{media_prefix};
152     if($mprefix and $mprefix !~ /^http/ and $mprefix !~ /^\//) {
153         # if a hostname is provided /w no protocol, match the protocol to the current page
154         $ctx->{media_prefix} = ($cgi->https) ? "https://$mprefix" : "http://$mprefix";
155     }
156
157     return $ctx;
158 }
159
160 # turn Accept-Language into sometihng EG can understand
161 sub parse_accept_lang {
162     my $al = shift;
163     return undef unless $al;
164     my ($locale) = split(/,/, $al);
165     ($locale) = split(/;/, $locale);
166     return undef unless $locale;
167     $locale =~ s/-(.*)/eval '-'.uc("$1")/e;
168     return $locale;
169 }
170
171 # Given a URI, finds the configured template and any extra page 
172 # arguments (trailing path info).  Any extra data is returned
173 # as page arguments, in the form of an array, one item per 
174 # /-separated URI component
175 sub find_template {
176     my $r = shift;
177     my $base = shift;
178     my $ctx = shift;
179     my $skin = $ctx->{skin};
180     my $path = $r->uri;
181     $path =~ s/$base//og;
182     my @parts = split('/', $path);
183     my $template = '';
184     my $page_args = [];
185     my $as_xml = $ctx->{force_valid_xml};
186     my $handler = $web_config->{handlers};
187
188     while(@parts) {
189         my $part = shift @parts;
190         next unless $part;
191         my $t = $handler->{$part};
192         if(ref($t) eq 'PathConfig') {
193             $template = $t->{template};
194             $as_xml = ($t->{as_xml} and $t->{as_xml} =~ /true/io) || $as_xml;
195             $page_args = [@parts];
196             last;
197         } else {
198             $handler = $t;
199         }
200     }
201
202     unless($template) { # no template configured
203
204         # see if we can magically find the template based on the path and default extension
205         my $ext = $ctx->{default_template_extension};
206
207         my @parts = split('/', $path);
208         my $localpath = $path;
209         my @args;
210         while(@parts) {
211             last unless $localpath;
212             for my $tpath (@{$ctx->{template_paths}}) {
213                 my $fpath = "$tpath/$skin/$localpath.$ext";
214                 $r->log->debug("egweb: looking at possible template $fpath");
215                 if(-r $fpath) {
216                     $template = "$localpath.$ext";
217                     last;
218                 }
219             }
220             last if $template;
221             push(@args, pop @parts);
222             $localpath = '/'.join('/', @parts);
223         } 
224
225         $page_args = [@args];
226
227         # no template configured or found
228         unless($template) {
229             $r->log->debug("egweb: No template configured for path $path");
230             return ();
231         }
232     }
233
234     $r->log->debug("egweb: template = $template : page args = @$page_args");
235     return ($template, $page_args, $as_xml);
236 }
237
238 # if the web configuration file has never been loaded or has
239 # changed since the last load, reload it
240 sub check_web_config {
241     my $r = shift;
242     my $epoch = stat($web_config_file)->mtime;
243     unless($web_config_edit_time and $web_config_edit_time == $epoch) {
244         $r->log->debug("egweb: Reloading web config after edit...") if $r;
245         $web_config_edit_time = $epoch;
246         $web_config = parse_config($web_config_file);
247     }
248 }
249
250 # Create an I18N sub-module for each supported locale
251 # Each module creates its own MakeText lexicon by parsing .po/.mo files
252 sub load_locale_handlers {
253     my $ctx = shift;
254     my $locales = $ctx->{locales};
255
256     $locales->{en_US} = {} unless exists $locales->{en_US};
257
258     for my $lang (keys %$locales) {
259         my $messages = $locales->{$lang};
260         $messages = '' if ref $messages; # empty {}
261
262         # TODO Can we do this without eval?
263         my $eval = <<EVAL;
264             package OpenILS::WWW::EGWeb::I18N::$lang;
265             use base 'OpenILS::WWW::EGWeb::I18N';
266             if(\$messages) {
267                 use Locale::Maketext::Lexicon::Gettext;
268                 if(open F, '$messages') {
269                     our %Lexicon = (%Lexicon, %{ Locale::Maketext::Lexicon::Gettext->parse(<F>) });
270                     close F;
271                 } else {
272                     warn "EGWeb: unable to open messages file: $messages"; 
273                 }
274             }
275 EVAL
276         eval $eval;
277         warn "$@\n" if $@; # TODO better logging
278         $lh_cache{$lang} = "OpenILS::WWW::EGWeb::I18N::$lang"->new;
279     }
280 }
281
282
283
284 sub parse_config {
285     my $cfg_file = shift;
286     my $data = XML::Simple->new->XMLin($cfg_file);
287     my $ctx = {};
288     my $handlers = {};
289
290     $ctx->{media_prefix} = (ref $data->{media_prefix}) ? '' : $data->{media_prefix};
291     $ctx->{base_path} = (ref $data->{base_path}) ? '' : $data->{base_path};
292     $ctx->{template_paths} = [];
293     $ctx->{force_valid_xml} = ( ($data->{force_valid_xml}||'') =~ /true/io) ? 1 : 0;
294     $ctx->{debug_template} = ( ($data->{debug_template}||'')  =~ /true/io) ? 1 : 0;
295     $ctx->{default_template_extension} = $data->{default_template_extension} || 'tt2';
296     $ctx->{web_dir} = $data->{web_dir};
297     $ctx->{locales} = $data->{locales};
298     load_locale_handlers($ctx);
299
300     my $tpaths = $data->{template_paths}->{path};
301     $tpaths = [$tpaths] unless ref $tpaths;
302     push(@{$ctx->{template_paths}}, $_) for @$tpaths;
303
304     for my $handler (@{$data->{handlers}->{handler}}) {
305         my @parts = split('/', $handler->{path});
306         my $h = $handlers;
307         my $pcount = scalar(@parts);
308         for(my $i = 0; $i < $pcount; $i++) {
309             my $p = $parts[$i];
310             unless(defined $h->{$p}) {
311                 if($i == $pcount - 1) {
312                     $h->{$p} = PathConfig->new(%$handler);
313                     last;
314                 } else {
315                     $h->{$p} = {};
316                 }
317             }
318             $h = $h->{$p};
319         }
320     }
321
322     return {base_ctx => $ctx, handlers => $handlers};
323 }
324
325 package PathConfig;
326 sub new {
327     my($class, %args) = @_;
328     return bless(\%args, $class);
329 }
330
331 # base class for all supported locales
332 package OpenILS::WWW::EGWeb::I18N;
333 use base 'Locale::Maketext';
334 our %Lexicon = (_AUTO => 1);
335
336 1;