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