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 || OpenILS::WWW::EGWeb::I18N->new;
95 return $lh->maketext(@_);
101 sub run_context_loader {
105 my $stat = Apache2::Const::OK;
107 my $loader = $r->dir_config('OILSWebContextLoader');
108 return $stat unless $loader;
112 $stat = $loader->new($r, $ctx)->load;
116 $r->log->error("egweb: Context Loader error: $@");
117 return Apache2::Const::HTTP_INTERNAL_SERVER_ERROR;
120 $r->log->debug("egweb: context loader resulted in status $stat");
132 my $doc = XML::LibXML->new->parse_string($data);
133 $data = $doc->documentElement->toStringC14N;
134 $data = $ctx->{final_dtd} . "\n" . $data;
138 my $err = "Invalid XML: $e";
139 $r->log->error("egweb: $err");
140 $r->content_type('text/plain; encoding=utf8');
141 $r->print("\n$err\n\n$data");
144 $r->print($data) if ($success);
150 my $ctx = {}; # new context for each page load
152 $ctx->{base_path} = $r->dir_config('OILSWebBasePath');
153 $ctx->{web_dir} = $r->dir_config('OILSWebWebDir');
154 $ctx->{debug_template} = ($r->dir_config('OILSWebDebugTemplate') =~ /true/io);
155 $ctx->{media_prefix} = $r->dir_config('OILSWebMediaPrefix');
156 $ctx->{hostname} = $r->hostname;
157 $ctx->{base_url} = $cgi->url(-base => 1);
158 $ctx->{skin} = $cgi->cookie(OILS_HTTP_COOKIE_SKIN) || 'default';
159 $ctx->{theme} = $cgi->cookie(OILS_HTTP_COOKIE_THEME) || 'default';
160 $ctx->{proto} = $cgi->https ? 'https' : 'http';
161 $ctx->{ext_proto} = $ctx->{proto};
162 my $default_locale = $r->dir_config('OILSWebDefaultLocale') || 'en_us';
164 my @template_paths = uniq $r->dir_config->get('OILSWebTemplatePath');
165 $ctx->{template_paths} = [ reverse @template_paths ];
167 my %locales = $r->dir_config->get('OILSWebLocale');
168 load_locale_handlers($ctx, %locales);
170 $ctx->{locales} = \%registered_locales;
172 # Set a locale cookie if the requested locale is valid
173 my $set_locale = $cgi->param('set_eg_locale') || '';
174 if (!(grep {$_ eq $set_locale} keys %registered_locales)) {
177 my $slc = $cgi->cookie({
178 '-name' => OILS_HTTP_COOKIE_LOCALE,
179 '-value' => $set_locale,
182 $r->headers_out->add('Set-Cookie' => $slc);
185 $ctx->{locale} = $set_locale ||
186 $cgi->cookie(OILS_HTTP_COOKIE_LOCALE) || $default_locale ||
187 parse_accept_lang($r->headers_in->get('Accept-Language'));
189 # set the editor default locale for each page load
190 my $ses_locale = parse_eg_locale($ctx->{locale});
191 OpenSRF::AppSession->default_locale($ses_locale);
192 # give templates access to the en-US style locale
193 $ctx->{eg_locale} = $ses_locale;
195 my $mprefix = $ctx->{media_prefix};
196 if($mprefix and $mprefix !~ /^http/ and $mprefix !~ /^\//) {
197 # if a hostname is provided /w no protocol, match the protocol to the current page
198 $ctx->{media_prefix} = ($cgi->https) ? "https://$mprefix" : "http://$mprefix";
204 # turn Accept-Language into something EG can understand
205 # TODO: try all langs, not just the first
206 sub parse_accept_lang {
208 return undef unless $al;
209 my ($locale) = split(/,/, $al);
210 ($locale) = split(/;/, $locale);
211 return undef unless $locale;
216 # Accept-Language uses locales like 'en', 'fr', 'fr_fr', while Evergreen
217 # internally uses 'en-US', 'fr-CA', 'fr-FR' (always with the 2 lowercase,
218 # hyphen, 2 uppercase convention)
219 sub parse_eg_locale {
220 my $ua_locale = shift || 'en_us';
222 $ua_locale =~ m/^(..).?(..)?$/;
223 my $lang_code = lc($1);
224 my $region_code = $2 ? uc($2) : uc($1);
225 return "$lang_code-$region_code";
228 # Given a URI, finds the configured template and any extra page
229 # arguments (trailing path info). Any extra data is returned
230 # as page arguments, in the form of an array, one item per
231 # /-separated URI component
237 $path =~ s/$base\/?//og;
240 my $as_xml = $r->dir_config('OILSWebForceValidXML');
241 my $ext = $r->dir_config('OILSWebDefaultTemplateExtension');
242 my $at_index = $r->dir_config('OILSWebStopAtIndex');
244 my @parts = split('/', $path);
245 my $localpath = $path;
247 if ($localpath =~ m|/css/|) {
248 $r->content_type('text/css; encoding=utf8');
250 $r->content_type('text/html; encoding=utf8');
254 last unless $localpath;
255 for my $tpath (@{$ctx->{template_paths}}) {
256 my $fpath = "$tpath/$localpath.$ext";
257 $r->log->debug("egweb: looking at possible template $fpath");
259 $template = "$localpath.$ext";
266 # no matching template was found in the current directory.
267 # stop-at-index requested; see if there is an index.ext
268 # file in the same directory instead.
269 for my $tpath (@{$ctx->{template_paths}}) {
270 # replace the final path component with 'index'
271 if ($localpath =~ m|/$|) {
272 $localpath .= 'index';
274 $localpath =~ s|/[^/]+$|/index|;
276 my $fpath = "$tpath/$localpath.$ext";
277 $r->log->debug("egweb: looking at possible template $fpath");
279 $template = "$localpath.$ext";
286 push(@args, pop @parts);
287 $localpath = join('/', @parts);
290 $page_args = [@args];
292 # no template configured or found
294 $r->log->debug("egweb: No template configured for path $path");
298 $r->log->debug("egweb: template = $template : page args = @$page_args");
299 return ($template, $page_args, $as_xml);
302 # Create an I18N sub-module for each supported locale
303 # Each module creates its own MakeText lexicon by parsing .po/.mo files
304 sub load_locale_handlers {
308 my $editor = new_editor();
309 my @locale_tags = sort { length($a) <=> length($b) } keys %locales;
311 # always fall back to en_us, the assumed template language
312 push(@locale_tags, 'en_us');
314 for my $idx (0..$#locale_tags) {
316 my $tag = $locale_tags[$idx];
317 next if grep { $_ eq $tag } keys %registered_locales;
319 my $res = $editor->json_query({
321 "evergreen.get_locale_name",
326 my $locale_name = $res->[0]->{"name"} if exists $res->[0]->{"name"};
327 next unless $locale_name;
332 # find the parent locale if possible. It will be
333 # longest left-anchored substring of the current tag
334 while( --$sub_idx >= 0 ) {
335 my $ptag = $locale_tags[$sub_idx];
336 if( substr($tag, 0, length($ptag)) eq $ptag ) {
337 $parent_tag = "::$ptag";
342 my $messages = $locales{$tag} || '';
344 # TODO Can we do this without eval?
345 my $eval = <<" EVAL";
346 package OpenILS::WWW::EGWeb::I18N::$tag;
347 use base 'OpenILS::WWW::EGWeb::I18N$parent_tag';
349 use Locale::Maketext::Lexicon {
352 use Locale::Maketext::Lexicon::Gettext;
353 if(open F, '$messages') {
354 our %Lexicon = (%Lexicon, %{ Locale::Maketext::Lexicon::Gettext->parse(<F>) });
357 warn "EGWeb: unable to open messages file: $messages";
366 $registered_locales{"$tag"} = $locale_name;
372 # base class for all supported locales
373 package OpenILS::WWW::EGWeb::I18N;
374 use base 'Locale::Maketext';
375 our %Lexicon = (_AUTO => 1);