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