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