Bug 13618: Use Template::Stash::AutoEscaping to use the html filter
[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 use Template::Stash::AutoEscaping;
9
10 # Copyright 2009 Chris Cormack and The Koha Dev Team
11 #
12 # This file is part of Koha.
13 #
14 # Koha is free software; you can redistribute it and/or modify it
15 # under the terms of the GNU General Public License as published by
16 # the Free Software Foundation; either version 3 of the License, or
17 # (at your option) any later version.
18 #
19 # Koha is distributed in the hope that it will be useful, but
20 # WITHOUT ANY WARRANTY; without even the implied warranty of
21 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
22 # GNU General Public License for more details.
23 #
24 # You should have received a copy of the GNU General Public License
25 # along with Koha; if not, see <http://www.gnu.org/licenses>.
26
27 =head1 NAME 
28
29     Koha::Templates - Object for manipulating templates for use with Koha
30
31 =cut
32
33 use base qw(Class::Accessor);
34 use Template;
35 use Template::Constants qw( :debug );
36 use C4::Languages qw(getTranslatedLanguages get_bidi regex_lang_subtags language_get_description accept_language );
37
38 use C4::Context;
39
40 __PACKAGE__->mk_accessors(qw( theme activethemes preferredtheme lang filename htdocs interface vars));
41
42
43
44 sub new {
45     my $class     = shift;
46     my $interface = shift;
47     my $filename  = shift;
48     my $tmplbase  = shift;
49     my $query     = @_? shift: undef;
50     my $htdocs;
51     if ( $interface ne "intranet" ) {
52         $htdocs = C4::Context->config('opachtdocs');
53     }
54     else {
55         $htdocs = C4::Context->config('intrahtdocs');
56     }
57     my ($theme, $lang, $activethemes)= themelanguage( $htdocs, $tmplbase, $interface, $query);
58     my @includes;
59     foreach (@$activethemes) {
60         push @includes, "$htdocs/$_/$lang/includes";
61         push @includes, "$htdocs/$_/en/includes" unless $lang eq 'en';
62     }
63     # Do not use template cache if script is called from commandline
64     my $use_template_cache = C4::Context->config('template_cache_dir') && defined $ENV{GATEWAY_INTERFACE};
65     my $template = Template->new(
66         {   EVAL_PERL    => 1,
67             ABSOLUTE     => 1,
68             PLUGIN_BASE => 'Koha::Template::Plugin',
69             COMPILE_EXT => $use_template_cache ? '.ttc' : '',
70             COMPILE_DIR => $use_template_cache ? C4::Context->config('template_cache_dir') : '',
71             INCLUDE_PATH => \@includes,
72             FILTERS => {},
73             STASH => Template::Stash::AutoEscaping->new,
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     # add variables set via param to $vars for processing
117     for my $k ( keys %{ $self->{VARS} } ) {
118         $vars->{$k} = $self->{VARS}->{$k};
119     }
120
121     my $data;
122     binmode( STDOUT, ":utf8" );
123     $template->process( $self->filename, $vars, \$data )
124       || die "Template process failed: ", $template->error();
125     return $data;
126 }
127
128 # wrapper method to allow easier transition from HTML template pro to Template Toolkit
129 sub param {
130     my $self = shift;
131     while (@_) {
132         my $key = shift;
133         my $val = shift;
134         if    ( ref($val) eq 'ARRAY' && !scalar @$val ) { $val = undef; }
135         elsif ( ref($val) eq 'HASH'  && !scalar %$val ) { $val = undef; }
136         if ( $key ) {
137             $self->{VARS}->{$key} = $val;
138         } else {
139             warn "Problem = a value of $val has been passed to param without key";
140         }
141     }
142 }
143
144
145 =head1 NAME
146
147 C4::Templates - Functions for managing templates
148
149 =head1 FUNCTIONS
150
151 =cut
152
153 # FIXME: this is a quick fix to stop rc1 installing broken
154 # Still trying to figure out the correct fix.
155 my $path = C4::Context->config('intrahtdocs') . "/prog/en/includes/";
156
157 #---------------------------------------------------------------------------------------------------------
158 # FIXME - POD
159
160 sub _get_template_file {
161     my ($tmplbase, $interface, $query) = @_;
162
163     my $is_intranet = $interface eq 'intranet';
164     my $htdocs = C4::Context->config($is_intranet ? 'intrahtdocs' : 'opachtdocs');
165     my ($theme, $lang, $availablethemes) = themelanguage($htdocs, $tmplbase, $interface, $query);
166     $lang //= 'en';
167     my $filename = "$htdocs/$theme/$lang/modules/$tmplbase";
168
169     return ($htdocs, $theme, $lang, $filename);
170 }
171
172
173 sub gettemplate {
174     my ( $tmplbase, $interface, $query, $is_plugin ) = @_;
175     ($query) or warn "no query in gettemplate";
176     my $path = C4::Context->preference('intranet_includes') || 'includes';
177     my ($htdocs, $theme, $lang, $filename)
178        =  _get_template_file($tmplbase, $interface, $query);
179     $filename = $tmplbase if ( $is_plugin );
180     my $template = C4::Templates->new($interface, $filename, $tmplbase, $query);
181
182 # NOTE: Commenting these out rather than deleting them so that those who need
183 # to know how we previously shimmed these directories will be able to understand.
184 #    my $is_intranet = $interface eq 'intranet';
185 #    my $themelang =
186 #        ($is_intranet ? '/intranet-tmpl' : '/opac-tmpl') .
187 #        "/$theme/$lang";
188 #    $template->param(
189 #        themelang => $themelang,
190 #        interface => $is_intranet ? '/intranet-tmpl' : '/opac-tmpl',
191 #        theme     => $theme,
192 #        lang      => $lang
193 #    );
194
195     # Bidirectionality, must be sent even if is the only language
196     my $current_lang = regex_lang_subtags($lang);
197     my $bidi;
198     $bidi = get_bidi($current_lang->{script}) if $current_lang->{script};
199     $template->param(
200             bidi                 => $bidi,
201     );
202     # Languages
203     my $languages_loop = getTranslatedLanguages($interface,$theme,$lang);
204     my $num_languages_enabled = 0;
205     foreach my $lang (@$languages_loop) {
206         foreach my $sublang (@{ $lang->{'sublanguages_loop'} }) {
207             $num_languages_enabled++ if $sublang->{enabled};
208          }
209     }
210     my $one_language_enabled = ($num_languages_enabled <= 1) ? 1 : 0; # deal with zero enabled langs as well
211     $template->param(
212             languages_loop       => $languages_loop,
213             one_language_enabled => $one_language_enabled,
214     ) unless $one_language_enabled;
215
216     return $template;
217 }
218
219
220 =head2 themelanguage
221
222     my ($theme,$lang,\@themes) = themelanguage($htdocs,$tmpl,$interface,query);
223
224 This function returns the theme and language to be used for rendering the UI.
225 It also returns the list of themes that should be applied as a fallback. This is
226 used for the theme overlay feature (i.e. if a file doesn't exist on the requested
227 theme, fallback to the configured fallback).
228
229 Important: this function is used on the webinstaller too, so always consider
230 the use case where the DB is not populated already when rewriting/fixing.
231
232 =cut
233
234 sub themelanguage {
235     my ($htdocs, $tmpl, $interface, $query) = @_;
236     ($query) or warn "no query in themelanguage";
237
238     # Select a language based on cookie, syspref available languages & browser
239     my $lang = C4::Languages::getlanguage($query);
240
241     # Get theme
242     my @themes;
243     my $theme_syspref    = ($interface eq 'intranet') ? 'template' : 'opacthemes';
244     my $fallback_syspref = ($interface eq 'intranet') ? 'template' : 'OPACFallback';
245     # Yeah, hardcoded, last resort if the DB is not populated
246     my $hardcoded_theme = ($interface eq 'intranet') ? 'prog' : 'bootstrap';
247
248     # Configured theme is the first one
249     push @themes, C4::Context->preference( $theme_syspref )
250         if C4::Context->preference( $theme_syspref );
251     # Configured fallback next
252     push @themes, C4::Context->preference( $fallback_syspref )
253         if C4::Context->preference( $fallback_syspref );
254     # The hardcoded fallback theme is the last one
255     push @themes, $hardcoded_theme;
256
257     # Try to find first theme for the selected theme/lang, then for fallback/lang
258     my $where = $tmpl =~ /xsl$/ ? 'xslt' : 'modules';
259     for my $theme (@themes) {
260         if ( -e "$htdocs/$theme/$lang/$where/$tmpl" ) {
261             return ( $theme, $lang, uniq( \@themes ) );
262         }
263     }
264     # Otherwise return theme/'en', last resort fallback/'en'
265     for my $theme (@themes) {
266         if ( -e "$htdocs/$theme/en/$where/$tmpl" ) {
267             return ( $theme, 'en', uniq( \@themes ) );
268         }
269     }
270     # tmpl is a full path, so this is a template for a plugin
271     if ( $tmpl =~ /^\// && -e $tmpl ) {
272         return ( $themes[0], $lang, uniq( \@themes ) );
273     }
274 }
275
276
277 sub setlanguagecookie {
278     my ( $query, $language, $uri ) = @_;
279
280     my $cookie = $query->cookie(
281         -name    => 'KohaOpacLanguage',
282         -value   => $language,
283         -HttpOnly => 1,
284         -expires => '+3y'
285     );
286     print $query->redirect(
287         -uri    => $uri,
288         -cookie => $cookie
289     );
290 }
291
292 =head2 getlanguagecookie
293
294     my $cookie = getlanguagecookie($query,$language);
295
296 Returns a cookie object containing the calculated language to be used.
297
298 =cut
299
300 sub getlanguagecookie {
301     my ( $query, $language ) = @_;
302     my $cookie = $query->cookie(
303         -name    => 'KohaOpacLanguage',
304         -value   => $language,
305         -HttpOnly => 1,
306         -expires => '+3y'
307     );
308
309     return $cookie;
310 }
311
312 =head2 GetColumnDefs
313
314     my $columns = GetColumnDefs( $cgi )
315
316 It is passed a CGI object and returns a hash of hashes containing
317 the column names and descriptions for each table defined in the
318 columns.def file corresponding to the CGI object.
319
320 =cut
321
322 sub GetColumnDefs {
323
324     my $query = shift;
325
326     my $columns = {};
327
328     my $htdocs = C4::Context->config('intrahtdocs');
329     my $columns_file = 'columns.def';
330
331     # Get theme and language to build the path to columns.def
332     my ($theme, $lang, $availablethemes) =
333         themelanguage($htdocs, 'about.tt', 'intranet', $query);
334     # Build columns.def path
335     my $path = "$htdocs/$theme/$lang/$columns_file";
336     my $fh;
337     if ( ! open ( $fh, q{<:encoding(utf-8)}, $path ) )  {
338         carp "Error opening $path. Check your templates.";
339         return;
340     }
341     # Loop through the columns.def file
342     while ( my $input = <$fh> ){
343         chomp $input;
344         if ( $input =~ m|<field name="(.*)">(.*)</field>| ) {
345             my ( $table, $column ) =  split( '\.', $1);
346             my $description        = $2;
347             # Initialize the table array if needed.
348             @{$columns->{ $table }} = () if ! defined $columns->{ $table };
349             # Push field and description
350             push @{$columns->{ $table }},
351                 { field => $column, description => $description };
352         }
353     }
354     close $fh;
355
356     return $columns;
357 }
358
359 1;