Bug 21908: Add biblio_metadata to rebuild_zebra.pl tables
[koha.git] / installer / install.pl
blob459606d4cf49de07c9d1226644ece202181a1347
1 #!/usr/bin/perl
3 # This file is part of Koha.
5 # Copyright (C) YEAR YOURNAME-OR-YOUREMPLOYER
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.
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.
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>.
20 use strict;
21 use warnings;
22 use diagnostics;
24 use C4::InstallAuth;
25 use CGI qw ( -utf8 );
26 use POSIX qw(strftime);
28 use C4::Context;
29 use C4::Output;
30 use C4::Templates;
31 use C4::Languages qw(getAllLanguages getTranslatedLanguages);
32 use C4::Installer;
34 use Koha;
36 my $query = new CGI;
37 my $step = $query->param('step');
39 my $language = $query->param('language');
40 my ( $template, $loggedinuser, $cookie );
42 my $all_languages = getAllLanguages();
44 if ( defined($language) ) {
45 C4::Templates::setlanguagecookie( $query, $language, "install.pl?step=1" );
47 ( $template, $loggedinuser, $cookie ) = get_template_and_user(
49 template_name => "installer/step" . ( $step ? $step : 1 ) . ".tt",
50 query => $query,
51 type => "intranet",
52 authnotrequired => 0,
53 debug => 1,
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"
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}." "
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'}
85 if ( $step && $step == 1 ) {
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
96 unless ( $] >= 5.010000 ) { # Bug 7375
97 $template->param( problems => 1, perlversion => 1, checkmodule => 0 );
98 $checkmodule = 0;
101 my $perl_modules = C4::Installer::PerlModules->new;
102 $perl_modules->versions_info;
104 my $modules = $perl_modules->get_attr('missing_pm');
105 if ( scalar(@$modules) ) {
106 my @components = ();
107 foreach (@$modules) {
108 my ( $module, $stats ) = each %$_;
109 $checkmodule = 0 if $stats->{'required'};
110 push(
111 @components,
113 name => $module,
114 version => $stats->{'min_ver'},
115 require => $stats->{'required'},
116 usage => $stats->{'usage'},
120 @components = sort { $a->{'name'} cmp $b->{'name'} } @components;
121 $template->param(
122 missing_modules => \@components,
123 checkmodule => $checkmodule,
124 op => $op
128 elsif ( $step && $step == 2 ) {
130 #STEP 2 Check Database connection and access
132 $template->param(%info);
133 my $checkdb = $query->param("checkdb");
134 $template->param( 'dbconnection' => $checkdb );
135 if ($checkdb) {
136 if ($dbh) {
138 # Can connect to the mysql
139 $template->param( "checkdatabaseaccess" => 1 );
140 if ( $info{dbms} eq "mysql" ) {
142 #Check if database created
143 my $rv = $dbh->do("SHOW DATABASES LIKE \'$info{dbname}\'");
144 if ( $rv == 1 ) {
145 $template->param( 'checkdatabasecreated' => 1 );
148 # Check if user have all necessary grants on this database.
149 # CURRENT_USER is ANSI SQL, and doesn't require mysql table
150 # privileges, making the % check pointless, since they
151 # couldn't even check GRANTS if they couldn't connect.
152 my $rq = $dbh->prepare('SHOW GRANTS FOR CURRENT_USER');
153 $rq->execute;
154 my $grantaccess;
155 while ( my ($line) = $rq->fetchrow ) {
156 my $dbname = $info{dbname};
157 if ( $line =~ m/^GRANT (.*?) ON `$dbname`\.\*/
158 || index( $line, '*.*' ) > 0 )
160 $grantaccess = 1
161 if (
162 index( $line, 'ALL PRIVILEGES' ) > 0
163 || ( ( index( $line, 'SELECT' ) > 0 )
164 && ( index( $line, 'INSERT' ) > 0 )
165 && ( index( $line, 'UPDATE' ) > 0 )
166 && ( index( $line, 'DELETE' ) > 0 )
167 && ( index( $line, 'CREATE' ) > 0 )
168 && ( index( $line, 'DROP' ) > 0 ) )
172 $template->param( "checkgrantaccess" => $grantaccess );
173 } # End mysql connect check...
175 elsif ( $info{dbms} eq "Pg" ) {
177 # Check if database has been created...
178 my $rv = $dbh->do(
179 "SELECT * FROM pg_catalog.pg_database WHERE datname = \'$info{dbname}\';"
181 if ( $rv == 1 ) {
182 $template->param( 'checkdatabasecreated' => 1 );
185 # Check if user has all necessary grants on this database...
186 my $rq = $dbh->do(
187 "SELECT u.usesuper
188 FROM pg_catalog.pg_user as u
189 WHERE u.usename = \'$info{user}\';"
191 if ( $rq == 1 ) {
192 $template->param( "checkgrantaccess" => 1 );
194 } # End Pg connect check...
196 else {
197 $template->param( "error" => DBI::err, "message" => DBI::errstr );
201 elsif ( $step && $step == 3 ) {
203 # STEP 3 : database setup
205 my $op = $query->param('op');
206 if ( $op && $op eq 'finished' ) {
208 # we have finished, just redirect to mainpage.
210 print $query->redirect("/cgi-bin/koha/mainpage.pl");
211 exit;
213 elsif ( $op && $op eq 'finish' ) {
214 $installer->set_version_syspref();
216 # Installation is finished.
217 # We just deny anybody access to install
218 # And we redirect people to mainpage.
219 # The installer will have to relogin since we do not pass cookie to redirection.
220 $template->param( "$op" => 1 );
223 elsif ( $op && $op eq 'addframeworks' ) {
225 # 1ST install, 3rd sub-step : insert the SQL files the user has selected
227 my ( $fwk_language, $list ) =
228 $installer->load_sql_in_order( $all_languages,
229 $query->multi_param('framework') );
230 $template->param(
231 "fwklanguage" => $fwk_language,
232 "list" => $list
234 use Koha::SearchEngine::Elasticsearch;
235 Koha::SearchEngine::Elasticsearch->reset_elasticsearch_mappings;
236 $template->param( "$op" => 1 );
238 elsif ( $op && $op eq 'selectframeworks' ) {
241 # 1ST install, 2nd sub-step : show the user the sql datas they can insert in the database.
244 # (note that the term "selectframeworks is not correct. The user can select various files, not only frameworks)
246 #Framework Selection
247 #sql data for import are supposed to be located in installer/data/<language>/<level>
248 # Where <language> is en|fr or any international abbreviation (provided language hash is updated... This will be a problem with internationlisation.)
249 # Where <level> is a category of requirement : required, recommended optional
250 # level should contain :
251 # SQL File for import With a readable name.
252 # txt File that explains what this SQL File is meant for.
253 # Could be VERY useful to have A Big file for a kind of library.
254 # But could also be useful to have some Authorised values data set prepared here.
255 # Framework Selection is achieved through checking boxes.
256 my $langchoice = $query->param('fwklanguage');
257 $langchoice = $query->cookie('KohaOpacLanguage') unless ($langchoice);
258 $langchoice =~ s/[^a-zA-Z_-]*//g;
259 my $marcflavour = $query->param('marcflavour');
260 if ($marcflavour) {
261 $installer->set_marcflavour_syspref($marcflavour);
263 $marcflavour = C4::Context->preference('marcflavour')
264 unless ($marcflavour);
266 #Insert into database the selected marcflavour
267 undef $/;
268 my ( $marc_defaulted_to_en, $fwklist ) =
269 $installer->marc_framework_sql_list( $langchoice, $marcflavour );
270 $template->param( 'en_marc_frameworks' => $marc_defaulted_to_en );
271 $template->param( "frameworksloop" => $fwklist );
272 $template->param( "marcflavour" => ucfirst($marcflavour) );
274 my ( $sample_defaulted_to_en, $levellist ) =
275 $installer->sample_data_sql_list($langchoice);
276 $template->param( "en_sample_data" => $sample_defaulted_to_en );
277 $template->param( "levelloop" => $levellist );
278 $template->param( "$op" => 1 );
281 elsif ( $op && $op eq 'choosemarc' ) {
284 # 1ST install, 2nd sub-step : show the user the marcflavour available.
288 #Choose Marc Flavour
289 #sql data are supposed to be located in installer/data/<dbms>/<language>/marcflavour/marcflavourname
290 # Where <dbms> is database type according to DBD syntax
291 # Where <language> is en|fr or any international abbreviation (provided language hash is updated... This will be a problem with internationlisation.)
292 # Where <level> is a category of requirement : required, recommended optional
293 # level should contain :
294 # SQL File for import With a readable name.
295 # txt File that explains what this SQL File is meant for.
296 # Could be VERY useful to have A Big file for a kind of library.
297 # But could also be useful to have some Authorised values data set prepared here.
298 # Marcflavour Selection is achieved through radiobuttons.
299 my $langchoice = $query->param('fwklanguage');
301 $langchoice = $query->cookie('KohaOpacLanguage') unless ($langchoice);
302 $langchoice =~ s/[^a-zA-Z_-]*//g;
303 my $dir =
304 C4::Context->config('intranetdir')
305 . "/installer/data/$info{dbms}/$langchoice/marcflavour";
306 unless ( opendir( MYDIR, $dir ) ) {
307 if ( $langchoice eq 'en' ) {
308 warn "cannot open MARC frameworks directory $dir";
310 else {
311 # if no translated MARC framework is available,
312 # default to English
313 $dir = C4::Context->config('intranetdir')
314 . "/installer/data/$info{dbms}/en/marcflavour";
315 opendir( MYDIR, $dir )
316 or warn "cannot open English MARC frameworks directory $dir";
319 my @listdir = grep { !/^\./ && -d "$dir/$_" } readdir(MYDIR);
320 closedir MYDIR;
321 my $marcflavour = C4::Context->preference("marcflavour");
322 my @flavourlist;
323 foreach my $marc (@listdir) {
324 my %cell=(
325 "label"=> ucfirst($marc),
326 "code"=>uc($marc),
327 "checked"=> defined($marcflavour) ? uc($marc) eq $marcflavour : 0);
328 # $cell{"description"}= do { local $/ = undef; open INPUT "<$dir/$marc.txt"||"";<INPUT> };
329 push @flavourlist, \%cell;
331 $template->param( "flavourloop" => \@flavourlist );
332 $template->param( "$op" => 1 );
334 elsif ( $op && $op eq 'importdatastructure' ) {
337 # 1st install, 1st "sub-step" : import kohastructure
340 my $error = $installer->load_db_schema();
341 $template->param(
342 "error" => $error,
343 "$op" => 1,
346 elsif ( $op && $op eq 'updatestructure' ) {
348 # Not 1st install, the only sub-step : update database
350 #Do updatedatabase And report
352 if ( !defined $ENV{PERL5LIB} ) {
353 my $find = "C4/Context.pm";
354 my $path = $INC{$find};
355 $path =~ s/\Q$find\E//;
356 $ENV{PERL5LIB} = "$path:$path/installer";
357 warn "# plack? inserted PERL5LIB $ENV{PERL5LIB}\n";
360 my $now = POSIX::strftime( "%Y-%m-%dT%H:%M:%S", localtime() );
361 my $logdir = C4::Context->config('logdir');
362 my $dbversion = C4::Context->preference('Version');
363 my $kohaversion = Koha::version;
364 $kohaversion =~ s/(.*\..*)\.(.*)\.(.*)/$1$2$3/;
366 my $filename_suffix = join '_', $now, $dbversion, $kohaversion;
367 my ( $logfilepath, $logfilepath_errors ) = (
368 chk_log( $logdir, "updatedatabase_$filename_suffix" ),
369 chk_log( $logdir, "updatedatabase-error_$filename_suffix" )
372 my $cmd = C4::Context->config("intranetdir")
373 . "/installer/data/$info{dbms}/updatedatabase.pl >> $logfilepath 2>> $logfilepath_errors";
375 system($cmd );
377 my $fh;
378 open( $fh, "<:encoding(utf-8)", $logfilepath )
379 or die "Cannot open log file $logfilepath: $!";
380 my @report = <$fh>;
381 close $fh;
382 if (@report) {
383 $template->param( update_report =>
384 [ map { { line => $_ } } split( /\n/, join( '', @report ) ) ]
386 $template->param( has_update_succeeds => 1 );
388 else {
389 eval { `rm $logfilepath` };
391 open( $fh, "<:encoding(utf-8)", $logfilepath_errors )
392 or die "Cannot open log file $logfilepath_errors: $!";
393 @report = <$fh>;
394 close $fh;
395 if (@report) {
396 $template->param( update_errors =>
397 [ map { { line => $_ } } split( /\n/, join( '', @report ) ) ]
399 $template->param( has_update_errors => 1 );
400 warn
401 "The following errors were returned while attempting to run the updatedatabase.pl script:\n";
402 foreach my $line (@report) { warn "$line\n"; }
404 else {
405 eval { `rm $logfilepath_errors` };
407 $template->param( $op => 1 );
409 else {
411 # check whether it's a 1st install or an update
413 #Check if there are enough tables.
414 # Paul has cleaned up tables so reduced the count
415 #I put it there because it implied a data import if condition was not satisfied.
416 my $dbh = DBI->connect(
417 "DBI:$info{dbms}:dbname=$info{dbname};host=$info{hostname}"
418 . ( $info{port} ? ";port=$info{port}" : "" )
419 . ( $info{tlsoptions} ? $info{tlsoptions} : "" ),
420 $info{'user'}, $info{'password'}
422 my $rq;
423 if ( $info{dbms} eq 'mysql' ) { $rq = $dbh->prepare("SHOW TABLES"); }
424 elsif ( $info{dbms} eq 'Pg' ) {
425 $rq = $dbh->prepare(
426 "SELECT *
427 FROM information_schema.tables
428 WHERE table_schema='public' and table_type='BASE TABLE';"
431 $rq->execute;
432 my $data = $rq->fetchall_arrayref( {} );
433 my $count = scalar(@$data);
435 # we don't have tables, propose DB import
437 if ( $count < 70 ) {
438 $template->param( "count" => $count, "proposeimport" => 1 );
440 else {
442 # we have tables, propose to select files to upload or updatedatabase
444 $template->param( "count" => $count, "default" => 1 );
446 # 1st part of step 3 : check if there is a databaseversion systempreference
447 # if there is, then we just need to upgrade
448 # if there is none, then we need to install the database
450 if ( C4::Context->preference('Version') ) {
451 my $dbversion = C4::Context->preference('Version');
452 $dbversion =~ /(.*)\.(..)(..)(...)/;
453 $dbversion = "$1.$2.$3.$4";
454 $template->param(
455 "upgrading" => 1,
456 "dbversion" => $dbversion,
457 "kohaversion" => Koha::version(),
463 else {
465 # LANGUAGE SELECTION page by default
466 # using opendir + language Hash
467 my $languages_loop = getTranslatedLanguages('intranet');
468 $template->param( installer_languages_loop => $languages_loop );
469 if ($dbh) {
470 my $rq =
471 $dbh->prepare(
472 "SELECT * from systempreferences WHERE variable='Version'");
473 if ( $rq->execute ) {
474 my ($version) = $rq->fetchrow;
475 if ($version) {
476 print $query->redirect(
477 "/cgi-bin/koha/installer/install.pl?step=3");
478 exit;
483 output_html_with_http_headers $query, $cookie, $template->output;
485 sub chk_log { #returns a logfile in $dir or - if that failed - in temp dir
486 my ( $dir, $name ) = @_;
487 my $fn = $dir . '/' . $name . '.log';
488 if ( !open my $fh, '>', $fn ) {
489 $name .= '_XXXX';
490 require File::Temp;
491 ( $fh, $fn ) =
492 File::Temp::tempfile( $name, TMPDIR => 1, SUFFIX => '.log' );
494 #if this should not work, let croak take over
496 return $fn;