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