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