Bug 34668: (QA follow-up) Change file permission
[koha.git] / installer / install.pl
1 #!/usr/bin/perl
2
3 # This file is part of Koha.
4 #
5 # Copyright (C) YEAR  YOURNAME-OR-YOUREMPLOYER
6 #
7 # Koha is free software; you can redistribute it and/or modify it
8 # under the terms of the GNU General Public License as published by
9 # the Free Software Foundation; either version 3 of the License, or
10 # (at your option) any later version.
11 #
12 # Koha is distributed in the hope that it will be useful, but
13 # WITHOUT ANY WARRANTY; without even the implied warranty of
14 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 # GNU General Public License for more details.
16 #
17 # You should have received a copy of the GNU General Public License
18 # along with Koha; if not, see <http://www.gnu.org/licenses>.
19
20 use Modern::Perl;
21 use diagnostics;
22
23 use C4::InstallAuth qw( get_template_and_user );
24 use CGI qw ( -utf8 );
25 use POSIX;
26
27 use C4::Context;
28 use C4::Output qw( output_html_with_http_headers );
29 use C4::Templates;
30 use C4::Languages qw( getAllLanguages getTranslatedLanguages );
31 use C4::Installer;
32 use C4::Installer::PerlModules;
33
34 use Koha;
35 use Koha::Caches;
36
37 my $query = CGI->new;
38 my $step  = $query->param('step');
39
40 # Flush memcached before we begin
41 Koha::Caches->get_instance('config')->flush_all;
42 Koha::Caches->get_instance('sysprefs')->flush_all;
43
44 my $language = $query->param('language');
45 my ( $template, $loggedinuser, $cookie );
46
47 my $all_languages = getAllLanguages();
48
49 if ( defined($language) ) {
50     C4::Templates::setlanguagecookie( $query, $language, "install.pl?step=1" );
51 }
52 ( $template, $loggedinuser, $cookie ) = get_template_and_user(
53     {
54         template_name => "installer/step" . ( $step ? $step : 1 ) . ".tt",
55         query         => $query,
56         type          => "intranet",
57     }
58 );
59
60 my $installer = C4::Installer->new();
61 my %info;
62 $info{'dbname'} = C4::Context->config("database_test") || C4::Context->config("database");
63 $info{'dbms'}   = (
64       C4::Context->config("db_scheme")
65     ? C4::Context->config("db_scheme")
66     : "mysql"
67 );
68 $info{'hostname'} = C4::Context->config("hostname");
69 $info{'port'}     = C4::Context->config("port");
70 $info{'user'}     = C4::Context->config("user");
71 $info{'password'} = C4::Context->config("pass");
72 $info{'tls'} = C4::Context->config("tls");
73     if ($info{'tls'} && $info{'tls'} eq 'yes'){
74         $info{'ca'} = C4::Context->config('ca');
75         $info{'cert'} = C4::Context->config('cert');
76         $info{'key'} = C4::Context->config('key');
77         $info{'tlsoptions'} = ";mysql_ssl=1;mysql_ssl_client_key=".$info{key}.";mysql_ssl_client_cert=".$info{cert}.";mysql_ssl_ca_file=".$info{ca};
78         $info{'tlscmdline'} =  " --ssl-cert ". $info{cert} . " --ssl-key " . $info{key} . " --ssl-ca ".$info{ca}." "
79     }
80
81 my $dbh = DBI->connect(
82     "DBI:$info{dbms}:dbname=$info{dbname};host=$info{hostname}"
83       . ( $info{port} ? ";port=$info{port}" : "" )
84       . ( $info{tlsoptions} ? $info{tlsoptions} : "" ),
85     $info{'user'}, $info{'password'}
86 );
87
88 my $op = $query->param('op') || q{};
89 if ( $step && $step == 1 ) {
90
91     #First Step (for both fresh installations and upgrades)
92     #Checking ALL perl Modules and services needed are installed.
93     #Whenever there is an error, adding a report to the page
94     $template->param( language      => 1 );
95     my $checkmodule = 1;
96     $template->param( 'checkmodule' => 1 )
97       ; # we start with the assumption that there are no problems and set this to 0 if there are
98
99     unless ( $] >= 5.010000 ) {    # Bug 7375
100         $template->param( problems => 1, perlversion => 1, checkmodule => 0 );
101         $checkmodule = 0;
102     }
103
104     my $perl_modules = C4::Installer::PerlModules->new;
105     $perl_modules->versions_info;
106
107     my $missing_modules = $perl_modules->get_attr('missing_pm');
108     my $upgrade_modules = $perl_modules->get_attr('upgrade_pm');
109     if ( scalar(@$missing_modules) || scalar(@$upgrade_modules) ) {
110         my @missing  = ();
111         my @upgrade = ();
112         foreach (@$missing_modules) {
113             my ( $module, $stats ) = each %$_;
114             $checkmodule = 0 if $stats->{'required'};
115             push(
116                 @missing,
117                 {
118                     name    => $module,
119                     min_version => $stats->{'min_ver'},
120                     max_version => $stats->{'max_ver'},
121                     require => $stats->{'required'}
122                 }
123             );
124         }
125         foreach (@$upgrade_modules) {
126             my ( $module, $stats ) = each %$_;
127             $checkmodule = 0 if $stats->{'required'};
128             push(
129                 @upgrade,
130                 {
131                     name    => $module,
132                     min_version => $stats->{'min_ver'},
133                     max_version => $stats->{'max_ver'},
134                     require => $stats->{'required'}
135                 }
136             );
137         }
138         @missing = sort { $a->{'name'} cmp $b->{'name'} } @missing;
139         @upgrade = sort { $a->{'name'} cmp $b->{'name'} } @upgrade;
140         $template->param(
141             missing_modules => \@missing,
142             upgrade_modules => \@upgrade,
143             checkmodule     => $checkmodule,
144         );
145     }
146 }
147 elsif ( $step && $step == 2 ) {
148
149     #STEP 2 Check Database connection and access
150
151     $template->param(%info);
152     my $checkdb = $query->param("checkdb");
153     $template->param( 'dbconnection' => $checkdb );
154     if ($checkdb) {
155         if ($dbh) {
156
157             # Can connect to the mysql
158             $template->param( "checkdatabaseaccess" => 1 );
159             if ( $info{dbms} eq "mysql" ) {
160
161                 #Check if database created
162                 my $rv = $dbh->do("SHOW DATABASES LIKE \'$info{dbname}\'");
163                 if ( $rv == 1 ) {
164                     $template->param( 'checkdatabasecreated' => 1 );
165                 }
166
167                 # Check if user have all necessary grants on this database.
168                 # CURRENT_USER is ANSI SQL, and doesn't require mysql table
169                 # privileges, making the % check pointless, since they
170                 # couldn't even check GRANTS if they couldn't connect.
171                 my $rq = $dbh->prepare('SHOW GRANTS FOR CURRENT_USER');
172                 $rq->execute;
173                 my $grantaccess;
174                 while ( my ($line) = $rq->fetchrow ) {
175                     my $dbname = $info{dbname};
176                     if ( $line =~ m/^GRANT (.*?) ON `$dbname`\.\*/
177                         || index( $line, '*.*' ) > 0 )
178                     {
179                         $grantaccess = 1
180                           if (
181                             index( $line, 'ALL PRIVILEGES' ) > 0
182                             || (   ( index( $line, 'SELECT' ) > 0 )
183                                 && ( index( $line, 'INSERT' ) > 0 )
184                                 && ( index( $line, 'UPDATE' ) > 0 )
185                                 && ( index( $line, 'DELETE' ) > 0 )
186                                 && ( index( $line, 'CREATE' ) > 0 )
187                                 && ( index( $line, 'DROP' ) > 0 ) )
188                           );
189                     }
190                 }
191                 $template->param( "checkgrantaccess" => $grantaccess );
192
193                 if ( my $count = $installer->has_non_dynamic_row_format ) {
194                     $template->param( warnDbRowFormat => $count );
195                     $template->param( error => "InnoDB row format" );
196                 }
197
198             }    # End mysql connect check...
199
200             elsif ( $info{dbms} eq "Pg" ) {
201
202                 # Check if database has been created...
203                 my $rv = $dbh->do(
204 "SELECT * FROM pg_catalog.pg_database WHERE datname = \'$info{dbname}\';"
205                 );
206                 if ( $rv == 1 ) {
207                     $template->param( 'checkdatabasecreated' => 1 );
208                 }
209
210                 # Check if user has all necessary grants on this database...
211                 my $rq = $dbh->do(
212                     "SELECT u.usesuper
213             FROM pg_catalog.pg_user as u
214             WHERE u.usename = \'$info{user}\';"
215                 );
216                 if ( $rq == 1 ) {
217                     $template->param( "checkgrantaccess" => 1 );
218                 }
219             }    # End Pg connect check...
220         }
221         else {
222             $template->param( "error" => DBI::err, "message" => DBI::errstr );
223         }
224     }
225 }
226 elsif ( $step && $step == 3 ) {
227
228     # STEP 3 : database setup
229
230     if ( $op eq 'finished' ) {
231         # Remove the HandleError set at the beginning of the installer process
232         C4::Context->dbh->disconnect;
233
234         my $cookie_mgr = Koha::CookieManager->new;
235         # Remove cookie of the installer session
236         my $cookies = [];
237         if ( !ref $cookie ) {
238             push( @$cookies, $cookie );
239         }
240         $cookies = $cookie_mgr->replace_in_list( $cookies, $query->cookie(
241             -name     => 'CGISESSID',
242             -value    => '',
243             -HttpOnly => 1,
244             -secure => ( C4::Context->https_enabled() ? 1 : 0 ),
245             -sameSite => 'Lax',
246         ));
247
248         # we have finished, just redirect to mainpage.
249         print $query->redirect( -uri => "/cgi-bin/koha/mainpage.pl", -cookie => $cookies );
250         exit;
251     }
252     elsif ( $op eq 'cud-finish' ) {
253         $installer->set_version_syspref();
254
255         my $langchoice = $query->param('fwklanguage');
256         $langchoice = $query->cookie('KohaOpacLanguage') unless ($langchoice);
257         $langchoice =~ s/[^a-zA-Z_-]*//g;
258         $installer->set_languages_syspref($langchoice);
259
260 # Installation is finished.
261 # We just deny anybody access to install
262 # And we redirect people to mainpage.
263 # The installer will have to relogin since we do not pass cookie to redirection.
264     }
265
266     elsif ( $op eq 'cud-addframeworks' ) {
267
268         # 1ST install, 3rd sub-step : insert the SQL files the user has selected
269         my $langchoice = $query->param('fwklanguage');
270         $langchoice = $query->cookie('KohaOpacLanguage') unless ($langchoice);
271         $langchoice =~ s/[^a-zA-Z_-]*//g;
272
273         my ( $fwk_language, $list ) =
274           $installer->load_sql_in_order( $langchoice, $all_languages,
275             $query->multi_param('framework') );
276         $template->param(
277             "fwklanguage" => $fwk_language,
278             "list"        => $list
279         );
280         use Koha::SearchEngine::Elasticsearch;
281         Koha::SearchEngine::Elasticsearch->reset_elasticsearch_mappings;
282     }
283     elsif ( $op eq 'cud-selectframeworks' ) {
284 #
285 #
286 # 1ST install, 2nd sub-step : show the user the sql datas they can insert in the database.
287 #
288 #
289 # (note that the term "selectframeworks is not correct. The user can select various files, not only frameworks)
290
291 #Framework Selection
292 #sql data for import are supposed to be located in installer/data/<language>/<level>
293 # Where <language> is en|fr or any international abbreviation (provided language hash is updated... This will be a problem with internationlisation.)
294 # Where <level> is a category of requirement : required, recommended optional
295 # level should contain :
296 #   SQL File for import With a readable name.
297 #   txt File that explains what this SQL File is meant for.
298 # Could be VERY useful to have A Big file for a kind of library.
299 # But could also be useful to have some Authorised values data set prepared here.
300 # Framework Selection is achieved through checking boxes.
301         my $langchoice = $query->param('fwklanguage');
302         $langchoice = $query->cookie('KohaOpacLanguage') unless ($langchoice);
303         $langchoice =~ s/[^a-zA-Z_-]*//g;
304         my $marcflavour = $query->param('marcflavour');
305         if ($marcflavour) {
306             $installer->set_marcflavour_syspref($marcflavour);
307         }
308         $marcflavour = C4::Context->preference('marcflavour')
309           unless ($marcflavour);
310
311         #Insert into database the selected marcflavour
312         undef $/;
313         my ( $marc_defaulted_to_en, $fwklist ) =
314           $installer->marc_framework_sql_list( $langchoice, $marcflavour );
315         $template->param( 'en_marc_frameworks' => $marc_defaulted_to_en );
316         $template->param( "frameworksloop"     => $fwklist );
317         $template->param( "marcflavour"        => ucfirst($marcflavour) );
318
319         my ( $sample_defaulted_to_en, $levellist ) =
320           $installer->sample_data_sql_list($langchoice);
321         $template->param( "en_sample_data" => $sample_defaulted_to_en );
322         $template->param( "levelloop"      => $levellist );
323
324     }
325     elsif ( $op eq 'cud-choosemarc' ) {
326         #
327         #
328         # 1ST install, 2nd sub-step : show the user the marcflavour available.
329         #
330         #
331
332 #Choose Marc Flavour
333 #sql data are supposed to be located in installer/data/<dbms>/<language>/marcflavour/marcflavourname
334 # Where <dbms> is database type according to DBD syntax
335 # Where <language> is en|fr or any international abbreviation (provided language hash is updated... This will be a problem with internationlisation.)
336 # Where <level> is a category of requirement : required, recommended optional
337 # level should contain :
338 #   SQL File for import With a readable name.
339 #   txt File that explains what this SQL File is meant for.
340 # Could be VERY useful to have A Big file for a kind of library.
341 # But could also be useful to have some Authorised values data set prepared here.
342 # Marcflavour Selection is achieved through radiobuttons.
343         my $langchoice = $query->param('fwklanguage');
344
345         $langchoice = $query->cookie('KohaOpacLanguage') unless ($langchoice);
346         $langchoice =~ s/[^a-zA-Z_-]*//g;
347         my $dir =
348           C4::Context->config('intranetdir')
349           . "/installer/data/$info{dbms}/$langchoice/marcflavour";
350         my $dir_h;
351         unless ( opendir( $dir_h, $dir ) ) {
352             if ( $langchoice eq 'en' ) {
353                 warn "cannot open MARC frameworks directory $dir";
354             }
355             else {
356                 # if no translated MARC framework is available,
357                 # default to English
358                 $dir = C4::Context->config('intranetdir')
359                   . "/installer/data/$info{dbms}/en/marcflavour";
360                 opendir( $dir_h, $dir )
361                   or warn "cannot open English MARC frameworks directory $dir";
362             }
363         }
364         my @listdir = grep { !/^\./ && -d "$dir/$_" } readdir($dir_h);
365         closedir $dir_h;
366         my $marcflavour = C4::Context->preference("marcflavour");
367         my @flavourlist;
368         foreach my $marc (@listdir) {
369              my %cell=(
370                  "label"=> ucfirst($marc),
371                   "code"=>uc($marc),
372                "checked"=> defined($marcflavour) ? uc($marc) eq $marcflavour : 0);
373 #             $cell{"description"}= do { local $/ = undef; open INPUT "<$dir/$marc.txt"||"";<INPUT> };
374              push @flavourlist, \%cell;
375         }
376         $template->param( "flavourloop" => \@flavourlist );
377     }
378     elsif ( $op eq 'cud-importdatastructure' ) {
379         #
380         #
381         # 1st install, 1st "sub-step" : import kohastructure
382         #
383         #
384         my $error = $installer->load_db_schema();
385         $template->param(
386             "error" => $error,
387         );
388     }
389     elsif ( $op eq 'cud-updatestructure' ) {
390         #
391         # Not 1st install, the only sub-step : update database
392         #
393         #Do updatedatabase And report
394
395         if ( !defined $ENV{PERL5LIB} ) {
396             my $find = "C4/Context.pm";
397             my $path = $INC{$find};
398             $path =~ s/\Q$find\E//;
399             $ENV{PERL5LIB} = "$path:$path/installer";
400             warn "# plack? inserted PERL5LIB $ENV{PERL5LIB}\n";
401         }
402
403         my $now         = POSIX::strftime( "%Y-%m-%dT%H:%M:%S", localtime() );
404         my $logdir      = C4::Context->config('logdir');
405         my $dbversion   = C4::Context->preference('Version');
406         my $kohaversion = Koha::version;
407         $kohaversion =~ s/(.*\..*)\.(.*)\.(.*)/$1$2$3/;
408
409         my $filename_suffix = join '_', $now, $dbversion, $kohaversion;
410         my ( $logfilepath, $logfilepath_errors ) = (
411             chk_log( $logdir, "updatedatabase_$filename_suffix" ),
412             chk_log( $logdir, "updatedatabase-error_$filename_suffix" )
413         );
414
415         my $cmd = C4::Context->config("intranetdir")
416           . "/installer/data/$info{dbms}/updatedatabase.pl >> $logfilepath 2>> $logfilepath_errors";
417
418         system( $cmd );
419
420         my $fh;
421         open( $fh, "<:encoding(utf-8)", $logfilepath )
422           or die "Cannot open log file $logfilepath: $!";
423         my @report = <$fh>;
424         close $fh;
425         if (@report) {
426             $template->param( update_report =>
427                   [ map { { line => $_ =~ s/\t/&emsp;&emsp;/gr } } split( /\n/, join( '', @report ) ) ]
428             );
429             $template->param( has_update_succeeds => 1 );
430         }
431         else {
432             eval { `rm $logfilepath` };
433         }
434         open( $fh, "<:encoding(utf-8)", $logfilepath_errors )
435           or die "Cannot open log file $logfilepath_errors: $!";
436         @report = <$fh>;
437         close $fh;
438         my $update_errors;
439         if (@report) {
440             $template->param( update_errors =>
441                   [ map { { line => $_ } } split( /\n/, join( '', @report ) ) ]
442             );
443             $update_errors = 1;
444             $template->param( has_update_errors => 1 );
445             warn
446 "The following errors were returned while attempting to run the updatedatabase.pl script:\n";
447             foreach my $line (@report) { warn "$line\n"; }
448         }
449         else {
450             eval { `rm $logfilepath_errors` };
451         }
452
453         unless ( $update_errors ) {
454             my $db_entries = get_db_entries();
455             my $report = update( $db_entries );
456             my $atomic_update_files = get_atomic_updates;
457             my $atomic_update_report = run_atomic_updates( $atomic_update_files );
458
459             $template->param(
460                 success        => $report->{success},
461                 error          => $report->{error},
462                 atomic_updates => {
463                     success => $atomic_update_report->{success},
464                     error   => $atomic_update_report->{error}
465                 }
466             );
467         }
468     }
469     else {
470 #
471 # check whether it's a 1st install or an update
472 #
473 #Check if there are enough tables.
474 # Paul has cleaned up tables so reduced the count
475 #I put it there because it implied a data import if condition was not satisfied.
476         my $dbh = DBI->connect(
477                 "DBI:$info{dbms}:dbname=$info{dbname};host=$info{hostname}"
478                 . ( $info{port} ? ";port=$info{port}" : "" )
479                 . ( $info{tlsoptions} ? $info{tlsoptions} : "" ),
480                 $info{'user'}, $info{'password'}
481         );
482         my $rq;
483         if ( $info{dbms} eq 'mysql' ) { $rq = $dbh->prepare("SHOW TABLES"); }
484         elsif ( $info{dbms} eq 'Pg' ) {
485             $rq = $dbh->prepare(
486                 "SELECT *
487                 FROM information_schema.tables
488                 WHERE table_schema='public' and table_type='BASE TABLE';"
489             );
490         }
491         $rq->execute;
492         my $data = $rq->fetchall_arrayref( {} );
493         my $count = scalar(@$data);
494         #
495         # we don't have tables, propose DB import
496         #
497         if ( $count < 70 ) {
498             $template->param( "count" => $count, "proposeimport" => 1 );
499         }
500         else {
501            #
502            # we have tables, propose to select files to upload or updatedatabase
503            #
504             $template->param( "count" => $count, "default" => 1 );
505      #
506      # 1st part of step 3 : check if there is a databaseversion systempreference
507      # if there is, then we just need to upgrade
508      # if there is none, then we need to install the database
509      #
510             if ( C4::Context->preference('Version') ) {
511                 my $dbversion = C4::Context->preference('Version');
512                 $dbversion =~ /(.*)\.(..)(..)(...)/;
513                 $dbversion = "$1.$2.$3.$4";
514                 $template->param(
515                     "upgrading"   => 1,
516                     "dbversion"   => $dbversion,
517                     "kohaversion" => Koha::version(),
518                 );
519             }
520         }
521     }
522 }
523 else {
524
525     # LANGUAGE SELECTION page by default
526     # using opendir + language Hash
527     my $languages_loop = getTranslatedLanguages('intranet');
528     $template->param( installer_languages_loop => $languages_loop );
529     if ($dbh) {
530         my $rq =
531           $dbh->prepare(
532             "SELECT * from systempreferences WHERE variable='Version'");
533         if ( $rq->execute ) {
534             my ($version) = $rq->fetchrow;
535             if ($version) {
536                 print $query->redirect(
537                     "/cgi-bin/koha/installer/install.pl?step=3");
538                 exit;
539             }
540         }
541     }
542 }
543
544 if ($op) {
545     $op =~ s/cud-//;
546     $template->param( op => $op, $op => 1 );
547 }
548
549 output_html_with_http_headers $query, $cookie, $template->output;
550
551 sub chk_log {    #returns a logfile in $dir or - if that failed - in temp dir
552     my ( $dir, $name ) = @_;
553     my $fn = $dir . '/' . $name . '.log';
554     if ( !open my $fh, '>', $fn ) {
555         $name .= '_XXXX';
556         require File::Temp;
557         ( $fh, $fn ) =
558           File::Temp::tempfile( $name, TMPDIR => 1, SUFFIX => '.log' );
559
560         #if this should not work, let croak take over
561     }
562     return $fn;
563 }