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);
54 require "bin/mozilla/common.pl";
55 require "bin/mozilla/admin_groups.pl";
56 require "bin/mozilla/admin_printer.pl";
66 $::lxdebug->enter_sub;
67 my $session_result = shift;
74 $::auth->set_session_value('rpw', $::form->{rpw}) if $session_result == SL::Auth->SESSION_OK;
76 $form->{stylesheet} = "lx-office-erp.css";
77 $form->{favicon} = "favicon.ico";
79 if ($form->{action}) {
80 if ($auth->authenticate_root($form->{rpw}, 0) != $auth->OK()) {
81 $form->{error_message} = $locale->text('Incorrect Password!');
84 if ($auth->session_tables_present()) {
85 $::auth->set_session_value('rpw', $::form->{rpw});
86 $::auth->create_or_refresh_session();
87 _apply_dbupgrade_scripts();
90 call_sub($locale->findsub($form->{action}));
93 # if there are no drivers bail out
94 $form->error($locale->text('No Database Drivers available!'))
95 unless (User->dbdrivers);
99 $::lxdebug->leave_sub;
103 my $form = $main::form;
104 my $locale = $main::locale;
106 $form->{title} = qq|Lx-Office ERP $form->{version} | . $locale->text('Administration');
109 print $form->parse_html_template('admin/adminlogin');
113 check_auth_db_and_tables();
118 $main::auth->destroy_session();
122 sub check_auth_db_and_tables {
123 my $form = $main::form;
124 my $locale = $main::locale;
128 map { $params{"db_${_}"} = $main::auth->{DB_config}->{$_} } keys %{ $auth->{DB_config} };
130 if (!$main::auth->check_database()) {
131 $form->{title} = $locale->text('Authentification database creation');
133 print $form->parse_html_template('admin/check_auth_database', \%params);
138 if (!$main::auth->check_tables()) {
139 $form->{title} = $locale->text('Authentification tables creation');
141 print $form->parse_html_template('admin/check_auth_tables', \%params);
146 if (-f $main::memberfile) {
149 if ($main::memberfile =~ m|^.*/|) {
153 my $backupdir = "${memberdir}member-file-migration";
155 $form->{title} = $locale->text('User data migration');
157 print $form->parse_html_template('admin/user_migration', { 'memberfile' => $main::memberfile,
158 'backupdir' => $backupdir });
165 my $form = $main::form;
167 $main::auth->create_database('superuser' => $form->{db_superuser},
168 'superuser_password' => $form->{db_superuser_password},
169 'template' => $form->{db_template});
173 sub create_auth_tables {
174 my $form = $main::form;
175 my $locale = $main::locale;
177 $main::auth->create_tables();
178 $main::auth->set_session_value('rpw', $form->{rpw});
179 $main::auth->create_or_refresh_session();
181 if (!-f $main::memberfile) {
182 # New installation -- create a standard group with full access
185 'name' => $locale->text('Full Access'),
186 'description' => $locale->text('Full access to all functions'),
187 'rights' => { map { $_ => 1 } SL::Auth::all_rights() },
188 'members' => [ map { $_->{id} } values %members ],
191 $main::auth->save_group($group);
194 _apply_dbupgrade_scripts();
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 if ($main::auth->can_change_password()
525 && defined $form->{new_password}
526 && ($form->{new_password} ne '********')) {
527 $main::auth->change_password($form->{login}, $form->{new_password});
530 $form->{templates} =~ s|.*/||;
531 $form->{templates} = "$main::templates/$form->{templates}";
532 $form->{mastertemplates} =~ s|.*/||;
534 # create user template directory and copy master files
535 if (!-d "$form->{templates}") {
538 if (mkdir "$form->{templates}", oct("771")) {
542 # copy templates to the directory
543 opendir TEMPLATEDIR, "$main::templates/." or $form->error("$main::templates : $ERRNO");
544 my @templates = grep /$form->{mastertemplates}.*?\.(html|tex|sty|odt|xml|txb)$/,
546 closedir TEMPLATEDIR;
548 foreach my $file (@templates) {
549 open(TEMP, "$main::templates/$file")
550 or $form->error("$main::templates/$file : $ERRNO");
552 $file =~ s/\Q$form->{mastertemplates}\E-//;
553 open(NEW, ">$form->{templates}/$file")
554 or $form->error("$form->{templates}/$file : $ERRNO");
556 while (my $line = <TEMP>) {
563 $form->error("$ERRNO: $form->{templates}");
567 # Add new user to his groups.
568 if (ref $form->{new_user_group_ids} eq 'ARRAY') {
569 my $all_groups = $main::auth->read_groups();
570 my %user = $main::auth->read_user($form->{login});
572 foreach my $group_id (@{ $form->{new_user_group_ids} }) {
573 my $group = $all_groups->{$group_id};
577 push @{ $group->{members} }, $user{id};
578 $main::auth->save_group($group);
582 $form->redirect($locale->text('User saved!'));
586 sub save_user_as_new {
587 my $form = $main::form;
589 $form->{login} = $form->{new_user_login};
590 delete @{$form}{qw(edit new_user_login)};
596 my $form = $main::form;
597 my $locale = $main::locale;
599 my %members = $main::auth->read_all_users();
600 my $templates = $members{$form->{login}}->{templates};
602 $main::auth->delete_user($form->{login});
605 my $templates_in_use = 0;
607 foreach my $login (keys %members) {
608 next if $form->{login} eq $login;
609 next if $members{$login}->{templates} ne $templates;
610 $templates_in_use = 1;
614 if (!$templates_in_use && -d $templates) {
615 unlink <$templates/*>;
620 $form->redirect($locale->text('User deleted!'));
628 return ($login) ? $login : undef;
634 my ($null, $value) = split(/=/, $line, 2);
637 $value =~ s/\s#.*//g;
639 # remove any trailing whitespace
640 $value =~ s/^\s*(.*?)\s*$/$1/;
645 sub pg_database_administration {
646 my $form = $main::form;
648 $form->{dbdriver} = 'Pg';
653 sub dbselect_source {
654 my $form = $main::form;
655 my $locale = $main::locale;
657 $form->{dbport} = $::auth->{DB_config}->{port} || 5432;
658 $form->{dbuser} = $::auth->{DB_config}->{user} || 'lxoffice';
659 $form->{dbdefault} = 'template1';
660 $form->{dbhost} = $::auth->{DB_config}->{host} || 'localhost';
662 $form->{title} = "Lx-Office ERP / " . $locale->text('Database Administration');
664 # Intentionnaly disabled unless fixed to work with the authentication DB.
665 $form->{ALLOW_DBBACKUP} = 0; # "$pg_dump_exe" ne "DISABLED";
668 print $form->parse_html_template("admin/dbadmin");
671 sub test_db_connection {
672 my $form = $main::form;
673 my $locale = $main::locale;
675 $form->{dbdriver} = 'Pg';
676 User::dbconnect_vars($form, $form->{dbname});
678 my $dbh = DBI->connect($form->{dbconnect}, $form->{dbuser}, $form->{dbpasswd});
680 $form->{connection_ok} = $dbh ? 1 : 0;
681 $form->{errstr} = $DBI::errstr;
683 $dbh->disconnect() if ($dbh);
685 $form->{title} = $locale->text('Database Connection Test');
687 print $form->parse_html_template("admin/test_db_connection");
691 call_sub($main::form->{"nextsub"});
695 my $form = $main::form;
696 my $locale = $main::locale;
698 $form->{title} = "Lx-Office ERP " . $locale->text('Database Administration') . " / " . $locale->text('Update Dataset');
700 my @need_updates = User->dbneedsupdate($form);
701 $form->{NEED_UPDATES} = \@need_updates;
702 $form->{ALL_UPDATED} = !scalar @need_updates;
705 print $form->parse_html_template("admin/update_dataset");
709 my $form = $main::form;
710 my $locale = $main::locale;
712 $form->{stylesheet} = "lx-office-erp.css";
713 $form->{title} = $locale->text("Dataset upgrade");
716 my $rowcount = $form->{rowcount} * 1;
717 my @update_rows = grep { $form->{"update_$_"} } (1 .. $rowcount);
718 $form->{NOTHING_TO_DO} = !scalar @update_rows;
719 my $saved_form = save_form();
723 print $form->parse_html_template("admin/dbupgrade_all_header");
725 foreach my $i (@update_rows) {
726 restore_form($saved_form);
728 map { $form->{$_} = $form->{"${_}_${i}"} } qw(dbname dbdriver dbhost dbport dbuser dbpasswd);
730 print $form->parse_html_template("admin/dbupgrade_header");
732 $form->{dbupdate} = $form->{dbname};
733 $form->{$form->{dbname}} = 1;
735 User->dbupdate($form);
736 User->dbupdate2($form, SL::DBUpgrade2->new(form => $form, dbdriver => $form->{dbdriver})->parse_dbupdate_controls);
738 print $form->parse_html_template("admin/dbupgrade_footer");
741 print $form->parse_html_template("admin/dbupgrade_all_done");
745 my $form = $main::form;
746 my $locale = $main::locale;
748 $form->{dbsources} = join " ", map { "[${_}]" } sort User->dbsources($form);
750 $form->{CHARTS} = [];
752 opendir SQLDIR, "sql/." or $form->error($ERRNO);
753 foreach my $item (sort grep /-chart\.sql\z/, readdir SQLDIR) {
754 next if ($item eq 'Default-chart.sql');
755 $item =~ s/-chart\.sql//;
756 push @{ $form->{CHARTS} }, { "name" => $item,
757 "selected" => $item eq "Germany-DATEV-SKR03EU" };
761 my $default_charset = $main::dbcharset;
762 $default_charset ||= Common::DEFAULT_CHARSET;
764 my $cluster_encoding = User->dbclusterencoding($form);
765 if ($cluster_encoding && ($cluster_encoding =~ m/^(?:UTF-?8|UNICODE)$/i)) {
766 if ($main::dbcharset !~ m/^UTF-?8$/i) {
767 $form->show_generic_error($locale->text('The selected PostgreSQL installation uses UTF-8 as its encoding. ' .
768 'Therefore you have to configure Lx-Office to use UTF-8 as well.'),
772 $form->{FORCE_DBENCODING} = 'UNICODE';
775 $form->{DBENCODINGS} = [];
777 foreach my $encoding (@Common::db_encodings) {
778 push @{ $form->{DBENCODINGS} }, { "dbencoding" => $encoding->{dbencoding},
779 "label" => $encoding->{label},
780 "selected" => $encoding->{charset} eq $default_charset };
784 $form->{title} = "Lx-Office ERP " . $locale->text('Database Administration') . " / " . $locale->text('Create Dataset');
787 print $form->parse_html_template("admin/create_dataset");
791 my $form = $main::form;
792 my $locale = $main::locale;
794 $form->isblank("db", $locale->text('Dataset missing!'));
796 User->dbcreate(\%$form);
798 $form->{title} = "Lx-Office ERP " . $locale->text('Database Administration') . " / " . $locale->text('Create Dataset');
801 print $form->parse_html_template("admin/dbcreate");
805 my $form = $main::form;
806 my $locale = $main::locale;
808 my @dbsources = User->dbsources_unused($form);
809 $form->error($locale->text('Nothing to delete!')) unless @dbsources;
811 $form->{title} = "Lx-Office ERP " . $locale->text('Database Administration') . " / " . $locale->text('Delete Dataset');
812 $form->{DBSOURCES} = [ map { { "name", $_ } } sort @dbsources ];
815 print $form->parse_html_template("admin/delete_dataset");
819 my $form = $main::form;
820 my $locale = $main::locale;
823 $form->error($locale->text('No Dataset selected!'));
826 User->dbdelete(\%$form);
828 $form->{title} = "Lx-Office ERP " . $locale->text('Database Administration') . " / " . $locale->text('Delete Dataset');
830 print $form->parse_html_template("admin/dbdelete");
834 my $form = $main::form;
835 my $locale = $main::locale;
837 $form->{title} = "Lx-Office ERP " . $locale->text('Database Administration') . " / " . $locale->text('Backup Dataset');
839 if ("$main::pg_dump_exe" eq "DISABLED") {
840 $form->error($locale->text('Database backups and restorations are disabled in lx-erp.conf.'));
843 my @dbsources = sort User->dbsources($form);
844 $form->{DATABASES} = [ map { { "dbname" => $_ } } @dbsources ];
845 $form->{NO_DATABASES} = !scalar @dbsources;
847 my $username = getpwuid $UID || "unknown-user";
848 my $hostname = hostname() || "unknown-host";
849 $form->{from} = "Lx-Office Admin <${username}\@${hostname}>";
852 print $form->parse_html_template("admin/backup_dataset");
855 sub backup_dataset_start {
856 my $form = $main::form;
857 my $locale = $main::locale;
859 $form->{title} = "Lx-Office ERP " . $locale->text('Database Administration') . " / " . $locale->text('Backup Dataset');
861 $main::pg_dump_exe ||= "pg_dump";
863 if ("$main::pg_dump_exe" eq "DISABLED") {
864 $form->error($locale->text('Database backups and restorations are disabled in lx-erp.conf.'));
867 $form->isblank("dbname", $locale->text('The dataset name is missing.'));
868 $form->isblank("to", $locale->text('The email address is missing.')) if $form->{destination} eq "email";
870 my $tmpdir = "/tmp/lx_office_backup_" . Common->unique_id();
871 mkdir $tmpdir, 0700 || $form->error($locale->text('A temporary directory could not be created:') . " $ERRNO");
873 my $pgpass = IO::File->new("${tmpdir}/.pgpass", O_WRONLY | O_CREAT, 0600);
877 $form->error($locale->text('A temporary file could not be created:') . " $ERRNO");
880 print $pgpass "$form->{dbhost}:$form->{dbport}:$form->{dbname}:$form->{dbuser}:$form->{dbpasswd}\n";
883 $ENV{HOME} = $tmpdir;
885 my @args = ("-Ft", "-c", "-o", "-h", $form->{dbhost}, "-U", $form->{dbuser});
886 push @args, ("-p", $form->{dbport}) if ($form->{dbport});
887 push @args, $form->{dbname};
889 my $cmd = "$main::pg_dump_exe " . join(" ", map { s/\\/\\\\/g; s/\"/\\\"/g; $_ } @args);
890 my $name = "dataset_backup_$form->{dbname}_" . strftime("%Y%m%d", localtime()) . ".tar";
892 if ($form->{destination} ne "email") {
893 my $in = IO::File->new("$cmd |");
896 unlink "${tmpdir}/.pgpass";
899 $form->error($locale->text('The pg_dump process could not be started.'));
902 print "content-type: application/x-tar\n";
903 print "content-disposition: attachment; filename=\"${name}\"\n\n";
905 while (my $line = <$in>) {
911 unlink "${tmpdir}/.pgpass";
915 my $tmp = $tmpdir . "/dump_" . Common::unique_id();
917 if (system("$cmd > $tmp") != 0) {
918 unlink "${tmpdir}/.pgpass", $tmp;
921 $form->error($locale->text('The pg_dump process could not be started.'));
924 my $mail = new Mailer;
926 map { $mail->{$_} = $form->{$_} } qw(from to cc subject message);
928 $mail->{charset} = $main::dbcharset ? $main::dbcharset : Common::DEFAULT_CHARSET;
929 $mail->{attachments} = [ { "filename" => $tmp, "name" => $name } ];
932 unlink "${tmpdir}/.pgpass", $tmp;
935 $form->{title} = "Lx-Office ERP " . $locale->text('Database Administration') . " / " . $locale->text('Backup Dataset');
938 print $form->parse_html_template("admin/backup_dataset_email_done");
942 sub restore_dataset {
943 my $form = $main::form;
944 my $locale = $main::locale;
946 $form->{title} = "Lx-Office ERP " . $locale->text('Database Administration') . " / " . $locale->text('Restore Dataset');
948 if ("$main::pg_restore_exe" eq "DISABLED") {
949 $form->error($locale->text('Database backups and restorations are disabled in lx-erp.conf.'));
952 my $default_charset = $main::dbcharset;
953 $default_charset ||= Common::DEFAULT_CHARSET;
955 $form->{DBENCODINGS} = [];
957 foreach my $encoding (@Common::db_encodings) {
958 push @{ $form->{DBENCODINGS} }, { "dbencoding" => $encoding->{dbencoding},
959 "label" => $encoding->{label},
960 "selected" => $encoding->{charset} eq $default_charset };
964 print $form->parse_html_template("admin/restore_dataset");
967 sub restore_dataset_start {
968 my $form = $main::form;
969 my $locale = $main::locale;
971 $form->{title} = "Lx-Office ERP " . $locale->text('Database Administration') . " / " . $locale->text('Restore Dataset');
973 $main::pg_restore_exe ||= "pg_restore";
975 if ("$main::pg_restore_exe" eq "DISABLED") {
976 $form->error($locale->text('Database backups and restorations are disabled in lx-erp.conf.'));
979 $form->isblank("new_dbname", $locale->text('The dataset name is missing.'));
980 $form->isblank("content", $locale->text('No backup file has been uploaded.'));
982 # Create temporary directories. Write the backup file contents to a temporary
983 # file. Create a .pgpass file with the username and password for the pg_restore
986 my $tmpdir = "/tmp/lx_office_backup_" . Common->unique_id();
987 mkdir $tmpdir, 0700 || $form->error($locale->text('A temporary directory could not be created:') . " $ERRNO");
989 my $pgpass = IO::File->new("${tmpdir}/.pgpass", O_WRONLY | O_CREAT, 0600);
993 $form->error($locale->text('A temporary file could not be created:') . " $ERRNO");
996 print $pgpass "$form->{dbhost}:$form->{dbport}:$form->{new_dbname}:$form->{dbuser}:$form->{dbpasswd}\n";
999 $ENV{HOME} = $tmpdir;
1001 my $tmp = $tmpdir . "/dump_" . Common::unique_id();
1004 if (substr($form->{content}, 0, 2) eq "\037\213") {
1005 $tmpfile = IO::File->new("| gzip -d > $tmp");
1009 $tmpfile = IO::File->new($tmp, O_WRONLY | O_CREAT | O_BINARY, 0600);
1013 unlink "${tmpdir}/.pgpass";
1016 $form->error($locale->text('A temporary file could not be created:') . " $ERRNO");
1019 print $tmpfile $form->{content};
1022 delete $form->{content};
1024 # Try to connect to the database. Find out if a database with the same name exists.
1025 # If yes, then drop the existing database. Create a new one with the name and encoding
1026 # given by the user.
1028 User::dbconnect_vars($form, "template1");
1030 my %myconfig = map { $_ => $form->{$_} } grep /^db/, keys %{ $form };
1031 my $dbh = $form->dbconnect(\%myconfig) || $form->dberror();
1035 $form->{new_dbname} =~ s|[^a-zA-Z0-9_\-]||g;
1037 $query = qq|SELECT COUNT(*) FROM pg_database WHERE datname = ?|;
1038 my ($count) = selectrow_query($form, $dbh, $query, $form->{new_dbname});
1040 do_query($form, $dbh, qq|DROP DATABASE $form->{new_dbname}|);
1044 foreach my $item (@Common::db_encodings) {
1045 if ($item->{dbencoding} eq $form->{dbencoding}) {
1050 $form->{dbencoding} = "LATIN9" unless $form->{dbencoding};
1052 do_query($form, $dbh, qq|CREATE DATABASE $form->{new_dbname} ENCODING ? TEMPLATE template0|, $form->{dbencoding});
1056 # Spawn pg_restore on the temporary file.
1058 my @args = ("-h", $form->{dbhost}, "-U", $form->{dbuser}, "-d", $form->{new_dbname});
1059 push @args, ("-p", $form->{dbport}) if ($form->{dbport});
1062 my $cmd = "$main::pg_restore_exe " . join(" ", map { s/\\/\\\\/g; s/\"/\\\"/g; $_ } @args);
1064 my $in = IO::File->new("$cmd 2>&1 |");
1067 unlink "${tmpdir}/.pgpass", $tmp;
1070 $form->error($locale->text('The pg_restore process could not be started.'));
1073 $English::AUTOFLUSH = 1;
1076 print $form->parse_html_template("admin/restore_dataset_start_header");
1078 while (my $line = <$in>) {
1083 $form->{retval} = $CHILD_ERROR >> 8;
1084 print $form->parse_html_template("admin/restore_dataset_start_footer");
1086 unlink "${tmpdir}/.pgpass", $tmp;
1091 my $form = $main::form;
1092 my $locale = $main::locale;
1094 unlink "$main::userspath/nologin";
1096 $form->{callback} = "admin.pl?action=list_users";
1098 $form->redirect($locale->text('Lockfile removed!'));
1103 my $form = $main::form;
1104 my $locale = $main::locale;
1106 open(FH, ">$main::userspath/nologin")
1107 or $form->error($locale->text('Cannot create Lock!'));
1110 $form->{callback} = "admin.pl?action=list_users";
1112 $form->redirect($locale->text('Lockfile created!'));
1117 call_sub($main::form->{yes_nextsub});
1121 call_sub($main::form->{no_nextsub});
1125 call_sub($main::form->{add_nextsub});
1129 my $form = $main::form;
1131 $form->{edit_nextsub} ||= 'edit_user';
1133 call_sub($form->{edit_nextsub});
1137 my $form = $main::form;
1139 $form->{delete_nextsub} ||= 'delete_user';
1141 call_sub($form->{delete_nextsub});
1145 my $form = $main::form;
1147 $form->{save_nextsub} ||= 'save_user';
1149 call_sub($form->{save_nextsub});
1153 call_sub($main::form->{back_nextsub});
1157 my $form = $main::form;
1158 my $locale = $main::locale;
1160 foreach my $action (qw(create_standard_group dont_create_standard_group
1161 save_user delete_user save_user_as_new)) {
1162 if ($form->{"action_${action}"}) {
1168 call_sub($form->{default_action}) if ($form->{default_action});
1170 $form->error($locale->text('No action defined.'));
1173 sub _apply_dbupgrade_scripts {
1174 ::end_of_request() if SL::DBUpgrade2->new(form => $::form, dbdriver => 'Pg', auth => 1)->apply_admin_dbupgrade_scripts(1);