]> git.mxchange.org Git - friendica.git/blob - src/Core/Config/Util/ConfigFileLoader.php
Merge pull request #11100 from nupplaphil/bug/session_cache
[friendica.git] / src / Core / Config / Util / ConfigFileLoader.php
1 <?php
2 /**
3  * @copyright Copyright (C) 2010-2021, the Friendica project
4  *
5  * @license GNU AGPL version 3 or any later version
6  *
7  * This program is free software: you can redistribute it and/or modify
8  * it under the terms of the GNU Affero General Public License as
9  * published by the Free Software Foundation, either version 3 of the
10  * License, or (at your option) any later version.
11  *
12  * This program is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15  * GNU Affero General Public License for more details.
16  *
17  * You should have received a copy of the GNU Affero General Public License
18  * along with this program.  If not, see <https://www.gnu.org/licenses/>.
19  *
20  */
21
22 namespace Friendica\Core\Config\Util;
23
24 use Friendica\Core\Addon;
25 use Friendica\Core\Config\Exception\ConfigFileException;
26 use Friendica\Core\Config\ValueObject\Cache;
27
28 /**
29  * The ConfigFileLoader loads config-files and stores them in a ConfigCache ( @see Cache )
30  *
31  * It is capable of loading the following config files:
32  * - *.config.php   (current)
33  * - *.ini.php      (deprecated)
34  * - *.htconfig.php (deprecated)
35  */
36 class ConfigFileLoader
37 {
38         /**
39          * The default name of the user defined ini file
40          *
41          * @var string
42          */
43         const CONFIG_INI = 'local';
44
45         /**
46          * The default name of the user defined legacy config file
47          *
48          * @var string
49          */
50         const CONFIG_HTCONFIG = 'htconfig';
51
52         /**
53          * The sample string inside the configs, which shouldn't get loaded
54          *
55          * @var string
56          */
57         const SAMPLE_END = '-sample';
58
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         /**
73          * @param string $baseDir   The base
74          * @param string $configDir
75          * @param string $staticDir
76          */
77         public function __construct(string $baseDir, string $configDir, string $staticDir)
78         {
79                 $this->baseDir   = $baseDir;
80                 $this->configDir = $configDir;
81                 $this->staticDir = $staticDir;
82         }
83
84         /**
85          * Load the configuration files into an configuration cache
86          *
87          * First loads the default value for all the configuration keys, then the legacy configuration files, then the
88          * expected local.config.php
89          *
90          * @param Cache $config The config cache to load to
91          * @param array $server The $_SERVER array
92          * @param bool  $raw    Setup the raw config format
93          *
94          * @throws ConfigFileException
95          */
96         public function setupCache(Cache $config, array $server = [], bool $raw = false)
97         {
98                 // Load static config files first, the order is important
99                 $config->load($this->loadStaticConfig('defaults'), Cache::SOURCE_STATIC);
100                 $config->load($this->loadStaticConfig('settings'), Cache::SOURCE_STATIC);
101
102                 // try to load the legacy config first
103                 $config->load($this->loadLegacyConfig('htpreconfig'), Cache::SOURCE_FILE);
104                 $config->load($this->loadLegacyConfig('htconfig'), Cache::SOURCE_FILE);
105
106                 // Now load every other config you find inside the 'config/' directory
107                 $this->loadCoreConfig($config);
108
109                 $config->load($this->loadEnvConfig($server), Cache::SOURCE_ENV);
110
111                 // In case of install mode, add the found basepath (because there isn't a basepath set yet
112                 if (!$raw && empty($config->get('system', 'basepath'))) {
113                         // Setting at least the basepath we know
114                         $config->set('system', 'basepath', $this->baseDir, Cache::SOURCE_FILE);
115                 }
116         }
117
118         /**
119          * Tries to load the static core-configuration and returns the config array.
120          *
121          * @param string $name The name of the configuration
122          *
123          * @return array The config array (empty if no config found)
124          *
125          * @throws ConfigFileException if the configuration file isn't readable
126          */
127         private function loadStaticConfig(string $name): array
128         {
129                 $configName = $this->staticDir . DIRECTORY_SEPARATOR . $name . '.config.php';
130                 $iniName    = $this->staticDir . DIRECTORY_SEPARATOR . $name . '.ini.php';
131
132                 if (file_exists($configName)) {
133                         return $this->loadConfigFile($configName);
134                 } elseif (file_exists($iniName)) {
135                         return $this->loadINIConfigFile($iniName);
136                 } else {
137                         return [];
138                 }
139         }
140
141         /**
142          * Tries to load the specified core-configuration into the config cache.
143          *
144          * @param Cache $config The Config cache
145          *
146          * @throws ConfigFileException if the configuration file isn't readable
147          */
148         private function loadCoreConfig(Cache $config)
149         {
150                 // try to load legacy ini-files first
151                 foreach ($this->getConfigFiles(true) as $configFile) {
152                         $config->load($this->loadINIConfigFile($configFile), Cache::SOURCE_FILE);
153                 }
154
155                 // try to load supported config at last to overwrite it
156                 foreach ($this->getConfigFiles() as $configFile) {
157                         $config->load($this->loadConfigFile($configFile), Cache::SOURCE_FILE);
158                 }
159         }
160
161         /**
162          * Tries to load the specified addon-configuration and returns the config array.
163          *
164          * @param string $name The name of the configuration
165          *
166          * @return array The config array (empty if no config found)
167          *
168          * @throws ConfigFileException if the configuration file isn't readable
169          */
170         public function loadAddonConfig(string $name): array
171         {
172                 $filepath = $this->baseDir . DIRECTORY_SEPARATOR .   // /var/www/html/
173                                         Addon::DIRECTORY . DIRECTORY_SEPARATOR . // addon/
174                                         $name . DIRECTORY_SEPARATOR .            // openstreetmap/
175                                         'config'. DIRECTORY_SEPARATOR .                  // config/
176                                         $name . ".config.php";                   // openstreetmap.config.php
177
178                 if (file_exists($filepath)) {
179                         return $this->loadConfigFile($filepath);
180                 } else {
181                         return [];
182                 }
183         }
184
185         /**
186          * Tries to load environment specific variables, based on the `env.config.php` mapping table
187          *
188          * @param array $server The $_SERVER variable
189          *
190          * @return array The config array (empty if no config was found)
191          *
192          * @throws ConfigFileException if the configuration file isn't readable
193          */
194         public function loadEnvConfig(array $server): array
195         {
196                 $filepath = $this->staticDir . DIRECTORY_SEPARATOR .   // /var/www/html/static/
197                                         "env.config.php";                          // env.config.php
198
199                 if (!file_exists($filepath)) {
200                         return [];
201                 }
202
203                 $envConfig = $this->loadConfigFile($filepath);
204
205                 $return = [];
206
207                 foreach ($envConfig as $envKey => $configStructure) {
208                         if (isset($server[$envKey])) {
209                                 $return[$configStructure[0]][$configStructure[1]] = $server[$envKey];
210                         }
211                 }
212
213                 return $return;
214         }
215
216         /**
217          * Get the config files of the config-directory
218          *
219          * @param bool $ini True, if scan for ini-files instead of config files
220          *
221          * @return array
222          */
223         private function getConfigFiles(bool $ini = false): array
224         {
225                 $files = scandir($this->configDir);
226                 $found = [];
227
228                 $filePattern = ($ini ? '*.ini.php' : '*.config.php');
229
230                 // Don't load sample files
231                 $sampleEnd = self::SAMPLE_END . ($ini ? '.ini.php' : '.config.php');
232
233                 foreach ($files as $filename) {
234                         if (fnmatch($filePattern, $filename) && substr_compare($filename, $sampleEnd, -strlen($sampleEnd))) {
235                                 $found[] = $this->configDir . '/' . $filename;
236                         }
237                 }
238
239                 return $found;
240         }
241
242         /**
243          * Tries to load the legacy config files (.htconfig.php, .htpreconfig.php) and returns the config array.
244          *
245          * @param string $name The name of the config file (default is empty, which means .htconfig.php)
246          *
247          * @return array The configuration array (empty if no config found)
248          *
249          * @deprecated since version 2018.09
250          */
251         private function loadLegacyConfig(string $name = ''): array
252         {
253                 $name     = !empty($name) ? $name : self::CONFIG_HTCONFIG;
254                 $fullName = $this->baseDir . DIRECTORY_SEPARATOR . '.' . $name . '.php';
255
256                 $config = [];
257                 if (file_exists($fullName)) {
258                         $a         = new \stdClass();
259                         $a->config = [];
260                         include $fullName;
261
262                         $htConfigCategories = array_keys($a->config);
263
264                         // map the legacy configuration structure to the current structure
265                         foreach ($htConfigCategories as $htConfigCategory) {
266                                 if (is_array($a->config[$htConfigCategory])) {
267                                         $keys = array_keys($a->config[$htConfigCategory]);
268
269                                         foreach ($keys as $key) {
270                                                 $config[$htConfigCategory][$key] = $a->config[$htConfigCategory][$key];
271                                         }
272                                 } else {
273                                         $config['config'][$htConfigCategory] = $a->config[$htConfigCategory];
274                                 }
275                         }
276
277                         unset($a);
278
279                         if (isset($db_host)) {
280                                 $config['database']['hostname'] = $db_host;
281                                 unset($db_host);
282                         }
283                         if (isset($db_user)) {
284                                 $config['database']['username'] = $db_user;
285                                 unset($db_user);
286                         }
287                         if (isset($db_pass)) {
288                                 $config['database']['password'] = $db_pass;
289                                 unset($db_pass);
290                         }
291                         if (isset($db_data)) {
292                                 $config['database']['database'] = $db_data;
293                                 unset($db_data);
294                         }
295                         if (isset($config['system']['db_charset'])) {
296                                 $config['database']['charset'] = $config['system']['db_charset'];
297                         }
298                         if (isset($pidfile)) {
299                                 $config['system']['pidfile'] = $pidfile;
300                                 unset($pidfile);
301                         }
302                         if (isset($default_timezone)) {
303                                 $config['system']['default_timezone'] = $default_timezone;
304                                 unset($default_timezone);
305                         }
306                         if (isset($lang)) {
307                                 $config['system']['language'] = $lang;
308                                 unset($lang);
309                         }
310                 }
311
312                 return $config;
313         }
314
315         /**
316          * Tries to load the specified legacy configuration file and returns the config array.
317          *
318          * @param string $filepath
319          *
320          * @return array The configuration array
321          * @throws ConfigFileException
322          * @deprecated since version 2018.12
323          */
324         private function loadINIConfigFile(string $filepath): array
325         {
326                 $contents = include($filepath);
327
328                 $config = parse_ini_string($contents, true, INI_SCANNER_TYPED);
329
330                 if ($config === false) {
331                         throw new ConfigFileException('Error parsing INI config file ' . $filepath);
332                 }
333
334                 return $config;
335         }
336
337         /**
338          * Tries to load the specified configuration file and returns the config array.
339          *
340          * The config format is PHP array and the template for configuration files is the following:
341          *
342          * <?php return [
343          *      'section' => [
344          *          'key' => 'value',
345          *      ],
346          * ];
347          *
348          * @param string $filepath The filepath of the
349          *
350          * @return array The config array0
351          *
352          * @throws ConfigFileException if the config cannot get loaded.
353          */
354         private function loadConfigFile(string $filepath): array
355         {
356                 $config = include($filepath);
357
358                 if (!is_array($config)) {
359                         throw new ConfigFileException('Error loading config file ' . $filepath);
360                 }
361
362                 return $config;
363         }
364 }