Bug 11944: Remove all utf8 filter from templates
[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::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         }
73     ) or die Template->error();
74     my $self = {
75         TEMPLATE => $template,
76         VARS     => {},
77     };
78     bless $self, $class;
79     $self->theme($theme);
80     $self->lang($lang);
81     $self->activethemes($activethemes);
82     $self->preferredtheme($activethemes->[0]);
83     $self->filename($filename);
84     $self->htdocs($htdocs);
85     $self->interface($interface);
86     $self->{VARS}->{"test"} = "value";
87     return $self;
88
89 }
90
91 sub output {
92     my $self = shift;
93     my $vars = shift;
94
95 #    my $file = $self->htdocs . '/' . $self->theme .'/'.$self->lang.'/'.$self->filename;
96     my $template = $self->{TEMPLATE};
97     if ( $self->interface eq 'intranet' ) {
98         $vars->{themelang} = '/intranet-tmpl';
99     }
100     else {
101         $vars->{themelang} = '/opac-tmpl';
102     }
103     $vars->{lang} = $self->lang;
104     $vars->{themelang} .= '/' . $self->preferredtheme . '/' . $self->lang;
105     $vars->{interface} =
106       ( $self->{interface} ne 'intranet' ? '/opac-tmpl' : '/intranet-tmpl' );
107     $vars->{theme} = $self->theme;
108     $vars->{opaccolorstylesheet} =
109         C4::Context->preference('opaccolorstylesheet');
110     $vars->{opaclayoutstylesheet} =
111         C4::Context->preference('opaclayoutstylesheet');
112
113     # add variables set via param to $vars for processing
114     # and clean any utf8 mess
115     for my $k ( keys %{ $self->{VARS} } ) {
116         $vars->{$k} = $self->{VARS}->{$k};
117         if (ref($vars->{$k}) eq 'ARRAY'){
118             utf8_arrayref($vars->{$k});
119         }
120         elsif (ref($vars->{$k}) eq 'HASH'){
121             utf8_hashref($vars->{$k});
122         }
123         else {
124             utf8::encode($vars->{$k}) if utf8::is_utf8($vars->{$k});
125         }
126     }
127     my $data;
128     binmode( STDOUT, ":utf8" );
129     $template->process( $self->filename, $vars, \$data )
130       || die "Template process failed: ", $template->error();
131     return $data;
132 }
133
134 sub utf8_arrayref {
135     my $arrayref = shift;
136     foreach my $element (@$arrayref){
137         if (ref($element) eq 'ARRAY'){
138             utf8_arrayref($element);
139             next;
140         }
141         if (ref($element) eq 'HASH'){
142             utf8_hashref($element);
143             next;
144         }
145         utf8::encode($element) if utf8::is_utf8($element);
146     }        
147 }         
148
149 sub utf8_hashref {
150     my $hashref = shift;
151     for my $key (keys %{$hashref}){
152         if (ref($hashref->{$key}) eq 'ARRAY'){
153             utf8_arrayref($hashref->{$key});
154             next;
155         }
156         if (ref($hashref->{$key}) eq 'HASH'){
157             utf8_hashref($hashref->{$key});
158             next;
159         }
160         utf8::encode($hashref->{$key}) if utf8::is_utf8($hashref->{$key});
161     }
162 }
163
164 # wrapper method to allow easier transition from HTML template pro to Template Toolkit
165 sub param {
166     my $self = shift;
167     while (@_) {
168         my $key = shift;
169         my $val = shift;
170         if    ( ref($val) eq 'ARRAY' && !scalar @$val ) { $val = undef; }
171         elsif ( ref($val) eq 'HASH'  && !scalar %$val ) { $val = undef; }
172         if ( $key ) {
173             $self->{VARS}->{$key} = $val;
174         } else {
175             warn "Problem = a value of $val has been passed to param without key";
176         }
177     }
178 }
179
180
181 =head1 NAME
182
183 C4::Templates - Functions for managing templates
184
185 =head1 FUNCTIONS
186
187 =cut
188
189 # FIXME: this is a quick fix to stop rc1 installing broken
190 # Still trying to figure out the correct fix.
191 my $path = C4::Context->config('intrahtdocs') . "/prog/en/includes/";
192
193 #---------------------------------------------------------------------------------------------------------
194 # FIXME - POD
195
196 sub _get_template_file {
197     my ($tmplbase, $interface, $query) = @_;
198
199     my $is_intranet = $interface eq 'intranet';
200     my $htdocs = C4::Context->config($is_intranet ? 'intrahtdocs' : 'opachtdocs');
201     my ($theme, $lang, $availablethemes) = themelanguage($htdocs, $tmplbase, $interface, $query);
202     my $filename = "$htdocs/$theme/$lang/modules/$tmplbase";
203
204     return ($htdocs, $theme, $lang, $filename);
205 }
206
207
208 sub gettemplate {
209     my ( $tmplbase, $interface, $query, $is_plugin ) = @_;
210     ($query) or warn "no query in gettemplate";
211     my $path = C4::Context->preference('intranet_includes') || 'includes';
212     my ($htdocs, $theme, $lang, $filename)
213        =  _get_template_file($tmplbase, $interface, $query);
214     $filename = $tmplbase if ( $is_plugin );
215     my $template = C4::Templates->new($interface, $filename, $tmplbase, $query);
216
217 # NOTE: Commenting these out rather than deleting them so that those who need
218 # to know how we previously shimmed these directories will be able to understand.
219 #    my $is_intranet = $interface eq 'intranet';
220 #    my $themelang =
221 #        ($is_intranet ? '/intranet-tmpl' : '/opac-tmpl') .
222 #        "/$theme/$lang";
223 #    $template->param(
224 #        themelang => $themelang,
225 #        interface => $is_intranet ? '/intranet-tmpl' : '/opac-tmpl',
226 #        theme     => $theme,
227 #        lang      => $lang
228 #    );
229
230     # Bidirectionality, must be sent even if is the only language
231     my $current_lang = regex_lang_subtags($lang);
232     my $bidi;
233     $bidi = get_bidi($current_lang->{script}) if $current_lang->{script};
234     $template->param(
235             bidi                 => $bidi,
236     );
237     # Languages
238     my $languages_loop = getTranslatedLanguages($interface,$theme,$lang);
239     my $num_languages_enabled = 0;
240     foreach my $lang (@$languages_loop) {
241         foreach my $sublang (@{ $lang->{'sublanguages_loop'} }) {
242             $num_languages_enabled++ if $sublang->{enabled};
243          }
244     }
245     my $one_language_enabled = ($num_languages_enabled <= 1) ? 1 : 0; # deal with zero enabled langs as well
246     $template->param(
247             languages_loop       => $languages_loop,
248             one_language_enabled => $one_language_enabled,
249     ) unless $one_language_enabled;
250
251     return $template;
252 }
253
254
255 =head2 themelanguage
256
257     my ($theme,$lang,\@themes) = themelanguage($htdocs,$tmpl,$interface,query);
258
259 This function returns the theme and language to be used for rendering the UI.
260 It also returns the list of themes that should be applied as a fallback. This is
261 used for the theme overlay feature (i.e. if a file doesn't exist on the requested
262 theme, fallback to the configured fallback).
263
264 Important: this function is used on the webinstaller too, so always consider
265 the use case where the DB is not populated already when rewriting/fixing.
266
267 =cut
268
269 sub themelanguage {
270     my ($htdocs, $tmpl, $interface, $query) = @_;
271     ($query) or warn "no query in themelanguage";
272
273     # Select a language based on cookie, syspref available languages & browser
274     my $lang = C4::Languages::getlanguage($query);
275
276     # Get theme
277     my @themes;
278     my $theme_syspref    = ($interface eq 'intranet') ? 'template' : 'opacthemes';
279     my $fallback_syspref = ($interface eq 'intranet') ? 'template' : 'OPACFallback';
280     # Yeah, hardcoded, last resort if the DB is not populated
281     my $hardcoded_theme = ($interface eq 'intranet') ? 'prog' : 'bootstrap';
282
283     # Configured theme is the first one
284     push @themes, C4::Context->preference( $theme_syspref )
285         if C4::Context->preference( $theme_syspref );
286     # Configured fallback next
287     push @themes, C4::Context->preference( $fallback_syspref )
288         if C4::Context->preference( $fallback_syspref );
289     # The hardcoded fallback theme is the last one
290     push @themes, $hardcoded_theme;
291
292     # Try to find first theme for the selected theme/lang, then for fallback/lang
293     my $where = $tmpl =~ /xsl$/ ? 'xslt' : 'modules';
294     for my $theme (@themes) {
295         if ( -e "$htdocs/$theme/$lang/$where/$tmpl" ) {
296             return ( $theme, $lang, uniq( \@themes ) );
297         }
298     }
299     # Otherwise return theme/'en', last resort fallback/'en'
300     for my $theme (@themes) {
301         if ( -e "$htdocs/$theme/en/$where/$tmpl" ) {
302             return ( $theme, 'en', uniq( \@themes ) );
303         }
304     }
305 }
306
307
308 sub setlanguagecookie {
309     my ( $query, $language, $uri ) = @_;
310
311     my $cookie = $query->cookie(
312         -name    => 'KohaOpacLanguage',
313         -value   => $language,
314         -HttpOnly => 1,
315         -expires => '+3y'
316     );
317     print $query->redirect(
318         -uri    => $uri,
319         -cookie => $cookie
320     );
321 }
322
323 =head2 getlanguagecookie
324
325     my $cookie = getlanguagecookie($query,$language);
326
327 Returns a cookie object containing the calculated language to be used.
328
329 =cut
330
331 sub getlanguagecookie {
332     my ( $query, $language ) = @_;
333     my $cookie = $query->cookie(
334         -name    => 'KohaOpacLanguage',
335         -value   => $language,
336         -HttpOnly => 1,
337         -expires => '+3y'
338     );
339
340     return $cookie;
341 }
342
343 =head2 GetColumnDefs
344
345     my $columns = GetColumnDefs( $cgi )
346
347 It is passed a CGI object and returns a hash of hashes containing
348 the column names and descriptions for each table defined in the
349 columns.def file corresponding to the CGI object.
350
351 =cut
352
353 sub GetColumnDefs {
354
355     my $query = shift;
356
357     my $columns = {};
358
359     my $htdocs = C4::Context->config('intrahtdocs');
360     my $columns_file = 'columns.def';
361
362     # Get theme and language to build the path to columns.def
363     my ($theme, $lang, $availablethemes) =
364         themelanguage($htdocs, 'about.tt', 'intranet', $query);
365     # Build columns.def path
366     my $path = "$htdocs/$theme/$lang/$columns_file";
367     my $fh;
368     if ( ! open ( $fh, q{<}, $path ) )  {
369         carp "Error opening $path. Check your templates.";
370         return;
371     }
372     # Loop through the columns.def file
373     while ( my $input = <$fh> ){
374         chomp $input;
375         if ( $input =~ m|<field name="(.*)">(.*)</field>| ) {
376             my ( $table, $column ) =  split( '\.', $1);
377             my $description        = $2;
378             # Initialize the table array if needed.
379             @{$columns->{ $table }} = () if ! defined $columns->{ $table };
380             # Push field and description
381             push @{$columns->{ $table }},
382                 { field => $column, description => $description };
383         }
384     }
385     close $fh;
386
387     return $columns;
388 }
389
390 1;