4f2c485b5078bc959ff61be98476bd82830db052
[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 =over 2
243
244 =cut
245
246 #FIXME: this is a quick fix to stop rc1 installing broken
247 #Still trying to figure out the correct fix.
248 my $path = C4::Context->config('intrahtdocs') . "/prog/en/includes/";
249
250 #---------------------------------------------------------------------------------------------------------
251 # FIXME - POD
252
253 sub _get_template_file {
254     my ( $tmplbase, $interface, $query ) = @_;
255     my $htdocs = C4::Context->config( $interface ne 'intranet' ? 'opachtdocs' : 'intrahtdocs' );
256     my ( $theme, $lang ) = themelanguage( $htdocs, $tmplbase, $interface, $query );
257     my $opacstylesheet = C4::Context->preference('opacstylesheet');
258
259     # if the template doesn't exist, load the English one as a last resort
260     my $filename = "$htdocs/$theme/$lang/modules/$tmplbase";
261     unless (-f $filename) {
262         $lang = 'en';
263         $filename = "$htdocs/$theme/$lang/modules/$tmplbase";
264     }
265
266     return ( $htdocs, $theme, $lang, $filename );
267 }
268
269 sub gettemplate {
270     my ( $tmplbase, $interface, $query ) = @_;
271     ($query) or warn "no query in gettemplate";
272     my $path = C4::Context->preference('intranet_includes') || 'includes';
273     my $opacstylesheet = C4::Context->preference('opacstylesheet');
274     $tmplbase =~ s/\.tmpl$/.tt/;
275     my ( $htdocs, $theme, $lang, $filename ) = _get_template_file( $tmplbase, $interface, $query );
276     my $template = C4::Templates->new($interface, $filename, $tmplbase, $query);
277     my $themelang=( $interface ne 'intranet' ? '/opac-tmpl' : '/intranet-tmpl' )
278           . "/$theme/$lang";
279     $template->param(
280         themelang => $themelang,
281         yuipath   => (C4::Context->preference("yuipath") eq "local"?"$themelang/lib/yui":C4::Context->preference("yuipath")),
282         interface => ( $interface ne 'intranet' ? '/opac-tmpl' : '/intranet-tmpl' ),
283         theme     => $theme,
284         lang      => $lang
285     );
286
287     # Bidirectionality
288     my $current_lang = regex_lang_subtags($lang);
289     my $bidi;
290     $bidi = get_bidi($current_lang->{script}) if $current_lang->{script};
291     # Languages
292     my $languages_loop = getTranslatedLanguages($interface,$theme,$lang);
293     my $num_languages_enabled = 0;
294     foreach my $lang (@$languages_loop) {
295         foreach my $sublang (@{ $lang->{'sublanguages_loop'} }) {
296             $num_languages_enabled++ if $sublang->{enabled};
297          }
298     }
299     $template->param(
300             languages_loop       => $languages_loop,
301             bidi                 => $bidi,
302             one_language_enabled => ($num_languages_enabled <= 1) ? 1 : 0, # deal with zero enabled langs as well
303     ) unless @$languages_loop<2;
304
305     return $template;
306 }
307
308
309 #---------------------------------------------------------------------------------------------------------
310 # FIXME - POD
311 sub themelanguage {
312     my ( $htdocs, $tmpl, $interface, $query ) = @_;
313     ($query) or warn "no query in themelanguage";
314
315     # Set some defaults for language and theme
316     # First, check the user's preferences
317     my $lang;
318     my $http_accept_language = $ENV{ HTTP_ACCEPT_LANGUAGE };
319     $lang = accept_language( $http_accept_language, 
320               getTranslatedLanguages($interface,'prog') )
321       if $http_accept_language;
322     # But, if there's a cookie set, obey it
323     $lang = $query->cookie('KohaOpacLanguage') if (defined $query and $query->cookie('KohaOpacLanguage'));
324     # Fall back to English
325     my @languages;
326     if ($interface eq 'intranet') {
327         @languages = split ",", C4::Context->preference("language");
328     } else {
329         @languages = split ",", C4::Context->preference("opaclanguages");
330     }
331     if ($lang){  
332         @languages=($lang,@languages);
333     } else {
334         $lang = $languages[0];
335     }      
336     my $theme = 'prog'; # in the event of theme failure default to 'prog' -fbcit
337     my $dbh = C4::Context->dbh;
338     my @themes;
339     if ( $interface eq "intranet" ) {
340         @themes    = split " ", C4::Context->preference("template");
341     }
342     else {
343       # we are in the opac here, what im trying to do is let the individual user
344       # set the theme they want to use.
345       # and perhaps the them as well.
346         #my $lang = $query->cookie('KohaOpacLanguage');
347         @themes = split " ", C4::Context->preference("opacthemes");
348     }
349
350  # searches through the themes and languages. First template it find it returns.
351  # Priority is for getting the theme right.
352     THEME:
353     foreach my $th (@themes) {
354         foreach my $la (@languages) {
355             #for ( my $pass = 1 ; $pass <= 2 ; $pass += 1 ) {
356                 # warn "$htdocs/$th/$la/modules/$interface-"."tmpl";
357                 #$la =~ s/([-_])/ $1 eq '-'? '_': '-' /eg if $pass == 2;
358                                 if ( -e "$htdocs/$th/$la/modules/$tmpl") {
359                 #".($interface eq 'intranet'?"modules":"")."/$tmpl" ) {
360                     $theme = $th;
361                     $lang  = $la;
362                     last THEME;
363                 }
364                 last unless $la =~ /[-_]/;
365             #}
366         }
367     }
368
369     $_current_language = $lang; # FIXME part of bad hack to paper over bug 4403
370     return ( $theme, $lang );
371 }
372
373 sub setlanguagecookie {
374     my ( $query, $language, $uri ) = @_;
375     my $cookie = $query->cookie(
376         -name    => 'KohaOpacLanguage',
377         -value   => $language,
378         -expires => ''
379     );
380     print $query->redirect(
381         -uri    => $uri,
382         -cookie => $cookie
383     );
384 }
385
386 sub getlanguagecookie {
387     my ($query) = @_;
388     my $lang;
389     if ($query->cookie('KohaOpacLanguage')){
390         $lang = $query->cookie('KohaOpacLanguage') ;
391     }else{
392         $lang = $ENV{HTTP_ACCEPT_LANGUAGE};
393         
394     }
395     $lang = substr($lang, 0, 2);
396
397     return $lang;
398 }
399
400 1;
401