1 package OpenILS::WWW::EGWeb;
2 use strict; use warnings;
8 use Apache2::Const -compile => qw(OK DECLINED HTTP_INTERNAL_SERVER_ERROR HTTP_NOT_FOUND HTTP_GONE);
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;
22 # cache template path -r tests
25 # cache template processors by vhost
26 my %vhost_processor_cache;
30 my $stat = handler_guts($r);
32 # other opensrf clients share this apache process,
33 # so it's critical to reset the locale after each
34 # response is handled, lest the other clients
35 # adopt our temporary, global locale value.
36 OpenSRF::AppSession->reset_locale;
42 my $ctx = load_context($r);
43 my $base = $ctx->{base_path};
45 my($template, $page_args, $as_xml) = find_template($r, $base, $ctx);
46 $ctx->{page_args} = $page_args;
48 my $stat = run_context_loader($r, $ctx);
50 # Handle deleted or never existing records a little more gracefully.
51 # For these two special cases, we set the status so that the request
52 # header will contain the appropriate HTTP status code, but reset the
53 # status so that Apache will continue to process the request and provide
54 # more than just the raw HTTP error page.
55 if ($stat == Apache2::Const::HTTP_GONE || $stat == Apache2::Const::HTTP_NOT_FOUND) {
57 $stat = Apache2::Const::OK;
59 return $stat unless $stat == Apache2::Const::OK;
60 return Apache2::Const::DECLINED unless $template;
62 my $text_handler = set_text_handler($ctx, $r);
64 my $processor_key = $as_xml ? 'xml:' : 'text:'; # separate by XML strictness
65 $processor_key .= $ctx->{hostname}.':'; # ... and vhost
66 $processor_key .= $r->dir_config('OILSWebContextLoader').':'; # ... and context loader
67 $processor_key .= $ctx->{locale}; # ... and locale
68 # NOTE: context loader and vhost together imply template path and debug template values
69 # TODO: maybe add STAT_TTL and cache dir from LP#1449709?
71 my $tt = $vhost_processor_cache{$processor_key} || Template->new({
73 OUTPUT => ($as_xml) ? sub { parse_as_xml($r, $ctx, @_); } : $r,
74 INCLUDE_PATH => $ctx->{template_paths},
75 DEBUG => $ctx->{debug_template},
77 EGI18N => 'OpenILS::WWW::EGWeb::I18NFilter',
78 CGI_utf8 => 'OpenILS::WWW::EGWeb::CGI_utf8'
81 # Register a dynamic filter factory for our locale::maketext generator
85 return sub { $text_handler->(shift(), @args); }
92 $r->log->error("Error creating template processor: $@");
93 return Apache2::Const::HTTP_INTERNAL_SERVER_ERROR;
96 $vhost_processor_cache{$processor_key} = $tt;
97 $ctx->{encode_utf8} = sub {return encode_utf8(shift())};
99 unless($tt->process($template, {ctx => $ctx, ENV => \%ENV, l => $text_handler}, $r)) {
100 $r->log->warn('egweb: template error: ' . $tt->error);
101 return Apache2::Const::HTTP_INTERNAL_SERVER_ERROR;
104 return Apache2::Const::OK;
107 sub set_text_handler {
111 my $locale = $ctx->{locale};
113 $r->log->debug("egweb: messages locale = $locale");
116 my $lh = OpenILS::WWW::EGWeb::I18N->get_handle($locale)
117 || OpenILS::WWW::EGWeb::I18N->new;
118 return $lh->maketext(@_);
124 sub run_context_loader {
128 my $stat = Apache2::Const::OK;
130 my $loader = $r->dir_config('OILSWebContextLoader');
131 return $stat unless $loader;
135 $stat = $loader->new($r, $ctx)->load;
139 $r->log->error("egweb: Context Loader error: $@");
140 return Apache2::Const::HTTP_INTERNAL_SERVER_ERROR;
143 $r->log->debug("egweb: context loader resulted in status $stat");
155 my $doc = XML::LibXML->new->parse_string($data);
156 $data = $doc->documentElement->toStringC14N;
157 $data = $ctx->{final_dtd} . "\n" . $data;
161 my $err = "Invalid XML: $e";
162 $r->log->error("egweb: $err");
163 $r->content_type('text/plain; encoding=utf8');
164 $r->print("\n$err\n\n$data");
167 $r->print($data) if ($success);
173 my $ctx = {}; # new context for each page load
175 $ctx->{base_path} = $r->dir_config('OILSWebBasePath');
176 $ctx->{web_dir} = $r->dir_config('OILSWebWebDir');
177 $ctx->{debug_template} = ($r->dir_config('OILSWebDebugTemplate') =~ /true/io);
178 $ctx->{media_prefix} = $r->dir_config('OILSWebMediaPrefix');
179 $ctx->{hostname} = $r->hostname;
180 $ctx->{base_url} = $cgi->url(-base => 1);
181 $ctx->{skin} = $cgi->cookie(OILS_HTTP_COOKIE_SKIN) || 'default';
182 $ctx->{theme} = $cgi->cookie(OILS_HTTP_COOKIE_THEME) || 'default';
183 $ctx->{proto} = $cgi->https ? 'https' : 'http';
184 $ctx->{ext_proto} = $ctx->{proto};
185 my $default_locale = $r->dir_config('OILSWebDefaultLocale') || 'en_us';
187 my @template_paths = uniq $r->dir_config->get('OILSWebTemplatePath');
188 $ctx->{template_paths} = [ reverse @template_paths ];
190 my %locales = $r->dir_config->get('OILSWebLocale');
191 load_locale_handlers($ctx, %locales);
193 $ctx->{locales} = \%registered_locales;
195 # Set a locale cookie if the requested locale is valid
196 my $set_locale = $cgi->param('set_eg_locale') || '';
197 if (!(grep {$_ eq $set_locale} keys %registered_locales)) {
200 my $slc = $cgi->cookie({
201 '-name' => OILS_HTTP_COOKIE_LOCALE,
202 '-value' => $set_locale,
205 $r->headers_out->add('Set-Cookie' => $slc);
208 $ctx->{locale} = $set_locale ||
209 $cgi->cookie(OILS_HTTP_COOKIE_LOCALE) || $default_locale ||
210 parse_accept_lang($r->headers_in->get('Accept-Language'));
212 # set the editor default locale for each page load
213 my $ses_locale = parse_eg_locale($ctx->{locale});
214 OpenSRF::AppSession->default_locale($ses_locale);
215 # give templates access to the en-US style locale
216 $ctx->{eg_locale} = $ses_locale;
218 my $mprefix = $ctx->{media_prefix};
219 if($mprefix and $mprefix !~ /^http/ and $mprefix !~ /^\//) {
220 # if a hostname is provided /w no protocol, match the protocol to the current page
221 $ctx->{media_prefix} = ($cgi->https) ? "https://$mprefix" : "http://$mprefix";
227 # turn Accept-Language into something EG can understand
228 # TODO: try all langs, not just the first
229 sub parse_accept_lang {
231 return undef unless $al;
232 my ($locale) = split(/,/, $al);
233 ($locale) = split(/;/, $locale);
234 return undef unless $locale;
239 # Accept-Language uses locales like 'en', 'fr', 'fr_fr', while Evergreen
240 # internally uses 'en-US', 'fr-CA', 'fr-FR' (always with the 2 lowercase,
241 # hyphen, 2 uppercase convention)
242 sub parse_eg_locale {
243 my $ua_locale = shift || 'en_us';
245 $ua_locale =~ m/^(..).?(..)?$/;
246 my $lang_code = lc($1);
247 my $region_code = $2 ? uc($2) : uc($1);
248 return "$lang_code-$region_code";
251 # Given a URI, finds the configured template and any extra page
252 # arguments (trailing path info). Any extra data is returned
253 # as page arguments, in the form of an array, one item per
254 # /-separated URI component
260 $path =~ s/$base\/?//og;
263 my $as_xml = $r->dir_config('OILSWebForceValidXML');
264 my $ext = $r->dir_config('OILSWebDefaultTemplateExtension');
265 my $at_index = $r->dir_config('OILSWebStopAtIndex');
267 $vhost_path_cache{$ctx->{hostname}} ||= {};
268 my $path_cache = $vhost_path_cache{$ctx->{hostname}};
270 my @parts = split('/', $path);
271 my $localpath = $path;
273 if ($localpath =~ m|/css/|) {
274 $r->content_type('text/css; encoding=utf8');
276 $r->content_type('text/html; encoding=utf8');
281 last unless $localpath;
282 for my $tpath (@{$ctx->{template_paths}}) {
283 my $fpath = "$tpath/$localpath.$ext";
284 $r->log->debug("egweb: looking at possible template $fpath");
285 if ($template = $path_cache->{$fpath}) { # we've checked with -r before...
286 next if ($template eq '0E0'); # ... and found nothing
288 } elsif (-r $fpath) { # or, we haven't checked, and if we find a file...
289 $path_cache->{$fpath} = $template = "$localpath.$ext"; # ... note it
291 } else { # Nothing there...
292 $path_cache->{$fpath} = '0E0'; # ... note that fact
295 last if $template and $template ne '0E0';
298 # no matching template was found in the current directory.
299 # stop-at-index requested; see if there is an index.ext
300 # file in the same directory instead.
301 for my $tpath (@{$ctx->{template_paths}}) {
302 # replace the final path component with 'index'
303 if ($localpath =~ m|/$|) {
304 $localpath .= 'index';
306 $localpath =~ s|/[^/]+$|/index|;
308 my $fpath = "$tpath/$localpath.$ext";
309 $r->log->debug("egweb: looking at possible template $fpath");
310 if ($template = $path_cache->{$fpath}) { # See above block
311 next if ($template eq '0E0');
313 } elsif (-r $fpath) {
314 $path_cache->{$fpath} = $template = "$localpath.$ext";
317 $path_cache->{$fpath} = '0E0';
321 last if $template and $template ne '0E0';
323 push(@args, pop @parts);
324 $localpath = join('/', @parts);
327 $page_args = [@args];
329 # no template configured or found
330 if(!$template or $template eq '0E0') {
331 $r->log->debug("egweb: No template configured for path $path");
335 $r->log->debug("egweb: template = $template : page args = @$page_args");
336 return ($template, $page_args, $as_xml);
339 # Create an I18N sub-module for each supported locale
340 # Each module creates its own MakeText lexicon by parsing .po/.mo files
341 sub load_locale_handlers {
345 my $editor = new_editor();
346 my @locale_tags = sort { length($a) <=> length($b) } keys %locales;
348 # always fall back to en_us, the assumed template language
349 push(@locale_tags, 'en_us');
351 for my $idx (0..$#locale_tags) {
353 my $tag = $locale_tags[$idx];
354 next if grep { $_ eq $tag } keys %registered_locales;
356 my $res = $editor->json_query({
358 "evergreen.get_locale_name",
363 my $locale_name = $res->[0]->{"name"} if exists $res->[0]->{"name"};
364 next unless $locale_name;
369 # find the parent locale if possible. It will be
370 # longest left-anchored substring of the current tag
371 while( --$sub_idx >= 0 ) {
372 my $ptag = $locale_tags[$sub_idx];
373 if( substr($tag, 0, length($ptag)) eq $ptag ) {
374 $parent_tag = "::$ptag";
379 my $messages = $locales{$tag} || '';
381 # TODO Can we do this without eval?
382 my $eval = <<" EVAL";
383 package OpenILS::WWW::EGWeb::I18N::$tag;
384 use base 'OpenILS::WWW::EGWeb::I18N$parent_tag';
386 use Locale::Maketext::Lexicon {
389 use Locale::Maketext::Lexicon::Gettext;
390 if(open F, '$messages') {
391 our %Lexicon = (%Lexicon, %{ Locale::Maketext::Lexicon::Gettext->parse(<F>) });
394 warn "EGWeb: unable to open messages file: $messages";
403 $registered_locales{"$tag"} = $locale_name;
409 # base class for all supported locales
410 package OpenILS::WWW::EGWeb::I18N;
411 use base 'Locale::Maketext';
412 our %Lexicon = (_AUTO => 1);