Merge pull request #6581 from nupplaphil/config_refact

Config Refactoring
This commit is contained in:
Hypolite Petovan 2019-02-06 09:57:41 -05:00 committed by GitHub
commit a0b14a46cb
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
50 changed files with 1168 additions and 777 deletions

View file

@ -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
*

View file

@ -8,8 +8,9 @@
*/
namespace Friendica\Core;
use Friendica\App;
use Friendica\BaseObject;
use Friendica\Core\Config\ConfigCache;
use Friendica\Core\Config\IConfigAdapter;
use Friendica\Core\Config\IConfigCache;
/**
* @brief Arbitrary system configuration storage
@ -18,49 +19,53 @@ 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
{
/**
* @var \Friendica\Core\Config\IConfigAdapter
* @var Config\IConfigAdapter
*/
private static $adapter = null;
private static $adapter;
public static function init()
/**
* @var Config\IConfigCache
*/
private static $cache;
/**
* Initialize the config with only the cache
*
* @param Config\IConfigCache $cache The configuration cache
*/
public static function init(Config\IConfigCache $cache)
{
// Database isn't ready or populated yet
if (!self::getApp()->getMode()->has(App\Mode::DBCONFIGAVAILABLE)) {
return;
}
self::$cache = $cache;
}
if (self::getApp()->getConfigValue('system', 'config_adapter') == 'preload') {
self::$adapter = new Config\PreloadConfigAdapter();
} else {
self::$adapter = new Config\JITConfigAdapter();
}
/**
* Add the adapter for DB-backend
*
* @param Config\IConfigAdapter $adapter
*/
public static function setAdapter(Config\IConfigAdapter $adapter)
{
self::$adapter = $adapter;
}
/**
* @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
* All configuration values of the system are stored in the cache ( @see IConfigCache )
*
* @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);
}
@ -69,12 +74,8 @@ 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].
* $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
@ -82,17 +83,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::getApp()->getConfigValue($family, $key, $default_value);
}
if (empty(self::$adapter)) {
self::init();
if (!isset(self::$adapter)) {
return self::$cache->get($family, $key, $default_value);
}
return self::$adapter->get($family, $key, $default_value, $refresh);
@ -102,7 +97,6 @@ class Config extends BaseObject
* @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!
*
@ -111,17 +105,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::$cache->set($family, $key, $value);
return true;
}
return self::$adapter->set($family, $key, $value);
@ -130,24 +119,18 @@ class Config extends BaseObject
/**
* @brief Deletes the given key from the system configuration.
*
* Removes the configured value from the stored cache in $a->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
*
* @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::$cache->delete($family, $key);
}
return self::$adapter->delete($family, $key);

View file

@ -0,0 +1,173 @@
<?php
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
{
private $config;
/**
* @param array $config A initial config array
*/
public function __construct(array $config = [])
{
$this->config = $config;
}
/**
* 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) {
$this->set($category, $key, $value);
} else {
$this->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])) {
$this->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;
}
}

View file

@ -0,0 +1,208 @@
<?php
namespace Friendica\Core\Config;
use Friendica\Core\Addon;
/**
* 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 . DIRECTORY_SEPARATOR . self::SUBDIRECTORY;
}
/**
* 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->loadCoreConfig('defaults'));
$config->loadConfigArray($this->loadCoreConfig('settings'));
$config->loadConfigArray($this->loadLegacyConfig('htpreconfig'), true);
$config->loadConfigArray($this->loadLegacyConfig('htconfig'), true);
$config->loadConfigArray($this->loadCoreConfig('local'), true);
}
/**
* 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 (empty if no config found)
*
* @deprecated since version 2018.09
*/
private function loadLegacyConfig($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 $filepath
*
* @return array The configuration array
* @throws \Exception
*/
private function loadINIConfigFile($filepath)
{
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 and returns the config array.
*
* The config format is PHP array and the template for configuration files is the following:
*
* <?php return [
* 'section' => [
* 'key' => 'value',
* ],
* ];
*
* @param string $filepath The filepath of the
* @return array The config array0
*
* @throws \Exception if the config cannot get loaded.
*/
private function loadConfigFile($filepath)
{
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;
}
}

View file

@ -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 $a->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 $a->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 $a->config
* Removes the configured value from the stored cache
* and removes it from the database.
*
* @param string $cat The category of the configuration value

View file

@ -0,0 +1,37 @@
<?php
namespace Friendica\Core\Config;
/**
* The interface for a system-wide ConfigCache
*/
interface IConfigCache
{
/**
* @param string $cat Config category
* @param string $key Config key
* @param mixed $default Default value if it isn't set
*
* @return mixed Returns the value of the Config entry
*/
function get($cat, $key = null, $default = null);
/**
* Sets a value in the config cache. Accepts raw output from the config table
*
* @param string $cat Config category
* @param string $key Config key
* @param mixed $value Value to set
*/
function set($cat, $key, $value);
/**
* Deletes a value from the config cache
*
* @param string $cat Config category
* @param string $key Config key
*/
function delete($cat, $key);
function getAll();
}

View file

@ -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 $a->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 $a->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 $a->config[$uid]
* Removes the configured value from the stored cache
* and removes it from the database.
*
* @param string $uid The user_id

View file

@ -0,0 +1,44 @@
<?php
namespace Friendica\Core\Config;
/**
* The interface for a user-specific config cache
*/
interface IPConfigCache
{
/**
* Retrieves a value from the user config cache
*
* @param int $uid User Id
* @param string $cat Config category
* @param string $key Config key
* @param mixed $default Default value if key isn't set
*
* @return string The value of the config entry
*/
function getP($uid, $cat, $key = null, $default = null);
/**
* 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 $key Config key
* @param mixed $value Value to set
*/
function setP($uid, $cat, $key, $value);
/**
* Deletes a value from the user config cache
*
* @param int $uid User Id
* @param string $cat Config category
* @param string $key Config key
*/
function deleteP($uid, $cat, $key);
function getAll();
}

View file

@ -1,7 +1,6 @@
<?php
namespace Friendica\Core\Config;
use Friendica\BaseObject;
use Friendica\Database\DBA;
/**
@ -11,11 +10,27 @@ use Friendica\Database\DBA;
*
* @author Hypolite Petovan <hypolite@mrpetovan.com>
*/
class JITConfigAdapter extends BaseObject implements IConfigAdapter
class JITConfigAdapter implements IConfigAdapter
{
private $cache;
private $in_db;
/**
* @var IConfigCache The config cache of this driver
*/
private $configCache;
/**
* @param IConfigCache $configCache The config cache of this driver
*/
public function __construct(IConfigCache $configCache)
{
$this->configCache = $configCache;
}
/**
* {@inheritdoc}
*/
public function load($cat = "config")
{
// We don't preload "system" anymore.
@ -28,7 +43,7 @@ class JITConfigAdapter extends BaseObject implements IConfigAdapter
while ($config = DBA::fetch($configs)) {
$k = $config['k'];
self::getApp()->setConfigValue($cat, $k, $config['v']);
$this->configCache->set($cat, $k, $config['v']);
if ($cat !== 'config') {
$this->cache[$cat][$k] = $config['v'];
@ -38,10 +53,11 @@ class JITConfigAdapter extends BaseObject implements IConfigAdapter
DBA::close($configs);
}
/**
* {@inheritdoc}
*/
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 +78,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 ($this->configCache->get($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] = $this->configCache->get($cat, $k);
$this->in_db[$cat][$k] = false;
return $a->config[$cat][$k];
} elseif (isset($a->config[$k])) {
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] = $a->config[$k];
$this->cache[$k] = $this->configCache->get('config', $k);
$this->in_db[$k] = false;
return $a->config[$k];
return $this->configCache->get('config', $k);
}
$this->cache[$cat][$k] = '!<unset>!';
@ -82,6 +98,9 @@ class JITConfigAdapter extends BaseObject implements IConfigAdapter
return $default_value;
}
/**
* {@inheritdoc}
*/
public function set($cat, $k, $value)
{
// We store our setting values in a string variable.
@ -102,7 +121,7 @@ class JITConfigAdapter extends BaseObject implements IConfigAdapter
return true;
}
self::getApp()->setConfigValue($cat, $k, $value);
$this->configCache->set($cat, $k, $value);
// Assign the just added value to the cache
$this->cache[$cat][$k] = $dbvalue;
@ -119,6 +138,9 @@ class JITConfigAdapter extends BaseObject implements IConfigAdapter
return $result;
}
/**
* {@inheritdoc}
*/
public function delete($cat, $k)
{
if (isset($this->cache[$cat][$k])) {

View file

@ -1,7 +1,6 @@
<?php
namespace Friendica\Core\Config;
use Friendica\BaseObject;
use Friendica\Database\DBA;
/**
@ -11,47 +10,63 @@ use Friendica\Database\DBA;
*
* @author Hypolite Petovan <hypolite@mrpetovan.com>
*/
class JITPConfigAdapter extends BaseObject implements IPConfigAdapter
class JITPConfigAdapter implements IPConfigAdapter
{
private $in_db;
/**
* The config cache of this adapter
* @var IPConfigCache
*/
private $configCache;
/**
* @param IPConfigCache $configCache The config cache of this adapter
*/
public function __construct(IPConfigCache $configCache)
{
$this->configCache = $configCache;
}
/**
* {@inheritdoc}
*/
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']);
$this->configCache->setP($uid, $cat, $k, $pconfig['v']);
$this->in_db[$uid][$cat][$k] = true;
}
} else if ($cat != 'config') {
// Negative caching
$a->config[$uid][$cat] = "!<unset>!";
$this->configCache->setP($uid, $cat, null, "!<unset>!");
}
DBA::close($pconfigs);
}
/**
* {@inheritdoc}
*/
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] === '!<unset>!') {
if ($this->configCache->getP($uid, $cat) !== null) {
if ($this->configCache->getP($uid, $cat) === '!<unset>!') {
return $default_value;
}
}
if (isset($a->config[$uid][$cat][$k])) {
if ($a->config[$uid][$cat][$k] === '!<unset>!') {
if ($this->configCache->getP($uid, $cat, $k) !== null) {
if ($this->configCache->getP($uid, $cat, $k) === '!<unset>!') {
return $default_value;
}
return $a->config[$uid][$cat][$k];
return $this->configCache->getP($uid, $cat, $k);
}
}
@ -59,13 +74,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);
$this->configCache->setP($uid, $cat, $k, $val);
$this->in_db[$uid][$cat][$k] = true;
return $val;
} else {
self::getApp()->setPConfigValue($uid, $cat, $k, '!<unset>!');
$this->configCache->setP($uid, $cat, $k, '!<unset>!');
$this->in_db[$uid][$cat][$k] = false;
@ -73,6 +88,9 @@ class JITPConfigAdapter extends BaseObject implements IPConfigAdapter
}
}
/**
* {@inheritdoc}
*/
public function set($uid, $cat, $k, $value)
{
// We store our setting values in a string variable.
@ -86,7 +104,7 @@ class JITPConfigAdapter extends BaseObject implements IPConfigAdapter
return true;
}
self::getApp()->setPConfigValue($uid, $cat, $k, $value);
$this->configCache->setP($uid, $cat, $k, $value);
// manage array value
$dbvalue = (is_array($value) ? serialize($value) : $dbvalue);
@ -100,9 +118,12 @@ class JITPConfigAdapter extends BaseObject implements IPConfigAdapter
return $result;
}
/**
* {@inheritdoc}
*/
public function delete($uid, $cat, $k)
{
self::getApp()->deletePConfigValue($uid, $cat, $k);
$this->configCache->deleteP($uid, $cat, $k);
if (!empty($this->in_db[$uid][$cat][$k])) {
unset($this->in_db[$uid][$cat][$k]);

View file

@ -3,7 +3,6 @@
namespace Friendica\Core\Config;
use Exception;
use Friendica\BaseObject;
use Friendica\Database\DBA;
/**
@ -13,15 +12,27 @@ use Friendica\Database\DBA;
*
* @author Hypolite Petovan <hypolite@mrpetovan.com>
*/
class PreloadConfigAdapter extends BaseObject implements IConfigAdapter
class PreloadConfigAdapter implements IConfigAdapter
{
private $config_loaded = false;
public function __construct()
/**
* @var IConfigCache The config cache of this driver
*/
private $configCache;
/**
* @param IConfigCache $configCache The config cache of this driver
*/
public function __construct(IConfigCache $configCache)
{
$this->configCache = $configCache;
$this->load();
}
/**
* {@inheritdoc}
*/
public function load($family = 'config')
{
if ($this->config_loaded) {
@ -30,27 +41,33 @@ 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']);
$this->configCache->set($config['cat'], $config['k'], $config['v']);
}
DBA::close($configs);
$this->config_loaded = true;
}
/**
* {@inheritdoc}
*/
public function get($cat, $k, $default_value = null, $refresh = false)
{
if ($refresh) {
$config = DBA::selectFirst('config', ['v'], ['cat' => $cat, 'k' => $k]);
if (DBA::isResult($config)) {
self::getApp()->setConfigValue($cat, $k, $config['v']);
$this->configCache->set($cat, $k, $config['v']);
}
}
$return = self::getApp()->getConfigValue($cat, $k, $default_value);
$return = $this->configCache->get($cat, $k, $default_value);
return $return;
}
/**
* {@inheritdoc}
*/
public function set($cat, $k, $value)
{
// We store our setting values as strings.
@ -58,11 +75,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 ($this->configCache->get($cat, $k) === $compare_value) {
return true;
}
self::getApp()->setConfigValue($cat, $k, $value);
$this->configCache->set($cat, $k, $value);
// manage array value
$dbvalue = is_array($value) ? serialize($value) : $value;
@ -75,9 +92,12 @@ class PreloadConfigAdapter extends BaseObject implements IConfigAdapter
return true;
}
/**
* {@inheritdoc}
*/
public function delete($cat, $k)
{
self::getApp()->deleteConfigValue($cat, $k);
$this->configCache->delete($cat, $k);
$result = DBA::delete('config', ['cat' => $cat, 'k' => $k]);

View file

@ -3,7 +3,6 @@
namespace Friendica\Core\Config;
use Exception;
use Friendica\BaseObject;
use Friendica\Database\DBA;
/**
@ -13,15 +12,31 @@ use Friendica\Database\DBA;
*
* @author Hypolite Petovan <hypolite@mrpetovan.com>
*/
class PreloadPConfigAdapter extends BaseObject implements IPConfigAdapter
class PreloadPConfigAdapter implements IPConfigAdapter
{
private $config_loaded = false;
public function __construct($uid)
/**
* The config cache of this adapter
* @var IPConfigCache
*/
private $configCache;
/**
* @param IPConfigCache $configCache The config cache of this adapter
* @param int $uid The UID of the current user
*/
public function __construct(IPConfigCache $configCache, $uid = null)
{
$this->load($uid, 'config');
$this->configCache = $configCache;
if (isset($uid)) {
$this->load($uid, 'config');
}
}
/**
* {@inheritdoc}
*/
public function load($uid, $family)
{
if ($this->config_loaded) {
@ -34,13 +49,16 @@ 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']);
$this->configCache->setP($uid, $pconfig['cat'], $pconfig['k'], $pconfig['v']);
}
DBA::close($pconfigs);
$this->config_loaded = true;
}
/**
* {@inheritdoc}
*/
public function get($uid, $cat, $k, $default_value = null, $refresh = false)
{
if (!$this->config_loaded) {
@ -50,17 +68,18 @@ 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']);
$this->configCache->setP($uid, $cat, $k, $config['v']);
} else {
self::getApp()->deletePConfigValue($uid, $cat, $k);
$this->configCache->deleteP($uid, $cat, $k);
}
}
$return = self::getApp()->getPConfigValue($uid, $cat, $k, $default_value);
return $return;
return $this->configCache->getP($uid, $cat, $k, $default_value);;
}
/**
* {@inheritdoc}
*/
public function set($uid, $cat, $k, $value)
{
if (!$this->config_loaded) {
@ -71,11 +90,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 ($this->configCache->getP($uid, $cat, $k) === $compare_value) {
return true;
}
self::getApp()->setPConfigValue($uid, $cat, $k, $value);
$this->configCache->setP($uid, $cat, $k, $value);
// manage array value
$dbvalue = is_array($value) ? serialize($value) : $value;
@ -88,13 +107,16 @@ class PreloadPConfigAdapter extends BaseObject implements IPConfigAdapter
return true;
}
/**
* {@inheritdoc}
*/
public function delete($uid, $cat, $k)
{
if (!$this->config_loaded) {
$this->load($uid, $cat);
}
self::getApp()->deletePConfigValue($uid, $cat, $k);
$this->configCache->deleteP($uid, $cat, $k);
$result = DBA::delete('pconfig', ['uid' => $uid, 'cat' => $cat, 'k' => $k]);

View file

@ -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 = $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");
@ -158,7 +158,7 @@ HELP;
$installer->resetChecks();
if (!$installer->installDatabase()) {
if (!$installer->installDatabase($a->getBasePath())) {
$errorMessage = $this->extractErrors($installer->getChecks());
throw new RuntimeException($errorMessage);
}

View file

@ -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);
@ -124,12 +124,13 @@ HELP;
$cat = $this->getArgument(0);
Core\Config::load($cat);
if (!is_null($a->config[$cat])) {
if ($a->getConfig()->get($cat) !== null) {
$this->out("[{$cat}]");
foreach ($a->config[$cat] as $key => $value) {
$catVal = $a->getConfig()->get($cat);
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);
@ -147,12 +148,13 @@ 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 = $a->getConfig()->getAll();
foreach ($config as $cat => $section) {
if (is_array($section)) {
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);

View file

@ -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":

View file

@ -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";

View file

@ -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,9 +43,7 @@ HELP;
throw new \Asika\SimpleConsole\CommandArgsException('Too many arguments');
}
$a = \get_app();
$php_path = $a->getConfigValue('config', 'php_path', 'php');
$php_path = BaseObject::getApp()->getConfig()->get('config', 'php_path', 'php');
if ($this->getOption('v')) {
$this->out('Directory: src');

View file

@ -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;

View file

@ -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;

View file

@ -8,9 +8,6 @@
*/
namespace Friendica\Core;
use Friendica\App;
use Friendica\BaseObject;
/**
* @brief Management of user configuration storage
* Note:
@ -18,52 +15,55 @@ 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
{
/**
* @var \Friendica\Core\Config\IPConfigAdapter
* @var Config\IPConfigAdapter
*/
private static $adapter = null;
private static $adapter;
public static function init($uid)
/**
* @var Config\IPConfigCache
*/
private static $cache;
/**
* Initialize the config with only the cache
*
* @param Config\IPConfigCache $cache The configuration cache
*/
public static function init(Config\IPConfigCache $cache)
{
$a = self::getApp();
self::$cache = $cache;
}
// Database isn't ready or populated yet
if (!$a->getMode()->has(App\Mode::DBCONFIGAVAILABLE)) {
return;
}
if ($a->getConfigValue('system', 'config_adapter') == 'preload') {
self::$adapter = new Config\PreloadPConfigAdapter($uid);
} else {
self::$adapter = new Config\JITPConfigAdapter();
}
/**
* Add the adapter for DB-backend
*
* @param Config\IPConfigAdapter $adapter
*/
public static function setAdapter(Config\IPConfigAdapter $adapter)
{
self::$adapter = $adapter;
}
/**
* @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].
* 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
*
* @return void
* @throws \Friendica\Network\HTTPException\InternalServerErrorException
*/
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);
}
@ -72,7 +72,8 @@ 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 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
@ -81,17 +82,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::$cache->getP($uid, $family, $key, $default_value);
}
return self::$adapter->get($uid, $family, $key, $default_value, $refresh);
@ -111,17 +106,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::$cache->setP($uid, $family, $key, $value);
}
return self::$adapter->set($uid, $family, $key, $value);
@ -130,25 +119,20 @@ 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]
* 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
* @param string $key The configuration key to delete
*
* @return mixed
* @throws \Friendica\Network\HTTPException\InternalServerErrorException
*/
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::$cache->deleteP($uid, $family, $key);
}
return self::$adapter->delete($uid, $family, $key);

View file

@ -286,6 +286,61 @@ 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'];
}
/**
* @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()

View file

@ -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 '';