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