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 );
26 use HTML::FromANSI::Tiny::Bootstrap;
29 use C4::Output qw( output_html_with_http_headers );
31 use C4::Languages qw( getAllLanguages getTranslatedLanguages );
33 use C4::Installer::PerlModules;
39 my $step = $query->param('step');
41 # Flush memcached before we begin
42 Koha::Caches->get_instance('config')->flush_all;
43 Koha::Caches->get_instance('sysprefs')->flush_all;
45 my $language = $query->param('language');
46 my ( $template, $loggedinuser, $cookie );
48 my $all_languages = getAllLanguages();
50 if ( defined($language) ) {
51 C4::Templates::setlanguagecookie( $query, $language, "install.pl?step=1" );
53 ( $template, $loggedinuser, $cookie ) = get_template_and_user(
55 template_name => "installer/step" . ( $step ? $step : 1 ) . ".tt",
61 my $installer = C4::Installer->new();
63 $info{'dbname'} = C4::Context->config("database_test") || C4::Context->config("database");
65 C4::Context->config("db_scheme")
66 ? C4::Context->config("db_scheme")
69 $info{'hostname'} = C4::Context->config("hostname");
70 $info{'port'} = C4::Context->config("port");
71 $info{'user'} = C4::Context->config("user");
72 $info{'password'} = C4::Context->config("pass");
73 $info{'tls'} = C4::Context->config("tls");
74 if ($info{'tls'} && $info{'tls'} eq 'yes'){
75 $info{'ca'} = C4::Context->config('ca');
76 $info{'cert'} = C4::Context->config('cert');
77 $info{'key'} = C4::Context->config('key');
78 $info{'tlsoptions'} = ";mysql_ssl=1;mysql_ssl_client_key=".$info{key}.";mysql_ssl_client_cert=".$info{cert}.";mysql_ssl_ca_file=".$info{ca};
79 $info{'tlscmdline'} = " --ssl-cert ". $info{cert} . " --ssl-key " . $info{key} . " --ssl-ca ".$info{ca}." "
82 my $dbh = DBI->connect(
83 "DBI:$info{dbms}:dbname=$info{dbname};host=$info{hostname}"
84 . ( $info{port} ? ";port=$info{port}" : "" )
85 . ( $info{tlsoptions} ? $info{tlsoptions} : "" ),
86 $info{'user'}, $info{'password'}
89 my $op = $query->param('op') || q{};
90 if ( $step && $step == 1 ) {
92 #First Step (for both fresh installations and upgrades)
93 #Checking ALL perl Modules and services needed are installed.
94 #Whenever there is an error, adding a report to the page
95 $template->param( language => 1 );
97 $template->param( 'checkmodule' => 1 )
98 ; # we start with the assumption that there are no problems and set this to 0 if there are
100 unless ( $] >= 5.010000 ) { # Bug 7375
101 $template->param( problems => 1, perlversion => 1, checkmodule => 0 );
105 my $perl_modules = C4::Installer::PerlModules->new;
106 $perl_modules->versions_info;
108 my $missing_modules = $perl_modules->get_attr('missing_pm');
109 my $upgrade_modules = $perl_modules->get_attr('upgrade_pm');
110 if ( scalar(@$missing_modules) || scalar(@$upgrade_modules) ) {
113 foreach (@$missing_modules) {
114 my ( $module, $stats ) = each %$_;
115 $checkmodule = 0 if $stats->{'required'};
120 min_version => $stats->{'min_ver'},
121 max_version => $stats->{'max_ver'},
122 require => $stats->{'required'}
126 foreach (@$upgrade_modules) {
127 my ( $module, $stats ) = each %$_;
128 $checkmodule = 0 if $stats->{'required'};
133 min_version => $stats->{'min_ver'},
134 max_version => $stats->{'max_ver'},
135 require => $stats->{'required'}
139 @missing = sort { $a->{'name'} cmp $b->{'name'} } @missing;
140 @upgrade = sort { $a->{'name'} cmp $b->{'name'} } @upgrade;
142 missing_modules => \@missing,
143 upgrade_modules => \@upgrade,
144 checkmodule => $checkmodule,
148 elsif ( $step && $step == 2 ) {
150 #STEP 2 Check Database connection and access
152 $template->param(%info);
153 my $checkdb = $query->param("checkdb");
154 $template->param( 'dbconnection' => $checkdb );
158 # Can connect to the mysql
159 $template->param( "checkdatabaseaccess" => 1 );
160 if ( $info{dbms} eq "mysql" ) {
162 #Check if database created
163 my $rv = $dbh->do("SHOW DATABASES LIKE \'$info{dbname}\'");
165 $template->param( 'checkdatabasecreated' => 1 );
168 # Check if user have all necessary grants on this database.
169 # CURRENT_USER is ANSI SQL, and doesn't require mysql table
170 # privileges, making the % check pointless, since they
171 # couldn't even check GRANTS if they couldn't connect.
172 my $rq = $dbh->prepare('SHOW GRANTS FOR CURRENT_USER');
175 while ( my ($line) = $rq->fetchrow ) {
176 my $dbname = $info{dbname};
177 if ( $line =~ m/^GRANT (.*?) ON `$dbname`\.\*/
178 || index( $line, '*.*' ) > 0 )
182 index( $line, 'ALL PRIVILEGES' ) > 0
183 || ( ( index( $line, 'SELECT' ) > 0 )
184 && ( index( $line, 'INSERT' ) > 0 )
185 && ( index( $line, 'UPDATE' ) > 0 )
186 && ( index( $line, 'DELETE' ) > 0 )
187 && ( index( $line, 'CREATE' ) > 0 )
188 && ( index( $line, 'DROP' ) > 0 ) )
192 $template->param( "checkgrantaccess" => $grantaccess );
194 if ( my $count = $installer->has_non_dynamic_row_format ) {
195 $template->param( warnDbRowFormat => $count );
196 $template->param( error => "InnoDB row format" );
199 } # End mysql connect check...
201 elsif ( $info{dbms} eq "Pg" ) {
203 # Check if database has been created...
205 "SELECT * FROM pg_catalog.pg_database WHERE datname = \'$info{dbname}\';"
208 $template->param( 'checkdatabasecreated' => 1 );
211 # Check if user has all necessary grants on this database...
214 FROM pg_catalog.pg_user as u
215 WHERE u.usename = \'$info{user}\';"
218 $template->param( "checkgrantaccess" => 1 );
220 } # End Pg connect check...
223 $template->param( "error" => DBI::err, "message" => DBI::errstr );
227 elsif ( $step && $step == 3 ) {
229 # STEP 3 : database setup
231 if ( $op eq 'finished' ) {
232 # Remove the HandleError set at the beginning of the installer process
233 C4::Context->dbh->disconnect;
235 my $cookie_mgr = Koha::CookieManager->new;
236 # Remove cookie of the installer session
238 if ( !ref $cookie ) {
239 push( @$cookies, $cookie );
241 $cookies = $cookie_mgr->replace_in_list( $cookies, $query->cookie(
242 -name => 'CGISESSID',
245 -secure => ( C4::Context->https_enabled() ? 1 : 0 ),
249 # we have finished, just redirect to mainpage.
250 print $query->redirect( -uri => "/cgi-bin/koha/mainpage.pl", -cookie => $cookies );
253 elsif ( $op eq 'cud-finish' ) {
254 $installer->set_version_syspref();
256 my $langchoice = $query->param('fwklanguage');
257 $langchoice = $query->cookie('KohaOpacLanguage') unless ($langchoice);
258 $langchoice =~ s/[^a-zA-Z_-]*//g;
259 $installer->set_languages_syspref($langchoice);
261 # Installation is finished.
262 # We just deny anybody access to install
263 # And we redirect people to mainpage.
264 # The installer will have to relogin since we do not pass cookie to redirection.
267 elsif ( $op eq 'cud-addframeworks' ) {
269 # 1ST install, 3rd sub-step : insert the SQL files the user has selected
270 my $langchoice = $query->param('fwklanguage');
271 $langchoice = $query->cookie('KohaOpacLanguage') unless ($langchoice);
272 $langchoice =~ s/[^a-zA-Z_-]*//g;
274 my ( $fwk_language, $list ) =
275 $installer->load_sql_in_order( $langchoice, $all_languages,
276 $query->multi_param('framework') );
278 "fwklanguage" => $fwk_language,
281 use Koha::SearchEngine::Elasticsearch;
282 Koha::SearchEngine::Elasticsearch->reset_elasticsearch_mappings;
284 elsif ( $op eq 'cud-selectframeworks' ) {
287 # 1ST install, 2nd sub-step : show the user the sql datas they can insert in the database.
290 # (note that the term "selectframeworks is not correct. The user can select various files, not only frameworks)
293 #sql data for import are supposed to be located in installer/data/<language>/<level>
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 # Framework Selection is achieved through checking boxes.
302 my $langchoice = $query->param('fwklanguage');
303 $langchoice = $query->cookie('KohaOpacLanguage') unless ($langchoice);
304 $langchoice =~ s/[^a-zA-Z_-]*//g;
305 my $marcflavour = $query->param('marcflavour');
307 $installer->set_marcflavour_syspref($marcflavour);
309 $marcflavour = C4::Context->preference('marcflavour')
310 unless ($marcflavour);
312 #Insert into database the selected marcflavour
314 my ( $marc_defaulted_to_en, $fwklist ) =
315 $installer->marc_framework_sql_list( $langchoice, $marcflavour );
316 $template->param( 'en_marc_frameworks' => $marc_defaulted_to_en );
317 $template->param( "frameworksloop" => $fwklist );
318 $template->param( "marcflavour" => ucfirst($marcflavour) );
320 my ( $sample_defaulted_to_en, $levellist ) =
321 $installer->sample_data_sql_list($langchoice);
322 $template->param( "en_sample_data" => $sample_defaulted_to_en );
323 $template->param( "levelloop" => $levellist );
326 elsif ( $op eq 'cud-choosemarc' ) {
329 # 1ST install, 2nd sub-step : show the user the marcflavour available.
334 #sql data are supposed to be located in installer/data/<dbms>/<language>/marcflavour/marcflavourname
335 # Where <dbms> is database type according to DBD syntax
336 # Where <language> is en|fr or any international abbreviation (provided language hash is updated... This will be a problem with internationlisation.)
337 # Where <level> is a category of requirement : required, recommended optional
338 # level should contain :
339 # SQL File for import With a readable name.
340 # txt File that explains what this SQL File is meant for.
341 # Could be VERY useful to have A Big file for a kind of library.
342 # But could also be useful to have some Authorised values data set prepared here.
343 # Marcflavour Selection is achieved through radiobuttons.
344 my $langchoice = $query->param('fwklanguage');
346 $langchoice = $query->cookie('KohaOpacLanguage') unless ($langchoice);
347 $langchoice =~ s/[^a-zA-Z_-]*//g;
349 C4::Context->config('intranetdir')
350 . "/installer/data/$info{dbms}/$langchoice/marcflavour";
352 unless ( opendir( $dir_h, $dir ) ) {
353 if ( $langchoice eq 'en' ) {
354 warn "cannot open MARC frameworks directory $dir";
357 # if no translated MARC framework is available,
359 $dir = C4::Context->config('intranetdir')
360 . "/installer/data/$info{dbms}/en/marcflavour";
361 opendir( $dir_h, $dir )
362 or warn "cannot open English MARC frameworks directory $dir";
365 my @listdir = grep { !/^\./ && -d "$dir/$_" } readdir($dir_h);
367 my $marcflavour = C4::Context->preference("marcflavour");
369 foreach my $marc (@listdir) {
371 "label"=> ucfirst($marc),
373 "checked"=> defined($marcflavour) ? uc($marc) eq $marcflavour : 0);
374 # $cell{"description"}= do { local $/ = undef; open INPUT "<$dir/$marc.txt"||"";<INPUT> };
375 push @flavourlist, \%cell;
377 $template->param( "flavourloop" => \@flavourlist );
379 elsif ( $op eq 'cud-importdatastructure' ) {
382 # 1st install, 1st "sub-step" : import kohastructure
385 my $error = $installer->load_db_schema();
390 elsif ( $op eq 'cud-updatestructure' ) {
392 # Not 1st install, the only sub-step : update database
394 #Do updatedatabase And report
396 if ( !defined $ENV{PERL5LIB} ) {
397 my $find = "C4/Context.pm";
398 my $path = $INC{$find};
399 $path =~ s/\Q$find\E//;
400 $ENV{PERL5LIB} = "$path:$path/installer";
401 warn "# plack? inserted PERL5LIB $ENV{PERL5LIB}\n";
404 my $now = POSIX::strftime( "%Y-%m-%dT%H:%M:%S", localtime() );
405 my $logdir = C4::Context->config('logdir');
406 my $dbversion = C4::Context->preference('Version');
407 my $kohaversion = Koha::version;
408 $kohaversion =~ s/(.*\..*)\.(.*)\.(.*)/$1$2$3/;
410 my $filename_suffix = join '_', $now, $dbversion, $kohaversion;
411 my ( $logfilepath, $logfilepath_errors ) = (
412 chk_log( $logdir, "updatedatabase_$filename_suffix" ),
413 chk_log( $logdir, "updatedatabase-error_$filename_suffix" )
416 my $cmd = C4::Context->config("intranetdir")
417 . "/installer/data/$info{dbms}/updatedatabase.pl >> $logfilepath 2>> $logfilepath_errors";
422 open( $fh, "<:encoding(utf-8)", $logfilepath )
423 or die "Cannot open log file $logfilepath: $!";
428 $template->param( update_report =>
429 [ map { { line => $_ =~ s/\t/  /gr } } split( /\n/, join( '', @report ) ) ]
431 $template->param( has_update_succeeds => 1 );
434 eval { `rm $logfilepath` };
436 open( $fh, "<:encoding(utf-8)", $logfilepath_errors )
437 or die "Cannot open log file $logfilepath_errors: $!";
442 $template->param( update_errors =>
443 [ map { { line => $_ } } split( /\n/, join( '', @report ) ) ]
446 $template->param( has_update_errors => 1 );
448 "The following errors were returned while attempting to run the updatedatabase.pl script:\n";
449 foreach my $line (@report) { warn "$line\n"; }
452 eval { `rm $logfilepath_errors` };
455 unless ( $update_errors ) {
456 my $db_entries = get_db_entries();
457 my $report = update( $db_entries );
458 my $atomic_update_files = get_atomic_updates;
459 my $atomic_update_report = run_atomic_updates( $atomic_update_files );
462 colorize($atomic_update_report);
464 success => $report->{success},
465 error => $report->{error},
467 success => $atomic_update_report->{success},
468 error => $atomic_update_report->{error}
475 # check whether it's a 1st install or an update
477 #Check if there are enough tables.
478 # Paul has cleaned up tables so reduced the count
479 #I put it there because it implied a data import if condition was not satisfied.
480 my $dbh = DBI->connect(
481 "DBI:$info{dbms}:dbname=$info{dbname};host=$info{hostname}"
482 . ( $info{port} ? ";port=$info{port}" : "" )
483 . ( $info{tlsoptions} ? $info{tlsoptions} : "" ),
484 $info{'user'}, $info{'password'}
487 if ( $info{dbms} eq 'mysql' ) { $rq = $dbh->prepare("SHOW TABLES"); }
488 elsif ( $info{dbms} eq 'Pg' ) {
491 FROM information_schema.tables
492 WHERE table_schema='public' and table_type='BASE TABLE';"
496 my $data = $rq->fetchall_arrayref( {} );
497 my $count = scalar(@$data);
499 # we don't have tables, propose DB import
502 $template->param( "count" => $count, "proposeimport" => 1 );
506 # we have tables, propose to select files to upload or updatedatabase
508 $template->param( "count" => $count, "default" => 1 );
510 # 1st part of step 3 : check if there is a databaseversion systempreference
511 # if there is, then we just need to upgrade
512 # if there is none, then we need to install the database
514 if ( C4::Context->preference('Version') ) {
515 my $dbversion = C4::Context->preference('Version');
516 $dbversion =~ /(.*)\.(..)(..)(...)/;
517 $dbversion = "$1.$2.$3.$4";
520 "dbversion" => $dbversion,
521 "kohaversion" => Koha::version(),
529 # LANGUAGE SELECTION page by default
530 # using opendir + language Hash
531 my $languages_loop = getTranslatedLanguages('intranet');
532 $template->param( installer_languages_loop => $languages_loop );
536 "SELECT * from systempreferences WHERE variable='Version'");
537 if ( $rq->execute ) {
538 my ($version) = $rq->fetchrow;
540 print $query->redirect(
541 "/cgi-bin/koha/installer/install.pl?step=3");
550 $template->param( op => $op, $op => 1 );
553 output_html_with_http_headers $query, $cookie, $template->output;
555 sub chk_log { #returns a logfile in $dir or - if that failed - in temp dir
556 my ( $dir, $name ) = @_;
557 my $fn = $dir . '/' . $name . '.log';
558 if ( !open my $fh, '>', $fn ) {
562 File::Temp::tempfile( $name, TMPDIR => 1, SUFFIX => '.log' );
564 #if this should not work, let croak take over
571 my $h = HTML::FromANSI::Tiny::Bootstrap->new(
573 background => 'white',
574 foreground => 'black',
578 my @states = ( 'success', 'error' );
579 for my $state (@states) {
580 for my $result ( @{ $report->{$state} } ) {
582 #@{ $result->{output} } = map { s/^\t+//; $h->html($_) } @{ $result->{output} };
583 for my $output ( @{ $result->{output} } ) {
584 $output = $h->html($output);