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 my $ses_locale = parse_eg_locale($ctx->{locale});
190 OpenSRF::AppSession->default_locale($ses_locale);
191 # give templates access to the en-US style locale
192 $ctx->{eg_locale} = $ses_locale;
194 my $mprefix = $ctx->{media_prefix};
195 if($mprefix and $mprefix !~ /^http/ and $mprefix !~ /^\//) {
196 # if a hostname is provided /w no protocol, match the protocol to the current page
197 $ctx->{media_prefix} = ($cgi->https) ? "https://$mprefix" : "http://$mprefix";
203 # turn Accept-Language into something EG can understand
204 # TODO: try all langs, not just the first
205 sub parse_accept_lang {
207 return undef unless $al;
208 my ($locale) = split(/,/, $al);
209 ($locale) = split(/;/, $locale);
210 return undef unless $locale;
215 # Accept-Language uses locales like 'en', 'fr', 'fr_fr', while Evergreen
216 # internally uses 'en-US', 'fr-CA', 'fr-FR' (always with the 2 lowercase,
217 # hyphen, 2 uppercase convention)
218 sub parse_eg_locale {
219 my $ua_locale = shift || 'en_us';
221 $ua_locale =~ m/^(..).?(..)?$/;
222 my $lang_code = lc($1);
223 my $region_code = $2 ? uc($2) : uc($1);
224 return "$lang_code-$region_code";
227 # Given a URI, finds the configured template and any extra page
228 # arguments (trailing path info). Any extra data is returned
229 # as page arguments, in the form of an array, one item per
230 # /-separated URI component
236 $path =~ s/$base\/?//og;
239 my $as_xml = $r->dir_config('OILSWebForceValidXML');
240 my $ext = $r->dir_config('OILSWebDefaultTemplateExtension');
242 my @parts = split('/', $path);
243 my $localpath = $path;
245 if ($localpath =~ m|opac/css|) {
246 $r->content_type('text/css; encoding=utf8');
248 $r->content_type('text/html; encoding=utf8');
252 last unless $localpath;
253 for my $tpath (@{$ctx->{template_paths}}) {
254 my $fpath = "$tpath/$localpath.$ext";
255 $r->log->debug("egweb: looking at possible template $fpath");
257 $template = "$localpath.$ext";
262 push(@args, pop @parts);
263 $localpath = join('/', @parts);
266 $page_args = [@args];
268 # no template configured or found
270 $r->log->debug("egweb: No template configured for path $path");
274 $r->log->debug("egweb: template = $template : page args = @$page_args");
275 return ($template, $page_args, $as_xml);
278 # Create an I18N sub-module for each supported locale
279 # Each module creates its own MakeText lexicon by parsing .po/.mo files
280 sub load_locale_handlers {
284 my $editor = new_editor();
285 my @locale_tags = sort { length($a) <=> length($b) } keys %locales;
287 # always fall back to en_us, the assumed template language
288 push(@locale_tags, 'en_us');
290 for my $idx (0..$#locale_tags) {
292 my $tag = $locale_tags[$idx];
293 next if grep { $_ eq $tag } keys %registered_locales;
295 my $res = $editor->json_query({
297 "evergreen.get_locale_name",
302 my $locale_name = $res->[0]->{"name"} if exists $res->[0]->{"name"};
303 next unless $locale_name;
308 # find the parent locale if possible. It will be
309 # longest left-anchored substring of the current tag
310 while( --$sub_idx >= 0 ) {
311 my $ptag = $locale_tags[$sub_idx];
312 if( substr($tag, 0, length($ptag)) eq $ptag ) {
313 $parent_tag = "::$ptag";
318 my $messages = $locales{$tag} || '';
320 # TODO Can we do this without eval?
321 my $eval = <<" EVAL";
322 package OpenILS::WWW::EGWeb::I18N::$tag;
323 use base 'OpenILS::WWW::EGWeb::I18N$parent_tag';
325 use Locale::Maketext::Lexicon {
328 use Locale::Maketext::Lexicon::Gettext;
329 if(open F, '$messages') {
330 our %Lexicon = (%Lexicon, %{ Locale::Maketext::Lexicon::Gettext->parse(<F>) });
333 warn "EGWeb: unable to open messages file: $messages";
342 $registered_locales{"$tag"} = $locale_name;
348 # base class for all supported locales
349 package OpenILS::WWW::EGWeb::I18N;
350 use base 'Locale::Maketext';
351 our %Lexicon = (_AUTO => 1);