From be6b2295349d4d3e399b58f845efc5014e299275 Mon Sep 17 00:00:00 2001 From: Philipp Holzer Date: Sun, 3 Feb 2019 18:54:25 +0100 Subject: [PATCH 01/31] 1) Refactor App->config[] into Core\Config --- mod/friendica.php | 7 +- src/App.php | 150 ++++----------------- src/Core/Config.php | 120 ++++++++++++++++- src/Core/Config/IConfigAdapter.php | 2 +- src/Core/Config/JITConfigAdapter.php | 22 ++- src/Core/Config/PreloadConfigAdapter.php | 16 +-- src/Core/Console/AutomaticInstallation.php | 8 +- src/Core/Console/Config.php | 8 +- src/Core/Console/Typo.php | 4 +- src/Core/PConfig.php | 2 +- src/Database/DBA.php | 29 ++-- 11 files changed, 191 insertions(+), 177 deletions(-) diff --git a/mod/friendica.php b/mod/friendica.php index d10deb2e88..10a4f93aff 100644 --- a/mod/friendica.php +++ b/mod/friendica.php @@ -29,7 +29,7 @@ function friendica_init(App $a) } $sql_extra = ''; - if (!empty($a->config['admin_nickname'])) { + if (Config::getConfigValue('config', 'admin_nickname') !== null) { $sql_extra = sprintf(" AND `nickname` = '%s' ", DBA::escape(Config::get('config', 'admin_nickname'))); } if (!empty(Config::get('config', 'admin_email'))) { @@ -48,8 +48,9 @@ function friendica_init(App $a) Config::load('feature_lock'); $locked_features = []; - if (!empty($a->config['feature_lock'])) { - foreach ($a->config['feature_lock'] as $k => $v) { + $featureLock = Config::getConfigValue('config', 'feature_lock'); + if (isset($featureLock)) { + foreach ($featureLock as $k => $v) { if ($k === 'config_loaded') { continue; } diff --git a/src/App.php b/src/App.php index b910765e12..db35c45c19 100644 --- a/src/App.php +++ b/src/App.php @@ -381,28 +381,29 @@ class App include $this->getBasePath() . '/.htconfig.php'; - $this->setConfigValue('database', 'hostname', $db_host); - $this->setConfigValue('database', 'username', $db_user); - $this->setConfigValue('database', 'password', $db_pass); - $this->setConfigValue('database', 'database', $db_data); - if (isset($a->config['system']['db_charset'])) { - $this->setConfigValue('database', 'charset', $a->config['system']['db_charset']); + Core\Config::setConfigValue('database', 'hostname', $db_host); + Core\Config::setConfigValue('database', 'username', $db_user); + Core\Config::setConfigValue('database', 'password', $db_pass); + Core\Config::setConfigValue('database', 'database', $db_data); + $charset = Core\Config::getConfigValue('system', 'db_charset'); + if (isset($charset)) { + Core\Config::setConfigValue('database', 'charset', $charset); } unset($db_host, $db_user, $db_pass, $db_data); if (isset($default_timezone)) { - $this->setConfigValue('system', 'default_timezone', $default_timezone); + Core\Config::setConfigValue('system', 'default_timezone', $default_timezone); unset($default_timezone); } if (isset($pidfile)) { - $this->setConfigValue('system', 'pidfile', $pidfile); + Core\Config::setConfigValue('system', 'pidfile', $pidfile); unset($pidfile); } if (isset($lang)) { - $this->setConfigValue('system', 'language', $lang); + Core\Config::setConfigValue('system', 'language', $lang); unset($lang); } } @@ -437,7 +438,7 @@ class App throw new Exception('Error parsing INI config file ' . $filepath); } - $this->loadConfigArray($config, $overwrite); + Core\Config::loadConfigArray($config, $overwrite); } /** @@ -468,7 +469,7 @@ class App throw new Exception('Error loading config file ' . $filepath); } - $this->loadConfigArray($config, $overwrite); + Core\Config::loadConfigArray($config, $overwrite); } /** @@ -490,26 +491,6 @@ class App } } - /** - * Tries to load the specified configuration array into the App->config array. - * Doesn't overwrite previously set values by default to prevent default config files to supersede DB Config. - * - * @param array $config - * @param bool $overwrite Force value overwrite if the config key already exists - */ - private function loadConfigArray(array $config, $overwrite = false) - { - foreach ($config as $category => $values) { - foreach ($values as $key => $value) { - if ($overwrite) { - $this->setConfigValue($category, $key, $value); - } else { - $this->setDefaultConfigValue($category, $key, $value); - } - } - } - } - /** * Loads the default timezone * @@ -519,8 +500,8 @@ class App */ private function loadDefaultTimezone() { - if ($this->getConfigValue('system', 'default_timezone')) { - $this->timezone = $this->getConfigValue('system', 'default_timezone'); + if (Core\Config::getConfigValue('system', 'default_timezone')) { + $this->timezone = Core\Config::getConfigValue('system', 'default_timezone'); } else { global $default_timezone; $this->timezone = !empty($default_timezone) ? $default_timezone : 'UTC'; @@ -546,7 +527,7 @@ class App $relative_script_path = defaults($_SERVER, 'SCRIPT_URL' , $relative_script_path); $relative_script_path = defaults($_SERVER, 'REQUEST_URI' , $relative_script_path); - $this->urlPath = $this->getConfigValue('system', 'urlpath'); + $this->urlPath = Core\Config::getConfigValue('system', 'urlpath'); /* $relative_script_path gives /relative/path/to/friendica/module/parameter * QUERY_STRING gives pagename=module/parameter @@ -574,11 +555,11 @@ class App return; } - $db_host = $this->getConfigValue('database', 'hostname'); - $db_user = $this->getConfigValue('database', 'username'); - $db_pass = $this->getConfigValue('database', 'password'); - $db_data = $this->getConfigValue('database', 'database'); - $charset = $this->getConfigValue('database', 'charset'); + $db_host = Core\Config::getConfigValue('database', 'hostname'); + $db_user = Core\Config::getConfigValue('database', 'username'); + $db_pass = Core\Config::getConfigValue('database', 'password'); + $db_data = Core\Config::getConfigValue('database', 'database'); + $charset = Core\Config::getConfigValue('database', 'charset'); // Use environment variables for mysql if they are set beforehand if (!empty(getenv('MYSQL_HOST')) @@ -789,9 +770,9 @@ class App // compose the page title from the sitename and the // current module called if (!$this->module == '') { - $this->page['title'] = $this->config['sitename'] . ' (' . $this->module . ')'; + $this->page['title'] = Core\Config::getConfigValue('config', 'sitename') . ' (' . $this->module . ')'; } else { - $this->page['title'] = $this->config['sitename']; + $this->page['title'] = Core\Config::getConfigValue('config', 'sitename'); } if (!empty(Core\Renderer::$theme['stylesheet'])) { @@ -912,7 +893,9 @@ class App */ public function saveTimestamp($timestamp, $value) { - if (!isset($this->config['system']['profiler']) || !$this->config['system']['profiler']) { + $profiler = Core\Config::getConfigValue('system', 'profiler'); + + if (!isset($profiler) || !$profiler) { return; } @@ -1150,7 +1133,7 @@ class App return; } - $cmdline = $this->getConfigValue('config', 'php_path', 'php') . ' ' . escapeshellarg($command); + $cmdline = Core\Config::getConfigValue('config', 'php_path', 'php') . ' ' . escapeshellarg($command); foreach ($args as $key => $value) { if (!is_null($value) && is_bool($value) && !$value) { @@ -1234,87 +1217,6 @@ class App return true; } - /** - * @param string $cat Config category - * @param string $k Config key - * @param mixed $default Default value if it isn't set - * - * @return string Returns the value of the Config entry - */ - public function getConfigValue($cat, $k, $default = null) - { - $return = $default; - - if ($cat === 'config') { - if (isset($this->config[$k])) { - $return = $this->config[$k]; - } - } else { - if (isset($this->config[$cat][$k])) { - $return = $this->config[$cat][$k]; - } - } - - return $return; - } - - /** - * Sets a default value in the config cache. Ignores already existing keys. - * - * @param string $cat Config category - * @param string $k Config key - * @param mixed $v Default value to set - */ - private function setDefaultConfigValue($cat, $k, $v) - { - if (!isset($this->config[$cat][$k])) { - $this->setConfigValue($cat, $k, $v); - } - } - - /** - * Sets a value in the config cache. Accepts raw output from the config table - * - * @param string $cat Config category - * @param string $k Config key - * @param mixed $v Value to set - */ - public function setConfigValue($cat, $k, $v) - { - // Only arrays are serialized in database, so we have to unserialize sparingly - $value = is_string($v) && preg_match("|^a:[0-9]+:{.*}$|s", $v) ? unserialize($v) : $v; - - if ($cat === 'config') { - $this->config[$k] = $value; - } else { - if (!isset($this->config[$cat])) { - $this->config[$cat] = []; - } - - $this->config[$cat][$k] = $value; - } - } - - /** - * Deletes a value from the config cache - * - * @param string $cat Config category - * @param string $k Config key - */ - public function deleteConfigValue($cat, $k) - { - if ($cat === 'config') { - if (isset($this->config[$k])) { - unset($this->config[$k]); - } - } else { - if (isset($this->config[$cat][$k])) { - unset($this->config[$cat][$k]); - } - } - } - - /** * Retrieves a value from the user config cache * diff --git a/src/Core/Config.php b/src/Core/Config.php index 755dc6ebbc..2a719e8e41 100644 --- a/src/Core/Config.php +++ b/src/Core/Config.php @@ -20,6 +20,8 @@ use Friendica\BaseObject; */ class Config extends BaseObject { + public static $config = []; + /** * @var \Friendica\Core\Config\IConfigAdapter */ @@ -32,7 +34,7 @@ class Config extends BaseObject return; } - if (self::getApp()->getConfigValue('system', 'config_adapter') == 'preload') { + if (self::getConfigValue('system', 'config_adapter') == 'preload') { self::$adapter = new Config\PreloadConfigAdapter(); } else { self::$adapter = new Config\JITConfigAdapter(); @@ -69,7 +71,7 @@ class Config extends BaseObject * ($family) and a key. * * Get a particular config value from the given category ($family) - * and the $key from a cached storage in $a->config[$uid]. + * and the $key from a cached storage in static::config[$uid]. * $instore is only used by the set_config function * to determine if the key already exists in the DB * If a key is found in the DB but doesn't exist in @@ -88,7 +90,7 @@ class Config extends BaseObject { // Database isn't ready or populated yet, fallback to file config if (!self::getApp()->getMode()->has(App\Mode::DBCONFIGAVAILABLE)) { - return self::getApp()->getConfigValue($family, $key, $default_value); + return self::getConfigValue($family, $key, $default_value); } if (empty(self::$adapter)) { @@ -152,4 +154,116 @@ class Config extends BaseObject return self::$adapter->delete($family, $key); } + + /** + * Tries to load the specified configuration array into the App->config array. + * Doesn't overwrite previously set values by default to prevent default config files to supersede DB Config. + * + * @param array $config + * @param bool $overwrite Force value overwrite if the config key already exists + */ + public function loadConfigArray(array $config, $overwrite = false) + { + foreach ($config as $category => $values) { + foreach ($values as $key => $value) { + if ($overwrite) { + self::setConfigValue($category, $key, $value); + } else { + self::setDefaultConfigValue($category, $key, $value); + } + } + } + } + + /** + * @param string $cat Config category + * @param string $k Config key + * @param mixed $default Default value if it isn't set + * + * @return string Returns the value of the Config entry + */ + public static function getConfigValue($cat, $k = null, $default = null) + { + $return = $default; + + if ($cat === 'config') { + if (isset(self::$config[$k])) { + $return = self::$config[$k]; + } + } else { + if (isset(self::$config[$cat][$k])) { + $return = self::$config[$cat][$k]; + } elseif ($k == null && isset(self::$config[$cat])) { + $return = self::$config[$cat]; + } + } + + return $return; + } + + /** + * Sets a default value in the config cache. Ignores already existing keys. + * + * @param string $cat Config category + * @param string $k Config key + * @param mixed $v Default value to set + */ + private static function setDefaultConfigValue($cat, $k, $v) + { + if (!isset(self::$config[$cat][$k])) { + self::setConfigValue($cat, $k, $v); + } + } + + /** + * Sets a value in the config cache. Accepts raw output from the config table + * + * @param string $cat Config category + * @param string $k Config key + * @param mixed $v Value to set + */ + public static function setConfigValue($cat, $k, $v) + { + // Only arrays are serialized in database, so we have to unserialize sparingly + $value = is_string($v) && preg_match("|^a:[0-9]+:{.*}$|s", $v) ? unserialize($v) : $v; + + if ($cat === 'config') { + self::$config[$k] = $value; + } else { + if (!isset(self::$config[$cat])) { + self::$config[$cat] = []; + } + + self::$config[$cat][$k] = $value; + } + } + + /** + * Deletes a value from the config cache + * + * @param string $cat Config category + * @param string $k Config key + */ + public static function deleteConfigValue($cat, $k) + { + if ($cat === 'config') { + if (isset(self::$config[$k])) { + unset(self::$config[$k]); + } + } else { + if (isset(self::$config[$cat][$k])) { + unset(self::$config[$cat][$k]); + } + } + } + + /** + * Returns the whole configuration + * + * @return array The configuration + */ + public static function getAll() + { + return self::$config; + } } diff --git a/src/Core/Config/IConfigAdapter.php b/src/Core/Config/IConfigAdapter.php index 9d8eefd777..5861b4c7e1 100644 --- a/src/Core/Config/IConfigAdapter.php +++ b/src/Core/Config/IConfigAdapter.php @@ -25,7 +25,7 @@ interface IConfigAdapter * ($family) and a key. * * Get a particular config value from the given category ($family) - * and the $key from a cached storage in $a->config[$uid]. + * and the $key from a cached storage in static::$config[$uid]. * $instore is only used by the set_config function * to determine if the key already exists in the DB * If a key is found in the DB but doesn't exist in diff --git a/src/Core/Config/JITConfigAdapter.php b/src/Core/Config/JITConfigAdapter.php index ce1c13b2ca..dbae202917 100644 --- a/src/Core/Config/JITConfigAdapter.php +++ b/src/Core/Config/JITConfigAdapter.php @@ -1,7 +1,7 @@ */ -class JITConfigAdapter extends BaseObject implements IConfigAdapter +class JITConfigAdapter implements IConfigAdapter { private $cache; private $in_db; @@ -28,7 +28,7 @@ class JITConfigAdapter extends BaseObject implements IConfigAdapter while ($config = DBA::fetch($configs)) { $k = $config['k']; - self::getApp()->setConfigValue($cat, $k, $config['v']); + Config::setConfigValue($cat, $k, $config['v']); if ($cat !== 'config') { $this->cache[$cat][$k] = $config['v']; @@ -40,8 +40,6 @@ class JITConfigAdapter extends BaseObject implements IConfigAdapter public function get($cat, $k, $default_value = null, $refresh = false) { - $a = self::getApp(); - if (!$refresh) { // Do we have the cached value? Then return it if (isset($this->cache[$cat][$k])) { @@ -62,18 +60,18 @@ class JITConfigAdapter extends BaseObject implements IConfigAdapter $this->cache[$cat][$k] = $value; $this->in_db[$cat][$k] = true; return $value; - } elseif (isset($a->config[$cat][$k])) { + } elseif (Config::getConfigValue($cat, $k) !== null) { // Assign the value (mostly) from config/local.config.php file to the cache - $this->cache[$cat][$k] = $a->config[$cat][$k]; + $this->cache[$cat][$k] = Config::getConfigValue($cat, $k); $this->in_db[$cat][$k] = false; - return $a->config[$cat][$k]; - } elseif (isset($a->config[$k])) { + return Config::getConfigValue($cat, $k); + } elseif (Config::getConfigValue('config', $k) !== null) { // Assign the value (mostly) from config/local.config.php file to the cache - $this->cache[$k] = $a->config[$k]; + $this->cache[$k] = Config::getConfigValue('config', $k); $this->in_db[$k] = false; - return $a->config[$k]; + return Config::getConfigValue('config', $k); } $this->cache[$cat][$k] = '!!'; @@ -102,7 +100,7 @@ class JITConfigAdapter extends BaseObject implements IConfigAdapter return true; } - self::getApp()->setConfigValue($cat, $k, $value); + Config::setConfigValue($cat, $k, $value); // Assign the just added value to the cache $this->cache[$cat][$k] = $dbvalue; diff --git a/src/Core/Config/PreloadConfigAdapter.php b/src/Core/Config/PreloadConfigAdapter.php index ac59d94558..dc5c45379f 100644 --- a/src/Core/Config/PreloadConfigAdapter.php +++ b/src/Core/Config/PreloadConfigAdapter.php @@ -3,7 +3,7 @@ namespace Friendica\Core\Config; use Exception; -use Friendica\BaseObject; +use Friendica\Core\Config; use Friendica\Database\DBA; /** @@ -13,7 +13,7 @@ use Friendica\Database\DBA; * * @author Hypolite Petovan */ -class PreloadConfigAdapter extends BaseObject implements IConfigAdapter +class PreloadConfigAdapter implements IConfigAdapter { private $config_loaded = false; @@ -30,7 +30,7 @@ class PreloadConfigAdapter extends BaseObject implements IConfigAdapter $configs = DBA::select('config', ['cat', 'v', 'k']); while ($config = DBA::fetch($configs)) { - self::getApp()->setConfigValue($config['cat'], $config['k'], $config['v']); + Config::setConfigValue($config['cat'], $config['k'], $config['v']); } DBA::close($configs); @@ -42,11 +42,11 @@ class PreloadConfigAdapter extends BaseObject implements IConfigAdapter if ($refresh) { $config = DBA::selectFirst('config', ['v'], ['cat' => $cat, 'k' => $k]); if (DBA::isResult($config)) { - self::getApp()->setConfigValue($cat, $k, $config['v']); + Config::setConfigValue($cat, $k, $config['v']); } } - $return = self::getApp()->getConfigValue($cat, $k, $default_value); + $return = Config::getConfigValue($cat, $k, $default_value); return $return; } @@ -58,11 +58,11 @@ class PreloadConfigAdapter extends BaseObject implements IConfigAdapter // The exception are array values. $compare_value = !is_array($value) ? (string)$value : $value; - if (self::getApp()->getConfigValue($cat, $k) === $compare_value) { + if (Config::getConfigValue($cat, $k) === $compare_value) { return true; } - self::getApp()->setConfigValue($cat, $k, $value); + Config::setConfigValue($cat, $k, $value); // manage array value $dbvalue = is_array($value) ? serialize($value) : $value; @@ -77,7 +77,7 @@ class PreloadConfigAdapter extends BaseObject implements IConfigAdapter public function delete($cat, $k) { - self::getApp()->deleteConfigValue($cat, $k); + Config::deleteConfigValue($cat, $k); $result = DBA::delete('config', ['cat' => $cat, 'k' => $k]); diff --git a/src/Core/Console/AutomaticInstallation.php b/src/Core/Console/AutomaticInstallation.php index c38dab9806..9a63f56ed4 100644 --- a/src/Core/Console/AutomaticInstallation.php +++ b/src/Core/Console/AutomaticInstallation.php @@ -100,10 +100,10 @@ HELP; } } - $db_host = $a->getConfigValue('database', 'hostname'); - $db_user = $a->getConfigValue('database', 'username'); - $db_pass = $a->getConfigValue('database', 'password'); - $db_data = $a->getConfigValue('database', 'database'); + $db_host = Config::getConfigValue('database', 'hostname'); + $db_user = Config::getConfigValue('database', 'username'); + $db_pass = Config::getConfigValue('database', 'password'); + $db_data = Config::getConfigValue('database', 'database'); } else { // Creating config file $this->out("Creating config file...\n"); diff --git a/src/Core/Console/Config.php b/src/Core/Console/Config.php index ce367fffbf..8a0e0f88cf 100644 --- a/src/Core/Console/Config.php +++ b/src/Core/Console/Config.php @@ -124,9 +124,10 @@ HELP; $cat = $this->getArgument(0); Core\Config::load($cat); - if (!is_null($a->config[$cat])) { + if (Core\Config::getConfigValue($cat) !== null) { $this->out("[{$cat}]"); - foreach ($a->config[$cat] as $key => $value) { + $catVal = Core\Config::getConfigValue($cat); + foreach ($catVal as $key => $value) { if (is_array($value)) { foreach ($value as $k => $v) { $this->out("{$key}[{$k}] => " . $v); @@ -147,7 +148,8 @@ HELP; $this->out('Warning: The JIT (Just In Time) Config adapter doesn\'t support loading the entire configuration, showing file config only'); } - foreach ($a->config as $cat => $section) { + $config = Core\Config::getAll(); + foreach ($config as $cat => $section) { if (is_array($section)) { foreach ($section as $key => $value) { if (is_array($value)) { diff --git a/src/Core/Console/Typo.php b/src/Core/Console/Typo.php index 82357b4753..3f9dce84e0 100644 --- a/src/Core/Console/Typo.php +++ b/src/Core/Console/Typo.php @@ -41,9 +41,7 @@ HELP; throw new \Asika\SimpleConsole\CommandArgsException('Too many arguments'); } - $a = \get_app(); - - $php_path = $a->getConfigValue('config', 'php_path', 'php'); + $php_path = \Friendica\Core\Config::getConfigValue('config', 'php_path', 'php'); if ($this->getOption('v')) { $this->out('Directory: src'); diff --git a/src/Core/PConfig.php b/src/Core/PConfig.php index 584318adbc..ffd72f0a7f 100644 --- a/src/Core/PConfig.php +++ b/src/Core/PConfig.php @@ -34,7 +34,7 @@ class PConfig extends BaseObject return; } - if ($a->getConfigValue('system', 'config_adapter') == 'preload') { + if (Config::getConfigValue('system', 'config_adapter') == 'preload') { self::$adapter = new Config\PreloadPConfigAdapter($uid); } else { self::$adapter = new Config\JITPConfigAdapter(); diff --git a/src/Database/DBA.php b/src/Database/DBA.php index e14d94ce04..51b9be967e 100644 --- a/src/Database/DBA.php +++ b/src/Database/DBA.php @@ -2,10 +2,9 @@ namespace Friendica\Database; -// Do not use Core\Config in this class at risk of infinite loop. -// Please use App->getConfigVariable() instead. -//use Friendica\Core\Config; - +// Do not use native get/set/load of Core\Config in this class at risk of infinite loop. +// Please use Core\Config::getConfigVariable() instead. +use Friendica\Core\Config; use Friendica\Core\Logger; use Friendica\Core\System; use Friendica\Util\DateTimeFormat; @@ -212,7 +211,7 @@ class DBA private static function logIndex($query) { $a = \get_app(); - if (!$a->getConfigVariable('system', 'db_log_index')) { + if (!Config::getConfigValue('system', 'db_log_index')) { return; } @@ -231,18 +230,18 @@ class DBA return; } - $watchlist = explode(',', $a->getConfigVariable('system', 'db_log_index_watch')); - $blacklist = explode(',', $a->getConfigVariable('system', 'db_log_index_blacklist')); + $watchlist = explode(',', Config::getConfigValue('system', 'db_log_index_watch')); + $blacklist = explode(',', Config::getConfigValue('system', 'db_log_index_blacklist')); while ($row = self::fetch($r)) { - if ((intval($a->getConfigVariable('system', 'db_loglimit_index')) > 0)) { + if ((intval(Config::getConfigValue('system', 'db_loglimit_index')) > 0)) { $log = (in_array($row['key'], $watchlist) && - ($row['rows'] >= intval($a->getConfigVariable('system', 'db_loglimit_index')))); + ($row['rows'] >= intval(Config::getConfigValue('system', 'db_loglimit_index')))); } else { $log = false; } - if ((intval($a->getConfigVariable('system', 'db_loglimit_index_high')) > 0) && ($row['rows'] >= intval($a->getConfigVariable('system', 'db_loglimit_index_high')))) { + if ((intval(Config::getConfigValue('system', 'db_loglimit_index_high')) > 0) && ($row['rows'] >= intval($Config::getConfigValue('system', 'db_loglimit_index_high')))) { $log = true; } @@ -252,7 +251,7 @@ class DBA if ($log) { $backtrace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS); - @file_put_contents($a->getConfigVariable('system', 'db_log_index'), DateTimeFormat::utcNow()."\t". + @file_put_contents(Config::getConfigValue('system', 'db_log_index'), DateTimeFormat::utcNow()."\t". $row['key']."\t".$row['rows']."\t".$row['Extra']."\t". basename($backtrace[1]["file"])."\t". $backtrace[1]["line"]."\t".$backtrace[2]["function"]."\t". @@ -422,7 +421,7 @@ class DBA $orig_sql = $sql; - if ($a->getConfigValue('system', 'db_callstack')) { + if (Config::getConfigValue('system', 'db_callstack')) { $sql = "/*".System::callstack()." */ ".$sql; } @@ -583,15 +582,15 @@ class DBA $a->saveTimestamp($stamp1, 'database'); - if ($a->getConfigValue('system', 'db_log')) { + if (Config::getConfigValue('system', 'db_log')) { $stamp2 = microtime(true); $duration = (float)($stamp2 - $stamp1); - if (($duration > $a->getConfigValue('system', 'db_loglimit'))) { + if (($duration > Config::getConfigValue('system', 'db_loglimit'))) { $duration = round($duration, 3); $backtrace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS); - @file_put_contents($a->getConfigValue('system', 'db_log'), DateTimeFormat::utcNow()."\t".$duration."\t". + @file_put_contents(Config::getConfigValue('system', 'db_log'), DateTimeFormat::utcNow()."\t".$duration."\t". basename($backtrace[1]["file"])."\t". $backtrace[1]["line"]."\t".$backtrace[2]["function"]."\t". substr(self::replaceParameters($sql, $args), 0, 2000)."\n", FILE_APPEND); From d43a8184f49715d6716373d360551dcc7fa58d41 Mon Sep 17 00:00:00 2001 From: Philipp Holzer Date: Sun, 3 Feb 2019 19:04:41 +0100 Subject: [PATCH 02/31] 2) Refactor App->config[] into Core\PConfig --- src/App.php | 62 ------------------- src/Core/Config.php | 4 +- src/Core/Config/IConfigAdapter.php | 4 +- src/Core/Config/IPConfigAdapter.php | 6 +- src/Core/Config/JITPConfigAdapter.php | 30 ++++------ src/Core/Config/PreloadPConfigAdapter.php | 18 +++--- src/Core/PConfig.php | 72 ++++++++++++++++++++++- 7 files changed, 98 insertions(+), 98 deletions(-) diff --git a/src/App.php b/src/App.php index db35c45c19..5ebdbf92b8 100644 --- a/src/App.php +++ b/src/App.php @@ -30,7 +30,6 @@ class App public $module_loaded = false; public $module_class = null; public $query_string = ''; - public $config = []; public $page = []; public $profile; public $profile_uid; @@ -1217,67 +1216,6 @@ class App return true; } - /** - * Retrieves a value from the user config cache - * - * @param int $uid User Id - * @param string $cat Config category - * @param string $k Config key - * @param mixed $default Default value if key isn't set - * - * @return string The value of the config entry - */ - public function getPConfigValue($uid, $cat, $k, $default = null) - { - $return = $default; - - if (isset($this->config[$uid][$cat][$k])) { - $return = $this->config[$uid][$cat][$k]; - } - - return $return; - } - - /** - * Sets a value in the user config cache - * - * Accepts raw output from the pconfig table - * - * @param int $uid User Id - * @param string $cat Config category - * @param string $k Config key - * @param mixed $v Value to set - */ - public function setPConfigValue($uid, $cat, $k, $v) - { - // Only arrays are serialized in database, so we have to unserialize sparingly - $value = is_string($v) && preg_match("|^a:[0-9]+:{.*}$|s", $v) ? unserialize($v) : $v; - - if (!isset($this->config[$uid]) || !is_array($this->config[$uid])) { - $this->config[$uid] = []; - } - - if (!isset($this->config[$uid][$cat]) || !is_array($this->config[$uid][$cat])) { - $this->config[$uid][$cat] = []; - } - - $this->config[$uid][$cat][$k] = $value; - } - - /** - * Deletes a value from the user config cache - * - * @param int $uid User Id - * @param string $cat Config category - * @param string $k Config key - */ - public function deletePConfigValue($uid, $cat, $k) - { - if (isset($this->config[$uid][$cat][$k])) { - unset($this->config[$uid][$cat][$k]); - } - } - /** * Generates the site's default sender email address * diff --git a/src/Core/Config.php b/src/Core/Config.php index 2a719e8e41..6b9015c2eb 100644 --- a/src/Core/Config.php +++ b/src/Core/Config.php @@ -45,7 +45,7 @@ class Config extends BaseObject * @brief Loads all configuration values of family into a cached storage. * * All configuration values of the system are stored in global cache - * which is available under the global variable $a->config + * which is available under the global variable self::$config * * @param string $family The category of the configuration value * @@ -132,7 +132,7 @@ class Config extends BaseObject /** * @brief Deletes the given key from the system configuration. * - * Removes the configured value from the stored cache in $a->config + * Removes the configured value from the stored cache in Config::$config * and removes it from the database. * * @param string $family The category of the configuration value diff --git a/src/Core/Config/IConfigAdapter.php b/src/Core/Config/IConfigAdapter.php index 5861b4c7e1..5bbb61ae80 100644 --- a/src/Core/Config/IConfigAdapter.php +++ b/src/Core/Config/IConfigAdapter.php @@ -12,7 +12,7 @@ interface IConfigAdapter * @brief Loads all configuration values into a cached storage. * * All configuration values of the system are stored in global cache - * which is available under the global variable $a->config + * which is available under the global variable Config::$config * * @param string $cat The category of the configuration values to load * @@ -60,7 +60,7 @@ interface IConfigAdapter /** * @brief Deletes the given key from the system configuration. * - * Removes the configured value from the stored cache in $a->config + * Removes the configured value from the stored cache in Config::$config * and removes it from the database. * * @param string $cat The category of the configuration value diff --git a/src/Core/Config/IPConfigAdapter.php b/src/Core/Config/IPConfigAdapter.php index b912418432..f4ad392d7f 100644 --- a/src/Core/Config/IPConfigAdapter.php +++ b/src/Core/Config/IPConfigAdapter.php @@ -18,7 +18,7 @@ interface IPConfigAdapter * @brief Loads all configuration values of a user's config family into a cached storage. * * All configuration values of the given user are stored in global cache - * which is available under the global variable $a->config[$uid]. + * which is available under the global variable self::$config[$uid]. * * @param string $uid The user_id * @param string $cat The category of the configuration value @@ -32,7 +32,7 @@ interface IPConfigAdapter * ($family) and a key. * * Get a particular user's config value from the given category ($family) - * and the $key from a cached storage in $a->config[$uid]. + * and the $key from a cached storage in self::$config[$uid]. * * @param string $uid The user_id * @param string $cat The category of the configuration value @@ -64,7 +64,7 @@ interface IPConfigAdapter /** * @brief Deletes the given key from the users's configuration. * - * Removes the configured value from the stored cache in $a->config[$uid] + * Removes the configured value from the stored cache in self::$config[$uid] * and removes it from the database. * * @param string $uid The user_id diff --git a/src/Core/Config/JITPConfigAdapter.php b/src/Core/Config/JITPConfigAdapter.php index bdaca407ff..4992068f60 100644 --- a/src/Core/Config/JITPConfigAdapter.php +++ b/src/Core/Config/JITPConfigAdapter.php @@ -1,7 +1,7 @@ */ -class JITPConfigAdapter extends BaseObject implements IPConfigAdapter +class JITPConfigAdapter implements IPConfigAdapter { private $in_db; public function load($uid, $cat) { - $a = self::getApp(); - $pconfigs = DBA::select('pconfig', ['v', 'k'], ['cat' => $cat, 'uid' => $uid]); if (DBA::isResult($pconfigs)) { while ($pconfig = DBA::fetch($pconfigs)) { $k = $pconfig['k']; - self::getApp()->setPConfigValue($uid, $cat, $k, $pconfig['v']); + PConfig::setPConfigValue($uid, $cat, $k, $pconfig['v']); $this->in_db[$uid][$cat][$k] = true; } } else if ($cat != 'config') { // Negative caching - $a->config[$uid][$cat] = "!!"; + PConfig::setPConfigValue($uid, $cat, "!!"); } DBA::close($pconfigs); } public function get($uid, $cat, $k, $default_value = null, $refresh = false) { - $a = self::getApp(); - if (!$refresh) { // Looking if the whole family isn't set - if (isset($a->config[$uid][$cat])) { - if ($a->config[$uid][$cat] === '!!') { + if (PConfig::getPConfigValue($uid, $cat) !== null) { + if (PConfig::getPConfigValue($uid, $cat) === '!!') { return $default_value; } } - if (isset($a->config[$uid][$cat][$k])) { - if ($a->config[$uid][$cat][$k] === '!!') { + if (PConfig::getPConfigValue($uid, $cat, $k) !== null) { + if (PConfig::getPConfigValue($uid, $cat, $k) === '!!') { return $default_value; } - return $a->config[$uid][$cat][$k]; + return PConfig::getPConfigValue($uid, $cat, $k); } } @@ -59,13 +55,13 @@ class JITPConfigAdapter extends BaseObject implements IPConfigAdapter if (DBA::isResult($pconfig)) { $val = (preg_match("|^a:[0-9]+:{.*}$|s", $pconfig['v']) ? unserialize($pconfig['v']) : $pconfig['v']); - self::getApp()->setPConfigValue($uid, $cat, $k, $val); + PConfig::setPConfigValue($uid, $cat, $k, $val); $this->in_db[$uid][$cat][$k] = true; return $val; } else { - self::getApp()->setPConfigValue($uid, $cat, $k, '!!'); + PConfig::setPConfigValue($uid, $cat, $k, '!!'); $this->in_db[$uid][$cat][$k] = false; @@ -86,7 +82,7 @@ class JITPConfigAdapter extends BaseObject implements IPConfigAdapter return true; } - self::getApp()->setPConfigValue($uid, $cat, $k, $value); + PConfig::setPConfigValue($uid, $cat, $k, $value); // manage array value $dbvalue = (is_array($value) ? serialize($value) : $dbvalue); @@ -102,7 +98,7 @@ class JITPConfigAdapter extends BaseObject implements IPConfigAdapter public function delete($uid, $cat, $k) { - self::getApp()->deletePConfigValue($uid, $cat, $k); + PConfig::deletePConfigValue($uid, $cat, $k); if (!empty($this->in_db[$uid][$cat][$k])) { unset($this->in_db[$uid][$cat][$k]); diff --git a/src/Core/Config/PreloadPConfigAdapter.php b/src/Core/Config/PreloadPConfigAdapter.php index 6658efa3f6..88774f2979 100644 --- a/src/Core/Config/PreloadPConfigAdapter.php +++ b/src/Core/Config/PreloadPConfigAdapter.php @@ -3,7 +3,7 @@ namespace Friendica\Core\Config; use Exception; -use Friendica\BaseObject; +use Friendica\Core\PConfig; use Friendica\Database\DBA; /** @@ -13,7 +13,7 @@ use Friendica\Database\DBA; * * @author Hypolite Petovan */ -class PreloadPConfigAdapter extends BaseObject implements IPConfigAdapter +class PreloadPConfigAdapter implements IPConfigAdapter { private $config_loaded = false; @@ -34,7 +34,7 @@ class PreloadPConfigAdapter extends BaseObject implements IPConfigAdapter $pconfigs = DBA::select('pconfig', ['cat', 'v', 'k'], ['uid' => $uid]); while ($pconfig = DBA::fetch($pconfigs)) { - self::getApp()->setPConfigValue($uid, $pconfig['cat'], $pconfig['k'], $pconfig['v']); + PConfig::setPConfigValue($uid, $pconfig['cat'], $pconfig['k'], $pconfig['v']); } DBA::close($pconfigs); @@ -50,13 +50,13 @@ class PreloadPConfigAdapter extends BaseObject implements IPConfigAdapter if ($refresh) { $config = DBA::selectFirst('pconfig', ['v'], ['uid' => $uid, 'cat' => $cat, 'k' => $k]); if (DBA::isResult($config)) { - self::getApp()->setPConfigValue($uid, $cat, $k, $config['v']); + PConfig::setPConfigValue($uid, $cat, $k, $config['v']); } else { - self::getApp()->deletePConfigValue($uid, $cat, $k); + PConfig::deletePConfigValue($uid, $cat, $k); } } - $return = self::getApp()->getPConfigValue($uid, $cat, $k, $default_value); + $return = PConfig::getPConfigValue($uid, $cat, $k, $default_value); return $return; } @@ -71,11 +71,11 @@ class PreloadPConfigAdapter extends BaseObject implements IPConfigAdapter // The exception are array values. $compare_value = !is_array($value) ? (string)$value : $value; - if (self::getApp()->getPConfigValue($uid, $cat, $k) === $compare_value) { + if (PConfig::getPConfigValue($uid, $cat, $k) === $compare_value) { return true; } - self::getApp()->setPConfigValue($uid, $cat, $k, $value); + PConfig::setPConfigValue($uid, $cat, $k, $value); // manage array value $dbvalue = is_array($value) ? serialize($value) : $value; @@ -94,7 +94,7 @@ class PreloadPConfigAdapter extends BaseObject implements IPConfigAdapter $this->load($uid, $cat); } - self::getApp()->deletePConfigValue($uid, $cat, $k); + PConfig::deletePConfigValue($uid, $cat, $k); $result = DBA::delete('pconfig', ['uid' => $uid, 'cat' => $cat, 'k' => $k]); diff --git a/src/Core/PConfig.php b/src/Core/PConfig.php index ffd72f0a7f..7104ce83dc 100644 --- a/src/Core/PConfig.php +++ b/src/Core/PConfig.php @@ -20,6 +20,8 @@ use Friendica\BaseObject; */ class PConfig extends BaseObject { + private static $config; + /** * @var \Friendica\Core\Config\IPConfigAdapter */ @@ -45,7 +47,7 @@ class PConfig extends BaseObject * @brief Loads all configuration values of a user's config family into a cached storage. * * All configuration values of the given user are stored in global cache - * which is available under the global variable $a->config[$uid]. + * which is available under the global variable self::$config[$uid]. * * @param string $uid The user_id * @param string $family The category of the configuration value @@ -72,7 +74,7 @@ class PConfig extends BaseObject * ($family) and a key. * * Get a particular user's config value from the given category ($family) - * and the $key from a cached storage in $a->config[$uid]. + * and the $key from a cached storage in self::$config[$uid]. * * @param string $uid The user_id * @param string $family The category of the configuration value @@ -130,7 +132,7 @@ class PConfig extends BaseObject /** * @brief Deletes the given key from the users's configuration. * - * Removes the configured value from the stored cache in $a->config[$uid] + * Removes the configured value from the stored cache in self::$config[$uid] * and removes it from the database. * * @param string $uid The user_id @@ -153,4 +155,68 @@ class PConfig extends BaseObject return self::$adapter->delete($uid, $family, $key); } + + + /** + * Retrieves a value from the user config cache + * + * @param int $uid User Id + * @param string $cat Config category + * @param string $k Config key + * @param mixed $default Default value if key isn't set + * + * @return string The value of the config entry + */ + public static function getPConfigValue($uid, $cat, $k = null, $default = null) + { + $return = $default; + + if (isset(self::$config[$uid][$cat][$k])) { + $return = self::$config[$uid][$cat][$k]; + } elseif ($k == null && isset(self::$config[$uid][$cat])) { + $return = self::$config[$uid][$cat]; + } + + return $return; + } + + /** + * Sets a value in the user config cache + * + * Accepts raw output from the pconfig table + * + * @param int $uid User Id + * @param string $cat Config category + * @param string $k Config key + * @param mixed $v Value to set + */ + public static function setPConfigValue($uid, $cat, $k, $v) + { + // Only arrays are serialized in database, so we have to unserialize sparingly + $value = is_string($v) && preg_match("|^a:[0-9]+:{.*}$|s", $v) ? unserialize($v) : $v; + + if (!isset(self::$config[$uid]) || !is_array(self::$config[$uid])) { + self::$config[$uid] = []; + } + + if (!isset(self::$config[$uid][$cat]) || !is_array(self::$config[$uid][$cat])) { + self::$config[$uid][$cat] = []; + } + + self::$config[$uid][$cat][$k] = $value; + } + + /** + * Deletes a value from the user config cache + * + * @param int $uid User Id + * @param string $cat Config category + * @param string $k Config key + */ + public static function deletePConfigValue($uid, $cat, $k) + { + if (isset(self::$config[$uid][$cat][$k])) { + unset(self::$config[$uid][$cat][$k]); + } + } } From f40c57fc204ff47a3cf9f7eab75e8a635566275c Mon Sep 17 00:00:00 2001 From: Philipp Holzer Date: Sun, 3 Feb 2019 19:05:44 +0100 Subject: [PATCH 03/31] 2) Refactor App->config[] into Core\PConfig --- src/Core/Config/JITPConfigAdapter.php | 2 +- src/Core/PConfig.php | 6 +++++- 2 files changed, 6 insertions(+), 2 deletions(-) diff --git a/src/Core/Config/JITPConfigAdapter.php b/src/Core/Config/JITPConfigAdapter.php index 4992068f60..ac9a56076c 100644 --- a/src/Core/Config/JITPConfigAdapter.php +++ b/src/Core/Config/JITPConfigAdapter.php @@ -28,7 +28,7 @@ class JITPConfigAdapter implements IPConfigAdapter } } else if ($cat != 'config') { // Negative caching - PConfig::setPConfigValue($uid, $cat, "!!"); + PConfig::setPConfigValue($uid, $cat, null, "!!"); } DBA::close($pconfigs); } diff --git a/src/Core/PConfig.php b/src/Core/PConfig.php index 7104ce83dc..75403aaebe 100644 --- a/src/Core/PConfig.php +++ b/src/Core/PConfig.php @@ -203,7 +203,11 @@ class PConfig extends BaseObject self::$config[$uid][$cat] = []; } - self::$config[$uid][$cat][$k] = $value; + if ($k === null) { + self::$config[$uid][$cat] = $value; + } else { + self::$config[$uid][$cat][$k] = $value; + } } /** From 5c50684b5047e259517d67372658ca86976839df Mon Sep 17 00:00:00 2001 From: Philipp Holzer Date: Sun, 3 Feb 2019 19:32:31 +0100 Subject: [PATCH 04/31] 2) Refactor App->config[] into Core\PConfig --- src/Core/Config.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Core/Config.php b/src/Core/Config.php index 6b9015c2eb..bec6539e27 100644 --- a/src/Core/Config.php +++ b/src/Core/Config.php @@ -162,7 +162,7 @@ class Config extends BaseObject * @param array $config * @param bool $overwrite Force value overwrite if the config key already exists */ - public function loadConfigArray(array $config, $overwrite = false) + public static function loadConfigArray(array $config, $overwrite = false) { foreach ($config as $category => $values) { foreach ($values as $key => $value) { From 4af0119b7310e9731e60b11a14fd917580b95715 Mon Sep 17 00:00:00 2001 From: Philipp Holzer Date: Sun, 3 Feb 2019 22:22:04 +0100 Subject: [PATCH 05/31] 3) Introducing ConfigFactory --- boot.php | 14 +- index.php | 11 +- mod/admin.php | 9 +- mod/friendica.php | 6 +- src/App.php | 351 +++++----------------- src/Core/Config.php | 192 ++---------- src/Core/Config/ConfigCache.php | 173 +++++++++++ src/Core/Config/ConfigCacheLoader.php | 159 ++++++++++ src/Core/Config/IConfigCache.php | 34 +++ src/Core/Config/IPConfigCache.php | 41 +++ src/Core/Config/JITConfigAdapter.php | 30 +- src/Core/Config/JITPConfigAdapter.php | 37 ++- src/Core/Config/PreloadConfigAdapter.php | 24 +- src/Core/Config/PreloadPConfigAdapter.php | 30 +- src/Core/Logger.php | 2 +- src/Core/PConfig.php | 146 ++------- src/Core/System.php | 17 ++ src/Database/DBA.php | 36 +-- src/Database/DBStructure.php | 5 +- src/Factory/ConfigFactory.php | 45 +++ src/{Util => Factory}/LoggerFactory.php | 18 +- src/LegacyModule.php | 2 +- src/Util/BasePath.php | 93 ++++++ 23 files changed, 843 insertions(+), 632 deletions(-) create mode 100644 src/Core/Config/ConfigCache.php create mode 100644 src/Core/Config/ConfigCacheLoader.php create mode 100644 src/Core/Config/IConfigCache.php create mode 100644 src/Core/Config/IPConfigCache.php create mode 100644 src/Factory/ConfigFactory.php rename src/{Util => Factory}/LoggerFactory.php (88%) create mode 100644 src/Util/BasePath.php diff --git a/boot.php b/boot.php index 7dc99bbe88..4be12c6a2f 100644 --- a/boot.php +++ b/boot.php @@ -19,18 +19,12 @@ use Friendica\App; use Friendica\BaseObject; -use Friendica\Core\Addon; -use Friendica\Core\Cache; use Friendica\Core\Config; -use Friendica\Core\L10n; use Friendica\Core\PConfig; use Friendica\Core\Protocol; -use Friendica\Core\System; -use Friendica\Core\Update; -use Friendica\Core\Worker; use Friendica\Database\DBA; use Friendica\Model\Contact; -use Friendica\Model\Conversation; +use Friendica\Util\BasePath; use Friendica\Util\DateTimeFormat; define('FRIENDICA_PLATFORM', 'Friendica'); @@ -642,7 +636,7 @@ function get_temppath() if (($temppath != "") && App::isDirectoryUsable($temppath)) { // We have a temp path and it is usable - return App::getRealPath($temppath); + return BasePath::getRealPath($temppath); } // We don't have a working preconfigured temp path, so we take the system path. @@ -651,7 +645,7 @@ function get_temppath() // Check if it is usable if (($temppath != "") && App::isDirectoryUsable($temppath)) { // Always store the real path, not the path through symlinks - $temppath = App::getRealPath($temppath); + $temppath = BasePath::getRealPath($temppath); // To avoid any interferences with other systems we create our own directory $new_temppath = $temppath . "/" . $a->getHostName(); @@ -743,7 +737,7 @@ function get_itemcachepath() $itemcache = Config::get('system', 'itemcache'); if (($itemcache != "") && App::isDirectoryUsable($itemcache)) { - return App::getRealPath($itemcache); + return BasePath::getRealPath($itemcache); } $temppath = get_temppath(); diff --git a/index.php b/index.php index c2dd31bcf2..11b7879991 100644 --- a/index.php +++ b/index.php @@ -5,7 +5,9 @@ */ use Friendica\App; -use Friendica\Util\LoggerFactory; +use Friendica\Core\Config; +use Friendica\Factory; +use Friendica\Util\BasePath; if (!file_exists(__DIR__ . '/vendor/autoload.php')) { die('Vendor path not found. Please execute "bin/composer.phar --no-dev install" on the command line in the web root.'); @@ -13,10 +15,13 @@ if (!file_exists(__DIR__ . '/vendor/autoload.php')) { require __DIR__ . '/vendor/autoload.php'; -$logger = LoggerFactory::create('index'); +$basedir = BasePath::create(__DIR__); +$configLoader = new Config\ConfigCacheLoader($basedir); +$config = Factory\ConfigFactory::createCache($configLoader); +$logger = Factory\LoggerFactory::create('index', $config); // We assume that the index.php is called by a frontend process // The value is set to "true" by default in App -$a = new App(__DIR__, $logger, false); +$a = new App($config, $logger, false); $a->runFrontend(); diff --git a/mod/admin.php b/mod/admin.php index 7723a51556..8c47877010 100644 --- a/mod/admin.php +++ b/mod/admin.php @@ -15,11 +15,11 @@ use Friendica\Core\Config; use Friendica\Core\L10n; use Friendica\Core\Logger; use Friendica\Core\Renderer; +use Friendica\Core\StorageManager; use Friendica\Core\System; use Friendica\Core\Theme; use Friendica\Core\Update; use Friendica\Core\Worker; -use Friendica\Core\StorageManager; use Friendica\Database\DBA; use Friendica\Database\DBStructure; use Friendica\Model\Contact; @@ -30,6 +30,7 @@ use Friendica\Module; use Friendica\Module\Login; use Friendica\Module\Tos; use Friendica\Util\Arrays; +use Friendica\Util\BasePath; use Friendica\Util\DateTimeFormat; use Friendica\Util\Network; use Friendica\Util\Strings; @@ -1375,7 +1376,7 @@ function admin_page_site_post(App $a) Config::set('system', 'dbclean-expire-unclaimed', $dbclean_unclaimed); if ($itemcache != '') { - $itemcache = App::getRealPath($itemcache); + $itemcache = BasePath::getRealPath($itemcache); } Config::set('system', 'itemcache', $itemcache); @@ -1383,13 +1384,13 @@ function admin_page_site_post(App $a) Config::set('system', 'max_comments', $max_comments); if ($temppath != '') { - $temppath = App::getRealPath($temppath); + $temppath = BasePath::getRealPath($temppath); } Config::set('system', 'temppath', $temppath); if ($basepath != '') { - $basepath = App::getRealPath($basepath); + $basepath = BasePath::getRealPath($basepath); } Config::set('system', 'basepath' , $basepath); diff --git a/mod/friendica.php b/mod/friendica.php index 10a4f93aff..e960f575e5 100644 --- a/mod/friendica.php +++ b/mod/friendica.php @@ -12,7 +12,7 @@ use Friendica\Core\System; use Friendica\Database\DBA; use Friendica\Module\Register; -function friendica_init(App $a) +function friendica_init(App $a, Config\ConfigCache $config) { if (!empty($a->argv[1]) && ($a->argv[1] == "json")) { $register_policies = [ @@ -29,7 +29,7 @@ function friendica_init(App $a) } $sql_extra = ''; - if (Config::getConfigValue('config', 'admin_nickname') !== null) { + if ($config->get('config', 'admin_nickname') !== null) { $sql_extra = sprintf(" AND `nickname` = '%s' ", DBA::escape(Config::get('config', 'admin_nickname'))); } if (!empty(Config::get('config', 'admin_email'))) { @@ -48,7 +48,7 @@ function friendica_init(App $a) Config::load('feature_lock'); $locked_features = []; - $featureLock = Config::getConfigValue('config', 'feature_lock'); + $featureLock = $config->get('config', 'feature_lock'); if (isset($featureLock)) { foreach ($featureLock as $k => $v) { if ($k === 'config_loaded') { diff --git a/src/App.php b/src/App.php index 5ebdbf92b8..caf2026348 100644 --- a/src/App.php +++ b/src/App.php @@ -8,8 +8,12 @@ use Detection\MobileDetect; use DOMDocument; use DOMXPath; use Exception; +use Friendica\Core\Config\ConfigCache; +use Friendica\Core\Config\ConfigCacheLoader; use Friendica\Database\DBA; +use Friendica\Factory\ConfigFactory; use Friendica\Network\HTTPException\InternalServerErrorException; +use Friendica\Util\BasePath; use Psr\Log\LoggerInterface; /** @@ -111,6 +115,31 @@ class App */ private $logger; + /** + * @var ConfigCache The cached config + */ + private $config; + + /** + * Returns the current config cache of this node + * + * @return ConfigCache + */ + public function getConfig() + { + return $this->config; + } + + /** + * The basepath of this app + * + * @return string + */ + public function getBasePath() + { + return $this->basePath; + } + /** * Register a stylesheet file path to be included in the tag of every page. * Inclusion is done in App->initHead(). @@ -123,7 +152,7 @@ class App */ public function registerStylesheet($path) { - $url = str_replace($this->getBasePath() . DIRECTORY_SEPARATOR, '', $path); + $url = str_replace($this->basePath . DIRECTORY_SEPARATOR, '', $path); $this->stylesheets[] = trim($url, '/'); } @@ -140,7 +169,7 @@ class App */ public function registerFooterScript($path) { - $url = str_replace($this->getBasePath() . DIRECTORY_SEPARATOR, '', $path); + $url = str_replace($this->basePath . DIRECTORY_SEPARATOR, '', $path); $this->footerScripts[] = trim($url, '/'); } @@ -153,23 +182,25 @@ class App /** * @brief App constructor. * - * @param string $basePath Path to the app base folder + * @param ConfigCache $config The Cached Config * @param LoggerInterface $logger Logger of this application * @param bool $isBackend Whether it is used for backend or frontend (Default true=backend) * * @throws Exception if the Basepath is not usable */ - public function __construct($basePath, LoggerInterface $logger, $isBackend = true) + public function __construct(ConfigCache $config, LoggerInterface $logger, $isBackend = true) { - $this->logger = $logger; + $this->config = $config; + $this->logger = $logger; + $this->basePath = $this->config->get('system', 'basepath'); - if (!static::isDirectoryUsable($basePath, false)) { - throw new Exception('Basepath ' . $basePath . ' isn\'t usable.'); + if (!BasePath::isDirectoryUsable($this->basePath, false)) { + throw new Exception('Basepath ' . $this->basePath . ' isn\'t usable.'); } + $this->basePath = rtrim($this->basePath, DIRECTORY_SEPARATOR); BaseObject::setApp($this); - $this->basePath = rtrim($basePath, DIRECTORY_SEPARATOR); $this->checkBackend($isBackend); $this->checkFriendicaApp(); @@ -194,7 +225,7 @@ class App $this->callstack['rendering'] = []; $this->callstack['parser'] = []; - $this->mode = new App\Mode($basePath); + $this->mode = new App\Mode($this->basePath); $this->reload(); @@ -225,9 +256,9 @@ class App set_include_path( get_include_path() . PATH_SEPARATOR - . $this->getBasePath() . DIRECTORY_SEPARATOR . 'include' . PATH_SEPARATOR - . $this->getBasePath() . DIRECTORY_SEPARATOR . 'library' . PATH_SEPARATOR - . $this->getBasePath()); + . $this->basePath . DIRECTORY_SEPARATOR . 'include' . PATH_SEPARATOR + . $this->basePath . DIRECTORY_SEPARATOR . 'library' . PATH_SEPARATOR + . $this->basePath); if (!empty($_SERVER['QUERY_STRING']) && strpos($_SERVER['QUERY_STRING'], 'pagename=') === 0) { $this->query_string = substr($_SERVER['QUERY_STRING'], 9); @@ -331,21 +362,32 @@ class App */ public function reload() { - // The order of the following calls is important to ensure proper initialization - $this->loadConfigFiles(); + Core\Config::init($this->config); + Core\PConfig::init($this->config); $this->loadDatabase(); - $this->getMode()->determine($this->getBasePath()); + $this->getMode()->determine($this->basePath); $this->determineURLPath(); - Core\Config::load(); + if ($this->getMode()->has(App\Mode::DBCONFIGAVAILABLE)) { + $adapterType = $this->config->get('system', 'config_adapter'); + $adapter = ConfigFactory::createConfig($adapterType, $this->config); + Core\Config::setAdapter($adapter); + $adapterP = ConfigFactory::createConfig($adapterType, $this->config); + Core\PConfig::setAdapter($adapterP); + Core\Config::load(); + } + + // again because DB-config could change the config + $this->getMode()->determine($this->basePath); if ($this->getMode()->has(App\Mode::DBAVAILABLE)) { Core\Hook::loadHooks(); - - $this->loadAddonConfig(); + $loader = new ConfigCacheLoader($this->basePath); + Core\Hook::callAll('load_config', $loader); + $this->config->loadConfigArray($loader->loadAddonConfig(), true); } $this->loadDefaultTimezone(); @@ -357,139 +399,6 @@ class App Core\Logger::setLogger($this->logger); } - /** - * Load the configuration files - * - * First loads the default value for all the configuration keys, then the legacy configuration files, then the - * expected local.config.php - */ - private function loadConfigFiles() - { - $this->loadConfigFile($this->getBasePath() . '/config/defaults.config.php'); - $this->loadConfigFile($this->getBasePath() . '/config/settings.config.php'); - - // Legacy .htconfig.php support - if (file_exists($this->getBasePath() . '/.htpreconfig.php')) { - $a = $this; - include $this->getBasePath() . '/.htpreconfig.php'; - } - - // Legacy .htconfig.php support - if (file_exists($this->getBasePath() . '/.htconfig.php')) { - $a = $this; - - include $this->getBasePath() . '/.htconfig.php'; - - Core\Config::setConfigValue('database', 'hostname', $db_host); - Core\Config::setConfigValue('database', 'username', $db_user); - Core\Config::setConfigValue('database', 'password', $db_pass); - Core\Config::setConfigValue('database', 'database', $db_data); - $charset = Core\Config::getConfigValue('system', 'db_charset'); - if (isset($charset)) { - Core\Config::setConfigValue('database', 'charset', $charset); - } - - unset($db_host, $db_user, $db_pass, $db_data); - - if (isset($default_timezone)) { - Core\Config::setConfigValue('system', 'default_timezone', $default_timezone); - unset($default_timezone); - } - - if (isset($pidfile)) { - Core\Config::setConfigValue('system', 'pidfile', $pidfile); - unset($pidfile); - } - - if (isset($lang)) { - Core\Config::setConfigValue('system', 'language', $lang); - unset($lang); - } - } - - if (file_exists($this->getBasePath() . '/config/local.config.php')) { - $this->loadConfigFile($this->getBasePath() . '/config/local.config.php', true); - } elseif (file_exists($this->getBasePath() . '/config/local.ini.php')) { - $this->loadINIConfigFile($this->getBasePath() . '/config/local.ini.php', true); - } - } - - /** - * Tries to load the specified legacy configuration file into the App->config array. - * Doesn't overwrite previously set values by default to prevent default config files to supersede DB Config. - * - * @deprecated since version 2018.12 - * @param string $filepath - * @param bool $overwrite Force value overwrite if the config key already exists - * @throws Exception - */ - public function loadINIConfigFile($filepath, $overwrite = false) - { - if (!file_exists($filepath)) { - throw new Exception('Error parsing non-existent INI config file ' . $filepath); - } - - $contents = include($filepath); - - $config = parse_ini_string($contents, true, INI_SCANNER_TYPED); - - if ($config === false) { - throw new Exception('Error parsing INI config file ' . $filepath); - } - - Core\Config::loadConfigArray($config, $overwrite); - } - - /** - * Tries to load the specified configuration file into the App->config array. - * Doesn't overwrite previously set values by default to prevent default config files to supersede DB Config. - * - * The config format is PHP array and the template for configuration files is the following: - * - * [ - * 'key' => 'value', - * ], - * ]; - * - * @param string $filepath - * @param bool $overwrite Force value overwrite if the config key already exists - * @throws Exception - */ - public function loadConfigFile($filepath, $overwrite = false) - { - if (!file_exists($filepath)) { - throw new Exception('Error loading non-existent config file ' . $filepath); - } - - $config = include($filepath); - - if (!is_array($config)) { - throw new Exception('Error loading config file ' . $filepath); - } - - Core\Config::loadConfigArray($config, $overwrite); - } - - /** - * Loads addons configuration files - * - * First loads all activated addons default configuration through the load_config hook, then load the local.config.php - * again to overwrite potential local addon configuration. - */ - private function loadAddonConfig() - { - // Loads addons default config - Core\Hook::callAll('load_config'); - - // Load the local addon config file to overwritten default addon config values - if (file_exists($this->getBasePath() . '/config/addon.config.php')) { - $this->loadConfigFile($this->getBasePath() . '/config/addon.config.php', true); - } elseif (file_exists($this->getBasePath() . '/config/addon.ini.php')) { - $this->loadINIConfigFile($this->getBasePath() . '/config/addon.ini.php', true); - } - } - /** * Loads the default timezone * @@ -499,8 +408,8 @@ class App */ private function loadDefaultTimezone() { - if (Core\Config::getConfigValue('system', 'default_timezone')) { - $this->timezone = Core\Config::getConfigValue('system', 'default_timezone'); + if ($this->config->get('system', 'default_timezone')) { + $this->timezone = $this->config->get('system', 'default_timezone'); } else { global $default_timezone; $this->timezone = !empty($default_timezone) ? $default_timezone : 'UTC'; @@ -526,7 +435,7 @@ class App $relative_script_path = defaults($_SERVER, 'SCRIPT_URL' , $relative_script_path); $relative_script_path = defaults($_SERVER, 'REQUEST_URI' , $relative_script_path); - $this->urlPath = Core\Config::getConfigValue('system', 'urlpath'); + $this->urlPath = $this->config->get('system', 'urlpath'); /* $relative_script_path gives /relative/path/to/friendica/module/parameter * QUERY_STRING gives pagename=module/parameter @@ -554,11 +463,11 @@ class App return; } - $db_host = Core\Config::getConfigValue('database', 'hostname'); - $db_user = Core\Config::getConfigValue('database', 'username'); - $db_pass = Core\Config::getConfigValue('database', 'password'); - $db_data = Core\Config::getConfigValue('database', 'database'); - $charset = Core\Config::getConfigValue('database', 'charset'); + $db_host = $this->config->get('database', 'hostname'); + $db_user = $this->config->get('database', 'username'); + $db_pass = $this->config->get('database', 'password'); + $db_data = $this->config->get('database', 'database'); + $charset = $this->config->get('database', 'charset'); // Use environment variables for mysql if they are set beforehand if (!empty(getenv('MYSQL_HOST')) @@ -581,9 +490,9 @@ class App $stamp1 = microtime(true); - if (DBA::connect($db_host, $db_user, $db_pass, $db_data, $charset)) { + if (DBA::connect($this->config, $db_host, $db_user, $db_pass, $db_data, $charset)) { // Loads DB_UPDATE_VERSION constant - Database\DBStructure::definition(false); + Database\DBStructure::definition($this->basePath, false); } unset($db_host, $db_user, $db_pass, $db_data, $charset); @@ -591,55 +500,6 @@ class App $this->saveTimestamp($stamp1, 'network'); } - /** - * @brief Returns the base filesystem path of the App - * - * It first checks for the internal variable, then for DOCUMENT_ROOT and - * finally for PWD - * - * @return string - * @throws InternalServerErrorException - */ - public function getBasePath() - { - $basepath = $this->basePath; - - if (!$basepath) { - $basepath = Core\Config::get('system', 'basepath'); - } - - if (!$basepath && !empty($_SERVER['DOCUMENT_ROOT'])) { - $basepath = $_SERVER['DOCUMENT_ROOT']; - } - - if (!$basepath && !empty($_SERVER['PWD'])) { - $basepath = $_SERVER['PWD']; - } - - return self::getRealPath($basepath); - } - - /** - * @brief Returns a normalized file path - * - * This is a wrapper for the "realpath" function. - * That function cannot detect the real path when some folders aren't readable. - * Since this could happen with some hosters we need to handle this. - * - * @param string $path The path that is about to be normalized - * @return string normalized path - when possible - */ - public static function getRealPath($path) - { - $normalized = realpath($path); - - if (!is_bool($normalized)) { - return $normalized; - } else { - return $path; - } - } - public function getScheme() { return $this->scheme; @@ -715,8 +575,8 @@ class App $this->urlPath = trim($parsed['path'], '\\/'); } - if (file_exists($this->getBasePath() . '/.htpreconfig.php')) { - include $this->getBasePath() . '/.htpreconfig.php'; + if (file_exists($this->basePath . '/.htpreconfig.php')) { + include $this->basePath . '/.htpreconfig.php'; } if (Core\Config::get('config', 'hostname') != '') { @@ -769,9 +629,9 @@ class App // compose the page title from the sitename and the // current module called if (!$this->module == '') { - $this->page['title'] = Core\Config::getConfigValue('config', 'sitename') . ' (' . $this->module . ')'; + $this->page['title'] = $this->config->get('config', 'sitename') . ' (' . $this->module . ')'; } else { - $this->page['title'] = Core\Config::getConfigValue('config', 'sitename'); + $this->page['title'] = $this->config->get('config', 'sitename'); } if (!empty(Core\Renderer::$theme['stylesheet'])) { @@ -892,7 +752,7 @@ class App */ public function saveTimestamp($timestamp, $value) { - $profiler = Core\Config::getConfigValue('system', 'profiler'); + $profiler = $this->config->get('system', 'profiler'); if (!isset($profiler) || !$profiler) { return; @@ -1132,7 +992,7 @@ class App return; } - $cmdline = Core\Config::getConfigValue('config', 'php_path', 'php') . ' ' . escapeshellarg($command); + $cmdline = $this->config->get('config', 'php_path', 'php') . ' ' . escapeshellarg($command); foreach ($args as $key => $value) { if (!is_null($value) && is_bool($value) && !$value) { @@ -1150,9 +1010,9 @@ class App } if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') { - $resource = proc_open('cmd /c start /b ' . $cmdline, [], $foo, $this->getBasePath()); + $resource = proc_open('cmd /c start /b ' . $cmdline, [], $foo, $this->basePath); } else { - $resource = proc_open($cmdline . ' &', [], $foo, $this->getBasePath()); + $resource = proc_open($cmdline . ' &', [], $foo, $this->basePath); } if (!is_resource($resource)) { Core\Logger::log('We got no resource for command ' . $cmdline, Core\Logger::DEBUG); @@ -1161,61 +1021,6 @@ class App proc_close($resource); } - /** - * @brief Returns the system user that is executing the script - * - * This mostly returns something like "www-data". - * - * @return string system username - */ - private static function getSystemUser() - { - if (!function_exists('posix_getpwuid') || !function_exists('posix_geteuid')) { - return ''; - } - - $processUser = posix_getpwuid(posix_geteuid()); - return $processUser['name']; - } - - /** - * @brief Checks if a given directory is usable for the system - * - * @param $directory - * @param bool $check_writable - * @return boolean the directory is usable - * @throws Exception - */ - public static function isDirectoryUsable($directory, $check_writable = true) - { - if ($directory == '') { - Core\Logger::log('Directory is empty. This shouldn\'t happen.', Core\Logger::DEBUG); - return false; - } - - if (!file_exists($directory)) { - Core\Logger::log('Path "' . $directory . '" does not exist for user ' . self::getSystemUser(), Core\Logger::DEBUG); - return false; - } - - if (is_file($directory)) { - Core\Logger::log('Path "' . $directory . '" is a file for user ' . self::getSystemUser(), Core\Logger::DEBUG); - return false; - } - - if (!is_dir($directory)) { - Core\Logger::log('Path "' . $directory . '" is not a directory for user ' . self::getSystemUser(), Core\Logger::DEBUG); - return false; - } - - if ($check_writable && !is_writable($directory)) { - Core\Logger::log('Path "' . $directory . '" is not writable for user ' . self::getSystemUser(), Core\Logger::DEBUG); - return false; - } - - return true; - } - /** * Generates the site's default sender email address * diff --git a/src/Core/Config.php b/src/Core/Config.php index bec6539e27..c8edcb2928 100644 --- a/src/Core/Config.php +++ b/src/Core/Config.php @@ -8,8 +8,8 @@ */ namespace Friendica\Core; -use Friendica\App; -use Friendica\BaseObject; +use Friendica\Core\Config\IConfigAdapter; +use Friendica\Core\Config\IConfigCache; /** * @brief Arbitrary system configuration storage @@ -18,27 +18,36 @@ use Friendica\BaseObject; * If we ever would decide to return exactly the variable type as entered, * we will have fun with the additional features. :-) */ -class Config extends BaseObject +class Config { - public static $config = []; + /** + * @var IConfigAdapter + */ + private static $adapter; /** - * @var \Friendica\Core\Config\IConfigAdapter + * @var IConfigCache */ - private static $adapter = null; + private static $config; - public static function init() + /** + * Initialize the config with only the cache + * + * @param IConfigCache $config The configuration cache + */ + public static function init($config) { - // Database isn't ready or populated yet - if (!self::getApp()->getMode()->has(App\Mode::DBCONFIGAVAILABLE)) { - return; - } + self::$config = $config; + } - if (self::getConfigValue('system', 'config_adapter') == 'preload') { - self::$adapter = new Config\PreloadConfigAdapter(); - } else { - self::$adapter = new Config\JITConfigAdapter(); - } + /** + * Add the adapter for DB-backend + * + * @param $adapter + */ + public static function setAdapter($adapter) + { + self::$adapter = $adapter; } /** @@ -50,19 +59,13 @@ class Config extends BaseObject * @param string $family The category of the configuration value * * @return void - * @throws \Friendica\Network\HTTPException\InternalServerErrorException */ public static function load($family = "config") { - // Database isn't ready or populated yet - if (!self::getApp()->getMode()->has(App\Mode::DBCONFIGAVAILABLE)) { + if (!isset(self::$adapter)) { return; } - if (empty(self::$adapter)) { - self::init(); - } - self::$adapter->load($family); } @@ -84,17 +87,11 @@ class Config extends BaseObject * @param boolean $refresh optional, If true the config is loaded from the db and not from the cache (default: false) * * @return mixed Stored value or null if it does not exist - * @throws \Friendica\Network\HTTPException\InternalServerErrorException */ public static function get($family, $key, $default_value = null, $refresh = false) { - // Database isn't ready or populated yet, fallback to file config - if (!self::getApp()->getMode()->has(App\Mode::DBCONFIGAVAILABLE)) { - return self::getConfigValue($family, $key, $default_value); - } - - if (empty(self::$adapter)) { - self::init(); + if (!isset(self::$adapter)) { + return self::$config->get($family, $key, $default_value); } return self::$adapter->get($family, $key, $default_value, $refresh); @@ -113,17 +110,12 @@ class Config extends BaseObject * @param mixed $value The value to store * * @return bool Operation success - * @throws \Friendica\Network\HTTPException\InternalServerErrorException */ public static function set($family, $key, $value) { - // Database isn't ready or populated yet - if (!self::getApp()->getMode()->has(App\Mode::DBCONFIGAVAILABLE)) { - return false; - } - - if (empty(self::$adapter)) { - self::init(); + if (!isset(self::$adapter)) { + self::$config->set($family, $key, $value); + return true; } return self::$adapter->set($family, $key, $value); @@ -139,131 +131,13 @@ class Config extends BaseObject * @param string $key The configuration key to delete * * @return mixed - * @throws \Friendica\Network\HTTPException\InternalServerErrorException */ public static function delete($family, $key) { - // Database isn't ready or populated yet - if (!self::getApp()->getMode()->has(App\Mode::DBCONFIGAVAILABLE)) { - return false; - } - - if (empty(self::$adapter)) { - self::init(); + if (!isset(self::$adapter)) { + self::$config->delete($family, $key); } return self::$adapter->delete($family, $key); } - - /** - * Tries to load the specified configuration array into the App->config array. - * Doesn't overwrite previously set values by default to prevent default config files to supersede DB Config. - * - * @param array $config - * @param bool $overwrite Force value overwrite if the config key already exists - */ - public static function loadConfigArray(array $config, $overwrite = false) - { - foreach ($config as $category => $values) { - foreach ($values as $key => $value) { - if ($overwrite) { - self::setConfigValue($category, $key, $value); - } else { - self::setDefaultConfigValue($category, $key, $value); - } - } - } - } - - /** - * @param string $cat Config category - * @param string $k Config key - * @param mixed $default Default value if it isn't set - * - * @return string Returns the value of the Config entry - */ - public static function getConfigValue($cat, $k = null, $default = null) - { - $return = $default; - - if ($cat === 'config') { - if (isset(self::$config[$k])) { - $return = self::$config[$k]; - } - } else { - if (isset(self::$config[$cat][$k])) { - $return = self::$config[$cat][$k]; - } elseif ($k == null && isset(self::$config[$cat])) { - $return = self::$config[$cat]; - } - } - - return $return; - } - - /** - * Sets a default value in the config cache. Ignores already existing keys. - * - * @param string $cat Config category - * @param string $k Config key - * @param mixed $v Default value to set - */ - private static function setDefaultConfigValue($cat, $k, $v) - { - if (!isset(self::$config[$cat][$k])) { - self::setConfigValue($cat, $k, $v); - } - } - - /** - * Sets a value in the config cache. Accepts raw output from the config table - * - * @param string $cat Config category - * @param string $k Config key - * @param mixed $v Value to set - */ - public static function setConfigValue($cat, $k, $v) - { - // Only arrays are serialized in database, so we have to unserialize sparingly - $value = is_string($v) && preg_match("|^a:[0-9]+:{.*}$|s", $v) ? unserialize($v) : $v; - - if ($cat === 'config') { - self::$config[$k] = $value; - } else { - if (!isset(self::$config[$cat])) { - self::$config[$cat] = []; - } - - self::$config[$cat][$k] = $value; - } - } - - /** - * Deletes a value from the config cache - * - * @param string $cat Config category - * @param string $k Config key - */ - public static function deleteConfigValue($cat, $k) - { - if ($cat === 'config') { - if (isset(self::$config[$k])) { - unset(self::$config[$k]); - } - } else { - if (isset(self::$config[$cat][$k])) { - unset(self::$config[$cat][$k]); - } - } - } - - /** - * Returns the whole configuration - * - * @return array The configuration - */ - public static function getAll() - { - return self::$config; - } } diff --git a/src/Core/Config/ConfigCache.php b/src/Core/Config/ConfigCache.php new file mode 100644 index 0000000000..d7318537e9 --- /dev/null +++ b/src/Core/Config/ConfigCache.php @@ -0,0 +1,173 @@ +config = []; + + if (isset($config)) { + $this->loadConfigArray($config, $overwrite); + } + } + + /** + * Tries to load the specified configuration array into the App->config array. + * Doesn't overwrite previously set values by default to prevent default config files to supersede DB Config. + * + * @param array $config + * @param bool $overwrite Force value overwrite if the config key already exists + */ + public function loadConfigArray(array $config, $overwrite = false) + { + foreach ($config as $category => $values) { + foreach ($values as $key => $value) { + if ($overwrite) { + self::set($category, $key, $value); + } else { + self::setDefault($category, $key, $value); + } + } + } + } + + /** + * {@inheritdoc} + */ + public function get($cat, $key = null, $default = null) + { + $return = $default; + + if ($cat === 'config') { + if (isset($this->config[$key])) { + $return = $this->config[$key]; + } + } else { + if (isset($this->config[$cat][$key])) { + $return = $this->config[$cat][$key]; + } elseif ($key == null && isset($this->config[$cat])) { + $return = $this->config[$cat]; + } + } + + return $return; + } + + /** + * Sets a default value in the config cache. Ignores already existing keys. + * + * @param string $cat Config category + * @param string $k Config key + * @param mixed $v Default value to set + */ + private function setDefault($cat, $k, $v) + { + if (!isset($this->config[$cat][$k])) { + self::set($cat, $k, $v); + } + } + + /** + * {@inheritdoc} + */ + public function set($cat, $key, $value) + { + // Only arrays are serialized in database, so we have to unserialize sparingly + $value = is_string($value) && preg_match("|^a:[0-9]+:{.*}$|s", $value) ? unserialize($value) : $value; + + if ($cat === 'config') { + $this->config[$key] = $value; + } else { + if (!isset($this->config[$cat])) { + $this->config[$cat] = []; + } + + $this->config[$cat][$key] = $value; + } + } + + /** + * {@inheritdoc} + */ + public function delete($cat, $key) + { + if ($cat === 'config') { + if (isset($this->config[$key])) { + unset($this->config[$key]); + } + } else { + if (isset($this->config[$cat][$key])) { + unset($this->config[$cat][$key]); + } + } + } + + /** + * {@inheritdoc} + */ + public function getP($uid, $cat, $key = null, $default = null) + { + $return = $default; + + if (isset($this->config[$uid][$cat][$key])) { + $return = $this->config[$uid][$cat][$key]; + } elseif ($key == null && isset($this->config[$uid][$cat])) { + $return = $this->config[$uid][$cat]; + } + + return $return; + } + + /** + * {@inheritdoc} + */ + public function setP($uid, $cat, $key, $value) + { + // Only arrays are serialized in database, so we have to unserialize sparingly + $value = is_string($value) && preg_match("|^a:[0-9]+:{.*}$|s", $value) ? unserialize($value) : $value; + + if (!isset($this->config[$uid]) || !is_array($this->config[$uid])) { + $this->config[$uid] = []; + } + + if (!isset($this->config[$uid][$cat]) || !is_array($this->config[$uid][$cat])) { + $this->config[$uid][$cat] = []; + } + + if ($key === null) { + $this->config[$uid][$cat] = $value; + } else { + $this->config[$uid][$cat][$key] = $value; + } + } + + /** + * {@inheritdoc} + */ + public function deleteP($uid, $cat, $key) + { + if (isset($this->config[$uid][$cat][$key])) { + unset($this->config[$uid][$cat][$key]); + } + } + + /** + * Returns the whole configuration + * + * @return array The configuration + */ + public function getAll() + { + return $this->config; + } +} diff --git a/src/Core/Config/ConfigCacheLoader.php b/src/Core/Config/ConfigCacheLoader.php new file mode 100644 index 0000000000..287be7d522 --- /dev/null +++ b/src/Core/Config/ConfigCacheLoader.php @@ -0,0 +1,159 @@ +baseDir = $baseDir; + $this->configDir = $baseDir . '/config/'; + } + + /** + * Load the configuration files + * + * First loads the default value for all the configuration keys, then the legacy configuration files, then the + * expected local.config.php + */ + public function loadConfigFiles(ConfigCache $config) + { + // Setting at least the basepath we know + $config->set('system', 'basepath', $this->baseDir); + + $config->loadConfigArray($this->loadConfigFile('defaults')); + $config->loadConfigArray($this->loadConfigFile('settings')); + + // Legacy .htconfig.php support + if (file_exists($this->baseDir . '/.htpreconfig.php')) { + $a = $config; + include $this->baseDir . '/.htpreconfig.php'; + } + + // Legacy .htconfig.php support + if (file_exists($this->baseDir . '/.htconfig.php')) { + $a = $config; + + include $this->baseDir . '/.htconfig.php'; + + $config->set('database', 'hostname', $db_host); + $config->set('database', 'username', $db_user); + $config->set('database', 'password', $db_pass); + $config->set('database', 'database', $db_data); + $charset = $config->get('system', 'db_charset'); + if (isset($charset)) { + $config->set('database', 'charset', $charset); + } + + unset($db_host, $db_user, $db_pass, $db_data); + + if (isset($default_timezone)) { + $config->set('system', 'default_timezone', $default_timezone); + unset($default_timezone); + } + + if (isset($pidfile)) { + $config->set('system', 'pidfile', $pidfile); + unset($pidfile); + } + + if (isset($lang)) { + $config->set('system', 'language', $lang); + unset($lang); + } + } + + if (file_exists($this->baseDir . '/config/local.config.php')) { + $config->loadConfigArray($this->loadConfigFile('local'), true); + } elseif (file_exists($this->baseDir . '/config/local.ini.php')) { + $config->loadConfigArray($this->loadINIConfigFile('local'), true); + } + } + + /** + * Tries to load the specified legacy configuration file into the App->config array. + * Doesn't overwrite previously set values by default to prevent default config files to supersede DB Config. + * + * @deprecated since version 2018.12 + * @param string $filename + * + * @return array The configuration + * @throws \Exception + */ + public function loadINIConfigFile($filename) + { + $filepath = $this->configDir . $filename . ".ini.php"; + + if (!file_exists($filepath)) { + throw new \Exception('Error parsing non-existent INI config file ' . $filepath); + } + + $contents = include($filepath); + + $config = parse_ini_string($contents, true, INI_SCANNER_TYPED); + + if ($config === false) { + throw new \Exception('Error parsing INI config file ' . $filepath); + } + + return $config; + } + + /** + * Tries to load the specified configuration file into the App->config array. + * Doesn't overwrite previously set values by default to prevent default config files to supersede DB Config. + * + * The config format is PHP array and the template for configuration files is the following: + * + * [ + * 'key' => 'value', + * ], + * ]; + * + * @param string $filename + * @return array The configuration + * @throws \Exception + */ + public function loadConfigFile($filename) + { + $filepath = $this->configDir . $filename . ".config.php"; + + if (!file_exists($filepath)) { + throw new \Exception('Error loading non-existent config file ' . $filepath); + } + + $config = include($filepath); + + if (!is_array($config)) { + throw new \Exception('Error loading config file ' . $filepath); + } + + return $config; + } + + /** + * Loads addons configuration files + * + * First loads all activated addons default configuration through the load_config hook, then load the local.config.php + * again to overwrite potential local addon configuration. + * + * @return array The config array + * + * @throws \Exception + */ + public function loadAddonConfig() + { + // Load the local addon config file to overwritten default addon config values + if (file_exists($this->configDir . 'addon.config.php')) { + return $this->loadConfigFile('addon'); + } elseif (file_exists($this->configDir . 'addon.ini.php')) { + return $this->loadINIConfigFile('addon'); + } else { + return []; + } + } +} diff --git a/src/Core/Config/IConfigCache.php b/src/Core/Config/IConfigCache.php new file mode 100644 index 0000000000..191333c44a --- /dev/null +++ b/src/Core/Config/IConfigCache.php @@ -0,0 +1,34 @@ +config = $config; + } + public function load($cat = "config") { // We don't preload "system" anymore. @@ -28,7 +40,7 @@ class JITConfigAdapter implements IConfigAdapter while ($config = DBA::fetch($configs)) { $k = $config['k']; - Config::setConfigValue($cat, $k, $config['v']); + $this->config->set($cat, $k, $config['v']); if ($cat !== 'config') { $this->cache[$cat][$k] = $config['v']; @@ -60,18 +72,18 @@ class JITConfigAdapter implements IConfigAdapter $this->cache[$cat][$k] = $value; $this->in_db[$cat][$k] = true; return $value; - } elseif (Config::getConfigValue($cat, $k) !== null) { + } elseif ($this->config->get($cat, $k) !== null) { // Assign the value (mostly) from config/local.config.php file to the cache - $this->cache[$cat][$k] = Config::getConfigValue($cat, $k); + $this->cache[$cat][$k] = $this->config->get($cat, $k); $this->in_db[$cat][$k] = false; - return Config::getConfigValue($cat, $k); - } elseif (Config::getConfigValue('config', $k) !== null) { + return $this->config->get($cat, $k); + } elseif ($this->config->get('config', $k) !== null) { // Assign the value (mostly) from config/local.config.php file to the cache - $this->cache[$k] = Config::getConfigValue('config', $k); + $this->cache[$k] = $this->config->get('config', $k); $this->in_db[$k] = false; - return Config::getConfigValue('config', $k); + return $this->config->get('config', $k); } $this->cache[$cat][$k] = '!!'; @@ -100,7 +112,7 @@ class JITConfigAdapter implements IConfigAdapter return true; } - Config::setConfigValue($cat, $k, $value); + $this->config->set($cat, $k, $value); // Assign the just added value to the cache $this->cache[$cat][$k] = $dbvalue; diff --git a/src/Core/Config/JITPConfigAdapter.php b/src/Core/Config/JITPConfigAdapter.php index ac9a56076c..223cc542dc 100644 --- a/src/Core/Config/JITPConfigAdapter.php +++ b/src/Core/Config/JITPConfigAdapter.php @@ -1,7 +1,6 @@ config = $config; + } + public function load($uid, $cat) { $pconfigs = DBA::select('pconfig', ['v', 'k'], ['cat' => $cat, 'uid' => $uid]); @@ -22,13 +35,13 @@ class JITPConfigAdapter implements IPConfigAdapter while ($pconfig = DBA::fetch($pconfigs)) { $k = $pconfig['k']; - PConfig::setPConfigValue($uid, $cat, $k, $pconfig['v']); + $this->config->setP($uid, $cat, $k, $pconfig['v']); $this->in_db[$uid][$cat][$k] = true; } } else if ($cat != 'config') { // Negative caching - PConfig::setPConfigValue($uid, $cat, null, "!!"); + $this->config->setP($uid, $cat, null, "!!"); } DBA::close($pconfigs); } @@ -37,17 +50,17 @@ class JITPConfigAdapter implements IPConfigAdapter { if (!$refresh) { // Looking if the whole family isn't set - if (PConfig::getPConfigValue($uid, $cat) !== null) { - if (PConfig::getPConfigValue($uid, $cat) === '!!') { + if ($this->config->getP($uid, $cat) !== null) { + if ($this->config->getP($uid, $cat) === '!!') { return $default_value; } } - if (PConfig::getPConfigValue($uid, $cat, $k) !== null) { - if (PConfig::getPConfigValue($uid, $cat, $k) === '!!') { + if ($this->config->getP($uid, $cat, $k) !== null) { + if ($this->config->getP($uid, $cat, $k) === '!!') { return $default_value; } - return PConfig::getPConfigValue($uid, $cat, $k); + return $this->config->getP($uid, $cat, $k); } } @@ -55,13 +68,13 @@ class JITPConfigAdapter implements IPConfigAdapter if (DBA::isResult($pconfig)) { $val = (preg_match("|^a:[0-9]+:{.*}$|s", $pconfig['v']) ? unserialize($pconfig['v']) : $pconfig['v']); - PConfig::setPConfigValue($uid, $cat, $k, $val); + $this->config->setP($uid, $cat, $k, $val); $this->in_db[$uid][$cat][$k] = true; return $val; } else { - PConfig::setPConfigValue($uid, $cat, $k, '!!'); + $this->config->setP($uid, $cat, $k, '!!'); $this->in_db[$uid][$cat][$k] = false; @@ -82,7 +95,7 @@ class JITPConfigAdapter implements IPConfigAdapter return true; } - PConfig::setPConfigValue($uid, $cat, $k, $value); + $this->config->setP($uid, $cat, $k, $value); // manage array value $dbvalue = (is_array($value) ? serialize($value) : $dbvalue); @@ -98,7 +111,7 @@ class JITPConfigAdapter implements IPConfigAdapter public function delete($uid, $cat, $k) { - PConfig::deletePConfigValue($uid, $cat, $k); + $this->config->deleteP($uid, $cat, $k); if (!empty($this->in_db[$uid][$cat][$k])) { unset($this->in_db[$uid][$cat][$k]); diff --git a/src/Core/Config/PreloadConfigAdapter.php b/src/Core/Config/PreloadConfigAdapter.php index dc5c45379f..4461105e14 100644 --- a/src/Core/Config/PreloadConfigAdapter.php +++ b/src/Core/Config/PreloadConfigAdapter.php @@ -3,7 +3,6 @@ namespace Friendica\Core\Config; use Exception; -use Friendica\Core\Config; use Friendica\Database\DBA; /** @@ -17,8 +16,17 @@ class PreloadConfigAdapter implements IConfigAdapter { private $config_loaded = false; - public function __construct() + /** + * @var IConfigCache The config cache of this driver + */ + private $config; + + /** + * @param IConfigCache $config The config cache of this driver + */ + public function __construct($config) { + $this->config = $config; $this->load(); } @@ -30,7 +38,7 @@ class PreloadConfigAdapter implements IConfigAdapter $configs = DBA::select('config', ['cat', 'v', 'k']); while ($config = DBA::fetch($configs)) { - Config::setConfigValue($config['cat'], $config['k'], $config['v']); + $this->config->set($config['cat'], $config['k'], $config['v']); } DBA::close($configs); @@ -42,11 +50,11 @@ class PreloadConfigAdapter implements IConfigAdapter if ($refresh) { $config = DBA::selectFirst('config', ['v'], ['cat' => $cat, 'k' => $k]); if (DBA::isResult($config)) { - Config::setConfigValue($cat, $k, $config['v']); + $this->config->set($cat, $k, $config['v']); } } - $return = Config::getConfigValue($cat, $k, $default_value); + $return = $this->config->get($cat, $k, $default_value); return $return; } @@ -58,11 +66,11 @@ class PreloadConfigAdapter implements IConfigAdapter // The exception are array values. $compare_value = !is_array($value) ? (string)$value : $value; - if (Config::getConfigValue($cat, $k) === $compare_value) { + if ($this->config->get($cat, $k) === $compare_value) { return true; } - Config::setConfigValue($cat, $k, $value); + $this->config->set($cat, $k, $value); // manage array value $dbvalue = is_array($value) ? serialize($value) : $value; @@ -77,7 +85,7 @@ class PreloadConfigAdapter implements IConfigAdapter public function delete($cat, $k) { - Config::deleteConfigValue($cat, $k); + $this->config->delete($cat, $k); $result = DBA::delete('config', ['cat' => $cat, 'k' => $k]); diff --git a/src/Core/Config/PreloadPConfigAdapter.php b/src/Core/Config/PreloadPConfigAdapter.php index 88774f2979..311518bbe9 100644 --- a/src/Core/Config/PreloadPConfigAdapter.php +++ b/src/Core/Config/PreloadPConfigAdapter.php @@ -3,7 +3,6 @@ namespace Friendica\Core\Config; use Exception; -use Friendica\Core\PConfig; use Friendica\Database\DBA; /** @@ -17,8 +16,19 @@ class PreloadPConfigAdapter implements IPConfigAdapter { private $config_loaded = false; - public function __construct($uid) + /** + * The config cache of this adapter + * @var IPConfigCache + */ + private $config; + + /** + * @param int $uid The UID of the current user + * @param IPConfigCache $config The config cache of this adapter + */ + public function __construct($uid, $config) { + $this->config = $config; $this->load($uid, 'config'); } @@ -34,7 +44,7 @@ class PreloadPConfigAdapter implements IPConfigAdapter $pconfigs = DBA::select('pconfig', ['cat', 'v', 'k'], ['uid' => $uid]); while ($pconfig = DBA::fetch($pconfigs)) { - PConfig::setPConfigValue($uid, $pconfig['cat'], $pconfig['k'], $pconfig['v']); + $this->config->setP($uid, $pconfig['cat'], $pconfig['k'], $pconfig['v']); } DBA::close($pconfigs); @@ -50,15 +60,13 @@ class PreloadPConfigAdapter implements IPConfigAdapter if ($refresh) { $config = DBA::selectFirst('pconfig', ['v'], ['uid' => $uid, 'cat' => $cat, 'k' => $k]); if (DBA::isResult($config)) { - PConfig::setPConfigValue($uid, $cat, $k, $config['v']); + $this->config->setP($uid, $cat, $k, $config['v']); } else { - PConfig::deletePConfigValue($uid, $cat, $k); + $this->config->deleteP($uid, $cat, $k); } } - $return = PConfig::getPConfigValue($uid, $cat, $k, $default_value); - - return $return; + return $this->config->getP($uid, $cat, $k, $default_value);; } public function set($uid, $cat, $k, $value) @@ -71,11 +79,11 @@ class PreloadPConfigAdapter implements IPConfigAdapter // The exception are array values. $compare_value = !is_array($value) ? (string)$value : $value; - if (PConfig::getPConfigValue($uid, $cat, $k) === $compare_value) { + if ($this->config->getP($uid, $cat, $k) === $compare_value) { return true; } - PConfig::setPConfigValue($uid, $cat, $k, $value); + $this->config->setP($uid, $cat, $k, $value); // manage array value $dbvalue = is_array($value) ? serialize($value) : $value; @@ -94,7 +102,7 @@ class PreloadPConfigAdapter implements IPConfigAdapter $this->load($uid, $cat); } - PConfig::deletePConfigValue($uid, $cat, $k); + $this->config->deleteP($uid, $cat, $k); $result = DBA::delete('pconfig', ['uid' => $uid, 'cat' => $cat, 'k' => $k]); diff --git a/src/Core/Logger.php b/src/Core/Logger.php index 277a091641..6b8112796f 100644 --- a/src/Core/Logger.php +++ b/src/Core/Logger.php @@ -5,8 +5,8 @@ namespace Friendica\Core; use Friendica\BaseObject; +use Friendica\Factory\LoggerFactory; use Friendica\Network\HTTPException\InternalServerErrorException; -use Friendica\Util\LoggerFactory; use Psr\Log\LoggerInterface; use Psr\Log\LogLevel; diff --git a/src/Core/PConfig.php b/src/Core/PConfig.php index 75403aaebe..1f9f36638d 100644 --- a/src/Core/PConfig.php +++ b/src/Core/PConfig.php @@ -8,8 +8,7 @@ */ namespace Friendica\Core; -use Friendica\App; -use Friendica\BaseObject; +use Friendica\Core\Config\IPConfigCache; /** * @brief Management of user configuration storage @@ -18,29 +17,36 @@ use Friendica\BaseObject; * The PConfig::get() functions return boolean false for keys that are unset, * and this could lead to subtle bugs. */ -class PConfig extends BaseObject +class PConfig { - private static $config; - /** * @var \Friendica\Core\Config\IPConfigAdapter */ - private static $adapter = null; + private static $adapter; - public static function init($uid) + /** + * @var IPConfigCache + */ + private static $config; + + /** + * Initialize the config with only the cache + * + * @param IPConfigCache $config The configuration cache + */ + public static function init($config) { - $a = self::getApp(); + self::$config = $config; + } - // Database isn't ready or populated yet - if (!$a->getMode()->has(App\Mode::DBCONFIGAVAILABLE)) { - return; - } - - if (Config::getConfigValue('system', 'config_adapter') == 'preload') { - self::$adapter = new Config\PreloadPConfigAdapter($uid); - } else { - self::$adapter = new Config\JITPConfigAdapter(); - } + /** + * Add the adapter for DB-backend + * + * @param $adapter + */ + public static function setAdapter($adapter) + { + self::$adapter = $adapter; } /** @@ -57,15 +63,10 @@ class PConfig extends BaseObject */ public static function load($uid, $family) { - // Database isn't ready or populated yet - if (!self::getApp()->getMode()->has(App\Mode::DBCONFIGAVAILABLE)) { + if (!isset(self::$adapter)) { return; } - if (empty(self::$adapter)) { - self::init($uid); - } - self::$adapter->load($uid, $family); } @@ -83,17 +84,11 @@ class PConfig extends BaseObject * @param boolean $refresh optional, If true the config is loaded from the db and not from the cache (default: false) * * @return mixed Stored value or null if it does not exist - * @throws \Friendica\Network\HTTPException\InternalServerErrorException */ public static function get($uid, $family, $key, $default_value = null, $refresh = false) { - // Database isn't ready or populated yet - if (!self::getApp()->getMode()->has(App\Mode::DBCONFIGAVAILABLE)) { - return; - } - - if (empty(self::$adapter)) { - self::init($uid); + if (!isset(self::$adapter)) { + return self::$config->getP($uid, $family, $key, $default_value); } return self::$adapter->get($uid, $family, $key, $default_value, $refresh); @@ -113,17 +108,11 @@ class PConfig extends BaseObject * @param mixed $value The value to store * * @return bool Operation success - * @throws \Friendica\Network\HTTPException\InternalServerErrorException */ public static function set($uid, $family, $key, $value) { - // Database isn't ready or populated yet - if (!self::getApp()->getMode()->has(App\Mode::DBCONFIGAVAILABLE)) { - return false; - } - - if (empty(self::$adapter)) { - self::init($uid); + if (!isset(self::$adapter)) { + return self::$config->setP($uid, $family, $key, $value); } return self::$adapter->set($uid, $family, $key, $value); @@ -144,83 +133,10 @@ class PConfig extends BaseObject */ public static function delete($uid, $family, $key) { - // Database isn't ready or populated yet - if (!self::getApp()->getMode()->has(App\Mode::DBCONFIGAVAILABLE)) { - return false; - } - - if (empty(self::$adapter)) { - self::init($uid); + if (!isset(self::$adapter)) { + return self::$config->deleteP($uid, $family, $key); } return self::$adapter->delete($uid, $family, $key); } - - - /** - * Retrieves a value from the user config cache - * - * @param int $uid User Id - * @param string $cat Config category - * @param string $k Config key - * @param mixed $default Default value if key isn't set - * - * @return string The value of the config entry - */ - public static function getPConfigValue($uid, $cat, $k = null, $default = null) - { - $return = $default; - - if (isset(self::$config[$uid][$cat][$k])) { - $return = self::$config[$uid][$cat][$k]; - } elseif ($k == null && isset(self::$config[$uid][$cat])) { - $return = self::$config[$uid][$cat]; - } - - return $return; - } - - /** - * Sets a value in the user config cache - * - * Accepts raw output from the pconfig table - * - * @param int $uid User Id - * @param string $cat Config category - * @param string $k Config key - * @param mixed $v Value to set - */ - public static function setPConfigValue($uid, $cat, $k, $v) - { - // Only arrays are serialized in database, so we have to unserialize sparingly - $value = is_string($v) && preg_match("|^a:[0-9]+:{.*}$|s", $v) ? unserialize($v) : $v; - - if (!isset(self::$config[$uid]) || !is_array(self::$config[$uid])) { - self::$config[$uid] = []; - } - - if (!isset(self::$config[$uid][$cat]) || !is_array(self::$config[$uid][$cat])) { - self::$config[$uid][$cat] = []; - } - - if ($k === null) { - self::$config[$uid][$cat] = $value; - } else { - self::$config[$uid][$cat][$k] = $value; - } - } - - /** - * Deletes a value from the user config cache - * - * @param int $uid User Id - * @param string $cat Config category - * @param string $k Config key - */ - public static function deletePConfigValue($uid, $cat, $k) - { - if (isset(self::$config[$uid][$cat][$k])) { - unset(self::$config[$uid][$cat][$k]); - } - } } diff --git a/src/Core/System.php b/src/Core/System.php index ba3d03e622..c1d23a9ea1 100644 --- a/src/Core/System.php +++ b/src/Core/System.php @@ -286,6 +286,23 @@ class System extends BaseObject exit(); } + /** + * @brief Returns the system user that is executing the script + * + * This mostly returns something like "www-data". + * + * @return string system username + */ + public static function getUser() + { + if (!function_exists('posix_getpwuid') || !function_exists('posix_geteuid')) { + return ''; + } + + $processUser = posix_getpwuid(posix_geteuid()); + return $processUser['name']; + } + /// @todo Move the following functions from boot.php /* function killme() diff --git a/src/Database/DBA.php b/src/Database/DBA.php index 51b9be967e..62789589ce 100644 --- a/src/Database/DBA.php +++ b/src/Database/DBA.php @@ -2,9 +2,7 @@ namespace Friendica\Database; -// Do not use native get/set/load of Core\Config in this class at risk of infinite loop. -// Please use Core\Config::getConfigVariable() instead. -use Friendica\Core\Config; +use Friendica\Core\Config\ConfigCache; use Friendica\Core\Logger; use Friendica\Core\System; use Friendica\Util\DateTimeFormat; @@ -33,6 +31,10 @@ class DBA public static $connected = false; + /** + * @var ConfigCache + */ + private static $config; private static $server_info = ''; private static $connection; private static $driver; @@ -48,13 +50,14 @@ class DBA private static $db_name = ''; private static $db_charset = ''; - public static function connect($serveraddr, $user, $pass, $db, $charset = null) + public static function connect($config, $serveraddr, $user, $pass, $db, $charset = null) { if (!is_null(self::$connection) && self::connected()) { return true; } // We are storing these values for being able to perform a reconnect + self::$config = $config; self::$db_serveraddr = $serveraddr; self::$db_user = $user; self::$db_pass = $pass; @@ -155,7 +158,7 @@ class DBA public static function reconnect() { self::disconnect(); - $ret = self::connect(self::$db_serveraddr, self::$db_user, self::$db_pass, self::$db_name, self::$db_charset); + $ret = self::connect(self::$config, self::$db_serveraddr, self::$db_user, self::$db_pass, self::$db_name, self::$db_charset); return $ret; } @@ -209,9 +212,8 @@ class DBA * @throws \Exception */ private static function logIndex($query) { - $a = \get_app(); - if (!Config::getConfigValue('system', 'db_log_index')) { + if (!self::$config->get('system', 'db_log_index')) { return; } @@ -230,18 +232,18 @@ class DBA return; } - $watchlist = explode(',', Config::getConfigValue('system', 'db_log_index_watch')); - $blacklist = explode(',', Config::getConfigValue('system', 'db_log_index_blacklist')); + $watchlist = explode(',', self::$config->get('system', 'db_log_index_watch')); + $blacklist = explode(',', self::$config->get('system', 'db_log_index_blacklist')); while ($row = self::fetch($r)) { - if ((intval(Config::getConfigValue('system', 'db_loglimit_index')) > 0)) { + if ((intval(self::$config->get('system', 'db_loglimit_index')) > 0)) { $log = (in_array($row['key'], $watchlist) && - ($row['rows'] >= intval(Config::getConfigValue('system', 'db_loglimit_index')))); + ($row['rows'] >= intval(self::$config->get('system', 'db_loglimit_index')))); } else { $log = false; } - if ((intval(Config::getConfigValue('system', 'db_loglimit_index_high')) > 0) && ($row['rows'] >= intval($Config::getConfigValue('system', 'db_loglimit_index_high')))) { + if ((intval(self::$config->get('system', 'db_loglimit_index_high')) > 0) && ($row['rows'] >= intval($Config::getConfigValue('system', 'db_loglimit_index_high')))) { $log = true; } @@ -251,7 +253,7 @@ class DBA if ($log) { $backtrace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS); - @file_put_contents(Config::getConfigValue('system', 'db_log_index'), DateTimeFormat::utcNow()."\t". + @file_put_contents(self::$config->get('system', 'db_log_index'), DateTimeFormat::utcNow()."\t". $row['key']."\t".$row['rows']."\t".$row['Extra']."\t". basename($backtrace[1]["file"])."\t". $backtrace[1]["line"]."\t".$backtrace[2]["function"]."\t". @@ -421,7 +423,7 @@ class DBA $orig_sql = $sql; - if (Config::getConfigValue('system', 'db_callstack')) { + if (self::$config->get('system', 'db_callstack')) { $sql = "/*".System::callstack()." */ ".$sql; } @@ -582,15 +584,15 @@ class DBA $a->saveTimestamp($stamp1, 'database'); - if (Config::getConfigValue('system', 'db_log')) { + if (self::$config->get('system', 'db_log')) { $stamp2 = microtime(true); $duration = (float)($stamp2 - $stamp1); - if (($duration > Config::getConfigValue('system', 'db_loglimit'))) { + if (($duration > self::$config->get('system', 'db_loglimit'))) { $duration = round($duration, 3); $backtrace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS); - @file_put_contents(Config::getConfigValue('system', 'db_log'), DateTimeFormat::utcNow()."\t".$duration."\t". + @file_put_contents(self::$config->get('system', 'db_log'), DateTimeFormat::utcNow()."\t".$duration."\t". basename($backtrace[1]["file"])."\t". $backtrace[1]["line"]."\t".$backtrace[2]["function"]."\t". substr(self::replaceParameters($sql, $args), 0, 2000)."\n", FILE_APPEND); diff --git a/src/Database/DBStructure.php b/src/Database/DBStructure.php index 7d52e60cae..2724670e7b 100644 --- a/src/Database/DBStructure.php +++ b/src/Database/DBStructure.php @@ -101,12 +101,11 @@ class DBStructure * @return array * @throws Exception */ - public static function definition($with_addons_structure = true) + public static function definition($basepath, $with_addons_structure = true) { if (!self::$definition) { - $a = \Friendica\BaseObject::getApp(); - $filename = $a->getBasePath() . '/config/dbstructure.config.php'; + $filename = $basepath . '/config/dbstructure.config.php'; if (!is_readable($filename)) { throw new Exception('Missing database structure config file config/dbstructure.config.php'); diff --git a/src/Factory/ConfigFactory.php b/src/Factory/ConfigFactory.php new file mode 100644 index 0000000000..1b0b66eec3 --- /dev/null +++ b/src/Factory/ConfigFactory.php @@ -0,0 +1,45 @@ +loadConfigFiles($configCache); + + return $configCache; + } + + /** + * @param string $type The adapter type + * @param Config\IConfigCache $config The config cache of this adapter + * @return Config\IConfigAdapter + */ + public static function createConfig($type, $config) + { + if ($type == 'preload') { + return new Config\PreloadConfigAdapter($config); + } else { + return new Config\JITConfigAdapter($config); + } + } + + /** + * @param string $type The adapter type + * @param int $uid The UID of the current user + * @param Config\IPConfigCache $config The config cache of this adapter + * @return Config\IPConfigAdapter + */ + public static function createPConfig($type, $uid, $config) + { + if ($type == 'preload') { + return new Config\PreloadPConfigAdapter($uid, $config); + } else { + return new Config\JITPConfigAdapter($config); + } + } +} diff --git a/src/Util/LoggerFactory.php b/src/Factory/LoggerFactory.php similarity index 88% rename from src/Util/LoggerFactory.php rename to src/Factory/LoggerFactory.php index 4d3a287165..658d2c9bee 100644 --- a/src/Util/LoggerFactory.php +++ b/src/Factory/LoggerFactory.php @@ -1,7 +1,8 @@ pushProcessor(new Monolog\Processor\PsrLogMessageProcessor()); @@ -31,6 +33,16 @@ class LoggerFactory $logger->pushProcessor(new Monolog\Processor\UidProcessor()); $logger->pushProcessor(new FriendicaIntrospectionProcessor(LogLevel::DEBUG, ['Friendica\\Core\\Logger'])); + if (isset($config)) { + $debugging = $config->get('system', 'debugging'); + $stream = $config->get('system', 'logfile'); + $level = $config->get('system', 'loglevel'); + + if ($debugging) { + static::addStreamHandler($logger, $stream, $level); + } + } + return $logger; } diff --git a/src/LegacyModule.php b/src/LegacyModule.php index a0b23a5419..4fdfc17d9f 100644 --- a/src/LegacyModule.php +++ b/src/LegacyModule.php @@ -68,7 +68,7 @@ class LegacyModule extends BaseModule if (\function_exists($function_name)) { $a = self::getApp(); - return $function_name($a); + return $function_name($a, $a->getConfig()); } else { return parent::{$function_suffix}(); } diff --git a/src/Util/BasePath.php b/src/Util/BasePath.php new file mode 100644 index 0000000000..56b0fa1fe9 --- /dev/null +++ b/src/Util/BasePath.php @@ -0,0 +1,93 @@ + Date: Sun, 3 Feb 2019 22:46:50 +0100 Subject: [PATCH 06/31] 4) Adding Factories to other entrypoints --- bin/auth_ejabberd.php | 11 +++++++--- bin/console.php | 11 +++++++--- bin/daemon.php | 10 ++++++--- bin/worker.php | 15 +++++++++----- mod/admin.php | 4 ++-- src/App.php | 2 +- src/BaseObject.php | 11 +++++++--- src/Core/Console/AutomaticInstallation.php | 2 +- src/Core/Console/DatabaseStructure.php | 8 +++++--- src/Core/Console/PostUpdate.php | 4 ++-- src/Core/Installer.php | 6 ++++-- src/Core/Update.php | 18 ++++++++-------- src/Database/DBA.php | 6 +++--- src/Database/DBStructure.php | 24 ++++++++++++---------- src/Factory/ConfigFactory.php | 7 +++++++ src/Model/Attach.php | 6 +++--- src/Module/Install.php | 2 +- src/Worker/DBUpdate.php | 5 +++-- tests/DatabaseTest.php | 4 +++- tests/include/ApiTest.php | 2 +- 20 files changed, 100 insertions(+), 58 deletions(-) diff --git a/bin/auth_ejabberd.php b/bin/auth_ejabberd.php index a6f30d2019..af728f218c 100755 --- a/bin/auth_ejabberd.php +++ b/bin/auth_ejabberd.php @@ -33,8 +33,10 @@ */ use Friendica\App; +use Friendica\Core\Config; +use Friendica\Factory; +use Friendica\Util\BasePath; use Friendica\Util\ExAuth; -use Friendica\Util\LoggerFactory; if (sizeof($_SERVER["argv"]) == 0) { die(); @@ -52,9 +54,12 @@ chdir($directory); require dirname(__DIR__) . '/vendor/autoload.php'; -$logger = LoggerFactory::create('auth_ejabberd'); +$basedir = BasePath::create(dirname(__DIR__)); +$configLoader = new Config\ConfigCacheLoader($basedir); +$config = Factory\ConfigFactory::createCache($configLoader); +$logger = Factory\LoggerFactory::create('auth_ejabberd', $config); -$a = new App(dirname(__DIR__), $logger); +$a = new App($config, $logger); if ($a->getMode()->isNormal()) { $oAuth = new ExAuth(); diff --git a/bin/console.php b/bin/console.php index 9264e3eee4..e7b1786de7 100755 --- a/bin/console.php +++ b/bin/console.php @@ -3,11 +3,16 @@ require dirname(__DIR__) . '/vendor/autoload.php'; -use Friendica\Util\LoggerFactory; +use Friendica\Core\Config; +use Friendica\Factory; +use Friendica\Util\BasePath; -$logger = LoggerFactory::create('console'); +$basedir = BasePath::create(dirname(__DIR__)); +$configLoader = new Config\ConfigCacheLoader($basedir); +$config = Factory\ConfigFactory::createCache($configLoader); +$logger = Factory\LoggerFactory::create('console', $config); -$a = new Friendica\App(dirname(__DIR__), $logger); +$a = new Friendica\App($config, $logger); \Friendica\BaseObject::setApp($a); (new Friendica\Core\Console($argv))->execute(); diff --git a/bin/daemon.php b/bin/daemon.php index c7b321c11c..7e71571cb3 100755 --- a/bin/daemon.php +++ b/bin/daemon.php @@ -11,7 +11,8 @@ use Friendica\App; use Friendica\Core\Config; use Friendica\Core\Worker; use Friendica\Database\DBA; -use Friendica\Util\LoggerFactory; +use Friendica\Factory; +use Friendica\Util\BasePath; // Get options $shortopts = 'f'; @@ -32,9 +33,12 @@ if (!file_exists("boot.php") && (sizeof($_SERVER["argv"]) != 0)) { require dirname(__DIR__) . '/vendor/autoload.php'; -$logger = LoggerFactory::create('daemon'); +$basedir = BasePath::create(dirname(__DIR__)); +$configLoader = new Config\ConfigCacheLoader($basedir); +$config = Factory\ConfigFactory::createCache($configLoader); +$logger = Factory\LoggerFactory::create('daemon', $config); -$a = new App(dirname(__DIR__), $logger); +$a = new App($config, $logger); if ($a->getMode()->isInstall()) { die("Friendica isn't properly installed yet.\n"); diff --git a/bin/worker.php b/bin/worker.php index a64b6a8330..61fdbed544 100755 --- a/bin/worker.php +++ b/bin/worker.php @@ -4,11 +4,13 @@ * @file bin/worker.php * @brief Starts the background processing */ + use Friendica\App; use Friendica\Core\Config; -use Friendica\Core\Worker; use Friendica\Core\Update; -use Friendica\Util\LoggerFactory; +use Friendica\Core\Worker; +use Friendica\Factory; +use Friendica\Util\BasePath; // Get options $shortopts = 'sn'; @@ -29,12 +31,15 @@ if (!file_exists("boot.php") && (sizeof($_SERVER["argv"]) != 0)) { require dirname(__DIR__) . '/vendor/autoload.php'; -$logger = LoggerFactory::create('worker'); +$basedir = BasePath::create(dirname(__DIR__)); +$configLoader = new Config\ConfigCacheLoader($basedir); +$config = Factory\ConfigFactory::createCache($configLoader); +$logger = Factory\LoggerFactory::create('worker', $config); -$a = new App(dirname(__DIR__), $logger); +$a = new App($config, $logger); // Check the database structure and possibly fixes it -Update::check(true); +Update::check($a->getBasePath(), true); // Quit when in maintenance if (!$a->getMode()->has(App\Mode::MAINTENANCEDISABLED)) { diff --git a/mod/admin.php b/mod/admin.php index 8c47877010..51af866898 100644 --- a/mod/admin.php +++ b/mod/admin.php @@ -916,7 +916,7 @@ function admin_page_summary(App $a) } if (Config::get('system', 'dbupdate', DBStructure::UPDATE_NOT_CHECKED) == DBStructure::UPDATE_NOT_CHECKED) { - DBStructure::update(false, true); + DBStructure::update($a->getBasePath(), false, true); } if (Config::get('system', 'dbupdate') == DBStructure::UPDATE_FAILED) { $showwarning = true; @@ -1725,7 +1725,7 @@ function admin_page_dbsync(App $a) } if (($a->argc > 2) && (intval($a->argv[2]) || ($a->argv[2] === 'check'))) { - $retval = DBStructure::update(false, true); + $retval = DBStructure::update($a->getBasePath(), false, true); if ($retval === '') { $o .= L10n::t("Database structure update %s was successfully applied.", DB_UPDATE_VERSION) . "
"; Config::set('database', 'last_successful_update', DB_UPDATE_VERSION); diff --git a/src/App.php b/src/App.php index caf2026348..79e8428705 100644 --- a/src/App.php +++ b/src/App.php @@ -1288,7 +1288,7 @@ class App $this->module = 'maintenance'; } else { $this->checkURL(); - Core\Update::check(false); + Core\Update::check($this->basePath, false); Core\Addon::loadAddons(); Core\Hook::loadHooks(); } diff --git a/src/BaseObject.php b/src/BaseObject.php index 84ff193823..4deba1ced1 100644 --- a/src/BaseObject.php +++ b/src/BaseObject.php @@ -6,7 +6,9 @@ namespace Friendica; require_once 'boot.php'; -use Friendica\Util\LoggerFactory; +use Friendica\Core\Config; +use Friendica\Factory; +use Friendica\Util\BasePath; /** * Basic object @@ -28,8 +30,11 @@ class BaseObject public static function getApp() { if (empty(self::$app)) { - $logger = $logger = LoggerFactory::create('app'); - self::$app = new App(dirname(__DIR__), $logger); + $basedir = BasePath::create(dirname(__DIR__)); + $configLoader = new Config\ConfigCacheLoader($basedir); + $config = Factory\ConfigFactory::createCache($configLoader); + $logger = Factory\LoggerFactory::create('app', $config); + self::$app = new App($config, $logger); } return self::$app; diff --git a/src/Core/Console/AutomaticInstallation.php b/src/Core/Console/AutomaticInstallation.php index 9a63f56ed4..8c3e5ebbee 100644 --- a/src/Core/Console/AutomaticInstallation.php +++ b/src/Core/Console/AutomaticInstallation.php @@ -158,7 +158,7 @@ HELP; $installer->resetChecks(); - if (!$installer->installDatabase()) { + if (!$installer->installDatabase($a->getBasePath())) { $errorMessage = $this->extractErrors($installer->getChecks()); throw new RuntimeException($errorMessage); } diff --git a/src/Core/Console/DatabaseStructure.php b/src/Core/Console/DatabaseStructure.php index 724feea5e4..1ec108d2e6 100644 --- a/src/Core/Console/DatabaseStructure.php +++ b/src/Core/Console/DatabaseStructure.php @@ -61,17 +61,19 @@ HELP; Core\Config::load(); + $a = get_app(); + switch ($this->getArgument(0)) { case "dryrun": - $output = DBStructure::update(true, false); + $output = DBStructure::update($a->getBasePath(), true, false); break; case "update": $force = $this->getOption(['f', 'force'], false); - $output = Update::run($force, true, false); + $output = Update::run($a->getBasePath(), $force, true, false); break; case "dumpsql": ob_start(); - DBStructure::printStructure(); + DBStructure::printStructure($a->getBasePath()); $output = ob_get_clean(); break; case "toinnodb": diff --git a/src/Core/Console/PostUpdate.php b/src/Core/Console/PostUpdate.php index 17ed231f97..103d0fef7e 100644 --- a/src/Core/Console/PostUpdate.php +++ b/src/Core/Console/PostUpdate.php @@ -2,8 +2,8 @@ namespace Friendica\Core\Console; -use Friendica\Core\L10n; use Friendica\Core\Config; +use Friendica\Core\L10n; use Friendica\Core\Update; /** @@ -56,7 +56,7 @@ HELP; } echo L10n::t('Check for pending update actions.') . "\n"; - Update::run(true, true, false); + Update::run($a->getBasePath(), true, true, false); echo L10n::t('Done.') . "\n"; echo L10n::t('Execute pending post updates.') . "\n"; diff --git a/src/Core/Installer.php b/src/Core/Installer.php index a487aec78b..7e79f29f15 100644 --- a/src/Core/Installer.php +++ b/src/Core/Installer.php @@ -168,12 +168,14 @@ class Installer /*** * Installs the DB-Scheme for Friendica * + * @param string $basePath The base path of this application + * * @return bool true if the installation was successful, otherwise false * @throws Exception */ - public function installDatabase() + public function installDatabase($basePath) { - $result = DBStructure::update(false, true, true); + $result = DBStructure::update($basePath, false, true, true); if ($result) { $txt = L10n::t('You may need to import the file "database.sql" manually using phpmyadmin or mysql.') . EOL; diff --git a/src/Core/Update.php b/src/Core/Update.php index 368f5f55cc..5df0675cda 100644 --- a/src/Core/Update.php +++ b/src/Core/Update.php @@ -14,10 +14,11 @@ class Update /** * @brief Function to check if the Database structure needs an update. * + * @param string $basePath The base path of this application * @param boolean $via_worker boolean Is the check run via the worker? * @throws \Friendica\Network\HTTPException\InternalServerErrorException */ - public static function check($via_worker) + public static function check($basePath, $via_worker) { if (!DBA::connected()) { return; @@ -38,7 +39,7 @@ class Update if ($build < DB_UPDATE_VERSION) { // When we cannot execute the database update via the worker, we will do it directly if (!Worker::add(PRIORITY_CRITICAL, 'DBUpdate') && $via_worker) { - self::run(); + self::run($basePath); } } } @@ -46,14 +47,15 @@ class Update /** * Automatic database updates * - * @param bool $force Force the Update-Check even if the lock is set - * @param bool $verbose Run the Update-Check verbose - * @param bool $sendMail Sends a Mail to the administrator in case of success/failure + * @param string $basePath The base path of this application + * @param bool $force Force the Update-Check even if the lock is set + * @param bool $verbose Run the Update-Check verbose + * @param bool $sendMail Sends a Mail to the administrator in case of success/failure * * @return string Empty string if the update is successful, error messages otherwise * @throws \Friendica\Network\HTTPException\InternalServerErrorException */ - public static function run($force = false, $verbose = false, $sendMail = true) + public static function run($basePath, $force = false, $verbose = false, $sendMail = true) { // In force mode, we release the dbupdate lock first // Necessary in case of an stuck update @@ -91,7 +93,7 @@ class Update } // update the structure in one call - $retval = DBStructure::update($verbose, true); + $retval = DBStructure::update($basePath, $verbose, true); if ($retval) { if ($sendMail) { self::updateFailed( @@ -125,7 +127,7 @@ class Update } } } elseif ($force) { - DBStructure::update($verbose, true); + DBStructure::update($basePath, $verbose, true); } return ''; diff --git a/src/Database/DBA.php b/src/Database/DBA.php index 62789589ce..dc3c62abea 100644 --- a/src/Database/DBA.php +++ b/src/Database/DBA.php @@ -2,7 +2,7 @@ namespace Friendica\Database; -use Friendica\Core\Config\ConfigCache; +use Friendica\Core\Config\IConfigCache; use Friendica\Core\Logger; use Friendica\Core\System; use Friendica\Util\DateTimeFormat; @@ -32,7 +32,7 @@ class DBA public static $connected = false; /** - * @var ConfigCache + * @var IConfigCache */ private static $config; private static $server_info = ''; @@ -1031,7 +1031,7 @@ class DBA * This process must only be started once, since the value is cached. */ private static function buildRelationData() { - $definition = DBStructure::definition(); + $definition = DBStructure::definition(self::$config->get('system', 'basepath')); foreach ($definition AS $table => $structure) { foreach ($structure['fields'] AS $field => $field_struct) { diff --git a/src/Database/DBStructure.php b/src/Database/DBStructure.php index 2724670e7b..75a5c86241 100644 --- a/src/Database/DBStructure.php +++ b/src/Database/DBStructure.php @@ -74,9 +74,9 @@ class DBStructure return L10n::t('Errors encountered performing database changes: ') . $message . EOL; } - public static function printStructure() + public static function printStructure($basePath) { - $database = self::definition(false); + $database = self::definition($basePath, false); echo "-- ------------------------------------------\n"; echo "-- " . FRIENDICA_PLATFORM . " " . FRIENDICA_VERSION . " (" . FRIENDICA_CODENAME, ")\n"; @@ -98,14 +98,15 @@ class DBStructure * * @see config/dbstructure.config.php * @param boolean $with_addons_structure Whether to tack on addons additional tables + * @param string $basePath The base path of this application * @return array * @throws Exception */ - public static function definition($basepath, $with_addons_structure = true) + public static function definition($basePath, $with_addons_structure = true) { if (!self::$definition) { - $filename = $basepath . '/config/dbstructure.config.php'; + $filename = $basePath . '/config/dbstructure.config.php'; if (!is_readable($filename)) { throw new Exception('Missing database structure config file config/dbstructure.config.php'); @@ -246,15 +247,16 @@ class DBStructure /** * Updates DB structure and returns eventual errors messages * - * @param bool $verbose - * @param bool $action Whether to actually apply the update - * @param bool $install Is this the initial update during the installation? - * @param array $tables An array of the database tables - * @param array $definition An array of the definition tables + * @param string $basePath The base path of this application + * @param bool $verbose + * @param bool $action Whether to actually apply the update + * @param bool $install Is this the initial update during the installation? + * @param array $tables An array of the database tables + * @param array $definition An array of the definition tables * @return string Empty string if the update is successful, error messages otherwise * @throws Exception */ - public static function update($verbose, $action, $install = false, array $tables = null, array $definition = null) + public static function update($basePath, $verbose, $action, $install = false, array $tables = null, array $definition = null) { if ($action && !$install) { Config::set('system', 'maintenance', 1); @@ -283,7 +285,7 @@ class DBStructure // Get the definition if (is_null($definition)) { - $definition = self::definition(); + $definition = self::definition($basePath); } // MySQL >= 5.7.4 doesn't support the IGNORE keyword in ALTER TABLE statements diff --git a/src/Factory/ConfigFactory.php b/src/Factory/ConfigFactory.php index 1b0b66eec3..4ab20d1d56 100644 --- a/src/Factory/ConfigFactory.php +++ b/src/Factory/ConfigFactory.php @@ -6,6 +6,11 @@ use Friendica\Core\Config; class ConfigFactory { + /** + * @param Config\ConfigCacheLoader $loader The Config Cache loader (INI/config/.htconfig) + * + * @return Config\ConfigCache + */ public static function createCache(Config\ConfigCacheLoader $loader) { $configCache = new Config\ConfigCache(); @@ -17,6 +22,7 @@ class ConfigFactory /** * @param string $type The adapter type * @param Config\IConfigCache $config The config cache of this adapter + * * @return Config\IConfigAdapter */ public static function createConfig($type, $config) @@ -32,6 +38,7 @@ class ConfigFactory * @param string $type The adapter type * @param int $uid The UID of the current user * @param Config\IPConfigCache $config The config cache of this adapter + * * @return Config\IPConfigAdapter */ public static function createPConfig($type, $uid, $config) diff --git a/src/Model/Attach.php b/src/Model/Attach.php index 7efb56f95a..d65e67fe3e 100644 --- a/src/Model/Attach.php +++ b/src/Model/Attach.php @@ -7,15 +7,15 @@ namespace Friendica\Model; use Friendica\BaseObject; -use Friendica\Core\System; use Friendica\Core\StorageManager; +use Friendica\Core\System; use Friendica\Database\DBA; use Friendica\Database\DBStructure; use Friendica\Model\Storage\IStorage; use Friendica\Object\Image; -use Friendica\Util\Security; use Friendica\Util\DateTimeFormat; use Friendica\Util\Mimetype; +use Friendica\Util\Security; /** * Class to handle attach dabatase table @@ -31,7 +31,7 @@ class Attach extends BaseObject */ private static function getFields() { - $allfields = DBStructure::definition(false); + $allfields = DBStructure::definition(self::getApp()->getBasePath(), false); $fields = array_keys($allfields['attach']['fields']); array_splice($fields, array_search('data', $fields), 1); return $fields; diff --git a/src/Module/Install.php b/src/Module/Install.php index d1a35c1518..327e59422c 100644 --- a/src/Module/Install.php +++ b/src/Module/Install.php @@ -103,7 +103,7 @@ class Install extends BaseModule return; } - self::$installer->installDatabase(); + self::$installer->installDatabase($a->getBasePath()); break; } diff --git a/src/Worker/DBUpdate.php b/src/Worker/DBUpdate.php index 48c7e7ce6a..05bace1467 100644 --- a/src/Worker/DBUpdate.php +++ b/src/Worker/DBUpdate.php @@ -5,12 +5,13 @@ */ namespace Friendica\Worker; +use Friendica\BaseObject; use Friendica\Core\Update; -class DBUpdate +class DBUpdate extends BaseObject { public static function execute() { - Update::run(); + Update::run(self::getApp()->getBasePath()); } } diff --git a/tests/DatabaseTest.php b/tests/DatabaseTest.php index 2cb76dcad9..69ee750dbc 100644 --- a/tests/DatabaseTest.php +++ b/tests/DatabaseTest.php @@ -36,7 +36,9 @@ abstract class DatabaseTest extends MockedTest $this->markTestSkipped('Please set the MYSQL_* environment variables to your test database credentials.'); } - DBA::connect(getenv('MYSQL_HOST'), + DBA::connect( + __DIR__, + getenv('MYSQL_HOST'), getenv('MYSQL_USERNAME'), getenv('MYSQL_PASSWORD'), getenv('MYSQL_DATABASE')); diff --git a/tests/include/ApiTest.php b/tests/include/ApiTest.php index cf7571073a..9cf3e2ea5d 100644 --- a/tests/include/ApiTest.php +++ b/tests/include/ApiTest.php @@ -10,8 +10,8 @@ use Friendica\Core\Config; use Friendica\Core\PConfig; use Friendica\Core\Protocol; use Friendica\Core\System; +use Friendica\Factory\LoggerFactory; use Friendica\Network\HTTPException; -use Friendica\Util\LoggerFactory; use Monolog\Handler\TestHandler; require_once __DIR__ . '/../../include/api.php'; From 0f5a50b46b0433cc2f48321d8642da074552af38 Mon Sep 17 00:00:00 2001 From: Philipp Holzer Date: Sun, 3 Feb 2019 22:53:39 +0100 Subject: [PATCH 07/31] Bugfixing tests --- src/Database/DBA.php | 2 +- tests/DatabaseTest.php | 9 ++++++++- 2 files changed, 9 insertions(+), 2 deletions(-) diff --git a/src/Database/DBA.php b/src/Database/DBA.php index dc3c62abea..eaeeb9cbdd 100644 --- a/src/Database/DBA.php +++ b/src/Database/DBA.php @@ -423,7 +423,7 @@ class DBA $orig_sql = $sql; - if (self::$config->get('system', 'db_callstack')) { + if (self::$config->get('system', 'db_callstack') !== null) { $sql = "/*".System::callstack()." */ ".$sql; } diff --git a/tests/DatabaseTest.php b/tests/DatabaseTest.php index 69ee750dbc..79af5b5468 100644 --- a/tests/DatabaseTest.php +++ b/tests/DatabaseTest.php @@ -5,7 +5,10 @@ namespace Friendica\Test; +use Friendica\Core\Config; use Friendica\Database\DBA; +use Friendica\Factory; +use Friendica\Util\BasePath; use PHPUnit\DbUnit\DataSet\YamlDataSet; use PHPUnit\DbUnit\TestCaseTrait; use PHPUnit_Extensions_Database_DB_IDatabaseConnection; @@ -36,8 +39,12 @@ abstract class DatabaseTest extends MockedTest $this->markTestSkipped('Please set the MYSQL_* environment variables to your test database credentials.'); } + $basedir = BasePath::create(dirname(__DIR__)); + $configLoader = new Config\ConfigCacheLoader($basedir); + $config = Factory\ConfigFactory::createCache($configLoader); + DBA::connect( - __DIR__, + $config, getenv('MYSQL_HOST'), getenv('MYSQL_USERNAME'), getenv('MYSQL_PASSWORD'), From 8b70ae6d46b9a62e052039181dd1dfe5229e0225 Mon Sep 17 00:00:00 2001 From: Philipp Holzer Date: Sun, 3 Feb 2019 22:55:13 +0100 Subject: [PATCH 08/31] Bugfixing tests --- boot.php | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/boot.php b/boot.php index 4be12c6a2f..d812724c7b 100644 --- a/boot.php +++ b/boot.php @@ -634,7 +634,7 @@ function get_temppath() $temppath = Config::get("system", "temppath"); - if (($temppath != "") && App::isDirectoryUsable($temppath)) { + if (($temppath != "") && BasePath::isDirectoryUsable($temppath)) { // We have a temp path and it is usable return BasePath::getRealPath($temppath); } @@ -643,7 +643,7 @@ function get_temppath() $temppath = sys_get_temp_dir(); // Check if it is usable - if (($temppath != "") && App::isDirectoryUsable($temppath)) { + if (($temppath != "") && BasePath::isDirectoryUsable($temppath)) { // Always store the real path, not the path through symlinks $temppath = BasePath::getRealPath($temppath); @@ -654,7 +654,7 @@ function get_temppath() mkdir($new_temppath); } - if (App::isDirectoryUsable($new_temppath)) { + if (BasePath::isDirectoryUsable($new_temppath)) { // The new path is usable, we are happy Config::set("system", "temppath", $new_temppath); return $new_temppath; @@ -736,7 +736,7 @@ function get_itemcachepath() } $itemcache = Config::get('system', 'itemcache'); - if (($itemcache != "") && App::isDirectoryUsable($itemcache)) { + if (($itemcache != "") && BasePath::isDirectoryUsable($itemcache)) { return BasePath::getRealPath($itemcache); } @@ -748,7 +748,7 @@ function get_itemcachepath() mkdir($itemcache); } - if (App::isDirectoryUsable($itemcache)) { + if (BasePath::isDirectoryUsable($itemcache)) { Config::set("system", "itemcache", $itemcache); return $itemcache; } @@ -764,7 +764,7 @@ function get_itemcachepath() function get_spoolpath() { $spoolpath = Config::get('system', 'spoolpath'); - if (($spoolpath != "") && App::isDirectoryUsable($spoolpath)) { + if (($spoolpath != "") && BasePath::isDirectoryUsable($spoolpath)) { // We have a spool path and it is usable return $spoolpath; } @@ -779,7 +779,7 @@ function get_spoolpath() mkdir($spoolpath); } - if (App::isDirectoryUsable($spoolpath)) { + if (BasePath::isDirectoryUsable($spoolpath)) { // The new path is usable, we are happy Config::set("system", "spoolpath", $spoolpath); return $spoolpath; From f3da5b3a2f98883e4a06c345dfe2880394f7d21d Mon Sep 17 00:00:00 2001 From: Philipp Holzer Date: Sun, 3 Feb 2019 23:22:05 +0100 Subject: [PATCH 09/31] Bugfixing PConfig --- src/App.php | 2 +- src/Core/Config/ConfigCache.php | 2 +- src/Core/Config/PreloadPConfigAdapter.php | 8 +++++--- src/Factory/ConfigFactory.php | 6 +++--- 4 files changed, 10 insertions(+), 8 deletions(-) diff --git a/src/App.php b/src/App.php index 79e8428705..5d557738da 100644 --- a/src/App.php +++ b/src/App.php @@ -375,7 +375,7 @@ class App $adapterType = $this->config->get('system', 'config_adapter'); $adapter = ConfigFactory::createConfig($adapterType, $this->config); Core\Config::setAdapter($adapter); - $adapterP = ConfigFactory::createConfig($adapterType, $this->config); + $adapterP = ConfigFactory::createPConfig($adapterType, $this->config); Core\PConfig::setAdapter($adapterP); Core\Config::load(); } diff --git a/src/Core/Config/ConfigCache.php b/src/Core/Config/ConfigCache.php index d7318537e9..b50ba3e004 100644 --- a/src/Core/Config/ConfigCache.php +++ b/src/Core/Config/ConfigCache.php @@ -121,7 +121,7 @@ class ConfigCache implements IConfigCache, IPConfigCache if (isset($this->config[$uid][$cat][$key])) { $return = $this->config[$uid][$cat][$key]; - } elseif ($key == null && isset($this->config[$uid][$cat])) { + } elseif ($key === null && isset($this->config[$uid][$cat])) { $return = $this->config[$uid][$cat]; } diff --git a/src/Core/Config/PreloadPConfigAdapter.php b/src/Core/Config/PreloadPConfigAdapter.php index 311518bbe9..ed18bdf2e7 100644 --- a/src/Core/Config/PreloadPConfigAdapter.php +++ b/src/Core/Config/PreloadPConfigAdapter.php @@ -23,13 +23,15 @@ class PreloadPConfigAdapter implements IPConfigAdapter private $config; /** - * @param int $uid The UID of the current user * @param IPConfigCache $config The config cache of this adapter + * @param int $uid The UID of the current user */ - public function __construct($uid, $config) + public function __construct($config, $uid = null) { $this->config = $config; - $this->load($uid, 'config'); + if (isset($uid)) { + $this->load($uid, 'config'); + } } public function load($uid, $family) diff --git a/src/Factory/ConfigFactory.php b/src/Factory/ConfigFactory.php index 4ab20d1d56..46d55b30c3 100644 --- a/src/Factory/ConfigFactory.php +++ b/src/Factory/ConfigFactory.php @@ -36,15 +36,15 @@ class ConfigFactory /** * @param string $type The adapter type - * @param int $uid The UID of the current user * @param Config\IPConfigCache $config The config cache of this adapter + * @param int $uid The UID of the current user * * @return Config\IPConfigAdapter */ - public static function createPConfig($type, $uid, $config) + public static function createPConfig($type, $config, $uid = null) { if ($type == 'preload') { - return new Config\PreloadPConfigAdapter($uid, $config); + return new Config\PreloadPConfigAdapter($config, $uid); } else { return new Config\JITPConfigAdapter($config); } From bc73d4bd2bbbb7c045b063c25c136f00480179c0 Mon Sep 17 00:00:00 2001 From: Philipp Holzer Date: Sun, 3 Feb 2019 23:39:30 +0100 Subject: [PATCH 10/31] Adding descriptions --- src/Core/Config.php | 11 ++++------- src/Core/Config/ConfigCache.php | 14 ++++++++++++-- src/Core/Config/ConfigCacheLoader.php | 16 +++++++++++++++- src/Core/Config/IConfigCache.php | 3 +++ src/Core/Config/IPConfigCache.php | 3 +++ src/Core/PConfig.php | 12 ++++-------- 6 files changed, 41 insertions(+), 18 deletions(-) diff --git a/src/Core/Config.php b/src/Core/Config.php index c8edcb2928..0db8f0b882 100644 --- a/src/Core/Config.php +++ b/src/Core/Config.php @@ -8,9 +8,6 @@ */ namespace Friendica\Core; -use Friendica\Core\Config\IConfigAdapter; -use Friendica\Core\Config\IConfigCache; - /** * @brief Arbitrary system configuration storage * @@ -21,19 +18,19 @@ use Friendica\Core\Config\IConfigCache; class Config { /** - * @var IConfigAdapter + * @var Config\IConfigAdapter */ private static $adapter; /** - * @var IConfigCache + * @var Config\IConfigCache */ private static $config; /** * Initialize the config with only the cache * - * @param IConfigCache $config The configuration cache + * @param Config\IConfigCache $config The configuration cache */ public static function init($config) { @@ -43,7 +40,7 @@ class Config /** * Add the adapter for DB-backend * - * @param $adapter + * @param Config\IConfigAdapter $adapter */ public static function setAdapter($adapter) { diff --git a/src/Core/Config/ConfigCache.php b/src/Core/Config/ConfigCache.php index b50ba3e004..355b1df2f5 100644 --- a/src/Core/Config/ConfigCache.php +++ b/src/Core/Config/ConfigCache.php @@ -2,6 +2,13 @@ namespace Friendica\Core\Config; +/** + * The Friendica config cache for the application + * Initial, all *.config.php files are loaded into this cache with the + * ConfigCacheLoader ( @see ConfigCacheLoader ) + * + * Is used for further caching operations too (depending on the ConfigAdapter ) + */ class ConfigCache implements IConfigCache, IPConfigCache { /** @@ -12,12 +19,15 @@ class ConfigCache implements IConfigCache, IPConfigCache */ public $config; - public function __construct($config = [], $overwrite = false) + /** + * @param array $config A initial config array + */ + public function __construct($config = []) { $this->config = []; if (isset($config)) { - $this->loadConfigArray($config, $overwrite); + $this->loadConfigArray($config, true); } } diff --git a/src/Core/Config/ConfigCacheLoader.php b/src/Core/Config/ConfigCacheLoader.php index 287be7d522..a23e1e848a 100644 --- a/src/Core/Config/ConfigCacheLoader.php +++ b/src/Core/Config/ConfigCacheLoader.php @@ -2,15 +2,29 @@ namespace Friendica\Core\Config; +/** + * The ConfigCacheLoader loads config-files and stores them in a ConfigCache ( @see ConfigCache ) + * + * It is capable of loading the following config files: + * - *.config.php (current) + * - *.ini.php (deprecated) + * - *.htconfig.php (deprecated) + */ class ConfigCacheLoader { + /** + * The Sub directory of the config-files + * @var string + */ + const SUBDIRECTORY = '/config/'; + private $baseDir; private $configDir; public function __construct($baseDir) { $this->baseDir = $baseDir; - $this->configDir = $baseDir . '/config/'; + $this->configDir = $baseDir . self::SUBDIRECTORY; } /** diff --git a/src/Core/Config/IConfigCache.php b/src/Core/Config/IConfigCache.php index 191333c44a..8266cc2dd4 100644 --- a/src/Core/Config/IConfigCache.php +++ b/src/Core/Config/IConfigCache.php @@ -2,6 +2,9 @@ namespace Friendica\Core\Config; +/** + * The interface for a system-wide ConfigCache + */ interface IConfigCache { /** diff --git a/src/Core/Config/IPConfigCache.php b/src/Core/Config/IPConfigCache.php index a17e5a03be..6a57dafa89 100644 --- a/src/Core/Config/IPConfigCache.php +++ b/src/Core/Config/IPConfigCache.php @@ -2,6 +2,9 @@ namespace Friendica\Core\Config; +/** + * The interface for a user-specific config cache + */ interface IPConfigCache { /** diff --git a/src/Core/PConfig.php b/src/Core/PConfig.php index 1f9f36638d..8782a20d23 100644 --- a/src/Core/PConfig.php +++ b/src/Core/PConfig.php @@ -8,8 +8,6 @@ */ namespace Friendica\Core; -use Friendica\Core\Config\IPConfigCache; - /** * @brief Management of user configuration storage * Note: @@ -20,19 +18,19 @@ use Friendica\Core\Config\IPConfigCache; class PConfig { /** - * @var \Friendica\Core\Config\IPConfigAdapter + * @var Config\IPConfigAdapter */ private static $adapter; /** - * @var IPConfigCache + * @var Config\IPConfigCache */ private static $config; /** * Initialize the config with only the cache * - * @param IPConfigCache $config The configuration cache + * @param Config\IPConfigCache $config The configuration cache */ public static function init($config) { @@ -42,7 +40,7 @@ class PConfig /** * Add the adapter for DB-backend * - * @param $adapter + * @param Config\IPConfigAdapter $adapter */ public static function setAdapter($adapter) { @@ -59,7 +57,6 @@ class PConfig * @param string $family The category of the configuration value * * @return void - * @throws \Friendica\Network\HTTPException\InternalServerErrorException */ public static function load($uid, $family) { @@ -129,7 +126,6 @@ class PConfig * @param string $key The configuration key to delete * * @return mixed - * @throws \Friendica\Network\HTTPException\InternalServerErrorException */ public static function delete($uid, $family, $key) { From 90e88d6c35fdce069bf4c44774afab88a0bee208 Mon Sep 17 00:00:00 2001 From: Philipp Holzer Date: Mon, 4 Feb 2019 00:04:16 +0100 Subject: [PATCH 11/31] Bugfixing AutomaticInstallation test --- src/Core/Console/AutomaticInstallation.php | 8 +++---- src/Core/Console/Config.php | 6 ++--- src/Core/Console/Typo.php | 4 +++- tests/Util/AppMockTrait.php | 24 ++++++++++++------- tests/src/BaseObjectTest.php | 3 ++- tests/src/Core/Cache/CacheTest.php | 3 ++- .../AutomaticInstallationConsoleTest.php | 8 +++---- tests/src/Core/Console/ConsoleTest.php | 3 ++- tests/src/Core/Lock/LockTest.php | 3 ++- 9 files changed, 37 insertions(+), 25 deletions(-) diff --git a/src/Core/Console/AutomaticInstallation.php b/src/Core/Console/AutomaticInstallation.php index 8c3e5ebbee..da078545e3 100644 --- a/src/Core/Console/AutomaticInstallation.php +++ b/src/Core/Console/AutomaticInstallation.php @@ -100,10 +100,10 @@ HELP; } } - $db_host = Config::getConfigValue('database', 'hostname'); - $db_user = Config::getConfigValue('database', 'username'); - $db_pass = Config::getConfigValue('database', 'password'); - $db_data = Config::getConfigValue('database', 'database'); + $db_host = $a->getConfig()->get('database', 'hostname'); + $db_user = $a->getConfig()->get('database', 'username'); + $db_pass = $a->getConfig()->get('database', 'password'); + $db_data = $a->getConfig()->get('database', 'database'); } else { // Creating config file $this->out("Creating config file...\n"); diff --git a/src/Core/Console/Config.php b/src/Core/Console/Config.php index 8a0e0f88cf..c72e26906f 100644 --- a/src/Core/Console/Config.php +++ b/src/Core/Console/Config.php @@ -124,9 +124,9 @@ HELP; $cat = $this->getArgument(0); Core\Config::load($cat); - if (Core\Config::getConfigValue($cat) !== null) { + if ($a->getConfig()->get($cat) !== null) { $this->out("[{$cat}]"); - $catVal = Core\Config::getConfigValue($cat); + $catVal = $a->getConfig()->get($cat); foreach ($catVal as $key => $value) { if (is_array($value)) { foreach ($value as $k => $v) { @@ -148,7 +148,7 @@ HELP; $this->out('Warning: The JIT (Just In Time) Config adapter doesn\'t support loading the entire configuration, showing file config only'); } - $config = Core\Config::getAll(); + $config = $a->getConfig()->getAll(); foreach ($config as $cat => $section) { if (is_array($section)) { foreach ($section as $key => $value) { diff --git a/src/Core/Console/Typo.php b/src/Core/Console/Typo.php index 3f9dce84e0..32ba6ded35 100644 --- a/src/Core/Console/Typo.php +++ b/src/Core/Console/Typo.php @@ -2,6 +2,8 @@ namespace Friendica\Core\Console; +use Friendica\BaseObject; + /** * Tired of chasing typos and finding them after a commit. * Run this and quickly see if we've got any parse errors in our application files. @@ -41,7 +43,7 @@ HELP; throw new \Asika\SimpleConsole\CommandArgsException('Too many arguments'); } - $php_path = \Friendica\Core\Config::getConfigValue('config', 'php_path', 'php'); + $php_path = BaseObject::getApp()->getConfig()->get('config', 'php_path', 'php'); if ($this->getOption('v')) { $this->out('Directory: src'); diff --git a/tests/Util/AppMockTrait.php b/tests/Util/AppMockTrait.php index c679321844..290191cba1 100644 --- a/tests/Util/AppMockTrait.php +++ b/tests/Util/AppMockTrait.php @@ -4,6 +4,7 @@ namespace Friendica\Test\Util; use Friendica\App; use Friendica\BaseObject; +use Friendica\Core\Config\ConfigCache; use Friendica\Render\FriendicaSmartyEngine; use Mockery\MockInterface; use org\bovigo\vfs\vfsStreamDirectory; @@ -24,8 +25,9 @@ trait AppMockTrait * Mock the App * * @param vfsStreamDirectory $root The root directory + * @param MockInterface|ConfigCache $config The config cache */ - public function mockApp($root) + public function mockApp($root, $config) { $this->mockConfigGet('system', 'theme', 'testtheme'); @@ -35,22 +37,26 @@ trait AppMockTrait ->shouldReceive('getBasePath') ->andReturn($root->url()); - $this->app - ->shouldReceive('getConfigValue') + $config + ->shouldReceive('get') ->with('database', 'hostname') ->andReturn(getenv('MYSQL_HOST')); - $this->app - ->shouldReceive('getConfigValue') + $config + ->shouldReceive('get') ->with('database', 'username') ->andReturn(getenv('MYSQL_USERNAME')); - $this->app - ->shouldReceive('getConfigValue') + $config + ->shouldReceive('get') ->with('database', 'password') ->andReturn(getenv('MYSQL_PASSWORD')); - $this->app - ->shouldReceive('getConfigValue') + $config + ->shouldReceive('get') ->with('database', 'database') ->andReturn(getenv('MYSQL_DATABASE')); + $this->app + ->shouldReceive('getConfig') + ->andReturn($config); + $this->app ->shouldReceive('getTemplateEngine') ->andReturn(new FriendicaSmartyEngine()); diff --git a/tests/src/BaseObjectTest.php b/tests/src/BaseObjectTest.php index 2b10556af6..2dbf5580f6 100644 --- a/tests/src/BaseObjectTest.php +++ b/tests/src/BaseObjectTest.php @@ -32,7 +32,8 @@ class BaseObjectTest extends TestCase protected function setUp() { $this->setUpVfsDir(); - $this->mockApp($this->root); + $configMock = \Mockery::mock('Friendica\Core\Config\ConfigCache'); + $this->mockApp($this->root, $configMock); $this->baseObject = new BaseObject(); } diff --git a/tests/src/Core/Cache/CacheTest.php b/tests/src/Core/Cache/CacheTest.php index b9a22ee9ca..d0b357bf46 100644 --- a/tests/src/Core/Cache/CacheTest.php +++ b/tests/src/Core/Cache/CacheTest.php @@ -69,7 +69,8 @@ abstract class CacheTest extends MockedTest protected function setUp() { $this->setUpVfsDir(); - $this->mockApp($this->root); + $configMock = \Mockery::mock('Friendica\Core\Config\ConfigCache'); + $this->mockApp($this->root, $configMock); $this->app ->shouldReceive('getHostname') ->andReturn('friendica.local'); diff --git a/tests/src/Core/Console/AutomaticInstallationConsoleTest.php b/tests/src/Core/Console/AutomaticInstallationConsoleTest.php index 361608d375..127a8bc3f8 100644 --- a/tests/src/Core/Console/AutomaticInstallationConsoleTest.php +++ b/tests/src/Core/Console/AutomaticInstallationConsoleTest.php @@ -181,7 +181,7 @@ FIN; $this->mockConnect(true, 1); $this->mockConnected(true, 1); $this->mockExistsTable('user', false, 1); - $this->mockUpdate([false, true, true], null, 1); + $this->mockUpdate([$this->root->url(), false, true, true], null, 1); $config = <<mockConnect(true, 1); $this->mockConnected(true, 1); $this->mockExistsTable('user', false, 1); - $this->mockUpdate([false, true, true], null, 1); + $this->mockUpdate([$this->root->url(), false, true, true], null, 1); $this->mockGetMarkupTemplate('local.config.tpl', 'testTemplate', 1); $this->mockReplaceMacros('testTemplate', $this->createArgumentsForMacro(true), '', 1); @@ -267,7 +267,7 @@ CONF; $this->mockConnect(true, 1); $this->mockConnected(true, 1); $this->mockExistsTable('user', false, 1); - $this->mockUpdate([false, true, true], null, 1); + $this->mockUpdate([$this->root->url(), false, true, true], null, 1); $this->mockGetMarkupTemplate('local.config.tpl', 'testTemplate', 1); $this->mockReplaceMacros('testTemplate', $this->createArgumentsForMacro(false), '', 1); @@ -292,7 +292,7 @@ CONF; $this->mockConnect(true, 1); $this->mockConnected(true, 1); $this->mockExistsTable('user', false, 1); - $this->mockUpdate([false, true, true], null, 1); + $this->mockUpdate([$this->root->url(), false, true, true], null, 1); $this->mockGetMarkupTemplate('local.config.tpl', 'testTemplate', 1); $this->mockReplaceMacros('testTemplate', $this->createArgumentsForMacro(true), '', 1); diff --git a/tests/src/Core/Console/ConsoleTest.php b/tests/src/Core/Console/ConsoleTest.php index 4f7acc9c42..905d214cac 100644 --- a/tests/src/Core/Console/ConsoleTest.php +++ b/tests/src/Core/Console/ConsoleTest.php @@ -29,7 +29,8 @@ abstract class ConsoleTest extends MockedTest Intercept::setUp(); $this->setUpVfsDir(); - $this->mockApp($this->root); + $configMock = \Mockery::mock('Friendica\Core\Config\ConfigCache'); + $this->mockApp($this->root, $configMock); } /** diff --git a/tests/src/Core/Lock/LockTest.php b/tests/src/Core/Lock/LockTest.php index 320beb3054..2d11a71ae1 100644 --- a/tests/src/Core/Lock/LockTest.php +++ b/tests/src/Core/Lock/LockTest.php @@ -31,7 +31,8 @@ abstract class LockTest extends MockedTest // Reusable App object $this->setUpVfsDir(); - $this->mockApp($this->root); + $configMock = \Mockery::mock('Friendica\Core\Config\ConfigCache'); + $this->mockApp($this->root, $configMock); $this->app ->shouldReceive('getHostname') ->andReturn('friendica.local'); From d6dd74690d4474f5dac6ab92d6ebfe4844a27aca Mon Sep 17 00:00:00 2001 From: Philipp Holzer Date: Mon, 4 Feb 2019 01:19:01 +0100 Subject: [PATCH 12/31] Bugfixing Config output for memcached_hosts[] --- src/Core/Console/Config.php | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/Core/Console/Config.php b/src/Core/Console/Config.php index c72e26906f..b1c3df54e0 100644 --- a/src/Core/Console/Config.php +++ b/src/Core/Console/Config.php @@ -113,7 +113,7 @@ HELP; if (is_array($value)) { foreach ($value as $k => $v) { - $this->out("{$cat}.{$key}[{$k}] => " . $v); + $this->out("{$cat}.{$key}[{$k}] => " . (is_array($v) ? implode(', ', $v) : $v)); } } else { $this->out("{$cat}.{$key} => " . $value); @@ -130,7 +130,7 @@ HELP; foreach ($catVal as $key => $value) { if (is_array($value)) { foreach ($value as $k => $v) { - $this->out("{$key}[{$k}] => " . $v); + $this->out("{$key}[{$k}] => " . (is_array($v) ? implode(', ', $v) : $v)); } } else { $this->out("{$key} => " . $value); @@ -154,7 +154,7 @@ HELP; foreach ($section as $key => $value) { if (is_array($value)) { foreach ($value as $k => $v) { - $this->out("{$cat}.{$key}[{$k}] => " . $v); + $this->out("{$cat}.{$key}[{$k}] => " . (is_array($v) ? implode(', ', $v) : $v)); } } else { $this->out("{$cat}.{$key} => " . $value); From f2f8c97b7c672da589329bfdeb207e7164170773 Mon Sep 17 00:00:00 2001 From: Philipp Holzer Date: Mon, 4 Feb 2019 02:06:15 +0100 Subject: [PATCH 13/31] Bugfixing Addon-config --- src/Core/Config/ConfigCacheLoader.php | 16 +++++++++++++--- 1 file changed, 13 insertions(+), 3 deletions(-) diff --git a/src/Core/Config/ConfigCacheLoader.php b/src/Core/Config/ConfigCacheLoader.php index a23e1e848a..6a1d438401 100644 --- a/src/Core/Config/ConfigCacheLoader.php +++ b/src/Core/Config/ConfigCacheLoader.php @@ -16,7 +16,12 @@ class ConfigCacheLoader * The Sub directory of the config-files * @var string */ - const SUBDIRECTORY = '/config/'; + const SUBDIRECTORY = '/config/'; + /** + * The addon sub-directory + * @var string + */ + const ADDONDIRECTORY = '/addon/'; private $baseDir; private $configDir; @@ -129,12 +134,17 @@ class ConfigCacheLoader * ]; * * @param string $filename + * @param bool $addon True, if a config for an addon should be loaded * @return array The configuration * @throws \Exception */ - public function loadConfigFile($filename) + public function loadConfigFile($filename, $addon = false) { - $filepath = $this->configDir . $filename . ".config.php"; + if ($addon) { + $filepath = $this->baseDir . self::ADDONDIRECTORY . self::SUBDIRECTORY . $filename . ".config.php"; + } else { + $filepath = $this->configDir . $filename . ".config.php"; + } if (!file_exists($filepath)) { throw new \Exception('Error loading non-existent config file ' . $filepath); From bdfe0c35fb0c42e12fa5f530d3d80db0b498386f Mon Sep 17 00:00:00 2001 From: Philipp Holzer Date: Mon, 4 Feb 2019 02:14:20 +0100 Subject: [PATCH 14/31] Typo at addon-directory-name ... --- src/Core/Config/ConfigCacheLoader.php | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/Core/Config/ConfigCacheLoader.php b/src/Core/Config/ConfigCacheLoader.php index 6a1d438401..ea9cbf23db 100644 --- a/src/Core/Config/ConfigCacheLoader.php +++ b/src/Core/Config/ConfigCacheLoader.php @@ -21,7 +21,7 @@ class ConfigCacheLoader * The addon sub-directory * @var string */ - const ADDONDIRECTORY = '/addon/'; + const ADDONSDIRECTORY = '/addons/'; private $baseDir; private $configDir; @@ -141,7 +141,7 @@ class ConfigCacheLoader public function loadConfigFile($filename, $addon = false) { if ($addon) { - $filepath = $this->baseDir . self::ADDONDIRECTORY . self::SUBDIRECTORY . $filename . ".config.php"; + $filepath = $this->baseDir . self::ADDONSDIRECTORY . self::SUBDIRECTORY . $filename . ".config.php"; } else { $filepath = $this->configDir . $filename . ".config.php"; } From 1c51d7d22fde8f7d5a46d04ab8f6e3d1c3ac1aed Mon Sep 17 00:00:00 2001 From: Philipp Holzer Date: Mon, 4 Feb 2019 02:21:23 +0100 Subject: [PATCH 15/31] Typo at addon-directory-name ... --- src/Core/Config/ConfigCacheLoader.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Core/Config/ConfigCacheLoader.php b/src/Core/Config/ConfigCacheLoader.php index ea9cbf23db..bb6207f93d 100644 --- a/src/Core/Config/ConfigCacheLoader.php +++ b/src/Core/Config/ConfigCacheLoader.php @@ -141,7 +141,7 @@ class ConfigCacheLoader public function loadConfigFile($filename, $addon = false) { if ($addon) { - $filepath = $this->baseDir . self::ADDONSDIRECTORY . self::SUBDIRECTORY . $filename . ".config.php"; + $filepath = $this->baseDir . self::ADDONSDIRECTORY . $filename . self::SUBDIRECTORY . $filename . ".config.php"; } else { $filepath = $this->configDir . $filename . ".config.php"; } From d78ac575140c57b6cc8682eedb0bd227d37fb36f Mon Sep 17 00:00:00 2001 From: Philipp Holzer Date: Mon, 4 Feb 2019 09:30:48 +0100 Subject: [PATCH 16/31] Updating type-hints and some naming conventions --- src/Core/Config.php | 4 +-- src/Core/Config/ConfigCache.php | 8 +++--- src/Core/Config/ConfigCacheLoader.php | 4 +-- src/Core/Config/JITConfigAdapter.php | 24 ++++++++--------- src/Core/Config/JITPConfigAdapter.php | 30 ++++++++++----------- src/Core/Config/PreloadConfigAdapter.php | 20 +++++++------- src/Core/Config/PreloadPConfigAdapter.php | 22 ++++++++-------- src/Database/DBA.php | 32 +++++++++++------------ src/Factory/ConfigFactory.php | 4 +-- 9 files changed, 74 insertions(+), 74 deletions(-) diff --git a/src/Core/Config.php b/src/Core/Config.php index 0db8f0b882..3eace0fbc1 100644 --- a/src/Core/Config.php +++ b/src/Core/Config.php @@ -32,7 +32,7 @@ class Config * * @param Config\IConfigCache $config The configuration cache */ - public static function init($config) + public static function init(Config\IConfigCache $config) { self::$config = $config; } @@ -42,7 +42,7 @@ class Config * * @param Config\IConfigAdapter $adapter */ - public static function setAdapter($adapter) + public static function setAdapter(Config\IConfigAdapter $adapter) { self::$adapter = $adapter; } diff --git a/src/Core/Config/ConfigCache.php b/src/Core/Config/ConfigCache.php index 355b1df2f5..dba2a9dd11 100644 --- a/src/Core/Config/ConfigCache.php +++ b/src/Core/Config/ConfigCache.php @@ -22,7 +22,7 @@ class ConfigCache implements IConfigCache, IPConfigCache /** * @param array $config A initial config array */ - public function __construct($config = []) + public function __construct(array $config = []) { $this->config = []; @@ -43,9 +43,9 @@ class ConfigCache implements IConfigCache, IPConfigCache foreach ($config as $category => $values) { foreach ($values as $key => $value) { if ($overwrite) { - self::set($category, $key, $value); + $this->set($category, $key, $value); } else { - self::setDefault($category, $key, $value); + $this->setDefault($category, $key, $value); } } } @@ -83,7 +83,7 @@ class ConfigCache implements IConfigCache, IPConfigCache private function setDefault($cat, $k, $v) { if (!isset($this->config[$cat][$k])) { - self::set($cat, $k, $v); + $this->set($cat, $k, $v); } } diff --git a/src/Core/Config/ConfigCacheLoader.php b/src/Core/Config/ConfigCacheLoader.php index bb6207f93d..4f595bc1c4 100644 --- a/src/Core/Config/ConfigCacheLoader.php +++ b/src/Core/Config/ConfigCacheLoader.php @@ -21,7 +21,7 @@ class ConfigCacheLoader * The addon sub-directory * @var string */ - const ADDONSDIRECTORY = '/addons/'; + const ADDONDIRECTORY = '/addon/'; private $baseDir; private $configDir; @@ -141,7 +141,7 @@ class ConfigCacheLoader public function loadConfigFile($filename, $addon = false) { if ($addon) { - $filepath = $this->baseDir . self::ADDONSDIRECTORY . $filename . self::SUBDIRECTORY . $filename . ".config.php"; + $filepath = $this->baseDir . self::ADDONDIRECTORY . $filename . self::SUBDIRECTORY . $filename . ".config.php"; } else { $filepath = $this->configDir . $filename . ".config.php"; } diff --git a/src/Core/Config/JITConfigAdapter.php b/src/Core/Config/JITConfigAdapter.php index 256a2a956f..5e7e786f07 100644 --- a/src/Core/Config/JITConfigAdapter.php +++ b/src/Core/Config/JITConfigAdapter.php @@ -18,14 +18,14 @@ class JITConfigAdapter implements IConfigAdapter /** * @var IConfigCache The config cache of this driver */ - private $config; + private $configCache; /** - * @param IConfigCache $config The config cache of this driver + * @param IConfigCache $configCache The config cache of this driver */ - public function __construct($config) + public function __construct(IConfigCache $configCache) { - $this->config = $config; + $this->configCache = $configCache; } public function load($cat = "config") @@ -40,7 +40,7 @@ class JITConfigAdapter implements IConfigAdapter while ($config = DBA::fetch($configs)) { $k = $config['k']; - $this->config->set($cat, $k, $config['v']); + $this->configCache->set($cat, $k, $config['v']); if ($cat !== 'config') { $this->cache[$cat][$k] = $config['v']; @@ -72,18 +72,18 @@ class JITConfigAdapter implements IConfigAdapter $this->cache[$cat][$k] = $value; $this->in_db[$cat][$k] = true; return $value; - } elseif ($this->config->get($cat, $k) !== null) { + } elseif ($this->configCache->get($cat, $k) !== null) { // Assign the value (mostly) from config/local.config.php file to the cache - $this->cache[$cat][$k] = $this->config->get($cat, $k); + $this->cache[$cat][$k] = $this->configCache->get($cat, $k); $this->in_db[$cat][$k] = false; - return $this->config->get($cat, $k); - } elseif ($this->config->get('config', $k) !== null) { + return $this->configCache->get($cat, $k); + } elseif ($this->configCache->get('config', $k) !== null) { // Assign the value (mostly) from config/local.config.php file to the cache - $this->cache[$k] = $this->config->get('config', $k); + $this->cache[$k] = $this->configCache->get('config', $k); $this->in_db[$k] = false; - return $this->config->get('config', $k); + return $this->configCache->get('config', $k); } $this->cache[$cat][$k] = '!!'; @@ -112,7 +112,7 @@ class JITConfigAdapter implements IConfigAdapter return true; } - $this->config->set($cat, $k, $value); + $this->configCache->set($cat, $k, $value); // Assign the just added value to the cache $this->cache[$cat][$k] = $dbvalue; diff --git a/src/Core/Config/JITPConfigAdapter.php b/src/Core/Config/JITPConfigAdapter.php index 223cc542dc..2fd7705928 100644 --- a/src/Core/Config/JITPConfigAdapter.php +++ b/src/Core/Config/JITPConfigAdapter.php @@ -18,14 +18,14 @@ class JITPConfigAdapter implements IPConfigAdapter * The config cache of this adapter * @var IPConfigCache */ - private $config; + private $configCache; /** - * @param IPConfigCache $config The config cache of this adapter + * @param IPConfigCache $configCache The config cache of this adapter */ - public function __construct($config) + public function __construct(IPConfigCache $configCache) { - $this->config = $config; + $this->configCache = $configCache; } public function load($uid, $cat) @@ -35,13 +35,13 @@ class JITPConfigAdapter implements IPConfigAdapter while ($pconfig = DBA::fetch($pconfigs)) { $k = $pconfig['k']; - $this->config->setP($uid, $cat, $k, $pconfig['v']); + $this->configCache->setP($uid, $cat, $k, $pconfig['v']); $this->in_db[$uid][$cat][$k] = true; } } else if ($cat != 'config') { // Negative caching - $this->config->setP($uid, $cat, null, "!!"); + $this->configCache->setP($uid, $cat, null, "!!"); } DBA::close($pconfigs); } @@ -50,17 +50,17 @@ class JITPConfigAdapter implements IPConfigAdapter { if (!$refresh) { // Looking if the whole family isn't set - if ($this->config->getP($uid, $cat) !== null) { - if ($this->config->getP($uid, $cat) === '!!') { + if ($this->configCache->getP($uid, $cat) !== null) { + if ($this->configCache->getP($uid, $cat) === '!!') { return $default_value; } } - if ($this->config->getP($uid, $cat, $k) !== null) { - if ($this->config->getP($uid, $cat, $k) === '!!') { + if ($this->configCache->getP($uid, $cat, $k) !== null) { + if ($this->configCache->getP($uid, $cat, $k) === '!!') { return $default_value; } - return $this->config->getP($uid, $cat, $k); + return $this->configCache->getP($uid, $cat, $k); } } @@ -68,13 +68,13 @@ class JITPConfigAdapter implements IPConfigAdapter if (DBA::isResult($pconfig)) { $val = (preg_match("|^a:[0-9]+:{.*}$|s", $pconfig['v']) ? unserialize($pconfig['v']) : $pconfig['v']); - $this->config->setP($uid, $cat, $k, $val); + $this->configCache->setP($uid, $cat, $k, $val); $this->in_db[$uid][$cat][$k] = true; return $val; } else { - $this->config->setP($uid, $cat, $k, '!!'); + $this->configCache->setP($uid, $cat, $k, '!!'); $this->in_db[$uid][$cat][$k] = false; @@ -95,7 +95,7 @@ class JITPConfigAdapter implements IPConfigAdapter return true; } - $this->config->setP($uid, $cat, $k, $value); + $this->configCache->setP($uid, $cat, $k, $value); // manage array value $dbvalue = (is_array($value) ? serialize($value) : $dbvalue); @@ -111,7 +111,7 @@ class JITPConfigAdapter implements IPConfigAdapter public function delete($uid, $cat, $k) { - $this->config->deleteP($uid, $cat, $k); + $this->configCache->deleteP($uid, $cat, $k); if (!empty($this->in_db[$uid][$cat][$k])) { unset($this->in_db[$uid][$cat][$k]); diff --git a/src/Core/Config/PreloadConfigAdapter.php b/src/Core/Config/PreloadConfigAdapter.php index 4461105e14..bda9b28aae 100644 --- a/src/Core/Config/PreloadConfigAdapter.php +++ b/src/Core/Config/PreloadConfigAdapter.php @@ -19,14 +19,14 @@ class PreloadConfigAdapter implements IConfigAdapter /** * @var IConfigCache The config cache of this driver */ - private $config; + private $configCache; /** - * @param IConfigCache $config The config cache of this driver + * @param IConfigCache $configCache The config cache of this driver */ - public function __construct($config) + public function __construct(IConfigCache $configCache) { - $this->config = $config; + $this->configCache = $configCache; $this->load(); } @@ -38,7 +38,7 @@ class PreloadConfigAdapter implements IConfigAdapter $configs = DBA::select('config', ['cat', 'v', 'k']); while ($config = DBA::fetch($configs)) { - $this->config->set($config['cat'], $config['k'], $config['v']); + $this->configCache->set($config['cat'], $config['k'], $config['v']); } DBA::close($configs); @@ -50,11 +50,11 @@ class PreloadConfigAdapter implements IConfigAdapter if ($refresh) { $config = DBA::selectFirst('config', ['v'], ['cat' => $cat, 'k' => $k]); if (DBA::isResult($config)) { - $this->config->set($cat, $k, $config['v']); + $this->configCache->set($cat, $k, $config['v']); } } - $return = $this->config->get($cat, $k, $default_value); + $return = $this->configCache->get($cat, $k, $default_value); return $return; } @@ -66,11 +66,11 @@ class PreloadConfigAdapter implements IConfigAdapter // The exception are array values. $compare_value = !is_array($value) ? (string)$value : $value; - if ($this->config->get($cat, $k) === $compare_value) { + if ($this->configCache->get($cat, $k) === $compare_value) { return true; } - $this->config->set($cat, $k, $value); + $this->configCache->set($cat, $k, $value); // manage array value $dbvalue = is_array($value) ? serialize($value) : $value; @@ -85,7 +85,7 @@ class PreloadConfigAdapter implements IConfigAdapter public function delete($cat, $k) { - $this->config->delete($cat, $k); + $this->configCache->delete($cat, $k); $result = DBA::delete('config', ['cat' => $cat, 'k' => $k]); diff --git a/src/Core/Config/PreloadPConfigAdapter.php b/src/Core/Config/PreloadPConfigAdapter.php index ed18bdf2e7..b49f39382f 100644 --- a/src/Core/Config/PreloadPConfigAdapter.php +++ b/src/Core/Config/PreloadPConfigAdapter.php @@ -20,15 +20,15 @@ class PreloadPConfigAdapter implements IPConfigAdapter * The config cache of this adapter * @var IPConfigCache */ - private $config; + private $configCache; /** - * @param IPConfigCache $config The config cache of this adapter + * @param IPConfigCache $configCache The config cache of this adapter * @param int $uid The UID of the current user */ - public function __construct($config, $uid = null) + public function __construct(IPConfigCache $configCache, $uid = null) { - $this->config = $config; + $this->configCache = $configCache; if (isset($uid)) { $this->load($uid, 'config'); } @@ -46,7 +46,7 @@ class PreloadPConfigAdapter implements IPConfigAdapter $pconfigs = DBA::select('pconfig', ['cat', 'v', 'k'], ['uid' => $uid]); while ($pconfig = DBA::fetch($pconfigs)) { - $this->config->setP($uid, $pconfig['cat'], $pconfig['k'], $pconfig['v']); + $this->configCache->setP($uid, $pconfig['cat'], $pconfig['k'], $pconfig['v']); } DBA::close($pconfigs); @@ -62,13 +62,13 @@ class PreloadPConfigAdapter implements IPConfigAdapter if ($refresh) { $config = DBA::selectFirst('pconfig', ['v'], ['uid' => $uid, 'cat' => $cat, 'k' => $k]); if (DBA::isResult($config)) { - $this->config->setP($uid, $cat, $k, $config['v']); + $this->configCache->setP($uid, $cat, $k, $config['v']); } else { - $this->config->deleteP($uid, $cat, $k); + $this->configCache->deleteP($uid, $cat, $k); } } - return $this->config->getP($uid, $cat, $k, $default_value);; + return $this->configCache->getP($uid, $cat, $k, $default_value);; } public function set($uid, $cat, $k, $value) @@ -81,11 +81,11 @@ class PreloadPConfigAdapter implements IPConfigAdapter // The exception are array values. $compare_value = !is_array($value) ? (string)$value : $value; - if ($this->config->getP($uid, $cat, $k) === $compare_value) { + if ($this->configCache->getP($uid, $cat, $k) === $compare_value) { return true; } - $this->config->setP($uid, $cat, $k, $value); + $this->configCache->setP($uid, $cat, $k, $value); // manage array value $dbvalue = is_array($value) ? serialize($value) : $value; @@ -104,7 +104,7 @@ class PreloadPConfigAdapter implements IPConfigAdapter $this->load($uid, $cat); } - $this->config->deleteP($uid, $cat, $k); + $this->configCache->deleteP($uid, $cat, $k); $result = DBA::delete('pconfig', ['uid' => $uid, 'cat' => $cat, 'k' => $k]); diff --git a/src/Database/DBA.php b/src/Database/DBA.php index eaeeb9cbdd..d2a739e931 100644 --- a/src/Database/DBA.php +++ b/src/Database/DBA.php @@ -34,7 +34,7 @@ class DBA /** * @var IConfigCache */ - private static $config; + private static $configCache; private static $server_info = ''; private static $connection; private static $driver; @@ -50,14 +50,14 @@ class DBA private static $db_name = ''; private static $db_charset = ''; - public static function connect($config, $serveraddr, $user, $pass, $db, $charset = null) + public static function connect($configCache, $serveraddr, $user, $pass, $db, $charset = null) { if (!is_null(self::$connection) && self::connected()) { return true; } // We are storing these values for being able to perform a reconnect - self::$config = $config; + self::$configCache = $configCache; self::$db_serveraddr = $serveraddr; self::$db_user = $user; self::$db_pass = $pass; @@ -158,7 +158,7 @@ class DBA public static function reconnect() { self::disconnect(); - $ret = self::connect(self::$config, self::$db_serveraddr, self::$db_user, self::$db_pass, self::$db_name, self::$db_charset); + $ret = self::connect(self::$configCache, self::$db_serveraddr, self::$db_user, self::$db_pass, self::$db_name, self::$db_charset); return $ret; } @@ -213,7 +213,7 @@ class DBA */ private static function logIndex($query) { - if (!self::$config->get('system', 'db_log_index')) { + if (!self::$configCache->get('system', 'db_log_index')) { return; } @@ -232,18 +232,18 @@ class DBA return; } - $watchlist = explode(',', self::$config->get('system', 'db_log_index_watch')); - $blacklist = explode(',', self::$config->get('system', 'db_log_index_blacklist')); + $watchlist = explode(',', self::$configCache->get('system', 'db_log_index_watch')); + $blacklist = explode(',', self::$configCache->get('system', 'db_log_index_blacklist')); while ($row = self::fetch($r)) { - if ((intval(self::$config->get('system', 'db_loglimit_index')) > 0)) { + if ((intval(self::$configCache->get('system', 'db_loglimit_index')) > 0)) { $log = (in_array($row['key'], $watchlist) && - ($row['rows'] >= intval(self::$config->get('system', 'db_loglimit_index')))); + ($row['rows'] >= intval(self::$configCache->get('system', 'db_loglimit_index')))); } else { $log = false; } - if ((intval(self::$config->get('system', 'db_loglimit_index_high')) > 0) && ($row['rows'] >= intval($Config::getConfigValue('system', 'db_loglimit_index_high')))) { + if ((intval(self::$configCache->get('system', 'db_loglimit_index_high')) > 0) && ($row['rows'] >= intval(self::$configCache->get('system', 'db_loglimit_index_high')))) { $log = true; } @@ -253,7 +253,7 @@ class DBA if ($log) { $backtrace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS); - @file_put_contents(self::$config->get('system', 'db_log_index'), DateTimeFormat::utcNow()."\t". + @file_put_contents(self::$configCache->get('system', 'db_log_index'), DateTimeFormat::utcNow()."\t". $row['key']."\t".$row['rows']."\t".$row['Extra']."\t". basename($backtrace[1]["file"])."\t". $backtrace[1]["line"]."\t".$backtrace[2]["function"]."\t". @@ -423,7 +423,7 @@ class DBA $orig_sql = $sql; - if (self::$config->get('system', 'db_callstack') !== null) { + if (self::$configCache->get('system', 'db_callstack') !== null) { $sql = "/*".System::callstack()." */ ".$sql; } @@ -584,15 +584,15 @@ class DBA $a->saveTimestamp($stamp1, 'database'); - if (self::$config->get('system', 'db_log')) { + if (self::$configCache->get('system', 'db_log')) { $stamp2 = microtime(true); $duration = (float)($stamp2 - $stamp1); - if (($duration > self::$config->get('system', 'db_loglimit'))) { + if (($duration > self::$configCache->get('system', 'db_loglimit'))) { $duration = round($duration, 3); $backtrace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS); - @file_put_contents(self::$config->get('system', 'db_log'), DateTimeFormat::utcNow()."\t".$duration."\t". + @file_put_contents(self::$configCache->get('system', 'db_log'), DateTimeFormat::utcNow()."\t".$duration."\t". basename($backtrace[1]["file"])."\t". $backtrace[1]["line"]."\t".$backtrace[2]["function"]."\t". substr(self::replaceParameters($sql, $args), 0, 2000)."\n", FILE_APPEND); @@ -1031,7 +1031,7 @@ class DBA * This process must only be started once, since the value is cached. */ private static function buildRelationData() { - $definition = DBStructure::definition(self::$config->get('system', 'basepath')); + $definition = DBStructure::definition(self::$configCache->get('system', 'basepath')); foreach ($definition AS $table => $structure) { foreach ($structure['fields'] AS $field => $field_struct) { diff --git a/src/Factory/ConfigFactory.php b/src/Factory/ConfigFactory.php index 46d55b30c3..269daea8b8 100644 --- a/src/Factory/ConfigFactory.php +++ b/src/Factory/ConfigFactory.php @@ -25,7 +25,7 @@ class ConfigFactory * * @return Config\IConfigAdapter */ - public static function createConfig($type, $config) + public static function createConfig($type, Config\IConfigCache $config) { if ($type == 'preload') { return new Config\PreloadConfigAdapter($config); @@ -41,7 +41,7 @@ class ConfigFactory * * @return Config\IPConfigAdapter */ - public static function createPConfig($type, $config, $uid = null) + public static function createPConfig($type, Config\IPConfigCache $config, $uid = null) { if ($type == 'preload') { return new Config\PreloadPConfigAdapter($config, $uid); From f779110154b639d2774aa3154d1653bbd0a322f2 Mon Sep 17 00:00:00 2001 From: Philipp Holzer Date: Mon, 4 Feb 2019 09:32:13 +0100 Subject: [PATCH 17/31] Updating type-hints and some naming conventions --- src/Core/Config.php | 14 +++++++------- src/Core/PConfig.php | 16 ++++++++-------- 2 files changed, 15 insertions(+), 15 deletions(-) diff --git a/src/Core/Config.php b/src/Core/Config.php index 3eace0fbc1..81282d4df2 100644 --- a/src/Core/Config.php +++ b/src/Core/Config.php @@ -25,16 +25,16 @@ class Config /** * @var Config\IConfigCache */ - private static $config; + private static $cache; /** * Initialize the config with only the cache * - * @param Config\IConfigCache $config The configuration cache + * @param Config\IConfigCache $cache The configuration cache */ - public static function init(Config\IConfigCache $config) + public static function init(Config\IConfigCache $cache) { - self::$config = $config; + self::$cache = $cache; } /** @@ -88,7 +88,7 @@ class Config public static function get($family, $key, $default_value = null, $refresh = false) { if (!isset(self::$adapter)) { - return self::$config->get($family, $key, $default_value); + return self::$cache->get($family, $key, $default_value); } return self::$adapter->get($family, $key, $default_value, $refresh); @@ -111,7 +111,7 @@ class Config public static function set($family, $key, $value) { if (!isset(self::$adapter)) { - self::$config->set($family, $key, $value); + self::$cache->set($family, $key, $value); return true; } @@ -132,7 +132,7 @@ class Config public static function delete($family, $key) { if (!isset(self::$adapter)) { - self::$config->delete($family, $key); + self::$cache->delete($family, $key); } return self::$adapter->delete($family, $key); diff --git a/src/Core/PConfig.php b/src/Core/PConfig.php index 8782a20d23..908f0bf3dd 100644 --- a/src/Core/PConfig.php +++ b/src/Core/PConfig.php @@ -25,16 +25,16 @@ class PConfig /** * @var Config\IPConfigCache */ - private static $config; + private static $cache; /** * Initialize the config with only the cache * - * @param Config\IPConfigCache $config The configuration cache + * @param Config\IPConfigCache $cache The configuration cache */ - public static function init($config) + public static function init(Config\IPConfigCache $cache) { - self::$config = $config; + self::$cache = $cache; } /** @@ -42,7 +42,7 @@ class PConfig * * @param Config\IPConfigAdapter $adapter */ - public static function setAdapter($adapter) + public static function setAdapter(Config\IPConfigAdapter $adapter) { self::$adapter = $adapter; } @@ -85,7 +85,7 @@ class PConfig public static function get($uid, $family, $key, $default_value = null, $refresh = false) { if (!isset(self::$adapter)) { - return self::$config->getP($uid, $family, $key, $default_value); + return self::$cache->getP($uid, $family, $key, $default_value); } return self::$adapter->get($uid, $family, $key, $default_value, $refresh); @@ -109,7 +109,7 @@ class PConfig public static function set($uid, $family, $key, $value) { if (!isset(self::$adapter)) { - return self::$config->setP($uid, $family, $key, $value); + return self::$cache->setP($uid, $family, $key, $value); } return self::$adapter->set($uid, $family, $key, $value); @@ -130,7 +130,7 @@ class PConfig public static function delete($uid, $family, $key) { if (!isset(self::$adapter)) { - return self::$config->deleteP($uid, $family, $key); + return self::$cache->deleteP($uid, $family, $key); } return self::$adapter->delete($uid, $family, $key); From 4b82e47034b6847bc4ccf72dfae1703d99f0b2b8 Mon Sep 17 00:00:00 2001 From: Philipp Holzer Date: Mon, 4 Feb 2019 09:33:55 +0100 Subject: [PATCH 18/31] Moved addon directory constant --- src/Core/Addon.php | 6 ++++++ src/Core/Config/ConfigCacheLoader.php | 9 +++------ 2 files changed, 9 insertions(+), 6 deletions(-) diff --git a/src/Core/Addon.php b/src/Core/Addon.php index 1118280a53..e217cf8751 100644 --- a/src/Core/Addon.php +++ b/src/Core/Addon.php @@ -12,6 +12,12 @@ use Friendica\Database\DBA; */ class Addon extends BaseObject { + /** + * The addon sub-directory + * @var string + */ + const DIRECTORY = '/addon/'; + /** * List of the names of enabled addons * diff --git a/src/Core/Config/ConfigCacheLoader.php b/src/Core/Config/ConfigCacheLoader.php index 4f595bc1c4..58647e5aec 100644 --- a/src/Core/Config/ConfigCacheLoader.php +++ b/src/Core/Config/ConfigCacheLoader.php @@ -2,6 +2,8 @@ namespace Friendica\Core\Config; +use Friendica\Core\Addon; + /** * The ConfigCacheLoader loads config-files and stores them in a ConfigCache ( @see ConfigCache ) * @@ -17,11 +19,6 @@ class ConfigCacheLoader * @var string */ const SUBDIRECTORY = '/config/'; - /** - * The addon sub-directory - * @var string - */ - const ADDONDIRECTORY = '/addon/'; private $baseDir; private $configDir; @@ -141,7 +138,7 @@ class ConfigCacheLoader public function loadConfigFile($filename, $addon = false) { if ($addon) { - $filepath = $this->baseDir . self::ADDONDIRECTORY . $filename . self::SUBDIRECTORY . $filename . ".config.php"; + $filepath = $this->baseDir . Addon::DIRECTORY . $filename . self::SUBDIRECTORY . $filename . ".config.php"; } else { $filepath = $this->configDir . $filename . ".config.php"; } From 0d096cf32e3ea9adf77f6323ef4fc45213a8a1ff Mon Sep 17 00:00:00 2001 From: Philipp Holzer Date: Mon, 4 Feb 2019 09:35:01 +0100 Subject: [PATCH 19/31] type-hints --- src/Factory/LoggerFactory.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Factory/LoggerFactory.php b/src/Factory/LoggerFactory.php index 658d2c9bee..751a6357da 100644 --- a/src/Factory/LoggerFactory.php +++ b/src/Factory/LoggerFactory.php @@ -25,7 +25,7 @@ class LoggerFactory * * @return LoggerInterface The PSR-3 compliant logger instance */ - public static function create($channel, $config = null) + public static function create($channel, ConfigCache $config = null) { $logger = new Monolog\Logger($channel); $logger->pushProcessor(new Monolog\Processor\PsrLogMessageProcessor()); From 800dbc7f44ad7b9d2942691b3080c6d96753297e Mon Sep 17 00:00:00 2001 From: Philipp Holzer Date: Tue, 5 Feb 2019 21:54:55 +0100 Subject: [PATCH 20/31] Removed implicit ::getApp() instance and added docblock --- src/BaseObject.php | 10 ++-------- src/Core/Config.php | 20 +++++++++----------- src/Core/PConfig.php | 12 +++++++----- 3 files changed, 18 insertions(+), 24 deletions(-) diff --git a/src/BaseObject.php b/src/BaseObject.php index 4deba1ced1..1a23408ba1 100644 --- a/src/BaseObject.php +++ b/src/BaseObject.php @@ -6,9 +6,7 @@ namespace Friendica; require_once 'boot.php'; -use Friendica\Core\Config; -use Friendica\Factory; -use Friendica\Util\BasePath; +use Friendica\Network\HTTPException\InternalServerErrorException; /** * Basic object @@ -30,11 +28,7 @@ class BaseObject public static function getApp() { if (empty(self::$app)) { - $basedir = BasePath::create(dirname(__DIR__)); - $configLoader = new Config\ConfigCacheLoader($basedir); - $config = Factory\ConfigFactory::createCache($configLoader); - $logger = Factory\LoggerFactory::create('app', $config); - self::$app = new App($config, $logger); + throw new InternalServerErrorException('App isn\' initialized.'); } return self::$app; diff --git a/src/Core/Config.php b/src/Core/Config.php index 81282d4df2..6ceb637701 100644 --- a/src/Core/Config.php +++ b/src/Core/Config.php @@ -8,6 +8,10 @@ */ namespace Friendica\Core; +use Friendica\Core\Config\ConfigCache; +use Friendica\Core\Config\IConfigAdapter; +use Friendica\Core\Config\IConfigCache; + /** * @brief Arbitrary system configuration storage * @@ -50,8 +54,7 @@ class Config /** * @brief Loads all configuration values of family into a cached storage. * - * All configuration values of the system are stored in global cache - * which is available under the global variable self::$config + * All configuration values of the system are stored in the cache ( @see IConfigCache ) * * @param string $family The category of the configuration value * @@ -71,12 +74,8 @@ class Config * ($family) and a key. * * Get a particular config value from the given category ($family) - * and the $key from a cached storage in static::config[$uid]. - * $instore is only used by the set_config function - * to determine if the key already exists in the DB - * If a key is found in the DB but doesn't exist in - * local config cache, pull it into the cache so we don't have - * to hit the DB again for this item. + * and the $key from a cached storage either from the self::$adapter + * (@see IConfigAdapter ) or from the static::$cache (@see IConfigCache ). * * @param string $family The category of the configuration value * @param string $key The configuration key to query @@ -98,7 +97,6 @@ class Config * @brief Sets a configuration value for system config * * Stores a config value ($value) in the category ($family) under the key ($key) - * for the user_id $uid. * * Note: Please do not store booleans - convert to 0/1 integer values! * @@ -121,8 +119,8 @@ class Config /** * @brief Deletes the given key from the system configuration. * - * Removes the configured value from the stored cache in Config::$config - * and removes it from the database. + * Removes the configured value from the stored cache in self::$config + * (@see ConfigCache ) and removes it from the database (@see IConfigAdapter ). * * @param string $family The category of the configuration value * @param string $key The configuration key to delete diff --git a/src/Core/PConfig.php b/src/Core/PConfig.php index 908f0bf3dd..df024f0f34 100644 --- a/src/Core/PConfig.php +++ b/src/Core/PConfig.php @@ -50,8 +50,8 @@ class PConfig /** * @brief Loads all configuration values of a user's config family into a cached storage. * - * All configuration values of the given user are stored in global cache - * which is available under the global variable self::$config[$uid]. + * All configuration values of the given user are stored with the $uid in + * the cache ( @see IPConfigCache ) * * @param string $uid The user_id * @param string $family The category of the configuration value @@ -72,7 +72,8 @@ class PConfig * ($family) and a key. * * Get a particular user's config value from the given category ($family) - * and the $key from a cached storage in self::$config[$uid]. + * and the $key with the $uid from a cached storage either from the self::$adapter + * (@see IConfigAdapter ) or from the static::$cache (@see IConfigCache ). * * @param string $uid The user_id * @param string $family The category of the configuration value @@ -118,8 +119,9 @@ class PConfig /** * @brief Deletes the given key from the users's configuration. * - * Removes the configured value from the stored cache in self::$config[$uid] - * and removes it from the database. + * Removes the configured value from the stored cache in self::$config + * (@see ConfigCache ) and removes it from the database (@see IConfigAdapter ) + * with the given $uid. * * @param string $uid The user_id * @param string $family The category of the configuration value From 104086215c6c85cb84345f1379fee58ffbba99bd Mon Sep 17 00:00:00 2001 From: Philipp Holzer Date: Tue, 5 Feb 2019 22:03:07 +0100 Subject: [PATCH 21/31] Fixing tests --- tests/include/ApiTest.php | 15 ++++++++++----- tests/src/Database/DBATest.php | 14 ++++++++++---- tests/src/Database/DBStructureTest.php | 14 ++++++++++---- 3 files changed, 30 insertions(+), 13 deletions(-) diff --git a/tests/include/ApiTest.php b/tests/include/ApiTest.php index 9cf3e2ea5d..be70d923bd 100644 --- a/tests/include/ApiTest.php +++ b/tests/include/ApiTest.php @@ -5,13 +5,14 @@ namespace Friendica\Test; -use Friendica\BaseObject; +use Friendica\App; use Friendica\Core\Config; use Friendica\Core\PConfig; use Friendica\Core\Protocol; use Friendica\Core\System; -use Friendica\Factory\LoggerFactory; +use Friendica\Factory; use Friendica\Network\HTTPException; +use Friendica\Util\BasePath; use Monolog\Handler\TestHandler; require_once __DIR__ . '/../../include/api.php'; @@ -34,10 +35,14 @@ class ApiTest extends DatabaseTest */ public function setUp() { - parent::setUp(); + $basedir = BasePath::create(dirname(__DIR__) . '/../'); + $configLoader = new Config\ConfigCacheLoader($basedir); + $config = Factory\ConfigFactory::createCache($configLoader); + $logger = Factory\LoggerFactory::create('test', $config); + $this->app = new App($config, $logger, false); + $this->logOutput = FActory\LoggerFactory::enableTest($this->app->getLogger()); - $this->app = BaseObject::getApp(); - $this->logOutput = LoggerFactory::enableTest($this->app->getLogger()); + parent::setUp(); // User data that the test database is populated with $this->selfUser = [ diff --git a/tests/src/Database/DBATest.php b/tests/src/Database/DBATest.php index 17ac55fd7a..f2a5cc5558 100644 --- a/tests/src/Database/DBATest.php +++ b/tests/src/Database/DBATest.php @@ -1,19 +1,25 @@ app = new App($config, $logger, false); + $this->logOutput = FActory\LoggerFactory::enableTest($this->app->getLogger()); - // Reusable App object - $this->app = BaseObject::getApp(); + parent::setUp(); // Default config Config::set('config', 'hostname', 'localhost'); diff --git a/tests/src/Database/DBStructureTest.php b/tests/src/Database/DBStructureTest.php index 268bf8eedd..53c4e8895b 100644 --- a/tests/src/Database/DBStructureTest.php +++ b/tests/src/Database/DBStructureTest.php @@ -2,19 +2,25 @@ namespace Friendica\Test\Database; -use Friendica\BaseObject; +use Friendica\App; use Friendica\Core\Config; use Friendica\Database\DBStructure; +use Friendica\Factory; use Friendica\Test\DatabaseTest; +use Friendica\Util\BasePath; class DBStructureTest extends DatabaseTest { public function setUp() { - parent::setUp(); + $basedir = BasePath::create(dirname(__DIR__) . '/../../'); + $configLoader = new Config\ConfigCacheLoader($basedir); + $config = Factory\ConfigFactory::createCache($configLoader); + $logger = Factory\LoggerFactory::create('test', $config); + $this->app = new App($config, $logger, false); + $this->logOutput = FActory\LoggerFactory::enableTest($this->app->getLogger()); - // Reusable App object - $this->app = BaseObject::getApp(); + parent::setUp(); // Default config Config::set('config', 'hostname', 'localhost'); From 6a9d73f7d9711bcd29142b8614fe6ddc09f4eae1 Mon Sep 17 00:00:00 2001 From: Philipp Holzer Date: Tue, 5 Feb 2019 22:27:57 +0100 Subject: [PATCH 22/31] Refactoring ConfigCacheLoader methods --- bin/auth_ejabberd.php | 2 +- bin/console.php | 2 +- bin/daemon.php | 2 +- bin/worker.php | 2 +- index.php | 2 +- src/App.php | 2 +- src/Core/Config/ConfigCache.php | 14 +----- src/Core/Config/ConfigCacheLoader.php | 71 +++++++++++++++------------ src/Util/BasePath.php | 16 +++--- 9 files changed, 56 insertions(+), 57 deletions(-) diff --git a/bin/auth_ejabberd.php b/bin/auth_ejabberd.php index af728f218c..11df438952 100755 --- a/bin/auth_ejabberd.php +++ b/bin/auth_ejabberd.php @@ -54,7 +54,7 @@ chdir($directory); require dirname(__DIR__) . '/vendor/autoload.php'; -$basedir = BasePath::create(dirname(__DIR__)); +$basedir = BasePath::create(dirname(__DIR__), $_SERVER); $configLoader = new Config\ConfigCacheLoader($basedir); $config = Factory\ConfigFactory::createCache($configLoader); $logger = Factory\LoggerFactory::create('auth_ejabberd', $config); diff --git a/bin/console.php b/bin/console.php index e7b1786de7..9061824d87 100755 --- a/bin/console.php +++ b/bin/console.php @@ -7,7 +7,7 @@ use Friendica\Core\Config; use Friendica\Factory; use Friendica\Util\BasePath; -$basedir = BasePath::create(dirname(__DIR__)); +$basedir = BasePath::create(dirname(__DIR__), $_SERVER); $configLoader = new Config\ConfigCacheLoader($basedir); $config = Factory\ConfigFactory::createCache($configLoader); $logger = Factory\LoggerFactory::create('console', $config); diff --git a/bin/daemon.php b/bin/daemon.php index 7e71571cb3..5c014a9270 100755 --- a/bin/daemon.php +++ b/bin/daemon.php @@ -33,7 +33,7 @@ if (!file_exists("boot.php") && (sizeof($_SERVER["argv"]) != 0)) { require dirname(__DIR__) . '/vendor/autoload.php'; -$basedir = BasePath::create(dirname(__DIR__)); +$basedir = BasePath::create(dirname(__DIR__), $_SERVER); $configLoader = new Config\ConfigCacheLoader($basedir); $config = Factory\ConfigFactory::createCache($configLoader); $logger = Factory\LoggerFactory::create('daemon', $config); diff --git a/bin/worker.php b/bin/worker.php index 61fdbed544..553e984977 100755 --- a/bin/worker.php +++ b/bin/worker.php @@ -31,7 +31,7 @@ if (!file_exists("boot.php") && (sizeof($_SERVER["argv"]) != 0)) { require dirname(__DIR__) . '/vendor/autoload.php'; -$basedir = BasePath::create(dirname(__DIR__)); +$basedir = BasePath::create(dirname(__DIR__), $_SERVER); $configLoader = new Config\ConfigCacheLoader($basedir); $config = Factory\ConfigFactory::createCache($configLoader); $logger = Factory\LoggerFactory::create('worker', $config); diff --git a/index.php b/index.php index 11b7879991..7e7396785f 100644 --- a/index.php +++ b/index.php @@ -15,7 +15,7 @@ if (!file_exists(__DIR__ . '/vendor/autoload.php')) { require __DIR__ . '/vendor/autoload.php'; -$basedir = BasePath::create(__DIR__); +$basedir = BasePath::create(__DIR__, $_SERVER); $configLoader = new Config\ConfigCacheLoader($basedir); $config = Factory\ConfigFactory::createCache($configLoader); $logger = Factory\LoggerFactory::create('index', $config); diff --git a/src/App.php b/src/App.php index 5d557738da..38d41cfcf8 100644 --- a/src/App.php +++ b/src/App.php @@ -387,7 +387,7 @@ class App Core\Hook::loadHooks(); $loader = new ConfigCacheLoader($this->basePath); Core\Hook::callAll('load_config', $loader); - $this->config->loadConfigArray($loader->loadAddonConfig(), true); + $this->config->loadConfigArray($loader->loadCoreConfig('addon'), true); } $this->loadDefaultTimezone(); diff --git a/src/Core/Config/ConfigCache.php b/src/Core/Config/ConfigCache.php index dba2a9dd11..e03d352566 100644 --- a/src/Core/Config/ConfigCache.php +++ b/src/Core/Config/ConfigCache.php @@ -11,24 +11,14 @@ namespace Friendica\Core\Config; */ class ConfigCache implements IConfigCache, IPConfigCache { - /** - * NEVER, EVER use this public config array outside of the class - * It is only public due to backward compatibility to .htconfig.php - * - * @var array The cached config array - */ - public $config; + private $config; /** * @param array $config A initial config array */ public function __construct(array $config = []) { - $this->config = []; - - if (isset($config)) { - $this->loadConfigArray($config, true); - } + $this->config = $config; } /** diff --git a/src/Core/Config/ConfigCacheLoader.php b/src/Core/Config/ConfigCacheLoader.php index 58647e5aec..5521349376 100644 --- a/src/Core/Config/ConfigCacheLoader.php +++ b/src/Core/Config/ConfigCacheLoader.php @@ -40,8 +40,8 @@ class ConfigCacheLoader // Setting at least the basepath we know $config->set('system', 'basepath', $this->baseDir); - $config->loadConfigArray($this->loadConfigFile('defaults')); - $config->loadConfigArray($this->loadConfigFile('settings')); + $config->loadConfigArray($this->loadCoreConfig('defaults')); + $config->loadConfigArray($this->loadCoreConfig('settings')); // Legacy .htconfig.php support if (file_exists($this->baseDir . '/.htpreconfig.php')) { @@ -82,16 +82,11 @@ class ConfigCacheLoader } } - if (file_exists($this->baseDir . '/config/local.config.php')) { - $config->loadConfigArray($this->loadConfigFile('local'), true); - } elseif (file_exists($this->baseDir . '/config/local.ini.php')) { - $config->loadConfigArray($this->loadINIConfigFile('local'), true); - } + $config->loadConfigArray($this->loadCoreConfig('local'), true); } /** - * Tries to load the specified legacy configuration file into the App->config array. - * Doesn't overwrite previously set values by default to prevent default config files to supersede DB Config. + * Tries to load the specified legacy configuration file into the ConfigCache (@see ConfigCache ). * * @deprecated since version 2018.12 * @param string $filename @@ -119,8 +114,7 @@ class ConfigCacheLoader } /** - * Tries to load the specified configuration file into the App->config array. - * Doesn't overwrite previously set values by default to prevent default config files to supersede DB Config. + * Tries to load the specified configuration file and returns the config array. * * The config format is PHP array and the template for configuration files is the following: * @@ -130,19 +124,13 @@ class ConfigCacheLoader * ], * ]; * - * @param string $filename - * @param bool $addon True, if a config for an addon should be loaded - * @return array The configuration - * @throws \Exception + * @param string $filepath The filepath of the + * @return array The config array0 + * + * @throws \Exception if the config cannot get loaded. */ - public function loadConfigFile($filename, $addon = false) + private function loadConfigFile($filepath) { - if ($addon) { - $filepath = $this->baseDir . Addon::DIRECTORY . $filename . self::SUBDIRECTORY . $filename . ".config.php"; - } else { - $filepath = $this->configDir . $filename . ".config.php"; - } - if (!file_exists($filepath)) { throw new \Exception('Error loading non-existent config file ' . $filepath); } @@ -157,22 +145,43 @@ class ConfigCacheLoader } /** - * Loads addons configuration files + * Tries to load the specified core-configuration and returns the config array. + * + * @param string $name The name of the configuration + * + * @return array The config array (empty if no config found) + * + * @throws \Exception if the configuration file isn't readable + */ + public function loadCoreConfig($name) + { + if (file_exists($this->configDir . $name . '.config.php')) { + return $this->loadConfigFile($this->configDir . $name . '.config.php'); + } elseif (file_exists($this->configDir . $name . '.ini.php')) { + return $this->loadINIConfigFile($this->configDir . $name . '.ini.php'); + } else { + return []; + } + } + + /** + * Tries to load the specified addon-configuration and returns the config array. * * First loads all activated addons default configuration through the load_config hook, then load the local.config.php * again to overwrite potential local addon configuration. * - * @return array The config array + * @param string $name The name of the configuration * - * @throws \Exception + * @return array The config array (empty if no config found) + * + * @throws \Exception if the configuration file isn't readable */ - public function loadAddonConfig() + public function loadAddonConfig($name) { - // Load the local addon config file to overwritten default addon config values - if (file_exists($this->configDir . 'addon.config.php')) { - return $this->loadConfigFile('addon'); - } elseif (file_exists($this->configDir . 'addon.ini.php')) { - return $this->loadINIConfigFile('addon'); + $filepath = $this->baseDir . Addon::DIRECTORY . $name . self::SUBDIRECTORY . $name . ".config.php"; + + if (file_exists($filepath)) { + return $this->loadConfigFile($filepath); } else { return []; } diff --git a/src/Util/BasePath.php b/src/Util/BasePath.php index 56b0fa1fe9..fecc63a2ab 100644 --- a/src/Util/BasePath.php +++ b/src/Util/BasePath.php @@ -12,23 +12,24 @@ class BasePath * It first checks for the internal variable, then for DOCUMENT_ROOT and * finally for PWD * - * @param string|null $basepath + * @param string|null $basePath The default base path + * @param array $server server arguments * * @return string * * @throws \Exception if directory isn't usable */ - public static function create($basepath) + public static function create($basePath, $server = []) { - if (!$basepath && !empty($_SERVER['DOCUMENT_ROOT'])) { - $basepath = $_SERVER['DOCUMENT_ROOT']; + if (!$basePath && !empty($server['DOCUMENT_ROOT'])) { + $basePath = $server['DOCUMENT_ROOT']; } - if (!$basepath && !empty($_SERVER['PWD'])) { - $basepath = $_SERVER['PWD']; + if (!$basePath && !empty($server['PWD'])) { + $basePath = $server['PWD']; } - return self::getRealPath($basepath); + return self::getRealPath($basePath); } /** @@ -52,7 +53,6 @@ class BasePath } } - /** * @brief Checks if a given directory is usable for the system * From b79bd63231554b386e7fffdc03a914395fe67d20 Mon Sep 17 00:00:00 2001 From: Philipp Holzer Date: Tue, 5 Feb 2019 22:30:18 +0100 Subject: [PATCH 23/31] move isDirectoryUsable to System --- boot.php | 15 ++++++++------- src/App.php | 3 +-- src/Core/System.php | 38 ++++++++++++++++++++++++++++++++++++++ src/Util/BasePath.php | 40 ---------------------------------------- 4 files changed, 47 insertions(+), 49 deletions(-) diff --git a/boot.php b/boot.php index d812724c7b..318798e324 100644 --- a/boot.php +++ b/boot.php @@ -22,6 +22,7 @@ use Friendica\BaseObject; use Friendica\Core\Config; use Friendica\Core\PConfig; use Friendica\Core\Protocol; +use Friendica\Core\System; use Friendica\Database\DBA; use Friendica\Model\Contact; use Friendica\Util\BasePath; @@ -634,7 +635,7 @@ function get_temppath() $temppath = Config::get("system", "temppath"); - if (($temppath != "") && BasePath::isDirectoryUsable($temppath)) { + if (($temppath != "") && System::isDirectoryUsable($temppath)) { // We have a temp path and it is usable return BasePath::getRealPath($temppath); } @@ -643,7 +644,7 @@ function get_temppath() $temppath = sys_get_temp_dir(); // Check if it is usable - if (($temppath != "") && BasePath::isDirectoryUsable($temppath)) { + if (($temppath != "") && System::isDirectoryUsable($temppath)) { // Always store the real path, not the path through symlinks $temppath = BasePath::getRealPath($temppath); @@ -654,7 +655,7 @@ function get_temppath() mkdir($new_temppath); } - if (BasePath::isDirectoryUsable($new_temppath)) { + if (System::isDirectoryUsable($new_temppath)) { // The new path is usable, we are happy Config::set("system", "temppath", $new_temppath); return $new_temppath; @@ -736,7 +737,7 @@ function get_itemcachepath() } $itemcache = Config::get('system', 'itemcache'); - if (($itemcache != "") && BasePath::isDirectoryUsable($itemcache)) { + if (($itemcache != "") && System::isDirectoryUsable($itemcache)) { return BasePath::getRealPath($itemcache); } @@ -748,7 +749,7 @@ function get_itemcachepath() mkdir($itemcache); } - if (BasePath::isDirectoryUsable($itemcache)) { + if (System::isDirectoryUsable($itemcache)) { Config::set("system", "itemcache", $itemcache); return $itemcache; } @@ -764,7 +765,7 @@ function get_itemcachepath() function get_spoolpath() { $spoolpath = Config::get('system', 'spoolpath'); - if (($spoolpath != "") && BasePath::isDirectoryUsable($spoolpath)) { + if (($spoolpath != "") && System::isDirectoryUsable($spoolpath)) { // We have a spool path and it is usable return $spoolpath; } @@ -779,7 +780,7 @@ function get_spoolpath() mkdir($spoolpath); } - if (BasePath::isDirectoryUsable($spoolpath)) { + if (System::isDirectoryUsable($spoolpath)) { // The new path is usable, we are happy Config::set("system", "spoolpath", $spoolpath); return $spoolpath; diff --git a/src/App.php b/src/App.php index 38d41cfcf8..8068a1530b 100644 --- a/src/App.php +++ b/src/App.php @@ -13,7 +13,6 @@ use Friendica\Core\Config\ConfigCacheLoader; use Friendica\Database\DBA; use Friendica\Factory\ConfigFactory; use Friendica\Network\HTTPException\InternalServerErrorException; -use Friendica\Util\BasePath; use Psr\Log\LoggerInterface; /** @@ -194,7 +193,7 @@ class App $this->logger = $logger; $this->basePath = $this->config->get('system', 'basepath'); - if (!BasePath::isDirectoryUsable($this->basePath, false)) { + if (!Core\System::isDirectoryUsable($this->basePath, false)) { throw new Exception('Basepath ' . $this->basePath . ' isn\'t usable.'); } $this->basePath = rtrim($this->basePath, DIRECTORY_SEPARATOR); diff --git a/src/Core/System.php b/src/Core/System.php index c1d23a9ea1..f0ed083573 100644 --- a/src/Core/System.php +++ b/src/Core/System.php @@ -303,6 +303,44 @@ class System extends BaseObject return $processUser['name']; } + /** + * @brief Checks if a given directory is usable for the system + * + * @param $directory + * @param bool $check_writable + * + * @return boolean the directory is usable + */ + public static function isDirectoryUsable($directory, $check_writable = true) + { + if ($directory == '') { + Logger::log('Directory is empty. This shouldn\'t happen.', Logger::DEBUG); + return false; + } + + if (!file_exists($directory)) { + Logger::log('Path "' . $directory . '" does not exist for user ' . static::getUser(), Logger::DEBUG); + return false; + } + + if (is_file($directory)) { + Logger::log('Path "' . $directory . '" is a file for user ' . static::getUser(), Logger::DEBUG); + return false; + } + + if (!is_dir($directory)) { + Logger::log('Path "' . $directory . '" is not a directory for user ' . static::getUser(), Logger::DEBUG); + return false; + } + + if ($check_writable && !is_writable($directory)) { + Logger::log('Path "' . $directory . '" is not writable for user ' . static::getUser(), Logger::DEBUG); + return false; + } + + return true; + } + /// @todo Move the following functions from boot.php /* function killme() diff --git a/src/Util/BasePath.php b/src/Util/BasePath.php index fecc63a2ab..a2849831eb 100644 --- a/src/Util/BasePath.php +++ b/src/Util/BasePath.php @@ -2,8 +2,6 @@ namespace Friendica\Util; -use Friendica\Core; - class BasePath { /** @@ -52,42 +50,4 @@ class BasePath return $path; } } - - /** - * @brief Checks if a given directory is usable for the system - * - * @param $directory - * @param bool $check_writable - * - * @return boolean the directory is usable - */ - public static function isDirectoryUsable($directory, $check_writable = true) - { - if ($directory == '') { - Core\Logger::log('Directory is empty. This shouldn\'t happen.', Core\Logger::DEBUG); - return false; - } - - if (!file_exists($directory)) { - Core\Logger::log('Path "' . $directory . '" does not exist for user ' . Core\System::getUser(), Core\Logger::DEBUG); - return false; - } - - if (is_file($directory)) { - Core\Logger::log('Path "' . $directory . '" is a file for user ' . Core\System::getUser(), Core\Logger::DEBUG); - return false; - } - - if (!is_dir($directory)) { - Core\Logger::log('Path "' . $directory . '" is not a directory for user ' . Core\System::getUser(), Core\Logger::DEBUG); - return false; - } - - if ($check_writable && !is_writable($directory)) { - Core\Logger::log('Path "' . $directory . '" is not writable for user ' . Core\System::getUser(), Core\Logger::DEBUG); - return false; - } - - return true; - } } From ef16e1a037019e8539fa6fae5cd9242fc4162a7f Mon Sep 17 00:00:00 2001 From: Philipp Holzer Date: Tue, 5 Feb 2019 22:56:57 +0100 Subject: [PATCH 24/31] Adding unittest for empty setApp() --- src/BaseObject.php | 2 +- tests/src/BaseObjectTest.php | 21 +++++++++++++++++---- 2 files changed, 18 insertions(+), 5 deletions(-) diff --git a/src/BaseObject.php b/src/BaseObject.php index 1a23408ba1..4a6fa12d24 100644 --- a/src/BaseObject.php +++ b/src/BaseObject.php @@ -28,7 +28,7 @@ class BaseObject public static function getApp() { if (empty(self::$app)) { - throw new InternalServerErrorException('App isn\' initialized.'); + throw new InternalServerErrorException('App isn\'t initialized.'); } return self::$app; diff --git a/tests/src/BaseObjectTest.php b/tests/src/BaseObjectTest.php index 2dbf5580f6..b2c73780a4 100644 --- a/tests/src/BaseObjectTest.php +++ b/tests/src/BaseObjectTest.php @@ -31,10 +31,6 @@ class BaseObjectTest extends TestCase */ protected function setUp() { - $this->setUpVfsDir(); - $configMock = \Mockery::mock('Friendica\Core\Config\ConfigCache'); - $this->mockApp($this->root, $configMock); - $this->baseObject = new BaseObject(); } @@ -44,6 +40,10 @@ class BaseObjectTest extends TestCase */ public function testGetApp() { + $this->setUpVfsDir(); + $configMock = \Mockery::mock('Friendica\Core\Config\ConfigCache'); + $this->mockApp($this->root, $configMock); + $this->assertInstanceOf(App::class, $this->baseObject->getApp()); } @@ -53,7 +53,20 @@ class BaseObjectTest extends TestCase */ public function testSetApp() { + $this->setUpVfsDir(); + $configMock = \Mockery::mock('Friendica\Core\Config\ConfigCache'); + $this->mockApp($this->root, $configMock); + $this->assertNull($this->baseObject->setApp($this->app)); $this->assertEquals($this->app, $this->baseObject->getApp()); } + + /** + * Test the getApp() function without App + * @expectedException Friendica\Network\HTTPException\InternalServerErrorException + */ + public function testGetAppFailed() + { + BaseObject::getApp(); + } } From 87acace6605fdd01f31e1ac3bf1956fe47b50409 Mon Sep 17 00:00:00 2001 From: Philipp Holzer Date: Tue, 5 Feb 2019 23:06:28 +0100 Subject: [PATCH 25/31] removing code for now --- mod/friendica.php | 4 ++-- src/LegacyModule.php | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/mod/friendica.php b/mod/friendica.php index e960f575e5..77daabd150 100644 --- a/mod/friendica.php +++ b/mod/friendica.php @@ -12,7 +12,7 @@ use Friendica\Core\System; use Friendica\Database\DBA; use Friendica\Module\Register; -function friendica_init(App $a, Config\ConfigCache $config) +function friendica_init(App $a) { if (!empty($a->argv[1]) && ($a->argv[1] == "json")) { $register_policies = [ @@ -29,7 +29,7 @@ function friendica_init(App $a, Config\ConfigCache $config) } $sql_extra = ''; - if ($config->get('config', 'admin_nickname') !== null) { + if (Config::get('config', 'admin_nickname') !== null) { $sql_extra = sprintf(" AND `nickname` = '%s' ", DBA::escape(Config::get('config', 'admin_nickname'))); } if (!empty(Config::get('config', 'admin_email'))) { diff --git a/src/LegacyModule.php b/src/LegacyModule.php index 4fdfc17d9f..a0b23a5419 100644 --- a/src/LegacyModule.php +++ b/src/LegacyModule.php @@ -68,7 +68,7 @@ class LegacyModule extends BaseModule if (\function_exists($function_name)) { $a = self::getApp(); - return $function_name($a, $a->getConfig()); + return $function_name($a); } else { return parent::{$function_suffix}(); } From 40d8b047957ec6bfa47d4f6bdad0c361dc74fd52 Mon Sep 17 00:00:00 2001 From: Philipp Holzer Date: Tue, 5 Feb 2019 23:09:57 +0100 Subject: [PATCH 26/31] using Config::get (automatically use the right cache) --- mod/friendica.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/mod/friendica.php b/mod/friendica.php index 77daabd150..80d5f34cc8 100644 --- a/mod/friendica.php +++ b/mod/friendica.php @@ -48,7 +48,7 @@ function friendica_init(App $a) Config::load('feature_lock'); $locked_features = []; - $featureLock = $config->get('config', 'feature_lock'); + $featureLock = Config::get('config', 'feature_lock'); if (isset($featureLock)) { foreach ($featureLock as $k => $v) { if ($k === 'config_loaded') { From d9e38be4df399b58abaf8b2104dde506df7a4b1d Mon Sep 17 00:00:00 2001 From: Philipp Holzer Date: Tue, 5 Feb 2019 23:36:01 +0100 Subject: [PATCH 27/31] Creating legacy config loading method --- src/Core/Addon.php | 2 +- src/Core/Config/ConfigCacheLoader.php | 119 +++++++++++++++----------- 2 files changed, 72 insertions(+), 49 deletions(-) diff --git a/src/Core/Addon.php b/src/Core/Addon.php index e217cf8751..14b163f165 100644 --- a/src/Core/Addon.php +++ b/src/Core/Addon.php @@ -16,7 +16,7 @@ class Addon extends BaseObject * The addon sub-directory * @var string */ - const DIRECTORY = '/addon/'; + const DIRECTORY = 'addon'; /** * List of the names of enabled addons diff --git a/src/Core/Config/ConfigCacheLoader.php b/src/Core/Config/ConfigCacheLoader.php index 5521349376..b95f7aa5a4 100644 --- a/src/Core/Config/ConfigCacheLoader.php +++ b/src/Core/Config/ConfigCacheLoader.php @@ -18,7 +18,7 @@ class ConfigCacheLoader * The Sub directory of the config-files * @var string */ - const SUBDIRECTORY = '/config/'; + const SUBDIRECTORY = 'config'; private $baseDir; private $configDir; @@ -26,7 +26,7 @@ class ConfigCacheLoader public function __construct($baseDir) { $this->baseDir = $baseDir; - $this->configDir = $baseDir . self::SUBDIRECTORY; + $this->configDir = $baseDir . DIRECTORY_SEPARATOR . self::SUBDIRECTORY; } /** @@ -43,60 +43,79 @@ class ConfigCacheLoader $config->loadConfigArray($this->loadCoreConfig('defaults')); $config->loadConfigArray($this->loadCoreConfig('settings')); - // Legacy .htconfig.php support - if (file_exists($this->baseDir . '/.htpreconfig.php')) { - $a = $config; - include $this->baseDir . '/.htpreconfig.php'; - } - - // Legacy .htconfig.php support - if (file_exists($this->baseDir . '/.htconfig.php')) { - $a = $config; - - include $this->baseDir . '/.htconfig.php'; - - $config->set('database', 'hostname', $db_host); - $config->set('database', 'username', $db_user); - $config->set('database', 'password', $db_pass); - $config->set('database', 'database', $db_data); - $charset = $config->get('system', 'db_charset'); - if (isset($charset)) { - $config->set('database', 'charset', $charset); - } - - unset($db_host, $db_user, $db_pass, $db_data); - - if (isset($default_timezone)) { - $config->set('system', 'default_timezone', $default_timezone); - unset($default_timezone); - } - - if (isset($pidfile)) { - $config->set('system', 'pidfile', $pidfile); - unset($pidfile); - } - - if (isset($lang)) { - $config->set('system', 'language', $lang); - unset($lang); - } - } + $config->loadConfigArray($this->loadLegacyConfigFile('htpreconfig'), true); + $config->loadConfigArray($this->loadLegacyConfigFile('htconfig'), true); $config->loadConfigArray($this->loadCoreConfig('local'), true); } /** - * Tries to load the specified legacy configuration file into the ConfigCache (@see ConfigCache ). + * Tries to load the legacy config files (.htconfig.php, .htpreconfig.php) + * + * @param string $name The name of the config file + * @return array The configuration array + * + * @deprecated since version 2018.09 + */ + private function loadLegacyConfigFile($name) + { + $filePath = $this->baseDir . DIRECTORY_SEPARATOR . '.' . $name . '.php'; + + if (file_exists($filePath)) { + $a = new \stdClass(); + $a->config = []; + include $filePath; + + if (isset($db_host)) { + $a->config['database']['hostname'] = $db_host; + unset($db_host); + } + if (isset($db_user)) { + $a->config['database']['username'] = $db_user; + unset($db_user); + } + if (isset($db_pass)) { + $a->config['database']['password'] = $db_pass; + unset($db_pass); + } + if (isset($db_data)) { + $a->config['database']['database'] = $db_data; + unset($db_data); + } + if (isset($a->config['system']['db_charset'])) { + $a->config['database']['charset'] = $a->config['system']['charset']; + } + if (isset($pidfile)) { + $a->config['system']['pidfile'] = $pidfile; + unset($pidfile); + } + if (isset($default_timezone)) { + $a->config['system']['default_timezone'] = $default_timezone; + unset($default_timezone); + } + if (isset($lang)) { + $a->config['system']['language'] = $lang; + unset($lang); + } + + return $a->config; + } else { + return []; + } + } + + /** + * Tries to load the specified legacy configuration file and returns the config array. * * @deprecated since version 2018.12 * @param string $filename * - * @return array The configuration + * @return array The configuration array * @throws \Exception */ public function loadINIConfigFile($filename) { - $filepath = $this->configDir . $filename . ".ini.php"; + $filepath = $this->configDir . DIRECTORY_SEPARATOR . $filename . ".ini.php"; if (!file_exists($filepath)) { throw new \Exception('Error parsing non-existent INI config file ' . $filepath); @@ -155,10 +174,10 @@ class ConfigCacheLoader */ public function loadCoreConfig($name) { - if (file_exists($this->configDir . $name . '.config.php')) { - return $this->loadConfigFile($this->configDir . $name . '.config.php'); - } elseif (file_exists($this->configDir . $name . '.ini.php')) { - return $this->loadINIConfigFile($this->configDir . $name . '.ini.php'); + if (file_exists($this->configDir . DIRECTORY_SEPARATOR . $name . '.config.php')) { + return $this->loadConfigFile($this->configDir . DIRECTORY_SEPARATOR . $name . '.config.php'); + } elseif (file_exists($this->configDir . DIRECTORY_SEPARATOR . $name . '.ini.php')) { + return $this->loadINIConfigFile($this->configDir . DIRECTORY_SEPARATOR . $name . '.ini.php'); } else { return []; } @@ -178,7 +197,11 @@ class ConfigCacheLoader */ public function loadAddonConfig($name) { - $filepath = $this->baseDir . Addon::DIRECTORY . $name . self::SUBDIRECTORY . $name . ".config.php"; + $filepath = $this->baseDir . DIRECTORY_SEPARATOR . // /var/www/html/ + Addon::DIRECTORY . DIRECTORY_SEPARATOR . // addon/ + $name . DIRECTORY_SEPARATOR . // openstreetmap/ + self::SUBDIRECTORY . DIRECTORY_SEPARATOR . // config/ + $name . ".config.php"; // openstreetmap.config.php if (file_exists($filepath)) { return $this->loadConfigFile($filepath); From 62c79e1c4f1d48310b9df102777812a3e2310bae Mon Sep 17 00:00:00 2001 From: Philipp Holzer Date: Tue, 5 Feb 2019 23:42:49 +0100 Subject: [PATCH 28/31] codeblock updates --- src/Core/Config/IConfigAdapter.php | 21 +++------------------ src/Core/Config/IPConfigAdapter.php | 16 +++------------- src/Core/Config/JITConfigAdapter.php | 12 ++++++++++++ src/Core/Config/JITPConfigAdapter.php | 12 ++++++++++++ src/Core/Config/PreloadConfigAdapter.php | 12 ++++++++++++ src/Core/Config/PreloadPConfigAdapter.php | 12 ++++++++++++ 6 files changed, 54 insertions(+), 31 deletions(-) diff --git a/src/Core/Config/IConfigAdapter.php b/src/Core/Config/IConfigAdapter.php index 5bbb61ae80..139483de26 100644 --- a/src/Core/Config/IConfigAdapter.php +++ b/src/Core/Config/IConfigAdapter.php @@ -9,10 +9,7 @@ namespace Friendica\Core\Config; interface IConfigAdapter { /** - * @brief Loads all configuration values into a cached storage. - * - * All configuration values of the system are stored in global cache - * which is available under the global variable Config::$config + * Loads all configuration values into a cached storage. * * @param string $cat The category of the configuration values to load * @@ -21,17 +18,9 @@ interface IConfigAdapter public function load($cat = "config"); /** - * @brief Get a particular user's config variable given the category name + * Get a particular user's config variable given the category name * ($family) and a key. * - * Get a particular config value from the given category ($family) - * and the $key from a cached storage in static::$config[$uid]. - * $instore is only used by the set_config function - * to determine if the key already exists in the DB - * If a key is found in the DB but doesn't exist in - * local config cache, pull it into the cache so we don't have - * to hit the DB again for this item. - * * @param string $cat The category of the configuration value * @param string $k The configuration key to query * @param mixed $default_value optional, The value to return if key is not set (default: null) @@ -42,8 +31,6 @@ interface IConfigAdapter public function get($cat, $k, $default_value = null, $refresh = false); /** - * @brief Sets a configuration value for system config - * * Stores a config value ($value) in the category ($family) under the key ($key) * for the user_id $uid. * @@ -58,9 +45,7 @@ interface IConfigAdapter public function set($cat, $k, $value); /** - * @brief Deletes the given key from the system configuration. - * - * Removes the configured value from the stored cache in Config::$config + * Removes the configured value from the stored cache * and removes it from the database. * * @param string $cat The category of the configuration value diff --git a/src/Core/Config/IPConfigAdapter.php b/src/Core/Config/IPConfigAdapter.php index f4ad392d7f..e62fc9c93f 100644 --- a/src/Core/Config/IPConfigAdapter.php +++ b/src/Core/Config/IPConfigAdapter.php @@ -15,10 +15,7 @@ namespace Friendica\Core\Config; interface IPConfigAdapter { /** - * @brief Loads all configuration values of a user's config family into a cached storage. - * - * All configuration values of the given user are stored in global cache - * which is available under the global variable self::$config[$uid]. + * Loads all configuration values of a user's config family into a cached storage. * * @param string $uid The user_id * @param string $cat The category of the configuration value @@ -28,12 +25,9 @@ interface IPConfigAdapter public function load($uid, $cat); /** - * @brief Get a particular user's config variable given the category name + * Get a particular user's config variable given the category name * ($family) and a key. * - * Get a particular user's config value from the given category ($family) - * and the $key from a cached storage in self::$config[$uid]. - * * @param string $uid The user_id * @param string $cat The category of the configuration value * @param string $k The configuration key to query @@ -45,8 +39,6 @@ interface IPConfigAdapter public function get($uid, $cat, $k, $default_value = null, $refresh = false); /** - * @brief Sets a configuration value for a user - * * Stores a config value ($value) in the category ($family) under the key ($key) * for the user_id $uid. * @@ -62,9 +54,7 @@ interface IPConfigAdapter public function set($uid, $cat, $k, $value); /** - * @brief Deletes the given key from the users's configuration. - * - * Removes the configured value from the stored cache in self::$config[$uid] + * Removes the configured value from the stored cache * and removes it from the database. * * @param string $uid The user_id diff --git a/src/Core/Config/JITConfigAdapter.php b/src/Core/Config/JITConfigAdapter.php index 5e7e786f07..e7aecb933b 100644 --- a/src/Core/Config/JITConfigAdapter.php +++ b/src/Core/Config/JITConfigAdapter.php @@ -28,6 +28,9 @@ class JITConfigAdapter implements IConfigAdapter $this->configCache = $configCache; } + /** + * {@inheritdoc} + */ public function load($cat = "config") { // We don't preload "system" anymore. @@ -50,6 +53,9 @@ class JITConfigAdapter implements IConfigAdapter DBA::close($configs); } + /** + * {@inheritdoc} + */ public function get($cat, $k, $default_value = null, $refresh = false) { if (!$refresh) { @@ -92,6 +98,9 @@ class JITConfigAdapter implements IConfigAdapter return $default_value; } + /** + * {@inheritdoc} + */ public function set($cat, $k, $value) { // We store our setting values in a string variable. @@ -129,6 +138,9 @@ class JITConfigAdapter implements IConfigAdapter return $result; } + /** + * {@inheritdoc} + */ public function delete($cat, $k) { if (isset($this->cache[$cat][$k])) { diff --git a/src/Core/Config/JITPConfigAdapter.php b/src/Core/Config/JITPConfigAdapter.php index 2fd7705928..b1a15601cc 100644 --- a/src/Core/Config/JITPConfigAdapter.php +++ b/src/Core/Config/JITPConfigAdapter.php @@ -28,6 +28,9 @@ class JITPConfigAdapter implements IPConfigAdapter $this->configCache = $configCache; } + /** + * {@inheritdoc} + */ public function load($uid, $cat) { $pconfigs = DBA::select('pconfig', ['v', 'k'], ['cat' => $cat, 'uid' => $uid]); @@ -46,6 +49,9 @@ class JITPConfigAdapter implements IPConfigAdapter DBA::close($pconfigs); } + /** + * {@inheritdoc} + */ public function get($uid, $cat, $k, $default_value = null, $refresh = false) { if (!$refresh) { @@ -82,6 +88,9 @@ class JITPConfigAdapter implements IPConfigAdapter } } + /** + * {@inheritdoc} + */ public function set($uid, $cat, $k, $value) { // We store our setting values in a string variable. @@ -109,6 +118,9 @@ class JITPConfigAdapter implements IPConfigAdapter return $result; } + /** + * {@inheritdoc} + */ public function delete($uid, $cat, $k) { $this->configCache->deleteP($uid, $cat, $k); diff --git a/src/Core/Config/PreloadConfigAdapter.php b/src/Core/Config/PreloadConfigAdapter.php index bda9b28aae..d5fbd982bf 100644 --- a/src/Core/Config/PreloadConfigAdapter.php +++ b/src/Core/Config/PreloadConfigAdapter.php @@ -30,6 +30,9 @@ class PreloadConfigAdapter implements IConfigAdapter $this->load(); } + /** + * {@inheritdoc} + */ public function load($family = 'config') { if ($this->config_loaded) { @@ -45,6 +48,9 @@ class PreloadConfigAdapter implements IConfigAdapter $this->config_loaded = true; } + /** + * {@inheritdoc} + */ public function get($cat, $k, $default_value = null, $refresh = false) { if ($refresh) { @@ -59,6 +65,9 @@ class PreloadConfigAdapter implements IConfigAdapter return $return; } + /** + * {@inheritdoc} + */ public function set($cat, $k, $value) { // We store our setting values as strings. @@ -83,6 +92,9 @@ class PreloadConfigAdapter implements IConfigAdapter return true; } + /** + * {@inheritdoc} + */ public function delete($cat, $k) { $this->configCache->delete($cat, $k); diff --git a/src/Core/Config/PreloadPConfigAdapter.php b/src/Core/Config/PreloadPConfigAdapter.php index b49f39382f..af97815ade 100644 --- a/src/Core/Config/PreloadPConfigAdapter.php +++ b/src/Core/Config/PreloadPConfigAdapter.php @@ -34,6 +34,9 @@ class PreloadPConfigAdapter implements IPConfigAdapter } } + /** + * {@inheritdoc} + */ public function load($uid, $family) { if ($this->config_loaded) { @@ -53,6 +56,9 @@ class PreloadPConfigAdapter implements IPConfigAdapter $this->config_loaded = true; } + /** + * {@inheritdoc} + */ public function get($uid, $cat, $k, $default_value = null, $refresh = false) { if (!$this->config_loaded) { @@ -71,6 +77,9 @@ class PreloadPConfigAdapter implements IPConfigAdapter return $this->configCache->getP($uid, $cat, $k, $default_value);; } + /** + * {@inheritdoc} + */ public function set($uid, $cat, $k, $value) { if (!$this->config_loaded) { @@ -98,6 +107,9 @@ class PreloadPConfigAdapter implements IPConfigAdapter return true; } + /** + * {@inheritdoc} + */ public function delete($uid, $cat, $k) { if (!$this->config_loaded) { From 3cd654e76f32dbcf505aef6a60a3e42d318f8b61 Mon Sep 17 00:00:00 2001 From: Philipp Holzer Date: Tue, 5 Feb 2019 23:47:40 +0100 Subject: [PATCH 29/31] bugfixing ini-loading --- src/Core/Config/ConfigCacheLoader.php | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) diff --git a/src/Core/Config/ConfigCacheLoader.php b/src/Core/Config/ConfigCacheLoader.php index b95f7aa5a4..768e30e242 100644 --- a/src/Core/Config/ConfigCacheLoader.php +++ b/src/Core/Config/ConfigCacheLoader.php @@ -108,15 +108,13 @@ class ConfigCacheLoader * Tries to load the specified legacy configuration file and returns the config array. * * @deprecated since version 2018.12 - * @param string $filename + * @param string $filepath * * @return array The configuration array * @throws \Exception */ - public function loadINIConfigFile($filename) + public function loadINIConfigFile($filepath) { - $filepath = $this->configDir . DIRECTORY_SEPARATOR . $filename . ".ini.php"; - if (!file_exists($filepath)) { throw new \Exception('Error parsing non-existent INI config file ' . $filepath); } From 7947db8537cacbf9d63cc320c5482e8dcef7f72a Mon Sep 17 00:00:00 2001 From: Philipp Holzer Date: Tue, 5 Feb 2019 23:58:38 +0100 Subject: [PATCH 30/31] codeblock updates --- src/Core/Config/ConfigCacheLoader.php | 3 --- 1 file changed, 3 deletions(-) diff --git a/src/Core/Config/ConfigCacheLoader.php b/src/Core/Config/ConfigCacheLoader.php index 768e30e242..dd753458b1 100644 --- a/src/Core/Config/ConfigCacheLoader.php +++ b/src/Core/Config/ConfigCacheLoader.php @@ -184,9 +184,6 @@ class ConfigCacheLoader /** * Tries to load the specified addon-configuration and returns the config array. * - * First loads all activated addons default configuration through the load_config hook, then load the local.config.php - * again to overwrite potential local addon configuration. - * * @param string $name The name of the configuration * * @return array The config array (empty if no config found) From fcd7627c491739d2b9ae4bea50204126ffb3a450 Mon Sep 17 00:00:00 2001 From: Philipp Holzer Date: Wed, 6 Feb 2019 00:02:25 +0100 Subject: [PATCH 31/31] method refactoring & docblock --- src/Core/Config/ConfigCacheLoader.php | 101 +++++++++++++------------- 1 file changed, 51 insertions(+), 50 deletions(-) diff --git a/src/Core/Config/ConfigCacheLoader.php b/src/Core/Config/ConfigCacheLoader.php index dd753458b1..0b8761415c 100644 --- a/src/Core/Config/ConfigCacheLoader.php +++ b/src/Core/Config/ConfigCacheLoader.php @@ -43,21 +43,66 @@ class ConfigCacheLoader $config->loadConfigArray($this->loadCoreConfig('defaults')); $config->loadConfigArray($this->loadCoreConfig('settings')); - $config->loadConfigArray($this->loadLegacyConfigFile('htpreconfig'), true); - $config->loadConfigArray($this->loadLegacyConfigFile('htconfig'), true); + $config->loadConfigArray($this->loadLegacyConfig('htpreconfig'), true); + $config->loadConfigArray($this->loadLegacyConfig('htconfig'), true); $config->loadConfigArray($this->loadCoreConfig('local'), true); } /** - * Tries to load the legacy config files (.htconfig.php, .htpreconfig.php) + * Tries to load the specified core-configuration and returns the config array. + * + * @param string $name The name of the configuration + * + * @return array The config array (empty if no config found) + * + * @throws \Exception if the configuration file isn't readable + */ + public function loadCoreConfig($name) + { + if (file_exists($this->configDir . DIRECTORY_SEPARATOR . $name . '.config.php')) { + return $this->loadConfigFile($this->configDir . DIRECTORY_SEPARATOR . $name . '.config.php'); + } elseif (file_exists($this->configDir . DIRECTORY_SEPARATOR . $name . '.ini.php')) { + return $this->loadINIConfigFile($this->configDir . DIRECTORY_SEPARATOR . $name . '.ini.php'); + } else { + return []; + } + } + + /** + * Tries to load the specified addon-configuration and returns the config array. + * + * @param string $name The name of the configuration + * + * @return array The config array (empty if no config found) + * + * @throws \Exception if the configuration file isn't readable + */ + public function loadAddonConfig($name) + { + $filepath = $this->baseDir . DIRECTORY_SEPARATOR . // /var/www/html/ + Addon::DIRECTORY . DIRECTORY_SEPARATOR . // addon/ + $name . DIRECTORY_SEPARATOR . // openstreetmap/ + self::SUBDIRECTORY . DIRECTORY_SEPARATOR . // config/ + $name . ".config.php"; // openstreetmap.config.php + + if (file_exists($filepath)) { + return $this->loadConfigFile($filepath); + } else { + return []; + } + } + + /** + * Tries to load the legacy config files (.htconfig.php, .htpreconfig.php) and returns the config array. * * @param string $name The name of the config file - * @return array The configuration array + * + * @return array The configuration array (empty if no config found) * * @deprecated since version 2018.09 */ - private function loadLegacyConfigFile($name) + private function loadLegacyConfig($name) { $filePath = $this->baseDir . DIRECTORY_SEPARATOR . '.' . $name . '.php'; @@ -113,7 +158,7 @@ class ConfigCacheLoader * @return array The configuration array * @throws \Exception */ - public function loadINIConfigFile($filepath) + private function loadINIConfigFile($filepath) { if (!file_exists($filepath)) { throw new \Exception('Error parsing non-existent INI config file ' . $filepath); @@ -160,48 +205,4 @@ class ConfigCacheLoader return $config; } - - /** - * Tries to load the specified core-configuration and returns the config array. - * - * @param string $name The name of the configuration - * - * @return array The config array (empty if no config found) - * - * @throws \Exception if the configuration file isn't readable - */ - public function loadCoreConfig($name) - { - if (file_exists($this->configDir . DIRECTORY_SEPARATOR . $name . '.config.php')) { - return $this->loadConfigFile($this->configDir . DIRECTORY_SEPARATOR . $name . '.config.php'); - } elseif (file_exists($this->configDir . DIRECTORY_SEPARATOR . $name . '.ini.php')) { - return $this->loadINIConfigFile($this->configDir . DIRECTORY_SEPARATOR . $name . '.ini.php'); - } else { - return []; - } - } - - /** - * Tries to load the specified addon-configuration and returns the config array. - * - * @param string $name The name of the configuration - * - * @return array The config array (empty if no config found) - * - * @throws \Exception if the configuration file isn't readable - */ - public function loadAddonConfig($name) - { - $filepath = $this->baseDir . DIRECTORY_SEPARATOR . // /var/www/html/ - Addon::DIRECTORY . DIRECTORY_SEPARATOR . // addon/ - $name . DIRECTORY_SEPARATOR . // openstreetmap/ - self::SUBDIRECTORY . DIRECTORY_SEPARATOR . // config/ - $name . ".config.php"; // openstreetmap.config.php - - if (file_exists($filepath)) { - return $this->loadConfigFile($filepath); - } else { - return []; - } - } }