eee799958f92a7173a98634dd926e4ffd91b35a6
[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   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     dbport         => $::auth->{DB_config}->{port} || 5432,
367     dbuser         => $::auth->{DB_config}->{user} || 'lxoffice',
368     dbhost         => $::auth->{DB_config}->{host} || 'localhost',
369   };
370
371
372   edit_user_form($myconfig);
373 }
374
375 sub edit_user {
376   my $form       = $main::form;
377   my $locale     = $main::locale;
378
379   $form->{title} = "Lx-Office ERP " . $locale->text('Administration') . " / " . $locale->text('Edit User');
380   $form->{edit}  = 1;
381
382   $form->isblank("login", $locale->text("The login is missing."));
383
384   # get user
385   my $myconfig = new User($form->{login});
386
387   # strip basedir from templates directory
388   $myconfig->{templates} =~ s|.*/||;
389
390   edit_user_form($myconfig);
391 }
392
393 sub edit_user_form {
394   my ($myconfig) = @_;
395
396   my $form       = $main::form;
397   my $locale     = $main::locale;
398
399   my @valid_dateformats = qw(mm-dd-yy mm/dd/yy dd-mm-yy dd/mm/yy dd.mm.yy yyyy-mm-dd);
400   $form->{ALL_DATEFORMATS} = [ map { { "format" => $_, "selected" => $_ eq $myconfig->{dateformat} } } @valid_dateformats ];
401
402   my @valid_numberformats = ('1,000.00', '1000.00', '1.000,00', '1000,00');
403   $form->{ALL_NUMBERFORMATS} = [ map { { "format" => $_, "selected" => $_ eq $myconfig->{numberformat} } } @valid_numberformats ];
404
405   my %countrycodes = User->country_codes;
406   $form->{ALL_COUNTRYCODES} = [];
407   foreach my $countrycode (sort { $countrycodes{$a} cmp $countrycodes{$b} } keys %countrycodes) {
408     push @{ $form->{ALL_COUNTRYCODES} }, { "value"    => $countrycode,
409                                            "name"     => $countrycodes{$countrycode},
410                                            "selected" => $countrycode eq $myconfig->{countrycode} };
411   }
412
413   # is there a templates basedir
414   if (!-d "$main::templates") {
415     $form->error(sprintf($locale->text("The directory %s does not exist."), $main::templates));
416   }
417
418   opendir TEMPLATEDIR, "$main::templates/." or $form->error("$main::templates : $ERRNO");
419   my @all     = readdir(TEMPLATEDIR);
420   my @alldir  = sort grep { -d "$main::templates/$_" && !/^\.\.?$/ } @all;
421   my @allhtml = sort grep { -f "$main::templates/$_" && /\.html$/ } @all;
422   closedir TEMPLATEDIR;
423
424   @alldir = grep !/\.(html|tex|sty|odt|xml|txb)$/, @alldir;
425   @alldir = grep !/^(webpages|\.svn)$/, @alldir;
426
427   @allhtml = reverse grep !/Default/, @allhtml;
428   push @allhtml, 'Default';
429   @allhtml = reverse @allhtml;
430
431   $form->{ALL_TEMPLATES} = [ map { { "name", => $_, "selected" => $_ eq $myconfig->{templates} } } @alldir ];
432
433   my $lastitem = $allhtml[0];
434   $lastitem =~ s/-.*//g;
435   $form->{ALL_MASTER_TEMPLATES} = [ { "name" => $lastitem, "selected" => $lastitem eq "German" } ];
436   foreach my $item (@allhtml) {
437     $item =~ s/-.*//g;
438     next if ($item eq $lastitem);
439
440     push @{ $form->{ALL_MASTER_TEMPLATES} }, { "name" => $item, "selected" => $item eq "German" };
441     $lastitem = $item;
442   }
443
444   # css dir has styles that are not intended as general layouts.
445   # reverting to hardcoded list
446   $form->{ALL_STYLESHEETS} = [ map { { "name" => $_, "selected" => $_ eq $myconfig->{stylesheet} } } qw(lx-office-erp.css Win2000.css) ];
447
448   $form->{"menustyle_" . $myconfig->{menustyle} } = 1;
449
450   map { $form->{"myc_${_}"} = $myconfig->{$_} } keys %{ $myconfig };
451
452   my $groups = [];
453
454   if ($form->{edit}) {
455     my $user_id    = $main::auth->get_user_id($form->{login});
456     my $all_groups = $main::auth->read_groups();
457
458     foreach my $group (values %{ $all_groups }) {
459       push @{ $groups }, $group if (grep { $user_id == $_ } @{ $group->{members} });
460     }
461
462     $groups = [ sort { lc $a->{name} cmp lc $b->{name} } @{ $groups } ];
463   }
464
465   $form->{CAN_CHANGE_PASSWORD} = $main::auth->can_change_password();
466
467   $form->header();
468   print $form->parse_html_template("admin/edit_user", { 'GROUPS' => $groups });
469 }
470
471 sub save_user {
472   my $form          = $main::form;
473   my $locale        = $main::locale;
474
475   $form->{dbdriver} = 'Pg';
476
477   # no spaces allowed in login name
478   $form->{login} =~ s|\s||g;
479   $form->isblank("login", $locale->text('Login name missing!'));
480
481   # check for duplicates
482   if (!$form->{edit}) {
483     my %members = $main::auth->read_all_users();
484     if ($members{$form->{login}}) {
485       $form->show_generic_error($locale->text('Another user with the login #1 does already exist.', $form->{login}), 'back_button' => 1);
486     }
487   }
488
489   # no spaces allowed in directories
490   ($form->{newtemplates}) = split / /, $form->{newtemplates};
491
492   if ($form->{newtemplates}) {
493     $form->{templates} = $form->{newtemplates};
494   } else {
495     $form->{templates} =
496       ($form->{usetemplates}) ? $form->{usetemplates} : $form->{login};
497   }
498
499   # is there a basedir
500   if (!-d "$main::templates") {
501     $form->error(sprintf($locale->text("The directory %s does not exist."), $main::templates));
502   }
503
504   # add base directory to $form->{templates}
505   $form->{templates} =~ s|.*/||;
506   $form->{templates} =  "$main::templates/$form->{templates}";
507
508   my $myconfig = new User($form->{login});
509
510   $form->isblank("dbname", $locale->text('Dataset missing!'));
511   $form->isblank("dbuser", $locale->text('Database User missing!'));
512
513   foreach my $item (keys %{$form}) {
514     $myconfig->{$item} = $form->{$item};
515   }
516
517   delete $myconfig->{stylesheet};
518   if ($form->{userstylesheet}) {
519     $myconfig->{stylesheet} = $form->{userstylesheet};
520   }
521
522   $myconfig->save_member();
523
524   $form->{templates}       =~ s|.*/||;
525   $form->{templates}       =  "$main::templates/$form->{templates}";
526   $form->{mastertemplates} =~ s|.*/||;
527
528   # create user template directory and copy master files
529   if (!-d "$form->{templates}") {
530     umask(002);
531
532     if (mkdir "$form->{templates}", oct("771")) {
533
534       umask(007);
535
536       # copy templates to the directory
537       opendir TEMPLATEDIR, "$main::templates/." or $form->error("$main::templates : $ERRNO");
538       my @templates = grep /$form->{mastertemplates}.*?\.(html|tex|sty|odt|xml|txb)$/,
539         readdir TEMPLATEDIR;
540       closedir TEMPLATEDIR;
541
542       foreach my $file (@templates) {
543         open(TEMP, "$main::templates/$file")
544           or $form->error("$main::templates/$file : $ERRNO");
545
546         $file =~ s/\Q$form->{mastertemplates}\E-//;
547         open(NEW, ">$form->{templates}/$file")
548           or $form->error("$form->{templates}/$file : $ERRNO");
549
550         while (my $line = <TEMP>) {
551           print NEW $line;
552         }
553         close(TEMP);
554         close(NEW);
555       }
556     } else {
557       $form->error("$ERRNO: $form->{templates}");
558     }
559   }
560
561   # Add new user to his groups.
562   if (ref $form->{new_user_group_ids} eq 'ARRAY') {
563     my $all_groups = $main::auth->read_groups();
564     my %user       = $main::auth->read_user($form->{login});
565
566     foreach my $group_id (@{ $form->{new_user_group_ids} }) {
567       my $group = $all_groups->{$group_id};
568
569       next if !$group;
570
571       push @{ $group->{members} }, $user{id};
572       $main::auth->save_group($group);
573     }
574   }
575
576   if ($main::auth->can_change_password()
577       && defined $form->{new_password}
578       && ($form->{new_password} ne '********')) {
579     my $verifier = SL::Auth::PasswordPolicy->new;
580     my $result   = $verifier->verify($form->{new_password}, 1);
581
582     if ($result != SL::Auth::PasswordPolicy->OK()) {
583       $form->error($::locale->text('The settings were saved, but the password was not changed.') . ' ' . join(' ', $verifier->errors($result)));
584     }
585
586     $main::auth->change_password($form->{login}, $form->{new_password});
587   }
588
589   $form->redirect($locale->text('User saved!'));
590 }
591
592 sub save_user_as_new {
593   my $form       = $main::form;
594
595   $form->{login} = $form->{new_user_login};
596   delete @{$form}{qw(edit new_user_login)};
597
598   save_user();
599 }
600
601 sub delete_user {
602   my $form      = $main::form;
603   my $locale    = $main::locale;
604
605   my %members   = $main::auth->read_all_users();
606   my $templates = $members{$form->{login}}->{templates};
607
608   $main::auth->delete_user($form->{login});
609
610   if ($templates) {
611     my $templates_in_use = 0;
612
613     foreach my $login (keys %members) {
614       next if $form->{login} eq $login;
615       next if $members{$login}->{templates} ne $templates;
616       $templates_in_use = 1;
617       last;
618     }
619
620     if (!$templates_in_use && -d $templates) {
621       unlink <$templates/*>;
622       rmdir $templates;
623     }
624   }
625
626   $form->redirect($locale->text('User deleted!'));
627
628 }
629
630 sub login_name {
631   my $login = shift;
632
633   $login =~ s/\[\]//g;
634   return ($login) ? $login : undef;
635
636 }
637
638 sub get_value {
639   my $line           = shift;
640   my ($null, $value) = split(/=/, $line, 2);
641
642   # remove comments
643   $value =~ s/\s#.*//g;
644
645   # remove any trailing whitespace
646   $value =~ s/^\s*(.*?)\s*$/$1/;
647
648   $value;
649 }
650
651 sub pg_database_administration {
652   my $form = $main::form;
653
654   $form->{dbdriver} = 'Pg';
655   dbselect_source();
656
657 }
658
659 sub dbselect_source {
660   my $form           = $main::form;
661   my $locale         = $main::locale;
662
663   $form->{dbport}    = $::auth->{DB_config}->{port} || 5432;
664   $form->{dbuser}    = $::auth->{DB_config}->{user} || 'lxoffice';
665   $form->{dbdefault} = 'template1';
666   $form->{dbhost}    = $::auth->{DB_config}->{host} || 'localhost';
667
668   $form->{title}     = "Lx-Office ERP / " . $locale->text('Database Administration');
669
670   # Intentionnaly disabled unless fixed to work with the authentication DB.
671   $form->{ALLOW_DBBACKUP} = 0; # "$pg_dump_exe" ne "DISABLED";
672
673   $form->header();
674   print $form->parse_html_template("admin/dbadmin");
675 }
676
677 sub test_db_connection {
678   my $form   = $main::form;
679   my $locale = $main::locale;
680
681   $form->{dbdriver} = 'Pg';
682   User::dbconnect_vars($form, $form->{dbname});
683
684   my $dbh = DBI->connect($form->{dbconnect}, $form->{dbuser}, $form->{dbpasswd});
685
686   $form->{connection_ok} = $dbh ? 1 : 0;
687   $form->{errstr}        = $DBI::errstr;
688
689   $dbh->disconnect() if ($dbh);
690
691   $form->{title} = $locale->text('Database Connection Test');
692   $form->header();
693   print $form->parse_html_template("admin/test_db_connection");
694 }
695
696 sub continue {
697   call_sub($main::form->{"nextsub"});
698 }
699
700 sub update_dataset {
701   my $form              = $main::form;
702   my $locale            = $main::locale;
703
704   $form->{title}        = "Lx-Office ERP " . $locale->text('Database Administration') . " / " . $locale->text('Update Dataset');
705
706   my @need_updates      = User->dbneedsupdate($form);
707   $form->{NEED_UPDATES} = \@need_updates;
708   $form->{ALL_UPDATED}  = !scalar @need_updates;
709
710   $form->header();
711   print $form->parse_html_template("admin/update_dataset");
712 }
713
714 sub dbupdate {
715   my $form            = $main::form;
716   my $locale          = $main::locale;
717
718   $form->{stylesheet} = "lx-office-erp.css";
719   $form->{title}      = $locale->text("Dataset upgrade");
720   $form->header();
721
722   my $rowcount           = $form->{rowcount} * 1;
723   my @update_rows        = grep { $form->{"update_$_"} } (1 .. $rowcount);
724   $form->{NOTHING_TO_DO} = !scalar @update_rows;
725   my $saved_form         = save_form();
726
727   $| = 1;
728
729   print $form->parse_html_template("admin/dbupgrade_all_header");
730
731   foreach my $i (@update_rows) {
732     restore_form($saved_form);
733
734     map { $form->{$_} = $form->{"${_}_${i}"} } qw(dbname dbdriver dbhost dbport dbuser dbpasswd);
735
736     print $form->parse_html_template("admin/dbupgrade_header");
737
738     $form->{dbupdate}        = $form->{dbname};
739     $form->{$form->{dbname}} = 1;
740
741     User->dbupdate($form);
742     User->dbupdate2($form, SL::DBUpgrade2->new(form => $form, dbdriver => $form->{dbdriver})->parse_dbupdate_controls);
743
744     print $form->parse_html_template("admin/dbupgrade_footer");
745   }
746
747   print $form->parse_html_template("admin/dbupgrade_all_done");
748 }
749
750 sub create_dataset {
751   my $form           = $main::form;
752   my $locale         = $main::locale;
753
754   $form->{dbsources} = join " ", map { "[${_}]" } sort User->dbsources($form);
755
756   $form->{CHARTS}    = [];
757
758   opendir SQLDIR, "sql/." or $form->error($ERRNO);
759   foreach my $item (sort grep /-chart\.sql\z/, readdir SQLDIR) {
760     next if ($item eq 'Default-chart.sql');
761     $item =~ s/-chart\.sql//;
762     push @{ $form->{CHARTS} }, { "name"     => $item,
763                                  "selected" => $item eq "Germany-DATEV-SKR03EU" };
764   }
765   closedir SQLDIR;
766
767   my $default_charset = $main::dbcharset;
768   $default_charset ||= Common::DEFAULT_CHARSET;
769
770   my $cluster_encoding = User->dbclusterencoding($form);
771   if ($cluster_encoding && ($cluster_encoding =~ m/^(?:UTF-?8|UNICODE)$/i)) {
772     if ($main::dbcharset !~ m/^UTF-?8$/i) {
773       $form->show_generic_error($locale->text('The selected  PostgreSQL installation uses UTF-8 as its encoding. ' .
774                                               'Therefore you have to configure Lx-Office to use UTF-8 as well.'),
775                                 'back_button' => 1);
776     }
777
778     $form->{FORCE_DBENCODING} = 'UNICODE';
779
780   } else {
781     $form->{DBENCODINGS} = [];
782
783     foreach my $encoding (@Common::db_encodings) {
784       push @{ $form->{DBENCODINGS} }, { "dbencoding" => $encoding->{dbencoding},
785                                         "label"      => $encoding->{label},
786                                         "selected"   => $encoding->{charset} eq $default_charset };
787     }
788   }
789
790   $form->{title} = "Lx-Office ERP " . $locale->text('Database Administration') . " / " . $locale->text('Create Dataset');
791
792   $form->header();
793   print $form->parse_html_template("admin/create_dataset");
794 }
795
796 sub dbcreate {
797   my $form   = $main::form;
798   my $locale = $main::locale;
799
800   $form->isblank("db", $locale->text('Dataset missing!'));
801
802   User->dbcreate(\%$form);
803
804   $form->{title} = "Lx-Office ERP " . $locale->text('Database Administration') . " / " . $locale->text('Create Dataset');
805
806   $form->header();
807   print $form->parse_html_template("admin/dbcreate");
808 }
809
810 sub delete_dataset {
811   my $form      = $main::form;
812   my $locale    = $main::locale;
813
814   my @dbsources = User->dbsources_unused($form);
815   $form->error($locale->text('Nothing to delete!')) unless @dbsources;
816
817   $form->{title}     = "Lx-Office ERP " . $locale->text('Database Administration') . " / " . $locale->text('Delete Dataset');
818   $form->{DBSOURCES} = [ map { { "name", $_ } } sort @dbsources ];
819
820   $form->header();
821   print $form->parse_html_template("admin/delete_dataset");
822 }
823
824 sub dbdelete {
825   my $form   = $main::form;
826   my $locale = $main::locale;
827
828   if (!$form->{db}) {
829     $form->error($locale->text('No Dataset selected!'));
830   }
831
832   User->dbdelete(\%$form);
833
834   $form->{title} = "Lx-Office ERP " . $locale->text('Database Administration') . " / " . $locale->text('Delete Dataset');
835   $form->header();
836   print $form->parse_html_template("admin/dbdelete");
837 }
838
839 sub backup_dataset {
840   my $form       = $main::form;
841   my $locale     = $main::locale;
842
843   $form->{title} = "Lx-Office ERP " . $locale->text('Database Administration') . " / " . $locale->text('Backup Dataset');
844
845   if ("$main::pg_dump_exe" eq "DISABLED") {
846     $form->error($locale->text('Database backups and restorations are disabled in lx-erp.conf.'));
847   }
848
849   my @dbsources         = sort User->dbsources($form);
850   $form->{DATABASES}    = [ map { { "dbname" => $_ } } @dbsources ];
851   $form->{NO_DATABASES} = !scalar @dbsources;
852
853   my $username  = getpwuid $UID || "unknown-user";
854   my $hostname  = hostname() || "unknown-host";
855   $form->{from} = "Lx-Office Admin <${username}\@${hostname}>";
856
857   $form->header();
858   print $form->parse_html_template("admin/backup_dataset");
859 }
860
861 sub backup_dataset_start {
862   my $form       = $main::form;
863   my $locale     = $main::locale;
864
865   $form->{title} = "Lx-Office ERP " . $locale->text('Database Administration') . " / " . $locale->text('Backup Dataset');
866
867   $main::pg_dump_exe ||= "pg_dump";
868
869   if ("$main::pg_dump_exe" eq "DISABLED") {
870     $form->error($locale->text('Database backups and restorations are disabled in lx-erp.conf.'));
871   }
872
873   $form->isblank("dbname", $locale->text('The dataset name is missing.'));
874   $form->isblank("to", $locale->text('The email address is missing.')) if $form->{destination} eq "email";
875
876   my $tmpdir = "/tmp/lx_office_backup_" . Common->unique_id();
877   mkdir $tmpdir, 0700 || $form->error($locale->text('A temporary directory could not be created:') . " $ERRNO");
878
879   my $pgpass = IO::File->new("${tmpdir}/.pgpass", O_WRONLY | O_CREAT, 0600);
880
881   if (!$pgpass) {
882     unlink $tmpdir;
883     $form->error($locale->text('A temporary file could not be created:') . " $ERRNO");
884   }
885
886   print $pgpass "$form->{dbhost}:$form->{dbport}:$form->{dbname}:$form->{dbuser}:$form->{dbpasswd}\n";
887   $pgpass->close();
888
889   $ENV{HOME} = $tmpdir;
890
891   my @args = ("-Ft", "-c", "-o", "-h", $form->{dbhost}, "-U", $form->{dbuser});
892   push @args, ("-p", $form->{dbport}) if ($form->{dbport});
893   push @args, $form->{dbname};
894
895   my $cmd  = "$main::pg_dump_exe " . join(" ", map { s/\\/\\\\/g; s/\"/\\\"/g; $_ } @args);
896   my $name = "dataset_backup_$form->{dbname}_" . strftime("%Y%m%d", localtime()) . ".tar";
897
898   if ($form->{destination} ne "email") {
899     my $in = IO::File->new("$cmd |");
900
901     if (!$in) {
902       unlink "${tmpdir}/.pgpass";
903       rmdir $tmpdir;
904
905       $form->error($locale->text('The pg_dump process could not be started.'));
906     }
907
908     print "content-type: application/x-tar\n";
909     print "content-disposition: attachment; filename=\"${name}\"\n\n";
910
911     while (my $line = <$in>) {
912       print $line;
913     }
914
915     $in->close();
916
917     unlink "${tmpdir}/.pgpass";
918     rmdir $tmpdir;
919
920   } else {
921     my $tmp = $tmpdir . "/dump_" . Common::unique_id();
922
923     if (system("$cmd > $tmp") != 0) {
924       unlink "${tmpdir}/.pgpass", $tmp;
925       rmdir $tmpdir;
926
927       $form->error($locale->text('The pg_dump process could not be started.'));
928     }
929
930     my $mail = new Mailer;
931
932     map { $mail->{$_} = $form->{$_} } qw(from to cc subject message);
933
934     $mail->{charset}     = $main::dbcharset ? $main::dbcharset : Common::DEFAULT_CHARSET;
935     $mail->{attachments} = [ { "filename" => $tmp, "name" => $name } ];
936     $mail->send();
937
938     unlink "${tmpdir}/.pgpass", $tmp;
939     rmdir $tmpdir;
940
941     $form->{title} = "Lx-Office ERP " . $locale->text('Database Administration') . " / " . $locale->text('Backup Dataset');
942
943     $form->header();
944     print $form->parse_html_template("admin/backup_dataset_email_done");
945   }
946 }
947
948 sub restore_dataset {
949   my $form       = $main::form;
950   my $locale     = $main::locale;
951
952   $form->{title} = "Lx-Office ERP " . $locale->text('Database Administration') . " / " . $locale->text('Restore Dataset');
953
954   if ("$main::pg_restore_exe" eq "DISABLED") {
955     $form->error($locale->text('Database backups and restorations are disabled in lx-erp.conf.'));
956   }
957
958   my $default_charset   = $main::dbcharset;
959   $default_charset    ||= Common::DEFAULT_CHARSET;
960
961   $form->{DBENCODINGS}  = [];
962
963   foreach my $encoding (@Common::db_encodings) {
964     push @{ $form->{DBENCODINGS} }, { "dbencoding" => $encoding->{dbencoding},
965                                       "label"      => $encoding->{label},
966                                       "selected"   => $encoding->{charset} eq $default_charset };
967   }
968
969   $form->header();
970   print $form->parse_html_template("admin/restore_dataset");
971 }
972
973 sub restore_dataset_start {
974   my $form       = $main::form;
975   my $locale     = $main::locale;
976
977   $form->{title} = "Lx-Office ERP " . $locale->text('Database Administration') . " / " . $locale->text('Restore Dataset');
978
979   $main::pg_restore_exe ||= "pg_restore";
980
981   if ("$main::pg_restore_exe" eq "DISABLED") {
982     $form->error($locale->text('Database backups and restorations are disabled in lx-erp.conf.'));
983   }
984
985   $form->isblank("new_dbname", $locale->text('The dataset name is missing.'));
986   $form->isblank("content", $locale->text('No backup file has been uploaded.'));
987
988   # Create temporary directories. Write the backup file contents to a temporary
989   # file. Create a .pgpass file with the username and password for the pg_restore
990   # utility.
991
992   my $tmpdir = "/tmp/lx_office_backup_" . Common->unique_id();
993   mkdir $tmpdir, 0700 || $form->error($locale->text('A temporary directory could not be created:') . " $ERRNO");
994
995   my $pgpass = IO::File->new("${tmpdir}/.pgpass", O_WRONLY | O_CREAT, 0600);
996
997   if (!$pgpass) {
998     unlink $tmpdir;
999     $form->error($locale->text('A temporary file could not be created:') . " $ERRNO");
1000   }
1001
1002   print $pgpass "$form->{dbhost}:$form->{dbport}:$form->{new_dbname}:$form->{dbuser}:$form->{dbpasswd}\n";
1003   $pgpass->close();
1004
1005   $ENV{HOME} = $tmpdir;
1006
1007   my $tmp = $tmpdir . "/dump_" . Common::unique_id();
1008   my $tmpfile;
1009
1010   if (substr($form->{content}, 0, 2) eq "\037\213") {
1011     $tmpfile = IO::File->new("| gzip -d > $tmp");
1012     $tmpfile->binary();
1013
1014   } else {
1015     $tmpfile = IO::File->new($tmp, O_WRONLY | O_CREAT | O_BINARY, 0600);
1016   }
1017
1018   if (!$tmpfile) {
1019     unlink "${tmpdir}/.pgpass";
1020     rmdir $tmpdir;
1021
1022     $form->error($locale->text('A temporary file could not be created:') . " $ERRNO");
1023   }
1024
1025   print $tmpfile $form->{content};
1026   $tmpfile->close();
1027
1028   delete $form->{content};
1029
1030   # Try to connect to the database. Find out if a database with the same name exists.
1031   # If yes, then drop the existing database. Create a new one with the name and encoding
1032   # given by the user.
1033
1034   User::dbconnect_vars($form, "template1");
1035
1036   my %myconfig = map { $_ => $form->{$_} } grep /^db/, keys %{ $form };
1037   my $dbh      = $form->dbconnect(\%myconfig) || $form->dberror();
1038
1039   my ($query, $sth);
1040
1041   $form->{new_dbname} =~ s|[^a-zA-Z0-9_\-]||g;
1042
1043   $query = qq|SELECT COUNT(*) FROM pg_database WHERE datname = ?|;
1044   my ($count) = selectrow_query($form, $dbh, $query, $form->{new_dbname});
1045   if ($count) {
1046     do_query($form, $dbh, qq|DROP DATABASE $form->{new_dbname}|);
1047   }
1048
1049   my $found = 0;
1050   foreach my $item (@Common::db_encodings) {
1051     if ($item->{dbencoding} eq $form->{dbencoding}) {
1052       $found = 1;
1053       last;
1054     }
1055   }
1056   $form->{dbencoding} = "LATIN9" unless $form->{dbencoding};
1057
1058   do_query($form, $dbh, qq|CREATE DATABASE $form->{new_dbname} ENCODING ? TEMPLATE template0|, $form->{dbencoding});
1059
1060   $dbh->disconnect();
1061
1062   # Spawn pg_restore on the temporary file.
1063
1064   my @args = ("-h", $form->{dbhost}, "-U", $form->{dbuser}, "-d", $form->{new_dbname});
1065   push @args, ("-p", $form->{dbport}) if ($form->{dbport});
1066   push @args, $tmp;
1067
1068   my $cmd = "$main::pg_restore_exe " . join(" ", map { s/\\/\\\\/g; s/\"/\\\"/g; $_ } @args);
1069
1070   my $in = IO::File->new("$cmd 2>&1 |");
1071
1072   if (!$in) {
1073     unlink "${tmpdir}/.pgpass", $tmp;
1074     rmdir $tmpdir;
1075
1076     $form->error($locale->text('The pg_restore process could not be started.'));
1077   }
1078
1079   $English::AUTOFLUSH = 1;
1080
1081   $form->header();
1082   print $form->parse_html_template("admin/restore_dataset_start_header");
1083
1084   while (my $line = <$in>) {
1085     print $line;
1086   }
1087   $in->close();
1088
1089   $form->{retval} = $CHILD_ERROR >> 8;
1090   print $form->parse_html_template("admin/restore_dataset_start_footer");
1091
1092   unlink "${tmpdir}/.pgpass", $tmp;
1093   rmdir $tmpdir;
1094 }
1095
1096 sub unlock_system {
1097   my $form   = $main::form;
1098   my $locale = $main::locale;
1099
1100   unlink "$main::userspath/nologin";
1101
1102   $form->{callback} = "admin.pl?action=list_users";
1103
1104   $form->redirect($locale->text('Lockfile removed!'));
1105
1106 }
1107
1108 sub lock_system {
1109   my $form   = $main::form;
1110   my $locale = $main::locale;
1111
1112   open(FH, ">$main::userspath/nologin")
1113     or $form->error($locale->text('Cannot create Lock!'));
1114   close(FH);
1115
1116   $form->{callback} = "admin.pl?action=list_users";
1117
1118   $form->redirect($locale->text('Lockfile created!'));
1119
1120 }
1121
1122 sub yes {
1123   call_sub($main::form->{yes_nextsub});
1124 }
1125
1126 sub no {
1127   call_sub($main::form->{no_nextsub});
1128 }
1129
1130 sub add {
1131   call_sub($main::form->{add_nextsub});
1132 }
1133
1134 sub edit {
1135   my $form = $main::form;
1136
1137   $form->{edit_nextsub} ||= 'edit_user';
1138
1139   call_sub($form->{edit_nextsub});
1140 }
1141
1142 sub delete {
1143   my $form     = $main::form;
1144
1145   $form->{delete_nextsub} ||= 'delete_user';
1146
1147   call_sub($form->{delete_nextsub});
1148 }
1149
1150 sub save {
1151   my $form = $main::form;
1152
1153   $form->{save_nextsub} ||= 'save_user';
1154
1155   call_sub($form->{save_nextsub});
1156 }
1157
1158 sub back {
1159   call_sub($main::form->{back_nextsub});
1160 }
1161
1162 sub dispatcher {
1163   my $form   = $main::form;
1164   my $locale = $main::locale;
1165
1166   foreach my $action (qw(create_standard_group dont_create_standard_group
1167                          save_user delete_user save_user_as_new)) {
1168     if ($form->{"action_${action}"}) {
1169       call_sub($action);
1170       return;
1171     }
1172   }
1173
1174   call_sub($form->{default_action}) if ($form->{default_action});
1175
1176   $form->error($locale->text('No action defined.'));
1177 }
1178
1179 sub _apply_dbupgrade_scripts {
1180   ::end_of_request() if SL::DBUpgrade2->new(form => $::form, dbdriver => 'Pg', auth => 1)->apply_admin_dbupgrade_scripts(1);
1181 }
1182
1183 1;