Unterstützung für andere Datenbankencodings als Unicode/UTF-8 entfernt
[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 $dbupdater = SL::DBUpgrade2->new(form => $form);
262   # create the tables
263   $dbupdater->process_query($dbh, "sql/lx-office.sql");
264
265   # load chart of accounts
266   $dbupdater->process_query($dbh, "sql/$form->{chart}-chart.sql");
267
268   my $query = qq|UPDATE defaults SET coa = ?, accounting_method = ?, profit_determination = ?, inventory_system = ?, curr = ?|;
269   do_query($form, $dbh, $query, map { $form->{$_} } qw(chart accounting_method profit_determination inventory_system defaultcurrency));
270
271   $dbh->disconnect;
272
273   $main::lxdebug->leave_sub();
274 }
275
276 sub dbdelete {
277   $main::lxdebug->enter_sub();
278
279   my ($self, $form) = @_;
280   $form->{db} =~ s/\"//g;
281
282   &dbconnect_vars($form, $form->{dbdefault});
283   my $dbh = SL::DBConnect->connect($form->{dbconnect}, $form->{dbuser}, $form->{dbpasswd}, SL::DBConnect->get_options)
284     or $form->dberror;
285   my $query = qq|DROP DATABASE "$form->{db}"|;
286   do_query($form, $dbh, $query);
287
288   $dbh->disconnect;
289
290   $main::lxdebug->leave_sub();
291 }
292
293 sub dbsources_unused {
294   $main::lxdebug->enter_sub();
295
296   my ($self, $form) = @_;
297
298   my %dbexcl = map  { $_->dbname => 1 }
299                grep { ($_->dbhost eq $form->{dbhost}) && ($_->dbport eq $form->{dbport}) }
300                     @{ SL::DB::Manager::AuthClient->get_all };
301
302   $form->{only_acc_db} = 1;
303
304   $dbexcl{$form->{dbdefault}}             = 1;
305   $dbexcl{$main::auth->{DB_config}->{db}} = 1;
306
307   my @dbunused = grep { !$dbexcl{$_} } dbsources("", $form);
308
309   $main::lxdebug->leave_sub();
310
311   return @dbunused;
312 }
313
314 sub calc_version {
315   $main::lxdebug->enter_sub(2);
316
317   my (@v, $version, $i);
318
319   @v = split(/\./, $_[0]);
320   while (scalar(@v) < 4) {
321     push(@v, 0);
322   }
323   $version = 0;
324   for ($i = 0; $i < 4; $i++) {
325     $version *= 1000;
326     $version += $v[$i];
327   }
328
329   $main::lxdebug->leave_sub(2);
330   return $version;
331 }
332
333 sub cmp_script_version {
334   my ($a_from, $a_to, $b_from, $b_to);
335   my ($i, $res_a, $res_b);
336   my ($my_a, $my_b) = ($a, $b);
337
338   $my_a =~ s/.*-upgrade-//;
339   $my_a =~ s/.sql$//;
340   $my_b =~ s/.*-upgrade-//;
341   $my_b =~ s/.sql$//;
342   my ($my_a_from, $my_a_to) = split(/-/, $my_a);
343   my ($my_b_from, $my_b_to) = split(/-/, $my_b);
344
345   $res_a = calc_version($my_a_from);
346   $res_b = calc_version($my_b_from);
347
348   if ($res_a == $res_b) {
349     $res_a = calc_version($my_a_to);
350     $res_b = calc_version($my_b_to);
351   }
352
353   return $res_a <=> $res_b;
354 }
355
356 sub create_schema_info_table {
357   $main::lxdebug->enter_sub();
358
359   my ($self, $form, $dbh) = @_;
360
361   my $query = "SELECT tag FROM schema_info LIMIT 1";
362   if (!$dbh->do($query)) {
363     $dbh->rollback();
364     $query =
365       qq|CREATE TABLE schema_info (| .
366       qq|  tag text, | .
367       qq|  login text, | .
368       qq|  itime timestamp DEFAULT now(), | .
369       qq|  PRIMARY KEY (tag))|;
370     $dbh->do($query) || $form->dberror($query);
371   }
372
373   $main::lxdebug->leave_sub();
374 }
375
376 sub dbupdate {
377   $main::lxdebug->enter_sub();
378
379   my ($self, $form) = @_;
380
381   local *SQLDIR;
382
383   my @upgradescripts = ();
384   my $query;
385   my $rc = -2;
386
387   if ($form->{dbupdate}) {
388
389     # read update scripts into memory
390     opendir(SQLDIR, "sql/Pg-upgrade")
391       or &error("", "sql/Pg-upgrade : $!");
392     @upgradescripts =
393       sort(cmp_script_version
394            grep(/Pg-upgrade-.*?\.(sql|pl)$/,
395                 readdir(SQLDIR)));
396     closedir(SQLDIR);
397   }
398
399   my $dbupdater = SL::DBUpgrade2->new(form => $form);
400
401   foreach my $db (split(/ /, $form->{dbupdate})) {
402
403     next unless $form->{$db};
404
405     # strip db from dataset
406     $db =~ s/^db//;
407     &dbconnect_vars($form, $db);
408
409     my $dbh = SL::DBConnect->connect($form->{dbconnect}, $form->{dbuser}, $form->{dbpasswd}, SL::DBConnect->get_options)
410       or $form->dberror;
411
412     $dbh->do($form->{dboptions}) if ($form->{dboptions});
413
414     # check version
415     $query = qq|SELECT version FROM defaults|;
416     my ($version) = selectrow_query($form, $dbh, $query);
417
418     next unless $version;
419
420     $version = calc_version($version);
421
422     foreach my $upgradescript (@upgradescripts) {
423       my $a = $upgradescript;
424       $a =~ s/^Pg-upgrade-|\.(sql|pl)$//g;
425
426       my ($mindb, $maxdb) = split /-/, $a;
427       my $str_maxdb = $maxdb;
428       $mindb = calc_version($mindb);
429       $maxdb = calc_version($maxdb);
430
431       next if ($version >= $maxdb);
432
433       # if there is no upgrade script exit
434       last if ($version < $mindb);
435
436       # apply upgrade
437       $main::lxdebug->message(LXDebug->DEBUG2(), "Applying Update $upgradescript");
438       $dbupdater->process_file($dbh, "sql/Pg-upgrade/$upgradescript", $str_maxdb);
439
440       $version = $maxdb;
441
442     }
443
444     $rc = 0;
445     $dbh->disconnect;
446
447   }
448
449   $main::lxdebug->leave_sub();
450
451   return $rc;
452 }
453
454 sub dbupdate2 {
455   $main::lxdebug->enter_sub();
456
457   my ($self, %params) = @_;
458
459   my $form            = $params{form};
460   my $dbupdater       = $params{updater};
461   my $db              = $params{database};
462   my $rc              = -2;
463
464   map { $_->{description} = SL::Iconv::convert($_->{charset}, 'UTF-8', $_->{description}) } values %{ $dbupdater->{all_controls} };
465
466   &dbconnect_vars($form, $db);
467
468   my $dbh = SL::DBConnect->connect($form->{dbconnect}, $form->{dbuser}, $form->{dbpasswd}, SL::DBConnect->get_options) or $form->dberror;
469
470   $dbh->do($form->{dboptions}) if ($form->{dboptions});
471
472   $self->create_schema_info_table($form, $dbh);
473
474   my @upgradescripts = $dbupdater->unapplied_upgrade_scripts($dbh);
475
476   $dbh->disconnect and next if !@upgradescripts;
477
478   foreach my $control (@upgradescripts) {
479     # apply upgrade
480     $main::lxdebug->message(LXDebug->DEBUG2(), "Applying Update $control->{file}");
481     print $form->parse_html_template("dbupgrade/upgrade_message2", $control);
482
483     $dbupdater->process_file($dbh, "sql/Pg-upgrade2/$control->{file}", $control);
484   }
485
486   $rc = 0;
487   $dbh->disconnect;
488
489   $main::lxdebug->leave_sub();
490
491   return $rc;
492 }
493
494 sub data {
495   +{ %{ $_[0] } }
496 }
497
498 1;