Merge remote-tracking branch 'kc/new/bug_6755' into kcmaster
[koha.git] / C4 / Templates.pm
1 package C4::Templates;
2
3 use strict;
4 use warnings;
5 use Carp;
6 use CGI;
7
8 # Copyright 2009 Chris Cormack and The Koha Dev Team
9 #
10 # This file is part of Koha.
11 #
12 # Koha is free software; you can redistribute it and/or modify it under the
13 # terms of the GNU General Public License as published by the Free Software
14 # Foundation; either version 2 of the License, or (at your option) any later
15 # version.
16 #
17 # Koha is distributed in the hope that it will be useful, but WITHOUT ANY
18 # WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
19 # A PARTICULAR PURPOSE.  See the GNU General Public License for more details.
20 #
21 # You should have received a copy of the GNU General Public License along with
22 # Koha; if not, write to the Free Software Foundation, Inc., 59 Temple Place,
23 # Suite 330, Boston, MA  02111-1307 USA
24
25 =head1 NAME 
26
27     Koha::Templates - Object for manipulating templates for use with Koha
28
29 =cut
30
31 use base qw(Class::Accessor);
32 use Template;
33 use Template::Constants qw( :debug );
34 use C4::Languages qw(getTranslatedLanguages get_bidi regex_lang_subtags language_get_description accept_language );
35
36 use C4::Context;
37
38 __PACKAGE__->mk_accessors(qw( theme lang filename htdocs interface vars));
39
40
41
42 sub new {
43     my $class     = shift;
44     my $interface = shift;
45     my $filename  = shift;
46     my $tmplbase  = shift;
47     my $query     = @_? shift: undef;
48     my $htdocs;
49     if ( $interface ne "intranet" ) {
50         $htdocs = C4::Context->config('opachtdocs');
51     }
52     else {
53         $htdocs = C4::Context->config('intrahtdocs');
54     }
55
56     my ($theme, $lang)= themelanguage( $htdocs, $tmplbase, $interface, $query);
57     my $template = Template->new(
58         {   EVAL_PERL    => 1,
59             ABSOLUTE     => 1,
60             INCLUDE_PATH => [
61                 "$htdocs/$theme/$lang/includes",
62                 "$htdocs/$theme/en/includes"
63             ],
64             FILTERS => {},
65         }
66     ) or die Template->error();
67     my $self = {
68         TEMPLATE => $template,
69         VARS     => {},
70     };
71     bless $self, $class;
72     $self->theme($theme);
73     $self->lang($lang);
74     $self->filename($filename);
75     $self->htdocs($htdocs);
76     $self->interface($interface);
77     $self->{VARS}->{"test"} = "value";
78     return $self;
79
80 }
81
82 sub output {
83     my $self = shift;
84     my $vars = shift;
85
86 #    my $file = $self->htdocs . '/' . $self->theme .'/'.$self->lang.'/'.$self->filename;
87     my $template = $self->{TEMPLATE};
88     if ( $self->interface eq 'intranet' ) {
89         $vars->{themelang} = '/intranet-tmpl';
90     }
91     else {
92         $vars->{themelang} = '/opac-tmpl';
93     }
94     $vars->{lang} = $self->lang;
95     $vars->{themelang} .= '/' . $self->theme . '/' . $self->lang;
96     $vars->{yuipath} =
97       ( C4::Context->preference("yuipath") eq "local"
98         ? $vars->{themelang} . "/lib/yui"
99         : C4::Context->preference("yuipath") );
100     $vars->{interface} =
101       ( $self->{interface} ne 'intranet' ? '/opac-tmpl' : '/intranet-tmpl' );
102     $vars->{theme} = $self->theme;
103     $vars->{opaccolorstylesheet} =
104       C4::Context->preference('opaccolorstylesheet');
105     $vars->{opacsmallimage} = C4::Context->preference('opacsmallimage');
106     $vars->{opacstylesheet} = C4::Context->preference('opacstylesheet');
107
108     # add variables set via param to $vars for processing
109     # and clean any utf8 mess
110     for my $k ( keys %{ $self->{VARS} } ) {
111         $vars->{$k} = $self->{VARS}->{$k};
112         if (ref($vars->{$k}) eq 'ARRAY'){
113             utf8_arrayref($vars->{$k});
114         }
115         elsif (ref($vars->{$k}) eq 'HASH'){
116             utf8_hashref($vars->{$k});
117         }
118         else {
119             utf8::encode($vars->{$k}) if utf8::is_utf8($vars->{$k});
120         }
121     }
122     my $data;
123 #    binmode( STDOUT, ":utf8" );
124     $template->process( $self->filename, $vars, \$data )
125       || die "Template process failed: ", $template->error();
126     return $data;
127 }
128
129 sub utf8_arrayref {
130     my $arrayref = shift;
131     foreach my $element (@$arrayref){
132         if (ref($element) eq 'ARRAY'){
133             utf8_arrayref($element);
134             next;
135         }
136         if (ref($element) eq 'HASH'){
137             utf8_hashref($element);
138             next;
139         }
140         utf8::encode($element) if utf8::is_utf8($element);
141     }        
142 }         
143
144 sub utf8_hashref {
145     my $hashref = shift;
146     for my $key (keys %{$hashref}){
147         if (ref($hashref->{$key}) eq 'ARRAY'){
148             utf8_arrayref($hashref->{$key});
149             next;
150         }
151         if (ref($hashref->{$key}) eq 'HASH'){
152             utf8_hashref($hashref->{$key});
153             next;
154         }
155         utf8::encode($hashref->{$key}) if utf8::is_utf8($hashref->{$key});
156     }
157 }
158         
159         
160 # FIXME - this is a horrible hack to cache
161 # the current known-good language, temporarily
162 # put in place to resolve bug 4403.  It is
163 # used only by C4::XSLT::XSLTParse4Display;
164 # the language is set via the usual call
165 # to themelanguage.
166 my $_current_language = 'en';
167
168 sub _current_language {
169     return $_current_language;
170 }
171
172 sub themelanguage_lite {
173     my ( $htdocs, $tmpl, $interface ) = @_;
174     my $query = new CGI;
175
176     # Set some defaults for language and theme
177     # First, check the user's preferences
178     my $lang;
179
180     # But, if there's a cookie set, obey it
181     $lang = $query->cookie('KohaOpacLanguage')
182       if ( defined $query and $query->cookie('KohaOpacLanguage') );
183
184     # Fall back to English
185     my @languages;
186     if ( $interface eq 'intranet' ) {
187         @languages = split ",", C4::Context->preference("language");
188     }
189     else {
190         @languages = split ",", C4::Context->preference("opaclanguages");
191     }
192     if ($lang) {
193         @languages = ( $lang, @languages );
194     }
195     else {
196         $lang = $languages[0] || 'en';
197     }
198     my $theme = 'prog'; # in the event of theme failure default to 'prog' -fbcit
199     my @themes;
200     if ( $interface eq "intranet" ) {
201         @themes = split " ", C4::Context->preference("template");
202     }
203     else {
204         @themes = split " ", C4::Context->preference("opacthemes");
205     }
206
207  # searches through the themes and languages. First template it find it returns.
208  # Priority is for getting the theme right.
209   THEME:
210     foreach my $th (@themes) {
211         foreach my $la (@languages) {
212             if ( -e "$htdocs/$th/$la/modules/$tmpl" ) {
213                 $theme = $th;
214                 $lang  = $la;
215                 last THEME;
216             }
217             last unless $la =~ /[-_]/;
218         }
219     }
220     $_current_language = $lang;  # FIXME part of bad hack to paper over bug 4403
221     return ( $theme, $lang );
222 }
223
224 # wrapper method to allow easier transition from HTML template pro to Template Toolkit
225 sub param {
226     my $self = shift;
227     while (@_) {
228         my $key = shift;
229         my $val = shift;
230         if    ( ref($val) eq 'ARRAY' && !scalar @$val ) { $val = undef; }
231         elsif ( ref($val) eq 'HASH'  && !scalar %$val ) { $val = undef; }
232         $self->{VARS}->{$key} = $val;
233     }
234 }
235
236
237 =head1 NAME
238
239 C4::Templates - Functions for managing templates
240
241 =head1 FUNCTIONS
242
243 =cut
244
245 # FIXME: this is a quick fix to stop rc1 installing broken
246 # Still trying to figure out the correct fix.
247 my $path = C4::Context->config('intrahtdocs') . "/prog/en/includes/";
248
249 #---------------------------------------------------------------------------------------------------------
250 # FIXME - POD
251
252 sub _get_template_file {
253     my ( $tmplbase, $interface, $query ) = @_;
254     my $htdocs = C4::Context->config( $interface ne 'intranet' ? 'opachtdocs' : 'intrahtdocs' );
255     my ( $theme, $lang ) = themelanguage( $htdocs, $tmplbase, $interface, $query );
256     my $opacstylesheet = C4::Context->preference('opacstylesheet');
257
258     # if the template doesn't exist, load the English one as a last resort
259     my $filename = "$htdocs/$theme/$lang/modules/$tmplbase";
260     unless (-f $filename) {
261         $lang = 'en';
262         $filename = "$htdocs/$theme/$lang/modules/$tmplbase";
263     }
264
265     return ( $htdocs, $theme, $lang, $filename );
266 }
267
268 sub gettemplate {
269     my ( $tmplbase, $interface, $query ) = @_;
270     ($query) or warn "no query in gettemplate";
271     my $path = C4::Context->preference('intranet_includes') || 'includes';
272     my $opacstylesheet = C4::Context->preference('opacstylesheet');
273     $tmplbase =~ s/\.tmpl$/.tt/;
274     my ( $htdocs, $theme, $lang, $filename ) = _get_template_file( $tmplbase, $interface, $query );
275     my $template = C4::Templates->new($interface, $filename, $tmplbase, $query);
276     my $themelang=( $interface ne 'intranet' ? '/opac-tmpl' : '/intranet-tmpl' )
277           . "/$theme/$lang";
278     $template->param(
279         themelang => $themelang,
280         yuipath   => (C4::Context->preference("yuipath") eq "local"?"$themelang/lib/yui":C4::Context->preference("yuipath")),
281         interface => ( $interface ne 'intranet' ? '/opac-tmpl' : '/intranet-tmpl' ),
282         theme     => $theme,
283         lang      => $lang
284     );
285
286     # Bidirectionality
287     my $current_lang = regex_lang_subtags($lang);
288     my $bidi;
289     $bidi = get_bidi($current_lang->{script}) if $current_lang->{script};
290     # Languages
291     my $languages_loop = getTranslatedLanguages($interface,$theme,$lang);
292     my $num_languages_enabled = 0;
293     foreach my $lang (@$languages_loop) {
294         foreach my $sublang (@{ $lang->{'sublanguages_loop'} }) {
295             $num_languages_enabled++ if $sublang->{enabled};
296          }
297     }
298     $template->param(
299             languages_loop       => $languages_loop,
300             bidi                 => $bidi,
301             one_language_enabled => ($num_languages_enabled <= 1) ? 1 : 0, # deal with zero enabled langs as well
302     ) unless @$languages_loop<2;
303
304     return $template;
305 }
306
307
308 #---------------------------------------------------------------------------------------------------------
309 # FIXME - POD
310 sub themelanguage {
311     my ( $htdocs, $tmpl, $interface, $query ) = @_;
312     ($query) or warn "no query in themelanguage";
313
314     # Set some defaults for language and theme
315     # First, check the user's preferences
316     my $lang;
317     my $http_accept_language = $ENV{ HTTP_ACCEPT_LANGUAGE };
318     $lang = accept_language( $http_accept_language, 
319               getTranslatedLanguages($interface,'prog') )
320       if $http_accept_language;
321     # But, if there's a cookie set, obey it
322     $lang = $query->cookie('KohaOpacLanguage') if (defined $query and $query->cookie('KohaOpacLanguage'));
323     # Fall back to English
324     my @languages;
325     if ($interface eq 'intranet') {
326         @languages = split ",", C4::Context->preference("language");
327     } else {
328         @languages = split ",", C4::Context->preference("opaclanguages");
329     }
330     if ($lang){  
331         @languages=($lang,@languages);
332     } else {
333         $lang = $languages[0];
334     }      
335     my $theme = 'prog'; # in the event of theme failure default to 'prog' -fbcit
336     my $dbh = C4::Context->dbh;
337     my @themes;
338     if ( $interface eq "intranet" ) {
339         @themes    = split " ", C4::Context->preference("template");
340     }
341     else {
342       # we are in the opac here, what im trying to do is let the individual user
343       # set the theme they want to use.
344       # and perhaps the them as well.
345         #my $lang = $query->cookie('KohaOpacLanguage');
346         @themes = split " ", C4::Context->preference("opacthemes");
347     }
348
349  # searches through the themes and languages. First template it find it returns.
350  # Priority is for getting the theme right.
351     THEME:
352     foreach my $th (@themes) {
353         foreach my $la (@languages) {
354             #for ( my $pass = 1 ; $pass <= 2 ; $pass += 1 ) {
355                 # warn "$htdocs/$th/$la/modules/$interface-"."tmpl";
356                 #$la =~ s/([-_])/ $1 eq '-'? '_': '-' /eg if $pass == 2;
357                                 if ( -e "$htdocs/$th/$la/modules/$tmpl") {
358                 #".($interface eq 'intranet'?"modules":"")."/$tmpl" ) {
359                     $theme = $th;
360                     $lang  = $la;
361                     last THEME;
362                 }
363                 last unless $la =~ /[-_]/;
364             #}
365         }
366     }
367
368     $_current_language = $lang; # FIXME part of bad hack to paper over bug 4403
369     return ( $theme, $lang );
370 }
371
372 sub setlanguagecookie {
373     my ( $query, $language, $uri ) = @_;
374     my $cookie = $query->cookie(
375         -name    => 'KohaOpacLanguage',
376         -value   => $language,
377         -expires => ''
378     );
379     print $query->redirect(
380         -uri    => $uri,
381         -cookie => $cookie
382     );
383 }
384
385 sub getlanguagecookie {
386     my ($query) = @_;
387     my $lang;
388     if ($query->cookie('KohaOpacLanguage')){
389         $lang = $query->cookie('KohaOpacLanguage') ;
390     }else{
391         $lang = $ENV{HTTP_ACCEPT_LANGUAGE};
392         
393     }
394     $lang = substr($lang, 0, 2);
395
396     return $lang;
397 }
398
399 1;
400