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