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