Bug 28870: Remove traces of Email::Valid
[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
190         my $dirs = C4::Context->config("pluginsdir");
191         $dirs = [ $dirs ] if !ref($dirs);
192         unshift @$dirs, C4::Context->config('opachtdocs'), C4::Context->config('intrahtdocs');
193         my $found = 0;
194         foreach my $dir ( @$dirs ) {
195             $dir .= '/' if $dir !~ m/\/$/;
196             $found++ if $template =~ m/^$dir/;
197             last if $found;
198         }
199         Koha::Exceptions::NoPermission->throw( 'bad template path' ) if !$found;
200     }
201 }
202
203 sub gettemplate {
204     my ( $tmplbase, $interface, $query ) = @_;
205     ($query) or warn "no query in gettemplate";
206     my ($htdocs, $theme, $lang, $filename)
207        =  _get_template_file($tmplbase, $interface, $query);
208     badtemplatecheck( $filename ); # single trip for bad templates
209     my $template = C4::Templates->new($interface, $filename, $tmplbase, $query);
210
211 # NOTE: Commenting these out rather than deleting them so that those who need
212 # to know how we previously shimmed these directories will be able to understand.
213 #    my $is_intranet = $interface eq 'intranet';
214 #    my $themelang =
215 #        ($is_intranet ? '/intranet-tmpl' : '/opac-tmpl') .
216 #        "/$theme/$lang";
217 #    $template->param(
218 #        themelang => $themelang,
219 #        interface => $is_intranet ? '/intranet-tmpl' : '/opac-tmpl',
220 #        theme     => $theme,
221 #        lang      => $lang
222 #    );
223
224     # Bidirectionality, must be sent even if is the only language
225     my $current_lang = regex_lang_subtags($lang);
226     my $bidi;
227     $bidi = get_bidi($current_lang->{script}) if $current_lang->{script};
228     $template->param(
229             bidi                 => $bidi,
230     );
231     # Languages
232     my $languages_loop = getTranslatedLanguages($interface,$theme,$lang);
233     my $num_languages_enabled = 0;
234     foreach my $lang (@$languages_loop) {
235         foreach my $sublang (@{ $lang->{'sublanguages_loop'} }) {
236             $num_languages_enabled++ if $sublang->{enabled};
237          }
238     }
239     my $one_language_enabled = ($num_languages_enabled <= 1) ? 1 : 0; # deal with zero enabled langs as well
240     $template->param(
241             languages_loop       => $languages_loop,
242             one_language_enabled => $one_language_enabled,
243     ) unless $one_language_enabled;
244
245     return $template;
246 }
247
248
249 =head2 themelanguage
250
251     my ($theme,$lang,\@themes) = themelanguage($htdocs,$tmpl,$interface,query);
252
253 This function returns the theme and language to be used for rendering the UI.
254 It also returns the list of themes that should be applied as a fallback. This is
255 used for the theme overlay feature (i.e. if a file doesn't exist on the requested
256 theme, fallback to the configured fallback).
257
258 Important: this function is used on the webinstaller too, so always consider
259 the use case where the DB is not populated already when rewriting/fixing.
260
261 =cut
262
263 sub themelanguage {
264     my ($htdocs, $tmpl, $interface, $query) = @_;
265     ($query) or warn "no query in themelanguage";
266
267     # Select a language based on cookie, syspref available languages & browser
268     my $lang = C4::Languages::getlanguage($query);
269
270     return availablethemes($htdocs, $tmpl, $interface, $lang);
271 }
272
273 sub availablethemes {
274     my ($htdocs, $tmpl, $interface, $lang) = @_;
275
276     # Get theme
277     my @themes;
278     my $theme_syspref    = ($interface eq 'intranet') ? 'template' : 'opacthemes';
279     my $fallback_syspref = ($interface eq 'intranet') ? 'template' : 'OPACFallback';
280     # Yeah, hardcoded, last resort if the DB is not populated
281     my $hardcoded_theme = ($interface eq 'intranet') ? 'prog' : 'bootstrap';
282
283     # Configured theme is the first one
284     push @themes, C4::Context->preference( $theme_syspref )
285         if C4::Context->preference( $theme_syspref );
286     # Configured fallback next
287     push @themes, C4::Context->preference( $fallback_syspref )
288         if C4::Context->preference( $fallback_syspref );
289     # The hardcoded fallback theme is the last one
290     push @themes, $hardcoded_theme;
291
292     # Try to find first theme for the selected theme/lang, then for fallback/lang
293     my $where = $tmpl =~ /xsl$/ ? 'xslt' : 'modules';
294     for my $theme (@themes) {
295         if ( -e "$htdocs/$theme/$lang/$where/$tmpl" ) {
296             return ( $theme, $lang, [ uniq(@themes) ] );
297         }
298     }
299     # Otherwise return theme/'en', last resort fallback/'en'
300     for my $theme (@themes) {
301         if ( -e "$htdocs/$theme/en/$where/$tmpl" ) {
302             return ( $theme, 'en', [ uniq(@themes) ] );
303         }
304     }
305     # tmpl is a full path, so this is a template for a plugin
306     if ( $tmpl =~ /^\// && -e $tmpl ) {
307         return ( $themes[0], $lang, [ uniq(@themes) ] );
308     }
309 }
310
311 sub setlanguagecookie {
312     my ( $query, $language, $uri ) = @_;
313
314     my $cookie = getlanguagecookie( $query, $language );
315
316     # We do not want to set getlanguage in cache, some additional checks are
317     # done in C4::Languages::getlanguage
318     Koha::Cache::Memory::Lite->get_instance()->clear_from_cache( 'getlanguage' );
319
320     print $query->redirect(
321         -uri    => $uri,
322         -cookie => $cookie
323     );
324 }
325
326 =head2 getlanguagecookie
327
328     my $cookie = getlanguagecookie($query,$language);
329
330 Returns a cookie object containing the calculated language to be used.
331
332 =cut
333
334 sub getlanguagecookie {
335     my ( $query, $language ) = @_;
336     my $cookie = $query->cookie(
337         -name    => 'KohaOpacLanguage',
338         -value   => $language,
339         -HttpOnly => 1,
340         -expires => '+3y'
341     );
342
343     return $cookie;
344 }
345
346 =head2 GetColumnDefs
347
348     my $columns = GetColumnDefs( $cgi )
349
350 It is passed a CGI object and returns a hash of hashes containing
351 the column names and descriptions for each table defined in the
352 columns.def file corresponding to the CGI object.
353
354 =cut
355
356 sub GetColumnDefs {
357
358     my $query = shift;
359
360     my $columns = {};
361
362     my $htdocs = C4::Context->config('intrahtdocs');
363     my $columns_file = 'columns.def';
364
365     # Get theme and language to build the path to columns.def
366     my ($theme, $lang, $availablethemes) =
367         themelanguage($htdocs, 'about.tt', 'intranet', $query);
368     # Build columns.def path
369     my $path = "$htdocs/$theme/$lang/$columns_file";
370     my $fh;
371     if ( ! open ( $fh, q{<:encoding(utf-8)}, $path ) )  {
372         carp "Error opening $path. Check your templates.";
373         return;
374     }
375     # Loop through the columns.def file
376     while ( my $input = <$fh> ){
377         chomp $input;
378         if ( $input =~ m|<field name="(.*)">(.*)</field>| ) {
379             my ( $table, $column ) =  split( '\.', $1);
380             my $description        = $2;
381             # Initialize the table array if needed.
382             @{$columns->{ $table }} = () if ! defined $columns->{ $table };
383             # Push field and description
384             push @{$columns->{ $table }},
385                 { field => $column, description => $description };
386         }
387     }
388     close $fh;
389
390     return $columns;
391 }
392
393 1;