Bug 10328 - Rename opaccolorstylesheet to OpacAdditionalStylesheet
[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 under the
14 # terms of the GNU General Public License as published by the Free Software
15 # Foundation; either version 2 of the License, or (at your option) any later
16 # version.
17 #
18 # Koha is distributed in the hope that it will be useful, but WITHOUT ANY
19 # WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
20 # A PARTICULAR PURPOSE.  See the GNU General Public License for more details.
21 #
22 # You should have received a copy of the GNU General Public License along with
23 # Koha; if not, write to the Free Software Foundation, Inc., 59 Temple Place,
24 # Suite 330, Boston, MA  02111-1307 USA
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     for my $k ( keys %{ $self->{VARS} } ) {
116         $vars->{$k} = $self->{VARS}->{$k};
117     }
118
119     my $data;
120     binmode( STDOUT, ":utf8" );
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     my $filename = "$htdocs/$theme/$lang/modules/$tmplbase";
165
166     return ($htdocs, $theme, $lang, $filename);
167 }
168
169
170 sub gettemplate {
171     my ( $tmplbase, $interface, $query, $is_plugin ) = @_;
172     ($query) or warn "no query in gettemplate";
173     my $path = C4::Context->preference('intranet_includes') || 'includes';
174     my ($htdocs, $theme, $lang, $filename)
175        =  _get_template_file($tmplbase, $interface, $query);
176     $filename = $tmplbase if ( $is_plugin );
177     my $template = C4::Templates->new($interface, $filename, $tmplbase, $query);
178
179 # NOTE: Commenting these out rather than deleting them so that those who need
180 # to know how we previously shimmed these directories will be able to understand.
181 #    my $is_intranet = $interface eq 'intranet';
182 #    my $themelang =
183 #        ($is_intranet ? '/intranet-tmpl' : '/opac-tmpl') .
184 #        "/$theme/$lang";
185 #    $template->param(
186 #        themelang => $themelang,
187 #        interface => $is_intranet ? '/intranet-tmpl' : '/opac-tmpl',
188 #        theme     => $theme,
189 #        lang      => $lang
190 #    );
191
192     # Bidirectionality, must be sent even if is the only language
193     my $current_lang = regex_lang_subtags($lang);
194     my $bidi;
195     $bidi = get_bidi($current_lang->{script}) if $current_lang->{script};
196     $template->param(
197             bidi                 => $bidi,
198     );
199     # Languages
200     my $languages_loop = getTranslatedLanguages($interface,$theme,$lang);
201     my $num_languages_enabled = 0;
202     foreach my $lang (@$languages_loop) {
203         foreach my $sublang (@{ $lang->{'sublanguages_loop'} }) {
204             $num_languages_enabled++ if $sublang->{enabled};
205          }
206     }
207     my $one_language_enabled = ($num_languages_enabled <= 1) ? 1 : 0; # deal with zero enabled langs as well
208     $template->param(
209             languages_loop       => $languages_loop,
210             one_language_enabled => $one_language_enabled,
211     ) unless $one_language_enabled;
212
213     return $template;
214 }
215
216
217 =head2 themelanguage
218
219     my ($theme,$lang,\@themes) = themelanguage($htdocs,$tmpl,$interface,query);
220
221 This function returns the theme and language to be used for rendering the UI.
222 It also returns the list of themes that should be applied as a fallback. This is
223 used for the theme overlay feature (i.e. if a file doesn't exist on the requested
224 theme, fallback to the configured fallback).
225
226 Important: this function is used on the webinstaller too, so always consider
227 the use case where the DB is not populated already when rewriting/fixing.
228
229 =cut
230
231 sub themelanguage {
232     my ($htdocs, $tmpl, $interface, $query) = @_;
233     ($query) or warn "no query in themelanguage";
234
235     # Select a language based on cookie, syspref available languages & browser
236     my $lang = C4::Languages::getlanguage($query);
237
238     # Get theme
239     my @themes;
240     my $theme_syspref    = ($interface eq 'intranet') ? 'template' : 'opacthemes';
241     my $fallback_syspref = ($interface eq 'intranet') ? 'template' : 'OPACFallback';
242     # Yeah, hardcoded, last resort if the DB is not populated
243     my $hardcoded_theme = ($interface eq 'intranet') ? 'prog' : 'bootstrap';
244
245     # Configured theme is the first one
246     push @themes, C4::Context->preference( $theme_syspref )
247         if C4::Context->preference( $theme_syspref );
248     # Configured fallback next
249     push @themes, C4::Context->preference( $fallback_syspref )
250         if C4::Context->preference( $fallback_syspref );
251     # The hardcoded fallback theme is the last one
252     push @themes, $hardcoded_theme;
253
254     # Try to find first theme for the selected theme/lang, then for fallback/lang
255     my $where = $tmpl =~ /xsl$/ ? 'xslt' : 'modules';
256     for my $theme (@themes) {
257         if ( -e "$htdocs/$theme/$lang/$where/$tmpl" ) {
258             return ( $theme, $lang, uniq( \@themes ) );
259         }
260     }
261     # Otherwise return theme/'en', last resort fallback/'en'
262     for my $theme (@themes) {
263         if ( -e "$htdocs/$theme/en/$where/$tmpl" ) {
264             return ( $theme, 'en', uniq( \@themes ) );
265         }
266     }
267     # tmpl is a full path, so this is a template for a plugin
268     if ( $tmpl =~ /^\// && -e $tmpl ) {
269         return ( $themes[0], $lang, uniq( \@themes ) );
270     }
271 }
272
273
274 sub setlanguagecookie {
275     my ( $query, $language, $uri ) = @_;
276
277     my $cookie = $query->cookie(
278         -name    => 'KohaOpacLanguage',
279         -value   => $language,
280         -HttpOnly => 1,
281         -expires => '+3y'
282     );
283     print $query->redirect(
284         -uri    => $uri,
285         -cookie => $cookie
286     );
287 }
288
289 =head2 getlanguagecookie
290
291     my $cookie = getlanguagecookie($query,$language);
292
293 Returns a cookie object containing the calculated language to be used.
294
295 =cut
296
297 sub getlanguagecookie {
298     my ( $query, $language ) = @_;
299     my $cookie = $query->cookie(
300         -name    => 'KohaOpacLanguage',
301         -value   => $language,
302         -HttpOnly => 1,
303         -expires => '+3y'
304     );
305
306     return $cookie;
307 }
308
309 =head2 GetColumnDefs
310
311     my $columns = GetColumnDefs( $cgi )
312
313 It is passed a CGI object and returns a hash of hashes containing
314 the column names and descriptions for each table defined in the
315 columns.def file corresponding to the CGI object.
316
317 =cut
318
319 sub GetColumnDefs {
320
321     my $query = shift;
322
323     my $columns = {};
324
325     my $htdocs = C4::Context->config('intrahtdocs');
326     my $columns_file = 'columns.def';
327
328     # Get theme and language to build the path to columns.def
329     my ($theme, $lang, $availablethemes) =
330         themelanguage($htdocs, 'about.tt', 'intranet', $query);
331     # Build columns.def path
332     my $path = "$htdocs/$theme/$lang/$columns_file";
333     my $fh;
334     if ( ! open ( $fh, q{<}, $path ) )  {
335         carp "Error opening $path. Check your templates.";
336         return;
337     }
338     # Loop through the columns.def file
339     while ( my $input = <$fh> ){
340         chomp $input;
341         if ( $input =~ m|<field name="(.*)">(.*)</field>| ) {
342             my ( $table, $column ) =  split( '\.', $1);
343             my $description        = $2;
344             # Initialize the table array if needed.
345             @{$columns->{ $table }} = () if ! defined $columns->{ $table };
346             # Push field and description
347             push @{$columns->{ $table }},
348                 { field => $column, description => $description };
349         }
350     }
351     close $fh;
352
353     return $columns;
354 }
355
356 1;