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