Bug 20056: Resolve uninitialized warn in cmp_sysprefs.pl
[koha.git] / C4 / Installer.pm
blob1a5c037a422ea8d9261be32d346bf3d50e19f628
1 package C4::Installer;
3 # Copyright (C) 2008 LibLime
5 # This file is part of Koha.
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;
22 use Encode qw( encode is_utf8 );
23 use DBIx::RunSQL;
24 use C4::Context;
25 use C4::Installer::PerlModules;
26 use DBI;
27 use Koha;
29 use vars qw(@ISA @EXPORT);
30 BEGIN {
31 require Exporter;
32 @ISA = qw( Exporter );
33 push @EXPORT, qw( foreign_key_exists index_exists column_exists );
36 =head1 NAME
38 C4::Installer
40 =head1 SYNOPSIS
42 use C4::Installer;
43 my $installer = C4::Installer->new();
44 my $all_languages = getAllLanguages();
45 my $error = $installer->load_db_schema();
46 my $list;
47 #fill $list with list of sql files
48 my ($fwk_language, $error_list) = $installer->load_sql_in_order($all_languages, @$list);
49 $installer->set_version_syspref();
50 $installer->set_marcflavour_syspref('MARC21');
52 =head1 DESCRIPTION
54 =cut
56 =head1 METHODS
58 =head2 new
60 my $installer = C4::Installer->new();
62 Creates a new installer.
64 =cut
66 sub new {
67 my $class = shift;
69 my $self = {};
71 # get basic information from context
72 $self->{'dbname'} = C4::Context->config("database");
73 $self->{'dbms'} = C4::Context->config("db_scheme") ? C4::Context->config("db_scheme") : "mysql";
74 $self->{'hostname'} = C4::Context->config("hostname");
75 $self->{'port'} = C4::Context->config("port");
76 $self->{'user'} = C4::Context->config("user");
77 $self->{'password'} = C4::Context->config("pass");
78 $self->{'tls'} = C4::Context->config("tls");
79 if( $self->{'tls'} && $self->{'tls'} eq 'yes' ) {
80 $self->{'ca'} = C4::Context->config('ca');
81 $self->{'cert'} = C4::Context->config('cert');
82 $self->{'key'} = C4::Context->config('key');
83 $self->{'tlsoptions'} = ";mysql_ssl=1;mysql_ssl_client_key=".$self->{key}.";mysql_ssl_client_cert=".$self->{cert}.";mysql_ssl_ca_file=".$self->{ca};
84 $self->{'tlscmdline'} = " --ssl-cert ". $self->{cert} . " --ssl-key " . $self->{key} . " --ssl-ca ".$self->{ca}." "
86 $self->{'dbh'} = DBI->connect("DBI:$self->{dbms}:dbname=$self->{dbname};host=$self->{hostname}" .
87 ( $self->{port} ? ";port=$self->{port}" : "" ).
88 ( $self->{tlsoptions} ? $self->{tlsoptions} : ""),
89 $self->{'user'}, $self->{'password'});
90 $self->{'language'} = undef;
91 $self->{'marcflavour'} = undef;
92 $self->{'dbh'}->do('set NAMES "utf8"');
93 $self->{'dbh'}->{'mysql_enable_utf8'}=1;
95 bless $self, $class;
96 return $self;
99 =head2 marc_framework_sql_list
101 my ($defaulted_to_en, $list) =
102 $installer->marc_framework_sql_list($lang, $marcflavour);
104 Returns in C<$list> a structure listing the filename, description, section,
105 and mandatory/optional status of MARC framework scripts available for C<$lang>
106 and C<$marcflavour>.
108 If the C<$defaulted_to_en> return value is true, no scripts are available
109 for language C<$lang> and the 'en' ones are returned.
111 =cut
113 sub marc_framework_sql_list {
114 my $self = shift;
115 my $lang = shift;
116 my $marcflavour = shift;
118 my $defaulted_to_en = 0;
120 undef $/;
121 my $dir = C4::Context->config('intranetdir') . "/installer/data/$self->{dbms}/$lang/marcflavour/".lc($marcflavour);
122 unless (opendir( MYDIR, $dir )) {
123 if ($lang eq 'en') {
124 warn "cannot open MARC frameworks directory $dir";
125 } else {
126 # if no translated MARC framework is available,
127 # default to English
128 $dir = C4::Context->config('intranetdir') . "/installer/data/$self->{dbms}/en/marcflavour/".lc($marcflavour);
129 opendir(MYDIR, $dir) or warn "cannot open English MARC frameworks directory $dir";
130 $defaulted_to_en = 1;
133 my @listdir = sort grep { !/^\.|marcflavour/ && -d "$dir/$_" } readdir(MYDIR);
134 closedir MYDIR;
136 my @fwklist;
137 my $request = $self->{'dbh'}->prepare("SELECT value FROM systempreferences WHERE variable='FrameworksLoaded'");
138 $request->execute;
139 my ($frameworksloaded) = $request->fetchrow;
140 $frameworksloaded = '' unless defined $frameworksloaded; # avoid warning
141 my %frameworksloaded;
142 foreach ( split( /\|/, $frameworksloaded ) ) {
143 $frameworksloaded{$_} = 1;
146 foreach my $requirelevel (@listdir) {
147 opendir( MYDIR, "$dir/$requirelevel" );
148 my @listname = grep { !/^\./ && -f "$dir/$requirelevel/$_" && $_ =~ m/\.sql$/ } readdir(MYDIR);
149 closedir MYDIR;
150 my %cell;
151 my @frameworklist;
152 map {
153 my $name = substr( $_, 0, -4 );
154 open my $fh, "<:encoding(UTF-8)", "$dir/$requirelevel/$name.txt";
155 my $lines = <$fh>;
156 $lines =~ s/\n|\r/<br \/>/g;
157 $lines = Encode::encode('UTF-8', $lines) unless ( Encode::is_utf8($lines) );
158 my $mandatory = ($requirelevel =~ /(mandatory|requi|oblig|necess)/i);
159 push @frameworklist,
161 'fwkname' => $name,
162 'fwkfile' => "$dir/$requirelevel/$_",
163 'fwkdescription' => $lines,
164 'checked' => ( ( $frameworksloaded{$_} || $mandatory ) ? 1 : 0 ),
165 'mandatory' => $mandatory,
167 } @listname;
168 my @fwks =
169 sort { $a->{'fwkname'} cmp $b->{'fwkname'} } @frameworklist;
171 $cell{"frameworks"} = \@fwks;
172 $cell{"label"} = ucfirst($requirelevel);
173 $cell{"code"} = lc($requirelevel);
174 push @fwklist, \%cell;
177 return ($defaulted_to_en, \@fwklist);
180 =head2 sample_data_sql_list
182 my ($defaulted_to_en, $list) = $installer->sample_data_sql_list($lang);
184 Returns in C<$list> a structure listing the filename, description, section,
185 and mandatory/optional status of sample data scripts available for C<$lang>.
186 If the C<$defaulted_to_en> return value is true, no scripts are available
187 for language C<$lang> and the 'en' ones are returned.
189 =cut
191 sub sample_data_sql_list {
192 my $self = shift;
193 my $lang = shift;
195 my $defaulted_to_en = 0;
197 undef $/;
198 my $dir = C4::Context->config('intranetdir') . "/installer/data/$self->{dbms}/$lang";
199 unless (opendir( MYDIR, $dir )) {
200 if ($lang eq 'en') {
201 warn "cannot open sample data directory $dir";
202 } else {
203 # if no sample data is available,
204 # default to English
205 $dir = C4::Context->config('intranetdir') . "/installer/data/$self->{dbms}/en";
206 opendir(MYDIR, $dir) or warn "cannot open English sample data directory $dir";
207 $defaulted_to_en = 1;
210 my @listdir = sort grep { !/^\.|marcflavour/ && -d "$dir/$_" } readdir(MYDIR);
211 closedir MYDIR;
213 my @levellist;
214 my $request = $self->{'dbh'}->prepare("SELECT value FROM systempreferences WHERE variable='FrameworksLoaded'");
215 $request->execute;
216 my ($frameworksloaded) = $request->fetchrow;
217 $frameworksloaded = '' unless defined $frameworksloaded; # avoid warning
218 my %frameworksloaded;
219 foreach ( split( /\|/, $frameworksloaded ) ) {
220 $frameworksloaded{$_} = 1;
223 foreach my $requirelevel (@listdir) {
224 opendir( MYDIR, "$dir/$requirelevel" );
225 my @listname = grep { !/^\./ && -f "$dir/$requirelevel/$_" && $_ =~ m/\.sql$/ } readdir(MYDIR);
226 closedir MYDIR;
227 my %cell;
228 my @frameworklist;
229 map {
230 my $name = substr( $_, 0, -4 );
231 open my $fh , "<:encoding(UTF-8)", "$dir/$requirelevel/$name.txt";
232 my $lines = <$fh>;
233 $lines =~ s/\n|\r/<br \/>/g;
234 $lines = Encode::encode('UTF-8', $lines) unless ( Encode::is_utf8($lines) );
235 my $mandatory = ($requirelevel =~ /(mandatory|requi|oblig|necess)/i);
236 push @frameworklist,
238 'fwkname' => $name,
239 'fwkfile' => "$dir/$requirelevel/$_",
240 'fwkdescription' => $lines,
241 'checked' => ( ( $frameworksloaded{$_} || $mandatory ) ? 1 : 0 ),
242 'mandatory' => $mandatory,
244 } @listname;
245 my @fwks = sort { $a->{'fwkname'} cmp $b->{'fwkname'} } @frameworklist;
247 $cell{"frameworks"} = \@fwks;
248 $cell{"label"} = ucfirst($requirelevel);
249 $cell{"code"} = lc($requirelevel);
250 push @levellist, \%cell;
253 return ($defaulted_to_en, \@levellist);
256 =head2 load_db_schema
258 my $error = $installer->load_db_schema();
260 Loads the SQL script that creates Koha's tables and indexes. The
261 return value is a string containing error messages reported by the
262 load.
264 =cut
266 sub load_db_schema {
267 my $self = shift;
269 my $datadir = C4::Context->config('intranetdir') . "/installer/data/$self->{dbms}";
270 my $error = $self->load_sql("$datadir/kohastructure.sql");
271 return $error;
275 =head2 load_sql_in_order
277 my ($fwk_language, $list) = $installer->load_sql_in_order($all_languages, @sql_list);
279 Given a list of SQL scripts supplied in C<@sql_list>, loads each of them
280 into the database and sets the FrameworksLoaded system preference to names
281 of the scripts that were loaded.
283 The SQL files are loaded in alphabetical order by filename (not including
284 directory path). This means that dependencies among the scripts are to
285 be resolved by carefully naming them, keeping in mind that the directory name
286 does *not* currently count.
288 B<FIXME:> this is a rather delicate way of dealing with dependencies between
289 the install scripts.
291 The return value C<$list> is an arrayref containing a hashref for each
292 "level" or directory containing SQL scripts; the hashref in turns contains
293 a list of hashrefs containing a list of each script load and any error
294 messages associated with the loading of each script.
296 B<FIXME:> The C<$fwk_language> code probably doesn't belong and needs to be
297 moved to a different method.
299 =cut
301 sub load_sql_in_order {
302 my $self = shift;
303 my $all_languages = shift;
304 my @sql_list = @_;
306 my $lang;
307 my %hashlevel;
308 my @fnames = sort {
309 my @aa = split /\/|\\/, ($a);
310 my @bb = split /\/|\\/, ($b);
311 $aa[-1] cmp $bb[-1]
312 } @sql_list;
313 my $request = $self->{'dbh'}->prepare( "SELECT value FROM systempreferences WHERE variable='FrameworksLoaded'" );
314 $request->execute;
315 my ($systempreference) = $request->fetchrow;
316 $systempreference = '' unless defined $systempreference; # avoid warning
317 # Make sure subtag_registry.sql is loaded second
318 my $subtag_registry = C4::Context->config('intranetdir') . "/installer/data/$self->{dbms}/mandatory/subtag_registry.sql";
319 unshift(@fnames, $subtag_registry);
320 # Make sure authorised value categories are loaded at the beginning
321 my $av_cat = C4::Context->config('intranetdir') . "/installer/data/$self->{dbms}/mandatory/auth_val_cat.sql";
322 unshift(@fnames, $av_cat);
323 # Make sure the global sysprefs.sql file is loaded first
324 my $globalsysprefs = C4::Context->config('intranetdir') . "/installer/data/$self->{dbms}/sysprefs.sql";
325 unshift(@fnames, $globalsysprefs);
326 push @fnames, C4::Context->config('intranetdir') . "/installer/data/mysql/userflags.sql";
327 push @fnames, C4::Context->config('intranetdir') . "/installer/data/mysql/userpermissions.sql";
328 push @fnames, C4::Context->config('intranetdir') . "/installer/data/mysql/audio_alerts.sql";
329 push @fnames, C4::Context->config('intranetdir') . "/installer/data/mysql/mandatory/refund_lost_item_fee_rules.sql";
330 push @fnames, C4::Context->config('intranetdir') . "/installer/data/mysql/account_offset_types.sql";
331 foreach my $file (@fnames) {
332 # warn $file;
333 undef $/;
334 my $error = $self->load_sql($file);
335 my @file = split qr(\/|\\), $file;
336 $lang = $file[ scalar(@file) - 3 ] unless ($lang);
337 my $level = $file[ scalar(@file) - 2 ];
338 unless ($error) {
339 $systempreference .= "$file[scalar(@file)-1]|"
340 unless ( index( $systempreference, $file[ scalar(@file) - 1 ] ) >= 0 );
343 #Bulding here a hierarchy to display files by level.
344 push @{ $hashlevel{$level} },
345 { "fwkname" => $file[ scalar(@file) - 1 ], "error" => $error };
348 #systempreference contains an ending |
349 chop $systempreference;
350 my @list;
351 map { push @list, { "level" => $_, "fwklist" => $hashlevel{$_} } } keys %hashlevel;
352 my $fwk_language;
353 for my $each_language (@$all_languages) {
355 # warn "CODE".$each_language->{'language_code'};
356 # warn "LANG:".$lang;
357 if ( $lang eq $each_language->{'language_code'} ) {
358 $fwk_language = $each_language->{language_locale_name};
361 my $updateflag =
362 $self->{'dbh'}->do(
363 "UPDATE systempreferences set value=\"$systempreference\" where variable='FrameworksLoaded'"
366 unless ( $updateflag == 1 ) {
367 my $string =
368 "INSERT INTO systempreferences (value, variable, explanation, type) VALUES (\"$systempreference\",'FrameworksLoaded','Frameworks loaded through webinstaller','choice')";
369 my $rq = $self->{'dbh'}->prepare($string);
370 $rq->execute;
372 return ($fwk_language, \@list);
375 =head2 set_marcflavour_syspref
377 $installer->set_marcflavour_syspref($marcflavour);
379 Set the 'marcflavour' system preference. The incoming
380 C<$marcflavour> references to a subdirectory of
381 installer/data/$dbms/$lang/marcflavour, and is
382 normalized to MARC21, UNIMARC or NORMARC.
384 FIXME: this method assumes that the MARC flavour will be either
385 MARC21, UNIMARC or NORMARC.
387 =cut
389 sub set_marcflavour_syspref {
390 my $self = shift;
391 my $marcflavour = shift;
393 # we can have some variants of marc flavour, by having different directories, like : unimarc_small and unimarc_full, for small and complete unimarc frameworks.
394 # marc_cleaned finds the marcflavour, without the variant.
395 my $marc_cleaned = 'MARC21';
396 $marc_cleaned = 'UNIMARC' if $marcflavour =~ /unimarc/i;
397 $marc_cleaned = 'NORMARC' if $marcflavour =~ /normarc/i;
398 my $request =
399 $self->{'dbh'}->prepare(
400 "INSERT IGNORE INTO `systempreferences` (variable,value,explanation,options,type) VALUES('marcflavour','$marc_cleaned','Define global MARC flavor (MARC21, UNIMARC or NORMARC) used for character encoding','MARC21|UNIMARC|NORMARC','Choice');"
402 $request->execute;
405 =head2 set_version_syspref
407 $installer->set_version_syspref();
409 Set or update the 'Version' system preference to the current
410 Koha software version.
412 =cut
414 sub set_version_syspref {
415 my $self = shift;
417 my $kohaversion = Koha::version();
418 # remove the 3 last . to have a Perl number
419 $kohaversion =~ s/(.*\..*)\.(.*)\.(.*)/$1$2$3/;
420 if (C4::Context->preference('Version')) {
421 warn "UPDATE Version";
422 my $finish=$self->{'dbh'}->prepare("UPDATE systempreferences SET value=? WHERE variable='Version'");
423 $finish->execute($kohaversion);
424 } else {
425 warn "INSERT Version";
426 my $finish=$self->{'dbh'}->prepare("INSERT into systempreferences (variable,value,explanation) values ('Version',?,'The Koha database version. WARNING: Do not change this value manually, it is maintained by the webinstaller')");
427 $finish->execute($kohaversion);
429 C4::Context->clear_syspref_cache();
432 =head2 load_sql
434 my $error = $installer->load_sql($filename);
436 Runs a the specified SQL file using a sql loader DBIx::RunSQL
437 Returns any strings sent to STDERR
439 # FIXME This should be improved: sometimes the caller and load_sql warn the same
440 error.
442 =cut
444 sub load_sql {
445 my $self = shift;
446 my $filename = shift;
447 my $error;
449 my $dbh = $self->{ dbh };
451 my $dup_stderr;
452 do {
453 local *STDERR;
454 open STDERR, ">>", \$dup_stderr;
456 eval {
457 DBIx::RunSQL->run_sql_file(
458 dbh => $dbh,
459 sql => $filename,
463 # errors thrown while loading installer data should be logged
464 if( $dup_stderr ) {
465 warn "C4::Installer::load_sql returned the following errors while attempting to load $filename:\n";
466 $error = $dup_stderr;
469 return $error;
472 =head2 get_file_path_from_name
474 my $filename = $installer->get_file_path_from_name('script_name');
476 searches through the set of known SQL scripts and finds the fully
477 qualified path name for the script that mathches the input.
479 returns undef if no match was found.
482 =cut
484 sub get_file_path_from_name {
485 my $self = shift;
486 my $partialname = shift;
488 my $lang = 'en'; # FIXME: how do I know what language I want?
490 my ($defaulted_to_en, $list) = $self->sample_data_sql_list($lang);
491 # warn( Data::Dumper->Dump( [ $list ], [ 'list' ] ) );
493 my @found;
494 foreach my $frameworklist ( @$list ) {
495 push @found, grep { $_->{'fwkfile'} =~ /$partialname$/ } @{$frameworklist->{'frameworks'}};
498 # warn( Data::Dumper->Dump( [ \@found ], [ 'found' ] ) );
499 if ( 0 == scalar @found ) {
500 return;
501 } elsif ( 1 < scalar @found ) {
502 warn "multiple results found for $partialname";
503 return;
504 } else {
505 return $found[0]->{'fwkfile'};
510 sub foreign_key_exists {
511 my ( $table_name, $constraint_name ) = @_;
512 my $dbh = C4::Context->dbh;
513 my (undef, $infos) = $dbh->selectrow_array(qq|SHOW CREATE TABLE $table_name|);
514 return $infos =~ m|CONSTRAINT `$constraint_name` FOREIGN KEY|;
517 sub index_exists {
518 my ( $table_name, $key_name ) = @_;
519 my $dbh = C4::Context->dbh;
520 my ($exists) = $dbh->selectrow_array(
522 SHOW INDEX FROM $table_name
523 WHERE key_name = ?
524 |, undef, $key_name
526 return $exists;
529 sub column_exists {
530 my ( $table_name, $column_name ) = @_;
531 my $dbh = C4::Context->dbh;
532 my ($exists) = $dbh->selectrow_array(
534 SHOW COLUMNS FROM $table_name
535 WHERE Field = ?
536 |, undef, $column_name
538 return $exists;
541 =head1 AUTHOR
543 C4::Installer is a refactoring of logic originally from installer/installer.pl, which was
544 originally written by Henri-Damien Laurant.
546 Koha Development Team <http://koha-community.org/>
548 Galen Charlton <galen.charlton@liblime.com>
550 =cut