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);
 
  53 require "bin/mozilla/common.pl";
 
  54 require "bin/mozilla/admin_groups.pl";
 
  55 require "bin/mozilla/admin_printer.pl";
 
  65   $::lxdebug->enter_sub;
 
  66   my $session_result = shift;
 
  73   $::auth->set_session_value('rpw', $::form->{rpw}) if $session_result == SL::Auth->SESSION_OK;
 
  75   $form->{stylesheet} = "lx-office-erp.css";
 
  76   $form->{favicon}    = "favicon.ico";
 
  78   if ($form->{action}) {
 
  79     if ($auth->authenticate_root($form->{rpw}, 0) != $auth->OK()) {
 
  80       $form->{error_message} = $locale->text('Incorrect Password!');
 
  83       if ($auth->session_tables_present()) {
 
  84         $::auth->set_session_value('rpw', $::form->{rpw});
 
  85         $::auth->create_or_refresh_session();
 
  87       call_sub($locale->findsub($form->{action}));
 
  90     # if there are no drivers bail out
 
  91     $form->error($locale->text('No Database Drivers available!'))
 
  92       unless (User->dbdrivers);
 
  96   $::lxdebug->leave_sub;
 
 100   my $form   = $main::form;
 
 101   my $locale = $main::locale;
 
 103   $form->{title} = qq|Lx-Office ERP $form->{version} | . $locale->text('Administration');
 
 106   print $form->parse_html_template('admin/adminlogin');
 
 110   check_auth_db_and_tables();
 
 115   $main::auth->destroy_session();
 
 119 sub check_auth_db_and_tables {
 
 120   my $form   = $main::form;
 
 121   my $locale = $main::locale;
 
 125   map { $params{"db_${_}"} = $main::auth->{DB_config}->{$_} } keys %{ $auth->{DB_config} };
 
 127   if (!$main::auth->check_database()) {
 
 128     $form->{title} = $locale->text('Authentification database creation');
 
 130     print $form->parse_html_template('admin/check_auth_database', \%params);
 
 135   if (!$main::auth->check_tables()) {
 
 136     $form->{title} = $locale->text('Authentification tables creation');
 
 138     print $form->parse_html_template('admin/check_auth_tables', \%params);
 
 143   if (-f $main::memberfile) {
 
 146     if ($main::memberfile =~ m|^.*/|) {
 
 150     my $backupdir = "${memberdir}member-file-migration";
 
 152     $form->{title} = $locale->text('User data migration');
 
 154     print $form->parse_html_template('admin/user_migration', { 'memberfile' => $main::memberfile,
 
 155                                                                'backupdir'  => $backupdir });
 
 162   my $form = $main::form;
 
 164   $main::auth->create_database('superuser'          => $form->{db_superuser},
 
 165                                'superuser_password' => $form->{db_superuser_password},
 
 166                                'template'           => $form->{db_template});
 
 170 sub create_auth_tables {
 
 171   my $form   = $main::form;
 
 172   my $locale = $main::locale;
 
 174   $main::auth->create_tables();
 
 175   $main::auth->set_session_value('rpw', $form->{rpw});
 
 176   $main::auth->create_or_refresh_session();
 
 178   if (!-f $main::memberfile) {
 
 179     # New installation -- create a standard group with full access
 
 182       'name'        => $locale->text('Full Access'),
 
 183       'description' => $locale->text('Full access to all functions'),
 
 184       'rights'      => { map { $_ => 1 } SL::Auth::all_rights() },
 
 185       'members'     => [ map { $_->{id} } values %members ],
 
 188     $main::auth->save_group($group);
 
 195   $main::lxdebug->enter_sub();
 
 197   my $form      = $main::form;
 
 198   my $locale    = $main::locale;
 
 202   if ($main::memberfile =~ m|^.*/|) {
 
 206   my $backupdir = "${memberdir}member-file-migration";
 
 208   if (! -d $backupdir && !mkdir $backupdir, 0700) {
 
 209     $form->error(sprintf($locale->text('The directory "%s" could not be created:\n%s'), $backupdir, $!));
 
 212   copy $main::memberfile, "users/member-file-migration/members";
 
 214   my $in = IO::File->new($main::memberfile, "r");
 
 216   $form->error($locale->text('Could not open the old memberfile.')) if (!$in);
 
 218   my (%members, $login);
 
 227       $login =~ s/(\[|\])//g;
 
 231       $members{$login} = { "login" => $login };
 
 235     if ($login && m/=/) {
 
 236       my ($key, $value) = split m/\s*=\s*/, $_, 2;
 
 241       $value =~ s|\\n|\n|g;
 
 243       $members{$login}->{$key} = $value;
 
 249   delete $members{"root login"};
 
 251   map { $_->{dbpasswd} = unpack 'u', $_->{dbpasswd} } values %members;
 
 253   while (my ($login, $params) = each %members) {
 
 254     $main::auth->save_user($login, %{ $params });
 
 255     $main::auth->change_password($login, $params->{password}, 1);
 
 257     my $conf_file = "${memberdir}${login}.conf";
 
 260       copy   $conf_file, "${backupdir}/${login}.conf";
 
 265   unlink $main::memberfile;
 
 267   my @member_list = sort { lc $a->{login} cmp lc $b->{login} } values %members;
 
 269   $form->{title} = $locale->text('User data migration');
 
 271   print $form->parse_html_template('admin/user_migration_done', { 'MEMBERS' => \@member_list });
 
 273   $main::lxdebug->leave_sub();
 
 276 sub create_standard_group_ask {
 
 277   my $form   = $main::form;
 
 278   my $locale = $main::locale;
 
 280   $form->{title} = $locale->text('Create a standard group');
 
 283   print $form->parse_html_template("admin/create_standard_group_ask");
 
 286 sub create_standard_group {
 
 287   my $form    = $main::form;
 
 288   my $locale  = $main::locale;
 
 290   my %members = $main::auth->read_all_users();
 
 292   my $groups  = $main::auth->read_groups();
 
 294   foreach my $group (values %{$groups}) {
 
 295     if (($form->{group_id} != $group->{id})
 
 296         && ($form->{name} eq $group->{name})) {
 
 297       $form->show_generic_error($locale->text("A group with that name does already exist."));
 
 302     'name'        => $locale->text('Full Access'),
 
 303     'description' => $locale->text('Full access to all functions'),
 
 304     'rights'      => { map { $_ => 1 } SL::Auth::all_rights() },
 
 305     'members'     => [ map { $_->{id} } values %members ],
 
 308   $main::auth->save_group($group);
 
 310   user_migration_complete(1);
 
 313 sub dont_create_standard_group {
 
 314   user_migration_complete(0);
 
 317 sub user_migration_complete {
 
 318   my $standard_group_created = shift;
 
 320   my $form                   = $main::form;
 
 321   my $locale                 = $main::locale;
 
 323   $form->{title} = $locale->text('User migration complete');
 
 326   print $form->parse_html_template('admin/user_migration_complete', { 'standard_group_created' => $standard_group_created });
 
 330   my $form    = $main::form;
 
 331   my $locale  = $main::locale;
 
 333   my %members = $main::auth->read_all_users();
 
 335   delete $members{"root login"};
 
 337   map { $_->{templates} =~ s|.*/||; } values %members;
 
 339   $form->{title}   = "Lx-Office ERP " . $locale->text('Administration');
 
 340   $form->{LOCKED}  = -e "$main::userspath/nologin";
 
 341   $form->{MEMBERS} = [ @members{sort { lc $a cmp lc $b } keys %members} ];
 
 344   print $form->parse_html_template("admin/list_users");
 
 348   my $form         = $main::form;
 
 349   my $locale       = $main::locale;
 
 351   $form->{title}   = "Lx-Office ERP " . $locale->text('Administration') . " / " . $locale->text('Add User');
 
 353 # Note: Menu Style 'v3' is not compatible to all browsers!
 
 354 # "menustyle"    => "old" sets the HTML Menu to default.
 
 357     "countrycode"  => "de",
 
 358     "numberformat" => "1.000,00",
 
 359     "dateformat"   => "dd.mm.yy",
 
 360     "stylesheet"   => "lx-office-erp.css",
 
 361     "menustyle"    => "old",
 
 364   edit_user_form($myconfig);
 
 368   my $form       = $main::form;
 
 369   my $locale     = $main::locale;
 
 371   $form->{title} = "Lx-Office ERP " . $locale->text('Administration') . " / " . $locale->text('Edit User');
 
 374   $form->isblank("login", $locale->text("The login is missing."));
 
 377   my $myconfig = new User($form->{login});
 
 379   # strip basedir from templates directory
 
 380   $myconfig->{templates} =~ s|.*/||;
 
 382   edit_user_form($myconfig);
 
 388   my $form       = $main::form;
 
 389   my $locale     = $main::locale;
 
 391   my @valid_dateformats = qw(mm-dd-yy mm/dd/yy dd-mm-yy dd/mm/yy dd.mm.yy yyyy-mm-dd);
 
 392   $form->{ALL_DATEFORMATS} = [ map { { "format" => $_, "selected" => $_ eq $myconfig->{dateformat} } } @valid_dateformats ];
 
 394   my @valid_numberformats = ('1,000.00', '1000.00', '1.000,00', '1000,00');
 
 395   $form->{ALL_NUMBERFORMATS} = [ map { { "format" => $_, "selected" => $_ eq $myconfig->{numberformat} } } @valid_numberformats ];
 
 397   my %countrycodes = User->country_codes;
 
 398   $form->{ALL_COUNTRYCODES} = [];
 
 399   foreach my $countrycode (sort { $countrycodes{$a} cmp $countrycodes{$b} } keys %countrycodes) {
 
 400     push @{ $form->{ALL_COUNTRYCODES} }, { "value"    => $countrycode,
 
 401                                            "name"     => $countrycodes{$countrycode},
 
 402                                            "selected" => $countrycode eq $myconfig->{countrycode} };
 
 405   # is there a templates basedir
 
 406   if (!-d "$main::templates") {
 
 407     $form->error(sprintf($locale->text("The directory %s does not exist."), $main::templates));
 
 410   opendir TEMPLATEDIR, "$main::templates/." or $form->error("$main::templates : $ERRNO");
 
 411   my @all     = readdir(TEMPLATEDIR);
 
 412   my @alldir  = sort grep { -d "$main::templates/$_" && !/^\.\.?$/ } @all;
 
 413   my @allhtml = sort grep { -f "$main::templates/$_" && /\.html$/ } @all;
 
 414   closedir TEMPLATEDIR;
 
 416   @alldir = grep !/\.(html|tex|sty|odt|xml|txb)$/, @alldir;
 
 417   @alldir = grep !/^(webpages|\.svn)$/, @alldir;
 
 419   @allhtml = reverse grep !/Default/, @allhtml;
 
 420   push @allhtml, 'Default';
 
 421   @allhtml = reverse @allhtml;
 
 423   $form->{ALL_TEMPLATES} = [ map { { "name", => $_, "selected" => $_ eq $myconfig->{templates} } } @alldir ];
 
 425   my $lastitem = $allhtml[0];
 
 426   $lastitem =~ s/-.*//g;
 
 427   $form->{ALL_MASTER_TEMPLATES} = [ { "name" => $lastitem, "selected" => $lastitem eq "German" } ];
 
 428   foreach my $item (@allhtml) {
 
 430     next if ($item eq $lastitem);
 
 432     push @{ $form->{ALL_MASTER_TEMPLATES} }, { "name" => $item, "selected" => $item eq "German" };
 
 436   # css dir has styles that are not intended as general layouts.
 
 437   # reverting to hardcoded list
 
 438   $form->{ALL_STYLESHEETS} = [ map { { "name" => $_, "selected" => $_ eq $myconfig->{stylesheet} } } qw(lx-office-erp.css Win2000.css) ];
 
 440   $form->{"menustyle_" . $myconfig->{menustyle} } = 1;
 
 442   map { $form->{"myc_${_}"} = $myconfig->{$_} } keys %{ $myconfig };
 
 447     my $user_id    = $main::auth->get_user_id($form->{login});
 
 448     my $all_groups = $main::auth->read_groups();
 
 450     foreach my $group (values %{ $all_groups }) {
 
 451       push @{ $groups }, $group if (grep { $user_id == $_ } @{ $group->{members} });
 
 454     $groups = [ sort { lc $a->{name} cmp lc $b->{name} } @{ $groups } ];
 
 457   $form->{CAN_CHANGE_PASSWORD} = $main::auth->can_change_password();
 
 460   print $form->parse_html_template("admin/edit_user", { 'GROUPS' => $groups });
 
 464   my $form          = $main::form;
 
 465   my $locale        = $main::locale;
 
 467   $form->{dbdriver} = 'Pg';
 
 469   # no spaces allowed in login name
 
 470   $form->{login} =~ s|\s||g;
 
 471   $form->isblank("login", $locale->text('Login name missing!'));
 
 473   # check for duplicates
 
 474   if (!$form->{edit}) {
 
 475     my %members = $main::auth->read_all_users();
 
 476     if ($members{$form->{login}}) {
 
 477       $form->show_generic_error($locale->text('Another user with the login #1 does already exist.', $form->{login}), 'back_button' => 1);
 
 481   # no spaces allowed in directories
 
 482   ($form->{newtemplates}) = split / /, $form->{newtemplates};
 
 484   if ($form->{newtemplates}) {
 
 485     $form->{templates} = $form->{newtemplates};
 
 488       ($form->{usetemplates}) ? $form->{usetemplates} : $form->{login};
 
 492   if (!-d "$main::templates") {
 
 493     $form->error(sprintf($locale->text("The directory %s does not exist."), $main::templates));
 
 496   # add base directory to $form->{templates}
 
 497   $form->{templates} =~ s|.*/||;
 
 498   $form->{templates} =  "$main::templates/$form->{templates}";
 
 500   my $myconfig = new User($form->{login});
 
 502   $form->isblank("dbname", $locale->text('Dataset missing!'));
 
 503   $form->isblank("dbuser", $locale->text('Database User missing!'));
 
 505   foreach my $item (keys %{$form}) {
 
 506     $myconfig->{$item} = $form->{$item};
 
 509   delete $myconfig->{stylesheet};
 
 510   if ($form->{userstylesheet}) {
 
 511     $myconfig->{stylesheet} = $form->{userstylesheet};
 
 514   $myconfig->save_member();
 
 516   if ($main::auth->can_change_password()
 
 517       && defined $form->{new_password}
 
 518       && ($form->{new_password} ne '********')) {
 
 519     $main::auth->change_password($form->{login}, $form->{new_password});
 
 522   $form->{templates}       =~ s|.*/||;
 
 523   $form->{templates}       =  "$main::templates/$form->{templates}";
 
 524   $form->{mastertemplates} =~ s|.*/||;
 
 526   # create user template directory and copy master files
 
 527   if (!-d "$form->{templates}") {
 
 530     if (mkdir "$form->{templates}", oct("771")) {
 
 534       # copy templates to the directory
 
 535       opendir TEMPLATEDIR, "$main::templates/." or $form->error("$main::templates : $ERRNO");
 
 536       my @templates = grep /$form->{mastertemplates}.*?\.(html|tex|sty|odt|xml|txb)$/,
 
 538       closedir TEMPLATEDIR;
 
 540       foreach my $file (@templates) {
 
 541         open(TEMP, "$main::templates/$file")
 
 542           or $form->error("$main::templates/$file : $ERRNO");
 
 544         $file =~ s/\Q$form->{mastertemplates}\E-//;
 
 545         open(NEW, ">$form->{templates}/$file")
 
 546           or $form->error("$form->{templates}/$file : $ERRNO");
 
 548         while (my $line = <TEMP>) {
 
 555       $form->error("$ERRNO: $form->{templates}");
 
 559   # Add new user to his groups.
 
 560   if (ref $form->{new_user_group_ids} eq 'ARRAY') {
 
 561     my $all_groups = $main::auth->read_groups();
 
 562     my %user       = $main::auth->read_user($form->{login});
 
 564     foreach my $group_id (@{ $form->{new_user_group_ids} }) {
 
 565       my $group = $all_groups->{$group_id};
 
 569       push @{ $group->{members} }, $user{id};
 
 570       $main::auth->save_group($group);
 
 574   $form->redirect($locale->text('User saved!'));
 
 578 sub save_user_as_new {
 
 579   my $form       = $main::form;
 
 581   $form->{login} = $form->{new_user_login};
 
 582   delete @{$form}{qw(edit new_user_login)};
 
 588   my $form      = $main::form;
 
 589   my $locale    = $main::locale;
 
 591   my %members   = $main::auth->read_all_users();
 
 592   my $templates = $members{$form->{login}}->{templates};
 
 594   $main::auth->delete_user($form->{login});
 
 597     my $templates_in_use = 0;
 
 599     foreach my $login (keys %members) {
 
 600       next if $form->{login} eq $login;
 
 601       next if $members{$login}->{templates} ne $templates;
 
 602       $templates_in_use = 1;
 
 606     if (!$templates_in_use && -d $templates) {
 
 607       unlink <$templates/*>;
 
 612   $form->redirect($locale->text('User deleted!'));
 
 620   return ($login) ? $login : undef;
 
 626   my ($null, $value) = split(/=/, $line, 2);
 
 629   $value =~ s/\s#.*//g;
 
 631   # remove any trailing whitespace
 
 632   $value =~ s/^\s*(.*?)\s*$/$1/;
 
 637 sub pg_database_administration {
 
 638   my $form = $main::form;
 
 640   $form->{dbdriver} = 'Pg';
 
 645 sub dbselect_source {
 
 646   my $form           = $main::form;
 
 647   my $locale         = $main::locale;
 
 649   $form->{dbport}    = '5432';
 
 650   $form->{dbuser}    = 'lxoffice';
 
 651   $form->{dbdefault} = 'template1';
 
 652   $form->{dbhost}    = 'localhost';
 
 654   $form->{title}     = "Lx-Office ERP / " . $locale->text('Database Administration');
 
 656   # Intentionnaly disabled unless fixed to work with the authentication DB.
 
 657   $form->{ALLOW_DBBACKUP} = 0; # "$pg_dump_exe" ne "DISABLED";
 
 660   print $form->parse_html_template("admin/dbadmin");
 
 663 sub test_db_connection {
 
 664   my $form   = $main::form;
 
 665   my $locale = $main::locale;
 
 667   $form->{dbdriver} = 'Pg';
 
 668   User::dbconnect_vars($form, $form->{dbname});
 
 670   my $dbh = DBI->connect($form->{dbconnect}, $form->{dbuser}, $form->{dbpasswd});
 
 672   $form->{connection_ok} = $dbh ? 1 : 0;
 
 673   $form->{errstr}        = $DBI::errstr;
 
 675   $dbh->disconnect() if ($dbh);
 
 677   $form->{title} = $locale->text('Database Connection Test');
 
 679   print $form->parse_html_template("admin/test_db_connection");
 
 683   call_sub($main::form->{"nextsub"});
 
 687   my $form              = $main::form;
 
 688   my $locale            = $main::locale;
 
 690   $form->{title}        = "Lx-Office ERP " . $locale->text('Database Administration') . " / " . $locale->text('Update Dataset');
 
 692   my @need_updates      = User->dbneedsupdate($form);
 
 693   $form->{NEED_UPDATES} = \@need_updates;
 
 694   $form->{ALL_UPDATED}  = !scalar @need_updates;
 
 697   print $form->parse_html_template("admin/update_dataset");
 
 701   my $form            = $main::form;
 
 702   my $locale          = $main::locale;
 
 704   $form->{stylesheet} = "lx-office-erp.css";
 
 705   $form->{title}      = $locale->text("Dataset upgrade");
 
 708   my $rowcount           = $form->{rowcount} * 1;
 
 709   my @update_rows        = grep { $form->{"update_$_"} } (1 .. $rowcount);
 
 710   $form->{NOTHING_TO_DO} = !scalar @update_rows;
 
 711   my $saved_form         = save_form();
 
 715   print $form->parse_html_template("admin/dbupgrade_all_header");
 
 717   foreach my $i (@update_rows) {
 
 718     restore_form($saved_form);
 
 720     map { $form->{$_} = $form->{"${_}_${i}"} } qw(dbname dbdriver dbhost dbport dbuser dbpasswd);
 
 722     my $controls = parse_dbupdate_controls($form, $form->{dbdriver});
 
 724     print $form->parse_html_template("admin/dbupgrade_header");
 
 726     $form->{dbupdate}        = $form->{dbname};
 
 727     $form->{$form->{dbname}} = 1;
 
 729     User->dbupdate($form);
 
 730     User->dbupdate2($form, $controls);
 
 732     print $form->parse_html_template("admin/dbupgrade_footer");
 
 735   print $form->parse_html_template("admin/dbupgrade_all_done");
 
 739   my $form           = $main::form;
 
 740   my $locale         = $main::locale;
 
 742   $form->{dbsources} = join " ", map { "[${_}]" } sort User->dbsources($form);
 
 744   $form->{CHARTS}    = [];
 
 746   opendir SQLDIR, "sql/." or $form->error($ERRNO);
 
 747   foreach my $item (sort grep /-chart\.sql\z/, readdir SQLDIR) {
 
 748     next if ($item eq 'Default-chart.sql');
 
 749     $item =~ s/-chart\.sql//;
 
 750     push @{ $form->{CHARTS} }, { "name"     => $item,
 
 751                                  "selected" => $item eq "Germany-DATEV-SKR03EU" };
 
 755   my $default_charset = $main::dbcharset;
 
 756   $default_charset ||= Common::DEFAULT_CHARSET;
 
 758   my $cluster_encoding = User->dbclusterencoding($form);
 
 759   if ($cluster_encoding && ($cluster_encoding =~ m/^(?:UTF-?8|UNICODE)$/i)) {
 
 760     if ($main::dbcharset !~ m/^UTF-?8$/i) {
 
 761       $form->show_generic_error($locale->text('The selected  PostgreSQL installation uses UTF-8 as its encoding. ' .
 
 762                                               'Therefore you have to configure Lx-Office to use UTF-8 as well.'),
 
 766     $form->{FORCE_DBENCODING} = 'UNICODE';
 
 769     $form->{DBENCODINGS} = [];
 
 771     foreach my $encoding (@Common::db_encodings) {
 
 772       push @{ $form->{DBENCODINGS} }, { "dbencoding" => $encoding->{dbencoding},
 
 773                                         "label"      => $encoding->{label},
 
 774                                         "selected"   => $encoding->{charset} eq $default_charset };
 
 778   $form->{title} = "Lx-Office ERP " . $locale->text('Database Administration') . " / " . $locale->text('Create Dataset');
 
 781   print $form->parse_html_template("admin/create_dataset");
 
 785   my $form   = $main::form;
 
 786   my $locale = $main::locale;
 
 788   $form->isblank("db", $locale->text('Dataset missing!'));
 
 790   User->dbcreate(\%$form);
 
 792   $form->{title} = "Lx-Office ERP " . $locale->text('Database Administration') . " / " . $locale->text('Create Dataset');
 
 795   print $form->parse_html_template("admin/dbcreate");
 
 799   my $form      = $main::form;
 
 800   my $locale    = $main::locale;
 
 802   my @dbsources = User->dbsources_unused($form);
 
 803   $form->error($locale->text('Nothing to delete!')) unless @dbsources;
 
 805   $form->{title}     = "Lx-Office ERP " . $locale->text('Database Administration') . " / " . $locale->text('Delete Dataset');
 
 806   $form->{DBSOURCES} = [ map { { "name", $_ } } sort @dbsources ];
 
 809   print $form->parse_html_template("admin/delete_dataset");
 
 813   my $form   = $main::form;
 
 814   my $locale = $main::locale;
 
 817     $form->error($locale->text('No Dataset selected!'));
 
 820   User->dbdelete(\%$form);
 
 822   $form->{title} = "Lx-Office ERP " . $locale->text('Database Administration') . " / " . $locale->text('Delete Dataset');
 
 824   print $form->parse_html_template("admin/dbdelete");
 
 828   my $form       = $main::form;
 
 829   my $locale     = $main::locale;
 
 831   $form->{title} = "Lx-Office ERP " . $locale->text('Database Administration') . " / " . $locale->text('Backup Dataset');
 
 833   if ("$main::pg_dump_exe" eq "DISABLED") {
 
 834     $form->error($locale->text('Database backups and restorations are disabled in lx-erp.conf.'));
 
 837   my @dbsources         = sort User->dbsources($form);
 
 838   $form->{DATABASES}    = [ map { { "dbname" => $_ } } @dbsources ];
 
 839   $form->{NO_DATABASES} = !scalar @dbsources;
 
 841   my $username  = getpwuid $UID || "unknown-user";
 
 842   my $hostname  = hostname() || "unknown-host";
 
 843   $form->{from} = "Lx-Office Admin <${username}\@${hostname}>";
 
 846   print $form->parse_html_template("admin/backup_dataset");
 
 849 sub backup_dataset_start {
 
 850   my $form       = $main::form;
 
 851   my $locale     = $main::locale;
 
 853   $form->{title} = "Lx-Office ERP " . $locale->text('Database Administration') . " / " . $locale->text('Backup Dataset');
 
 855   $main::pg_dump_exe ||= "pg_dump";
 
 857   if ("$main::pg_dump_exe" eq "DISABLED") {
 
 858     $form->error($locale->text('Database backups and restorations are disabled in lx-erp.conf.'));
 
 861   $form->isblank("dbname", $locale->text('The dataset name is missing.'));
 
 862   $form->isblank("to", $locale->text('The email address is missing.')) if $form->{destination} eq "email";
 
 864   my $tmpdir = "/tmp/lx_office_backup_" . Common->unique_id();
 
 865   mkdir $tmpdir, 0700 || $form->error($locale->text('A temporary directory could not be created:') . " $ERRNO");
 
 867   my $pgpass = IO::File->new("${tmpdir}/.pgpass", O_WRONLY | O_CREAT, 0600);
 
 871     $form->error($locale->text('A temporary file could not be created:') . " $ERRNO");
 
 874   print $pgpass "$form->{dbhost}:$form->{dbport}:$form->{dbname}:$form->{dbuser}:$form->{dbpasswd}\n";
 
 877   $ENV{HOME} = $tmpdir;
 
 879   my @args = ("-Ft", "-c", "-o", "-h", $form->{dbhost}, "-U", $form->{dbuser});
 
 880   push @args, ("-p", $form->{dbport}) if ($form->{dbport});
 
 881   push @args, $form->{dbname};
 
 883   my $cmd  = "$main::pg_dump_exe " . join(" ", map { s/\\/\\\\/g; s/\"/\\\"/g; $_ } @args);
 
 884   my $name = "dataset_backup_$form->{dbname}_" . strftime("%Y%m%d", localtime()) . ".tar";
 
 886   if ($form->{destination} ne "email") {
 
 887     my $in = IO::File->new("$cmd |");
 
 890       unlink "${tmpdir}/.pgpass";
 
 893       $form->error($locale->text('The pg_dump process could not be started.'));
 
 896     print "content-type: application/x-tar\n";
 
 897     print "content-disposition: attachment; filename=\"${name}\"\n\n";
 
 899     while (my $line = <$in>) {
 
 905     unlink "${tmpdir}/.pgpass";
 
 909     my $tmp = $tmpdir . "/dump_" . Common::unique_id();
 
 911     if (system("$cmd > $tmp") != 0) {
 
 912       unlink "${tmpdir}/.pgpass", $tmp;
 
 915       $form->error($locale->text('The pg_dump process could not be started.'));
 
 918     my $mail = new Mailer;
 
 920     map { $mail->{$_} = $form->{$_} } qw(from to cc subject message);
 
 922     $mail->{charset}     = $main::dbcharset ? $main::dbcharset : Common::DEFAULT_CHARSET;
 
 923     $mail->{attachments} = [ { "filename" => $tmp, "name" => $name } ];
 
 926     unlink "${tmpdir}/.pgpass", $tmp;
 
 929     $form->{title} = "Lx-Office ERP " . $locale->text('Database Administration') . " / " . $locale->text('Backup Dataset');
 
 932     print $form->parse_html_template("admin/backup_dataset_email_done");
 
 936 sub restore_dataset {
 
 937   my $form       = $main::form;
 
 938   my $locale     = $main::locale;
 
 940   $form->{title} = "Lx-Office ERP " . $locale->text('Database Administration') . " / " . $locale->text('Restore Dataset');
 
 942   if ("$main::pg_restore_exe" eq "DISABLED") {
 
 943     $form->error($locale->text('Database backups and restorations are disabled in lx-erp.conf.'));
 
 946   my $default_charset   = $main::dbcharset;
 
 947   $default_charset    ||= Common::DEFAULT_CHARSET;
 
 949   $form->{DBENCODINGS}  = [];
 
 951   foreach my $encoding (@Common::db_encodings) {
 
 952     push @{ $form->{DBENCODINGS} }, { "dbencoding" => $encoding->{dbencoding},
 
 953                                       "label"      => $encoding->{label},
 
 954                                       "selected"   => $encoding->{charset} eq $default_charset };
 
 958   print $form->parse_html_template("admin/restore_dataset");
 
 961 sub restore_dataset_start {
 
 962   my $form       = $main::form;
 
 963   my $locale     = $main::locale;
 
 965   $form->{title} = "Lx-Office ERP " . $locale->text('Database Administration') . " / " . $locale->text('Restore Dataset');
 
 967   $main::pg_restore_exe ||= "pg_restore";
 
 969   if ("$main::pg_restore_exe" eq "DISABLED") {
 
 970     $form->error($locale->text('Database backups and restorations are disabled in lx-erp.conf.'));
 
 973   $form->isblank("new_dbname", $locale->text('The dataset name is missing.'));
 
 974   $form->isblank("content", $locale->text('No backup file has been uploaded.'));
 
 976   # Create temporary directories. Write the backup file contents to a temporary
 
 977   # file. Create a .pgpass file with the username and password for the pg_restore
 
 980   my $tmpdir = "/tmp/lx_office_backup_" . Common->unique_id();
 
 981   mkdir $tmpdir, 0700 || $form->error($locale->text('A temporary directory could not be created:') . " $ERRNO");
 
 983   my $pgpass = IO::File->new("${tmpdir}/.pgpass", O_WRONLY | O_CREAT, 0600);
 
 987     $form->error($locale->text('A temporary file could not be created:') . " $ERRNO");
 
 990   print $pgpass "$form->{dbhost}:$form->{dbport}:$form->{new_dbname}:$form->{dbuser}:$form->{dbpasswd}\n";
 
 993   $ENV{HOME} = $tmpdir;
 
 995   my $tmp = $tmpdir . "/dump_" . Common::unique_id();
 
 998   if (substr($form->{content}, 0, 2) eq "\037\213") {
 
 999     $tmpfile = IO::File->new("| gzip -d > $tmp");
 
1003     $tmpfile = IO::File->new($tmp, O_WRONLY | O_CREAT | O_BINARY, 0600);
 
1007     unlink "${tmpdir}/.pgpass";
 
1010     $form->error($locale->text('A temporary file could not be created:') . " $ERRNO");
 
1013   print $tmpfile $form->{content};
 
1016   delete $form->{content};
 
1018   # Try to connect to the database. Find out if a database with the same name exists.
 
1019   # If yes, then drop the existing database. Create a new one with the name and encoding
 
1020   # given by the user.
 
1022   User::dbconnect_vars($form, "template1");
 
1024   my %myconfig = map { $_ => $form->{$_} } grep /^db/, keys %{ $form };
 
1025   my $dbh      = $form->dbconnect(\%myconfig) || $form->dberror();
 
1029   $form->{new_dbname} =~ s|[^a-zA-Z0-9_\-]||g;
 
1031   $query = qq|SELECT COUNT(*) FROM pg_database WHERE datname = ?|;
 
1032   my ($count) = selectrow_query($form, $dbh, $query, $form->{new_dbname});
 
1034     do_query($form, $dbh, qq|DROP DATABASE $form->{new_dbname}|);
 
1038   foreach my $item (@Common::db_encodings) {
 
1039     if ($item->{dbencoding} eq $form->{dbencoding}) {
 
1044   $form->{dbencoding} = "LATIN9" unless $form->{dbencoding};
 
1046   do_query($form, $dbh, qq|CREATE DATABASE $form->{new_dbname} ENCODING ? TEMPLATE template0|, $form->{dbencoding});
 
1050   # Spawn pg_restore on the temporary file.
 
1052   my @args = ("-h", $form->{dbhost}, "-U", $form->{dbuser}, "-d", $form->{new_dbname});
 
1053   push @args, ("-p", $form->{dbport}) if ($form->{dbport});
 
1056   my $cmd = "$main::pg_restore_exe " . join(" ", map { s/\\/\\\\/g; s/\"/\\\"/g; $_ } @args);
 
1058   my $in = IO::File->new("$cmd 2>&1 |");
 
1061     unlink "${tmpdir}/.pgpass", $tmp;
 
1064     $form->error($locale->text('The pg_restore process could not be started.'));
 
1067   $English::AUTOFLUSH = 1;
 
1070   print $form->parse_html_template("admin/restore_dataset_start_header");
 
1072   while (my $line = <$in>) {
 
1077   $form->{retval} = $CHILD_ERROR >> 8;
 
1078   print $form->parse_html_template("admin/restore_dataset_start_footer");
 
1080   unlink "${tmpdir}/.pgpass", $tmp;
 
1085   my $form   = $main::form;
 
1086   my $locale = $main::locale;
 
1088   unlink "$main::userspath/nologin";
 
1090   $form->{callback} = "admin.pl?action=list_users";
 
1092   $form->redirect($locale->text('Lockfile removed!'));
 
1097   my $form   = $main::form;
 
1098   my $locale = $main::locale;
 
1100   open(FH, ">$main::userspath/nologin")
 
1101     or $form->error($locale->text('Cannot create Lock!'));
 
1104   $form->{callback} = "admin.pl?action=list_users";
 
1106   $form->redirect($locale->text('Lockfile created!'));
 
1111   call_sub($main::form->{yes_nextsub});
 
1115   call_sub($main::form->{no_nextsub});
 
1119   call_sub($main::form->{add_nextsub});
 
1123   my $form = $main::form;
 
1125   $form->{edit_nextsub} ||= 'edit_user';
 
1127   call_sub($form->{edit_nextsub});
 
1131   my $form     = $main::form;
 
1133   $form->{delete_nextsub} ||= 'delete_user';
 
1135   call_sub($form->{delete_nextsub});
 
1139   my $form = $main::form;
 
1141   $form->{save_nextsub} ||= 'save_user';
 
1143   call_sub($form->{save_nextsub});
 
1147   call_sub($main::form->{back_nextsub});
 
1151   my $form   = $main::form;
 
1152   my $locale = $main::locale;
 
1154   foreach my $action (qw(create_standard_group dont_create_standard_group
 
1155                          save_user delete_user save_user_as_new)) {
 
1156     if ($form->{"action_${action}"}) {
 
1162   call_sub($form->{default_action}) if ($form->{default_action});
 
1164   $form->error($locale->text('No action defined.'));