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";
70 $::lxdebug->enter_sub;
71 my $session_result = shift;
77 $::auth->store_root_credentials_in_session($form->{rpw}) if $session_result == SL::Auth->SESSION_OK;
79 $form->{stylesheet} = "lx-office-erp.css";
80 $form->{favicon} = "favicon.ico";
82 if ($form->{action}) {
83 if ($auth->authenticate_root($form->{rpw}) != $auth->OK()) {
84 $form->{error_message} = $locale->text('Incorrect Password!');
85 $auth->delete_session_value('rpw');
88 if ($auth->session_tables_present()) {
89 $::auth->store_root_credentials_in_session($::form->{rpw});
90 delete $::form->{rpw};
91 _apply_dbupgrade_scripts();
94 call_sub($locale->findsub($form->{action}));
97 # if there are no drivers bail out
98 $form->error($locale->text('No Database Drivers available!'))
99 unless (User->dbdrivers);
103 $::lxdebug->leave_sub;
107 my $form = $main::form;
108 my $locale = $main::locale;
110 $form->{title} = qq|Lx-Office ERP $form->{version} | . $locale->text('Administration');
113 print $form->parse_html_template('admin/adminlogin');
117 check_auth_db_and_tables();
122 $main::auth->destroy_session();
126 sub check_auth_db_and_tables {
127 my $form = $main::form;
128 my $locale = $main::locale;
132 map { $params{"db_${_}"} = $main::auth->{DB_config}->{$_} } keys %{ $auth->{DB_config} };
134 if (!$main::auth->check_database()) {
135 $form->{title} = $locale->text('Authentification database creation');
137 print $form->parse_html_template('admin/check_auth_database', \%params);
142 if (!$main::auth->check_tables()) {
143 $form->{title} = $locale->text('Authentification tables creation');
145 print $form->parse_html_template('admin/check_auth_tables', \%params);
150 my $memberfile = $::lx_office_conf{paths}->{memberfile};
151 if (-f $memberfile) {
154 if ($memberfile =~ m|^.*/|) {
158 my $backupdir = "${memberdir}member-file-migration";
160 $form->{title} = $locale->text('User data migration');
162 print $form->parse_html_template('admin/user_migration', { 'memberfile' => $memberfile,
163 'backupdir' => $backupdir });
170 my $form = $main::form;
172 $main::auth->create_database('superuser' => $form->{db_superuser},
173 'superuser_password' => $form->{db_superuser_password},
174 'template' => $form->{db_template});
178 sub create_auth_tables {
179 my $form = $main::form;
180 my $locale = $main::locale;
182 $main::auth->create_tables();
183 $main::auth->set_session_value('rpw', $form->{rpw});
184 $main::auth->create_or_refresh_session();
186 my $memberfile = $::lx_office_conf{paths}->{memberfile};
187 if (!-f $memberfile) {
188 # New installation -- create a standard group with full access
191 'name' => $locale->text('Full Access'),
192 'description' => $locale->text('Full access to all functions'),
193 'rights' => { map { $_ => 1 } SL::Auth::all_rights() },
194 'members' => [ map { $_->{id} } values %members ],
197 $main::auth->save_group($group);
200 _apply_dbupgrade_scripts();
205 $main::lxdebug->enter_sub();
207 my $form = $main::form;
208 my $locale = $main::locale;
212 my $memberfile = $::lx_office_conf{paths}->{memberfile};
213 if ($memberfile =~ m|^.*/|) {
217 my $backupdir = "${memberdir}member-file-migration";
219 if (! -d $backupdir && !mkdir $backupdir, 0700) {
220 $form->error(sprintf($locale->text('The directory "%s" could not be created:\n%s'), $backupdir, $!));
223 copy $memberfile, "users/member-file-migration/members";
225 my $in = IO::File->new($memberfile, "r");
227 $form->error($locale->text('Could not open the old memberfile.')) if (!$in);
229 my (%members, $login);
238 $login =~ s/(\[|\])//g;
242 $members{$login} = { "login" => $login };
246 if ($login && m/=/) {
247 my ($key, $value) = split m/\s*=\s*/, $_, 2;
252 $value =~ s|\\n|\n|g;
254 $members{$login}->{$key} = $value;
260 delete $members{"root login"};
262 map { $_->{dbpasswd} = unpack 'u', $_->{dbpasswd} } values %members;
264 while (my ($login, $params) = each %members) {
265 $main::auth->save_user($login, %{ $params });
266 $main::auth->change_password($login, $params->{password}, 1);
268 my $conf_file = "${memberdir}${login}.conf";
271 copy $conf_file, "${backupdir}/${login}.conf";
278 my @member_list = sort { lc $a->{login} cmp lc $b->{login} } values %members;
280 $form->{title} = $locale->text('User data migration');
282 print $form->parse_html_template('admin/user_migration_done', { 'MEMBERS' => \@member_list });
284 $main::lxdebug->leave_sub();
287 sub create_standard_group_ask {
288 my $form = $main::form;
289 my $locale = $main::locale;
291 $form->{title} = $locale->text('Create a standard group');
294 print $form->parse_html_template("admin/create_standard_group_ask");
297 sub create_standard_group {
298 my $form = $main::form;
299 my $locale = $main::locale;
301 my %members = $main::auth->read_all_users();
303 my $groups = $main::auth->read_groups();
305 foreach my $group (values %{$groups}) {
306 if (($form->{group_id} != $group->{id})
307 && ($form->{name} eq $group->{name})) {
308 $form->show_generic_error($locale->text("A group with that name does already exist."));
313 'name' => $locale->text('Full Access'),
314 'description' => $locale->text('Full access to all functions'),
315 'rights' => { map { $_ => 1 } SL::Auth::all_rights() },
316 'members' => [ map { $_->{id} } values %members ],
319 $main::auth->save_group($group);
321 user_migration_complete(1);
324 sub dont_create_standard_group {
325 user_migration_complete(0);
328 sub user_migration_complete {
329 my $standard_group_created = shift;
331 my $form = $main::form;
332 my $locale = $main::locale;
334 $form->{title} = $locale->text('User migration complete');
337 print $form->parse_html_template('admin/user_migration_complete', { 'standard_group_created' => $standard_group_created });
341 my $form = $main::form;
342 my $locale = $main::locale;
344 my %members = $main::auth->read_all_users();
346 delete $members{"root login"};
348 for (values %members) {
349 $_->{templates} =~ s|.*/||;
350 $_->{login_url} = $::locale->is_utf8 ? Encode::encode('utf-8-strict', $_->{login}) : $_->{login_url};
353 $form->{title} = "Lx-Office ERP " . $locale->text('Administration');
354 $form->{LOCKED} = -e _nologin_file_name();
355 $form->{MEMBERS} = [ @members{sort { lc $a cmp lc $b } keys %members} ];
358 print $form->parse_html_template("admin/list_users");
362 my $form = $main::form;
363 my $locale = $main::locale;
365 $form->{title} = "Lx-Office ERP " . $locale->text('Administration') . " / " . $locale->text('Add User');
367 # Note: Menu Style 'v3' is not compatible to all browsers!
368 # "menustyle" => "old" sets the HTML Menu to default.
371 "countrycode" => "de",
372 "numberformat" => "1.000,00",
373 "dateformat" => "dd.mm.yy",
374 "stylesheet" => "lx-office-erp.css",
375 "menustyle" => "old",
376 dbport => $::auth->{DB_config}->{port} || 5432,
377 dbuser => $::auth->{DB_config}->{user} || 'lxoffice',
378 dbhost => $::auth->{DB_config}->{host} || 'localhost',
382 edit_user_form($myconfig);
386 my $form = $main::form;
387 my $locale = $main::locale;
389 $form->{title} = "Lx-Office ERP " . $locale->text('Administration') . " / " . $locale->text('Edit User');
392 $form->isblank("login", $locale->text("The login is missing."));
395 my $myconfig = new User($form->{login});
397 # strip basedir from templates directory
398 $myconfig->{templates} =~ s|.*/||;
400 edit_user_form($myconfig);
406 my $form = $main::form;
407 my $locale = $main::locale;
409 my @valid_dateformats = qw(mm-dd-yy mm/dd/yy dd-mm-yy dd/mm/yy dd.mm.yy yyyy-mm-dd);
410 $form->{ALL_DATEFORMATS} = [ map { { "format" => $_, "selected" => $_ eq $myconfig->{dateformat} } } @valid_dateformats ];
412 my @valid_numberformats = ('1,000.00', '1000.00', '1.000,00', '1000,00');
413 $form->{ALL_NUMBERFORMATS} = [ map { { "format" => $_, "selected" => $_ eq $myconfig->{numberformat} } } @valid_numberformats ];
415 my %countrycodes = User->country_codes;
416 $form->{ALL_COUNTRYCODES} = [];
417 foreach my $countrycode (sort { $countrycodes{$a} cmp $countrycodes{$b} } keys %countrycodes) {
418 push @{ $form->{ALL_COUNTRYCODES} }, { "value" => $countrycode,
419 "name" => $countrycodes{$countrycode},
420 "selected" => $countrycode eq $myconfig->{countrycode} };
423 # is there a templates basedir
424 if (!-d $::lx_office_conf{paths}->{templates}) {
425 $form->error(sprintf($locale->text("The directory %s does not exist."), $::lx_office_conf{paths}->{templates}));
428 opendir TEMPLATEDIR, $::lx_office_conf{paths}->{templates} or $form->error($::lx_office_conf{paths}->{templates} . " : $ERRNO");
429 my @all = readdir(TEMPLATEDIR);
430 my @alldir = sort grep { -d ($::lx_office_conf{paths}->{templates} . "/$_") && !/^\.\.?$/ } @all;
431 closedir TEMPLATEDIR;
433 @alldir = grep !/\.(html|tex|sty|odt|xml|txb)$/, @alldir;
434 @alldir = grep !/^(webpages|print|\.svn)$/, @alldir;
436 $form->{ALL_TEMPLATES} = [ map { { "name", => $_, "selected" => $_ eq $myconfig->{templates} } } @alldir ];
439 opendir TEMPLATEDIR, "$::lx_office_conf{paths}->{templates}/print" or $form->error("$::lx_office_conf{paths}->{templates}/print" . " : $ERRNO");
440 my @allmaster = readdir(TEMPLATEDIR);
441 closedir TEMPLATEDIR;
443 @allmaster = sort grep { -d ("$::lx_office_conf{paths}->{templates}/print" . "/$_") && !/^\.\.?$/ } @allmaster;
444 @allmaster = reverse grep !/Default/, @allmaster;
445 push @allmaster, 'Default';
446 @allmaster = reverse @allmaster;
448 foreach my $item (@allmaster) {
449 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
546 my $oldcurrdir = getcwd();
547 if (!chdir("$::lx_office_conf{paths}->{templates}/print/$form->{mastertemplates}")) {
548 $form->error("$ERRNO: chdir $::lx_office_conf{paths}->{templates}/print/$form->{mastertemplates}");
551 my $newdir = File::Spec->catdir($oldcurrdir, $form->{templates});
559 if (!mkdir (File::Spec->catdir($newdir, $File::Find::name))) {
561 $form->error("$ERRNO: mkdir $File::Find::name");
564 if (!symlink (readlink($_),
565 File::Spec->catfile($newdir, $File::Find::name))) {
567 $form->error("$ERRNO: symlink $File::Find::name");
569 } elsif (-f $_ && $_ =~ m/.*?\.(html|tex|sty|odt|xml|txb|eps|pdf|png|jpg)$/) {
570 if (!copy($_, File::Spec->catfile($newdir, $File::Find::name))) {
572 $form->error("$ERRNO: cp $File::Find::name");
580 $form->error("$ERRNO: $form->{templates}");
584 # Add new user to his groups.
585 if (ref $form->{new_user_group_ids} eq 'ARRAY') {
586 my $all_groups = $main::auth->read_groups();
587 my %user = $main::auth->read_user($form->{login});
589 foreach my $group_id (@{ $form->{new_user_group_ids} }) {
590 my $group = $all_groups->{$group_id};
594 push @{ $group->{members} }, $user{id};
595 $main::auth->save_group($group);
599 if ($main::auth->can_change_password()
600 && defined $form->{new_password}
601 && ($form->{new_password} ne '********')) {
602 my $verifier = SL::Auth::PasswordPolicy->new;
603 my $result = $verifier->verify($form->{new_password}, 1);
605 if ($result != SL::Auth::PasswordPolicy->OK()) {
606 $form->error($::locale->text('The settings were saved, but the password was not changed.') . ' ' . join(' ', $verifier->errors($result)));
609 $main::auth->change_password($form->{login}, $form->{new_password});
612 $form->redirect($locale->text('User saved!'));
615 sub save_user_as_new {
616 my $form = $main::form;
618 $form->{login} = $form->{new_user_login};
619 delete @{$form}{qw(edit new_user_login)};
625 my $form = $main::form;
626 my $locale = $main::locale;
628 my %members = $main::auth->read_all_users();
629 my $templates = $members{$form->{login}}->{templates};
631 $main::auth->delete_user($form->{login});
634 my $templates_in_use = 0;
636 foreach my $login (keys %members) {
637 next if $form->{login} eq $login;
638 next if $members{$login}->{templates} ne $templates;
639 $templates_in_use = 1;
643 if (!$templates_in_use && -d $templates) {
644 unlink <$templates/*>;
649 $form->redirect($locale->text('User deleted!'));
657 return ($login) ? $login : undef;
663 my ($null, $value) = split(/=/, $line, 2);
666 $value =~ s/\s#.*//g;
668 # remove any trailing whitespace
669 $value =~ s/^\s*(.*?)\s*$/$1/;
674 sub pg_database_administration {
675 my $form = $main::form;
677 $form->{dbdriver} = 'Pg';
682 sub dbselect_source {
683 my $form = $main::form;
684 my $locale = $main::locale;
686 $form->{dbport} = $::auth->{DB_config}->{port} || 5432;
687 $form->{dbuser} = $::auth->{DB_config}->{user} || 'lxoffice';
688 $form->{dbdefault} = 'template1';
689 $form->{dbhost} = $::auth->{DB_config}->{host} || 'localhost';
691 $form->{title} = "Lx-Office ERP / " . $locale->text('Database Administration');
693 # Intentionnaly disabled unless fixed to work with the authentication DB.
694 $form->{ALLOW_DBBACKUP} = 0; # "$pg_dump_exe" ne "DISABLED";
697 print $form->parse_html_template("admin/dbadmin");
700 sub test_db_connection {
701 my $form = $main::form;
702 my $locale = $main::locale;
704 $form->{dbdriver} = 'Pg';
705 User::dbconnect_vars($form, $form->{dbname});
707 my $dbh = DBI->connect($form->{dbconnect}, $form->{dbuser}, $form->{dbpasswd});
709 $form->{connection_ok} = $dbh ? 1 : 0;
710 $form->{errstr} = $DBI::errstr;
712 $dbh->disconnect() if ($dbh);
714 $form->{title} = $locale->text('Database Connection Test');
716 print $form->parse_html_template("admin/test_db_connection");
720 call_sub($main::form->{"nextsub"});
724 my $form = $main::form;
725 my $locale = $main::locale;
727 $form->{title} = "Lx-Office ERP " . $locale->text('Database Administration') . " / " . $locale->text('Update Dataset');
729 my @need_updates = User->dbneedsupdate($form);
730 $form->{NEED_UPDATES} = \@need_updates;
731 $form->{ALL_UPDATED} = !scalar @need_updates;
734 print $form->parse_html_template("admin/update_dataset");
738 my $form = $main::form;
739 my $locale = $main::locale;
741 $form->{stylesheet} = "lx-office-erp.css";
742 $form->{title} = $locale->text("Dataset upgrade");
745 my $rowcount = $form->{rowcount} * 1;
746 my @update_rows = grep { $form->{"update_$_"} } (1 .. $rowcount);
747 $form->{NOTHING_TO_DO} = !scalar @update_rows;
748 my $saved_form = save_form();
752 print $form->parse_html_template("admin/dbupgrade_all_header");
754 foreach my $i (@update_rows) {
755 restore_form($saved_form);
758 map { $form->{$_} = $::myconfig{$_} = $form->{"${_}_${i}"} } qw(dbname dbdriver dbhost dbport dbuser dbpasswd);
760 print $form->parse_html_template("admin/dbupgrade_header");
762 $form->{dbupdate} = $form->{dbname};
763 $form->{$form->{dbname}} = 1;
765 User->dbupdate($form);
766 User->dbupdate2($form, SL::DBUpgrade2->new(form => $form, dbdriver => $form->{dbdriver})->parse_dbupdate_controls);
768 print $form->parse_html_template("admin/dbupgrade_footer");
771 print $form->parse_html_template("admin/dbupgrade_all_done");
775 my $form = $main::form;
776 my $locale = $main::locale;
778 $form->{dbsources} = join " ", map { "[${_}]" } sort User->dbsources($form);
780 $form->{CHARTS} = [];
782 opendir SQLDIR, "sql/." or $form->error($ERRNO);
783 foreach my $item (sort grep /-chart\.sql\z/, readdir SQLDIR) {
784 next if ($item eq 'Default-chart.sql');
785 $item =~ s/-chart\.sql//;
786 push @{ $form->{CHARTS} }, { "name" => $item,
787 "selected" => $item eq "Germany-DATEV-SKR03EU" };
791 $form->{ACCOUNTING_METHODS} = [];
792 foreach my $item ( qw(accrual cash) ) {
793 push @{ $form->{ACCOUNTING_METHODS} }, { "name" => $item,
794 "selected" => $item eq "cash" };
797 $form->{INVENTORY_SYSTEMS} = [];
798 foreach my $item ( qw(perpetual periodic) ) {
799 push @{ $form->{INVENTORY_SYSTEMS} }, { "name" => $item,
800 "selected" => $item eq "periodic" };
803 $form->{PROFIT_DETERMINATIONS} = [];
804 foreach my $item ( qw(balance income) ) {
805 push @{ $form->{PROFIT_DETERMINATIONS} }, { "name" => $item,
806 "selected" => $item eq "income" };
809 my $default_charset = $::lx_office_conf{system}->{dbcharset};
810 $default_charset ||= Common::DEFAULT_CHARSET;
812 my $cluster_encoding = User->dbclusterencoding($form);
813 if ($cluster_encoding && ($cluster_encoding =~ m/^(?:UTF-?8|UNICODE)$/i)) {
814 if ($::lx_office_conf{system}->{dbcharset} !~ m/^UTF-?8$/i) {
815 $form->show_generic_error($locale->text('The selected PostgreSQL installation uses UTF-8 as its encoding. ' .
816 'Therefore you have to configure Lx-Office to use UTF-8 as well.'),
820 $form->{FORCE_DBENCODING} = 'UNICODE';
823 $form->{DBENCODINGS} = [];
825 foreach my $encoding (@Common::db_encodings) {
826 push @{ $form->{DBENCODINGS} }, { "dbencoding" => $encoding->{dbencoding},
827 "label" => $encoding->{label},
828 "selected" => $encoding->{charset} eq $default_charset };
832 $form->{title} = "Lx-Office ERP " . $locale->text('Database Administration') . " / " . $locale->text('Create Dataset');
835 print $form->parse_html_template("admin/create_dataset");
839 my $form = $main::form;
840 my $locale = $main::locale;
842 $form->isblank("db", $locale->text('Dataset missing!'));
844 User->dbcreate(\%$form);
846 $form->{title} = "Lx-Office ERP " . $locale->text('Database Administration') . " / " . $locale->text('Create Dataset');
849 print $form->parse_html_template("admin/dbcreate");
853 my $form = $main::form;
854 my $locale = $main::locale;
856 my @dbsources = User->dbsources_unused($form);
857 $form->error($locale->text('Nothing to delete!')) unless @dbsources;
859 $form->{title} = "Lx-Office ERP " . $locale->text('Database Administration') . " / " . $locale->text('Delete Dataset');
860 $form->{DBSOURCES} = [ map { { "name", $_ } } sort @dbsources ];
863 print $form->parse_html_template("admin/delete_dataset");
867 my $form = $main::form;
868 my $locale = $main::locale;
871 $form->error($locale->text('No Dataset selected!'));
874 User->dbdelete(\%$form);
876 $form->{title} = "Lx-Office ERP " . $locale->text('Database Administration') . " / " . $locale->text('Delete Dataset');
878 print $form->parse_html_template("admin/dbdelete");
882 my $form = $main::form;
883 my $locale = $main::locale;
885 $form->{title} = "Lx-Office ERP " . $locale->text('Database Administration') . " / " . $locale->text('Backup Dataset');
887 if ($::lx_office_conf{applications}->{pg_dump} eq "DISABLED") {
888 $form->error($locale->text('Database backups and restorations are disabled in the configuration.'));
891 my @dbsources = sort User->dbsources($form);
892 $form->{DATABASES} = [ map { { "dbname" => $_ } } @dbsources ];
893 $form->{NO_DATABASES} = !scalar @dbsources;
895 my $username = getpwuid $UID || "unknown-user";
896 my $hostname = hostname() || "unknown-host";
897 $form->{from} = "Lx-Office Admin <${username}\@${hostname}>";
900 print $form->parse_html_template("admin/backup_dataset");
903 sub backup_dataset_start {
904 my $form = $main::form;
905 my $locale = $main::locale;
907 $form->{title} = "Lx-Office ERP " . $locale->text('Database Administration') . " / " . $locale->text('Backup Dataset');
909 my $pg_dump_exe = $::lx_office_conf{applications}->{pg_dump} || "pg_dump";
911 if ("$pg_dump_exe" eq "DISABLED") {
912 $form->error($locale->text('Database backups and restorations are disabled in the configuration.'));
915 $form->isblank("dbname", $locale->text('The dataset name is missing.'));
916 $form->isblank("to", $locale->text('The email address is missing.')) if $form->{destination} eq "email";
918 my $tmpdir = "/tmp/lx_office_backup_" . Common->unique_id();
919 mkdir $tmpdir, 0700 || $form->error($locale->text('A temporary directory could not be created:') . " $ERRNO");
921 my $pgpass = IO::File->new("${tmpdir}/.pgpass", O_WRONLY | O_CREAT, 0600);
925 $form->error($locale->text('A temporary file could not be created:') . " $ERRNO");
928 print $pgpass "$form->{dbhost}:$form->{dbport}:$form->{dbname}:$form->{dbuser}:$form->{dbpasswd}\n";
931 $ENV{HOME} = $tmpdir;
933 my @args = ("-Ft", "-c", "-o", "-h", $form->{dbhost}, "-U", $form->{dbuser});
934 push @args, ("-p", $form->{dbport}) if ($form->{dbport});
935 push @args, $form->{dbname};
937 my $cmd = "$pg_dump_exe " . join(" ", map { s/\\/\\\\/g; s/\"/\\\"/g; $_ } @args);
938 my $name = "dataset_backup_$form->{dbname}_" . strftime("%Y%m%d", localtime()) . ".tar";
940 if ($form->{destination} ne "email") {
941 my $in = IO::File->new("$cmd |");
944 unlink "${tmpdir}/.pgpass";
947 $form->error($locale->text('The pg_dump process could not be started.'));
950 print "content-type: application/x-tar\n";
951 print "content-disposition: attachment; filename=\"${name}\"\n\n";
953 while (my $line = <$in>) {
959 unlink "${tmpdir}/.pgpass";
963 my $tmp = $tmpdir . "/dump_" . Common::unique_id();
965 if (system("$cmd > $tmp") != 0) {
966 unlink "${tmpdir}/.pgpass", $tmp;
969 $form->error($locale->text('The pg_dump process could not be started.'));
972 my $mail = new Mailer;
974 map { $mail->{$_} = $form->{$_} } qw(from to cc subject message);
976 $mail->{charset} = $::lx_office_conf{system}->{dbcharset} || Common::DEFAULT_CHARSET;
977 $mail->{attachments} = [ { "filename" => $tmp, "name" => $name } ];
980 unlink "${tmpdir}/.pgpass", $tmp;
983 $form->{title} = "Lx-Office ERP " . $locale->text('Database Administration') . " / " . $locale->text('Backup Dataset');
986 print $form->parse_html_template("admin/backup_dataset_email_done");
990 sub restore_dataset {
991 my $form = $main::form;
992 my $locale = $main::locale;
994 $form->{title} = "Lx-Office ERP " . $locale->text('Database Administration') . " / " . $locale->text('Restore Dataset');
996 if ($::lx_office_conf{applications}->{pg_restore} eq "DISABLED") {
997 $form->error($locale->text('Database backups and restorations are disabled in the configuration.'));
1000 my $default_charset = $::lx_office_conf{system}->{dbcharset};
1001 $default_charset ||= Common::DEFAULT_CHARSET;
1003 $form->{DBENCODINGS} = [];
1005 foreach my $encoding (@Common::db_encodings) {
1006 push @{ $form->{DBENCODINGS} }, { "dbencoding" => $encoding->{dbencoding},
1007 "label" => $encoding->{label},
1008 "selected" => $encoding->{charset} eq $default_charset };
1012 print $form->parse_html_template("admin/restore_dataset");
1015 sub restore_dataset_start {
1016 my $form = $main::form;
1017 my $locale = $main::locale;
1019 $form->{title} = "Lx-Office ERP " . $locale->text('Database Administration') . " / " . $locale->text('Restore Dataset');
1021 my $pg_restore_exe = $::lx_office_conf{applications}->{pg_restore} || "pg_restore";
1023 if ("$pg_restore_exe" eq "DISABLED") {
1024 $form->error($locale->text('Database backups and restorations are disabled in the configuration.'));
1027 $form->isblank("new_dbname", $locale->text('The dataset name is missing.'));
1028 $form->isblank("content", $locale->text('No backup file has been uploaded.'));
1030 # Create temporary directories. Write the backup file contents to a temporary
1031 # file. Create a .pgpass file with the username and password for the pg_restore
1034 my $tmpdir = "/tmp/lx_office_backup_" . Common->unique_id();
1035 mkdir $tmpdir, 0700 || $form->error($locale->text('A temporary directory could not be created:') . " $ERRNO");
1037 my $pgpass = IO::File->new("${tmpdir}/.pgpass", O_WRONLY | O_CREAT, 0600);
1041 $form->error($locale->text('A temporary file could not be created:') . " $ERRNO");
1044 print $pgpass "$form->{dbhost}:$form->{dbport}:$form->{new_dbname}:$form->{dbuser}:$form->{dbpasswd}\n";
1047 $ENV{HOME} = $tmpdir;
1049 my $tmp = $tmpdir . "/dump_" . Common::unique_id();
1052 if (substr($form->{content}, 0, 2) eq "\037\213") {
1053 $tmpfile = IO::File->new("| gzip -d > $tmp");
1057 $tmpfile = IO::File->new($tmp, O_WRONLY | O_CREAT | O_BINARY, 0600);
1061 unlink "${tmpdir}/.pgpass";
1064 $form->error($locale->text('A temporary file could not be created:') . " $ERRNO");
1067 print $tmpfile $form->{content};
1070 delete $form->{content};
1072 # Try to connect to the database. Find out if a database with the same name exists.
1073 # If yes, then drop the existing database. Create a new one with the name and encoding
1074 # given by the user.
1076 User::dbconnect_vars($form, "template1");
1078 my %myconfig = map { $_ => $form->{$_} } grep /^db/, keys %{ $form };
1079 my $dbh = $form->dbconnect(\%myconfig) || $form->dberror();
1083 $form->{new_dbname} =~ s|[^a-zA-Z0-9_\-]||g;
1085 $query = qq|SELECT COUNT(*) FROM pg_database WHERE datname = ?|;
1086 my ($count) = selectrow_query($form, $dbh, $query, $form->{new_dbname});
1088 do_query($form, $dbh, qq|DROP DATABASE $form->{new_dbname}|);
1092 foreach my $item (@Common::db_encodings) {
1093 if ($item->{dbencoding} eq $form->{dbencoding}) {
1098 $form->{dbencoding} = "LATIN9" unless $form->{dbencoding};
1100 do_query($form, $dbh, qq|CREATE DATABASE $form->{new_dbname} ENCODING ? TEMPLATE template0|, $form->{dbencoding});
1104 # Spawn pg_restore on the temporary file.
1106 my @args = ("-h", $form->{dbhost}, "-U", $form->{dbuser}, "-d", $form->{new_dbname});
1107 push @args, ("-p", $form->{dbport}) if ($form->{dbport});
1110 my $cmd = "$pg_restore_exe " . join(" ", map { s/\\/\\\\/g; s/\"/\\\"/g; $_ } @args);
1112 my $in = IO::File->new("$cmd 2>&1 |");
1115 unlink "${tmpdir}/.pgpass", $tmp;
1118 $form->error($locale->text('The pg_restore process could not be started.'));
1121 $English::AUTOFLUSH = 1;
1124 print $form->parse_html_template("admin/restore_dataset_start_header");
1126 while (my $line = <$in>) {
1131 $form->{retval} = $CHILD_ERROR >> 8;
1132 print $form->parse_html_template("admin/restore_dataset_start_footer");
1134 unlink "${tmpdir}/.pgpass", $tmp;
1139 my $form = $main::form;
1140 my $locale = $main::locale;
1142 unlink _nologin_file_name();;
1144 $form->{callback} = "admin.pl?action=list_users";
1146 $form->redirect($locale->text('Lockfile removed!'));
1151 my $form = $main::form;
1152 my $locale = $main::locale;
1154 open(FH, ">", _nologin_file_name())
1155 or $form->error($locale->text('Cannot create Lock!'));
1158 $form->{callback} = "admin.pl?action=list_users";
1160 $form->redirect($locale->text('Lockfile created!'));
1165 call_sub($main::form->{yes_nextsub});
1169 call_sub($main::form->{no_nextsub});
1173 call_sub($main::form->{add_nextsub});
1177 my $form = $main::form;
1179 $form->{edit_nextsub} ||= 'edit_user';
1181 call_sub($form->{edit_nextsub});
1185 my $form = $main::form;
1187 $form->{delete_nextsub} ||= 'delete_user';
1189 call_sub($form->{delete_nextsub});
1193 my $form = $main::form;
1195 $form->{save_nextsub} ||= 'save_user';
1197 call_sub($form->{save_nextsub});
1201 call_sub($main::form->{back_nextsub});
1205 my $form = $main::form;
1206 my $locale = $main::locale;
1208 foreach my $action (qw(create_standard_group dont_create_standard_group
1209 save_user delete_user save_user_as_new)) {
1210 if ($form->{"action_${action}"}) {
1216 call_sub($form->{default_action}) if ($form->{default_action});
1218 $form->error($locale->text('No action defined.'));
1221 sub _apply_dbupgrade_scripts {
1222 ::end_of_request() if SL::DBUpgrade2->new(form => $::form, dbdriver => 'Pg', auth => 1)->apply_admin_dbupgrade_scripts(1);
1225 sub _nologin_file_name {
1226 return $::lx_office_conf{paths}->{userspath} . '/nologin';