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