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