3 * @copyright Copyright (C) 2010-2023, the Friendica project
5 * @license GNU AGPL version 3 or any later version
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.
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.
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/>.
22 namespace Friendica\Core\Config\Util;
24 use Friendica\Core\Addon;
25 use Friendica\Core\Config\Exception\ConfigFileException;
26 use Friendica\Core\Config\ValueObject\Cache;
29 * The ConfigFileLoader loads and saves config-files and stores them in a ConfigCache ( @see Cache )
31 * It is capable of loading the following config files:
32 * - *.config.php (current)
33 * - *.ini.php (deprecated)
34 * - *.htconfig.php (deprecated)
36 class ConfigFileManager
39 * The default name of the user defined legacy config file
43 const CONFIG_HTCONFIG = 'htconfig';
46 * The config file, where overrides per admin page/console are saved at
50 const CONFIG_DATA_FILE = 'node.config.php';
53 * The sample string inside the configs, which shouldn't get loaded
57 const SAMPLE_END = '-sample';
78 * @param string $baseDir The base
79 * @param string $configDir
80 * @param string $staticDir
82 public function __construct(string $baseDir, string $configDir, string $staticDir, array $server = [])
84 $this->baseDir = $baseDir;
85 $this->configDir = $configDir;
86 $this->staticDir = $staticDir;
87 $this->server = $server;
91 * Load the configuration files into an configuration cache
93 * First loads the default value for all the configuration keys, then the legacy configuration files, then the
94 * expected local.config.php
96 * @param Cache $configCache The config cache to load to
97 * @param bool $raw Set up the raw config format
99 * @throws ConfigFileException
101 public function setupCache(Cache $configCache, bool $raw = false)
103 // Load static config files first, the order is important
104 $configCache->load($this->loadStaticConfig('defaults'), Cache::SOURCE_STATIC);
105 $configCache->load($this->loadStaticConfig('settings'), Cache::SOURCE_STATIC);
107 // try to load the legacy config first
108 $configCache->load($this->loadLegacyConfig('htpreconfig'), Cache::SOURCE_FILE);
109 $configCache->load($this->loadLegacyConfig('htconfig'), Cache::SOURCE_FILE);
111 // Now load every other config you find inside the 'config/' directory
112 $this->loadCoreConfig($configCache);
114 // Now load the node.config.php file with the node specific config values (based on admin gui/console actions)
115 $this->loadDataConfig($configCache);
117 $configCache->load($this->loadEnvConfig(), Cache::SOURCE_ENV);
119 // In case of install mode, add the found basepath (because there isn't a basepath set yet
120 if (!$raw && empty($configCache->get('system', 'basepath'))) {
121 // Setting at least the basepath we know
122 $configCache->set('system', 'basepath', $this->baseDir, Cache::SOURCE_FILE);
127 * Tries to load the static core-configuration and returns the config array.
129 * @param string $name The name of the configuration
131 * @return array The config array (empty if no config found)
133 * @throws ConfigFileException if the configuration file isn't readable
135 private function loadStaticConfig(string $name): array
137 $configName = $this->staticDir . DIRECTORY_SEPARATOR . $name . '.config.php';
138 $iniName = $this->staticDir . DIRECTORY_SEPARATOR . $name . '.ini.php';
140 if (file_exists($configName)) {
141 return $this->loadConfigFile($configName);
142 } else if (file_exists($iniName)) {
143 return $this->loadINIConfigFile($iniName);
150 * Tries to load the specified core-configuration into the config cache.
152 * @param Cache $configCache The Config cache
154 * @throws ConfigFileException if the configuration file isn't readable
156 private function loadCoreConfig(Cache $configCache)
158 // try to load legacy ini-files first
159 foreach ($this->getConfigFiles(true) as $configFile) {
160 $configCache->load($this->loadINIConfigFile($configFile), Cache::SOURCE_FILE);
163 // try to load supported config at last to overwrite it
164 foreach ($this->getConfigFiles() as $configFile) {
165 $configCache->load($this->loadConfigFile($configFile), Cache::SOURCE_FILE);
170 * Tries to load the data config file with the overridden data
172 * @param Cache $configCache The Config cache
174 * @throws ConfigFileException In case the config file isn't loadable
176 private function loadDataConfig(Cache $configCache)
178 $filename = $this->configDir . '/' . self::CONFIG_DATA_FILE;
180 if (file_exists($filename) && (filesize($filename) > 0)) {
182 // The fallback empty return content
183 $content = '<?php return [];';
186 * This code-block creates a readonly node.config.php content stream (fopen() with "r")
187 * The stream is locked shared (LOCK_SH), so not exclusively, but the OS knows that there's a lock
189 * Any exclusive locking (LOCK_EX) would need to wait until all LOCK_SHs are unlocked
191 if (($configStream = @fopen($filename, 'r')) === false) {
192 throw new ConfigFileException(sprintf('Cannot open file "%s" in mode r', $filename));
196 if (flock($configStream, LOCK_SH)) {
197 clearstatcache(true, $filename);
199 if (($filesize = filesize($filename)) === 0) {
203 $content = fread($configStream, $filesize);
205 throw new ConfigFileException(sprintf('Couldn\'t read file %s', $filename));
209 // unlock and close the stream for every circumstances
210 flock($configStream, LOCK_UN);
211 fclose($configStream);
215 * Evaluate the content string as PHP code
217 * @see https://www.php.net/manual/en/function.eval.php
220 * To leave the PHP mode, we have to use the appropriate PHP tags '?>' as prefix.
222 $dataArray = eval('?>' . $content);
224 if (is_array($dataArray)) {
225 $configCache->load($dataArray, Cache::SOURCE_DATA);
231 * Checks, if the node.config.php is writable
235 public function dataIsWritable(): bool
237 $filename = $this->configDir . '/' . self::CONFIG_DATA_FILE;
239 if (file_exists($filename)) {
240 return is_writable($filename);
242 return is_writable($this->configDir);
247 * Saves overridden config entries back into the data.config.php
249 * @param Cache $configCache The config cache
251 * @throws ConfigFileException In case the config file isn't writeable or the data is invalid
253 public function saveData(Cache $configCache)
255 $filename = $this->configDir . '/' . self::CONFIG_DATA_FILE;
257 if (file_exists($filename)) {
264 * Creates a read-write stream
266 * @see https://www.php.net/manual/en/function.fopen.php
267 * @note Open the file for reading and writing. If the file does not exist, it is created.
268 * If it exists, it is neither truncated (as opposed to 'w'), nor the call to this function fails
269 * (as is the case with 'x'). The file pointer is positioned on the beginning of the file.
272 if (($configStream = @fopen($filename, 'c+')) === false) {
273 throw new ConfigFileException(sprintf('Cannot open file "%s" in mode c+', $filename));
277 // We do want an exclusive lock, so we wait until every LOCK_SH (config reading) is unlocked
278 if (flock($configStream, LOCK_EX)) {
281 * If the file exists, we read the whole file again to avoid a race condition with concurrent threads that could have modified the file between the first config read of this thread and now
282 * Since we're currently exclusive locked, no other process can now change the config again
285 // When reading the config file too fast, we get a wrong filesize, "clearstatcache" prevents that
286 clearstatcache(true, $filename);
287 $content = fread($configStream, filesize($filename));
289 throw new ConfigFileException(sprintf('Cannot read file %s', $filename));
292 // Event truncating the whole content wouldn't automatically rewind the stream,
293 // so we need to do it manually
294 rewind($configStream);
296 $dataArray = eval('?>' . $content);
298 // Merge the new content into the existing file based config cache and use it
299 // as the new config cache
300 if (is_array($dataArray)) {
301 $fileConfigCache = new Cache();
302 $fileConfigCache->load($dataArray, Cache::SOURCE_DATA);
303 $configCache = $fileConfigCache->merge($configCache);
307 // Only SOURCE_DATA is wanted, the rest isn't part of the node.config.php file
308 $data = $configCache->getDataBySource(Cache::SOURCE_DATA);
310 $encodedData = ConfigFileTransformer::encode($data);
312 throw new ConfigFileException('config source cannot get encoded');
315 // Once again to avoid wrong, implicit "filesize" calls during the fwrite() or ftruncate() call
316 clearstatcache(true, $filename);
317 if (!ftruncate($configStream, 0) ||
318 !fwrite($configStream, $encodedData) ||
319 !fflush($configStream)) {
320 throw new ConfigFileException(sprintf('Cannot modify locked file %s', $filename));
324 // unlock and close the stream for every circumstances
325 flock($configStream, LOCK_UN);
326 fclose($configStream);
331 * Tries to load the specified addon-configuration and returns the config array.
333 * @param string $name The name of the configuration
335 * @return array The config array (empty if no config found)
337 * @throws ConfigFileException if the configuration file isn't readable
339 public function loadAddonConfig(string $name): array
341 $filepath = $this->baseDir . DIRECTORY_SEPARATOR . // /var/www/html/
342 Addon::DIRECTORY . DIRECTORY_SEPARATOR . // addon/
343 $name . DIRECTORY_SEPARATOR . // openstreetmap/
344 'config' . DIRECTORY_SEPARATOR . // config/
345 $name . ".config.php"; // openstreetmap.config.php
347 if (file_exists($filepath)) {
348 return $this->loadConfigFile($filepath);
355 * Tries to load environment specific variables, based on the `env.config.php` mapping table
357 * @return array The config array (empty if no config was found)
359 * @throws ConfigFileException if the configuration file isn't readable
361 protected function loadEnvConfig(): array
363 $filepath = $this->staticDir . DIRECTORY_SEPARATOR . // /var/www/html/static/
364 "env.config.php"; // env.config.php
366 if (!file_exists($filepath)) {
370 $envConfig = $this->loadConfigFile($filepath);
374 foreach ($envConfig as $envKey => $configStructure) {
375 if (isset($this->server[$envKey])) {
376 $return[$configStructure[0]][$configStructure[1]] = $this->server[$envKey];
384 * Get the config files of the config-directory
386 * @param bool $ini True, if scan for ini-files instead of config files
390 private function getConfigFiles(bool $ini = false): array
392 $files = scandir($this->configDir);
395 $filePattern = ($ini ? '*.ini.php' : '*.config.php');
397 // Don't load sample files
398 $sampleEnd = self::SAMPLE_END . ($ini ? '.ini.php' : '.config.php');
400 foreach ($files as $filename) {
401 if (fnmatch($filePattern, $filename) &&
402 substr_compare($filename, $sampleEnd, -strlen($sampleEnd)) &&
403 $filename !== self::CONFIG_DATA_FILE) {
404 $found[] = $this->configDir . '/' . $filename;
412 * Tries to load the legacy config files (.htconfig.php, .htpreconfig.php) and returns the config array.
414 * @param string $name The name of the config file (default is empty, which means .htconfig.php)
416 * @return array The configuration array (empty if no config found)
418 * @deprecated since version 2018.09
420 private function loadLegacyConfig(string $name = ''): array
422 $name = !empty($name) ? $name : self::CONFIG_HTCONFIG;
423 $fullName = $this->baseDir . DIRECTORY_SEPARATOR . '.' . $name . '.php';
426 if (file_exists($fullName)) {
427 $a = new \stdClass();
431 $htConfigCategories = array_keys($a->config);
433 // map the legacy configuration structure to the current structure
434 foreach ($htConfigCategories as $htConfigCategory) {
435 if (is_array($a->config[$htConfigCategory])) {
436 $keys = array_keys($a->config[$htConfigCategory]);
438 foreach ($keys as $key) {
439 $config[$htConfigCategory][$key] = $a->config[$htConfigCategory][$key];
442 $config['config'][$htConfigCategory] = $a->config[$htConfigCategory];
448 if (isset($db_host)) {
449 $config['database']['hostname'] = $db_host;
452 if (isset($db_user)) {
453 $config['database']['username'] = $db_user;
456 if (isset($db_pass)) {
457 $config['database']['password'] = $db_pass;
460 if (isset($db_data)) {
461 $config['database']['database'] = $db_data;
464 if (isset($config['system']['db_charset'])) {
465 $config['database']['charset'] = $config['system']['db_charset'];
467 if (isset($pidfile)) {
468 $config['system']['pidfile'] = $pidfile;
471 if (isset($default_timezone)) {
472 $config['system']['default_timezone'] = $default_timezone;
473 unset($default_timezone);
476 $config['system']['language'] = $lang;
485 * Tries to load the specified legacy configuration file and returns the config array.
487 * @param string $filepath
489 * @return array The configuration array
490 * @throws ConfigFileException
491 * @deprecated since version 2018.12
493 private function loadINIConfigFile(string $filepath): array
495 $contents = include($filepath);
497 $config = parse_ini_string($contents, true, INI_SCANNER_TYPED);
499 if ($config === false) {
500 throw new ConfigFileException('Error parsing INI config file ' . $filepath);
507 * Tries to load the specified configuration file and returns the config array.
509 * The config format is PHP array and the template for configuration files is the following:
517 * @param string $filepath The filepath of the
519 * @return array The config array0
521 * @throws ConfigFileException if the config cannot get loaded.
523 private function loadConfigFile(string $filepath): array
525 if (file_exists($filepath)) {
526 $config = include $filepath;
528 if (!is_array($config)) {
529 throw new ConfigFileException('Error loading config file ' . $filepath);