summaryrefslogtreecommitdiff
path: root/C4/Templates.pm
blob: 3a3a65cfdb84feea350cbdef253b99248893f892 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
package C4::Templates;

use strict;
use warnings;
use Carp;
use CGI;
use List::MoreUtils qw/any uniq/;

# Copyright 2009 Chris Cormack and The Koha Dev Team
#
# This file is part of Koha.
#
# Koha is free software; you can redistribute it and/or modify it under the
# terms of the GNU General Public License as published by the Free Software
# Foundation; either version 2 of the License, or (at your option) any later
# version.
#
# Koha is distributed in the hope that it will be useful, but WITHOUT ANY
# WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
# A PARTICULAR PURPOSE.  See the GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License along with
# Koha; if not, write to the Free Software Foundation, Inc., 59 Temple Place,
# Suite 330, Boston, MA  02111-1307 USA

=head1 NAME 

    Koha::Templates - Object for manipulating templates for use with Koha

=cut

use base qw(Class::Accessor);
use Template;
use Template::Constants qw( :debug );
use C4::Languages qw(getTranslatedLanguages get_bidi regex_lang_subtags language_get_description accept_language );

use C4::Context;

__PACKAGE__->mk_accessors(qw( theme activethemes preferredtheme lang filename htdocs interface vars));



sub new {
    my $class     = shift;
    my $interface = shift;
    my $filename  = shift;
    my $tmplbase  = shift;
    my $query     = @_? shift: undef;
    my $htdocs;
    if ( $interface ne "intranet" ) {
        $htdocs = C4::Context->config('opachtdocs');
    }
    else {
        $htdocs = C4::Context->config('intrahtdocs');
    }
    my ($theme, $lang, $activethemes)= themelanguage( $htdocs, $tmplbase, $interface, $query);
    my @includes;
    foreach (@$activethemes) {
        push @includes, "$htdocs/$_/$lang/includes";
        push @includes, "$htdocs/$_/en/includes" unless $lang eq 'en';
    }
    my $template = Template->new(
        {   EVAL_PERL    => 1,
            ABSOLUTE     => 1,
            PLUGIN_BASE => 'Koha::Template::Plugin',
            COMPILE_EXT => C4::Context->config('template_cache_dir')?'.ttc':'',
            COMPILE_DIR => C4::Context->config('template_cache_dir')?C4::Context->config('template_cache_dir'):'',,
            INCLUDE_PATH => \@includes,
            FILTERS => {},
        }
    ) or die Template->error();
    my $self = {
        TEMPLATE => $template,
        VARS     => {},
    };
    bless $self, $class;
    $self->theme($theme);
    $self->lang($lang);
    $self->activethemes($activethemes);
    $self->preferredtheme($activethemes->[0]);
    $self->filename($filename);
    $self->htdocs($htdocs);
    $self->interface($interface);
    $self->{VARS}->{"test"} = "value";
    return $self;

}

sub output {
    my $self = shift;
    my $vars = shift;

#    my $file = $self->htdocs . '/' . $self->theme .'/'.$self->lang.'/'.$self->filename;
    my $template = $self->{TEMPLATE};
    if ( $self->interface eq 'intranet' ) {
        $vars->{themelang} = '/intranet-tmpl';
    }
    else {
        $vars->{themelang} = '/opac-tmpl';
    }
    $vars->{lang} = $self->lang;
    $vars->{themelang} .= '/' . $self->preferredtheme . '/' . $self->lang;
    $vars->{interface} =
      ( $self->{interface} ne 'intranet' ? '/opac-tmpl' : '/intranet-tmpl' );
    $vars->{theme} = $self->theme;
    $vars->{opaccolorstylesheet} =
        C4::Context->preference('opaccolorstylesheet');
    $vars->{opaclayoutstylesheet} =
        C4::Context->preference('opaclayoutstylesheet');

    # add variables set via param to $vars for processing
    # and clean any utf8 mess
    for my $k ( keys %{ $self->{VARS} } ) {
        $vars->{$k} = $self->{VARS}->{$k};
        if (ref($vars->{$k}) eq 'ARRAY'){
            utf8_arrayref($vars->{$k});
        }
        elsif (ref($vars->{$k}) eq 'HASH'){
            utf8_hashref($vars->{$k});
        }
        else {
            utf8::encode($vars->{$k}) if utf8::is_utf8($vars->{$k});
        }
    }
    my $data;
#    binmode( STDOUT, ":utf8" );
    $template->process( $self->filename, $vars, \$data )
      || die "Template process failed: ", $template->error();
    return $data;
}

