Bug 28782: (follow-up) Pass real array to query_form()
[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     # add variables set via param to $vars for processing
117     $vars = { %$vars, %{ $self->{VARS} } };
118
119     my $data;
120     binmode( STDOUT, ":encoding(UTF-8)" );
121     $template->process( $self->filename, $vars, \$data )
122       || die "Template process failed: ", $template->error();
123     return $data;
124 }
125
126 # wrapper method to allow easier transition from HTML template pro to Template Toolkit
127 sub param {
128     my $self = shift;
129     while (@_) {
130         my $key = shift;
131         my $val = shift;
132         if    ( ref($val) eq 'ARRAY' && !scalar @$val ) { $val = undef; }
133         elsif ( ref($val) eq 'HASH'  && !scalar %$val ) { $val = undef; }
134         if ( $key ) {
135             $self->{VARS}->{$key} = $val;
136         } else {
137             warn "Problem = a value of $val has been passed to param without key";
138         }
139     }
140 }
141
142
143 =head1 NAME
144
145 C4::Templates - Functions for managing templates
146
147 =head1 FUNCTIONS
148
149 =cut
150
151 # FIXME: this is a quick fix to stop rc1 installing broken
152 # Still trying to figure out the correct fix.
153 my $path = C4::Context->config('intrahtdocs') . "/prog/en/includes/";
154
155 #---------------------------------------------------------------------------------------------------------
156 # FIXME - POD
157
158 sub _get_template_file {
159     my ($tmplbase, $interface, $query) = @_;
160
161     my $is_intranet = $interface eq 'intranet';
162     my $htdocs = C4::Context->config($is_intranet ? 'intrahtdocs' : 'opachtdocs');
163     my ($theme, $lang, $availablethemes) = themelanguage($htdocs, $tmplbase, $interface, $query);
164     $lang //= 'en';
165     $theme //= '';
166     $tmplbase = "$htdocs/$theme/$lang/modules/$tmplbase" if $tmplbase !~ /^\//;
167         # do not prefix an absolute path
168
169     return ( $htdocs, $theme, $lang, $tmplbase );
170 }
171
172 =head2 badtemplatecheck
173
174     badtemplatecheck( $template_path );
175
176     The sub will throw an exception if the template path is not allowed.
177
178     Note: At this moment the sub is actually a helper routine for
179     sub gettemplate.
180
181 =cut
182
183 sub badtemplatecheck {
184     my ( $template ) = @_;
185     if( !$template || $template !~ m/^[a-zA-Z0-9_\-\/]+\.(tt|pref)$/ ) {
186         # This also includes two dots
187         Koha::Exceptions::NoPermission->throw( 'bad template path' );
188     } else {
189         # Check allowed dirs - make sure we operate on a copy of the config
190         my $dirs = C4::Context->config("pluginsdir");
191         if ( !ref($dirs) ) {
192             $dirs = [ $dirs ];
193         }
194         else {
195             $dirs = [ @$dirs ];
196         }
197         unshift @$dirs, C4::Context->config('opachtdocs'), C4::Context->config('intrahtdocs');
198         my $found = 0;
199         foreach my $dir ( @$dirs ) {
200             $dir .= '/' if $dir !~ m/\/$/;
201             $found++ if $template =~ m/^$dir/;
202             last if $found;
203         }
204         Koha::Exceptions::NoPermission->throw( 'bad template path' ) if !$found;
205     }
206 }
207
208 sub gettemplate {
209     my ( $tmplbase, $interface, $query ) = @_;
210     ($query) or warn "no query in gettemplate";
211     my ($htdocs, $theme, $lang, $filename)
212        =  _get_template_file($tmplbase, $interface, $query);
213     badtemplatecheck( $filename ); # single trip for bad templates
214     my $template = C4::Templates->new($interface, $filename, $tmplbase, $query);
215
216 # NOTE: Commenting these out rather than deleting them so that those who need
217 # to know how we previously shimmed these directories will be able to understand.
218 #    my $is_intranet = $interface eq 'intranet';
219 #    my $themelang =
220 #        ($is_intranet ? '/intranet-tmpl' : '/opac-tmpl') .
221 #        "/$theme/$lang";
222 #    $template->param(
223 #        themelang => $themelang,
224 #        interface => $is_intranet ? '/intranet-tmpl' : '/opac-tmpl',
225 #        theme     => $theme,
226 #        lang      => $lang
227 #    );
228
229     # Bidirectionality, must be sent even if is the only language
230     my $current_lang = regex_lang_subtags($lang);
231     my $bidi;
232     $bidi = get_bidi($current_lang->{script}) if $current_lang->{script};
233     $template->param(
234             bidi                 => $bidi,
235     );
236     # Languages
237     my $languages_loop = getTranslatedLanguages($interface,$theme,$lang);
238     my $num_languages_enabled = 0;
239     foreach my $lang (@$languages_loop) {
240         foreach my $sublang (@{ $lang->{'sublanguages_loop'} }) {
241             $num_languages_enabled++ if $sublang->{enabled};
242          }
243     }
244     my $one_language_enabled = ($num_languages_enabled <= 1) ? 1 : 0; # deal with zero enabled langs as well
245     $template->param(
246             languages_loop       => $languages_loop,
247             one_language_enabled => $one_language_enabled,
248     ) unless $one_language_enabled;
249
250     return $template;
251 }
252
253
254 =head2 themelanguage
255
256     my ($theme,$lang,\@themes) = themelanguage($htdocs,$tmpl,$interface,query);
257
258 This function returns the theme and language to be used for rendering the UI.
259 It also returns the list of themes that should be applied as a fallback. This is
260 used for the theme overlay feature (i.e. if a file doesn't exist on the requested
261 theme, fallback to the configured fallback).
262
263 Important: this function is used on the webinstaller too, so always consider
264 the use case where the DB is not populated already when rewriting/fixing.
265
266 =cut
267
268 sub themelanguage {
269     my ($htdocs, $tmpl, $interface, $query) = @_;
270     ($query) or warn "no query in themelanguage";
271
272     # Select a language based on cookie, syspref available languages & browser
273     my $lang = C4::Languages::getlanguage($query);
274
275     return availablethemes($htdocs, $tmpl, $interface, $lang);
276 }
277
278 sub availablethemes {
279     my ($htdocs, $tmpl, $interface, $lang) = @_;
280
281     # Get theme
282     my @themes;
283     my $theme_syspref    = ($interface eq 'intranet') ? 'template' : 'opacthemes';
284     my $fallback_syspref = ($interface eq 'intranet') ? 'template' : 'OPACFallback';
285     # Yeah, hardcoded, last resort if the DB is not populated
286     my $hardcoded_theme = ($interface eq 'intranet') ? 'prog' : 'bootstrap';
287
288     # Configured theme is the first one
289     push @themes, C4::Context->preference( $theme_syspref )
290         if C4::Context->preference( $theme_syspref );
291     # Configured fallback next
292     push @themes, C4::Context->preference( $fallback_syspref )
293         if C4::Context->preference( $fallback_syspref );
294     # The hardcoded fallback theme is the last one
295     push @themes, $hardcoded_theme;
296
297     # Try to find first theme for the selected theme/lang, then for fallback/lang
298     my $where = $tmpl =~ /xsl$/ ? 'xslt' : 'modules';
299     for my $theme (@themes) {
300         if ( -e "$htdocs/$theme/$lang/$where/$tmpl" ) {
301             return ( $theme, $lang, [ uniq(@themes) ] );
302         }
303     }
304     # Otherwise return theme/'en', last resort fallback/'en'
305     for my $theme (@themes) {
306         if ( -e "$htdocs/$theme/en/$where/$tmpl" ) {
307             return ( $theme, 'en', [ uniq(@themes) ] );
308         }
309     }
310     # tmpl is a full path, so this is a template for a plugin
311     if ( $tmpl =~ /^\// && -e $tmpl ) {
312         return ( $themes[0], $lang, [ uniq(@themes) ] );
313     }
314 }
315
316 sub setlanguagecookie {
317     my ( $query, $language, $uri ) = @_;
318
319     my $cookie = getlanguagecookie( $query, $language );
320
321     # We do not want to set getlanguage in cache, some additional checks are
322     # done in C4::Languages::getlanguage
323     Koha::Cache::Memory::Lite->get_instance()->clear_from_cache( 'getlanguage' );
324
325     print $query->redirect(
326         -uri    => $uri,
327         -cookie => $cookie
328     );
329 }
330
331 =head2 getlanguagecookie
332
333     my $cookie = getlanguagecookie($query,$language);
334
335 Returns a cookie object containing the calculated language to be used.
336
337 =cut
338
339 sub getlanguagecookie {
340     my ( $query, $language ) = @_;
341     my $cookie = $query->cookie(
342         -name    => 'KohaOpacLanguage',
343         -value   => $language,
344         -HttpOnly => 1,
345         -expires => '+3y'
346     );
347
348     return $cookie;
349 }
350
351 =head2 GetColumnDefs
352
353     my $columns = GetColumnDefs( $cgi )
354
355 It is passed a CGI object and returns a hash of hashes containing
356 the column names and descriptions for each table defined in the
357 columns.def file corresponding to the CGI object.
358
359 =cut
360
361 sub GetColumnDefs {
362
363     my $query = shift;
364
365     my $columns = {};
366
367     my $htdocs = C4::Context->config('intrahtdocs');
368     my $columns_file = 'columns.def';
369
370     # Get theme and language to build the path to columns.def
371     my ($theme, $lang, $availablethemes) =
372         themelanguage($htdocs, 'about.tt', 'intranet', $query);
373     # Build columns.def path
374     my $path = "$htdocs/$theme/$lang/$columns_file";
375     my $fh;
376     if ( ! open ( $fh, q{<:encoding(utf-8)}, $path ) )  {
377         carp "Error opening $path. Check your templates.";
378         return;
379     }
380     # Loop through the columns.def file
381     while ( my $input = <$fh> ){
382         chomp $input;
383         if ( $input =~ m|<field name="(.*)">(.*)</field>| ) {
384             my ( $table, $column ) =  split( '\.', $1);
385             my $description        = $2;
386             # Initialize the table array if needed.
387             @{$columns->{ $table }} = () if ! defined $columns->{ $table };
388             # Push field and description
389             push @{$columns->{ $table }},
390                 { field => $column, description => $description };
391         }
392     }
393     close $fh;
394
395     return $columns;
396 }
397
398 1;