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>.
25 use POSIX qw(strftime);
30 use C4::Languages qw(getAllLanguages getTranslatedLanguages);
36 my $step = $query->param('step');
38 my $language = $query->param('language');
39 my ( $template, $loggedinuser, $cookie );
41 my $all_languages = getAllLanguages();
43 if ( defined($language) ) {
44 C4::Templates::setlanguagecookie( $query, $language, "install.pl?step=1" );
46 ( $template, $loggedinuser, $cookie ) = get_template_and_user(
48 template_name => "installer/step" . ( $step ? $step : 1 ) . ".tt",
55 my $installer = C4::Installer->new();
57 $info{'dbname'} = C4::Context->config("database");
59 C4::Context->config("db_scheme")
60 ? C4::Context->config("db_scheme")
63 $info{'hostname'} = C4::Context->config("hostname");
64 $info{'port'} = C4::Context->config("port");
65 $info{'user'} = C4::Context->config("user");
66 $info{'password'} = C4::Context->config("pass");
67 $info{'tls'} = C4::Context->config("tls");
68 if ($info{'tls'} && $info{'tls'} eq 'yes'){
69 $info{'ca'} = C4::Context->config('ca');
70 $info{'cert'} = C4::Context->config('cert');
71 $info{'key'} = C4::Context->config('key');
72 $info{'tlsoptions'} = ";mysql_ssl=1;mysql_ssl_client_key=".$info{key}.";mysql_ssl_client_cert=".$info{cert}.";mysql_ssl_ca_file=".$info{ca};
73 $info{'tlscmdline'} = " --ssl-cert ". $info{cert} . " --ssl-key " . $info{key} . " --ssl-ca ".$info{ca}." "
76 my $dbh = DBI->connect(
77 "DBI:$info{dbms}:dbname=$info{dbname};host=$info{hostname}"
78 . ( $info{port} ? ";port=$info{port}" : "" )
79 . ( $info{tlsoptions} ? $info{tlsoptions} : "" ),
80 $info{'user'}, $info{'password'}
83 if ( $step && $step == 1 ) {
85 #First Step (for both fresh installations and upgrades)
86 #Checking ALL perl Modules and services needed are installed.
87 #Whenever there is an error, adding a report to the page
88 my $op = $query->param('op') || 'noop';
89 $template->param( language => 1 );
91 $template->param( 'checkmodule' => 1 )
92 ; # we start with the assumption that there are no problems and set this to 0 if there are
94 unless ( $] >= 5.010000 ) { # Bug 7375
95 $template->param( problems => 1, perlversion => 1, checkmodule => 0 );
99 my $perl_modules = C4::Installer::PerlModules->new;
100 $perl_modules->versions_info;
102 my $modules = $perl_modules->get_attr('missing_pm');
103 if ( scalar(@$modules) ) {
105 foreach (@$modules) {
106 my ( $module, $stats ) = each %$_;
107 $checkmodule = 0 if $stats->{'required'};
112 version => $stats->{'min_ver'},
113 require => $stats->{'required'},
114 usage => $stats->{'usage'},
118 @components = sort { $a->{'name'} cmp $b->{'name'} } @components;
120 missing_modules => \@components,
121 checkmodule => $checkmodule,
126 elsif ( $step && $step == 2 ) {
128 #STEP 2 Check Database connection and access
130 $template->param(%info);
131 my $checkdb = $query->param("checkdb");
132 $template->param( 'dbconnection' => $checkdb );
136 # Can connect to the mysql
137 $template->param( "checkdatabaseaccess" => 1 );
138 if ( $info{dbms} eq "mysql" ) {
140 #Check if database created
141 my $rv = $dbh->do("SHOW DATABASES LIKE \'$info{dbname}\'");
143 $template->param( 'checkdatabasecreated' => 1 );
146 # Check if user have all necessary grants on this database.
147 # CURRENT_USER is ANSI SQL, and doesn't require mysql table
148 # privileges, making the % check pointless, since they
149 # couldn't even check GRANTS if they couldn't connect.
150 my $rq = $dbh->prepare('SHOW GRANTS FOR CURRENT_USER');
153 while ( my ($line) = $rq->fetchrow ) {
154 my $dbname = $info{dbname};
155 if ( $line =~ m/^GRANT (.*?) ON `$dbname`\.\*/
156 || index( $line, '*.*' ) > 0 )
160 index( $line, 'ALL PRIVILEGES' ) > 0
161 || ( ( index( $line, 'SELECT' ) > 0 )
162 && ( index( $line, 'INSERT' ) > 0 )
163 && ( index( $line, 'UPDATE' ) > 0 )
164 && ( index( $line, 'DELETE' ) > 0 )
165 && ( index( $line, 'CREATE' ) > 0 )
166 && ( index( $line, 'DROP' ) > 0 ) )
170 $template->param( "checkgrantaccess" => $grantaccess );
171 } # End mysql connect check...
173 elsif ( $info{dbms} eq "Pg" ) {
175 # Check if database has been created...
177 "SELECT * FROM pg_catalog.pg_database WHERE datname = \'$info{dbname}\';"
180 $template->param( 'checkdatabasecreated' => 1 );
183 # Check if user has all necessary grants on this database...
186 FROM pg_catalog.pg_user as u
187 WHERE u.usename = \'$info{user}\';"
190 $template->param( "checkgrantaccess" => 1 );
192 } # End Pg connect check...
195 $template->param( "error" => DBI::err, "message" => DBI::errstr );
199 elsif ( $step && $step == 3 ) {
201 # STEP 3 : database setup
203 my $op = $query->param('op');
204 if ( $op && $op eq 'finished' ) {
206 # we have finished, just redirect to mainpage.
208 print $query->redirect("/cgi-bin/koha/mainpage.pl");
211 elsif ( $op && $op eq 'finish' ) {
212 $installer->set_version_syspref();
214 my $langchoice = $query->param('fwklanguage');
215 $langchoice = $query->cookie('KohaOpacLanguage') unless ($langchoice);
216 $langchoice =~ s/[^a-zA-Z_-]*//g;
217 $installer->set_languages_syspref($langchoice);
219 # Installation is finished.
220 # We just deny anybody access to install
221 # And we redirect people to mainpage.
222 # The installer will have to relogin since we do not pass cookie to redirection.
223 $template->param( "$op" => 1 );
226 elsif ( $op && $op eq 'addframeworks' ) {
228 # 1ST install, 3rd sub-step : insert the SQL files the user has selected
230 my ( $fwk_language, $list ) =
231 $installer->load_sql_in_order( $all_languages,
232 $query->multi_param('framework') );
234 "fwklanguage" => $fwk_language,
237 use Koha::SearchEngine::Elasticsearch;
238 Koha::SearchEngine::Elasticsearch->reset_elasticsearch_mappings;
239 $template->param( "$op" => 1 );
241 elsif ( $op && $op eq 'selectframeworks' ) {
244 # 1ST install, 2nd sub-step : show the user the sql datas they can insert in the database.
247 # (note that the term "selectframeworks is not correct. The user can select various files, not only frameworks)
250 #sql data for import are supposed to be located in installer/data/<language>/<level>
251 # Where <language> is en|fr or any international abbreviation (provided language hash is updated... This will be a problem with internationlisation.)
252 # Where <level> is a category of requirement : required, recommended optional
253 # level should contain :
254 # SQL File for import With a readable name.
255 # txt File that explains what this SQL File is meant for.
256 # Could be VERY useful to have A Big file for a kind of library.
257 # But could also be useful to have some Authorised values data set prepared here.
258 # Framework Selection is achieved through checking boxes.
259 my $langchoice = $query->param('fwklanguage');
260 $langchoice = $query->cookie('KohaOpacLanguage') unless ($langchoice);
261 $langchoice =~ s/[^a-zA-Z_-]*//g;
262 my $marcflavour = $query->param('marcflavour');
264 $installer->set_marcflavour_syspref($marcflavour);
266 $marcflavour = C4::Context->preference('marcflavour')
267 unless ($marcflavour);
269 #Insert into database the selected marcflavour
271 my ( $marc_defaulted_to_en, $fwklist ) =
272 $installer->marc_framework_sql_list( $langchoice, $marcflavour );
273 $template->param( 'en_marc_frameworks' => $marc_defaulted_to_en );
274 $template->param( "frameworksloop" => $fwklist );
275 $template->param( "marcflavour" => ucfirst($marcflavour) );
277 my ( $sample_defaulted_to_en, $levellist ) =
278 $installer->sample_data_sql_list($langchoice);
279 $template->param( "en_sample_data" => $sample_defaulted_to_en );
280 $template->param( "levelloop" => $levellist );
281 $template->param( "$op" => 1 );
284 elsif ( $op && $op eq 'choosemarc' ) {
287 # 1ST install, 2nd sub-step : show the user the marcflavour available.
292 #sql data are supposed to be located in installer/data/<dbms>/<language>/marcflavour/marcflavourname
293 # Where <dbms> is database type according to DBD syntax
294 # Where <language> is en|fr or any international abbreviation (provided language hash is updated... This will be a problem with internationlisation.)
295 # Where <level> is a category of requirement : required, recommended optional
296 # level should contain :
297 # SQL File for import With a readable name.
298 # txt File that explains what this SQL File is meant for.
299 # Could be VERY useful to have A Big file for a kind of library.
300 # But could also be useful to have some Authorised values data set prepared here.
301 # Marcflavour Selection is achieved through radiobuttons.
302 my $langchoice = $query->param('fwklanguage');
304 $langchoice = $query->cookie('KohaOpacLanguage') unless ($langchoice);
305 $langchoice =~ s/[^a-zA-Z_-]*//g;
307 C4::Context->config('intranetdir')
308 . "/installer/data/$info{dbms}/$langchoice/marcflavour";
309 unless ( opendir( MYDIR, $dir ) ) {
310 if ( $langchoice eq 'en' ) {
311 warn "cannot open MARC frameworks directory $dir";
314 # if no translated MARC framework is available,
316 $dir = C4::Context->config('intranetdir')
317 . "/installer/data/$info{dbms}/en/marcflavour";
318 opendir( MYDIR, $dir )
319 or warn "cannot open English MARC frameworks directory $dir";
322 my @listdir = grep { !/^\./ && -d "$dir/$_" } readdir(MYDIR);
324 my $marcflavour = C4::Context->preference("marcflavour");
326 foreach my $marc (@listdir) {
328 "label"=> ucfirst($marc),
330 "checked"=> defined($marcflavour) ? uc($marc) eq $marcflavour : 0);
331 # $cell{"description"}= do { local $/ = undef; open INPUT "<$dir/$marc.txt"||"";<INPUT> };
332 push @flavourlist, \%cell;
334 $template->param( "flavourloop" => \@flavourlist );
335 $template->param( "$op" => 1 );
337 elsif ( $op && $op eq 'importdatastructure' ) {
340 # 1st install, 1st "sub-step" : import kohastructure
343 my $error = $installer->load_db_schema();
349 elsif ( $op && $op eq 'updatestructure' ) {
351 # Not 1st install, the only sub-step : update database
353 #Do updatedatabase And report
355 if ( !defined $ENV{PERL5LIB} ) {
356 my $find = "C4/Context.pm";
357 my $path = $INC{$find};
358 $path =~ s/\Q$find\E//;
359 $ENV{PERL5LIB} = "$path:$path/installer";
360 warn "# plack? inserted PERL5LIB $ENV{PERL5LIB}\n";
363 my $now = POSIX::strftime( "%Y-%m-%dT%H:%M:%S", localtime() );
364 my $logdir = C4::Context->config('logdir');
365 my $dbversion = C4::Context->preference('Version');
366 my $kohaversion = Koha::version;
367 $kohaversion =~ s/(.*\..*)\.(.*)\.(.*)/$1$2$3/;
369 my $filename_suffix = join '_', $now, $dbversion, $kohaversion;
370 my ( $logfilepath, $logfilepath_errors ) = (
371 chk_log( $logdir, "updatedatabase_$filename_suffix" ),
372 chk_log( $logdir, "updatedatabase-error_$filename_suffix" )
375 my $cmd = C4::Context->config("intranetdir")
376 . "/installer/data/$info{dbms}/updatedatabase.pl >> $logfilepath 2>> $logfilepath_errors";
381 open( $fh, "<:encoding(utf-8)", $logfilepath )
382 or die "Cannot open log file $logfilepath: $!";
386 $template->param( update_report =>
387 [ map { { line => $_ } } split( /\n/, join( '', @report ) ) ]
389 $template->param( has_update_succeeds => 1 );
392 eval { `rm $logfilepath` };
394 open( $fh, "<:encoding(utf-8)", $logfilepath_errors )
395 or die "Cannot open log file $logfilepath_errors: $!";
399 $template->param( update_errors =>
400 [ map { { line => $_ } } split( /\n/, join( '', @report ) ) ]
402 $template->param( has_update_errors => 1 );
404 "The following errors were returned while attempting to run the updatedatabase.pl script:\n";
405 foreach my $line (@report) { warn "$line\n"; }
408 eval { `rm $logfilepath_errors` };
410 $template->param( $op => 1 );
414 # check whether it's a 1st install or an update
416 #Check if there are enough tables.
417 # Paul has cleaned up tables so reduced the count
418 #I put it there because it implied a data import if condition was not satisfied.
419 my $dbh = DBI->connect(
420 "DBI:$info{dbms}:dbname=$info{dbname};host=$info{hostname}"
421 . ( $info{port} ? ";port=$info{port}" : "" )
422 . ( $info{tlsoptions} ? $info{tlsoptions} : "" ),
423 $info{'user'}, $info{'password'}
426 if ( $info{dbms} eq 'mysql' ) { $rq = $dbh->prepare("SHOW TABLES"); }
427 elsif ( $info{dbms} eq 'Pg' ) {
430 FROM information_schema.tables
431 WHERE table_schema='public' and table_type='BASE TABLE';"
435 my $data = $rq->fetchall_arrayref( {} );
436 my $count = scalar(@$data);
438 # we don't have tables, propose DB import
441 $template->param( "count" => $count, "proposeimport" => 1 );
445 # we have tables, propose to select files to upload or updatedatabase
447 $template->param( "count" => $count, "default" => 1 );
449 # 1st part of step 3 : check if there is a databaseversion systempreference
450 # if there is, then we just need to upgrade
451 # if there is none, then we need to install the database
453 if ( C4::Context->preference('Version') ) {
454 my $dbversion = C4::Context->preference('Version');
455 $dbversion =~ /(.*)\.(..)(..)(...)/;
456 $dbversion = "$1.$2.$3.$4";
459 "dbversion" => $dbversion,
460 "kohaversion" => Koha::version(),
468 # LANGUAGE SELECTION page by default
469 # using opendir + language Hash
470 my $languages_loop = getTranslatedLanguages('intranet');
471 $template->param( installer_languages_loop => $languages_loop );
475 "SELECT * from systempreferences WHERE variable='Version'");
476 if ( $rq->execute ) {
477 my ($version) = $rq->fetchrow;
479 print $query->redirect(
480 "/cgi-bin/koha/installer/install.pl?step=3");
486 output_html_with_http_headers $query, $cookie, $template->output;
488 sub chk_log { #returns a logfile in $dir or - if that failed - in temp dir
489 my ( $dir, $name ) = @_;
490 my $fn = $dir . '/' . $name . '.log';
491 if ( !open my $fh, '>', $fn ) {
495 File::Temp::tempfile( $name, TMPDIR => 1, SUFFIX => '.log' );
497 #if this should not work, let croak take over