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