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