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