1 #=====================================================================
 
   4 # Based on SQL-Ledger Version 2.1.9
 
   5 # Web http://www.lx-office.org
 
   7 #=====================================================================
 
   8 # SQL-Ledger Accounting
 
  11 #  Author: Dieter Simader
 
  12 #   Email: dsimader@sql-ledger.org
 
  13 #     Web: http://www.sql-ledger.org
 
  16 # This program is free software; you can redistribute it and/or modify
 
  17 # it under the terms of the GNU General Public License as published by
 
  18 # the Free Software Foundation; either version 2 of the License, or
 
  19 # (at your option) any later version.
 
  21 # This program is distributed in the hope that it will be useful,
 
  22 # but WITHOUT ANY WARRANTY; without even the implied warranty of
 
  23 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 
  24 # GNU General Public License for more details.
 
  25 # You should have received a copy of the GNU General Public License
 
  26 # along with this program; if not, write to the Free Software
 
  27 # Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
 
  28 #======================================================================
 
  31 # add/edit/delete users
 
  33 #======================================================================
 
  37 use English qw(-no_match_vars);
 
  44 use POSIX qw(strftime);
 
  48 use SL::Auth::PasswordPolicy;
 
  58 require "bin/mozilla/common.pl";
 
  59 require "bin/mozilla/admin_groups.pl";
 
  60 require "bin/mozilla/admin_printer.pl";
 
  66 #  $locale->text('periodic')
 
  67 #  $locale->text('income')
 
  68 #  $locale->text('perpetual')
 
  69 #  $locale->text('balance')
 
  76 my @valid_dateformats = qw(mm-dd-yy mm/dd/yy dd-mm-yy dd/mm/yy dd.mm.yy yyyy-mm-dd);
 
  77 my @valid_numberformats = ('1,000.00', '1000.00', '1.000,00', '1000,00');
 
  78 my @all_stylesheets = qw(lx-office-erp.css Win2000.css Mobile.css kivitendo.css);
 
  79 my @all_menustyles = (
 
  80   { id => 'old', title => $::locale->text('Old (on the side)') },
 
  81   { id => 'v3',  title => $::locale->text('Top (CSS)') },
 
  82   { id => 'v4',  title => $::locale->text('Top (CSS) new') },
 
  83   { id => 'neu', title => $::locale->text('Top (Javascript)') },
 
  87   $::lxdebug->enter_sub;
 
  88   my $session_result = shift;
 
  94   $::auth->store_root_credentials_in_session($form->{rpw}) if $session_result == SL::Auth->SESSION_OK;
 
  96   $form->{stylesheet} = "lx-office-erp.css";
 
  97   $form->{favicon}    = "favicon.ico";
 
  99   if ($form->{action}) {
 
 100     if ($auth->authenticate_root($form->{rpw}) != $auth->OK()) {
 
 101       $form->{error_message} = $locale->text('Incorrect Password!');
 
 102       $auth->delete_session_value('rpw');
 
 105       if ($auth->session_tables_present()) {
 
 106         $::auth->store_root_credentials_in_session($::form->{rpw});
 
 107         delete $::form->{rpw};
 
 108         _apply_dbupgrade_scripts();
 
 111       call_sub($locale->findsub($form->{action}));
 
 114     # if there are no drivers bail out
 
 115     $form->error($locale->text('No Database Drivers available!'))
 
 116       unless (User->dbdrivers);
 
 120   $::lxdebug->leave_sub;
 
 124   my $form   = $main::form;
 
 125   my $locale = $main::locale;
 
 127   $form->{title} = qq|kivitendo $form->{version} | . $locale->text('Administration');
 
 130   print $form->parse_html_template('admin/adminlogin');
 
 134   check_auth_db_and_tables();
 
 139   $main::auth->destroy_session();
 
 143 sub check_auth_db_and_tables {
 
 144   my $form   = $main::form;
 
 145   my $locale = $main::locale;
 
 149   map { $params{"db_${_}"} = $main::auth->{DB_config}->{$_} } keys %{ $auth->{DB_config} };
 
 151   if (!$main::auth->check_database()) {
 
 152     $form->{title} = $locale->text('Authentification database creation');
 
 154     print $form->parse_html_template('admin/check_auth_database', \%params);
 
 159   if (!$main::auth->check_tables()) {
 
 160     $form->{title} = $locale->text('Authentification tables creation');
 
 162     print $form->parse_html_template('admin/check_auth_tables', \%params);
 
 167   my $memberfile = $::lx_office_conf{paths}->{memberfile};
 
 168   if (-f $memberfile) {
 
 171     if ($memberfile =~ m|^.*/|) {
 
 175     my $backupdir = "${memberdir}member-file-migration";
 
 177     $form->{title} = $locale->text('User data migration');
 
 179     print $form->parse_html_template('admin/user_migration', { 'memberfile' => $memberfile,
 
 180                                                                'backupdir'  => $backupdir });
 
 187   my $form = $main::form;
 
 189   $main::auth->create_database('superuser'          => $form->{db_superuser},
 
 190                                'superuser_password' => $form->{db_superuser_password},
 
 191                                'template'           => $form->{db_template});
 
 195 sub create_auth_tables {
 
 196   my $form   = $main::form;
 
 197   my $locale = $main::locale;
 
 199   $main::auth->create_tables();
 
 200   $main::auth->set_session_value('rpw', $form->{rpw});
 
 201   $main::auth->create_or_refresh_session();
 
 203   my $memberfile = $::lx_office_conf{paths}->{memberfile};
 
 204   if (!-f $memberfile) {
 
 205     # New installation -- create a standard group with full access
 
 208       'name'        => $locale->text('Full Access'),
 
 209       'description' => $locale->text('Full access to all functions'),
 
 210       'rights'      => { map { $_ => 1 } SL::Auth::all_rights() },
 
 211       'members'     => [ map { $_->{id} } values %members ],
 
 214     $main::auth->save_group($group);
 
 217   _apply_dbupgrade_scripts();
 
 222   $main::lxdebug->enter_sub();
 
 224   my $form      = $main::form;
 
 225   my $locale    = $main::locale;
 
 229   my $memberfile = $::lx_office_conf{paths}->{memberfile};
 
 230   if ($memberfile =~ m|^.*/|) {
 
 234   my $backupdir = "${memberdir}member-file-migration";
 
 236   if (! -d $backupdir && !mkdir $backupdir, 0700) {
 
 237     $form->error(sprintf($locale->text('The directory "%s" could not be created:\n%s'), $backupdir, $!));
 
 240   copy $memberfile, "users/member-file-migration/members";
 
 242   my $in = IO::File->new($memberfile, "r");
 
 244   $form->error($locale->text('Could not open the old memberfile.')) if (!$in);
 
 246   my (%members, $login);
 
 255       $login =~ s/(\[|\])//g;
 
 259       $members{$login} = { "login" => $login };
 
 263     if ($login && m/=/) {
 
 264       my ($key, $value) = split m/\s*=\s*/, $_, 2;
 
 269       $value =~ s|\\n|\n|g;
 
 271       $members{$login}->{$key} = $value;
 
 277   delete $members{"root login"};
 
 279   map { $_->{dbpasswd} = unpack 'u', $_->{dbpasswd} } values %members;
 
 281   while (my ($login, $params) = each %members) {
 
 282     $main::auth->save_user($login, %{ $params });
 
 283     $main::auth->change_password($login, $params->{password}, 1);
 
 285     my $conf_file = "${memberdir}${login}.conf";
 
 288       copy   $conf_file, "${backupdir}/${login}.conf";
 
 295   my @member_list = sort { lc $a->{login} cmp lc $b->{login} } values %members;
 
 297   $form->{title} = $locale->text('User data migration');
 
 299   print $form->parse_html_template('admin/user_migration_done', { 'MEMBERS' => \@member_list });
 
 301   $main::lxdebug->leave_sub();
 
 304 sub create_standard_group_ask {
 
 305   my $form   = $main::form;
 
 306   my $locale = $main::locale;
 
 308   $form->{title} = $locale->text('Create a standard group');
 
 311   print $form->parse_html_template("admin/create_standard_group_ask");
 
 314 sub create_standard_group {
 
 315   my $form    = $main::form;
 
 316   my $locale  = $main::locale;
 
 318   my %members = $main::auth->read_all_users();
 
 320   my $groups  = $main::auth->read_groups();
 
 322   foreach my $group (values %{$groups}) {
 
 323     if (($form->{group_id} != $group->{id})
 
 324         && ($form->{name} eq $group->{name})) {
 
 325       $form->show_generic_error($locale->text("A group with that name does already exist."));
 
 330     'name'        => $locale->text('Full Access'),
 
 331     'description' => $locale->text('Full access to all functions'),
 
 332     'rights'      => { map { $_ => 1 } SL::Auth::all_rights() },
 
 333     'members'     => [ map { $_->{id} } values %members ],
 
 336   $main::auth->save_group($group);
 
 338   user_migration_complete(1);
 
 341 sub dont_create_standard_group {
 
 342   user_migration_complete(0);
 
 345 sub user_migration_complete {
 
 346   my $standard_group_created = shift;
 
 348   my $form                   = $main::form;
 
 349   my $locale                 = $main::locale;
 
 351   $form->{title} = $locale->text('User migration complete');
 
 354   print $form->parse_html_template('admin/user_migration_complete', { 'standard_group_created' => $standard_group_created });
 
 358   my $form    = $main::form;
 
 359   my $locale  = $main::locale;
 
 361   my %members = $main::auth->read_all_users();
 
 363   delete $members{"root login"};
 
 365   for (values %members) {
 
 366     $_->{templates} =~ s|.*/||;
 
 367     $_->{login_url} =  $::locale->is_utf8 ? Encode::encode('utf-8-strict', $_->{login}) : $_->{login_url};
 
 370   $form->{title}   = "kivitendo " . $locale->text('Administration');
 
 371   $form->{LOCKED}  = -e _nologin_file_name();
 
 372   $form->{MEMBERS} = [ @members{sort { lc $a cmp lc $b } keys %members} ];
 
 375   print $form->parse_html_template("admin/list_users");
 
 379   $::form->{title}   = "kivitendo " . $::locale->text('Administration') . " / " . $::locale->text('Add User');
 
 381 # Note: Menu Style 'v3' is not compatible to all browsers!
 
 382 # "menustyle"    => "old" sets the HTML Menu to default.
 
 383 # User does not have a well behaved new constructor, so we#Ll just have to build one ourself
 
 386     "countrycode"  => "de",
 
 387     "numberformat" => "1.000,00",
 
 388     "dateformat"   => "dd.mm.yy",
 
 389     "stylesheet"   => "lx-office-erp.css",
 
 390     "menustyle"    => "old",
 
 391     dbport         => $::auth->{DB_config}->{port} || 5432,
 
 392     dbuser         => $::auth->{DB_config}->{user} || 'lxoffice',
 
 393     dbhost         => $::auth->{DB_config}->{host} || 'localhost',
 
 396   edit_user_form($user);
 
 400   $::form->{title} = "kivitendo " . $::locale->text('Administration') . " / " . $::locale->text('Edit User');
 
 404   my $user = User->new(id => $::form->{user}{id});
 
 406   # strip basedir from templates directory
 
 407   $user->{templates} =~ s|.*/||;
 
 409   edit_user_form($user);
 
 415   my %cc = $user->country_codes;
 
 416   my @all_countrycodes = map { id => $_, title => $cc{$_} }, sort { $cc{$a} cmp $cc{$b} } keys %cc;
 
 417   my ($all_dir, $all_master) = _search_templates();
 
 420   if ($::form->{edit}) {
 
 421     my $user_id    = $::auth->get_user_id($user->{login});
 
 422     my $all_groups = $::auth->read_groups();
 
 424     for my $group (values %{ $all_groups }) {
 
 425       push @{ $groups }, $group if (grep { $user_id == $_ } @{ $group->{members} });
 
 428     $groups = [ sort { lc $a->{name} cmp lc $b->{name} } @{ $groups } ];
 
 432   print $::form->parse_html_template("admin/edit_user", {
 
 434     CAN_CHANGE_PASSWORD  => $::auth->can_change_password,
 
 436     all_stylesheets      => \@all_stylesheets,
 
 437     all_numberformats    => \@valid_numberformats,
 
 438     all_dateformats      => \@valid_dateformats,
 
 439     all_countrycodes     => \@all_countrycodes,
 
 440     all_menustyles       => \@all_menustyles,
 
 441     all_templates        => $all_dir,
 
 442     all_master_templates => $all_master,
 
 447   my $form          = $main::form;
 
 448   my $locale        = $main::locale;
 
 450   my $user = $form->{user};
 
 452   $user->{dbdriver} = 'Pg';
 
 454   if (!$::form->{edit}) {
 
 455     # no spaces allowed in login name
 
 456     $user->{login} =~ s/\s//g;
 
 457     $::form->show_generic_error($::locale->text('Login name missing!')) unless $user->{login};
 
 459     # check for duplicates
 
 460     my %members = $::auth->read_all_users;
 
 461     if ($members{$user->{login}}) {
 
 462       $::form->show_generic_error($locale->text('Another user with the login #1 does already exist.', $user->{login}), 'back_button' => 1);
 
 466   # no spaces allowed in directories
 
 467   ($::form->{newtemplates}) = split / /, $::form->{newtemplates};
 
 468   $user->{templates} = $::form->{newtemplates} || $::form->{usetemplates} || $user->{login};
 
 471   if (!-d $::lx_office_conf{paths}->{templates}) {
 
 472     $::form->error(sprintf($::locale->text("The directory %s does not exist."), $::lx_office_conf{paths}->{templates}));
 
 475   # add base directory to $form->{templates}
 
 476   $user->{templates} =~ s|.*/||;
 
 477   $user->{templates} =  $::lx_office_conf{paths}->{templates} . "/$user->{templates}";
 
 479   my $myconfig = new User(id => $user->{id});
 
 481   $::form->show_generic_error($::locale->text('Dataset missing!'))       unless $user->{dbname};
 
 482   $::form->show_generic_error($::locale->text('Database User missing!')) unless $user->{dbuser};
 
 484   foreach my $item (keys %{$user}) {
 
 485     $myconfig->{$item} = $user->{$item};
 
 488   $myconfig->save_member;
 
 490   $user->{templates}       =~ s|.*/||;
 
 491   $user->{templates}       =  $::lx_office_conf{paths}->{templates} . "/$user->{templates}";
 
 492   $::form->{mastertemplates} =~ s|.*/||;
 
 494   # create user template directory and copy master files
 
 495   if (!-d "$user->{templates}") {
 
 498     if (mkdir "$user->{templates}", oct("771")) {
 
 502       # copy templates to the directory
 
 504       my $oldcurrdir = getcwd();
 
 505       if (!chdir("$::lx_office_conf{paths}->{templates}/print/$::form->{mastertemplates}")) {
 
 506         $form->error("$ERRNO: chdir $::lx_office_conf{paths}->{templates}/print/$::form->{mastertemplates}");
 
 509       my $newdir = File::Spec->catdir($oldcurrdir, $user->{templates});
 
 517             if (!mkdir (File::Spec->catdir($newdir, $File::Find::name))) {
 
 519               $form->error("$ERRNO: mkdir $File::Find::name");
 
 522             if (!symlink (readlink($_),
 
 523                           File::Spec->catfile($newdir, $File::Find::name))) {
 
 525               $form->error("$ERRNO: symlink $File::Find::name");
 
 528             if (!copy($_, File::Spec->catfile($newdir, $File::Find::name))) {
 
 530               $form->error("$ERRNO: cp $File::Find::name");
 
 538       $form->error("$ERRNO: $user->{templates}");
 
 542   # Add new user to his groups.
 
 543   if (ref $form->{new_user_group_ids} eq 'ARRAY') {
 
 544     my $all_groups = $main::auth->read_groups();
 
 545     my %user       = $main::auth->read_user(login => $myconfig->{login});
 
 547     foreach my $group_id (@{ $form->{new_user_group_ids} }) {
 
 548       my $group = $all_groups->{$group_id};
 
 552       push @{ $group->{members} }, $user{id};
 
 553       $main::auth->save_group($group);
 
 557   if ($main::auth->can_change_password()
 
 558       && defined $::form->{new_password}
 
 559       && ($::form->{new_password} ne '********')) {
 
 560     my $verifier = SL::Auth::PasswordPolicy->new;
 
 561     my $result   = $verifier->verify($::form->{new_password}, 1);
 
 563     if ($result != SL::Auth::PasswordPolicy->OK()) {
 
 564       $form->error($::locale->text('The settings were saved, but the password was not changed.') . ' ' . join(' ', $verifier->errors($result)));
 
 567     $main::auth->change_password($myconfig->{login}, $::form->{new_password});
 
 570   $::form->redirect($::locale->text('User saved!'));
 
 573 sub save_user_as_new {
 
 574   my $form       = $main::form;
 
 576   $form->{user}{login} = $::form->{new_user_login};
 
 577   delete $form->{user}{id};
 
 578   delete @{$form}{qw(id edit new_user_login)};
 
 584   my $form      = $main::form;
 
 585   my $locale    = $main::locale;
 
 587   my $user = $::form->{user} || {};
 
 589   $::form->show_generic_error($::locale->text('Missing user id!')) unless $user->{id};
 
 591   my $loaded_user = User->new(id => $user->{id});
 
 593   my %members   = $main::auth->read_all_users();
 
 594   my $templates = $members{$loaded_user->{login}}->{templates};
 
 596   $main::auth->delete_user($loaded_user->{login});
 
 599     my $templates_in_use = 0;
 
 601     foreach my $login (keys %members) {
 
 602       next if $loaded_user->{login} eq $login;
 
 603       next if $members{$login}->{templates} ne $templates;
 
 604       $templates_in_use = 1;
 
 608     if (!$templates_in_use && -d $templates) {
 
 609       unlink <$templates/*>;
 
 614   $form->redirect($locale->text('User deleted!'));
 
 622   return ($login) ? $login : undef;
 
 628   my ($null, $value) = split(/=/, $line, 2);
 
 631   $value =~ s/\s#.*//g;
 
 633   # remove any trailing whitespace
 
 634   $value =~ s/^\s*(.*?)\s*$/$1/;
 
 639 sub pg_database_administration {
 
 640   my $form = $main::form;
 
 642   $form->{dbdriver} = 'Pg';
 
 647 sub dbselect_source {
 
 648   my $form           = $main::form;
 
 649   my $locale         = $main::locale;
 
 651   $form->{dbport}    = $::auth->{DB_config}->{port} || 5432;
 
 652   $form->{dbuser}    = $::auth->{DB_config}->{user} || 'lxoffice';
 
 653   $form->{dbdefault} = 'template1';
 
 654   $form->{dbhost}    = $::auth->{DB_config}->{host} || 'localhost';
 
 656   $form->{title}     = "kivitendo / " . $locale->text('Database Administration');
 
 658   # Intentionnaly disabled unless fixed to work with the authentication DB.
 
 659   $form->{ALLOW_DBBACKUP} = 0; # "$pg_dump_exe" ne "DISABLED";
 
 662   print $form->parse_html_template("admin/dbadmin");
 
 665 sub test_db_connection {
 
 666   my $form   = $main::form;
 
 667   my $locale = $main::locale;
 
 669   $form->{dbdriver} = 'Pg';
 
 670   User::dbconnect_vars($form, $form->{dbname});
 
 672   my $dbh = DBI->connect($form->{dbconnect}, $form->{dbuser}, $form->{dbpasswd});
 
 674   $form->{connection_ok} = $dbh ? 1 : 0;
 
 675   $form->{errstr}        = $DBI::errstr;
 
 677   $dbh->disconnect() if ($dbh);
 
 679   $form->{title} = $locale->text('Database Connection Test');
 
 681   print $form->parse_html_template("admin/test_db_connection");
 
 685   call_sub($main::form->{"nextsub"});
 
 689   my $form              = $main::form;
 
 690   my $locale            = $main::locale;
 
 692   $form->{title}        = "kivitendo " . $locale->text('Database Administration') . " / " . $locale->text('Update Dataset');
 
 694   my @need_updates      = User->dbneedsupdate($form);
 
 695   $form->{NEED_UPDATES} = \@need_updates;
 
 696   $form->{ALL_UPDATED}  = !scalar @need_updates;
 
 699   print $form->parse_html_template("admin/update_dataset");
 
 703   my $form            = $main::form;
 
 704   my $locale          = $main::locale;
 
 706   $form->{stylesheet} = "lx-office-erp.css";
 
 707   $form->{title}      = $locale->text("Dataset upgrade");
 
 710   my $rowcount           = $form->{rowcount} * 1;
 
 711   my @update_rows        = grep { $form->{"update_$_"} } (1 .. $rowcount);
 
 712   $form->{NOTHING_TO_DO} = !scalar @update_rows;
 
 713   my $saved_form         = save_form();
 
 717   print $form->parse_html_template("admin/dbupgrade_all_header");
 
 719   foreach my $i (@update_rows) {
 
 720     restore_form($saved_form);
 
 723     map { $form->{$_} = $::myconfig{$_} = $form->{"${_}_${i}"} } qw(dbname dbdriver dbhost dbport dbuser dbpasswd);
 
 725     print $form->parse_html_template("admin/dbupgrade_header");
 
 727     $form->{dbupdate}        = $form->{dbname};
 
 728     $form->{$form->{dbname}} = 1;
 
 730     User->dbupdate($form);
 
 731     User->dbupdate2($form, SL::DBUpgrade2->new(form => $form, dbdriver => $form->{dbdriver})->parse_dbupdate_controls);
 
 733     print $form->parse_html_template("admin/dbupgrade_footer");
 
 736   print $form->parse_html_template("admin/dbupgrade_all_done");
 
 740   my $form           = $main::form;
 
 741   my $locale         = $main::locale;
 
 743   $form->{dbsources} = join " ", map { "[${_}]" } sort User->dbsources($form);
 
 745   $form->{CHARTS}    = [];
 
 747   opendir SQLDIR, "sql/." or $form->error($ERRNO);
 
 748   foreach my $item (sort grep /-chart\.sql\z/, readdir SQLDIR) {
 
 749     next if ($item eq 'Default-chart.sql');
 
 750     $item =~ s/-chart\.sql//;
 
 751     push @{ $form->{CHARTS} }, { "name"     => $item,
 
 752                                  "selected" => $item eq "Germany-DATEV-SKR03EU" };
 
 756   $form->{ACCOUNTING_METHODS} = [];
 
 757   foreach my $item ( qw(accrual cash) ) {
 
 758     push @{ $form->{ACCOUNTING_METHODS} }, { "name"     => $item,
 
 759                                  "selected" => $item eq "cash" };
 
 762   $form->{INVENTORY_SYSTEMS} = [];
 
 763   foreach my $item ( qw(perpetual periodic) ) {
 
 764     push @{ $form->{INVENTORY_SYSTEMS} }, { "name"     => $item,
 
 765                                  "selected" => $item eq "periodic" };
 
 768   $form->{PROFIT_DETERMINATIONS} = [];
 
 769   foreach my $item ( qw(balance income) ) {
 
 770     push @{ $form->{PROFIT_DETERMINATIONS} }, { "name"     => $item,
 
 771                                  "selected" => $item eq "income" };
 
 774   my $default_charset = $::lx_office_conf{system}->{dbcharset};
 
 775   $default_charset ||= Common::DEFAULT_CHARSET;
 
 777   my $cluster_encoding = User->dbclusterencoding($form);
 
 778   if ($cluster_encoding && ($cluster_encoding =~ m/^(?:UTF-?8|UNICODE)$/i)) {
 
 779     if ($::lx_office_conf{system}->{dbcharset} !~ m/^UTF-?8$/i) {
 
 780       $form->show_generic_error($locale->text('The selected  PostgreSQL installation uses UTF-8 as its encoding. ' .
 
 781                                               'Therefore you have to configure Lx-Office to use UTF-8 as well.'),
 
 785     $form->{FORCE_DBENCODING} = 'UNICODE';
 
 788     $form->{DBENCODINGS} = [];
 
 790     foreach my $encoding (@Common::db_encodings) {
 
 791       push @{ $form->{DBENCODINGS} }, { "dbencoding" => $encoding->{dbencoding},
 
 792                                         "label"      => $encoding->{label},
 
 793                                         "selected"   => $encoding->{charset} eq $default_charset };
 
 797   $form->{title} = "kivitendo " . $locale->text('Database Administration') . " / " . $locale->text('Create Dataset');
 
 800   print $form->parse_html_template("admin/create_dataset");
 
 804   my $form   = $main::form;
 
 805   my $locale = $main::locale;
 
 807   $form->isblank("db", $locale->text('Dataset missing!'));
 
 809   User->dbcreate(\%$form);
 
 811   $form->{title} = "kivitendo " . $locale->text('Database Administration') . " / " . $locale->text('Create Dataset');
 
 814   print $form->parse_html_template("admin/dbcreate");
 
 818   my $form      = $main::form;
 
 819   my $locale    = $main::locale;
 
 821   my @dbsources = User->dbsources_unused($form);
 
 822   $form->error($locale->text('Nothing to delete!')) unless @dbsources;
 
 824   $form->{title}     = "kivitendo " . $locale->text('Database Administration') . " / " . $locale->text('Delete Dataset');
 
 825   $form->{DBSOURCES} = [ map { { "name", $_ } } sort @dbsources ];
 
 828   print $form->parse_html_template("admin/delete_dataset");
 
 832   my $form   = $main::form;
 
 833   my $locale = $main::locale;
 
 836     $form->error($locale->text('No Dataset selected!'));
 
 839   User->dbdelete(\%$form);
 
 841   $form->{title} = "kivitendo " . $locale->text('Database Administration') . " / " . $locale->text('Delete Dataset');
 
 843   print $form->parse_html_template("admin/dbdelete");
 
 847   my $form       = $main::form;
 
 848   my $locale     = $main::locale;
 
 850   $form->{title} = "kivitendo " . $locale->text('Database Administration') . " / " . $locale->text('Backup Dataset');
 
 852   if ($::lx_office_conf{applications}->{pg_dump} eq "DISABLED") {
 
 853     $form->error($locale->text('Database backups and restorations are disabled in the configuration.'));
 
 856   my @dbsources         = sort User->dbsources($form);
 
 857   $form->{DATABASES}    = [ map { { "dbname" => $_ } } @dbsources ];
 
 858   $form->{NO_DATABASES} = !scalar @dbsources;
 
 860   my $username  = getpwuid $UID || "unknown-user";
 
 861   my $hostname  = hostname() || "unknown-host";
 
 862   $form->{from} = "kivitendo Admin <${username}\@${hostname}>";
 
 865   print $form->parse_html_template("admin/backup_dataset");
 
 868 sub backup_dataset_start {
 
 869   my $form       = $main::form;
 
 870   my $locale     = $main::locale;
 
 872   $form->{title} = "kivitendo " . $locale->text('Database Administration') . " / " . $locale->text('Backup Dataset');
 
 874   my $pg_dump_exe = $::lx_office_conf{applications}->{pg_dump} || "pg_dump";
 
 876   if ("$pg_dump_exe" eq "DISABLED") {
 
 877     $form->error($locale->text('Database backups and restorations are disabled in the configuration.'));
 
 880   $form->isblank("dbname", $locale->text('The dataset name is missing.'));
 
 881   $form->isblank("to", $locale->text('The email address is missing.')) if $form->{destination} eq "email";
 
 883   my $tmpdir = "/tmp/lx_office_backup_" . Common->unique_id();
 
 884   mkdir $tmpdir, 0700 || $form->error($locale->text('A temporary directory could not be created:') . " $ERRNO");
 
 886   my $pgpass = IO::File->new("${tmpdir}/.pgpass", O_WRONLY | O_CREAT, 0600);
 
 890     $form->error($locale->text('A temporary file could not be created:') . " $ERRNO");
 
 893   print $pgpass "$form->{dbhost}:$form->{dbport}:$form->{dbname}:$form->{dbuser}:$form->{dbpasswd}\n";
 
 896   $ENV{HOME} = $tmpdir;
 
 898   my @args = ("-Ft", "-c", "-o", "-h", $form->{dbhost}, "-U", $form->{dbuser});
 
 899   push @args, ("-p", $form->{dbport}) if ($form->{dbport});
 
 900   push @args, $form->{dbname};
 
 902   my $cmd  = "$pg_dump_exe " . join(" ", map { s/\\/\\\\/g; s/\"/\\\"/g; $_ } @args);
 
 903   my $name = "dataset_backup_$form->{dbname}_" . strftime("%Y%m%d", localtime()) . ".tar";
 
 905   if ($form->{destination} ne "email") {
 
 906     my $in = IO::File->new("$cmd |");
 
 909       unlink "${tmpdir}/.pgpass";
 
 912       $form->error($locale->text('The pg_dump process could not be started.'));
 
 915     print "content-type: application/x-tar\n";
 
 916     print "content-disposition: attachment; filename=\"${name}\"\n\n";
 
 918     while (my $line = <$in>) {
 
 924     unlink "${tmpdir}/.pgpass";
 
 928     my $tmp = $tmpdir . "/dump_" . Common::unique_id();
 
 930     if (system("$cmd > $tmp") != 0) {
 
 931       unlink "${tmpdir}/.pgpass", $tmp;
 
 934       $form->error($locale->text('The pg_dump process could not be started.'));
 
 937     my $mail = new Mailer;
 
 939     map { $mail->{$_} = $form->{$_} } qw(from to cc subject message);
 
 941     $mail->{charset}     = $::lx_office_conf{system}->{dbcharset} || Common::DEFAULT_CHARSET;
 
 942     $mail->{attachments} = [ { "filename" => $tmp, "name" => $name } ];
 
 945     unlink "${tmpdir}/.pgpass", $tmp;
 
 948     $form->{title} = "kivitendo " . $locale->text('Database Administration') . " / " . $locale->text('Backup Dataset');
 
 951     print $form->parse_html_template("admin/backup_dataset_email_done");
 
 955 sub restore_dataset {
 
 956   my $form       = $main::form;
 
 957   my $locale     = $main::locale;
 
 959   $form->{title} = "kivitendo " . $locale->text('Database Administration') . " / " . $locale->text('Restore Dataset');
 
 961   if ($::lx_office_conf{applications}->{pg_restore} eq "DISABLED") {
 
 962     $form->error($locale->text('Database backups and restorations are disabled in the configuration.'));
 
 965   my $default_charset   = $::lx_office_conf{system}->{dbcharset};
 
 966   $default_charset    ||= Common::DEFAULT_CHARSET;
 
 968   $form->{DBENCODINGS}  = [];
 
 970   foreach my $encoding (@Common::db_encodings) {
 
 971     push @{ $form->{DBENCODINGS} }, { "dbencoding" => $encoding->{dbencoding},
 
 972                                       "label"      => $encoding->{label},
 
 973                                       "selected"   => $encoding->{charset} eq $default_charset };
 
 977   print $form->parse_html_template("admin/restore_dataset");
 
 980 sub restore_dataset_start {
 
 981   my $form       = $main::form;
 
 982   my $locale     = $main::locale;
 
 984   $form->{title} = "kivitendo " . $locale->text('Database Administration') . " / " . $locale->text('Restore Dataset');
 
 986   my $pg_restore_exe = $::lx_office_conf{applications}->{pg_restore} || "pg_restore";
 
 988   if ("$pg_restore_exe" eq "DISABLED") {
 
 989     $form->error($locale->text('Database backups and restorations are disabled in the configuration.'));
 
 992   $form->isblank("new_dbname", $locale->text('The dataset name is missing.'));
 
 993   $form->isblank("content", $locale->text('No backup file has been uploaded.'));
 
 995   # Create temporary directories. Write the backup file contents to a temporary
 
 996   # file. Create a .pgpass file with the username and password for the pg_restore
 
 999   my $tmpdir = "/tmp/lx_office_backup_" . Common->unique_id();
 
1000   mkdir $tmpdir, 0700 || $form->error($locale->text('A temporary directory could not be created:') . " $ERRNO");
 
1002   my $pgpass = IO::File->new("${tmpdir}/.pgpass", O_WRONLY | O_CREAT, 0600);
 
1006     $form->error($locale->text('A temporary file could not be created:') . " $ERRNO");
 
1009   print $pgpass "$form->{dbhost}:$form->{dbport}:$form->{new_dbname}:$form->{dbuser}:$form->{dbpasswd}\n";
 
1012   $ENV{HOME} = $tmpdir;
 
1014   my $tmp = $tmpdir . "/dump_" . Common::unique_id();
 
1017   if (substr($form->{content}, 0, 2) eq "\037\213") {
 
1018     $tmpfile = IO::File->new("| gzip -d > $tmp");
 
1022     $tmpfile = IO::File->new($tmp, O_WRONLY | O_CREAT | O_BINARY, 0600);
 
1026     unlink "${tmpdir}/.pgpass";
 
1029     $form->error($locale->text('A temporary file could not be created:') . " $ERRNO");
 
1032   print $tmpfile $form->{content};
 
1035   delete $form->{content};
 
1037   # Try to connect to the database. Find out if a database with the same name exists.
 
1038   # If yes, then drop the existing database. Create a new one with the name and encoding
 
1039   # given by the user.
 
1041   User::dbconnect_vars($form, "template1");
 
1043   my %myconfig = map { $_ => $form->{$_} } grep /^db/, keys %{ $form };
 
1044   my $dbh      = $form->dbconnect(\%myconfig) || $form->dberror();
 
1048   $form->{new_dbname} =~ s|[^a-zA-Z0-9_\-]||g;
 
1050   $query = qq|SELECT COUNT(*) FROM pg_database WHERE datname = ?|;
 
1051   my ($count) = selectrow_query($form, $dbh, $query, $form->{new_dbname});
 
1053     do_query($form, $dbh, qq|DROP DATABASE $form->{new_dbname}|);
 
1057   foreach my $item (@Common::db_encodings) {
 
1058     if ($item->{dbencoding} eq $form->{dbencoding}) {
 
1063   $form->{dbencoding} = "LATIN9" unless $form->{dbencoding};
 
1065   do_query($form, $dbh, qq|CREATE DATABASE $form->{new_dbname} ENCODING ? TEMPLATE template0|, $form->{dbencoding});
 
1069   # Spawn pg_restore on the temporary file.
 
1071   my @args = ("-h", $form->{dbhost}, "-U", $form->{dbuser}, "-d", $form->{new_dbname});
 
1072   push @args, ("-p", $form->{dbport}) if ($form->{dbport});
 
1075   my $cmd = "$pg_restore_exe " . join(" ", map { s/\\/\\\\/g; s/\"/\\\"/g; $_ } @args);
 
1077   my $in = IO::File->new("$cmd 2>&1 |");
 
1080     unlink "${tmpdir}/.pgpass", $tmp;
 
1083     $form->error($locale->text('The pg_restore process could not be started.'));
 
1086   $English::AUTOFLUSH = 1;
 
1089   print $form->parse_html_template("admin/restore_dataset_start_header");
 
1091   while (my $line = <$in>) {
 
1096   $form->{retval} = $CHILD_ERROR >> 8;
 
1097   print $form->parse_html_template("admin/restore_dataset_start_footer");
 
1099   unlink "${tmpdir}/.pgpass", $tmp;
 
1104   my $form   = $main::form;
 
1105   my $locale = $main::locale;
 
1107   unlink _nologin_file_name();;
 
1109   $form->{callback} = "admin.pl?action=list_users";
 
1111   $form->redirect($locale->text('Lockfile removed!'));
 
1116   my $form   = $main::form;
 
1117   my $locale = $main::locale;
 
1119   open(FH, ">", _nologin_file_name())
 
1120     or $form->error($locale->text('Cannot create Lock!'));
 
1123   $form->{callback} = "admin.pl?action=list_users";
 
1125   $form->redirect($locale->text('Lockfile created!'));
 
1130   call_sub($main::form->{yes_nextsub});
 
1134   call_sub($main::form->{no_nextsub});
 
1138   call_sub($main::form->{add_nextsub});
 
1142   my $form = $main::form;
 
1144   $form->{edit_nextsub} ||= 'edit_user';
 
1146   call_sub($form->{edit_nextsub});
 
1150   my $form     = $main::form;
 
1152   $form->{delete_nextsub} ||= 'delete_user';
 
1154   call_sub($form->{delete_nextsub});
 
1158   my $form = $main::form;
 
1160   $form->{save_nextsub} ||= 'save_user';
 
1162   call_sub($form->{save_nextsub});
 
1166   call_sub($main::form->{back_nextsub});
 
1170   my $form   = $main::form;
 
1171   my $locale = $main::locale;
 
1173   foreach my $action (qw(create_standard_group dont_create_standard_group
 
1174                          save_user delete_user save_user_as_new)) {
 
1175     if ($form->{"action_${action}"}) {
 
1181   call_sub($form->{default_action}) if ($form->{default_action});
 
1183   $form->error($locale->text('No action defined.'));
 
1186 sub _apply_dbupgrade_scripts {
 
1187   ::end_of_request() if SL::DBUpgrade2->new(form => $::form, dbdriver => 'Pg', auth => 1)->apply_admin_dbupgrade_scripts(1);
 
1190 sub _nologin_file_name {
 
1191   return $::lx_office_conf{paths}->{userspath} . '/nologin';
 
1194 sub _search_templates {
 
1195   # is there a templates basedir
 
1196   if (!-d $::lx_office_conf{paths}->{templates}) {
 
1197     $::form->error(sprintf($::locale->text("The directory %s does not exist."), $::lx_office_conf{paths}->{templates}));
 
1200   opendir TEMPLATEDIR, $::lx_office_conf{paths}->{templates} or $::form->error($::lx_office_conf{paths}->{templates} . " : $ERRNO");
 
1201   my @all     = readdir(TEMPLATEDIR);
 
1202   my @alldir  = sort grep { -d ($::lx_office_conf{paths}->{templates} . "/$_") && !/^\.\.?$/ } @all;
 
1203   closedir TEMPLATEDIR;
 
1205   @alldir = grep !/\.(html|tex|sty|odt|xml|txb)$/, @alldir;
 
1206   @alldir = grep !/^(webpages|print|\.svn)$/, @alldir;
 
1209   opendir TEMPLATEDIR, "$::lx_office_conf{paths}->{templates}/print" or $::form->error("$::lx_office_conf{paths}->{templates}/print" . " : $ERRNO");
 
1210   my @allmaster = readdir(TEMPLATEDIR);
 
1211   closedir TEMPLATEDIR;
 
1213   @allmaster  = sort grep { -d ("$::lx_office_conf{paths}->{templates}/print" . "/$_") && !/^\.\.?$/ } @allmaster;
 
1214   @allmaster = reverse grep !/Default/, @allmaster;
 
1215   push @allmaster, 'Default';
 
1216   @allmaster = reverse @allmaster;
 
1218   return \@alldir, \@allmaster;