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