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 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 $::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_message} = $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 # Note: Menu Style 'v3' is not compatible to all browsers!
383 # "menustyle" => "old" sets the HTML Menu to default.
384 # User does not have a well behaved new constructor, so we#Ll just have to build one ourself
387 "countrycode" => "de",
388 "numberformat" => "1.000,00",
389 "dateformat" => "dd.mm.yy",
390 "stylesheet" => "lx-office-erp.css",
391 "menustyle" => "old",
392 dbport => $::auth->{DB_config}->{port} || 5432,
393 dbuser => $::auth->{DB_config}->{user} || 'lxoffice',
394 dbhost => $::auth->{DB_config}->{host} || 'localhost',
397 edit_user_form($user);
401 $::form->{title} = "kivitendo " . $::locale->text('Administration') . " / " . $::locale->text('Edit User');
405 my $user = User->new(id => $::form->{user}{id});
407 # strip basedir from templates directory
408 $user->{templates} =~ s|.*/||;
410 edit_user_form($user);
416 my %cc = $user->country_codes;
417 my @all_countrycodes = map { id => $_, title => $cc{$_} }, sort { $cc{$a} cmp $cc{$b} } keys %cc;
418 my ($all_dir, $all_master) = _search_templates();
421 if ($::form->{edit}) {
422 my $user_id = $::auth->get_user_id($user->{login});
423 my $all_groups = $::auth->read_groups();
425 for my $group (values %{ $all_groups }) {
426 push @{ $groups }, $group if (grep { $user_id == $_ } @{ $group->{members} });
429 $groups = [ sort { lc $a->{name} cmp lc $b->{name} } @{ $groups } ];
433 print $::form->parse_html_template("admin/edit_user", {
435 CAN_CHANGE_PASSWORD => $::auth->can_change_password,
437 all_stylesheets => \@all_stylesheets,
438 all_numberformats => \@valid_numberformats,
439 all_dateformats => \@valid_dateformats,
440 all_countrycodes => \@all_countrycodes,
441 all_menustyles => \@all_menustyles,
442 all_templates => $all_dir,
443 all_master_templates => $all_master,
448 my $form = $main::form;
449 my $locale = $main::locale;
451 my $user = $form->{user};
453 $user->{dbdriver} = 'Pg';
455 if (!$::form->{edit}) {
456 # no spaces allowed in login name
457 $user->{login} =~ s/\s//g;
458 $::form->show_generic_error($::locale->text('Login name missing!')) unless $user->{login};
460 # check for duplicates
461 my %members = $::auth->read_all_users;
462 if ($members{$user->{login}}) {
463 $::form->show_generic_error($locale->text('Another user with the login #1 does already exist.', $user->{login}), 'back_button' => 1);
467 # no spaces allowed in directories
468 ($::form->{newtemplates}) = split / /, $::form->{newtemplates};
469 $user->{templates} = $::form->{newtemplates} || $::form->{usetemplates} || $user->{login};
472 if (!-d $::lx_office_conf{paths}->{templates}) {
473 $::form->error(sprintf($::locale->text("The directory %s does not exist."), $::lx_office_conf{paths}->{templates}));
476 # add base directory to $form->{templates}
477 $user->{templates} =~ s|.*/||;
478 $user->{templates} = $::lx_office_conf{paths}->{templates} . "/$user->{templates}";
480 my $myconfig = new User(id => $user->{id});
482 $::form->show_generic_error($::locale->text('Dataset missing!')) unless $user->{dbname};
483 $::form->show_generic_error($::locale->text('Database User missing!')) unless $user->{dbuser};
485 foreach my $item (keys %{$user}) {
486 $myconfig->{$item} = $user->{$item};
489 $myconfig->save_member;
491 $user->{templates} =~ s|.*/||;
492 $user->{templates} = $::lx_office_conf{paths}->{templates} . "/$user->{templates}";
493 $::form->{mastertemplates} =~ s|.*/||;
495 # create user template directory and copy master files
496 if (!-d "$user->{templates}") {
499 if (mkdir "$user->{templates}", oct("771")) {
503 # copy templates to the directory
505 my $oldcurrdir = getcwd();
506 if (!chdir("$::lx_office_conf{paths}->{templates}/print/$::form->{mastertemplates}")) {
507 $form->error("$ERRNO: chdir $::lx_office_conf{paths}->{templates}/print/$::form->{mastertemplates}");
510 my $newdir = File::Spec->catdir($oldcurrdir, $user->{templates});
518 if (!mkdir (File::Spec->catdir($newdir, $File::Find::name))) {
520 $form->error("$ERRNO: mkdir $File::Find::name");
523 if (!symlink (readlink($_),
524 File::Spec->catfile($newdir, $File::Find::name))) {
526 $form->error("$ERRNO: symlink $File::Find::name");
529 if (!copy($_, File::Spec->catfile($newdir, $File::Find::name))) {
531 $form->error("$ERRNO: cp $File::Find::name");
539 $form->error("$ERRNO: $user->{templates}");
543 # Add new user to his groups.
544 if (ref $form->{new_user_group_ids} eq 'ARRAY') {
545 my $all_groups = $main::auth->read_groups();
546 my %user = $main::auth->read_user(login => $myconfig->{login});
548 foreach my $group_id (@{ $form->{new_user_group_ids} }) {
549 my $group = $all_groups->{$group_id};
553 push @{ $group->{members} }, $user{id};
554 $main::auth->save_group($group);
558 if ($main::auth->can_change_password()
559 && defined $::form->{new_password}
560 && ($::form->{new_password} ne '********')) {
561 my $verifier = SL::Auth::PasswordPolicy->new;
562 my $result = $verifier->verify($::form->{new_password}, 1);
564 if ($result != SL::Auth::PasswordPolicy->OK()) {
565 $form->error($::locale->text('The settings were saved, but the password was not changed.') . ' ' . join(' ', $verifier->errors($result)));
568 $main::auth->change_password($myconfig->{login}, $::form->{new_password});
571 $::form->redirect($::locale->text('User saved!'));
574 sub save_user_as_new {
575 my $form = $main::form;
577 $form->{user}{login} = $::form->{new_user_login};
578 delete $form->{user}{id};
579 delete @{$form}{qw(id edit new_user_login)};
585 my $form = $main::form;
586 my $locale = $main::locale;
588 my $user = $::form->{user} || {};
590 $::form->show_generic_error($::locale->text('Missing user id!')) unless $user->{id};
592 my $loaded_user = User->new(id => $user->{id});
594 my %members = $main::auth->read_all_users();
595 my $templates = $members{$loaded_user->{login}}->{templates};
597 $main::auth->delete_user($loaded_user->{login});
600 my $templates_in_use = 0;
602 foreach my $login (keys %members) {
603 next if $loaded_user->{login} eq $login;
604 next if $members{$login}->{templates} ne $templates;
605 $templates_in_use = 1;
609 if (!$templates_in_use && -d $templates) {
610 unlink <$templates/*>;
615 $form->redirect($locale->text('User deleted!'));
623 return ($login) ? $login : undef;
629 my ($null, $value) = split(/=/, $line, 2);
632 $value =~ s/\s#.*//g;
634 # remove any trailing whitespace
635 $value =~ s/^\s*(.*?)\s*$/$1/;
640 sub pg_database_administration {
641 my $form = $main::form;
643 $form->{dbdriver} = 'Pg';
648 sub dbselect_source {
649 my $form = $main::form;
650 my $locale = $main::locale;
652 $form->{dbport} = $::auth->{DB_config}->{port} || 5432;
653 $form->{dbuser} = $::auth->{DB_config}->{user} || 'lxoffice';
654 $form->{dbdefault} = 'template1';
655 $form->{dbhost} = $::auth->{DB_config}->{host} || 'localhost';
657 $form->{title} = "kivitendo / " . $locale->text('Database Administration');
659 # Intentionnaly disabled unless fixed to work with the authentication DB.
660 $form->{ALLOW_DBBACKUP} = 0; # "$pg_dump_exe" ne "DISABLED";
663 print $form->parse_html_template("admin/dbadmin");
666 sub test_db_connection {
667 my $form = $main::form;
668 my $locale = $main::locale;
670 $form->{dbdriver} = 'Pg';
671 User::dbconnect_vars($form, $form->{dbname});
673 my $dbh = DBI->connect($form->{dbconnect}, $form->{dbuser}, $form->{dbpasswd});
675 $form->{connection_ok} = $dbh ? 1 : 0;
676 $form->{errstr} = $DBI::errstr;
678 $dbh->disconnect() if ($dbh);
680 $form->{title} = $locale->text('Database Connection Test');
682 print $form->parse_html_template("admin/test_db_connection");
686 call_sub($main::form->{"nextsub"});
690 my $form = $main::form;
691 my $locale = $main::locale;
693 $form->{title} = "kivitendo " . $locale->text('Database Administration') . " / " . $locale->text('Update Dataset');
695 my @need_updates = User->dbneedsupdate($form);
696 $form->{NEED_UPDATES} = \@need_updates;
697 $form->{ALL_UPDATED} = !scalar @need_updates;
700 print $form->parse_html_template("admin/update_dataset");
704 my $form = $main::form;
705 my $locale = $main::locale;
707 $::request->{layout}->use_stylesheet("lx-office-erp.css");
708 $form->{title} = $locale->text("Dataset upgrade");
711 my $rowcount = $form->{rowcount} * 1;
712 my @update_rows = grep { $form->{"update_$_"} } (1 .. $rowcount);
713 $form->{NOTHING_TO_DO} = !scalar @update_rows;
714 my $saved_form = save_form();
718 print $form->parse_html_template("admin/dbupgrade_all_header");
720 foreach my $i (@update_rows) {
721 restore_form($saved_form);
724 map { $form->{$_} = $::myconfig{$_} = $form->{"${_}_${i}"} } qw(dbname dbdriver dbhost dbport dbuser dbpasswd);
726 print $form->parse_html_template("admin/dbupgrade_header");
728 $form->{dbupdate} = $form->{dbname};
729 $form->{$form->{dbname}} = 1;
731 User->dbupdate($form);
732 User->dbupdate2($form, SL::DBUpgrade2->new(form => $form, dbdriver => $form->{dbdriver})->parse_dbupdate_controls);
734 print $form->parse_html_template("admin/dbupgrade_footer");
737 print $form->parse_html_template("admin/dbupgrade_all_done");
741 my $form = $main::form;
742 my $locale = $main::locale;
744 $form->{dbsources} = join " ", map { "[${_}]" } sort User->dbsources($form);
746 $form->{CHARTS} = [];
748 opendir SQLDIR, "sql/." or $form->error($ERRNO);
749 foreach my $item (sort grep /-chart\.sql\z/, readdir SQLDIR) {
750 next if ($item eq 'Default-chart.sql');
751 $item =~ s/-chart\.sql//;
752 push @{ $form->{CHARTS} }, { "name" => $item,
753 "selected" => $item eq "Germany-DATEV-SKR03EU" };
757 $form->{ACCOUNTING_METHODS} = [];
758 foreach my $item ( qw(accrual cash) ) {
759 push @{ $form->{ACCOUNTING_METHODS} }, { "name" => $item,
760 "selected" => $item eq "cash" };
763 $form->{INVENTORY_SYSTEMS} = [];
764 foreach my $item ( qw(perpetual periodic) ) {
765 push @{ $form->{INVENTORY_SYSTEMS} }, { "name" => $item,
766 "selected" => $item eq "periodic" };
769 $form->{PROFIT_DETERMINATIONS} = [];
770 foreach my $item ( qw(balance income) ) {
771 push @{ $form->{PROFIT_DETERMINATIONS} }, { "name" => $item,
772 "selected" => $item eq "income" };
775 my $default_charset = $::lx_office_conf{system}->{dbcharset};
776 $default_charset ||= Common::DEFAULT_CHARSET;
778 my $cluster_encoding = User->dbclusterencoding($form);
779 if ($cluster_encoding && ($cluster_encoding =~ m/^(?:UTF-?8|UNICODE)$/i)) {
780 if ($::lx_office_conf{system}->{dbcharset} !~ m/^UTF-?8$/i) {
781 $form->show_generic_error($locale->text('The selected PostgreSQL installation uses UTF-8 as its encoding. ' .
782 'Therefore you have to configure Lx-Office to use UTF-8 as well.'),
786 $form->{FORCE_DBENCODING} = 'UNICODE';
789 $form->{DBENCODINGS} = [];
791 foreach my $encoding (@Common::db_encodings) {
792 push @{ $form->{DBENCODINGS} }, { "dbencoding" => $encoding->{dbencoding},
793 "label" => $encoding->{label},
794 "selected" => $encoding->{charset} eq $default_charset };
798 $form->{title} = "kivitendo " . $locale->text('Database Administration') . " / " . $locale->text('Create Dataset');
801 print $form->parse_html_template("admin/create_dataset");
805 my $form = $main::form;
806 my $locale = $main::locale;
808 $form->isblank("db", $locale->text('Dataset missing!'));
810 User->dbcreate(\%$form);
812 $form->{title} = "kivitendo " . $locale->text('Database Administration') . " / " . $locale->text('Create Dataset');
815 print $form->parse_html_template("admin/dbcreate");
819 my $form = $main::form;
820 my $locale = $main::locale;
822 my @dbsources = User->dbsources_unused($form);
823 $form->error($locale->text('Nothing to delete!')) unless @dbsources;
825 $form->{title} = "kivitendo " . $locale->text('Database Administration') . " / " . $locale->text('Delete Dataset');
826 $form->{DBSOURCES} = [ map { { "name", $_ } } sort @dbsources ];
829 print $form->parse_html_template("admin/delete_dataset");
833 my $form = $main::form;
834 my $locale = $main::locale;
837 $form->error($locale->text('No Dataset selected!'));
840 User->dbdelete(\%$form);
842 $form->{title} = "kivitendo " . $locale->text('Database Administration') . " / " . $locale->text('Delete Dataset');
844 print $form->parse_html_template("admin/dbdelete");
848 my $form = $main::form;
849 my $locale = $main::locale;
851 $form->{title} = "kivitendo " . $locale->text('Database Administration') . " / " . $locale->text('Backup Dataset');
853 if ($::lx_office_conf{applications}->{pg_dump} eq "DISABLED") {
854 $form->error($locale->text('Database backups and restorations are disabled in the configuration.'));
857 my @dbsources = sort User->dbsources($form);
858 $form->{DATABASES} = [ map { { "dbname" => $_ } } @dbsources ];
859 $form->{NO_DATABASES} = !scalar @dbsources;
861 my $username = getpwuid $UID || "unknown-user";
862 my $hostname = hostname() || "unknown-host";
863 $form->{from} = "kivitendo Admin <${username}\@${hostname}>";
866 print $form->parse_html_template("admin/backup_dataset");
869 sub backup_dataset_start {
870 my $form = $main::form;
871 my $locale = $main::locale;
873 $form->{title} = "kivitendo " . $locale->text('Database Administration') . " / " . $locale->text('Backup Dataset');
875 my $pg_dump_exe = $::lx_office_conf{applications}->{pg_dump} || "pg_dump";
877 if ("$pg_dump_exe" eq "DISABLED") {
878 $form->error($locale->text('Database backups and restorations are disabled in the configuration.'));
881 $form->isblank("dbname", $locale->text('The dataset name is missing.'));
882 $form->isblank("to", $locale->text('The email address is missing.')) if $form->{destination} eq "email";
884 my $tmpdir = "/tmp/lx_office_backup_" . Common->unique_id();
885 mkdir $tmpdir, 0700 || $form->error($locale->text('A temporary directory could not be created:') . " $ERRNO");
887 my $pgpass = IO::File->new("${tmpdir}/.pgpass", O_WRONLY | O_CREAT, 0600);
891 $form->error($locale->text('A temporary file could not be created:') . " $ERRNO");
894 print $pgpass "$form->{dbhost}:$form->{dbport}:$form->{dbname}:$form->{dbuser}:$form->{dbpasswd}\n";
897 $ENV{HOME} = $tmpdir;
899 my @args = ("-Ft", "-c", "-o", "-h", $form->{dbhost}, "-U", $form->{dbuser});
900 push @args, ("-p", $form->{dbport}) if ($form->{dbport});
901 push @args, $form->{dbname};
903 my $cmd = "$pg_dump_exe " . join(" ", map { s/\\/\\\\/g; s/\"/\\\"/g; $_ } @args);
904 my $name = "dataset_backup_$form->{dbname}_" . strftime("%Y%m%d", localtime()) . ".tar";
906 if ($form->{destination} ne "email") {
907 my $in = IO::File->new("$cmd |");
910 unlink "${tmpdir}/.pgpass";
913 $form->error($locale->text('The pg_dump process could not be started.'));
916 print "content-type: application/x-tar\n";
917 print "content-disposition: attachment; filename=\"${name}\"\n\n";
919 while (my $line = <$in>) {
925 unlink "${tmpdir}/.pgpass";
929 my $tmp = $tmpdir . "/dump_" . Common::unique_id();
931 if (system("$cmd > $tmp") != 0) {
932 unlink "${tmpdir}/.pgpass", $tmp;
935 $form->error($locale->text('The pg_dump process could not be started.'));
938 my $mail = new Mailer;
940 map { $mail->{$_} = $form->{$_} } qw(from to cc subject message);
942 $mail->{charset} = $::lx_office_conf{system}->{dbcharset} || Common::DEFAULT_CHARSET;
943 $mail->{attachments} = [ { "filename" => $tmp, "name" => $name } ];
946 unlink "${tmpdir}/.pgpass", $tmp;
949 $form->{title} = "kivitendo " . $locale->text('Database Administration') . " / " . $locale->text('Backup Dataset');
952 print $form->parse_html_template("admin/backup_dataset_email_done");
956 sub restore_dataset {
957 my $form = $main::form;
958 my $locale = $main::locale;
960 $form->{title} = "kivitendo " . $locale->text('Database Administration') . " / " . $locale->text('Restore Dataset');
962 if ($::lx_office_conf{applications}->{pg_restore} eq "DISABLED") {
963 $form->error($locale->text('Database backups and restorations are disabled in the configuration.'));
966 my $default_charset = $::lx_office_conf{system}->{dbcharset};
967 $default_charset ||= Common::DEFAULT_CHARSET;
969 $form->{DBENCODINGS} = [];
971 foreach my $encoding (@Common::db_encodings) {
972 push @{ $form->{DBENCODINGS} }, { "dbencoding" => $encoding->{dbencoding},
973 "label" => $encoding->{label},
974 "selected" => $encoding->{charset} eq $default_charset };
978 print $form->parse_html_template("admin/restore_dataset");
981 sub restore_dataset_start {
982 my $form = $main::form;
983 my $locale = $main::locale;
985 $form->{title} = "kivitendo " . $locale->text('Database Administration') . " / " . $locale->text('Restore Dataset');
987 my $pg_restore_exe = $::lx_office_conf{applications}->{pg_restore} || "pg_restore";
989 if ("$pg_restore_exe" eq "DISABLED") {
990 $form->error($locale->text('Database backups and restorations are disabled in the configuration.'));
993 $form->isblank("new_dbname", $locale->text('The dataset name is missing.'));
994 $form->isblank("content", $locale->text('No backup file has been uploaded.'));
996 # Create temporary directories. Write the backup file contents to a temporary
997 # file. Create a .pgpass file with the username and password for the pg_restore
1000 my $tmpdir = "/tmp/lx_office_backup_" . Common->unique_id();
1001 mkdir $tmpdir, 0700 || $form->error($locale->text('A temporary directory could not be created:') . " $ERRNO");
1003 my $pgpass = IO::File->new("${tmpdir}/.pgpass", O_WRONLY | O_CREAT, 0600);
1007 $form->error($locale->text('A temporary file could not be created:') . " $ERRNO");
1010 print $pgpass "$form->{dbhost}:$form->{dbport}:$form->{new_dbname}:$form->{dbuser}:$form->{dbpasswd}\n";
1013 $ENV{HOME} = $tmpdir;
1015 my $tmp = $tmpdir . "/dump_" . Common::unique_id();
1018 if (substr($form->{content}, 0, 2) eq "\037\213") {
1019 $tmpfile = IO::File->new("| gzip -d > $tmp");
1023 $tmpfile = IO::File->new($tmp, O_WRONLY | O_CREAT | O_BINARY, 0600);
1027 unlink "${tmpdir}/.pgpass";
1030 $form->error($locale->text('A temporary file could not be created:') . " $ERRNO");
1033 print $tmpfile $form->{content};
1036 delete $form->{content};
1038 # Try to connect to the database. Find out if a database with the same name exists.
1039 # If yes, then drop the existing database. Create a new one with the name and encoding
1040 # given by the user.
1042 User::dbconnect_vars($form, "template1");
1044 my %myconfig = map { $_ => $form->{$_} } grep /^db/, keys %{ $form };
1045 my $dbh = $form->dbconnect(\%myconfig) || $form->dberror();
1049 $form->{new_dbname} =~ s|[^a-zA-Z0-9_\-]||g;
1051 $query = qq|SELECT COUNT(*) FROM pg_database WHERE datname = ?|;
1052 my ($count) = selectrow_query($form, $dbh, $query, $form->{new_dbname});
1054 do_query($form, $dbh, qq|DROP DATABASE $form->{new_dbname}|);
1058 foreach my $item (@Common::db_encodings) {
1059 if ($item->{dbencoding} eq $form->{dbencoding}) {
1064 $form->{dbencoding} = "LATIN9" unless $form->{dbencoding};
1066 do_query($form, $dbh, qq|CREATE DATABASE $form->{new_dbname} ENCODING ? TEMPLATE template0|, $form->{dbencoding});
1070 # Spawn pg_restore on the temporary file.
1072 my @args = ("-h", $form->{dbhost}, "-U", $form->{dbuser}, "-d", $form->{new_dbname});
1073 push @args, ("-p", $form->{dbport}) if ($form->{dbport});
1076 my $cmd = "$pg_restore_exe " . join(" ", map { s/\\/\\\\/g; s/\"/\\\"/g; $_ } @args);
1078 my $in = IO::File->new("$cmd 2>&1 |");
1081 unlink "${tmpdir}/.pgpass", $tmp;
1084 $form->error($locale->text('The pg_restore process could not be started.'));
1087 $English::AUTOFLUSH = 1;
1090 print $form->parse_html_template("admin/restore_dataset_start_header");
1092 while (my $line = <$in>) {
1097 $form->{retval} = $CHILD_ERROR >> 8;
1098 print $form->parse_html_template("admin/restore_dataset_start_footer");
1100 unlink "${tmpdir}/.pgpass", $tmp;
1105 my $form = $main::form;
1106 my $locale = $main::locale;
1108 unlink _nologin_file_name();;
1110 $form->{callback} = "admin.pl?action=list_users";
1112 $form->redirect($locale->text('Lockfile removed!'));
1117 my $form = $main::form;
1118 my $locale = $main::locale;
1120 open(FH, ">", _nologin_file_name())
1121 or $form->error($locale->text('Cannot create Lock!'));
1124 $form->{callback} = "admin.pl?action=list_users";
1126 $form->redirect($locale->text('Lockfile created!'));
1131 call_sub($main::form->{yes_nextsub});
1135 call_sub($main::form->{no_nextsub});
1139 call_sub($main::form->{add_nextsub});
1143 my $form = $main::form;
1145 $form->{edit_nextsub} ||= 'edit_user';
1147 call_sub($form->{edit_nextsub});
1151 my $form = $main::form;
1153 $form->{delete_nextsub} ||= 'delete_user';
1155 call_sub($form->{delete_nextsub});
1159 my $form = $main::form;
1161 $form->{save_nextsub} ||= 'save_user';
1163 call_sub($form->{save_nextsub});
1167 call_sub($main::form->{back_nextsub});
1171 my $form = $main::form;
1172 my $locale = $main::locale;
1174 foreach my $action (qw(create_standard_group dont_create_standard_group
1175 save_user delete_user save_user_as_new)) {
1176 if ($form->{"action_${action}"}) {
1182 call_sub($form->{default_action}) if ($form->{default_action});
1184 $form->error($locale->text('No action defined.'));
1187 sub _apply_dbupgrade_scripts {
1188 ::end_of_request() if SL::DBUpgrade2->new(form => $::form, dbdriver => 'Pg', auth => 1)->apply_admin_dbupgrade_scripts(1);
1191 sub _nologin_file_name {
1192 return $::lx_office_conf{paths}->{userspath} . '/nologin';
1195 sub _search_templates {
1196 # is there a templates basedir
1197 if (!-d $::lx_office_conf{paths}->{templates}) {
1198 $::form->error(sprintf($::locale->text("The directory %s does not exist."), $::lx_office_conf{paths}->{templates}));
1201 opendir TEMPLATEDIR, $::lx_office_conf{paths}->{templates} or $::form->error($::lx_office_conf{paths}->{templates} . " : $ERRNO");
1202 my @all = readdir(TEMPLATEDIR);
1203 my @alldir = sort grep { -d ($::lx_office_conf{paths}->{templates} . "/$_") && !/^\.\.?$/ } @all;
1204 closedir TEMPLATEDIR;
1206 @alldir = grep !/\.(html|tex|sty|odt|xml|txb)$/, @alldir;
1207 @alldir = grep !/^(webpages|print|\.svn)$/, @alldir;
1210 opendir TEMPLATEDIR, "$::lx_office_conf{paths}->{templates}/print" or $::form->error("$::lx_office_conf{paths}->{templates}/print" . " : $ERRNO");
1211 my @allmaster = readdir(TEMPLATEDIR);
1212 closedir TEMPLATEDIR;
1214 @allmaster = sort grep { -d ("$::lx_office_conf{paths}->{templates}/print" . "/$_") && !/^\.\.?$/ } @allmaster;
1215 @allmaster = reverse grep !/Default/, @allmaster;
1216 push @allmaster, 'Default';
1217 @allmaster = reverse @allmaster;
1219 return \@alldir, \@allmaster;