]> git.evergreen-ils.org Git - working/Evergreen.git/blob - Open-ILS/src/perlmods/lib/OpenILS/WWW/EGWeb.pm
db0645ddbcb03998f84fbf05e47b914f1771f992
[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 Encode;
8 use Apache2::Const -compile => qw(OK DECLINED HTTP_INTERNAL_SERVER_ERROR HTTP_NOT_FOUND HTTP_GONE);
9 use Apache2::Log;
10 use OpenSRF::EX qw(:try);
11 use OpenSRF::AppSession;
12 use OpenILS::Utils::CStoreEditor q/:funcs/;
13 use List::MoreUtils qw/uniq/;
14
15 use constant OILS_HTTP_COOKIE_SKIN => 'eg_skin';
16 use constant OILS_HTTP_COOKIE_THEME => 'eg_theme';
17 use constant OILS_HTTP_COOKIE_LOCALE => 'eg_locale';
18
19 # cache string bundles
20 my %registered_locales;
21
22 # cache template path -r tests
23 my %vhost_path_cache;
24
25 # cache template processors by vhost
26 my %vhost_processor_cache;
27
28 sub handler {
29     my $r = shift;
30     my $stat = handler_guts($r);
31
32     # other opensrf clients share this apache process,
33     # so it's critical to reset the locale after each
34     # response is handled, lest the other clients 
35     # adopt our temporary, global locale value.
36     OpenSRF::AppSession->reset_locale;
37     return $stat;
38 }
39     
40 sub handler_guts {
41     my $r = shift;
42     my $ctx = load_context($r);
43     my $base = $ctx->{base_path};
44
45     my($template, $page_args, $as_xml) = find_template($r, $base, $ctx);
46     $ctx->{page_args} = $page_args;
47
48     my $stat = run_context_loader($r, $ctx);
49
50     # Handle deleted or never existing records a little more gracefully.
51     # For these two special cases, we set the status so that the request
52     # header will contain the appropriate HTTP status code, but reset the
53     # status so that Apache will continue to process the request and provide
54     # more than just the raw HTTP error page.
55     if ($stat == Apache2::Const::HTTP_GONE || $stat == Apache2::Const::HTTP_NOT_FOUND) {
56         $r->status($stat);
57         $stat = Apache2::Const::OK;
58     }   
59     return $stat unless $stat == Apache2::Const::OK;
60     return Apache2::Const::DECLINED unless $template;
61
62     my $text_handler = set_text_handler($ctx, $r);
63
64     my $processor_key = $as_xml ? 'xml:' : 'text:';                 # separate by XML strictness
65     $processor_key .= $ctx->{hostname}.':';                         # ... and vhost
66     $processor_key .= $r->dir_config('OILSWebContextLoader').':';   # ... and context loader
67     $processor_key .= $ctx->{locale};                               # ... and locale
68     # NOTE: context loader and vhost together imply template path and debug template values
69     # TODO: maybe add STAT_TTL and cache dir from LP#1449709?
70
71     my $tt = $vhost_processor_cache{$processor_key} || Template->new({
72         ENCODING => 'utf-8',
73         OUTPUT => ($as_xml) ?  sub { parse_as_xml($r, $ctx, @_); } : $r,
74         INCLUDE_PATH => $ctx->{template_paths},
75         DEBUG => $ctx->{debug_template},
76         PLUGINS => {
77             EGI18N => 'OpenILS::WWW::EGWeb::I18NFilter',
78             CGI_utf8 => 'OpenILS::WWW::EGWeb::CGI_utf8'
79         },
80         FILTERS => {
81             # Register a dynamic filter factory for our locale::maketext generator
82             l => [
83                 sub {
84                     my($ctx, @args) = @_;
85                     return sub { $text_handler->(shift(), @args); }
86                 }, 1
87             ]
88         }
89     });
90
91     if (!$tt) {
92         $r->log->error("Error creating template processor: $@");
93         return Apache2::Const::HTTP_INTERNAL_SERVER_ERROR;
94     }   
95
96     $vhost_processor_cache{$processor_key} = $tt;
97     $ctx->{encode_utf8} = sub {return encode_utf8(shift())};
98
99     unless($tt->process($template, {ctx => $ctx, ENV => \%ENV, l => $text_handler}, $r)) {
100         $r->log->warn('egweb: template error: ' . $tt->error);
101         return Apache2::Const::HTTP_INTERNAL_SERVER_ERROR;
102     }
103
104     return Apache2::Const::OK;
105 }
106
107 sub set_text_handler {
108     my $ctx = shift;
109     my $r = shift;
110
111     my $locale = $ctx->{locale};
112
113     $r->log->debug("egweb: messages locale = $locale");
114
115     return sub {
116         my $lh = OpenILS::WWW::EGWeb::I18N->get_handle($locale) 
117             || OpenILS::WWW::EGWeb::I18N->new;
118         return $lh->maketext(@_);
119     };
120 }
121
122
123
124 sub run_context_loader {
125     my $r = shift;
126     my $ctx = shift;
127
128     my $stat = Apache2::Const::OK;
129
130     my $loader = $r->dir_config('OILSWebContextLoader');
131     return $stat unless $loader;
132
133     eval {
134         $loader->use;
135         $stat = $loader->new($r, $ctx)->load;
136     };
137
138     if($@) {
139         $r->log->error("egweb: Context Loader error: $@");
140         return Apache2::Const::HTTP_INTERNAL_SERVER_ERROR;
141     }
142
143     $r->log->debug("egweb: context loader resulted in status $stat");
144     return $stat;
145 }
146
147 sub parse_as_xml {
148     my $r = shift;
149     my $ctx = shift;
150     my $data = shift;
151
152     my $success = 0;
153
154     try { 
155         my $doc = XML::LibXML->new->parse_string($data); 
156         $data = $doc->documentElement->toStringC14N;
157         $data = $ctx->{final_dtd} . "\n" . $data;
158         $success = 1;
159     } otherwise {
160         my $e = shift;
161         my $err = "Invalid XML: $e";
162         $r->log->error("egweb: $err");
163         $r->content_type('text/plain; encoding=utf8');
164         $r->print("\n$err\n\n$data");
165     };
166
167     $r->print($data) if ($success);
168 }
169
170 sub load_context {
171     my $r = shift;
172     my $cgi = CGI->new;
173     my $ctx = {}; # new context for each page load
174
175     $ctx->{base_path} = $r->dir_config('OILSWebBasePath');
176     $ctx->{web_dir} = $r->dir_config('OILSWebWebDir');
177     $ctx->{debug_template} = ($r->dir_config('OILSWebDebugTemplate') =~ /true/io);
178     $ctx->{media_prefix} = $r->dir_config('OILSWebMediaPrefix');
179     $ctx->{hostname} = $r->hostname;
180     $ctx->{base_url} = $cgi->url(-base => 1);
181     $ctx->{skin} = $cgi->cookie(OILS_HTTP_COOKIE_SKIN) || 'default';
182     $ctx->{theme} = $cgi->cookie(OILS_HTTP_COOKIE_THEME) || 'default';
183     $ctx->{proto} = $cgi->https ? 'https' : 'http';
184     $ctx->{ext_proto} = $ctx->{proto};
185     my $default_locale = $r->dir_config('OILSWebDefaultLocale') || 'en_us';
186
187     my @template_paths = uniq $r->dir_config->get('OILSWebTemplatePath');
188     $ctx->{template_paths} = [ reverse @template_paths ];
189
190     my %locales = $r->dir_config->get('OILSWebLocale');
191     load_locale_handlers($ctx, %locales);
192
193     $ctx->{locales} = \%registered_locales;
194
195     # Set a locale cookie if the requested locale is valid
196     my $set_locale = $cgi->param('set_eg_locale') || '';
197     if (!(grep {$_ eq $set_locale} keys %registered_locales)) {
198         $set_locale = '';
199     } else {
200         my $slc = $cgi->cookie({
201             '-name' => OILS_HTTP_COOKIE_LOCALE,
202             '-value' => $set_locale,
203             '-expires' => '+10y'
204         });
205         $r->headers_out->add('Set-Cookie' => $slc);
206     }
207
208     $ctx->{locale} = $set_locale ||
209         $cgi->cookie(OILS_HTTP_COOKIE_LOCALE) || $default_locale ||
210         parse_accept_lang($r->headers_in->get('Accept-Language'));
211
212     # set the editor default locale for each page load
213     my $ses_locale = parse_eg_locale($ctx->{locale});
214     OpenSRF::AppSession->default_locale($ses_locale);
215     # give templates access to the en-US style locale
216     $ctx->{eg_locale} = $ses_locale;
217
218     my $mprefix = $ctx->{media_prefix};
219     if($mprefix and $mprefix !~ /^http/ and $mprefix !~ /^\//) {
220         # if a hostname is provided /w no protocol, match the protocol to the current page
221         $ctx->{media_prefix} = ($cgi->https) ? "https://$mprefix" : "http://$mprefix";
222     }
223
224     return $ctx;
225 }
226
227 # turn Accept-Language into something EG can understand
228 # TODO: try all langs, not just the first
229 sub parse_accept_lang {
230     my $al = shift;
231     return undef unless $al;
232     my ($locale) = split(/,/, $al);
233     ($locale) = split(/;/, $locale);
234     return undef unless $locale;
235     $locale =~ s/-/_/og;
236     return $locale;
237 }
238
239 # Accept-Language uses locales like 'en', 'fr', 'fr_fr', while Evergreen
240 # internally uses 'en-US', 'fr-CA', 'fr-FR' (always with the 2 lowercase,
241 # hyphen, 2 uppercase convention)
242 sub parse_eg_locale {
243     my $ua_locale = shift || 'en_us';
244
245     $ua_locale =~ m/^(..).?(..)?$/;
246     my $lang_code = lc($1);
247     my $region_code = $2 ? uc($2) : uc($1);
248     return "$lang_code-$region_code";
249 }
250
251 # Given a URI, finds the configured template and any extra page 
252 # arguments (trailing path info).  Any extra data is returned
253 # as page arguments, in the form of an array, one item per 
254 # /-separated URI component
255 sub find_template {
256     my $r = shift;
257     my $base = shift;
258     my $ctx = shift;
259     my $path = $r->uri;
260     $path =~ s/$base\/?//og;
261     my $template = '';
262     my $page_args = [];
263     my $as_xml = $r->dir_config('OILSWebForceValidXML');
264     my $ext = $r->dir_config('OILSWebDefaultTemplateExtension');
265     my $at_index = $r->dir_config('OILSWebStopAtIndex');
266
267     $vhost_path_cache{$ctx->{hostname}} ||= {};
268     my $path_cache = $vhost_path_cache{$ctx->{hostname}};
269
270     my @parts = split('/', $path);
271     my $localpath = $path;
272
273     if ($localpath =~ m|/css/|) {
274         $r->content_type('text/css; encoding=utf8');
275     } else {
276         $r->content_type('text/html; encoding=utf8');
277     }
278
279     my @args;
280     while(@parts) {
281         last unless $localpath;
282         for my $tpath (@{$ctx->{template_paths}}) {
283             my $fpath = "$tpath/$localpath.$ext";
284             $r->log->debug("egweb: looking at possible template $fpath");
285             if ($template = $path_cache->{$fpath}) { # we've checked with -r before...
286                 next if ($template eq '0E0'); # ... and found nothing
287                 last;
288             } elsif (-r $fpath) { # or, we haven't checked, and if we find a file...
289                 $path_cache->{$fpath} = $template = "$localpath.$ext"; # ... note it
290                 last;
291             } else { # Nothing there...
292                 $path_cache->{$fpath} = '0E0'; # ... note that fact
293             }
294         }
295         last if $template and $template ne '0E0';
296
297         if ($at_index) {
298             # no matching template was found in the current directory.
299             # stop-at-index requested; see if there is an index.ext 
300             # file in the same directory instead.
301             for my $tpath (@{$ctx->{template_paths}}) {
302                 # replace the final path component with 'index'
303                 if ($localpath =~ m|/$|) {
304                     $localpath .= 'index';
305                 } else {
306                     $localpath =~ s|/[^/]+$|/index|;
307                 }
308                 my $fpath = "$tpath/$localpath.$ext";
309                 $r->log->debug("egweb: looking at possible template $fpath");
310                 if ($template = $path_cache->{$fpath}) { # See above block
311                     next if ($template eq '0E0');
312                     last;
313                 } elsif (-r $fpath) {
314                     $path_cache->{$fpath} = $template = "$localpath.$ext";
315                     last;
316                 } else {
317                     $path_cache->{$fpath} = '0E0';
318                 } 
319             }
320         }
321         last if $template and $template ne '0E0';
322
323         push(@args, pop @parts);
324         $localpath = join('/', @parts);
325     } 
326
327     $page_args = [@args];
328
329     # no template configured or found
330     if(!$template or $template eq '0E0') {
331         $r->log->debug("egweb: No template configured for path $path");
332         return ();
333     }
334
335     $r->log->debug("egweb: template = $template : page args = @$page_args");
336     return ($template, $page_args, $as_xml);
337 }
338
339 # Create an I18N sub-module for each supported locale
340 # Each module creates its own MakeText lexicon by parsing .po/.mo files
341 sub load_locale_handlers {
342     my $ctx = shift;
343     my %locales = @_;
344
345     my $editor = new_editor();
346     my @locale_tags = sort { length($a) <=> length($b) } keys %locales;
347
348     # always fall back to en_us, the assumed template language
349     push(@locale_tags, 'en_us');
350
351     for my $idx (0..$#locale_tags) {
352
353         my $tag = $locale_tags[$idx];
354         next if grep { $_ eq $tag } keys %registered_locales;
355
356         my $res = $editor->json_query({
357             "from" => [
358                 "evergreen.get_locale_name",
359                 $tag
360             ]
361         });
362
363         my $locale_name = $res->[0]->{"name"} if exists $res->[0]->{"name"};
364         next unless $locale_name;
365
366         my $parent_tag = '';
367         my $sub_idx = $idx;
368
369         # find the parent locale if possible.  It will be 
370         # longest left-anchored substring of the current tag
371         while( --$sub_idx >= 0 ) {
372             my $ptag = $locale_tags[$sub_idx];
373             if( substr($tag, 0, length($ptag)) eq $ptag ) {
374                 $parent_tag = "::$ptag";
375                 last;
376             }
377         }
378
379         my $messages = $locales{$tag} || '';
380
381         # TODO Can we do this without eval?
382         my $eval = <<"        EVAL";
383             package OpenILS::WWW::EGWeb::I18N::$tag;
384             use base 'OpenILS::WWW::EGWeb::I18N$parent_tag';
385             if(\$messages) {
386                 use Locale::Maketext::Lexicon {
387                     _decode => 1
388                 };
389                 use Locale::Maketext::Lexicon::Gettext;
390                 if(open F, '$messages') {
391                     our %Lexicon = (%Lexicon, %{ Locale::Maketext::Lexicon::Gettext->parse(<F>) });
392                     close F;
393                 } else {
394                     warn "EGWeb: unable to open messages file: $messages"; 
395                 }
396             }
397         EVAL
398         eval $eval;
399
400         if ($@) {
401             warn "$@\n" if $@;
402         } else {
403             $registered_locales{"$tag"} = $locale_name;
404         }
405     }
406 }
407
408
409 # base class for all supported locales
410 package OpenILS::WWW::EGWeb::I18N;
411 use base 'Locale::Maketext';
412 our %Lexicon = (_AUTO => 1);
413
414 1;