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