]> git.evergreen-ils.org Git - Evergreen.git/blob - Open-ILS/src/perlmods/lib/OpenILS/WWW/EGWeb.pm
TPAC: Decode translated strings into UTF8
[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 OpenILS::Utils::CStoreEditor q/:funcs/;
12
13 use constant OILS_HTTP_COOKIE_SKIN => 'eg_skin';
14 use constant OILS_HTTP_COOKIE_THEME => 'eg_theme';
15 use constant OILS_HTTP_COOKIE_LOCALE => 'eg_locale';
16
17 # cache string bundles
18 my %registered_locales;
19
20 sub handler {
21     my $r = shift;
22     my $ctx = load_context($r);
23     my $base = $ctx->{base_path};
24
25     $r->content_type('text/html; encoding=utf8');
26
27     my($template, $page_args, $as_xml) = find_template($r, $base, $ctx);
28     $ctx->{page_args} = $page_args;
29
30     my $stat = run_context_loader($r, $ctx);
31
32     return $stat unless $stat == Apache2::Const::OK;
33     return Apache2::Const::DECLINED unless $template;
34
35     my $text_handler = set_text_handler($ctx, $r);
36
37     my $tt = Template->new({
38         ENCODING => 'utf-8',
39         OUTPUT => ($as_xml) ?  sub { parse_as_xml($r, $ctx, @_); } : $r,
40         INCLUDE_PATH => $ctx->{template_paths},
41         DEBUG => $ctx->{debug_template},
42         PLUGINS => {
43             EGI18N => 'OpenILS::WWW::EGWeb::I18NFilter',
44             CGI_utf8 => 'OpenILS::WWW::EGWeb::CGI_utf8'
45         },
46         FILTERS => {
47             # Register a dynamic filter factory for our locale::maketext generator
48             l => [
49                 sub {
50                     my($ctx, @args) = @_;
51                     return sub { $text_handler->(shift(), @args); }
52                 }, 1
53             ]
54         }
55     });
56
57     if (!$tt) {
58         $r->log->error("Error creating template processor: $@");
59         return Apache2::Const::HTTP_INTERNAL_SERVER_ERROR;
60     }   
61
62     $ctx->{encode_utf8} = sub {return encode_utf8(shift())};
63
64     unless($tt->process($template, {ctx => $ctx, ENV => \%ENV, l => $text_handler})) {
65         $r->log->warn('egweb: template error: ' . $tt->error);
66         return Apache2::Const::HTTP_INTERNAL_SERVER_ERROR;
67     }
68
69     return Apache2::Const::OK;
70 }
71
72 sub set_text_handler {
73     my $ctx = shift;
74     my $r = shift;
75
76     my $locale = $ctx->{locale};
77
78     $r->log->debug("egweb: messages locale = $locale");
79
80     return sub {
81         my $lh = OpenILS::WWW::EGWeb::I18N->get_handle($locale);
82         return $lh->maketext(@_);
83     };
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 sub load_context {
135     my $r = shift;
136     my $cgi = CGI->new;
137     my $ctx = {}; # new context for each page load
138
139     $ctx->{base_path} = $r->dir_config('OILSWebBasePath');
140     $ctx->{web_dir} = $r->dir_config('OILSWebWebDir');
141     $ctx->{debug_template} = ($r->dir_config('OILSWebDebugTemplate') =~ /true/io);
142     $ctx->{media_prefix} = $r->dir_config('OILSWebMediaPrefix');
143     $ctx->{hostname} = $r->hostname;
144     $ctx->{base_url} = $cgi->url(-base => 1);
145     $ctx->{skin} = $cgi->cookie(OILS_HTTP_COOKIE_SKIN) || 'default';
146     $ctx->{theme} = $cgi->cookie(OILS_HTTP_COOKIE_THEME) || 'default';
147     $ctx->{proto} = $cgi->https ? 'https' : 'http';
148
149     my @template_paths = $r->dir_config->get('OILSWebTemplatePath');
150     $ctx->{template_paths} = [ reverse @template_paths ];
151
152     my %locales = $r->dir_config->get('OILSWebLocale');
153     load_locale_handlers($ctx, %locales);
154
155     $ctx->{locales} = \%registered_locales;
156
157     # Set a locale cookie if the requested locale is valid
158     my $set_locale = $cgi->param('set_eg_locale');
159     if (!(grep {$_ eq $set_locale} keys %registered_locales)) {
160         $set_locale = '';
161     } else {
162         my $slc = $cgi->cookie({
163             '-name' => OILS_HTTP_COOKIE_LOCALE,
164             '-value' => $set_locale,
165             '-expires' => '+10y'
166         });
167         $r->headers_out->add('Set-Cookie' => $slc);
168     }
169
170     $ctx->{locale} = $set_locale ||
171         $cgi->cookie(OILS_HTTP_COOKIE_LOCALE) || 
172         parse_accept_lang($r->headers_in->get('Accept-Language')) || 'en_us';
173
174     my $mprefix = $ctx->{media_prefix};
175     if($mprefix and $mprefix !~ /^http/ and $mprefix !~ /^\//) {
176         # if a hostname is provided /w no protocol, match the protocol to the current page
177         $ctx->{media_prefix} = ($cgi->https) ? "https://$mprefix" : "http://$mprefix";
178     }
179
180     return $ctx;
181 }
182
183 # turn Accept-Language into sometihng EG can understand
184 # TODO: try all langs, not just the first
185 sub parse_accept_lang {
186     my $al = shift;
187     return undef unless $al;
188     my ($locale) = split(/,/, $al);
189     ($locale) = split(/;/, $locale);
190     return undef unless $locale;
191     $locale =~ s/-/_/og;
192     return $locale;
193 }
194
195 # Given a URI, finds the configured template and any extra page 
196 # arguments (trailing path info).  Any extra data is returned
197 # as page arguments, in the form of an array, one item per 
198 # /-separated URI component
199 sub find_template {
200     my $r = shift;
201     my $base = shift;
202     my $ctx = shift;
203     my $path = $r->uri;
204     $path =~ s/$base\/?//og;
205     my $template = '';
206     my $page_args = [];
207     my $as_xml = $r->dir_config('OILSWebForceValidXML');
208     my $ext = $r->dir_config('OILSWebDefaultTemplateExtension');
209
210     my @parts = split('/', $path);
211     my $localpath = $path;
212     my @args;
213     while(@parts) {
214         last unless $localpath;
215         for my $tpath (@{$ctx->{template_paths}}) {
216             my $fpath = "$tpath/$localpath.$ext";
217             $r->log->debug("egweb: looking at possible template $fpath");
218             if(-r $fpath) {
219                 $template = "$localpath.$ext";
220                 last;
221             }
222         }
223         last if $template;
224         push(@args, pop @parts);
225         $localpath = join('/', @parts);
226     } 
227
228     $page_args = [@args];
229
230     # no template configured or found
231     unless($template) {
232         $r->log->debug("egweb: No template configured for path $path");
233         return ();
234     }
235
236     $r->log->debug("egweb: template = $template : page args = @$page_args");
237     return ($template, $page_args, $as_xml);
238 }
239
240 # Create an I18N sub-module for each supported locale
241 # Each module creates its own MakeText lexicon by parsing .po/.mo files
242 sub load_locale_handlers {
243     my $ctx = shift;
244     my %locales = @_;
245
246     my $editor = new_editor();
247     my @locale_tags = sort { length($a) <=> length($b) } keys %locales;
248
249     # always fall back to en_us, the assumed template language
250     push(@locale_tags, 'en_us');
251
252     for my $idx (0..$#locale_tags) {
253
254         my $tag = $locale_tags[$idx];
255         next if grep { $_ eq $tag } keys %registered_locales;
256
257         my $res = $editor->json_query({
258             "from" => [
259                 "evergreen.get_locale_name",
260                 $tag
261             ]
262         });
263
264         my $locale_name = $res->[0]->{"name"} if exists $res->[0]->{"name"};
265         next unless $locale_name;
266
267         my $parent_tag = '';
268         my $sub_idx = $idx;
269
270         # find the parent locale if possible.  It will be 
271         # longest left-anchored substring of the current tag
272         while( --$sub_idx >= 0 ) {
273             my $ptag = $locale_tags[$sub_idx];
274             if( substr($tag, 0, length($ptag)) eq $ptag ) {
275                 $parent_tag = "::$ptag";
276                 last;
277             }
278         }
279
280         my $messages = $locales{$tag} || '';
281
282         # TODO Can we do this without eval?
283         my $eval = <<"        EVAL";
284             package OpenILS::WWW::EGWeb::I18N::$tag;
285             use base 'OpenILS::WWW::EGWeb::I18N$parent_tag';
286             if(\$messages) {
287                 use Locale::Maketext::Lexicon {
288                     _decode => 1
289                 };
290                 use Locale::Maketext::Lexicon::Gettext;
291                 if(open F, '$messages') {
292                     our %Lexicon = (%Lexicon, %{ Locale::Maketext::Lexicon::Gettext->parse(<F>) });
293                     close F;
294                 } else {
295                     warn "EGWeb: unable to open messages file: $messages"; 
296                 }
297             }
298         EVAL
299         eval $eval;
300
301         if ($@) {
302             warn "$@\n" if $@;
303         } else {
304             $registered_locales{"$tag"} = $locale_name;
305         }
306     }
307 }
308
309
310 # base class for all supported locales
311 package OpenILS::WWW::EGWeb::I18N;
312 use base 'Locale::Maketext';
313 our %Lexicon = (_AUTO => 1);
314
315 1;