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 #======================================================================
 
  35 my $menufile = "menu.ini";
 
  39 use English qw(-no_match_vars);
 
  43 use POSIX qw(strftime);
 
  55 require "bin/mozilla/common.pl";
 
  56 require "bin/mozilla/admin_groups.pl";
 
  60 our $cgi    = new CGI('');
 
  62 our $locale = new Locale $main::language, "admin";
 
  63 our $auth = SL::Auth->new();
 
  65 if ($auth->session_tables_present()) {
 
  66   $auth->expire_sessions();
 
  67   $auth->restore_session();
 
  68   $auth->set_session_value('rpw', $form->{rpw});
 
  72 if (-f "bin/mozilla/custom_$form->{script}") {
 
  73   eval { require "bin/mozilla/custom_$form->{script}"; };
 
  74   $form->error($@) if ($@);
 
  77 $form->{stylesheet} = "lx-office-erp.css";
 
  78 $form->{favicon}    = "favicon.ico";
 
  80 if ($form->{action}) {
 
  81   if ($auth->authenticate_root($form->{rpw}, 0) != $auth->OK()) {
 
  82     $form->{error_message} = $locale->text('Incorrect Password!');
 
  87   $auth->create_or_refresh_session() if ($auth->session_tables_present());
 
  89   call_sub($locale->findsub($form->{action}));
 
  91 } elsif ($auth->authenticate_root($form->{rpw}, 0) == $auth->OK()) {
 
  93   $auth->create_or_refresh_session() if ($auth->session_tables_present());
 
  98   # if there are no drivers bail out
 
  99   $form->error($locale->text('No Database Drivers available!'))
 
 100     unless (User->dbdrivers);
 
 111   my $form     = $main::form;
 
 112   my $locale   = $main::locale;
 
 114   $form->{title} = qq|Lx-Office ERP $form->{version} | . $locale->text('Administration');
 
 117   print $form->parse_html_template('admin/adminlogin');
 
 121   check_auth_db_and_tables();
 
 126   $main::auth->destroy_session();
 
 130 sub check_auth_db_and_tables {
 
 131   my $form     = $main::form;
 
 132   my $locale   = $main::locale;
 
 136   map { $params{"db_${_}"} = $main::auth->{DB_config}->{$_} } keys %{ $auth->{DB_config} };
 
 138   if (!$main::auth->check_database()) {
 
 139     $form->{title} = $locale->text('Authentification database creation');
 
 141     print $form->parse_html_template('admin/check_auth_database', \%params);
 
 146   if (!$main::auth->check_tables()) {
 
 147     $form->{title} = $locale->text('Authentification tables creation');
 
 149     print $form->parse_html_template('admin/check_auth_tables', \%params);
 
 154   if (-f $main::memberfile) {
 
 157     if ($main::memberfile =~ m|^.*/|) {
 
 161     my $backupdir = "${memberdir}member-file-migration";
 
 163     $form->{title} = $locale->text('User data migration');
 
 165     print $form->parse_html_template('admin/user_migration', { 'memberfile' => $main::memberfile,
 
 166                                                                'backupdir'  => $backupdir });
 
 173   my $form     = $main::form;
 
 175   $main::auth->create_database('superuser'          => $form->{db_superuser},
 
 176                          'superuser_password' => $form->{db_superuser_password},
 
 177                          'template'           => $form->{db_template});
 
 181 sub create_auth_tables {
 
 182   my $form     = $main::form;
 
 183   my $locale   = $main::locale;
 
 185   $main::auth->create_tables();
 
 186   $main::auth->set_session_value('rpw', $form->{rpw});
 
 187   $main::auth->create_or_refresh_session();
 
 189   if (!-f $main::memberfile) {
 
 190     # New installation -- create a standard group with full access
 
 193       'name'        => $locale->text('Full Access'),
 
 194       'description' => $locale->text('Full access to all functions'),
 
 195       'rights'      => { map { $_ => 1 } SL::Auth::all_rights() },
 
 196       'members'     => [ map { $_->{id} } values %members ],
 
 199     $main::auth->save_group($group);
 
 206   $main::lxdebug->enter_sub();
 
 208   my $form     = $main::form;
 
 209   my $locale   = $main::locale;
 
 213   if ($main::memberfile =~ m|^.*/|) {
 
 217   my $backupdir = "${memberdir}member-file-migration";
 
 219   if (! -d $backupdir && !mkdir $backupdir, 0700) {
 
 220     $form->error(sprintf($locale->text('The directory "%s" could not be created:\n%s'), $backupdir, $!));
 
 223   copy $main::memberfile, "users/member-file-migration/members";
 
 225   my $in = IO::File->new($main::memberfile, "r");
 
 227   $form->error($locale->text('Could not open the old memberfile.')) if (!$in);
 
 229   my (%members, $login);
 
 238       $login =~ s/(\[|\])//g;
 
 242       $members{$login} = { "login" => $login };
 
 246     if ($login && m/=/) {
 
 247       my ($key, $value) = split m/\s*=\s*/, $_, 2;
 
 252       $value =~ s|\\n|\n|g;
 
 254       $members{$login}->{$key} = $value;
 
 260   delete $members{"root login"};
 
 262   map { $_->{dbpasswd} = unpack 'u', $_->{dbpasswd} } values %members;
 
 264   while (my ($login, $params) = each %members) {
 
 265     $main::auth->save_user($login, %{ $params });
 
 266     $main::auth->change_password($login, $params->{password}, 1);
 
 268     my $conf_file = "${memberdir}${login}.conf";
 
 271       copy   $conf_file, "${backupdir}/${login}.conf";
 
 276   unlink $main::memberfile;
 
 278   my @member_list = sort { lc $a->{login} cmp lc $b->{login} } values %members;
 
 280   $form->{title} = $locale->text('User data migration');
 
 282   print $form->parse_html_template('admin/user_migration_done', { 'MEMBERS' => \@member_list });
 
 284   $main::lxdebug->leave_sub();
 
 287 sub create_standard_group_ask {
 
 288   my $form     = $main::form;
 
 289   my $locale   = $main::locale;
 
 291   $form->{title} = $locale->text('Create a standard group');
 
 294   print $form->parse_html_template("admin/create_standard_group_ask");
 
 297 sub create_standard_group {
 
 298   my $form     = $main::form;
 
 299   my $locale   = $main::locale;
 
 301   my %members = $main::auth->read_all_users();
 
 303   my $groups = $main::auth->read_groups();
 
 305   foreach my $group (values %{$groups}) {
 
 306     if (($form->{group_id} != $group->{id})
 
 307         && ($form->{name} eq $group->{name})) {
 
 308       $form->show_generic_error($locale->text("A group with that name does already exist."));
 
 313     'name'        => $locale->text('Full Access'),
 
 314     'description' => $locale->text('Full access to all functions'),
 
 315     'rights'      => { map { $_ => 1 } SL::Auth::all_rights() },
 
 316     'members'     => [ map { $_->{id} } values %members ],
 
 319   $main::auth->save_group($group);
 
 321   user_migration_complete(1);
 
 324 sub dont_create_standard_group {
 
 325   user_migration_complete(0);
 
 328 sub user_migration_complete {
 
 329   my $standard_group_created = shift;
 
 331   my $form     = $main::form;
 
 332   my $locale   = $main::locale;
 
 334   $form->{title} = $locale->text('User migration complete');
 
 337   print $form->parse_html_template('admin/user_migration_complete', { 'standard_group_created' => $standard_group_created });
 
 341   my $form     = $main::form;
 
 342   my $locale   = $main::locale;
 
 344   my %members = $main::auth->read_all_users();
 
 346   delete $members{"root login"};
 
 348   map { $_->{templates} =~ s|.*/||; } values %members;
 
 350   $form->{title}   = "Lx-Office ERP " . $locale->text('Administration');
 
 351   $form->{LOCKED}  = -e "$main::userspath/nologin";
 
 352   $form->{MEMBERS} = [ @members{sort { lc $a cmp lc $b } keys %members} ];
 
 355   print $form->parse_html_template("admin/list_users");
 
 360   my $form     = $main::form;
 
 361   my $locale   = $main::locale;
 
 365     . $locale->text('Administration') . " / "
 
 366     . $locale->text('Add User');
 
 370     "countrycode"  => "de",
 
 371     "numberformat" => "1.000,00",
 
 372     "dateformat"   => "dd.mm.yy",
 
 373     "stylesheet"   => "lx-office-erp.css",
 
 377   edit_user_form($myconfig);
 
 381   my $form     = $main::form;
 
 382   my $locale   = $main::locale;
 
 387     . $locale->text('Administration') . " / "
 
 388     . $locale->text('Edit User');
 
 391   $form->isblank("login", $locale->text("The login is missing."));
 
 394   my $myconfig = new User($form->{login});
 
 396   # strip basedir from templates directory
 
 397   $myconfig->{templates} =~ s|.*/||;
 
 399   edit_user_form($myconfig);
 
 405   my $form     = $main::form;
 
 406   my $locale   = $main::locale;
 
 408   my @valid_dateformats = qw(mm-dd-yy mm/dd/yy dd-mm-yy dd/mm/yy dd.mm.yy yyyy-mm-dd);
 
 409   $form->{ALL_DATEFORMATS} = [ map { { "format" => $_, "selected" => $_ eq $myconfig->{dateformat} } } @valid_dateformats ];
 
 411   my @valid_numberformats = ('1,000.00', '1000.00', '1.000,00', '1000,00');
 
 412   $form->{ALL_NUMBERFORMATS} = [ map { { "format" => $_, "selected" => $_ eq $myconfig->{numberformat} } } @valid_numberformats ];
 
 414   my %countrycodes = User->country_codes;
 
 415   $form->{ALL_COUNTRYCODES} = [];
 
 416   foreach my $countrycode (sort { $countrycodes{$a} cmp $countrycodes{$b} } keys %countrycodes) {
 
 417     push @{ $form->{ALL_COUNTRYCODES} }, { "value"    => $countrycode,
 
 418                                            "name"     => $countrycodes{$countrycode},
 
 419                                            "selected" => $countrycode eq $myconfig->{countrycode} };
 
 422   # is there a templates basedir
 
 423   if (!-d "$main::templates") {
 
 424     $form->error(sprintf($locale->text("The directory %s does not exist."), $main::templates));
 
 427   opendir TEMPLATEDIR, "$main::templates/." or $form->error("$main::templates : $ERRNO");
 
 428   my @all     = readdir(TEMPLATEDIR);
 
 429   my @alldir  = sort grep { -d "$main::templates/$_" && !/^\.\.?$/ } @all;
 
 430   my @allhtml = sort grep { -f "$main::templates/$_" && /\.html$/ } @all;
 
 431   closedir TEMPLATEDIR;
 
 433   @alldir = grep !/\.(html|tex|sty|odt|xml|txb)$/, @alldir;
 
 434   @alldir = grep !/^(webpages|\.svn)$/, @alldir;
 
 436   @allhtml = reverse grep !/Default/, @allhtml;
 
 437   push @allhtml, 'Default';
 
 438   @allhtml = reverse @allhtml;
 
 440   $form->{ALL_TEMPLATES} = [ map { { "name", => $_, "selected" => $_ eq $myconfig->{templates} } } @alldir ];
 
 442   my $lastitem = $allhtml[0];
 
 443   $lastitem =~ s/-.*//g;
 
 444   $form->{ALL_MASTER_TEMPLATES} = [ { "name" => $lastitem, "selected" => $lastitem eq "German" } ];
 
 445   foreach my $item (@allhtml) {
 
 447     next if ($item eq $lastitem);
 
 449     push @{ $form->{ALL_MASTER_TEMPLATES} }, { "name" => $item, "selected" => $item eq "German" };
 
 453   # css dir has styles that are not intended as general layouts.
 
 454   # reverting to hardcoded list
 
 455   $form->{ALL_STYLESHEETS} = [ map { { "name" => $_, "selected" => $_ eq $myconfig->{stylesheet} } } qw(lx-office-erp.css Win2000.css) ];
 
 457   $form->{"menustyle_" . $myconfig->{menustyle} } = 1;
 
 459   map { $form->{"myc_${_}"} = $myconfig->{$_} } keys %{ $myconfig };
 
 464     my $user_id    = $main::auth->get_user_id($form->{login});
 
 465     my $all_groups = $main::auth->read_groups();
 
 467     foreach my $group (values %{ $all_groups }) {
 
 468       push @{ $groups }, $group if (grep { $user_id == $_ } @{ $group->{members} });
 
 471     $groups = [ sort { lc $a->{name} cmp lc $b->{name} } @{ $groups } ];
 
 474   $form->{CAN_CHANGE_PASSWORD} = $main::auth->can_change_password();
 
 477   print $form->parse_html_template("admin/edit_user", { 'GROUPS' => $groups });
 
 481   my $form     = $main::form;
 
 482   my $locale   = $main::locale;
 
 484   $form->{dbdriver} = 'Pg';
 
 486   # no spaces allowed in login name
 
 487   $form->{login} =~ s|\s||g;
 
 488   $form->isblank("login", $locale->text('Login name missing!'));
 
 490   # check for duplicates
 
 491   if (!$form->{edit}) {
 
 492     my %members = $main::auth->read_all_users();
 
 493     if ($members{$form->{login}}) {
 
 494       $form->show_generic_error($locale->text('Another user with the login #1 does already exist.', $form->{login}), 'back_button' => 1);
 
 498   # no spaces allowed in directories
 
 499   ($form->{newtemplates}) = split / /, $form->{newtemplates};
 
 501   if ($form->{newtemplates}) {
 
 502     $form->{templates} = $form->{newtemplates};
 
 505       ($form->{usetemplates}) ? $form->{usetemplates} : $form->{login};
 
 509   if (!-d "$main::templates") {
 
 510     $form->error(sprintf($locale->text("The directory %s does not exist."), $main::templates));
 
 513   # add base directory to $form->{templates}
 
 514   $form->{templates} =~ s|.*/||;
 
 515   $form->{templates} =  "$main::templates/$form->{templates}";
 
 517   my $myconfig = new User($form->{login});
 
 519   $form->isblank("dbname", $locale->text('Dataset missing!'));
 
 520   $form->isblank("dbuser", $locale->text('Database User missing!'));
 
 522   foreach my $item (keys %{$form}) {
 
 523     $myconfig->{$item} = $form->{$item};
 
 526   delete $myconfig->{stylesheet};
 
 527   if ($form->{userstylesheet}) {
 
 528     $myconfig->{stylesheet} = $form->{userstylesheet};
 
 531   $myconfig->save_member();
 
 533   if ($main::auth->can_change_password()
 
 534       && defined $form->{new_password}
 
 535       && ($form->{new_password} ne '********')) {
 
 536     $main::auth->change_password($form->{login}, $form->{new_password});
 
 539   my ($login, $password, $newfile);
 
 542       qw(angebote bestellungen rechnungen anfragen lieferantenbestellungen einkaufsrechnungen);
 
 543     foreach my $directory (@webdavdirs) {
 
 544       my $file = "webdav/" . $directory . "/webdav-user";
 
 545       if ($form->{$directory}) {
 
 546         if (open(HTACCESS, "$file")) {
 
 548             ($login, $password) = split(/:/, $_);
 
 549             if ($login ne $form->{login}) {
 
 555         open(HTACCESS, "> $file") or die "cannot open $file $ERRNO\n";
 
 556         $newfile .= $myconfig->{login} . ":" . $myconfig->{password} . "\n";
 
 557         print(HTACCESS $newfile);
 
 560         $form->{$directory} = 0;
 
 561         if (open(HTACCESS, "$file")) {
 
 563             ($login, $password) = split(/:/, $_);
 
 564             if ($login ne $form->{login}) {
 
 570         open(HTACCESS, "> $file") or die "cannot open $file $ERRNO\n";
 
 571         print(HTACCESS $newfile);
 
 577   $form->{templates}       =~ s|.*/||;
 
 578   $form->{templates}       =  "$main::templates/$form->{templates}";
 
 579   $form->{mastertemplates} =~ s|.*/||;
 
 581   # create user template directory and copy master files
 
 582   if (!-d "$form->{templates}") {
 
 585     if (mkdir "$form->{templates}", oct("771")) {
 
 589       # copy templates to the directory
 
 590       opendir TEMPLATEDIR, "$main::templates/." or $form->error("$main::templates : $ERRNO");
 
 591       my @templates = grep /$form->{mastertemplates}.*?\.(html|tex|sty|odt|xml|txb)$/,
 
 593       closedir TEMPLATEDIR;
 
 595       foreach my $file (@templates) {
 
 596         open(TEMP, "$main::templates/$file")
 
 597           or $form->error("$main::templates/$file : $ERRNO");
 
 599         $file =~ s/\Q$form->{mastertemplates}\E-//;
 
 600         open(NEW, ">$form->{templates}/$file")
 
 601           or $form->error("$form->{templates}/$file : $ERRNO");
 
 603         while (my $line = <TEMP>) {
 
 610       $form->error("$ERRNO: $form->{templates}");
 
 614   # Add new user to his groups.
 
 615   if (ref $form->{new_user_group_ids} eq 'ARRAY') {
 
 616     my $all_groups = $main::auth->read_groups();
 
 617     my %user       = $main::auth->read_user($form->{login});
 
 619     foreach my $group_id (@{ $form->{new_user_group_ids} }) {
 
 620       my $group = $all_groups->{$group_id};
 
 624       push @{ $group->{members} }, $user{id};
 
 625       $main::auth->save_group($group);
 
 629   $form->redirect($locale->text('User saved!'));
 
 633 sub save_user_as_new {
 
 634   my $form     = $main::form;
 
 636   $form->{login} = $form->{new_user_login};
 
 637   delete @{$form}{qw(edit new_user_login)};
 
 643   my $form     = $main::form;
 
 644   my $locale   = $main::locale;
 
 646   my %members   = $main::auth->read_all_users();
 
 647   my $templates = $members{$form->{login}}->{templates};
 
 649   $main::auth->delete_user($form->{login});
 
 652     my $templates_in_use = 0;
 
 654     foreach my $login (keys %members) {
 
 655       next if $form->{login} eq $login;
 
 656       next if $members{$login}->{templates} ne $templates;
 
 657       $templates_in_use = 1;
 
 661     if (!$templates_in_use && -d $templates) {
 
 662       unlink <$templates/*>;
 
 667   $form->redirect($locale->text('User deleted!'));
 
 675   return ($login) ? $login : undef;
 
 682   my $form     = $main::form;
 
 684   my ($null, $value) = split(/=/, $line, 2);
 
 687   $value =~ s/\s#.*//g;
 
 689   # remove any trailing whitespace
 
 690   $value =~ s/^\s*(.*?)\s*$/$1/;
 
 695 sub pg_database_administration {
 
 696   my $form     = $main::form;
 
 698   $form->{dbdriver} = 'Pg';
 
 703 sub dbselect_source {
 
 704   my $form     = $main::form;
 
 705   my $locale   = $main::locale;
 
 707   $form->{dbport}    = '5432';
 
 708   $form->{dbuser}    = 'postgres';
 
 709   $form->{dbdefault} = 'template1';
 
 710   $form->{dbhost}    = 'localhost';
 
 712   $form->{title}     = "Lx-Office ERP / " . $locale->text('Database Administration');
 
 714   # Intentionnaly disabled unless fixed to work with the authentication DB.
 
 715   $form->{ALLOW_DBBACKUP} = 0; # "$pg_dump_exe" ne "DISABLED";
 
 718   print $form->parse_html_template("admin/dbadmin");
 
 721 sub test_db_connection {
 
 722   my $form     = $main::form;
 
 723   my $locale   = $main::locale;
 
 725   $form->{dbdriver} = 'Pg';
 
 726   User::dbconnect_vars($form, $form->{dbname});
 
 728   my $dbh = DBI->connect($form->{dbconnect}, $form->{dbuser}, $form->{dbpasswd});
 
 730   $form->{connection_ok} = $dbh ? 1 : 0;
 
 731   $form->{errstr}        = $DBI::errstr;
 
 733   $dbh->disconnect() if ($dbh);
 
 735   $form->{title} = $locale->text('Database Connection Test');
 
 737   print $form->parse_html_template("admin/test_db_connection");
 
 741   call_sub($main::form->{"nextsub"});
 
 745   my $form     = $main::form;
 
 746   my $locale   = $main::locale;
 
 750     . $locale->text('Database Administration') . " / "
 
 751     . $locale->text('Update Dataset');
 
 753   my @need_updates      = User->dbneedsupdate($form);
 
 754   $form->{NEED_UPDATES} = \@need_updates;
 
 755   $form->{ALL_UPDATED}  = !scalar @need_updates;
 
 758   print $form->parse_html_template("admin/update_dataset");
 
 762   my $form     = $main::form;
 
 763   my $locale   = $main::locale;
 
 765   $form->{stylesheet} = "lx-office-erp.css";
 
 766   $form->{title}      = $locale->text("Dataset upgrade");
 
 769   my $rowcount           = $form->{rowcount} * 1;
 
 770   my @update_rows        = grep { $form->{"update_$_"} } (1 .. $rowcount);
 
 771   $form->{NOTHING_TO_DO} = !scalar @update_rows;
 
 772   my $saved_form         = save_form();
 
 776   print $form->parse_html_template("admin/dbupgrade_all_header");
 
 778   foreach my $i (@update_rows) {
 
 779     restore_form($saved_form);
 
 781     map { $form->{$_} = $form->{"${_}_${i}"} } qw(dbname dbdriver dbhost dbport dbuser dbpasswd);
 
 783     my $controls = parse_dbupdate_controls($form, $form->{dbdriver});
 
 785     print $form->parse_html_template("admin/dbupgrade_header");
 
 787     $form->{dbupdate}        = $form->{dbname};
 
 788     $form->{$form->{dbname}} = 1;
 
 790     User->dbupdate($form);
 
 791     User->dbupdate2($form, $controls);
 
 793     print $form->parse_html_template("admin/dbupgrade_footer");
 
 796   print $form->parse_html_template("admin/dbupgrade_all_done");
 
 800   my $form     = $main::form;
 
 801   my $locale   = $main::locale;
 
 803   $form->{dbsources} = join " ", map { "[${_}]" } sort User->dbsources($form);
 
 805   $form->{CHARTS} = [];
 
 807   opendir SQLDIR, "sql/." or $form->error($ERRNO);
 
 808   foreach my $item (sort grep /-chart\.sql\z/, readdir SQLDIR) {
 
 809     next if ($item eq 'Default-chart.sql');
 
 810     $item =~ s/-chart\.sql//;
 
 811     push @{ $form->{CHARTS} }, { "name"     => $item,
 
 812                                  "selected" => $item eq "Germany-DATEV-SKR03EU" };
 
 816   my $default_charset = $main::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 ($main::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 };
 
 841     . $locale->text('Database Administration') . " / "
 
 842     . $locale->text('Create Dataset');
 
 845   print $form->parse_html_template("admin/create_dataset");
 
 849   my $form     = $main::form;
 
 850   my $locale   = $main::locale;
 
 852   $form->isblank("db", $locale->text('Dataset missing!'));
 
 854   User->dbcreate(\%$form);
 
 858     . $locale->text('Database Administration') . " / "
 
 859     . $locale->text('Create Dataset');
 
 862   print $form->parse_html_template("admin/dbcreate");
 
 866   my $form     = $main::form;
 
 867   my $locale   = $main::locale;
 
 869   my @dbsources = User->dbsources_unused($form);
 
 870   $form->error($locale->text('Nothing to delete!')) unless @dbsources;
 
 874     . $locale->text('Database Administration') . " / "
 
 875     . $locale->text('Delete Dataset');
 
 876   $form->{DBSOURCES} = [ map { { "name", $_ } } sort @dbsources ];
 
 879   print $form->parse_html_template("admin/delete_dataset");
 
 883   my $form     = $main::form;
 
 884   my $locale   = $main::locale;
 
 887     $form->error($locale->text('No Dataset selected!'));
 
 890   User->dbdelete(\%$form);
 
 894     . $locale->text('Database Administration') . " / "
 
 895     . $locale->text('Delete Dataset');
 
 897   print $form->parse_html_template("admin/dbdelete");
 
 901   my $form     = $main::form;
 
 902   my $locale   = $main::locale;
 
 906     . $locale->text('Database Administration') . " / "
 
 907     . $locale->text('Backup Dataset');
 
 909   if ("$main::pg_dump_exe" eq "DISABLED") {
 
 910     $form->error($locale->text('Database backups and restorations are disabled in lx-erp.conf.'));
 
 913   my @dbsources         = sort User->dbsources($form);
 
 914   $form->{DATABASES}    = [ map { { "dbname" => $_ } } @dbsources ];
 
 915   $form->{NO_DATABASES} = !scalar @dbsources;
 
 917   my $username  = getpwuid $UID || "unknown-user";
 
 918   my $hostname  = hostname() || "unknown-host";
 
 919   $form->{from} = "Lx-Office Admin <${username}\@${hostname}>";
 
 922   print $form->parse_html_template("admin/backup_dataset");
 
 925 sub backup_dataset_start {
 
 926   my $form     = $main::form;
 
 927   my $locale   = $main::locale;
 
 931     . $locale->text('Database Administration') . " / "
 
 932     . $locale->text('Backup Dataset');
 
 934   $main::pg_dump_exe ||= "pg_dump";
 
 936   if ("$main::pg_dump_exe" eq "DISABLED") {
 
 937     $form->error($locale->text('Database backups and restorations are disabled in lx-erp.conf.'));
 
 940   $form->isblank("dbname", $locale->text('The dataset name is missing.'));
 
 941   $form->isblank("to", $locale->text('The email address is missing.')) if $form->{destination} eq "email";
 
 943   my $tmpdir = "/tmp/lx_office_backup_" . Common->unique_id();
 
 944   mkdir $tmpdir, 0700 || $form->error($locale->text('A temporary directory could not be created:') . " $ERRNO");
 
 946   my $pgpass = IO::File->new("${tmpdir}/.pgpass", O_WRONLY | O_CREAT, 0600);
 
 950     $form->error($locale->text('A temporary file could not be created:') . " $ERRNO");
 
 953   print $pgpass "$form->{dbhost}:$form->{dbport}:$form->{dbname}:$form->{dbuser}:$form->{dbpasswd}\n";
 
 956   $ENV{HOME} = $tmpdir;
 
 958   my @args = ("-Ft", "-c", "-o", "-h", $form->{dbhost}, "-U", $form->{dbuser});
 
 959   push @args, ("-p", $form->{dbport}) if ($form->{dbport});
 
 960   push @args, $form->{dbname};
 
 962   my $cmd  = "$main::pg_dump_exe " . join(" ", map { s/\\/\\\\/g; s/\"/\\\"/g; $_ } @args);
 
 963   my $name = "dataset_backup_$form->{dbname}_" . strftime("%Y%m%d", localtime()) . ".tar";
 
 965   if ($form->{destination} ne "email") {
 
 966     my $in = IO::File->new("$cmd |");
 
 969       unlink "${tmpdir}/.pgpass";
 
 972       $form->error($locale->text('The pg_dump process could not be started.'));
 
 975     print "content-type: application/x-tar\n";
 
 976     print "content-disposition: attachment; filename=\"${name}\"\n\n";
 
 978     while (my $line = <$in>) {
 
 984     unlink "${tmpdir}/.pgpass";
 
 988     my $tmp = $tmpdir . "/dump_" . Common::unique_id();
 
 990     if (system("$cmd > $tmp") != 0) {
 
 991       unlink "${tmpdir}/.pgpass", $tmp;
 
 994       $form->error($locale->text('The pg_dump process could not be started.'));
 
 997     my $mail = new Mailer;
 
 999     map { $mail->{$_} = $form->{$_} } qw(from to cc subject message);
 
1001     $mail->{charset}     = $main::dbcharset ? $main::dbcharset : Common::DEFAULT_CHARSET;
 
1002     $mail->{attachments} = [ { "filename" => $tmp, "name" => $name } ];
 
1005     unlink "${tmpdir}/.pgpass", $tmp;
 
1010       . $locale->text('Database Administration') . " / "
 
1011       . $locale->text('Backup Dataset');
 
1014     print $form->parse_html_template("admin/backup_dataset_email_done");
 
1018 sub restore_dataset {
 
1019   my $form     = $main::form;
 
1020   my $locale   = $main::locale;
 
1024     . $locale->text('Database Administration') . " / "
 
1025     . $locale->text('Restore Dataset');
 
1027   if ("$main::pg_restore_exe" eq "DISABLED") {
 
1028     $form->error($locale->text('Database backups and restorations are disabled in lx-erp.conf.'));
 
1031   my $default_charset   = $main::dbcharset;
 
1032   $default_charset    ||= Common::DEFAULT_CHARSET;
 
1034   $form->{DBENCODINGS}  = [];
 
1036   foreach my $encoding (@Common::db_encodings) {
 
1037     push @{ $form->{DBENCODINGS} }, { "dbencoding" => $encoding->{dbencoding},
 
1038                                       "label"      => $encoding->{label},
 
1039                                       "selected"   => $encoding->{charset} eq $default_charset };
 
1043   print $form->parse_html_template("admin/restore_dataset");
 
1046 sub restore_dataset_start {
 
1047   my $form     = $main::form;
 
1048   my $locale   = $main::locale;
 
1052     . $locale->text('Database Administration') . " / "
 
1053     . $locale->text('Restore Dataset');
 
1055   $main::pg_restore_exe ||= "pg_restore";
 
1057   if ("$main::pg_restore_exe" eq "DISABLED") {
 
1058     $form->error($locale->text('Database backups and restorations are disabled in lx-erp.conf.'));
 
1061   $form->isblank("new_dbname", $locale->text('The dataset name is missing.'));
 
1062   $form->isblank("content", $locale->text('No backup file has been uploaded.'));
 
1064   # Create temporary directories. Write the backup file contents to a temporary
 
1065   # file. Create a .pgpass file with the username and password for the pg_restore
 
1068   my $tmpdir = "/tmp/lx_office_backup_" . Common->unique_id();
 
1069   mkdir $tmpdir, 0700 || $form->error($locale->text('A temporary directory could not be created:') . " $ERRNO");
 
1071   my $pgpass = IO::File->new("${tmpdir}/.pgpass", O_WRONLY | O_CREAT, 0600);
 
1075     $form->error($locale->text('A temporary file could not be created:') . " $ERRNO");
 
1078   print $pgpass "$form->{dbhost}:$form->{dbport}:$form->{new_dbname}:$form->{dbuser}:$form->{dbpasswd}\n";
 
1081   $ENV{HOME} = $tmpdir;
 
1083   my $tmp = $tmpdir . "/dump_" . Common::unique_id();
 
1086   if (substr($form->{content}, 0, 2) eq "\037\213") {
 
1087     $tmpfile = IO::File->new("| gzip -d > $tmp");
 
1091     $tmpfile = IO::File->new($tmp, O_WRONLY | O_CREAT | O_BINARY, 0600);
 
1095     unlink "${tmpdir}/.pgpass";
 
1098     $form->error($locale->text('A temporary file could not be created:') . " $ERRNO");
 
1101   print $tmpfile $form->{content};
 
1104   delete $form->{content};
 
1106   # Try to connect to the database. Find out if a database with the same name exists.
 
1107   # If yes, then drop the existing database. Create a new one with the name and encoding
 
1108   # given by the user.
 
1110   User::dbconnect_vars($form, "template1");
 
1112   my %myconfig = map { $_ => $form->{$_} } grep /^db/, keys %{ $form };
 
1113   my $dbh      = $form->dbconnect(\%myconfig) || $form->dberror();
 
1117   $form->{new_dbname} =~ s|[^a-zA-Z0-9_\-]||g;
 
1119   $query = qq|SELECT COUNT(*) FROM pg_database WHERE datname = ?|;
 
1120   my ($count) = selectrow_query($form, $dbh, $query, $form->{new_dbname});
 
1122     do_query($form, $dbh, qq|DROP DATABASE $form->{new_dbname}|);
 
1126   foreach my $item (@Common::db_encodings) {
 
1127     if ($item->{dbencoding} eq $form->{dbencoding}) {
 
1132   $form->{dbencoding} = "LATIN9" unless $form->{dbencoding};
 
1134   do_query($form, $dbh, qq|CREATE DATABASE $form->{new_dbname} ENCODING ? TEMPLATE template0|, $form->{dbencoding});
 
1138   # Spawn pg_restore on the temporary file.
 
1140   my @args = ("-h", $form->{dbhost}, "-U", $form->{dbuser}, "-d", $form->{new_dbname});
 
1141   push @args, ("-p", $form->{dbport}) if ($form->{dbport});
 
1144   my $cmd = "$main::pg_restore_exe " . join(" ", map { s/\\/\\\\/g; s/\"/\\\"/g; $_ } @args);
 
1146   my $in = IO::File->new("$cmd 2>&1 |");
 
1149     unlink "${tmpdir}/.pgpass", $tmp;
 
1152     $form->error($locale->text('The pg_restore process could not be started.'));
 
1155   $English::AUTOFLUSH = 1;
 
1158   print $form->parse_html_template("admin/restore_dataset_start_header");
 
1160   while (my $line = <$in>) {
 
1165   $form->{retval} = $CHILD_ERROR >> 8;
 
1166   print $form->parse_html_template("admin/restore_dataset_start_footer");
 
1168   unlink "${tmpdir}/.pgpass", $tmp;
 
1173   my $form     = $main::form;
 
1174   my $locale   = $main::locale;
 
1176   unlink "$main::userspath/nologin";
 
1178   $form->{callback} = "admin.pl?action=list_users";
 
1180   $form->redirect($locale->text('Lockfile removed!'));
 
1185   my $form     = $main::form;
 
1186   my $locale   = $main::locale;
 
1188   open(FH, ">$main::userspath/nologin")
 
1189     or $form->error($locale->text('Cannot create Lock!'));
 
1192   $form->{callback} = "admin.pl?action=list_users";
 
1194   $form->redirect($locale->text('Lockfile created!'));
 
1199   call_sub($main::form->{yes_nextsub});
 
1203   call_sub($main::form->{no_nextsub});
 
1207   call_sub($main::form->{add_nextsub});
 
1211   my $form     = $main::form;
 
1213   $form->{edit_nextsub} ||= 'edit_user';
 
1215   call_sub($form->{edit_nextsub});
 
1219   my $form     = $main::form;
 
1221   $form->{delete_nextsub} ||= 'delete_user';
 
1223   call_sub($form->{delete_nextsub});
 
1227   my $form     = $main::form;
 
1229   $form->{save_nextsub} ||= 'save_user';
 
1231   call_sub($form->{save_nextsub});
 
1235   call_sub($main::form->{back_nextsub});
 
1239   my $form     = $main::form;
 
1240   my $locale   = $main::locale;
 
1242   foreach my $action (qw(create_standard_group dont_create_standard_group
 
1243                          save_user delete_user save_user_as_new)) {
 
1244     if ($form->{"action_${action}"}) {
 
1250   call_sub($form->{default_action}) if ($form->{default_action});
 
1252   $form->error($locale->text('No action defined.'));