Alle Vorkommen von dbdriver, sid, Oracle 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::DBConnect;
42 use SL::DBUpgrade2;
43 use SL::DBUtils;
44 use SL::Iconv;
45 use SL::Inifile;
46
47 use strict;
48
49 sub new {
50   $main::lxdebug->enter_sub();
51
52   my ($type, %params) = @_;
53
54   my $self = {};
55
56   if ($params{id} || $params{login}) {
57     my %user_data = $main::auth->read_user(%params);
58     map { $self->{$_} = $user_data{$_} } keys %user_data;
59   }
60
61   $main::lxdebug->leave_sub();
62
63   bless $self, $type;
64 }
65
66 sub country_codes {
67   $main::lxdebug->enter_sub();
68
69   local *DIR;
70
71   my %cc       = ();
72   my @language = ();
73
74   # scan the locale directory and read in the LANGUAGE files
75   opendir(DIR, "locale");
76
77   my @dir = grep(!/(^\.\.?$|\..*)/, readdir(DIR));
78
79   foreach my $dir (@dir) {
80     next unless open(my $fh, '<:encoding(UTF-8)', "locale/$dir/LANGUAGE");
81     @language = <$fh>;
82     close $fh;
83
84     $cc{$dir} = "@language";
85   }
86
87   closedir(DIR);
88
89   $main::lxdebug->leave_sub();
90
91   return %cc;
92 }
93
94 sub login {
95   my ($self, $form) = @_;
96
97   return -3 if !$self->{login} || !$::auth->client;
98
99   my %myconfig = $main::auth->read_user(login => $self->{login});
100
101   # check if database is down
102   my $dbh = $form->dbconnect_noauto;
103
104   # we got a connection, check the version
105   my ($dbversion) = $dbh->selectrow_array(qq|SELECT version FROM defaults|);
106
107   $self->create_employee_entry($form, $dbh, \%myconfig);
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   $form->{$_} = $::auth->client->{$_} for qw(dbname dbhost dbport dbuser dbpasswd);
118   $form->{$_} = $myconfig{$_}         for qw(dateformat);
119
120   dbconnect_vars($form, $form->{dbname});
121
122   my $update_available = $dbupdater->update_available($dbversion) || $dbupdater->update2_available($dbh);
123   $dbh->disconnect;
124
125   return 0 if !$update_available;
126   $form->{"title"} = $main::locale->text("Dataset upgrade");
127   $form->header(no_layout => $form->{no_layout});
128   print $form->parse_html_template("dbupgrade/header");
129
130   $form->{dbupdate} = "db" . $form->{dbname};
131
132   if ($form->{"show_dbupdate_warning"}) {
133     print $form->parse_html_template("dbupgrade/warning");
134     ::end_of_request();
135   }
136
137   # update the tables
138   my $fh;
139   if (!$::lx_office_conf{debug}->{keep_installation_unlocked} && !open($fh, ">", $::lx_office_conf{paths}->{userspath} . "/nologin")) {
140     $form->show_generic_error($main::locale->text('A temporary file could not be created. ' .
141                                                   'Please verify that the directory "#1" is writeable by the webserver.',
142                                                   $::lx_office_conf{paths}->{userspath}),
143                               'back_button' => 1);
144   }
145
146   # ignore HUP, QUIT in case the webserver times out
147   $SIG{HUP}  = 'IGNORE';
148   $SIG{QUIT} = 'IGNORE';
149
150   $self->dbupdate($form);
151   $self->dbupdate2($form, $dbupdater);
152   SL::DBUpgrade2->new(form => $::form, auth => 1)->apply_admin_dbupgrade_scripts(0);
153
154   close($fh);
155
156   # remove lock file
157   unlink($::lx_office_conf{paths}->{userspath} . "/nologin");
158
159   print $form->parse_html_template("dbupgrade/footer");
160
161   return -2;
162 }
163
164 sub dbconnect_vars {
165   $main::lxdebug->enter_sub();
166
167   my ($form, $db) = @_;
168
169   my %dboptions = (
170     'yy-mm-dd'   => 'set DateStyle to \'ISO\'',
171     'yyyy-mm-dd' => 'set DateStyle to \'ISO\'',
172     'mm/dd/yy'   => 'set DateStyle to \'SQL, US\'',
173     'dd/mm/yy'   => 'set DateStyle to \'SQL, EUROPEAN\'',
174     'dd.mm.yy'   => 'set DateStyle to \'GERMAN\''
175   );
176
177   $form->{dboptions} = $dboptions{ $form->{dateformat} };
178   $form->{dbconnect} = "dbi:Pg:dbname=${db};host=" . ($form->{dbhost} || 'localhost') . ";port=" . ($form->{dbport} || 5432);
179
180   $main::lxdebug->leave_sub();
181 }
182
183 sub dbsources {
184   $main::lxdebug->enter_sub();
185
186   my ($self, $form) = @_;
187
188   my @dbsources = ();
189   my ($sth, $query);
190
191   $form->{dbdefault} = $form->{dbuser} unless $form->{dbdefault};
192   &dbconnect_vars($form, $form->{dbdefault});
193
194   my $dbh = SL::DBConnect->connect($form->{dbconnect}, $form->{dbuser}, $form->{dbpasswd}, SL::DBConnect->get_options)
195     or $form->dberror;
196
197   $query =
198     qq|SELECT datname FROM pg_database | .
199     qq|WHERE NOT datname IN ('template0', 'template1')|;
200   $sth = $dbh->prepare($query);
201   $sth->execute() || $form->dberror($query);
202
203   while (my ($db) = $sth->fetchrow_array) {
204
205     if ($form->{only_acc_db}) {
206
207       next if ($db =~ /^template/);
208
209       &dbconnect_vars($form, $db);
210       my $dbh = SL::DBConnect->connect($form->{dbconnect}, $form->{dbuser}, $form->{dbpasswd}, SL::DBConnect->get_options)
211         or $form->dberror;
212
213       $query =
214         qq|SELECT tablename FROM pg_tables | .
215         qq|WHERE (tablename = 'defaults') AND (tableowner = ?)|;
216       my $sth = $dbh->prepare($query);
217       $sth->execute($form->{dbuser}) ||
218         $form->dberror($query . " ($form->{dbuser})");
219
220       if ($sth->fetchrow_array) {
221         push(@dbsources, $db);
222       }
223       $sth->finish;
224       $dbh->disconnect;
225       next;
226     }
227     push(@dbsources, $db);
228   }
229
230   $sth->finish;
231   $dbh->disconnect;
232
233   $main::lxdebug->leave_sub();
234
235   return @dbsources;
236 }
237
238 sub dbclusterencoding {
239   $main::lxdebug->enter_sub();
240
241   my ($self, $form) = @_;
242
243   $form->{dbdefault} ||= $form->{dbuser};
244
245   dbconnect_vars($form, $form->{dbdefault});
246
247   my $dbh                = SL::DBConnect->connect($form->{dbconnect}, $form->{dbuser}, $form->{dbpasswd}, SL::DBConnect->get_options) || $form->dberror();
248   my $query              = qq|SELECT pg_encoding_to_char(encoding) FROM pg_database WHERE datname = 'template0'|;
249   my ($cluster_encoding) = $dbh->selectrow_array($query);
250   $dbh->disconnect();
251
252   $main::lxdebug->leave_sub();
253
254   return $cluster_encoding;
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   $dbh = SL::DBConnect->connect($form->{dbconnect}, $form->{dbuser}, $form->{dbpasswd}, SL::DBConnect->get_options)
288     or $form->dberror;
289
290   my $db_charset = $Common::db_encoding_to_charset{$form->{encoding}};
291   $db_charset ||= Common::DEFAULT_CHARSET;
292
293   my $dbupdater = SL::DBUpgrade2->new(form => $form);
294   # create the tables
295   $dbupdater->process_query($dbh, "sql/lx-office.sql", undef, $db_charset);
296
297   # load chart of accounts
298   $dbupdater->process_query($dbh, "sql/$form->{chart}-chart.sql", undef, $db_charset);
299
300   $query = "UPDATE defaults SET coa = ?";
301   do_query($form, $dbh, $query, $form->{chart});
302   $query = "UPDATE defaults SET accounting_method = ?";
303   do_query($form, $dbh, $query, $form->{accounting_method});
304   $query = "UPDATE defaults SET profit_determination = ?";
305   do_query($form, $dbh, $query, $form->{profit_determination});
306   $query = "UPDATE defaults SET inventory_system = ?";
307   do_query($form, $dbh, $query, $form->{inventory_system});
308   $query = "UPDATE defaults SET curr = ?";
309   do_query($form, $dbh, $query, $form->{defaultcurrency});
310
311   $dbh->disconnect;
312
313   $main::lxdebug->leave_sub();
314 }
315
316 sub dbdelete {
317   $main::lxdebug->enter_sub();
318
319   my ($self, $form) = @_;
320   $form->{db} =~ s/\"//g;
321
322   &dbconnect_vars($form, $form->{dbdefault});
323   my $dbh = SL::DBConnect->connect($form->{dbconnect}, $form->{dbuser}, $form->{dbpasswd}, SL::DBConnect->get_options)
324     or $form->dberror;
325   my $query = qq|DROP DATABASE "$form->{db}"|;
326   do_query($form, $dbh, $query);
327
328   $dbh->disconnect;
329
330   $main::lxdebug->leave_sub();
331 }
332
333 sub dbsources_unused {
334   $main::lxdebug->enter_sub();
335
336   my ($self, $form) = @_;
337
338   $form->{only_acc_db} = 1;
339
340   my %members = $main::auth->read_all_users();
341   my %dbexcl  = map { $_ => 1 } grep { $_ } map { $_->{dbname} } values %members;
342
343   $dbexcl{$form->{dbdefault}}             = 1;
344   $dbexcl{$main::auth->{DB_config}->{db}} = 1;
345
346   my @dbunused = grep { !$dbexcl{$_} } dbsources("", $form);
347
348   $main::lxdebug->leave_sub();
349
350   return @dbunused;
351 }
352
353 sub dbneedsupdate {
354   $main::lxdebug->enter_sub();
355
356   my ($self, $form) = @_;
357
358   my %members   = $main::auth->read_all_users();
359   my $dbupdater = SL::DBUpgrade2->new(form => $form)->parse_dbupdate_controls;
360
361   my ($query, $sth, %dbs_needing_updates);
362
363   foreach my $login (grep /[a-z]/, keys %members) {
364     my $member = $members{$login};
365
366     map { $form->{$_} = $member->{$_} } qw(dbname dbuser dbpasswd dbhost dbport);
367     dbconnect_vars($form, $form->{dbname});
368
369     my $dbh = SL::DBConnect->connect($form->{dbconnect}, $form->{dbuser}, $form->{dbpasswd}, SL::DBConnect->get_options);
370
371     next unless $dbh;
372
373     my $version;
374
375     $query = qq|SELECT version FROM defaults|;
376     $sth = prepare_query($form, $dbh, $query);
377     if ($sth->execute()) {
378       ($version) = $sth->fetchrow_array();
379     }
380     $sth->finish();
381
382     $dbh->disconnect and next unless $version;
383
384     my $update_available = $dbupdater->update_available($version) || $dbupdater->update2_available($dbh);
385     $dbh->disconnect;
386
387    if ($update_available) {
388       my $dbinfo = {};
389       map { $dbinfo->{$_} = $member->{$_} } grep /^db/, keys %{ $member };
390       $dbs_needing_updates{$member->{dbhost} . "::" . $member->{dbname}} = $dbinfo;
391     }
392   }
393
394   $main::lxdebug->leave_sub();
395
396   return values %dbs_needing_updates;
397 }
398
399 sub calc_version {
400   $main::lxdebug->enter_sub(2);
401
402   my (@v, $version, $i);
403
404   @v = split(/\./, $_[0]);
405   while (scalar(@v) < 4) {
406     push(@v, 0);
407   }
408   $version = 0;
409   for ($i = 0; $i < 4; $i++) {
410     $version *= 1000;
411     $version += $v[$i];
412   }
413
414   $main::lxdebug->leave_sub(2);
415   return $version;
416 }
417
418 sub cmp_script_version {
419   my ($a_from, $a_to, $b_from, $b_to);
420   my ($i, $res_a, $res_b);
421   my ($my_a, $my_b) = ($a, $b);
422
423   $my_a =~ s/.*-upgrade-//;
424   $my_a =~ s/.sql$//;
425   $my_b =~ s/.*-upgrade-//;
426   $my_b =~ s/.sql$//;
427   my ($my_a_from, $my_a_to) = split(/-/, $my_a);
428   my ($my_b_from, $my_b_to) = split(/-/, $my_b);
429
430   $res_a = calc_version($my_a_from);
431   $res_b = calc_version($my_b_from);
432
433   if ($res_a == $res_b) {
434     $res_a = calc_version($my_a_to);
435     $res_b = calc_version($my_b_to);
436   }
437
438   return $res_a <=> $res_b;
439 }
440
441 sub create_schema_info_table {
442   $main::lxdebug->enter_sub();
443
444   my ($self, $form, $dbh) = @_;
445
446   my $query = "SELECT tag FROM schema_info LIMIT 1";
447   if (!$dbh->do($query)) {
448     $dbh->rollback();
449     $query =
450       qq|CREATE TABLE schema_info (| .
451       qq|  tag text, | .
452       qq|  login text, | .
453       qq|  itime timestamp DEFAULT now(), | .
454       qq|  PRIMARY KEY (tag))|;
455     $dbh->do($query) || $form->dberror($query);
456   }
457
458   $main::lxdebug->leave_sub();
459 }
460
461 sub dbupdate {
462   $main::lxdebug->enter_sub();
463
464   my ($self, $form) = @_;
465
466   local *SQLDIR;
467
468   my @upgradescripts = ();
469   my $query;
470   my $rc = -2;
471
472   if ($form->{dbupdate}) {
473
474     # read update scripts into memory
475     opendir(SQLDIR, "sql/Pg-upgrade")
476       or &error("", "sql/Pg-upgrade : $!");
477     @upgradescripts =
478       sort(cmp_script_version
479            grep(/Pg-upgrade-.*?\.(sql|pl)$/,
480                 readdir(SQLDIR)));
481     closedir(SQLDIR);
482   }
483
484   my $db_charset = $::lx_office_conf{system}->{dbcharset};
485   $db_charset ||= Common::DEFAULT_CHARSET;
486
487   my $dbupdater = SL::DBUpgrade2->new(form => $form);
488
489   foreach my $db (split(/ /, $form->{dbupdate})) {
490
491     next unless $form->{$db};
492
493     # strip db from dataset
494     $db =~ s/^db//;
495     &dbconnect_vars($form, $db);
496
497     my $dbh = SL::DBConnect->connect($form->{dbconnect}, $form->{dbuser}, $form->{dbpasswd}, SL::DBConnect->get_options)
498       or $form->dberror;
499
500     $dbh->do($form->{dboptions}) if ($form->{dboptions});
501
502     # check version
503     $query = qq|SELECT version FROM defaults|;
504     my ($version) = selectrow_query($form, $dbh, $query);
505
506     next unless $version;
507
508     $version = calc_version($version);
509
510     foreach my $upgradescript (@upgradescripts) {
511       my $a = $upgradescript;
512       $a =~ s/^Pg-upgrade-|\.(sql|pl)$//g;
513
514       my ($mindb, $maxdb) = split /-/, $a;
515       my $str_maxdb = $maxdb;
516       $mindb = calc_version($mindb);
517       $maxdb = calc_version($maxdb);
518
519       next if ($version >= $maxdb);
520
521       # if there is no upgrade script exit
522       last if ($version < $mindb);
523
524       # apply upgrade
525       $main::lxdebug->message(LXDebug->DEBUG2(), "Applying Update $upgradescript");
526       $dbupdater->process_file($dbh, "sql/Pg-upgrade/$upgradescript", $str_maxdb, $db_charset);
527
528       $version = $maxdb;
529
530     }
531
532     $rc = 0;
533     $dbh->disconnect;
534
535   }
536
537   $main::lxdebug->leave_sub();
538
539   return $rc;
540 }
541
542 sub dbupdate2 {
543   $main::lxdebug->enter_sub();
544
545   my ($self, $form, $dbupdater) = @_;
546
547   my $rc         = -2;
548   my $db_charset = $::lx_office_conf{system}->{dbcharset} || Common::DEFAULT_CHARSET;
549
550   map { $_->{description} = SL::Iconv::convert($_->{charset}, $db_charset, $_->{description}) } values %{ $dbupdater->{all_controls} };
551
552   foreach my $db (split / /, $form->{dbupdate}) {
553     next unless $form->{$db};
554
555     # strip db from dataset
556     $db =~ s/^db//;
557     &dbconnect_vars($form, $db);
558
559     my $dbh = SL::DBConnect->connect($form->{dbconnect}, $form->{dbuser}, $form->{dbpasswd}, SL::DBConnect->get_options) or $form->dberror;
560
561     $dbh->do($form->{dboptions}) if ($form->{dboptions});
562
563     $self->create_schema_info_table($form, $dbh);
564
565     my @upgradescripts = $dbupdater->unapplied_upgrade_scripts($dbh);
566
567     $dbh->disconnect and next if !@upgradescripts;
568
569     foreach my $control (@upgradescripts) {
570       # apply upgrade
571       $main::lxdebug->message(LXDebug->DEBUG2(), "Applying Update $control->{file}");
572       print $form->parse_html_template("dbupgrade/upgrade_message2", $control);
573
574       $dbupdater->process_file($dbh, "sql/Pg-upgrade2/$control->{file}", $control, $db_charset);
575     }
576
577     $rc = 0;
578     $dbh->disconnect;
579
580   }
581
582   $main::lxdebug->leave_sub();
583
584   return $rc;
585 }
586
587 sub save_member {
588   $main::lxdebug->enter_sub();
589
590   my ($self) = @_;
591
592   # format dbconnect and dboptions string
593   dbconnect_vars($self, $self->{dbname});
594
595   map { $self->{$_} =~ s/\r//g; } qw(address signature);
596
597   $main::auth->save_user($self->{login}, map { $_, $self->{$_} } config_vars());
598
599   my $dbh = SL::DBConnect->connect($self->{dbconnect}, $self->{dbuser}, $self->{dbpasswd}, SL::DBConnect->get_options);
600   if ($dbh) {
601     $self->create_employee_entry($::form, $dbh, $self, 1);
602     $dbh->disconnect();
603   }
604
605   $main::lxdebug->leave_sub();
606 }
607
608 sub create_employee_entry {
609   $main::lxdebug->enter_sub();
610
611   my $self            = shift;
612   my $form            = shift;
613   my $dbh             = shift;
614   my $myconfig        = shift;
615   my $update_existing = shift;
616
617   if (!does_table_exist($dbh, 'employee')) {
618     $main::lxdebug->leave_sub();
619     return;
620   }
621
622   # add login to employee table if it does not exist
623   # no error check for employee table, ignore if it does not exist
624   my ($id)         = selectrow_query($form, $dbh, qq|SELECT id FROM employee WHERE login = ?|, $self->{login});
625   my ($good_db)    = selectrow_query($form, $dbh, qq|select * from pg_tables where tablename = ? and schemaname = ?|, 'schema_info', 'public');
626   my  $can_delete;
627      ($can_delete) = selectrow_query($form, $dbh, qq|SELECT tag FROM schema_info WHERE tag = ?|, 'employee_deleted') if $good_db;
628
629   if (!$id) {
630     my $query = qq|INSERT INTO employee (login, name, workphone, role) VALUES (?, ?, ?, ?)|;
631     do_query($form, $dbh, $query, ($self->{login}, $myconfig->{name}, $myconfig->{tel}, "user"));
632
633   } elsif ($update_existing && $can_delete) {
634     my $query = qq|UPDATE employee SET name = ?, workphone = ?, role = 'user', deleted = 'f' WHERE id = ?|;
635     do_query($form, $dbh, $query, $myconfig->{name}, $myconfig->{tel}, $id);
636   }
637
638   $main::lxdebug->leave_sub();
639 }
640
641 sub config_vars {
642   $main::lxdebug->enter_sub();
643
644   my @conf = qw(copies countrycode dateformat default_media default_printer_id email favorites fax hide_cvar_search_options mandatory_departments menustyle name
645                 numberformat show_form_details signature stylesheet taxincluded_checked tel template_format vclimit);
646
647   $main::lxdebug->leave_sub();
648
649   return @conf;
650 }
651
652 sub data {
653   +{ %{ $_[0] } }
654 }
655
656 1;