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