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