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