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>.
23 use C4::InstallAuth qw( get_template_and_user );
28 use C4::Output qw( output_html_with_http_headers );
30 use C4::Languages qw( getAllLanguages getTranslatedLanguages );
32 use C4::Installer::PerlModules;
38 my $step = $query->param('step');
40 # Flush memcached before we begin
41 Koha::Caches->get_instance('config')->flush_all;
42 Koha::Caches->get_instance('sysprefs')->flush_all;
44 my $language = $query->param('language');
45 my ( $template, $loggedinuser, $cookie );
47 my $all_languages = getAllLanguages();
49 if ( defined($language) ) {
50 C4::Templates::setlanguagecookie( $query, $language, "install.pl?step=1" );
52 ( $template, $loggedinuser, $cookie ) = get_template_and_user(
54 template_name => "installer/step" . ( $step ? $step : 1 ) . ".tt",
60 my $installer = C4::Installer->new();
62 $info{'dbname'} = C4::Context->config("database_test") || C4::Context->config("database");
64 C4::Context->config("db_scheme")
65 ? C4::Context->config("db_scheme")
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}." "
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'}
88 my $op = $query->param('op') || q{};
89 if ( $step && $step == 1 ) {
91 #First Step (for both fresh installations and upgrades)
92 #Checking ALL perl Modules and services needed are installed.
93 #Whenever there is an error, adding a report to the page
94 $template->param( language => 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
99 unless ( $] >= 5.010000 ) { # Bug 7375
100 $template->param( problems => 1, perlversion => 1, checkmodule => 0 );
104 my $perl_modules = C4::Installer::PerlModules->new;
105 $perl_modules->versions_info;
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) ) {
112 foreach (@$missing_modules) {
113 my ( $module, $stats ) = each %$_;
114 $checkmodule = 0 if $stats->{'required'};
119 min_version => $stats->{'min_ver'},
120 max_version => $stats->{'max_ver'},
121 require => $stats->{'required'}
125 foreach (@$upgrade_modules) {
126 my ( $module, $stats ) = each %$_;
127 $checkmodule = 0 if $stats->{'required'};
132 min_version => $stats->{'min_ver'},
133 max_version => $stats->{'max_ver'},
134 require => $stats->{'required'}
138 @missing = sort { $a->{'name'} cmp $b->{'name'} } @missing;
139 @upgrade = sort { $a->{'name'} cmp $b->{'name'} } @upgrade;
141 missing_modules => \@missing,
142 upgrade_modules => \@upgrade,
143 checkmodule => $checkmodule,
147 elsif ( $step && $step == 2 ) {
149 #STEP 2 Check Database connection and access
151 $template->param(%info);
152 my $checkdb = $query->param("checkdb");
153 $template->param( 'dbconnection' => $checkdb );
157 # Can connect to the mysql
158 $template->param( "checkdatabaseaccess" => 1 );
159 if ( $info{dbms} eq "mysql" ) {
161 #Check if database created
162 my $rv = $dbh->do("SHOW DATABASES LIKE \'$info{dbname}\'");
164 $template->param( 'checkdatabasecreated' => 1 );
167 # Check if user have all necessary grants on this database.
168 # CURRENT_USER is ANSI SQL, and doesn't require mysql table
169 # privileges, making the % check pointless, since they
170 # couldn't even check GRANTS if they couldn't connect.
171 my $rq = $dbh->prepare('SHOW GRANTS FOR CURRENT_USER');
174 while ( my ($line) = $rq->fetchrow ) {
175 my $dbname = $info{dbname};
176 if ( $line =~ m/^GRANT (.*?) ON `$dbname`\.\*/
177 || index( $line, '*.*' ) > 0 )
181 index( $line, 'ALL PRIVILEGES' ) > 0
182 || ( ( index( $line, 'SELECT' ) > 0 )
183 && ( index( $line, 'INSERT' ) > 0 )
184 && ( index( $line, 'UPDATE' ) > 0 )
185 && ( index( $line, 'DELETE' ) > 0 )
186 && ( index( $line, 'CREATE' ) > 0 )
187 && ( index( $line, 'DROP' ) > 0 ) )
191 $template->param( "checkgrantaccess" => $grantaccess );
193 if ( my $count = $installer->has_non_dynamic_row_format ) {
194 $template->param( warnDbRowFormat => $count );
195 $template->param( error => "InnoDB row format" );
198 } # End mysql connect check...
200 elsif ( $info{dbms} eq "Pg" ) {
202 # Check if database has been created...
204 "SELECT * FROM pg_catalog.pg_database WHERE datname = \'$info{dbname}\';"
207 $template->param( 'checkdatabasecreated' => 1 );
210 # Check if user has all necessary grants on this database...
213 FROM pg_catalog.pg_user as u
214 WHERE u.usename = \'$info{user}\';"
217 $template->param( "checkgrantaccess" => 1 );
219 } # End Pg connect check...
222 $template->param( "error" => DBI::err, "message" => DBI::errstr );
226 elsif ( $step && $step == 3 ) {
228 # STEP 3 : database setup
230 if ( $op eq 'finished' ) {
231 # Remove the HandleError set at the beginning of the installer process
232 C4::Context->dbh->disconnect;
234 my $cookie_mgr = Koha::CookieManager->new;
235 # Remove cookie of the installer session
237 if ( !ref $cookie ) {
238 push( @$cookies, $cookie );
240 $cookies = $cookie_mgr->replace_in_list( $cookies, $query->cookie(
241 -name => 'CGISESSID',
244 -secure => ( C4::Context->https_enabled() ? 1 : 0 ),
248 # we have finished, just redirect to mainpage.
249 print $query->redirect( -uri => "/cgi-bin/koha/mainpage.pl", -cookie => $cookies );
252 elsif ( $op eq 'cud-finish' ) {
253 $installer->set_version_syspref();
255 my $langchoice = $query->param('fwklanguage');
256 $langchoice = $query->cookie('KohaOpacLanguage') unless ($langchoice);
257 $langchoice =~ s/[^a-zA-Z_-]*//g;
258 $installer->set_languages_syspref($langchoice);
260 # Installation is finished.
261 # We just deny anybody access to install
262 # And we redirect people to mainpage.
263 # The installer will have to relogin since we do not pass cookie to redirection.
266 elsif ( $op eq 'cud-addframeworks' ) {
268 # 1ST install, 3rd sub-step : insert the SQL files the user has selected
269 my $langchoice = $query->param('fwklanguage');
270 $langchoice = $query->cookie('KohaOpacLanguage') unless ($langchoice);
271 $langchoice =~ s/[^a-zA-Z_-]*//g;
273 my ( $fwk_language, $list ) =
274 $installer->load_sql_in_order( $langchoice, $all_languages,
275 $query->multi_param('framework') );
277 "fwklanguage" => $fwk_language,
280 use Koha::SearchEngine::Elasticsearch;
281 Koha::SearchEngine::Elasticsearch->reset_elasticsearch_mappings;
283 elsif ( $op eq 'cud-selectframeworks' ) {
286 # 1ST install, 2nd sub-step : show the user the sql datas they can insert in the database.
289 # (note that the term "selectframeworks is not correct. The user can select various files, not only frameworks)
292 #sql data for import are supposed to be located in installer/data/<language>/<level>
293 # Where <language> is en|fr or any international abbreviation (provided language hash is updated... This will be a problem with internationlisation.)
294 # Where <level> is a category of requirement : required, recommended optional
295 # level should contain :
296 # SQL File for import With a readable name.
297 # txt File that explains what this SQL File is meant for.
298 # Could be VERY useful to have A Big file for a kind of library.
299 # But could also be useful to have some Authorised values data set prepared here.
300 # Framework Selection is achieved through checking boxes.
301 my $langchoice = $query->param('fwklanguage');
302 $langchoice = $query->cookie('KohaOpacLanguage') unless ($langchoice);
303 $langchoice =~ s/[^a-zA-Z_-]*//g;
304 my $marcflavour = $query->param('marcflavour');
306 $installer->set_marcflavour_syspref($marcflavour);
308 $marcflavour = C4::Context->preference('marcflavour')
309 unless ($marcflavour);
311 #Insert into database the selected marcflavour
313 my ( $marc_defaulted_to_en, $fwklist ) =
314 $installer->marc_framework_sql_list( $langchoice, $marcflavour );
315 $template->param( 'en_marc_frameworks' => $marc_defaulted_to_en );
316 $template->param( "frameworksloop" => $fwklist );
317 $template->param( "marcflavour" => ucfirst($marcflavour) );
319 my ( $sample_defaulted_to_en, $levellist ) =
320 $installer->sample_data_sql_list($langchoice);
321 $template->param( "en_sample_data" => $sample_defaulted_to_en );
322 $template->param( "levelloop" => $levellist );
325 elsif ( $op eq 'cud-choosemarc' ) {
328 # 1ST install, 2nd sub-step : show the user the marcflavour available.
333 #sql data are supposed to be located in installer/data/<dbms>/<language>/marcflavour/marcflavourname
334 # Where <dbms> is database type according to DBD syntax
335 # Where <language> is en|fr or any international abbreviation (provided language hash is updated... This will be a problem with internationlisation.)
336 # Where <level> is a category of requirement : required, recommended optional
337 # level should contain :
338 # SQL File for import With a readable name.
339 # txt File that explains what this SQL File is meant for.
340 # Could be VERY useful to have A Big file for a kind of library.
341 # But could also be useful to have some Authorised values data set prepared here.
342 # Marcflavour Selection is achieved through radiobuttons.
343 my $langchoice = $query->param('fwklanguage');
345 $langchoice = $query->cookie('KohaOpacLanguage') unless ($langchoice);
346 $langchoice =~ s/[^a-zA-Z_-]*//g;
348 C4::Context->config('intranetdir')
349 . "/installer/data/$info{dbms}/$langchoice/marcflavour";
351 unless ( opendir( $dir_h, $dir ) ) {
352 if ( $langchoice eq 'en' ) {
353 warn "cannot open MARC frameworks directory $dir";
356 # if no translated MARC framework is available,
358 $dir = C4::Context->config('intranetdir')
359 . "/installer/data/$info{dbms}/en/marcflavour";
360 opendir( $dir_h, $dir )
361 or warn "cannot open English MARC frameworks directory $dir";
364 my @listdir = grep { !/^\./ && -d "$dir/$_" } readdir($dir_h);
366 my $marcflavour = C4::Context->preference("marcflavour");
368 foreach my $marc (@listdir) {
370 "label"=> ucfirst($marc),
372 "checked"=> defined($marcflavour) ? uc($marc) eq $marcflavour : 0);
373 # $cell{"description"}= do { local $/ = undef; open INPUT "<$dir/$marc.txt"||"";<INPUT> };
374 push @flavourlist, \%cell;
376 $template->param( "flavourloop" => \@flavourlist );
378 elsif ( $op eq 'cud-importdatastructure' ) {
381 # 1st install, 1st "sub-step" : import kohastructure
384 my $error = $installer->load_db_schema();
389 elsif ( $op eq 'cud-updatestructure' ) {
391 # Not 1st install, the only sub-step : update database
393 #Do updatedatabase And report
395 if ( !defined $ENV{PERL5LIB} ) {
396 my $find = "C4/Context.pm";
397 my $path = $INC{$find};
398 $path =~ s/\Q$find\E//;
399 $ENV{PERL5LIB} = "$path:$path/installer";
400 warn "# plack? inserted PERL5LIB $ENV{PERL5LIB}\n";
403 my $now = POSIX::strftime( "%Y-%m-%dT%H:%M:%S", localtime() );
404 my $logdir = C4::Context->config('logdir');
405 my $dbversion = C4::Context->preference('Version');
406 my $kohaversion = Koha::version;
407 $kohaversion =~ s/(.*\..*)\.(.*)\.(.*)/$1$2$3/;
409 my $filename_suffix = join '_', $now, $dbversion, $kohaversion;
410 my ( $logfilepath, $logfilepath_errors ) = (
411 chk_log( $logdir, "updatedatabase_$filename_suffix" ),
412 chk_log( $logdir, "updatedatabase-error_$filename_suffix" )
415 my $cmd = C4::Context->config("intranetdir")
416 . "/installer/data/$info{dbms}/updatedatabase.pl >> $logfilepath 2>> $logfilepath_errors";
421 open( $fh, "<:encoding(utf-8)", $logfilepath )
422 or die "Cannot open log file $logfilepath: $!";
426 $template->param( update_report =>
427 [ map { { line => $_ =~ s/\t/  /gr } } split( /\n/, join( '', @report ) ) ]
429 $template->param( has_update_succeeds => 1 );
432 eval { `rm $logfilepath` };
434 open( $fh, "<:encoding(utf-8)", $logfilepath_errors )
435 or die "Cannot open log file $logfilepath_errors: $!";
440 $template->param( update_errors =>
441 [ map { { line => $_ } } split( /\n/, join( '', @report ) ) ]
444 $template->param( has_update_errors => 1 );
446 "The following errors were returned while attempting to run the updatedatabase.pl script:\n";
447 foreach my $line (@report) { warn "$line\n"; }
450 eval { `rm $logfilepath_errors` };
453 unless ( $update_errors ) {
454 my $db_entries = get_db_entries();
455 my $report = update( $db_entries );
456 my $atomic_update_files = get_atomic_updates;
457 my $atomic_update_report = run_atomic_updates( $atomic_update_files );
460 success => $report->{success},
461 error => $report->{error},
463 success => $atomic_update_report->{success},
464 error => $atomic_update_report->{error}
471 # check whether it's a 1st install or an update
473 #Check if there are enough tables.
474 # Paul has cleaned up tables so reduced the count
475 #I put it there because it implied a data import if condition was not satisfied.
476 my $dbh = DBI->connect(
477 "DBI:$info{dbms}:dbname=$info{dbname};host=$info{hostname}"
478 . ( $info{port} ? ";port=$info{port}" : "" )
479 . ( $info{tlsoptions} ? $info{tlsoptions} : "" ),
480 $info{'user'}, $info{'password'}
483 if ( $info{dbms} eq 'mysql' ) { $rq = $dbh->prepare("SHOW TABLES"); }
484 elsif ( $info{dbms} eq 'Pg' ) {
487 FROM information_schema.tables
488 WHERE table_schema='public' and table_type='BASE TABLE';"
492 my $data = $rq->fetchall_arrayref( {} );
493 my $count = scalar(@$data);
495 # we don't have tables, propose DB import
498 $template->param( "count" => $count, "proposeimport" => 1 );
502 # we have tables, propose to select files to upload or updatedatabase
504 $template->param( "count" => $count, "default" => 1 );
506 # 1st part of step 3 : check if there is a databaseversion systempreference
507 # if there is, then we just need to upgrade
508 # if there is none, then we need to install the database
510 if ( C4::Context->preference('Version') ) {
511 my $dbversion = C4::Context->preference('Version');
512 $dbversion =~ /(.*)\.(..)(..)(...)/;
513 $dbversion = "$1.$2.$3.$4";
516 "dbversion" => $dbversion,
517 "kohaversion" => Koha::version(),
525 # LANGUAGE SELECTION page by default
526 # using opendir + language Hash
527 my $languages_loop = getTranslatedLanguages('intranet');
528 $template->param( installer_languages_loop => $languages_loop );
532 "SELECT * from systempreferences WHERE variable='Version'");
533 if ( $rq->execute ) {
534 my ($version) = $rq->fetchrow;
536 print $query->redirect(
537 "/cgi-bin/koha/installer/install.pl?step=3");
546 $template->param( op => $op, $op => 1 );
549 output_html_with_http_headers $query, $cookie, $template->output;
551 sub chk_log { #returns a logfile in $dir or - if that failed - in temp dir
552 my ( $dir, $name ) = @_;
553 my $fn = $dir . '/' . $name . '.log';
554 if ( !open my $fh, '>', $fn ) {
558 File::Temp::tempfile( $name, TMPDIR => 1, SUFFIX => '.log' );
560 #if this should not work, let croak take over