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