2da3ba58ab6e57b7ca61739b6ccafcb76ddebaab
[kivitendo-erp.git] / bin / mozilla / admin.pl
1 #=====================================================================
2 # LX-Office ERP
3 # Copyright (C) 2004
4 # Based on SQL-Ledger Version 2.1.9
5 # Web http://www.lx-office.org
6 #
7 #=====================================================================
8 # SQL-Ledger Accounting
9 # Copyright (c) 2002
10 #
11 #  Author: Dieter Simader
12 #   Email: dsimader@sql-ledger.org
13 #     Web: http://www.sql-ledger.org
14 #
15 #
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.
20 #
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 #======================================================================
29 #
30 # setup module
31 # add/edit/delete users
32 #
33 #======================================================================
34
35 use DBI;
36 use CGI;
37 use English qw(-no_match_vars);
38 use Fcntl;
39 use File::Copy;
40 use IO::File;
41 use POSIX qw(strftime);
42 use Sys::Hostname;
43
44 use SL::Auth;
45 use SL::Form;
46 use SL::Iconv;
47 use SL::Mailer;
48 use SL::User;
49 use SL::Common;
50 use SL::Inifile;
51 use SL::DBUpgrade2;
52 use SL::DBUtils;
53
54 require "bin/mozilla/common.pl";
55 require "bin/mozilla/admin_groups.pl";
56 require "bin/mozilla/admin_printer.pl";
57
58 use strict;
59
60 our $cgi;
61 our $form;
62 our $locale;
63 our $auth;
64
65 sub run {
66   $::lxdebug->enter_sub;
67   my $session_result = shift;
68
69   $cgi    = $::cgi;
70   $form   = $::form;
71   $locale = $::locale;
72   $auth   = $::auth;
73
74   $::auth->set_session_value('rpw', $::form->{rpw}) if $session_result == SL::Auth->SESSION_OK;
75
76   $form->{stylesheet} = "lx-office-erp.css";
77   $form->{favicon}    = "favicon.ico";
78
79   if ($form->{action}) {
80     if ($auth->authenticate_root($form->{rpw}, 0) != $auth->OK()) {
81       $form->{error_message} = $locale->text('Incorrect Password!');
82       adminlogin();
83     } else {
84       if ($auth->session_tables_present()) {
85         $::auth->set_session_value('rpw', $::form->{rpw});
86         $::auth->create_or_refresh_session();
87         _apply_dbupgrade_scripts();
88       }
89
90       call_sub($locale->findsub($form->{action}));
91     }
92   } else {
93     # if there are no drivers bail out
94     $form->error($locale->text('No Database Drivers available!'))
95       unless (User->dbdrivers);
96
97     adminlogin();
98   }
99   $::lxdebug->leave_sub;
100 }
101
102 sub adminlogin {
103   my $form   = $main::form;
104   my $locale = $main::locale;
105
106   $form->{title} = qq|Lx-Office ERP $form->{version} | . $locale->text('Administration');
107
108   $form->header();
109   print $form->parse_html_template('admin/adminlogin');
110 }
111
112 sub login {
113   check_auth_db_and_tables();
114   list_users();
115 }
116
117 sub logout {
118   $main::auth->destroy_session();
119   adminlogin();
120 }
121
122 sub check_auth_db_and_tables {
123   my $form   = $main::form;
124   my $locale = $main::locale;
125
126   my %params;
127
128   map { $params{"db_${_}"} = $main::auth->{DB_config}->{$_} } keys %{ $auth->{DB_config} };
129
130   if (!$main::auth->check_database()) {
131     $form->{title} = $locale->text('Authentification database creation');
132     $form->header();
133     print $form->parse_html_template('admin/check_auth_database', \%params);
134
135     ::end_of_request();
136   }
137
138   if (!$main::auth->check_tables()) {
139     $form->{title} = $locale->text('Authentification tables creation');
140     $form->header();
141     print $form->parse_html_template('admin/check_auth_tables', \%params);
142
143     ::end_of_request();
144   }
145
146   if (-f $main::memberfile) {
147     my $memberdir = "";
148
149     if ($main::memberfile =~ m|^.*/|) {
150       $memberdir = $&;
151     }
152
153     my $backupdir = "${memberdir}member-file-migration";
154
155     $form->{title} = $locale->text('User data migration');
156     $form->header();
157     print $form->parse_html_template('admin/user_migration', { 'memberfile' => $main::memberfile,
158                                                                'backupdir'  => $backupdir });
159
160     ::end_of_request();
161   }
162 }
163
164 sub create_auth_db {
165   my $form = $main::form;
166
167   $main::auth->create_database('superuser'          => $form->{db_superuser},
168                                'superuser_password' => $form->{db_superuser_password},
169                                'template'           => $form->{db_template});
170   login();
171 }
172
173 sub create_auth_tables {
174   my $form   = $main::form;
175   my $locale = $main::locale;
176
177   $main::auth->create_tables();
178   $main::auth->set_session_value('rpw', $form->{rpw});
179   $main::auth->create_or_refresh_session();
180
181   if (!-f $main::memberfile) {
182     # New installation -- create a standard group with full access
183     my %members;
184     my $group = {
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 ],
189     };
190
191     $main::auth->save_group($group);
192   }
193
194   _apply_dbupgrade_scripts();
195   login();
196 }
197
198 sub migrate_users {
199   $main::lxdebug->enter_sub();
200
201   my $form      = $main::form;
202   my $locale    = $main::locale;
203
204   my $memberdir = "";
205
206   if ($main::memberfile =~ m|^.*/|) {
207     $memberdir = $&;
208   }
209
210   my $backupdir = "${memberdir}member-file-migration";
211
212   if (! -d $backupdir && !mkdir $backupdir, 0700) {
213     $form->error(sprintf($locale->text('The directory "%s" could not be created:\n%s'), $backupdir, $!));
214   }
215
216   copy $main::memberfile, "users/member-file-migration/members";
217
218   my $in = IO::File->new($main::memberfile, "r");
219
220   $form->error($locale->text('Could not open the old memberfile.')) if (!$in);
221
222   my (%members, $login);
223
224   while (<$in>) {
225     chomp;
226
227     next if (m/^\s*\#/);
228
229     if (m/^\[.*\]/) {
230       $login = $_;
231       $login =~ s/(\[|\])//g;
232       $login =~ s/^\s*//;
233       $login =~ s/\s*$//;
234
235       $members{$login} = { "login" => $login };
236       next;
237     }
238
239     if ($login && m/=/) {
240       my ($key, $value) = split m/\s*=\s*/, $_, 2;
241       $key   =~ s|^\s*||;
242       $value =~ s|\s*$||;
243
244       $value =~ s|\\r||g;
245       $value =~ s|\\n|\n|g;
246
247       $members{$login}->{$key} = $value;
248     }
249   }
250
251   $in->close();
252
253   delete $members{"root login"};
254
255   map { $_->{dbpasswd} = unpack 'u', $_->{dbpasswd} } values %members;
256
257   while (my ($login, $params) = each %members) {
258     $main::auth->save_user($login, %{ $params });
259     $main::auth->change_password($login, $params->{password}, 1);
260
261     my $conf_file = "${memberdir}${login}.conf";
262
263     if (-f $conf_file) {
264       copy   $conf_file, "${backupdir}/${login}.conf";
265       unlink $conf_file;
266     }
267   }
268
269   unlink $main::memberfile;
270
271   my @member_list = sort { lc $a->{login} cmp lc $b->{login} } values %members;
272
273   $form->{title} = $locale->text('User data migration');
274   $form->header();
275   print $form->parse_html_template('admin/user_migration_done', { 'MEMBERS' => \@member_list });
276
277   $main::lxdebug->leave_sub();
278 }
279
280 sub create_standard_group_ask {
281   my $form   = $main::form;
282   my $locale = $main::locale;
283
284   $form->{title} = $locale->text('Create a standard group');
285
286   $form->header();
287   print $form->parse_html_template("admin/create_standard_group_ask");
288 }
289
290 sub create_standard_group {
291   my $form    = $main::form;
292   my $locale  = $main::locale;
293
294   my %members = $main::auth->read_all_users();
295
296   my $groups  = $main::auth->read_groups();
297
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."));
302     }
303   }
304
305   my $group = {
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 ],
310   };
311
312   $main::auth->save_group($group);
313
314   user_migration_complete(1);
315 }
316
317 sub dont_create_standard_group {
318   user_migration_complete(0);
319 }
320
321 sub user_migration_complete {
322   my $standard_group_created = shift;
323
324   my $form                   = $main::form;
325   my $locale                 = $main::locale;
326
327   $form->{title} = $locale->text('User migration complete');
328   $form->header();
329
330   print $form->parse_html_template('admin/user_migration_complete', { 'standard_group_created' => $standard_group_created });
331 }
332
333 sub list_users {
334   my $form    = $main::form;
335   my $locale  = $main::locale;
336
337   my %members = $main::auth->read_all_users();
338
339   delete $members{"root login"};
340
341   map { $_->{templates} =~ s|.*/||; } values %members;
342
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} ];
346
347   $form->header();
348   print $form->parse_html_template("admin/list_users");
349 }
350
351 sub add_user {
352   my $form         = $main::form;
353   my $locale       = $main::locale;
354
355   $form->{title}   = "Lx-Office ERP " . $locale->text('Administration') . " / " . $locale->text('Add User');
356
357 # Note: Menu Style 'v3' is not compatible to all browsers!
358 # "menustyle"    => "old" sets the HTML Menu to default.
359   my $myconfig     = {
360     "vclimit"      => 200,
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',
369   };
370
371
372   edit_user_form($myconfig);
373 }
374
375 sub edit_user {
376   my $form       = $main::form;
377   my $locale     = $main::locale;
378
379   $form->{title} = "Lx-Office ERP " . $locale->text('Administration') . " / " . $locale->text('Edit User');
380   $form->{edit}  = 1;
381
382   $form->isblank("login", $locale->text("The login is missing."));
383
384   # get user
385   my $myconfig = new User($form->{login});
386
387   # strip basedir from templates directory
388   $myconfig->{templates} =~ s|.*/||;
389
390   edit_user_form($myconfig);
391 }
392
393 sub edit_user_form {
394   my ($myconfig) = @_;
395
396   my $form       = $main::form;
397   my $locale     = $main::locale;
398
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 ];
401
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 ];
404
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} };
411   }
412
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));
416   }
417
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;
423
424   @alldir = grep !/\.(html|tex|sty|odt|xml|txb)$/, @alldir;
425   @alldir = grep !/^(webpages|\.svn)$/, @alldir;
426
427   @allhtml = reverse grep !/Default/, @allhtml;
428   push @allhtml, 'Default';
429   @allhtml = reverse @allhtml;
430
431   $form->{ALL_TEMPLATES} = [ map { { "name", => $_, "selected" => $_ eq $myconfig->{templates} } } @alldir ];
432
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) {
437     $item =~ s/-.*//g;
438     next if ($item eq $lastitem);
439
440     push @{ $form->{ALL_MASTER_TEMPLATES} }, { "name" => $item, "selected" => $item eq "German" };
441     $lastitem = $item;
442   }
443
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) ];
447
448   $form->{"menustyle_" . $myconfig->{menustyle} } = 1;
449
450   map { $form->{"myc_${_}"} = $myconfig->{$_} } keys %{ $myconfig };
451
452   my $groups = [];
453
454   if ($form->{edit}) {
455     my $user_id    = $main::auth->get_user_id($form->{login});
456     my $all_groups = $main::auth->read_groups();
457
458     foreach my $group (values %{ $all_groups }) {
459       push @{ $groups }, $group if (grep { $user_id == $_ } @{ $group->{members} });
460     }
461
462     $groups = [ sort { lc $a->{name} cmp lc $b->{name} } @{ $groups } ];
463   }
464
465   $form->{CAN_CHANGE_PASSWORD} = $main::auth->can_change_password();
466
467   $form->header();
468   print $form->parse_html_template("admin/edit_user", { 'GROUPS' => $groups });
469 }
470
471 sub save_user {
472   my $form          = $main::form;
473   my $locale        = $main::locale;
474
475   $form->{dbdriver} = 'Pg';
476
477   # no spaces allowed in login name
478   $form->{login} =~ s|\s||g;
479   $form->isblank("login", $locale->text('Login name missing!'));
480
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);
486     }
487   }
488
489   # no spaces allowed in directories
490   ($form->{newtemplates}) = split / /, $form->{newtemplates};
491
492   if ($form->{newtemplates}) {
493     $form->{templates} = $form->{newtemplates};
494   } else {
495     $form->{templates} =
496       ($form->{usetemplates}) ? $form->{usetemplates} : $form->{login};
497   }
498
499   # is there a basedir
500   if (!-d "$main::templates") {
501     $form->error(sprintf($locale->text("The directory %s does not exist."), $main::templates));
502   }
503
504   # add base directory to $form->{templates}
505   $form->{templates} =~ s|.*/||;
506   $form->{templates} =  "$main::templates/$form->{templates}";
507
508   my $myconfig = new User($form->{login});
509
510   $form->isblank("dbname", $locale->text('Dataset missing!'));
511   $form->isblank("dbuser", $locale->text('Database User missing!'));
512
513   foreach my $item (keys %{$form}) {
514     $myconfig->{$item} = $form->{$item};
515   }
516
517   delete $myconfig->{stylesheet};
518   if ($form->{userstylesheet}) {
519     $myconfig->{stylesheet} = $form->{userstylesheet};
520   }
521
522   $myconfig->save_member();
523
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});
528   }
529
530   $form->{templates}       =~ s|.*/||;
531   $form->{templates}       =  "$main::templates/$form->{templates}";
532   $form->{mastertemplates} =~ s|.*/||;
533
534   # create user template directory and copy master files
535   if (!-d "$form->{templates}") {
536     umask(002);
537
538     if (mkdir "$form->{templates}", oct("771")) {
539
540       umask(007);
541
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)$/,
545         readdir TEMPLATEDIR;
546       closedir TEMPLATEDIR;
547
548       foreach my $file (@templates) {
549         open(TEMP, "$main::templates/$file")
550           or $form->error("$main::templates/$file : $ERRNO");
551
552         $file =~ s/\Q$form->{mastertemplates}\E-//;
553         open(NEW, ">$form->{templates}/$file")
554           or $form->error("$form->{templates}/$file : $ERRNO");
555
556         while (my $line = <TEMP>) {
557           print NEW $line;
558         }
559         close(TEMP);
560         close(NEW);
561       }
562     } else {
563       $form->error("$ERRNO: $form->{templates}");
564     }
565   }
566
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});
571
572     foreach my $group_id (@{ $form->{new_user_group_ids} }) {
573       my $group = $all_groups->{$group_id};
574
575       next if !$group;
576
577       push @{ $group->{members} }, $user{id};
578       $main::auth->save_group($group);
579     }
580   }
581
582   $form->redirect($locale->text('User saved!'));
583
584 }
585
586 sub save_user_as_new {
587   my $form       = $main::form;
588
589   $form->{login} = $form->{new_user_login};
590   delete @{$form}{qw(edit new_user_login)};
591
592   save_user();
593 }
594
595 sub delete_user {
596   my $form      = $main::form;
597   my $locale    = $main::locale;
598
599   my %members   = $main::auth->read_all_users();
600   my $templates = $members{$form->{login}}->{templates};
601
602   $main::auth->delete_user($form->{login});
603
604   if ($templates) {
605     my $templates_in_use = 0;
606
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;
611       last;
612     }
613
614     if (!$templates_in_use && -d $templates) {
615       unlink <$templates/*>;
616       rmdir $templates;
617     }
618   }
619
620   $form->redirect($locale->text('User deleted!'));
621
622 }
623
624 sub login_name {
625   my $login = shift;
626
627   $login =~ s/\[\]//g;
628   return ($login) ? $login : undef;
629
630 }
631
632 sub get_value {
633   my $line           = shift;
634   my ($null, $value) = split(/=/, $line, 2);
635
636   # remove comments
637   $value =~ s/\s#.*//g;
638
639   # remove any trailing whitespace
640   $value =~ s/^\s*(.*?)\s*$/$1/;
641
642   $value;
643 }
644
645 sub pg_database_administration {
646   my $form = $main::form;
647
648   $form->{dbdriver} = 'Pg';
649   dbselect_source();
650
651 }
652
653 sub dbselect_source {
654   my $form           = $main::form;
655   my $locale         = $main::locale;
656
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';
661
662   $form->{title}     = "Lx-Office ERP / " . $locale->text('Database Administration');
663
664   # Intentionnaly disabled unless fixed to work with the authentication DB.
665   $form->{ALLOW_DBBACKUP} = 0; # "$pg_dump_exe" ne "DISABLED";
666
667   $form->header();
668   print $form->parse_html_template("admin/dbadmin");
669 }
670
671 sub test_db_connection {
672   my $form   = $main::form;
673   my $locale = $main::locale;
674
675   $form->{dbdriver} = 'Pg';
676   User::dbconnect_vars($form, $form->{dbname});
677
678   my $dbh = DBI->connect($form->{dbconnect}, $form->{dbuser}, $form->{dbpasswd});
679
680   $form->{connection_ok} = $dbh ? 1 : 0;
681   $form->{errstr}        = $DBI::errstr;
682
683   $dbh->disconnect() if ($dbh);
684
685   $form->{title} = $locale->text('Database Connection Test');
686   $form->header();
687   print $form->parse_html_template("admin/test_db_connection");
688 }
689
690 sub continue {
691   call_sub($main::form->{"nextsub"});
692 }
693
694 sub update_dataset {
695   my $form              = $main::form;
696   my $locale            = $main::locale;
697
698   $form->{title}        = "Lx-Office ERP " . $locale->text('Database Administration') . " / " . $locale->text('Update Dataset');
699
700   my @need_updates      = User->dbneedsupdate($form);
701   $form->{NEED_UPDATES} = \@need_updates;
702   $form->{ALL_UPDATED}  = !scalar @need_updates;
703
704   $form->header();
705   print $form->parse_html_template("admin/update_dataset");
706 }
707
708 sub dbupdate {
709   my $form            = $main::form;
710   my $locale          = $main::locale;
711
712   $form->{stylesheet} = "lx-office-erp.css";
713   $form->{title}      = $locale->text("Dataset upgrade");
714   $form->header();
715
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();
720
721   $| = 1;
722
723   print $form->parse_html_template("admin/dbupgrade_all_header");
724
725   foreach my $i (@update_rows) {
726     restore_form($saved_form);
727
728     map { $form->{$_} = $form->{"${_}_${i}"} } qw(dbname dbdriver dbhost dbport dbuser dbpasswd);
729
730     print $form->parse_html_template("admin/dbupgrade_header");
731
732     $form->{dbupdate}        = $form->{dbname};
733     $form->{$form->{dbname}} = 1;
734
735     User->dbupdate($form);
736     User->dbupdate2($form, SL::DBUpgrade2->new(form => $form, dbdriver => $form->{dbdriver})->parse_dbupdate_controls);
737
738     print $form->parse_html_template("admin/dbupgrade_footer");
739   }
740
741   print $form->parse_html_template("admin/dbupgrade_all_done");
742 }
743
744 sub create_dataset {
745   my $form           = $main::form;
746   my $locale         = $main::locale;
747
748   $form->{dbsources} = join " ", map { "[${_}]" } sort User->dbsources($form);
749
750   $form->{CHARTS}    = [];
751
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" };
758   }
759   closedir SQLDIR;
760
761   my $default_charset = $main::dbcharset;
762   $default_charset ||= Common::DEFAULT_CHARSET;
763
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.'),
769                                 'back_button' => 1);
770     }
771
772     $form->{FORCE_DBENCODING} = 'UNICODE';
773
774   } else {
775     $form->{DBENCODINGS} = [];
776
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 };
781     }
782   }
783
784   $form->{title} = "Lx-Office ERP " . $locale->text('Database Administration') . " / " . $locale->text('Create Dataset');
785
786   $form->header();
787   print $form->parse_html_template("admin/create_dataset");
788 }
789
790 sub dbcreate {
791   my $form   = $main::form;
792   my $locale = $main::locale;
793
794   $form->isblank("db", $locale->text('Dataset missing!'));
795
796   User->dbcreate(\%$form);
797
798   $form->{title} = "Lx-Office ERP " . $locale->text('Database Administration') . " / " . $locale->text('Create Dataset');
799
800   $form->header();
801   print $form->parse_html_template("admin/dbcreate");
802 }
803
804 sub delete_dataset {
805   my $form      = $main::form;
806   my $locale    = $main::locale;
807
808   my @dbsources = User->dbsources_unused($form);
809   $form->error($locale->text('Nothing to delete!')) unless @dbsources;
810
811   $form->{title}     = "Lx-Office ERP " . $locale->text('Database Administration') . " / " . $locale->text('Delete Dataset');
812   $form->{DBSOURCES} = [ map { { "name", $_ } } sort @dbsources ];
813
814   $form->header();
815   print $form->parse_html_template("admin/delete_dataset");
816 }
817
818 sub dbdelete {
819   my $form   = $main::form;
820   my $locale = $main::locale;
821
822   if (!$form->{db}) {
823     $form->error($locale->text('No Dataset selected!'));
824   }
825
826   User->dbdelete(\%$form);
827
828   $form->{title} = "Lx-Office ERP " . $locale->text('Database Administration') . " / " . $locale->text('Delete Dataset');
829   $form->header();
830   print $form->parse_html_template("admin/dbdelete");
831 }
832
833 sub backup_dataset {
834   my $form       = $main::form;
835   my $locale     = $main::locale;
836
837   $form->{title} = "Lx-Office ERP " . $locale->text('Database Administration') . " / " . $locale->text('Backup Dataset');
838
839   if ("$main::pg_dump_exe" eq "DISABLED") {
840     $form->error($locale->text('Database backups and restorations are disabled in lx-erp.conf.'));
841   }
842
843   my @dbsources         = sort User->dbsources($form);
844   $form->{DATABASES}    = [ map { { "dbname" => $_ } } @dbsources ];
845   $form->{NO_DATABASES} = !scalar @dbsources;
846
847   my $username  = getpwuid $UID || "unknown-user";
848   my $hostname  = hostname() || "unknown-host";
849   $form->{from} = "Lx-Office Admin <${username}\@${hostname}>";
850
851   $form->header();
852   print $form->parse_html_template("admin/backup_dataset");
853 }
854
855 sub backup_dataset_start {
856   my $form       = $main::form;
857   my $locale     = $main::locale;
858
859   $form->{title} = "Lx-Office ERP " . $locale->text('Database Administration') . " / " . $locale->text('Backup Dataset');
860
861   $main::pg_dump_exe ||= "pg_dump";
862
863   if ("$main::pg_dump_exe" eq "DISABLED") {
864     $form->error($locale->text('Database backups and restorations are disabled in lx-erp.conf.'));
865   }
866
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";
869
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");
872
873   my $pgpass = IO::File->new("${tmpdir}/.pgpass", O_WRONLY | O_CREAT, 0600);
874
875   if (!$pgpass) {
876     unlink $tmpdir;
877     $form->error($locale->text('A temporary file could not be created:') . " $ERRNO");
878   }
879
880   print $pgpass "$form->{dbhost}:$form->{dbport}:$form->{dbname}:$form->{dbuser}:$form->{dbpasswd}\n";
881   $pgpass->close();
882
883   $ENV{HOME} = $tmpdir;
884
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};
888
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";
891
892   if ($form->{destination} ne "email") {
893     my $in = IO::File->new("$cmd |");
894
895     if (!$in) {
896       unlink "${tmpdir}/.pgpass";
897       rmdir $tmpdir;
898
899       $form->error($locale->text('The pg_dump process could not be started.'));
900     }
901
902     print "content-type: application/x-tar\n";
903     print "content-disposition: attachment; filename=\"${name}\"\n\n";
904
905     while (my $line = <$in>) {
906       print $line;
907     }
908
909     $in->close();
910
911     unlink "${tmpdir}/.pgpass";
912     rmdir $tmpdir;
913
914   } else {
915     my $tmp = $tmpdir . "/dump_" . Common::unique_id();
916
917     if (system("$cmd > $tmp") != 0) {
918       unlink "${tmpdir}/.pgpass", $tmp;
919       rmdir $tmpdir;
920
921       $form->error($locale->text('The pg_dump process could not be started.'));
922     }
923
924     my $mail = new Mailer;
925
926     map { $mail->{$_} = $form->{$_} } qw(from to cc subject message);
927
928     $mail->{charset}     = $main::dbcharset ? $main::dbcharset : Common::DEFAULT_CHARSET;
929     $mail->{attachments} = [ { "filename" => $tmp, "name" => $name } ];
930     $mail->send();
931
932     unlink "${tmpdir}/.pgpass", $tmp;
933     rmdir $tmpdir;
934
935     $form->{title} = "Lx-Office ERP " . $locale->text('Database Administration') . " / " . $locale->text('Backup Dataset');
936
937     $form->header();
938     print $form->parse_html_template("admin/backup_dataset_email_done");
939   }
940 }
941
942 sub restore_dataset {
943   my $form       = $main::form;
944   my $locale     = $main::locale;
945
946   $form->{title} = "Lx-Office ERP " . $locale->text('Database Administration') . " / " . $locale->text('Restore Dataset');
947
948   if ("$main::pg_restore_exe" eq "DISABLED") {
949     $form->error($locale->text('Database backups and restorations are disabled in lx-erp.conf.'));
950   }
951
952   my $default_charset   = $main::dbcharset;
953   $default_charset    ||= Common::DEFAULT_CHARSET;
954
955   $form->{DBENCODINGS}  = [];
956
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 };
961   }
962
963   $form->header();
964   print $form->parse_html_template("admin/restore_dataset");
965 }
966
967 sub restore_dataset_start {
968   my $form       = $main::form;
969   my $locale     = $main::locale;
970
971   $form->{title} = "Lx-Office ERP " . $locale->text('Database Administration') . " / " . $locale->text('Restore Dataset');
972
973   $main::pg_restore_exe ||= "pg_restore";
974
975   if ("$main::pg_restore_exe" eq "DISABLED") {
976     $form->error($locale->text('Database backups and restorations are disabled in lx-erp.conf.'));
977   }
978
979   $form->isblank("new_dbname", $locale->text('The dataset name is missing.'));
980   $form->isblank("content", $locale->text('No backup file has been uploaded.'));
981
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
984   # utility.
985
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");
988
989   my $pgpass = IO::File->new("${tmpdir}/.pgpass", O_WRONLY | O_CREAT, 0600);
990
991   if (!$pgpass) {
992     unlink $tmpdir;
993     $form->error($locale->text('A temporary file could not be created:') . " $ERRNO");
994   }
995
996   print $pgpass "$form->{dbhost}:$form->{dbport}:$form->{new_dbname}:$form->{dbuser}:$form->{dbpasswd}\n";
997   $pgpass->close();
998
999   $ENV{HOME} = $tmpdir;
1000
1001   my $tmp = $tmpdir . "/dump_" . Common::unique_id();
1002   my $tmpfile;
1003
1004   if (substr($form->{content}, 0, 2) eq "\037\213") {
1005     $tmpfile = IO::File->new("| gzip -d > $tmp");
1006     $tmpfile->binary();
1007
1008   } else {
1009     $tmpfile = IO::File->new($tmp, O_WRONLY | O_CREAT | O_BINARY, 0600);
1010   }
1011
1012   if (!$tmpfile) {
1013     unlink "${tmpdir}/.pgpass";
1014     rmdir $tmpdir;
1015
1016     $form->error($locale->text('A temporary file could not be created:') . " $ERRNO");
1017   }
1018
1019   print $tmpfile $form->{content};
1020   $tmpfile->close();
1021
1022   delete $form->{content};
1023
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.
1027
1028   User::dbconnect_vars($form, "template1");
1029
1030   my %myconfig = map { $_ => $form->{$_} } grep /^db/, keys %{ $form };
1031   my $dbh      = $form->dbconnect(\%myconfig) || $form->dberror();
1032
1033   my ($query, $sth);
1034
1035   $form->{new_dbname} =~ s|[^a-zA-Z0-9_\-]||g;
1036
1037   $query = qq|SELECT COUNT(*) FROM pg_database WHERE datname = ?|;
1038   my ($count) = selectrow_query($form, $dbh, $query, $form->{new_dbname});
1039   if ($count) {
1040     do_query($form, $dbh, qq|DROP DATABASE $form->{new_dbname}|);
1041   }
1042
1043   my $found = 0;
1044   foreach my $item (@Common::db_encodings) {
1045     if ($item->{dbencoding} eq $form->{dbencoding}) {
1046       $found = 1;
1047       last;
1048     }
1049   }
1050   $form->{dbencoding} = "LATIN9" unless $form->{dbencoding};
1051
1052   do_query($form, $dbh, qq|CREATE DATABASE $form->{new_dbname} ENCODING ? TEMPLATE template0|, $form->{dbencoding});
1053
1054   $dbh->disconnect();
1055
1056   # Spawn pg_restore on the temporary file.
1057
1058   my @args = ("-h", $form->{dbhost}, "-U", $form->{dbuser}, "-d", $form->{new_dbname});
1059   push @args, ("-p", $form->{dbport}) if ($form->{dbport});
1060   push @args, $tmp;
1061
1062   my $cmd = "$main::pg_restore_exe " . join(" ", map { s/\\/\\\\/g; s/\"/\\\"/g; $_ } @args);
1063
1064   my $in = IO::File->new("$cmd 2>&1 |");
1065
1066   if (!$in) {
1067     unlink "${tmpdir}/.pgpass", $tmp;
1068     rmdir $tmpdir;
1069
1070     $form->error($locale->text('The pg_restore process could not be started.'));
1071   }
1072
1073   $English::AUTOFLUSH = 1;
1074
1075   $form->header();
1076   print $form->parse_html_template("admin/restore_dataset_start_header");
1077
1078   while (my $line = <$in>) {
1079     print $line;
1080   }
1081   $in->close();
1082
1083   $form->{retval} = $CHILD_ERROR >> 8;
1084   print $form->parse_html_template("admin/restore_dataset_start_footer");
1085
1086   unlink "${tmpdir}/.pgpass", $tmp;
1087   rmdir $tmpdir;
1088 }
1089
1090 sub unlock_system {
1091   my $form   = $main::form;
1092   my $locale = $main::locale;
1093
1094   unlink "$main::userspath/nologin";
1095
1096   $form->{callback} = "admin.pl?action=list_users";
1097
1098   $form->redirect($locale->text('Lockfile removed!'));
1099
1100 }
1101
1102 sub lock_system {
1103   my $form   = $main::form;
1104   my $locale = $main::locale;
1105
1106   open(FH, ">$main::userspath/nologin")
1107     or $form->error($locale->text('Cannot create Lock!'));
1108   close(FH);
1109
1110   $form->{callback} = "admin.pl?action=list_users";
1111
1112   $form->redirect($locale->text('Lockfile created!'));
1113
1114 }
1115
1116 sub yes {
1117   call_sub($main::form->{yes_nextsub});
1118 }
1119
1120 sub no {
1121   call_sub($main::form->{no_nextsub});
1122 }
1123
1124 sub add {
1125   call_sub($main::form->{add_nextsub});
1126 }
1127
1128 sub edit {
1129   my $form = $main::form;
1130
1131   $form->{edit_nextsub} ||= 'edit_user';
1132
1133   call_sub($form->{edit_nextsub});
1134 }
1135
1136 sub delete {
1137   my $form     = $main::form;
1138
1139   $form->{delete_nextsub} ||= 'delete_user';
1140
1141   call_sub($form->{delete_nextsub});
1142 }
1143
1144 sub save {
1145   my $form = $main::form;
1146
1147   $form->{save_nextsub} ||= 'save_user';
1148
1149   call_sub($form->{save_nextsub});
1150 }
1151
1152 sub back {
1153   call_sub($main::form->{back_nextsub});
1154 }
1155
1156 sub dispatcher {
1157   my $form   = $main::form;
1158   my $locale = $main::locale;
1159
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}"}) {
1163       call_sub($action);
1164       return;
1165     }
1166   }
1167
1168   call_sub($form->{default_action}) if ($form->{default_action});
1169
1170   $form->error($locale->text('No action defined.'));
1171 }
1172
1173 sub _apply_dbupgrade_scripts {
1174   ::end_of_request() if SL::DBUpgrade2->new(form => $::form, dbdriver => 'Pg', auth => 1)->apply_admin_dbupgrade_scripts(1);
1175 }
1176
1177 1;