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