Bug 17990: Refactor Perl module versions check
[koha.git] / installer / install.pl
blob10b642292a8326b4cf671b0a52930a3c0a97f6e3
1 #!/usr/bin/perl
3 use strict;
4 use warnings;
5 use diagnostics;
7 use C4::InstallAuth;
8 use CGI qw ( -utf8 );
9 use POSIX qw(strftime);
11 use C4::Context;
12 use C4::Output;
13 use C4::Templates;
14 use C4::Languages qw(getAllLanguages getTranslatedLanguages);
15 use C4::Installer;
17 use Koha;
19 my $query = new CGI;
20 my $step = $query->param('step');
22 my $language = $query->param('language');
23 my ( $template, $loggedinuser, $cookie );
25 my $all_languages = getAllLanguages();
27 if ( defined($language) ) {
28 C4::Templates::setlanguagecookie( $query, $language, "install.pl?step=1" );
30 ( $template, $loggedinuser, $cookie ) = get_template_and_user(
32 template_name => "installer/step" . ( $step ? $step : 1 ) . ".tt",
33 query => $query,
34 type => "intranet",
35 authnotrequired => 0,
36 debug => 1,
40 my $installer = C4::Installer->new();
41 my %info;
42 $info{'dbname'} = C4::Context->config("database");
43 $info{'dbms'} =
44 ( C4::Context->config("db_scheme")
45 ? C4::Context->config("db_scheme")
46 : "mysql" );
47 $info{'hostname'} = C4::Context->config("hostname");
48 $info{'port'} = C4::Context->config("port");
49 $info{'user'} = C4::Context->config("user");
50 $info{'password'} = C4::Context->config("pass");
51 my $dbh = DBI->connect(
52 "DBI:$info{dbms}:dbname=$info{dbname};host=$info{hostname}"
53 . ( $info{port} ? ";port=$info{port}" : "" ),
54 $info{'user'}, $info{'password'}
57 if ( $step && $step == 1 ) {
58 #First Step (for both fresh installations and upgrades)
59 #Checking ALL perl Modules and services needed are installed.
60 #Whenever there is an error, adding a report to the page
61 my $op = $query->param('op') || 'noop';
62 $template->param( language => 1 );
63 $template->param( 'checkmodule' => 1 ); # we start with the assumption that there are no problems and set this to 0 if there are
65 unless ( $] >= 5.010000 ) { # Bug 7375
66 $template->param( problems => 1, perlversion => 1, checkmodule => 0 );
69 my $perl_modules = C4::Installer::PerlModules->new;
70 $perl_modules->versions_info;
72 my $modules = $perl_modules->get_attr('missing_pm');
73 if (scalar(@$modules)) {
74 my @components = ();
75 my $checkmodule = 1;
76 foreach (@$modules) {
77 my ($module, $stats) = each %$_;
78 $checkmodule = 0 if $stats->{'required'};
79 push(
80 @components,
82 name => $module,
83 version => $stats->{'min_ver'},
84 require => $stats->{'required'},
85 usage => $stats->{'usage'},
89 @components = sort {$a->{'name'} cmp $b->{'name'}} @components;
90 $template->param( missing_modules => \@components, checkmodule => $checkmodule, op => $op );
93 elsif ( $step && $step == 2 ) {
95 #STEP 2 Check Database connection and access
97 $template->param(%info);
98 my $checkdb = $query->param("checkdb");
99 $template->param( 'dbconnection' => $checkdb );
100 if ($checkdb) {
101 if ($dbh) {
103 # Can connect to the mysql
104 $template->param( "checkdatabaseaccess" => 1 );
105 if ( $info{dbms} eq "mysql" ) {
107 #Check if database created
108 my $rv = $dbh->do("SHOW DATABASES LIKE \'$info{dbname}\'");
109 if ( $rv == 1 ) {
110 $template->param( 'checkdatabasecreated' => 1 );
113 #Check if user have all necessary grants on this database.
114 my $rq =
115 $dbh->prepare(
116 "SHOW GRANTS FOR \'$info{user}\'\@'$info{hostname}'");
117 $rq->execute;
118 my $grantaccess;
119 while ( my ($line) = $rq->fetchrow ) {
120 my $dbname = $info{dbname};
121 if ( $line =~ m/^GRANT (.*?) ON `$dbname`\.\*/ || index( $line, '*.*' ) > 0 ) {
122 $grantaccess = 1
123 if (
124 index( $line, 'ALL PRIVILEGES' ) > 0
125 || ( ( index( $line, 'SELECT' ) > 0 )
126 && ( index( $line, 'INSERT' ) > 0 )
127 && ( index( $line, 'UPDATE' ) > 0 )
128 && ( index( $line, 'DELETE' ) > 0 )
129 && ( index( $line, 'CREATE' ) > 0 )
130 && ( index( $line, 'DROP' ) > 0 ) )
134 unless ($grantaccess) {
135 $rq =
136 $dbh->prepare("SHOW GRANTS FOR \'$info{user}\'\@'\%'");
137 $rq->execute;
138 while ( my ($line) = $rq->fetchrow ) {
139 my $dbname = $info{dbname};
140 if ( $line =~ m/$dbname/ || index( $line, '*.*' ) > 0 )
142 $grantaccess = 1
143 if (
144 index( $line, 'ALL PRIVILEGES' ) > 0
145 || ( ( index( $line, 'SELECT' ) > 0 )
146 && ( index( $line, 'INSERT' ) > 0 )
147 && ( index( $line, 'UPDATE' ) > 0 )
148 && ( index( $line, 'DELETE' ) > 0 )
149 && ( index( $line, 'CREATE' ) > 0 )
150 && ( index( $line, 'DROP' ) > 0 ) )
155 $template->param( "checkgrantaccess" => $grantaccess );
156 } # End mysql connect check...
158 elsif ( $info{dbms} eq "Pg" ) {
159 # Check if database has been created...
160 my $rv = $dbh->do( "SELECT * FROM pg_catalog.pg_database WHERE datname = \'$info{dbname}\';" );
161 if ( $rv == 1 ) {
162 $template->param( 'checkdatabasecreated' => 1 );
165 # Check if user has all necessary grants on this database...
166 my $rq = $dbh->do( "SELECT u.usesuper
167 FROM pg_catalog.pg_user as u
168 WHERE u.usename = \'$info{user}\';" );
169 if ( $rq == 1 ) {
170 $template->param( "checkgrantaccess" => 1 );
172 } # End Pg connect check...
174 else {
175 $template->param( "error" => DBI::err, "message" => DBI::errstr );
179 elsif ( $step && $step == 3 ) {
182 # STEP 3 : database setup
185 my $op = $query->param('op');
186 if ( $op && $op eq 'finished' ) {
188 # we have finished, just redirect to mainpage.
190 print $query->redirect("/cgi-bin/koha/mainpage.pl");
191 exit;
193 elsif ( $op && $op eq 'finish' ) {
194 $installer->set_version_syspref();
196 # Installation is finished.
197 # We just deny anybody access to install
198 # And we redirect people to mainpage.
199 # The installer will have to relogin since we do not pass cookie to redirection.
200 $template->param( "$op" => 1 );
202 elsif ( $op && $op eq 'addframeworks' ) {
204 # 1ST install, 3rd sub-step : insert the SQL files the user has selected
207 my ($fwk_language, $list) = $installer->load_sql_in_order($all_languages, $query->param('framework'));
208 $template->param(
209 "fwklanguage" => $fwk_language,
210 "list" => $list
212 use Koha::SearchEngine::Elasticsearch;
213 Koha::SearchEngine::Elasticsearch->reset_elasticsearch_mappings;
214 $template->param( "$op" => 1 );
216 elsif ( $op && $op eq 'selectframeworks' ) {
219 # 1ST install, 2nd sub-step : show the user the sql datas he can insert in the database.
222 # (note that the term "selectframeworks is not correct. The user can select various files, not only frameworks)
224 #Framework Selection
225 #sql data for import are supposed to be located in installer/data/<language>/<level>
226 # Where <language> is en|fr or any international abbreviation (provided language hash is updated... This will be a problem with internationlisation.)
227 # Where <level> is a category of requirement : required, recommended optional
228 # level should contain :
229 # SQL File for import With a readable name.
230 # txt File that explains what this SQL File is meant for.
231 # Could be VERY useful to have A Big file for a kind of library.
232 # But could also be useful to have some Authorised values data set prepared here.
233 # Framework Selection is achieved through checking boxes.
234 my $langchoice = $query->param('fwklanguage');
235 $langchoice = $query->cookie('KohaOpacLanguage') unless ($langchoice);
236 $langchoice =~ s/[^a-zA-Z_-]*//g;
237 my $marcflavour = $query->param('marcflavour');
238 if ($marcflavour){
239 $installer->set_marcflavour_syspref($marcflavour);
241 $marcflavour = C4::Context->preference('marcflavour') unless ($marcflavour);
242 #Insert into database the selected marcflavour
243 undef $/;
244 my ($marc_defaulted_to_en, $fwklist) = $installer->marc_framework_sql_list($langchoice, $marcflavour);
245 $template->param('en_marc_frameworks' => $marc_defaulted_to_en);
246 $template->param( "frameworksloop" => $fwklist );
247 $template->param( "marcflavour" => ucfirst($marcflavour));
249 my ($sample_defaulted_to_en, $levellist) = $installer->sample_data_sql_list($langchoice);
250 $template->param( "en_sample_data" => $sample_defaulted_to_en);
251 $template->param( "levelloop" => $levellist );
252 $template->param( "$op" => 1 );
254 elsif ( $op && $op eq 'choosemarc' ) {
257 # 1ST install, 2nd sub-step : show the user the marcflavour available.
261 #Choose Marc Flavour
262 #sql data are supposed to be located in installer/data/<dbms>/<language>/marcflavour/marcflavourname
263 # Where <dbms> is database type according to DBD syntax
264 # Where <language> is en|fr or any international abbreviation (provided language hash is updated... This will be a problem with internationlisation.)
265 # Where <level> is a category of requirement : required, recommended optional
266 # level should contain :
267 # SQL File for import With a readable name.
268 # txt File taht explains what this SQL File is meant for.
269 # Could be VERY useful to have A Big file for a kind of library.
270 # But could also be useful to have some Authorised values data set prepared here.
271 # Marcflavour Selection is achieved through radiobuttons.
272 my $langchoice = $query->param('fwklanguage');
273 $langchoice = $query->cookie('KohaOpacLanguage') unless ($langchoice);
274 $langchoice =~ s/[^a-zA-Z_-]*//g;
275 my $dir =
276 C4::Context->config('intranetdir') . "/installer/data/$info{dbms}/$langchoice/marcflavour";
277 unless (opendir( MYDIR, $dir )) {
278 if ($langchoice eq 'en') {
279 warn "cannot open MARC frameworks directory $dir";
280 } else {
281 # if no translated MARC framework is available,
282 # default to English
283 $dir = C4::Context->config('intranetdir') . "/installer/data/$info{dbms}/en/marcflavour";
284 opendir(MYDIR, $dir) or warn "cannot open English MARC frameworks directory $dir";
287 my @listdir = grep { !/^\./ && -d "$dir/$_" } readdir(MYDIR);
288 closedir MYDIR;
289 my $marcflavour=C4::Context->preference("marcflavour");
290 my @flavourlist;
291 foreach my $marc (@listdir) {
292 my %cell=(
293 "label"=> ucfirst($marc),
294 "code"=>uc($marc),
295 "checked"=> defined($marcflavour) ? uc($marc) eq $marcflavour : 0);
296 # $cell{"description"}= do { local $/ = undef; open INPUT "<$dir/$marc.txt"||"";<INPUT> };
297 push @flavourlist, \%cell;
299 $template->param( "flavourloop" => \@flavourlist );
300 $template->param( "$op" => 1 );
302 elsif ( $op && $op eq 'importdatastructure' ) {
305 # 1st install, 1st "sub-step" : import kohastructure
308 my $error = $installer->load_db_schema();
309 $template->param(
310 "error" => $error,
311 "$op" => 1,
314 elsif ( $op && $op eq 'updatestructure' ) {
316 # Not 1st install, the only sub-step : update database
318 #Do updatedatabase And report
320 if ( ! defined $ENV{PERL5LIB} ) {
321 my $find = "C4/Context.pm";
322 my $path = $INC{$find};
323 $path =~ s/\Q$find\E//;
324 $ENV{PERL5LIB} = "$path:$path/installer";
325 warn "# plack? inserted PERL5LIB $ENV{PERL5LIB}\n";
328 my $now = POSIX::strftime( "%Y-%m-%dT%H:%M:%S", localtime() );
329 my $logdir = C4::Context->config('logdir');
330 my $dbversion = C4::Context->preference('Version');
331 my $kohaversion = Koha::version;
332 $kohaversion =~ s/(.*\..*)\.(.*)\.(.*)/$1$2$3/;
334 my $filename_suffix = join '_', $now, $dbversion, $kohaversion;
335 my ( $logfilepath, $logfilepath_errors ) = ( chk_log($logdir, "updatedatabase_$filename_suffix"), chk_log($logdir, "updatedatabase-error_$filename_suffix") );
337 my $cmd = C4::Context->config("intranetdir") . "/installer/data/$info{dbms}/updatedatabase.pl >> $logfilepath 2>> $logfilepath_errors";
339 system($cmd );
341 my $fh;
342 open( $fh, "<", $logfilepath ) or die "Cannot open log file $logfilepath: $!";
343 my @report = <$fh>;
344 close $fh;
345 if (@report) {
346 $template->param( update_report => [ map { { line => $_ } } split( /\n/, join( '', @report ) ) ] );
347 $template->param( has_update_succeeds => 1 );
348 } else {
349 eval{ `rm $logfilepath` };
351 open( $fh, "<", $logfilepath_errors ) or die "Cannot open log file $logfilepath_errors: $!";
352 @report = <$fh>;
353 close $fh;
354 if (@report) {
355 $template->param( update_errors => [ map { { line => $_ } } split( /\n/, join( '', @report ) ) ] );
356 $template->param( has_update_errors => 1 );
357 warn "The following errors were returned while attempting to run the updatedatabase.pl script:\n";
358 foreach my $line (@report) { warn "$line\n"; }
359 } else {
360 eval{ `rm $logfilepath_errors` };
362 $template->param( $op => 1 );
364 else {
366 # check whether it's a 1st install or an update
368 #Check if there are enough tables.
369 # Paul has cleaned up tables so reduced the count
370 #I put it there because it implied a data import if condition was not satisfied.
371 my $dbh = DBI->connect(
372 "DBI:$info{dbms}:dbname=$info{dbname};host=$info{hostname}"
373 . ( $info{port} ? ";port=$info{port}" : "" ),
374 $info{'user'}, $info{'password'}
376 my $rq;
377 if ( $info{dbms} eq 'mysql' ) { $rq = $dbh->prepare( "SHOW TABLES" ); }
378 elsif ( $info{dbms} eq 'Pg' ) { $rq = $dbh->prepare( "SELECT *
379 FROM information_schema.tables
380 WHERE table_schema='public' and table_type='BASE TABLE';" ); }
381 $rq->execute;
382 my $data = $rq->fetchall_arrayref( {} );
383 my $count = scalar(@$data);
385 # we don't have tables, propose DB import
387 if ( $count < 70 ) {
388 $template->param( "count" => $count, "proposeimport" => 1 );
390 else {
392 # we have tables, propose to select files to upload or updatedatabase
394 $template->param( "count" => $count, "default" => 1 );
396 # 1st part of step 3 : check if there is a databaseversion systempreference
397 # if there is, then we just need to upgrade
398 # if there is none, then we need to install the database
400 if (C4::Context->preference('Version')) {
401 my $dbversion = C4::Context->preference('Version');
402 $dbversion =~ /(.*)\.(..)(..)(...)/;
403 $dbversion = "$1.$2.$3.$4";
404 $template->param("upgrading" => 1,
405 "dbversion" => $dbversion,
406 "kohaversion" => Koha::version(),
412 else {
414 # LANGUAGE SELECTION page by default
415 # using opendir + language Hash
416 my $languages_loop = getTranslatedLanguages('intranet');
417 $template->param( installer_languages_loop => $languages_loop );
418 if ($dbh) {
419 my $rq =
420 $dbh->prepare(
421 "SELECT * from systempreferences WHERE variable='Version'");
422 if ( $rq->execute ) {
423 my ($version) = $rq->fetchrow;
424 if ($version) {
425 print $query->redirect("/cgi-bin/koha/installer/install.pl?step=3");
426 exit;
431 output_html_with_http_headers $query, $cookie, $template->output;
433 sub chk_log { #returns a logfile in $dir or - if that failed - in temp dir
434 my ($dir, $name) = @_;
435 my $fn=$dir.'/'.$name.'.log';
436 if( ! open my $fh, '>', $fn ) {
437 $name.= '_XXXX';
438 require File::Temp;
439 ($fh, $fn)= File::Temp::tempfile( $name, TMPDIR => 1, SUFFIX => '.log');
440 #if this should not work, let croak take over
442 return $fn;