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