Bug 16911: Koha::Patrons - Move ExtendMemberSubscriptionTo to ->extend_subscription
[koha.git] / installer / install.pl
blobcc67557ccca5a774ab5e2571fd82fa29946dcb7d
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->version_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 $template->param( "$op" => 1 );
214 elsif ( $op && $op eq 'selectframeworks' ) {
217 # 1ST install, 2nd sub-step : show the user the sql datas he can insert in the database.
220 # (note that the term "selectframeworks is not correct. The user can select various files, not only frameworks)
222 #Framework Selection
223 #sql data for import are supposed to be located in installer/data/<language>/<level>
224 # Where <language> is en|fr or any international abbreviation (provided language hash is updated... This will be a problem with internationlisation.)
225 # Where <level> is a category of requirement : required, recommended optional
226 # level should contain :
227 # SQL File for import With a readable name.
228 # txt File that explains what this SQL File is meant for.
229 # Could be VERY useful to have A Big file for a kind of library.
230 # But could also be useful to have some Authorised values data set prepared here.
231 # Framework Selection is achieved through checking boxes.
232 my $langchoice = $query->param('fwklanguage');
233 $langchoice = $query->cookie('KohaOpacLanguage') unless ($langchoice);
234 $langchoice =~ s/[^a-zA-Z_-]*//g;
235 my $marcflavour = $query->param('marcflavour');
236 if ($marcflavour){
237 $installer->set_marcflavour_syspref($marcflavour);
239 $marcflavour = C4::Context->preference('marcflavour') unless ($marcflavour);
240 #Insert into database the selected marcflavour
241 undef $/;
242 my ($marc_defaulted_to_en, $fwklist) = $installer->marc_framework_sql_list($langchoice, $marcflavour);
243 $template->param('en_marc_frameworks' => $marc_defaulted_to_en);
244 $template->param( "frameworksloop" => $fwklist );
245 $template->param( "marcflavour" => ucfirst($marcflavour));
247 my ($sample_defaulted_to_en, $levellist) = $installer->sample_data_sql_list($langchoice);
248 $template->param( "en_sample_data" => $sample_defaulted_to_en);
249 $template->param( "levelloop" => $levellist );
250 $template->param( "$op" => 1 );
252 elsif ( $op && $op eq 'choosemarc' ) {
255 # 1ST install, 2nd sub-step : show the user the marcflavour available.
259 #Choose Marc Flavour
260 #sql data are supposed to be located in installer/data/<dbms>/<language>/marcflavour/marcflavourname
261 # Where <dbms> is database type according to DBD syntax
262 # Where <language> is en|fr or any international abbreviation (provided language hash is updated... This will be a problem with internationlisation.)
263 # Where <level> is a category of requirement : required, recommended optional
264 # level should contain :
265 # SQL File for import With a readable name.
266 # txt File taht explains what this SQL File is meant for.
267 # Could be VERY useful to have A Big file for a kind of library.
268 # But could also be useful to have some Authorised values data set prepared here.
269 # Marcflavour Selection is achieved through radiobuttons.
270 my $langchoice = $query->param('fwklanguage');
271 $langchoice = $query->cookie('KohaOpacLanguage') unless ($langchoice);
272 $langchoice =~ s/[^a-zA-Z_-]*//g;
273 my $dir =
274 C4::Context->config('intranetdir') . "/installer/data/$info{dbms}/$langchoice/marcflavour";
275 unless (opendir( MYDIR, $dir )) {
276 if ($langchoice eq 'en') {
277 warn "cannot open MARC frameworks directory $dir";
278 } else {
279 # if no translated MARC framework is available,
280 # default to English
281 $dir = C4::Context->config('intranetdir') . "/installer/data/$info{dbms}/en/marcflavour";
282 opendir(MYDIR, $dir) or warn "cannot open English MARC frameworks directory $dir";
285 my @listdir = grep { !/^\./ && -d "$dir/$_" } readdir(MYDIR);
286 closedir MYDIR;
287 my $marcflavour=C4::Context->preference("marcflavour");
288 my @flavourlist;
289 foreach my $marc (@listdir) {
290 my %cell=(
291 "label"=> ucfirst($marc),
292 "code"=>uc($marc),
293 "checked"=> defined($marcflavour) ? uc($marc) eq $marcflavour : 0);
294 # $cell{"description"}= do { local $/ = undef; open INPUT "<$dir/$marc.txt"||"";<INPUT> };
295 push @flavourlist, \%cell;
297 $template->param( "flavourloop" => \@flavourlist );
298 $template->param( "$op" => 1 );
300 elsif ( $op && $op eq 'importdatastructure' ) {
303 # 1st install, 1st "sub-step" : import kohastructure
306 my $error = $installer->load_db_schema();
307 $template->param(
308 "error" => $error,
309 "$op" => 1,
312 elsif ( $op && $op eq 'updatestructure' ) {
314 # Not 1st install, the only sub-step : update database
316 #Do updatedatabase And report
318 if ( ! defined $ENV{PERL5LIB} ) {
319 my $find = "C4/Context.pm";
320 my $path = $INC{$find};
321 $path =~ s/\Q$find\E//;
322 $ENV{PERL5LIB} = "$path:$path/installer";
323 warn "# plack? inserted PERL5LIB $ENV{PERL5LIB}\n";
326 my $now = POSIX::strftime( "%Y-%m-%dT%H:%M:%S", localtime() );
327 my $logdir = C4::Context->config('logdir');
328 my $dbversion = C4::Context->preference('Version');
329 my $kohaversion = Koha::version;
330 $kohaversion =~ s/(.*\..*)\.(.*)\.(.*)/$1$2$3/;
332 my $filename_suffix = join '_', $now, $dbversion, $kohaversion;
333 my ( $logfilepath, $logfilepath_errors ) = ( chk_log($logdir, "updatedatabase_$filename_suffix"), chk_log($logdir, "updatedatabase-error_$filename_suffix") );
335 my $cmd = C4::Context->config("intranetdir") . "/installer/data/$info{dbms}/updatedatabase.pl >> $logfilepath 2>> $logfilepath_errors";
337 system($cmd );
339 my $fh;
340 open( $fh, "<", $logfilepath ) or die "Cannot open log file $logfilepath: $!";
341 my @report = <$fh>;
342 close $fh;
343 if (@report) {
344 $template->param( update_report => [ map { { line => $_ } } split( /\n/, join( '', @report ) ) ] );
345 $template->param( has_update_succeeds => 1 );
346 } else {
347 eval{ `rm $logfilepath` };
349 open( $fh, "<", $logfilepath_errors ) or die "Cannot open log file $logfilepath_errors: $!";
350 @report = <$fh>;
351 close $fh;
352 if (@report) {
353 $template->param( update_errors => [ map { { line => $_ } } split( /\n/, join( '', @report ) ) ] );
354 $template->param( has_update_errors => 1 );
355 warn "The following errors were returned while attempting to run the updatedatabase.pl script:\n";
356 foreach my $line (@report) { warn "$line\n"; }
357 } else {
358 eval{ `rm $logfilepath_errors` };
360 $template->param( $op => 1 );
362 else {
364 # check whether it's a 1st install or an update
366 #Check if there are enough tables.
367 # Paul has cleaned up tables so reduced the count
368 #I put it there because it implied a data import if condition was not satisfied.
369 my $dbh = DBI->connect(
370 "DBI:$info{dbms}:dbname=$info{dbname};host=$info{hostname}"
371 . ( $info{port} ? ";port=$info{port}" : "" ),
372 $info{'user'}, $info{'password'}
374 my $rq;
375 if ( $info{dbms} eq 'mysql' ) { $rq = $dbh->prepare( "SHOW TABLES" ); }
376 elsif ( $info{dbms} eq 'Pg' ) { $rq = $dbh->prepare( "SELECT *
377 FROM information_schema.tables
378 WHERE table_schema='public' and table_type='BASE TABLE';" ); }
379 $rq->execute;
380 my $data = $rq->fetchall_arrayref( {} );
381 my $count = scalar(@$data);
383 # we don't have tables, propose DB import
385 if ( $count < 70 ) {
386 $template->param( "count" => $count, "proposeimport" => 1 );
388 else {
390 # we have tables, propose to select files to upload or updatedatabase
392 $template->param( "count" => $count, "default" => 1 );
394 # 1st part of step 3 : check if there is a databaseversion systempreference
395 # if there is, then we just need to upgrade
396 # if there is none, then we need to install the database
398 if (C4::Context->preference('Version')) {
399 my $dbversion = C4::Context->preference('Version');
400 $dbversion =~ /(.*)\.(..)(..)(...)/;
401 $dbversion = "$1.$2.$3.$4";
402 $template->param("upgrading" => 1,
403 "dbversion" => $dbversion,
404 "kohaversion" => Koha::version(),
410 else {
412 # LANGUAGE SELECTION page by default
413 # using opendir + language Hash
414 my $languages_loop = getTranslatedLanguages('intranet');
415 $template->param( installer_languages_loop => $languages_loop );
416 if ($dbh) {
417 my $rq =
418 $dbh->prepare(
419 "SELECT * from systempreferences WHERE variable='Version'");
420 if ( $rq->execute ) {
421 my ($version) = $rq->fetchrow;
422 if ($version) {
423 print $query->redirect("/cgi-bin/koha/installer/install.pl?step=3");
424 exit;
429 output_html_with_http_headers $query, $cookie, $template->output;
431 sub chk_log { #returns a logfile in $dir or - if that failed - in temp dir
432 my ($dir, $name) = @_;
433 my $fn=$dir.'/'.$name.'.log';
434 if( ! open my $fh, '>', $fn ) {
435 $name.= '_XXXX';
436 require File::Temp;
437 ($fh, $fn)= File::Temp::tempfile( $name, TMPDIR => 1, SUFFIX => '.log');
438 #if this should not work, let croak take over
440 return $fn;