ConfigManager.php 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369
  1. <?php
  2. namespace Shaarli\Config;
  3. use Shaarli\Config\Exception\MissingFieldConfigException;
  4. use Shaarli\Config\Exception\UnauthorizedConfigException;
  5. /**
  6. * Class ConfigManager
  7. *
  8. * Manages all Shaarli's settings.
  9. * See the documentation for more information on settings:
  10. * - doc/md/Shaarli-configuration.md
  11. * - https://shaarli.readthedocs.io/en/master/Shaarli-configuration/#configuration
  12. */
  13. class ConfigManager
  14. {
  15. /**
  16. * @var string Flag telling a setting is not found.
  17. */
  18. protected static $NOT_FOUND = 'NOT_FOUND';
  19. public static $DEFAULT_PLUGINS = array('qrcode');
  20. /**
  21. * @var string Config folder.
  22. */
  23. protected $configFile;
  24. /**
  25. * @var array Loaded config array.
  26. */
  27. protected $loadedConfig;
  28. /**
  29. * @var ConfigIO implementation instance.
  30. */
  31. protected $configIO;
  32. /**
  33. * Constructor.
  34. *
  35. * @param string $configFile Configuration file path without extension.
  36. */
  37. public function __construct($configFile = 'data/config')
  38. {
  39. $this->configFile = $configFile;
  40. $this->initialize();
  41. }
  42. /**
  43. * Reset the ConfigManager instance.
  44. */
  45. public function reset()
  46. {
  47. $this->initialize();
  48. }
  49. /**
  50. * Rebuild the loaded config array from config files.
  51. */
  52. public function reload()
  53. {
  54. $this->load();
  55. }
  56. /**
  57. * Initialize the ConfigIO and loaded the conf.
  58. */
  59. protected function initialize()
  60. {
  61. if (file_exists($this->configFile . '.php')) {
  62. $this->configIO = new ConfigPhp();
  63. } else {
  64. $this->configIO = new ConfigJson();
  65. }
  66. $this->load();
  67. }
  68. /**
  69. * Load configuration in the ConfigurationManager.
  70. */
  71. protected function load()
  72. {
  73. try {
  74. $this->loadedConfig = $this->configIO->read($this->getConfigFileExt());
  75. } catch (\Exception $e) {
  76. die($e->getMessage());
  77. }
  78. $this->setDefaultValues();
  79. }
  80. /**
  81. * Get a setting.
  82. *
  83. * Supports nested settings with dot separated keys.
  84. * Eg. 'config.stuff.option' will find $conf[config][stuff][option],
  85. * or in JSON:
  86. * { "config": { "stuff": {"option": "mysetting" } } } }
  87. *
  88. * @param string $setting Asked setting, keys separated with dots.
  89. * @param string $default Default value if not found.
  90. *
  91. * @return mixed Found setting, or the default value.
  92. */
  93. public function get($setting, $default = '')
  94. {
  95. // During the ConfigIO transition, map legacy settings to the new ones.
  96. if ($this->configIO instanceof ConfigPhp && isset(ConfigPhp::$LEGACY_KEYS_MAPPING[$setting])) {
  97. $setting = ConfigPhp::$LEGACY_KEYS_MAPPING[$setting];
  98. }
  99. $settings = explode('.', $setting);
  100. $value = self::getConfig($settings, $this->loadedConfig);
  101. if ($value === self::$NOT_FOUND) {
  102. return $default;
  103. }
  104. return $value;
  105. }
  106. /**
  107. * Set a setting, and eventually write it.
  108. *
  109. * Supports nested settings with dot separated keys.
  110. *
  111. * @param string $setting Asked setting, keys separated with dots.
  112. * @param string $value Value to set.
  113. * @param bool $write Write the new setting in the config file, default false.
  114. * @param bool $isLoggedIn User login state, default false.
  115. *
  116. * @throws \Exception Invalid
  117. */
  118. public function set($setting, $value, $write = false, $isLoggedIn = false)
  119. {
  120. if (empty($setting) || ! is_string($setting)) {
  121. throw new \Exception('Invalid setting key parameter. String expected, got: '. gettype($setting));
  122. }
  123. // During the ConfigIO transition, map legacy settings to the new ones.
  124. if ($this->configIO instanceof ConfigPhp && isset(ConfigPhp::$LEGACY_KEYS_MAPPING[$setting])) {
  125. $setting = ConfigPhp::$LEGACY_KEYS_MAPPING[$setting];
  126. }
  127. $settings = explode('.', $setting);
  128. self::setConfig($settings, $value, $this->loadedConfig);
  129. if ($write) {
  130. $this->write($isLoggedIn);
  131. }
  132. }
  133. /**
  134. * Check if a settings exists.
  135. *
  136. * Supports nested settings with dot separated keys.
  137. *
  138. * @param string $setting Asked setting, keys separated with dots.
  139. *
  140. * @return bool true if the setting exists, false otherwise.
  141. */
  142. public function exists($setting)
  143. {
  144. // During the ConfigIO transition, map legacy settings to the new ones.
  145. if ($this->configIO instanceof ConfigPhp && isset(ConfigPhp::$LEGACY_KEYS_MAPPING[$setting])) {
  146. $setting = ConfigPhp::$LEGACY_KEYS_MAPPING[$setting];
  147. }
  148. $settings = explode('.', $setting);
  149. $value = self::getConfig($settings, $this->loadedConfig);
  150. if ($value === self::$NOT_FOUND) {
  151. return false;
  152. }
  153. return true;
  154. }
  155. /**
  156. * Call the config writer.
  157. *
  158. * @param bool $isLoggedIn User login state.
  159. *
  160. * @return bool True if the configuration has been successfully written, false otherwise.
  161. *
  162. * @throws MissingFieldConfigException: a mandatory field has not been provided in $conf.
  163. * @throws UnauthorizedConfigException: user is not authorize to change configuration.
  164. * @throws \IOException: an error occurred while writing the new config file.
  165. */
  166. public function write($isLoggedIn)
  167. {
  168. // These fields are required in configuration.
  169. $mandatoryFields = array(
  170. 'credentials.login',
  171. 'credentials.hash',
  172. 'credentials.salt',
  173. 'security.session_protection_disabled',
  174. 'general.timezone',
  175. 'general.title',
  176. 'general.header_link',
  177. 'privacy.default_private_links',
  178. 'redirector.url',
  179. );
  180. // Only logged in user can alter config.
  181. if (is_file($this->getConfigFileExt()) && !$isLoggedIn) {
  182. throw new UnauthorizedConfigException();
  183. }
  184. // Check that all mandatory fields are provided in $conf.
  185. foreach ($mandatoryFields as $field) {
  186. if (! $this->exists($field)) {
  187. throw new MissingFieldConfigException($field);
  188. }
  189. }
  190. return $this->configIO->write($this->getConfigFileExt(), $this->loadedConfig);
  191. }
  192. /**
  193. * Set the config file path (without extension).
  194. *
  195. * @param string $configFile File path.
  196. */
  197. public function setConfigFile($configFile)
  198. {
  199. $this->configFile = $configFile;
  200. }
  201. /**
  202. * Return the configuration file path (without extension).
  203. *
  204. * @return string Config path.
  205. */
  206. public function getConfigFile()
  207. {
  208. return $this->configFile;
  209. }
  210. /**
  211. * Get the configuration file path with its extension.
  212. *
  213. * @return string Config file path.
  214. */
  215. public function getConfigFileExt()
  216. {
  217. return $this->configFile . $this->configIO->getExtension();
  218. }
  219. /**
  220. * Recursive function which find asked setting in the loaded config.
  221. *
  222. * @param array $settings Ordered array which contains keys to find.
  223. * @param array $conf Loaded settings, then sub-array.
  224. *
  225. * @return mixed Found setting or NOT_FOUND flag.
  226. */
  227. protected static function getConfig($settings, $conf)
  228. {
  229. if (!is_array($settings) || count($settings) == 0) {
  230. return self::$NOT_FOUND;
  231. }
  232. $setting = array_shift($settings);
  233. if (!isset($conf[$setting])) {
  234. return self::$NOT_FOUND;
  235. }
  236. if (count($settings) > 0) {
  237. return self::getConfig($settings, $conf[$setting]);
  238. }
  239. return $conf[$setting];
  240. }
  241. /**
  242. * Recursive function which find asked setting in the loaded config.
  243. *
  244. * @param array $settings Ordered array which contains keys to find.
  245. * @param mixed $value
  246. * @param array $conf Loaded settings, then sub-array.
  247. *
  248. * @return mixed Found setting or NOT_FOUND flag.
  249. */
  250. protected static function setConfig($settings, $value, &$conf)
  251. {
  252. if (!is_array($settings) || count($settings) == 0) {
  253. return self::$NOT_FOUND;
  254. }
  255. $setting = array_shift($settings);
  256. if (count($settings) > 0) {
  257. return self::setConfig($settings, $value, $conf[$setting]);
  258. }
  259. $conf[$setting] = $value;
  260. }
  261. /**
  262. * Set a bunch of default values allowing Shaarli to start without a config file.
  263. */
  264. protected function setDefaultValues()
  265. {
  266. $this->setEmpty('resource.data_dir', 'data');
  267. $this->setEmpty('resource.config', 'data/config.php');
  268. $this->setEmpty('resource.datastore', 'data/datastore.php');
  269. $this->setEmpty('resource.ban_file', 'data/ipbans.php');
  270. $this->setEmpty('resource.updates', 'data/updates.txt');
  271. $this->setEmpty('resource.log', 'data/log.txt');
  272. $this->setEmpty('resource.update_check', 'data/lastupdatecheck.txt');
  273. $this->setEmpty('resource.history', 'data/history.php');
  274. $this->setEmpty('resource.raintpl_tpl', 'tpl/');
  275. $this->setEmpty('resource.theme', 'default');
  276. $this->setEmpty('resource.raintpl_tmp', 'tmp/');
  277. $this->setEmpty('resource.thumbnails_cache', 'cache');
  278. $this->setEmpty('resource.page_cache', 'pagecache');
  279. $this->setEmpty('security.ban_after', 4);
  280. $this->setEmpty('security.ban_duration', 1800);
  281. $this->setEmpty('security.session_protection_disabled', false);
  282. $this->setEmpty('security.open_shaarli', false);
  283. $this->setEmpty('security.allowed_protocols', ['ftp', 'ftps', 'magnet']);
  284. $this->setEmpty('general.header_link', '?');
  285. $this->setEmpty('general.links_per_page', 20);
  286. $this->setEmpty('general.enabled_plugins', self::$DEFAULT_PLUGINS);
  287. $this->setEmpty('updates.check_updates', false);
  288. $this->setEmpty('updates.check_updates_branch', 'stable');
  289. $this->setEmpty('updates.check_updates_interval', 86400);
  290. $this->setEmpty('feed.rss_permalinks', true);
  291. $this->setEmpty('feed.show_atom', true);
  292. $this->setEmpty('privacy.default_private_links', false);
  293. $this->setEmpty('privacy.hide_public_links', false);
  294. $this->setEmpty('privacy.hide_timestamps', false);
  295. $this->setEmpty('thumbnail.enable_thumbnails', true);
  296. $this->setEmpty('thumbnail.enable_localcache', true);
  297. $this->setEmpty('redirector.url', '');
  298. $this->setEmpty('redirector.encode_url', true);
  299. $this->setEmpty('plugins', array());
  300. }
  301. /**
  302. * Set only if the setting does not exists.
  303. *
  304. * @param string $key Setting key.
  305. * @param mixed $value Setting value.
  306. */
  307. public function setEmpty($key, $value)
  308. {
  309. if (! $this->exists($key)) {
  310. $this->set($key, $value);
  311. }
  312. }
  313. /**
  314. * @return ConfigIO
  315. */
  316. public function getConfigIO()
  317. {
  318. return $this->configIO;
  319. }
  320. /**
  321. * @param ConfigIO $configIO
  322. */
  323. public function setConfigIO($configIO)
  324. {
  325. $this->configIO = $configIO;
  326. }
  327. }