Bug 7359 - Begin migration to a new "Koha" namespace from the old "C4" namespace
[koha.git] / C4 / Templates.pm
1 package C4::Templates;
2
3 use strict;
4 use warnings;
5 use Carp;
6 use CGI;
7 use List::Util qw/first/;
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 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
57     my ($theme, $lang)= themelanguage( $htdocs, $tmplbase, $interface, $query);
58     my $template = Template->new(
59         {   EVAL_PERL    => 1,
60             ABSOLUTE     => 1,
61             PLUGIN_BASE => 'Koha::Template::Plugin',
62             INCLUDE_PATH => [
63                 "$htdocs/$theme/$lang/includes",
64                 "$htdocs/$theme/en/includes"
65             ],
66             FILTERS => {},
67         }
68     ) or die Template->error();
69     my $self = {
70         TEMPLATE => $template,
71         VARS     => {},
72     };
73     bless $self, $class;
74     $self->theme($theme);
75     $self->lang($lang);
76     $self->filename($filename);
77     $self->htdocs($htdocs);
78     $self->interface($interface);
79     $self->{VARS}->{"test"} = "value";
80     return $self;
81
82 }
83
84 sub output {
85     my $self = shift;
86     my $vars = shift;
87
88 #    my $file = $self->htdocs . '/' . $self->theme .'/'.$self->lang.'/'.$self->filename;
89     my $template = $self->{TEMPLATE};
90     if ( $self->interface eq 'intranet' ) {
91         $vars->{themelang} = '/intranet-tmpl';
92     }
93     else {
94         $vars->{themelang} = '/opac-tmpl';
95     }
96     $vars->{lang} = $self->lang;
97     $vars->{themelang} .= '/' . $self->theme . '/' . $self->lang;
98     $vars->{yuipath} =
99       ( C4::Context->preference("yuipath") eq "local"
100         ? $vars->{themelang} . "/lib/yui"
101         : C4::Context->preference("yuipath") );
102     $vars->{interface} =
103       ( $self->{interface} ne 'intranet' ? '/opac-tmpl' : '/intranet-tmpl' );
104     $vars->{theme} = $self->theme;
105     $vars->{opaccolorstylesheet} =
106       C4::Context->preference('opaccolorstylesheet');
107     $vars->{opacsmallimage} = C4::Context->preference('opacsmallimage');
108     $vars->{opacstylesheet} = C4::Context->preference('opacstylesheet');
109
110     # add variables set via param to $vars for processing
111     # and clean any utf8 mess
112     for my $k ( keys %{ $self->{VARS} } ) {
113         $vars->{$k} = $self->{VARS}->{$k};
114         if (ref($vars->{$k}) eq 'ARRAY'){
115             utf8_arrayref($vars->{$k});
116         }
117         elsif (ref($vars->{$k}) eq 'HASH'){
118             utf8_hashref($vars->{$k});
119         }
120         else {
121             utf8::encode($vars->{$k}) if utf8::is_utf8($vars->{$k});
122         }
123     }
124     my $data;
125 #    binmode( STDOUT, ":utf8" );
126     $template->process( $self->filename, $vars, \$data )
127       || die "Template process failed: ", $template->error();
128     return $data;
129 }
130
131 sub utf8_arrayref {
132     my $arrayref = shift;
133     foreach my $element (@$arrayref){
134         if (ref($element) eq 'ARRAY'){
135             utf8_arrayref($element);
136             next;
137         }
138         if (ref($element) eq 'HASH'){
139             utf8_hashref($element);
140             next;
141         }
142         utf8::encode($element) if utf8::is_utf8($element);
143     }        
144 }         
145
146 sub utf8_hashref {
147     my $hashref = shift;
148     for my $key (keys %{$hashref}){
149         if (ref($hashref->{$key}) eq 'ARRAY'){
150             utf8_arrayref($hashref->{$key});
151             next;
152         }
153         if (ref($hashref->{$key}) eq 'HASH'){
154             utf8_hashref($hashref->{$key});
155             next;
156         }
157         utf8::encode($hashref->{$key}) if utf8::is_utf8($hashref->{$key});
158     }
159 }
160         
161         
162 # FIXME - this is a horrible hack to cache
163 # the current known-good language, temporarily
164 # put in place to resolve bug 4403.  It is
165 # used only by C4::XSLT::XSLTParse4Display;
166 # the language is set via the usual call
167 # to themelanguage.
168 my $_current_language = 'en';
169
170 sub _current_language {
171     return $_current_language;
172 }
173
174
175 # wrapper method to allow easier transition from HTML template pro to Template Toolkit
176 sub param {
177     my $self = shift;
178     while (@_) {
179         my $key = shift;
180         my $val = shift;
181         if    ( ref($val) eq 'ARRAY' && !scalar @$val ) { $val = undef; }
182         elsif ( ref($val) eq 'HASH'  && !scalar %$val ) { $val = undef; }
183         if ( $key ) {
184             $self->{VARS}->{$key} = $val;
185         } else {
186             warn "Problem = a value of $val has been passed to param without key";
187         }
188     }
189 }
190
191
192 =head1 NAME
193
194 C4::Templates - Functions for managing templates
195
196 =head1 FUNCTIONS
197
198 =cut
199
200 # FIXME: this is a quick fix to stop rc1 installing broken
201 # Still trying to figure out the correct fix.
202 my $path = C4::Context->config('intrahtdocs') . "/prog/en/includes/";
203
204 #---------------------------------------------------------------------------------------------------------
205 # FIXME - POD
206
207 sub _get_template_file {
208     my ($tmplbase, $interface, $query) = @_;
209
210     my $is_intranet = $interface eq 'intranet';
211     my $htdocs = C4::Context->config($is_intranet ? 'intrahtdocs' : 'opachtdocs');
212     my ($theme, $lang) = themelanguage($htdocs, $tmplbase, $interface, $query);
213     my $opacstylesheet = C4::Context->preference('opacstylesheet');
214
215     # if the template doesn't exist, load the English one as a last resort
216     my $filename = "$htdocs/$theme/$lang/modules/$tmplbase";
217     unless (-f $filename) {
218         $lang = 'en';
219         $filename = "$htdocs/$theme/$lang/modules/$tmplbase";
220     }
221     return ($htdocs, $theme, $lang, $filename);
222 }
223
224
225 sub gettemplate {
226     my ( $tmplbase, $interface, $query ) = @_;
227     ($query) or warn "no query in gettemplate";
228     my $path = C4::Context->preference('intranet_includes') || 'includes';
229     my $opacstylesheet = C4::Context->preference('opacstylesheet');
230     $tmplbase =~ s/\.tmpl$/.tt/;
231     my ($htdocs, $theme, $lang, $filename)
232        =  _get_template_file($tmplbase, $interface, $query);
233     my $template = C4::Templates->new($interface, $filename, $tmplbase, $query);
234     my $is_intranet = $interface eq 'intranet';
235     my $themelang =
236         ($is_intranet ? '/intranet-tmpl' : '/opac-tmpl') .
237         "/$theme/$lang";
238     $template->param(
239         themelang => $themelang,
240         yuipath   => C4::Context->preference("yuipath") eq "local"
241                      ? "$themelang/lib/yui"
242                      : C4::Context->preference("yuipath"),
243         interface => $is_intranet ? '/intranet-tmpl' : '/opac-tmpl',
244         theme     => $theme,
245         lang      => $lang
246     );
247
248     # Bidirectionality
249     my $current_lang = regex_lang_subtags($lang);
250     my $bidi;
251     $bidi = get_bidi($current_lang->{script}) if $current_lang->{script};
252     # Languages
253     my $languages_loop = getTranslatedLanguages($interface,$theme,$lang);
254     my $num_languages_enabled = 0;
255     foreach my $lang (@$languages_loop) {
256         foreach my $sublang (@{ $lang->{'sublanguages_loop'} }) {
257             $num_languages_enabled++ if $sublang->{enabled};
258          }
259     }
260     $template->param(
261             languages_loop       => $languages_loop,
262             bidi                 => $bidi,
263             one_language_enabled => ($num_languages_enabled <= 1) ? 1 : 0, # deal with zero enabled langs as well
264     ) unless @$languages_loop<2;
265
266     return $template;
267 }
268
269
270 #---------------------------------------------------------------------------------------------------------
271 # FIXME - POD
272 sub themelanguage {
273     my ($htdocs, $tmpl, $interface, $query) = @_;
274     ($query) or warn "no query in themelanguage";
275
276     # Select a language based on cookie, syspref available languages & browser
277     my $lang = getlanguage($query, $interface);
278
279     # Select theme
280     my $is_intranet = $interface eq 'intranet';
281     my @themes = split(" ", C4::Context->preference(
282         $is_intranet ? "template" : "opacthemes" ));
283     push @themes, 'prog';
284
285     # Try to find first theme for the selected language
286     for my $theme (@themes) {
287         if ( -e "$htdocs/$theme/$lang/modules/$tmpl" ) {
288             $_current_language = $lang;
289             return ($theme, $lang)
290         }
291     }
292     # Otherwise, return prog theme in English 'en'
293     return ('prog', 'en');
294 }
295
296
297 sub setlanguagecookie {
298     my ( $query, $language, $uri ) = @_;
299     my $cookie = $query->cookie(
300         -name    => 'KohaOpacLanguage',
301         -value   => $language,
302         -expires => ''
303     );
304     print $query->redirect(
305         -uri    => $uri,
306         -cookie => $cookie
307     );
308 }
309
310
311 sub getlanguage {
312     my ($query, $interface) = @_;
313
314     # Select a language based on cookie, syspref available languages & browser
315     my $is_intranet = $interface eq 'intranet';
316     my @languages = split(",", C4::Context->preference(
317         $is_intranet ? 'language' : 'opaclanguages'));
318
319     my $lang;
320
321     # cookie
322     if ( $query->cookie('KohaOpacLanguage') ) {
323         $lang = $query->cookie('KohaOpacLanguage');
324         $lang =~ s/[^a-zA-Z_-]*//; # sanitize cookie
325     }
326
327     # HTTP_ACCEPT_LANGUAGE
328     unless ($lang) {
329         my $http_accept_language = $ENV{ HTTP_ACCEPT_LANGUAGE };
330         $lang = accept_language( $http_accept_language,
331             getTranslatedLanguages($interface,'prog') );
332     }
333
334     # Ignore a lang not selected in sysprefs
335     $lang = undef  unless first { $_ eq $lang } @languages;
336
337     # Fall back to English if necessary
338     $lang = 'en' unless $lang;
339
340     return $lang;
341 }
342
343 1;
344