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 if ( $step && $step == 1 ) {
90 #First Step (for both fresh installations and upgrades)
91 #Checking ALL perl Modules and services needed are installed.
92 #Whenever there is an error, adding a report to the page
93 my $op = $query->param('op') || 'noop';
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,
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 my $op = $query->param('op');
232 if ( $op && $op eq 'finished' ) {
233 # Remove the HandleError set at the beginning of the installer process
234 C4::Context->dbh->disconnect;
236 # we have finished, just redirect to mainpage.
237 print $query->redirect("/cgi-bin/koha/mainpage.pl");
240 elsif ( $op && $op eq 'cud-finish' ) {
241 $installer->set_version_syspref();
243 my $langchoice = $query->param('fwklanguage');
244 $langchoice = $query->cookie('KohaOpacLanguage') unless ($langchoice);
245 $langchoice =~ s/[^a-zA-Z_-]*//g;
246 $installer->set_languages_syspref($langchoice);
248 # Installation is finished.
249 # We just deny anybody access to install
250 # And we redirect people to mainpage.
251 # The installer will have to relogin since we do not pass cookie to redirection.
252 $template->param( "$op" => 1 );
255 elsif ( $op && $op eq 'cud-addframeworks' ) {
257 # 1ST install, 3rd sub-step : insert the SQL files the user has selected
258 my $langchoice = $query->param('fwklanguage');
259 $langchoice = $query->cookie('KohaOpacLanguage') unless ($langchoice);
260 $langchoice =~ s/[^a-zA-Z_-]*//g;
262 my ( $fwk_language, $list ) =
263 $installer->load_sql_in_order( $langchoice, $all_languages,
264 $query->multi_param('framework') );
266 "fwklanguage" => $fwk_language,
269 use Koha::SearchEngine::Elasticsearch;
270 Koha::SearchEngine::Elasticsearch->reset_elasticsearch_mappings;
271 $template->param( "$op" => 1 );
273 elsif ( $op && $op eq 'cud-selectframeworks' ) {
276 # 1ST install, 2nd sub-step : show the user the sql datas they can insert in the database.
279 # (note that the term "selectframeworks is not correct. The user can select various files, not only frameworks)
282 #sql data for import are supposed to be located in installer/data/<language>/<level>
283 # Where <language> is en|fr or any international abbreviation (provided language hash is updated... This will be a problem with internationlisation.)
284 # Where <level> is a category of requirement : required, recommended optional
285 # level should contain :
286 # SQL File for import With a readable name.
287 # txt File that explains what this SQL File is meant for.
288 # Could be VERY useful to have A Big file for a kind of library.
289 # But could also be useful to have some Authorised values data set prepared here.
290 # Framework Selection is achieved through checking boxes.
291 my $langchoice = $query->param('fwklanguage');
292 $langchoice = $query->cookie('KohaOpacLanguage') unless ($langchoice);
293 $langchoice =~ s/[^a-zA-Z_-]*//g;
294 my $marcflavour = $query->param('marcflavour');
296 $installer->set_marcflavour_syspref($marcflavour);
298 $marcflavour = C4::Context->preference('marcflavour')
299 unless ($marcflavour);
301 #Insert into database the selected marcflavour
303 my ( $marc_defaulted_to_en, $fwklist ) =
304 $installer->marc_framework_sql_list( $langchoice, $marcflavour );
305 $template->param( 'en_marc_frameworks' => $marc_defaulted_to_en );
306 $template->param( "frameworksloop" => $fwklist );
307 $template->param( "marcflavour" => ucfirst($marcflavour) );
309 my ( $sample_defaulted_to_en, $levellist ) =
310 $installer->sample_data_sql_list($langchoice);
311 $template->param( "en_sample_data" => $sample_defaulted_to_en );
312 $template->param( "levelloop" => $levellist );
313 $template->param( "$op" => 1 );
316 elsif ( $op && $op eq 'cud-choosemarc' ) {
319 # 1ST install, 2nd sub-step : show the user the marcflavour available.
324 #sql data are supposed to be located in installer/data/<dbms>/<language>/marcflavour/marcflavourname
325 # Where <dbms> is database type according to DBD syntax
326 # Where <language> is en|fr or any international abbreviation (provided language hash is updated... This will be a problem with internationlisation.)
327 # Where <level> is a category of requirement : required, recommended optional
328 # level should contain :
329 # SQL File for import With a readable name.
330 # txt File that explains what this SQL File is meant for.
331 # Could be VERY useful to have A Big file for a kind of library.
332 # But could also be useful to have some Authorised values data set prepared here.
333 # Marcflavour Selection is achieved through radiobuttons.
334 my $langchoice = $query->param('fwklanguage');
336 $langchoice = $query->cookie('KohaOpacLanguage') unless ($langchoice);
337 $langchoice =~ s/[^a-zA-Z_-]*//g;
339 C4::Context->config('intranetdir')
340 . "/installer/data/$info{dbms}/$langchoice/marcflavour";
342 unless ( opendir( $dir_h, $dir ) ) {
343 if ( $langchoice eq 'en' ) {
344 warn "cannot open MARC frameworks directory $dir";
347 # if no translated MARC framework is available,
349 $dir = C4::Context->config('intranetdir')
350 . "/installer/data/$info{dbms}/en/marcflavour";
351 opendir( $dir_h, $dir )
352 or warn "cannot open English MARC frameworks directory $dir";
355 my @listdir = grep { !/^\./ && -d "$dir/$_" } readdir($dir_h);
357 my $marcflavour = C4::Context->preference("marcflavour");
359 foreach my $marc (@listdir) {
361 "label"=> ucfirst($marc),
363 "checked"=> defined($marcflavour) ? uc($marc) eq $marcflavour : 0);
364 # $cell{"description"}= do { local $/ = undef; open INPUT "<$dir/$marc.txt"||"";<INPUT> };
365 push @flavourlist, \%cell;
367 $template->param( "flavourloop" => \@flavourlist );
368 $template->param( "$op" => 1 );
370 elsif ( $op && $op eq 'cud-importdatastructure' ) {
373 # 1st install, 1st "sub-step" : import kohastructure
376 my $error = $installer->load_db_schema();
382 elsif ( $op && $op eq 'updatestructure' ) {
384 # Not 1st install, the only sub-step : update database
386 #Do updatedatabase And report
388 if ( !defined $ENV{PERL5LIB} ) {
389 my $find = "C4/Context.pm";
390 my $path = $INC{$find};
391 $path =~ s/\Q$find\E//;
392 $ENV{PERL5LIB} = "$path:$path/installer";
393 warn "# plack? inserted PERL5LIB $ENV{PERL5LIB}\n";
396 my $now = POSIX::strftime( "%Y-%m-%dT%H:%M:%S", localtime() );
397 my $logdir = C4::Context->config('logdir');
398 my $dbversion = C4::Context->preference('Version');
399 my $kohaversion = Koha::version;
400 $kohaversion =~ s/(.*\..*)\.(.*)\.(.*)/$1$2$3/;
402 my $filename_suffix = join '_', $now, $dbversion, $kohaversion;
403 my ( $logfilepath, $logfilepath_errors ) = (
404 chk_log( $logdir, "updatedatabase_$filename_suffix" ),
405 chk_log( $logdir, "updatedatabase-error_$filename_suffix" )
408 my $cmd = C4::Context->config("intranetdir")
409 . "/installer/data/$info{dbms}/updatedatabase.pl >> $logfilepath 2>> $logfilepath_errors";
414 open( $fh, "<:encoding(utf-8)", $logfilepath )
415 or die "Cannot open log file $logfilepath: $!";
419 $template->param( update_report =>
420 [ map { { line => $_ =~ s/\t/  /gr } } split( /\n/, join( '', @report ) ) ]
422 $template->param( has_update_succeeds => 1 );
425 eval { `rm $logfilepath` };
427 open( $fh, "<:encoding(utf-8)", $logfilepath_errors )
428 or die "Cannot open log file $logfilepath_errors: $!";
433 $template->param( update_errors =>
434 [ map { { line => $_ } } split( /\n/, join( '', @report ) ) ]
437 $template->param( has_update_errors => 1 );
439 "The following errors were returned while attempting to run the updatedatabase.pl script:\n";
440 foreach my $line (@report) { warn "$line\n"; }
443 eval { `rm $logfilepath_errors` };
446 unless ( $update_errors ) {
447 my $db_entries = get_db_entries();
448 my $report = update( $db_entries );
449 my $atomic_update_files = get_atomic_updates;
450 my $atomic_update_report = run_atomic_updates( $atomic_update_files );
453 success => $report->{success},
454 error => $report->{error},
456 success => $atomic_update_report->{success},
457 error => $atomic_update_report->{error}
462 $template->param( $op => 1 );
466 # check whether it's a 1st install or an update
468 #Check if there are enough tables.
469 # Paul has cleaned up tables so reduced the count
470 #I put it there because it implied a data import if condition was not satisfied.
471 my $dbh = DBI->connect(
472 "DBI:$info{dbms}:dbname=$info{dbname};host=$info{hostname}"
473 . ( $info{port} ? ";port=$info{port}" : "" )
474 . ( $info{tlsoptions} ? $info{tlsoptions} : "" ),
475 $info{'user'}, $info{'password'}
478 if ( $info{dbms} eq 'mysql' ) { $rq = $dbh->prepare("SHOW TABLES"); }
479 elsif ( $info{dbms} eq 'Pg' ) {
482 FROM information_schema.tables
483 WHERE table_schema='public' and table_type='BASE TABLE';"
487 my $data = $rq->fetchall_arrayref( {} );
488 my $count = scalar(@$data);
490 # we don't have tables, propose DB import
493 $template->param( "count" => $count, "proposeimport" => 1 );
497 # we have tables, propose to select files to upload or updatedatabase
499 $template->param( "count" => $count, "default" => 1 );
501 # 1st part of step 3 : check if there is a databaseversion systempreference
502 # if there is, then we just need to upgrade
503 # if there is none, then we need to install the database
505 if ( C4::Context->preference('Version') ) {
506 my $dbversion = C4::Context->preference('Version');
507 $dbversion =~ /(.*)\.(..)(..)(...)/;
508 $dbversion = "$1.$2.$3.$4";
511 "dbversion" => $dbversion,
512 "kohaversion" => Koha::version(),
520 # LANGUAGE SELECTION page by default
521 # using opendir + language Hash
522 my $languages_loop = getTranslatedLanguages('intranet');
523 $template->param( installer_languages_loop => $languages_loop );
527 "SELECT * from systempreferences WHERE variable='Version'");
528 if ( $rq->execute ) {
529 my ($version) = $rq->fetchrow;
531 print $query->redirect(
532 "/cgi-bin/koha/installer/install.pl?step=3");
538 output_html_with_http_headers $query, $cookie, $template->output;
540 sub chk_log { #returns a logfile in $dir or - if that failed - in temp dir
541 my ( $dir, $name ) = @_;
542 my $fn = $dir . '/' . $name . '.log';
543 if ( !open my $fh, '>', $fn ) {
547 File::Temp::tempfile( $name, TMPDIR => 1, SUFFIX => '.log' );
549 #if this should not work, let croak take over