Bug 24120: URI filter search terms in sort dropdowns
[koha.git] / installer / install.pl
blobbf9ccc42297a4a1f60d3e0b28235b414bee2b0d6
1 #!/usr/bin/perl
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>.
20 use Modern::Perl;
21 use diagnostics;
23 use C4::InstallAuth;
24 use CGI qw ( -utf8 );
25 use POSIX qw(strftime);
27 use C4::Context;
28 use C4::Output;
29 use C4::Templates;
30 use C4::Languages qw(getAllLanguages getTranslatedLanguages);
31 use C4::Installer;
33 use Koha;
35 my $query = new CGI;
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",
49 query => $query,
50 type => "intranet",
51 authnotrequired => 0,
52 debug => 1,
56 my $installer = C4::Installer->new();
57 my %info;
58 $info{'dbname'} = C4::Context->config("database");
59 $info{'dbms'} = (
60 C4::Context->config("db_scheme")
61 ? C4::Context->config("db_scheme")
62 : "mysql"
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 );
91 my $checkmodule = 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 );
97 $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) ) {
105 my @components = ();
106 foreach (@$modules) {
107 my ( $module, $stats ) = each %$_;
108 $checkmodule = 0 if $stats->{'required'};
109 push(
110 @components,
112 name => $module,
113 version => $stats->{'min_ver'},
114 require => $stats->{'required'},
115 usage => $stats->{'usage'},
119 @components = sort { $a->{'name'} cmp $b->{'name'} } @components;
120 $template->param(
121 missing_modules => \@components,
122 checkmodule => $checkmodule,
123 op => $op
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 );
134 if ($checkdb) {
135 if ($dbh) {
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}\'");
143 if ( $rv == 1 ) {
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');
152 $rq->execute;
153 my $grantaccess;
154 while ( my ($line) = $rq->fetchrow ) {
155 my $dbname = $info{dbname};
156 if ( $line =~ m/^GRANT (.*?) ON `$dbname`\.\*/
157 || index( $line, '*.*' ) > 0 )
159 $grantaccess = 1
160 if (
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...
177 my $rv = $dbh->do(
178 "SELECT * FROM pg_catalog.pg_database WHERE datname = \'$info{dbname}\';"
180 if ( $rv == 1 ) {
181 $template->param( 'checkdatabasecreated' => 1 );
184 # Check if user has all necessary grants on this database...
185 my $rq = $dbh->do(
186 "SELECT u.usesuper
187 FROM pg_catalog.pg_user as u
188 WHERE u.usename = \'$info{user}\';"
190 if ( $rq == 1 ) {
191 $template->param( "checkgrantaccess" => 1 );
193 } # End Pg connect check...
195 else {
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");
210 exit;
212 elsif ( $op && $op eq 'finish' ) {
213 $installer->set_version_syspref();
215 # Installation is finished.
216 # We just deny anybody access to install
217 # And we redirect people to mainpage.
218 # The installer will have to relogin since we do not pass cookie to redirection.
219 $template->param( "$op" => 1 );
222 elsif ( $op && $op eq 'addframeworks' ) {
224 # 1ST install, 3rd sub-step : insert the SQL files the user has selected
226 my ( $fwk_language, $list ) =
227 $installer->load_sql_in_order( $all_languages,
228 $query->multi_param('framework') );
229 $template->param(
230 "fwklanguage" => $fwk_language,
231 "list" => $list
233 use Koha::SearchEngine::Elasticsearch;
234 Koha::SearchEngine::Elasticsearch->reset_elasticsearch_mappings;
235 $template->param( "$op" => 1 );
237 elsif ( $op && $op eq 'selectframeworks' ) {
240 # 1ST install, 2nd sub-step : show the user the sql datas they can insert in the database.
243 # (note that the term "selectframeworks is not correct. The user can select various files, not only frameworks)
245 #Framework Selection
246 #sql data for import are supposed to be located in installer/data/<language>/<level>
247 # Where <language> is en|fr or any international abbreviation (provided language hash is updated... This will be a problem with internationlisation.)
248 # Where <level> is a category of requirement : required, recommended optional
249 # level should contain :
250 # SQL File for import With a readable name.
251 # txt File that explains what this SQL File is meant for.
252 # Could be VERY useful to have A Big file for a kind of library.
253 # But could also be useful to have some Authorised values data set prepared here.
254 # Framework Selection is achieved through checking boxes.
255 my $langchoice = $query->param('fwklanguage');
256 $langchoice = $query->cookie('KohaOpacLanguage') unless ($langchoice);
257 $langchoice =~ s/[^a-zA-Z_-]*//g;
258 my $marcflavour = $query->param('marcflavour');
259 if ($marcflavour) {
260 $installer->set_marcflavour_syspref($marcflavour);
262 $marcflavour = C4::Context->preference('marcflavour')
263 unless ($marcflavour);
265 #Insert into database the selected marcflavour
266 undef $/;
267 my ( $marc_defaulted_to_en, $fwklist ) =
268 $installer->marc_framework_sql_list( $langchoice, $marcflavour );
269 $template->param( 'en_marc_frameworks' => $marc_defaulted_to_en );
270 $template->param( "frameworksloop" => $fwklist );
271 $template->param( "marcflavour" => ucfirst($marcflavour) );
273 my ( $sample_defaulted_to_en, $levellist ) =
274 $installer->sample_data_sql_list($langchoice);
275 $template->param( "en_sample_data" => $sample_defaulted_to_en );
276 $template->param( "levelloop" => $levellist );
277 $template->param( "$op" => 1 );
280 elsif ( $op && $op eq 'choosemarc' ) {
283 # 1ST install, 2nd sub-step : show the user the marcflavour available.
287 #Choose Marc Flavour
288 #sql data are supposed to be located in installer/data/<dbms>/<language>/marcflavour/marcflavourname
289 # Where <dbms> is database type according to DBD syntax
290 # Where <language> is en|fr or any international abbreviation (provided language hash is updated... This will be a problem with internationlisation.)
291 # Where <level> is a category of requirement : required, recommended optional
292 # level should contain :
293 # SQL File for import With a readable name.
294 # txt File that explains what this SQL File is meant for.
295 # Could be VERY useful to have A Big file for a kind of library.
296 # But could also be useful to have some Authorised values data set prepared here.
297 # Marcflavour Selection is achieved through radiobuttons.
298 my $langchoice = $query->param('fwklanguage');
300 $langchoice = $query->cookie('KohaOpacLanguage') unless ($langchoice);
301 $langchoice =~ s/[^a-zA-Z_-]*//g;
302 my $dir =
303 C4::Context->config('intranetdir')
304 . "/installer/data/$info{dbms}/$langchoice/marcflavour";
305 unless ( opendir( MYDIR, $dir ) ) {
306 if ( $langchoice eq 'en' ) {
307 warn "cannot open MARC frameworks directory $dir";
309 else {
310 # if no translated MARC framework is available,
311 # default to English
312 $dir = C4::Context->config('intranetdir')
313 . "/installer/data/$info{dbms}/en/marcflavour";
314 opendir( MYDIR, $dir )
315 or warn "cannot open English MARC frameworks directory $dir";
318 my @listdir = grep { !/^\./ && -d "$dir/$_" } readdir(MYDIR);
319 closedir MYDIR;
320 my $marcflavour = C4::Context->preference("marcflavour");
321 my @flavourlist;
322 foreach my $marc (@listdir) {
323 my %cell=(
324 "label"=> ucfirst($marc),
325 "code"=>uc($marc),
326 "checked"=> defined($marcflavour) ? uc($marc) eq $marcflavour : 0);
327 # $cell{"description"}= do { local $/ = undef; open INPUT "<$dir/$marc.txt"||"";<INPUT> };
328 push @flavourlist, \%cell;
330 $template->param( "flavourloop" => \@flavourlist );
331 $template->param( "$op" => 1 );
333 elsif ( $op && $op eq 'importdatastructure' ) {
336 # 1st install, 1st "sub-step" : import kohastructure
339 my $error = $installer->load_db_schema();
340 $template->param(
341 "error" => $error,
342 "$op" => 1,
345 elsif ( $op && $op eq 'updatestructure' ) {
347 # Not 1st install, the only sub-step : update database
349 #Do updatedatabase And report
351 if ( !defined $ENV{PERL5LIB} ) {
352 my $find = "C4/Context.pm";
353 my $path = $INC{$find};
354 $path =~ s/\Q$find\E//;
355 $ENV{PERL5LIB} = "$path:$path/installer";
356 warn "# plack? inserted PERL5LIB $ENV{PERL5LIB}\n";
359 my $now = POSIX::strftime( "%Y-%m-%dT%H:%M:%S", localtime() );
360 my $logdir = C4::Context->config('logdir');
361 my $dbversion = C4::Context->preference('Version');
362 my $kohaversion = Koha::version;
363 $kohaversion =~ s/(.*\..*)\.(.*)\.(.*)/$1$2$3/;
365 my $filename_suffix = join '_', $now, $dbversion, $kohaversion;
366 my ( $logfilepath, $logfilepath_errors ) = (
367 chk_log( $logdir, "updatedatabase_$filename_suffix" ),
368 chk_log( $logdir, "updatedatabase-error_$filename_suffix" )
371 my $cmd = C4::Context->config("intranetdir")
372 . "/installer/data/$info{dbms}/updatedatabase.pl >> $logfilepath 2>> $logfilepath_errors";
374 system($cmd );
376 my $fh;
377 open( $fh, "<:encoding(utf-8)", $logfilepath )
378 or die "Cannot open log file $logfilepath: $!";
379 my @report = <$fh>;
380 close $fh;
381 if (@report) {
382 $template->param( update_report =>
383 [ map { { line => $_ } } split( /\n/, join( '', @report ) ) ]
385 $template->param( has_update_succeeds => 1 );
387 else {
388 eval { `rm $logfilepath` };
390 open( $fh, "<:encoding(utf-8)", $logfilepath_errors )
391 or die "Cannot open log file $logfilepath_errors: $!";
392 @report = <$fh>;
393 close $fh;
394 if (@report) {
395 $template->param( update_errors =>
396 [ map { { line => $_ } } split( /\n/, join( '', @report ) ) ]
398 $template->param( has_update_errors => 1 );
399 warn
400 "The following errors were returned while attempting to run the updatedatabase.pl script:\n";
401 foreach my $line (@report) { warn "$line\n"; }
403 else {
404 eval { `rm $logfilepath_errors` };
406 $template->param( $op => 1 );
408 else {
410 # check whether it's a 1st install or an update
412 #Check if there are enough tables.
413 # Paul has cleaned up tables so reduced the count
414 #I put it there because it implied a data import if condition was not satisfied.
415 my $dbh = DBI->connect(
416 "DBI:$info{dbms}:dbname=$info{dbname};host=$info{hostname}"
417 . ( $info{port} ? ";port=$info{port}" : "" )
418 . ( $info{tlsoptions} ? $info{tlsoptions} : "" ),
419 $info{'user'}, $info{'password'}
421 my $rq;
422 if ( $info{dbms} eq 'mysql' ) { $rq = $dbh->prepare("SHOW TABLES"); }
423 elsif ( $info{dbms} eq 'Pg' ) {
424 $rq = $dbh->prepare(
425 "SELECT *
426 FROM information_schema.tables
427 WHERE table_schema='public' and table_type='BASE TABLE';"
430 $rq->execute;
431 my $data = $rq->fetchall_arrayref( {} );
432 my $count = scalar(@$data);
434 # we don't have tables, propose DB import
436 if ( $count < 70 ) {
437 $template->param( "count" => $count, "proposeimport" => 1 );
439 else {
441 # we have tables, propose to select files to upload or updatedatabase
443 $template->param( "count" => $count, "default" => 1 );
445 # 1st part of step 3 : check if there is a databaseversion systempreference
446 # if there is, then we just need to upgrade
447 # if there is none, then we need to install the database
449 if ( C4::Context->preference('Version') ) {
450 my $dbversion = C4::Context->preference('Version');
451 $dbversion =~ /(.*)\.(..)(..)(...)/;
452 $dbversion = "$1.$2.$3.$4";
453 $template->param(
454 "upgrading" => 1,
455 "dbversion" => $dbversion,
456 "kohaversion" => Koha::version(),
462 else {
464 # LANGUAGE SELECTION page by default
465 # using opendir + language Hash
466 my $languages_loop = getTranslatedLanguages('intranet');
467 $template->param( installer_languages_loop => $languages_loop );
468 if ($dbh) {
469 my $rq =
470 $dbh->prepare(
471 "SELECT * from systempreferences WHERE variable='Version'");
472 if ( $rq->execute ) {
473 my ($version) = $rq->fetchrow;
474 if ($version) {
475 print $query->redirect(
476 "/cgi-bin/koha/installer/install.pl?step=3");
477 exit;
482 output_html_with_http_headers $query, $cookie, $template->output;
484 sub chk_log { #returns a logfile in $dir or - if that failed - in temp dir
485 my ( $dir, $name ) = @_;
486 my $fn = $dir . '/' . $name . '.log';
487 if ( !open my $fh, '>', $fn ) {
488 $name .= '_XXXX';
489 require File::Temp;
490 ( $fh, $fn ) =
491 File::Temp::tempfile( $name, TMPDIR => 1, SUFFIX => '.log' );
493 #if this should not work, let croak take over
495 return $fn;