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