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