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
70 my $tt = $vhost_processor_cache{$processor_key} || Template->new({
72 OUTPUT => ($as_xml) ? sub { parse_as_xml($r, $ctx, @_); } : $r,
73 INCLUDE_PATH => $ctx->{template_paths},
74 DEBUG => $ctx->{debug_template},
76 $r->dir_config('OILSWebCompiledTemplateCache') ?
77 (COMPILE_DIR => $r->dir_config('OILSWebCompiledTemplateCache')) :
81 ($r->dir_config('OILSWebTemplateStatTTL') =~ /^\d+$/) ?
82 (STAT_TTL => $r->dir_config('OILSWebTemplateStatTTL')) :
86 EGI18N => 'OpenILS::WWW::EGWeb::I18NFilter',
87 CGI_utf8 => 'OpenILS::WWW::EGWeb::CGI_utf8'
90 # Register a dynamic filter factory for our locale::maketext generator
94 return sub { $text_handler->(shift(), @args); }
101 $r->log->error("Error creating template processor: $@");
102 return Apache2::Const::HTTP_INTERNAL_SERVER_ERROR;
105 $vhost_processor_cache{$processor_key} = $tt;
106 $ctx->{encode_utf8} = sub {return encode_utf8(shift())};
108 unless($tt->process($template, {ctx => $ctx, ENV => \%ENV, l => $text_handler}, $r)) {
109 $r->log->warn('egweb: template error: ' . $tt->error);
110 return Apache2::Const::HTTP_INTERNAL_SERVER_ERROR;
113 return Apache2::Const::OK;
116 sub set_text_handler {
120 my $locale = $ctx->{locale};
122 $r->log->debug("egweb: messages locale = $locale");
125 my $lh = OpenILS::WWW::EGWeb::I18N->get_handle($locale)
126 || OpenILS::WWW::EGWeb::I18N->new;
127 return $lh->maketext(@_);
133 sub run_context_loader {
137 my $stat = Apache2::Const::OK;
139 my $loader = $r->dir_config('OILSWebContextLoader');
140 return $stat unless $loader;
144 $stat = $loader->new($r, $ctx)->load;
148 $r->log->error("egweb: Context Loader error: $@");
149 return Apache2::Const::HTTP_INTERNAL_SERVER_ERROR;
152 $r->log->debug("egweb: context loader resulted in status $stat");
164 my $doc = XML::LibXML->new->parse_string($data);
165 $data = $doc->documentElement->toStringC14N;
166 $data = $ctx->{final_dtd} . "\n" . $data;
170 my $err = "Invalid XML: $e";
171 $r->log->error("egweb: $err");
172 $r->content_type('text/plain; encoding=utf8');
173 $r->print("\n$err\n\n$data");
176 $r->print($data) if ($success);
182 my $ctx = {}; # new context for each page load
184 $ctx->{base_path} = $r->dir_config('OILSWebBasePath');
185 $ctx->{web_dir} = $r->dir_config('OILSWebWebDir');
186 $ctx->{debug_template} = ($r->dir_config('OILSWebDebugTemplate') =~ /true/io) ? 1 : 0;
187 $ctx->{media_prefix} = $r->dir_config('OILSWebMediaPrefix');
188 $ctx->{hostname} = $r->hostname;
189 $ctx->{base_url} = $cgi->url(-base => 1);
190 $ctx->{skin} = $cgi->cookie(OILS_HTTP_COOKIE_SKIN) || 'default';
191 $ctx->{theme} = $cgi->cookie(OILS_HTTP_COOKIE_THEME) || 'default';
192 $ctx->{proto} = $cgi->https ? 'https' : 'http';
193 $ctx->{ext_proto} = $ctx->{proto};
194 my $default_locale = $r->dir_config('OILSWebDefaultLocale') || 'en_us';
196 my @template_paths = uniq $r->dir_config->get('OILSWebTemplatePath');
197 $ctx->{template_paths} = [ reverse @template_paths ];
199 my %locales = $r->dir_config->get('OILSWebLocale');
200 load_locale_handlers($ctx, %locales);
202 $ctx->{locales} = \%registered_locales;
204 # Set a locale cookie if the requested locale is valid
205 my $set_locale = $cgi->param('set_eg_locale') || '';
206 if (!(grep {$_ eq $set_locale} keys %registered_locales)) {
209 my $slc = $cgi->cookie({
210 '-name' => OILS_HTTP_COOKIE_LOCALE,
211 '-value' => $set_locale,
214 $r->headers_out->add('Set-Cookie' => $slc);
217 $ctx->{locale} = $set_locale ||
218 $cgi->cookie(OILS_HTTP_COOKIE_LOCALE) || $default_locale ||
219 parse_accept_lang($r->headers_in->get('Accept-Language'));
221 # set the editor default locale for each page load
222 my $ses_locale = parse_eg_locale($ctx->{locale});
223 OpenSRF::AppSession->default_locale($ses_locale);
224 # give templates access to the en-US style locale
225 $ctx->{eg_locale} = $ses_locale;
227 my $mprefix = $ctx->{media_prefix};
228 if($mprefix and $mprefix !~ /^http/ and $mprefix !~ /^\//) {
229 # if a hostname is provided /w no protocol, match the protocol to the current page
230 $ctx->{media_prefix} = ($cgi->https) ? "https://$mprefix" : "http://$mprefix";
236 # turn Accept-Language into something EG can understand
237 # TODO: try all langs, not just the first
238 sub parse_accept_lang {
240 return undef unless $al;
241 my ($locale) = split(/,/, $al);
242 ($locale) = split(/;/, $locale);
243 return undef unless $locale;
248 # Accept-Language uses locales like 'en', 'fr', 'fr_fr', while Evergreen
249 # internally uses 'en-US', 'fr-CA', 'fr-FR' (always with the 2 lowercase,
250 # hyphen, 2 uppercase convention)
251 sub parse_eg_locale {
252 my $ua_locale = shift || 'en_us';
254 $ua_locale =~ m/^(..).?(..)?$/;
255 my $lang_code = lc($1);
256 my $region_code = $2 ? uc($2) : uc($1);
257 return "$lang_code-$region_code";
260 # Given a URI, finds the configured template and any extra page
261 # arguments (trailing path info). Any extra data is returned
262 # as page arguments, in the form of an array, one item per
263 # /-separated URI component
269 $path =~ s/$base\/?//og;
272 my $as_xml = $r->dir_config('OILSWebForceValidXML');
273 my $ext = $r->dir_config('OILSWebDefaultTemplateExtension');
274 my $at_index = $r->dir_config('OILSWebStopAtIndex');
276 $vhost_path_cache{$ctx->{hostname}} ||= {};
277 my $path_cache = $vhost_path_cache{$ctx->{hostname}};
279 my @parts = split('/', $path);
280 my $localpath = $path;
282 if ($localpath =~ m|/css/|) {
283 $r->content_type('text/css; encoding=utf8');
285 $r->content_type('text/html; encoding=utf8');
290 last unless $localpath;
291 for my $tpath (@{$ctx->{template_paths}}) {
292 my $fpath = "$tpath/$localpath.$ext";
293 $r->log->debug("egweb: looking at possible template $fpath");
294 if ($template = $path_cache->{$fpath}) { # we've checked with -r before...
295 next if ($template eq '0E0'); # ... and found nothing
297 } elsif (-r $fpath) { # or, we haven't checked, and if we find a file...
298 $path_cache->{$fpath} = $template = "$localpath.$ext"; # ... note it
300 } else { # Nothing there...
301 $path_cache->{$fpath} = '0E0'; # ... note that fact
304 last if $template and $template ne '0E0';
307 # no matching template was found in the current directory.
308 # stop-at-index requested; see if there is an index.ext
309 # file in the same directory instead.
310 for my $tpath (@{$ctx->{template_paths}}) {
311 # replace the final path component with 'index'
312 if ($localpath =~ m|/$|) {
313 $localpath .= 'index';
315 $localpath =~ s|/[^/]+$|/index|;
317 my $fpath = "$tpath/$localpath.$ext";
318 $r->log->debug("egweb: looking at possible template $fpath");
319 if ($template = $path_cache->{$fpath}) { # See above block
320 next if ($template eq '0E0');
322 } elsif (-r $fpath) {
323 $path_cache->{$fpath} = $template = "$localpath.$ext";
326 $path_cache->{$fpath} = '0E0';
330 last if $template and $template ne '0E0';
332 push(@args, pop @parts);
333 $localpath = join('/', @parts);
336 $page_args = [@args];
338 # no template configured or found
339 if(!$template or $template eq '0E0') {
340 $r->log->debug("egweb: No template configured for path $path");
344 $r->log->debug("egweb: template = $template : page args = @$page_args");
345 return ($template, $page_args, $as_xml);
348 # Create an I18N sub-module for each supported locale
349 # Each module creates its own MakeText lexicon by parsing .po/.mo files
350 sub load_locale_handlers {
354 my $editor = new_editor();
355 my @locale_tags = sort { length($a) <=> length($b) } keys %locales;
357 # always fall back to en_us, the assumed template language
358 push(@locale_tags, 'en_us');
360 for my $idx (0..$#locale_tags) {
362 my $tag = $locale_tags[$idx];
363 next if grep { $_ eq $tag } keys %registered_locales;
365 my $res = $editor->json_query({
367 "evergreen.get_locale_name",
372 my $locale_name = $res->[0]->{"name"} if exists $res->[0]->{"name"};
373 next unless $locale_name;
378 # find the parent locale if possible. It will be
379 # longest left-anchored substring of the current tag
380 while( --$sub_idx >= 0 ) {
381 my $ptag = $locale_tags[$sub_idx];
382 if( substr($tag, 0, length($ptag)) eq $ptag ) {
383 $parent_tag = "::$ptag";
388 my $messages = $locales{$tag} || '';
390 # TODO Can we do this without eval?
391 my $eval = <<" EVAL";
392 package OpenILS::WWW::EGWeb::I18N::$tag;
393 use base 'OpenILS::WWW::EGWeb::I18N$parent_tag';
395 use Locale::Maketext::Lexicon {
398 use Locale::Maketext::Lexicon::Gettext;
399 if(open F, '$messages') {
400 our %Lexicon = (%Lexicon, %{ Locale::Maketext::Lexicon::Gettext->parse(<F>) });
403 warn "EGWeb: unable to open messages file: $messages";
412 $registered_locales{"$tag"} = $locale_name;
418 # base class for all supported locales
419 package OpenILS::WWW::EGWeb::I18N;
420 use base 'Locale::Maketext';
421 our %Lexicon = (_AUTO => 1);