Revert "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
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   # Store the fact that we're applying database upgrades at the
136   # moment. That way functions called from the layout modules that may
137   # require updated tables can chose only to use basic features.
138   $::request->applying_database_upgrades(1);
139
140   $form->{$_} = $::auth->client->{$_} for qw(dbname dbhost dbport dbuser dbpasswd);
141   $form->{$_} = $myconfig{$_}         for qw(datestyle);
142
143   $form->{"title"} = $main::locale->text("Dataset upgrade");
144   $form->header(no_layout => $form->{no_layout});
145   print $form->parse_html_template("dbupgrade/header");
146
147   $form->{dbupdate} = "db" . $::auth->client->{dbname};
148
149   if ($form->{"show_dbupdate_warning"}) {
150     print $form->parse_html_template("dbupgrade/warning", { unapplied_scripts => \@unapplied_scripts });
151     ::end_of_request();
152   }
153
154   # update the tables
155   SL::System::InstallationLock->lock;
156
157   # ignore HUP, QUIT in case the webserver times out
158   $SIG{HUP}  = 'IGNORE';
159   $SIG{QUIT} = 'IGNORE';
160
161   $self->dbupdate2(form => $form, updater => $dbupdater, database => $::auth->client->{dbname});
162
163   # If $self->dbupdate2 returns than this means all upgrade scripts
164   # have been applied successfully, none required user
165   # interaction. Otherwise the deeper layers would have called
166   # ::end_of_request() already, and return would not have returned to
167   # us. Therefore we can now use RDBO instances because their supposed
168   # table structures do match the actual structures. So let's ensure
169   # that the "employee" table contains the appropriate entries for all
170   # users authorized for the current client.
171   SL::DB::Manager::Employee->update_entries_for_authorized_users;
172
173   SL::System::InstallationLock->unlock;
174
175   print $form->parse_html_template("dbupgrade/footer");
176
177   return LOGIN_DBUPDATE_AVAILABLE();
178 }
179
180 sub dbconnect_vars {
181   $main::lxdebug->enter_sub();
182
183   my ($form, $db) = @_;
184
185   my %dboptions = (
186     'yy-mm-dd'   => 'set DateStyle to \'ISO\'',
187     'yyyy-mm-dd' => 'set DateStyle to \'ISO\'',
188     'mm/dd/yy'   => 'set DateStyle to \'SQL, US\'',
189     'dd/mm/yy'   => 'set DateStyle to \'SQL, EUROPEAN\'',
190     'dd.mm.yy'   => 'set DateStyle to \'GERMAN\''
191   );
192
193   $form->{dboptions} = $dboptions{ $form->{dateformat} };
194   $form->{dbconnect} = "dbi:Pg:dbname=${db};host=" . ($form->{dbhost} || 'localhost') . ";port=" . ($form->{dbport} || 5432);
195
196   $main::lxdebug->leave_sub();
197 }
198
199 sub dbsources {
200   $main::lxdebug->enter_sub();
201
202   my ($self, $form) = @_;
203
204   my @dbsources = ();
205   my ($sth, $query);
206
207   $form->{dbdefault} = $form->{dbuser} unless $form->{dbdefault};
208   &dbconnect_vars($form, $form->{dbdefault});
209
210   my $dbh = SL::DBConnect->connect($form->{dbconnect}, $form->{dbuser}, $form->{dbpasswd}, SL::DBConnect->get_options)
211     or $form->dberror;
212
213   $query =
214     qq|SELECT datname FROM pg_database | .
215     qq|WHERE NOT datname IN ('template0', 'template1')|;
216   $sth = $dbh->prepare($query);
217   $sth->execute() || $form->dberror($query);
218
219   while (my ($db) = $sth->fetchrow_array) {
220
221     if ($form->{only_acc_db}) {
222
223       next if ($db =~ /^template/);
224
225       &dbconnect_vars($form, $db);
226       my $dbh = SL::DBConnect->connect($form->{dbconnect}, $form->{dbuser}, $form->{dbpasswd}, SL::DBConnect->get_options)
227         or $form->dberror;
228
229       $query =
230         qq|SELECT tablename FROM pg_tables | .
231         qq|WHERE (tablename = 'defaults') AND (tableowner = ?)|;
232       my $sth = $dbh->prepare($query);
233       $sth->execute($form->{dbuser}) ||
234         $form->dberror($query . " ($form->{dbuser})");
235
236       if ($sth->fetchrow_array) {
237         push(@dbsources, $db);
238       }
239       $sth->finish;
240       $dbh->disconnect;
241       next;
242     }
243     push(@dbsources, $db);
244   }
245
246   $sth->finish;
247   $dbh->disconnect;
248
249   $main::lxdebug->leave_sub();
250
251   return @dbsources;
252 }
253
254 sub dbcreate {
255   $main::lxdebug->enter_sub();
256
257   my ($self, $form) = @_;
258
259   &dbconnect_vars($form, $form->{dbdefault});
260   my $dbh =
261     SL::DBConnect->connect($form->{dbconnect}, $form->{dbuser}, $form->{dbpasswd}, SL::DBConnect->get_options)
262     or $form->dberror;
263   $form->{db} =~ s/\"//g;
264
265   my @dboptions;
266
267   push @dboptions, "ENCODING = " . $dbh->quote($form->{"encoding"}) if $form->{"encoding"};
268   if ($form->{"dbdefault"}) {
269     my $dbdefault = $form->{"dbdefault"};
270     $dbdefault =~ s/[^a-zA-Z0-9_\-]//g;
271     push @dboptions, "TEMPLATE = $dbdefault";
272   }
273
274   my $query = qq|CREATE DATABASE "$form->{db}"|;
275   $query   .= " WITH " . join(" ", @dboptions) if @dboptions;
276
277   # Ignore errors if the database exists.
278   $dbh->do($query);
279
280   $dbh->disconnect;
281
282   &dbconnect_vars($form, $form->{db});
283
284   # make a shim myconfig so that rose db connections work
285   $::myconfig{$_}     = $form->{$_} for qw(dbhost dbport dbuser dbpasswd);
286   $::myconfig{dbname} = $form->{db};
287
288   $dbh = SL::DBConnect->connect($form->{dbconnect}, $form->{dbuser}, $form->{dbpasswd}, SL::DBConnect->get_options)
289     or $form->dberror;
290
291   my $dbupdater = SL::DBUpgrade2->new(form => $form, return_on_error => 1, silent => 1)->parse_dbupdate_controls;
292   # create the tables
293   $dbupdater->process_query($dbh, "sql/lx-office.sql");
294
295   # load chart of accounts
296   $dbupdater->process_query($dbh, "sql/$form->{chart}-chart.sql");
297
298   $query = qq|UPDATE defaults SET coa = ?, accounting_method = ?, profit_determination = ?, inventory_system = ?, curr = ?|;
299   do_query($form, $dbh, $query, map { $form->{$_} } qw(chart accounting_method profit_determination inventory_system defaultcurrency));
300
301   $dbh->disconnect;
302
303   $main::lxdebug->leave_sub();
304 }
305
306 sub dbdelete {
307   $main::lxdebug->enter_sub();
308
309   my ($self, $form) = @_;
310   $form->{db} =~ s/\"//g;
311
312   &dbconnect_vars($form, $form->{dbdefault});
313   my $dbh = SL::DBConnect->connect($form->{dbconnect}, $form->{dbuser}, $form->{dbpasswd}, SL::DBConnect->get_options)
314     or $form->dberror;
315   my $query = qq|DROP DATABASE "$form->{db}"|;
316   do_query($form, $dbh, $query);
317
318   $dbh->disconnect;
319
320   $main::lxdebug->leave_sub();
321 }
322
323 sub calc_version {
324   $main::lxdebug->enter_sub(2);
325
326   my (@v, $version, $i);
327
328   @v = split(/\./, $_[0]);
329   while (scalar(@v) < 4) {
330     push(@v, 0);
331   }
332   $version = 0;
333   for ($i = 0; $i < 4; $i++) {
334     $version *= 1000;
335     $version += $v[$i];
336   }
337
338   $main::lxdebug->leave_sub(2);
339   return $version;
340 }
341
342 sub cmp_script_version {
343   my ($a_from, $a_to, $b_from, $b_to);
344   my ($i, $res_a, $res_b);
345   my ($my_a, $my_b) = do { no warnings 'once'; ($a, $b) };
346
347   $my_a =~ s/.*-upgrade-//;
348   $my_a =~ s/.sql$//;
349   $my_b =~ s/.*-upgrade-//;
350   $my_b =~ s/.sql$//;
351   my ($my_a_from, $my_a_to) = split(/-/, $my_a);
352   my ($my_b_from, $my_b_to) = split(/-/, $my_b);
353
354   $res_a = calc_version($my_a_from);
355   $res_b = calc_version($my_b_from);
356
357   if ($res_a == $res_b) {
358     $res_a = calc_version($my_a_to);
359     $res_b = calc_version($my_b_to);
360   }
361
362   return $res_a <=> $res_b;
363 }
364
365 sub create_schema_info_table {
366   $main::lxdebug->enter_sub();
367
368   my ($self, $form, $dbh) = @_;
369
370   my $query = "SELECT tag FROM schema_info LIMIT 1";
371   if (!$dbh->do($query)) {
372     $dbh->rollback();
373     $query =
374       qq|CREATE TABLE schema_info (| .
375       qq|  tag text, | .
376       qq|  login text, | .
377       qq|  itime timestamp DEFAULT now(), | .
378       qq|  PRIMARY KEY (tag))|;
379     $dbh->do($query) || $form->dberror($query);
380   }
381
382   $main::lxdebug->leave_sub();
383 }
384
385 sub dbupdate2 {
386   my ($self, %params) = @_;
387
388   my $form            = $params{form};
389   my $dbupdater       = $params{updater};
390   my $db              = $params{database};
391   my $silent          = $params{silent};
392
393   map { $_->{description} = SL::Iconv::convert($_->{charset}, 'UTF-8', $_->{description}) } values %{ $dbupdater->{all_controls} };
394
395   &dbconnect_vars($form, $db);
396
397   # Flush potentially held database locks.
398 #   $form->get_standard_dbh->commit;
399
400   my $dbh = SL::DBConnect->connect($form->{dbconnect}, $form->{dbuser}, $form->{dbpasswd}, SL::DBConnect->get_options) or $form->dberror;
401
402   $dbh->do($form->{dboptions}) if ($form->{dboptions});
403
404   $self->create_schema_info_table($form, $dbh);
405
406   my @upgradescripts = $dbupdater->unapplied_upgrade_scripts($dbh);
407
408   foreach my $control (@upgradescripts) {
409     # Apply upgrade. Control will only return to us if the upgrade has
410     # been applied correctly and if the update has not requested user
411     # interaction.
412     $main::lxdebug->message(LXDebug->DEBUG2(), "Applying Update $control->{file}");
413     print $form->parse_html_template("dbupgrade/upgrade_message2", $control) unless $silent;
414
415     $dbupdater->process_file($dbh, "sql/Pg-upgrade2/$control->{file}", $control);
416   }
417
418   $dbh->disconnect;
419 }
420
421 sub data {
422   +{ %{ $_[0] } }
423 }
424
425 sub get_default_myconfig {
426   my ($self_or_class, %user_config) = @_;
427
428   return (
429     countrycode  => 'de',
430     css_path     => 'css',      # Needed for menunew, see SL::Layout::Base::get_stylesheet_for_user
431     dateformat   => 'dd.mm.yy',
432     numberformat => '1.000,00',
433     stylesheet   => 'kivitendo.css',
434     timeformat   => 'hh:mm',
435     %user_config,
436   );
437 }
438
439 1;