Basis-Module ("Encode") normal mit "use" laden
[kivitendo-erp.git] / SL / LxOfficeConf.pm
1 package SL::LxOfficeConf;
2
3 use strict;
4
5 use Encode;
6
7 my $environment_initialized;
8
9 sub safe_require {
10   my ($class, $may_fail);
11
12   my $failed = !eval { require Config::Std; };
13
14   if ($failed) {
15     if ($may_fail) {
16       warn $@;
17       return 0;
18     } else {
19       die $@;
20     }
21   }
22
23   Config::Std->import;
24
25   return 1;
26 }
27
28 sub read {
29   my ($class, $file_name, $may_fail) = @_;
30
31   return unless $class->safe_require($may_fail);
32
33   read_config('config/lx_office.conf.default' => \%::lx_office_conf);
34   _decode_recursively(\%::lx_office_conf);
35
36   $file_name ||= 'config/lx_office.conf';
37
38   if (-f $file_name) {
39     read_config($file_name => \ my %local_conf);
40     _decode_recursively(\%local_conf);
41     _flat_merge(\%::lx_office_conf, \%local_conf);
42   }
43
44   _init_environment();
45   _determine_application_paths();
46
47   return 1;
48 }
49
50 sub _decode_recursively {
51   my ($obj) = @_;
52
53   while (my ($key, $value) = each %{ $obj }) {
54     if (ref($value) eq 'HASH') {
55       _decode_recursively($value);
56     } else {
57       $obj->{$key} = decode('UTF-8', $value);
58     }
59   }
60 }
61
62 sub _flat_merge {
63   my ($dst, $src) = @_;
64
65   while (my ($key, $value) = each %{ $src }) {
66     if (!exists $dst->{$key}) {
67       $dst->{$key} = $value;
68
69     } else {
70       map { $dst->{$key}->{$_} = $value->{$_} } keys %{ $value };
71     }
72   }
73 }
74
75 sub _init_environment {
76   return if $environment_initialized;
77
78   my %key_map = ( lib  => { name => 'PERL5LIB', append_path => 1 },
79                   path => { name => 'PATH',     append_path => 1 },
80                 );
81   my $cfg     = $::lx_office_conf{environment} || {};
82
83   while (my ($key, $value) = each %{ $cfg }) {
84     next unless $value;
85
86     my $info = $key_map{$key} || {};
87     $key     = $info->{name}  || $key;
88
89     if ($info->{append_path}) {
90       $value = ':' . $value unless $value =~ m/^:/ || !$ENV{$key};
91       $value = $ENV{$key} . $value if $ENV{$key};
92     }
93
94     $ENV{$key} = $value;
95   }
96
97   $environment_initialized = 1;
98 }
99
100 sub _determine_application_paths {
101   my @paths = grep { $_ } split m/:/, $ENV{PATH};
102
103   foreach my $key (keys %{ $::lx_office_conf{applications} }) {
104     my ($program) = split m/\s+/, $::lx_office_conf{applications}->{$key};
105     next if $program =~ m|/|;
106
107     foreach my $path (@paths) {
108       next unless -f "${path}/${program}";
109       $::lx_office_conf{applications}->{$key} = "${path}/" . $::lx_office_conf{applications}->{$key};
110       last;
111     }
112   }
113 }
114
115 1;