Bug 30572: Adjust search_marc_to_field.sort in kohastructure
[koha.git] / installer / install.pl
1 #!/usr/bin/perl
2
3 # This file is part of Koha.
4 #
5 # Copyright (C) YEAR  YOURNAME-OR-YOUREMPLOYER
6 #
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.
11 #
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.
16 #
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>.
19
20 use Modern::Perl;
21 use diagnostics;
22
23 use C4::InstallAuth qw( get_template_and_user );
24 use CGI qw ( -utf8 );
25 use POSIX;
26
27 use C4::Context;
28 use C4::Output qw( output_html_with_http_headers );
29 use C4::Templates;
30 use C4::Languages qw( getAllLanguages getTranslatedLanguages );
31 use C4::Installer;
32 use C4::Installer::PerlModules;
33
34 use Koha;
35
36 my $query = CGI->new;
37 my $step  = $query->param('step');
38
39 my $language = $query->param('language');
40 my ( $template, $loggedinuser, $cookie );
41
42 my $all_languages = getAllLanguages();
43
44 if ( defined($language) ) {
45     C4::Templates::setlanguagecookie( $query, $language, "install.pl?step=1" );
46 }
47 ( $template, $loggedinuser, $cookie ) = get_template_and_user(
48     {
49         template_name => "installer/step" . ( $step ? $step : 1 ) . ".tt",
50         query         => $query,
51         type          => "intranet",
52     }
53 );
54
55 my $installer = C4::Installer->new();
56 my %info;
57 $info{'dbname'} = C4::Context->config("database_test") || C4::Context->config("database");
58 $info{'dbms'}   = (
59       C4::Context->config("db_scheme")
60     ? C4::Context->config("db_scheme")
61     : "mysql"
62 );
63 $info{'hostname'} = C4::Context->config("hostname");
64 $info{'port'}     = C4::Context->config("port");
65 $info{'user'}     = C4::Context->config("user");
66 $info{'password'} = C4::Context->config("pass");
67 $info{'tls'} = C4::Context->config("tls");
68     if ($info{'tls'} && $info{'tls'} eq 'yes'){
69         $info{'ca'} = C4::Context->config('ca');
70         $info{'cert'} = C4::Context->config('cert');
71         $info{'key'} = C4::Context->config('key');
72         $info{'tlsoptions'} = ";mysql_ssl=1;mysql_ssl_client_key=".$info{key}.";mysql_ssl_client_cert=".$info{cert}.";mysql_ssl_ca_file=".$info{ca};
73         $info{'tlscmdline'} =  " --ssl-cert ". $info{cert} . " --ssl-key " . $info{key} . " --ssl-ca ".$info{ca}." "
74     }
75
76 my $dbh = DBI->connect(
77     "DBI:$info{dbms}:dbname=$info{dbname};host=$info{hostname}"
78       . ( $info{port} ? ";port=$info{port}" : "" )
79       . ( $info{tlsoptions} ? $info{tlsoptions} : "" ),
80     $info{'user'}, $info{'password'}
81 );
82
83 if ( $step && $step == 1 ) {
84
85     #First Step (for both fresh installations and upgrades)
86     #Checking ALL perl Modules and services needed are installed.
87     #Whenever there is an error, adding a report to the page
88     my $op = $query->param('op') || 'noop';
89     $template->param( language      => 1 );
90     my $checkmodule = 1;
91     $template->param( 'checkmodule' => 1 )
92       ; # we start with the assumption that there are no problems and set this to 0 if there are
93
94     unless ( $] >= 5.010000 ) {    # Bug 7375
95         $template->param( problems => 1, perlversion => 1, checkmodule => 0 );
96         $checkmodule = 0;
97     }
98
99     my $perl_modules = C4::Installer::PerlModules->new;
100     $perl_modules->versions_info;
101
102     my $missing_modules = $perl_modules->get_attr('missing_pm');
103     my $upgrade_modules = $perl_modules->get_attr('upgrade_pm');
104     if ( scalar(@$missing_modules) || scalar(@$upgrade_modules) ) {
105         my @missing  = ();
106         my @upgrade = ();
107         foreach (@$missing_modules) {
108             my ( $module, $stats ) = each %$_;
109             $checkmodule = 0 if $stats->{'required'};
110             push(
111                 @missing,
112                 {
113                     name    => $module,
114                     min_version => $stats->{'min_ver'},
115                     max_version => $stats->{'max_ver'},
116                     require => $stats->{'required'}
117                 }
118             );
119         }
120         foreach (@$upgrade_modules) {
121             my ( $module, $stats ) = each %$_;
122             $checkmodule = 0 if $stats->{'required'};
123             push(
124                 @upgrade,
125                 {
126                     name    => $module,
127                     min_version => $stats->{'min_ver'},
128                     max_version => $stats->{'max_ver'},
129                     require => $stats->{'required'}
130                 }
131             );
132         }
133         @missing = sort { $a->{'name'} cmp $b->{'name'} } @missing;
134         @upgrade = sort { $a->{'name'} cmp $b->{'name'} } @upgrade;
135         $template->param(
136             missing_modules => \@missing,
137             upgrade_modules => \@upgrade,
138             checkmodule     => $checkmodule,
139             op              => $op
140         );
141     }
142 }
143 elsif ( $step && $step == 2 ) {
144
145     #STEP 2 Check Database connection and access
146
147     $template->param(%info);
148     my $checkdb = $query->param("checkdb");
149     $template->param( 'dbconnection' => $checkdb );
150     if ($checkdb) {
151         if ($dbh) {
152
153             # Can connect to the mysql
154             $template->param( "checkdatabaseaccess" => 1 );
155             if ( $info{dbms} eq "mysql" ) {
156
157                 #Check if database created
158                 my $rv = $dbh->do("SHOW DATABASES LIKE \'$info{dbname}\'");
159                 if ( $rv == 1 ) {
160                     $template->param( 'checkdatabasecreated' => 1 );
161                 }
162
163                 # Check if user have all necessary grants on this database.
164                 # CURRENT_USER is ANSI SQL, and doesn't require mysql table
165                 # privileges, making the % check pointless, since they
166                 # couldn't even check GRANTS if they couldn't connect.
167                 my $rq = $dbh->prepare('SHOW GRANTS FOR CURRENT_USER');
168                 $rq->execute;
169                 my $grantaccess;
170                 while ( my ($line) = $rq->fetchrow ) {
171                     my $dbname = $info{dbname};
172                     if ( $line =~ m/^GRANT (.*?) ON `$dbname`\.\*/
173                         || index( $line, '*.*' ) > 0 )
174                     {
175                         $grantaccess = 1
176                           if (
177                             index( $line, 'ALL PRIVILEGES' ) > 0
178                             || (   ( index( $line, 'SELECT' ) > 0 )
179                                 && ( index( $line, 'INSERT' ) > 0 )
180                                 && ( index( $line, 'UPDATE' ) > 0 )
181                                 && ( index( $line, 'DELETE' ) > 0 )
182                                 && ( index( $line, 'CREATE' ) > 0 )
183                                 && ( index( $line, 'DROP' ) > 0 ) )
184                           );
185                     }
186                 }
187                 $template->param( "checkgrantaccess" => $grantaccess );
188             }    # End mysql connect check...
189
190             elsif ( $info{dbms} eq "Pg" ) {
191
192                 # Check if database has been created...
193                 my $rv = $dbh->do(
194 "SELECT * FROM pg_catalog.pg_database WHERE datname = \'$info{dbname}\';"
195                 );
196                 if ( $rv == 1 ) {
197                     $template->param( 'checkdatabasecreated' => 1 );
198                 }
199
200                 # Check if user has all necessary grants on this database...
201                 my $rq = $dbh->do(
202                     "SELECT u.usesuper
203             FROM pg_catalog.pg_user as u
204             WHERE u.usename = \'$info{user}\';"
205                 );
206                 if ( $rq == 1 ) {
207                     $template->param( "checkgrantaccess" => 1 );
208                 }
209             }    # End Pg connect check...
210         }
211         else {
212             $template->param( "error" => DBI::err, "message" => DBI::errstr );
213         }
214     }
215 }
216 elsif ( $step && $step == 3 ) {
217
218     # STEP 3 : database setup
219
220     my $op = $query->param('op');
221     if ( $op && $op eq 'finished' ) {
222         # Remove the HandleError set at the beginning of the installer process
223         C4::Context->dbh->disconnect;
224
225         # we have finished, just redirect to mainpage.
226         print $query->redirect("/cgi-bin/koha/mainpage.pl");
227         exit;
228     }
229     elsif ( $op && $op eq 'finish' ) {
230         $installer->set_version_syspref();
231
232         my $langchoice = $query->param('fwklanguage');
233         $langchoice = $query->cookie('KohaOpacLanguage') unless ($langchoice);
234         $langchoice =~ s/[^a-zA-Z_-]*//g;
235         $installer->set_languages_syspref($langchoice);
236
237 # Installation is finished.
238 # We just deny anybody access to install
239 # And we redirect people to mainpage.
240 # The installer will have to relogin since we do not pass cookie to redirection.
241         $template->param( "$op" => 1 );
242     }
243
244     elsif ( $op && $op eq 'addframeworks' ) {
245
246         # 1ST install, 3rd sub-step : insert the SQL files the user has selected
247         my $langchoice = $query->param('fwklanguage');
248         $langchoice = $query->cookie('KohaOpacLanguage') unless ($langchoice);
249         $langchoice =~ s/[^a-zA-Z_-]*//g;
250
251         my ( $fwk_language, $list ) =
252           $installer->load_sql_in_order( $langchoice, $all_languages,
253             $query->multi_param('framework') );
254         $template->param(
255             "fwklanguage" => $fwk_language,
256             "list"        => $list
257         );
258         use Koha::SearchEngine::Elasticsearch;
259         Koha::SearchEngine::Elasticsearch->reset_elasticsearch_mappings;
260         $template->param( "$op" => 1 );
261     }
262     elsif ( $op && $op eq 'selectframeworks' ) {
263 #
264 #
265 # 1ST install, 2nd sub-step : show the user the sql datas they can insert in the database.
266 #
267 #
268 # (note that the term "selectframeworks is not correct. The user can select various files, not only frameworks)
269
270 #Framework Selection
271 #sql data for import are supposed to be located in installer/data/<language>/<level>
272 # Where <language> is en|fr or any international abbreviation (provided language hash is updated... This will be a problem with internationlisation.)
273 # Where <level> is a category of requirement : required, recommended optional
274 # level should contain :
275 #   SQL File for import With a readable name.
276 #   txt File that explains what this SQL File is meant for.
277 # Could be VERY useful to have A Big file for a kind of library.
278 # But could also be useful to have some Authorised values data set prepared here.
279 # Framework Selection is achieved through checking boxes.
280         my $langchoice = $query->param('fwklanguage');
281         $langchoice = $query->cookie('KohaOpacLanguage') unless ($langchoice);
282         $langchoice =~ s/[^a-zA-Z_-]*//g;
283         my $marcflavour = $query->param('marcflavour');
284         if ($marcflavour) {
285             $installer->set_marcflavour_syspref($marcflavour);
286         }
287         $marcflavour = C4::Context->preference('marcflavour')
288           unless ($marcflavour);
289
290         #Insert into database the selected marcflavour
291         undef $/;
292         my ( $marc_defaulted_to_en, $fwklist ) =
293           $installer->marc_framework_sql_list( $langchoice, $marcflavour );
294         $template->param( 'en_marc_frameworks' => $marc_defaulted_to_en );
295         $template->param( "frameworksloop"     => $fwklist );
296         $template->param( "marcflavour"        => ucfirst($marcflavour) );
297
298         my ( $sample_defaulted_to_en, $levellist ) =
299           $installer->sample_data_sql_list($langchoice);
300         $template->param( "en_sample_data" => $sample_defaulted_to_en );
301         $template->param( "levelloop"      => $levellist );
302         $template->param( "$op"            => 1 );
303
304     }
305     elsif ( $op && $op eq 'choosemarc' ) {
306         #
307         #
308         # 1ST install, 2nd sub-step : show the user the marcflavour available.
309         #
310         #
311
312 #Choose Marc Flavour
313 #sql data are supposed to be located in installer/data/<dbms>/<language>/marcflavour/marcflavourname
314 # Where <dbms> is database type according to DBD syntax
315 # Where <language> is en|fr or any international abbreviation (provided language hash is updated... This will be a problem with internationlisation.)
316 # Where <level> is a category of requirement : required, recommended optional
317 # level should contain :
318 #   SQL File for import With a readable name.
319 #   txt File that explains what this SQL File is meant for.
320 # Could be VERY useful to have A Big file for a kind of library.
321 # But could also be useful to have some Authorised values data set prepared here.
322 # Marcflavour Selection is achieved through radiobuttons.
323         my $langchoice = $query->param('fwklanguage');
324
325         $langchoice = $query->cookie('KohaOpacLanguage') unless ($langchoice);
326         $langchoice =~ s/[^a-zA-Z_-]*//g;
327         my $dir =
328           C4::Context->config('intranetdir')
329           . "/installer/data/$info{dbms}/$langchoice/marcflavour";
330         unless ( opendir( MYDIR, $dir ) ) {
331             if ( $langchoice eq 'en' ) {
332                 warn "cannot open MARC frameworks directory $dir";
333             }
334             else {
335                 # if no translated MARC framework is available,
336                 # default to English
337                 $dir = C4::Context->config('intranetdir')
338                   . "/installer/data/$info{dbms}/en/marcflavour";
339                 opendir( MYDIR, $dir )
340                   or warn "cannot open English MARC frameworks directory $dir";
341             }
342         }
343         my @listdir = grep { !/^\./ && -d "$dir/$_" } readdir(MYDIR);
344         closedir MYDIR;
345         my $marcflavour = C4::Context->preference("marcflavour");
346         my @flavourlist;
347         foreach my $marc (@listdir) {
348              my %cell=(
349                  "label"=> ucfirst($marc),
350                   "code"=>uc($marc),
351                "checked"=> defined($marcflavour) ? uc($marc) eq $marcflavour : 0);
352 #             $cell{"description"}= do { local $/ = undef; open INPUT "<$dir/$marc.txt"||"";<INPUT> };
353              push @flavourlist, \%cell;
354         }
355         $template->param( "flavourloop" => \@flavourlist );
356         $template->param( "$op"         => 1 );
357     }
358     elsif ( $op && $op eq 'importdatastructure' ) {
359         #
360         #
361         # 1st install, 1st "sub-step" : import kohastructure
362         #
363         #
364         my $error = $installer->load_db_schema();
365         $template->param(
366             "error" => $error,
367             "$op"   => 1,
368         );
369     }
370     elsif ( $op && $op eq 'updatestructure' ) {
371         #
372         # Not 1st install, the only sub-step : update database
373         #
374         #Do updatedatabase And report
375
376         if ( !defined $ENV{PERL5LIB} ) {
377             my $find = "C4/Context.pm";
378             my $path = $INC{$find};
379             $path =~ s/\Q$find\E//;
380             $ENV{PERL5LIB} = "$path:$path/installer";
381             warn "# plack? inserted PERL5LIB $ENV{PERL5LIB}\n";
382         }
383
384         my $now         = POSIX::strftime( "%Y-%m-%dT%H:%M:%S", localtime() );
385         my $logdir      = C4::Context->config('logdir');
386         my $dbversion   = C4::Context->preference('Version');
387         my $kohaversion = Koha::version;
388         $kohaversion =~ s/(.*\..*)\.(.*)\.(.*)/$1$2$3/;
389
390         my $filename_suffix = join '_', $now, $dbversion, $kohaversion;
391         my ( $logfilepath, $logfilepath_errors ) = (
392             chk_log( $logdir, "updatedatabase_$filename_suffix" ),
393             chk_log( $logdir, "updatedatabase-error_$filename_suffix" )
394         );
395
396         my $cmd = C4::Context->config("intranetdir")
397           . "/installer/data/$info{dbms}/updatedatabase.pl >> $logfilepath 2>> $logfilepath_errors";
398
399         system( $cmd );
400
401         my $fh;
402         open( $fh, "<:encoding(utf-8)", $logfilepath )
403           or die "Cannot open log file $logfilepath: $!";
404         my @report = <$fh>;
405         close $fh;
406         if (@report) {
407             $template->param( update_report =>
408                   [ map { { line => $_ =~ s/\t/&emsp;&emsp;/gr } } split( /\n/, join( '', @report ) ) ]
409             );
410             $template->param( has_update_succeeds => 1 );
411         }
412         else {
413             eval { `rm $logfilepath` };
414         }
415         open( $fh, "<:encoding(utf-8)", $logfilepath_errors )
416           or die "Cannot open log file $logfilepath_errors: $!";
417         @report = <$fh>;
418         close $fh;
419         my $update_errors;
420         if (@report) {
421             $template->param( update_errors =>
422                   [ map { { line => $_ } } split( /\n/, join( '', @report ) ) ]
423             );
424             $update_errors = 1;
425             $template->param( has_update_errors => 1 );
426             warn
427 "The following errors were returned while attempting to run the updatedatabase.pl script:\n";
428             foreach my $line (@report) { warn "$line\n"; }
429         }
430         else {
431             eval { `rm $logfilepath_errors` };
432         }
433
434         unless ( $update_errors ) {
435             my $db_entries = get_db_entries();
436             my $report = update( $db_entries );
437             my $atomic_update_files = get_atomic_updates;
438             my $atomic_update_report = run_atomic_updates( $atomic_update_files );
439
440             $template->param(
441                 success        => $report->{success},
442                 error          => $report->{error},
443                 atomic_updates => {
444                     success => $atomic_update_report->{success},
445                     error   => $atomic_update_report->{error}
446                 }
447             );
448         }
449
450         $template->param( $op => 1 );
451     }
452     else {
453 #
454 # check whether it's a 1st install or an update
455 #
456 #Check if there are enough tables.
457 # Paul has cleaned up tables so reduced the count
458 #I put it there because it implied a data import if condition was not satisfied.
459         my $dbh = DBI->connect(
460                 "DBI:$info{dbms}:dbname=$info{dbname};host=$info{hostname}"
461                 . ( $info{port} ? ";port=$info{port}" : "" )
462                 . ( $info{tlsoptions} ? $info{tlsoptions} : "" ),
463                 $info{'user'}, $info{'password'}
464         );
465         my $rq;
466         if ( $info{dbms} eq 'mysql' ) { $rq = $dbh->prepare("SHOW TABLES"); }
467         elsif ( $info{dbms} eq 'Pg' ) {
468             $rq = $dbh->prepare(
469                 "SELECT *
470                 FROM information_schema.tables
471                 WHERE table_schema='public' and table_type='BASE TABLE';"
472             );
473         }
474         $rq->execute;
475         my $data = $rq->fetchall_arrayref( {} );
476         my $count = scalar(@$data);
477         #
478         # we don't have tables, propose DB import
479         #
480         if ( $count < 70 ) {
481             $template->param( "count" => $count, "proposeimport" => 1 );
482         }
483         else {
484            #
485            # we have tables, propose to select files to upload or updatedatabase
486            #
487             $template->param( "count" => $count, "default" => 1 );
488      #
489      # 1st part of step 3 : check if there is a databaseversion systempreference
490      # if there is, then we just need to upgrade
491      # if there is none, then we need to install the database
492      #
493             if ( C4::Context->preference('Version') ) {
494                 my $dbversion = C4::Context->preference('Version');
495                 $dbversion =~ /(.*)\.(..)(..)(...)/;
496                 $dbversion = "$1.$2.$3.$4";
497                 $template->param(
498                     "upgrading"   => 1,
499                     "dbversion"   => $dbversion,
500                     "kohaversion" => Koha::version(),
501                 );
502             }
503         }
504     }
505 }
506 else {
507
508     # LANGUAGE SELECTION page by default
509     # using opendir + language Hash
510     my $languages_loop = getTranslatedLanguages('intranet');
511     $template->param( installer_languages_loop => $languages_loop );
512     if ($dbh) {
513         my $rq =
514           $dbh->prepare(
515             "SELECT * from systempreferences WHERE variable='Version'");
516         if ( $rq->execute ) {
517             my ($version) = $rq->fetchrow;
518             if ($version) {
519                 print $query->redirect(
520                     "/cgi-bin/koha/installer/install.pl?step=3");
521                 exit;
522             }
523         }
524     }
525 }
526 output_html_with_http_headers $query, $cookie, $template->output;
527
528 sub chk_log {    #returns a logfile in $dir or - if that failed - in temp dir
529     my ( $dir, $name ) = @_;
530     my $fn = $dir . '/' . $name . '.log';
531     if ( !open my $fh, '>', $fn ) {
532         $name .= '_XXXX';
533         require File::Temp;
534         ( $fh, $fn ) =
535           File::Temp::tempfile( $name, TMPDIR => 1, SUFFIX => '.log' );
536
537         #if this should not work, let croak take over
538     }
539     return $fn;
540 }