Consolidation and extended test runs
[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::DB::Employee;
43 use SL::DBConnect;
44 use SL::DBUpgrade2;
45 use SL::DBUtils;
46 use SL::Iconv;
47 use SL::Inifile;
48 use SL::System::InstallationLock;
49 use SL::DefaultManager;
50
51 use strict;
52
53 use constant LOGIN_OK                      =>  0;
54 use constant LOGIN_BASIC_TABLES_MISSING    => -1;
55 use constant LOGIN_DBUPDATE_AVAILABLE      => -2;
56 use constant LOGIN_AUTH_DBUPDATE_AVAILABLE => -3;
57 use constant LOGIN_GENERAL_ERROR           => -4;
58
59 sub new {
60   $main::lxdebug->enter_sub();
61
62   my ($type, %params) = @_;
63
64   my $self = {};
65
66   if ($params{id} || $params{login}) {
67     my %user_data = $main::auth->read_user(%params);
68     map { $self->{$_} = $user_data{$_} } keys %user_data;
69   }
70
71   $main::lxdebug->leave_sub();
72
73   bless $self, $type;
74 }
75
76 sub country_codes {
77   $main::lxdebug->enter_sub();
78
79   local *DIR;
80
81   my %cc       = ();
82   my @language = ();
83
84   # scan the locale directory and read in the LANGUAGE files
85   opendir(DIR, "locale");
86
87   my @dir = grep(!/(^\.\.?$|\..*)/, readdir(DIR));
88
89   foreach my $dir (@dir) {
90     next unless open(my $fh, '<:encoding(UTF-8)', "locale/$dir/LANGUAGE");
91     @language = <$fh>;
92     close $fh;
93
94     $cc{$dir} = "@language";
95   }
96
97   closedir(DIR);
98
99   $main::lxdebug->leave_sub();
100
101   return %cc;
102 }
103
104 sub login {
105   my ($self, $form) = @_;
106
107   return LOGIN_GENERAL_ERROR() if !$self->{login} || !$::auth->client;
108
109   my %myconfig = $main::auth->read_user(login => $self->{login});
110
111   # Auth DB upgrades available?
112   my $dbupdater_auth = SL::DBUpgrade2->new(form => $form, auth => 1)->parse_dbupdate_controls;
113   return LOGIN_AUTH_DBUPDATE_AVAILABLE() if $dbupdater_auth->unapplied_upgrade_scripts($::auth->dbconnect);
114
115   # check if database is down
116   my $dbh = $form->dbconnect_noauto;
117
118   # we got a connection, check the version
119   my ($dbversion) = $dbh->selectrow_array(qq|SELECT version FROM defaults|);
120   if (!$dbversion) {
121     $dbh->disconnect;
122     return LOGIN_BASIC_TABLES_MISSING();
123   }
124
125   $self->create_schema_info_table($form, $dbh);
126
127   my $dbupdater        = SL::DBUpgrade2->new(form => $form)->parse_dbupdate_controls;
128   my @unapplied_scripts = $dbupdater->unapplied_upgrade_scripts($dbh);
129   $dbh->disconnect;
130
131   if (!@unapplied_scripts) {
132     SL::DB::Manager::Employee->update_entries_for_authorized_users;
133     return LOGIN_OK();
134   }
135
136   $form->{$_} = $::auth->client->{$_} for qw(dbname dbhost dbport dbuser dbpasswd);
137   $form->{$_} = $myconfig{$_}         for qw(datestyle);
138
139   $form->{"title"} = $main::locale->text("Dataset upgrade");
140   $form->header(no_layout => $form->{no_layout});
141   print $form->parse_html_template("dbupgrade/header");
142
143   $form->{dbupdate} = "db" . $::auth->client->{dbname};
144
145   if ($form->{"show_dbupdate_warning"}) {
146     print $form->parse_html_template("dbupgrade/warning", { unapplied_scripts => \@unapplied_scripts });
147     ::end_of_request();
148   }
149
150   # update the tables
151   SL::System::InstallationLock->lock;
152
153   # ignore HUP, QUIT in case the webserver times out
154   $SIG{HUP}  = 'IGNORE';
155   $SIG{QUIT} = 'IGNORE';
156
157   $self->dbupdate2(form => $form, updater => $dbupdater, database => $::auth->client->{dbname});
158
159   # If $self->dbupdate2 returns than this means all upgrade scripts
160   # have been applied successfully, none required user
161   # interaction. Otherwise the deeper layers would have called
162   # ::end_of_request() already, and return would not have returned to
163   # us. Therefore we can now use RDBO instances because their supposed
164   # table structures do match the actual structures. So let's ensure
165   # that the "employee" table contains the appropriate entries for all
166   # users authorized for the current client.
167   SL::DB::Manager::Employee->update_entries_for_authorized_users;
168
169   SL::System::InstallationLock->unlock;
170
171   print $form->parse_html_template("dbupgrade/footer");
172
173   return LOGIN_DBUPDATE_AVAILABLE();
174 }
175
176 sub dbconnect_vars {
177   $main::lxdebug->enter_sub();
178
179   my ($form, $db) = @_;
180
181   my %dboptions = (
182     'yy-mm-dd'   => 'set DateStyle to \'ISO\'',
183     'yyyy-mm-dd' => 'set DateStyle to \'ISO\'',
184     'mm/dd/yy'   => 'set DateStyle to \'SQL, US\'',
185     'dd/mm/yy'   => 'set DateStyle to \'SQL, EUROPEAN\'',
186     'dd.mm.yy'   => 'set DateStyle to \'GERMAN\''
187   );
188
189   $form->{dboptions} = $dboptions{ $form->{dateformat} };
190   $form->{dbconnect} = "dbi:Pg:dbname=${db};host=" . ($form->{dbhost} || 'localhost') . ";port=" . ($form->{dbport} || 5432);
191
192   $main::lxdebug->leave_sub();
193 }
194
195 sub dbsources {
196   $main::lxdebug->enter_sub();
197
198   my ($self, $form) = @_;
199
200   my @dbsources = ();
201   my ($sth, $query);
202
203   $form->{dbdefault} = $form->{dbuser} unless $form->{dbdefault};
204   &dbconnect_vars($form, $form->{dbdefault});
205
206   my $dbh = SL::DBConnect->connect($form->{dbconnect}, $form->{dbuser}, $form->{dbpasswd}, SL::DBConnect->get_options)
207     or $form->dberror;
208
209   $query =
210     qq|SELECT datname FROM pg_database | .
211     qq|WHERE NOT datname IN ('template0', 'template1')|;
212   $sth = $dbh->prepare($query);
213   $sth->execute() || $form->dberror($query);
214
215   while (my ($db) = $sth->fetchrow_array) {
216
217     if ($form->{only_acc_db}) {
218
219       next if ($db =~ /^template/);
220
221       &dbconnect_vars($form, $db);
222       my $dbh = SL::DBConnect->connect($form->{dbconnect}, $form->{dbuser}, $form->{dbpasswd}, SL::DBConnect->get_options)
223         or $form->dberror;
224
225       $query =
226         qq|SELECT tablename FROM pg_tables | .
227         qq|WHERE (tablename = 'defaults') AND (tableowner = ?)|;
228       my $sth = $dbh->prepare($query);
229       $sth->execute($form->{dbuser}) ||
230         $form->dberror($query . " ($form->{dbuser})");
231
232       if ($sth->fetchrow_array) {
233         push(@dbsources, $db);
234       }
235       $sth->finish;
236       $dbh->disconnect;
237       next;
238     }
239     push(@dbsources, $db);
240   }
241
242   $sth->finish;
243   $dbh->disconnect;
244
245   $main::lxdebug->leave_sub();
246
247   return @dbsources;
248 }
249
250 sub dbcreate {
251   $main::lxdebug->enter_sub();
252
253   my ($self, $form) = @_;
254
255   &dbconnect_vars($form, $form->{dbdefault});
256   my $dbh =
257     SL::DBConnect->connect($form->{dbconnect}, $form->{dbuser}, $form->{dbpasswd}, SL::DBConnect->get_options)
258     or $form->dberror;
259   $form->{db} =~ s/\"//g;
260
261   my @dboptions;
262
263   push @dboptions, "ENCODING = " . $dbh->quote($form->{"encoding"}) if $form->{"encoding"};
264   if ($form->{"dbdefault"}) {
265     my $dbdefault = $form->{"dbdefault"};
266     $dbdefault =~ s/[^a-zA-Z0-9_\-]//g;
267     push @dboptions, "TEMPLATE = $dbdefault";
268   }
269
270   my $query = qq|CREATE DATABASE "$form->{db}"|;
271   $query   .= " WITH " . join(" ", @dboptions) if @dboptions;
272
273   # Ignore errors if the database exists.
274   $dbh->do($query);
275
276   $dbh->disconnect;
277
278   &dbconnect_vars($form, $form->{db});
279
280   $dbh = SL::DBConnect->connect($form->{dbconnect}, $form->{dbuser}, $form->{dbpasswd}, SL::DBConnect->get_options)
281     or $form->dberror;
282
283   my $dbupdater = SL::DBUpgrade2->new(form => $form);
284   # create the tables
285   $dbupdater->process_query($dbh, "sql/lx-office.sql");
286
287   # process update-scripts needed before 1st user-login
288   $self->create_schema_info_table($form, $dbh);
289   $dbupdater->process_query($dbh, "sql/Pg-upgrade2/defaults_add_precision.sql");
290   $dbh->do("INSERT INTO schema_info (tag, login) VALUES ('defaults_add_precision', 'admin')");
291   $dbupdater->process_query($dbh, "sql/Pg-upgrade2/defaults_add_country_mode.sql");
292   $dbh->do("INSERT INTO schema_info (tag, login) VALUES ('defaults_add_country_mode', 'admin')");
293
294   # load chart of accounts
295   $dbupdater->process_query($dbh, "sql/$form->{chart}-chart.sql");
296
297   $query = qq|UPDATE defaults SET coa = ?, accounting_method = ?, profit_determination = ?, inventory_system = ?, curr = ?, precision = ?, country_mode = ?|;
298   do_query($form, $dbh, $query, map { $form->{$_} } qw(chart accounting_method profit_determination inventory_system defaultcurrency precision countrymode));
299
300   $dbh->disconnect;
301
302   $main::lxdebug->leave_sub();
303 }
304
305 sub dbdelete {
306   $main::lxdebug->enter_sub();
307
308   my ($self, $form) = @_;
309   $form->{db} =~ s/\"//g;
310
311   &dbconnect_vars($form, $form->{dbdefault});
312   my $dbh = SL::DBConnect->connect($form->{dbconnect}, $form->{dbuser}, $form->{dbpasswd}, SL::DBConnect->get_options)
313     or $form->dberror;
314   my $query = qq|DROP DATABASE "$form->{db}"|;
315   do_query($form, $dbh, $query);
316
317   $dbh->disconnect;
318
319   $main::lxdebug->leave_sub();
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) = do { no warnings 'once'; ($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   my ($self, %params) = @_;
386
387   my $form            = $params{form};
388   my $dbupdater       = $params{updater};
389   my $db              = $params{database};
390
391   map { $_->{description} = SL::Iconv::convert($_->{charset}, 'UTF-8', $_->{description}) } values %{ $dbupdater->{all_controls} };
392
393   &dbconnect_vars($form, $db);
394
395   # Flush potentially held database locks.
396   $form->get_standard_dbh->commit;
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   foreach my $control (@upgradescripts) {
407     # Apply upgrade. Control will only return to us if the upgrade has
408     # been applied correctly and if the update has not requested user
409     # interaction.
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   $dbh->disconnect;
417 }
418
419 sub data {
420   +{ %{ $_[0] } }
421 }
422
423 sub get_default_myconfig {
424   my ($self_or_class, %user_config) = @_;
425   my $defaults = SL::DefaultManager->new($::lx_office_conf{system}->{default_manager});
426
427   return (
428     countrycode  => $defaults->language('de'),
429     css_path     => 'css',      # Needed for menunew, see SL::Layout::Base::get_stylesheet_for_user
430     dateformat   => $defaults->dateformat('dd.mm.yy'),
431     numberformat => $defaults->numberformat('1.000,00'),
432     stylesheet   => 'kivitendo.css',
433     timeformat   => $defaults->timeformat('hh:mm'),
434     %user_config,
435   );
436 }
437
438 1;