]> git.mxchange.org Git - friendica.git/blob - src/Util/ConfigFileLoader.php
Reverted indention
[friendica.git] / src / Util / ConfigFileLoader.php
1 <?php
2
3 namespace Friendica\Util;
4
5 use Exception;
6 use Friendica\App;
7 use Friendica\Core\Addon;
8 use Friendica\Core\Config\Cache\ConfigCache;
9
10 /**
11  * The ConfigFileLoader loads config-files and stores them in a ConfigCache ( @see ConfigCache )
12  *
13  * It is capable of loading the following config files:
14  * - *.config.php   (current)
15  * - *.ini.php      (deprecated)
16  * - *.htconfig.php (deprecated)
17  */
18 class ConfigFileLoader
19 {
20         /**
21          * The Sub directory of the config-files
22          *
23          * @var string
24          */
25         const CONFIG_DIR = 'config';
26
27         /**
28          * The Sub directory of the static config-files
29          *
30          * @var string
31          */
32         const STATIC_DIR = 'static';
33
34         /**
35          * The default name of the user defined ini file
36          *
37          * @var string
38          */
39         const CONFIG_INI = 'local';
40
41         /**
42          * The default name of the user defined legacy config file
43          *
44          * @var string
45          */
46         const CONFIG_HTCONFIG = 'htconfig';
47
48         /**
49          * The sample string inside the configs, which shouldn't get loaded
50          *
51          * @var string
52          */
53         const SAMPLE_END = '-sample';
54
55         /**
56          * @var App\Mode
57          */
58         private $appMode;
59         /**
60          * @var string
61          */
62         private $baseDir;
63         /**
64          * @var string
65          */
66         private $configDir;
67         /**
68          * @var string
69          */
70         private $staticDir;
71
72         public function __construct($baseDir, App\Mode $mode)
73         {
74                 $this->baseDir   = $baseDir;
75                 $this->configDir = $baseDir . DIRECTORY_SEPARATOR . self::CONFIG_DIR;
76                 $this->staticDir = $baseDir . DIRECTORY_SEPARATOR . self::STATIC_DIR;
77                 $this->appMode   = $mode;
78         }
79
80         /**
81          * Load the configuration files into an configuration cache
82          *
83          * First loads the default value for all the configuration keys, then the legacy configuration files, then the
84          * expected local.config.php
85          *
86          * @param ConfigCache $config The config cache to load to
87          * @param bool        $raw    Setup the raw config format
88          *
89          * @throws Exception
90          */
91         public function setupCache(ConfigCache $config, $raw = false)
92         {
93                 // Load static config files first, the order is important
94                 $config->load($this->loadStaticConfig('defaults'));
95                 $config->load($this->loadStaticConfig('settings'));
96
97                 // try to load the legacy config first
98                 $config->load($this->loadLegacyConfig('htpreconfig'), true);
99                 $config->load($this->loadLegacyConfig('htconfig'), true);
100
101                 // Now load every other config you find inside the 'config/' directory
102                 $this->loadCoreConfig($config);
103
104                 // In case of install mode, add the found basepath (because there isn't a basepath set yet
105                 if (!$raw && ($this->appMode->isInstall() || empty($config->get('system', 'basepath')))) {
106                         // Setting at least the basepath we know
107                         $config->set('system', 'basepath', $this->baseDir);
108                 }
109         }
110
111         /**
112          * Tries to load the static core-configuration and returns the config array.
113          *
114          * @param string $name The name of the configuration
115          *
116          * @return array The config array (empty if no config found)
117          *
118          * @throws Exception if the configuration file isn't readable
119          */
120         private function loadStaticConfig($name)
121         {
122                 $configName = $this->staticDir . DIRECTORY_SEPARATOR . $name . '.config.php';
123                 $iniName    = $this->staticDir . DIRECTORY_SEPARATOR . $name . '.ini.php';
124
125                 if (file_exists($configName)) {
126                         return $this->loadConfigFile($configName);
127                 } elseif (file_exists($iniName)) {
128                         return $this->loadINIConfigFile($iniName);
129                 } else {
130                         return [];
131                 }
132         }
133
134         /**
135          * Tries to load the specified core-configuration into the config cache.
136          *
137          * @param ConfigCache $config The Config cache
138          *
139          * @return array The config array (empty if no config found)
140          *
141          * @throws Exception if the configuration file isn't readable
142          */
143         private function loadCoreConfig(ConfigCache $config)
144         {
145                 // try to load legacy ini-files first
146                 foreach ($this->getConfigFiles(true) as $configFile) {
147                         $config->load($this->loadINIConfigFile($configFile), true);
148                 }
149
150                 // try to load supported config at last to overwrite it
151                 foreach ($this->getConfigFiles() as $configFile) {
152                         $config->load($this->loadConfigFile($configFile), true);
153                 }
154
155                 return [];
156         }
157
158         /**
159          * Tries to load the specified addon-configuration and returns the config array.
160          *
161          * @param string $name The name of the configuration
162          *
163          * @return array The config array (empty if no config found)
164          *
165          * @throws Exception if the configuration file isn't readable
166          */
167         public function loadAddonConfig($name)
168         {
169                 $filepath = $this->baseDir . DIRECTORY_SEPARATOR .   // /var/www/html/
170                             Addon::DIRECTORY . DIRECTORY_SEPARATOR . // addon/
171                             $name . DIRECTORY_SEPARATOR .            // openstreetmap/
172                             self::CONFIG_DIR . DIRECTORY_SEPARATOR . // config/
173                             $name . ".config.php";                   // openstreetmap.config.php
174
175                 if (file_exists($filepath)) {
176                         return $this->loadConfigFile($filepath);
177                 } else {
178                         return [];
179                 }
180         }
181
182         /**
183          * Get the config files of the config-directory
184          *
185          * @param bool $ini True, if scan for ini-files instead of config files
186          *
187          * @return array
188          */
189         private function getConfigFiles(bool $ini = false)
190         {
191                 $files = scandir($this->configDir);
192                 $found = array();
193
194                 $filePattern = ($ini ? '*.ini.php' : '*.config.php');
195
196                 // Don't load sample files
197                 $sampleEnd = self::SAMPLE_END . ($ini ? '.ini.php' : '.config.php');
198
199                 foreach ($files as $filename) {
200                         if (fnmatch($filePattern, $filename) && substr_compare($filename, $sampleEnd, -strlen($sampleEnd))) {
201                                 $found[] = $this->configDir . '/' . $filename;
202                         }
203                 }
204
205                 return $found;
206         }
207
208         /**
209          * Tries to load the legacy config files (.htconfig.php, .htpreconfig.php) and returns the config array.
210          *
211          * @param string $name The name of the config file (default is empty, which means .htconfig.php)
212          *
213          * @return array The configuration array (empty if no config found)
214          *
215          * @deprecated since version 2018.09
216          */
217         private function loadLegacyConfig($name = '')
218         {
219                 $name     = !empty($name) ? $name : self::CONFIG_HTCONFIG;
220                 $fullName = $this->baseDir . DIRECTORY_SEPARATOR . '.' . $name . '.php';
221
222                 $config = [];
223                 if (file_exists($fullName)) {
224                         $a         = new \stdClass();
225                         $a->config = [];
226                         include $fullName;
227
228                         $htConfigCategories = array_keys($a->config);
229
230                         // map the legacy configuration structure to the current structure
231                         foreach ($htConfigCategories as $htConfigCategory) {
232                                 if (is_array($a->config[$htConfigCategory])) {
233                                         $keys = array_keys($a->config[$htConfigCategory]);
234
235                                         foreach ($keys as $key) {
236                                                 $config[$htConfigCategory][$key] = $a->config[$htConfigCategory][$key];
237                                         }
238                                 } else {
239                                         $config['config'][$htConfigCategory] = $a->config[$htConfigCategory];
240                                 }
241                         }
242
243                         unset($a);
244
245                         if (isset($db_host)) {
246                                 $config['database']['hostname'] = $db_host;
247                                 unset($db_host);
248                         }
249                         if (isset($db_user)) {
250                                 $config['database']['username'] = $db_user;
251                                 unset($db_user);
252                         }
253                         if (isset($db_pass)) {
254                                 $config['database']['password'] = $db_pass;
255                                 unset($db_pass);
256                         }
257                         if (isset($db_data)) {
258                                 $config['database']['database'] = $db_data;
259                                 unset($db_data);
260                         }
261                         if (isset($config['system']['db_charset'])) {
262                                 $config['database']['charset'] = $config['system']['db_charset'];
263                         }
264                         if (isset($pidfile)) {
265                                 $config['system']['pidfile'] = $pidfile;
266                                 unset($pidfile);
267                         }
268                         if (isset($default_timezone)) {
269                                 $config['system']['default_timezone'] = $default_timezone;
270                                 unset($default_timezone);
271                         }
272                         if (isset($lang)) {
273                                 $config['system']['language'] = $lang;
274                                 unset($lang);
275                         }
276                 }
277
278                 return $config;
279         }
280
281         /**
282          * Tries to load the specified legacy configuration file and returns the config array.
283          *
284          * @param string $filepath
285          *
286          * @return array The configuration array
287          * @throws Exception
288          * @deprecated since version 2018.12
289          */
290         private function loadINIConfigFile($filepath)
291         {
292                 $contents = include($filepath);
293
294                 $config = parse_ini_string($contents, true, INI_SCANNER_TYPED);
295
296                 if ($config === false) {
297                         throw new Exception('Error parsing INI config file ' . $filepath);
298                 }
299
300                 return $config;
301         }
302
303         /**
304          * Tries to load the specified configuration file and returns the config array.
305          *
306          * The config format is PHP array and the template for configuration files is the following:
307          *
308          * <?php return [
309          *      'section' => [
310          *          'key' => 'value',
311          *      ],
312          * ];
313          *
314          * @param string $filepath The filepath of the
315          *
316          * @return array The config array0
317          *
318          * @throws Exception if the config cannot get loaded.
319          */
320         private function loadConfigFile($filepath)
321         {
322                 $config = include($filepath);
323
324                 if (!is_array($config)) {
325                         throw new Exception('Error loading config file ' . $filepath);
326                 }
327
328                 return $config;
329         }
330 }