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