]> git.evergreen-ils.org Git - working/Evergreen.git/blob - Open-ILS/src/perlmods/lib/OpenILS/WWW/EGWeb.pm
Default per-request TPAC locale
[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);
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 sub handler {
23     my $r = shift;
24     my $stat = handler_guts($r);
25
26     # other opensrf clients share this apache process,
27     # so it's critical to reset the locale after each
28     # response is handled, lest the other clients 
29     # adopt our temporary, global locale value.
30     OpenSRF::AppSession->reset_locale;
31     return $stat;
32 }
33     
34 sub handler_guts {
35     my $r = shift;
36     my $ctx = load_context($r);
37     my $base = $ctx->{base_path};
38
39     my($template, $page_args, $as_xml) = find_template($r, $base, $ctx);
40     $ctx->{page_args} = $page_args;
41
42     my $stat = run_context_loader($r, $ctx);
43
44     return $stat unless $stat == Apache2::Const::OK;
45     return Apache2::Const::DECLINED unless $template;
46
47     my $text_handler = set_text_handler($ctx, $r);
48
49     my $tt = Template->new({
50         ENCODING => 'utf-8',
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         FILTERS => {
59             # Register a dynamic filter factory for our locale::maketext generator
60             l => [
61                 sub {
62                     my($ctx, @args) = @_;
63                     return sub { $text_handler->(shift(), @args); }
64                 }, 1
65             ]
66         }
67     });
68
69     if (!$tt) {
70         $r->log->error("Error creating template processor: $@");
71         return Apache2::Const::HTTP_INTERNAL_SERVER_ERROR;
72     }   
73
74     $ctx->{encode_utf8} = sub {return encode_utf8(shift())};
75
76     unless($tt->process($template, {ctx => $ctx, ENV => \%ENV, l => $text_handler})) {
77         $r->log->warn('egweb: template error: ' . $tt->error);
78         return Apache2::Const::HTTP_INTERNAL_SERVER_ERROR;
79     }
80
81     return Apache2::Const::OK;
82 }
83
84 sub set_text_handler {
85     my $ctx = shift;
86     my $r = shift;
87
88     my $locale = $ctx->{locale};
89
90     $r->log->debug("egweb: messages locale = $locale");
91
92     return sub {
93         my $lh = OpenILS::WWW::EGWeb::I18N->get_handle($locale);
94         return $lh->maketext(@_);
95     };
96 }
97
98
99
100 sub run_context_loader {
101     my $r = shift;
102     my $ctx = shift;
103
104     my $stat = Apache2::Const::OK;
105
106     my $loader = $r->dir_config('OILSWebContextLoader');
107     return $stat unless $loader;
108
109     eval {
110         $loader->use;
111         $stat = $loader->new($r, $ctx)->load;
112     };
113
114     if($@) {
115         $r->log->error("egweb: Context Loader error: $@");
116         return Apache2::Const::HTTP_INTERNAL_SERVER_ERROR;
117     }
118
119     $r->log->debug("egweb: context loader resulted in status $stat");
120     return $stat;
121 }
122
123 sub parse_as_xml {
124     my $r = shift;
125     my $ctx = shift;
126     my $data = shift;
127
128     my $success = 0;
129
130     try { 
131         my $doc = XML::LibXML->new->parse_string($data); 
132         $data = $doc->documentElement->toStringC14N;
133         $data = $ctx->{final_dtd} . "\n" . $data;
134         $success = 1;
135     } otherwise {
136         my $e = shift;
137         my $err = "Invalid XML: $e";
138         $r->log->error("egweb: $err");
139         $r->content_type('text/plain; encoding=utf8');
140         $r->print("\n$err\n\n$data");
141     };
142
143     $r->print($data) if ($success);
144 }
145
146 sub load_context {
147     my $r = shift;
148     my $cgi = CGI->new;
149     my $ctx = {}; # new context for each page load
150
151     $ctx->{base_path} = $r->dir_config('OILSWebBasePath');
152     $ctx->{web_dir} = $r->dir_config('OILSWebWebDir');
153     $ctx->{debug_template} = ($r->dir_config('OILSWebDebugTemplate') =~ /true/io);
154     $ctx->{media_prefix} = $r->dir_config('OILSWebMediaPrefix');
155     $ctx->{hostname} = $r->hostname;
156     $ctx->{base_url} = $cgi->url(-base => 1);
157     $ctx->{skin} = $cgi->cookie(OILS_HTTP_COOKIE_SKIN) || 'default';
158     $ctx->{theme} = $cgi->cookie(OILS_HTTP_COOKIE_THEME) || 'default';
159     $ctx->{proto} = $cgi->https ? 'https' : 'http';
160     $ctx->{ext_proto} = $ctx->{proto};
161     my $default_locale = $r->dir_config('OILSWebDefaultLocale') || 'en_us';
162
163     my @template_paths = uniq $r->dir_config->get('OILSWebTemplatePath');
164     $ctx->{template_paths} = [ reverse @template_paths ];
165
166     my %locales = $r->dir_config->get('OILSWebLocale');
167     load_locale_handlers($ctx, %locales);
168
169     $ctx->{locales} = \%registered_locales;
170
171     # Set a locale cookie if the requested locale is valid
172     my $set_locale = $cgi->param('set_eg_locale') || '';
173     if (!(grep {$_ eq $set_locale} keys %registered_locales)) {
174         $set_locale = '';
175     } else {
176         my $slc = $cgi->cookie({
177             '-name' => OILS_HTTP_COOKIE_LOCALE,
178             '-value' => $set_locale,
179             '-expires' => '+10y'
180         });
181         $r->headers_out->add('Set-Cookie' => $slc);
182     }
183
184     $ctx->{locale} = $set_locale ||
185         $cgi->cookie(OILS_HTTP_COOKIE_LOCALE) || $default_locale ||
186         parse_accept_lang($r->headers_in->get('Accept-Language'));
187
188     # set the editor default locale for each page load
189     OpenSRF::AppSession->default_locale(parse_eg_locale($ctx->{locale}));
190
191     my $mprefix = $ctx->{media_prefix};
192     if($mprefix and $mprefix !~ /^http/ and $mprefix !~ /^\//) {
193         # if a hostname is provided /w no protocol, match the protocol to the current page
194         $ctx->{media_prefix} = ($cgi->https) ? "https://$mprefix" : "http://$mprefix";
195     }
196
197     return $ctx;
198 }
199
200 # turn Accept-Language into something EG can understand
201 # TODO: try all langs, not just the first
202 sub parse_accept_lang {
203     my $al = shift;
204     return undef unless $al;
205     my ($locale) = split(/,/, $al);
206     ($locale) = split(/;/, $locale);
207     return undef unless $locale;
208     $locale =~ s/-/_/og;
209     return $locale;
210 }
211
212 # Accept-Language uses locales like 'en', 'fr', 'fr_fr', while Evergreen
213 # internally uses 'en-US', 'fr-CA', 'fr-FR' (always with the 2 lowercase,
214 # hyphen, 2 uppercase convention)
215 sub parse_eg_locale {
216     my $ua_locale = shift || 'en_us';
217
218     $ua_locale =~ m/^(..).?(..)?$/;
219     my $lang_code = lc($1);
220     my $region_code = $2 ? uc($2) : uc($1);
221     return "$lang_code-$region_code";
222 }
223
224 # Given a URI, finds the configured template and any extra page 
225 # arguments (trailing path info).  Any extra data is returned
226 # as page arguments, in the form of an array, one item per 
227 # /-separated URI component
228 sub find_template {
229     my $r = shift;
230     my $base = shift;
231     my $ctx = shift;
232     my $path = $r->uri;
233     $path =~ s/$base\/?//og;
234     my $template = '';
235     my $page_args = [];
236     my $as_xml = $r->dir_config('OILSWebForceValidXML');
237     my $ext = $r->dir_config('OILSWebDefaultTemplateExtension');
238
239     my @parts = split('/', $path);
240     my $localpath = $path;
241
242     if ($localpath =~ m|opac/css|) {
243         $r->content_type('text/css; encoding=utf8');
244     } else {
245         $r->content_type('text/html; encoding=utf8');
246     }
247     my @args;
248     while(@parts) {
249         last unless $localpath;
250         for my $tpath (@{$ctx->{template_paths}}) {
251             my $fpath = "$tpath/$localpath.$ext";
252             $r->log->debug("egweb: looking at possible template $fpath");
253             if(-r $fpath) {
254                 $template = "$localpath.$ext";
255                 last;
256             }
257         }
258         last if $template;
259         push(@args, pop @parts);
260         $localpath = join('/', @parts);
261     } 
262
263     $page_args = [@args];
264
265     # no template configured or found
266     unless($template) {
267         $r->log->debug("egweb: No template configured for path $path");
268         return ();
269     }
270
271     $r->log->debug("egweb: template = $template : page args = @$page_args");
272     return ($template, $page_args, $as_xml);
273 }
274
275 # Create an I18N sub-module for each supported locale
276 # Each module creates its own MakeText lexicon by parsing .po/.mo files
277 sub load_locale_handlers {
278     my $ctx = shift;
279     my %locales = @_;
280
281     my $editor = new_editor();
282     my @locale_tags = sort { length($a) <=> length($b) } keys %locales;
283
284     # always fall back to en_us, the assumed template language
285     push(@locale_tags, 'en_us');
286
287     for my $idx (0..$#locale_tags) {
288
289         my $tag = $locale_tags[$idx];
290         next if grep { $_ eq $tag } keys %registered_locales;
291
292         my $res = $editor->json_query({
293             "from" => [
294                 "evergreen.get_locale_name",
295                 $tag
296             ]
297         });
298
299         my $locale_name = $res->[0]->{"name"} if exists $res->[0]->{"name"};
300         next unless $locale_name;
301
302         my $parent_tag = '';
303         my $sub_idx = $idx;
304
305         # find the parent locale if possible.  It will be 
306         # longest left-anchored substring of the current tag
307         while( --$sub_idx >= 0 ) {
308             my $ptag = $locale_tags[$sub_idx];
309             if( substr($tag, 0, length($ptag)) eq $ptag ) {
310                 $parent_tag = "::$ptag";
311                 last;
312             }
313         }
314
315         my $messages = $locales{$tag} || '';
316
317         # TODO Can we do this without eval?
318         my $eval = <<"        EVAL";
319             package OpenILS::WWW::EGWeb::I18N::$tag;
320             use base 'OpenILS::WWW::EGWeb::I18N$parent_tag';
321             if(\$messages) {
322                 use Locale::Maketext::Lexicon {
323                     _decode => 1
324                 };
325                 use Locale::Maketext::Lexicon::Gettext;
326                 if(open F, '$messages') {
327                     our %Lexicon = (%Lexicon, %{ Locale::Maketext::Lexicon::Gettext->parse(<F>) });
328                     close F;
329                 } else {
330                     warn "EGWeb: unable to open messages file: $messages"; 
331                 }
332             }
333         EVAL
334         eval $eval;
335
336         if ($@) {
337             warn "$@\n" if $@;
338         } else {
339             $registered_locales{"$tag"} = $locale_name;
340         }
341     }
342 }
343
344
345 # base class for all supported locales
346 package OpenILS::WWW::EGWeb::I18N;
347 use base 'Locale::Maketext';
348 our %Lexicon = (_AUTO => 1);
349
350 1;