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
 
  16 # This program is free software; you can redistribute it and/or modify
 
  17 # it under the terms of the GNU General Public License as published by
 
  18 # the Free Software Foundation; either version 2 of the License, or
 
  19 # (at your option) any later version.
 
  21 # This program is distributed in the hope that it will be useful,
 
  22 # but WITHOUT ANY WARRANTY; without even the implied warranty of
 
  23 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 
  24 # GNU General Public License for more details.
 
  25 # You should have received a copy of the GNU General Public License
 
  26 # along with this program; if not, write to the Free Software
 
  27 # Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
 
  28 #======================================================================
 
  31 # add/edit/delete users
 
  33 #======================================================================
 
  37 use English qw(-no_match_vars);
 
  44 use POSIX qw(strftime);
 
  48 use SL::Auth::PasswordPolicy;
 
  58 require "bin/mozilla/common.pl";
 
  59 require "bin/mozilla/admin_groups.pl";
 
  60 require "bin/mozilla/admin_printer.pl";
 
  66 #  $locale->text('periodic')
 
  67 #  $locale->text('income')
 
  68 #  $locale->text('perpetual')
 
  69 #  $locale->text('balance')
 
  77   $::lxdebug->enter_sub;
 
  78   my $session_result = shift;
 
  84   $::auth->store_root_credentials_in_session($form->{rpw}) if $session_result == SL::Auth->SESSION_OK;
 
  86   $form->{stylesheet} = "lx-office-erp.css";
 
  87   $form->{favicon}    = "favicon.ico";
 
  89   if ($form->{action}) {
 
  90     if ($auth->authenticate_root($form->{rpw}) != $auth->OK()) {
 
  91       $form->{error_message} = $locale->text('Incorrect Password!');
 
  92       $auth->delete_session_value('rpw');
 
  95       if ($auth->session_tables_present()) {
 
  96         $::auth->store_root_credentials_in_session($::form->{rpw});
 
  97         delete $::form->{rpw};
 
  98         _apply_dbupgrade_scripts();
 
 101       call_sub($locale->findsub($form->{action}));
 
 104     # if there are no drivers bail out
 
 105     $form->error($locale->text('No Database Drivers available!'))
 
 106       unless (User->dbdrivers);
 
 110   $::lxdebug->leave_sub;
 
 114   my $form   = $main::form;
 
 115   my $locale = $main::locale;
 
 117   $form->{title} = qq|Lx-Office ERP $form->{version} | . $locale->text('Administration');
 
 120   print $form->parse_html_template('admin/adminlogin');
 
 124   check_auth_db_and_tables();
 
 129   $main::auth->destroy_session();
 
 133 sub check_auth_db_and_tables {
 
 134   my $form   = $main::form;
 
 135   my $locale = $main::locale;
 
 139   map { $params{"db_${_}"} = $main::auth->{DB_config}->{$_} } keys %{ $auth->{DB_config} };
 
 141   if (!$main::auth->check_database()) {
 
 142     $form->{title} = $locale->text('Authentification database creation');
 
 144     print $form->parse_html_template('admin/check_auth_database', \%params);
 
 149   if (!$main::auth->check_tables()) {
 
 150     $form->{title} = $locale->text('Authentification tables creation');
 
 152     print $form->parse_html_template('admin/check_auth_tables', \%params);
 
 157   my $memberfile = $::lx_office_conf{paths}->{memberfile};
 
 158   if (-f $memberfile) {
 
 161     if ($memberfile =~ m|^.*/|) {
 
 165     my $backupdir = "${memberdir}member-file-migration";
 
 167     $form->{title} = $locale->text('User data migration');
 
 169     print $form->parse_html_template('admin/user_migration', { 'memberfile' => $memberfile,
 
 170                                                                'backupdir'  => $backupdir });
 
 177   my $form = $main::form;
 
 179   $main::auth->create_database('superuser'          => $form->{db_superuser},
 
 180                                'superuser_password' => $form->{db_superuser_password},
 
 181                                'template'           => $form->{db_template});
 
 185 sub create_auth_tables {
 
 186   my $form   = $main::form;
 
 187   my $locale = $main::locale;
 
 189   $main::auth->create_tables();
 
 190   $main::auth->set_session_value('rpw', $form->{rpw});
 
 191   $main::auth->create_or_refresh_session();
 
 193   my $memberfile = $::lx_office_conf{paths}->{memberfile};
 
 194   if (!-f $memberfile) {
 
 195     # New installation -- create a standard group with full access
 
 198       'name'        => $locale->text('Full Access'),
 
 199       'description' => $locale->text('Full access to all functions'),
 
 200       'rights'      => { map { $_ => 1 } SL::Auth::all_rights() },
 
 201       'members'     => [ map { $_->{id} } values %members ],
 
 204     $main::auth->save_group($group);
 
 207   _apply_dbupgrade_scripts();
 
 212   $main::lxdebug->enter_sub();
 
 214   my $form      = $main::form;
 
 215   my $locale    = $main::locale;
 
 219   my $memberfile = $::lx_office_conf{paths}->{memberfile};
 
 220   if ($memberfile =~ m|^.*/|) {
 
 224   my $backupdir = "${memberdir}member-file-migration";
 
 226   if (! -d $backupdir && !mkdir $backupdir, 0700) {
 
 227     $form->error(sprintf($locale->text('The directory "%s" could not be created:\n%s'), $backupdir, $!));
 
 230   copy $memberfile, "users/member-file-migration/members";
 
 232   my $in = IO::File->new($memberfile, "r");
 
 234   $form->error($locale->text('Could not open the old memberfile.')) if (!$in);
 
 236   my (%members, $login);
 
 245       $login =~ s/(\[|\])//g;
 
 249       $members{$login} = { "login" => $login };
 
 253     if ($login && m/=/) {
 
 254       my ($key, $value) = split m/\s*=\s*/, $_, 2;
 
 259       $value =~ s|\\n|\n|g;
 
 261       $members{$login}->{$key} = $value;
 
 267   delete $members{"root login"};
 
 269   map { $_->{dbpasswd} = unpack 'u', $_->{dbpasswd} } values %members;
 
 271   while (my ($login, $params) = each %members) {
 
 272     $main::auth->save_user($login, %{ $params });
 
 273     $main::auth->change_password($login, $params->{password}, 1);
 
 275     my $conf_file = "${memberdir}${login}.conf";
 
 278       copy   $conf_file, "${backupdir}/${login}.conf";
 
 285   my @member_list = sort { lc $a->{login} cmp lc $b->{login} } values %members;
 
 287   $form->{title} = $locale->text('User data migration');
 
 289   print $form->parse_html_template('admin/user_migration_done', { 'MEMBERS' => \@member_list });
 
 291   $main::lxdebug->leave_sub();
 
 294 sub create_standard_group_ask {
 
 295   my $form   = $main::form;
 
 296   my $locale = $main::locale;
 
 298   $form->{title} = $locale->text('Create a standard group');
 
 301   print $form->parse_html_template("admin/create_standard_group_ask");
 
 304 sub create_standard_group {
 
 305   my $form    = $main::form;
 
 306   my $locale  = $main::locale;
 
 308   my %members = $main::auth->read_all_users();
 
 310   my $groups  = $main::auth->read_groups();
 
 312   foreach my $group (values %{$groups}) {
 
 313     if (($form->{group_id} != $group->{id})
 
 314         && ($form->{name} eq $group->{name})) {
 
 315       $form->show_generic_error($locale->text("A group with that name does already exist."));
 
 320     'name'        => $locale->text('Full Access'),
 
 321     'description' => $locale->text('Full access to all functions'),
 
 322     'rights'      => { map { $_ => 1 } SL::Auth::all_rights() },
 
 323     'members'     => [ map { $_->{id} } values %members ],
 
 326   $main::auth->save_group($group);
 
 328   user_migration_complete(1);
 
 331 sub dont_create_standard_group {
 
 332   user_migration_complete(0);
 
 335 sub user_migration_complete {
 
 336   my $standard_group_created = shift;
 
 338   my $form                   = $main::form;
 
 339   my $locale                 = $main::locale;
 
 341   $form->{title} = $locale->text('User migration complete');
 
 344   print $form->parse_html_template('admin/user_migration_complete', { 'standard_group_created' => $standard_group_created });
 
 348   my $form    = $main::form;
 
 349   my $locale  = $main::locale;
 
 351   my %members = $main::auth->read_all_users();
 
 353   delete $members{"root login"};
 
 355   for (values %members) {
 
 356     $_->{templates} =~ s|.*/||;
 
 357     $_->{login_url} =  $::locale->is_utf8 ? Encode::encode('utf-8-strict', $_->{login}) : $_->{login_url};
 
 360   $form->{title}   = "Lx-Office ERP " . $locale->text('Administration');
 
 361   $form->{LOCKED}  = -e _nologin_file_name();
 
 362   $form->{MEMBERS} = [ @members{sort { lc $a cmp lc $b } keys %members} ];
 
 365   print $form->parse_html_template("admin/list_users");
 
 369   my $form         = $main::form;
 
 370   my $locale       = $main::locale;
 
 372   $form->{title}   = "Lx-Office ERP " . $locale->text('Administration') . " / " . $locale->text('Add User');
 
 374 # Note: Menu Style 'v3' is not compatible to all browsers!
 
 375 # "menustyle"    => "old" sets the HTML Menu to default.
 
 378     "countrycode"  => "de",
 
 379     "numberformat" => "1.000,00",
 
 380     "dateformat"   => "dd.mm.yy",
 
 381     "stylesheet"   => "lx-office-erp.css",
 
 382     "menustyle"    => "old",
 
 383     dbport         => $::auth->{DB_config}->{port} || 5432,
 
 384     dbuser         => $::auth->{DB_config}->{user} || 'lxoffice',
 
 385     dbhost         => $::auth->{DB_config}->{host} || 'localhost',
 
 389   edit_user_form($myconfig);
 
 393   my $form       = $main::form;
 
 394   my $locale     = $main::locale;
 
 396   $form->{title} = "Lx-Office ERP " . $locale->text('Administration') . " / " . $locale->text('Edit User');
 
 399   $form->isblank("login", $locale->text("The login is missing."));
 
 402   my $myconfig = new User($form->{login});
 
 404   # strip basedir from templates directory
 
 405   $myconfig->{templates} =~ s|.*/||;
 
 407   edit_user_form($myconfig);
 
 413   my $form       = $main::form;
 
 414   my $locale     = $main::locale;
 
 416   my @valid_dateformats = qw(mm-dd-yy mm/dd/yy dd-mm-yy dd/mm/yy dd.mm.yy yyyy-mm-dd);
 
 417   $form->{ALL_DATEFORMATS} = [ map { { "format" => $_, "selected" => $_ eq $myconfig->{dateformat} } } @valid_dateformats ];
 
 419   my @valid_numberformats = ('1,000.00', '1000.00', '1.000,00', '1000,00');
 
 420   $form->{ALL_NUMBERFORMATS} = [ map { { "format" => $_, "selected" => $_ eq $myconfig->{numberformat} } } @valid_numberformats ];
 
 422   my %countrycodes = User->country_codes;
 
 423   $form->{ALL_COUNTRYCODES} = [];
 
 424   foreach my $countrycode (sort { $countrycodes{$a} cmp $countrycodes{$b} } keys %countrycodes) {
 
 425     push @{ $form->{ALL_COUNTRYCODES} }, { "value"    => $countrycode,
 
 426                                            "name"     => $countrycodes{$countrycode},
 
 427                                            "selected" => $countrycode eq $myconfig->{countrycode} };
 
 430   # is there a templates basedir
 
 431   if (!-d $::lx_office_conf{paths}->{templates}) {
 
 432     $form->error(sprintf($locale->text("The directory %s does not exist."), $::lx_office_conf{paths}->{templates}));
 
 435   opendir TEMPLATEDIR, $::lx_office_conf{paths}->{templates} or $form->error($::lx_office_conf{paths}->{templates} . " : $ERRNO");
 
 436   my @all     = readdir(TEMPLATEDIR);
 
 437   my @alldir  = sort grep { -d ($::lx_office_conf{paths}->{templates} . "/$_") && !/^\.\.?$/ } @all;
 
 438   closedir TEMPLATEDIR;
 
 440   @alldir = grep !/\.(html|tex|sty|odt|xml|txb)$/, @alldir;
 
 441   @alldir = grep !/^(webpages|print|\.svn)$/, @alldir;
 
 443   $form->{ALL_TEMPLATES} = [ map { { "name", => $_, "selected" => $_ eq $myconfig->{templates} } } @alldir ];
 
 446   opendir TEMPLATEDIR, "$::lx_office_conf{paths}->{templates}/print" or $form->error("$::lx_office_conf{paths}->{templates}/print" . " : $ERRNO");
 
 447   my @allmaster = readdir(TEMPLATEDIR);
 
 448   closedir TEMPLATEDIR;
 
 450   @allmaster  = sort grep { -d ("$::lx_office_conf{paths}->{templates}/print" . "/$_") && !/^\.\.?$/ } @allmaster;
 
 451   @allmaster = reverse grep !/Default/, @allmaster;
 
 452   push @allmaster, 'Default';
 
 453   @allmaster = reverse @allmaster;
 
 455   foreach my $item (@allmaster) {
 
 456     push @{ $form->{ALL_MASTER_TEMPLATES} }, { "name" => $item, "selected" => $item eq "German" };
 
 459   # css dir has styles that are not intended as general layouts.
 
 460   # reverting to hardcoded list
 
 461   $form->{ALL_STYLESHEETS} = [ map { { "name" => $_, "selected" => $_ eq $myconfig->{stylesheet} } } qw(lx-office-erp.css Win2000.css) ];
 
 463   $form->{"menustyle_" . $myconfig->{menustyle} } = 1;
 
 465   map { $form->{"myc_${_}"} = $myconfig->{$_} } keys %{ $myconfig };
 
 470     my $user_id    = $main::auth->get_user_id($form->{login});
 
 471     my $all_groups = $main::auth->read_groups();
 
 473     foreach my $group (values %{ $all_groups }) {
 
 474       push @{ $groups }, $group if (grep { $user_id == $_ } @{ $group->{members} });
 
 477     $groups = [ sort { lc $a->{name} cmp lc $b->{name} } @{ $groups } ];
 
 480   $form->{CAN_CHANGE_PASSWORD} = $main::auth->can_change_password();
 
 483   print $form->parse_html_template("admin/edit_user", { 'GROUPS' => $groups });
 
 487   my $form          = $main::form;
 
 488   my $locale        = $main::locale;
 
 490   $form->{dbdriver} = 'Pg';
 
 492   # no spaces allowed in login name
 
 493   $form->{login} =~ s|\s||g;
 
 494   $form->isblank("login", $locale->text('Login name missing!'));
 
 496   # check for duplicates
 
 497   if (!$form->{edit}) {
 
 498     my %members = $main::auth->read_all_users();
 
 499     if ($members{$form->{login}}) {
 
 500       $form->show_generic_error($locale->text('Another user with the login #1 does already exist.', $form->{login}), 'back_button' => 1);
 
 504   # no spaces allowed in directories
 
 505   ($form->{newtemplates}) = split / /, $form->{newtemplates};
 
 507   if ($form->{newtemplates}) {
 
 508     $form->{templates} = $form->{newtemplates};
 
 511       ($form->{usetemplates}) ? $form->{usetemplates} : $form->{login};
 
 515   if (!-d $::lx_office_conf{paths}->{templates}) {
 
 516     $form->error(sprintf($locale->text("The directory %s does not exist."), $::lx_office_conf{paths}->{templates}));
 
 519   # add base directory to $form->{templates}
 
 520   $form->{templates} =~ s|.*/||;
 
 521   $form->{templates} =  $::lx_office_conf{paths}->{templates} . "/$form->{templates}";
 
 523   my $myconfig = new User($form->{login});
 
 525   $form->isblank("dbname", $locale->text('Dataset missing!'));
 
 526   $form->isblank("dbuser", $locale->text('Database User missing!'));
 
 528   foreach my $item (keys %{$form}) {
 
 529     $myconfig->{$item} = $form->{$item};
 
 532   delete $myconfig->{stylesheet};
 
 533   if ($form->{userstylesheet}) {
 
 534     $myconfig->{stylesheet} = $form->{userstylesheet};
 
 537   $myconfig->save_member();
 
 539   $form->{templates}       =~ s|.*/||;
 
 540   $form->{templates}       =  $::lx_office_conf{paths}->{templates} . "/$form->{templates}";
 
 541   $form->{mastertemplates} =~ s|.*/||;
 
 543   # create user template directory and copy master files
 
 544   if (!-d "$form->{templates}") {
 
 547     if (mkdir "$form->{templates}", oct("771")) {
 
 551       # copy templates to the directory
 
 553       my $oldcurrdir = getcwd();
 
 554       if (!chdir("$::lx_office_conf{paths}->{templates}/print/$form->{mastertemplates}")) {
 
 555         $form->error("$ERRNO: chdir $::lx_office_conf{paths}->{templates}/print/$form->{mastertemplates}");
 
 558       my $newdir = File::Spec->catdir($oldcurrdir, $form->{templates});
 
 566             if (!mkdir (File::Spec->catdir($newdir, $File::Find::name))) {
 
 568               $form->error("$ERRNO: mkdir $File::Find::name");
 
 571             if (!symlink (readlink($_),
 
 572                           File::Spec->catfile($newdir, $File::Find::name))) {
 
 574               $form->error("$ERRNO: symlink $File::Find::name");
 
 577             if (!copy($_, File::Spec->catfile($newdir, $File::Find::name))) {
 
 579               $form->error("$ERRNO: cp $File::Find::name");
 
 587       $form->error("$ERRNO: $form->{templates}");
 
 591   # Add new user to his groups.
 
 592   if (ref $form->{new_user_group_ids} eq 'ARRAY') {
 
 593     my $all_groups = $main::auth->read_groups();
 
 594     my %user       = $main::auth->read_user($form->{login});
 
 596     foreach my $group_id (@{ $form->{new_user_group_ids} }) {
 
 597       my $group = $all_groups->{$group_id};
 
 601       push @{ $group->{members} }, $user{id};
 
 602       $main::auth->save_group($group);
 
 606   if ($main::auth->can_change_password()
 
 607       && defined $form->{new_password}
 
 608       && ($form->{new_password} ne '********')) {
 
 609     my $verifier = SL::Auth::PasswordPolicy->new;
 
 610     my $result   = $verifier->verify($form->{new_password}, 1);
 
 612     if ($result != SL::Auth::PasswordPolicy->OK()) {
 
 613       $form->error($::locale->text('The settings were saved, but the password was not changed.') . ' ' . join(' ', $verifier->errors($result)));
 
 616     $main::auth->change_password($form->{login}, $form->{new_password});
 
 619   $form->redirect($locale->text('User saved!'));
 
 622 sub save_user_as_new {
 
 623   my $form       = $main::form;
 
 625   $form->{login} = $form->{new_user_login};
 
 626   delete @{$form}{qw(edit new_user_login)};
 
 632   my $form      = $main::form;
 
 633   my $locale    = $main::locale;
 
 635   my %members   = $main::auth->read_all_users();
 
 636   my $templates = $members{$form->{login}}->{templates};
 
 638   $main::auth->delete_user($form->{login});
 
 641     my $templates_in_use = 0;
 
 643     foreach my $login (keys %members) {
 
 644       next if $form->{login} eq $login;
 
 645       next if $members{$login}->{templates} ne $templates;
 
 646       $templates_in_use = 1;
 
 650     if (!$templates_in_use && -d $templates) {
 
 651       unlink <$templates/*>;
 
 656   $form->redirect($locale->text('User deleted!'));
 
 664   return ($login) ? $login : undef;
 
 670   my ($null, $value) = split(/=/, $line, 2);
 
 673   $value =~ s/\s#.*//g;
 
 675   # remove any trailing whitespace
 
 676   $value =~ s/^\s*(.*?)\s*$/$1/;
 
 681 sub pg_database_administration {
 
 682   my $form = $main::form;
 
 684   $form->{dbdriver} = 'Pg';
 
 689 sub dbselect_source {
 
 690   my $form           = $main::form;
 
 691   my $locale         = $main::locale;
 
 693   $form->{dbport}    = $::auth->{DB_config}->{port} || 5432;
 
 694   $form->{dbuser}    = $::auth->{DB_config}->{user} || 'lxoffice';
 
 695   $form->{dbdefault} = 'template1';
 
 696   $form->{dbhost}    = $::auth->{DB_config}->{host} || 'localhost';
 
 698   $form->{title}     = "Lx-Office ERP / " . $locale->text('Database Administration');
 
 700   # Intentionnaly disabled unless fixed to work with the authentication DB.
 
 701   $form->{ALLOW_DBBACKUP} = 0; # "$pg_dump_exe" ne "DISABLED";
 
 704   print $form->parse_html_template("admin/dbadmin");
 
 707 sub test_db_connection {
 
 708   my $form   = $main::form;
 
 709   my $locale = $main::locale;
 
 711   $form->{dbdriver} = 'Pg';
 
 712   User::dbconnect_vars($form, $form->{dbname});
 
 714   my $dbh = DBI->connect($form->{dbconnect}, $form->{dbuser}, $form->{dbpasswd});
 
 716   $form->{connection_ok} = $dbh ? 1 : 0;
 
 717   $form->{errstr}        = $DBI::errstr;
 
 719   $dbh->disconnect() if ($dbh);
 
 721   $form->{title} = $locale->text('Database Connection Test');
 
 723   print $form->parse_html_template("admin/test_db_connection");
 
 727   call_sub($main::form->{"nextsub"});
 
 731   my $form              = $main::form;
 
 732   my $locale            = $main::locale;
 
 734   $form->{title}        = "Lx-Office ERP " . $locale->text('Database Administration') . " / " . $locale->text('Update Dataset');
 
 736   my @need_updates      = User->dbneedsupdate($form);
 
 737   $form->{NEED_UPDATES} = \@need_updates;
 
 738   $form->{ALL_UPDATED}  = !scalar @need_updates;
 
 741   print $form->parse_html_template("admin/update_dataset");
 
 745   my $form            = $main::form;
 
 746   my $locale          = $main::locale;
 
 748   $form->{stylesheet} = "lx-office-erp.css";
 
 749   $form->{title}      = $locale->text("Dataset upgrade");
 
 752   my $rowcount           = $form->{rowcount} * 1;
 
 753   my @update_rows        = grep { $form->{"update_$_"} } (1 .. $rowcount);
 
 754   $form->{NOTHING_TO_DO} = !scalar @update_rows;
 
 755   my $saved_form         = save_form();
 
 759   print $form->parse_html_template("admin/dbupgrade_all_header");
 
 761   foreach my $i (@update_rows) {
 
 762     restore_form($saved_form);
 
 765     map { $form->{$_} = $::myconfig{$_} = $form->{"${_}_${i}"} } qw(dbname dbdriver dbhost dbport dbuser dbpasswd);
 
 767     print $form->parse_html_template("admin/dbupgrade_header");
 
 769     $form->{dbupdate}        = $form->{dbname};
 
 770     $form->{$form->{dbname}} = 1;
 
 772     User->dbupdate($form);
 
 773     User->dbupdate2($form, SL::DBUpgrade2->new(form => $form, dbdriver => $form->{dbdriver})->parse_dbupdate_controls);
 
 775     print $form->parse_html_template("admin/dbupgrade_footer");
 
 778   print $form->parse_html_template("admin/dbupgrade_all_done");
 
 782   my $form           = $main::form;
 
 783   my $locale         = $main::locale;
 
 785   $form->{dbsources} = join " ", map { "[${_}]" } sort User->dbsources($form);
 
 787   $form->{CHARTS}    = [];
 
 789   opendir SQLDIR, "sql/." or $form->error($ERRNO);
 
 790   foreach my $item (sort grep /-chart\.sql\z/, readdir SQLDIR) {
 
 791     next if ($item eq 'Default-chart.sql');
 
 792     $item =~ s/-chart\.sql//;
 
 793     push @{ $form->{CHARTS} }, { "name"     => $item,
 
 794                                  "selected" => $item eq "Germany-DATEV-SKR03EU" };
 
 798   $form->{ACCOUNTING_METHODS} = [];
 
 799   foreach my $item ( qw(accrual cash) ) {
 
 800     push @{ $form->{ACCOUNTING_METHODS} }, { "name"     => $item,
 
 801                                  "selected" => $item eq "cash" };
 
 804   $form->{INVENTORY_SYSTEMS} = [];
 
 805   foreach my $item ( qw(perpetual periodic) ) {
 
 806     push @{ $form->{INVENTORY_SYSTEMS} }, { "name"     => $item,
 
 807                                  "selected" => $item eq "periodic" };
 
 810   $form->{PROFIT_DETERMINATIONS} = [];
 
 811   foreach my $item ( qw(balance income) ) {
 
 812     push @{ $form->{PROFIT_DETERMINATIONS} }, { "name"     => $item,
 
 813                                  "selected" => $item eq "income" };
 
 816   my $default_charset = $::lx_office_conf{system}->{dbcharset};
 
 817   $default_charset ||= Common::DEFAULT_CHARSET;
 
 819   my $cluster_encoding = User->dbclusterencoding($form);
 
 820   if ($cluster_encoding && ($cluster_encoding =~ m/^(?:UTF-?8|UNICODE)$/i)) {
 
 821     if ($::lx_office_conf{system}->{dbcharset} !~ m/^UTF-?8$/i) {
 
 822       $form->show_generic_error($locale->text('The selected  PostgreSQL installation uses UTF-8 as its encoding. ' .
 
 823                                               'Therefore you have to configure Lx-Office to use UTF-8 as well.'),
 
 827     $form->{FORCE_DBENCODING} = 'UNICODE';
 
 830     $form->{DBENCODINGS} = [];
 
 832     foreach my $encoding (@Common::db_encodings) {
 
 833       push @{ $form->{DBENCODINGS} }, { "dbencoding" => $encoding->{dbencoding},
 
 834                                         "label"      => $encoding->{label},
 
 835                                         "selected"   => $encoding->{charset} eq $default_charset };
 
 839   $form->{title} = "Lx-Office ERP " . $locale->text('Database Administration') . " / " . $locale->text('Create Dataset');
 
 842   print $form->parse_html_template("admin/create_dataset");
 
 846   my $form   = $main::form;
 
 847   my $locale = $main::locale;
 
 849   $form->isblank("db", $locale->text('Dataset missing!'));
 
 851   User->dbcreate(\%$form);
 
 853   $form->{title} = "Lx-Office ERP " . $locale->text('Database Administration') . " / " . $locale->text('Create Dataset');
 
 856   print $form->parse_html_template("admin/dbcreate");
 
 860   my $form      = $main::form;
 
 861   my $locale    = $main::locale;
 
 863   my @dbsources = User->dbsources_unused($form);
 
 864   $form->error($locale->text('Nothing to delete!')) unless @dbsources;
 
 866   $form->{title}     = "Lx-Office ERP " . $locale->text('Database Administration') . " / " . $locale->text('Delete Dataset');
 
 867   $form->{DBSOURCES} = [ map { { "name", $_ } } sort @dbsources ];
 
 870   print $form->parse_html_template("admin/delete_dataset");
 
 874   my $form   = $main::form;
 
 875   my $locale = $main::locale;
 
 878     $form->error($locale->text('No Dataset selected!'));
 
 881   User->dbdelete(\%$form);
 
 883   $form->{title} = "Lx-Office ERP " . $locale->text('Database Administration') . " / " . $locale->text('Delete Dataset');
 
 885   print $form->parse_html_template("admin/dbdelete");
 
 889   my $form       = $main::form;
 
 890   my $locale     = $main::locale;
 
 892   $form->{title} = "Lx-Office ERP " . $locale->text('Database Administration') . " / " . $locale->text('Backup Dataset');
 
 894   if ($::lx_office_conf{applications}->{pg_dump} eq "DISABLED") {
 
 895     $form->error($locale->text('Database backups and restorations are disabled in the configuration.'));
 
 898   my @dbsources         = sort User->dbsources($form);
 
 899   $form->{DATABASES}    = [ map { { "dbname" => $_ } } @dbsources ];
 
 900   $form->{NO_DATABASES} = !scalar @dbsources;
 
 902   my $username  = getpwuid $UID || "unknown-user";
 
 903   my $hostname  = hostname() || "unknown-host";
 
 904   $form->{from} = "Lx-Office Admin <${username}\@${hostname}>";
 
 907   print $form->parse_html_template("admin/backup_dataset");
 
 910 sub backup_dataset_start {
 
 911   my $form       = $main::form;
 
 912   my $locale     = $main::locale;
 
 914   $form->{title} = "Lx-Office ERP " . $locale->text('Database Administration') . " / " . $locale->text('Backup Dataset');
 
 916   my $pg_dump_exe = $::lx_office_conf{applications}->{pg_dump} || "pg_dump";
 
 918   if ("$pg_dump_exe" eq "DISABLED") {
 
 919     $form->error($locale->text('Database backups and restorations are disabled in the configuration.'));
 
 922   $form->isblank("dbname", $locale->text('The dataset name is missing.'));
 
 923   $form->isblank("to", $locale->text('The email address is missing.')) if $form->{destination} eq "email";
 
 925   my $tmpdir = "/tmp/lx_office_backup_" . Common->unique_id();
 
 926   mkdir $tmpdir, 0700 || $form->error($locale->text('A temporary directory could not be created:') . " $ERRNO");
 
 928   my $pgpass = IO::File->new("${tmpdir}/.pgpass", O_WRONLY | O_CREAT, 0600);
 
 932     $form->error($locale->text('A temporary file could not be created:') . " $ERRNO");
 
 935   print $pgpass "$form->{dbhost}:$form->{dbport}:$form->{dbname}:$form->{dbuser}:$form->{dbpasswd}\n";
 
 938   $ENV{HOME} = $tmpdir;
 
 940   my @args = ("-Ft", "-c", "-o", "-h", $form->{dbhost}, "-U", $form->{dbuser});
 
 941   push @args, ("-p", $form->{dbport}) if ($form->{dbport});
 
 942   push @args, $form->{dbname};
 
 944   my $cmd  = "$pg_dump_exe " . join(" ", map { s/\\/\\\\/g; s/\"/\\\"/g; $_ } @args);
 
 945   my $name = "dataset_backup_$form->{dbname}_" . strftime("%Y%m%d", localtime()) . ".tar";
 
 947   if ($form->{destination} ne "email") {
 
 948     my $in = IO::File->new("$cmd |");
 
 951       unlink "${tmpdir}/.pgpass";
 
 954       $form->error($locale->text('The pg_dump process could not be started.'));
 
 957     print "content-type: application/x-tar\n";
 
 958     print "content-disposition: attachment; filename=\"${name}\"\n\n";
 
 960     while (my $line = <$in>) {
 
 966     unlink "${tmpdir}/.pgpass";
 
 970     my $tmp = $tmpdir . "/dump_" . Common::unique_id();
 
 972     if (system("$cmd > $tmp") != 0) {
 
 973       unlink "${tmpdir}/.pgpass", $tmp;
 
 976       $form->error($locale->text('The pg_dump process could not be started.'));
 
 979     my $mail = new Mailer;
 
 981     map { $mail->{$_} = $form->{$_} } qw(from to cc subject message);
 
 983     $mail->{charset}     = $::lx_office_conf{system}->{dbcharset} || Common::DEFAULT_CHARSET;
 
 984     $mail->{attachments} = [ { "filename" => $tmp, "name" => $name } ];
 
 987     unlink "${tmpdir}/.pgpass", $tmp;
 
 990     $form->{title} = "Lx-Office ERP " . $locale->text('Database Administration') . " / " . $locale->text('Backup Dataset');
 
 993     print $form->parse_html_template("admin/backup_dataset_email_done");
 
 997 sub restore_dataset {
 
 998   my $form       = $main::form;
 
 999   my $locale     = $main::locale;
 
1001   $form->{title} = "Lx-Office ERP " . $locale->text('Database Administration') . " / " . $locale->text('Restore Dataset');
 
1003   if ($::lx_office_conf{applications}->{pg_restore} eq "DISABLED") {
 
1004     $form->error($locale->text('Database backups and restorations are disabled in the configuration.'));
 
1007   my $default_charset   = $::lx_office_conf{system}->{dbcharset};
 
1008   $default_charset    ||= Common::DEFAULT_CHARSET;
 
1010   $form->{DBENCODINGS}  = [];
 
1012   foreach my $encoding (@Common::db_encodings) {
 
1013     push @{ $form->{DBENCODINGS} }, { "dbencoding" => $encoding->{dbencoding},
 
1014                                       "label"      => $encoding->{label},
 
1015                                       "selected"   => $encoding->{charset} eq $default_charset };
 
1019   print $form->parse_html_template("admin/restore_dataset");
 
1022 sub restore_dataset_start {
 
1023   my $form       = $main::form;
 
1024   my $locale     = $main::locale;
 
1026   $form->{title} = "Lx-Office ERP " . $locale->text('Database Administration') . " / " . $locale->text('Restore Dataset');
 
1028   my $pg_restore_exe = $::lx_office_conf{applications}->{pg_restore} || "pg_restore";
 
1030   if ("$pg_restore_exe" eq "DISABLED") {
 
1031     $form->error($locale->text('Database backups and restorations are disabled in the configuration.'));
 
1034   $form->isblank("new_dbname", $locale->text('The dataset name is missing.'));
 
1035   $form->isblank("content", $locale->text('No backup file has been uploaded.'));
 
1037   # Create temporary directories. Write the backup file contents to a temporary
 
1038   # file. Create a .pgpass file with the username and password for the pg_restore
 
1041   my $tmpdir = "/tmp/lx_office_backup_" . Common->unique_id();
 
1042   mkdir $tmpdir, 0700 || $form->error($locale->text('A temporary directory could not be created:') . " $ERRNO");
 
1044   my $pgpass = IO::File->new("${tmpdir}/.pgpass", O_WRONLY | O_CREAT, 0600);
 
1048     $form->error($locale->text('A temporary file could not be created:') . " $ERRNO");
 
1051   print $pgpass "$form->{dbhost}:$form->{dbport}:$form->{new_dbname}:$form->{dbuser}:$form->{dbpasswd}\n";
 
1054   $ENV{HOME} = $tmpdir;
 
1056   my $tmp = $tmpdir . "/dump_" . Common::unique_id();
 
1059   if (substr($form->{content}, 0, 2) eq "\037\213") {
 
1060     $tmpfile = IO::File->new("| gzip -d > $tmp");
 
1064     $tmpfile = IO::File->new($tmp, O_WRONLY | O_CREAT | O_BINARY, 0600);
 
1068     unlink "${tmpdir}/.pgpass";
 
1071     $form->error($locale->text('A temporary file could not be created:') . " $ERRNO");
 
1074   print $tmpfile $form->{content};
 
1077   delete $form->{content};
 
1079   # Try to connect to the database. Find out if a database with the same name exists.
 
1080   # If yes, then drop the existing database. Create a new one with the name and encoding
 
1081   # given by the user.
 
1083   User::dbconnect_vars($form, "template1");
 
1085   my %myconfig = map { $_ => $form->{$_} } grep /^db/, keys %{ $form };
 
1086   my $dbh      = $form->dbconnect(\%myconfig) || $form->dberror();
 
1090   $form->{new_dbname} =~ s|[^a-zA-Z0-9_\-]||g;
 
1092   $query = qq|SELECT COUNT(*) FROM pg_database WHERE datname = ?|;
 
1093   my ($count) = selectrow_query($form, $dbh, $query, $form->{new_dbname});
 
1095     do_query($form, $dbh, qq|DROP DATABASE $form->{new_dbname}|);
 
1099   foreach my $item (@Common::db_encodings) {
 
1100     if ($item->{dbencoding} eq $form->{dbencoding}) {
 
1105   $form->{dbencoding} = "LATIN9" unless $form->{dbencoding};
 
1107   do_query($form, $dbh, qq|CREATE DATABASE $form->{new_dbname} ENCODING ? TEMPLATE template0|, $form->{dbencoding});
 
1111   # Spawn pg_restore on the temporary file.
 
1113   my @args = ("-h", $form->{dbhost}, "-U", $form->{dbuser}, "-d", $form->{new_dbname});
 
1114   push @args, ("-p", $form->{dbport}) if ($form->{dbport});
 
1117   my $cmd = "$pg_restore_exe " . join(" ", map { s/\\/\\\\/g; s/\"/\\\"/g; $_ } @args);
 
1119   my $in = IO::File->new("$cmd 2>&1 |");
 
1122     unlink "${tmpdir}/.pgpass", $tmp;
 
1125     $form->error($locale->text('The pg_restore process could not be started.'));
 
1128   $English::AUTOFLUSH = 1;
 
1131   print $form->parse_html_template("admin/restore_dataset_start_header");
 
1133   while (my $line = <$in>) {
 
1138   $form->{retval} = $CHILD_ERROR >> 8;
 
1139   print $form->parse_html_template("admin/restore_dataset_start_footer");
 
1141   unlink "${tmpdir}/.pgpass", $tmp;
 
1146   my $form   = $main::form;
 
1147   my $locale = $main::locale;
 
1149   unlink _nologin_file_name();;
 
1151   $form->{callback} = "admin.pl?action=list_users";
 
1153   $form->redirect($locale->text('Lockfile removed!'));
 
1158   my $form   = $main::form;
 
1159   my $locale = $main::locale;
 
1161   open(FH, ">", _nologin_file_name())
 
1162     or $form->error($locale->text('Cannot create Lock!'));
 
1165   $form->{callback} = "admin.pl?action=list_users";
 
1167   $form->redirect($locale->text('Lockfile created!'));
 
1172   call_sub($main::form->{yes_nextsub});
 
1176   call_sub($main::form->{no_nextsub});
 
1180   call_sub($main::form->{add_nextsub});
 
1184   my $form = $main::form;
 
1186   $form->{edit_nextsub} ||= 'edit_user';
 
1188   call_sub($form->{edit_nextsub});
 
1192   my $form     = $main::form;
 
1194   $form->{delete_nextsub} ||= 'delete_user';
 
1196   call_sub($form->{delete_nextsub});
 
1200   my $form = $main::form;
 
1202   $form->{save_nextsub} ||= 'save_user';
 
1204   call_sub($form->{save_nextsub});
 
1208   call_sub($main::form->{back_nextsub});
 
1212   my $form   = $main::form;
 
1213   my $locale = $main::locale;
 
1215   foreach my $action (qw(create_standard_group dont_create_standard_group
 
1216                          save_user delete_user save_user_as_new)) {
 
1217     if ($form->{"action_${action}"}) {
 
1223   call_sub($form->{default_action}) if ($form->{default_action});
 
1225   $form->error($locale->text('No action defined.'));
 
1228 sub _apply_dbupgrade_scripts {
 
1229   ::end_of_request() if SL::DBUpgrade2->new(form => $::form, dbdriver => 'Pg', auth => 1)->apply_admin_dbupgrade_scripts(1);
 
1232 sub _nologin_file_name {
 
1233   return $::lx_office_conf{paths}->{userspath} . '/nologin';