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