Bug 36328: (QA follow-up) Expand tests and reorder elements to clarify differences
[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 Modern::Perl;
29
30 use HTML::Entities;
31 use Scalar::Util qw( looks_like_number );
32 use URI::Escape;
33
34 use C4::Auth qw( get_template_and_user );
35 use C4::Context;
36 use C4::Templates;
37 use Koha::Token;
38
39 our (@ISA, @EXPORT_OK);
40
41 BEGIN {
42     require Exporter;
43
44     @ISA    = qw(Exporter);
45     @EXPORT_OK = qw(
46         is_ajax
47         ajax_fail
48         setlanguagecookie getlanguagecookie pagination_bar parametrized_url
49         output_html_with_http_headers output_ajax_with_http_headers output_with_http_headers
50         output_and_exit_if_error output_and_exit output_error
51     );
52 }
53
54 =head1 NAME
55
56 C4::Output - Functions for managing output, is slowly being deprecated
57
58 =head1 FUNCTIONS
59
60 =over 2
61
62 =item pagination_bar
63
64    pagination_bar($base_url, $nb_pages, $current_page, $startfrom_name)
65
66 Build an HTML pagination bar based on the number of page to display, the
67 current page and the url to give to each page link.
68
69 C<$base_url> is the URL for each page link. The
70 C<$startfrom_name>=page_number is added at the end of the each URL.
71
72 C<$nb_pages> is the total number of pages available.
73
74 C<$current_page> is the current page number. This page number won't become a
75 link.
76
77 This function returns HTML, without any language dependency.
78
79 =cut
80
81 sub pagination_bar {
82     my $base_url = (@_ ? shift : return);
83     my $nb_pages       = (@_) ? shift : 1;
84     my $current_page   = (@_) ? shift : undef;  # delay default until later
85     my $startfrom_name = (@_) ? shift : 'page';
86     my $additional_parameters = shift || {};
87
88     $base_url = HTML::Entities::encode($base_url);
89
90     $current_page = looks_like_number($current_page) ? $current_page : undef;
91     $nb_pages     = looks_like_number($nb_pages)     ? $nb_pages     : undef;
92
93     # how many pages to show before and after the current page?
94     my $pages_around = 2;
95
96         my $delim = qr/\&(?:amp;)?|;/;          # "non memory" cluster: no backreference
97         $base_url =~ s/$delim*\b$startfrom_name=(\d+)//g; # remove previous pagination var
98     unless (defined $current_page and $current_page > 0 and $current_page <= $nb_pages) {
99         $current_page = ($1) ? $1 : 1;  # pull current page from param in URL, else default to 1
100     }
101         $base_url =~ s/($delim)+/$1/g;  # compress duplicate delims
102         $base_url =~ s/$delim;//g;              # remove empties
103         $base_url =~ s/$delim$//;               # remove trailing delim
104
105     my $url = $base_url . (($base_url =~ m/$delim/ or $base_url =~ m/\?/) ? '&amp;' : '?' ) . $startfrom_name . '=';
106     my $url_suffix = '';
107     while ( my ( $k, $v ) = each %$additional_parameters ) {
108         $url_suffix .= '&amp;' . URI::Escape::uri_escape_utf8($k) . '=' . URI::Escape::uri_escape_utf8($v);
109     }
110     my $pagination_bar = '';
111
112     # navigation bar useful only if more than one page to display !
113     if ( $nb_pages > 1 ) {
114
115         # link to first page?
116         if ( $current_page > 1 ) {
117             $pagination_bar .=
118                 "\n" . '&nbsp;'
119               . '<a href="'
120               . $url
121               . '1'
122               . $url_suffix
123               . '"rel="start">'
124               . '&lt;&lt;' . '</a>';
125         }
126         else {
127             $pagination_bar .=
128               "\n" . '&nbsp;<span class="inactive">&lt;&lt;</span>';
129         }
130
131         # link on previous page ?
132         if ( $current_page > 1 ) {
133             my $previous = $current_page - 1;
134
135             $pagination_bar .=
136                 "\n" . '&nbsp;'
137               . '<a href="'
138               . $url
139               . $previous
140               . $url_suffix
141               . '" rel="prev">' . '&lt;' . '</a>';
142         }
143         else {
144             $pagination_bar .=
145               "\n" . '&nbsp;<span class="inactive">&lt;</span>';
146         }
147
148         my $min_to_display      = $current_page - $pages_around;
149         my $max_to_display      = $current_page + $pages_around;
150         my $last_displayed_page = undef;
151
152         for my $page_number ( 1 .. $nb_pages ) {
153             if (
154                    $page_number == 1
155                 or $page_number == $nb_pages
156                 or (    $page_number >= $min_to_display
157                     and $page_number <= $max_to_display )
158               )
159             {
160                 if ( defined $last_displayed_page
161                     and $last_displayed_page != $page_number - 1 )
162                 {
163                     $pagination_bar .=
164                       "\n" . '&nbsp;<span class="inactive">...</span>';
165                 }
166
167                 if ( $page_number == $current_page ) {
168                     $pagination_bar .=
169                         "\n" . '&nbsp;'
170                       . '<span class="currentPage">'
171                       . $page_number
172                       . '</span>';
173                 }
174                 else {
175                     $pagination_bar .=
176                         "\n" . '&nbsp;'
177                       . '<a href="'
178                       . $url
179                       . $page_number
180                       . $url_suffix
181                       . '">'
182                       . $page_number . '</a>';
183                 }
184                 $last_displayed_page = $page_number;
185             }
186         }
187
188         # link on next page?
189         if ( $current_page < $nb_pages ) {
190             my $next = $current_page + 1;
191
192             $pagination_bar .= "\n"
193               . '&nbsp;<a href="'
194               . $url
195               . $next
196               . $url_suffix
197               . '" rel="next">' . '&gt;' . '</a>';
198         }
199         else {
200             $pagination_bar .=
201               "\n" . '&nbsp;<span class="inactive">&gt;</span>';
202         }
203
204         # link to last page?
205         if ( $current_page != $nb_pages ) {
206             $pagination_bar .= "\n"
207               . '&nbsp;<a href="'
208               . $url
209               . $nb_pages
210               . $url_suffix
211               . '" rel="last">'
212               . '&gt;&gt;' . '</a>';
213         }
214         else {
215             $pagination_bar .=
216               "\n" . '&nbsp;<span class="inactive">&gt;&gt;</span>';
217         }
218     }
219
220     return $pagination_bar;
221 }
222
223 =item output_with_http_headers
224
225    &output_with_http_headers($query, $cookie, $data, $content_type[, $status[, $extra_options]])
226
227 Outputs $data with the appropriate HTTP headers,
228 the authentication cookie $cookie and a Content-Type specified in
229 $content_type.
230
231 If applicable, $cookie can be undef, and it will not be sent.
232
233 $content_type is one of the following: 'html', 'js', 'json', 'opensearchdescription', 'xml', 'rss', or 'atom'.
234
235 $status is an HTTP status message, like '403 Authentication Required'. It defaults to '200 OK'.
236
237 $extra_options is hashref.  If the key 'force_no_caching' is present and has
238 a true value, the HTTP headers include directives to force there to be no
239 caching whatsoever.
240
241 =cut
242
243 sub output_with_http_headers {
244     my ( $query, $cookie, $data, $content_type, $status, $extra_options ) = @_;
245     $status ||= '200 OK';
246
247     $extra_options //= {};
248
249     my %content_type_map = (
250         'html' => 'text/html',
251         'js'   => 'text/javascript',
252         'json' => 'application/json',
253         'xml'  => 'text/xml',
254         # NOTE: not using application/atom+xml or application/rss+xml because of
255         # Internet Explorer 6; see bug 2078.
256         'rss'  => 'text/xml',
257         'atom' => 'text/xml',
258         'opensearchdescription' => 'application/opensearchdescription+xml',
259     );
260
261     die "Unknown content type '$content_type'" if ( !defined( $content_type_map{$content_type} ) );
262     my $cache_policy = 'no-cache';
263     $cache_policy .= ', no-store, max-age=0' if $extra_options->{force_no_caching};
264     my $options = {
265         type              => $content_type_map{$content_type},
266         status            => $status,
267         charset           => 'UTF-8',
268         Pragma            => 'no-cache',
269         'Cache-Control'   => $cache_policy,
270         'X-Frame-Options' => 'SAMEORIGIN',
271     };
272     $options->{expires} = 'now' if $extra_options->{force_no_caching};
273     $options->{'Access-Control-Allow-Origin'} = C4::Context->preference('AccessControlAllowOrigin')
274         if C4::Context->preference('AccessControlAllowOrigin');
275
276     $options->{cookie} = $cookie if $cookie;
277     if ($content_type eq 'html') {  # guaranteed to be one of the content_type_map keys, else we'd have died
278         $options->{'Content-Style-Type' } = 'text/css';
279         $options->{'Content-Script-Type'} = 'text/javascript';
280     }
281
282 # We can't encode here, that will double encode our templates, and xslt
283 # We need to fix the encoding as it comes out of the database, or when we pass the variables to templates
284
285     $data =~ s/\&amp\;amp\; /\&amp\; /g;
286     print $query->header($options), $data;
287 }
288
289 sub output_html_with_http_headers {
290     my ( $query, $cookie, $data, $status, $extra_options ) = @_;
291     output_with_http_headers( $query, $cookie, $data, 'html', $status, $extra_options );
292 }
293
294
295 sub output_ajax_with_http_headers {
296     my ( $query, $js ) = @_;
297     print $query->header(
298         -type            => 'text/javascript',
299         -charset         => 'UTF-8',
300         -Pragma          => 'no-cache',
301         -'Cache-Control' => 'no-cache',
302         -expires         => '-1d',
303     ), $js;
304 }
305
306 sub is_ajax {
307     my $x_req = $ENV{HTTP_X_REQUESTED_WITH};
308     return ( $x_req and $x_req =~ /XMLHttpRequest/i ) ? 1 : 0;
309 }
310
311 =item output_and_exit_if_error
312
313     output_and_exit_if_error( $query, $cookie, $template, $params );
314
315 To executed at the beginning of scripts to stop the script at this point if
316 some errors are found.
317
318 A series of tests can be run for a given module, or a specific check.
319 Params "module" and "check" are mutually exclusive.
320
321 Tests for modules:
322 * members:
323     - Patron is not defined (we are looking for a patron that does no longer exist/never existed)
324     - The logged in user cannot see patron's infos (feature 'cannot_see_patron_infos')
325
326 Tests for specific check:
327 * csrf_token
328     will test if the csrf_token CGI param is valid
329
330 Others will be added here depending on the needs (for instance biblio does not exist will be useful).
331
332 =cut
333
334 sub output_and_exit_if_error {
335     my ( $query, $cookie, $template, $params ) = @_;
336     my $error;
337     if ( $params and exists $params->{module} ) {
338         if ( $params->{module} eq 'members' ) {
339             my $logged_in_user = $params->{logged_in_user};
340             my $current_patron = $params->{current_patron};
341             if ( not $current_patron ) {
342                 $error = 'unknown_patron';
343             }
344             elsif ( not $logged_in_user->can_see_patron_infos($current_patron) )
345             {
346                 $error = 'cannot_see_patron_infos';
347             }
348         }
349         elsif ( $params->{module} eq 'cataloguing' ) {
350             # We are testing the record to avoid additem to fetch the Koha::Biblio
351             # But in the long term we will want to get a biblio in parameter
352             $error = 'unknown_biblio' unless $params->{record};
353         }
354     }
355     elsif ( $params and exists $params->{check} ) {
356         if ( $params->{check} eq 'csrf_token' ) {
357             $error = 'wrong_csrf_token'
358               unless Koha::Token->new->check_csrf(
359                 {
360                     session_id => scalar $query->cookie('CGISESSID'),
361                     token      => scalar $query->param('csrf_token'),
362                 }
363               );
364         }
365     }
366     output_and_exit( $query, $cookie, $template, $error ) if $error;
367     return;
368 }
369
370 =item output_and_exit
371
372     output_and_exit( $query, $cookie, $template, $error );
373
374     $error is a blocking error like biblionumber not found or so.
375     We should output the error and exit.
376
377 =cut
378
379 sub output_and_exit {
380     my ( $query, $cookie, $template, $error ) = @_;
381     $template->param( blocking_error => $error );
382     output_html_with_http_headers ( $query, $cookie, $template->output );
383     exit;
384 }
385
386 sub output_error {
387     my ( $query, $error ) = @_;
388     my ( $template, $loggedinuser, $cookie ) = get_template_and_user(
389         {
390             template_name   => 'errors/errorpage.tt',
391             query           => $query,
392             type            => 'intranet',
393             authnotrequired => 1,
394         }
395     );
396     my $admin = C4::Context->preference('KohaAdminEmailAddress');
397     $template->param (
398         admin => $admin,
399         errno => $error,
400     );
401     output_with_http_headers $query, $cookie, $template->output, 'html', '404 Not Found';
402 }
403
404 sub parametrized_url {
405     my $url = shift || ''; # ie page.pl?ln={LANG}
406     my $vars = shift || {}; # ie { LANG => en }
407     my $ret = $url;
408     while ( my ($key,$val) = each %$vars) {
409         my $val_url = URI::Escape::uri_escape_utf8( $val // q{} );
410         $ret =~ s/\{$key\}/$val_url/g;
411     }
412     $ret =~ s/\{[^\{]*\}//g; # remove remaining vars
413     return $ret;
414 }
415
416 END { }    # module clean-up code here (global destructor)
417
418 1;
419 __END__
420
421 =back
422
423 =head1 AUTHOR
424
425 Koha Development Team <http://koha-community.org/>
426
427 =cut