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);
198 $main::lxdebug->enter_sub();
200 my $form = $main::form;
201 my $locale = $main::locale;
205 if ($main::memberfile =~ m|^.*/|) {
209 my $backupdir = "${memberdir}member-file-migration";
211 if (! -d $backupdir && !mkdir $backupdir, 0700) {
212 $form->error(sprintf($locale->text('The directory "%s" could not be created:\n%s'), $backupdir, $!));
215 copy $main::memberfile, "users/member-file-migration/members";
217 my $in = IO::File->new($main::memberfile, "r");
219 $form->error($locale->text('Could not open the old memberfile.')) if (!$in);
221 my (%members, $login);
230 $login =~ s/(\[|\])//g;
234 $members{$login} = { "login" => $login };
238 if ($login && m/=/) {
239 my ($key, $value) = split m/\s*=\s*/, $_, 2;
244 $value =~ s|\\n|\n|g;
246 $members{$login}->{$key} = $value;
252 delete $members{"root login"};
254 map { $_->{dbpasswd} = unpack 'u', $_->{dbpasswd} } values %members;
256 while (my ($login, $params) = each %members) {
257 $main::auth->save_user($login, %{ $params });
258 $main::auth->change_password($login, $params->{password}, 1);
260 my $conf_file = "${memberdir}${login}.conf";
263 copy $conf_file, "${backupdir}/${login}.conf";
268 unlink $main::memberfile;
270 my @member_list = sort { lc $a->{login} cmp lc $b->{login} } values %members;
272 $form->{title} = $locale->text('User data migration');
274 print $form->parse_html_template('admin/user_migration_done', { 'MEMBERS' => \@member_list });
276 $main::lxdebug->leave_sub();
279 sub create_standard_group_ask {
280 my $form = $main::form;
281 my $locale = $main::locale;
283 $form->{title} = $locale->text('Create a standard group');
286 print $form->parse_html_template("admin/create_standard_group_ask");
289 sub create_standard_group {
290 my $form = $main::form;
291 my $locale = $main::locale;
293 my %members = $main::auth->read_all_users();
295 my $groups = $main::auth->read_groups();
297 foreach my $group (values %{$groups}) {
298 if (($form->{group_id} != $group->{id})
299 && ($form->{name} eq $group->{name})) {
300 $form->show_generic_error($locale->text("A group with that name does already exist."));
305 'name' => $locale->text('Full Access'),
306 'description' => $locale->text('Full access to all functions'),
307 'rights' => { map { $_ => 1 } SL::Auth::all_rights() },
308 'members' => [ map { $_->{id} } values %members ],
311 $main::auth->save_group($group);
313 user_migration_complete(1);
316 sub dont_create_standard_group {
317 user_migration_complete(0);
320 sub user_migration_complete {
321 my $standard_group_created = shift;
323 my $form = $main::form;
324 my $locale = $main::locale;
326 $form->{title} = $locale->text('User migration complete');
329 print $form->parse_html_template('admin/user_migration_complete', { 'standard_group_created' => $standard_group_created });
333 my $form = $main::form;
334 my $locale = $main::locale;
336 my %members = $main::auth->read_all_users();
338 delete $members{"root login"};
340 map { $_->{templates} =~ s|.*/||; } values %members;
342 $form->{title} = "Lx-Office ERP " . $locale->text('Administration');
343 $form->{LOCKED} = -e "$main::userspath/nologin";
344 $form->{MEMBERS} = [ @members{sort { lc $a cmp lc $b } keys %members} ];
347 print $form->parse_html_template("admin/list_users");
351 my $form = $main::form;
352 my $locale = $main::locale;
354 $form->{title} = "Lx-Office ERP " . $locale->text('Administration') . " / " . $locale->text('Add User');
356 # Note: Menu Style 'v3' is not compatible to all browsers!
357 # "menustyle" => "old" sets the HTML Menu to default.
360 "countrycode" => "de",
361 "numberformat" => "1.000,00",
362 "dateformat" => "dd.mm.yy",
363 "stylesheet" => "lx-office-erp.css",
364 "menustyle" => "old",
365 dbport => $::auth->{DB_config}->{port} || 5432,
366 dbuser => $::auth->{DB_config}->{user} || 'lxoffice',
367 dbhost => $::auth->{DB_config}->{host} || 'localhost',
371 edit_user_form($myconfig);
375 my $form = $main::form;
376 my $locale = $main::locale;
378 $form->{title} = "Lx-Office ERP " . $locale->text('Administration') . " / " . $locale->text('Edit User');
381 $form->isblank("login", $locale->text("The login is missing."));
384 my $myconfig = new User($form->{login});
386 # strip basedir from templates directory
387 $myconfig->{templates} =~ s|.*/||;
389 edit_user_form($myconfig);
395 my $form = $main::form;
396 my $locale = $main::locale;
398 my @valid_dateformats = qw(mm-dd-yy mm/dd/yy dd-mm-yy dd/mm/yy dd.mm.yy yyyy-mm-dd);
399 $form->{ALL_DATEFORMATS} = [ map { { "format" => $_, "selected" => $_ eq $myconfig->{dateformat} } } @valid_dateformats ];
401 my @valid_numberformats = ('1,000.00', '1000.00', '1.000,00', '1000,00');
402 $form->{ALL_NUMBERFORMATS} = [ map { { "format" => $_, "selected" => $_ eq $myconfig->{numberformat} } } @valid_numberformats ];
404 my %countrycodes = User->country_codes;
405 $form->{ALL_COUNTRYCODES} = [];
406 foreach my $countrycode (sort { $countrycodes{$a} cmp $countrycodes{$b} } keys %countrycodes) {
407 push @{ $form->{ALL_COUNTRYCODES} }, { "value" => $countrycode,
408 "name" => $countrycodes{$countrycode},
409 "selected" => $countrycode eq $myconfig->{countrycode} };
412 # is there a templates basedir
413 if (!-d "$main::templates") {
414 $form->error(sprintf($locale->text("The directory %s does not exist."), $main::templates));
417 opendir TEMPLATEDIR, "$main::templates/." or $form->error("$main::templates : $ERRNO");
418 my @all = readdir(TEMPLATEDIR);
419 my @alldir = sort grep { -d "$main::templates/$_" && !/^\.\.?$/ } @all;
420 my @allhtml = sort grep { -f "$main::templates/$_" && /\.html$/ } @all;
421 closedir TEMPLATEDIR;
423 @alldir = grep !/\.(html|tex|sty|odt|xml|txb)$/, @alldir;
424 @alldir = grep !/^(webpages|\.svn)$/, @alldir;
426 @allhtml = reverse grep !/Default/, @allhtml;
427 push @allhtml, 'Default';
428 @allhtml = reverse @allhtml;
430 $form->{ALL_TEMPLATES} = [ map { { "name", => $_, "selected" => $_ eq $myconfig->{templates} } } @alldir ];
432 my $lastitem = $allhtml[0];
433 $lastitem =~ s/-.*//g;
434 $form->{ALL_MASTER_TEMPLATES} = [ { "name" => $lastitem, "selected" => $lastitem eq "German" } ];
435 foreach my $item (@allhtml) {
437 next if ($item eq $lastitem);
439 push @{ $form->{ALL_MASTER_TEMPLATES} }, { "name" => $item, "selected" => $item eq "German" };
443 # css dir has styles that are not intended as general layouts.
444 # reverting to hardcoded list
445 $form->{ALL_STYLESHEETS} = [ map { { "name" => $_, "selected" => $_ eq $myconfig->{stylesheet} } } qw(lx-office-erp.css Win2000.css) ];
447 $form->{"menustyle_" . $myconfig->{menustyle} } = 1;
449 map { $form->{"myc_${_}"} = $myconfig->{$_} } keys %{ $myconfig };
454 my $user_id = $main::auth->get_user_id($form->{login});
455 my $all_groups = $main::auth->read_groups();
457 foreach my $group (values %{ $all_groups }) {
458 push @{ $groups }, $group if (grep { $user_id == $_ } @{ $group->{members} });
461 $groups = [ sort { lc $a->{name} cmp lc $b->{name} } @{ $groups } ];
464 $form->{CAN_CHANGE_PASSWORD} = $main::auth->can_change_password();
467 print $form->parse_html_template("admin/edit_user", { 'GROUPS' => $groups });
471 my $form = $main::form;
472 my $locale = $main::locale;
474 $form->{dbdriver} = 'Pg';
476 # no spaces allowed in login name
477 $form->{login} =~ s|\s||g;
478 $form->isblank("login", $locale->text('Login name missing!'));
480 # check for duplicates
481 if (!$form->{edit}) {
482 my %members = $main::auth->read_all_users();
483 if ($members{$form->{login}}) {
484 $form->show_generic_error($locale->text('Another user with the login #1 does already exist.', $form->{login}), 'back_button' => 1);
488 # no spaces allowed in directories
489 ($form->{newtemplates}) = split / /, $form->{newtemplates};
491 if ($form->{newtemplates}) {
492 $form->{templates} = $form->{newtemplates};
495 ($form->{usetemplates}) ? $form->{usetemplates} : $form->{login};
499 if (!-d "$main::templates") {
500 $form->error(sprintf($locale->text("The directory %s does not exist."), $main::templates));
503 # add base directory to $form->{templates}
504 $form->{templates} =~ s|.*/||;
505 $form->{templates} = "$main::templates/$form->{templates}";
507 my $myconfig = new User($form->{login});
509 $form->isblank("dbname", $locale->text('Dataset missing!'));
510 $form->isblank("dbuser", $locale->text('Database User missing!'));
512 foreach my $item (keys %{$form}) {
513 $myconfig->{$item} = $form->{$item};
516 delete $myconfig->{stylesheet};
517 if ($form->{userstylesheet}) {
518 $myconfig->{stylesheet} = $form->{userstylesheet};
521 $myconfig->save_member();
523 if ($main::auth->can_change_password()
524 && defined $form->{new_password}
525 && ($form->{new_password} ne '********')) {
526 $main::auth->change_password($form->{login}, $form->{new_password});
529 $form->{templates} =~ s|.*/||;
530 $form->{templates} = "$main::templates/$form->{templates}";
531 $form->{mastertemplates} =~ s|.*/||;
533 # create user template directory and copy master files
534 if (!-d "$form->{templates}") {
537 if (mkdir "$form->{templates}", oct("771")) {
541 # copy templates to the directory
542 opendir TEMPLATEDIR, "$main::templates/." or $form->error("$main::templates : $ERRNO");
543 my @templates = grep /$form->{mastertemplates}.*?\.(html|tex|sty|odt|xml|txb)$/,
545 closedir TEMPLATEDIR;
547 foreach my $file (@templates) {
548 open(TEMP, "$main::templates/$file")
549 or $form->error("$main::templates/$file : $ERRNO");
551 $file =~ s/\Q$form->{mastertemplates}\E-//;
552 open(NEW, ">$form->{templates}/$file")
553 or $form->error("$form->{templates}/$file : $ERRNO");
555 while (my $line = <TEMP>) {
562 $form->error("$ERRNO: $form->{templates}");
566 # Add new user to his groups.
567 if (ref $form->{new_user_group_ids} eq 'ARRAY') {
568 my $all_groups = $main::auth->read_groups();
569 my %user = $main::auth->read_user($form->{login});
571 foreach my $group_id (@{ $form->{new_user_group_ids} }) {
572 my $group = $all_groups->{$group_id};
576 push @{ $group->{members} }, $user{id};
577 $main::auth->save_group($group);
581 $form->redirect($locale->text('User saved!'));
585 sub save_user_as_new {
586 my $form = $main::form;
588 $form->{login} = $form->{new_user_login};
589 delete @{$form}{qw(edit new_user_login)};
595 my $form = $main::form;
596 my $locale = $main::locale;
598 my %members = $main::auth->read_all_users();
599 my $templates = $members{$form->{login}}->{templates};
601 $main::auth->delete_user($form->{login});
604 my $templates_in_use = 0;
606 foreach my $login (keys %members) {
607 next if $form->{login} eq $login;
608 next if $members{$login}->{templates} ne $templates;
609 $templates_in_use = 1;
613 if (!$templates_in_use && -d $templates) {
614 unlink <$templates/*>;
619 $form->redirect($locale->text('User deleted!'));
627 return ($login) ? $login : undef;
633 my ($null, $value) = split(/=/, $line, 2);
636 $value =~ s/\s#.*//g;
638 # remove any trailing whitespace
639 $value =~ s/^\s*(.*?)\s*$/$1/;
644 sub pg_database_administration {
645 my $form = $main::form;
647 $form->{dbdriver} = 'Pg';
652 sub dbselect_source {
653 my $form = $main::form;
654 my $locale = $main::locale;
656 $form->{dbport} = $::auth->{DB_config}->{port} || 5432;
657 $form->{dbuser} = $::auth->{DB_config}->{user} || 'lxoffice';
658 $form->{dbdefault} = 'template1';
659 $form->{dbhost} = $::auth->{DB_config}->{host} || 'localhost';
661 $form->{title} = "Lx-Office ERP / " . $locale->text('Database Administration');
663 # Intentionnaly disabled unless fixed to work with the authentication DB.
664 $form->{ALLOW_DBBACKUP} = 0; # "$pg_dump_exe" ne "DISABLED";
667 print $form->parse_html_template("admin/dbadmin");
670 sub test_db_connection {
671 my $form = $main::form;
672 my $locale = $main::locale;
674 $form->{dbdriver} = 'Pg';
675 User::dbconnect_vars($form, $form->{dbname});
677 my $dbh = DBI->connect($form->{dbconnect}, $form->{dbuser}, $form->{dbpasswd});
679 $form->{connection_ok} = $dbh ? 1 : 0;
680 $form->{errstr} = $DBI::errstr;
682 $dbh->disconnect() if ($dbh);
684 $form->{title} = $locale->text('Database Connection Test');
686 print $form->parse_html_template("admin/test_db_connection");
690 call_sub($main::form->{"nextsub"});
694 my $form = $main::form;
695 my $locale = $main::locale;
697 $form->{title} = "Lx-Office ERP " . $locale->text('Database Administration') . " / " . $locale->text('Update Dataset');
699 my @need_updates = User->dbneedsupdate($form);
700 $form->{NEED_UPDATES} = \@need_updates;
701 $form->{ALL_UPDATED} = !scalar @need_updates;
704 print $form->parse_html_template("admin/update_dataset");
708 my $form = $main::form;
709 my $locale = $main::locale;
711 $form->{stylesheet} = "lx-office-erp.css";
712 $form->{title} = $locale->text("Dataset upgrade");
715 my $rowcount = $form->{rowcount} * 1;
716 my @update_rows = grep { $form->{"update_$_"} } (1 .. $rowcount);
717 $form->{NOTHING_TO_DO} = !scalar @update_rows;
718 my $saved_form = save_form();
722 print $form->parse_html_template("admin/dbupgrade_all_header");
724 foreach my $i (@update_rows) {
725 restore_form($saved_form);
727 map { $form->{$_} = $form->{"${_}_${i}"} } qw(dbname dbdriver dbhost dbport dbuser dbpasswd);
729 print $form->parse_html_template("admin/dbupgrade_header");
731 $form->{dbupdate} = $form->{dbname};
732 $form->{$form->{dbname}} = 1;
734 User->dbupdate($form);
735 User->dbupdate2($form, SL::DBUpgrade2->new(form => $form, dbdriver => $form->{dbdriver})->parse_dbupdate_controls);
737 print $form->parse_html_template("admin/dbupgrade_footer");
740 print $form->parse_html_template("admin/dbupgrade_all_done");
744 my $form = $main::form;
745 my $locale = $main::locale;
747 $form->{dbsources} = join " ", map { "[${_}]" } sort User->dbsources($form);
749 $form->{CHARTS} = [];
751 opendir SQLDIR, "sql/." or $form->error($ERRNO);
752 foreach my $item (sort grep /-chart\.sql\z/, readdir SQLDIR) {
753 next if ($item eq 'Default-chart.sql');
754 $item =~ s/-chart\.sql//;
755 push @{ $form->{CHARTS} }, { "name" => $item,
756 "selected" => $item eq "Germany-DATEV-SKR03EU" };
760 my $default_charset = $main::dbcharset;
761 $default_charset ||= Common::DEFAULT_CHARSET;
763 my $cluster_encoding = User->dbclusterencoding($form);
764 if ($cluster_encoding && ($cluster_encoding =~ m/^(?:UTF-?8|UNICODE)$/i)) {
765 if ($main::dbcharset !~ m/^UTF-?8$/i) {
766 $form->show_generic_error($locale->text('The selected PostgreSQL installation uses UTF-8 as its encoding. ' .
767 'Therefore you have to configure Lx-Office to use UTF-8 as well.'),
771 $form->{FORCE_DBENCODING} = 'UNICODE';
774 $form->{DBENCODINGS} = [];
776 foreach my $encoding (@Common::db_encodings) {
777 push @{ $form->{DBENCODINGS} }, { "dbencoding" => $encoding->{dbencoding},
778 "label" => $encoding->{label},
779 "selected" => $encoding->{charset} eq $default_charset };
783 $form->{title} = "Lx-Office ERP " . $locale->text('Database Administration') . " / " . $locale->text('Create Dataset');
786 print $form->parse_html_template("admin/create_dataset");
790 my $form = $main::form;
791 my $locale = $main::locale;
793 $form->isblank("db", $locale->text('Dataset missing!'));
795 User->dbcreate(\%$form);
797 $form->{title} = "Lx-Office ERP " . $locale->text('Database Administration') . " / " . $locale->text('Create Dataset');
800 print $form->parse_html_template("admin/dbcreate");
804 my $form = $main::form;
805 my $locale = $main::locale;
807 my @dbsources = User->dbsources_unused($form);
808 $form->error($locale->text('Nothing to delete!')) unless @dbsources;
810 $form->{title} = "Lx-Office ERP " . $locale->text('Database Administration') . " / " . $locale->text('Delete Dataset');
811 $form->{DBSOURCES} = [ map { { "name", $_ } } sort @dbsources ];
814 print $form->parse_html_template("admin/delete_dataset");
818 my $form = $main::form;
819 my $locale = $main::locale;
822 $form->error($locale->text('No Dataset selected!'));
825 User->dbdelete(\%$form);
827 $form->{title} = "Lx-Office ERP " . $locale->text('Database Administration') . " / " . $locale->text('Delete Dataset');
829 print $form->parse_html_template("admin/dbdelete");
833 my $form = $main::form;
834 my $locale = $main::locale;
836 $form->{title} = "Lx-Office ERP " . $locale->text('Database Administration') . " / " . $locale->text('Backup Dataset');
838 if ("$main::pg_dump_exe" eq "DISABLED") {
839 $form->error($locale->text('Database backups and restorations are disabled in lx-erp.conf.'));
842 my @dbsources = sort User->dbsources($form);
843 $form->{DATABASES} = [ map { { "dbname" => $_ } } @dbsources ];
844 $form->{NO_DATABASES} = !scalar @dbsources;
846 my $username = getpwuid $UID || "unknown-user";
847 my $hostname = hostname() || "unknown-host";
848 $form->{from} = "Lx-Office Admin <${username}\@${hostname}>";
851 print $form->parse_html_template("admin/backup_dataset");
854 sub backup_dataset_start {
855 my $form = $main::form;
856 my $locale = $main::locale;
858 $form->{title} = "Lx-Office ERP " . $locale->text('Database Administration') . " / " . $locale->text('Backup Dataset');
860 $main::pg_dump_exe ||= "pg_dump";
862 if ("$main::pg_dump_exe" eq "DISABLED") {
863 $form->error($locale->text('Database backups and restorations are disabled in lx-erp.conf.'));
866 $form->isblank("dbname", $locale->text('The dataset name is missing.'));
867 $form->isblank("to", $locale->text('The email address is missing.')) if $form->{destination} eq "email";
869 my $tmpdir = "/tmp/lx_office_backup_" . Common->unique_id();
870 mkdir $tmpdir, 0700 || $form->error($locale->text('A temporary directory could not be created:') . " $ERRNO");
872 my $pgpass = IO::File->new("${tmpdir}/.pgpass", O_WRONLY | O_CREAT, 0600);
876 $form->error($locale->text('A temporary file could not be created:') . " $ERRNO");
879 print $pgpass "$form->{dbhost}:$form->{dbport}:$form->{dbname}:$form->{dbuser}:$form->{dbpasswd}\n";
882 $ENV{HOME} = $tmpdir;
884 my @args = ("-Ft", "-c", "-o", "-h", $form->{dbhost}, "-U", $form->{dbuser});
885 push @args, ("-p", $form->{dbport}) if ($form->{dbport});
886 push @args, $form->{dbname};
888 my $cmd = "$main::pg_dump_exe " . join(" ", map { s/\\/\\\\/g; s/\"/\\\"/g; $_ } @args);
889 my $name = "dataset_backup_$form->{dbname}_" . strftime("%Y%m%d", localtime()) . ".tar";
891 if ($form->{destination} ne "email") {
892 my $in = IO::File->new("$cmd |");
895 unlink "${tmpdir}/.pgpass";
898 $form->error($locale->text('The pg_dump process could not be started.'));
901 print "content-type: application/x-tar\n";
902 print "content-disposition: attachment; filename=\"${name}\"\n\n";
904 while (my $line = <$in>) {
910 unlink "${tmpdir}/.pgpass";
914 my $tmp = $tmpdir . "/dump_" . Common::unique_id();
916 if (system("$cmd > $tmp") != 0) {
917 unlink "${tmpdir}/.pgpass", $tmp;
920 $form->error($locale->text('The pg_dump process could not be started.'));
923 my $mail = new Mailer;
925 map { $mail->{$_} = $form->{$_} } qw(from to cc subject message);
927 $mail->{charset} = $main::dbcharset ? $main::dbcharset : Common::DEFAULT_CHARSET;
928 $mail->{attachments} = [ { "filename" => $tmp, "name" => $name } ];
931 unlink "${tmpdir}/.pgpass", $tmp;
934 $form->{title} = "Lx-Office ERP " . $locale->text('Database Administration') . " / " . $locale->text('Backup Dataset');
937 print $form->parse_html_template("admin/backup_dataset_email_done");
941 sub restore_dataset {
942 my $form = $main::form;
943 my $locale = $main::locale;
945 $form->{title} = "Lx-Office ERP " . $locale->text('Database Administration') . " / " . $locale->text('Restore Dataset');
947 if ("$main::pg_restore_exe" eq "DISABLED") {
948 $form->error($locale->text('Database backups and restorations are disabled in lx-erp.conf.'));
951 my $default_charset = $main::dbcharset;
952 $default_charset ||= Common::DEFAULT_CHARSET;
954 $form->{DBENCODINGS} = [];
956 foreach my $encoding (@Common::db_encodings) {
957 push @{ $form->{DBENCODINGS} }, { "dbencoding" => $encoding->{dbencoding},
958 "label" => $encoding->{label},
959 "selected" => $encoding->{charset} eq $default_charset };
963 print $form->parse_html_template("admin/restore_dataset");
966 sub restore_dataset_start {
967 my $form = $main::form;
968 my $locale = $main::locale;
970 $form->{title} = "Lx-Office ERP " . $locale->text('Database Administration') . " / " . $locale->text('Restore Dataset');
972 $main::pg_restore_exe ||= "pg_restore";
974 if ("$main::pg_restore_exe" eq "DISABLED") {
975 $form->error($locale->text('Database backups and restorations are disabled in lx-erp.conf.'));
978 $form->isblank("new_dbname", $locale->text('The dataset name is missing.'));
979 $form->isblank("content", $locale->text('No backup file has been uploaded.'));
981 # Create temporary directories. Write the backup file contents to a temporary
982 # file. Create a .pgpass file with the username and password for the pg_restore
985 my $tmpdir = "/tmp/lx_office_backup_" . Common->unique_id();
986 mkdir $tmpdir, 0700 || $form->error($locale->text('A temporary directory could not be created:') . " $ERRNO");
988 my $pgpass = IO::File->new("${tmpdir}/.pgpass", O_WRONLY | O_CREAT, 0600);
992 $form->error($locale->text('A temporary file could not be created:') . " $ERRNO");
995 print $pgpass "$form->{dbhost}:$form->{dbport}:$form->{new_dbname}:$form->{dbuser}:$form->{dbpasswd}\n";
998 $ENV{HOME} = $tmpdir;
1000 my $tmp = $tmpdir . "/dump_" . Common::unique_id();
1003 if (substr($form->{content}, 0, 2) eq "\037\213") {
1004 $tmpfile = IO::File->new("| gzip -d > $tmp");
1008 $tmpfile = IO::File->new($tmp, O_WRONLY | O_CREAT | O_BINARY, 0600);
1012 unlink "${tmpdir}/.pgpass";
1015 $form->error($locale->text('A temporary file could not be created:') . " $ERRNO");
1018 print $tmpfile $form->{content};
1021 delete $form->{content};
1023 # Try to connect to the database. Find out if a database with the same name exists.
1024 # If yes, then drop the existing database. Create a new one with the name and encoding
1025 # given by the user.
1027 User::dbconnect_vars($form, "template1");
1029 my %myconfig = map { $_ => $form->{$_} } grep /^db/, keys %{ $form };
1030 my $dbh = $form->dbconnect(\%myconfig) || $form->dberror();
1034 $form->{new_dbname} =~ s|[^a-zA-Z0-9_\-]||g;
1036 $query = qq|SELECT COUNT(*) FROM pg_database WHERE datname = ?|;
1037 my ($count) = selectrow_query($form, $dbh, $query, $form->{new_dbname});
1039 do_query($form, $dbh, qq|DROP DATABASE $form->{new_dbname}|);
1043 foreach my $item (@Common::db_encodings) {
1044 if ($item->{dbencoding} eq $form->{dbencoding}) {
1049 $form->{dbencoding} = "LATIN9" unless $form->{dbencoding};
1051 do_query($form, $dbh, qq|CREATE DATABASE $form->{new_dbname} ENCODING ? TEMPLATE template0|, $form->{dbencoding});
1055 # Spawn pg_restore on the temporary file.
1057 my @args = ("-h", $form->{dbhost}, "-U", $form->{dbuser}, "-d", $form->{new_dbname});
1058 push @args, ("-p", $form->{dbport}) if ($form->{dbport});
1061 my $cmd = "$main::pg_restore_exe " . join(" ", map { s/\\/\\\\/g; s/\"/\\\"/g; $_ } @args);
1063 my $in = IO::File->new("$cmd 2>&1 |");
1066 unlink "${tmpdir}/.pgpass", $tmp;
1069 $form->error($locale->text('The pg_restore process could not be started.'));
1072 $English::AUTOFLUSH = 1;
1075 print $form->parse_html_template("admin/restore_dataset_start_header");
1077 while (my $line = <$in>) {
1082 $form->{retval} = $CHILD_ERROR >> 8;
1083 print $form->parse_html_template("admin/restore_dataset_start_footer");
1085 unlink "${tmpdir}/.pgpass", $tmp;
1090 my $form = $main::form;
1091 my $locale = $main::locale;
1093 unlink "$main::userspath/nologin";
1095 $form->{callback} = "admin.pl?action=list_users";
1097 $form->redirect($locale->text('Lockfile removed!'));
1102 my $form = $main::form;
1103 my $locale = $main::locale;
1105 open(FH, ">$main::userspath/nologin")
1106 or $form->error($locale->text('Cannot create Lock!'));
1109 $form->{callback} = "admin.pl?action=list_users";
1111 $form->redirect($locale->text('Lockfile created!'));
1116 call_sub($main::form->{yes_nextsub});
1120 call_sub($main::form->{no_nextsub});
1124 call_sub($main::form->{add_nextsub});
1128 my $form = $main::form;
1130 $form->{edit_nextsub} ||= 'edit_user';
1132 call_sub($form->{edit_nextsub});
1136 my $form = $main::form;
1138 $form->{delete_nextsub} ||= 'delete_user';
1140 call_sub($form->{delete_nextsub});
1144 my $form = $main::form;
1146 $form->{save_nextsub} ||= 'save_user';
1148 call_sub($form->{save_nextsub});
1152 call_sub($main::form->{back_nextsub});
1156 my $form = $main::form;
1157 my $locale = $main::locale;
1159 foreach my $action (qw(create_standard_group dont_create_standard_group
1160 save_user delete_user save_user_as_new)) {
1161 if ($form->{"action_${action}"}) {
1167 call_sub($form->{default_action}) if ($form->{default_action});
1169 $form->error($locale->text('No action defined.'));
1172 sub _apply_dbupgrade_scripts {
1173 ::end_of_request() if SL::DBUpgrade2->new(form => $::form, dbdriver => 'Pg', auth => 1)->apply_admin_dbupgrade_scripts(1);