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