1 package OpenILS::WWW::EGWeb;
2 use strict; use warnings;
8 use Apache2::Const -compile => qw(OK DECLINED HTTP_INTERNAL_SERVER_ERROR);
10 use OpenSRF::EX qw(:try);
11 use OpenSRF::AppSession;
12 use OpenILS::Utils::CStoreEditor q/:funcs/;
13 use List::MoreUtils qw/uniq/;
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';
19 # cache string bundles
20 my %registered_locales;
24 my $stat = handler_guts($r);
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;
36 my $ctx = load_context($r);
37 my $base = $ctx->{base_path};
39 my($template, $page_args, $as_xml) = find_template($r, $base, $ctx);
40 $ctx->{page_args} = $page_args;
42 my $stat = run_context_loader($r, $ctx);
44 return $stat unless $stat == Apache2::Const::OK;
45 return Apache2::Const::DECLINED unless $template;
47 my $text_handler = set_text_handler($ctx, $r);
49 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},
55 EGI18N => 'OpenILS::WWW::EGWeb::I18NFilter',
56 CGI_utf8 => 'OpenILS::WWW::EGWeb::CGI_utf8'
59 # Register a dynamic filter factory for our locale::maketext generator
63 return sub { $text_handler->(shift(), @args); }
70 $r->log->error("Error creating template processor: $@");
71 return Apache2::Const::HTTP_INTERNAL_SERVER_ERROR;
74 $ctx->{encode_utf8} = sub {return encode_utf8(shift())};
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;
81 return Apache2::Const::OK;
84 sub set_text_handler {
88 my $locale = $ctx->{locale};
90 $r->log->debug("egweb: messages locale = $locale");
93 my $lh = OpenILS::WWW::EGWeb::I18N->get_handle($locale);
94 return $lh->maketext(@_);
100 sub run_context_loader {
104 my $stat = Apache2::Const::OK;
106 my $loader = $r->dir_config('OILSWebContextLoader');
107 return $stat unless $loader;
111 $stat = $loader->new($r, $ctx)->load;
115 $r->log->error("egweb: Context Loader error: $@");
116 return Apache2::Const::HTTP_INTERNAL_SERVER_ERROR;
119 $r->log->debug("egweb: context loader resulted in status $stat");
131 my $doc = XML::LibXML->new->parse_string($data);
132 $data = $doc->documentElement->toStringC14N;
133 $data = $ctx->{final_dtd} . "\n" . $data;
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");
143 $r->print($data) if ($success);
149 my $ctx = {}; # new context for each page load
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';
163 my @template_paths = uniq $r->dir_config->get('OILSWebTemplatePath');
164 $ctx->{template_paths} = [ reverse @template_paths ];
166 my %locales = $r->dir_config->get('OILSWebLocale');
167 load_locale_handlers($ctx, %locales);
169 $ctx->{locales} = \%registered_locales;
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)) {
176 my $slc = $cgi->cookie({
177 '-name' => OILS_HTTP_COOKIE_LOCALE,
178 '-value' => $set_locale,
181 $r->headers_out->add('Set-Cookie' => $slc);
184 $ctx->{locale} = $set_locale ||
185 $cgi->cookie(OILS_HTTP_COOKIE_LOCALE) || $default_locale ||
186 parse_accept_lang($r->headers_in->get('Accept-Language'));
188 # set the editor default locale for each page load
189 OpenSRF::AppSession->default_locale(parse_eg_locale($ctx->{locale}));
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";
200 # turn Accept-Language into something EG can understand
201 # TODO: try all langs, not just the first
202 sub parse_accept_lang {
204 return undef unless $al;
205 my ($locale) = split(/,/, $al);
206 ($locale) = split(/;/, $locale);
207 return undef unless $locale;
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';
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";
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
233 $path =~ s/$base\/?//og;
236 my $as_xml = $r->dir_config('OILSWebForceValidXML');
237 my $ext = $r->dir_config('OILSWebDefaultTemplateExtension');
239 my @parts = split('/', $path);
240 my $localpath = $path;
242 if ($localpath =~ m|opac/css|) {
243 $r->content_type('text/css; encoding=utf8');
245 $r->content_type('text/html; encoding=utf8');
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");
254 $template = "$localpath.$ext";
259 push(@args, pop @parts);
260 $localpath = join('/', @parts);
263 $page_args = [@args];
265 # no template configured or found
267 $r->log->debug("egweb: No template configured for path $path");
271 $r->log->debug("egweb: template = $template : page args = @$page_args");
272 return ($template, $page_args, $as_xml);
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 {
281 my $editor = new_editor();
282 my @locale_tags = sort { length($a) <=> length($b) } keys %locales;
284 # always fall back to en_us, the assumed template language
285 push(@locale_tags, 'en_us');
287 for my $idx (0..$#locale_tags) {
289 my $tag = $locale_tags[$idx];
290 next if grep { $_ eq $tag } keys %registered_locales;
292 my $res = $editor->json_query({
294 "evergreen.get_locale_name",
299 my $locale_name = $res->[0]->{"name"} if exists $res->[0]->{"name"};
300 next unless $locale_name;
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";
315 my $messages = $locales{$tag} || '';
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';
322 use Locale::Maketext::Lexicon {
325 use Locale::Maketext::Lexicon::Gettext;
326 if(open F, '$messages') {
327 our %Lexicon = (%Lexicon, %{ Locale::Maketext::Lexicon::Gettext->parse(<F>) });
330 warn "EGWeb: unable to open messages file: $messages";
339 $registered_locales{"$tag"} = $locale_name;
345 # base class for all supported locales
346 package OpenILS::WWW::EGWeb::I18N;
347 use base 'Locale::Maketext';
348 our %Lexicon = (_AUTO => 1);