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