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