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 $form->{stylesheet} = "lx-office-erp.css";
95 $form->{favicon} = "favicon.ico";
97 if ($form->{action}) {
98 if ($auth->authenticate_root($form->{rpw}) != $auth->OK()) {
99 $form->{error_message} = $locale->text('Incorrect Password!');
100 $auth->delete_session_value('rpw');
103 if ($auth->session_tables_present()) {
104 delete $::form->{rpw};
105 _apply_dbupgrade_scripts();
108 call_sub($locale->findsub($form->{action}));
111 # if there are no drivers bail out
112 $form->error($locale->text('No Database Drivers available!'))
113 unless (User->dbdrivers);
117 $::lxdebug->leave_sub;
121 my $form = $main::form;
122 my $locale = $main::locale;
124 $form->{title} = qq|kivitendo $form->{version} | . $locale->text('Administration');
127 print $form->parse_html_template('admin/adminlogin');
131 check_auth_db_and_tables();
136 $main::auth->destroy_session();
140 sub check_auth_db_and_tables {
141 my $form = $main::form;
142 my $locale = $main::locale;
146 map { $params{"db_${_}"} = $main::auth->{DB_config}->{$_} } keys %{ $auth->{DB_config} };
148 if (!$main::auth->check_database()) {
149 $form->{title} = $locale->text('Authentification database creation');
151 print $form->parse_html_template('admin/check_auth_database', \%params);
156 if (!$main::auth->check_tables()) {
157 $form->{title} = $locale->text('Authentification tables creation');
159 print $form->parse_html_template('admin/check_auth_tables', \%params);
164 my $memberfile = $::lx_office_conf{paths}->{memberfile};
165 if (-f $memberfile) {
168 if ($memberfile =~ m|^.*/|) {
172 my $backupdir = "${memberdir}member-file-migration";
174 $form->{title} = $locale->text('User data migration');
176 print $form->parse_html_template('admin/user_migration', { 'memberfile' => $memberfile,
177 'backupdir' => $backupdir });
184 my $form = $main::form;
186 $main::auth->create_database('superuser' => $form->{db_superuser},
187 'superuser_password' => $form->{db_superuser_password},
188 'template' => $form->{db_template});
192 sub create_auth_tables {
193 my $form = $main::form;
194 my $locale = $main::locale;
196 $main::auth->create_tables();
197 $main::auth->set_session_value('rpw', $form->{rpw});
198 $main::auth->create_or_refresh_session();
200 my $memberfile = $::lx_office_conf{paths}->{memberfile};
201 if (!-f $memberfile) {
202 # New installation -- create a standard group with full access
205 'name' => $locale->text('Full Access'),
206 'description' => $locale->text('Full access to all functions'),
207 'rights' => { map { $_ => 1 } SL::Auth::all_rights() },
208 'members' => [ map { $_->{id} } values %members ],
211 $main::auth->save_group($group);
214 _apply_dbupgrade_scripts();
219 $main::lxdebug->enter_sub();
221 my $form = $main::form;
222 my $locale = $main::locale;
226 my $memberfile = $::lx_office_conf{paths}->{memberfile};
227 if ($memberfile =~ m|^.*/|) {
231 my $backupdir = "${memberdir}member-file-migration";
233 if (! -d $backupdir && !mkdir $backupdir, 0700) {
234 $form->error(sprintf($locale->text('The directory "%s" could not be created:\n%s'), $backupdir, $!));
237 copy $memberfile, "users/member-file-migration/members";
239 my $in = IO::File->new($memberfile, "r");
241 $form->error($locale->text('Could not open the old memberfile.')) if (!$in);
243 my (%members, $login);
252 $login =~ s/(\[|\])//g;
256 $members{$login} = { "login" => $login };
260 if ($login && m/=/) {
261 my ($key, $value) = split m/\s*=\s*/, $_, 2;
266 $value =~ s|\\n|\n|g;
268 $members{$login}->{$key} = $value;
274 delete $members{"root login"};
276 map { $_->{dbpasswd} = unpack 'u', $_->{dbpasswd} } values %members;
278 while (my ($login, $params) = each %members) {
279 $main::auth->save_user($login, %{ $params });
280 $main::auth->change_password($login, $params->{password}, 1);
282 my $conf_file = "${memberdir}${login}.conf";
285 copy $conf_file, "${backupdir}/${login}.conf";
292 my @member_list = sort { lc $a->{login} cmp lc $b->{login} } values %members;
294 $form->{title} = $locale->text('User data migration');
296 print $form->parse_html_template('admin/user_migration_done', { 'MEMBERS' => \@member_list });
298 $main::lxdebug->leave_sub();
301 sub create_standard_group_ask {
302 my $form = $main::form;
303 my $locale = $main::locale;
305 $form->{title} = $locale->text('Create a standard group');
308 print $form->parse_html_template("admin/create_standard_group_ask");
311 sub create_standard_group {
312 my $form = $main::form;
313 my $locale = $main::locale;
315 my %members = $main::auth->read_all_users();
317 my $groups = $main::auth->read_groups();
319 foreach my $group (values %{$groups}) {
320 if (($form->{group_id} != $group->{id})
321 && ($form->{name} eq $group->{name})) {
322 $form->show_generic_error($locale->text("A group with that name does already exist."));
327 'name' => $locale->text('Full Access'),
328 'description' => $locale->text('Full access to all functions'),
329 'rights' => { map { $_ => 1 } SL::Auth::all_rights() },
330 'members' => [ map { $_->{id} } values %members ],
333 $main::auth->save_group($group);
335 user_migration_complete(1);
338 sub dont_create_standard_group {
339 user_migration_complete(0);
342 sub user_migration_complete {
343 my $standard_group_created = shift;
345 my $form = $main::form;
346 my $locale = $main::locale;
348 $form->{title} = $locale->text('User migration complete');
351 print $form->parse_html_template('admin/user_migration_complete', { 'standard_group_created' => $standard_group_created });
355 my $form = $main::form;
356 my $locale = $main::locale;
358 my %members = $main::auth->read_all_users();
360 delete $members{"root login"};
362 for (values %members) {
363 $_->{templates} =~ s|.*/||;
364 $_->{login_url} = $::locale->is_utf8 ? Encode::encode('utf-8-strict', $_->{login}) : $_->{login_url};
367 $form->{title} = "kivitendo " . $locale->text('Administration');
368 $form->{LOCKED} = -e _nologin_file_name();
369 $form->{MEMBERS} = [ @members{sort { lc $a cmp lc $b } keys %members} ];
372 print $form->parse_html_template("admin/list_users");
376 $::form->{title} = "kivitendo " . $::locale->text('Administration') . " / " . $::locale->text('Add User');
378 # Note: Menu Style 'v3' is not compatible to all browsers!
379 # "menustyle" => "old" sets the HTML Menu to default.
380 # User does not have a well behaved new constructor, so we#Ll just have to build one ourself
383 "countrycode" => "de",
384 "numberformat" => "1.000,00",
385 "dateformat" => "dd.mm.yy",
386 "stylesheet" => "lx-office-erp.css",
387 "menustyle" => "old",
388 dbport => $::auth->{DB_config}->{port} || 5432,
389 dbuser => $::auth->{DB_config}->{user} || 'lxoffice',
390 dbhost => $::auth->{DB_config}->{host} || 'localhost',
393 edit_user_form($user);
397 $::form->{title} = "kivitendo " . $::locale->text('Administration') . " / " . $::locale->text('Edit User');
401 my $user = User->new(id => $::form->{user}{id});
403 # strip basedir from templates directory
404 $user->{templates} =~ s|.*/||;
406 edit_user_form($user);
412 my %cc = $user->country_codes;
413 my @all_countrycodes = map { id => $_, title => $cc{$_} }, sort { $cc{$a} cmp $cc{$b} } keys %cc;
414 my ($all_dir, $all_master) = _search_templates();
417 if ($::form->{edit}) {
418 my $user_id = $::auth->get_user_id($user->{login});
419 my $all_groups = $::auth->read_groups();
421 for my $group (values %{ $all_groups }) {
422 push @{ $groups }, $group if (grep { $user_id == $_ } @{ $group->{members} });
425 $groups = [ sort { lc $a->{name} cmp lc $b->{name} } @{ $groups } ];
429 print $::form->parse_html_template("admin/edit_user", {
431 CAN_CHANGE_PASSWORD => $::auth->can_change_password,
433 all_stylesheets => \@all_stylesheets,
434 all_numberformats => \@valid_numberformats,
435 all_dateformats => \@valid_dateformats,
436 all_countrycodes => \@all_countrycodes,
437 all_menustyles => \@all_menustyles,
438 all_templates => $all_dir,
439 all_master_templates => $all_master,
444 my $form = $main::form;
445 my $locale = $main::locale;
447 my $user = $form->{user};
449 $user->{dbdriver} = 'Pg';
451 if (!$::form->{edit}) {
452 # no spaces allowed in login name
453 $user->{login} =~ s/\s//g;
454 $::form->show_generic_error($::locale->text('Login name missing!')) unless $user->{login};
456 # check for duplicates
457 my %members = $::auth->read_all_users;
458 if ($members{$user->{login}}) {
459 $::form->show_generic_error($locale->text('Another user with the login #1 does already exist.', $user->{login}), 'back_button' => 1);
463 # no spaces allowed in directories
464 ($::form->{newtemplates}) = split / /, $::form->{newtemplates};
465 $user->{templates} = $::form->{newtemplates} || $::form->{usetemplates} || $user->{login};
468 if (!-d $::lx_office_conf{paths}->{templates}) {
469 $::form->error(sprintf($::locale->text("The directory %s does not exist."), $::lx_office_conf{paths}->{templates}));
472 # add base directory to $form->{templates}
473 $user->{templates} =~ s|.*/||;
474 $user->{templates} = $::lx_office_conf{paths}->{templates} . "/$user->{templates}";
476 my $myconfig = new User(id => $user->{id});
478 $::form->show_generic_error($::locale->text('Dataset missing!')) unless $user->{dbname};
479 $::form->show_generic_error($::locale->text('Database User missing!')) unless $user->{dbuser};
481 foreach my $item (keys %{$user}) {
482 $myconfig->{$item} = $user->{$item};
485 $myconfig->save_member;
487 $user->{templates} =~ s|.*/||;
488 $user->{templates} = $::lx_office_conf{paths}->{templates} . "/$user->{templates}";
489 $::form->{mastertemplates} =~ s|.*/||;
491 # create user template directory and copy master files
492 if (!-d "$user->{templates}") {
495 if (mkdir "$user->{templates}", oct("771")) {
499 # copy templates to the directory
501 my $oldcurrdir = getcwd();
502 if (!chdir("$::lx_office_conf{paths}->{templates}/print/$::form->{mastertemplates}")) {
503 $form->error("$ERRNO: chdir $::lx_office_conf{paths}->{templates}/print/$::form->{mastertemplates}");
506 my $newdir = File::Spec->catdir($oldcurrdir, $user->{templates});
514 if (!mkdir (File::Spec->catdir($newdir, $File::Find::name))) {
516 $form->error("$ERRNO: mkdir $File::Find::name");
519 if (!symlink (readlink($_),
520 File::Spec->catfile($newdir, $File::Find::name))) {
522 $form->error("$ERRNO: symlink $File::Find::name");
525 if (!copy($_, File::Spec->catfile($newdir, $File::Find::name))) {
527 $form->error("$ERRNO: cp $File::Find::name");
535 $form->error("$ERRNO: $user->{templates}");
539 # Add new user to his groups.
540 if (ref $form->{new_user_group_ids} eq 'ARRAY') {
541 my $all_groups = $main::auth->read_groups();
542 my %user = $main::auth->read_user(login => $myconfig->{login});
544 foreach my $group_id (@{ $form->{new_user_group_ids} }) {
545 my $group = $all_groups->{$group_id};
549 push @{ $group->{members} }, $user{id};
550 $main::auth->save_group($group);
554 if ($main::auth->can_change_password()
555 && defined $::form->{new_password}
556 && ($::form->{new_password} ne '********')) {
557 my $verifier = SL::Auth::PasswordPolicy->new;
558 my $result = $verifier->verify($::form->{new_password}, 1);
560 if ($result != SL::Auth::PasswordPolicy->OK()) {
561 $form->error($::locale->text('The settings were saved, but the password was not changed.') . ' ' . join(' ', $verifier->errors($result)));
564 $main::auth->change_password($myconfig->{login}, $::form->{new_password});
567 $::form->redirect($::locale->text('User saved!'));
570 sub save_user_as_new {
571 my $form = $main::form;
573 $form->{user}{login} = $::form->{new_user_login};
574 delete $form->{user}{id};
575 delete @{$form}{qw(id edit new_user_login)};
581 my $form = $main::form;
582 my $locale = $main::locale;
584 my $user = $::form->{user} || {};
586 $::form->show_generic_error($::locale->text('Missing user id!')) unless $user->{id};
588 my $loaded_user = User->new(id => $user->{id});
590 my %members = $main::auth->read_all_users();
591 my $templates = $members{$loaded_user->{login}}->{templates};
593 $main::auth->delete_user($loaded_user->{login});
596 my $templates_in_use = 0;
598 foreach my $login (keys %members) {
599 next if $loaded_user->{login} eq $login;
600 next if $members{$login}->{templates} ne $templates;
601 $templates_in_use = 1;
605 if (!$templates_in_use && -d $templates) {
606 unlink <$templates/*>;
611 $form->redirect($locale->text('User deleted!'));
619 return ($login) ? $login : undef;
625 my ($null, $value) = split(/=/, $line, 2);
628 $value =~ s/\s#.*//g;
630 # remove any trailing whitespace
631 $value =~ s/^\s*(.*?)\s*$/$1/;
636 sub pg_database_administration {
637 my $form = $main::form;
639 $form->{dbdriver} = 'Pg';
644 sub dbselect_source {
645 my $form = $main::form;
646 my $locale = $main::locale;
648 $form->{dbport} = $::auth->{DB_config}->{port} || 5432;
649 $form->{dbuser} = $::auth->{DB_config}->{user} || 'lxoffice';
650 $form->{dbdefault} = 'template1';
651 $form->{dbhost} = $::auth->{DB_config}->{host} || 'localhost';
653 $form->{title} = "kivitendo / " . $locale->text('Database Administration');
655 # Intentionnaly disabled unless fixed to work with the authentication DB.
656 $form->{ALLOW_DBBACKUP} = 0; # "$pg_dump_exe" ne "DISABLED";
659 print $form->parse_html_template("admin/dbadmin");
662 sub test_db_connection {
663 my $form = $main::form;
664 my $locale = $main::locale;
666 $form->{dbdriver} = 'Pg';
667 User::dbconnect_vars($form, $form->{dbname});
669 my $dbh = DBI->connect($form->{dbconnect}, $form->{dbuser}, $form->{dbpasswd});
671 $form->{connection_ok} = $dbh ? 1 : 0;
672 $form->{errstr} = $DBI::errstr;
674 $dbh->disconnect() if ($dbh);
676 $form->{title} = $locale->text('Database Connection Test');
678 print $form->parse_html_template("admin/test_db_connection");
682 call_sub($main::form->{"nextsub"});
686 my $form = $main::form;
687 my $locale = $main::locale;
689 $form->{title} = "kivitendo " . $locale->text('Database Administration') . " / " . $locale->text('Update Dataset');
691 my @need_updates = User->dbneedsupdate($form);
692 $form->{NEED_UPDATES} = \@need_updates;
693 $form->{ALL_UPDATED} = !scalar @need_updates;
696 print $form->parse_html_template("admin/update_dataset");
700 my $form = $main::form;
701 my $locale = $main::locale;
703 $form->{stylesheet} = "lx-office-erp.css";
704 $form->{title} = $locale->text("Dataset upgrade");
707 my $rowcount = $form->{rowcount} * 1;
708 my @update_rows = grep { $form->{"update_$_"} } (1 .. $rowcount);
709 $form->{NOTHING_TO_DO} = !scalar @update_rows;
710 my $saved_form = save_form();
714 print $form->parse_html_template("admin/dbupgrade_all_header");
716 foreach my $i (@update_rows) {
717 restore_form($saved_form);
720 map { $form->{$_} = $::myconfig{$_} = $form->{"${_}_${i}"} } qw(dbname dbdriver dbhost dbport dbuser dbpasswd);
722 print $form->parse_html_template("admin/dbupgrade_header");
724 $form->{dbupdate} = $form->{dbname};
725 $form->{$form->{dbname}} = 1;
727 User->dbupdate($form);
728 User->dbupdate2($form, SL::DBUpgrade2->new(form => $form, dbdriver => $form->{dbdriver})->parse_dbupdate_controls);
730 print $form->parse_html_template("admin/dbupgrade_footer");
733 print $form->parse_html_template("admin/dbupgrade_all_done");
737 my $form = $main::form;
738 my $locale = $main::locale;
740 $form->{dbsources} = join " ", map { "[${_}]" } sort User->dbsources($form);
742 $form->{CHARTS} = [];
744 opendir SQLDIR, "sql/." or $form->error($ERRNO);
745 foreach my $item (sort grep /-chart\.sql\z/, readdir SQLDIR) {
746 next if ($item eq 'Default-chart.sql');
747 $item =~ s/-chart\.sql//;
748 push @{ $form->{CHARTS} }, { "name" => $item,
749 "selected" => $item eq "Germany-DATEV-SKR03EU" };
753 $form->{ACCOUNTING_METHODS} = [];
754 foreach my $item ( qw(accrual cash) ) {
755 push @{ $form->{ACCOUNTING_METHODS} }, { "name" => $item,
756 "selected" => $item eq "cash" };
759 $form->{INVENTORY_SYSTEMS} = [];
760 foreach my $item ( qw(perpetual periodic) ) {
761 push @{ $form->{INVENTORY_SYSTEMS} }, { "name" => $item,
762 "selected" => $item eq "periodic" };
765 $form->{PROFIT_DETERMINATIONS} = [];
766 foreach my $item ( qw(balance income) ) {
767 push @{ $form->{PROFIT_DETERMINATIONS} }, { "name" => $item,
768 "selected" => $item eq "income" };
771 my $default_charset = $::lx_office_conf{system}->{dbcharset};
772 $default_charset ||= Common::DEFAULT_CHARSET;
774 my $cluster_encoding = User->dbclusterencoding($form);
775 if ($cluster_encoding && ($cluster_encoding =~ m/^(?:UTF-?8|UNICODE)$/i)) {
776 if ($::lx_office_conf{system}->{dbcharset} !~ m/^UTF-?8$/i) {
777 $form->show_generic_error($locale->text('The selected PostgreSQL installation uses UTF-8 as its encoding. ' .
778 'Therefore you have to configure Lx-Office to use UTF-8 as well.'),
782 $form->{FORCE_DBENCODING} = 'UNICODE';
785 $form->{DBENCODINGS} = [];
787 foreach my $encoding (@Common::db_encodings) {
788 push @{ $form->{DBENCODINGS} }, { "dbencoding" => $encoding->{dbencoding},
789 "label" => $encoding->{label},
790 "selected" => $encoding->{charset} eq $default_charset };
794 $form->{title} = "kivitendo " . $locale->text('Database Administration') . " / " . $locale->text('Create Dataset');
797 print $form->parse_html_template("admin/create_dataset");
801 my $form = $main::form;
802 my $locale = $main::locale;
804 $form->isblank("db", $locale->text('Dataset missing!'));
806 User->dbcreate(\%$form);
808 $form->{title} = "kivitendo " . $locale->text('Database Administration') . " / " . $locale->text('Create Dataset');
811 print $form->parse_html_template("admin/dbcreate");
815 my $form = $main::form;
816 my $locale = $main::locale;
818 my @dbsources = User->dbsources_unused($form);
819 $form->error($locale->text('Nothing to delete!')) unless @dbsources;
821 $form->{title} = "kivitendo " . $locale->text('Database Administration') . " / " . $locale->text('Delete Dataset');
822 $form->{DBSOURCES} = [ map { { "name", $_ } } sort @dbsources ];
825 print $form->parse_html_template("admin/delete_dataset");
829 my $form = $main::form;
830 my $locale = $main::locale;
833 $form->error($locale->text('No Dataset selected!'));
836 User->dbdelete(\%$form);
838 $form->{title} = "kivitendo " . $locale->text('Database Administration') . " / " . $locale->text('Delete Dataset');
840 print $form->parse_html_template("admin/dbdelete");
844 my $form = $main::form;
845 my $locale = $main::locale;
847 $form->{title} = "kivitendo " . $locale->text('Database Administration') . " / " . $locale->text('Backup Dataset');
849 if ($::lx_office_conf{applications}->{pg_dump} eq "DISABLED") {
850 $form->error($locale->text('Database backups and restorations are disabled in the configuration.'));
853 my @dbsources = sort User->dbsources($form);
854 $form->{DATABASES} = [ map { { "dbname" => $_ } } @dbsources ];
855 $form->{NO_DATABASES} = !scalar @dbsources;
857 my $username = getpwuid $UID || "unknown-user";
858 my $hostname = hostname() || "unknown-host";
859 $form->{from} = "kivitendo Admin <${username}\@${hostname}>";
862 print $form->parse_html_template("admin/backup_dataset");
865 sub backup_dataset_start {
866 my $form = $main::form;
867 my $locale = $main::locale;
869 $form->{title} = "kivitendo " . $locale->text('Database Administration') . " / " . $locale->text('Backup Dataset');
871 my $pg_dump_exe = $::lx_office_conf{applications}->{pg_dump} || "pg_dump";
873 if ("$pg_dump_exe" eq "DISABLED") {
874 $form->error($locale->text('Database backups and restorations are disabled in the configuration.'));
877 $form->isblank("dbname", $locale->text('The dataset name is missing.'));
878 $form->isblank("to", $locale->text('The email address is missing.')) if $form->{destination} eq "email";
880 my $tmpdir = "/tmp/lx_office_backup_" . Common->unique_id();
881 mkdir $tmpdir, 0700 || $form->error($locale->text('A temporary directory could not be created:') . " $ERRNO");
883 my $pgpass = IO::File->new("${tmpdir}/.pgpass", O_WRONLY | O_CREAT, 0600);
887 $form->error($locale->text('A temporary file could not be created:') . " $ERRNO");
890 print $pgpass "$form->{dbhost}:$form->{dbport}:$form->{dbname}:$form->{dbuser}:$form->{dbpasswd}\n";
893 $ENV{HOME} = $tmpdir;
895 my @args = ("-Ft", "-c", "-o", "-h", $form->{dbhost}, "-U", $form->{dbuser});
896 push @args, ("-p", $form->{dbport}) if ($form->{dbport});
897 push @args, $form->{dbname};
899 my $cmd = "$pg_dump_exe " . join(" ", map { s/\\/\\\\/g; s/\"/\\\"/g; $_ } @args);
900 my $name = "dataset_backup_$form->{dbname}_" . strftime("%Y%m%d", localtime()) . ".tar";
902 if ($form->{destination} ne "email") {
903 my $in = IO::File->new("$cmd |");
906 unlink "${tmpdir}/.pgpass";
909 $form->error($locale->text('The pg_dump process could not be started.'));
912 print "content-type: application/x-tar\n";
913 print "content-disposition: attachment; filename=\"${name}\"\n\n";
915 while (my $line = <$in>) {
921 unlink "${tmpdir}/.pgpass";
925 my $tmp = $tmpdir . "/dump_" . Common::unique_id();
927 if (system("$cmd > $tmp") != 0) {
928 unlink "${tmpdir}/.pgpass", $tmp;
931 $form->error($locale->text('The pg_dump process could not be started.'));
934 my $mail = new Mailer;
936 map { $mail->{$_} = $form->{$_} } qw(from to cc subject message);
938 $mail->{charset} = $::lx_office_conf{system}->{dbcharset} || Common::DEFAULT_CHARSET;
939 $mail->{attachments} = [ { "filename" => $tmp, "name" => $name } ];
942 unlink "${tmpdir}/.pgpass", $tmp;
945 $form->{title} = "kivitendo " . $locale->text('Database Administration') . " / " . $locale->text('Backup Dataset');
948 print $form->parse_html_template("admin/backup_dataset_email_done");
952 sub restore_dataset {
953 my $form = $main::form;
954 my $locale = $main::locale;
956 $form->{title} = "kivitendo " . $locale->text('Database Administration') . " / " . $locale->text('Restore Dataset');
958 if ($::lx_office_conf{applications}->{pg_restore} eq "DISABLED") {
959 $form->error($locale->text('Database backups and restorations are disabled in the configuration.'));
962 my $default_charset = $::lx_office_conf{system}->{dbcharset};
963 $default_charset ||= Common::DEFAULT_CHARSET;
965 $form->{DBENCODINGS} = [];
967 foreach my $encoding (@Common::db_encodings) {
968 push @{ $form->{DBENCODINGS} }, { "dbencoding" => $encoding->{dbencoding},
969 "label" => $encoding->{label},
970 "selected" => $encoding->{charset} eq $default_charset };
974 print $form->parse_html_template("admin/restore_dataset");
977 sub restore_dataset_start {
978 my $form = $main::form;
979 my $locale = $main::locale;
981 $form->{title} = "kivitendo " . $locale->text('Database Administration') . " / " . $locale->text('Restore Dataset');
983 my $pg_restore_exe = $::lx_office_conf{applications}->{pg_restore} || "pg_restore";
985 if ("$pg_restore_exe" eq "DISABLED") {
986 $form->error($locale->text('Database backups and restorations are disabled in the configuration.'));
989 $form->isblank("new_dbname", $locale->text('The dataset name is missing.'));
990 $form->isblank("content", $locale->text('No backup file has been uploaded.'));
992 # Create temporary directories. Write the backup file contents to a temporary
993 # file. Create a .pgpass file with the username and password for the pg_restore
996 my $tmpdir = "/tmp/lx_office_backup_" . Common->unique_id();
997 mkdir $tmpdir, 0700 || $form->error($locale->text('A temporary directory could not be created:') . " $ERRNO");
999 my $pgpass = IO::File->new("${tmpdir}/.pgpass", O_WRONLY | O_CREAT, 0600);
1003 $form->error($locale->text('A temporary file could not be created:') . " $ERRNO");
1006 print $pgpass "$form->{dbhost}:$form->{dbport}:$form->{new_dbname}:$form->{dbuser}:$form->{dbpasswd}\n";
1009 $ENV{HOME} = $tmpdir;
1011 my $tmp = $tmpdir . "/dump_" . Common::unique_id();
1014 if (substr($form->{content}, 0, 2) eq "\037\213") {
1015 $tmpfile = IO::File->new("| gzip -d > $tmp");
1019 $tmpfile = IO::File->new($tmp, O_WRONLY | O_CREAT | O_BINARY, 0600);
1023 unlink "${tmpdir}/.pgpass";
1026 $form->error($locale->text('A temporary file could not be created:') . " $ERRNO");
1029 print $tmpfile $form->{content};
1032 delete $form->{content};
1034 # Try to connect to the database. Find out if a database with the same name exists.
1035 # If yes, then drop the existing database. Create a new one with the name and encoding
1036 # given by the user.
1038 User::dbconnect_vars($form, "template1");
1040 my %myconfig = map { $_ => $form->{$_} } grep /^db/, keys %{ $form };
1041 my $dbh = $form->dbconnect(\%myconfig) || $form->dberror();
1045 $form->{new_dbname} =~ s|[^a-zA-Z0-9_\-]||g;
1047 $query = qq|SELECT COUNT(*) FROM pg_database WHERE datname = ?|;
1048 my ($count) = selectrow_query($form, $dbh, $query, $form->{new_dbname});
1050 do_query($form, $dbh, qq|DROP DATABASE $form->{new_dbname}|);
1054 foreach my $item (@Common::db_encodings) {
1055 if ($item->{dbencoding} eq $form->{dbencoding}) {
1060 $form->{dbencoding} = "LATIN9" unless $form->{dbencoding};
1062 do_query($form, $dbh, qq|CREATE DATABASE $form->{new_dbname} ENCODING ? TEMPLATE template0|, $form->{dbencoding});
1066 # Spawn pg_restore on the temporary file.
1068 my @args = ("-h", $form->{dbhost}, "-U", $form->{dbuser}, "-d", $form->{new_dbname});
1069 push @args, ("-p", $form->{dbport}) if ($form->{dbport});
1072 my $cmd = "$pg_restore_exe " . join(" ", map { s/\\/\\\\/g; s/\"/\\\"/g; $_ } @args);
1074 my $in = IO::File->new("$cmd 2>&1 |");
1077 unlink "${tmpdir}/.pgpass", $tmp;
1080 $form->error($locale->text('The pg_restore process could not be started.'));
1083 $English::AUTOFLUSH = 1;
1086 print $form->parse_html_template("admin/restore_dataset_start_header");
1088 while (my $line = <$in>) {
1093 $form->{retval} = $CHILD_ERROR >> 8;
1094 print $form->parse_html_template("admin/restore_dataset_start_footer");
1096 unlink "${tmpdir}/.pgpass", $tmp;
1101 my $form = $main::form;
1102 my $locale = $main::locale;
1104 unlink _nologin_file_name();;
1106 $form->{callback} = "admin.pl?action=list_users";
1108 $form->redirect($locale->text('Lockfile removed!'));
1113 my $form = $main::form;
1114 my $locale = $main::locale;
1116 open(FH, ">", _nologin_file_name())
1117 or $form->error($locale->text('Cannot create Lock!'));
1120 $form->{callback} = "admin.pl?action=list_users";
1122 $form->redirect($locale->text('Lockfile created!'));
1127 call_sub($main::form->{yes_nextsub});
1131 call_sub($main::form->{no_nextsub});
1135 call_sub($main::form->{add_nextsub});
1139 my $form = $main::form;
1141 $form->{edit_nextsub} ||= 'edit_user';
1143 call_sub($form->{edit_nextsub});
1147 my $form = $main::form;
1149 $form->{delete_nextsub} ||= 'delete_user';
1151 call_sub($form->{delete_nextsub});
1155 my $form = $main::form;
1157 $form->{save_nextsub} ||= 'save_user';
1159 call_sub($form->{save_nextsub});
1163 call_sub($main::form->{back_nextsub});
1167 my $form = $main::form;
1168 my $locale = $main::locale;
1170 foreach my $action (qw(create_standard_group dont_create_standard_group
1171 save_user delete_user save_user_as_new)) {
1172 if ($form->{"action_${action}"}) {
1178 call_sub($form->{default_action}) if ($form->{default_action});
1180 $form->error($locale->text('No action defined.'));
1183 sub _apply_dbupgrade_scripts {
1184 ::end_of_request() if SL::DBUpgrade2->new(form => $::form, dbdriver => 'Pg', auth => 1)->apply_admin_dbupgrade_scripts(1);
1187 sub _nologin_file_name {
1188 return $::lx_office_conf{paths}->{userspath} . '/nologin';
1191 sub _search_templates {
1192 # is there a templates basedir
1193 if (!-d $::lx_office_conf{paths}->{templates}) {
1194 $::form->error(sprintf($::locale->text("The directory %s does not exist."), $::lx_office_conf{paths}->{templates}));
1197 opendir TEMPLATEDIR, $::lx_office_conf{paths}->{templates} or $::form->error($::lx_office_conf{paths}->{templates} . " : $ERRNO");
1198 my @all = readdir(TEMPLATEDIR);
1199 my @alldir = sort grep { -d ($::lx_office_conf{paths}->{templates} . "/$_") && !/^\.\.?$/ } @all;
1200 closedir TEMPLATEDIR;
1202 @alldir = grep !/\.(html|tex|sty|odt|xml|txb)$/, @alldir;
1203 @alldir = grep !/^(webpages|print|\.svn)$/, @alldir;
1206 opendir TEMPLATEDIR, "$::lx_office_conf{paths}->{templates}/print" or $::form->error("$::lx_office_conf{paths}->{templates}/print" . " : $ERRNO");
1207 my @allmaster = readdir(TEMPLATEDIR);
1208 closedir TEMPLATEDIR;
1210 @allmaster = sort grep { -d ("$::lx_office_conf{paths}->{templates}/print" . "/$_") && !/^\.\.?$/ } @allmaster;
1211 @allmaster = reverse grep !/Default/, @allmaster;
1212 push @allmaster, 'Default';
1213 @allmaster = reverse @allmaster;
1215 return \@alldir, \@allmaster;