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);
45 use POSIX qw(strftime);
49 use SL::Auth::PasswordPolicy;
59 require "bin/mozilla/common.pl";
60 require "bin/mozilla/admin_groups.pl";
61 require "bin/mozilla/admin_printer.pl";
67 # $locale->text('periodic')
68 # $locale->text('income')
69 # $locale->text('perpetual')
70 # $locale->text('balance')
77 my @valid_dateformats = qw(mm/dd/yy dd/mm/yy dd.mm.yy yyyy-mm-dd);
78 my @valid_numberformats = ('1,000.00', '1000.00', '1.000,00', '1000,00');
79 my @all_stylesheets = qw(lx-office-erp.css Mobile.css kivitendo.css);
80 my @all_menustyles = (
81 { id => 'old', title => $::locale->text('Old (on the side)') },
82 { id => 'v3', title => $::locale->text('Top (CSS)') },
83 { id => 'neu', title => $::locale->text('Top (Javascript)') },
87 $::lxdebug->enter_sub;
88 my $session_result = shift;
94 $::request->{layout} = SL::Layout::Dispatcher->new(style => 'admin');
95 $::request->{layout}->use_stylesheet("lx-office-erp.css");
96 $form->{favicon} = "favicon.ico";
98 if ($form->{action}) {
99 if ($auth->authenticate_root($form->{'{AUTH}admin_password'}) != $auth->OK()) {
100 $auth->punish_wrong_login;
101 $form->{error} = $locale->text('Incorrect Password!');
102 $auth->delete_session_value('admin_password');
105 if ($auth->session_tables_present()) {
106 delete $::form->{'{AUTH}admin_password'};
107 _apply_dbupgrade_scripts();
110 call_sub($locale->findsub($form->{action}));
113 # if there are no drivers bail out
114 $form->error($locale->text('No Database Drivers available!'))
115 unless (User->dbdrivers);
119 $::lxdebug->leave_sub;
123 my $form = $main::form;
124 my $locale = $main::locale;
126 $form->{title} = qq|kivitendo $form->{version} | . $locale->text('Administration');
129 print $form->parse_html_template('admin/adminlogin');
133 check_auth_db_and_tables();
138 $main::auth->destroy_session();
142 sub check_auth_db_and_tables {
143 my $form = $main::form;
144 my $locale = $main::locale;
148 map { $params{"db_${_}"} = $main::auth->{DB_config}->{$_} } keys %{ $auth->{DB_config} };
150 $params{admin_password} = $::lx_office_conf{authentication}->{admin_password};
152 if (!$main::auth->check_database()) {
153 $form->{title} = $locale->text('Authentification database creation');
155 print $form->parse_html_template('admin/check_auth_database', \%params);
160 if (!$main::auth->check_tables()) {
161 $form->{title} = $locale->text('Authentification tables creation');
163 print $form->parse_html_template('admin/check_auth_tables', \%params);
168 my $memberfile = $::lx_office_conf{paths}->{memberfile};
169 if (-f $memberfile) {
172 if ($memberfile =~ m|^.*/|) {
176 my $backupdir = "${memberdir}member-file-migration";
178 $form->{title} = $locale->text('User data migration');
180 print $form->parse_html_template('admin/user_migration', { 'memberfile' => $memberfile,
181 'backupdir' => $backupdir });
188 my $form = $main::form;
190 $main::auth->create_database('superuser' => $form->{db_superuser},
191 'superuser_password' => $form->{db_superuser_password},
192 'template' => $form->{db_template});
196 sub create_auth_tables {
197 my $form = $main::form;
198 my $locale = $main::locale;
200 $main::auth->create_tables();
201 $main::auth->set_session_value('admin_password', $form->{'{AUTH}admin_password'});
202 $main::auth->create_or_refresh_session();
204 my $memberfile = $::lx_office_conf{paths}->{memberfile};
205 if (!-f $memberfile) {
206 # New installation -- create a standard group with full access
209 'name' => $locale->text('Full Access'),
210 'description' => $locale->text('Full access to all functions'),
211 'rights' => { map { $_ => 1 } SL::Auth::all_rights() },
212 'members' => [ map { $_->{id} } values %members ],
215 $main::auth->save_group($group);
218 _apply_dbupgrade_scripts();
223 $main::lxdebug->enter_sub();
225 my $form = $main::form;
226 my $locale = $main::locale;
230 my $memberfile = $::lx_office_conf{paths}->{memberfile};
231 if ($memberfile =~ m|^.*/|) {
235 my $backupdir = "${memberdir}member-file-migration";
237 if (! -d $backupdir && !mkdir $backupdir, 0700) {
238 $form->error(sprintf($locale->text('The directory "%s" could not be created:\n%s'), $backupdir, $!));
241 copy $memberfile, "users/member-file-migration/members";
243 my $in = IO::File->new($memberfile, "r");
245 $form->error($locale->text('Could not open the old memberfile.')) if (!$in);
247 my (%members, $login);
256 $login =~ s/(\[|\])//g;
260 $members{$login} = { "login" => $login };
264 if ($login && m/=/) {
265 my ($key, $value) = split m/\s*=\s*/, $_, 2;
270 $value =~ s|\\n|\n|g;
272 $members{$login}->{$key} = $value;
278 delete $members{"root login"};
280 map { $_->{dbpasswd} = unpack 'u', $_->{dbpasswd} } values %members;
282 while (my ($login, $params) = each %members) {
283 $main::auth->save_user($login, %{ $params });
284 $main::auth->change_password($login, $params->{password}, 1);
286 my $conf_file = "${memberdir}${login}.conf";
289 copy $conf_file, "${backupdir}/${login}.conf";
296 my @member_list = sort { lc $a->{login} cmp lc $b->{login} } values %members;
298 $form->{title} = $locale->text('User data migration');
300 print $form->parse_html_template('admin/user_migration_done', { 'MEMBERS' => \@member_list });
302 $main::lxdebug->leave_sub();
305 sub create_standard_group_ask {
306 my $form = $main::form;
307 my $locale = $main::locale;
309 $form->{title} = $locale->text('Create a standard group');
312 print $form->parse_html_template("admin/create_standard_group_ask");
315 sub create_standard_group {
316 my $form = $main::form;
317 my $locale = $main::locale;
319 my %members = $main::auth->read_all_users();
321 my $groups = $main::auth->read_groups();
323 foreach my $group (values %{$groups}) {
324 if (($form->{group_id} != $group->{id})
325 && ($form->{name} eq $group->{name})) {
326 $form->show_generic_error($locale->text("A group with that name does already exist."));
331 'name' => $locale->text('Full Access'),
332 'description' => $locale->text('Full access to all functions'),
333 'rights' => { map { $_ => 1 } SL::Auth::all_rights() },
334 'members' => [ map { $_->{id} } values %members ],
337 $main::auth->save_group($group);
339 user_migration_complete(1);
342 sub dont_create_standard_group {
343 user_migration_complete(0);
346 sub user_migration_complete {
347 my $standard_group_created = shift;
349 my $form = $main::form;
350 my $locale = $main::locale;
352 $form->{title} = $locale->text('User migration complete');
355 print $form->parse_html_template('admin/user_migration_complete', { 'standard_group_created' => $standard_group_created });
359 my $form = $main::form;
360 my $locale = $main::locale;
362 my %members = $main::auth->read_all_users();
364 delete $members{"root login"};
366 for (values %members) {
367 $_->{templates} =~ s|.*/||;
368 $_->{login_url} = $::locale->is_utf8 ? Encode::encode('utf-8-strict', $_->{login}) : $_->{login_url};
371 $form->{title} = "kivitendo " . $locale->text('Administration');
372 $form->{LOCKED} = -e _nologin_file_name();
373 $form->{MEMBERS} = [ @members{sort { lc $a cmp lc $b } keys %members} ];
376 print $form->parse_html_template("admin/list_users");
380 $::form->{title} = "kivitendo " . $::locale->text('Administration') . " / " . $::locale->text('Add User');
382 # User does not have a well behaved new constructor, so we'll just have to build one ourself
385 "countrycode" => "de",
386 "numberformat" => "1.000,00",
387 "dateformat" => "dd.mm.yy",
388 "stylesheet" => "kivitendo.css",
389 "menustyle" => "neu",
390 dbport => $::auth->{DB_config}->{port} || 5432,
391 dbuser => $::auth->{DB_config}->{user} || 'lxoffice',
392 dbhost => $::auth->{DB_config}->{host} || 'localhost',
395 edit_user_form($user);
399 $::form->{title} = "kivitendo " . $::locale->text('Administration') . " / " . $::locale->text('Edit User');
403 my $user = User->new(id => $::form->{user}{id});
405 # strip basedir from templates directory
406 $user->{templates} =~ s|.*/||;
408 edit_user_form($user);
414 my %cc = $user->country_codes;
415 my @all_countrycodes = map { id => $_, title => $cc{$_} }, sort { $cc{$a} cmp $cc{$b} } keys %cc;
416 my ($all_dir, $all_master) = _search_templates();
419 if ($::form->{edit}) {
420 my $user_id = $::auth->get_user_id($user->{login});
421 my $all_groups = $::auth->read_groups();
423 for my $group (values %{ $all_groups }) {
424 push @{ $groups }, $group if (grep { $user_id == $_ } @{ $group->{members} });
427 $groups = [ sort { lc $a->{name} cmp lc $b->{name} } @{ $groups } ];
431 print $::form->parse_html_template("admin/edit_user", {
433 CAN_CHANGE_PASSWORD => $::auth->can_change_password,
435 all_stylesheets => \@all_stylesheets,
436 all_numberformats => \@valid_numberformats,
437 all_dateformats => \@valid_dateformats,
438 all_countrycodes => \@all_countrycodes,
439 all_menustyles => \@all_menustyles,
440 all_templates => $all_dir,
441 all_master_templates => $all_master,
446 my $form = $main::form;
447 my $locale = $main::locale;
449 my $user = $form->{user};
451 $user->{dbdriver} = 'Pg';
453 if (!$::form->{edit}) {
454 # no spaces allowed in login name
455 $user->{login} =~ s/\s//g;
456 $::form->show_generic_error($::locale->text('Login name missing!')) unless $user->{login};
458 # check for duplicates
459 my %members = $::auth->read_all_users;
460 if ($members{$user->{login}}) {
461 $::form->show_generic_error($locale->text('Another user with the login #1 does already exist.', $user->{login}), 'back_button' => 1);
465 # no spaces allowed in directories
466 ($::form->{newtemplates}) = split / /, $::form->{newtemplates};
467 $user->{templates} = $::form->{newtemplates} || $::form->{usetemplates} || $user->{login};
470 if (!-d $::lx_office_conf{paths}->{templates}) {
471 $::form->error(sprintf($::locale->text("The directory %s does not exist."), $::lx_office_conf{paths}->{templates}));
474 # add base directory to $form->{templates}
475 $user->{templates} =~ s|.*/||;
476 $user->{templates} = $::lx_office_conf{paths}->{templates} . "/$user->{templates}";
478 my $myconfig = new User(id => $user->{id});
480 $::form->show_generic_error($::locale->text('Dataset missing!')) unless $user->{dbname};
481 $::form->show_generic_error($::locale->text('Database User missing!')) unless $user->{dbuser};
483 foreach my $item (keys %{$user}) {
484 $myconfig->{$item} = $user->{$item};
487 $myconfig->save_member;
489 $user->{templates} =~ s|.*/||;
490 $user->{templates} = $::lx_office_conf{paths}->{templates} . "/$user->{templates}";
491 $::form->{mastertemplates} =~ s|.*/||;
493 # create user template directory and copy master files
494 if (!-d "$user->{templates}") {
497 if (mkdir "$user->{templates}", oct("771")) {
501 # copy templates to the directory
503 my $oldcurrdir = getcwd();
504 if (!chdir("$::lx_office_conf{paths}->{templates}/print/$::form->{mastertemplates}")) {
505 $form->error("$ERRNO: chdir $::lx_office_conf{paths}->{templates}/print/$::form->{mastertemplates}");
508 my $newdir = File::Spec->catdir($oldcurrdir, $user->{templates});
516 if (!mkdir (File::Spec->catdir($newdir, $File::Find::name))) {
518 $form->error("$ERRNO: mkdir $File::Find::name");
521 if (!symlink (readlink($_),
522 File::Spec->catfile($newdir, $File::Find::name))) {
524 $form->error("$ERRNO: symlink $File::Find::name");
527 if (!copy($_, File::Spec->catfile($newdir, $File::Find::name))) {
529 $form->error("$ERRNO: cp $File::Find::name");
537 $form->error("$ERRNO: $user->{templates}");
541 # Add new user to his groups.
542 if (ref $form->{new_user_group_ids} eq 'ARRAY') {
543 my $all_groups = $main::auth->read_groups();
544 my %user = $main::auth->read_user(login => $myconfig->{login});
546 foreach my $group_id (@{ $form->{new_user_group_ids} }) {
547 my $group = $all_groups->{$group_id};
551 push @{ $group->{members} }, $user{id};
552 $main::auth->save_group($group);
556 if ($main::auth->can_change_password()
557 && defined $::form->{new_password}
558 && ($::form->{new_password} ne '********')) {
559 my $verifier = SL::Auth::PasswordPolicy->new;
560 my $result = $verifier->verify($::form->{new_password}, 1);
562 if ($result != SL::Auth::PasswordPolicy->OK()) {
563 $form->error($::locale->text('The settings were saved, but the password was not changed.') . ' ' . join(' ', $verifier->errors($result)));
566 $main::auth->change_password($myconfig->{login}, $::form->{new_password});
569 $::form->redirect($::locale->text('User saved!'));
572 sub save_user_as_new {
573 my $form = $main::form;
575 $form->{user}{login} = $::form->{new_user_login};
576 delete $form->{user}{id};
577 delete @{$form}{qw(id edit new_user_login)};
583 my $form = $main::form;
584 my $locale = $main::locale;
586 my $user = $::form->{user} || {};
588 $::form->show_generic_error($::locale->text('Missing user id!')) unless $user->{id};
590 my $loaded_user = User->new(id => $user->{id});
592 my %members = $main::auth->read_all_users();
593 my $templates = $members{$loaded_user->{login}}->{templates};
595 $main::auth->delete_user($loaded_user->{login});
598 my $templates_in_use = 0;
600 foreach my $login (keys %members) {
601 next if $loaded_user->{login} eq $login;
602 next if $members{$login}->{templates} ne $templates;
603 $templates_in_use = 1;
607 if (!$templates_in_use && -d $templates) {
608 unlink <$templates/*>;
613 $form->redirect($locale->text('User deleted!'));
621 return ($login) ? $login : undef;
627 my ($null, $value) = split(/=/, $line, 2);
630 $value =~ s/\s#.*//g;
632 # remove any trailing whitespace
633 $value =~ s/^\s*(.*?)\s*$/$1/;
638 sub pg_database_administration {
639 my $form = $main::form;
641 $form->{dbdriver} = 'Pg';
646 sub dbselect_source {
647 my $form = $main::form;
648 my $locale = $main::locale;
650 $form->{dbport} = $::auth->{DB_config}->{port} || 5432;
651 $form->{dbuser} = $::auth->{DB_config}->{user} || 'lxoffice';
652 $form->{dbdefault} = 'template1';
653 $form->{dbhost} = $::auth->{DB_config}->{host} || 'localhost';
655 $form->{title} = "kivitendo / " . $locale->text('Database Administration');
657 # Intentionnaly disabled unless fixed to work with the authentication DB.
658 $form->{ALLOW_DBBACKUP} = 0; # "$pg_dump_exe" ne "DISABLED";
661 print $form->parse_html_template("admin/dbadmin");
664 sub test_db_connection {
665 my $form = $main::form;
666 my $locale = $main::locale;
668 $form->{dbdriver} = 'Pg';
669 User::dbconnect_vars($form, $form->{dbname});
671 my $dbh = DBI->connect($form->{dbconnect}, $form->{dbuser}, $form->{dbpasswd});
673 $form->{connection_ok} = $dbh ? 1 : 0;
674 $form->{errstr} = $DBI::errstr;
676 $dbh->disconnect() if ($dbh);
678 $form->{title} = $locale->text('Database Connection Test');
680 print $form->parse_html_template("admin/test_db_connection");
684 call_sub($main::form->{"nextsub"});
688 my $form = $main::form;
689 my $locale = $main::locale;
691 $form->{title} = "kivitendo " . $locale->text('Database Administration') . " / " . $locale->text('Update Dataset');
693 my @need_updates = User->dbneedsupdate($form);
694 $form->{NEED_UPDATES} = \@need_updates;
695 $form->{ALL_UPDATED} = !scalar @need_updates;
698 print $form->parse_html_template("admin/update_dataset");
702 my $form = $main::form;
703 my $locale = $main::locale;
705 $::request->{layout}->use_stylesheet("lx-office-erp.css");
706 $form->{title} = $locale->text("Dataset upgrade");
709 my $rowcount = $form->{rowcount} * 1;
710 my @update_rows = grep { $form->{"update_$_"} } (1 .. $rowcount);
711 $form->{NOTHING_TO_DO} = !scalar @update_rows;
712 my $saved_form = save_form();
716 print $form->parse_html_template("admin/dbupgrade_all_header");
718 foreach my $i (@update_rows) {
719 restore_form($saved_form);
722 map { $form->{$_} = $::myconfig{$_} = $form->{"${_}_${i}"} } qw(dbname dbdriver dbhost dbport dbuser dbpasswd);
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, SL::DBUpgrade2->new(form => $form, dbdriver => $form->{dbdriver})->parse_dbupdate_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 tie my %dir_h, 'IO::Dir', 'sql/';
747 foreach my $item (map { s/-chart\.sql$//; $_ } sort grep { /-chart\.sql\z/ && !/Default-chart.sql\z/ } keys %dir_h) {
748 push @{ $form->{CHARTS} }, { name => $item,
749 selected => $item eq "Germany-DATEV-SKR03EU" };
752 $form->{ACCOUNTING_METHODS} = [ map { { name => $_, selected => $_ eq 'cash' } } qw(accrual cash) ];
753 $form->{INVENTORY_SYSTEMS} = [ map { { name => $_, selected => $_ eq 'periodic' } } qw(perpetual periodic) ];
754 $form->{PROFIT_DETERMINATIONS} = [ map { { name => $_, selected => $_ eq 'income' } } qw(balance income) ];
756 my $default_charset = $::lx_office_conf{system}->{dbcharset} || Common::DEFAULT_CHARSET;
758 my $cluster_encoding = User->dbclusterencoding($form);
759 if ($cluster_encoding && ($cluster_encoding =~ m/^(?:UTF-?8|UNICODE)$/i)) {
760 if ($::lx_office_conf{system}->{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 kivitendo to use UTF-8 as well.'),
766 $form->{FORCE_DBENCODING} = 'UNICODE';
769 $form->{DBENCODINGS} = [ map { { %{$_}, selected => $_->{charset} eq $default_charset } } @Common::db_encodings ];
772 $form->{title} = "kivitendo " . $locale->text('Database Administration') . " / " . $locale->text('Create Dataset');
775 print $form->parse_html_template("admin/create_dataset");
779 my $form = $main::form;
780 my $locale = $main::locale;
782 $form->isblank("db", $locale->text('Dataset missing!'));
784 User->dbcreate(\%$form);
786 $form->{title} = "kivitendo " . $locale->text('Database Administration') . " / " . $locale->text('Create Dataset');
789 print $form->parse_html_template("admin/dbcreate");
793 my $form = $main::form;
794 my $locale = $main::locale;
796 my @dbsources = User->dbsources_unused($form);
797 $form->error($locale->text('Nothing to delete!')) unless @dbsources;
799 $form->{title} = "kivitendo " . $locale->text('Database Administration') . " / " . $locale->text('Delete Dataset');
800 $form->{DBSOURCES} = [ map { { "name", $_ } } sort @dbsources ];
803 print $form->parse_html_template("admin/delete_dataset");
807 my $form = $main::form;
808 my $locale = $main::locale;
811 $form->error($locale->text('No Dataset selected!'));
814 User->dbdelete(\%$form);
816 $form->{title} = "kivitendo " . $locale->text('Database Administration') . " / " . $locale->text('Delete Dataset');
818 print $form->parse_html_template("admin/dbdelete");
822 my $form = $main::form;
823 my $locale = $main::locale;
825 $form->{title} = "kivitendo " . $locale->text('Database Administration') . " / " . $locale->text('Backup Dataset');
827 if ($::lx_office_conf{applications}->{pg_dump} eq "DISABLED") {
828 $form->error($locale->text('Database backups and restorations are disabled in the configuration.'));
831 my @dbsources = sort User->dbsources($form);
832 $form->{DATABASES} = [ map { { "dbname" => $_ } } @dbsources ];
833 $form->{NO_DATABASES} = !scalar @dbsources;
835 my $username = getpwuid $UID || "unknown-user";
836 my $hostname = hostname() || "unknown-host";
837 $form->{from} = "kivitendo Admin <${username}\@${hostname}>";
840 print $form->parse_html_template("admin/backup_dataset");
843 sub backup_dataset_start {
844 my $form = $main::form;
845 my $locale = $main::locale;
847 $form->{title} = "kivitendo " . $locale->text('Database Administration') . " / " . $locale->text('Backup Dataset');
849 my $pg_dump_exe = $::lx_office_conf{applications}->{pg_dump} || "pg_dump";
851 if ("$pg_dump_exe" eq "DISABLED") {
852 $form->error($locale->text('Database backups and restorations are disabled in the configuration.'));
855 $form->isblank("dbname", $locale->text('The dataset name is missing.'));
856 $form->isblank("to", $locale->text('The email address is missing.')) if $form->{destination} eq "email";
858 my $tmpdir = "/tmp/lx_office_backup_" . Common->unique_id();
859 mkdir $tmpdir, 0700 || $form->error($locale->text('A temporary directory could not be created:') . " $ERRNO");
861 my $pgpass = IO::File->new("${tmpdir}/.pgpass", O_WRONLY | O_CREAT, 0600);
865 $form->error($locale->text('A temporary file could not be created:') . " $ERRNO");
868 print $pgpass "$form->{dbhost}:$form->{dbport}:$form->{dbname}:$form->{dbuser}:$form->{dbpasswd}\n";
871 $ENV{HOME} = $tmpdir;
873 my @args = ("-Ft", "-c", "-o", "-h", $form->{dbhost}, "-U", $form->{dbuser});
874 push @args, ("-p", $form->{dbport}) if ($form->{dbport});
875 push @args, $form->{dbname};
877 my $cmd = "$pg_dump_exe " . join(" ", map { s/\\/\\\\/g; s/\"/\\\"/g; $_ } @args);
878 my $name = "dataset_backup_$form->{dbname}_" . strftime("%Y%m%d", localtime()) . ".tar";
880 if ($form->{destination} ne "email") {
881 my $in = IO::File->new("$cmd |");
884 unlink "${tmpdir}/.pgpass";
887 $form->error($locale->text('The pg_dump process could not be started.'));
890 print "content-type: application/x-tar\n";
891 print "content-disposition: attachment; filename=\"${name}\"\n\n";
893 while (my $line = <$in>) {
899 unlink "${tmpdir}/.pgpass";
903 my $tmp = $tmpdir . "/dump_" . Common::unique_id();
905 if (system("$cmd > $tmp") != 0) {
906 unlink "${tmpdir}/.pgpass", $tmp;
909 $form->error($locale->text('The pg_dump process could not be started.'));
912 my $mail = new Mailer;
914 map { $mail->{$_} = $form->{$_} } qw(from to cc subject message);
916 $mail->{charset} = $::lx_office_conf{system}->{dbcharset} || Common::DEFAULT_CHARSET;
917 $mail->{attachments} = [ { "filename" => $tmp, "name" => $name } ];
920 unlink "${tmpdir}/.pgpass", $tmp;
923 $form->{title} = "kivitendo " . $locale->text('Database Administration') . " / " . $locale->text('Backup Dataset');
926 print $form->parse_html_template("admin/backup_dataset_email_done");
930 sub restore_dataset {
931 my $form = $main::form;
932 my $locale = $main::locale;
934 $form->{title} = "kivitendo " . $locale->text('Database Administration') . " / " . $locale->text('Restore Dataset');
936 if ($::lx_office_conf{applications}->{pg_restore} eq "DISABLED") {
937 $form->error($locale->text('Database backups and restorations are disabled in the configuration.'));
940 my $default_charset = $::lx_office_conf{system}->{dbcharset};
941 $default_charset ||= Common::DEFAULT_CHARSET;
943 $form->{DBENCODINGS} = [];
945 foreach my $encoding (@Common::db_encodings) {
946 push @{ $form->{DBENCODINGS} }, { "dbencoding" => $encoding->{dbencoding},
947 "label" => $encoding->{label},
948 "selected" => $encoding->{charset} eq $default_charset };
952 print $form->parse_html_template("admin/restore_dataset");
955 sub restore_dataset_start {
956 my $form = $main::form;
957 my $locale = $main::locale;
959 $form->{title} = "kivitendo " . $locale->text('Database Administration') . " / " . $locale->text('Restore Dataset');
961 my $pg_restore_exe = $::lx_office_conf{applications}->{pg_restore} || "pg_restore";
963 if ("$pg_restore_exe" eq "DISABLED") {
964 $form->error($locale->text('Database backups and restorations are disabled in the configuration.'));
967 $form->isblank("new_dbname", $locale->text('The dataset name is missing.'));
968 $form->isblank("content", $locale->text('No backup file has been uploaded.'));
970 # Create temporary directories. Write the backup file contents to a temporary
971 # file. Create a .pgpass file with the username and password for the pg_restore
974 my $tmpdir = "/tmp/lx_office_backup_" . Common->unique_id();
975 mkdir $tmpdir, 0700 || $form->error($locale->text('A temporary directory could not be created:') . " $ERRNO");
977 my $pgpass = IO::File->new("${tmpdir}/.pgpass", O_WRONLY | O_CREAT, 0600);
981 $form->error($locale->text('A temporary file could not be created:') . " $ERRNO");
984 print $pgpass "$form->{dbhost}:$form->{dbport}:$form->{new_dbname}:$form->{dbuser}:$form->{dbpasswd}\n";
987 $ENV{HOME} = $tmpdir;
989 my $tmp = $tmpdir . "/dump_" . Common::unique_id();
992 if (substr($form->{content}, 0, 2) eq "\037\213") {
993 $tmpfile = IO::File->new("| gzip -d > $tmp");
997 $tmpfile = IO::File->new($tmp, O_WRONLY | O_CREAT | O_BINARY, 0600);
1001 unlink "${tmpdir}/.pgpass";
1004 $form->error($locale->text('A temporary file could not be created:') . " $ERRNO");
1007 print $tmpfile $form->{content};
1010 delete $form->{content};
1012 # Try to connect to the database. Find out if a database with the same name exists.
1013 # If yes, then drop the existing database. Create a new one with the name and encoding
1014 # given by the user.
1016 User::dbconnect_vars($form, "template1");
1018 my %myconfig = map { $_ => $form->{$_} } grep /^db/, keys %{ $form };
1019 my $dbh = $form->dbconnect(\%myconfig) || $form->dberror();
1023 $form->{new_dbname} =~ s|[^a-zA-Z0-9_\-]||g;
1025 $query = qq|SELECT COUNT(*) FROM pg_database WHERE datname = ?|;
1026 my ($count) = selectrow_query($form, $dbh, $query, $form->{new_dbname});
1028 do_query($form, $dbh, qq|DROP DATABASE $form->{new_dbname}|);
1032 foreach my $item (@Common::db_encodings) {
1033 if ($item->{dbencoding} eq $form->{dbencoding}) {
1038 $form->{dbencoding} = "LATIN9" unless $form->{dbencoding};
1040 do_query($form, $dbh, qq|CREATE DATABASE $form->{new_dbname} ENCODING ? TEMPLATE template0|, $form->{dbencoding});
1044 # Spawn pg_restore on the temporary file.
1046 my @args = ("-h", $form->{dbhost}, "-U", $form->{dbuser}, "-d", $form->{new_dbname});
1047 push @args, ("-p", $form->{dbport}) if ($form->{dbport});
1050 my $cmd = "$pg_restore_exe " . join(" ", map { s/\\/\\\\/g; s/\"/\\\"/g; $_ } @args);
1052 my $in = IO::File->new("$cmd 2>&1 |");
1055 unlink "${tmpdir}/.pgpass", $tmp;
1058 $form->error($locale->text('The pg_restore process could not be started.'));
1061 $English::AUTOFLUSH = 1;
1064 print $form->parse_html_template("admin/restore_dataset_start_header");
1066 while (my $line = <$in>) {
1071 $form->{retval} = $CHILD_ERROR >> 8;
1072 print $form->parse_html_template("admin/restore_dataset_start_footer");
1074 unlink "${tmpdir}/.pgpass", $tmp;
1079 my $form = $main::form;
1080 my $locale = $main::locale;
1082 unlink _nologin_file_name();;
1084 $form->{callback} = "admin.pl?action=list_users";
1086 $form->redirect($locale->text('Lockfile removed!'));
1091 my $form = $main::form;
1092 my $locale = $main::locale;
1094 open(FH, ">", _nologin_file_name())
1095 or $form->error($locale->text('Cannot create Lock!'));
1098 $form->{callback} = "admin.pl?action=list_users";
1100 $form->redirect($locale->text('Lockfile created!'));
1105 call_sub($main::form->{yes_nextsub});
1109 call_sub($main::form->{no_nextsub});
1113 call_sub($main::form->{add_nextsub});
1117 my $form = $main::form;
1119 $form->{edit_nextsub} ||= 'edit_user';
1121 call_sub($form->{edit_nextsub});
1125 my $form = $main::form;
1127 $form->{delete_nextsub} ||= 'delete_user';
1129 call_sub($form->{delete_nextsub});
1133 my $form = $main::form;
1135 $form->{save_nextsub} ||= 'save_user';
1137 call_sub($form->{save_nextsub});
1141 call_sub($main::form->{back_nextsub});
1145 my $form = $main::form;
1146 my $locale = $main::locale;
1148 foreach my $action (qw(create_standard_group dont_create_standard_group
1149 save_user delete_user save_user_as_new)) {
1150 if ($form->{"action_${action}"}) {
1156 call_sub($form->{default_action}) if ($form->{default_action});
1158 $form->error($locale->text('No action defined.'));
1161 sub _apply_dbupgrade_scripts {
1162 ::end_of_request() if SL::DBUpgrade2->new(form => $::form, dbdriver => 'Pg', auth => 1)->apply_admin_dbupgrade_scripts(1);
1165 sub _nologin_file_name {
1166 return $::lx_office_conf{paths}->{userspath} . '/nologin';
1169 sub _search_templates {
1170 # is there a templates basedir
1171 if (!-d $::lx_office_conf{paths}->{templates}) {
1172 $::form->error(sprintf($::locale->text("The directory %s does not exist."), $::lx_office_conf{paths}->{templates}));
1175 tie my %dir_h, 'IO::Dir', $::lx_office_conf{paths}->{templates};
1177 my @alldir = sort grep {
1178 -d ($::lx_office_conf{paths}->{templates} . "/$_")
1180 && !m/\.(?:html|tex|sty|odt|xml|txb)$/
1181 && !m/^(?:webpages$|print$|mail$|\.)/
1184 tie %dir_h, 'IO::Dir', "$::lx_office_conf{paths}->{templates}/print";
1185 my @allmaster = ('Standard', sort grep { -d ("$::lx_office_conf{paths}->{templates}/print" . "/$_") && !/^\.\.?$/ && !/^Standard$/ } keys %dir_h);
1187 return \@alldir, \@allmaster;