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;
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",
55 my $installer = C4::Installer->new();
57 $info{'dbname'} = C4::Context->config("database_test") || 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 $missing_modules = $perl_modules->get_attr('missing_pm');
103 my $upgrade_modules = $perl_modules->get_attr('upgrade_pm');
104 if ( scalar(@$missing_modules) || scalar(@$upgrade_modules) ) {
107 foreach (@$missing_modules) {
108 my ( $module, $stats ) = each %$_;
109 $checkmodule = 0 if $stats->{'required'};
114 min_version => $stats->{'min_ver'},
115 max_version => $stats->{'max_ver'},
116 require => $stats->{'required'}
120 foreach (@$upgrade_modules) {
121 my ( $module, $stats ) = each %$_;
122 $checkmodule = 0 if $stats->{'required'};
127 min_version => $stats->{'min_ver'},
128 max_version => $stats->{'max_ver'},
129 require => $stats->{'required'}
133 @missing = sort { $a->{'name'} cmp $b->{'name'} } @missing;
134 @upgrade = sort { $a->{'name'} cmp $b->{'name'} } @upgrade;
136 missing_modules => \@missing,
137 upgrade_modules => \@upgrade,
138 checkmodule => $checkmodule,
143 elsif ( $step && $step == 2 ) {
145 #STEP 2 Check Database connection and access
147 $template->param(%info);
148 my $checkdb = $query->param("checkdb");
149 $template->param( 'dbconnection' => $checkdb );
153 # Can connect to the mysql
154 $template->param( "checkdatabaseaccess" => 1 );
155 if ( $info{dbms} eq "mysql" ) {
157 #Check if database created
158 my $rv = $dbh->do("SHOW DATABASES LIKE \'$info{dbname}\'");
160 $template->param( 'checkdatabasecreated' => 1 );
163 # Check if user have all necessary grants on this database.
164 # CURRENT_USER is ANSI SQL, and doesn't require mysql table
165 # privileges, making the % check pointless, since they
166 # couldn't even check GRANTS if they couldn't connect.
167 my $rq = $dbh->prepare('SHOW GRANTS FOR CURRENT_USER');
170 while ( my ($line) = $rq->fetchrow ) {
171 my $dbname = $info{dbname};
172 if ( $line =~ m/^GRANT (.*?) ON `$dbname`\.\*/
173 || index( $line, '*.*' ) > 0 )
177 index( $line, 'ALL PRIVILEGES' ) > 0
178 || ( ( index( $line, 'SELECT' ) > 0 )
179 && ( index( $line, 'INSERT' ) > 0 )
180 && ( index( $line, 'UPDATE' ) > 0 )
181 && ( index( $line, 'DELETE' ) > 0 )
182 && ( index( $line, 'CREATE' ) > 0 )
183 && ( index( $line, 'DROP' ) > 0 ) )
187 $template->param( "checkgrantaccess" => $grantaccess );
189 if ( my $count = $installer->has_non_dynamic_row_format ) {
190 $template->param( warnDbRowFormat => $count );
191 $template->param( error => "InnoDB row format" );
194 } # End mysql connect check...
196 elsif ( $info{dbms} eq "Pg" ) {
198 # Check if database has been created...
200 "SELECT * FROM pg_catalog.pg_database WHERE datname = \'$info{dbname}\';"
203 $template->param( 'checkdatabasecreated' => 1 );
206 # Check if user has all necessary grants on this database...
209 FROM pg_catalog.pg_user as u
210 WHERE u.usename = \'$info{user}\';"
213 $template->param( "checkgrantaccess" => 1 );
215 } # End Pg connect check...
218 $template->param( "error" => DBI::err, "message" => DBI::errstr );
222 elsif ( $step && $step == 3 ) {
224 # STEP 3 : database setup
226 my $op = $query->param('op');
227 if ( $op && $op eq 'finished' ) {
228 # Remove the HandleError set at the beginning of the installer process
229 C4::Context->dbh->disconnect;
231 # we have finished, just redirect to mainpage.
232 print $query->redirect("/cgi-bin/koha/mainpage.pl");
235 elsif ( $op && $op eq 'finish' ) {
236 $installer->set_version_syspref();
238 my $langchoice = $query->param('fwklanguage');
239 $langchoice = $query->cookie('KohaOpacLanguage') unless ($langchoice);
240 $langchoice =~ s/[^a-zA-Z_-]*//g;
241 $installer->set_languages_syspref($langchoice);
243 # Installation is finished.
244 # We just deny anybody access to install
245 # And we redirect people to mainpage.
246 # The installer will have to relogin since we do not pass cookie to redirection.
247 $template->param( "$op" => 1 );
250 elsif ( $op && $op eq 'addframeworks' ) {
252 # 1ST install, 3rd sub-step : insert the SQL files the user has selected
253 my $langchoice = $query->param('fwklanguage');
254 $langchoice = $query->cookie('KohaOpacLanguage') unless ($langchoice);
255 $langchoice =~ s/[^a-zA-Z_-]*//g;
257 my ( $fwk_language, $list ) =
258 $installer->load_sql_in_order( $langchoice, $all_languages,
259 $query->multi_param('framework') );
261 "fwklanguage" => $fwk_language,
264 use Koha::SearchEngine::Elasticsearch;
265 Koha::SearchEngine::Elasticsearch->reset_elasticsearch_mappings;
266 $template->param( "$op" => 1 );
268 elsif ( $op && $op eq 'selectframeworks' ) {
271 # 1ST install, 2nd sub-step : show the user the sql datas they can insert in the database.
274 # (note that the term "selectframeworks is not correct. The user can select various files, not only frameworks)
277 #sql data for import are supposed to be located in installer/data/<language>/<level>
278 # Where <language> is en|fr or any international abbreviation (provided language hash is updated... This will be a problem with internationlisation.)
279 # Where <level> is a category of requirement : required, recommended optional
280 # level should contain :
281 # SQL File for import With a readable name.
282 # txt File that explains what this SQL File is meant for.
283 # Could be VERY useful to have A Big file for a kind of library.
284 # But could also be useful to have some Authorised values data set prepared here.
285 # Framework Selection is achieved through checking boxes.
286 my $langchoice = $query->param('fwklanguage');
287 $langchoice = $query->cookie('KohaOpacLanguage') unless ($langchoice);
288 $langchoice =~ s/[^a-zA-Z_-]*//g;
289 my $marcflavour = $query->param('marcflavour');
291 $installer->set_marcflavour_syspref($marcflavour);
293 $marcflavour = C4::Context->preference('marcflavour')
294 unless ($marcflavour);
296 #Insert into database the selected marcflavour
298 my ( $marc_defaulted_to_en, $fwklist ) =
299 $installer->marc_framework_sql_list( $langchoice, $marcflavour );
300 $template->param( 'en_marc_frameworks' => $marc_defaulted_to_en );
301 $template->param( "frameworksloop" => $fwklist );
302 $template->param( "marcflavour" => ucfirst($marcflavour) );
304 my ( $sample_defaulted_to_en, $levellist ) =
305 $installer->sample_data_sql_list($langchoice);
306 $template->param( "en_sample_data" => $sample_defaulted_to_en );
307 $template->param( "levelloop" => $levellist );
308 $template->param( "$op" => 1 );
311 elsif ( $op && $op eq 'choosemarc' ) {
314 # 1ST install, 2nd sub-step : show the user the marcflavour available.
319 #sql data are supposed to be located in installer/data/<dbms>/<language>/marcflavour/marcflavourname
320 # Where <dbms> is database type according to DBD syntax
321 # Where <language> is en|fr or any international abbreviation (provided language hash is updated... This will be a problem with internationlisation.)
322 # Where <level> is a category of requirement : required, recommended optional
323 # level should contain :
324 # SQL File for import With a readable name.
325 # txt File that explains what this SQL File is meant for.
326 # Could be VERY useful to have A Big file for a kind of library.
327 # But could also be useful to have some Authorised values data set prepared here.
328 # Marcflavour Selection is achieved through radiobuttons.
329 my $langchoice = $query->param('fwklanguage');
331 $langchoice = $query->cookie('KohaOpacLanguage') unless ($langchoice);
332 $langchoice =~ s/[^a-zA-Z_-]*//g;
334 C4::Context->config('intranetdir')
335 . "/installer/data/$info{dbms}/$langchoice/marcflavour";
337 unless ( opendir( $dir_h, $dir ) ) {
338 if ( $langchoice eq 'en' ) {
339 warn "cannot open MARC frameworks directory $dir";
342 # if no translated MARC framework is available,
344 $dir = C4::Context->config('intranetdir')
345 . "/installer/data/$info{dbms}/en/marcflavour";
346 opendir( $dir_h, $dir )
347 or warn "cannot open English MARC frameworks directory $dir";
350 my @listdir = grep { !/^\./ && -d "$dir/$_" } readdir($dir_h);
352 my $marcflavour = C4::Context->preference("marcflavour");
354 foreach my $marc (@listdir) {
356 "label"=> ucfirst($marc),
358 "checked"=> defined($marcflavour) ? uc($marc) eq $marcflavour : 0);
359 # $cell{"description"}= do { local $/ = undef; open INPUT "<$dir/$marc.txt"||"";<INPUT> };
360 push @flavourlist, \%cell;
362 $template->param( "flavourloop" => \@flavourlist );
363 $template->param( "$op" => 1 );
365 elsif ( $op && $op eq 'importdatastructure' ) {
368 # 1st install, 1st "sub-step" : import kohastructure
371 my $error = $installer->load_db_schema();
377 elsif ( $op && $op eq 'updatestructure' ) {
379 # Not 1st install, the only sub-step : update database
381 #Do updatedatabase And report
383 if ( !defined $ENV{PERL5LIB} ) {
384 my $find = "C4/Context.pm";
385 my $path = $INC{$find};
386 $path =~ s/\Q$find\E//;
387 $ENV{PERL5LIB} = "$path:$path/installer";
388 warn "# plack? inserted PERL5LIB $ENV{PERL5LIB}\n";
391 my $now = POSIX::strftime( "%Y-%m-%dT%H:%M:%S", localtime() );
392 my $logdir = C4::Context->config('logdir');
393 my $dbversion = C4::Context->preference('Version');
394 my $kohaversion = Koha::version;
395 $kohaversion =~ s/(.*\..*)\.(.*)\.(.*)/$1$2$3/;
397 my $filename_suffix = join '_', $now, $dbversion, $kohaversion;
398 my ( $logfilepath, $logfilepath_errors ) = (
399 chk_log( $logdir, "updatedatabase_$filename_suffix" ),
400 chk_log( $logdir, "updatedatabase-error_$filename_suffix" )
403 my $cmd = C4::Context->config("intranetdir")
404 . "/installer/data/$info{dbms}/updatedatabase.pl >> $logfilepath 2>> $logfilepath_errors";
409 open( $fh, "<:encoding(utf-8)", $logfilepath )
410 or die "Cannot open log file $logfilepath: $!";
414 $template->param( update_report =>
415 [ map { { line => $_ =~ s/\t/  /gr } } split( /\n/, join( '', @report ) ) ]
417 $template->param( has_update_succeeds => 1 );
420 eval { `rm $logfilepath` };
422 open( $fh, "<:encoding(utf-8)", $logfilepath_errors )
423 or die "Cannot open log file $logfilepath_errors: $!";
428 $template->param( update_errors =>
429 [ map { { line => $_ } } split( /\n/, join( '', @report ) ) ]
432 $template->param( has_update_errors => 1 );
434 "The following errors were returned while attempting to run the updatedatabase.pl script:\n";
435 foreach my $line (@report) { warn "$line\n"; }
438 eval { `rm $logfilepath_errors` };
441 unless ( $update_errors ) {
442 my $db_entries = get_db_entries();
443 my $report = update( $db_entries );
444 my $atomic_update_files = get_atomic_updates;
445 my $atomic_update_report = run_atomic_updates( $atomic_update_files );
448 success => $report->{success},
449 error => $report->{error},
451 success => $atomic_update_report->{success},
452 error => $atomic_update_report->{error}
457 $template->param( $op => 1 );
461 # check whether it's a 1st install or an update
463 #Check if there are enough tables.
464 # Paul has cleaned up tables so reduced the count
465 #I put it there because it implied a data import if condition was not satisfied.
466 my $dbh = DBI->connect(
467 "DBI:$info{dbms}:dbname=$info{dbname};host=$info{hostname}"
468 . ( $info{port} ? ";port=$info{port}" : "" )
469 . ( $info{tlsoptions} ? $info{tlsoptions} : "" ),
470 $info{'user'}, $info{'password'}
473 if ( $info{dbms} eq 'mysql' ) { $rq = $dbh->prepare("SHOW TABLES"); }
474 elsif ( $info{dbms} eq 'Pg' ) {
477 FROM information_schema.tables
478 WHERE table_schema='public' and table_type='BASE TABLE';"
482 my $data = $rq->fetchall_arrayref( {} );
483 my $count = scalar(@$data);
485 # we don't have tables, propose DB import
488 $template->param( "count" => $count, "proposeimport" => 1 );
492 # we have tables, propose to select files to upload or updatedatabase
494 $template->param( "count" => $count, "default" => 1 );
496 # 1st part of step 3 : check if there is a databaseversion systempreference
497 # if there is, then we just need to upgrade
498 # if there is none, then we need to install the database
500 if ( C4::Context->preference('Version') ) {
501 my $dbversion = C4::Context->preference('Version');
502 $dbversion =~ /(.*)\.(..)(..)(...)/;
503 $dbversion = "$1.$2.$3.$4";
506 "dbversion" => $dbversion,
507 "kohaversion" => Koha::version(),
515 # LANGUAGE SELECTION page by default
516 # using opendir + language Hash
517 my $languages_loop = getTranslatedLanguages('intranet');
518 $template->param( installer_languages_loop => $languages_loop );
522 "SELECT * from systempreferences WHERE variable='Version'");
523 if ( $rq->execute ) {
524 my ($version) = $rq->fetchrow;
526 print $query->redirect(
527 "/cgi-bin/koha/installer/install.pl?step=3");
533 output_html_with_http_headers $query, $cookie, $template->output;
535 sub chk_log { #returns a logfile in $dir or - if that failed - in temp dir
536 my ( $dir, $name ) = @_;
537 my $fn = $dir . '/' . $name . '.log';
538 if ( !open my $fh, '>', $fn ) {
542 File::Temp::tempfile( $name, TMPDIR => 1, SUFFIX => '.log' );
544 #if this should not work, let croak take over