Bug 35070: Add plugin hook template_include_paths
[koha.git] / C4 / Templates.pm
1 package C4::Templates;
2
3 use strict;
4 use warnings;
5 use Carp qw( carp );
6 use CGI qw ( -utf8 );
7 use List::MoreUtils qw( uniq );
8
9 # Copyright 2009 Chris Cormack and The Koha Dev Team
10 #
11 # This file is part of Koha.
12 #
13 # Koha is free software; you can redistribute it and/or modify it
14 # under the terms of the GNU General Public License as published by
15 # the Free Software Foundation; either version 3 of the License, or
16 # (at your option) any later version.
17 #
18 # Koha is distributed in the hope that it will be useful, but
19 # WITHOUT ANY WARRANTY; without even the implied warranty of
20 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
21 # GNU General Public License for more details.
22 #
23 # You should have received a copy of the GNU General Public License
24 # along with Koha; if not, see <http://www.gnu.org/licenses>.
25
26 =head1 NAME 
27
28 C4::Templates - Object for manipulating templates for use with Koha
29
30 =cut
31
32 use base qw(Class::Accessor);
33 use Template;
34 use C4::Languages qw( get_bidi getTranslatedLanguages regex_lang_subtags );
35
36 use C4::Context;
37
38 use Koha::Cache::Memory::Lite;
39 use Koha::Exceptions;
40
41 __PACKAGE__->mk_accessors(qw( theme activethemes preferredtheme lang filename htdocs interface vars));
42
43
44
45 sub new {
46     my $class     = shift;
47     my $interface = shift;
48     my $filename  = shift;
49     my $tmplbase  = shift;
50     my $query     = @_? shift: undef;
51     my $htdocs;
52     if ( $interface ne "intranet" ) {
53         $htdocs = C4::Context->config('opachtdocs');
54     }
55     else {
56         $htdocs = C4::Context->config('intrahtdocs');
57     }
58     my ($theme, $lang, $activethemes)= themelanguage( $htdocs, $tmplbase, $interface, $query);
59     my @includes;
60     foreach (@$activethemes) {
61         push @includes, "$htdocs/$_/$lang/includes";
62         push @includes, "$htdocs/$_/en/includes" unless $lang eq 'en';
63     }
64
65     my @plugins_include_paths = Koha::Plugins->call( 'template_include_paths',
66         { interface => $interface, lang => $lang } );
67     push @includes, map { $_ ? @$_ : () } @plugins_include_paths;
68
69     # Do not use template cache if script is called from commandline
70     my $use_template_cache = C4::Context->config('template_cache_dir') && defined $ENV{GATEWAY_INTERFACE};
71     my $template = Template->new(
72         {   EVAL_PERL    => 1,
73             ABSOLUTE     => 1,
74             PLUGIN_BASE => 'Koha::Template::Plugin',
75             COMPILE_EXT => $use_template_cache ? '.ttc' : '',
76             COMPILE_DIR => $use_template_cache ? C4::Context->config('template_cache_dir') : '',
77             INCLUDE_PATH => \@includes,
78             FILTERS => {},
79             ENCODING => 'UTF-8',
80         }
81     ) or die Template->error();
82     my $self = {
83         TEMPLATE => $template,
84         VARS     => {},
85     };
86     bless $self, $class;
87     $self->theme($theme);
88     $self->lang($lang);
89     $self->activethemes($activethemes);
90     $self->preferredtheme($activethemes->[0]);
91     $self->filename($filename);
92     $self->htdocs($htdocs);
93     $self->interface($interface);
94     $self->{VARS}->{"test"} = "value";
95     return $self;
96
97 }
98
99 sub output {
100     my $self = shift;
101     my $vars = shift;
102
103 #    my $file = $self->htdocs . '/' . $self->theme .'/'.$self->lang.'/'.$self->filename;
104     my $template = $self->{TEMPLATE};
105     if ( $self->interface eq 'intranet' ) {
106         $vars->{themelang} = '/intranet-tmpl';
107     }
108     else {
109         $vars->{themelang} = '/opac-tmpl';
110     }
111     $vars->{lang} = $self->lang;
112     $vars->{themelang} .= '/' . $self->preferredtheme . '/' . $self->lang;
113     $vars->{interface} =
114       ( $self->{interface} ne 'intranet' ? '/opac-tmpl' : '/intranet-tmpl' );
115     $vars->{theme} = $self->theme;
116     $vars->{OpacAdditionalStylesheet} =
117         C4::Context->preference('OpacAdditionalStylesheet');
118     $vars->{opaclayoutstylesheet} =
119         C4::Context->preference('opaclayoutstylesheet');
120
121     if(exists $self->{VARS}{lang}) {
122         warn "Preventing \$template->lang='" . ($self->{vars}{lang}//'-undef-')
123             . "' to be overwritten by template->{VARS}{lang}='" . ($self->{VARS}{lang}//'-undef-') . "'";
124         delete $self->{VARS}{lang};
125     }
126
127     # add variables set via param to $vars for processing
128     $vars = { %$vars, %{ $self->{VARS} } };
129
130     my $data;
131     binmode( STDOUT, ":encoding(UTF-8)" );
132     $template->process( $self->filename, $vars, \$data )
133       || die "Template process failed: ", $template->error();
134     return $data;
135 }
136
137 # wrapper method to allow easier transition from HTML template pro to Template Toolkit
138 sub param {
139     my $self = shift;
140     while (@_) {
141         my $key = shift;
142         my $val = shift;
143         if    ( ref($val) eq 'ARRAY' && !scalar @$val ) { $val = undef; }
144         elsif ( ref($val) eq 'HASH'  && !scalar %$val ) { $val = undef; }
145         if ( $key ) {
146             $self->{VARS}->{$key} = $val;
147         } else {
148             warn "Problem = a value of $val has been passed to param without key";
149         }
150     }
151 }
152
153
154 =head1 NAME
155
156 C4::Templates - Functions for managing templates
157
158 =head1 FUNCTIONS
159
160 =cut
161
162 # FIXME: this is a quick fix to stop rc1 installing broken
163 # Still trying to figure out the correct fix.
164 my $path = C4::Context->config('intrahtdocs') . "/prog/en/includes/";
165
166 #---------------------------------------------------------------------------------------------------------
167 # FIXME - POD
168
169 sub _get_template_file {
170     my ($tmplbase, $interface, $query) = @_;
171
172     my $is_intranet = $interface eq 'intranet';
173     my $htdocs = C4::Context->config($is_intranet ? 'intrahtdocs' : 'opachtdocs');
174     my ($theme, $lang, $availablethemes) = themelanguage($htdocs, $tmplbase, $interface, $query);
175     $lang //= 'en';
176     $theme //= '';
177     $tmplbase = "$htdocs/$theme/$lang/modules/$tmplbase" if $tmplbase !~ /^\//;
178         # do not prefix an absolute path
179
180     return ( $htdocs, $theme, $lang, $tmplbase );
181 }
182
183 =head2 badtemplatecheck
184
185     badtemplatecheck( $template_path );
186
187     The sub will throw an exception if the template path is not allowed.
188
189     Note: At this moment the sub is actually a helper routine for
190     sub gettemplate.
191
192 =cut
193
194 sub badtemplatecheck {
195     my ( $template ) = @_;
196     if( !$template || $template !~ m/^[a-zA-Z0-9_\-\/]+\.(tt|pref)$/ ) {
197         # This also includes two dots
198         Koha::Exceptions::NoPermission->throw( 'bad template path' );
199     } else {
200         # Check allowed dirs - make sure we operate on a copy of the config
201         my $dirs = C4::Context->config("pluginsdir");
202         if ( !ref($dirs) ) {
203             $dirs = [ $dirs ];
204         }
205         else {
206             $dirs = [ @$dirs ];
207         }
208         unshift @$dirs, C4::Context->config('opachtdocs'), C4::Context->config('intrahtdocs');
209         my $found = 0;
210         foreach my $dir ( @$dirs ) {
211             $dir .= '/' if $dir !~ m/\/$/;
212             $found++ if $template =~ m/^$dir/;
213             last if $found;
214         }
215         Koha::Exceptions::NoPermission->throw( 'bad template path' ) if !$found;
216     }
217 }
218
219 sub gettemplate {
220     my ( $tmplbase, $interface, $query ) = @_;
221     my ($htdocs, $theme, $lang, $filename)
222        =  _get_template_file($tmplbase, $interface, $query);
223     badtemplatecheck( $filename ); # single trip for bad templates
224     my $template = C4::Templates->new($interface, $filename, $tmplbase, $query);
225
226 # NOTE: Commenting these out rather than deleting them so that those who need
227 # to know how we previously shimmed these directories will be able to understand.
228 #    my $is_intranet = $interface eq 'intranet';
229 #    my $themelang =
230 #        ($is_intranet ? '/intranet-tmpl' : '/opac-tmpl') .
231 #        "/$theme/$lang";
232 #    $template->param(
233 #        themelang => $themelang,
234 #        interface => $is_intranet ? '/intranet-tmpl' : '/opac-tmpl',
235 #        theme     => $theme,
236 #        lang      => $lang
237 #    );
238
239     # Bidirectionality, must be sent even if is the only language
240     my $current_lang = regex_lang_subtags($lang);
241     my $bidi;
242     $bidi = get_bidi($current_lang->{script}) if $current_lang->{script};
243     $template->param(
244             bidi                 => $bidi,
245     );
246     # Languages
247     my $languages_loop = getTranslatedLanguages($interface,$theme,$lang);
248     my $num_languages_enabled = 0;
249     foreach my $lang (@$languages_loop) {
250         foreach my $sublang (@{ $lang->{'sublanguages_loop'} }) {
251             $num_languages_enabled++ if $sublang->{enabled};
252          }
253     }
254     my $one_language_enabled = ($num_languages_enabled <= 1) ? 1 : 0; # deal with zero enabled langs as well
255     $template->param(
256             languages_loop       => $languages_loop,
257             one_language_enabled => $one_language_enabled,
258     ) unless $one_language_enabled;
259
260     return $template;
261 }
262
263
264 =head2 themelanguage
265
266     my ($theme,$lang,\@themes) = themelanguage($htdocs,$tmpl,$interface,query);
267
268 This function returns the theme and language to be used for rendering the UI.
269 It also returns the list of themes that should be applied as a fallback. This is
270 used for the theme overlay feature (i.e. if a file doesn't exist on the requested
271 theme, fallback to the configured fallback).
272
273 Important: this function is used on the webinstaller too, so always consider
274 the use case where the DB is not populated already when rewriting/fixing.
275
276 =cut
277
278 sub themelanguage {
279     my ($htdocs, $tmpl, $interface, $query) = @_;
280
281     # Select a language based on cookie, syspref available languages & browser
282     my $lang = C4::Languages::getlanguage($query);
283
284     return availablethemes($htdocs, $tmpl, $interface, $lang);
285 }
286
287 sub availablethemes {
288     my ($htdocs, $tmpl, $interface, $lang) = @_;
289
290     # Get theme
291     my @themes;
292     my $theme_syspref    = ($interface eq 'intranet') ? 'template' : 'opacthemes';
293     my $fallback_syspref = ($interface eq 'intranet') ? 'template' : 'OPACFallback';
294     # Yeah, hardcoded, last resort if the DB is not populated
295     my $hardcoded_theme = ($interface eq 'intranet') ? 'prog' : 'bootstrap';
296
297     # Configured theme is the first one
298     push @themes, C4::Context->preference( $theme_syspref )
299         if C4::Context->preference( $theme_syspref );
300     # Configured fallback next
301     push @themes, C4::Context->preference( $fallback_syspref )
302         if C4::Context->preference( $fallback_syspref );
303     # The hardcoded fallback theme is the last one
304     push @themes, $hardcoded_theme;
305
306     # Try to find first theme for the selected theme/lang, then for fallback/lang
307     my $where = $tmpl =~ /xsl$/ ? 'xslt' : 'modules';
308     for my $theme (@themes) {
309         if ( -e "$htdocs/$theme/$lang/$where/$tmpl" ) {
310             return ( $theme, $lang, [ uniq(@themes) ] );
311         }
312     }
313     # Otherwise return theme/'en', last resort fallback/'en'
314     for my $theme (@themes) {
315         if ( -e "$htdocs/$theme/en/$where/$tmpl" ) {
316             return ( $theme, 'en', [ uniq(@themes) ] );
317         }
318     }
319     # tmpl is a full path, so this is a template for a plugin
320     if ( $tmpl =~ /^\// && -e $tmpl ) {
321         return ( $themes[0], $lang, [ uniq(@themes) ] );
322     }
323 }
324
325 sub setlanguagecookie {
326     my ( $query, $language, $uri ) = @_;
327
328     my $cookie = getlanguagecookie( $query, $language );
329
330     # We do not want to set getlanguage in cache, some additional checks are
331     # done in C4::Languages::getlanguage
332     Koha::Cache::Memory::Lite->get_instance()->clear_from_cache( 'getlanguage' );
333
334     print $query->redirect(
335         -uri    => $uri,
336         -cookie => $cookie
337     );
338 }
339
340 =head2 getlanguagecookie
341
342     my $cookie = getlanguagecookie($query,$language);
343
344 Returns a cookie object containing the calculated language to be used.
345
346 =cut
347
348 sub getlanguagecookie {
349     my ( $query, $language ) = @_;
350     my $cookie = $query->cookie(
351         -name    => 'KohaOpacLanguage',
352         -value   => $language,
353         -HttpOnly => 1,
354         -expires => '+3y',
355         -sameSite => 'Lax',
356         -secure => ( C4::Context->https_enabled() ? 1 : 0 ),
357     );
358
359     return $cookie;
360 }
361
362 1;