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);
41 use POSIX qw(strftime);
45 use SL::Auth::PasswordPolicy;
55 require "bin/mozilla/common.pl";
56 require "bin/mozilla/admin_groups.pl";
57 require "bin/mozilla/admin_printer.pl";
67 $::lxdebug->enter_sub;
68 my $session_result = shift;
75 $::auth->set_session_value('rpw', $::form->{rpw}) if $session_result == SL::Auth->SESSION_OK;
77 $form->{stylesheet} = "lx-office-erp.css";
78 $form->{favicon} = "favicon.ico";
80 if ($form->{action}) {
81 if ($auth->authenticate_root($form->{rpw}, 0) != $auth->OK()) {
82 $form->{error_message} = $locale->text('Incorrect Password!');
85 if ($auth->session_tables_present()) {
86 $::auth->set_session_value('rpw', $::form->{rpw});
87 $::auth->create_or_refresh_session();
88 _apply_dbupgrade_scripts();
91 call_sub($locale->findsub($form->{action}));
94 # if there are no drivers bail out
95 $form->error($locale->text('No Database Drivers available!'))
96 unless (User->dbdrivers);
100 $::lxdebug->leave_sub;
104 my $form = $main::form;
105 my $locale = $main::locale;
107 $form->{title} = qq|Lx-Office ERP $form->{version} | . $locale->text('Administration');
110 print $form->parse_html_template('admin/adminlogin');
114 check_auth_db_and_tables();
119 $main::auth->destroy_session();
123 sub check_auth_db_and_tables {
124 my $form = $main::form;
125 my $locale = $main::locale;
129 map { $params{"db_${_}"} = $main::auth->{DB_config}->{$_} } keys %{ $auth->{DB_config} };
131 if (!$main::auth->check_database()) {
132 $form->{title} = $locale->text('Authentification database creation');
134 print $form->parse_html_template('admin/check_auth_database', \%params);
139 if (!$main::auth->check_tables()) {
140 $form->{title} = $locale->text('Authentification tables creation');
142 print $form->parse_html_template('admin/check_auth_tables', \%params);
147 if (-f $main::memberfile) {
150 if ($main::memberfile =~ m|^.*/|) {
154 my $backupdir = "${memberdir}member-file-migration";
156 $form->{title} = $locale->text('User data migration');
158 print $form->parse_html_template('admin/user_migration', { 'memberfile' => $main::memberfile,
159 'backupdir' => $backupdir });
166 my $form = $main::form;
168 $main::auth->create_database('superuser' => $form->{db_superuser},
169 'superuser_password' => $form->{db_superuser_password},
170 'template' => $form->{db_template});
174 sub create_auth_tables {
175 my $form = $main::form;
176 my $locale = $main::locale;
178 $main::auth->create_tables();
179 $main::auth->set_session_value('rpw', $form->{rpw});
180 $main::auth->create_or_refresh_session();
182 if (!-f $main::memberfile) {
183 # New installation -- create a standard group with full access
186 'name' => $locale->text('Full Access'),
187 'description' => $locale->text('Full access to all functions'),
188 'rights' => { map { $_ => 1 } SL::Auth::all_rights() },
189 'members' => [ map { $_->{id} } values %members ],
192 $main::auth->save_group($group);
199 $main::lxdebug->enter_sub();
201 my $form = $main::form;
202 my $locale = $main::locale;
206 if ($main::memberfile =~ m|^.*/|) {
210 my $backupdir = "${memberdir}member-file-migration";
212 if (! -d $backupdir && !mkdir $backupdir, 0700) {
213 $form->error(sprintf($locale->text('The directory "%s" could not be created:\n%s'), $backupdir, $!));
216 copy $main::memberfile, "users/member-file-migration/members";
218 my $in = IO::File->new($main::memberfile, "r");
220 $form->error($locale->text('Could not open the old memberfile.')) if (!$in);
222 my (%members, $login);
231 $login =~ s/(\[|\])//g;
235 $members{$login} = { "login" => $login };
239 if ($login && m/=/) {
240 my ($key, $value) = split m/\s*=\s*/, $_, 2;
245 $value =~ s|\\n|\n|g;
247 $members{$login}->{$key} = $value;
253 delete $members{"root login"};
255 map { $_->{dbpasswd} = unpack 'u', $_->{dbpasswd} } values %members;
257 while (my ($login, $params) = each %members) {
258 $main::auth->save_user($login, %{ $params });
259 $main::auth->change_password($login, $params->{password}, 1);
261 my $conf_file = "${memberdir}${login}.conf";
264 copy $conf_file, "${backupdir}/${login}.conf";
269 unlink $main::memberfile;
271 my @member_list = sort { lc $a->{login} cmp lc $b->{login} } values %members;
273 $form->{title} = $locale->text('User data migration');
275 print $form->parse_html_template('admin/user_migration_done', { 'MEMBERS' => \@member_list });
277 $main::lxdebug->leave_sub();
280 sub create_standard_group_ask {
281 my $form = $main::form;
282 my $locale = $main::locale;
284 $form->{title} = $locale->text('Create a standard group');
287 print $form->parse_html_template("admin/create_standard_group_ask");
290 sub create_standard_group {
291 my $form = $main::form;
292 my $locale = $main::locale;
294 my %members = $main::auth->read_all_users();
296 my $groups = $main::auth->read_groups();
298 foreach my $group (values %{$groups}) {
299 if (($form->{group_id} != $group->{id})
300 && ($form->{name} eq $group->{name})) {
301 $form->show_generic_error($locale->text("A group with that name does already exist."));
306 'name' => $locale->text('Full Access'),
307 'description' => $locale->text('Full access to all functions'),
308 'rights' => { map { $_ => 1 } SL::Auth::all_rights() },
309 'members' => [ map { $_->{id} } values %members ],
312 $main::auth->save_group($group);
314 user_migration_complete(1);
317 sub dont_create_standard_group {
318 user_migration_complete(0);
321 sub user_migration_complete {
322 my $standard_group_created = shift;
324 my $form = $main::form;
325 my $locale = $main::locale;
327 $form->{title} = $locale->text('User migration complete');
330 print $form->parse_html_template('admin/user_migration_complete', { 'standard_group_created' => $standard_group_created });
334 my $form = $main::form;
335 my $locale = $main::locale;
337 my %members = $main::auth->read_all_users();
339 delete $members{"root login"};
341 map { $_->{templates} =~ s|.*/||; } values %members;
343 $form->{title} = "Lx-Office ERP " . $locale->text('Administration');
344 $form->{LOCKED} = -e "$main::userspath/nologin";
345 $form->{MEMBERS} = [ @members{sort { lc $a cmp lc $b } keys %members} ];
348 print $form->parse_html_template("admin/list_users");
352 my $form = $main::form;
353 my $locale = $main::locale;
355 $form->{title} = "Lx-Office ERP " . $locale->text('Administration') . " / " . $locale->text('Add User');
357 # Note: Menu Style 'v3' is not compatible to all browsers!
358 # "menustyle" => "old" sets the HTML Menu to default.
361 "countrycode" => "de",
362 "numberformat" => "1.000,00",
363 "dateformat" => "dd.mm.yy",
364 "stylesheet" => "lx-office-erp.css",
365 "menustyle" => "old",
366 dbport => $::auth->{DB_config}->{port} || 5432,
367 dbuser => $::auth->{DB_config}->{user} || 'lxoffice',
368 dbhost => $::auth->{DB_config}->{host} || 'localhost',
372 edit_user_form($myconfig);
376 my $form = $main::form;
377 my $locale = $main::locale;
379 $form->{title} = "Lx-Office ERP " . $locale->text('Administration') . " / " . $locale->text('Edit User');
382 $form->isblank("login", $locale->text("The login is missing."));
385 my $myconfig = new User($form->{login});
387 # strip basedir from templates directory
388 $myconfig->{templates} =~ s|.*/||;
390 edit_user_form($myconfig);
396 my $form = $main::form;
397 my $locale = $main::locale;
399 my @valid_dateformats = qw(mm-dd-yy mm/dd/yy dd-mm-yy dd/mm/yy dd.mm.yy yyyy-mm-dd);
400 $form->{ALL_DATEFORMATS} = [ map { { "format" => $_, "selected" => $_ eq $myconfig->{dateformat} } } @valid_dateformats ];
402 my @valid_numberformats = ('1,000.00', '1000.00', '1.000,00', '1000,00');
403 $form->{ALL_NUMBERFORMATS} = [ map { { "format" => $_, "selected" => $_ eq $myconfig->{numberformat} } } @valid_numberformats ];
405 my %countrycodes = User->country_codes;
406 $form->{ALL_COUNTRYCODES} = [];
407 foreach my $countrycode (sort { $countrycodes{$a} cmp $countrycodes{$b} } keys %countrycodes) {
408 push @{ $form->{ALL_COUNTRYCODES} }, { "value" => $countrycode,
409 "name" => $countrycodes{$countrycode},
410 "selected" => $countrycode eq $myconfig->{countrycode} };
413 # is there a templates basedir
414 if (!-d "$main::templates") {
415 $form->error(sprintf($locale->text("The directory %s does not exist."), $main::templates));
418 opendir TEMPLATEDIR, "$main::templates/." or $form->error("$main::templates : $ERRNO");
419 my @all = readdir(TEMPLATEDIR);
420 my @alldir = sort grep { -d "$main::templates/$_" && !/^\.\.?$/ } @all;
421 my @allhtml = sort grep { -f "$main::templates/$_" && /\.html$/ } @all;
422 closedir TEMPLATEDIR;
424 @alldir = grep !/\.(html|tex|sty|odt|xml|txb)$/, @alldir;
425 @alldir = grep !/^(webpages|\.svn)$/, @alldir;
427 @allhtml = reverse grep !/Default/, @allhtml;
428 push @allhtml, 'Default';
429 @allhtml = reverse @allhtml;
431 $form->{ALL_TEMPLATES} = [ map { { "name", => $_, "selected" => $_ eq $myconfig->{templates} } } @alldir ];
433 my $lastitem = $allhtml[0];
434 $lastitem =~ s/-.*//g;
435 $form->{ALL_MASTER_TEMPLATES} = [ { "name" => $lastitem, "selected" => $lastitem eq "German" } ];
436 foreach my $item (@allhtml) {
438 next if ($item eq $lastitem);
440 push @{ $form->{ALL_MASTER_TEMPLATES} }, { "name" => $item, "selected" => $item eq "German" };
444 # css dir has styles that are not intended as general layouts.
445 # reverting to hardcoded list
446 $form->{ALL_STYLESHEETS} = [ map { { "name" => $_, "selected" => $_ eq $myconfig->{stylesheet} } } qw(lx-office-erp.css Win2000.css) ];
448 $form->{"menustyle_" . $myconfig->{menustyle} } = 1;
450 map { $form->{"myc_${_}"} = $myconfig->{$_} } keys %{ $myconfig };
455 my $user_id = $main::auth->get_user_id($form->{login});
456 my $all_groups = $main::auth->read_groups();
458 foreach my $group (values %{ $all_groups }) {
459 push @{ $groups }, $group if (grep { $user_id == $_ } @{ $group->{members} });
462 $groups = [ sort { lc $a->{name} cmp lc $b->{name} } @{ $groups } ];
465 $form->{CAN_CHANGE_PASSWORD} = $main::auth->can_change_password();
468 print $form->parse_html_template("admin/edit_user", { 'GROUPS' => $groups });
472 my $form = $main::form;
473 my $locale = $main::locale;
475 $form->{dbdriver} = 'Pg';
477 # no spaces allowed in login name
478 $form->{login} =~ s|\s||g;
479 $form->isblank("login", $locale->text('Login name missing!'));
481 # check for duplicates
482 if (!$form->{edit}) {
483 my %members = $main::auth->read_all_users();
484 if ($members{$form->{login}}) {
485 $form->show_generic_error($locale->text('Another user with the login #1 does already exist.', $form->{login}), 'back_button' => 1);
489 # no spaces allowed in directories
490 ($form->{newtemplates}) = split / /, $form->{newtemplates};
492 if ($form->{newtemplates}) {
493 $form->{templates} = $form->{newtemplates};
496 ($form->{usetemplates}) ? $form->{usetemplates} : $form->{login};
500 if (!-d "$main::templates") {
501 $form->error(sprintf($locale->text("The directory %s does not exist."), $main::templates));
504 # add base directory to $form->{templates}
505 $form->{templates} =~ s|.*/||;
506 $form->{templates} = "$main::templates/$form->{templates}";
508 my $myconfig = new User($form->{login});
510 $form->isblank("dbname", $locale->text('Dataset missing!'));
511 $form->isblank("dbuser", $locale->text('Database User missing!'));
513 foreach my $item (keys %{$form}) {
514 $myconfig->{$item} = $form->{$item};
517 delete $myconfig->{stylesheet};
518 if ($form->{userstylesheet}) {
519 $myconfig->{stylesheet} = $form->{userstylesheet};
522 $myconfig->save_member();
524 $form->{templates} =~ s|.*/||;
525 $form->{templates} = "$main::templates/$form->{templates}";
526 $form->{mastertemplates} =~ s|.*/||;
528 # create user template directory and copy master files
529 if (!-d "$form->{templates}") {
532 if (mkdir "$form->{templates}", oct("771")) {
536 # copy templates to the directory
537 opendir TEMPLATEDIR, "$main::templates/." or $form->error("$main::templates : $ERRNO");
538 my @templates = grep /$form->{mastertemplates}.*?\.(html|tex|sty|odt|xml|txb)$/,
540 closedir TEMPLATEDIR;
542 foreach my $file (@templates) {
543 open(TEMP, "$main::templates/$file")
544 or $form->error("$main::templates/$file : $ERRNO");
546 $file =~ s/\Q$form->{mastertemplates}\E-//;
547 open(NEW, ">$form->{templates}/$file")
548 or $form->error("$form->{templates}/$file : $ERRNO");
550 while (my $line = <TEMP>) {
557 $form->error("$ERRNO: $form->{templates}");
561 # Add new user to his groups.
562 if (ref $form->{new_user_group_ids} eq 'ARRAY') {
563 my $all_groups = $main::auth->read_groups();
564 my %user = $main::auth->read_user($form->{login});
566 foreach my $group_id (@{ $form->{new_user_group_ids} }) {
567 my $group = $all_groups->{$group_id};
571 push @{ $group->{members} }, $user{id};
572 $main::auth->save_group($group);
576 if ($main::auth->can_change_password()
577 && defined $form->{new_password}
578 && ($form->{new_password} ne '********')) {
579 my $verifier = SL::Auth::PasswordPolicy->new;
580 my $result = $verifier->verify($form->{new_password}, 1);
582 if ($result != SL::Auth::PasswordPolicy->OK()) {
583 $form->error($::locale->text('The settings were saved, but the password was not changed.') . ' ' . join(' ', $verifier->errors($result)));
586 $main::auth->change_password($form->{login}, $form->{new_password});
589 $form->redirect($locale->text('User saved!'));
592 sub save_user_as_new {
593 my $form = $main::form;
595 $form->{login} = $form->{new_user_login};
596 delete @{$form}{qw(edit new_user_login)};
602 my $form = $main::form;
603 my $locale = $main::locale;
605 my %members = $main::auth->read_all_users();
606 my $templates = $members{$form->{login}}->{templates};
608 $main::auth->delete_user($form->{login});
611 my $templates_in_use = 0;
613 foreach my $login (keys %members) {
614 next if $form->{login} eq $login;
615 next if $members{$login}->{templates} ne $templates;
616 $templates_in_use = 1;
620 if (!$templates_in_use && -d $templates) {
621 unlink <$templates/*>;
626 $form->redirect($locale->text('User deleted!'));
634 return ($login) ? $login : undef;
640 my ($null, $value) = split(/=/, $line, 2);
643 $value =~ s/\s#.*//g;
645 # remove any trailing whitespace
646 $value =~ s/^\s*(.*?)\s*$/$1/;
651 sub pg_database_administration {
652 my $form = $main::form;
654 $form->{dbdriver} = 'Pg';
659 sub dbselect_source {
660 my $form = $main::form;
661 my $locale = $main::locale;
663 $form->{dbport} = $::auth->{DB_config}->{port} || 5432;
664 $form->{dbuser} = $::auth->{DB_config}->{user} || 'lxoffice';
665 $form->{dbdefault} = 'template1';
666 $form->{dbhost} = $::auth->{DB_config}->{host} || 'localhost';
668 $form->{title} = "Lx-Office ERP / " . $locale->text('Database Administration');
670 # Intentionnaly disabled unless fixed to work with the authentication DB.
671 $form->{ALLOW_DBBACKUP} = 0; # "$pg_dump_exe" ne "DISABLED";
674 print $form->parse_html_template("admin/dbadmin");
677 sub test_db_connection {
678 my $form = $main::form;
679 my $locale = $main::locale;
681 $form->{dbdriver} = 'Pg';
682 User::dbconnect_vars($form, $form->{dbname});
684 my $dbh = DBI->connect($form->{dbconnect}, $form->{dbuser}, $form->{dbpasswd});
686 $form->{connection_ok} = $dbh ? 1 : 0;
687 $form->{errstr} = $DBI::errstr;
689 $dbh->disconnect() if ($dbh);
691 $form->{title} = $locale->text('Database Connection Test');
693 print $form->parse_html_template("admin/test_db_connection");
697 call_sub($main::form->{"nextsub"});
701 my $form = $main::form;
702 my $locale = $main::locale;
704 $form->{title} = "Lx-Office ERP " . $locale->text('Database Administration') . " / " . $locale->text('Update Dataset');
706 my @need_updates = User->dbneedsupdate($form);
707 $form->{NEED_UPDATES} = \@need_updates;
708 $form->{ALL_UPDATED} = !scalar @need_updates;
711 print $form->parse_html_template("admin/update_dataset");
715 my $form = $main::form;
716 my $locale = $main::locale;
718 $form->{stylesheet} = "lx-office-erp.css";
719 $form->{title} = $locale->text("Dataset upgrade");
722 my $rowcount = $form->{rowcount} * 1;
723 my @update_rows = grep { $form->{"update_$_"} } (1 .. $rowcount);
724 $form->{NOTHING_TO_DO} = !scalar @update_rows;
725 my $saved_form = save_form();
729 print $form->parse_html_template("admin/dbupgrade_all_header");
731 foreach my $i (@update_rows) {
732 restore_form($saved_form);
734 map { $form->{$_} = $form->{"${_}_${i}"} } qw(dbname dbdriver dbhost dbport dbuser dbpasswd);
736 print $form->parse_html_template("admin/dbupgrade_header");
738 $form->{dbupdate} = $form->{dbname};
739 $form->{$form->{dbname}} = 1;
741 User->dbupdate($form);
742 User->dbupdate2($form, SL::DBUpgrade2->new(form => $form, dbdriver => $form->{dbdriver})->parse_dbupdate_controls);
744 print $form->parse_html_template("admin/dbupgrade_footer");
747 print $form->parse_html_template("admin/dbupgrade_all_done");
751 my $form = $main::form;
752 my $locale = $main::locale;
754 $form->{dbsources} = join " ", map { "[${_}]" } sort User->dbsources($form);
756 $form->{CHARTS} = [];
758 opendir SQLDIR, "sql/." or $form->error($ERRNO);
759 foreach my $item (sort grep /-chart\.sql\z/, readdir SQLDIR) {
760 next if ($item eq 'Default-chart.sql');
761 $item =~ s/-chart\.sql//;
762 push @{ $form->{CHARTS} }, { "name" => $item,
763 "selected" => $item eq "Germany-DATEV-SKR03EU" };
767 my $default_charset = $main::dbcharset;
768 $default_charset ||= Common::DEFAULT_CHARSET;
770 my $cluster_encoding = User->dbclusterencoding($form);
771 if ($cluster_encoding && ($cluster_encoding =~ m/^(?:UTF-?8|UNICODE)$/i)) {
772 if ($main::dbcharset !~ m/^UTF-?8$/i) {
773 $form->show_generic_error($locale->text('The selected PostgreSQL installation uses UTF-8 as its encoding. ' .
774 'Therefore you have to configure Lx-Office to use UTF-8 as well.'),
778 $form->{FORCE_DBENCODING} = 'UNICODE';
781 $form->{DBENCODINGS} = [];
783 foreach my $encoding (@Common::db_encodings) {
784 push @{ $form->{DBENCODINGS} }, { "dbencoding" => $encoding->{dbencoding},
785 "label" => $encoding->{label},
786 "selected" => $encoding->{charset} eq $default_charset };
790 $form->{title} = "Lx-Office ERP " . $locale->text('Database Administration') . " / " . $locale->text('Create Dataset');
793 print $form->parse_html_template("admin/create_dataset");
797 my $form = $main::form;
798 my $locale = $main::locale;
800 $form->isblank("db", $locale->text('Dataset missing!'));
802 User->dbcreate(\%$form);
804 $form->{title} = "Lx-Office ERP " . $locale->text('Database Administration') . " / " . $locale->text('Create Dataset');
807 print $form->parse_html_template("admin/dbcreate");
811 my $form = $main::form;
812 my $locale = $main::locale;
814 my @dbsources = User->dbsources_unused($form);
815 $form->error($locale->text('Nothing to delete!')) unless @dbsources;
817 $form->{title} = "Lx-Office ERP " . $locale->text('Database Administration') . " / " . $locale->text('Delete Dataset');
818 $form->{DBSOURCES} = [ map { { "name", $_ } } sort @dbsources ];
821 print $form->parse_html_template("admin/delete_dataset");
825 my $form = $main::form;
826 my $locale = $main::locale;
829 $form->error($locale->text('No Dataset selected!'));
832 User->dbdelete(\%$form);
834 $form->{title} = "Lx-Office ERP " . $locale->text('Database Administration') . " / " . $locale->text('Delete Dataset');
836 print $form->parse_html_template("admin/dbdelete");
840 my $form = $main::form;
841 my $locale = $main::locale;
843 $form->{title} = "Lx-Office ERP " . $locale->text('Database Administration') . " / " . $locale->text('Backup Dataset');
845 if ("$main::pg_dump_exe" eq "DISABLED") {
846 $form->error($locale->text('Database backups and restorations are disabled in lx-erp.conf.'));
849 my @dbsources = sort User->dbsources($form);
850 $form->{DATABASES} = [ map { { "dbname" => $_ } } @dbsources ];
851 $form->{NO_DATABASES} = !scalar @dbsources;
853 my $username = getpwuid $UID || "unknown-user";
854 my $hostname = hostname() || "unknown-host";
855 $form->{from} = "Lx-Office Admin <${username}\@${hostname}>";
858 print $form->parse_html_template("admin/backup_dataset");
861 sub backup_dataset_start {
862 my $form = $main::form;
863 my $locale = $main::locale;
865 $form->{title} = "Lx-Office ERP " . $locale->text('Database Administration') . " / " . $locale->text('Backup Dataset');
867 $main::pg_dump_exe ||= "pg_dump";
869 if ("$main::pg_dump_exe" eq "DISABLED") {
870 $form->error($locale->text('Database backups and restorations are disabled in lx-erp.conf.'));
873 $form->isblank("dbname", $locale->text('The dataset name is missing.'));
874 $form->isblank("to", $locale->text('The email address is missing.')) if $form->{destination} eq "email";
876 my $tmpdir = "/tmp/lx_office_backup_" . Common->unique_id();
877 mkdir $tmpdir, 0700 || $form->error($locale->text('A temporary directory could not be created:') . " $ERRNO");
879 my $pgpass = IO::File->new("${tmpdir}/.pgpass", O_WRONLY | O_CREAT, 0600);
883 $form->error($locale->text('A temporary file could not be created:') . " $ERRNO");
886 print $pgpass "$form->{dbhost}:$form->{dbport}:$form->{dbname}:$form->{dbuser}:$form->{dbpasswd}\n";
889 $ENV{HOME} = $tmpdir;
891 my @args = ("-Ft", "-c", "-o", "-h", $form->{dbhost}, "-U", $form->{dbuser});
892 push @args, ("-p", $form->{dbport}) if ($form->{dbport});
893 push @args, $form->{dbname};
895 my $cmd = "$main::pg_dump_exe " . join(" ", map { s/\\/\\\\/g; s/\"/\\\"/g; $_ } @args);
896 my $name = "dataset_backup_$form->{dbname}_" . strftime("%Y%m%d", localtime()) . ".tar";
898 if ($form->{destination} ne "email") {
899 my $in = IO::File->new("$cmd |");
902 unlink "${tmpdir}/.pgpass";
905 $form->error($locale->text('The pg_dump process could not be started.'));
908 print "content-type: application/x-tar\n";
909 print "content-disposition: attachment; filename=\"${name}\"\n\n";
911 while (my $line = <$in>) {
917 unlink "${tmpdir}/.pgpass";
921 my $tmp = $tmpdir . "/dump_" . Common::unique_id();
923 if (system("$cmd > $tmp") != 0) {
924 unlink "${tmpdir}/.pgpass", $tmp;
927 $form->error($locale->text('The pg_dump process could not be started.'));
930 my $mail = new Mailer;
932 map { $mail->{$_} = $form->{$_} } qw(from to cc subject message);
934 $mail->{charset} = $main::dbcharset ? $main::dbcharset : Common::DEFAULT_CHARSET;
935 $mail->{attachments} = [ { "filename" => $tmp, "name" => $name } ];
938 unlink "${tmpdir}/.pgpass", $tmp;
941 $form->{title} = "Lx-Office ERP " . $locale->text('Database Administration') . " / " . $locale->text('Backup Dataset');
944 print $form->parse_html_template("admin/backup_dataset_email_done");
948 sub restore_dataset {
949 my $form = $main::form;
950 my $locale = $main::locale;
952 $form->{title} = "Lx-Office ERP " . $locale->text('Database Administration') . " / " . $locale->text('Restore Dataset');
954 if ("$main::pg_restore_exe" eq "DISABLED") {
955 $form->error($locale->text('Database backups and restorations are disabled in lx-erp.conf.'));
958 my $default_charset = $main::dbcharset;
959 $default_charset ||= Common::DEFAULT_CHARSET;
961 $form->{DBENCODINGS} = [];
963 foreach my $encoding (@Common::db_encodings) {
964 push @{ $form->{DBENCODINGS} }, { "dbencoding" => $encoding->{dbencoding},
965 "label" => $encoding->{label},
966 "selected" => $encoding->{charset} eq $default_charset };
970 print $form->parse_html_template("admin/restore_dataset");
973 sub restore_dataset_start {
974 my $form = $main::form;
975 my $locale = $main::locale;
977 $form->{title} = "Lx-Office ERP " . $locale->text('Database Administration') . " / " . $locale->text('Restore Dataset');
979 $main::pg_restore_exe ||= "pg_restore";
981 if ("$main::pg_restore_exe" eq "DISABLED") {
982 $form->error($locale->text('Database backups and restorations are disabled in lx-erp.conf.'));
985 $form->isblank("new_dbname", $locale->text('The dataset name is missing.'));
986 $form->isblank("content", $locale->text('No backup file has been uploaded.'));
988 # Create temporary directories. Write the backup file contents to a temporary
989 # file. Create a .pgpass file with the username and password for the pg_restore
992 my $tmpdir = "/tmp/lx_office_backup_" . Common->unique_id();
993 mkdir $tmpdir, 0700 || $form->error($locale->text('A temporary directory could not be created:') . " $ERRNO");
995 my $pgpass = IO::File->new("${tmpdir}/.pgpass", O_WRONLY | O_CREAT, 0600);
999 $form->error($locale->text('A temporary file could not be created:') . " $ERRNO");
1002 print $pgpass "$form->{dbhost}:$form->{dbport}:$form->{new_dbname}:$form->{dbuser}:$form->{dbpasswd}\n";
1005 $ENV{HOME} = $tmpdir;
1007 my $tmp = $tmpdir . "/dump_" . Common::unique_id();
1010 if (substr($form->{content}, 0, 2) eq "\037\213") {
1011 $tmpfile = IO::File->new("| gzip -d > $tmp");
1015 $tmpfile = IO::File->new($tmp, O_WRONLY | O_CREAT | O_BINARY, 0600);
1019 unlink "${tmpdir}/.pgpass";
1022 $form->error($locale->text('A temporary file could not be created:') . " $ERRNO");
1025 print $tmpfile $form->{content};
1028 delete $form->{content};
1030 # Try to connect to the database. Find out if a database with the same name exists.
1031 # If yes, then drop the existing database. Create a new one with the name and encoding
1032 # given by the user.
1034 User::dbconnect_vars($form, "template1");
1036 my %myconfig = map { $_ => $form->{$_} } grep /^db/, keys %{ $form };
1037 my $dbh = $form->dbconnect(\%myconfig) || $form->dberror();
1041 $form->{new_dbname} =~ s|[^a-zA-Z0-9_\-]||g;
1043 $query = qq|SELECT COUNT(*) FROM pg_database WHERE datname = ?|;
1044 my ($count) = selectrow_query($form, $dbh, $query, $form->{new_dbname});
1046 do_query($form, $dbh, qq|DROP DATABASE $form->{new_dbname}|);
1050 foreach my $item (@Common::db_encodings) {
1051 if ($item->{dbencoding} eq $form->{dbencoding}) {
1056 $form->{dbencoding} = "LATIN9" unless $form->{dbencoding};
1058 do_query($form, $dbh, qq|CREATE DATABASE $form->{new_dbname} ENCODING ? TEMPLATE template0|, $form->{dbencoding});
1062 # Spawn pg_restore on the temporary file.
1064 my @args = ("-h", $form->{dbhost}, "-U", $form->{dbuser}, "-d", $form->{new_dbname});
1065 push @args, ("-p", $form->{dbport}) if ($form->{dbport});
1068 my $cmd = "$main::pg_restore_exe " . join(" ", map { s/\\/\\\\/g; s/\"/\\\"/g; $_ } @args);
1070 my $in = IO::File->new("$cmd 2>&1 |");
1073 unlink "${tmpdir}/.pgpass", $tmp;
1076 $form->error($locale->text('The pg_restore process could not be started.'));
1079 $English::AUTOFLUSH = 1;
1082 print $form->parse_html_template("admin/restore_dataset_start_header");
1084 while (my $line = <$in>) {
1089 $form->{retval} = $CHILD_ERROR >> 8;
1090 print $form->parse_html_template("admin/restore_dataset_start_footer");
1092 unlink "${tmpdir}/.pgpass", $tmp;
1097 my $form = $main::form;
1098 my $locale = $main::locale;
1100 unlink "$main::userspath/nologin";
1102 $form->{callback} = "admin.pl?action=list_users";
1104 $form->redirect($locale->text('Lockfile removed!'));
1109 my $form = $main::form;
1110 my $locale = $main::locale;
1112 open(FH, ">$main::userspath/nologin")
1113 or $form->error($locale->text('Cannot create Lock!'));
1116 $form->{callback} = "admin.pl?action=list_users";
1118 $form->redirect($locale->text('Lockfile created!'));
1123 call_sub($main::form->{yes_nextsub});
1127 call_sub($main::form->{no_nextsub});
1131 call_sub($main::form->{add_nextsub});
1135 my $form = $main::form;
1137 $form->{edit_nextsub} ||= 'edit_user';
1139 call_sub($form->{edit_nextsub});
1143 my $form = $main::form;
1145 $form->{delete_nextsub} ||= 'delete_user';
1147 call_sub($form->{delete_nextsub});
1151 my $form = $main::form;
1153 $form->{save_nextsub} ||= 'save_user';
1155 call_sub($form->{save_nextsub});
1159 call_sub($main::form->{back_nextsub});
1163 my $form = $main::form;
1164 my $locale = $main::locale;
1166 foreach my $action (qw(create_standard_group dont_create_standard_group
1167 save_user delete_user save_user_as_new)) {
1168 if ($form->{"action_${action}"}) {
1174 call_sub($form->{default_action}) if ($form->{default_action});
1176 $form->error($locale->text('No action defined.'));
1179 sub _apply_dbupgrade_scripts {
1180 ::end_of_request() if SL::DBUpgrade2->new(form => $::form, dbdriver => 'Pg', auth => 1)->apply_admin_dbupgrade_scripts(1);