Add new system preferences editor
[koha.git] / C4 / Output.pm
1 package C4::Output;
2
3 #package to deal with marking up output
4 #You will need to edit parts of this pm
5 #set the value of path to be where your html lives
6
7 # Copyright 2000-2002 Katipo Communications
8 #
9 # This file is part of Koha.
10 #
11 # Koha is free software; you can redistribute it and/or modify it under the
12 # terms of the GNU General Public License as published by the Free Software
13 # Foundation; either version 2 of the License, or (at your option) any later
14 # version.
15 #
16 # Koha is distributed in the hope that it will be useful, but WITHOUT ANY
17 # WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
18 # A PARTICULAR PURPOSE.  See the GNU General Public License for more details.
19 #
20 # You should have received a copy of the GNU General Public License along with
21 # Koha; if not, write to the Free Software Foundation, Inc., 59 Temple Place,
22 # Suite 330, Boston, MA  02111-1307 USA
23
24
25 # NOTE: I'm pretty sure this module is deprecated in favor of
26 # templates.
27
28 use strict;
29 use warnings;
30
31 use C4::Context;
32 use C4::Languages qw(getTranslatedLanguages get_bidi regex_lang_subtags language_get_description accept_language );
33
34 use HTML::Template::Pro;
35 use vars qw($VERSION @ISA @EXPORT @EXPORT_OK %EXPORT_TAGS);
36
37 BEGIN {
38     # set the version for version checking
39     $VERSION = 3.03;
40     require Exporter;
41     @ISA    = qw(Exporter);
42         @EXPORT_OK = qw(&is_ajax ajax_fail); # More stuff should go here instead
43         %EXPORT_TAGS = ( all =>[qw(&themelanguage &gettemplate setlanguagecookie pagination_bar
44                                                                 &output_with_http_headers &output_html_with_http_headers)],
45                                         ajax =>[qw(&output_with_http_headers is_ajax)],
46                                         html =>[qw(&output_with_http_headers &output_html_with_http_headers)]
47                                 );
48     push @EXPORT, qw(
49         &themelanguage &gettemplate setlanguagecookie pagination_bar
50     );
51     push @EXPORT, qw(
52         &output_html_with_http_headers &output_with_http_headers
53     );
54 }
55
56 =head1 NAME
57
58 C4::Output - Functions for managing templates
59
60 =head1 FUNCTIONS
61
62 =over 2
63
64 =cut
65
66 #FIXME: this is a quick fix to stop rc1 installing broken
67 #Still trying to figure out the correct fix.
68 my $path = C4::Context->config('intrahtdocs') . "/prog/en/includes/";
69
70 #---------------------------------------------------------------------------------------------------------
71 # FIXME - POD
72
73 sub _get_template_file {
74     my ( $tmplbase, $interface, $query ) = @_;
75     my $htdocs = C4::Context->config( $interface ne 'intranet' ? 'opachtdocs' : 'intrahtdocs' );
76     my ( $theme, $lang ) = themelanguage( $htdocs, $tmplbase, $interface, $query );
77
78     # if the template doesn't exist, load the English one as a last resort
79     my $filename = "$htdocs/$theme/$lang/modules/$tmplbase";
80     unless (-f $filename) {
81         $lang = 'en';
82         $filename = "$htdocs/$theme/$lang/modules/$tmplbase";
83     }
84
85     return ( $htdocs, $theme, $lang, $filename );
86 }
87
88 sub gettemplate {
89     my ( $tmplbase, $interface, $query ) = @_;
90     ($query) or warn "no query in gettemplate";
91     my $path = C4::Context->preference('intranet_includes') || 'includes';
92     my $opacstylesheet = C4::Context->preference('opacstylesheet');
93     my ( $htdocs, $theme, $lang, $filename ) = _get_template_file( $tmplbase, $interface, $query );
94
95     my $template       = HTML::Template::Pro->new(
96         filename          => $filename,
97         die_on_bad_params => 1,
98         global_vars       => 1,
99         case_sensitive    => 1,
100         loop_context_vars => 1, # enable: __first__, __last__, __inner__, __odd__, __counter__ 
101         path              => ["$htdocs/$theme/$lang/$path"]
102     );
103     my $themelang=( $interface ne 'intranet' ? '/opac-tmpl' : '/intranet-tmpl' )
104           . "/$theme/$lang";
105     $template->param(
106         themelang => $themelang,
107         yuipath   => (C4::Context->preference("yuipath") eq "local"?"$themelang/lib/yui":C4::Context->preference("yuipath")),
108         interface => ( $interface ne 'intranet' ? '/opac-tmpl' : '/intranet-tmpl' ),
109         theme     => $theme,
110         lang      => $lang
111     );
112
113     # Bidirectionality
114     my $current_lang = regex_lang_subtags($lang);
115     my $bidi;
116     $bidi = get_bidi($current_lang->{script}) if $current_lang->{script};
117     # Languages
118     my $languages_loop = getTranslatedLanguages($interface,$theme,$lang);
119     my $num_languages_enabled = 0;
120     foreach my $lang (@$languages_loop) {
121         foreach my $sublang (@{ $lang->{'sublanguages_loop'} }) {
122             $num_languages_enabled++ if $sublang->{enabled};
123          }
124     }
125     $template->param(
126             languages_loop       => $languages_loop,
127             bidi                 => $bidi,
128             one_language_enabled => ($num_languages_enabled <= 1) ? 1 : 0, # deal with zero enabled langs as well
129     ) unless @$languages_loop<2;
130
131     return $template;
132 }
133
134 #---------------------------------------------------------------------------------------------------------
135 # FIXME - POD
136 sub themelanguage {
137     my ( $htdocs, $tmpl, $interface, $query ) = @_;
138     ($query) or warn "no query in themelanguage";
139
140     # Set some defaults for language and theme
141     # First, check the user's preferences
142     my $lang;
143     my $http_accept_language = $ENV{ HTTP_ACCEPT_LANGUAGE };
144     $lang = accept_language( $http_accept_language, 
145               getTranslatedLanguages($interface,'prog') )
146       if $http_accept_language;
147     # But, if there's a cookie set, obey it
148     $lang = $query->cookie('KohaOpacLanguage') if $query->cookie('KohaOpacLanguage');
149     # Fall back to English
150     my @languages;
151     if ($interface eq 'intranet') {
152         @languages = split ",", C4::Context->preference("language");
153     } else {
154         @languages = split ",", C4::Context->preference("opaclanguages");
155     }
156     if ($lang){  
157         @languages=($lang,@languages);
158     } else {
159         $lang = $languages[0];
160     }      
161     my $theme = 'prog'; # in the event of theme failure default to 'prog' -fbcit
162     my $dbh = C4::Context->dbh;
163     my @themes;
164     if ( $interface eq "intranet" ) {
165         @themes    = split " ", C4::Context->preference("template");
166     }
167     else {
168       # we are in the opac here, what im trying to do is let the individual user
169       # set the theme they want to use.
170       # and perhaps the them as well.
171         #my $lang = $query->cookie('KohaOpacLanguage');
172         @themes = split " ", C4::Context->preference("opacthemes");
173     }
174
175  # searches through the themes and languages. First template it find it returns.
176  # Priority is for getting the theme right.
177     THEME:
178     foreach my $th (@themes) {
179         foreach my $la (@languages) {
180             #for ( my $pass = 1 ; $pass <= 2 ; $pass += 1 ) {
181                 # warn "$htdocs/$th/$la/modules/$interface-"."tmpl";
182                 #$la =~ s/([-_])/ $1 eq '-'? '_': '-' /eg if $pass == 2;
183                                 if ( -e "$htdocs/$th/$la/modules/$tmpl") {
184                 #".($interface eq 'intranet'?"modules":"")."/$tmpl" ) {
185                     $theme = $th;
186                     $lang  = $la;
187                     last THEME;
188                 }
189                 last unless $la =~ /[-_]/;
190             #}
191         }
192     }
193     return ( $theme, $lang );
194 }
195
196 sub setlanguagecookie {
197     my ( $query, $language, $uri ) = @_;
198     my $cookie = $query->cookie(
199         -name    => 'KohaOpacLanguage',
200         -value   => $language,
201         -expires => ''
202     );
203     print $query->redirect(
204         -uri    => $uri,
205         -cookie => $cookie
206     );
207 }
208
209 =item pagination_bar
210
211    pagination_bar($base_url, $nb_pages, $current_page, $startfrom_name)
212
213 Build an HTML pagination bar based on the number of page to display, the
214 current page and the url to give to each page link.
215
216 C<$base_url> is the URL for each page link. The
217 C<$startfrom_name>=page_number is added at the end of the each URL.
218
219 C<$nb_pages> is the total number of pages available.
220
221 C<$current_page> is the current page number. This page number won't become a
222 link.
223
224 This function returns HTML, without any language dependency.
225
226 =cut
227
228 sub pagination_bar {
229         my $base_url = (@_ ? shift : $ENV{SCRIPT_NAME} . $ENV{QUERY_STRING}) or return undef;
230     my $nb_pages       = (@_) ? shift : 1;
231     my $current_page   = (@_) ? shift : undef;  # delay default until later
232     my $startfrom_name = (@_) ? shift : 'page';
233
234     # how many pages to show before and after the current page?
235     my $pages_around = 2;
236
237         my $delim = qr/\&(?:amp;)?|;/;          # "non memory" cluster: no backreference
238         $base_url =~ s/$delim*\b$startfrom_name=(\d+)//g; # remove previous pagination var
239     unless (defined $current_page and $current_page > 0 and $current_page <= $nb_pages) {
240         $current_page = ($1) ? $1 : 1;  # pull current page from param in URL, else default to 1
241                 # $debug and    # FIXME: use C4::Debug;
242                 # warn "with QUERY_STRING:" .$ENV{QUERY_STRING}. "\ncurrent_page:$current_page\n1:$1  2:$2  3:$3";
243     }
244         $base_url =~ s/($delim)+/$1/g;  # compress duplicate delims
245         $base_url =~ s/$delim;//g;              # remove empties
246         $base_url =~ s/$delim$//;               # remove trailing delim
247
248     my $url = $base_url . (($base_url =~ m/$delim/ or $base_url =~ m/\?/) ? '&amp;' : '?' ) . $startfrom_name . '=';
249     my $pagination_bar = '';
250
251     # navigation bar useful only if more than one page to display !
252     if ( $nb_pages > 1 ) {
253
254         # link to first page?
255         if ( $current_page > 1 ) {
256             $pagination_bar .=
257                 "\n" . '&nbsp;'
258               . '<a href="'
259               . $url
260               . '1" rel="start">'
261               . '&lt;&lt;' . '</a>';
262         }
263         else {
264             $pagination_bar .=
265               "\n" . '&nbsp;<span class="inactive">&lt;&lt;</span>';
266         }
267
268         # link on previous page ?
269         if ( $current_page > 1 ) {
270             my $previous = $current_page - 1;
271
272             $pagination_bar .=
273                 "\n" . '&nbsp;'
274               . '<a href="'
275               . $url
276               . $previous
277               . '" rel="prev">' . '&lt;' . '</a>';
278         }
279         else {
280             $pagination_bar .=
281               "\n" . '&nbsp;<span class="inactive">&lt;</span>';
282         }
283
284         my $min_to_display      = $current_page - $pages_around;
285         my $max_to_display      = $current_page + $pages_around;
286         my $last_displayed_page = undef;
287
288         for my $page_number ( 1 .. $nb_pages ) {
289             if (
290                    $page_number == 1
291                 or $page_number == $nb_pages
292                 or (    $page_number >= $min_to_display
293                     and $page_number <= $max_to_display )
294               )
295             {
296                 if ( defined $last_displayed_page
297                     and $last_displayed_page != $page_number - 1 )
298                 {
299                     $pagination_bar .=
300                       "\n" . '&nbsp;<span class="inactive">...</span>';
301                 }
302
303                 if ( $page_number == $current_page ) {
304                     $pagination_bar .=
305                         "\n" . '&nbsp;'
306                       . '<span class="currentPage">'
307                       . $page_number
308                       . '</span>';
309                 }
310                 else {
311                     $pagination_bar .=
312                         "\n" . '&nbsp;'
313                       . '<a href="'
314                       . $url
315                       . $page_number . '">'
316                       . $page_number . '</a>';
317                 }
318                 $last_displayed_page = $page_number;
319             }
320         }
321
322         # link on next page?
323         if ( $current_page < $nb_pages ) {
324             my $next = $current_page + 1;
325
326             $pagination_bar .= "\n"
327               . '&nbsp;<a href="'
328               . $url
329               . $next
330               . '" rel="next">' . '&gt;' . '</a>';
331         }
332         else {
333             $pagination_bar .=
334               "\n" . '&nbsp;<span class="inactive">&gt;</span>';
335         }
336
337         # link to last page?
338         if ( $current_page != $nb_pages ) {
339             $pagination_bar .= "\n"
340               . '&nbsp;<a href="'
341               . $url
342               . $nb_pages
343               . '" rel="last">'
344               . '&gt;&gt;' . '</a>';
345         }
346         else {
347             $pagination_bar .=
348               "\n" . '&nbsp;<span class="inactive">&gt;&gt;</span>';
349         }
350     }
351
352     return $pagination_bar;
353 }
354
355 =item output_with_http_headers
356
357    &output_with_http_headers($query, $cookie, $data, $content_type[, $status])
358
359 Outputs $data with the appropriate HTTP headers,
360 the authentication cookie $cookie and a Content-Type specified in
361 $content_type.
362
363 If applicable, $cookie can be undef, and it will not be sent.
364
365 $content_type is one of the following: 'html', 'js', 'json', 'xml', 'rss', or 'atom'.
366
367 $status is an HTTP status message, like '403 Authentication Required'. It defaults to '200 OK'.
368
369 =cut
370
371 sub output_with_http_headers($$$$;$) {
372     my ( $query, $cookie, $data, $content_type, $status ) = @_;
373     $status ||= '200 OK';
374
375     my %content_type_map = (
376         'html' => 'text/html',
377         'js'   => 'text/javascript',
378         'json' => 'application/json',
379         'xml'  => 'text/xml',
380         # NOTE: not using application/atom+xml or application/rss+xml because of
381         # Internet Explorer 6; see bug 2078.
382         'rss'  => 'text/xml',
383         'atom' => 'text/xml'
384     );
385
386     die "Unknown content type '$content_type'" if ( !defined( $content_type_map{$content_type} ) );
387     my $options = {
388         type    => $content_type_map{$content_type},
389         status  => $status,
390         charset => 'UTF-8',
391         Pragma          => 'no-cache',
392         'Cache-Control' => 'no-cache',
393     };
394     $options->{cookie} = $cookie if $cookie;
395     if ($content_type eq 'html') {  # guaranteed to be one of the content_type_map keys, else we'd have died
396         $options->{'Content-Style-Type' } = 'text/css';
397         $options->{'Content-Script-Type'} = 'text/javascript';
398     }
399     print $query->header($options), $data;
400 }
401
402 sub output_html_with_http_headers ($$$) {
403     my ( $query, $cookie, $data ) = @_;
404     output_with_http_headers( $query, $cookie, $data, 'html' );
405 }
406
407 sub is_ajax () {
408     my $x_req = $ENV{HTTP_X_REQUESTED_WITH};
409     return ( $x_req and $x_req =~ /XMLHttpRequest/i ) ? 1 : 0;
410 }
411
412 END { }    # module clean-up code here (global destructor)
413
414 1;
415 __END__
416
417 =back
418
419 =head1 AUTHOR
420
421 Koha Developement team <info@koha.org>
422
423 =cut