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