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., 675 Mass Ave, Cambridge, MA 02139, USA.
 
  29 #=====================================================================
 
  31 # user related functions
 
  33 #=====================================================================
 
  41 use SL::DB::AuthClient;
 
  48 use SL::System::InstallationLock;
 
  49 use SL::DefaultManager;
 
  53 use constant LOGIN_OK                      =>  0;
 
  54 use constant LOGIN_BASIC_TABLES_MISSING    => -1;
 
  55 use constant LOGIN_DBUPDATE_AVAILABLE      => -2;
 
  56 use constant LOGIN_AUTH_DBUPDATE_AVAILABLE => -3;
 
  57 use constant LOGIN_GENERAL_ERROR           => -4;
 
  60   $main::lxdebug->enter_sub();
 
  62   my ($type, %params) = @_;
 
  66   if ($params{id} || $params{login}) {
 
  67     my %user_data = $main::auth->read_user(%params);
 
  68     map { $self->{$_} = $user_data{$_} } keys %user_data;
 
  71   $main::lxdebug->leave_sub();
 
  77   $main::lxdebug->enter_sub();
 
  84   # scan the locale directory and read in the LANGUAGE files
 
  85   opendir(DIR, "locale");
 
  87   my @dir = grep(!/(^\.\.?$|\..*)/, readdir(DIR));
 
  89   foreach my $dir (@dir) {
 
  90     next unless open(my $fh, '<:encoding(UTF-8)', "locale/$dir/LANGUAGE");
 
  94     $cc{$dir} = "@language";
 
  99   $main::lxdebug->leave_sub();
 
 105   my ($self, $form) = @_;
 
 107   return LOGIN_GENERAL_ERROR() if !$self->{login} || !$::auth->client;
 
 109   my %myconfig = $main::auth->read_user(login => $self->{login});
 
 111   # Auth DB upgrades available?
 
 112   my $dbupdater_auth = SL::DBUpgrade2->new(form => $form, auth => 1)->parse_dbupdate_controls;
 
 113   return LOGIN_AUTH_DBUPDATE_AVAILABLE() if $dbupdater_auth->unapplied_upgrade_scripts($::auth->dbconnect);
 
 115   # check if database is down
 
 116   my $dbh = $form->dbconnect_noauto;
 
 118   # we got a connection, check the version
 
 119   my ($dbversion) = $dbh->selectrow_array(qq|SELECT version FROM defaults|);
 
 122     return LOGIN_BASIC_TABLES_MISSING();
 
 125   $self->create_schema_info_table($form, $dbh);
 
 127   my $dbupdater        = SL::DBUpgrade2->new(form => $form)->parse_dbupdate_controls;
 
 128   my @unapplied_scripts = $dbupdater->unapplied_upgrade_scripts($dbh);
 
 131   if (!@unapplied_scripts) {
 
 132     SL::DB::Manager::Employee->update_entries_for_authorized_users;
 
 136   $form->{$_} = $::auth->client->{$_} for qw(dbname dbhost dbport dbuser dbpasswd);
 
 137   $form->{$_} = $myconfig{$_}         for qw(datestyle);
 
 139   $form->{"title"} = $main::locale->text("Dataset upgrade");
 
 140   $form->header(no_layout => $form->{no_layout});
 
 141   print $form->parse_html_template("dbupgrade/header");
 
 143   $form->{dbupdate} = "db" . $::auth->client->{dbname};
 
 145   if ($form->{"show_dbupdate_warning"}) {
 
 146     print $form->parse_html_template("dbupgrade/warning", { unapplied_scripts => \@unapplied_scripts });
 
 151   SL::System::InstallationLock->lock;
 
 153   # ignore HUP, QUIT in case the webserver times out
 
 154   $SIG{HUP}  = 'IGNORE';
 
 155   $SIG{QUIT} = 'IGNORE';
 
 157   $self->dbupdate2(form => $form, updater => $dbupdater, database => $::auth->client->{dbname});
 
 159   # If $self->dbupdate2 returns than this means all upgrade scripts
 
 160   # have been applied successfully, none required user
 
 161   # interaction. Otherwise the deeper layers would have called
 
 162   # ::end_of_request() already, and return would not have returned to
 
 163   # us. Therefore we can now use RDBO instances because their supposed
 
 164   # table structures do match the actual structures. So let's ensure
 
 165   # that the "employee" table contains the appropriate entries for all
 
 166   # users authorized for the current client.
 
 167   SL::DB::Manager::Employee->update_entries_for_authorized_users;
 
 169   SL::System::InstallationLock->unlock;
 
 171   print $form->parse_html_template("dbupgrade/footer");
 
 173   return LOGIN_DBUPDATE_AVAILABLE();
 
 177   $main::lxdebug->enter_sub();
 
 179   my ($form, $db) = @_;
 
 182     'yy-mm-dd'   => 'set DateStyle to \'ISO\'',
 
 183     'yyyy-mm-dd' => 'set DateStyle to \'ISO\'',
 
 184     'mm/dd/yy'   => 'set DateStyle to \'SQL, US\'',
 
 185     'dd/mm/yy'   => 'set DateStyle to \'SQL, EUROPEAN\'',
 
 186     'dd.mm.yy'   => 'set DateStyle to \'GERMAN\''
 
 189   $form->{dboptions} = $dboptions{ $form->{dateformat} };
 
 190   $form->{dbconnect} = "dbi:Pg:dbname=${db};host=" . ($form->{dbhost} || 'localhost') . ";port=" . ($form->{dbport} || 5432);
 
 192   $main::lxdebug->leave_sub();
 
 196   $main::lxdebug->enter_sub();
 
 198   my ($self, $form) = @_;
 
 203   $form->{dbdefault} = $form->{dbuser} unless $form->{dbdefault};
 
 204   &dbconnect_vars($form, $form->{dbdefault});
 
 206   my $dbh = SL::DBConnect->connect($form->{dbconnect}, $form->{dbuser}, $form->{dbpasswd}, SL::DBConnect->get_options)
 
 210     qq|SELECT datname FROM pg_database | .
 
 211     qq|WHERE NOT datname IN ('template0', 'template1')|;
 
 212   $sth = $dbh->prepare($query);
 
 213   $sth->execute() || $form->dberror($query);
 
 215   while (my ($db) = $sth->fetchrow_array) {
 
 217     if ($form->{only_acc_db}) {
 
 219       next if ($db =~ /^template/);
 
 221       &dbconnect_vars($form, $db);
 
 222       my $dbh = SL::DBConnect->connect($form->{dbconnect}, $form->{dbuser}, $form->{dbpasswd}, SL::DBConnect->get_options)
 
 226         qq|SELECT tablename FROM pg_tables | .
 
 227         qq|WHERE (tablename = 'defaults') AND (tableowner = ?)|;
 
 228       my $sth = $dbh->prepare($query);
 
 229       $sth->execute($form->{dbuser}) ||
 
 230         $form->dberror($query . " ($form->{dbuser})");
 
 232       if ($sth->fetchrow_array) {
 
 233         push(@dbsources, $db);
 
 239     push(@dbsources, $db);
 
 245   $main::lxdebug->leave_sub();
 
 251   $main::lxdebug->enter_sub();
 
 253   my ($self, $form) = @_;
 
 255   &dbconnect_vars($form, $form->{dbdefault});
 
 257     SL::DBConnect->connect($form->{dbconnect}, $form->{dbuser}, $form->{dbpasswd}, SL::DBConnect->get_options)
 
 259   $form->{db} =~ s/\"//g;
 
 263   push @dboptions, "ENCODING = " . $dbh->quote($form->{"encoding"}) if $form->{"encoding"};
 
 264   if ($form->{"dbdefault"}) {
 
 265     my $dbdefault = $form->{"dbdefault"};
 
 266     $dbdefault =~ s/[^a-zA-Z0-9_\-]//g;
 
 267     push @dboptions, "TEMPLATE = $dbdefault";
 
 270   my $query = qq|CREATE DATABASE "$form->{db}"|;
 
 271   $query   .= " WITH " . join(" ", @dboptions) if @dboptions;
 
 273   # Ignore errors if the database exists.
 
 278   &dbconnect_vars($form, $form->{db});
 
 280   # make a shim myconfig so that rose db connections work
 
 281   $::myconfig{$_}     = $form->{$_} for qw(dbhost dbport dbuser dbpasswd);
 
 282   $::myconfig{dbname} = $form->{db};
 
 284   $dbh = SL::DBConnect->connect($form->{dbconnect}, $form->{dbuser}, $form->{dbpasswd}, SL::DBConnect->get_options)
 
 287   my $dbupdater = SL::DBUpgrade2->new(form => $form, return_on_error => 1, silent => 1)->parse_dbupdate_controls;
 
 289   $dbupdater->process_query($dbh, "sql/lx-office.sql");
 
 290   $dbupdater->process_query($dbh, "sql/$form->{chart}-chart.sql");
 
 292   $query = qq|UPDATE defaults SET coa = ?|;
 
 293   do_query($form, $dbh, $query, map { $form->{$_} } qw(chart));
 
 297   # update new database
 
 298   $self->dbupdate2(form => $form, updater => $dbupdater, database => $form->{db}, silent => 1);
 
 300   $dbh = SL::DBConnect->connect($form->{dbconnect}, $form->{dbuser}, $form->{dbpasswd}, SL::DBConnect->get_options)
 
 303   $query = "SELECT * FROM currencies WHERE name = ?";
 
 304   my $curr = selectfirst_hashref_query($form, $dbh, $query, $form->{defaultcurrency});
 
 306     do_query($form, $dbh, "INSERT INTO currencies (name) VALUES (?)", $form->{defaultcurrency});
 
 307     $curr = selectfirst_hashref_query($form, $dbh, $query, $form->{defaultcurrency});
 
 310   $query = qq|UPDATE defaults SET accounting_method = ?, profit_determination = ?, inventory_system = ?, precision = ?, currency_id = ?|;
 
 311   do_query($form, $dbh, $query,
 
 312     $form->{accounting_method},
 
 313     $form->{profit_determination},
 
 314     $form->{inventory_system},
 
 315     $form->parse_amount(\%::myconfig, $form->{precision_as_number}),
 
 321   $main::lxdebug->leave_sub();
 
 325   $main::lxdebug->enter_sub();
 
 327   my ($self, $form) = @_;
 
 328   $form->{db} =~ s/\"//g;
 
 330   &dbconnect_vars($form, $form->{dbdefault});
 
 331   my $dbh = SL::DBConnect->connect($form->{dbconnect}, $form->{dbuser}, $form->{dbpasswd}, SL::DBConnect->get_options)
 
 333   my $query = qq|DROP DATABASE "$form->{db}"|;
 
 334   do_query($form, $dbh, $query);
 
 338   $main::lxdebug->leave_sub();
 
 342   $main::lxdebug->enter_sub(2);
 
 344   my (@v, $version, $i);
 
 346   @v = split(/\./, $_[0]);
 
 347   while (scalar(@v) < 4) {
 
 351   for ($i = 0; $i < 4; $i++) {
 
 356   $main::lxdebug->leave_sub(2);
 
 360 sub cmp_script_version {
 
 361   my ($a_from, $a_to, $b_from, $b_to);
 
 362   my ($i, $res_a, $res_b);
 
 363   my ($my_a, $my_b) = do { no warnings 'once'; ($a, $b) };
 
 365   $my_a =~ s/.*-upgrade-//;
 
 367   $my_b =~ s/.*-upgrade-//;
 
 369   my ($my_a_from, $my_a_to) = split(/-/, $my_a);
 
 370   my ($my_b_from, $my_b_to) = split(/-/, $my_b);
 
 372   $res_a = calc_version($my_a_from);
 
 373   $res_b = calc_version($my_b_from);
 
 375   if ($res_a == $res_b) {
 
 376     $res_a = calc_version($my_a_to);
 
 377     $res_b = calc_version($my_b_to);
 
 380   return $res_a <=> $res_b;
 
 383 sub create_schema_info_table {
 
 384   $main::lxdebug->enter_sub();
 
 386   my ($self, $form, $dbh) = @_;
 
 388   my $query = "SELECT tag FROM schema_info LIMIT 1";
 
 389   if (!$dbh->do($query)) {
 
 392       qq|CREATE TABLE schema_info (| .
 
 395       qq|  itime timestamp DEFAULT now(), | .
 
 396       qq|  PRIMARY KEY (tag))|;
 
 397     $dbh->do($query) || $form->dberror($query);
 
 400   $main::lxdebug->leave_sub();
 
 404   my ($self, %params) = @_;
 
 406   my $form            = $params{form};
 
 407   my $dbupdater       = $params{updater};
 
 408   my $db              = $params{database};
 
 409   my $silent          = $params{silent};
 
 411   map { $_->{description} = SL::Iconv::convert($_->{charset}, 'UTF-8', $_->{description}) } values %{ $dbupdater->{all_controls} };
 
 413   &dbconnect_vars($form, $db);
 
 415   # Flush potentially held database locks.
 
 416 #   $form->get_standard_dbh->commit;
 
 418   my $dbh = SL::DBConnect->connect($form->{dbconnect}, $form->{dbuser}, $form->{dbpasswd}, SL::DBConnect->get_options) or $form->dberror;
 
 420   $dbh->do($form->{dboptions}) if ($form->{dboptions});
 
 422   $self->create_schema_info_table($form, $dbh);
 
 424   my @upgradescripts = $dbupdater->unapplied_upgrade_scripts($dbh);
 
 426   foreach my $control (@upgradescripts) {
 
 427     # Apply upgrade. Control will only return to us if the upgrade has
 
 428     # been applied correctly and if the update has not requested user
 
 430     $main::lxdebug->message(LXDebug->DEBUG2(), "Applying Update $control->{file}");
 
 431     print $form->parse_html_template("dbupgrade/upgrade_message2", $control) unless $silent;
 
 433     $dbupdater->process_file($dbh, "sql/Pg-upgrade2/$control->{file}", $control);
 
 443 sub get_default_myconfig {
 
 444   my ($self_or_class, %user_config) = @_;
 
 445   my $defaults = SL::DefaultManager->new($::lx_office_conf{system}->{default_manager});
 
 448     countrycode  => $defaults->language('de'),
 
 449     css_path     => 'css',      # Needed for menunew, see SL::Layout::Base::get_stylesheet_for_user
 
 450     dateformat   => $defaults->dateformat('dd.mm.yy'),
 
 451     numberformat => $defaults->numberformat('1.000,00'),
 
 452     stylesheet   => $defaults->stylesheet('kivitendo.css'),
 
 453     timeformat   => $defaults->timeformat('hh:mm'),