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