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