Alten DB-Upgrademechnismus sql/Pg-upgrade entfernt
[kivitendo-erp.git] / SL / User.pm
1 #=====================================================================
2 # LX-Office ERP
3 # Copyright (C) 2004
4 # Based on SQL-Ledger Version 2.1.9
5 # Web http://www.lx-office.org
6 #
7 #=====================================================================
8 # SQL-Ledger Accounting
9 # Copyright (C) 2001
10 #
11 #  Author: Dieter Simader
12 #   Email: dsimader@sql-ledger.org
13 #     Web: http://www.sql-ledger.org
14 #
15 #  Contributors:
16 #
17 # This program is free software; you can redistribute it and/or modify
18 # it under the terms of the GNU General Public License as published by
19 # the Free Software Foundation; either version 2 of the License, or
20 # (at your option) any later version.
21 #
22 # This program is distributed in the hope that it will be useful,
23 # but WITHOUT ANY WARRANTY; without even the implied warranty of
24 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
25 # GNU General Public License for more details.
26 # You should have received a copy of the GNU General Public License
27 # along with this program; if not, write to the Free Software
28 # Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
29 #=====================================================================
30 #
31 # user related functions
32 #
33 #=====================================================================
34
35 package User;
36
37 use IO::File;
38 use Fcntl qw(:seek);
39
40 #use SL::Auth;
41 use SL::DB::AuthClient;
42 use SL::DBConnect;
43 use SL::DBUpgrade2;
44 use SL::DBUtils;
45 use SL::Iconv;
46 use SL::Inifile;
47 use SL::System::InstallationLock;
48
49 use strict;
50
51 sub new {
52   $main::lxdebug->enter_sub();
53
54   my ($type, %params) = @_;
55
56   my $self = {};
57
58   if ($params{id} || $params{login}) {
59     my %user_data = $main::auth->read_user(%params);
60     map { $self->{$_} = $user_data{$_} } keys %user_data;
61   }
62
63   $main::lxdebug->leave_sub();
64
65   bless $self, $type;
66 }
67
68 sub country_codes {
69   $main::lxdebug->enter_sub();
70
71   local *DIR;
72
73   my %cc       = ();
74   my @language = ();
75
76   # scan the locale directory and read in the LANGUAGE files
77   opendir(DIR, "locale");
78
79   my @dir = grep(!/(^\.\.?$|\..*)/, readdir(DIR));
80
81   foreach my $dir (@dir) {
82     next unless open(my $fh, '<:encoding(UTF-8)', "locale/$dir/LANGUAGE");
83     @language = <$fh>;
84     close $fh;
85
86     $cc{$dir} = "@language";
87   }
88
89   closedir(DIR);
90
91   $main::lxdebug->leave_sub();
92
93   return %cc;
94 }
95
96 sub login {
97   my ($self, $form) = @_;
98
99   return -3 if !$self->{login} || !$::auth->client;
100
101   my %myconfig = $main::auth->read_user(login => $self->{login});
102
103   # check if database is down
104   my $dbh = $form->dbconnect_noauto;
105
106   # we got a connection, check the version
107   my ($dbversion) = $dbh->selectrow_array(qq|SELECT version FROM defaults|);
108
109   $self->create_schema_info_table($form, $dbh);
110
111   # Auth DB upgrades available?
112   my $dbupdater_auth = SL::DBUpgrade2->new(form => $form, auth => 1)->parse_dbupdate_controls;
113   return -3 if $dbupdater_auth->unapplied_upgrade_scripts($::auth->dbconnect);
114
115   my $dbupdater = SL::DBUpgrade2->new(form => $form)->parse_dbupdate_controls;
116
117   my $update_available = $dbupdater->update2_available($dbh);
118   $dbh->disconnect;
119
120   return 0 if !$update_available;
121
122   $form->{$_} = $::auth->client->{$_} for qw(dbname dbhost dbport dbuser dbpasswd);
123   $form->{$_} = $myconfig{$_}         for qw(datestyle);
124
125   $form->{"title"} = $main::locale->text("Dataset upgrade");
126   $form->header(no_layout => $form->{no_layout});
127   print $form->parse_html_template("dbupgrade/header");
128
129   $form->{dbupdate} = "db" . $::auth->client->{dbname};
130
131   if ($form->{"show_dbupdate_warning"}) {
132     print $form->parse_html_template("dbupgrade/warning");
133     ::end_of_request();
134   }
135
136   # update the tables
137   SL::System::InstallationLock->lock;
138
139   # ignore HUP, QUIT in case the webserver times out
140   $SIG{HUP}  = 'IGNORE';
141   $SIG{QUIT} = 'IGNORE';
142
143   $self->dbupdate2(form => $form, updater => $dbupdater, database => $::auth->client->{dbname});
144   SL::DBUpgrade2->new(form => $::form, auth => 1)->apply_admin_dbupgrade_scripts(0);
145
146   SL::System::InstallationLock->unlock;
147
148   print $form->parse_html_template("dbupgrade/footer");
149
150   return -2;
151 }
152
153 sub dbconnect_vars {
154   $main::lxdebug->enter_sub();
155
156   my ($form, $db) = @_;
157
158   my %dboptions = (
159     'yy-mm-dd'   => 'set DateStyle to \'ISO\'',
160     'yyyy-mm-dd' => 'set DateStyle to \'ISO\'',
161     'mm/dd/yy'   => 'set DateStyle to \'SQL, US\'',
162     'dd/mm/yy'   => 'set DateStyle to \'SQL, EUROPEAN\'',
163     'dd.mm.yy'   => 'set DateStyle to \'GERMAN\''
164   );
165
166   $form->{dboptions} = $dboptions{ $form->{dateformat} };
167   $form->{dbconnect} = "dbi:Pg:dbname=${db};host=" . ($form->{dbhost} || 'localhost') . ";port=" . ($form->{dbport} || 5432);
168
169   $main::lxdebug->leave_sub();
170 }
171
172 sub dbsources {
173   $main::lxdebug->enter_sub();
174
175   my ($self, $form) = @_;
176
177   my @dbsources = ();
178   my ($sth, $query);
179
180   $form->{dbdefault} = $form->{dbuser} unless $form->{dbdefault};
181   &dbconnect_vars($form, $form->{dbdefault});
182
183   my $dbh = SL::DBConnect->connect($form->{dbconnect}, $form->{dbuser}, $form->{dbpasswd}, SL::DBConnect->get_options)
184     or $form->dberror;
185
186   $query =
187     qq|SELECT datname FROM pg_database | .
188     qq|WHERE NOT datname IN ('template0', 'template1')|;
189   $sth = $dbh->prepare($query);
190   $sth->execute() || $form->dberror($query);
191
192   while (my ($db) = $sth->fetchrow_array) {
193
194     if ($form->{only_acc_db}) {
195
196       next if ($db =~ /^template/);
197
198       &dbconnect_vars($form, $db);
199       my $dbh = SL::DBConnect->connect($form->{dbconnect}, $form->{dbuser}, $form->{dbpasswd}, SL::DBConnect->get_options)
200         or $form->dberror;
201
202       $query =
203         qq|SELECT tablename FROM pg_tables | .
204         qq|WHERE (tablename = 'defaults') AND (tableowner = ?)|;
205       my $sth = $dbh->prepare($query);
206       $sth->execute($form->{dbuser}) ||
207         $form->dberror($query . " ($form->{dbuser})");
208
209       if ($sth->fetchrow_array) {
210         push(@dbsources, $db);
211       }
212       $sth->finish;
213       $dbh->disconnect;
214       next;
215     }
216     push(@dbsources, $db);
217   }
218
219   $sth->finish;
220   $dbh->disconnect;
221
222   $main::lxdebug->leave_sub();
223
224   return @dbsources;
225 }
226
227 sub dbcreate {
228   $main::lxdebug->enter_sub();
229
230   my ($self, $form) = @_;
231
232   &dbconnect_vars($form, $form->{dbdefault});
233   my $dbh =
234     SL::DBConnect->connect($form->{dbconnect}, $form->{dbuser}, $form->{dbpasswd}, SL::DBConnect->get_options)
235     or $form->dberror;
236   $form->{db} =~ s/\"//g;
237
238   my @dboptions;
239
240   push @dboptions, "ENCODING = " . $dbh->quote($form->{"encoding"}) if $form->{"encoding"};
241   if ($form->{"dbdefault"}) {
242     my $dbdefault = $form->{"dbdefault"};
243     $dbdefault =~ s/[^a-zA-Z0-9_\-]//g;
244     push @dboptions, "TEMPLATE = $dbdefault";
245   }
246
247   my $query = qq|CREATE DATABASE "$form->{db}"|;
248   $query   .= " WITH " . join(" ", @dboptions) if @dboptions;
249
250   # Ignore errors if the database exists.
251   $dbh->do($query);
252
253   $dbh->disconnect;
254
255   &dbconnect_vars($form, $form->{db});
256
257   $dbh = SL::DBConnect->connect($form->{dbconnect}, $form->{dbuser}, $form->{dbpasswd}, SL::DBConnect->get_options)
258     or $form->dberror;
259
260   my $dbupdater = SL::DBUpgrade2->new(form => $form);
261   # create the tables
262   $dbupdater->process_query($dbh, "sql/lx-office.sql");
263
264   # load chart of accounts
265   $dbupdater->process_query($dbh, "sql/$form->{chart}-chart.sql");
266
267   my $query = qq|UPDATE defaults SET coa = ?, accounting_method = ?, profit_determination = ?, inventory_system = ?, curr = ?|;
268   do_query($form, $dbh, $query, map { $form->{$_} } qw(chart accounting_method profit_determination inventory_system defaultcurrency));
269
270   $dbh->disconnect;
271
272   $main::lxdebug->leave_sub();
273 }
274
275 sub dbdelete {
276   $main::lxdebug->enter_sub();
277
278   my ($self, $form) = @_;
279   $form->{db} =~ s/\"//g;
280
281   &dbconnect_vars($form, $form->{dbdefault});
282   my $dbh = SL::DBConnect->connect($form->{dbconnect}, $form->{dbuser}, $form->{dbpasswd}, SL::DBConnect->get_options)
283     or $form->dberror;
284   my $query = qq|DROP DATABASE "$form->{db}"|;
285   do_query($form, $dbh, $query);
286
287   $dbh->disconnect;
288
289   $main::lxdebug->leave_sub();
290 }
291
292 sub dbsources_unused {
293   $main::lxdebug->enter_sub();
294
295   my ($self, $form) = @_;
296
297   my %dbexcl = map  { $_->dbname => 1 }
298                grep { ($_->dbhost eq $form->{dbhost}) && ($_->dbport eq $form->{dbport}) }
299                     @{ SL::DB::Manager::AuthClient->get_all };
300
301   $form->{only_acc_db} = 1;
302
303   $dbexcl{$form->{dbdefault}}             = 1;
304   $dbexcl{$main::auth->{DB_config}->{db}} = 1;
305
306   my @dbunused = grep { !$dbexcl{$_} } dbsources("", $form);
307
308   $main::lxdebug->leave_sub();
309
310   return @dbunused;
311 }
312
313 sub calc_version {
314   $main::lxdebug->enter_sub(2);
315
316   my (@v, $version, $i);
317
318   @v = split(/\./, $_[0]);
319   while (scalar(@v) < 4) {
320     push(@v, 0);
321   }
322   $version = 0;
323   for ($i = 0; $i < 4; $i++) {
324     $version *= 1000;
325     $version += $v[$i];
326   }
327
328   $main::lxdebug->leave_sub(2);
329   return $version;
330 }
331
332 sub cmp_script_version {
333   my ($a_from, $a_to, $b_from, $b_to);
334   my ($i, $res_a, $res_b);
335   my ($my_a, $my_b) = ($a, $b);
336
337   $my_a =~ s/.*-upgrade-//;
338   $my_a =~ s/.sql$//;
339   $my_b =~ s/.*-upgrade-//;
340   $my_b =~ s/.sql$//;
341   my ($my_a_from, $my_a_to) = split(/-/, $my_a);
342   my ($my_b_from, $my_b_to) = split(/-/, $my_b);
343
344   $res_a = calc_version($my_a_from);
345   $res_b = calc_version($my_b_from);
346
347   if ($res_a == $res_b) {
348     $res_a = calc_version($my_a_to);
349     $res_b = calc_version($my_b_to);
350   }
351
352   return $res_a <=> $res_b;
353 }
354
355 sub create_schema_info_table {
356   $main::lxdebug->enter_sub();
357
358   my ($self, $form, $dbh) = @_;
359
360   my $query = "SELECT tag FROM schema_info LIMIT 1";
361   if (!$dbh->do($query)) {
362     $dbh->rollback();
363     $query =
364       qq|CREATE TABLE schema_info (| .
365       qq|  tag text, | .
366       qq|  login text, | .
367       qq|  itime timestamp DEFAULT now(), | .
368       qq|  PRIMARY KEY (tag))|;
369     $dbh->do($query) || $form->dberror($query);
370   }
371
372   $main::lxdebug->leave_sub();
373 }
374
375 sub dbupdate2 {
376   $main::lxdebug->enter_sub();
377
378   my ($self, %params) = @_;
379
380   my $form            = $params{form};
381   my $dbupdater       = $params{updater};
382   my $db              = $params{database};
383   my $rc              = -2;
384
385   map { $_->{description} = SL::Iconv::convert($_->{charset}, 'UTF-8', $_->{description}) } values %{ $dbupdater->{all_controls} };
386
387   &dbconnect_vars($form, $db);
388
389   my $dbh = SL::DBConnect->connect($form->{dbconnect}, $form->{dbuser}, $form->{dbpasswd}, SL::DBConnect->get_options) or $form->dberror;
390
391   $dbh->do($form->{dboptions}) if ($form->{dboptions});
392
393   $self->create_schema_info_table($form, $dbh);
394
395   my @upgradescripts = $dbupdater->unapplied_upgrade_scripts($dbh);
396
397   $dbh->disconnect and next if !@upgradescripts;
398
399   foreach my $control (@upgradescripts) {
400     # apply upgrade
401     $main::lxdebug->message(LXDebug->DEBUG2(), "Applying Update $control->{file}");
402     print $form->parse_html_template("dbupgrade/upgrade_message2", $control);
403
404     $dbupdater->process_file($dbh, "sql/Pg-upgrade2/$control->{file}", $control);
405   }
406
407   $rc = 0;
408   $dbh->disconnect;
409
410   $main::lxdebug->leave_sub();
411
412   return $rc;
413 }
414
415 sub data {
416   +{ %{ $_[0] } }
417 }
418
419 1;