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