mebil
[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     $::dispatcher->end_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   # $::dispatcher->end_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
316     accounting_method = ?,
317     profit_determination = ?,
318     inventory_system = ?,
319     precision = ?,
320     currency_id = ?,
321     feature_balance = ?,
322     feature_datev = ?,
323     feature_erfolgsrechnung = ?,
324     feature_eurechnung = ?,
325     feature_ustva = ?
326   |;
327   do_query($form, $dbh, $query,
328     $form->{accounting_method},
329     $form->{profit_determination},
330     $form->{inventory_system},
331     $form->parse_amount(\%::myconfig, $form->{precision_as_number}),
332     $curr->{id},
333     $form->{feature_balance},
334     $form->{feature_datev},
335     $form->{feature_erfolgsrechnung},
336     $form->{feature_eurechnung},
337     $form->{feature_ustva}
338   );
339
340   $dbh->disconnect;
341
342   $main::lxdebug->leave_sub();
343 }
344
345 sub dbdelete {
346   $main::lxdebug->enter_sub();
347
348   my ($self, $form) = @_;
349   $form->{db} =~ s/\"//g;
350
351   &dbconnect_vars($form, $form->{dbdefault});
352   my $dbh = SL::DBConnect->connect($form->{dbconnect}, $form->{dbuser}, $form->{dbpasswd}, SL::DBConnect->get_options)
353     or $form->dberror;
354   my $query = qq|DROP DATABASE "$form->{db}"|;
355   do_query($form, $dbh, $query);
356
357   $dbh->disconnect;
358
359   $main::lxdebug->leave_sub();
360 }
361
362 sub calc_version {
363   $main::lxdebug->enter_sub(2);
364
365   my (@v, $version, $i);
366
367   @v = split(/\./, $_[0]);
368   while (scalar(@v) < 4) {
369     push(@v, 0);
370   }
371   $version = 0;
372   for ($i = 0; $i < 4; $i++) {
373     $version *= 1000;
374     $version += $v[$i];
375   }
376
377   $main::lxdebug->leave_sub(2);
378   return $version;
379 }
380
381 sub cmp_script_version {
382   my ($a_from, $a_to, $b_from, $b_to);
383   my ($i, $res_a, $res_b);
384   my ($my_a, $my_b) = do { no warnings 'once'; ($a, $b) };
385
386   $my_a =~ s/.*-upgrade-//;
387   $my_a =~ s/.sql$//;
388   $my_b =~ s/.*-upgrade-//;
389   $my_b =~ s/.sql$//;
390   my ($my_a_from, $my_a_to) = split(/-/, $my_a);
391   my ($my_b_from, $my_b_to) = split(/-/, $my_b);
392
393   $res_a = calc_version($my_a_from);
394   $res_b = calc_version($my_b_from);
395
396   if ($res_a == $res_b) {
397     $res_a = calc_version($my_a_to);
398     $res_b = calc_version($my_b_to);
399   }
400
401   return $res_a <=> $res_b;
402 }
403
404 sub create_schema_info_table {
405   $main::lxdebug->enter_sub();
406
407   my ($self, $form, $dbh) = @_;
408
409   my $query = "SELECT tag FROM schema_info LIMIT 1";
410   if (!$dbh->do($query)) {
411     $dbh->rollback();
412     $query =
413       qq|CREATE TABLE schema_info (| .
414       qq|  tag text, | .
415       qq|  login text, | .
416       qq|  itime timestamp DEFAULT now(), | .
417       qq|  PRIMARY KEY (tag))|;
418     $dbh->do($query) || $form->dberror($query);
419   }
420
421   $main::lxdebug->leave_sub();
422 }
423
424 sub dbupdate2 {
425   my ($self, %params) = @_;
426
427   my $form            = $params{form};
428   my $dbupdater       = $params{updater};
429   my $db              = $params{database};
430   my $silent          = $params{silent};
431
432   map { $_->{description} = SL::Iconv::convert($_->{charset}, 'UTF-8', $_->{description}) } values %{ $dbupdater->{all_controls} };
433
434   &dbconnect_vars($form, $db);
435
436   # Flush potentially held database locks.
437 #   $form->get_standard_dbh->commit;
438
439   my $dbh = SL::DBConnect->connect($form->{dbconnect}, $form->{dbuser}, $form->{dbpasswd}, SL::DBConnect->get_options) or $form->dberror;
440
441   $dbh->do($form->{dboptions}) if ($form->{dboptions});
442
443   $self->create_schema_info_table($form, $dbh);
444
445   my @upgradescripts = $dbupdater->unapplied_upgrade_scripts($dbh);
446
447   foreach my $control (@upgradescripts) {
448     # Apply upgrade. Control will only return to us if the upgrade has
449     # been applied correctly and if the update has not requested user
450     # interaction.
451     $main::lxdebug->message(LXDebug->DEBUG2(), "Applying Update $control->{file}");
452     print $form->parse_html_template("dbupgrade/upgrade_message2", $control) unless $silent;
453
454     $dbupdater->process_file($dbh, "sql/Pg-upgrade2/$control->{file}", $control);
455   }
456
457   $dbh->disconnect;
458 }
459
460 sub data {
461   +{ %{ $_[0] } }
462 }
463
464 sub get_default_myconfig {
465   my ($self_or_class, %user_config) = @_;
466   my $defaults = SL::DefaultManager->new($::lx_office_conf{system}->{default_manager});
467
468   return (
469     countrycode  => $defaults->language('de'),
470     css_path     => 'css',      # Needed for menunew, see SL::Layout::Base::get_stylesheet_for_user
471     dateformat   => $defaults->dateformat('dd.mm.yy'),
472     numberformat => $defaults->numberformat('1.000,00'),
473     stylesheet   => $defaults->stylesheet('kivitendo.css'),
474     timeformat   => $defaults->timeformat('hh:mm'),
475     %user_config,
476   );
477 }
478
479 1;