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 #======================================================================
38 use English qw(-no_match_vars);
42 use POSIX qw(strftime);
46 use SL::Auth::PasswordPolicy;
56 require "bin/mozilla/common.pl";
57 require "bin/mozilla/admin_groups.pl";
58 require "bin/mozilla/admin_printer.pl";
68 $::lxdebug->enter_sub;
69 my $session_result = shift;
76 $::auth->set_session_value('rpw', $::form->{rpw}) if $session_result == SL::Auth->SESSION_OK;
78 $form->{stylesheet} = "lx-office-erp.css";
79 $form->{favicon} = "favicon.ico";
81 if ($form->{action}) {
82 if ($auth->authenticate_root($form->{rpw}) != $auth->OK()) {
83 $form->{error_message} = $locale->text('Incorrect Password!');
86 if ($auth->session_tables_present()) {
87 $::auth->set_session_value('rpw', $::form->{rpw});
88 $::auth->create_or_refresh_session();
89 _apply_dbupgrade_scripts();
92 call_sub($locale->findsub($form->{action}));
95 # if there are no drivers bail out
96 $form->error($locale->text('No Database Drivers available!'))
97 unless (User->dbdrivers);
101 $::lxdebug->leave_sub;
105 my $form = $main::form;
106 my $locale = $main::locale;
108 $form->{title} = qq|Lx-Office ERP $form->{version} | . $locale->text('Administration');
111 print $form->parse_html_template('admin/adminlogin');
115 check_auth_db_and_tables();
120 $main::auth->destroy_session();
124 sub check_auth_db_and_tables {
125 my $form = $main::form;
126 my $locale = $main::locale;
130 map { $params{"db_${_}"} = $main::auth->{DB_config}->{$_} } keys %{ $auth->{DB_config} };
132 if (!$main::auth->check_database()) {
133 $form->{title} = $locale->text('Authentification database creation');
135 print $form->parse_html_template('admin/check_auth_database', \%params);
140 if (!$main::auth->check_tables()) {
141 $form->{title} = $locale->text('Authentification tables creation');
143 print $form->parse_html_template('admin/check_auth_tables', \%params);
148 my $memberfile = $::lx_office_conf{paths}->{memberfile};
149 if (-f $memberfile) {
152 if ($memberfile =~ m|^.*/|) {
156 my $backupdir = "${memberdir}member-file-migration";
158 $form->{title} = $locale->text('User data migration');
160 print $form->parse_html_template('admin/user_migration', { 'memberfile' => $memberfile,
161 'backupdir' => $backupdir });
168 my $form = $main::form;
170 $main::auth->create_database('superuser' => $form->{db_superuser},
171 'superuser_password' => $form->{db_superuser_password},
172 'template' => $form->{db_template});
176 sub create_auth_tables {
177 my $form = $main::form;
178 my $locale = $main::locale;
180 $main::auth->create_tables();
181 $main::auth->set_session_value('rpw', $form->{rpw});
182 $main::auth->create_or_refresh_session();
184 my $memberfile = $::lx_office_conf{paths}->{memberfile};
185 if (!-f $memberfile) {
186 # New installation -- create a standard group with full access
189 'name' => $locale->text('Full Access'),
190 'description' => $locale->text('Full access to all functions'),
191 'rights' => { map { $_ => 1 } SL::Auth::all_rights() },
192 'members' => [ map { $_->{id} } values %members ],
195 $main::auth->save_group($group);
198 _apply_dbupgrade_scripts();
203 $main::lxdebug->enter_sub();
205 my $form = $main::form;
206 my $locale = $main::locale;
210 my $memberfile = $::lx_office_conf{paths}->{memberfile};
211 if ($memberfile =~ m|^.*/|) {
215 my $backupdir = "${memberdir}member-file-migration";
217 if (! -d $backupdir && !mkdir $backupdir, 0700) {
218 $form->error(sprintf($locale->text('The directory "%s" could not be created:\n%s'), $backupdir, $!));
221 copy $memberfile, "users/member-file-migration/members";
223 my $in = IO::File->new($memberfile, "r");
225 $form->error($locale->text('Could not open the old memberfile.')) if (!$in);
227 my (%members, $login);
236 $login =~ s/(\[|\])//g;
240 $members{$login} = { "login" => $login };
244 if ($login && m/=/) {
245 my ($key, $value) = split m/\s*=\s*/, $_, 2;
250 $value =~ s|\\n|\n|g;
252 $members{$login}->{$key} = $value;
258 delete $members{"root login"};
260 map { $_->{dbpasswd} = unpack 'u', $_->{dbpasswd} } values %members;
262 while (my ($login, $params) = each %members) {
263 $main::auth->save_user($login, %{ $params });
264 $main::auth->change_password($login, $params->{password}, 1);
266 my $conf_file = "${memberdir}${login}.conf";
269 copy $conf_file, "${backupdir}/${login}.conf";
276 my @member_list = sort { lc $a->{login} cmp lc $b->{login} } values %members;
278 $form->{title} = $locale->text('User data migration');
280 print $form->parse_html_template('admin/user_migration_done', { 'MEMBERS' => \@member_list });
282 $main::lxdebug->leave_sub();
285 sub create_standard_group_ask {
286 my $form = $main::form;
287 my $locale = $main::locale;
289 $form->{title} = $locale->text('Create a standard group');
292 print $form->parse_html_template("admin/create_standard_group_ask");
295 sub create_standard_group {
296 my $form = $main::form;
297 my $locale = $main::locale;
299 my %members = $main::auth->read_all_users();
301 my $groups = $main::auth->read_groups();
303 foreach my $group (values %{$groups}) {
304 if (($form->{group_id} != $group->{id})
305 && ($form->{name} eq $group->{name})) {
306 $form->show_generic_error($locale->text("A group with that name does already exist."));
311 'name' => $locale->text('Full Access'),
312 'description' => $locale->text('Full access to all functions'),
313 'rights' => { map { $_ => 1 } SL::Auth::all_rights() },
314 'members' => [ map { $_->{id} } values %members ],
317 $main::auth->save_group($group);
319 user_migration_complete(1);
322 sub dont_create_standard_group {
323 user_migration_complete(0);
326 sub user_migration_complete {
327 my $standard_group_created = shift;
329 my $form = $main::form;
330 my $locale = $main::locale;
332 $form->{title} = $locale->text('User migration complete');
335 print $form->parse_html_template('admin/user_migration_complete', { 'standard_group_created' => $standard_group_created });
339 my $form = $main::form;
340 my $locale = $main::locale;
342 my %members = $main::auth->read_all_users();
344 delete $members{"root login"};
346 for (values %members) {
347 $_->{templates} =~ s|.*/||;
348 $_->{login_url} = $::locale->is_utf8 ? Encode::encode('utf-8-strict', $_->{login}) : $_->{login_url};
351 $form->{title} = "Lx-Office ERP " . $locale->text('Administration');
352 $form->{LOCKED} = -e _nologin_file_name();
353 $form->{MEMBERS} = [ @members{sort { lc $a cmp lc $b } keys %members} ];
356 print $form->parse_html_template("admin/list_users");
360 my $form = $main::form;
361 my $locale = $main::locale;
363 $form->{title} = "Lx-Office ERP " . $locale->text('Administration') . " / " . $locale->text('Add User');
365 # Note: Menu Style 'v3' is not compatible to all browsers!
366 # "menustyle" => "old" sets the HTML Menu to default.
369 "countrycode" => "de",
370 "numberformat" => "1.000,00",
371 "dateformat" => "dd.mm.yy",
372 "stylesheet" => "lx-office-erp.css",
373 "menustyle" => "old",
374 dbport => $::auth->{DB_config}->{port} || 5432,
375 dbuser => $::auth->{DB_config}->{user} || 'lxoffice',
376 dbhost => $::auth->{DB_config}->{host} || 'localhost',
380 edit_user_form($myconfig);
384 my $form = $main::form;
385 my $locale = $main::locale;
387 $form->{title} = "Lx-Office ERP " . $locale->text('Administration') . " / " . $locale->text('Edit User');
390 $form->isblank("login", $locale->text("The login is missing."));
393 my $myconfig = new User($form->{login});
395 # strip basedir from templates directory
396 $myconfig->{templates} =~ s|.*/||;
398 edit_user_form($myconfig);
404 my $form = $main::form;
405 my $locale = $main::locale;
407 my @valid_dateformats = qw(mm-dd-yy mm/dd/yy dd-mm-yy dd/mm/yy dd.mm.yy yyyy-mm-dd);
408 $form->{ALL_DATEFORMATS} = [ map { { "format" => $_, "selected" => $_ eq $myconfig->{dateformat} } } @valid_dateformats ];
410 my @valid_numberformats = ('1,000.00', '1000.00', '1.000,00', '1000,00');
411 $form->{ALL_NUMBERFORMATS} = [ map { { "format" => $_, "selected" => $_ eq $myconfig->{numberformat} } } @valid_numberformats ];
413 my %countrycodes = User->country_codes;
414 $form->{ALL_COUNTRYCODES} = [];
415 foreach my $countrycode (sort { $countrycodes{$a} cmp $countrycodes{$b} } keys %countrycodes) {
416 push @{ $form->{ALL_COUNTRYCODES} }, { "value" => $countrycode,
417 "name" => $countrycodes{$countrycode},
418 "selected" => $countrycode eq $myconfig->{countrycode} };
421 # is there a templates basedir
422 if (!-d $::lx_office_conf{paths}->{templates}) {
423 $form->error(sprintf($locale->text("The directory %s does not exist."), $::lx_office_conf{paths}->{templates}));
426 opendir TEMPLATEDIR, $::lx_office_conf{paths}->{templates} or $form->error($::lx_office_conf{paths}->{templates} . " : $ERRNO");
427 my @all = readdir(TEMPLATEDIR);
428 my @alldir = sort grep { -d ($::lx_office_conf{paths}->{templates} . "/$_") && !/^\.\.?$/ } @all;
429 my @allhtml = sort grep { -f ($::lx_office_conf{paths}->{templates} . "/$_") && /\.html$/ } @all;
430 closedir TEMPLATEDIR;
432 @alldir = grep !/\.(html|tex|sty|odt|xml|txb)$/, @alldir;
433 @alldir = grep !/^(webpages|\.svn)$/, @alldir;
435 @allhtml = reverse grep !/Default/, @allhtml;
436 push @allhtml, 'Default';
437 @allhtml = reverse @allhtml;
439 $form->{ALL_TEMPLATES} = [ map { { "name", => $_, "selected" => $_ eq $myconfig->{templates} } } @alldir ];
441 my $lastitem = $allhtml[0];
442 $lastitem =~ s/-.*//g;
443 $form->{ALL_MASTER_TEMPLATES} = [ { "name" => $lastitem, "selected" => $lastitem eq "German" } ];
444 foreach my $item (@allhtml) {
446 next if ($item eq $lastitem);
448 push @{ $form->{ALL_MASTER_TEMPLATES} }, { "name" => $item, "selected" => $item eq "German" };
452 # css dir has styles that are not intended as general layouts.
453 # reverting to hardcoded list
454 $form->{ALL_STYLESHEETS} = [ map { { "name" => $_, "selected" => $_ eq $myconfig->{stylesheet} } } qw(lx-office-erp.css Win2000.css) ];
456 $form->{"menustyle_" . $myconfig->{menustyle} } = 1;
458 map { $form->{"myc_${_}"} = $myconfig->{$_} } keys %{ $myconfig };
463 my $user_id = $main::auth->get_user_id($form->{login});
464 my $all_groups = $main::auth->read_groups();
466 foreach my $group (values %{ $all_groups }) {
467 push @{ $groups }, $group if (grep { $user_id == $_ } @{ $group->{members} });
470 $groups = [ sort { lc $a->{name} cmp lc $b->{name} } @{ $groups } ];
473 $form->{CAN_CHANGE_PASSWORD} = $main::auth->can_change_password();
476 print $form->parse_html_template("admin/edit_user", { 'GROUPS' => $groups });
480 my $form = $main::form;
481 my $locale = $main::locale;
483 $form->{dbdriver} = 'Pg';
485 # no spaces allowed in login name
486 $form->{login} =~ s|\s||g;
487 $form->isblank("login", $locale->text('Login name missing!'));
489 # check for duplicates
490 if (!$form->{edit}) {
491 my %members = $main::auth->read_all_users();
492 if ($members{$form->{login}}) {
493 $form->show_generic_error($locale->text('Another user with the login #1 does already exist.', $form->{login}), 'back_button' => 1);
497 # no spaces allowed in directories
498 ($form->{newtemplates}) = split / /, $form->{newtemplates};
500 if ($form->{newtemplates}) {
501 $form->{templates} = $form->{newtemplates};
504 ($form->{usetemplates}) ? $form->{usetemplates} : $form->{login};
508 if (!-d $::lx_office_conf{paths}->{templates}) {
509 $form->error(sprintf($locale->text("The directory %s does not exist."), $::lx_office_conf{paths}->{templates}));
512 # add base directory to $form->{templates}
513 $form->{templates} =~ s|.*/||;
514 $form->{templates} = $::lx_office_conf{paths}->{templates} . "/$form->{templates}";
516 my $myconfig = new User($form->{login});
518 $form->isblank("dbname", $locale->text('Dataset missing!'));
519 $form->isblank("dbuser", $locale->text('Database User missing!'));
521 foreach my $item (keys %{$form}) {
522 $myconfig->{$item} = $form->{$item};
525 delete $myconfig->{stylesheet};
526 if ($form->{userstylesheet}) {
527 $myconfig->{stylesheet} = $form->{userstylesheet};
530 $myconfig->save_member();
532 $form->{templates} =~ s|.*/||;
533 $form->{templates} = $::lx_office_conf{paths}->{templates} . "/$form->{templates}";
534 $form->{mastertemplates} =~ s|.*/||;
536 # create user template directory and copy master files
537 if (!-d "$form->{templates}") {
540 if (mkdir "$form->{templates}", oct("771")) {
544 # copy templates to the directory
545 opendir TEMPLATEDIR, $::lx_office_conf{paths}->{templates} or $form->error($::lx_office_conf{paths}->{templates} . " : $ERRNO");
546 my @templates = grep /$form->{mastertemplates}.*?\.(html|tex|sty|odt|xml|txb)$/,
548 closedir TEMPLATEDIR;
550 foreach my $file (@templates) {
551 open(TEMP, $::lx_office_conf{paths}->{templates} . "/$file")
552 or $form->error($::lx_office_conf{paths}->{templates} . "/$file : $ERRNO");
554 $file =~ s/\Q$form->{mastertemplates}\E-//;
555 open(NEW, ">$form->{templates}/$file")
556 or $form->error("$form->{templates}/$file : $ERRNO");
558 while (my $line = <TEMP>) {
565 $form->error("$ERRNO: $form->{templates}");
569 # Add new user to his groups.
570 if (ref $form->{new_user_group_ids} eq 'ARRAY') {
571 my $all_groups = $main::auth->read_groups();
572 my %user = $main::auth->read_user($form->{login});
574 foreach my $group_id (@{ $form->{new_user_group_ids} }) {
575 my $group = $all_groups->{$group_id};
579 push @{ $group->{members} }, $user{id};
580 $main::auth->save_group($group);
584 if ($main::auth->can_change_password()
585 && defined $form->{new_password}
586 && ($form->{new_password} ne '********')) {
587 my $verifier = SL::Auth::PasswordPolicy->new;
588 my $result = $verifier->verify($form->{new_password}, 1);
590 if ($result != SL::Auth::PasswordPolicy->OK()) {
591 $form->error($::locale->text('The settings were saved, but the password was not changed.') . ' ' . join(' ', $verifier->errors($result)));
594 $main::auth->change_password($form->{login}, $form->{new_password});
597 $form->redirect($locale->text('User saved!'));
600 sub save_user_as_new {
601 my $form = $main::form;
603 $form->{login} = $form->{new_user_login};
604 delete @{$form}{qw(edit new_user_login)};
610 my $form = $main::form;
611 my $locale = $main::locale;
613 my %members = $main::auth->read_all_users();
614 my $templates = $members{$form->{login}}->{templates};
616 $main::auth->delete_user($form->{login});
619 my $templates_in_use = 0;
621 foreach my $login (keys %members) {
622 next if $form->{login} eq $login;
623 next if $members{$login}->{templates} ne $templates;
624 $templates_in_use = 1;
628 if (!$templates_in_use && -d $templates) {
629 unlink <$templates/*>;
634 $form->redirect($locale->text('User deleted!'));
642 return ($login) ? $login : undef;
648 my ($null, $value) = split(/=/, $line, 2);
651 $value =~ s/\s#.*//g;
653 # remove any trailing whitespace
654 $value =~ s/^\s*(.*?)\s*$/$1/;
659 sub pg_database_administration {
660 my $form = $main::form;
662 $form->{dbdriver} = 'Pg';
667 sub dbselect_source {
668 my $form = $main::form;
669 my $locale = $main::locale;
671 $form->{dbport} = $::auth->{DB_config}->{port} || 5432;
672 $form->{dbuser} = $::auth->{DB_config}->{user} || 'lxoffice';
673 $form->{dbdefault} = 'template1';
674 $form->{dbhost} = $::auth->{DB_config}->{host} || 'localhost';
676 $form->{title} = "Lx-Office ERP / " . $locale->text('Database Administration');
678 # Intentionnaly disabled unless fixed to work with the authentication DB.
679 $form->{ALLOW_DBBACKUP} = 0; # "$pg_dump_exe" ne "DISABLED";
682 print $form->parse_html_template("admin/dbadmin");
685 sub test_db_connection {
686 my $form = $main::form;
687 my $locale = $main::locale;
689 $form->{dbdriver} = 'Pg';
690 User::dbconnect_vars($form, $form->{dbname});
692 my $dbh = DBI->connect($form->{dbconnect}, $form->{dbuser}, $form->{dbpasswd});
694 $form->{connection_ok} = $dbh ? 1 : 0;
695 $form->{errstr} = $DBI::errstr;
697 $dbh->disconnect() if ($dbh);
699 $form->{title} = $locale->text('Database Connection Test');
701 print $form->parse_html_template("admin/test_db_connection");
705 call_sub($main::form->{"nextsub"});
709 my $form = $main::form;
710 my $locale = $main::locale;
712 $form->{title} = "Lx-Office ERP " . $locale->text('Database Administration') . " / " . $locale->text('Update Dataset');
714 my @need_updates = User->dbneedsupdate($form);
715 $form->{NEED_UPDATES} = \@need_updates;
716 $form->{ALL_UPDATED} = !scalar @need_updates;
719 print $form->parse_html_template("admin/update_dataset");
723 my $form = $main::form;
724 my $locale = $main::locale;
726 $form->{stylesheet} = "lx-office-erp.css";
727 $form->{title} = $locale->text("Dataset upgrade");
730 my $rowcount = $form->{rowcount} * 1;
731 my @update_rows = grep { $form->{"update_$_"} } (1 .. $rowcount);
732 $form->{NOTHING_TO_DO} = !scalar @update_rows;
733 my $saved_form = save_form();
737 print $form->parse_html_template("admin/dbupgrade_all_header");
739 foreach my $i (@update_rows) {
740 restore_form($saved_form);
743 map { $form->{$_} = $::myconfig{$_} = $form->{"${_}_${i}"} } qw(dbname dbdriver dbhost dbport dbuser dbpasswd);
745 print $form->parse_html_template("admin/dbupgrade_header");
747 $form->{dbupdate} = $form->{dbname};
748 $form->{$form->{dbname}} = 1;
750 User->dbupdate($form);
751 User->dbupdate2($form, SL::DBUpgrade2->new(form => $form, dbdriver => $form->{dbdriver})->parse_dbupdate_controls);
753 print $form->parse_html_template("admin/dbupgrade_footer");
756 print $form->parse_html_template("admin/dbupgrade_all_done");
760 my $form = $main::form;
761 my $locale = $main::locale;
763 $form->{dbsources} = join " ", map { "[${_}]" } sort User->dbsources($form);
765 $form->{CHARTS} = [];
767 opendir SQLDIR, "sql/." or $form->error($ERRNO);
768 foreach my $item (sort grep /-chart\.sql\z/, readdir SQLDIR) {
769 next if ($item eq 'Default-chart.sql');
770 $item =~ s/-chart\.sql//;
771 push @{ $form->{CHARTS} }, { "name" => $item,
772 "selected" => $item eq "Germany-DATEV-SKR03EU" };
776 my $default_charset = $::lx_office_conf{system}->{dbcharset};
777 $default_charset ||= Common::DEFAULT_CHARSET;
779 my $cluster_encoding = User->dbclusterencoding($form);
780 if ($cluster_encoding && ($cluster_encoding =~ m/^(?:UTF-?8|UNICODE)$/i)) {
781 if ($::lx_office_conf{system}->{dbcharset} !~ m/^UTF-?8$/i) {
782 $form->show_generic_error($locale->text('The selected PostgreSQL installation uses UTF-8 as its encoding. ' .
783 'Therefore you have to configure Lx-Office to use UTF-8 as well.'),
787 $form->{FORCE_DBENCODING} = 'UNICODE';
790 $form->{DBENCODINGS} = [];
792 foreach my $encoding (@Common::db_encodings) {
793 push @{ $form->{DBENCODINGS} }, { "dbencoding" => $encoding->{dbencoding},
794 "label" => $encoding->{label},
795 "selected" => $encoding->{charset} eq $default_charset };
799 $form->{title} = "Lx-Office ERP " . $locale->text('Database Administration') . " / " . $locale->text('Create Dataset');
802 print $form->parse_html_template("admin/create_dataset");
806 my $form = $main::form;
807 my $locale = $main::locale;
809 $form->isblank("db", $locale->text('Dataset missing!'));
811 User->dbcreate(\%$form);
813 $form->{title} = "Lx-Office ERP " . $locale->text('Database Administration') . " / " . $locale->text('Create Dataset');
816 print $form->parse_html_template("admin/dbcreate");
820 my $form = $main::form;
821 my $locale = $main::locale;
823 my @dbsources = User->dbsources_unused($form);
824 $form->error($locale->text('Nothing to delete!')) unless @dbsources;
826 $form->{title} = "Lx-Office ERP " . $locale->text('Database Administration') . " / " . $locale->text('Delete Dataset');
827 $form->{DBSOURCES} = [ map { { "name", $_ } } sort @dbsources ];
830 print $form->parse_html_template("admin/delete_dataset");
834 my $form = $main::form;
835 my $locale = $main::locale;
838 $form->error($locale->text('No Dataset selected!'));
841 User->dbdelete(\%$form);
843 $form->{title} = "Lx-Office ERP " . $locale->text('Database Administration') . " / " . $locale->text('Delete Dataset');
845 print $form->parse_html_template("admin/dbdelete");
849 my $form = $main::form;
850 my $locale = $main::locale;
852 $form->{title} = "Lx-Office ERP " . $locale->text('Database Administration') . " / " . $locale->text('Backup Dataset');
854 if ($::lx_office_conf{applications}->{pg_dump} eq "DISABLED") {
855 $form->error($locale->text('Database backups and restorations are disabled in the configuration.'));
858 my @dbsources = sort User->dbsources($form);
859 $form->{DATABASES} = [ map { { "dbname" => $_ } } @dbsources ];
860 $form->{NO_DATABASES} = !scalar @dbsources;
862 my $username = getpwuid $UID || "unknown-user";
863 my $hostname = hostname() || "unknown-host";
864 $form->{from} = "Lx-Office Admin <${username}\@${hostname}>";
867 print $form->parse_html_template("admin/backup_dataset");
870 sub backup_dataset_start {
871 my $form = $main::form;
872 my $locale = $main::locale;
874 $form->{title} = "Lx-Office ERP " . $locale->text('Database Administration') . " / " . $locale->text('Backup Dataset');
876 my $pg_dump_exe = $::lx_office_conf{applications}->{pg_dump} || "pg_dump";
878 if ("$pg_dump_exe" eq "DISABLED") {
879 $form->error($locale->text('Database backups and restorations are disabled in the configuration.'));
882 $form->isblank("dbname", $locale->text('The dataset name is missing.'));
883 $form->isblank("to", $locale->text('The email address is missing.')) if $form->{destination} eq "email";
885 my $tmpdir = "/tmp/lx_office_backup_" . Common->unique_id();
886 mkdir $tmpdir, 0700 || $form->error($locale->text('A temporary directory could not be created:') . " $ERRNO");
888 my $pgpass = IO::File->new("${tmpdir}/.pgpass", O_WRONLY | O_CREAT, 0600);
892 $form->error($locale->text('A temporary file could not be created:') . " $ERRNO");
895 print $pgpass "$form->{dbhost}:$form->{dbport}:$form->{dbname}:$form->{dbuser}:$form->{dbpasswd}\n";
898 $ENV{HOME} = $tmpdir;
900 my @args = ("-Ft", "-c", "-o", "-h", $form->{dbhost}, "-U", $form->{dbuser});
901 push @args, ("-p", $form->{dbport}) if ($form->{dbport});
902 push @args, $form->{dbname};
904 my $cmd = "$pg_dump_exe " . join(" ", map { s/\\/\\\\/g; s/\"/\\\"/g; $_ } @args);
905 my $name = "dataset_backup_$form->{dbname}_" . strftime("%Y%m%d", localtime()) . ".tar";
907 if ($form->{destination} ne "email") {
908 my $in = IO::File->new("$cmd |");
911 unlink "${tmpdir}/.pgpass";
914 $form->error($locale->text('The pg_dump process could not be started.'));
917 print "content-type: application/x-tar\n";
918 print "content-disposition: attachment; filename=\"${name}\"\n\n";
920 while (my $line = <$in>) {
926 unlink "${tmpdir}/.pgpass";
930 my $tmp = $tmpdir . "/dump_" . Common::unique_id();
932 if (system("$cmd > $tmp") != 0) {
933 unlink "${tmpdir}/.pgpass", $tmp;
936 $form->error($locale->text('The pg_dump process could not be started.'));
939 my $mail = new Mailer;
941 map { $mail->{$_} = $form->{$_} } qw(from to cc subject message);
943 $mail->{charset} = $::lx_office_conf{system}->{dbcharset} || Common::DEFAULT_CHARSET;
944 $mail->{attachments} = [ { "filename" => $tmp, "name" => $name } ];
947 unlink "${tmpdir}/.pgpass", $tmp;
950 $form->{title} = "Lx-Office ERP " . $locale->text('Database Administration') . " / " . $locale->text('Backup Dataset');
953 print $form->parse_html_template("admin/backup_dataset_email_done");
957 sub restore_dataset {
958 my $form = $main::form;
959 my $locale = $main::locale;
961 $form->{title} = "Lx-Office ERP " . $locale->text('Database Administration') . " / " . $locale->text('Restore Dataset');
963 if ($::lx_office_conf{applications}->{pg_restore} eq "DISABLED") {
964 $form->error($locale->text('Database backups and restorations are disabled in the configuration.'));
967 my $default_charset = $::lx_office_conf{system}->{dbcharset};
968 $default_charset ||= Common::DEFAULT_CHARSET;
970 $form->{DBENCODINGS} = [];
972 foreach my $encoding (@Common::db_encodings) {
973 push @{ $form->{DBENCODINGS} }, { "dbencoding" => $encoding->{dbencoding},
974 "label" => $encoding->{label},
975 "selected" => $encoding->{charset} eq $default_charset };
979 print $form->parse_html_template("admin/restore_dataset");
982 sub restore_dataset_start {
983 my $form = $main::form;
984 my $locale = $main::locale;
986 $form->{title} = "Lx-Office ERP " . $locale->text('Database Administration') . " / " . $locale->text('Restore Dataset');
988 my $pg_restore_exe = $::lx_office_conf{applications}->{pg_restore} || "pg_restore";
990 if ("$pg_restore_exe" eq "DISABLED") {
991 $form->error($locale->text('Database backups and restorations are disabled in the configuration.'));
994 $form->isblank("new_dbname", $locale->text('The dataset name is missing.'));
995 $form->isblank("content", $locale->text('No backup file has been uploaded.'));
997 # Create temporary directories. Write the backup file contents to a temporary
998 # file. Create a .pgpass file with the username and password for the pg_restore
1001 my $tmpdir = "/tmp/lx_office_backup_" . Common->unique_id();
1002 mkdir $tmpdir, 0700 || $form->error($locale->text('A temporary directory could not be created:') . " $ERRNO");
1004 my $pgpass = IO::File->new("${tmpdir}/.pgpass", O_WRONLY | O_CREAT, 0600);
1008 $form->error($locale->text('A temporary file could not be created:') . " $ERRNO");
1011 print $pgpass "$form->{dbhost}:$form->{dbport}:$form->{new_dbname}:$form->{dbuser}:$form->{dbpasswd}\n";
1014 $ENV{HOME} = $tmpdir;
1016 my $tmp = $tmpdir . "/dump_" . Common::unique_id();
1019 if (substr($form->{content}, 0, 2) eq "\037\213") {
1020 $tmpfile = IO::File->new("| gzip -d > $tmp");
1024 $tmpfile = IO::File->new($tmp, O_WRONLY | O_CREAT | O_BINARY, 0600);
1028 unlink "${tmpdir}/.pgpass";
1031 $form->error($locale->text('A temporary file could not be created:') . " $ERRNO");
1034 print $tmpfile $form->{content};
1037 delete $form->{content};
1039 # Try to connect to the database. Find out if a database with the same name exists.
1040 # If yes, then drop the existing database. Create a new one with the name and encoding
1041 # given by the user.
1043 User::dbconnect_vars($form, "template1");
1045 my %myconfig = map { $_ => $form->{$_} } grep /^db/, keys %{ $form };
1046 my $dbh = $form->dbconnect(\%myconfig) || $form->dberror();
1050 $form->{new_dbname} =~ s|[^a-zA-Z0-9_\-]||g;
1052 $query = qq|SELECT COUNT(*) FROM pg_database WHERE datname = ?|;
1053 my ($count) = selectrow_query($form, $dbh, $query, $form->{new_dbname});
1055 do_query($form, $dbh, qq|DROP DATABASE $form->{new_dbname}|);
1059 foreach my $item (@Common::db_encodings) {
1060 if ($item->{dbencoding} eq $form->{dbencoding}) {
1065 $form->{dbencoding} = "LATIN9" unless $form->{dbencoding};
1067 do_query($form, $dbh, qq|CREATE DATABASE $form->{new_dbname} ENCODING ? TEMPLATE template0|, $form->{dbencoding});
1071 # Spawn pg_restore on the temporary file.
1073 my @args = ("-h", $form->{dbhost}, "-U", $form->{dbuser}, "-d", $form->{new_dbname});
1074 push @args, ("-p", $form->{dbport}) if ($form->{dbport});
1077 my $cmd = "$pg_restore_exe " . join(" ", map { s/\\/\\\\/g; s/\"/\\\"/g; $_ } @args);
1079 my $in = IO::File->new("$cmd 2>&1 |");
1082 unlink "${tmpdir}/.pgpass", $tmp;
1085 $form->error($locale->text('The pg_restore process could not be started.'));
1088 $English::AUTOFLUSH = 1;
1091 print $form->parse_html_template("admin/restore_dataset_start_header");
1093 while (my $line = <$in>) {
1098 $form->{retval} = $CHILD_ERROR >> 8;
1099 print $form->parse_html_template("admin/restore_dataset_start_footer");
1101 unlink "${tmpdir}/.pgpass", $tmp;
1106 my $form = $main::form;
1107 my $locale = $main::locale;
1109 unlink _nologin_file_name();;
1111 $form->{callback} = "admin.pl?action=list_users";
1113 $form->redirect($locale->text('Lockfile removed!'));
1118 my $form = $main::form;
1119 my $locale = $main::locale;
1121 open(FH, ">" . _nologin_file_name())
1122 or $form->error($locale->text('Cannot create Lock!'));
1125 $form->{callback} = "admin.pl?action=list_users";
1127 $form->redirect($locale->text('Lockfile created!'));
1132 call_sub($main::form->{yes_nextsub});
1136 call_sub($main::form->{no_nextsub});
1140 call_sub($main::form->{add_nextsub});
1144 my $form = $main::form;
1146 $form->{edit_nextsub} ||= 'edit_user';
1148 call_sub($form->{edit_nextsub});
1152 my $form = $main::form;
1154 $form->{delete_nextsub} ||= 'delete_user';
1156 call_sub($form->{delete_nextsub});
1160 my $form = $main::form;
1162 $form->{save_nextsub} ||= 'save_user';
1164 call_sub($form->{save_nextsub});
1168 call_sub($main::form->{back_nextsub});
1172 my $form = $main::form;
1173 my $locale = $main::locale;
1175 foreach my $action (qw(create_standard_group dont_create_standard_group
1176 save_user delete_user save_user_as_new)) {
1177 if ($form->{"action_${action}"}) {
1183 call_sub($form->{default_action}) if ($form->{default_action});
1185 $form->error($locale->text('No action defined.'));
1188 sub _apply_dbupgrade_scripts {
1189 ::end_of_request() if SL::DBUpgrade2->new(form => $::form, dbdriver => 'Pg', auth => 1)->apply_admin_dbupgrade_scripts(1);
1192 sub _nologin_file_name {
1193 return $::lx_office_conf{paths}->{userspath} . '/nologin';