Admin-DB-Upgrade-Funktion nach DBUpgrade2 verschoben
[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::Iconv;
47 use SL::Mailer;
48 use SL::User;
49 use SL::Common;
50 use SL::Inifile;
51 use SL::DBUpgrade2;
52 use SL::DBUtils;
53
54 require "bin/mozilla/common.pl";
55 require "bin/mozilla/admin_groups.pl";
56 require "bin/mozilla/admin_printer.pl";
57
58 use strict;
59
60 our $cgi;
61 our $form;
62 our $locale;
63 our $auth;
64
65 sub run {
66   $::lxdebug->enter_sub;
67   my $session_result = shift;
68
69   $cgi    = $::cgi;
70   $form   = $::form;
71   $locale = $::locale;
72   $auth   = $::auth;
73
74   $::auth->set_session_value('rpw', $::form->{rpw}) if $session_result == SL::Auth->SESSION_OK;
75
76   $form->{stylesheet} = "lx-office-erp.css";
77   $form->{favicon}    = "favicon.ico";
78
79   if ($form->{action}) {
80     if ($auth->authenticate_root($form->{rpw}, 0) != $auth->OK()) {
81       $form->{error_message} = $locale->text('Incorrect Password!');
82       adminlogin();
83     } else {
84       if ($auth->session_tables_present()) {
85         $::auth->set_session_value('rpw', $::form->{rpw});
86         $::auth->create_or_refresh_session();
87       }
88
89       _apply_dbupgrade_scripts();
90
91       call_sub($locale->findsub($form->{action}));
92     }
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     print $form->parse_html_template("admin/dbupgrade_header");
727
728     $form->{dbupdate}        = $form->{dbname};
729     $form->{$form->{dbname}} = 1;
730
731     User->dbupdate($form);
732     User->dbupdate2($form, SL::DBUpgrade2->new(form => $form, dbdriver => $form->{dbdriver})->parse_dbupdate_controls);
733
734     print $form->parse_html_template("admin/dbupgrade_footer");
735   }
736
737   print $form->parse_html_template("admin/dbupgrade_all_done");
738 }
739
740 sub create_dataset {
741   my $form           = $main::form;
742   my $locale         = $main::locale;
743
744   $form->{dbsources} = join " ", map { "[${_}]" } sort User->dbsources($form);
745
746   $form->{CHARTS}    = [];
747
748   opendir SQLDIR, "sql/." or $form->error($ERRNO);
749   foreach my $item (sort grep /-chart\.sql\z/, readdir SQLDIR) {
750     next if ($item eq 'Default-chart.sql');
751     $item =~ s/-chart\.sql//;
752     push @{ $form->{CHARTS} }, { "name"     => $item,
753                                  "selected" => $item eq "Germany-DATEV-SKR03EU" };
754   }
755   closedir SQLDIR;
756
757   my $default_charset = $main::dbcharset;
758   $default_charset ||= Common::DEFAULT_CHARSET;
759
760   my $cluster_encoding = User->dbclusterencoding($form);
761   if ($cluster_encoding && ($cluster_encoding =~ m/^(?:UTF-?8|UNICODE)$/i)) {
762     if ($main::dbcharset !~ m/^UTF-?8$/i) {
763       $form->show_generic_error($locale->text('The selected  PostgreSQL installation uses UTF-8 as its encoding. ' .
764                                               'Therefore you have to configure Lx-Office to use UTF-8 as well.'),
765                                 'back_button' => 1);
766     }
767
768     $form->{FORCE_DBENCODING} = 'UNICODE';
769
770   } else {
771     $form->{DBENCODINGS} = [];
772
773     foreach my $encoding (@Common::db_encodings) {
774       push @{ $form->{DBENCODINGS} }, { "dbencoding" => $encoding->{dbencoding},
775                                         "label"      => $encoding->{label},
776                                         "selected"   => $encoding->{charset} eq $default_charset };
777     }
778   }
779
780   $form->{title} = "Lx-Office ERP " . $locale->text('Database Administration') . " / " . $locale->text('Create Dataset');
781
782   $form->header();
783   print $form->parse_html_template("admin/create_dataset");
784 }
785
786 sub dbcreate {
787   my $form   = $main::form;
788   my $locale = $main::locale;
789
790   $form->isblank("db", $locale->text('Dataset missing!'));
791
792   User->dbcreate(\%$form);
793
794   $form->{title} = "Lx-Office ERP " . $locale->text('Database Administration') . " / " . $locale->text('Create Dataset');
795
796   $form->header();
797   print $form->parse_html_template("admin/dbcreate");
798 }
799
800 sub delete_dataset {
801   my $form      = $main::form;
802   my $locale    = $main::locale;
803
804   my @dbsources = User->dbsources_unused($form);
805   $form->error($locale->text('Nothing to delete!')) unless @dbsources;
806
807   $form->{title}     = "Lx-Office ERP " . $locale->text('Database Administration') . " / " . $locale->text('Delete Dataset');
808   $form->{DBSOURCES} = [ map { { "name", $_ } } sort @dbsources ];
809
810   $form->header();
811   print $form->parse_html_template("admin/delete_dataset");
812 }
813
814 sub dbdelete {
815   my $form   = $main::form;
816   my $locale = $main::locale;
817
818   if (!$form->{db}) {
819     $form->error($locale->text('No Dataset selected!'));
820   }
821
822   User->dbdelete(\%$form);
823
824   $form->{title} = "Lx-Office ERP " . $locale->text('Database Administration') . " / " . $locale->text('Delete Dataset');
825   $form->header();
826   print $form->parse_html_template("admin/dbdelete");
827 }
828
829 sub backup_dataset {
830   my $form       = $main::form;
831   my $locale     = $main::locale;
832
833   $form->{title} = "Lx-Office ERP " . $locale->text('Database Administration') . " / " . $locale->text('Backup Dataset');
834
835   if ("$main::pg_dump_exe" eq "DISABLED") {
836     $form->error($locale->text('Database backups and restorations are disabled in lx-erp.conf.'));
837   }
838
839   my @dbsources         = sort User->dbsources($form);
840   $form->{DATABASES}    = [ map { { "dbname" => $_ } } @dbsources ];
841   $form->{NO_DATABASES} = !scalar @dbsources;
842
843   my $username  = getpwuid $UID || "unknown-user";
844   my $hostname  = hostname() || "unknown-host";
845   $form->{from} = "Lx-Office Admin <${username}\@${hostname}>";
846
847   $form->header();
848   print $form->parse_html_template("admin/backup_dataset");
849 }
850
851 sub backup_dataset_start {
852   my $form       = $main::form;
853   my $locale     = $main::locale;
854
855   $form->{title} = "Lx-Office ERP " . $locale->text('Database Administration') . " / " . $locale->text('Backup Dataset');
856
857   $main::pg_dump_exe ||= "pg_dump";
858
859   if ("$main::pg_dump_exe" eq "DISABLED") {
860     $form->error($locale->text('Database backups and restorations are disabled in lx-erp.conf.'));
861   }
862
863   $form->isblank("dbname", $locale->text('The dataset name is missing.'));
864   $form->isblank("to", $locale->text('The email address is missing.')) if $form->{destination} eq "email";
865
866   my $tmpdir = "/tmp/lx_office_backup_" . Common->unique_id();
867   mkdir $tmpdir, 0700 || $form->error($locale->text('A temporary directory could not be created:') . " $ERRNO");
868
869   my $pgpass = IO::File->new("${tmpdir}/.pgpass", O_WRONLY | O_CREAT, 0600);
870
871   if (!$pgpass) {
872     unlink $tmpdir;
873     $form->error($locale->text('A temporary file could not be created:') . " $ERRNO");
874   }
875
876   print $pgpass "$form->{dbhost}:$form->{dbport}:$form->{dbname}:$form->{dbuser}:$form->{dbpasswd}\n";
877   $pgpass->close();
878
879   $ENV{HOME} = $tmpdir;
880
881   my @args = ("-Ft", "-c", "-o", "-h", $form->{dbhost}, "-U", $form->{dbuser});
882   push @args, ("-p", $form->{dbport}) if ($form->{dbport});
883   push @args, $form->{dbname};
884
885   my $cmd  = "$main::pg_dump_exe " . join(" ", map { s/\\/\\\\/g; s/\"/\\\"/g; $_ } @args);
886   my $name = "dataset_backup_$form->{dbname}_" . strftime("%Y%m%d", localtime()) . ".tar";
887
888   if ($form->{destination} ne "email") {
889     my $in = IO::File->new("$cmd |");
890
891     if (!$in) {
892       unlink "${tmpdir}/.pgpass";
893       rmdir $tmpdir;
894
895       $form->error($locale->text('The pg_dump process could not be started.'));
896     }
897
898     print "content-type: application/x-tar\n";
899     print "content-disposition: attachment; filename=\"${name}\"\n\n";
900
901     while (my $line = <$in>) {
902       print $line;
903     }
904
905     $in->close();
906
907     unlink "${tmpdir}/.pgpass";
908     rmdir $tmpdir;
909
910   } else {
911     my $tmp = $tmpdir . "/dump_" . Common::unique_id();
912
913     if (system("$cmd > $tmp") != 0) {
914       unlink "${tmpdir}/.pgpass", $tmp;
915       rmdir $tmpdir;
916
917       $form->error($locale->text('The pg_dump process could not be started.'));
918     }
919
920     my $mail = new Mailer;
921
922     map { $mail->{$_} = $form->{$_} } qw(from to cc subject message);
923
924     $mail->{charset}     = $main::dbcharset ? $main::dbcharset : Common::DEFAULT_CHARSET;
925     $mail->{attachments} = [ { "filename" => $tmp, "name" => $name } ];
926     $mail->send();
927
928     unlink "${tmpdir}/.pgpass", $tmp;
929     rmdir $tmpdir;
930
931     $form->{title} = "Lx-Office ERP " . $locale->text('Database Administration') . " / " . $locale->text('Backup Dataset');
932
933     $form->header();
934     print $form->parse_html_template("admin/backup_dataset_email_done");
935   }
936 }
937
938 sub restore_dataset {
939   my $form       = $main::form;
940   my $locale     = $main::locale;
941
942   $form->{title} = "Lx-Office ERP " . $locale->text('Database Administration') . " / " . $locale->text('Restore Dataset');
943
944   if ("$main::pg_restore_exe" eq "DISABLED") {
945     $form->error($locale->text('Database backups and restorations are disabled in lx-erp.conf.'));
946   }
947
948   my $default_charset   = $main::dbcharset;
949   $default_charset    ||= Common::DEFAULT_CHARSET;
950
951   $form->{DBENCODINGS}  = [];
952
953   foreach my $encoding (@Common::db_encodings) {
954     push @{ $form->{DBENCODINGS} }, { "dbencoding" => $encoding->{dbencoding},
955                                       "label"      => $encoding->{label},
956                                       "selected"   => $encoding->{charset} eq $default_charset };
957   }
958
959   $form->header();
960   print $form->parse_html_template("admin/restore_dataset");
961 }
962
963 sub restore_dataset_start {
964   my $form       = $main::form;
965   my $locale     = $main::locale;
966
967   $form->{title} = "Lx-Office ERP " . $locale->text('Database Administration') . " / " . $locale->text('Restore Dataset');
968
969   $main::pg_restore_exe ||= "pg_restore";
970
971   if ("$main::pg_restore_exe" eq "DISABLED") {
972     $form->error($locale->text('Database backups and restorations are disabled in lx-erp.conf.'));
973   }
974
975   $form->isblank("new_dbname", $locale->text('The dataset name is missing.'));
976   $form->isblank("content", $locale->text('No backup file has been uploaded.'));
977
978   # Create temporary directories. Write the backup file contents to a temporary
979   # file. Create a .pgpass file with the username and password for the pg_restore
980   # utility.
981
982   my $tmpdir = "/tmp/lx_office_backup_" . Common->unique_id();
983   mkdir $tmpdir, 0700 || $form->error($locale->text('A temporary directory could not be created:') . " $ERRNO");
984
985   my $pgpass = IO::File->new("${tmpdir}/.pgpass", O_WRONLY | O_CREAT, 0600);
986
987   if (!$pgpass) {
988     unlink $tmpdir;
989     $form->error($locale->text('A temporary file could not be created:') . " $ERRNO");
990   }
991
992   print $pgpass "$form->{dbhost}:$form->{dbport}:$form->{new_dbname}:$form->{dbuser}:$form->{dbpasswd}\n";
993   $pgpass->close();
994
995   $ENV{HOME} = $tmpdir;
996
997   my $tmp = $tmpdir . "/dump_" . Common::unique_id();
998   my $tmpfile;
999
1000   if (substr($form->{content}, 0, 2) eq "\037\213") {
1001     $tmpfile = IO::File->new("| gzip -d > $tmp");
1002     $tmpfile->binary();
1003
1004   } else {
1005     $tmpfile = IO::File->new($tmp, O_WRONLY | O_CREAT | O_BINARY, 0600);
1006   }
1007
1008   if (!$tmpfile) {
1009     unlink "${tmpdir}/.pgpass";
1010     rmdir $tmpdir;
1011
1012     $form->error($locale->text('A temporary file could not be created:') . " $ERRNO");
1013   }
1014
1015   print $tmpfile $form->{content};
1016   $tmpfile->close();
1017
1018   delete $form->{content};
1019
1020   # Try to connect to the database. Find out if a database with the same name exists.
1021   # If yes, then drop the existing database. Create a new one with the name and encoding
1022   # given by the user.
1023
1024   User::dbconnect_vars($form, "template1");
1025
1026   my %myconfig = map { $_ => $form->{$_} } grep /^db/, keys %{ $form };
1027   my $dbh      = $form->dbconnect(\%myconfig) || $form->dberror();
1028
1029   my ($query, $sth);
1030
1031   $form->{new_dbname} =~ s|[^a-zA-Z0-9_\-]||g;
1032
1033   $query = qq|SELECT COUNT(*) FROM pg_database WHERE datname = ?|;
1034   my ($count) = selectrow_query($form, $dbh, $query, $form->{new_dbname});
1035   if ($count) {
1036     do_query($form, $dbh, qq|DROP DATABASE $form->{new_dbname}|);
1037   }
1038
1039   my $found = 0;
1040   foreach my $item (@Common::db_encodings) {
1041     if ($item->{dbencoding} eq $form->{dbencoding}) {
1042       $found = 1;
1043       last;
1044     }
1045   }
1046   $form->{dbencoding} = "LATIN9" unless $form->{dbencoding};
1047
1048   do_query($form, $dbh, qq|CREATE DATABASE $form->{new_dbname} ENCODING ? TEMPLATE template0|, $form->{dbencoding});
1049
1050   $dbh->disconnect();
1051
1052   # Spawn pg_restore on the temporary file.
1053
1054   my @args = ("-h", $form->{dbhost}, "-U", $form->{dbuser}, "-d", $form->{new_dbname});
1055   push @args, ("-p", $form->{dbport}) if ($form->{dbport});
1056   push @args, $tmp;
1057
1058   my $cmd = "$main::pg_restore_exe " . join(" ", map { s/\\/\\\\/g; s/\"/\\\"/g; $_ } @args);
1059
1060   my $in = IO::File->new("$cmd 2>&1 |");
1061
1062   if (!$in) {
1063     unlink "${tmpdir}/.pgpass", $tmp;
1064     rmdir $tmpdir;
1065
1066     $form->error($locale->text('The pg_restore process could not be started.'));
1067   }
1068
1069   $English::AUTOFLUSH = 1;
1070
1071   $form->header();
1072   print $form->parse_html_template("admin/restore_dataset_start_header");
1073
1074   while (my $line = <$in>) {
1075     print $line;
1076   }
1077   $in->close();
1078
1079   $form->{retval} = $CHILD_ERROR >> 8;
1080   print $form->parse_html_template("admin/restore_dataset_start_footer");
1081
1082   unlink "${tmpdir}/.pgpass", $tmp;
1083   rmdir $tmpdir;
1084 }
1085
1086 sub unlock_system {
1087   my $form   = $main::form;
1088   my $locale = $main::locale;
1089
1090   unlink "$main::userspath/nologin";
1091
1092   $form->{callback} = "admin.pl?action=list_users";
1093
1094   $form->redirect($locale->text('Lockfile removed!'));
1095
1096 }
1097
1098 sub lock_system {
1099   my $form   = $main::form;
1100   my $locale = $main::locale;
1101
1102   open(FH, ">$main::userspath/nologin")
1103     or $form->error($locale->text('Cannot create Lock!'));
1104   close(FH);
1105
1106   $form->{callback} = "admin.pl?action=list_users";
1107
1108   $form->redirect($locale->text('Lockfile created!'));
1109
1110 }
1111
1112 sub yes {
1113   call_sub($main::form->{yes_nextsub});
1114 }
1115
1116 sub no {
1117   call_sub($main::form->{no_nextsub});
1118 }
1119
1120 sub add {
1121   call_sub($main::form->{add_nextsub});
1122 }
1123
1124 sub edit {
1125   my $form = $main::form;
1126
1127   $form->{edit_nextsub} ||= 'edit_user';
1128
1129   call_sub($form->{edit_nextsub});
1130 }
1131
1132 sub delete {
1133   my $form     = $main::form;
1134
1135   $form->{delete_nextsub} ||= 'delete_user';
1136
1137   call_sub($form->{delete_nextsub});
1138 }
1139
1140 sub save {
1141   my $form = $main::form;
1142
1143   $form->{save_nextsub} ||= 'save_user';
1144
1145   call_sub($form->{save_nextsub});
1146 }
1147
1148 sub back {
1149   call_sub($main::form->{back_nextsub});
1150 }
1151
1152 sub dispatcher {
1153   my $form   = $main::form;
1154   my $locale = $main::locale;
1155
1156   foreach my $action (qw(create_standard_group dont_create_standard_group
1157                          save_user delete_user save_user_as_new)) {
1158     if ($form->{"action_${action}"}) {
1159       call_sub($action);
1160       return;
1161     }
1162   }
1163
1164   call_sub($form->{default_action}) if ($form->{default_action});
1165
1166   $form->error($locale->text('No action defined.'));
1167 }
1168
1169 sub _apply_dbupgrade_scripts {
1170   SL::DBUpgrade2->new(form => $::form, dbdriver => 'Pg', auth => 1)->parse_dbupdate_controls->apply_admin_dbupgrade_scripts(1);
1171 }
1172
1173 1;