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