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