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