bf9ccc42297a4a1f60d3e0b28235b414bee2b0d6
[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 # Installation is finished.
216 # We just deny anybody access to install
217 # And we redirect people to mainpage.
218 # The installer will have to relogin since we do not pass cookie to redirection.
219         $template->param( "$op" => 1 );
220     }
221
222     elsif ( $op && $op eq 'addframeworks' ) {
223
224         # 1ST install, 3rd sub-step : insert the SQL files the user has selected
225
226         my ( $fwk_language, $list ) =
227           $installer->load_sql_in_order( $all_languages,
228             $query->multi_param('framework') );
229         $template->param(
230             "fwklanguage" => $fwk_language,
231             "list"        => $list
232         );
233         use Koha::SearchEngine::Elasticsearch;
234         Koha::SearchEngine::Elasticsearch->reset_elasticsearch_mappings;
235         $template->param( "$op" => 1 );
236     }
237     elsif ( $op && $op eq 'selectframeworks' ) {
238 #
239 #
240 # 1ST install, 2nd sub-step : show the user the sql datas they can insert in the database.
241 #
242 #
243 # (note that the term "selectframeworks is not correct. The user can select various files, not only frameworks)
244
245 #Framework Selection
246 #sql data for import are supposed to be located in installer/data/<language>/<level>
247 # Where <language> is en|fr or any international abbreviation (provided language hash is updated... This will be a problem with internationlisation.)
248 # Where <level> is a category of requirement : required, recommended optional
249 # level should contain :
250 #   SQL File for import With a readable name.
251 #   txt File that explains what this SQL File is meant for.
252 # Could be VERY useful to have A Big file for a kind of library.
253 # But could also be useful to have some Authorised values data set prepared here.
254 # Framework Selection is achieved through checking boxes.
255         my $langchoice = $query->param('fwklanguage');
256         $langchoice = $query->cookie('KohaOpacLanguage') unless ($langchoice);
257         $langchoice =~ s/[^a-zA-Z_-]*//g;
258         my $marcflavour = $query->param('marcflavour');
259         if ($marcflavour) {
260             $installer->set_marcflavour_syspref($marcflavour);
261         }
262         $marcflavour = C4::Context->preference('marcflavour')
263           unless ($marcflavour);
264
265         #Insert into database the selected marcflavour
266         undef $/;
267         my ( $marc_defaulted_to_en, $fwklist ) =
268           $installer->marc_framework_sql_list( $langchoice, $marcflavour );
269         $template->param( 'en_marc_frameworks' => $marc_defaulted_to_en );
270         $template->param( "frameworksloop"     => $fwklist );
271         $template->param( "marcflavour"        => ucfirst($marcflavour) );
272
273         my ( $sample_defaulted_to_en, $levellist ) =
274           $installer->sample_data_sql_list($langchoice);
275         $template->param( "en_sample_data" => $sample_defaulted_to_en );
276         $template->param( "levelloop"      => $levellist );
277         $template->param( "$op"            => 1 );
278
279     }
280     elsif ( $op && $op eq 'choosemarc' ) {
281         #
282         #
283         # 1ST install, 2nd sub-step : show the user the marcflavour available.
284         #
285         #
286
287 #Choose Marc Flavour
288 #sql data are supposed to be located in installer/data/<dbms>/<language>/marcflavour/marcflavourname
289 # Where <dbms> is database type according to DBD syntax
290 # Where <language> is en|fr or any international abbreviation (provided language hash is updated... This will be a problem with internationlisation.)
291 # Where <level> is a category of requirement : required, recommended optional
292 # level should contain :
293 #   SQL File for import With a readable name.
294 #   txt File that explains what this SQL File is meant for.
295 # Could be VERY useful to have A Big file for a kind of library.
296 # But could also be useful to have some Authorised values data set prepared here.
297 # Marcflavour Selection is achieved through radiobuttons.
298         my $langchoice = $query->param('fwklanguage');
299
300         $langchoice = $query->cookie('KohaOpacLanguage') unless ($langchoice);
301         $langchoice =~ s/[^a-zA-Z_-]*//g;
302         my $dir =
303           C4::Context->config('intranetdir')
304           . "/installer/data/$info{dbms}/$langchoice/marcflavour";
305         unless ( opendir( MYDIR, $dir ) ) {
306             if ( $langchoice eq 'en' ) {
307                 warn "cannot open MARC frameworks directory $dir";
308             }
309             else {
310                 # if no translated MARC framework is available,
311                 # default to English
312                 $dir = C4::Context->config('intranetdir')
313                   . "/installer/data/$info{dbms}/en/marcflavour";
314                 opendir( MYDIR, $dir )
315                   or warn "cannot open English MARC frameworks directory $dir";
316             }
317         }
318         my @listdir = grep { !/^\./ && -d "$dir/$_" } readdir(MYDIR);
319         closedir MYDIR;
320         my $marcflavour = C4::Context->preference("marcflavour");
321         my @flavourlist;
322         foreach my $marc (@listdir) {
323              my %cell=(
324                  "label"=> ucfirst($marc),
325                   "code"=>uc($marc),
326                "checked"=> defined($marcflavour) ? uc($marc) eq $marcflavour : 0);
327 #             $cell{"description"}= do { local $/ = undef; open INPUT "<$dir/$marc.txt"||"";<INPUT> };
328              push @flavourlist, \%cell;
329         }
330         $template->param( "flavourloop" => \@flavourlist );
331         $template->param( "$op"         => 1 );
332     }
333     elsif ( $op && $op eq 'importdatastructure' ) {
334         #
335         #
336         # 1st install, 1st "sub-step" : import kohastructure
337         #
338         #
339         my $error = $installer->load_db_schema();
340         $template->param(
341             "error" => $error,
342             "$op"   => 1,
343         );
344     }
345     elsif ( $op && $op eq 'updatestructure' ) {
346         #
347         # Not 1st install, the only sub-step : update database
348         #
349         #Do updatedatabase And report
350
351         if ( !defined $ENV{PERL5LIB} ) {
352             my $find = "C4/Context.pm";
353             my $path = $INC{$find};
354             $path =~ s/\Q$find\E//;
355             $ENV{PERL5LIB} = "$path:$path/installer";
356             warn "# plack? inserted PERL5LIB $ENV{PERL5LIB}\n";
357         }
358
359         my $now         = POSIX::strftime( "%Y-%m-%dT%H:%M:%S", localtime() );
360         my $logdir      = C4::Context->config('logdir');
361         my $dbversion   = C4::Context->preference('Version');
362         my $kohaversion = Koha::version;
363         $kohaversion =~ s/(.*\..*)\.(.*)\.(.*)/$1$2$3/;
364
365         my $filename_suffix = join '_', $now, $dbversion, $kohaversion;
366         my ( $logfilepath, $logfilepath_errors ) = (
367             chk_log( $logdir, "updatedatabase_$filename_suffix" ),
368             chk_log( $logdir, "updatedatabase-error_$filename_suffix" )
369         );
370
371         my $cmd = C4::Context->config("intranetdir")
372           . "/installer/data/$info{dbms}/updatedatabase.pl >> $logfilepath 2>> $logfilepath_errors";
373
374         system($cmd );
375
376         my $fh;
377         open( $fh, "<:encoding(utf-8)", $logfilepath )
378           or die "Cannot open log file $logfilepath: $!";
379         my @report = <$fh>;
380         close $fh;
381         if (@report) {
382             $template->param( update_report =>
383                   [ map { { line => $_ } } split( /\n/, join( '', @report ) ) ]
384             );
385             $template->param( has_update_succeeds => 1 );
386         }
387         else {
388             eval { `rm $logfilepath` };
389         }
390         open( $fh, "<:encoding(utf-8)", $logfilepath_errors )
391           or die "Cannot open log file $logfilepath_errors: $!";
392         @report = <$fh>;
393         close $fh;
394         if (@report) {
395             $template->param( update_errors =>
396                   [ map { { line => $_ } } split( /\n/, join( '', @report ) ) ]
397             );
398             $template->param( has_update_errors => 1 );
399             warn
400 "The following errors were returned while attempting to run the updatedatabase.pl script:\n";
401             foreach my $line (@report) { warn "$line\n"; }
402         }
403         else {
404             eval { `rm $logfilepath_errors` };
405         }
406         $template->param( $op => 1 );
407     }
408     else {
409 #
410 # check whether it's a 1st install or an update
411 #
412 #Check if there are enough tables.
413 # Paul has cleaned up tables so reduced the count
414 #I put it there because it implied a data import if condition was not satisfied.
415         my $dbh = DBI->connect(
416                 "DBI:$info{dbms}:dbname=$info{dbname};host=$info{hostname}"
417                 . ( $info{port} ? ";port=$info{port}" : "" )
418                 . ( $info{tlsoptions} ? $info{tlsoptions} : "" ),
419                 $info{'user'}, $info{'password'}
420         );
421         my $rq;
422         if ( $info{dbms} eq 'mysql' ) { $rq = $dbh->prepare("SHOW TABLES"); }
423         elsif ( $info{dbms} eq 'Pg' ) {
424             $rq = $dbh->prepare(
425                 "SELECT *
426                 FROM information_schema.tables
427                 WHERE table_schema='public' and table_type='BASE TABLE';"
428             );
429         }
430         $rq->execute;
431         my $data = $rq->fetchall_arrayref( {} );
432         my $count = scalar(@$data);
433         #
434         # we don't have tables, propose DB import
435         #
436         if ( $count < 70 ) {
437             $template->param( "count" => $count, "proposeimport" => 1 );
438         }
439         else {
440            #
441            # we have tables, propose to select files to upload or updatedatabase
442            #
443             $template->param( "count" => $count, "default" => 1 );
444      #
445      # 1st part of step 3 : check if there is a databaseversion systempreference
446      # if there is, then we just need to upgrade
447      # if there is none, then we need to install the database
448      #
449             if ( C4::Context->preference('Version') ) {
450                 my $dbversion = C4::Context->preference('Version');
451                 $dbversion =~ /(.*)\.(..)(..)(...)/;
452                 $dbversion = "$1.$2.$3.$4";
453                 $template->param(
454                     "upgrading"   => 1,
455                     "dbversion"   => $dbversion,
456                     "kohaversion" => Koha::version(),
457                 );
458             }
459         }
460     }
461 }
462 else {
463
464     # LANGUAGE SELECTION page by default
465     # using opendir + language Hash
466     my $languages_loop = getTranslatedLanguages('intranet');
467     $template->param( installer_languages_loop => $languages_loop );
468     if ($dbh) {
469         my $rq =
470           $dbh->prepare(
471             "SELECT * from systempreferences WHERE variable='Version'");
472         if ( $rq->execute ) {
473             my ($version) = $rq->fetchrow;
474             if ($version) {
475                 print $query->redirect(
476                     "/cgi-bin/koha/installer/install.pl?step=3");
477                 exit;
478             }
479         }
480     }
481 }
482 output_html_with_http_headers $query, $cookie, $template->output;
483
484 sub chk_log {    #returns a logfile in $dir or - if that failed - in temp dir
485     my ( $dir, $name ) = @_;
486     my $fn = $dir . '/' . $name . '.log';
487     if ( !open my $fh, '>', $fn ) {
488         $name .= '_XXXX';
489         require File::Temp;
490         ( $fh, $fn ) =
491           File::Temp::tempfile( $name, TMPDIR => 1, SUFFIX => '.log' );
492
493         #if this should not work, let croak take over
494     }
495     return $fn;
496 }