Bug 22770: DBRev 19.05.00.003
[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
12 # under the terms of the GNU General Public License as published by
13 # the Free Software Foundation; either version 3 of the License, or
14 # (at your option) any later version.
15 #
16 # Koha is distributed in the hope that it will be useful, but
17 # WITHOUT ANY WARRANTY; without even the implied warranty of
18 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
19 # GNU General Public License for more details.
20 #
21 # You should have received a copy of the GNU General Public License
22 # along with Koha; if not, see <http://www.gnu.org/licenses>.
23
24
25 # NOTE: I'm pretty sure this module is deprecated in favor of
26 # templates.
27
28 use strict;
29 #use warnings; FIXME - Bug 2505
30
31 use URI::Escape;
32 use Scalar::Util qw( looks_like_number );
33
34 use C4::Context;
35 use C4::Templates;
36
37 use vars qw(@ISA @EXPORT @EXPORT_OK %EXPORT_TAGS);
38
39 BEGIN {
40     require Exporter;
41
42  @ISA    = qw(Exporter);
43     @EXPORT_OK = qw(&is_ajax ajax_fail); # More stuff should go here instead
44     %EXPORT_TAGS = ( all =>[qw(setlanguagecookie pagination_bar parametrized_url
45                                 &output_with_http_headers &output_ajax_with_http_headers &output_html_with_http_headers)],
46                     ajax =>[qw(&output_with_http_headers &output_ajax_with_http_headers is_ajax)],
47                     html =>[qw(&output_with_http_headers &output_html_with_http_headers)]
48                 );
49     push @EXPORT, qw(
50         setlanguagecookie getlanguagecookie pagination_bar parametrized_url
51     );
52     push @EXPORT, qw(
53         &output_html_with_http_headers &output_ajax_with_http_headers &output_with_http_headers
54         &output_and_exit_if_error &output_and_exit
55     );
56
57 }
58
59 =head1 NAME
60
61 C4::Output - Functions for managing output, is slowly being deprecated
62
63 =head1 FUNCTIONS
64
65 =over 2
66
67 =item pagination_bar
68
69    pagination_bar($base_url, $nb_pages, $current_page, $startfrom_name)
70
71 Build an HTML pagination bar based on the number of page to display, the
72 current page and the url to give to each page link.
73
74 C<$base_url> is the URL for each page link. The
75 C<$startfrom_name>=page_number is added at the end of the each URL.
76
77 C<$nb_pages> is the total number of pages available.
78
79 C<$current_page> is the current page number. This page number won't become a
80 link.
81
82 This function returns HTML, without any language dependency.
83
84 =cut
85
86 sub pagination_bar {
87     my $base_url = (@_ ? shift : return);
88     my $nb_pages       = (@_) ? shift : 1;
89     my $current_page   = (@_) ? shift : undef;  # delay default until later
90     my $startfrom_name = (@_) ? shift : 'page';
91     my $additional_parameters = shift || {};
92
93     $current_page = looks_like_number($current_page) ? $current_page : undef;
94     $nb_pages     = looks_like_number($nb_pages)     ? $nb_pages     : undef;
95
96     # how many pages to show before and after the current page?
97     my $pages_around = 2;
98
99         my $delim = qr/\&(?:amp;)?|;/;          # "non memory" cluster: no backreference
100         $base_url =~ s/$delim*\b$startfrom_name=(\d+)//g; # remove previous pagination var
101     unless (defined $current_page and $current_page > 0 and $current_page <= $nb_pages) {
102         $current_page = ($1) ? $1 : 1;  # pull current page from param in URL, else default to 1
103                 # $debug and    # FIXME: use C4::Debug;
104                 # warn "with QUERY_STRING:" .$ENV{QUERY_STRING}. "\ncurrent_page:$current_page\n1:$1  2:$2  3:$3";
105     }
106         $base_url =~ s/($delim)+/$1/g;  # compress duplicate delims
107         $base_url =~ s/$delim;//g;              # remove empties
108         $base_url =~ s/$delim$//;               # remove trailing delim
109
110     my $url = $base_url . (($base_url =~ m/$delim/ or $base_url =~ m/\?/) ? '&amp;' : '?' ) . $startfrom_name . '=';
111     my $url_suffix;
112     while ( my ( $k, $v ) = each %$additional_parameters ) {
113         $url_suffix .= '&amp;' . URI::Escape::uri_escape_utf8($k) . '=' . URI::Escape::uri_escape_utf8($v);
114     }
115     my $pagination_bar = '';
116
117     # navigation bar useful only if more than one page to display !
118     if ( $nb_pages > 1 ) {
119
120         # link to first page?
121         if ( $current_page > 1 ) {
122             $pagination_bar .=
123                 "\n" . '&nbsp;'
124               . '<a href="'
125               . $url
126               . '1'
127               . $url_suffix
128               . '"rel="start">'
129               . '&lt;&lt;' . '</a>';
130         }
131         else {
132             $pagination_bar .=
133               "\n" . '&nbsp;<span class="inactive">&lt;&lt;</span>';
134         }
135
136         # link on previous page ?
137         if ( $current_page > 1 ) {
138             my $previous = $current_page - 1;
139
140             $pagination_bar .=
141                 "\n" . '&nbsp;'
142               . '<a href="'
143               . $url
144               . $previous
145               . $url_suffix
146               . '" rel="prev">' . '&lt;' . '</a>';
147         }
148         else {
149             $pagination_bar .=
150               "\n" . '&nbsp;<span class="inactive">&lt;</span>';
151         }
152
153         my $min_to_display      = $current_page - $pages_around;
154         my $max_to_display      = $current_page + $pages_around;
155         my $last_displayed_page = undef;
156
157         for my $page_number ( 1 .. $nb_pages ) {
158             if (
159                    $page_number == 1
160                 or $page_number == $nb_pages
161                 or (    $page_number >= $min_to_display
162                     and $page_number <= $max_to_display )
163               )
164             {
165                 if ( defined $last_displayed_page
166                     and $last_displayed_page != $page_number - 1 )
167                 {
168                     $pagination_bar .=
169                       "\n" . '&nbsp;<span class="inactive">...</span>';
170                 }
171
172                 if ( $page_number == $current_page ) {
173                     $pagination_bar .=
174                         "\n" . '&nbsp;'
175                       . '<span class="currentPage">'
176                       . $page_number
177                       . '</span>';
178                 }
179                 else {
180                     $pagination_bar .=
181                         "\n" . '&nbsp;'
182                       . '<a href="'
183                       . $url
184                       . $page_number
185                       . $url_suffix
186                       . '">'
187                       . $page_number . '</a>';
188                 }
189                 $last_displayed_page = $page_number;
190             }
191         }
192
193         # link on next page?
194         if ( $current_page < $nb_pages ) {
195             my $next = $current_page + 1;
196
197             $pagination_bar .= "\n"
198               . '&nbsp;<a href="'
199               . $url
200               . $next
201               . $url_suffix
202               . '" rel="next">' . '&gt;' . '</a>';
203         }
204         else {
205             $pagination_bar .=
206               "\n" . '&nbsp;<span class="inactive">&gt;</span>';
207         }
208
209         # link to last page?
210         if ( $current_page != $nb_pages ) {
211             $pagination_bar .= "\n"
212               . '&nbsp;<a href="'
213               . $url
214               . $nb_pages
215               . $url_suffix
216               . '" rel="last">'
217               . '&gt;&gt;' . '</a>';
218         }
219         else {
220             $pagination_bar .=
221               "\n" . '&nbsp;<span class="inactive">&gt;&gt;</span>';
222         }
223     }
224
225     return $pagination_bar;
226 }
227
228 =item output_with_http_headers
229
230    &output_with_http_headers($query, $cookie, $data, $content_type[, $status[, $extra_options]])
231
232 Outputs $data with the appropriate HTTP headers,
233 the authentication cookie $cookie and a Content-Type specified in
234 $content_type.
235
236 If applicable, $cookie can be undef, and it will not be sent.
237
238 $content_type is one of the following: 'html', 'js', 'json', 'xml', 'rss', or 'atom'.
239
240 $status is an HTTP status message, like '403 Authentication Required'. It defaults to '200 OK'.
241
242 $extra_options is hashref.  If the key 'force_no_caching' is present and has
243 a true value, the HTTP headers include directives to force there to be no
244 caching whatsoever.
245
246 =cut
247
248 sub output_with_http_headers {
249     my ( $query, $cookie, $data, $content_type, $status, $extra_options ) = @_;
250     $status ||= '200 OK';
251
252     $extra_options //= {};
253
254     my %content_type_map = (
255         'html' => 'text/html',
256         'js'   => 'text/javascript',
257         'json' => 'application/json',
258         'xml'  => 'text/xml',
259         # NOTE: not using application/atom+xml or application/rss+xml because of
260         # Internet Explorer 6; see bug 2078.
261         'rss'  => 'text/xml',
262         'atom' => 'text/xml'
263     );
264
265     die "Unknown content type '$content_type'" if ( !defined( $content_type_map{$content_type} ) );
266     my $cache_policy = 'no-cache';
267     $cache_policy .= ', no-store, max-age=0' if $extra_options->{force_no_caching};
268     my $options = {
269         type              => $content_type_map{$content_type},
270         status            => $status,
271         charset           => 'UTF-8',
272         Pragma            => 'no-cache',
273         'Cache-Control'   => $cache_policy,
274         'X-Frame-Options' => 'SAMEORIGIN',
275     };
276     $options->{expires} = 'now' if $extra_options->{force_no_caching};
277
278     $options->{cookie} = $cookie if $cookie;
279     if ($content_type eq 'html') {  # guaranteed to be one of the content_type_map keys, else we'd have died
280         $options->{'Content-Style-Type' } = 'text/css';
281         $options->{'Content-Script-Type'} = 'text/javascript';
282     }
283
284 # We can't encode here, that will double encode our templates, and xslt
285 # We need to fix the encoding as it comes out of the database, or when we pass the variables to templates
286
287     $data =~ s/\&amp\;amp\; /\&amp\; /g;
288     print $query->header($options), $data;
289 }
290
291 sub output_html_with_http_headers {
292     my ( $query, $cookie, $data, $status, $extra_options ) = @_;
293     output_with_http_headers( $query, $cookie, $data, 'html', $status, $extra_options );
294 }
295
296
297 sub output_ajax_with_http_headers {
298     my ( $query, $js ) = @_;
299     print $query->header(
300         -type            => 'text/javascript',
301         -charset         => 'UTF-8',
302         -Pragma          => 'no-cache',
303         -'Cache-Control' => 'no-cache',
304         -expires         => '-1d',
305     ), $js;
306 }
307
308 sub is_ajax {
309     my $x_req = $ENV{HTTP_X_REQUESTED_WITH};
310     return ( $x_req and $x_req =~ /XMLHttpRequest/i ) ? 1 : 0;
311 }
312
313 =item output_and_exit_if_error
314
315     output_and_exit_if_error( $query, $cookie, $template, $params );
316
317 To executed at the beginning of scripts to stop the script at this point if
318 some errors are found.
319
320 Tests for module 'members':
321 * patron is not defined (we are looking for a patron that does no longer exist/never existed)
322 * The logged in user cannot see patron's infos (feature 'cannot_see_patron_infos')
323
324 Others will be added here depending on the needs (for instance biblio does not exist will be useful).
325
326 =cut
327
328 sub output_and_exit_if_error {
329     my ( $query, $cookie, $template, $params ) = @_;
330     my $error;
331     if ( $params and exists $params->{module} ) {
332         if ( $params->{module} eq 'members' ) {
333             my $logged_in_user = $params->{logged_in_user};
334             my $current_patron = $params->{current_patron};
335             if ( not $current_patron ) {
336                 $error = 'unknown_patron';
337             }
338             elsif( not $logged_in_user->can_see_patron_infos( $current_patron ) ) {
339                 $error = 'cannot_see_patron_infos';
340             }
341         }
342     }
343
344     output_and_exit( $query, $cookie, $template, $error ) if $error;
345     return;
346 }
347
348 =item output_and_exit
349
350     output_and_exit( $query, $cookie, $template, $error );
351
352     $error is a blocking error like biblionumber not found or so.
353     We should output the error and exit.
354
355 =cut
356
357 sub output_and_exit {
358     my ( $query, $cookie, $template, $error ) = @_;
359     $template->param( blocking_error => $error );
360     output_html_with_http_headers ( $query, $cookie, $template->output );
361     exit;
362 }
363
364 sub parametrized_url {
365     my $url = shift || ''; # ie page.pl?ln={LANG}
366     my $vars = shift || {}; # ie { LANG => en }
367     my $ret = $url;
368     while ( my ($key,$val) = each %$vars) {
369         my $val_url = URI::Escape::uri_escape_utf8( $val // q{} );
370         $ret =~ s/\{$key\}/$val_url/g;
371     }
372     $ret =~ s/\{[^\{]*\}//g; # remove remaining vars
373     return $ret;
374 }
375
376 END { }    # module clean-up code here (global destructor)
377
378 1;
379 __END__
380
381 =back
382
383 =head1 AUTHOR
384
385 Koha Development Team <http://koha-community.org/>
386
387 =cut