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