Nicht benutzte Spalte employee.role entfernen
[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_employee_entry($form, $dbh, \%myconfig);
109
110   $self->create_schema_info_table($form, $dbh);
111
112   # Auth DB upgrades available?
113   my $dbupdater_auth = SL::DBUpgrade2->new(form => $form, auth => 1)->parse_dbupdate_controls;
114   return -3 if $dbupdater_auth->unapplied_upgrade_scripts($::auth->dbconnect);
115
116   my $dbupdater = SL::DBUpgrade2->new(form => $form)->parse_dbupdate_controls;
117
118   my $update_available = $dbupdater->update_available($dbversion) || $dbupdater->update2_available($dbh);
119   $dbh->disconnect;
120
121   return 0 if !$update_available;
122
123   $form->{$_} = $::auth->client->{$_} for qw(dbname dbhost dbport dbuser dbpasswd);
124   $form->{$_} = $myconfig{$_}         for qw(datestyle);
125
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" . $::auth->client->{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   SL::System::InstallationLock->lock;
139
140   # ignore HUP, QUIT in case the webserver times out
141   $SIG{HUP}  = 'IGNORE';
142   $SIG{QUIT} = 'IGNORE';
143
144   $self->dbupdate($form);
145   $self->dbupdate2(form => $form, updater => $dbupdater, database => $::auth->client->{dbname});
146   SL::DBUpgrade2->new(form => $::form, auth => 1)->apply_admin_dbupgrade_scripts(0);
147
148   SL::System::InstallationLock->unlock;
149
150   print $form->parse_html_template("dbupgrade/footer");
151
152   return -2;
153 }
154
155 sub dbconnect_vars {
156   $main::lxdebug->enter_sub();
157
158   my ($form, $db) = @_;
159
160   my %dboptions = (
161     'yy-mm-dd'   => 'set DateStyle to \'ISO\'',
162     'yyyy-mm-dd' => 'set DateStyle to \'ISO\'',
163     'mm/dd/yy'   => 'set DateStyle to \'SQL, US\'',
164     'dd/mm/yy'   => 'set DateStyle to \'SQL, EUROPEAN\'',
165     'dd.mm.yy'   => 'set DateStyle to \'GERMAN\''
166   );
167
168   $form->{dboptions} = $dboptions{ $form->{dateformat} };
169   $form->{dbconnect} = "dbi:Pg:dbname=${db};host=" . ($form->{dbhost} || 'localhost') . ";port=" . ($form->{dbport} || 5432);
170
171   $main::lxdebug->leave_sub();
172 }
173
174 sub dbsources {
175   $main::lxdebug->enter_sub();
176
177   my ($self, $form) = @_;
178
179   my @dbsources = ();
180   my ($sth, $query);
181
182   $form->{dbdefault} = $form->{dbuser} unless $form->{dbdefault};
183   &dbconnect_vars($form, $form->{dbdefault});
184
185   my $dbh = SL::DBConnect->connect($form->{dbconnect}, $form->{dbuser}, $form->{dbpasswd}, SL::DBConnect->get_options)
186     or $form->dberror;
187
188   $query =
189     qq|SELECT datname FROM pg_database | .
190     qq|WHERE NOT datname IN ('template0', 'template1')|;
191   $sth = $dbh->prepare($query);
192   $sth->execute() || $form->dberror($query);
193
194   while (my ($db) = $sth->fetchrow_array) {
195
196     if ($form->{only_acc_db}) {
197
198       next if ($db =~ /^template/);
199
200       &dbconnect_vars($form, $db);
201       my $dbh = SL::DBConnect->connect($form->{dbconnect}, $form->{dbuser}, $form->{dbpasswd}, SL::DBConnect->get_options)
202         or $form->dberror;
203
204       $query =
205         qq|SELECT tablename FROM pg_tables | .
206         qq|WHERE (tablename = 'defaults') AND (tableowner = ?)|;
207       my $sth = $dbh->prepare($query);
208       $sth->execute($form->{dbuser}) ||
209         $form->dberror($query . " ($form->{dbuser})");
210
211       if ($sth->fetchrow_array) {
212         push(@dbsources, $db);
213       }
214       $sth->finish;
215       $dbh->disconnect;
216       next;
217     }
218     push(@dbsources, $db);
219   }
220
221   $sth->finish;
222   $dbh->disconnect;
223
224   $main::lxdebug->leave_sub();
225
226   return @dbsources;
227 }
228
229 sub dbclusterencoding {
230   $main::lxdebug->enter_sub();
231
232   my ($self, $form) = @_;
233
234   $form->{dbdefault} ||= $form->{dbuser};
235
236   dbconnect_vars($form, $form->{dbdefault});
237
238   my $dbh                = SL::DBConnect->connect($form->{dbconnect}, $form->{dbuser}, $form->{dbpasswd}, SL::DBConnect->get_options) || $form->dberror();
239   my $query              = qq|SELECT pg_encoding_to_char(encoding) FROM pg_database WHERE datname = 'template0'|;
240   my ($cluster_encoding) = $dbh->selectrow_array($query);
241   $dbh->disconnect();
242
243   $main::lxdebug->leave_sub();
244
245   return $cluster_encoding;
246 }
247
248 sub dbcreate {
249   $main::lxdebug->enter_sub();
250
251   my ($self, $form) = @_;
252
253   &dbconnect_vars($form, $form->{dbdefault});
254   my $dbh =
255     SL::DBConnect->connect($form->{dbconnect}, $form->{dbuser}, $form->{dbpasswd}, SL::DBConnect->get_options)
256     or $form->dberror;
257   $form->{db} =~ s/\"//g;
258
259   my @dboptions;
260
261   push @dboptions, "ENCODING = " . $dbh->quote($form->{"encoding"}) if $form->{"encoding"};
262   if ($form->{"dbdefault"}) {
263     my $dbdefault = $form->{"dbdefault"};
264     $dbdefault =~ s/[^a-zA-Z0-9_\-]//g;
265     push @dboptions, "TEMPLATE = $dbdefault";
266   }
267
268   my $query = qq|CREATE DATABASE "$form->{db}"|;
269   $query   .= " WITH " . join(" ", @dboptions) if @dboptions;
270
271   # Ignore errors if the database exists.
272   $dbh->do($query);
273
274   $dbh->disconnect;
275
276   &dbconnect_vars($form, $form->{db});
277
278   $dbh = SL::DBConnect->connect($form->{dbconnect}, $form->{dbuser}, $form->{dbpasswd}, SL::DBConnect->get_options)
279     or $form->dberror;
280
281   my $db_charset = $Common::db_encoding_to_charset{$form->{encoding}};
282   $db_charset ||= Common::DEFAULT_CHARSET;
283
284   my $dbupdater = SL::DBUpgrade2->new(form => $form);
285   # create the tables
286   $dbupdater->process_query($dbh, "sql/lx-office.sql", undef, $db_charset);
287
288   # load chart of accounts
289   $dbupdater->process_query($dbh, "sql/$form->{chart}-chart.sql", undef, $db_charset);
290
291   $query = "UPDATE defaults SET coa = ?";
292   do_query($form, $dbh, $query, $form->{chart});
293   $query = "UPDATE defaults SET accounting_method = ?";
294   do_query($form, $dbh, $query, $form->{accounting_method});
295   $query = "UPDATE defaults SET profit_determination = ?";
296   do_query($form, $dbh, $query, $form->{profit_determination});
297   $query = "UPDATE defaults SET inventory_system = ?";
298   do_query($form, $dbh, $query, $form->{inventory_system});
299   $query = "UPDATE defaults SET curr = ?";
300   do_query($form, $dbh, $query, $form->{defaultcurrency});
301
302   $dbh->disconnect;
303
304   $main::lxdebug->leave_sub();
305 }
306
307 sub dbdelete {
308   $main::lxdebug->enter_sub();
309
310   my ($self, $form) = @_;
311   $form->{db} =~ s/\"//g;
312
313   &dbconnect_vars($form, $form->{dbdefault});
314   my $dbh = SL::DBConnect->connect($form->{dbconnect}, $form->{dbuser}, $form->{dbpasswd}, SL::DBConnect->get_options)
315     or $form->dberror;
316   my $query = qq|DROP DATABASE "$form->{db}"|;
317   do_query($form, $dbh, $query);
318
319   $dbh->disconnect;
320
321   $main::lxdebug->leave_sub();
322 }
323
324 sub dbsources_unused {
325   $main::lxdebug->enter_sub();
326
327   my ($self, $form) = @_;
328
329   $form->{only_acc_db} = 1;
330
331   my %members = $main::auth->read_all_users();
332   my %dbexcl  = map { $_ => 1 } grep { $_ } map { $_->{dbname} } values %members;
333
334   $dbexcl{$form->{dbdefault}}             = 1;
335   $dbexcl{$main::auth->{DB_config}->{db}} = 1;
336
337   my @dbunused = grep { !$dbexcl{$_} } dbsources("", $form);
338
339   $main::lxdebug->leave_sub();
340
341   return @dbunused;
342 }
343
344 sub dbneedsupdate {
345   $main::lxdebug->enter_sub();
346
347   my ($self, $form) = @_;
348
349   my %members   = $main::auth->read_all_users();
350   my $dbupdater = SL::DBUpgrade2->new(form => $form)->parse_dbupdate_controls;
351
352   my ($query, $sth, %dbs_needing_updates);
353
354   foreach my $login (grep /[a-z]/, keys %members) {
355     my $member = $members{$login};
356
357     map { $form->{$_} = $member->{$_} } qw(dbname dbuser dbpasswd dbhost dbport);
358     dbconnect_vars($form, $form->{dbname});
359
360     my $dbh = SL::DBConnect->connect($form->{dbconnect}, $form->{dbuser}, $form->{dbpasswd}, SL::DBConnect->get_options);
361
362     next unless $dbh;
363
364     my $version;
365
366     $query = qq|SELECT version FROM defaults|;
367     $sth = prepare_query($form, $dbh, $query);
368     if ($sth->execute()) {
369       ($version) = $sth->fetchrow_array();
370     }
371     $sth->finish();
372
373     $dbh->disconnect and next unless $version;
374
375     my $update_available = $dbupdater->update_available($version) || $dbupdater->update2_available($dbh);
376     $dbh->disconnect;
377
378    if ($update_available) {
379       my $dbinfo = {};
380       map { $dbinfo->{$_} = $member->{$_} } grep /^db/, keys %{ $member };
381       $dbs_needing_updates{$member->{dbhost} . "::" . $member->{dbname}} = $dbinfo;
382     }
383   }
384
385   $main::lxdebug->leave_sub();
386
387   return values %dbs_needing_updates;
388 }
389
390 sub calc_version {
391   $main::lxdebug->enter_sub(2);
392
393   my (@v, $version, $i);
394
395   @v = split(/\./, $_[0]);
396   while (scalar(@v) < 4) {
397     push(@v, 0);
398   }
399   $version = 0;
400   for ($i = 0; $i < 4; $i++) {
401     $version *= 1000;
402     $version += $v[$i];
403   }
404
405   $main::lxdebug->leave_sub(2);
406   return $version;
407 }
408
409 sub cmp_script_version {
410   my ($a_from, $a_to, $b_from, $b_to);
411   my ($i, $res_a, $res_b);
412   my ($my_a, $my_b) = ($a, $b);
413
414   $my_a =~ s/.*-upgrade-//;
415   $my_a =~ s/.sql$//;
416   $my_b =~ s/.*-upgrade-//;
417   $my_b =~ s/.sql$//;
418   my ($my_a_from, $my_a_to) = split(/-/, $my_a);
419   my ($my_b_from, $my_b_to) = split(/-/, $my_b);
420
421   $res_a = calc_version($my_a_from);
422   $res_b = calc_version($my_b_from);
423
424   if ($res_a == $res_b) {
425     $res_a = calc_version($my_a_to);
426     $res_b = calc_version($my_b_to);
427   }
428
429   return $res_a <=> $res_b;
430 }
431
432 sub create_schema_info_table {
433   $main::lxdebug->enter_sub();
434
435   my ($self, $form, $dbh) = @_;
436
437   my $query = "SELECT tag FROM schema_info LIMIT 1";
438   if (!$dbh->do($query)) {
439     $dbh->rollback();
440     $query =
441       qq|CREATE TABLE schema_info (| .
442       qq|  tag text, | .
443       qq|  login text, | .
444       qq|  itime timestamp DEFAULT now(), | .
445       qq|  PRIMARY KEY (tag))|;
446     $dbh->do($query) || $form->dberror($query);
447   }
448
449   $main::lxdebug->leave_sub();
450 }
451
452 sub dbupdate {
453   $main::lxdebug->enter_sub();
454
455   my ($self, $form) = @_;
456
457   local *SQLDIR;
458
459   my @upgradescripts = ();
460   my $query;
461   my $rc = -2;
462
463   if ($form->{dbupdate}) {
464
465     # read update scripts into memory
466     opendir(SQLDIR, "sql/Pg-upgrade")
467       or &error("", "sql/Pg-upgrade : $!");
468     @upgradescripts =
469       sort(cmp_script_version
470            grep(/Pg-upgrade-.*?\.(sql|pl)$/,
471                 readdir(SQLDIR)));
472     closedir(SQLDIR);
473   }
474
475   my $db_charset = $::lx_office_conf{system}->{dbcharset};
476   $db_charset ||= Common::DEFAULT_CHARSET;
477
478   my $dbupdater = SL::DBUpgrade2->new(form => $form);
479
480   foreach my $db (split(/ /, $form->{dbupdate})) {
481
482     next unless $form->{$db};
483
484     # strip db from dataset
485     $db =~ s/^db//;
486     &dbconnect_vars($form, $db);
487
488     my $dbh = SL::DBConnect->connect($form->{dbconnect}, $form->{dbuser}, $form->{dbpasswd}, SL::DBConnect->get_options)
489       or $form->dberror;
490
491     $dbh->do($form->{dboptions}) if ($form->{dboptions});
492
493     # check version
494     $query = qq|SELECT version FROM defaults|;
495     my ($version) = selectrow_query($form, $dbh, $query);
496
497     next unless $version;
498
499     $version = calc_version($version);
500
501     foreach my $upgradescript (@upgradescripts) {
502       my $a = $upgradescript;
503       $a =~ s/^Pg-upgrade-|\.(sql|pl)$//g;
504
505       my ($mindb, $maxdb) = split /-/, $a;
506       my $str_maxdb = $maxdb;
507       $mindb = calc_version($mindb);
508       $maxdb = calc_version($maxdb);
509
510       next if ($version >= $maxdb);
511
512       # if there is no upgrade script exit
513       last if ($version < $mindb);
514
515       # apply upgrade
516       $main::lxdebug->message(LXDebug->DEBUG2(), "Applying Update $upgradescript");
517       $dbupdater->process_file($dbh, "sql/Pg-upgrade/$upgradescript", $str_maxdb, $db_charset);
518
519       $version = $maxdb;
520
521     }
522
523     $rc = 0;
524     $dbh->disconnect;
525
526   }
527
528   $main::lxdebug->leave_sub();
529
530   return $rc;
531 }
532
533 sub dbupdate2 {
534   $main::lxdebug->enter_sub();
535
536   my ($self, %params) = @_;
537
538   my $form            = $params{form};
539   my $dbupdater       = $params{updater};
540   my $db              = $params{database};
541   my $rc              = -2;
542   my $db_charset      = $::lx_office_conf{system}->{dbcharset} || Common::DEFAULT_CHARSET;
543
544   map { $_->{description} = SL::Iconv::convert($_->{charset}, $db_charset, $_->{description}) } values %{ $dbupdater->{all_controls} };
545
546   &dbconnect_vars($form, $db);
547
548   my $dbh = SL::DBConnect->connect($form->{dbconnect}, $form->{dbuser}, $form->{dbpasswd}, SL::DBConnect->get_options) or $form->dberror;
549
550   $dbh->do($form->{dboptions}) if ($form->{dboptions});
551
552   $self->create_schema_info_table($form, $dbh);
553
554   my @upgradescripts = $dbupdater->unapplied_upgrade_scripts($dbh);
555
556   $dbh->disconnect and next if !@upgradescripts;
557
558   foreach my $control (@upgradescripts) {
559     # apply upgrade
560     $main::lxdebug->message(LXDebug->DEBUG2(), "Applying Update $control->{file}");
561     print $form->parse_html_template("dbupgrade/upgrade_message2", $control);
562
563     $dbupdater->process_file($dbh, "sql/Pg-upgrade2/$control->{file}", $control, $db_charset);
564   }
565
566   $rc = 0;
567   $dbh->disconnect;
568
569   $main::lxdebug->leave_sub();
570
571   return $rc;
572 }
573
574 sub save_member {
575   $main::lxdebug->enter_sub();
576
577   my ($self) = @_;
578
579   # format dbconnect and dboptions string
580   dbconnect_vars($self, $self->{dbname});
581
582   map { $self->{$_} =~ s/\r//g; } qw(address signature);
583
584   $main::auth->save_user($self->{login}, map { $_, $self->{$_} } config_vars());
585
586   my $dbh = SL::DBConnect->connect($self->{dbconnect}, $self->{dbuser}, $self->{dbpasswd}, SL::DBConnect->get_options);
587   if ($dbh) {
588     $self->create_employee_entry($::form, $dbh, $self, 1);
589     $dbh->disconnect();
590   }
591
592   $main::lxdebug->leave_sub();
593 }
594
595 sub create_employee_entry {
596   $main::lxdebug->enter_sub();
597
598   my $self            = shift;
599   my $form            = shift;
600   my $dbh             = shift;
601   my $myconfig        = shift;
602   my $update_existing = shift;
603
604   if (!does_table_exist($dbh, 'employee')) {
605     $main::lxdebug->leave_sub();
606     return;
607   }
608
609   # add login to employee table if it does not exist
610   # no error check for employee table, ignore if it does not exist
611   my ($id)         = selectrow_query($form, $dbh, qq|SELECT id FROM employee WHERE login = ?|, $self->{login});
612   my ($good_db)    = selectrow_query($form, $dbh, qq|select * from pg_tables where tablename = ? and schemaname = ?|, 'schema_info', 'public');
613   my  $can_delete;
614      ($can_delete) = selectrow_query($form, $dbh, qq|SELECT tag FROM schema_info WHERE tag = ?|, 'employee_deleted') if $good_db;
615
616   if (!$id) {
617     my $query = qq|INSERT INTO employee (login, name, workphone) VALUES (?, ?, ?)|;
618     do_query($form, $dbh, $query, ($self->{login}, $myconfig->{name}, $myconfig->{tel}));
619
620   } elsif ($update_existing && $can_delete) {
621     my $query = qq|UPDATE employee SET name = ?, workphone = ?, deleted = 'f' WHERE id = ?|;
622     do_query($form, $dbh, $query, $myconfig->{name}, $myconfig->{tel}, $id);
623   }
624
625   $main::lxdebug->leave_sub();
626 }
627
628 sub config_vars {
629   $main::lxdebug->enter_sub();
630
631   my @conf = qw(copies countrycode dateformat default_media default_printer_id email favorites fax hide_cvar_search_options mandatory_departments menustyle name
632                 numberformat show_form_details signature stylesheet taxincluded_checked tel template_format vclimit);
633
634   $main::lxdebug->leave_sub();
635
636   return @conf;
637 }
638
639 sub data {
640   +{ %{ $_[0] } }
641 }
642
643 1;