sub utf8_arrayref {
    my $arrayref = shift;
    foreach my $element (@$arrayref){
        if (ref($element) eq 'ARRAY'){
            utf8_arrayref($element);
            next;
        }
        if (ref($element) eq 'HASH'){
            utf8_hashref($element);
            next;
        }
        utf8::encode($element) if utf8::is_utf8($element);
    }        
}         

sub utf8_hashref {
    my $hashref = shift;
    for my $key (keys %{$hashref}){
        if (ref($hashref->{$key}) eq 'ARRAY'){
            utf8_arrayref($hashref->{$key});
            next;
        }
        if (ref($hashref->{$key}) eq 'HASH'){
            utf8_hashref($hashref->{$key});
            next;
        }
        utf8::encode($hashref->{$key}) if utf8::is_utf8($hashref->{$key});
    }
}

# wrapper method to allow easier transition from HTML template pro to Template Toolkit
sub param {
    my $self = shift;
    while (@_) {
        my $key = shift;
        my $val = shift;
        if    ( ref($val) eq 'ARRAY' && !scalar @$val ) { $val = undef; }
        elsif ( ref($val) eq 'HASH'  && !scalar %$val ) { $val = undef; }
        if ( $key ) {
            $self->{VARS}->{$key} = $val;
        } else {
            warn "Problem = a value of $val has been passed to param without key";
        }
    }
}


=head1 NAME

C4::Templates - Functions for managing templates

=head1 FUNCTIONS

=cut

# FIXME: this is a quick fix to stop rc1 installing broken
# Still trying to figure out the correct fix.
my $path = C4::Context->config('intrahtdocs') . "/prog/en/includes/";

#---------------------------------------------------------------------------------------------------------
# FIXME - POD

sub _get_template_file {
    my ($tmplbase, $interface, $query) = @_;

    my $is_intranet = $interface eq 'intranet';
    my $htdocs = C4::Context->config($is_intranet ? 'intrahtdocs' : 'opachtdocs');
    my ($theme, $lang, $availablethemes) = themelanguage($htdocs, $tmplbase, $interface, $query);
    my $filename = "$htdocs/$theme/$lang/modules/$tmplbase";

    return ($htdocs, $theme, $lang, $filename);
}


sub gettemplate {
    my ( $tmplbase, $interface, $query, $is_plugin ) = @_;
    ($query) or warn "no query in gettemplate";
    my $path = C4::Context->preference('intranet_includes') || 'includes';
    my ($htdocs, $theme, $lang, $filename)
       =  _get_template_file($tmplbase, $interface, $query);
    $filename = $tmplbase if ( $is_plugin );
    my $template = C4::Templates->new($interface, $filename, $tmplbase, $query);

# NOTE: Commenting these out rather than deleting them so that those who need
# to know how we previously shimmed these directories will be able to understand.
#    my $is_intranet = $interface eq 'intranet';
#    my $themelang =
#        ($is_intranet ? '/intranet-tmpl' : '/opac-tmpl') .
#        "/$theme/$lang";
#    $template->param(
#        themelang => $themelang,
#        interface => $is_intranet ? '/intranet-tmpl' : '/opac-tmpl',
#        theme     => $theme,
#        lang      => $lang
#    );

    # Bidirectionality, must be sent even if is the only language
    my $current_lang = regex_lang_subtags($lang);
    my $bidi;
    $bidi = get_bidi($current_lang->{script}) if $current_lang->{script};
    $template->param(
            bidi                 => $bidi,
    );
    # Languages
    my $languages_loop = getTranslatedLanguages($interface,$theme,$lang);
    my $num_languages_enabled = 0;
    foreach my $lang (@$languages_loop) {
        foreach my $sublang (@{ $lang->{'sublanguages_loop'} }) {
            $num_languages_enabled++ if $sublang->{enabled};
         }
    }
    my $one_language_enabled = ($num_languages_enabled <= 1) ? 1 : 0; # deal with zero enabled langs as well
    $template->param(
            languages_loop       => $languages_loop,
            one_language_enabled => $one_language_enabled,
    ) unless $one_language_enabled;

    return $template;
}


