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);
36 my $step = $query->param('step');
38 my $language = $query->param('language');
39 my ( $template, $loggedinuser, $cookie );
41 my $all_languages = getAllLanguages();
43 if ( defined($language) ) {
44 C4::Templates::setlanguagecookie( $query, $language, "install.pl?step=1" );
46 ( $template, $loggedinuser, $cookie ) = get_template_and_user(
48 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 $modules = $perl_modules->get_attr('missing_pm');
104 if ( scalar(@$modules) ) {
106 foreach (@$modules) {
107 my ( $module, $stats ) = each %$_;
108 $checkmodule = 0 if $stats->{'required'};
113 version => $stats->{'min_ver'},
114 require => $stats->{'required'},
115 usage => $stats->{'usage'},
119 @components = sort { $a->{'name'} cmp $b->{'name'} } @components;
121 missing_modules => \@components,
122 checkmodule => $checkmodule,
127 elsif ( $step && $step == 2 ) {
129 #STEP 2 Check Database connection and access
131 $template->param(%info);
132 my $checkdb = $query->param("checkdb");
133 $template->param( 'dbconnection' => $checkdb );
137 # Can connect to the mysql
138 $template->param( "checkdatabaseaccess" => 1 );
139 if ( $info{dbms} eq "mysql" ) {
141 #Check if database created
142 my $rv = $dbh->do("SHOW DATABASES LIKE \'$info{dbname}\'");
144 $template->param( 'checkdatabasecreated' => 1 );
147 # Check if user have all necessary grants on this database.
148 # CURRENT_USER is ANSI SQL, and doesn't require mysql table
149 # privileges, making the % check pointless, since they
150 # couldn't even check GRANTS if they couldn't connect.
151 my $rq = $dbh->prepare('SHOW GRANTS FOR CURRENT_USER');
154 while ( my ($line) = $rq->fetchrow ) {
155 my $dbname = $info{dbname};
156 if ( $line =~ m/^GRANT (.*?) ON `$dbname`\.\*/
157 || index( $line, '*.*' ) > 0 )
161 index( $line, 'ALL PRIVILEGES' ) > 0
162 || ( ( index( $line, 'SELECT' ) > 0 )
163 && ( index( $line, 'INSERT' ) > 0 )
164 && ( index( $line, 'UPDATE' ) > 0 )
165 && ( index( $line, 'DELETE' ) > 0 )
166 && ( index( $line, 'CREATE' ) > 0 )
167 && ( index( $line, 'DROP' ) > 0 ) )
171 $template->param( "checkgrantaccess" => $grantaccess );
172 } # End mysql connect check...
174 elsif ( $info{dbms} eq "Pg" ) {
176 # Check if database has been created...
178 "SELECT * FROM pg_catalog.pg_database WHERE datname = \'$info{dbname}\';"
181 $template->param( 'checkdatabasecreated' => 1 );
184 # Check if user has all necessary grants on this database...
187 FROM pg_catalog.pg_user as u
188 WHERE u.usename = \'$info{user}\';"
191 $template->param( "checkgrantaccess" => 1 );
193 } # End Pg connect check...
196 $template->param( "error" => DBI::err, "message" => DBI::errstr );
200 elsif ( $step && $step == 3 ) {
202 # STEP 3 : database setup
204 my $op = $query->param('op');
205 if ( $op && $op eq 'finished' ) {
207 # we have finished, just redirect to mainpage.
209 print $query->redirect("/cgi-bin/koha/mainpage.pl");
212 elsif ( $op && $op eq 'finish' ) {
213 $installer->set_version_syspref();
215 my $langchoice = $query->param('fwklanguage');
216 $langchoice = $query->cookie('KohaOpacLanguage') unless ($langchoice);
217 $langchoice =~ s/[^a-zA-Z_-]*//g;
218 $installer->set_languages_syspref($langchoice);
220 # Installation is finished.
221 # We just deny anybody access to install
222 # And we redirect people to mainpage.
223 # The installer will have to relogin since we do not pass cookie to redirection.
224 $template->param( "$op" => 1 );
227 elsif ( $op && $op eq 'addframeworks' ) {
229 # 1ST install, 3rd sub-step : insert the SQL files the user has selected
231 my ( $fwk_language, $list ) =
232 $installer->load_sql_in_order( $all_languages,
233 $query->multi_param('framework') );
235 "fwklanguage" => $fwk_language,
238 use Koha::SearchEngine::Elasticsearch;
239 Koha::SearchEngine::Elasticsearch->reset_elasticsearch_mappings;
240 $template->param( "$op" => 1 );
242 elsif ( $op && $op eq 'selectframeworks' ) {
245 # 1ST install, 2nd sub-step : show the user the sql datas they can insert in the database.
248 # (note that the term "selectframeworks is not correct. The user can select various files, not only frameworks)
251 #sql data for import are supposed to be located in installer/data/<language>/<level>
252 # Where <language> is en|fr or any international abbreviation (provided language hash is updated... This will be a problem with internationlisation.)
253 # Where <level> is a category of requirement : required, recommended optional
254 # level should contain :
255 # SQL File for import With a readable name.
256 # txt File that explains what this SQL File is meant for.
257 # Could be VERY useful to have A Big file for a kind of library.
258 # But could also be useful to have some Authorised values data set prepared here.
259 # Framework Selection is achieved through checking boxes.
260 my $langchoice = $query->param('fwklanguage');
261 $langchoice = $query->cookie('KohaOpacLanguage') unless ($langchoice);
262 $langchoice =~ s/[^a-zA-Z_-]*//g;
263 my $marcflavour = $query->param('marcflavour');
265 $installer->set_marcflavour_syspref($marcflavour);
267 $marcflavour = C4::Context->preference('marcflavour')
268 unless ($marcflavour);
270 #Insert into database the selected marcflavour
272 my ( $marc_defaulted_to_en, $fwklist ) =
273 $installer->marc_framework_sql_list( $langchoice, $marcflavour );
274 $template->param( 'en_marc_frameworks' => $marc_defaulted_to_en );
275 $template->param( "frameworksloop" => $fwklist );
276 $template->param( "marcflavour" => ucfirst($marcflavour) );
278 my ( $sample_defaulted_to_en, $levellist ) =
279 $installer->sample_data_sql_list($langchoice);
280 $template->param( "en_sample_data" => $sample_defaulted_to_en );
281 $template->param( "levelloop" => $levellist );
282 $template->param( "$op" => 1 );
285 elsif ( $op && $op eq 'choosemarc' ) {
288 # 1ST install, 2nd sub-step : show the user the marcflavour available.
293 #sql data are supposed to be located in installer/data/<dbms>/<language>/marcflavour/marcflavourname
294 # Where <dbms> is database type according to DBD syntax
295 # Where <language> is en|fr or any international abbreviation (provided language hash is updated... This will be a problem with internationlisation.)
296 # Where <level> is a category of requirement : required, recommended optional
297 # level should contain :
298 # SQL File for import With a readable name.
299 # txt File that explains what this SQL File is meant for.
300 # Could be VERY useful to have A Big file for a kind of library.
301 # But could also be useful to have some Authorised values data set prepared here.
302 # Marcflavour Selection is achieved through radiobuttons.
303 my $langchoice = $query->param('fwklanguage');
305 $langchoice = $query->cookie('KohaOpacLanguage') unless ($langchoice);
306 $langchoice =~ s/[^a-zA-Z_-]*//g;
308 C4::Context->config('intranetdir')
309 . "/installer/data/$info{dbms}/$langchoice/marcflavour";
310 unless ( opendir( MYDIR, $dir ) ) {
311 if ( $langchoice eq 'en' ) {
312 warn "cannot open MARC frameworks directory $dir";
315 # if no translated MARC framework is available,
317 $dir = C4::Context->config('intranetdir')
318 . "/installer/data/$info{dbms}/en/marcflavour";
319 opendir( MYDIR, $dir )
320 or warn "cannot open English MARC frameworks directory $dir";
323 my @listdir = grep { !/^\./ && -d "$dir/$_" } readdir(MYDIR);
325 my $marcflavour = C4::Context->preference("marcflavour");
327 foreach my $marc (@listdir) {
329 "label"=> ucfirst($marc),
331 "checked"=> defined($marcflavour) ? uc($marc) eq $marcflavour : 0);
332 # $cell{"description"}= do { local $/ = undef; open INPUT "<$dir/$marc.txt"||"";<INPUT> };
333 push @flavourlist, \%cell;
335 $template->param( "flavourloop" => \@flavourlist );
336 $template->param( "$op" => 1 );
338 elsif ( $op && $op eq 'importdatastructure' ) {
341 # 1st install, 1st "sub-step" : import kohastructure
344 my $error = $installer->load_db_schema();
350 elsif ( $op && $op eq 'updatestructure' ) {
352 # Not 1st install, the only sub-step : update database
354 #Do updatedatabase And report
356 if ( !defined $ENV{PERL5LIB} ) {
357 my $find = "C4/Context.pm";
358 my $path = $INC{$find};
359 $path =~ s/\Q$find\E//;
360 $ENV{PERL5LIB} = "$path:$path/installer";
361 warn "# plack? inserted PERL5LIB $ENV{PERL5LIB}\n";
364 my $now = POSIX::strftime( "%Y-%m-%dT%H:%M:%S", localtime() );
365 my $logdir = C4::Context->config('logdir');
366 my $dbversion = C4::Context->preference('Version');
367 my $kohaversion = Koha::version;
368 $kohaversion =~ s/(.*\..*)\.(.*)\.(.*)/$1$2$3/;
370 my $filename_suffix = join '_', $now, $dbversion, $kohaversion;
371 my ( $logfilepath, $logfilepath_errors ) = (
372 chk_log( $logdir, "updatedatabase_$filename_suffix" ),
373 chk_log( $logdir, "updatedatabase-error_$filename_suffix" )
376 my $cmd = C4::Context->config("intranetdir")
377 . "/installer/data/$info{dbms}/updatedatabase.pl >> $logfilepath 2>> $logfilepath_errors";
382 open( $fh, "<:encoding(utf-8)", $logfilepath )
383 or die "Cannot open log file $logfilepath: $!";
387 $template->param( update_report =>
388 [ map { { line => $_ } } split( /\n/, join( '', @report ) ) ]
390 $template->param( has_update_succeeds => 1 );
393 eval { `rm $logfilepath` };
395 open( $fh, "<:encoding(utf-8)", $logfilepath_errors )
396 or die "Cannot open log file $logfilepath_errors: $!";
400 $template->param( update_errors =>
401 [ map { { line => $_ } } split( /\n/, join( '', @report ) ) ]
403 $template->param( has_update_errors => 1 );
405 "The following errors were returned while attempting to run the updatedatabase.pl script:\n";
406 foreach my $line (@report) { warn "$line\n"; }
409 eval { `rm $logfilepath_errors` };
411 $template->param( $op => 1 );
415 # check whether it's a 1st install or an update
417 #Check if there are enough tables.
418 # Paul has cleaned up tables so reduced the count
419 #I put it there because it implied a data import if condition was not satisfied.
420 my $dbh = DBI->connect(
421 "DBI:$info{dbms}:dbname=$info{dbname};host=$info{hostname}"
422 . ( $info{port} ? ";port=$info{port}" : "" )
423 . ( $info{tlsoptions} ? $info{tlsoptions} : "" ),
424 $info{'user'}, $info{'password'}
427 if ( $info{dbms} eq 'mysql' ) { $rq = $dbh->prepare("SHOW TABLES"); }
428 elsif ( $info{dbms} eq 'Pg' ) {
431 FROM information_schema.tables
432 WHERE table_schema='public' and table_type='BASE TABLE';"
436 my $data = $rq->fetchall_arrayref( {} );
437 my $count = scalar(@$data);
439 # we don't have tables, propose DB import
442 $template->param( "count" => $count, "proposeimport" => 1 );
446 # we have tables, propose to select files to upload or updatedatabase
448 $template->param( "count" => $count, "default" => 1 );
450 # 1st part of step 3 : check if there is a databaseversion systempreference
451 # if there is, then we just need to upgrade
452 # if there is none, then we need to install the database
454 if ( C4::Context->preference('Version') ) {
455 my $dbversion = C4::Context->preference('Version');
456 $dbversion =~ /(.*)\.(..)(..)(...)/;
457 $dbversion = "$1.$2.$3.$4";
460 "dbversion" => $dbversion,
461 "kohaversion" => Koha::version(),
469 # LANGUAGE SELECTION page by default
470 # using opendir + language Hash
471 my $languages_loop = getTranslatedLanguages('intranet');
472 $template->param( installer_languages_loop => $languages_loop );
476 "SELECT * from systempreferences WHERE variable='Version'");
477 if ( $rq->execute ) {
478 my ($version) = $rq->fetchrow;
480 print $query->redirect(
481 "/cgi-bin/koha/installer/install.pl?step=3");
487 output_html_with_http_headers $query, $cookie, $template->output;
489 sub chk_log { #returns a logfile in $dir or - if that failed - in temp dir
490 my ( $dir, $name ) = @_;
491 my $fn = $dir . '/' . $name . '.log';
492 if ( !open my $fh, '>', $fn ) {
496 File::Temp::tempfile( $name, TMPDIR => 1, SUFFIX => '.log' );
498 #if this should not work, let croak take over