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