Wenn DB existiert aber Basistabellen fehlen anständige Fehlermeldung anzeigen
[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 use constant LOGIN_OK                      =>  0;
52 use constant LOGIN_BASIC_TABLES_MISSING    => -1;
53 use constant LOGIN_DBUPDATE_AVAILABLE      => -2;
54 use constant LOGIN_AUTH_DBUPDATE_AVAILABLE => -3;
55 use constant LOGIN_GENERAL_ERROR           => -4;
56
57 sub new {
58   $main::lxdebug->enter_sub();
59
60   my ($type, %params) = @_;
61
62   my $self = {};
63
64   if ($params{id} || $params{login}) {
65     my %user_data = $main::auth->read_user(%params);
66     map { $self->{$_} = $user_data{$_} } keys %user_data;
67   }
68
69   $main::lxdebug->leave_sub();
70
71   bless $self, $type;
72 }
73
74 sub country_codes {
75   $main::lxdebug->enter_sub();
76
77   local *DIR;
78
79   my %cc       = ();
80   my @language = ();
81
82   # scan the locale directory and read in the LANGUAGE files
83   opendir(DIR, "locale");
84
85   my @dir = grep(!/(^\.\.?$|\..*)/, readdir(DIR));
86
87   foreach my $dir (@dir) {
88     next unless open(my $fh, '<:encoding(UTF-8)', "locale/$dir/LANGUAGE");
89     @language = <$fh>;
90     close $fh;
91
92     $cc{$dir} = "@language";
93   }
94
95   closedir(DIR);
96
97   $main::lxdebug->leave_sub();
98
99   return %cc;
100 }
101
102 sub login {
103   my ($self, $form) = @_;
104
105   return LOGIN_GENERAL_ERROR() if !$self->{login} || !$::auth->client;
106
107   my %myconfig = $main::auth->read_user(login => $self->{login});
108
109   # Auth DB upgrades available?
110   my $dbupdater_auth = SL::DBUpgrade2->new(form => $form, auth => 1)->parse_dbupdate_controls;
111   return LOGIN_AUTH_DBUPDATE_AVAILABLE() if $dbupdater_auth->unapplied_upgrade_scripts($::auth->dbconnect);
112
113   # check if database is down
114   my $dbh = $form->dbconnect_noauto;
115
116   # we got a connection, check the version
117   my ($dbversion) = $dbh->selectrow_array(qq|SELECT version FROM defaults|);
118   if (!$dbversion) {
119     $dbh->disconnect;
120     return LOGIN_BASIC_TABLES_MISSING();
121   }
122
123   $self->create_schema_info_table($form, $dbh);
124
125   my $dbupdater        = SL::DBUpgrade2->new(form => $form)->parse_dbupdate_controls;
126   my $update_available = $dbupdater->update2_available($dbh);
127   $dbh->disconnect;
128
129   return LOGIN_OK() if !$update_available;
130
131   $form->{$_} = $::auth->client->{$_} for qw(dbname dbhost dbport dbuser dbpasswd);
132   $form->{$_} = $myconfig{$_}         for qw(datestyle);
133
134   $form->{"title"} = $main::locale->text("Dataset upgrade");
135   $form->header(no_layout => $form->{no_layout});
136   print $form->parse_html_template("dbupgrade/header");
137
138   $form->{dbupdate} = "db" . $::auth->client->{dbname};
139
140   if ($form->{"show_dbupdate_warning"}) {
141     print $form->parse_html_template("dbupgrade/warning");
142     ::end_of_request();
143   }
144
145   # update the tables
146   SL::System::InstallationLock->lock;
147
148   # ignore HUP, QUIT in case the webserver times out
149   $SIG{HUP}  = 'IGNORE';
150   $SIG{QUIT} = 'IGNORE';
151
152   $self->dbupdate2(form => $form, updater => $dbupdater, database => $::auth->client->{dbname});
153   SL::DBUpgrade2->new(form => $::form, auth => 1)->apply_admin_dbupgrade_scripts(0);
154
155   SL::System::InstallationLock->unlock;
156
157   print $form->parse_html_template("dbupgrade/footer");
158
159   return LOGIN_DBUPDATE_AVAILABLE();
160 }
161
162 sub dbconnect_vars {
163   $main::lxdebug->enter_sub();
164
165   my ($form, $db) = @_;
166
167   my %dboptions = (
168     'yy-mm-dd'   => 'set DateStyle to \'ISO\'',
169     'yyyy-mm-dd' => 'set DateStyle to \'ISO\'',
170     'mm/dd/yy'   => 'set DateStyle to \'SQL, US\'',
171     'dd/mm/yy'   => 'set DateStyle to \'SQL, EUROPEAN\'',
172     'dd.mm.yy'   => 'set DateStyle to \'GERMAN\''
173   );
174
175   $form->{dboptions} = $dboptions{ $form->{dateformat} };
176   $form->{dbconnect} = "dbi:Pg:dbname=${db};host=" . ($form->{dbhost} || 'localhost') . ";port=" . ($form->{dbport} || 5432);
177
178   $main::lxdebug->leave_sub();
179 }
180
181 sub dbsources {
182   $main::lxdebug->enter_sub();
183
184   my ($self, $form) = @_;
185
186   my @dbsources = ();
187   my ($sth, $query);
188
189   $form->{dbdefault} = $form->{dbuser} unless $form->{dbdefault};
190   &dbconnect_vars($form, $form->{dbdefault});
191
192   my $dbh = SL::DBConnect->connect($form->{dbconnect}, $form->{dbuser}, $form->{dbpasswd}, SL::DBConnect->get_options)
193     or $form->dberror;
194
195   $query =
196     qq|SELECT datname FROM pg_database | .
197     qq|WHERE NOT datname IN ('template0', 'template1')|;
198   $sth = $dbh->prepare($query);
199   $sth->execute() || $form->dberror($query);
200
201   while (my ($db) = $sth->fetchrow_array) {
202
203     if ($form->{only_acc_db}) {
204
205       next if ($db =~ /^template/);
206
207       &dbconnect_vars($form, $db);
208       my $dbh = SL::DBConnect->connect($form->{dbconnect}, $form->{dbuser}, $form->{dbpasswd}, SL::DBConnect->get_options)
209         or $form->dberror;
210
211       $query =
212         qq|SELECT tablename FROM pg_tables | .
213         qq|WHERE (tablename = 'defaults') AND (tableowner = ?)|;
214       my $sth = $dbh->prepare($query);
215       $sth->execute($form->{dbuser}) ||
216         $form->dberror($query . " ($form->{dbuser})");
217
218       if ($sth->fetchrow_array) {
219         push(@dbsources, $db);
220       }
221       $sth->finish;
222       $dbh->disconnect;
223       next;
224     }
225     push(@dbsources, $db);
226   }
227
228   $sth->finish;
229   $dbh->disconnect;
230
231   $main::lxdebug->leave_sub();
232
233   return @dbsources;
234 }
235
236 sub dbcreate {
237   $main::lxdebug->enter_sub();
238
239   my ($self, $form) = @_;
240
241   &dbconnect_vars($form, $form->{dbdefault});
242   my $dbh =
243     SL::DBConnect->connect($form->{dbconnect}, $form->{dbuser}, $form->{dbpasswd}, SL::DBConnect->get_options)
244     or $form->dberror;
245   $form->{db} =~ s/\"//g;
246
247   my @dboptions;
248
249   push @dboptions, "ENCODING = " . $dbh->quote($form->{"encoding"}) if $form->{"encoding"};
250   if ($form->{"dbdefault"}) {
251     my $dbdefault = $form->{"dbdefault"};
252     $dbdefault =~ s/[^a-zA-Z0-9_\-]//g;
253     push @dboptions, "TEMPLATE = $dbdefault";
254   }
255
256   my $query = qq|CREATE DATABASE "$form->{db}"|;
257   $query   .= " WITH " . join(" ", @dboptions) if @dboptions;
258
259   # Ignore errors if the database exists.
260   $dbh->do($query);
261
262   $dbh->disconnect;
263
264   &dbconnect_vars($form, $form->{db});
265
266   $dbh = SL::DBConnect->connect($form->{dbconnect}, $form->{dbuser}, $form->{dbpasswd}, SL::DBConnect->get_options)
267     or $form->dberror;
268
269   my $dbupdater = SL::DBUpgrade2->new(form => $form);
270   # create the tables
271   $dbupdater->process_query($dbh, "sql/lx-office.sql");
272
273   # load chart of accounts
274   $dbupdater->process_query($dbh, "sql/$form->{chart}-chart.sql");
275
276   my $query = qq|UPDATE defaults SET coa = ?, accounting_method = ?, profit_determination = ?, inventory_system = ?, curr = ?|;
277   do_query($form, $dbh, $query, map { $form->{$_} } qw(chart accounting_method profit_determination inventory_system defaultcurrency));
278
279   $dbh->disconnect;
280
281   $main::lxdebug->leave_sub();
282 }
283
284 sub dbdelete {
285   $main::lxdebug->enter_sub();
286
287   my ($self, $form) = @_;
288   $form->{db} =~ s/\"//g;
289
290   &dbconnect_vars($form, $form->{dbdefault});
291   my $dbh = SL::DBConnect->connect($form->{dbconnect}, $form->{dbuser}, $form->{dbpasswd}, SL::DBConnect->get_options)
292     or $form->dberror;
293   my $query = qq|DROP DATABASE "$form->{db}"|;
294   do_query($form, $dbh, $query);
295
296   $dbh->disconnect;
297
298   $main::lxdebug->leave_sub();
299 }
300
301 sub dbsources_unused {
302   $main::lxdebug->enter_sub();
303
304   my ($self, $form) = @_;
305
306   my %dbexcl = map  { $_->dbname => 1 }
307                grep { ($_->dbhost eq $form->{dbhost}) && ($_->dbport eq $form->{dbport}) }
308                     @{ SL::DB::Manager::AuthClient->get_all };
309
310   $form->{only_acc_db} = 1;
311
312   $dbexcl{$form->{dbdefault}}             = 1;
313   $dbexcl{$main::auth->{DB_config}->{db}} = 1;
314
315   my @dbunused = grep { !$dbexcl{$_} } dbsources("", $form);
316
317   $main::lxdebug->leave_sub();
318
319   return @dbunused;
320 }
321
322 sub calc_version {
323   $main::lxdebug->enter_sub(2);
324
325   my (@v, $version, $i);
326
327   @v = split(/\./, $_[0]);
328   while (scalar(@v) < 4) {
329     push(@v, 0);
330   }
331   $version = 0;
332   for ($i = 0; $i < 4; $i++) {
333     $version *= 1000;
334     $version += $v[$i];
335   }
336
337   $main::lxdebug->leave_sub(2);
338   return $version;
339 }
340
341 sub cmp_script_version {
342   my ($a_from, $a_to, $b_from, $b_to);
343   my ($i, $res_a, $res_b);
344   my ($my_a, $my_b) = ($a, $b);
345
346   $my_a =~ s/.*-upgrade-//;
347   $my_a =~ s/.sql$//;
348   $my_b =~ s/.*-upgrade-//;
349   $my_b =~ s/.sql$//;
350   my ($my_a_from, $my_a_to) = split(/-/, $my_a);
351   my ($my_b_from, $my_b_to) = split(/-/, $my_b);
352
353   $res_a = calc_version($my_a_from);
354   $res_b = calc_version($my_b_from);
355
356   if ($res_a == $res_b) {
357     $res_a = calc_version($my_a_to);
358     $res_b = calc_version($my_b_to);
359   }
360
361   return $res_a <=> $res_b;
362 }
363
364 sub create_schema_info_table {
365   $main::lxdebug->enter_sub();
366
367   my ($self, $form, $dbh) = @_;
368
369   my $query = "SELECT tag FROM schema_info LIMIT 1";
370   if (!$dbh->do($query)) {
371     $dbh->rollback();
372     $query =
373       qq|CREATE TABLE schema_info (| .
374       qq|  tag text, | .
375       qq|  login text, | .
376       qq|  itime timestamp DEFAULT now(), | .
377       qq|  PRIMARY KEY (tag))|;
378     $dbh->do($query) || $form->dberror($query);
379   }
380
381   $main::lxdebug->leave_sub();
382 }
383
384 sub dbupdate2 {
385   $main::lxdebug->enter_sub();
386
387   my ($self, %params) = @_;
388
389   my $form            = $params{form};
390   my $dbupdater       = $params{updater};
391   my $db              = $params{database};
392   my $rc              = -2;
393
394   map { $_->{description} = SL::Iconv::convert($_->{charset}, 'UTF-8', $_->{description}) } values %{ $dbupdater->{all_controls} };
395
396   &dbconnect_vars($form, $db);
397
398   my $dbh = SL::DBConnect->connect($form->{dbconnect}, $form->{dbuser}, $form->{dbpasswd}, SL::DBConnect->get_options) or $form->dberror;
399
400   $dbh->do($form->{dboptions}) if ($form->{dboptions});
401
402   $self->create_schema_info_table($form, $dbh);
403
404   my @upgradescripts = $dbupdater->unapplied_upgrade_scripts($dbh);
405
406   $dbh->disconnect and next if !@upgradescripts;
407
408   foreach my $control (@upgradescripts) {
409     # apply upgrade
410     $main::lxdebug->message(LXDebug->DEBUG2(), "Applying Update $control->{file}");
411     print $form->parse_html_template("dbupgrade/upgrade_message2", $control);
412
413     $dbupdater->process_file($dbh, "sql/Pg-upgrade2/$control->{file}", $control);
414   }
415
416   $rc = 0;
417   $dbh->disconnect;
418
419   $main::lxdebug->leave_sub();
420
421   return $rc;
422 }
423
424 sub data {
425   +{ %{ $_[0] } }
426 }
427
428 1;