country_mode 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::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
292   # load chart of accounts
293   $dbupdater->process_query($dbh, "sql/$form->{chart}-chart.sql");
294
295   $query = qq|UPDATE defaults SET coa = ?, accounting_method = ?, profit_determination = ?, inventory_system = ?, curr = ?, precision = ?|;
296   do_query($form, $dbh, $query, map { $form->{$_} } qw(chart accounting_method profit_determination inventory_system defaultcurrency precision countrymode));
297
298   $dbh->disconnect;
299
300   $main::lxdebug->leave_sub();
301 }
302
303 sub dbdelete {
304   $main::lxdebug->enter_sub();
305
306   my ($self, $form) = @_;
307   $form->{db} =~ s/\"//g;
308
309   &dbconnect_vars($form, $form->{dbdefault});
310   my $dbh = SL::DBConnect->connect($form->{dbconnect}, $form->{dbuser}, $form->{dbpasswd}, SL::DBConnect->get_options)
311     or $form->dberror;
312   my $query = qq|DROP DATABASE "$form->{db}"|;
313   do_query($form, $dbh, $query);
314
315   $dbh->disconnect;
316
317   $main::lxdebug->leave_sub();
318 }
319
320 sub calc_version {
321   $main::lxdebug->enter_sub(2);
322
323   my (@v, $version, $i);
324
325   @v = split(/\./, $_[0]);
326   while (scalar(@v) < 4) {
327     push(@v, 0);
328   }
329   $version = 0;
330   for ($i = 0; $i < 4; $i++) {
331     $version *= 1000;
332     $version += $v[$i];
333   }
334
335   $main::lxdebug->leave_sub(2);
336   return $version;
337 }
338
339 sub cmp_script_version {
340   my ($a_from, $a_to, $b_from, $b_to);
341   my ($i, $res_a, $res_b);
342   my ($my_a, $my_b) = do { no warnings 'once'; ($a, $b) };
343
344   $my_a =~ s/.*-upgrade-//;
345   $my_a =~ s/.sql$//;
346   $my_b =~ s/.*-upgrade-//;
347   $my_b =~ s/.sql$//;
348   my ($my_a_from, $my_a_to) = split(/-/, $my_a);
349   my ($my_b_from, $my_b_to) = split(/-/, $my_b);
350
351   $res_a = calc_version($my_a_from);
352   $res_b = calc_version($my_b_from);
353
354   if ($res_a == $res_b) {
355     $res_a = calc_version($my_a_to);
356     $res_b = calc_version($my_b_to);
357   }
358
359   return $res_a <=> $res_b;
360 }
361
362 sub create_schema_info_table {
363   $main::lxdebug->enter_sub();
364
365   my ($self, $form, $dbh) = @_;
366
367   my $query = "SELECT tag FROM schema_info LIMIT 1";
368   if (!$dbh->do($query)) {
369     $dbh->rollback();
370     $query =
371       qq|CREATE TABLE schema_info (| .
372       qq|  tag text, | .
373       qq|  login text, | .
374       qq|  itime timestamp DEFAULT now(), | .
375       qq|  PRIMARY KEY (tag))|;
376     $dbh->do($query) || $form->dberror($query);
377   }
378
379   $main::lxdebug->leave_sub();
380 }
381
382 sub dbupdate2 {
383   my ($self, %params) = @_;
384
385   my $form            = $params{form};
386   my $dbupdater       = $params{updater};
387   my $db              = $params{database};
388
389   map { $_->{description} = SL::Iconv::convert($_->{charset}, 'UTF-8', $_->{description}) } values %{ $dbupdater->{all_controls} };
390
391   &dbconnect_vars($form, $db);
392
393   # Flush potentially held database locks.
394   $form->get_standard_dbh->commit;
395
396   my $dbh = SL::DBConnect->connect($form->{dbconnect}, $form->{dbuser}, $form->{dbpasswd}, SL::DBConnect->get_options) or $form->dberror;
397
398   $dbh->do($form->{dboptions}) if ($form->{dboptions});
399
400   $self->create_schema_info_table($form, $dbh);
401
402   my @upgradescripts = $dbupdater->unapplied_upgrade_scripts($dbh);
403
404   foreach my $control (@upgradescripts) {
405     # Apply upgrade. Control will only return to us if the upgrade has
406     # been applied correctly and if the update has not requested user
407     # interaction.
408     $main::lxdebug->message(LXDebug->DEBUG2(), "Applying Update $control->{file}");
409     print $form->parse_html_template("dbupgrade/upgrade_message2", $control);
410
411     $dbupdater->process_file($dbh, "sql/Pg-upgrade2/$control->{file}", $control);
412   }
413
414   $dbh->disconnect;
415 }
416
417 sub data {
418   +{ %{ $_[0] } }
419 }
420
421 sub get_default_myconfig {
422   my ($self_or_class, %user_config) = @_;
423   my $defaults = SL::DefaultManager->new($::lx_office_conf{system}->{default_manager});
424
425   return (
426     countrycode  => $defaults->language('de'),
427     css_path     => 'css',      # Needed for menunew, see SL::Layout::Base::get_stylesheet_for_user
428     dateformat   => $defaults->dateformat('dd.mm.yy'),
429     numberformat => $defaults->numberformat('1.000,00'),
430     stylesheet   => 'kivitendo.css',
431     timeformat   => $defaults->timeformat('hh:mm'),
432     %user_config,
433   );
434 }
435
436 1;