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