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