Merge branch 'dbupgrade-for-auth'
[kivitendo-erp.git] / SL / DBUpgrade2.pm
1 package SL::DBUpgrade2;
2
3 use IO::File;
4 use List::MoreUtils qw(any);
5
6 use SL::Common;
7 use SL::Iconv;
8
9 use strict;
10
11 sub new {
12   my $package = shift;
13
14   return bless({}, $package)->init(@_);
15 }
16
17 sub init {
18   my ($self, %params) = @_;
19
20   if ($params{auth}) {
21     $params{path_suffix} = "-auth";
22     $params{schema}      = "auth.";
23   }
24
25   $params{path_suffix} ||= '';
26   $params{schame}      ||= '';
27
28   map { $self->{$_} = $params{$_} } keys %params;
29
30   return $self;
31 }
32
33 sub parse_dbupdate_controls {
34   $::lxdebug->enter_sub();
35
36   my ($self) = @_;
37
38   my $form   = $self->{form};
39   my $locale = $::locale;
40
41   local *IN;
42   my %all_controls;
43
44   my $path = "sql/" . $self->{dbdriver} . "-upgrade2" . $self->{path_suffix};
45
46   foreach my $file_name (<$path/*.sql>, <$path/*.pl>) {
47     next unless (open(IN, $file_name));
48
49     my $file = $file_name;
50     $file =~ s|.*/||;
51
52     my $control = {
53       "priority" => 1000,
54       "depends"  => [],
55     };
56
57     while (<IN>) {
58       chomp();
59       next unless (/^(--|\#)\s*\@/);
60       s/^(--|\#)\s*\@//;
61       s/\s*$//;
62       next if ($_ eq "");
63
64       my @fields = split(/\s*:\s*/, $_, 2);
65       next unless (scalar(@fields) == 2);
66
67       if ($fields[0] eq "depends") {
68         push(@{$control->{"depends"}}, split(/\s+/, $fields[1]));
69       } else {
70         $control->{$fields[0]} = $fields[1];
71       }
72     }
73
74     next if ($control->{ignore});
75
76     $control->{charset} ||= Common::DEFAULT_CHARSET;
77
78     if (!$control->{"tag"}) {
79       _control_error($form, $file_name, $locale->text("Missing 'tag' field.")) ;
80     }
81
82     if ($control->{"tag"} =~ /[^a-zA-Z0-9_\(\)\-]/) {
83       _control_error($form, $file_name, $locale->text("The 'tag' field must only consist of alphanumeric characters or the carachters - _ ( )"))
84     }
85
86     if (defined($all_controls{$control->{"tag"}})) {
87       _control_error($form, $file_name, sprintf($locale->text("More than one control file with the tag '%s' exist."), $control->{"tag"}))
88     }
89
90     if (!$control->{"description"}) {
91       _control_error($form, $file_name, sprintf($locale->text("Missing 'description' field."))) ;
92     }
93
94     $control->{"priority"}  *= 1;
95     $control->{"priority"} ||= 1000;
96     $control->{"file"}       = $file;
97
98     delete @{$control}{qw(depth applied)};
99
100     $all_controls{$control->{"tag"}} = $control;
101
102     close(IN);
103   }
104
105   foreach my $control (values(%all_controls)) {
106     foreach my $dependency (@{$control->{"depends"}}) {
107       _control_error($form, $control->{"file"}, sprintf($locale->text("Unknown dependency '%s'."), $dependency)) if (!defined($all_controls{$dependency}));
108     }
109
110     map({ $_->{"loop"} = 0; } values(%all_controls));
111     _check_for_loops($form, $control->{"file"}, \%all_controls, $control->{"tag"});
112   }
113
114   map({ _dbupdate2_calculate_depth(\%all_controls, $_->{"tag"}) }
115       values(%all_controls));
116
117   $self->{all_controls} = \%all_controls;
118
119   $::lxdebug->leave_sub();
120
121   return $self;
122 }
123
124 sub process_query {
125   $::lxdebug->enter_sub();
126
127   my ($self, $dbh, $filename, $version_or_control, $db_charset) = @_;
128
129   my $form  = $self->{form};
130   my $fh    = IO::File->new($filename, "r") or $form->error("$filename : $!\n");
131   my $query = "";
132   my $sth;
133   my @quote_chars;
134
135   my $file_charset = Common::DEFAULT_CHARSET;
136   while (<$fh>) {
137     last if !/^--/;
138     next if !/^--\s*\@charset:\s*(.+)/;
139     $file_charset = $1;
140     last;
141   }
142   $fh->seek(0, SEEK_SET);
143
144   $db_charset ||= Common::DEFAULT_CHARSET;
145
146   $dbh->begin_work();
147
148   while (<$fh>) {
149     $_ = SL::Iconv::convert($file_charset, $db_charset, $_);
150
151     # Remove DOS and Unix style line endings.
152     chomp;
153
154     # remove comments
155     s/--.*$//;
156
157     for (my $i = 0; $i < length($_); $i++) {
158       my $char = substr($_, $i, 1);
159
160       # Are we inside a string?
161       if (@quote_chars) {
162         if ($char eq $quote_chars[-1]) {
163           pop(@quote_chars);
164         }
165         $query .= $char;
166
167       } else {
168         if (($char eq "'") || ($char eq "\"")) {
169           push(@quote_chars, $char);
170
171         } elsif ($char eq ";") {
172
173           # Query is complete. Send it.
174
175           $sth = $dbh->prepare($query);
176           if (!$sth->execute()) {
177             my $errstr = $dbh->errstr;
178             $sth->finish();
179             $dbh->rollback();
180             $form->dberror("The database update/creation did not succeed. " .
181                            "The file ${filename} containing the following " .
182                            "query failed:<br>${query}<br>" .
183                            "The error message was: ${errstr}<br>" .
184                            "All changes in that file have been reverted.");
185           }
186           $sth->finish();
187
188           $char  = "";
189           $query = "";
190         }
191
192         $query .= $char;
193       }
194     }
195
196     # Insert a space at the end of each line so that queries split
197     # over multiple lines work properly.
198     if ($query ne '') {
199       $query .= @quote_chars ? "\n" : ' ';
200     }
201   }
202
203   if (ref($version_or_control) eq "HASH") {
204     $dbh->do("INSERT INTO " . $self->{schema} . "schema_info (tag, login) VALUES (" . $dbh->quote($version_or_control->{"tag"}) . ", " . $dbh->quote($form->{"login"}) . ")");
205   } elsif ($version_or_control) {
206     $dbh->do("UPDATE defaults SET version = " . $dbh->quote($version_or_control));
207   }
208   $dbh->commit();
209
210   $fh->close();
211
212   $::lxdebug->leave_sub();
213 }
214
215 # Process a Perl script which updates the database.
216 # If the script returns 1 then the update was successful.
217 # Return code "2" means "needs more interaction; remove
218 # users/nologin and end current request".
219 # All other return codes are fatal errors.
220 sub process_perl_script {
221   $::lxdebug->enter_sub();
222
223   my ($self, $dbh, $filename, $version_or_control, $db_charset) = @_;
224
225   my $form         = $self->{form};
226   my $fh           = IO::File->new($filename, "r") or $form->error("$filename : $!\n");
227   my $file_charset = Common::DEFAULT_CHARSET;
228
229   if (ref($version_or_control) eq "HASH") {
230     $file_charset = $version_or_control->{charset};
231
232   } else {
233     while (<$fh>) {
234       last if !/^--/;
235       next if !/^--\s*\@charset:\s*(.+)/;
236       $file_charset = $1;
237       last;
238     }
239     $fh->seek(0, SEEK_SET);
240   }
241
242   my $contents = join "", <$fh>;
243   $fh->close();
244
245   $db_charset ||= Common::DEFAULT_CHARSET;
246
247   my $iconv = SL::Iconv::get_converter($file_charset, $db_charset);
248
249   $dbh->begin_work();
250
251   # setup dbup_ export vars
252   my %dbup_myconfig = ();
253   map({ $dbup_myconfig{$_} = $form->{$_}; } qw(dbname dbuser dbpasswd dbhost dbport dbconnect));
254
255   my $dbup_locale = $::locale;
256
257   my $result = eval($contents);
258
259   if (1 != $result) {
260     $dbh->rollback();
261     $dbh->disconnect();
262   }
263
264   if (!defined($result)) {
265     print $form->parse_html_template("dbupgrade/error",
266                                      { "file"  => $filename,
267                                        "error" => $@ });
268     ::end_of_request();
269   } elsif (1 != $result) {
270     unlink("users/nologin") if (2 == $result);
271     ::end_of_request();
272   }
273
274   if (ref($version_or_control) eq "HASH") {
275     $dbh->do("INSERT INTO " . $self->{schema} . "schema_info (tag, login) VALUES (" . $dbh->quote($version_or_control->{"tag"}) . ", " . $dbh->quote($form->{"login"}) . ")");
276   } elsif ($version_or_control) {
277     $dbh->do("UPDATE defaults SET version = " . $dbh->quote($version_or_control));
278   }
279   $dbh->commit();
280
281   $::lxdebug->leave_sub();
282 }
283
284 sub process_file {
285   my ($self, $dbh, $filename, $version_or_control, $db_charset) = @_;
286
287   if ($filename =~ m/sql$/) {
288     $self->process_query($dbh, $filename, $version_or_control, $db_charset);
289   } else {
290     $self->process_perl_script($dbh, $filename, $version_or_control, $db_charset);
291   }
292 }
293
294 sub update_available {
295   my ($self, $cur_version) = @_;
296
297   local *SQLDIR;
298
299   my $dbdriver = $self->{dbdriver};
300   opendir SQLDIR, "sql/${dbdriver}-upgrade" || error("", "sql/${dbdriver}-upgrade: $!");
301   my @upgradescripts = grep /${dbdriver}-upgrade-\Q$cur_version\E.*\.(sql|pl)$/, readdir SQLDIR;
302   closedir SQLDIR;
303
304   return ($#upgradescripts > -1);
305 }
306
307 sub update2_available {
308   $::lxdebug->enter_sub();
309
310   my ($self, $dbh) = @_;
311
312   map { $_->{applied} = 0; } values %{ $self->{all_controls} };
313
314   my $sth = $dbh->prepare(qq|SELECT tag FROM | . $self->{schema} . qq|schema_info|);
315   if ($sth->execute) {
316     while (my ($tag) = $sth->fetchrow_array) {
317       $self->{all_controls}->{$tag}->{applied} = 1 if defined $self->{all_controls}->{$tag};
318     }
319   }
320   $sth->finish();
321
322   my $needs_update = any { !$_->{applied} } values %{ $self->{all_controls} };
323
324   $::lxdebug->leave_sub();
325
326   return $needs_update;
327 }
328
329 sub unapplied_upgrade_scripts {
330   my ($self, $dbh) = @_;
331
332   my @all_scripts = map { $_->{applied} = 0; $_ } $self->sort_dbupdate_controls;
333
334   my $query = qq|SELECT tag FROM | . $self->{schema} . qq|schema_info|;
335   my $sth   = $dbh->prepare($query);
336   $sth->execute || $self->{form}->dberror($query);
337   while (my ($tag) = $sth->fetchrow_array()) {
338     $self->{all_controls}->{$tag}->{applied} = 1 if defined $self->{all_controls}->{$tag};
339   }
340   $sth->finish;
341
342   return grep { !$_->{applied} } @all_scripts;
343 }
344
345 sub apply_admin_dbupgrade_scripts {
346   my ($self, $called_from_admin) = @_;
347
348   return 0 if !$self->{auth};
349
350   my $dbh               = $::auth->dbconnect;
351   my @unapplied_scripts = $self->unapplied_upgrade_scripts($dbh);
352
353   return 0 if !@unapplied_scripts;
354
355   my $db_charset           = $main::dbcharset || Common::DEFAULT_CHARSET;
356   $self->{form}->{login} ||= 'admin';
357
358   map { $_->{description} = SL::Iconv::convert($_->{charset}, $db_charset, $_->{description}) } values %{ $self->{all_controls} };
359
360   if ($called_from_admin) {
361     $self->{form}->{title} = $::locale->text('Dataset upgrade');
362     $self->{form}->header;
363   }
364
365   print $self->{form}->parse_html_template("dbupgrade/header", { dbname => $::auth->{DB_config}->{db} });
366
367   foreach my $control (@unapplied_scripts) {
368     $::lxdebug->message(LXDebug->DEBUG2(), "Applying Update $control->{file}");
369     print $self->{form}->parse_html_template("dbupgrade/upgrade_message2", $control);
370
371     $self->process_file($dbh, "sql/$self->{dbdriver}-upgrade2-auth/$control->{file}", $control, $db_charset);
372   }
373
374   print $self->{form}->parse_html_template("dbupgrade/footer", { is_admin => 1 }) if $called_from_admin;
375
376   return 1;
377 }
378
379 sub _check_for_loops {
380   my ($form, $file_name, $controls, $tag, @path) = @_;
381
382   push(@path, $tag);
383
384   my $ctrl = $controls->{$tag};
385
386   if ($ctrl->{"loop"} == 1) {
387     # Not done yet.
388     _control_error($form, $file_name, $::locale->text("Dependency loop detected:") . " " . join(" -> ", @path))
389
390   } elsif ($ctrl->{"loop"} == 0) {
391     # Not checked yet.
392     $ctrl->{"loop"} = 1;
393     map({ _check_for_loops($form, $file_name, $controls, $_, @path); } @{ $ctrl->{"depends"} });
394     $ctrl->{"loop"} = 2;
395   }
396 }
397
398 sub _control_error {
399   my ($form, $file_name, $message) = @_;
400
401   $form = $::form;
402   my $locale = $::locale;
403
404   $form->error(sprintf($locale->text("Error in database control file '%s': %s"), $file_name, $message));
405 }
406
407 sub _dbupdate2_calculate_depth {
408   $::lxdebug->enter_sub(2);
409
410   my ($tree, $tag) = @_;
411
412   my $node = $tree->{$tag};
413
414   return $::lxdebug->leave_sub(2) if (defined($node->{"depth"}));
415
416   my $max_depth = 0;
417
418   foreach $tag (@{$node->{"depends"}}) {
419     _dbupdate2_calculate_depth($tree, $tag);
420     my $value = $tree->{$tag}->{"depth"};
421     $max_depth = $value if ($value > $max_depth);
422   }
423
424   $node->{"depth"} = $max_depth + 1;
425
426   $::lxdebug->leave_sub(2);
427 }
428
429 sub sort_dbupdate_controls {
430   my $self = shift;
431
432   $self->parse_dbupdate_controls unless $self->{all_controls};
433
434   return sort { ($a->{depth} <=> $b->{depth}) || ($a->{priority} <=> $b->{priority}) || ($a->{tag} cmp $b->{tag}) } values %{ $self->{all_controls} };
435 }
436
437 1;