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