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);
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",
56 my $installer = C4::Installer->new();
58 $info{'dbname'} = C4::Context->config("database");
60 C4::Context->config("db_scheme")
61 ? C4::Context->config("db_scheme")
64 $info{'hostname'} = C4::Context->config("hostname");
65 $info{'port'} = C4::Context->config("port");
66 $info{'user'} = C4::Context->config("user");
67 $info{'password'} = C4::Context->config("pass");
68 $info{'tls'} = C4::Context->config("tls");
69 if ($info{'tls'} && $info{'tls'} eq 'yes'){
70 $info{'ca'} = C4::Context->config('ca');
71 $info{'cert'} = C4::Context->config('cert');
72 $info{'key'} = C4::Context->config('key');
73 $info{'tlsoptions'} = ";mysql_ssl=1;mysql_ssl_client_key=".$info{key}.";mysql_ssl_client_cert=".$info{cert}.";mysql_ssl_ca_file=".$info{ca};
74 $info{'tlscmdline'} = " --ssl-cert ". $info{cert} . " --ssl-key " . $info{key} . " --ssl-ca ".$info{ca}." "
77 my $dbh = DBI->connect(
78 "DBI:$info{dbms}:dbname=$info{dbname};host=$info{hostname}"
79 . ( $info{port} ? ";port=$info{port}" : "" )
80 . ( $info{tlsoptions} ? $info{tlsoptions} : "" ),
81 $info{'user'}, $info{'password'}
84 if ( $step && $step == 1 ) {
86 #First Step (for both fresh installations and upgrades)
87 #Checking ALL perl Modules and services needed are installed.
88 #Whenever there is an error, adding a report to the page
89 my $op = $query->param('op') || 'noop';
90 $template->param( language => 1 );
92 $template->param( 'checkmodule' => 1 )
93 ; # we start with the assumption that there are no problems and set this to 0 if there are
95 unless ( $] >= 5.010000 ) { # Bug 7375
96 $template->param( problems => 1, perlversion => 1, checkmodule => 0 );
100 my $perl_modules = C4::Installer::PerlModules->new;
101 $perl_modules->versions_info;
103 my $missing_modules = $perl_modules->get_attr('missing_pm');
104 my $upgrade_modules = $perl_modules->get_attr('upgrade_pm');
105 if ( scalar(@$missing_modules) || scalar(@$upgrade_modules) ) {
108 foreach (@$missing_modules) {
109 my ( $module, $stats ) = each %$_;
110 $checkmodule = 0 if $stats->{'required'};
115 min_version => $stats->{'min_ver'},
116 max_version => $stats->{'max_ver'},
117 require => $stats->{'required'}
121 foreach (@$upgrade_modules) {
122 my ( $module, $stats ) = each %$_;
123 $checkmodule = 0 if $stats->{'required'};
128 min_version => $stats->{'min_ver'},
129 max_version => $stats->{'max_ver'},
130 require => $stats->{'required'}
134 @missing = sort { $a->{'name'} cmp $b->{'name'} } @missing;
135 @upgrade = sort { $a->{'name'} cmp $b->{'name'} } @upgrade;
137 missing_modules => \@missing,
138 upgrade_modules => \@upgrade,
139 checkmodule => $checkmodule,
144 elsif ( $step && $step == 2 ) {
146 #STEP 2 Check Database connection and access
148 $template->param(%info);
149 my $checkdb = $query->param("checkdb");
150 $template->param( 'dbconnection' => $checkdb );
154 # Can connect to the mysql
155 $template->param( "checkdatabaseaccess" => 1 );
156 if ( $info{dbms} eq "mysql" ) {
158 #Check if database created
159 my $rv = $dbh->do("SHOW DATABASES LIKE \'$info{dbname}\'");
161 $template->param( 'checkdatabasecreated' => 1 );
164 # Check if user have all necessary grants on this database.
165 # CURRENT_USER is ANSI SQL, and doesn't require mysql table
166 # privileges, making the % check pointless, since they
167 # couldn't even check GRANTS if they couldn't connect.
168 my $rq = $dbh->prepare('SHOW GRANTS FOR CURRENT_USER');
171 while ( my ($line) = $rq->fetchrow ) {
172 my $dbname = $info{dbname};
173 if ( $line =~ m/^GRANT (.*?) ON `$dbname`\.\*/
174 || index( $line, '*.*' ) > 0 )
178 index( $line, 'ALL PRIVILEGES' ) > 0
179 || ( ( index( $line, 'SELECT' ) > 0 )
180 && ( index( $line, 'INSERT' ) > 0 )
181 && ( index( $line, 'UPDATE' ) > 0 )
182 && ( index( $line, 'DELETE' ) > 0 )
183 && ( index( $line, 'CREATE' ) > 0 )
184 && ( index( $line, 'DROP' ) > 0 ) )
188 $template->param( "checkgrantaccess" => $grantaccess );
189 } # End mysql connect check...
191 elsif ( $info{dbms} eq "Pg" ) {
193 # Check if database has been created...
195 "SELECT * FROM pg_catalog.pg_database WHERE datname = \'$info{dbname}\';"
198 $template->param( 'checkdatabasecreated' => 1 );
201 # Check if user has all necessary grants on this database...
204 FROM pg_catalog.pg_user as u
205 WHERE u.usename = \'$info{user}\';"
208 $template->param( "checkgrantaccess" => 1 );
210 } # End Pg connect check...
213 $template->param( "error" => DBI::err, "message" => DBI::errstr );
217 elsif ( $step && $step == 3 ) {
219 # STEP 3 : database setup
221 my $op = $query->param('op');
222 if ( $op && $op eq 'finished' ) {
224 # we have finished, just redirect to mainpage.
226 print $query->redirect("/cgi-bin/koha/mainpage.pl");
229 elsif ( $op && $op eq 'finish' ) {
230 $installer->set_version_syspref();
232 my $langchoice = $query->param('fwklanguage');
233 $langchoice = $query->cookie('KohaOpacLanguage') unless ($langchoice);
234 $langchoice =~ s/[^a-zA-Z_-]*//g;
235 $installer->set_languages_syspref($langchoice);
237 # Installation is finished.
238 # We just deny anybody access to install
239 # And we redirect people to mainpage.
240 # The installer will have to relogin since we do not pass cookie to redirection.
241 $template->param( "$op" => 1 );
244 elsif ( $op && $op eq 'addframeworks' ) {
246 # 1ST install, 3rd sub-step : insert the SQL files the user has selected
248 my ( $fwk_language, $list ) =
249 $installer->load_sql_in_order( $all_languages,
250 $query->multi_param('framework') );
252 "fwklanguage" => $fwk_language,
255 use Koha::SearchEngine::Elasticsearch;
256 Koha::SearchEngine::Elasticsearch->reset_elasticsearch_mappings;
257 $template->param( "$op" => 1 );
259 elsif ( $op && $op eq 'selectframeworks' ) {
262 # 1ST install, 2nd sub-step : show the user the sql datas they can insert in the database.
265 # (note that the term "selectframeworks is not correct. The user can select various files, not only frameworks)
268 #sql data for import are supposed to be located in installer/data/<language>/<level>
269 # Where <language> is en|fr or any international abbreviation (provided language hash is updated... This will be a problem with internationlisation.)
270 # Where <level> is a category of requirement : required, recommended optional
271 # level should contain :
272 # SQL File for import With a readable name.
273 # txt File that explains what this SQL File is meant for.
274 # Could be VERY useful to have A Big file for a kind of library.
275 # But could also be useful to have some Authorised values data set prepared here.
276 # Framework Selection is achieved through checking boxes.
277 my $langchoice = $query->param('fwklanguage');
278 $langchoice = $query->cookie('KohaOpacLanguage') unless ($langchoice);
279 $langchoice =~ s/[^a-zA-Z_-]*//g;
280 my $marcflavour = $query->param('marcflavour');
282 $installer->set_marcflavour_syspref($marcflavour);
284 $marcflavour = C4::Context->preference('marcflavour')
285 unless ($marcflavour);
287 #Insert into database the selected marcflavour
289 my ( $marc_defaulted_to_en, $fwklist ) =
290 $installer->marc_framework_sql_list( $langchoice, $marcflavour );
291 $template->param( 'en_marc_frameworks' => $marc_defaulted_to_en );
292 $template->param( "frameworksloop" => $fwklist );
293 $template->param( "marcflavour" => ucfirst($marcflavour) );
295 my ( $sample_defaulted_to_en, $levellist ) =
296 $installer->sample_data_sql_list($langchoice);
297 $template->param( "en_sample_data" => $sample_defaulted_to_en );
298 $template->param( "levelloop" => $levellist );
299 $template->param( "$op" => 1 );
302 elsif ( $op && $op eq 'choosemarc' ) {
305 # 1ST install, 2nd sub-step : show the user the marcflavour available.
310 #sql data are supposed to be located in installer/data/<dbms>/<language>/marcflavour/marcflavourname
311 # Where <dbms> is database type according to DBD syntax
312 # Where <language> is en|fr or any international abbreviation (provided language hash is updated... This will be a problem with internationlisation.)
313 # Where <level> is a category of requirement : required, recommended optional
314 # level should contain :
315 # SQL File for import With a readable name.
316 # txt File that explains what this SQL File is meant for.
317 # Could be VERY useful to have A Big file for a kind of library.
318 # But could also be useful to have some Authorised values data set prepared here.
319 # Marcflavour Selection is achieved through radiobuttons.
320 my $langchoice = $query->param('fwklanguage');
322 $langchoice = $query->cookie('KohaOpacLanguage') unless ($langchoice);
323 $langchoice =~ s/[^a-zA-Z_-]*//g;
325 C4::Context->config('intranetdir')
326 . "/installer/data/$info{dbms}/$langchoice/marcflavour";
327 unless ( opendir( MYDIR, $dir ) ) {
328 if ( $langchoice eq 'en' ) {
329 warn "cannot open MARC frameworks directory $dir";
332 # if no translated MARC framework is available,
334 $dir = C4::Context->config('intranetdir')
335 . "/installer/data/$info{dbms}/en/marcflavour";
336 opendir( MYDIR, $dir )
337 or warn "cannot open English MARC frameworks directory $dir";
340 my @listdir = grep { !/^\./ && -d "$dir/$_" } readdir(MYDIR);
342 my $marcflavour = C4::Context->preference("marcflavour");
344 foreach my $marc (@listdir) {
346 "label"=> ucfirst($marc),
348 "checked"=> defined($marcflavour) ? uc($marc) eq $marcflavour : 0);
349 # $cell{"description"}= do { local $/ = undef; open INPUT "<$dir/$marc.txt"||"";<INPUT> };
350 push @flavourlist, \%cell;
352 $template->param( "flavourloop" => \@flavourlist );
353 $template->param( "$op" => 1 );
355 elsif ( $op && $op eq 'importdatastructure' ) {
358 # 1st install, 1st "sub-step" : import kohastructure
361 my $error = $installer->load_db_schema();
367 elsif ( $op && $op eq 'updatestructure' ) {
369 # Not 1st install, the only sub-step : update database
371 #Do updatedatabase And report
373 if ( !defined $ENV{PERL5LIB} ) {
374 my $find = "C4/Context.pm";
375 my $path = $INC{$find};
376 $path =~ s/\Q$find\E//;
377 $ENV{PERL5LIB} = "$path:$path/installer";
378 warn "# plack? inserted PERL5LIB $ENV{PERL5LIB}\n";
381 my $now = POSIX::strftime( "%Y-%m-%dT%H:%M:%S", localtime() );
382 my $logdir = C4::Context->config('logdir');
383 my $dbversion = C4::Context->preference('Version');
384 my $kohaversion = Koha::version;
385 $kohaversion =~ s/(.*\..*)\.(.*)\.(.*)/$1$2$3/;
387 my $filename_suffix = join '_', $now, $dbversion, $kohaversion;
388 my ( $logfilepath, $logfilepath_errors ) = (
389 chk_log( $logdir, "updatedatabase_$filename_suffix" ),
390 chk_log( $logdir, "updatedatabase-error_$filename_suffix" )
393 my $cmd = C4::Context->config("intranetdir")
394 . "/installer/data/$info{dbms}/updatedatabase.pl >> $logfilepath 2>> $logfilepath_errors";
399 open( $fh, "<:encoding(utf-8)", $logfilepath )
400 or die "Cannot open log file $logfilepath: $!";
404 $template->param( update_report =>
405 [ map { { line => $_ =~ s/\t/  /gr } } split( /\n/, join( '', @report ) ) ]
407 $template->param( has_update_succeeds => 1 );
410 eval { `rm $logfilepath` };
412 open( $fh, "<:encoding(utf-8)", $logfilepath_errors )
413 or die "Cannot open log file $logfilepath_errors: $!";
417 $template->param( update_errors =>
418 [ map { { line => $_ } } split( /\n/, join( '', @report ) ) ]
420 $template->param( has_update_errors => 1 );
422 "The following errors were returned while attempting to run the updatedatabase.pl script:\n";
423 foreach my $line (@report) { warn "$line\n"; }
426 eval { `rm $logfilepath_errors` };
428 $template->param( $op => 1 );
432 # check whether it's a 1st install or an update
434 #Check if there are enough tables.
435 # Paul has cleaned up tables so reduced the count
436 #I put it there because it implied a data import if condition was not satisfied.
437 my $dbh = DBI->connect(
438 "DBI:$info{dbms}:dbname=$info{dbname};host=$info{hostname}"
439 . ( $info{port} ? ";port=$info{port}" : "" )
440 . ( $info{tlsoptions} ? $info{tlsoptions} : "" ),
441 $info{'user'}, $info{'password'}
444 if ( $info{dbms} eq 'mysql' ) { $rq = $dbh->prepare("SHOW TABLES"); }
445 elsif ( $info{dbms} eq 'Pg' ) {
448 FROM information_schema.tables
449 WHERE table_schema='public' and table_type='BASE TABLE';"
453 my $data = $rq->fetchall_arrayref( {} );
454 my $count = scalar(@$data);
456 # we don't have tables, propose DB import
459 $template->param( "count" => $count, "proposeimport" => 1 );
463 # we have tables, propose to select files to upload or updatedatabase
465 $template->param( "count" => $count, "default" => 1 );
467 # 1st part of step 3 : check if there is a databaseversion systempreference
468 # if there is, then we just need to upgrade
469 # if there is none, then we need to install the database
471 if ( C4::Context->preference('Version') ) {
472 my $dbversion = C4::Context->preference('Version');
473 $dbversion =~ /(.*)\.(..)(..)(...)/;
474 $dbversion = "$1.$2.$3.$4";
477 "dbversion" => $dbversion,
478 "kohaversion" => Koha::version(),
486 # LANGUAGE SELECTION page by default
487 # using opendir + language Hash
488 my $languages_loop = getTranslatedLanguages('intranet');
489 $template->param( installer_languages_loop => $languages_loop );
493 "SELECT * from systempreferences WHERE variable='Version'");
494 if ( $rq->execute ) {
495 my ($version) = $rq->fetchrow;
497 print $query->redirect(
498 "/cgi-bin/koha/installer/install.pl?step=3");
504 output_html_with_http_headers $query, $cookie, $template->output;
506 sub chk_log { #returns a logfile in $dir or - if that failed - in temp dir
507 my ( $dir, $name ) = @_;
508 my $fn = $dir . '/' . $name . '.log';
509 if ( !open my $fh, '>', $fn ) {
513 File::Temp::tempfile( $name, TMPDIR => 1, SUFFIX => '.log' );
515 #if this should not work, let croak take over