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);
 
  41 use POSIX qw(strftime);
 
  45 use SL::Auth::PasswordPolicy;
 
  55 require "bin/mozilla/common.pl";
 
  56 require "bin/mozilla/admin_groups.pl";
 
  57 require "bin/mozilla/admin_printer.pl";
 
  67   $::lxdebug->enter_sub;
 
  68   my $session_result = shift;
 
  74   $::auth->store_root_credentials_in_session($form->{rpw}) if $session_result == SL::Auth->SESSION_OK;
 
  76   $form->{stylesheet} = "lx-office-erp.css";
 
  77   $form->{favicon}    = "favicon.ico";
 
  79   if ($form->{action}) {
 
  80     if ($auth->authenticate_root($form->{rpw}) != $auth->OK()) {
 
  81       $form->{error_message} = $locale->text('Incorrect Password!');
 
  82       $auth->delete_session_value('rpw');
 
  85       if ($auth->session_tables_present()) {
 
  86         $::auth->store_root_credentials_in_session($::form->{rpw});
 
  87         delete $::form->{rpw};
 
  88         _apply_dbupgrade_scripts();
 
  91       call_sub($locale->findsub($form->{action}));
 
  94     # if there are no drivers bail out
 
  95     $form->error($locale->text('No Database Drivers available!'))
 
  96       unless (User->dbdrivers);
 
 100   $::lxdebug->leave_sub;
 
 104   my $form   = $main::form;
 
 105   my $locale = $main::locale;
 
 107   $form->{title} = qq|Lx-Office ERP $form->{version} | . $locale->text('Administration');
 
 110   print $form->parse_html_template('admin/adminlogin');
 
 114   check_auth_db_and_tables();
 
 119   $main::auth->destroy_session();
 
 123 sub check_auth_db_and_tables {
 
 124   my $form   = $main::form;
 
 125   my $locale = $main::locale;
 
 129   map { $params{"db_${_}"} = $main::auth->{DB_config}->{$_} } keys %{ $auth->{DB_config} };
 
 131   if (!$main::auth->check_database()) {
 
 132     $form->{title} = $locale->text('Authentification database creation');
 
 134     print $form->parse_html_template('admin/check_auth_database', \%params);
 
 139   if (!$main::auth->check_tables()) {
 
 140     $form->{title} = $locale->text('Authentification tables creation');
 
 142     print $form->parse_html_template('admin/check_auth_tables', \%params);
 
 147   my $memberfile = $::lx_office_conf{paths}->{memberfile};
 
 148   if (-f $memberfile) {
 
 151     if ($memberfile =~ m|^.*/|) {
 
 155     my $backupdir = "${memberdir}member-file-migration";
 
 157     $form->{title} = $locale->text('User data migration');
 
 159     print $form->parse_html_template('admin/user_migration', { 'memberfile' => $memberfile,
 
 160                                                                'backupdir'  => $backupdir });
 
 167   my $form = $main::form;
 
 169   $main::auth->create_database('superuser'          => $form->{db_superuser},
 
 170                                'superuser_password' => $form->{db_superuser_password},
 
 171                                'template'           => $form->{db_template});
 
 175 sub create_auth_tables {
 
 176   my $form   = $main::form;
 
 177   my $locale = $main::locale;
 
 179   $main::auth->create_tables();
 
 180   $main::auth->set_session_value('rpw', $form->{rpw});
 
 181   $main::auth->create_or_refresh_session();
 
 183   my $memberfile = $::lx_office_conf{paths}->{memberfile};
 
 184   if (!-f $memberfile) {
 
 185     # New installation -- create a standard group with full access
 
 188       'name'        => $locale->text('Full Access'),
 
 189       'description' => $locale->text('Full access to all functions'),
 
 190       'rights'      => { map { $_ => 1 } SL::Auth::all_rights() },
 
 191       'members'     => [ map { $_->{id} } values %members ],
 
 194     $main::auth->save_group($group);
 
 197   _apply_dbupgrade_scripts();
 
 202   $main::lxdebug->enter_sub();
 
 204   my $form      = $main::form;
 
 205   my $locale    = $main::locale;
 
 209   my $memberfile = $::lx_office_conf{paths}->{memberfile};
 
 210   if ($memberfile =~ m|^.*/|) {
 
 214   my $backupdir = "${memberdir}member-file-migration";
 
 216   if (! -d $backupdir && !mkdir $backupdir, 0700) {
 
 217     $form->error(sprintf($locale->text('The directory "%s" could not be created:\n%s'), $backupdir, $!));
 
 220   copy $memberfile, "users/member-file-migration/members";
 
 222   my $in = IO::File->new($memberfile, "r");
 
 224   $form->error($locale->text('Could not open the old memberfile.')) if (!$in);
 
 226   my (%members, $login);
 
 235       $login =~ s/(\[|\])//g;
 
 239       $members{$login} = { "login" => $login };
 
 243     if ($login && m/=/) {
 
 244       my ($key, $value) = split m/\s*=\s*/, $_, 2;
 
 249       $value =~ s|\\n|\n|g;
 
 251       $members{$login}->{$key} = $value;
 
 257   delete $members{"root login"};
 
 259   map { $_->{dbpasswd} = unpack 'u', $_->{dbpasswd} } values %members;
 
 261   while (my ($login, $params) = each %members) {
 
 262     $main::auth->save_user($login, %{ $params });
 
 263     $main::auth->change_password($login, $params->{password}, 1);
 
 265     my $conf_file = "${memberdir}${login}.conf";
 
 268       copy   $conf_file, "${backupdir}/${login}.conf";
 
 275   my @member_list = sort { lc $a->{login} cmp lc $b->{login} } values %members;
 
 277   $form->{title} = $locale->text('User data migration');
 
 279   print $form->parse_html_template('admin/user_migration_done', { 'MEMBERS' => \@member_list });
 
 281   $main::lxdebug->leave_sub();
 
 284 sub create_standard_group_ask {
 
 285   my $form   = $main::form;
 
 286   my $locale = $main::locale;
 
 288   $form->{title} = $locale->text('Create a standard group');
 
 291   print $form->parse_html_template("admin/create_standard_group_ask");
 
 294 sub create_standard_group {
 
 295   my $form    = $main::form;
 
 296   my $locale  = $main::locale;
 
 298   my %members = $main::auth->read_all_users();
 
 300   my $groups  = $main::auth->read_groups();
 
 302   foreach my $group (values %{$groups}) {
 
 303     if (($form->{group_id} != $group->{id})
 
 304         && ($form->{name} eq $group->{name})) {
 
 305       $form->show_generic_error($locale->text("A group with that name does already exist."));
 
 310     'name'        => $locale->text('Full Access'),
 
 311     'description' => $locale->text('Full access to all functions'),
 
 312     'rights'      => { map { $_ => 1 } SL::Auth::all_rights() },
 
 313     'members'     => [ map { $_->{id} } values %members ],
 
 316   $main::auth->save_group($group);
 
 318   user_migration_complete(1);
 
 321 sub dont_create_standard_group {
 
 322   user_migration_complete(0);
 
 325 sub user_migration_complete {
 
 326   my $standard_group_created = shift;
 
 328   my $form                   = $main::form;
 
 329   my $locale                 = $main::locale;
 
 331   $form->{title} = $locale->text('User migration complete');
 
 334   print $form->parse_html_template('admin/user_migration_complete', { 'standard_group_created' => $standard_group_created });
 
 338   my $form    = $main::form;
 
 339   my $locale  = $main::locale;
 
 341   my %members = $main::auth->read_all_users();
 
 343   delete $members{"root login"};
 
 345   for (values %members) {
 
 346     $_->{templates} =~ s|.*/||;
 
 347     $_->{login_url} =  $::locale->is_utf8 ? Encode::encode('utf-8-strict', $_->{login}) : $_->{login_url};
 
 350   $form->{title}   = "Lx-Office ERP " . $locale->text('Administration');
 
 351   $form->{LOCKED}  = -e _nologin_file_name();
 
 352   $form->{MEMBERS} = [ @members{sort { lc $a cmp lc $b } keys %members} ];
 
 355   print $form->parse_html_template("admin/list_users");
 
 359   my $form         = $main::form;
 
 360   my $locale       = $main::locale;
 
 362   $form->{title}   = "Lx-Office ERP " . $locale->text('Administration') . " / " . $locale->text('Add User');
 
 364 # Note: Menu Style 'v3' is not compatible to all browsers!
 
 365 # "menustyle"    => "old" sets the HTML Menu to default.
 
 368     "countrycode"  => "de",
 
 369     "numberformat" => "1.000,00",
 
 370     "dateformat"   => "dd.mm.yy",
 
 371     "stylesheet"   => "lx-office-erp.css",
 
 372     "menustyle"    => "old",
 
 373     dbport         => $::auth->{DB_config}->{port} || 5432,
 
 374     dbuser         => $::auth->{DB_config}->{user} || 'lxoffice',
 
 375     dbhost         => $::auth->{DB_config}->{host} || 'localhost',
 
 379   edit_user_form($myconfig);
 
 383   my $form       = $main::form;
 
 384   my $locale     = $main::locale;
 
 386   $form->{title} = "Lx-Office ERP " . $locale->text('Administration') . " / " . $locale->text('Edit User');
 
 389   $form->isblank("login", $locale->text("The login is missing."));
 
 392   my $myconfig = new User($form->{login});
 
 394   # strip basedir from templates directory
 
 395   $myconfig->{templates} =~ s|.*/||;
 
 397   edit_user_form($myconfig);
 
 403   my $form       = $main::form;
 
 404   my $locale     = $main::locale;
 
 406   my @valid_dateformats = qw(mm-dd-yy mm/dd/yy dd-mm-yy dd/mm/yy dd.mm.yy yyyy-mm-dd);
 
 407   $form->{ALL_DATEFORMATS} = [ map { { "format" => $_, "selected" => $_ eq $myconfig->{dateformat} } } @valid_dateformats ];
 
 409   my @valid_numberformats = ('1,000.00', '1000.00', '1.000,00', '1000,00');
 
 410   $form->{ALL_NUMBERFORMATS} = [ map { { "format" => $_, "selected" => $_ eq $myconfig->{numberformat} } } @valid_numberformats ];
 
 412   my %countrycodes = User->country_codes;
 
 413   $form->{ALL_COUNTRYCODES} = [];
 
 414   foreach my $countrycode (sort { $countrycodes{$a} cmp $countrycodes{$b} } keys %countrycodes) {
 
 415     push @{ $form->{ALL_COUNTRYCODES} }, { "value"    => $countrycode,
 
 416                                            "name"     => $countrycodes{$countrycode},
 
 417                                            "selected" => $countrycode eq $myconfig->{countrycode} };
 
 420   # is there a templates basedir
 
 421   if (!-d $::lx_office_conf{paths}->{templates}) {
 
 422     $form->error(sprintf($locale->text("The directory %s does not exist."), $::lx_office_conf{paths}->{templates}));
 
 425   opendir TEMPLATEDIR, $::lx_office_conf{paths}->{templates} or $form->error($::lx_office_conf{paths}->{templates} . " : $ERRNO");
 
 426   my @all     = readdir(TEMPLATEDIR);
 
 427   my @alldir  = sort grep { -d ($::lx_office_conf{paths}->{templates} . "/$_") && !/^\.\.?$/ } @all;
 
 428   my @allhtml = sort grep { -f ($::lx_office_conf{paths}->{templates} . "/$_") &&  /\.html$/ } @all;
 
 429   closedir TEMPLATEDIR;
 
 431   @alldir = grep !/\.(html|tex|sty|odt|xml|txb)$/, @alldir;
 
 432   @alldir = grep !/^(webpages|\.svn)$/, @alldir;
 
 434   @allhtml = reverse grep !/Default/, @allhtml;
 
 435   push @allhtml, 'Default';
 
 436   @allhtml = reverse @allhtml;
 
 438   $form->{ALL_TEMPLATES} = [ map { { "name", => $_, "selected" => $_ eq $myconfig->{templates} } } @alldir ];
 
 440   my $lastitem = $allhtml[0];
 
 441   $lastitem =~ s/-.*//g;
 
 442   $form->{ALL_MASTER_TEMPLATES} = [ { "name" => $lastitem, "selected" => $lastitem eq "German" } ];
 
 443   foreach my $item (@allhtml) {
 
 445     next if ($item eq $lastitem);
 
 447     push @{ $form->{ALL_MASTER_TEMPLATES} }, { "name" => $item, "selected" => $item eq "German" };
 
 451   # css dir has styles that are not intended as general layouts.
 
 452   # reverting to hardcoded list
 
 453   $form->{ALL_STYLESHEETS} = [ map { { "name" => $_, "selected" => $_ eq $myconfig->{stylesheet} } } qw(lx-office-erp.css Win2000.css) ];
 
 455   $form->{"menustyle_" . $myconfig->{menustyle} } = 1;
 
 457   map { $form->{"myc_${_}"} = $myconfig->{$_} } keys %{ $myconfig };
 
 462     my $user_id    = $main::auth->get_user_id($form->{login});
 
 463     my $all_groups = $main::auth->read_groups();
 
 465     foreach my $group (values %{ $all_groups }) {
 
 466       push @{ $groups }, $group if (grep { $user_id == $_ } @{ $group->{members} });
 
 469     $groups = [ sort { lc $a->{name} cmp lc $b->{name} } @{ $groups } ];
 
 472   $form->{CAN_CHANGE_PASSWORD} = $main::auth->can_change_password();
 
 475   print $form->parse_html_template("admin/edit_user", { 'GROUPS' => $groups });
 
 479   my $form          = $main::form;
 
 480   my $locale        = $main::locale;
 
 482   $form->{dbdriver} = 'Pg';
 
 484   # no spaces allowed in login name
 
 485   $form->{login} =~ s|\s||g;
 
 486   $form->isblank("login", $locale->text('Login name missing!'));
 
 488   # check for duplicates
 
 489   if (!$form->{edit}) {
 
 490     my %members = $main::auth->read_all_users();
 
 491     if ($members{$form->{login}}) {
 
 492       $form->show_generic_error($locale->text('Another user with the login #1 does already exist.', $form->{login}), 'back_button' => 1);
 
 496   # no spaces allowed in directories
 
 497   ($form->{newtemplates}) = split / /, $form->{newtemplates};
 
 499   if ($form->{newtemplates}) {
 
 500     $form->{templates} = $form->{newtemplates};
 
 503       ($form->{usetemplates}) ? $form->{usetemplates} : $form->{login};
 
 507   if (!-d $::lx_office_conf{paths}->{templates}) {
 
 508     $form->error(sprintf($locale->text("The directory %s does not exist."), $::lx_office_conf{paths}->{templates}));
 
 511   # add base directory to $form->{templates}
 
 512   $form->{templates} =~ s|.*/||;
 
 513   $form->{templates} =  $::lx_office_conf{paths}->{templates} . "/$form->{templates}";
 
 515   my $myconfig = new User($form->{login});
 
 517   $form->isblank("dbname", $locale->text('Dataset missing!'));
 
 518   $form->isblank("dbuser", $locale->text('Database User missing!'));
 
 520   foreach my $item (keys %{$form}) {
 
 521     $myconfig->{$item} = $form->{$item};
 
 524   delete $myconfig->{stylesheet};
 
 525   if ($form->{userstylesheet}) {
 
 526     $myconfig->{stylesheet} = $form->{userstylesheet};
 
 529   $myconfig->save_member();
 
 531   $form->{templates}       =~ s|.*/||;
 
 532   $form->{templates}       =  $::lx_office_conf{paths}->{templates} . "/$form->{templates}";
 
 533   $form->{mastertemplates} =~ s|.*/||;
 
 535   # create user template directory and copy master files
 
 536   if (!-d "$form->{templates}") {
 
 539     if (mkdir "$form->{templates}", oct("771")) {
 
 543       # copy templates to the directory
 
 544       opendir TEMPLATEDIR, $::lx_office_conf{paths}->{templates} or $form->error($::lx_office_conf{paths}->{templates} . " : $ERRNO");
 
 545       my @templates = grep /$form->{mastertemplates}.*?\.(html|tex|sty|odt|xml|txb)$/,
 
 547       closedir TEMPLATEDIR;
 
 549       foreach my $file (@templates) {
 
 550         open(TEMP, "<", $::lx_office_conf{paths}->{templates} . "/$file")
 
 551           or $form->error($::lx_office_conf{paths}->{templates} . "/$file : $ERRNO");
 
 553         $file =~ s/\Q$form->{mastertemplates}\E-//;
 
 554         open(NEW, ">", "$form->{templates}/$file")
 
 555           or $form->error("$form->{templates}/$file : $ERRNO");
 
 557         while (my $line = <TEMP>) {
 
 564       $form->error("$ERRNO: $form->{templates}");
 
 568   # Add new user to his groups.
 
 569   if (ref $form->{new_user_group_ids} eq 'ARRAY') {
 
 570     my $all_groups = $main::auth->read_groups();
 
 571     my %user       = $main::auth->read_user($form->{login});
 
 573     foreach my $group_id (@{ $form->{new_user_group_ids} }) {
 
 574       my $group = $all_groups->{$group_id};
 
 578       push @{ $group->{members} }, $user{id};
 
 579       $main::auth->save_group($group);
 
 583   if ($main::auth->can_change_password()
 
 584       && defined $form->{new_password}
 
 585       && ($form->{new_password} ne '********')) {
 
 586     my $verifier = SL::Auth::PasswordPolicy->new;
 
 587     my $result   = $verifier->verify($form->{new_password}, 1);
 
 589     if ($result != SL::Auth::PasswordPolicy->OK()) {
 
 590       $form->error($::locale->text('The settings were saved, but the password was not changed.') . ' ' . join(' ', $verifier->errors($result)));
 
 593     $main::auth->change_password($form->{login}, $form->{new_password});
 
 596   $form->redirect($locale->text('User saved!'));
 
 599 sub save_user_as_new {
 
 600   my $form       = $main::form;
 
 602   $form->{login} = $form->{new_user_login};
 
 603   delete @{$form}{qw(edit new_user_login)};
 
 609   my $form      = $main::form;
 
 610   my $locale    = $main::locale;
 
 612   my %members   = $main::auth->read_all_users();
 
 613   my $templates = $members{$form->{login}}->{templates};
 
 615   $main::auth->delete_user($form->{login});
 
 618     my $templates_in_use = 0;
 
 620     foreach my $login (keys %members) {
 
 621       next if $form->{login} eq $login;
 
 622       next if $members{$login}->{templates} ne $templates;
 
 623       $templates_in_use = 1;
 
 627     if (!$templates_in_use && -d $templates) {
 
 628       unlink <$templates/*>;
 
 633   $form->redirect($locale->text('User deleted!'));
 
 641   return ($login) ? $login : undef;
 
 647   my ($null, $value) = split(/=/, $line, 2);
 
 650   $value =~ s/\s#.*//g;
 
 652   # remove any trailing whitespace
 
 653   $value =~ s/^\s*(.*?)\s*$/$1/;
 
 658 sub pg_database_administration {
 
 659   my $form = $main::form;
 
 661   $form->{dbdriver} = 'Pg';
 
 666 sub dbselect_source {
 
 667   my $form           = $main::form;
 
 668   my $locale         = $main::locale;
 
 670   $form->{dbport}    = $::auth->{DB_config}->{port} || 5432;
 
 671   $form->{dbuser}    = $::auth->{DB_config}->{user} || 'lxoffice';
 
 672   $form->{dbdefault} = 'template1';
 
 673   $form->{dbhost}    = $::auth->{DB_config}->{host} || 'localhost';
 
 675   $form->{title}     = "Lx-Office ERP / " . $locale->text('Database Administration');
 
 677   # Intentionnaly disabled unless fixed to work with the authentication DB.
 
 678   $form->{ALLOW_DBBACKUP} = 0; # "$pg_dump_exe" ne "DISABLED";
 
 681   print $form->parse_html_template("admin/dbadmin");
 
 684 sub test_db_connection {
 
 685   my $form   = $main::form;
 
 686   my $locale = $main::locale;
 
 688   $form->{dbdriver} = 'Pg';
 
 689   User::dbconnect_vars($form, $form->{dbname});
 
 691   my $dbh = DBI->connect($form->{dbconnect}, $form->{dbuser}, $form->{dbpasswd});
 
 693   $form->{connection_ok} = $dbh ? 1 : 0;
 
 694   $form->{errstr}        = $DBI::errstr;
 
 696   $dbh->disconnect() if ($dbh);
 
 698   $form->{title} = $locale->text('Database Connection Test');
 
 700   print $form->parse_html_template("admin/test_db_connection");
 
 704   call_sub($main::form->{"nextsub"});
 
 708   my $form              = $main::form;
 
 709   my $locale            = $main::locale;
 
 711   $form->{title}        = "Lx-Office ERP " . $locale->text('Database Administration') . " / " . $locale->text('Update Dataset');
 
 713   my @need_updates      = User->dbneedsupdate($form);
 
 714   $form->{NEED_UPDATES} = \@need_updates;
 
 715   $form->{ALL_UPDATED}  = !scalar @need_updates;
 
 718   print $form->parse_html_template("admin/update_dataset");
 
 722   my $form            = $main::form;
 
 723   my $locale          = $main::locale;
 
 725   $form->{stylesheet} = "lx-office-erp.css";
 
 726   $form->{title}      = $locale->text("Dataset upgrade");
 
 729   my $rowcount           = $form->{rowcount} * 1;
 
 730   my @update_rows        = grep { $form->{"update_$_"} } (1 .. $rowcount);
 
 731   $form->{NOTHING_TO_DO} = !scalar @update_rows;
 
 732   my $saved_form         = save_form();
 
 736   print $form->parse_html_template("admin/dbupgrade_all_header");
 
 738   foreach my $i (@update_rows) {
 
 739     restore_form($saved_form);
 
 742     map { $form->{$_} = $::myconfig{$_} = $form->{"${_}_${i}"} } qw(dbname dbdriver dbhost dbport dbuser dbpasswd);
 
 744     print $form->parse_html_template("admin/dbupgrade_header");
 
 746     $form->{dbupdate}        = $form->{dbname};
 
 747     $form->{$form->{dbname}} = 1;
 
 749     User->dbupdate($form);
 
 750     User->dbupdate2($form, SL::DBUpgrade2->new(form => $form, dbdriver => $form->{dbdriver})->parse_dbupdate_controls);
 
 752     print $form->parse_html_template("admin/dbupgrade_footer");
 
 755   print $form->parse_html_template("admin/dbupgrade_all_done");
 
 759   my $form           = $main::form;
 
 760   my $locale         = $main::locale;
 
 762   $form->{dbsources} = join " ", map { "[${_}]" } sort User->dbsources($form);
 
 764   $form->{CHARTS}    = [];
 
 766   opendir SQLDIR, "sql/." or $form->error($ERRNO);
 
 767   foreach my $item (sort grep /-chart\.sql\z/, readdir SQLDIR) {
 
 768     next if ($item eq 'Default-chart.sql');
 
 769     $item =~ s/-chart\.sql//;
 
 770     push @{ $form->{CHARTS} }, { "name"     => $item,
 
 771                                  "selected" => $item eq "Germany-DATEV-SKR03EU" };
 
 775   $form->{ACCOUNTING_METHODS} = [];
 
 776   foreach my $item ( qw(accrual cash) ) {
 
 777     push @{ $form->{ACCOUNTING_METHODS} }, { "name"     => $item,
 
 778                                  "selected" => $item eq "cash" };
 
 781   $form->{INVENTORY_SYSTEMS} = [];
 
 782   foreach my $item ( qw(perpetual periodic) ) {
 
 783     push @{ $form->{INVENTORY_SYSTEMS} }, { "name"     => $item,
 
 784                                  "selected" => $item eq "periodic" };
 
 787   $form->{PROFIT_DETERMINATIONS} = [];
 
 788   foreach my $item ( qw(balance income) ) {
 
 789     push @{ $form->{PROFIT_DETERMINATIONS} }, { "name"     => $item,
 
 790                                  "selected" => $item eq "income" };
 
 793   my $default_charset = $::lx_office_conf{system}->{dbcharset};
 
 794   $default_charset ||= Common::DEFAULT_CHARSET;
 
 796   my $cluster_encoding = User->dbclusterencoding($form);
 
 797   if ($cluster_encoding && ($cluster_encoding =~ m/^(?:UTF-?8|UNICODE)$/i)) {
 
 798     if ($::lx_office_conf{system}->{dbcharset} !~ m/^UTF-?8$/i) {
 
 799       $form->show_generic_error($locale->text('The selected  PostgreSQL installation uses UTF-8 as its encoding. ' .
 
 800                                               'Therefore you have to configure Lx-Office to use UTF-8 as well.'),
 
 804     $form->{FORCE_DBENCODING} = 'UNICODE';
 
 807     $form->{DBENCODINGS} = [];
 
 809     foreach my $encoding (@Common::db_encodings) {
 
 810       push @{ $form->{DBENCODINGS} }, { "dbencoding" => $encoding->{dbencoding},
 
 811                                         "label"      => $encoding->{label},
 
 812                                         "selected"   => $encoding->{charset} eq $default_charset };
 
 816   $form->{title} = "Lx-Office ERP " . $locale->text('Database Administration') . " / " . $locale->text('Create Dataset');
 
 819   print $form->parse_html_template("admin/create_dataset");
 
 823   my $form   = $main::form;
 
 824   my $locale = $main::locale;
 
 826   $form->isblank("db", $locale->text('Dataset missing!'));
 
 828   User->dbcreate(\%$form);
 
 830   $form->{title} = "Lx-Office ERP " . $locale->text('Database Administration') . " / " . $locale->text('Create Dataset');
 
 833   print $form->parse_html_template("admin/dbcreate");
 
 837   my $form      = $main::form;
 
 838   my $locale    = $main::locale;
 
 840   my @dbsources = User->dbsources_unused($form);
 
 841   $form->error($locale->text('Nothing to delete!')) unless @dbsources;
 
 843   $form->{title}     = "Lx-Office ERP " . $locale->text('Database Administration') . " / " . $locale->text('Delete Dataset');
 
 844   $form->{DBSOURCES} = [ map { { "name", $_ } } sort @dbsources ];
 
 847   print $form->parse_html_template("admin/delete_dataset");
 
 851   my $form   = $main::form;
 
 852   my $locale = $main::locale;
 
 855     $form->error($locale->text('No Dataset selected!'));
 
 858   User->dbdelete(\%$form);
 
 860   $form->{title} = "Lx-Office ERP " . $locale->text('Database Administration') . " / " . $locale->text('Delete Dataset');
 
 862   print $form->parse_html_template("admin/dbdelete");
 
 866   my $form       = $main::form;
 
 867   my $locale     = $main::locale;
 
 869   $form->{title} = "Lx-Office ERP " . $locale->text('Database Administration') . " / " . $locale->text('Backup Dataset');
 
 871   if ($::lx_office_conf{applications}->{pg_dump} eq "DISABLED") {
 
 872     $form->error($locale->text('Database backups and restorations are disabled in the configuration.'));
 
 875   my @dbsources         = sort User->dbsources($form);
 
 876   $form->{DATABASES}    = [ map { { "dbname" => $_ } } @dbsources ];
 
 877   $form->{NO_DATABASES} = !scalar @dbsources;
 
 879   my $username  = getpwuid $UID || "unknown-user";
 
 880   my $hostname  = hostname() || "unknown-host";
 
 881   $form->{from} = "Lx-Office Admin <${username}\@${hostname}>";
 
 884   print $form->parse_html_template("admin/backup_dataset");
 
 887 sub backup_dataset_start {
 
 888   my $form       = $main::form;
 
 889   my $locale     = $main::locale;
 
 891   $form->{title} = "Lx-Office ERP " . $locale->text('Database Administration') . " / " . $locale->text('Backup Dataset');
 
 893   my $pg_dump_exe = $::lx_office_conf{applications}->{pg_dump} || "pg_dump";
 
 895   if ("$pg_dump_exe" eq "DISABLED") {
 
 896     $form->error($locale->text('Database backups and restorations are disabled in the configuration.'));
 
 899   $form->isblank("dbname", $locale->text('The dataset name is missing.'));
 
 900   $form->isblank("to", $locale->text('The email address is missing.')) if $form->{destination} eq "email";
 
 902   my $tmpdir = "/tmp/lx_office_backup_" . Common->unique_id();
 
 903   mkdir $tmpdir, 0700 || $form->error($locale->text('A temporary directory could not be created:') . " $ERRNO");
 
 905   my $pgpass = IO::File->new("${tmpdir}/.pgpass", O_WRONLY | O_CREAT, 0600);
 
 909     $form->error($locale->text('A temporary file could not be created:') . " $ERRNO");
 
 912   print $pgpass "$form->{dbhost}:$form->{dbport}:$form->{dbname}:$form->{dbuser}:$form->{dbpasswd}\n";
 
 915   $ENV{HOME} = $tmpdir;
 
 917   my @args = ("-Ft", "-c", "-o", "-h", $form->{dbhost}, "-U", $form->{dbuser});
 
 918   push @args, ("-p", $form->{dbport}) if ($form->{dbport});
 
 919   push @args, $form->{dbname};
 
 921   my $cmd  = "$pg_dump_exe " . join(" ", map { s/\\/\\\\/g; s/\"/\\\"/g; $_ } @args);
 
 922   my $name = "dataset_backup_$form->{dbname}_" . strftime("%Y%m%d", localtime()) . ".tar";
 
 924   if ($form->{destination} ne "email") {
 
 925     my $in = IO::File->new("$cmd |");
 
 928       unlink "${tmpdir}/.pgpass";
 
 931       $form->error($locale->text('The pg_dump process could not be started.'));
 
 934     print "content-type: application/x-tar\n";
 
 935     print "content-disposition: attachment; filename=\"${name}\"\n\n";
 
 937     while (my $line = <$in>) {
 
 943     unlink "${tmpdir}/.pgpass";
 
 947     my $tmp = $tmpdir . "/dump_" . Common::unique_id();
 
 949     if (system("$cmd > $tmp") != 0) {
 
 950       unlink "${tmpdir}/.pgpass", $tmp;
 
 953       $form->error($locale->text('The pg_dump process could not be started.'));
 
 956     my $mail = new Mailer;
 
 958     map { $mail->{$_} = $form->{$_} } qw(from to cc subject message);
 
 960     $mail->{charset}     = $::lx_office_conf{system}->{dbcharset} || Common::DEFAULT_CHARSET;
 
 961     $mail->{attachments} = [ { "filename" => $tmp, "name" => $name } ];
 
 964     unlink "${tmpdir}/.pgpass", $tmp;
 
 967     $form->{title} = "Lx-Office ERP " . $locale->text('Database Administration') . " / " . $locale->text('Backup Dataset');
 
 970     print $form->parse_html_template("admin/backup_dataset_email_done");
 
 974 sub restore_dataset {
 
 975   my $form       = $main::form;
 
 976   my $locale     = $main::locale;
 
 978   $form->{title} = "Lx-Office ERP " . $locale->text('Database Administration') . " / " . $locale->text('Restore Dataset');
 
 980   if ($::lx_office_conf{applications}->{pg_restore} eq "DISABLED") {
 
 981     $form->error($locale->text('Database backups and restorations are disabled in the configuration.'));
 
 984   my $default_charset   = $::lx_office_conf{system}->{dbcharset};
 
 985   $default_charset    ||= Common::DEFAULT_CHARSET;
 
 987   $form->{DBENCODINGS}  = [];
 
 989   foreach my $encoding (@Common::db_encodings) {
 
 990     push @{ $form->{DBENCODINGS} }, { "dbencoding" => $encoding->{dbencoding},
 
 991                                       "label"      => $encoding->{label},
 
 992                                       "selected"   => $encoding->{charset} eq $default_charset };
 
 996   print $form->parse_html_template("admin/restore_dataset");
 
 999 sub restore_dataset_start {
 
1000   my $form       = $main::form;
 
1001   my $locale     = $main::locale;
 
1003   $form->{title} = "Lx-Office ERP " . $locale->text('Database Administration') . " / " . $locale->text('Restore Dataset');
 
1005   my $pg_restore_exe = $::lx_office_conf{applications}->{pg_restore} || "pg_restore";
 
1007   if ("$pg_restore_exe" eq "DISABLED") {
 
1008     $form->error($locale->text('Database backups and restorations are disabled in the configuration.'));
 
1011   $form->isblank("new_dbname", $locale->text('The dataset name is missing.'));
 
1012   $form->isblank("content", $locale->text('No backup file has been uploaded.'));
 
1014   # Create temporary directories. Write the backup file contents to a temporary
 
1015   # file. Create a .pgpass file with the username and password for the pg_restore
 
1018   my $tmpdir = "/tmp/lx_office_backup_" . Common->unique_id();
 
1019   mkdir $tmpdir, 0700 || $form->error($locale->text('A temporary directory could not be created:') . " $ERRNO");
 
1021   my $pgpass = IO::File->new("${tmpdir}/.pgpass", O_WRONLY | O_CREAT, 0600);
 
1025     $form->error($locale->text('A temporary file could not be created:') . " $ERRNO");
 
1028   print $pgpass "$form->{dbhost}:$form->{dbport}:$form->{new_dbname}:$form->{dbuser}:$form->{dbpasswd}\n";
 
1031   $ENV{HOME} = $tmpdir;
 
1033   my $tmp = $tmpdir . "/dump_" . Common::unique_id();
 
1036   if (substr($form->{content}, 0, 2) eq "\037\213") {
 
1037     $tmpfile = IO::File->new("| gzip -d > $tmp");
 
1041     $tmpfile = IO::File->new($tmp, O_WRONLY | O_CREAT | O_BINARY, 0600);
 
1045     unlink "${tmpdir}/.pgpass";
 
1048     $form->error($locale->text('A temporary file could not be created:') . " $ERRNO");
 
1051   print $tmpfile $form->{content};
 
1054   delete $form->{content};
 
1056   # Try to connect to the database. Find out if a database with the same name exists.
 
1057   # If yes, then drop the existing database. Create a new one with the name and encoding
 
1058   # given by the user.
 
1060   User::dbconnect_vars($form, "template1");
 
1062   my %myconfig = map { $_ => $form->{$_} } grep /^db/, keys %{ $form };
 
1063   my $dbh      = $form->dbconnect(\%myconfig) || $form->dberror();
 
1067   $form->{new_dbname} =~ s|[^a-zA-Z0-9_\-]||g;
 
1069   $query = qq|SELECT COUNT(*) FROM pg_database WHERE datname = ?|;
 
1070   my ($count) = selectrow_query($form, $dbh, $query, $form->{new_dbname});
 
1072     do_query($form, $dbh, qq|DROP DATABASE $form->{new_dbname}|);
 
1076   foreach my $item (@Common::db_encodings) {
 
1077     if ($item->{dbencoding} eq $form->{dbencoding}) {
 
1082   $form->{dbencoding} = "LATIN9" unless $form->{dbencoding};
 
1084   do_query($form, $dbh, qq|CREATE DATABASE $form->{new_dbname} ENCODING ? TEMPLATE template0|, $form->{dbencoding});
 
1088   # Spawn pg_restore on the temporary file.
 
1090   my @args = ("-h", $form->{dbhost}, "-U", $form->{dbuser}, "-d", $form->{new_dbname});
 
1091   push @args, ("-p", $form->{dbport}) if ($form->{dbport});
 
1094   my $cmd = "$pg_restore_exe " . join(" ", map { s/\\/\\\\/g; s/\"/\\\"/g; $_ } @args);
 
1096   my $in = IO::File->new("$cmd 2>&1 |");
 
1099     unlink "${tmpdir}/.pgpass", $tmp;
 
1102     $form->error($locale->text('The pg_restore process could not be started.'));
 
1105   $English::AUTOFLUSH = 1;
 
1108   print $form->parse_html_template("admin/restore_dataset_start_header");
 
1110   while (my $line = <$in>) {
 
1115   $form->{retval} = $CHILD_ERROR >> 8;
 
1116   print $form->parse_html_template("admin/restore_dataset_start_footer");
 
1118   unlink "${tmpdir}/.pgpass", $tmp;
 
1123   my $form   = $main::form;
 
1124   my $locale = $main::locale;
 
1126   unlink _nologin_file_name();;
 
1128   $form->{callback} = "admin.pl?action=list_users";
 
1130   $form->redirect($locale->text('Lockfile removed!'));
 
1135   my $form   = $main::form;
 
1136   my $locale = $main::locale;
 
1138   open(FH, ">", _nologin_file_name())
 
1139     or $form->error($locale->text('Cannot create Lock!'));
 
1142   $form->{callback} = "admin.pl?action=list_users";
 
1144   $form->redirect($locale->text('Lockfile created!'));
 
1149   call_sub($main::form->{yes_nextsub});
 
1153   call_sub($main::form->{no_nextsub});
 
1157   call_sub($main::form->{add_nextsub});
 
1161   my $form = $main::form;
 
1163   $form->{edit_nextsub} ||= 'edit_user';
 
1165   call_sub($form->{edit_nextsub});
 
1169   my $form     = $main::form;
 
1171   $form->{delete_nextsub} ||= 'delete_user';
 
1173   call_sub($form->{delete_nextsub});
 
1177   my $form = $main::form;
 
1179   $form->{save_nextsub} ||= 'save_user';
 
1181   call_sub($form->{save_nextsub});
 
1185   call_sub($main::form->{back_nextsub});
 
1189   my $form   = $main::form;
 
1190   my $locale = $main::locale;
 
1192   foreach my $action (qw(create_standard_group dont_create_standard_group
 
1193                          save_user delete_user save_user_as_new)) {
 
1194     if ($form->{"action_${action}"}) {
 
1200   call_sub($form->{default_action}) if ($form->{default_action});
 
1202   $form->error($locale->text('No action defined.'));
 
1205 sub _apply_dbupgrade_scripts {
 
1206   ::end_of_request() if SL::DBUpgrade2->new(form => $::form, dbdriver => 'Pg', auth => 1)->apply_admin_dbupgrade_scripts(1);
 
1209 sub _nologin_file_name {
 
1210   return $::lx_office_conf{paths}->{userspath} . '/nologin';