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 Win2000.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 => 'v4', title => $::locale->text('Top (CSS) new') },
84 { id => 'neu', title => $::locale->text('Top (Javascript)') },
88 $::lxdebug->enter_sub;
89 my $session_result = shift;
95 $::request->{layout} = SL::Layout::Dispatcher->new(style => 'admin');
96 $::request->{layout}->use_stylesheet("lx-office-erp.css");
97 $form->{favicon} = "favicon.ico";
99 if ($form->{action}) {
100 if ($auth->authenticate_root($form->{'{AUTH}admin_password'}) != $auth->OK()) {
101 $auth->punish_wrong_login;
102 $form->{error_message} = $locale->text('Incorrect Password!');
103 $auth->delete_session_value('admin_password');
106 if ($auth->session_tables_present()) {
107 delete $::form->{'{AUTH}admin_password'};
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 $params{admin_password} = $::lx_office_conf{authentication}->{admin_password};
153 if (!$main::auth->check_database()) {
154 $form->{title} = $locale->text('Authentification database creation');
156 print $form->parse_html_template('admin/check_auth_database', \%params);
161 if (!$main::auth->check_tables()) {
162 $form->{title} = $locale->text('Authentification tables creation');
164 print $form->parse_html_template('admin/check_auth_tables', \%params);
169 my $memberfile = $::lx_office_conf{paths}->{memberfile};
170 if (-f $memberfile) {
173 if ($memberfile =~ m|^.*/|) {
177 my $backupdir = "${memberdir}member-file-migration";
179 $form->{title} = $locale->text('User data migration');
181 print $form->parse_html_template('admin/user_migration', { 'memberfile' => $memberfile,
182 'backupdir' => $backupdir });
189 my $form = $main::form;
191 $main::auth->create_database('superuser' => $form->{db_superuser},
192 'superuser_password' => $form->{db_superuser_password},
193 'template' => $form->{db_template});
197 sub create_auth_tables {
198 my $form = $main::form;
199 my $locale = $main::locale;
201 $main::auth->create_tables();
202 $main::auth->set_session_value('admin_password', $form->{'{AUTH}admin_password'});
203 $main::auth->create_or_refresh_session();
205 my $memberfile = $::lx_office_conf{paths}->{memberfile};
206 if (!-f $memberfile) {
207 # New installation -- create a standard group with full access
210 'name' => $locale->text('Full Access'),
211 'description' => $locale->text('Full access to all functions'),
212 'rights' => { map { $_ => 1 } SL::Auth::all_rights() },
213 'members' => [ map { $_->{id} } values %members ],
216 $main::auth->save_group($group);
219 _apply_dbupgrade_scripts();
224 $main::lxdebug->enter_sub();
226 my $form = $main::form;
227 my $locale = $main::locale;
231 my $memberfile = $::lx_office_conf{paths}->{memberfile};
232 if ($memberfile =~ m|^.*/|) {
236 my $backupdir = "${memberdir}member-file-migration";
238 if (! -d $backupdir && !mkdir $backupdir, 0700) {
239 $form->error(sprintf($locale->text('The directory "%s" could not be created:\n%s'), $backupdir, $!));
242 copy $memberfile, "users/member-file-migration/members";
244 my $in = IO::File->new($memberfile, "r");
246 $form->error($locale->text('Could not open the old memberfile.')) if (!$in);
248 my (%members, $login);
257 $login =~ s/(\[|\])//g;
261 $members{$login} = { "login" => $login };
265 if ($login && m/=/) {
266 my ($key, $value) = split m/\s*=\s*/, $_, 2;
271 $value =~ s|\\n|\n|g;
273 $members{$login}->{$key} = $value;
279 delete $members{"root login"};
281 map { $_->{dbpasswd} = unpack 'u', $_->{dbpasswd} } values %members;
283 while (my ($login, $params) = each %members) {
284 $main::auth->save_user($login, %{ $params });
285 $main::auth->change_password($login, $params->{password}, 1);
287 my $conf_file = "${memberdir}${login}.conf";
290 copy $conf_file, "${backupdir}/${login}.conf";
297 my @member_list = sort { lc $a->{login} cmp lc $b->{login} } values %members;
299 $form->{title} = $locale->text('User data migration');
301 print $form->parse_html_template('admin/user_migration_done', { 'MEMBERS' => \@member_list });
303 $main::lxdebug->leave_sub();
306 sub create_standard_group_ask {
307 my $form = $main::form;
308 my $locale = $main::locale;
310 $form->{title} = $locale->text('Create a standard group');
313 print $form->parse_html_template("admin/create_standard_group_ask");
316 sub create_standard_group {
317 my $form = $main::form;
318 my $locale = $main::locale;
320 my %members = $main::auth->read_all_users();
322 my $groups = $main::auth->read_groups();
324 foreach my $group (values %{$groups}) {
325 if (($form->{group_id} != $group->{id})
326 && ($form->{name} eq $group->{name})) {
327 $form->show_generic_error($locale->text("A group with that name does already exist."));
332 'name' => $locale->text('Full Access'),
333 'description' => $locale->text('Full access to all functions'),
334 'rights' => { map { $_ => 1 } SL::Auth::all_rights() },
335 'members' => [ map { $_->{id} } values %members ],
338 $main::auth->save_group($group);
340 user_migration_complete(1);
343 sub dont_create_standard_group {
344 user_migration_complete(0);
347 sub user_migration_complete {
348 my $standard_group_created = shift;
350 my $form = $main::form;
351 my $locale = $main::locale;
353 $form->{title} = $locale->text('User migration complete');
356 print $form->parse_html_template('admin/user_migration_complete', { 'standard_group_created' => $standard_group_created });
360 my $form = $main::form;
361 my $locale = $main::locale;
363 my %members = $main::auth->read_all_users();
365 delete $members{"root login"};
367 for (values %members) {
368 $_->{templates} =~ s|.*/||;
369 $_->{login_url} = $::locale->is_utf8 ? Encode::encode('utf-8-strict', $_->{login}) : $_->{login_url};
372 $form->{title} = "kivitendo " . $locale->text('Administration');
373 $form->{LOCKED} = -e _nologin_file_name();
374 $form->{MEMBERS} = [ @members{sort { lc $a cmp lc $b } keys %members} ];
377 print $form->parse_html_template("admin/list_users");
381 $::form->{title} = "kivitendo " . $::locale->text('Administration') . " / " . $::locale->text('Add User');
383 # Note: Menu Style 'v3' is not compatible to all browsers!
384 # "menustyle" => "old" sets the HTML Menu to default.
385 # User does not have a well behaved new constructor, so we#Ll just have to build one ourself
388 "countrycode" => "de",
389 "numberformat" => "1.000,00",
390 "dateformat" => "dd.mm.yy",
391 "stylesheet" => "kivitendo.css",
392 "menustyle" => "old",
393 dbport => $::auth->{DB_config}->{port} || 5432,
394 dbuser => $::auth->{DB_config}->{user} || 'lxoffice',
395 dbhost => $::auth->{DB_config}->{host} || 'localhost',
398 edit_user_form($user);
402 $::form->{title} = "kivitendo " . $::locale->text('Administration') . " / " . $::locale->text('Edit User');
406 my $user = User->new(id => $::form->{user}{id});
408 # strip basedir from templates directory
409 $user->{templates} =~ s|.*/||;
411 edit_user_form($user);
417 my %cc = $user->country_codes;
418 my @all_countrycodes = map { id => $_, title => $cc{$_} }, sort { $cc{$a} cmp $cc{$b} } keys %cc;
419 my ($all_dir, $all_master) = _search_templates();
422 if ($::form->{edit}) {
423 my $user_id = $::auth->get_user_id($user->{login});
424 my $all_groups = $::auth->read_groups();
426 for my $group (values %{ $all_groups }) {
427 push @{ $groups }, $group if (grep { $user_id == $_ } @{ $group->{members} });
430 $groups = [ sort { lc $a->{name} cmp lc $b->{name} } @{ $groups } ];
434 print $::form->parse_html_template("admin/edit_user", {
436 CAN_CHANGE_PASSWORD => $::auth->can_change_password,
438 all_stylesheets => \@all_stylesheets,
439 all_numberformats => \@valid_numberformats,
440 all_dateformats => \@valid_dateformats,
441 all_countrycodes => \@all_countrycodes,
442 all_menustyles => \@all_menustyles,
443 all_templates => $all_dir,
444 all_master_templates => $all_master,
449 my $form = $main::form;
450 my $locale = $main::locale;
452 my $user = $form->{user};
454 $user->{dbdriver} = 'Pg';
456 if (!$::form->{edit}) {
457 # no spaces allowed in login name
458 $user->{login} =~ s/\s//g;
459 $::form->show_generic_error($::locale->text('Login name missing!')) unless $user->{login};
461 # check for duplicates
462 my %members = $::auth->read_all_users;
463 if ($members{$user->{login}}) {
464 $::form->show_generic_error($locale->text('Another user with the login #1 does already exist.', $user->{login}), 'back_button' => 1);
468 # no spaces allowed in directories
469 ($::form->{newtemplates}) = split / /, $::form->{newtemplates};
470 $user->{templates} = $::form->{newtemplates} || $::form->{usetemplates} || $user->{login};
473 if (!-d $::lx_office_conf{paths}->{templates}) {
474 $::form->error(sprintf($::locale->text("The directory %s does not exist."), $::lx_office_conf{paths}->{templates}));
477 # add base directory to $form->{templates}
478 $user->{templates} =~ s|.*/||;
479 $user->{templates} = $::lx_office_conf{paths}->{templates} . "/$user->{templates}";
481 my $myconfig = new User(id => $user->{id});
483 $::form->show_generic_error($::locale->text('Dataset missing!')) unless $user->{dbname};
484 $::form->show_generic_error($::locale->text('Database User missing!')) unless $user->{dbuser};
486 foreach my $item (keys %{$user}) {
487 $myconfig->{$item} = $user->{$item};
490 $myconfig->save_member;
492 $user->{templates} =~ s|.*/||;
493 $user->{templates} = $::lx_office_conf{paths}->{templates} . "/$user->{templates}";
494 $::form->{mastertemplates} =~ s|.*/||;
496 # create user template directory and copy master files
497 if (!-d "$user->{templates}") {
500 if (mkdir "$user->{templates}", oct("771")) {
504 # copy templates to the directory
506 my $oldcurrdir = getcwd();
507 if (!chdir("$::lx_office_conf{paths}->{templates}/print/$::form->{mastertemplates}")) {
508 $form->error("$ERRNO: chdir $::lx_office_conf{paths}->{templates}/print/$::form->{mastertemplates}");
511 my $newdir = File::Spec->catdir($oldcurrdir, $user->{templates});
519 if (!mkdir (File::Spec->catdir($newdir, $File::Find::name))) {
521 $form->error("$ERRNO: mkdir $File::Find::name");
524 if (!symlink (readlink($_),
525 File::Spec->catfile($newdir, $File::Find::name))) {
527 $form->error("$ERRNO: symlink $File::Find::name");
530 if (!copy($_, File::Spec->catfile($newdir, $File::Find::name))) {
532 $form->error("$ERRNO: cp $File::Find::name");
540 $form->error("$ERRNO: $user->{templates}");
544 # Add new user to his groups.
545 if (ref $form->{new_user_group_ids} eq 'ARRAY') {
546 my $all_groups = $main::auth->read_groups();
547 my %user = $main::auth->read_user(login => $myconfig->{login});
549 foreach my $group_id (@{ $form->{new_user_group_ids} }) {
550 my $group = $all_groups->{$group_id};
554 push @{ $group->{members} }, $user{id};
555 $main::auth->save_group($group);
559 if ($main::auth->can_change_password()
560 && defined $::form->{new_password}
561 && ($::form->{new_password} ne '********')) {
562 my $verifier = SL::Auth::PasswordPolicy->new;
563 my $result = $verifier->verify($::form->{new_password}, 1);
565 if ($result != SL::Auth::PasswordPolicy->OK()) {
566 $form->error($::locale->text('The settings were saved, but the password was not changed.') . ' ' . join(' ', $verifier->errors($result)));
569 $main::auth->change_password($myconfig->{login}, $::form->{new_password});
572 $::form->redirect($::locale->text('User saved!'));
575 sub save_user_as_new {
576 my $form = $main::form;
578 $form->{user}{login} = $::form->{new_user_login};
579 delete $form->{user}{id};
580 delete @{$form}{qw(id edit new_user_login)};
586 my $form = $main::form;
587 my $locale = $main::locale;
589 my $user = $::form->{user} || {};
591 $::form->show_generic_error($::locale->text('Missing user id!')) unless $user->{id};
593 my $loaded_user = User->new(id => $user->{id});
595 my %members = $main::auth->read_all_users();
596 my $templates = $members{$loaded_user->{login}}->{templates};
598 $main::auth->delete_user($loaded_user->{login});
601 my $templates_in_use = 0;
603 foreach my $login (keys %members) {
604 next if $loaded_user->{login} eq $login;
605 next if $members{$login}->{templates} ne $templates;
606 $templates_in_use = 1;
610 if (!$templates_in_use && -d $templates) {
611 unlink <$templates/*>;
616 $form->redirect($locale->text('User deleted!'));
624 return ($login) ? $login : undef;
630 my ($null, $value) = split(/=/, $line, 2);
633 $value =~ s/\s#.*//g;
635 # remove any trailing whitespace
636 $value =~ s/^\s*(.*?)\s*$/$1/;
641 sub pg_database_administration {
642 my $form = $main::form;
644 $form->{dbdriver} = 'Pg';
649 sub dbselect_source {
650 my $form = $main::form;
651 my $locale = $main::locale;
653 $form->{dbport} = $::auth->{DB_config}->{port} || 5432;
654 $form->{dbuser} = $::auth->{DB_config}->{user} || 'lxoffice';
655 $form->{dbdefault} = 'template1';
656 $form->{dbhost} = $::auth->{DB_config}->{host} || 'localhost';
658 $form->{title} = "kivitendo / " . $locale->text('Database Administration');
660 # Intentionnaly disabled unless fixed to work with the authentication DB.
661 $form->{ALLOW_DBBACKUP} = 0; # "$pg_dump_exe" ne "DISABLED";
664 print $form->parse_html_template("admin/dbadmin");
667 sub test_db_connection {
668 my $form = $main::form;
669 my $locale = $main::locale;
671 $form->{dbdriver} = 'Pg';
672 User::dbconnect_vars($form, $form->{dbname});
674 my $dbh = DBI->connect($form->{dbconnect}, $form->{dbuser}, $form->{dbpasswd});
676 $form->{connection_ok} = $dbh ? 1 : 0;
677 $form->{errstr} = $DBI::errstr;
679 $dbh->disconnect() if ($dbh);
681 $form->{title} = $locale->text('Database Connection Test');
683 print $form->parse_html_template("admin/test_db_connection");
687 call_sub($main::form->{"nextsub"});
691 my $form = $main::form;
692 my $locale = $main::locale;
694 $form->{title} = "kivitendo " . $locale->text('Database Administration') . " / " . $locale->text('Update Dataset');
696 my @need_updates = User->dbneedsupdate($form);
697 $form->{NEED_UPDATES} = \@need_updates;
698 $form->{ALL_UPDATED} = !scalar @need_updates;
701 print $form->parse_html_template("admin/update_dataset");
705 my $form = $main::form;
706 my $locale = $main::locale;
708 $::request->{layout}->use_stylesheet("lx-office-erp.css");
709 $form->{title} = $locale->text("Dataset upgrade");
712 my $rowcount = $form->{rowcount} * 1;
713 my @update_rows = grep { $form->{"update_$_"} } (1 .. $rowcount);
714 $form->{NOTHING_TO_DO} = !scalar @update_rows;
715 my $saved_form = save_form();
719 print $form->parse_html_template("admin/dbupgrade_all_header");
721 foreach my $i (@update_rows) {
722 restore_form($saved_form);
725 map { $form->{$_} = $::myconfig{$_} = $form->{"${_}_${i}"} } qw(dbname dbdriver dbhost dbport dbuser dbpasswd);
727 print $form->parse_html_template("admin/dbupgrade_header");
729 $form->{dbupdate} = $form->{dbname};
730 $form->{$form->{dbname}} = 1;
732 User->dbupdate($form);
733 User->dbupdate2($form, SL::DBUpgrade2->new(form => $form, dbdriver => $form->{dbdriver})->parse_dbupdate_controls);
735 print $form->parse_html_template("admin/dbupgrade_footer");
738 print $form->parse_html_template("admin/dbupgrade_all_done");
742 my $form = $main::form;
743 my $locale = $main::locale;
745 $form->{dbsources} = join " ", map { "[${_}]" } sort User->dbsources($form);
747 $form->{CHARTS} = [];
749 tie my %dir_h, 'IO::Dir', 'sql/';
750 foreach my $item (map { s/-chart\.sql$//; $_ } sort grep { /-chart\.sql\z/ && !/Default-chart.sql\z/ } keys %dir_h) {
751 push @{ $form->{CHARTS} }, { name => $item,
752 selected => $item eq "Germany-DATEV-SKR03EU" };
755 $form->{ACCOUNTING_METHODS} = [ map { { name => $_, selected => $_ eq 'cash' } } qw(accrual cash) ];
756 $form->{INVENTORY_SYSTEMS} = [ map { { name => $_, selected => $_ eq 'periodic' } } qw(perpetual periodic) ];
757 $form->{PROFIT_DETERMINATIONS} = [ map { { name => $_, selected => $_ eq 'income' } } qw(balance income) ];
759 my $default_charset = $::lx_office_conf{system}->{dbcharset} || Common::DEFAULT_CHARSET;
761 my $cluster_encoding = User->dbclusterencoding($form);
762 if ($cluster_encoding && ($cluster_encoding =~ m/^(?:UTF-?8|UNICODE)$/i)) {
763 if ($::lx_office_conf{system}->{dbcharset} !~ m/^UTF-?8$/i) {
764 $form->show_generic_error($locale->text('The selected PostgreSQL installation uses UTF-8 as its encoding. ' .
765 'Therefore you have to configure Lx-Office to use UTF-8 as well.'),
769 $form->{FORCE_DBENCODING} = 'UNICODE';
772 $form->{DBENCODINGS} = [ map { { %{$_}, selected => $_->{charset} eq $default_charset } } @Common::db_encodings ];
775 $form->{title} = "kivitendo " . $locale->text('Database Administration') . " / " . $locale->text('Create Dataset');
778 print $form->parse_html_template("admin/create_dataset");
782 my $form = $main::form;
783 my $locale = $main::locale;
785 $form->isblank("db", $locale->text('Dataset missing!'));
787 User->dbcreate(\%$form);
789 $form->{title} = "kivitendo " . $locale->text('Database Administration') . " / " . $locale->text('Create Dataset');
792 print $form->parse_html_template("admin/dbcreate");
796 my $form = $main::form;
797 my $locale = $main::locale;
799 my @dbsources = User->dbsources_unused($form);
800 $form->error($locale->text('Nothing to delete!')) unless @dbsources;
802 $form->{title} = "kivitendo " . $locale->text('Database Administration') . " / " . $locale->text('Delete Dataset');
803 $form->{DBSOURCES} = [ map { { "name", $_ } } sort @dbsources ];
806 print $form->parse_html_template("admin/delete_dataset");
810 my $form = $main::form;
811 my $locale = $main::locale;
814 $form->error($locale->text('No Dataset selected!'));
817 User->dbdelete(\%$form);
819 $form->{title} = "kivitendo " . $locale->text('Database Administration') . " / " . $locale->text('Delete Dataset');
821 print $form->parse_html_template("admin/dbdelete");
825 my $form = $main::form;
826 my $locale = $main::locale;
828 $form->{title} = "kivitendo " . $locale->text('Database Administration') . " / " . $locale->text('Backup Dataset');
830 if ($::lx_office_conf{applications}->{pg_dump} eq "DISABLED") {
831 $form->error($locale->text('Database backups and restorations are disabled in the configuration.'));
834 my @dbsources = sort User->dbsources($form);
835 $form->{DATABASES} = [ map { { "dbname" => $_ } } @dbsources ];
836 $form->{NO_DATABASES} = !scalar @dbsources;
838 my $username = getpwuid $UID || "unknown-user";
839 my $hostname = hostname() || "unknown-host";
840 $form->{from} = "kivitendo Admin <${username}\@${hostname}>";
843 print $form->parse_html_template("admin/backup_dataset");
846 sub backup_dataset_start {
847 my $form = $main::form;
848 my $locale = $main::locale;
850 $form->{title} = "kivitendo " . $locale->text('Database Administration') . " / " . $locale->text('Backup Dataset');
852 my $pg_dump_exe = $::lx_office_conf{applications}->{pg_dump} || "pg_dump";
854 if ("$pg_dump_exe" eq "DISABLED") {
855 $form->error($locale->text('Database backups and restorations are disabled in the configuration.'));
858 $form->isblank("dbname", $locale->text('The dataset name is missing.'));
859 $form->isblank("to", $locale->text('The email address is missing.')) if $form->{destination} eq "email";
861 my $tmpdir = "/tmp/lx_office_backup_" . Common->unique_id();
862 mkdir $tmpdir, 0700 || $form->error($locale->text('A temporary directory could not be created:') . " $ERRNO");
864 my $pgpass = IO::File->new("${tmpdir}/.pgpass", O_WRONLY | O_CREAT, 0600);
868 $form->error($locale->text('A temporary file could not be created:') . " $ERRNO");
871 print $pgpass "$form->{dbhost}:$form->{dbport}:$form->{dbname}:$form->{dbuser}:$form->{dbpasswd}\n";
874 $ENV{HOME} = $tmpdir;
876 my @args = ("-Ft", "-c", "-o", "-h", $form->{dbhost}, "-U", $form->{dbuser});
877 push @args, ("-p", $form->{dbport}) if ($form->{dbport});
878 push @args, $form->{dbname};
880 my $cmd = "$pg_dump_exe " . join(" ", map { s/\\/\\\\/g; s/\"/\\\"/g; $_ } @args);
881 my $name = "dataset_backup_$form->{dbname}_" . strftime("%Y%m%d", localtime()) . ".tar";
883 if ($form->{destination} ne "email") {
884 my $in = IO::File->new("$cmd |");
887 unlink "${tmpdir}/.pgpass";
890 $form->error($locale->text('The pg_dump process could not be started.'));
893 print "content-type: application/x-tar\n";
894 print "content-disposition: attachment; filename=\"${name}\"\n\n";
896 while (my $line = <$in>) {
902 unlink "${tmpdir}/.pgpass";
906 my $tmp = $tmpdir . "/dump_" . Common::unique_id();
908 if (system("$cmd > $tmp") != 0) {
909 unlink "${tmpdir}/.pgpass", $tmp;
912 $form->error($locale->text('The pg_dump process could not be started.'));
915 my $mail = new Mailer;
917 map { $mail->{$_} = $form->{$_} } qw(from to cc subject message);
919 $mail->{charset} = $::lx_office_conf{system}->{dbcharset} || Common::DEFAULT_CHARSET;
920 $mail->{attachments} = [ { "filename" => $tmp, "name" => $name } ];
923 unlink "${tmpdir}/.pgpass", $tmp;
926 $form->{title} = "kivitendo " . $locale->text('Database Administration') . " / " . $locale->text('Backup Dataset');
929 print $form->parse_html_template("admin/backup_dataset_email_done");
933 sub restore_dataset {
934 my $form = $main::form;
935 my $locale = $main::locale;
937 $form->{title} = "kivitendo " . $locale->text('Database Administration') . " / " . $locale->text('Restore Dataset');
939 if ($::lx_office_conf{applications}->{pg_restore} eq "DISABLED") {
940 $form->error($locale->text('Database backups and restorations are disabled in the configuration.'));
943 my $default_charset = $::lx_office_conf{system}->{dbcharset};
944 $default_charset ||= Common::DEFAULT_CHARSET;
946 $form->{DBENCODINGS} = [];
948 foreach my $encoding (@Common::db_encodings) {
949 push @{ $form->{DBENCODINGS} }, { "dbencoding" => $encoding->{dbencoding},
950 "label" => $encoding->{label},
951 "selected" => $encoding->{charset} eq $default_charset };
955 print $form->parse_html_template("admin/restore_dataset");
958 sub restore_dataset_start {
959 my $form = $main::form;
960 my $locale = $main::locale;
962 $form->{title} = "kivitendo " . $locale->text('Database Administration') . " / " . $locale->text('Restore Dataset');
964 my $pg_restore_exe = $::lx_office_conf{applications}->{pg_restore} || "pg_restore";
966 if ("$pg_restore_exe" eq "DISABLED") {
967 $form->error($locale->text('Database backups and restorations are disabled in the configuration.'));
970 $form->isblank("new_dbname", $locale->text('The dataset name is missing.'));
971 $form->isblank("content", $locale->text('No backup file has been uploaded.'));
973 # Create temporary directories. Write the backup file contents to a temporary
974 # file. Create a .pgpass file with the username and password for the pg_restore
977 my $tmpdir = "/tmp/lx_office_backup_" . Common->unique_id();
978 mkdir $tmpdir, 0700 || $form->error($locale->text('A temporary directory could not be created:') . " $ERRNO");
980 my $pgpass = IO::File->new("${tmpdir}/.pgpass", O_WRONLY | O_CREAT, 0600);
984 $form->error($locale->text('A temporary file could not be created:') . " $ERRNO");
987 print $pgpass "$form->{dbhost}:$form->{dbport}:$form->{new_dbname}:$form->{dbuser}:$form->{dbpasswd}\n";
990 $ENV{HOME} = $tmpdir;
992 my $tmp = $tmpdir . "/dump_" . Common::unique_id();
995 if (substr($form->{content}, 0, 2) eq "\037\213") {
996 $tmpfile = IO::File->new("| gzip -d > $tmp");
1000 $tmpfile = IO::File->new($tmp, O_WRONLY | O_CREAT | O_BINARY, 0600);
1004 unlink "${tmpdir}/.pgpass";
1007 $form->error($locale->text('A temporary file could not be created:') . " $ERRNO");
1010 print $tmpfile $form->{content};
1013 delete $form->{content};
1015 # Try to connect to the database. Find out if a database with the same name exists.
1016 # If yes, then drop the existing database. Create a new one with the name and encoding
1017 # given by the user.
1019 User::dbconnect_vars($form, "template1");
1021 my %myconfig = map { $_ => $form->{$_} } grep /^db/, keys %{ $form };
1022 my $dbh = $form->dbconnect(\%myconfig) || $form->dberror();
1026 $form->{new_dbname} =~ s|[^a-zA-Z0-9_\-]||g;
1028 $query = qq|SELECT COUNT(*) FROM pg_database WHERE datname = ?|;
1029 my ($count) = selectrow_query($form, $dbh, $query, $form->{new_dbname});
1031 do_query($form, $dbh, qq|DROP DATABASE $form->{new_dbname}|);
1035 foreach my $item (@Common::db_encodings) {
1036 if ($item->{dbencoding} eq $form->{dbencoding}) {
1041 $form->{dbencoding} = "LATIN9" unless $form->{dbencoding};
1043 do_query($form, $dbh, qq|CREATE DATABASE $form->{new_dbname} ENCODING ? TEMPLATE template0|, $form->{dbencoding});
1047 # Spawn pg_restore on the temporary file.
1049 my @args = ("-h", $form->{dbhost}, "-U", $form->{dbuser}, "-d", $form->{new_dbname});
1050 push @args, ("-p", $form->{dbport}) if ($form->{dbport});
1053 my $cmd = "$pg_restore_exe " . join(" ", map { s/\\/\\\\/g; s/\"/\\\"/g; $_ } @args);
1055 my $in = IO::File->new("$cmd 2>&1 |");
1058 unlink "${tmpdir}/.pgpass", $tmp;
1061 $form->error($locale->text('The pg_restore process could not be started.'));
1064 $English::AUTOFLUSH = 1;
1067 print $form->parse_html_template("admin/restore_dataset_start_header");
1069 while (my $line = <$in>) {
1074 $form->{retval} = $CHILD_ERROR >> 8;
1075 print $form->parse_html_template("admin/restore_dataset_start_footer");
1077 unlink "${tmpdir}/.pgpass", $tmp;
1082 my $form = $main::form;
1083 my $locale = $main::locale;
1085 unlink _nologin_file_name();;
1087 $form->{callback} = "admin.pl?action=list_users";
1089 $form->redirect($locale->text('Lockfile removed!'));
1094 my $form = $main::form;
1095 my $locale = $main::locale;
1097 open(FH, ">", _nologin_file_name())
1098 or $form->error($locale->text('Cannot create Lock!'));
1101 $form->{callback} = "admin.pl?action=list_users";
1103 $form->redirect($locale->text('Lockfile created!'));
1108 call_sub($main::form->{yes_nextsub});
1112 call_sub($main::form->{no_nextsub});
1116 call_sub($main::form->{add_nextsub});
1120 my $form = $main::form;
1122 $form->{edit_nextsub} ||= 'edit_user';
1124 call_sub($form->{edit_nextsub});
1128 my $form = $main::form;
1130 $form->{delete_nextsub} ||= 'delete_user';
1132 call_sub($form->{delete_nextsub});
1136 my $form = $main::form;
1138 $form->{save_nextsub} ||= 'save_user';
1140 call_sub($form->{save_nextsub});
1144 call_sub($main::form->{back_nextsub});
1148 my $form = $main::form;
1149 my $locale = $main::locale;
1151 foreach my $action (qw(create_standard_group dont_create_standard_group
1152 save_user delete_user save_user_as_new)) {
1153 if ($form->{"action_${action}"}) {
1159 call_sub($form->{default_action}) if ($form->{default_action});
1161 $form->error($locale->text('No action defined.'));
1164 sub _apply_dbupgrade_scripts {
1165 ::end_of_request() if SL::DBUpgrade2->new(form => $::form, dbdriver => 'Pg', auth => 1)->apply_admin_dbupgrade_scripts(1);
1168 sub _nologin_file_name {
1169 return $::lx_office_conf{paths}->{userspath} . '/nologin';
1172 sub _search_templates {
1173 # is there a templates basedir
1174 if (!-d $::lx_office_conf{paths}->{templates}) {
1175 $::form->error(sprintf($::locale->text("The directory %s does not exist."), $::lx_office_conf{paths}->{templates}));
1178 tie my %dir_h, 'IO::Dir', $::lx_office_conf{paths}->{templates};
1180 my @alldir = sort grep {
1181 -d ($::lx_office_conf{paths}->{templates} . "/$_")
1183 && !m/\.(?:html|tex|sty|odt|xml|txb)$/
1184 && !m/^(?:webpages$|print$|\.)/
1187 tie %dir_h, 'IO::Dir', "$::lx_office_conf{paths}->{templates}/print";
1188 my @allmaster = ('Standard', sort grep { -d ("$::lx_office_conf{paths}->{templates}/print" . "/$_") && !/^\.\.?$/ && !/^Standard$/ } keys %dir_h);
1190 return \@alldir, \@allmaster;