1 #=====================================================================
 
   4 # Based on SQL-Ledger Version 2.1.9
 
   5 # Web http://www.lx-office.org
 
   7 #=====================================================================
 
   8 # SQL-Ledger Accounting
 
  11 #  Author: Dieter Simader
 
  12 #   Email: dsimader@sql-ledger.org
 
  13 #     Web: http://www.sql-ledger.org
 
  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.
 
  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., 51 Franklin Street, Fifth Floor, Boston,
 
  30 #=====================================================================
 
  32 # user related functions
 
  34 #=====================================================================
 
  39 use List::MoreUtils qw(any);
 
  43 use SL::DB::AuthClient;
 
  50 use SL::System::InstallationLock;
 
  51 use SL::DefaultManager;
 
  55 use constant LOGIN_OK                      =>  0;
 
  56 use constant LOGIN_BASIC_TABLES_MISSING    => -1;
 
  57 use constant LOGIN_DBUPDATE_AVAILABLE      => -2;
 
  58 use constant LOGIN_AUTH_DBUPDATE_AVAILABLE => -3;
 
  59 use constant LOGIN_GENERAL_ERROR           => -4;
 
  62   $main::lxdebug->enter_sub();
 
  64   my ($type, %params) = @_;
 
  68   if ($params{id} || $params{login}) {
 
  69     my %user_data = $main::auth->read_user(%params);
 
  70     map { $self->{$_} = $user_data{$_} } keys %user_data;
 
  73   $main::lxdebug->leave_sub();
 
  79   $main::lxdebug->enter_sub();
 
  86   # scan the locale directory and read in the LANGUAGE files
 
  87   opendir(DIR, "locale");
 
  89   my @dir = grep(!/(^\.\.?$|\..*)/, readdir(DIR));
 
  91   foreach my $dir (@dir) {
 
  92     next unless open(my $fh, '<:encoding(UTF-8)', "locale/$dir/LANGUAGE");
 
  96     $cc{$dir} = "@language";
 
 101   $main::lxdebug->leave_sub();
 
 106 sub _handle_superuser_privileges {
 
 107   my ($self, $form) = @_;
 
 109   if ($form->{database_superuser_username}) {
 
 110     $::auth->set_session_value("database_superuser_username" => $form->{database_superuser_username}, "database_superuser_password" => $form->{database_superuser_password});
 
 113   my %dbconnect_form          = %{ $form };
 
 114   my ($su_user, $su_password) = map { $::auth->get_session_value("database_superuser_$_") } qw(username password);
 
 117     $dbconnect_form{dbuser}   = $su_user;
 
 118     $dbconnect_form{dbpasswd} = $su_password;
 
 121   dbconnect_vars(\%dbconnect_form, $form->{dbname});
 
 124     username => $dbconnect_form{dbuser},
 
 125     password => $dbconnect_form{dbpasswd},
 
 128   $::auth->set_session_value("database_superuser_username" => $dbconnect_form{dbuser}, "database_superuser_password" => $dbconnect_form{dbpasswd});
 
 130   my $dbh = SL::DBConnect->connect($dbconnect_form{dbconnect}, $dbconnect_form{dbuser}, $dbconnect_form{dbpasswd}, SL::DBConnect->get_options);
 
 131   return (%result, error => $::locale->text('The credentials (username & password) for connecting database are wrong.')) if !$dbh;
 
 133   my $is_superuser = SL::DBUtils::role_is_superuser($dbh, $dbconnect_form{dbuser});
 
 137   return (%result, have_privileges => 1) if $is_superuser;
 
 138   return (%result)                       if !$su_user; # no error message if credentials weren't set by the user
 
 139   return (%result, error => $::locale->text('The database user \'#1\' does not have superuser privileges.', $dbconnect_form{dbuser}));
 
 143   my ($self, $form) = @_;
 
 145   return LOGIN_GENERAL_ERROR() if !$self->{login} || !$::auth->client;
 
 147   my %myconfig = $main::auth->read_user(login => $self->{login});
 
 149   # Auth DB upgrades available?
 
 150   my $dbupdater_auth = SL::DBUpgrade2->new(form => $form, auth => 1)->parse_dbupdate_controls;
 
 151   return LOGIN_AUTH_DBUPDATE_AVAILABLE() if $dbupdater_auth->unapplied_upgrade_scripts($::auth->dbconnect);
 
 153   # check if database is down
 
 154   my $dbh = SL::DB->client->dbh;
 
 156   # we got a connection, check the version
 
 157   my ($dbversion) = $dbh->selectrow_array(qq|SELECT version FROM defaults|);
 
 160     return LOGIN_BASIC_TABLES_MISSING();
 
 163   $self->create_schema_info_table($form, $dbh);
 
 165   my $dbupdater        = SL::DBUpgrade2->new(form => $form)->parse_dbupdate_controls;
 
 166   my @unapplied_scripts = $dbupdater->unapplied_upgrade_scripts($dbh);
 
 169   if (!@unapplied_scripts) {
 
 170     SL::DB::Manager::Employee->update_entries_for_authorized_users;
 
 174   # Store the fact that we're applying database upgrades at the
 
 175   # moment. That way functions called from the layout modules that may
 
 176   # require updated tables can chose only to use basic features.
 
 177   $::request->applying_database_upgrades(1);
 
 179   $form->{$_} = $::auth->client->{$_} for qw(dbname dbhost dbport dbuser dbpasswd);
 
 180   $form->{$_} = $myconfig{$_}         for qw(datestyle);
 
 182   $form->{"title"} = $main::locale->text("Dataset upgrade");
 
 183   $form->header(no_layout => $form->{no_layout});
 
 184   print $form->parse_html_template("dbupgrade/header");
 
 186   $form->{dbupdate} = "db" . $::auth->client->{dbname};
 
 188   my $show_update_warning = $form->{"show_dbupdate_warning"};
 
 189   my %superuser           = (need_privileges => (any { $_->{superuser_privileges} } @unapplied_scripts));
 
 191   if ($superuser{need_privileges}) {
 
 194       $self->_handle_superuser_privileges($form),
 
 196     $show_update_warning = 1 if !$superuser{have_privileges};
 
 199   if ($show_update_warning) {
 
 200     print $form->parse_html_template("dbupgrade/warning", {
 
 201       unapplied_scripts => \@unapplied_scripts,
 
 202       superuser         => \%superuser,
 
 204     $::dispatcher->end_request;
 
 208   SL::System::InstallationLock->lock;
 
 210   # ignore HUP, QUIT in case the webserver times out
 
 211   $SIG{HUP}  = 'IGNORE';
 
 212   $SIG{QUIT} = 'IGNORE';
 
 214   $self->dbupdate2(form => $form, updater => $dbupdater, database => $::auth->client->{dbname});
 
 216   # If $self->dbupdate2 returns than this means all upgrade scripts
 
 217   # have been applied successfully, none required user
 
 218   # interaction. Otherwise the deeper layers would have called
 
 219   # $::dispatcher->end_request already, and return would not have returned to
 
 220   # us. Therefore we can now use RDBO instances because their supposed
 
 221   # table structures do match the actual structures. So let's ensure
 
 222   # that the "employee" table contains the appropriate entries for all
 
 223   # users authorized for the current client.
 
 224   SL::DB::Manager::Employee->update_entries_for_authorized_users;
 
 226   SL::System::InstallationLock->unlock;
 
 228   print $form->parse_html_template("dbupgrade/footer");
 
 230   return LOGIN_DBUPDATE_AVAILABLE();
 
 234   $main::lxdebug->enter_sub();
 
 236   my ($form, $db) = @_;
 
 239     'yy-mm-dd'   => 'set DateStyle to \'ISO\'',
 
 240     'yyyy-mm-dd' => 'set DateStyle to \'ISO\'',
 
 241     'mm/dd/yy'   => 'set DateStyle to \'SQL, US\'',
 
 242     'dd/mm/yy'   => 'set DateStyle to \'SQL, EUROPEAN\'',
 
 243     'dd.mm.yy'   => 'set DateStyle to \'GERMAN\''
 
 246   $form->{dboptions} = $dboptions{ $form->{dateformat} };
 
 247   $form->{dbconnect} = "dbi:Pg:dbname=${db};host=" . ($form->{dbhost} || 'localhost') . ";port=" . ($form->{dbport} || 5432);
 
 249   $main::lxdebug->leave_sub();
 
 253   $main::lxdebug->enter_sub();
 
 255   my ($self, $form) = @_;
 
 260   $form->{dbdefault} = $form->{dbuser} unless $form->{dbdefault};
 
 261   &dbconnect_vars($form, $form->{dbdefault});
 
 263   my $dbh = SL::DBConnect->connect($form->{dbconnect}, $form->{dbuser}, $form->{dbpasswd}, SL::DBConnect->get_options)
 
 267     qq|SELECT datname FROM pg_database | .
 
 268     qq|WHERE NOT datname IN ('template0', 'template1')|;
 
 269   $sth = $dbh->prepare($query);
 
 270   $sth->execute() || $form->dberror($query);
 
 272   while (my ($db) = $sth->fetchrow_array) {
 
 274     if ($form->{only_acc_db}) {
 
 276       next if ($db =~ /^template/);
 
 278       &dbconnect_vars($form, $db);
 
 279       my $dbh = SL::DBConnect->connect($form->{dbconnect}, $form->{dbuser}, $form->{dbpasswd}, SL::DBConnect->get_options)
 
 283         qq|SELECT tablename FROM pg_tables | .
 
 284         qq|WHERE (tablename = 'defaults') AND (tableowner = ?)|;
 
 285       my $sth = $dbh->prepare($query);
 
 286       $sth->execute($form->{dbuser}) ||
 
 287         $form->dberror($query . " ($form->{dbuser})");
 
 289       if ($sth->fetchrow_array) {
 
 290         push(@dbsources, $db);
 
 296     push(@dbsources, $db);
 
 302   $main::lxdebug->leave_sub();
 
 308   $main::lxdebug->enter_sub();
 
 310   my ($self, $form) = @_;
 
 312   &dbconnect_vars($form, $form->{dbdefault});
 
 314     SL::DBConnect->connect($form->{dbconnect}, $form->{dbuser}, $form->{dbpasswd}, SL::DBConnect->get_options)
 
 316   $form->{db} =~ s/\"//g;
 
 320   push @dboptions, "ENCODING = " . $dbh->quote($form->{"encoding"}) if $form->{"encoding"};
 
 321   if ($form->{"dbdefault"}) {
 
 322     my $dbdefault = $form->{"dbdefault"};
 
 323     $dbdefault =~ s/[^a-zA-Z0-9_\-]//g;
 
 324     push @dboptions, "TEMPLATE = $dbdefault";
 
 327   my $query = qq|CREATE DATABASE "$form->{db}"|;
 
 328   $query   .= " WITH " . join(" ", @dboptions) if @dboptions;
 
 330   # Ignore errors if the database exists.
 
 335   &dbconnect_vars($form, $form->{db});
 
 337   # make a shim myconfig so that rose db connections work
 
 338   $::myconfig{$_}     = $form->{$_} for qw(dbhost dbport dbuser dbpasswd);
 
 339   $::myconfig{dbname} = $form->{db};
 
 341   $dbh = SL::DBConnect->connect($form->{dbconnect}, $form->{dbuser}, $form->{dbpasswd}, SL::DBConnect->get_options)
 
 344   my $dbupdater = SL::DBUpgrade2->new(form => $form, return_on_error => 1, silent => 1)->parse_dbupdate_controls;
 
 346   $dbupdater->process_query($dbh, "sql/lx-office.sql");
 
 347   $dbupdater->process_query($dbh, "sql/$form->{chart}-chart.sql");
 
 349   $query = qq|UPDATE defaults SET coa = ?|;
 
 350   do_query($form, $dbh, $query, map { $form->{$_} } qw(chart));
 
 354   # update new database
 
 355   $self->dbupdate2(form => $form, updater => $dbupdater, database => $form->{db}, silent => 1);
 
 357   $dbh = SL::DBConnect->connect($form->{dbconnect}, $form->{dbuser}, $form->{dbpasswd}, SL::DBConnect->get_options)
 
 360   $query = "SELECT * FROM currencies WHERE name = ?";
 
 361   my $curr = selectfirst_hashref_query($form, $dbh, $query, $form->{defaultcurrency});
 
 363     do_query($form, $dbh, "INSERT INTO currencies (name) VALUES (?)", $form->{defaultcurrency});
 
 364     $curr = selectfirst_hashref_query($form, $dbh, $query, $form->{defaultcurrency});
 
 367   $query = qq|UPDATE defaults SET
 
 368     accounting_method = ?,
 
 369     profit_determination = ?,
 
 370     inventory_system = ?,
 
 375     feature_erfolgsrechnung = ?,
 
 376     feature_eurechnung = ?,
 
 379   do_query($form, $dbh, $query,
 
 380     $form->{accounting_method},
 
 381     $form->{profit_determination},
 
 382     $form->{inventory_system},
 
 383     $form->parse_amount(\%::myconfig, $form->{precision_as_number}),
 
 385     $form->{feature_balance},
 
 386     $form->{feature_datev},
 
 387     $form->{feature_erfolgsrechnung},
 
 388     $form->{feature_eurechnung},
 
 389     $form->{feature_ustva}
 
 394   $main::lxdebug->leave_sub();
 
 398   $main::lxdebug->enter_sub();
 
 400   my ($self, $form) = @_;
 
 401   $form->{db} =~ s/\"//g;
 
 403   &dbconnect_vars($form, $form->{dbdefault});
 
 404   my $dbh = SL::DBConnect->connect($form->{dbconnect}, $form->{dbuser}, $form->{dbpasswd}, SL::DBConnect->get_options)
 
 406   my $query = qq|DROP DATABASE "$form->{db}"|;
 
 407   do_query($form, $dbh, $query);
 
 411   $main::lxdebug->leave_sub();
 
 415   $main::lxdebug->enter_sub(2);
 
 417   my (@v, $version, $i);
 
 419   @v = split(/\./, $_[0]);
 
 420   while (scalar(@v) < 4) {
 
 424   for ($i = 0; $i < 4; $i++) {
 
 429   $main::lxdebug->leave_sub(2);
 
 433 sub cmp_script_version {
 
 434   my ($a_from, $a_to, $b_from, $b_to);
 
 435   my ($i, $res_a, $res_b);
 
 436   my ($my_a, $my_b) = do { no warnings 'once'; ($a, $b) };
 
 438   $my_a =~ s/.*-upgrade-//;
 
 440   $my_b =~ s/.*-upgrade-//;
 
 442   my ($my_a_from, $my_a_to) = split(/-/, $my_a);
 
 443   my ($my_b_from, $my_b_to) = split(/-/, $my_b);
 
 445   $res_a = calc_version($my_a_from);
 
 446   $res_b = calc_version($my_b_from);
 
 448   if ($res_a == $res_b) {
 
 449     $res_a = calc_version($my_a_to);
 
 450     $res_b = calc_version($my_b_to);
 
 453   return $res_a <=> $res_b;
 
 456 sub create_schema_info_table {
 
 457   $main::lxdebug->enter_sub();
 
 459   my ($self, $form, $dbh) = @_;
 
 461   my $query = "SELECT tag FROM schema_info LIMIT 1";
 
 462   if (!$dbh->do($query)) {
 
 465       qq|CREATE TABLE schema_info (| .
 
 468       qq|  itime timestamp DEFAULT now(), | .
 
 469       qq|  PRIMARY KEY (tag))|;
 
 470     $dbh->do($query) || $form->dberror($query);
 
 473   $main::lxdebug->leave_sub();
 
 477   my ($self, %params) = @_;
 
 479   my $form            = $params{form};
 
 480   my $dbupdater       = $params{updater};
 
 481   my $db              = $params{database};
 
 482   my $silent          = $params{silent};
 
 484   map { $_->{description} = SL::Iconv::convert($_->{charset}, 'UTF-8', $_->{description}) } values %{ $dbupdater->{all_controls} };
 
 486   &dbconnect_vars($form, $db);
 
 488   my $dbh = SL::DBConnect->connect($form->{dbconnect}, $form->{dbuser}, $form->{dbpasswd}, SL::DBConnect->get_options) or $form->dberror;
 
 490   $dbh->do($form->{dboptions}) if ($form->{dboptions});
 
 492   $self->create_schema_info_table($form, $dbh);
 
 494   my @upgradescripts = $dbupdater->unapplied_upgrade_scripts($dbh);
 
 495   my $need_superuser = (any { $_->{superuser_privileges} } @upgradescripts);
 
 498   if ($need_superuser) {
 
 499     my %dbconnect_form = (
 
 501       dbuser   => $::auth->get_session_value("database_superuser_username"),
 
 502       dbpasswd => $::auth->get_session_value("database_superuser_password"),
 
 505     if ($dbconnect_form{dbuser} ne $form->{dbuser}) {
 
 506       dbconnect_vars(\%dbconnect_form, $db);
 
 507       $superuser_dbh = SL::DBConnect->connect($dbconnect_form{dbconnect}, $dbconnect_form{dbuser}, $dbconnect_form{dbpasswd}, SL::DBConnect->get_options) or $form->dberror;
 
 511   $::lxdebug->log_time("DB upgrades commencing");
 
 513   foreach my $control (@upgradescripts) {
 
 514     # Apply upgrade. Control will only return to us if the upgrade has
 
 515     # been applied correctly and if the update has not requested user
 
 517     my $script_dbh = $control->{superuser_privileges} ? ($superuser_dbh // $dbh) : $dbh;
 
 519     $::lxdebug->message(LXDebug->DEBUG2(), "Applying Update $control->{file}" . ($control->{superuser_privileges} ? " with superuser privileges" : ""));
 
 520     print $form->parse_html_template("dbupgrade/upgrade_message2", $control) unless $silent;
 
 522     $dbupdater->process_file($script_dbh, "sql/Pg-upgrade2/$control->{file}", $control);
 
 525   $::lxdebug->log_time("DB upgrades finished");
 
 528   $superuser_dbh->disconnect if $superuser_dbh;
 
 535 sub get_default_myconfig {
 
 536   my ($self_or_class, %user_config) = @_;
 
 537   my $defaults = SL::DefaultManager->new($::lx_office_conf{system}->{default_manager});
 
 540     countrycode  => $defaults->language('de'),
 
 541     css_path     => 'css',      # Needed for menunew, see SL::Layout::Base::get_stylesheet_for_user
 
 542     dateformat   => $defaults->dateformat('dd.mm.yy'),
 
 543     numberformat => $defaults->numberformat('1.000,00'),
 
 544     stylesheet   => $defaults->stylesheet('kivitendo.css'),
 
 545     timeformat   => $defaults->timeformat('hh:mm'),