Datenbankverwaltung in neuen Admin-Controller verschoben
[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::DBConnect;
43 use SL::DBUpgrade2;
44 use SL::DBUtils;
45 use SL::Iconv;
46 use SL::Inifile;
47 use SL::System::InstallationLock;
48
49 use strict;
50
51 sub new {
52   $main::lxdebug->enter_sub();
53
54   my ($type, %params) = @_;
55
56   my $self = {};
57
58   if ($params{id} || $params{login}) {
59     my %user_data = $main::auth->read_user(%params);
60     map { $self->{$_} = $user_data{$_} } keys %user_data;
61   }
62
63   $main::lxdebug->leave_sub();
64
65   bless $self, $type;
66 }
67
68 sub country_codes {
69   $main::lxdebug->enter_sub();
70
71   local *DIR;
72
73   my %cc       = ();
74   my @language = ();
75
76   # scan the locale directory and read in the LANGUAGE files
77   opendir(DIR, "locale");
78
79   my @dir = grep(!/(^\.\.?$|\..*)/, readdir(DIR));
80
81   foreach my $dir (@dir) {
82     next unless open(my $fh, '<:encoding(UTF-8)', "locale/$dir/LANGUAGE");
83     @language = <$fh>;
84     close $fh;
85
86     $cc{$dir} = "@language";
87   }
88
89   closedir(DIR);
90
91   $main::lxdebug->leave_sub();
92
93   return %cc;
94 }
95
96 sub login {
97   my ($self, $form) = @_;
98
99   return -3 if !$self->{login} || !$::auth->client;
100
101   my %myconfig = $main::auth->read_user(login => $self->{login});
102
103   # check if database is down
104   my $dbh = $form->dbconnect_noauto;
105
106   # we got a connection, check the version
107   my ($dbversion) = $dbh->selectrow_array(qq|SELECT version FROM defaults|);
108
109   $self->create_schema_info_table($form, $dbh);
110
111   # Auth DB upgrades available?
112   my $dbupdater_auth = SL::DBUpgrade2->new(form => $form, auth => 1)->parse_dbupdate_controls;
113   return -3 if $dbupdater_auth->unapplied_upgrade_scripts($::auth->dbconnect);
114
115   my $dbupdater = SL::DBUpgrade2->new(form => $form)->parse_dbupdate_controls;
116
117   my $update_available = $dbupdater->update_available($dbversion) || $dbupdater->update2_available($dbh);
118   $dbh->disconnect;
119
120   return 0 if !$update_available;
121
122   $form->{$_} = $::auth->client->{$_} for qw(dbname dbhost dbport dbuser dbpasswd);
123   $form->{$_} = $myconfig{$_}         for qw(datestyle);
124
125   $form->{"title"} = $main::locale->text("Dataset upgrade");
126   $form->header(no_layout => $form->{no_layout});
127   print $form->parse_html_template("dbupgrade/header");
128
129   $form->{dbupdate} = "db" . $::auth->client->{dbname};
130
131   if ($form->{"show_dbupdate_warning"}) {
132     print $form->parse_html_template("dbupgrade/warning");
133     ::end_of_request();
134   }
135
136   # update the tables
137   SL::System::InstallationLock->lock;
138
139   # ignore HUP, QUIT in case the webserver times out
140   $SIG{HUP}  = 'IGNORE';
141   $SIG{QUIT} = 'IGNORE';
142
143   $self->dbupdate($form);
144   $self->dbupdate2(form => $form, updater => $dbupdater, database => $::auth->client->{dbname});
145   SL::DBUpgrade2->new(form => $::form, auth => 1)->apply_admin_dbupgrade_scripts(0);
146
147   SL::System::InstallationLock->unlock;
148
149   print $form->parse_html_template("dbupgrade/footer");
150
151   return -2;
152 }
153
154 sub dbconnect_vars {
155   $main::lxdebug->enter_sub();
156
157   my ($form, $db) = @_;
158
159   my %dboptions = (
160     'yy-mm-dd'   => 'set DateStyle to \'ISO\'',
161     'yyyy-mm-dd' => 'set DateStyle to \'ISO\'',
162     'mm/dd/yy'   => 'set DateStyle to \'SQL, US\'',
163     'dd/mm/yy'   => 'set DateStyle to \'SQL, EUROPEAN\'',
164     'dd.mm.yy'   => 'set DateStyle to \'GERMAN\''
165   );
166
167   $form->{dboptions} = $dboptions{ $form->{dateformat} };
168   $form->{dbconnect} = "dbi:Pg:dbname=${db};host=" . ($form->{dbhost} || 'localhost') . ";port=" . ($form->{dbport} || 5432);
169
170   $main::lxdebug->leave_sub();
171 }
172
173 sub dbsources {
174   $main::lxdebug->enter_sub();
175
176   my ($self, $form) = @_;
177
178   my @dbsources = ();
179   my ($sth, $query);
180
181   $form->{dbdefault} = $form->{dbuser} unless $form->{dbdefault};
182   &dbconnect_vars($form, $form->{dbdefault});
183
184   my $dbh = SL::DBConnect->connect($form->{dbconnect}, $form->{dbuser}, $form->{dbpasswd}, SL::DBConnect->get_options)
185     or $form->dberror;
186
187   $query =
188     qq|SELECT datname FROM pg_database | .
189     qq|WHERE NOT datname IN ('template0', 'template1')|;
190   $sth = $dbh->prepare($query);
191   $sth->execute() || $form->dberror($query);
192
193   while (my ($db) = $sth->fetchrow_array) {
194
195     if ($form->{only_acc_db}) {
196
197       next if ($db =~ /^template/);
198
199       &dbconnect_vars($form, $db);
200       my $dbh = SL::DBConnect->connect($form->{dbconnect}, $form->{dbuser}, $form->{dbpasswd}, SL::DBConnect->get_options)
201         or $form->dberror;
202
203       $query =
204         qq|SELECT tablename FROM pg_tables | .
205         qq|WHERE (tablename = 'defaults') AND (tableowner = ?)|;
206       my $sth = $dbh->prepare($query);
207       $sth->execute($form->{dbuser}) ||
208         $form->dberror($query . " ($form->{dbuser})");
209
210       if ($sth->fetchrow_array) {
211         push(@dbsources, $db);
212       }
213       $sth->finish;
214       $dbh->disconnect;
215       next;
216     }
217     push(@dbsources, $db);
218   }
219
220   $sth->finish;
221   $dbh->disconnect;
222
223   $main::lxdebug->leave_sub();
224
225   return @dbsources;
226 }
227
228 sub dbcreate {
229   $main::lxdebug->enter_sub();
230
231   my ($self, $form) = @_;
232
233   &dbconnect_vars($form, $form->{dbdefault});
234   my $dbh =
235     SL::DBConnect->connect($form->{dbconnect}, $form->{dbuser}, $form->{dbpasswd}, SL::DBConnect->get_options)
236     or $form->dberror;
237   $form->{db} =~ s/\"//g;
238
239   my @dboptions;
240
241   push @dboptions, "ENCODING = " . $dbh->quote($form->{"encoding"}) if $form->{"encoding"};
242   if ($form->{"dbdefault"}) {
243     my $dbdefault = $form->{"dbdefault"};
244     $dbdefault =~ s/[^a-zA-Z0-9_\-]//g;
245     push @dboptions, "TEMPLATE = $dbdefault";
246   }
247
248   my $query = qq|CREATE DATABASE "$form->{db}"|;
249   $query   .= " WITH " . join(" ", @dboptions) if @dboptions;
250
251   # Ignore errors if the database exists.
252   $dbh->do($query);
253
254   $dbh->disconnect;
255
256   &dbconnect_vars($form, $form->{db});
257
258   $dbh = SL::DBConnect->connect($form->{dbconnect}, $form->{dbuser}, $form->{dbpasswd}, SL::DBConnect->get_options)
259     or $form->dberror;
260
261   my $db_charset = $Common::db_encoding_to_charset{$form->{encoding}};
262   $db_charset ||= Common::DEFAULT_CHARSET;
263
264   my $dbupdater = SL::DBUpgrade2->new(form => $form);
265   # create the tables
266   $dbupdater->process_query($dbh, "sql/lx-office.sql", undef, $db_charset);
267
268   # load chart of accounts
269   $dbupdater->process_query($dbh, "sql/$form->{chart}-chart.sql", undef, $db_charset);
270
271   my $query = qq|UPDATE defaults SET coa = ?, accounting_method = ?, profit_determination = ?, inventory_system = ?, curr = ?|;
272   do_query($form, $dbh, $query, map { $form->{$_} } qw(chart accounting_method profit_determination inventory_system defaultcurrency));
273
274   $dbh->disconnect;
275
276   $main::lxdebug->leave_sub();
277 }
278
279 sub dbdelete {
280   $main::lxdebug->enter_sub();
281
282   my ($self, $form) = @_;
283   $form->{db} =~ s/\"//g;
284
285   &dbconnect_vars($form, $form->{dbdefault});
286   my $dbh = SL::DBConnect->connect($form->{dbconnect}, $form->{dbuser}, $form->{dbpasswd}, SL::DBConnect->get_options)
287     or $form->dberror;
288   my $query = qq|DROP DATABASE "$form->{db}"|;
289   do_query($form, $dbh, $query);
290
291   $dbh->disconnect;
292
293   $main::lxdebug->leave_sub();
294 }
295
296 sub dbsources_unused {
297   $main::lxdebug->enter_sub();
298
299   my ($self, $form) = @_;
300
301   my %dbexcl = map  { $_->dbname => 1 }
302                grep { ($_->dbhost eq $form->{dbhost}) && ($_->dbport eq $form->{dbport}) }
303                     @{ SL::DB::Manager::AuthClient->get_all };
304
305   $form->{only_acc_db} = 1;
306
307   $dbexcl{$form->{dbdefault}}             = 1;
308   $dbexcl{$main::auth->{DB_config}->{db}} = 1;
309
310   my @dbunused = grep { !$dbexcl{$_} } dbsources("", $form);
311
312   $main::lxdebug->leave_sub();
313
314   return @dbunused;
315 }
316
317 sub calc_version {
318   $main::lxdebug->enter_sub(2);
319
320   my (@v, $version, $i);
321
322   @v = split(/\./, $_[0]);
323   while (scalar(@v) < 4) {
324     push(@v, 0);
325   }
326   $version = 0;
327   for ($i = 0; $i < 4; $i++) {
328     $version *= 1000;
329     $version += $v[$i];
330   }
331
332   $main::lxdebug->leave_sub(2);
333   return $version;
334 }
335
336 sub cmp_script_version {
337   my ($a_from, $a_to, $b_from, $b_to);
338   my ($i, $res_a, $res_b);
339   my ($my_a, $my_b) = ($a, $b);
340
341   $my_a =~ s/.*-upgrade-//;
342   $my_a =~ s/.sql$//;
343   $my_b =~ s/.*-upgrade-//;
344   $my_b =~ s/.sql$//;
345   my ($my_a_from, $my_a_to) = split(/-/, $my_a);
346   my ($my_b_from, $my_b_to) = split(/-/, $my_b);
347
348   $res_a = calc_version($my_a_from);
349   $res_b = calc_version($my_b_from);
350
351   if ($res_a == $res_b) {
352     $res_a = calc_version($my_a_to);
353     $res_b = calc_version($my_b_to);
354   }
355
356   return $res_a <=> $res_b;
357 }
358
359 sub create_schema_info_table {
360   $main::lxdebug->enter_sub();
361
362   my ($self, $form, $dbh) = @_;
363
364   my $query = "SELECT tag FROM schema_info LIMIT 1";
365   if (!$dbh->do($query)) {
366     $dbh->rollback();
367     $query =
368       qq|CREATE TABLE schema_info (| .
369       qq|  tag text, | .
370       qq|  login text, | .
371       qq|  itime timestamp DEFAULT now(), | .
372       qq|  PRIMARY KEY (tag))|;
373     $dbh->do($query) || $form->dberror($query);
374   }
375
376   $main::lxdebug->leave_sub();
377 }
378
379 sub dbupdate {
380   $main::lxdebug->enter_sub();
381
382   my ($self, $form) = @_;
383
384   local *SQLDIR;
385
386   my @upgradescripts = ();
387   my $query;
388   my $rc = -2;
389
390   if ($form->{dbupdate}) {
391
392     # read update scripts into memory
393     opendir(SQLDIR, "sql/Pg-upgrade")
394       or &error("", "sql/Pg-upgrade : $!");
395     @upgradescripts =
396       sort(cmp_script_version
397            grep(/Pg-upgrade-.*?\.(sql|pl)$/,
398                 readdir(SQLDIR)));
399     closedir(SQLDIR);
400   }
401
402   my $db_charset = $::lx_office_conf{system}->{dbcharset};
403   $db_charset ||= Common::DEFAULT_CHARSET;
404
405   my $dbupdater = SL::DBUpgrade2->new(form => $form);
406
407   foreach my $db (split(/ /, $form->{dbupdate})) {
408
409     next unless $form->{$db};
410
411     # strip db from dataset
412     $db =~ s/^db//;
413     &dbconnect_vars($form, $db);
414
415     my $dbh = SL::DBConnect->connect($form->{dbconnect}, $form->{dbuser}, $form->{dbpasswd}, SL::DBConnect->get_options)
416       or $form->dberror;
417
418     $dbh->do($form->{dboptions}) if ($form->{dboptions});
419
420     # check version
421     $query = qq|SELECT version FROM defaults|;
422     my ($version) = selectrow_query($form, $dbh, $query);
423
424     next unless $version;
425
426     $version = calc_version($version);
427
428     foreach my $upgradescript (@upgradescripts) {
429       my $a = $upgradescript;
430       $a =~ s/^Pg-upgrade-|\.(sql|pl)$//g;
431
432       my ($mindb, $maxdb) = split /-/, $a;
433       my $str_maxdb = $maxdb;
434       $mindb = calc_version($mindb);
435       $maxdb = calc_version($maxdb);
436
437       next if ($version >= $maxdb);
438
439       # if there is no upgrade script exit
440       last if ($version < $mindb);
441
442       # apply upgrade
443       $main::lxdebug->message(LXDebug->DEBUG2(), "Applying Update $upgradescript");
444       $dbupdater->process_file($dbh, "sql/Pg-upgrade/$upgradescript", $str_maxdb, $db_charset);
445
446       $version = $maxdb;
447
448     }
449
450     $rc = 0;
451     $dbh->disconnect;
452
453   }
454
455   $main::lxdebug->leave_sub();
456
457   return $rc;
458 }
459
460 sub dbupdate2 {
461   $main::lxdebug->enter_sub();
462
463   my ($self, %params) = @_;
464
465   my $form            = $params{form};
466   my $dbupdater       = $params{updater};
467   my $db              = $params{database};
468   my $rc              = -2;
469   my $db_charset      = $::lx_office_conf{system}->{dbcharset} || Common::DEFAULT_CHARSET;
470
471   map { $_->{description} = SL::Iconv::convert($_->{charset}, $db_charset, $_->{description}) } values %{ $dbupdater->{all_controls} };
472
473   &dbconnect_vars($form, $db);
474
475   my $dbh = SL::DBConnect->connect($form->{dbconnect}, $form->{dbuser}, $form->{dbpasswd}, SL::DBConnect->get_options) or $form->dberror;
476
477   $dbh->do($form->{dboptions}) if ($form->{dboptions});
478
479   $self->create_schema_info_table($form, $dbh);
480
481   my @upgradescripts = $dbupdater->unapplied_upgrade_scripts($dbh);
482
483   $dbh->disconnect and next if !@upgradescripts;
484
485   foreach my $control (@upgradescripts) {
486     # apply upgrade
487     $main::lxdebug->message(LXDebug->DEBUG2(), "Applying Update $control->{file}");
488     print $form->parse_html_template("dbupgrade/upgrade_message2", $control);
489
490     $dbupdater->process_file($dbh, "sql/Pg-upgrade2/$control->{file}", $control, $db_charset);
491   }
492
493   $rc = 0;
494   $dbh->disconnect;
495
496   $main::lxdebug->leave_sub();
497
498   return $rc;
499 }
500
501 sub data {
502   +{ %{ $_[0] } }
503 }
504
505 1;