1 #=====================================================================
4 # Based on SQL-Ledger Version 2.1.9
5 # Web http://www.lx-office.org
7 #=====================================================================
8 # SQL-Ledger Accounting
11 # Author: Dieter Simader
12 # Email: dsimader@sql-ledger.org
13 # Web: http://www.sql-ledger.org
16 # This program is free software; you can redistribute it and/or modify
17 # it under the terms of the GNU General Public License as published by
18 # the Free Software Foundation; either version 2 of the License, or
19 # (at your option) any later version.
21 # This program is distributed in the hope that it will be useful,
22 # but WITHOUT ANY WARRANTY; without even the implied warranty of
23 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
24 # GNU General Public License for more details.
25 # You should have received a copy of the GNU General Public License
26 # along with this program; if not, write to the Free Software
27 # Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
28 #======================================================================
31 # add/edit/delete users
33 #======================================================================
38 use English qw(-no_match_vars);
42 use POSIX qw(strftime);
46 use SL::Auth::PasswordPolicy;
56 require "bin/mozilla/common.pl";
57 require "bin/mozilla/admin_groups.pl";
58 require "bin/mozilla/admin_printer.pl";
68 $::lxdebug->enter_sub;
69 my $session_result = shift;
76 $::auth->store_root_credentials_in_session($form->{rpw}) if $session_result == SL::Auth->SESSION_OK;
78 $form->{stylesheet} = "lx-office-erp.css";
79 $form->{favicon} = "favicon.ico";
81 if ($form->{action}) {
82 if ($auth->authenticate_root($form->{rpw}) != $auth->OK()) {
83 $form->{error_message} = $locale->text('Incorrect Password!');
84 $auth->delete_session_value('rpw');
87 if ($auth->session_tables_present()) {
88 $::auth->store_root_credentials_in_session($::form->{rpw});
89 delete $::form->{rpw};
90 _apply_dbupgrade_scripts();
93 call_sub($locale->findsub($form->{action}));
96 # if there are no drivers bail out
97 $form->error($locale->text('No Database Drivers available!'))
98 unless (User->dbdrivers);
102 $::lxdebug->leave_sub;
106 my $form = $main::form;
107 my $locale = $main::locale;
109 $form->{title} = qq|Lx-Office ERP $form->{version} | . $locale->text('Administration');
112 print $form->parse_html_template('admin/adminlogin');
116 check_auth_db_and_tables();
121 $main::auth->destroy_session();
125 sub check_auth_db_and_tables {
126 my $form = $main::form;
127 my $locale = $main::locale;
131 map { $params{"db_${_}"} = $main::auth->{DB_config}->{$_} } keys %{ $auth->{DB_config} };
133 if (!$main::auth->check_database()) {
134 $form->{title} = $locale->text('Authentification database creation');
136 print $form->parse_html_template('admin/check_auth_database', \%params);
141 if (!$main::auth->check_tables()) {
142 $form->{title} = $locale->text('Authentification tables creation');
144 print $form->parse_html_template('admin/check_auth_tables', \%params);
149 my $memberfile = $::lx_office_conf{paths}->{memberfile};
150 if (-f $memberfile) {
153 if ($memberfile =~ m|^.*/|) {
157 my $backupdir = "${memberdir}member-file-migration";
159 $form->{title} = $locale->text('User data migration');
161 print $form->parse_html_template('admin/user_migration', { 'memberfile' => $memberfile,
162 'backupdir' => $backupdir });
169 my $form = $main::form;
171 $main::auth->create_database('superuser' => $form->{db_superuser},
172 'superuser_password' => $form->{db_superuser_password},
173 'template' => $form->{db_template});
177 sub create_auth_tables {
178 my $form = $main::form;
179 my $locale = $main::locale;
181 $main::auth->create_tables();
182 $main::auth->set_session_value('rpw', $form->{rpw});
183 $main::auth->create_or_refresh_session();
185 my $memberfile = $::lx_office_conf{paths}->{memberfile};
186 if (!-f $memberfile) {
187 # New installation -- create a standard group with full access
190 'name' => $locale->text('Full Access'),
191 'description' => $locale->text('Full access to all functions'),
192 'rights' => { map { $_ => 1 } SL::Auth::all_rights() },
193 'members' => [ map { $_->{id} } values %members ],
196 $main::auth->save_group($group);
199 _apply_dbupgrade_scripts();
204 $main::lxdebug->enter_sub();
206 my $form = $main::form;
207 my $locale = $main::locale;
211 my $memberfile = $::lx_office_conf{paths}->{memberfile};
212 if ($memberfile =~ m|^.*/|) {
216 my $backupdir = "${memberdir}member-file-migration";
218 if (! -d $backupdir && !mkdir $backupdir, 0700) {
219 $form->error(sprintf($locale->text('The directory "%s" could not be created:\n%s'), $backupdir, $!));
222 copy $memberfile, "users/member-file-migration/members";
224 my $in = IO::File->new($memberfile, "r");
226 $form->error($locale->text('Could not open the old memberfile.')) if (!$in);
228 my (%members, $login);
237 $login =~ s/(\[|\])//g;
241 $members{$login} = { "login" => $login };
245 if ($login && m/=/) {
246 my ($key, $value) = split m/\s*=\s*/, $_, 2;
251 $value =~ s|\\n|\n|g;
253 $members{$login}->{$key} = $value;
259 delete $members{"root login"};
261 map { $_->{dbpasswd} = unpack 'u', $_->{dbpasswd} } values %members;
263 while (my ($login, $params) = each %members) {
264 $main::auth->save_user($login, %{ $params });
265 $main::auth->change_password($login, $params->{password}, 1);
267 my $conf_file = "${memberdir}${login}.conf";
270 copy $conf_file, "${backupdir}/${login}.conf";
277 my @member_list = sort { lc $a->{login} cmp lc $b->{login} } values %members;
279 $form->{title} = $locale->text('User data migration');
281 print $form->parse_html_template('admin/user_migration_done', { 'MEMBERS' => \@member_list });
283 $main::lxdebug->leave_sub();
286 sub create_standard_group_ask {
287 my $form = $main::form;
288 my $locale = $main::locale;
290 $form->{title} = $locale->text('Create a standard group');
293 print $form->parse_html_template("admin/create_standard_group_ask");
296 sub create_standard_group {
297 my $form = $main::form;
298 my $locale = $main::locale;
300 my %members = $main::auth->read_all_users();
302 my $groups = $main::auth->read_groups();
304 foreach my $group (values %{$groups}) {
305 if (($form->{group_id} != $group->{id})
306 && ($form->{name} eq $group->{name})) {
307 $form->show_generic_error($locale->text("A group with that name does already exist."));
312 'name' => $locale->text('Full Access'),
313 'description' => $locale->text('Full access to all functions'),
314 'rights' => { map { $_ => 1 } SL::Auth::all_rights() },
315 'members' => [ map { $_->{id} } values %members ],
318 $main::auth->save_group($group);
320 user_migration_complete(1);
323 sub dont_create_standard_group {
324 user_migration_complete(0);
327 sub user_migration_complete {
328 my $standard_group_created = shift;
330 my $form = $main::form;
331 my $locale = $main::locale;
333 $form->{title} = $locale->text('User migration complete');
336 print $form->parse_html_template('admin/user_migration_complete', { 'standard_group_created' => $standard_group_created });
340 my $form = $main::form;
341 my $locale = $main::locale;
343 my %members = $main::auth->read_all_users();
345 delete $members{"root login"};
347 for (values %members) {
348 $_->{templates} =~ s|.*/||;
349 $_->{login_url} = $::locale->is_utf8 ? Encode::encode('utf-8-strict', $_->{login}) : $_->{login_url};
352 $form->{title} = "Lx-Office ERP " . $locale->text('Administration');
353 $form->{LOCKED} = -e _nologin_file_name();
354 $form->{MEMBERS} = [ @members{sort { lc $a cmp lc $b } keys %members} ];
357 print $form->parse_html_template("admin/list_users");
361 my $form = $main::form;
362 my $locale = $main::locale;
364 $form->{title} = "Lx-Office ERP " . $locale->text('Administration') . " / " . $locale->text('Add User');
366 # Note: Menu Style 'v3' is not compatible to all browsers!
367 # "menustyle" => "old" sets the HTML Menu to default.
370 "countrycode" => "de",
371 "numberformat" => "1.000,00",
372 "dateformat" => "dd.mm.yy",
373 "stylesheet" => "lx-office-erp.css",
374 "menustyle" => "old",
375 dbport => $::auth->{DB_config}->{port} || 5432,
376 dbuser => $::auth->{DB_config}->{user} || 'lxoffice',
377 dbhost => $::auth->{DB_config}->{host} || 'localhost',
381 edit_user_form($myconfig);
385 my $form = $main::form;
386 my $locale = $main::locale;
388 $form->{title} = "Lx-Office ERP " . $locale->text('Administration') . " / " . $locale->text('Edit User');
391 $form->isblank("login", $locale->text("The login is missing."));
394 my $myconfig = new User($form->{login});
396 # strip basedir from templates directory
397 $myconfig->{templates} =~ s|.*/||;
399 edit_user_form($myconfig);
405 my $form = $main::form;
406 my $locale = $main::locale;
408 my @valid_dateformats = qw(mm-dd-yy mm/dd/yy dd-mm-yy dd/mm/yy dd.mm.yy yyyy-mm-dd);
409 $form->{ALL_DATEFORMATS} = [ map { { "format" => $_, "selected" => $_ eq $myconfig->{dateformat} } } @valid_dateformats ];
411 my @valid_numberformats = ('1,000.00', '1000.00', '1.000,00', '1000,00');
412 $form->{ALL_NUMBERFORMATS} = [ map { { "format" => $_, "selected" => $_ eq $myconfig->{numberformat} } } @valid_numberformats ];
414 my %countrycodes = User->country_codes;
415 $form->{ALL_COUNTRYCODES} = [];
416 foreach my $countrycode (sort { $countrycodes{$a} cmp $countrycodes{$b} } keys %countrycodes) {
417 push @{ $form->{ALL_COUNTRYCODES} }, { "value" => $countrycode,
418 "name" => $countrycodes{$countrycode},
419 "selected" => $countrycode eq $myconfig->{countrycode} };
422 # is there a templates basedir
423 if (!-d $::lx_office_conf{paths}->{templates}) {
424 $form->error(sprintf($locale->text("The directory %s does not exist."), $::lx_office_conf{paths}->{templates}));
427 opendir TEMPLATEDIR, $::lx_office_conf{paths}->{templates} or $form->error($::lx_office_conf{paths}->{templates} . " : $ERRNO");
428 my @all = readdir(TEMPLATEDIR);
429 my @alldir = sort grep { -d ($::lx_office_conf{paths}->{templates} . "/$_") && !/^\.\.?$/ } @all;
430 my @allhtml = sort grep { -f ($::lx_office_conf{paths}->{templates} . "/$_") && /\.html$/ } @all;
431 closedir TEMPLATEDIR;
433 @alldir = grep !/\.(html|tex|sty|odt|xml|txb)$/, @alldir;
434 @alldir = grep !/^(webpages|\.svn)$/, @alldir;
436 @allhtml = reverse grep !/Default/, @allhtml;
437 push @allhtml, 'Default';
438 @allhtml = reverse @allhtml;
440 $form->{ALL_TEMPLATES} = [ map { { "name", => $_, "selected" => $_ eq $myconfig->{templates} } } @alldir ];
442 my $lastitem = $allhtml[0];
443 $lastitem =~ s/-.*//g;
444 $form->{ALL_MASTER_TEMPLATES} = [ { "name" => $lastitem, "selected" => $lastitem eq "German" } ];
445 foreach my $item (@allhtml) {
447 next if ($item eq $lastitem);
449 push @{ $form->{ALL_MASTER_TEMPLATES} }, { "name" => $item, "selected" => $item eq "German" };
453 # css dir has styles that are not intended as general layouts.
454 # reverting to hardcoded list
455 $form->{ALL_STYLESHEETS} = [ map { { "name" => $_, "selected" => $_ eq $myconfig->{stylesheet} } } qw(lx-office-erp.css Win2000.css) ];
457 $form->{"menustyle_" . $myconfig->{menustyle} } = 1;
459 map { $form->{"myc_${_}"} = $myconfig->{$_} } keys %{ $myconfig };
464 my $user_id = $main::auth->get_user_id($form->{login});
465 my $all_groups = $main::auth->read_groups();
467 foreach my $group (values %{ $all_groups }) {
468 push @{ $groups }, $group if (grep { $user_id == $_ } @{ $group->{members} });
471 $groups = [ sort { lc $a->{name} cmp lc $b->{name} } @{ $groups } ];
474 $form->{CAN_CHANGE_PASSWORD} = $main::auth->can_change_password();
477 print $form->parse_html_template("admin/edit_user", { 'GROUPS' => $groups });
481 my $form = $main::form;
482 my $locale = $main::locale;
484 $form->{dbdriver} = 'Pg';
486 # no spaces allowed in login name
487 $form->{login} =~ s|\s||g;
488 $form->isblank("login", $locale->text('Login name missing!'));
490 # check for duplicates
491 if (!$form->{edit}) {
492 my %members = $main::auth->read_all_users();
493 if ($members{$form->{login}}) {
494 $form->show_generic_error($locale->text('Another user with the login #1 does already exist.', $form->{login}), 'back_button' => 1);
498 # no spaces allowed in directories
499 ($form->{newtemplates}) = split / /, $form->{newtemplates};
501 if ($form->{newtemplates}) {
502 $form->{templates} = $form->{newtemplates};
505 ($form->{usetemplates}) ? $form->{usetemplates} : $form->{login};
509 if (!-d $::lx_office_conf{paths}->{templates}) {
510 $form->error(sprintf($locale->text("The directory %s does not exist."), $::lx_office_conf{paths}->{templates}));
513 # add base directory to $form->{templates}
514 $form->{templates} =~ s|.*/||;
515 $form->{templates} = $::lx_office_conf{paths}->{templates} . "/$form->{templates}";
517 my $myconfig = new User($form->{login});
519 $form->isblank("dbname", $locale->text('Dataset missing!'));
520 $form->isblank("dbuser", $locale->text('Database User missing!'));
522 foreach my $item (keys %{$form}) {
523 $myconfig->{$item} = $form->{$item};
526 delete $myconfig->{stylesheet};
527 if ($form->{userstylesheet}) {
528 $myconfig->{stylesheet} = $form->{userstylesheet};
531 $myconfig->save_member();
533 $form->{templates} =~ s|.*/||;
534 $form->{templates} = $::lx_office_conf{paths}->{templates} . "/$form->{templates}";
535 $form->{mastertemplates} =~ s|.*/||;
537 # create user template directory and copy master files
538 if (!-d "$form->{templates}") {
541 if (mkdir "$form->{templates}", oct("771")) {
545 # copy templates to the directory
546 opendir TEMPLATEDIR, $::lx_office_conf{paths}->{templates} or $form->error($::lx_office_conf{paths}->{templates} . " : $ERRNO");
547 my @templates = grep /$form->{mastertemplates}.*?\.(html|tex|sty|odt|xml|txb)$/,
549 closedir TEMPLATEDIR;
551 foreach my $file (@templates) {
552 open(TEMP, $::lx_office_conf{paths}->{templates} . "/$file")
553 or $form->error($::lx_office_conf{paths}->{templates} . "/$file : $ERRNO");
555 $file =~ s/\Q$form->{mastertemplates}\E-//;
556 open(NEW, ">$form->{templates}/$file")
557 or $form->error("$form->{templates}/$file : $ERRNO");
559 while (my $line = <TEMP>) {
566 $form->error("$ERRNO: $form->{templates}");
570 # Add new user to his groups.
571 if (ref $form->{new_user_group_ids} eq 'ARRAY') {
572 my $all_groups = $main::auth->read_groups();
573 my %user = $main::auth->read_user($form->{login});
575 foreach my $group_id (@{ $form->{new_user_group_ids} }) {
576 my $group = $all_groups->{$group_id};
580 push @{ $group->{members} }, $user{id};
581 $main::auth->save_group($group);
585 if ($main::auth->can_change_password()
586 && defined $form->{new_password}
587 && ($form->{new_password} ne '********')) {
588 my $verifier = SL::Auth::PasswordPolicy->new;
589 my $result = $verifier->verify($form->{new_password}, 1);
591 if ($result != SL::Auth::PasswordPolicy->OK()) {
592 $form->error($::locale->text('The settings were saved, but the password was not changed.') . ' ' . join(' ', $verifier->errors($result)));
595 $main::auth->change_password($form->{login}, $form->{new_password});
598 $form->redirect($locale->text('User saved!'));
601 sub save_user_as_new {
602 my $form = $main::form;
604 $form->{login} = $form->{new_user_login};
605 delete @{$form}{qw(edit new_user_login)};
611 my $form = $main::form;
612 my $locale = $main::locale;
614 my %members = $main::auth->read_all_users();
615 my $templates = $members{$form->{login}}->{templates};
617 $main::auth->delete_user($form->{login});
620 my $templates_in_use = 0;
622 foreach my $login (keys %members) {
623 next if $form->{login} eq $login;
624 next if $members{$login}->{templates} ne $templates;
625 $templates_in_use = 1;
629 if (!$templates_in_use && -d $templates) {
630 unlink <$templates/*>;
635 $form->redirect($locale->text('User deleted!'));
643 return ($login) ? $login : undef;
649 my ($null, $value) = split(/=/, $line, 2);
652 $value =~ s/\s#.*//g;
654 # remove any trailing whitespace
655 $value =~ s/^\s*(.*?)\s*$/$1/;
660 sub pg_database_administration {
661 my $form = $main::form;
663 $form->{dbdriver} = 'Pg';
668 sub dbselect_source {
669 my $form = $main::form;
670 my $locale = $main::locale;
672 $form->{dbport} = $::auth->{DB_config}->{port} || 5432;
673 $form->{dbuser} = $::auth->{DB_config}->{user} || 'lxoffice';
674 $form->{dbdefault} = 'template1';
675 $form->{dbhost} = $::auth->{DB_config}->{host} || 'localhost';
677 $form->{title} = "Lx-Office ERP / " . $locale->text('Database Administration');
679 # Intentionnaly disabled unless fixed to work with the authentication DB.
680 $form->{ALLOW_DBBACKUP} = 0; # "$pg_dump_exe" ne "DISABLED";
683 print $form->parse_html_template("admin/dbadmin");
686 sub test_db_connection {
687 my $form = $main::form;
688 my $locale = $main::locale;
690 $form->{dbdriver} = 'Pg';
691 User::dbconnect_vars($form, $form->{dbname});
693 my $dbh = DBI->connect($form->{dbconnect}, $form->{dbuser}, $form->{dbpasswd});
695 $form->{connection_ok} = $dbh ? 1 : 0;
696 $form->{errstr} = $DBI::errstr;
698 $dbh->disconnect() if ($dbh);
700 $form->{title} = $locale->text('Database Connection Test');
702 print $form->parse_html_template("admin/test_db_connection");
706 call_sub($main::form->{"nextsub"});
710 my $form = $main::form;
711 my $locale = $main::locale;
713 $form->{title} = "Lx-Office ERP " . $locale->text('Database Administration') . " / " . $locale->text('Update Dataset');
715 my @need_updates = User->dbneedsupdate($form);
716 $form->{NEED_UPDATES} = \@need_updates;
717 $form->{ALL_UPDATED} = !scalar @need_updates;
720 print $form->parse_html_template("admin/update_dataset");
724 my $form = $main::form;
725 my $locale = $main::locale;
727 $form->{stylesheet} = "lx-office-erp.css";
728 $form->{title} = $locale->text("Dataset upgrade");
731 my $rowcount = $form->{rowcount} * 1;
732 my @update_rows = grep { $form->{"update_$_"} } (1 .. $rowcount);
733 $form->{NOTHING_TO_DO} = !scalar @update_rows;
734 my $saved_form = save_form();
738 print $form->parse_html_template("admin/dbupgrade_all_header");
740 foreach my $i (@update_rows) {
741 restore_form($saved_form);
744 map { $form->{$_} = $::myconfig{$_} = $form->{"${_}_${i}"} } qw(dbname dbdriver dbhost dbport dbuser dbpasswd);
746 print $form->parse_html_template("admin/dbupgrade_header");
748 $form->{dbupdate} = $form->{dbname};
749 $form->{$form->{dbname}} = 1;
751 User->dbupdate($form);
752 User->dbupdate2($form, SL::DBUpgrade2->new(form => $form, dbdriver => $form->{dbdriver})->parse_dbupdate_controls);
754 print $form->parse_html_template("admin/dbupgrade_footer");
757 print $form->parse_html_template("admin/dbupgrade_all_done");
761 my $form = $main::form;
762 my $locale = $main::locale;
764 $form->{dbsources} = join " ", map { "[${_}]" } sort User->dbsources($form);
766 $form->{CHARTS} = [];
768 opendir SQLDIR, "sql/." or $form->error($ERRNO);
769 foreach my $item (sort grep /-chart\.sql\z/, readdir SQLDIR) {
770 next if ($item eq 'Default-chart.sql');
771 $item =~ s/-chart\.sql//;
772 push @{ $form->{CHARTS} }, { "name" => $item,
773 "selected" => $item eq "Germany-DATEV-SKR03EU" };
777 $form->{ACCOUNTING_METHODS} = [];
778 foreach my $item ( qw(accrual cash) ) {
779 push @{ $form->{ACCOUNTING_METHODS} }, { "name" => $item,
780 "selected" => $item eq "cash" };
783 $form->{INVENTORY_SYSTEMS} = [];
784 foreach my $item ( qw(perpetual periodic) ) {
785 push @{ $form->{INVENTORY_SYSTEMS} }, { "name" => $item,
786 "selected" => $item eq "periodic" };
789 $form->{PROFIT_DETERMINATIONS} = [];
790 foreach my $item ( qw(balance income) ) {
791 push @{ $form->{PROFIT_DETERMINATIONS} }, { "name" => $item,
792 "selected" => $item eq "income" };
795 my $default_charset = $::lx_office_conf{system}->{dbcharset};
796 $default_charset ||= Common::DEFAULT_CHARSET;
798 my $cluster_encoding = User->dbclusterencoding($form);
799 if ($cluster_encoding && ($cluster_encoding =~ m/^(?:UTF-?8|UNICODE)$/i)) {
800 if ($::lx_office_conf{system}->{dbcharset} !~ m/^UTF-?8$/i) {
801 $form->show_generic_error($locale->text('The selected PostgreSQL installation uses UTF-8 as its encoding. ' .
802 'Therefore you have to configure Lx-Office to use UTF-8 as well.'),
806 $form->{FORCE_DBENCODING} = 'UNICODE';
809 $form->{DBENCODINGS} = [];
811 foreach my $encoding (@Common::db_encodings) {
812 push @{ $form->{DBENCODINGS} }, { "dbencoding" => $encoding->{dbencoding},
813 "label" => $encoding->{label},
814 "selected" => $encoding->{charset} eq $default_charset };
818 $form->{title} = "Lx-Office ERP " . $locale->text('Database Administration') . " / " . $locale->text('Create Dataset');
821 print $form->parse_html_template("admin/create_dataset");
825 my $form = $main::form;
826 my $locale = $main::locale;
828 $form->isblank("db", $locale->text('Dataset missing!'));
830 User->dbcreate(\%$form);
832 $form->{title} = "Lx-Office ERP " . $locale->text('Database Administration') . " / " . $locale->text('Create Dataset');
835 print $form->parse_html_template("admin/dbcreate");
839 my $form = $main::form;
840 my $locale = $main::locale;
842 my @dbsources = User->dbsources_unused($form);
843 $form->error($locale->text('Nothing to delete!')) unless @dbsources;
845 $form->{title} = "Lx-Office ERP " . $locale->text('Database Administration') . " / " . $locale->text('Delete Dataset');
846 $form->{DBSOURCES} = [ map { { "name", $_ } } sort @dbsources ];
849 print $form->parse_html_template("admin/delete_dataset");
853 my $form = $main::form;
854 my $locale = $main::locale;
857 $form->error($locale->text('No Dataset selected!'));
860 User->dbdelete(\%$form);
862 $form->{title} = "Lx-Office ERP " . $locale->text('Database Administration') . " / " . $locale->text('Delete Dataset');
864 print $form->parse_html_template("admin/dbdelete");
868 my $form = $main::form;
869 my $locale = $main::locale;
871 $form->{title} = "Lx-Office ERP " . $locale->text('Database Administration') . " / " . $locale->text('Backup Dataset');
873 if ($::lx_office_conf{applications}->{pg_dump} eq "DISABLED") {
874 $form->error($locale->text('Database backups and restorations are disabled in the configuration.'));
877 my @dbsources = sort User->dbsources($form);
878 $form->{DATABASES} = [ map { { "dbname" => $_ } } @dbsources ];
879 $form->{NO_DATABASES} = !scalar @dbsources;
881 my $username = getpwuid $UID || "unknown-user";
882 my $hostname = hostname() || "unknown-host";
883 $form->{from} = "Lx-Office Admin <${username}\@${hostname}>";
886 print $form->parse_html_template("admin/backup_dataset");
889 sub backup_dataset_start {
890 my $form = $main::form;
891 my $locale = $main::locale;
893 $form->{title} = "Lx-Office ERP " . $locale->text('Database Administration') . " / " . $locale->text('Backup Dataset');
895 my $pg_dump_exe = $::lx_office_conf{applications}->{pg_dump} || "pg_dump";
897 if ("$pg_dump_exe" eq "DISABLED") {
898 $form->error($locale->text('Database backups and restorations are disabled in the configuration.'));
901 $form->isblank("dbname", $locale->text('The dataset name is missing.'));
902 $form->isblank("to", $locale->text('The email address is missing.')) if $form->{destination} eq "email";
904 my $tmpdir = "/tmp/lx_office_backup_" . Common->unique_id();
905 mkdir $tmpdir, 0700 || $form->error($locale->text('A temporary directory could not be created:') . " $ERRNO");
907 my $pgpass = IO::File->new("${tmpdir}/.pgpass", O_WRONLY | O_CREAT, 0600);
911 $form->error($locale->text('A temporary file could not be created:') . " $ERRNO");
914 print $pgpass "$form->{dbhost}:$form->{dbport}:$form->{dbname}:$form->{dbuser}:$form->{dbpasswd}\n";
917 $ENV{HOME} = $tmpdir;
919 my @args = ("-Ft", "-c", "-o", "-h", $form->{dbhost}, "-U", $form->{dbuser});
920 push @args, ("-p", $form->{dbport}) if ($form->{dbport});
921 push @args, $form->{dbname};
923 my $cmd = "$pg_dump_exe " . join(" ", map { s/\\/\\\\/g; s/\"/\\\"/g; $_ } @args);
924 my $name = "dataset_backup_$form->{dbname}_" . strftime("%Y%m%d", localtime()) . ".tar";
926 if ($form->{destination} ne "email") {
927 my $in = IO::File->new("$cmd |");
930 unlink "${tmpdir}/.pgpass";
933 $form->error($locale->text('The pg_dump process could not be started.'));
936 print "content-type: application/x-tar\n";
937 print "content-disposition: attachment; filename=\"${name}\"\n\n";
939 while (my $line = <$in>) {
945 unlink "${tmpdir}/.pgpass";
949 my $tmp = $tmpdir . "/dump_" . Common::unique_id();
951 if (system("$cmd > $tmp") != 0) {
952 unlink "${tmpdir}/.pgpass", $tmp;
955 $form->error($locale->text('The pg_dump process could not be started.'));
958 my $mail = new Mailer;
960 map { $mail->{$_} = $form->{$_} } qw(from to cc subject message);
962 $mail->{charset} = $::lx_office_conf{system}->{dbcharset} || Common::DEFAULT_CHARSET;
963 $mail->{attachments} = [ { "filename" => $tmp, "name" => $name } ];
966 unlink "${tmpdir}/.pgpass", $tmp;
969 $form->{title} = "Lx-Office ERP " . $locale->text('Database Administration') . " / " . $locale->text('Backup Dataset');
972 print $form->parse_html_template("admin/backup_dataset_email_done");
976 sub restore_dataset {
977 my $form = $main::form;
978 my $locale = $main::locale;
980 $form->{title} = "Lx-Office ERP " . $locale->text('Database Administration') . " / " . $locale->text('Restore Dataset');
982 if ($::lx_office_conf{applications}->{pg_restore} eq "DISABLED") {
983 $form->error($locale->text('Database backups and restorations are disabled in the configuration.'));
986 my $default_charset = $::lx_office_conf{system}->{dbcharset};
987 $default_charset ||= Common::DEFAULT_CHARSET;
989 $form->{DBENCODINGS} = [];
991 foreach my $encoding (@Common::db_encodings) {
992 push @{ $form->{DBENCODINGS} }, { "dbencoding" => $encoding->{dbencoding},
993 "label" => $encoding->{label},
994 "selected" => $encoding->{charset} eq $default_charset };
998 print $form->parse_html_template("admin/restore_dataset");
1001 sub restore_dataset_start {
1002 my $form = $main::form;
1003 my $locale = $main::locale;
1005 $form->{title} = "Lx-Office ERP " . $locale->text('Database Administration') . " / " . $locale->text('Restore Dataset');
1007 my $pg_restore_exe = $::lx_office_conf{applications}->{pg_restore} || "pg_restore";
1009 if ("$pg_restore_exe" eq "DISABLED") {
1010 $form->error($locale->text('Database backups and restorations are disabled in the configuration.'));
1013 $form->isblank("new_dbname", $locale->text('The dataset name is missing.'));
1014 $form->isblank("content", $locale->text('No backup file has been uploaded.'));
1016 # Create temporary directories. Write the backup file contents to a temporary
1017 # file. Create a .pgpass file with the username and password for the pg_restore
1020 my $tmpdir = "/tmp/lx_office_backup_" . Common->unique_id();
1021 mkdir $tmpdir, 0700 || $form->error($locale->text('A temporary directory could not be created:') . " $ERRNO");
1023 my $pgpass = IO::File->new("${tmpdir}/.pgpass", O_WRONLY | O_CREAT, 0600);
1027 $form->error($locale->text('A temporary file could not be created:') . " $ERRNO");
1030 print $pgpass "$form->{dbhost}:$form->{dbport}:$form->{new_dbname}:$form->{dbuser}:$form->{dbpasswd}\n";
1033 $ENV{HOME} = $tmpdir;
1035 my $tmp = $tmpdir . "/dump_" . Common::unique_id();
1038 if (substr($form->{content}, 0, 2) eq "\037\213") {
1039 $tmpfile = IO::File->new("| gzip -d > $tmp");
1043 $tmpfile = IO::File->new($tmp, O_WRONLY | O_CREAT | O_BINARY, 0600);
1047 unlink "${tmpdir}/.pgpass";
1050 $form->error($locale->text('A temporary file could not be created:') . " $ERRNO");
1053 print $tmpfile $form->{content};
1056 delete $form->{content};
1058 # Try to connect to the database. Find out if a database with the same name exists.
1059 # If yes, then drop the existing database. Create a new one with the name and encoding
1060 # given by the user.
1062 User::dbconnect_vars($form, "template1");
1064 my %myconfig = map { $_ => $form->{$_} } grep /^db/, keys %{ $form };
1065 my $dbh = $form->dbconnect(\%myconfig) || $form->dberror();
1069 $form->{new_dbname} =~ s|[^a-zA-Z0-9_\-]||g;
1071 $query = qq|SELECT COUNT(*) FROM pg_database WHERE datname = ?|;
1072 my ($count) = selectrow_query($form, $dbh, $query, $form->{new_dbname});
1074 do_query($form, $dbh, qq|DROP DATABASE $form->{new_dbname}|);
1078 foreach my $item (@Common::db_encodings) {
1079 if ($item->{dbencoding} eq $form->{dbencoding}) {
1084 $form->{dbencoding} = "LATIN9" unless $form->{dbencoding};
1086 do_query($form, $dbh, qq|CREATE DATABASE $form->{new_dbname} ENCODING ? TEMPLATE template0|, $form->{dbencoding});
1090 # Spawn pg_restore on the temporary file.
1092 my @args = ("-h", $form->{dbhost}, "-U", $form->{dbuser}, "-d", $form->{new_dbname});
1093 push @args, ("-p", $form->{dbport}) if ($form->{dbport});
1096 my $cmd = "$pg_restore_exe " . join(" ", map { s/\\/\\\\/g; s/\"/\\\"/g; $_ } @args);
1098 my $in = IO::File->new("$cmd 2>&1 |");
1101 unlink "${tmpdir}/.pgpass", $tmp;
1104 $form->error($locale->text('The pg_restore process could not be started.'));
1107 $English::AUTOFLUSH = 1;
1110 print $form->parse_html_template("admin/restore_dataset_start_header");
1112 while (my $line = <$in>) {
1117 $form->{retval} = $CHILD_ERROR >> 8;
1118 print $form->parse_html_template("admin/restore_dataset_start_footer");
1120 unlink "${tmpdir}/.pgpass", $tmp;
1125 my $form = $main::form;
1126 my $locale = $main::locale;
1128 unlink _nologin_file_name();;
1130 $form->{callback} = "admin.pl?action=list_users";
1132 $form->redirect($locale->text('Lockfile removed!'));
1137 my $form = $main::form;
1138 my $locale = $main::locale;
1140 open(FH, ">" . _nologin_file_name())
1141 or $form->error($locale->text('Cannot create Lock!'));
1144 $form->{callback} = "admin.pl?action=list_users";
1146 $form->redirect($locale->text('Lockfile created!'));
1151 call_sub($main::form->{yes_nextsub});
1155 call_sub($main::form->{no_nextsub});
1159 call_sub($main::form->{add_nextsub});
1163 my $form = $main::form;
1165 $form->{edit_nextsub} ||= 'edit_user';
1167 call_sub($form->{edit_nextsub});
1171 my $form = $main::form;
1173 $form->{delete_nextsub} ||= 'delete_user';
1175 call_sub($form->{delete_nextsub});
1179 my $form = $main::form;
1181 $form->{save_nextsub} ||= 'save_user';
1183 call_sub($form->{save_nextsub});
1187 call_sub($main::form->{back_nextsub});
1191 my $form = $main::form;
1192 my $locale = $main::locale;
1194 foreach my $action (qw(create_standard_group dont_create_standard_group
1195 save_user delete_user save_user_as_new)) {
1196 if ($form->{"action_${action}"}) {
1202 call_sub($form->{default_action}) if ($form->{default_action});
1204 $form->error($locale->text('No action defined.'));
1207 sub _apply_dbupgrade_scripts {
1208 ::end_of_request() if SL::DBUpgrade2->new(form => $::form, dbdriver => 'Pg', auth => 1)->apply_admin_dbupgrade_scripts(1);
1211 sub _nologin_file_name {
1212 return $::lx_office_conf{paths}->{userspath} . '/nologin';