Bug 19542: Add Elasticsearch information in the 'About' page
[koha.git] / about.pl
1 #!/usr/bin/perl
2
3 # Copyright Pat Eyler 2003
4 # Copyright Biblibre 2006
5 # Parts Copyright Liblime 2008
6 # Parts Copyright Chris Nighswonger 2010
7 #
8 # This file is part of Koha.
9 #
10 # Koha is free software; you can redistribute it and/or modify it
11 # under the terms of the GNU General Public License as published by
12 # the Free Software Foundation; either version 3 of the License, or
13 # (at your option) any later version.
14 #
15 # Koha is distributed in the hope that it will be useful, but
16 # WITHOUT ANY WARRANTY; without even the implied warranty of
17 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18 # GNU General Public License for more details.
19 #
20 # You should have received a copy of the GNU General Public License
21 # along with Koha; if not, see <http://www.gnu.org/licenses>.
22
23 use Modern::Perl;
24
25 use CGI qw ( -utf8 );
26 use List::MoreUtils qw/ any /;
27 use LWP::Simple;
28 use XML::Simple;
29 use Config;
30 use Search::Elasticsearch;
31 use Try::Tiny;
32
33 use C4::Output;
34 use C4::Auth;
35 use C4::Context;
36 use C4::Installer;
37
38 use Koha;
39 use Koha::Acquisition::Currencies;
40 use Koha::Patron::Categories;
41 use Koha::Patrons;
42 use Koha::Caches;
43 use Koha::Config::SysPrefs;
44 use Koha::Illrequest::Config;
45 use Koha::SearchEngine::Elasticsearch;
46
47 use C4::Members::Statistics;
48
49
50 #use Smart::Comments '####';
51
52 my $query = new CGI;
53 my ( $template, $loggedinuser, $cookie ) = get_template_and_user(
54     {
55         template_name   => "about.tt",
56         query           => $query,
57         type            => "intranet",
58         authnotrequired => 0,
59         flagsrequired   => { catalogue => 1 },
60         debug           => 1,
61     }
62 );
63
64 my $perl_path = $^X;
65 if ($^O ne 'VMS') {
66     $perl_path .= $Config{_exe} unless $perl_path =~ m/$Config{_exe}$/i;
67 }
68
69 my $zebraVersion = `zebraidx -V`;
70
71 # Check running PSGI env
72 if ( any { /(^psgi\.|^plack\.)/i } keys %ENV ) {
73     $template->param(
74         is_psgi => 1,
75         psgi_server => ($ENV{ PLACK_ENV }) ? "Plack ($ENV{PLACK_ENV})" :
76                        ($ENV{ MOD_PERL })  ? "mod_perl ($ENV{MOD_PERL})" :
77                                              'Unknown'
78     );
79 }
80
81 # Memcached configuration
82 my $memcached_servers   = $ENV{MEMCACHED_SERVERS} || C4::Context->config('memcached_servers');
83 my $memcached_namespace = $ENV{MEMCACHED_NAMESPACE} || C4::Context->config('memcached_namespace') // 'koha';
84
85 my $cache = Koha::Caches->get_instance;
86 my $effective_caching_method = ref($cache->cache);
87 # Memcached may have been running when plack has been initialized but could have been stopped since
88 # FIXME What are the consequences of that??
89 my $is_memcached_still_active = $cache->set_in_cache('test_for_about_page', "just a simple value");
90
91 my $where_is_memcached_config = 'nowhere';
92 if ( $ENV{MEMCACHED_SERVERS} and C4::Context->config('memcached_servers') ) {
93     $where_is_memcached_config = 'both';
94 } elsif ( $ENV{MEMCACHED_SERVERS} and not C4::Context->config('memcached_servers') ) {
95     $where_is_memcached_config = 'ENV_only';
96 } elsif ( C4::Context->config('memcached_servers') ) {
97     $where_is_memcached_config = 'config_only';
98 }
99
100 $template->param(
101     effective_caching_method => $effective_caching_method,
102     memcached_servers   => $memcached_servers,
103     memcached_namespace => $memcached_namespace,
104     is_memcached_still_active => $is_memcached_still_active,
105     where_is_memcached_config => $where_is_memcached_config,
106     memcached_running   => Koha::Caches->get_instance->memcached_cache,
107 );
108
109 # Additional system information for warnings
110
111 my $warnStatisticsFieldsError;
112 my $prefStatisticsFields = C4::Context->preference('StatisticsFields');
113 if ($prefStatisticsFields) {
114     $warnStatisticsFieldsError = $prefStatisticsFields
115         unless ( $prefStatisticsFields eq C4::Members::Statistics->get_fields() );
116 }
117
118 my $prefAutoCreateAuthorities = C4::Context->preference('AutoCreateAuthorities');
119 my $prefBiblioAddsAuthorities = C4::Context->preference('BiblioAddsAuthorities');
120 my $warnPrefBiblioAddsAuthorities = ( $prefAutoCreateAuthorities && ( !$prefBiblioAddsAuthorities) );
121
122 my $prefEasyAnalyticalRecords  = C4::Context->preference('EasyAnalyticalRecords');
123 my $prefUseControlNumber  = C4::Context->preference('UseControlNumber');
124 my $warnPrefEasyAnalyticalRecords  = ( $prefEasyAnalyticalRecords  && $prefUseControlNumber );
125 my $warnPrefAnonymousPatron = (
126     C4::Context->preference('OPACPrivacy')
127         and not C4::Context->preference('AnonymousPatron')
128 );
129
130 my $anonymous_patron = Koha::Patrons->find( C4::Context->preference('AnonymousPatron') );
131 my $warnPrefAnonymousPatron_PatronDoesNotExist = ( not $anonymous_patron and Koha::Patrons->search({ privacy => 2 })->count );
132
133 my $errZebraConnection = C4::Context->Zconn("biblioserver",0)->errcode();
134
135 my $warnIsRootUser   = (! $loggedinuser);
136
137 my $warnNoActiveCurrency = (! defined Koha::Acquisition::Currencies->get_active);
138
139 my @xml_config_warnings;
140
141 my $context = new C4::Context;
142
143 if ( ! defined C4::Context->config('zebra_bib_index_mode') ) {
144     push @xml_config_warnings, {
145         error => 'zebra_bib_index_mode_warn'
146     };
147     if ($context->{'server'}->{'biblioserver'}->{'config'} !~ /zebra-biblios-dom.cfg/) {
148         push @xml_config_warnings, {
149             error => 'zebra_bib_mode_seems_grs1'
150         };
151     }
152     else {
153         push @xml_config_warnings, {
154             error => 'zebra_bib_mode_seems_dom'
155         };
156     }
157 } else {
158     push @xml_config_warnings, { error => 'zebra_bib_grs_warn' }
159         if C4::Context->config('zebra_bib_index_mode') eq 'grs1';
160 }
161
162 if ( (C4::Context->config('zebra_bib_index_mode') eq 'dom') &&
163      ($context->{'server'}->{'biblioserver'}->{'config'} !~ /zebra-biblios-dom.cfg/) ) {
164
165     push @xml_config_warnings, {
166         error => 'zebra_bib_index_mode_mismatch_warn'
167     };
168 }
169
170 if ( (C4::Context->config('zebra_bib_index_mode') eq 'grs1') &&
171      ($context->{'server'}->{'biblioserver'}->{'config'} =~ /zebra-biblios-dom.cfg/) ) {
172
173     push @xml_config_warnings, {
174         error => 'zebra_bib_index_mode_mismatch_warn'
175     };
176 }
177
178 if ( ! defined C4::Context->config('zebra_auth_index_mode') ) {
179     push @xml_config_warnings, {
180         error => 'zebra_auth_index_mode_warn'
181     };
182     if ($context->{'server'}->{'authorityserver'}->{'config'} !~ /zebra-authorities-dom.cfg/) {
183         push @xml_config_warnings, {
184             error => 'zebra_auth_mode_seems_grs1'
185         };
186     }
187     else {
188         push @xml_config_warnings, {
189             error => 'zebra_auth_mode_seems_dom'
190         };
191     }
192 } else {
193     push @xml_config_warnings, { error => 'zebra_auth_grs_warn' }
194         if C4::Context->config('zebra_auth_index_mode') eq 'grs1';
195 }
196
197 if ( (C4::Context->config('zebra_auth_index_mode') eq 'dom') && ($context->{'server'}->{'authorityserver'}->{'config'} !~ /zebra-authorities-dom.cfg/) ) {
198     push @xml_config_warnings, {
199         error => 'zebra_auth_index_mode_mismatch_warn'
200     };
201 }
202
203 if ( (C4::Context->config('zebra_auth_index_mode') eq 'grs1') && ($context->{'server'}->{'authorityserver'}->{'config'} =~ /zebra-authorities-dom.cfg/) ) {
204     push @xml_config_warnings, {
205         error => 'zebra_auth_index_mode_mismatch_warn'
206     };
207 }
208
209 if ( ! defined C4::Context->config('log4perl_conf') ) {
210     push @xml_config_warnings, {
211         error => 'log4perl_entry_missing'
212     }
213 }
214
215 if ( ! defined C4::Context->config('upload_path') ) {
216     if ( Koha::Config::SysPrefs->find('OPACBaseURL')->value ) {
217         # OPACBaseURL seems to be set
218         push @xml_config_warnings, {
219             error => 'uploadpath_entry_missing'
220         }
221     } else {
222         push @xml_config_warnings, {
223             error => 'uploadpath_and_opacbaseurl_entry_missing'
224         }
225     }
226 }
227
228 # Test QueryParser configuration sanity
229 if ( C4::Context->preference( 'UseQueryParser' ) ) {
230     # Get the QueryParser configuration file name
231     my $queryparser_file          = C4::Context->config( 'queryparser_config' );
232     my $queryparser_fallback_file = '/etc/koha/searchengine/queryparser.yaml';
233     # Check QueryParser is functional
234     my $QParser = C4::Context->queryparser();
235     my $queryparser_error = {};
236     if ( ! defined $QParser || ref($QParser) ne 'Koha::QueryParser::Driver::PQF' ) {
237         # Error initializing the QueryParser object
238         # Get the used queryparser.yaml file path to report the user
239         $queryparser_error->{ fallback } = ( defined $queryparser_file ) ? 0 : 1;
240         $queryparser_error->{ file }     = ( defined $queryparser_file )
241                                                 ? $queryparser_file
242                                                 : $queryparser_fallback_file;
243         # Report error data to the template
244         $template->param( QueryParserError => $queryparser_error );
245     } else {
246         # Check for an absent queryparser_config entry in koha-conf.xml
247         if ( ! defined $queryparser_file ) {
248             # Not an error but a warning for the missing entry in koha-conf-xml
249             push @xml_config_warnings, {
250                     error => 'queryparser_entry_missing',
251                     file  => $queryparser_fallback_file
252             };
253         }
254     }
255 }
256
257 # Test Zebra facets configuration
258 if ( !defined C4::Context->config('use_zebra_facets') ) {
259     push @xml_config_warnings, { error => 'use_zebra_facets_entry_missing' };
260 } else {
261     if ( C4::Context->config('use_zebra_facets') &&
262          C4::Context->config('zebra_bib_index_mode') ) {
263         # use_zebra_facets works with DOM
264         push @xml_config_warnings, {
265             error => 'use_zebra_facets_needs_dom'
266         } if C4::Context->config('zebra_bib_index_mode') ne 'dom' ;
267     }
268 }
269
270 # ILL module checks
271 if ( C4::Context->preference('ILLModule') ) {
272     my $warnILLConfiguration = 0;
273     my $ill_config_from_file = C4::Context->config("interlibrary_loans");
274     my $ill_config = Koha::Illrequest::Config->new;
275
276     my $available_ill_backends =
277       ( scalar @{ $ill_config->available_backends } > 0 );
278
279     # Check backends
280     if ( !$available_ill_backends ) {
281         $template->param( no_ill_backends => 1 );
282         $warnILLConfiguration = 1;
283     }
284
285     # Check partner_code
286     if ( !Koha::Patron::Categories->find($ill_config->partner_code) ) {
287         $template->param( ill_partner_code_doesnt_exist => $ill_config->partner_code );
288         $warnILLConfiguration = 1;
289     }
290
291     if ( !$ill_config_from_file->{partner_code} ) {
292         # partner code not defined
293         $template->param( ill_partner_code_not_defined => 1 );
294         $warnILLConfiguration = 1;
295     }
296
297     $template->param( warnILLConfiguration => $warnILLConfiguration );
298 }
299
300 if ( C4::Context->preference('SearchEngine') eq 'Elasticsearch' ) {
301     # Check ES configuration health and runtime status
302
303     my $es_status;
304     my $es_config_error;
305     my $es_running = 1;
306
307     my $es_conf;
308     try {
309         $es_conf = Koha::SearchEngine::Elasticsearch::_read_configuration();
310     }
311     catch {
312         if ( ref($_) eq 'Koha::Exceptions::Config::MissingEntry' ) {
313             $template->param( elasticsearch_fatal_config_error => $_->message );
314             $es_config_error = 1;
315         }
316         warn p($_);
317     };
318     if ( !$es_config_error ) {
319
320         my $biblios_index_name     = $es_conf->{index_name} . "_" . $Koha::SearchEngine::BIBLIOS_INDEX;
321         my $authorities_index_name = $es_conf->{index_name} . "_" . $Koha::SearchEngine::AUTHORITIES_INDEX;
322
323         my @indexes = ($biblios_index_name, $authorities_index_name);
324         # TODO: When new indexes get added, we could have other ways to
325         #       fetch the list of available indexes (e.g. plugins, etc)
326         $es_status->{nodes} = $es_conf->{nodes};
327         my $es = Search::Elasticsearch->new({ nodes => $es_conf->{nodes} });
328
329         foreach my $index ( @indexes ) {
330             my $count;
331             try {
332                 $count = $es->indices->stats( index => $index )
333                       ->{_all}{primaries}{docs}{count};
334             }
335             catch {
336                 if ( ref($_) eq 'Search::Elasticsearch::Error::Missing' ) {
337                     push @{ $es_status->{errors} }, "Index not found ($index)";
338                     $count = -1;
339                 }
340                 elsif ( ref($_) eq 'Search::Elasticsearch::Error::NoNodes' ) {
341                     $es_running = 0;
342                 }
343                 else {
344                     # TODO: when time comes, we will cover more use cases
345                     die $_;
346                 }
347             };
348
349             push @{ $es_status->{indexes} },
350               {
351                 index_name => $index,
352                 count      => $count
353               };
354         }
355         $es_status->{running} = $es_running;
356
357         $template->param( elasticsearch_status => $es_status );
358     }
359 }
360
361 # Sco Patron should not contain any other perms than circulate => self_checkout
362 if (  C4::Context->preference('WebBasedSelfCheck')
363       and C4::Context->preference('AutoSelfCheckAllowed')
364 ) {
365     my $userid = C4::Context->preference('AutoSelfCheckID');
366     my $all_permissions = C4::Auth::get_user_subpermissions( $userid );
367     my ( $has_self_checkout_perm, $has_other_permissions );
368     while ( my ( $module, $permissions ) = each %$all_permissions ) {
369         if ( $module eq 'circulate' ) {
370             while ( my ( $permission, $flag ) = each %$permissions ) {
371                 if ( $permission eq 'self_checkout' ) {
372                     $has_self_checkout_perm = 1;
373                 } else {
374                     $has_other_permissions = 1;
375                 }
376             }
377         } else {
378             $has_other_permissions = 1;
379         }
380     }
381     $template->param(
382         AutoSelfCheckPatronDoesNotHaveSelfCheckPerm => not ( $has_self_checkout_perm ),
383         AutoSelfCheckPatronHasTooManyPerm => $has_other_permissions,
384     );
385 }
386
387 {
388     my $dbh       = C4::Context->dbh;
389     my $patrons = $dbh->selectall_arrayref(
390         q|select b.borrowernumber from borrowers b join deletedborrowers db on b.borrowernumber=db.borrowernumber|,
391         { Slice => {} }
392     );
393     my $biblios = $dbh->selectall_arrayref(
394         q|select b.biblionumber from biblio b join deletedbiblio db on b.biblionumber=db.biblionumber|,
395         { Slice => {} }
396     );
397     my $items = $dbh->selectall_arrayref(
398         q|select i.itemnumber from items i join deleteditems di on i.itemnumber=di.itemnumber|,
399         { Slice => {} }
400     );
401     my $checkouts = $dbh->selectall_arrayref(
402         q|select i.issue_id from issues i join old_issues oi on i.issue_id=oi.issue_id|,
403         { Slice => {} }
404     );
405     my $holds = $dbh->selectall_arrayref(
406         q|select r.reserve_id from reserves r join old_reserves o on r.reserve_id=o.reserve_id|,
407         { Slice => {} }
408     );
409     if ( @$patrons or @$biblios or @$items or @$checkouts or @$holds ) {
410         $template->param(
411             has_ai_issues => 1,
412             ai_patrons    => $patrons,
413             ai_biblios    => $biblios,
414             ai_items      => $items,
415             ai_checkouts  => $checkouts,
416             ai_holds      => $holds,
417         );
418     }
419 }
420 my %versions = C4::Context::get_versions();
421
422 $template->param(
423     kohaVersion   => $versions{'kohaVersion'},
424     osVersion     => $versions{'osVersion'},
425     perlPath      => $perl_path,
426     perlVersion   => $versions{'perlVersion'},
427     perlIncPath   => [ map { perlinc => $_ }, @INC ],
428     mysqlVersion  => $versions{'mysqlVersion'},
429     apacheVersion => $versions{'apacheVersion'},
430     zebraVersion  => $zebraVersion,
431     prefBiblioAddsAuthorities => $prefBiblioAddsAuthorities,
432     prefAutoCreateAuthorities => $prefAutoCreateAuthorities,
433     warnPrefBiblioAddsAuthorities => $warnPrefBiblioAddsAuthorities,
434     warnPrefEasyAnalyticalRecords  => $warnPrefEasyAnalyticalRecords,
435     warnPrefAnonymousPatron => $warnPrefAnonymousPatron,
436     warnPrefAnonymousPatron_PatronDoesNotExist => $warnPrefAnonymousPatron_PatronDoesNotExist,
437     errZebraConnection => $errZebraConnection,
438     warnIsRootUser => $warnIsRootUser,
439     warnNoActiveCurrency => $warnNoActiveCurrency,
440     warnNoTemplateCaching => ( C4::Context->config('template_cache_dir') ? 0 : 1 ),
441     xml_config_warnings => \@xml_config_warnings,
442     warnStatisticsFieldsError => $warnStatisticsFieldsError,
443 );
444
445 my @components = ();
446
447 my $perl_modules = C4::Installer::PerlModules->new;
448 $perl_modules->versions_info;
449
450 my @pm_types = qw(missing_pm upgrade_pm current_pm);
451
452 foreach my $pm_type(@pm_types) {
453     my $modules = $perl_modules->get_attr($pm_type);
454     foreach (@$modules) {
455         my ($module, $stats) = each %$_;
456         push(
457             @components,
458             {
459                 name    => $module,
460                 version => $stats->{'cur_ver'},
461                 missing => ($pm_type eq 'missing_pm' ? 1 : 0),
462                 upgrade => ($pm_type eq 'upgrade_pm' ? 1 : 0),
463                 current => ($pm_type eq 'current_pm' ? 1 : 0),
464                 require => $stats->{'required'},
465                 reqversion => $stats->{'min_ver'},
466             }
467         );
468     }
469 }
470
471 @components = sort {$a->{'name'} cmp $b->{'name'}} @components;
472
473 my $counter=0;
474 my $row = [];
475 my $table = [];
476 foreach (@components) {
477     push (@$row, $_);
478     unless (++$counter % 4) {
479         push (@$table, {row => $row});
480         $row = [];
481     }
482 }
483 # Processing the last line (if there are any modules left)
484 if (scalar(@$row) > 0) {
485     # Extending $row to the table size
486     $$row[3] = '';
487     # Pushing the last line
488     push (@$table, {row => $row});
489 }
490 ## ## $table
491
492 $template->param( table => $table );
493
494
495 ## ------------------------------------------
496 ## Koha time line code
497
498 #get file location
499 my $docdir;
500 if ( defined C4::Context->config('docdir') ) {
501     $docdir = C4::Context->config('docdir');
502 } else {
503     # if no <docdir> is defined in koha-conf.xml, use the default location
504     # this is a work-around to stop breakage on upgraded Kohas, bug 8911
505     $docdir = C4::Context->config('intranetdir') . '/docs';
506 }
507
508 if ( open( my $file, "<:encoding(UTF-8)", "$docdir" . "/history.txt" ) ) {
509
510     my $i = 0;
511
512     my @rows2 = ();
513     my $row2  = [];
514
515     my @lines = <$file>;
516     close($file);
517
518     shift @lines; #remove header row
519
520     foreach (@lines) {
521         my ( $epoch, $date, $desc, $tag ) = split(/\t/);
522         if(!$desc && $date=~ /(?<=\d{4})\s+/) {
523             ($date, $desc)= ($`, $');
524         }
525         push(
526             @rows2,
527             {
528                 date => $date,
529                 desc => $desc,
530             }
531         );
532     }
533
534     my $table2 = [];
535     #foreach my $row2 (@rows2) {
536     foreach  (@rows2) {
537         push (@$row2, $_);
538         push( @$table2, { row2 => $row2 } );
539         $row2 = [];
540     }
541
542     $template->param( table2 => $table2 );
543 } else {
544     $template->param( timeline_read_error => 1 );
545 }
546
547 output_html_with_http_headers $query, $cookie, $template->output;