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