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