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