=head2 themelanguage

    my ($theme,$lang,\@themes) = themelanguage($htdocs,$tmpl,$interface,query);

This function returns the theme and language to be used for rendering the UI.
It also returns the list of themes that should be applied as a fallback. This is
used for the theme overlay feature (i.e. if a file doesn't exist on the requested
theme, fallback to the configured fallback).

Important: this function is used on the webinstaller too, so always consider
the use case where the DB is not populated already when rewriting/fixing.

=cut

sub themelanguage {
    my ($htdocs, $tmpl, $interface, $query) = @_;
    ($query) or warn "no query in themelanguage";

    # Select a language based on cookie, syspref available languages & browser
    my $lang = C4::Languages::getlanguage($query);

    # Get theme
    my @themes;
    my $theme_syspref    = ($interface eq 'intranet') ? 'template' : 'opacthemes';
    my $fallback_syspref = ($interface eq 'intranet') ? 'template' : 'OPACFallback';
    # Yeah, hardcoded, last resort if the DB is not populated
    my $hardcoded_theme = ($interface eq 'intranet') ? 'prog' : 'bootstrap';

    # Configured theme is the first one
    push @themes, C4::Context->preference( $theme_syspref )
        if C4::Context->preference( $theme_syspref );
    # Configured fallback next
    push @themes, C4::Context->preference( $fallback_syspref )
        if C4::Context->preference( $fallback_syspref );
    # The hardcoded fallback theme is the last one
    push @themes, $hardcoded_theme;

    # Try to find first theme for the selected theme/lang, then for fallback/lang
    for my $theme (@themes) {
        if ( -e "$htdocs/$theme/$lang/modules/$tmpl" ) {
            return ( $theme, $lang, uniq( \@themes ) );
        }
    }
    # Otherwise return theme/'en', last resort fallback/'en'
    for my $theme (@themes) {
        if ( -e "$htdocs/$theme/en/modules/$tmpl" ) {
            return ( $theme, 'en', uniq( \@themes ) );
        }
    }
}


sub setlanguagecookie {
    my ( $query, $language, $uri ) = @_;

    my $cookie = $query->cookie(
        -name    => 'KohaOpacLanguage',
        -value   => $language,
        -HttpOnly => 1,
        -expires => '+3y'
    );
    print $query->redirect(
        -uri    => $uri,
        -cookie => $cookie
    );
}

=head2 getlanguagecookie

    my $cookie = getlanguagecookie($query,$language);

Returns a cookie object containing the calculated language to be used.

=cut

sub getlanguagecookie {
    my ( $query, $language ) = @_;
    my $cookie = $query->cookie(
        -name    => 'KohaOpacLanguage',
        -value   => $language,
        -HttpOnly => 1,
        -expires => '+3y'
    );

    return $cookie;
}

=head2 GetColumnDefs

    my $columns = GetColumnDefs( $cgi )

It is passed a CGI object and returns a hash of hashes containing
the column names and descriptions for each table defined in the
columns.def file corresponding to the CGI object.

=cut

sub GetColumnDefs {

    my $query = shift;

    my $columns = {};

    my $htdocs = C4::Context->config('intrahtdocs');
    my $columns_file = 'columns.def';

    # Get theme and language to build the path to columns.def
    my ($theme, $lang, $availablethemes) =
        themelanguage($htdocs, 'about.tt', 'intranet', $query);
    # Build columns.def path
    my $path = "$htdocs/$theme/$lang/$columns_file";
    my $fh;
    if ( ! open ( $fh, q{<}, $path ) )  {
        carp "Error opening $path. Check your templates.";
        return;
    }
    # Loop through the columns.def file
    while ( my $input = <$fh> ){
        chomp $input;
        if ( $input =~ m|<field name="(.*)">(.*)</field>| ) {
            my ( $table, $column ) =  split( '\.', $1);
            my $description        = $2;
            # Initialize the table array if needed.
            @{$columns->{ $table }} = () if ! defined $columns->{ $table };
            # Push field and description
            push @{$columns->{ $table }},
                { field => $column, description => $description };
        }
    }
    close $fh;

    return $columns;
}

1;