ConfigManager.php 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422
  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 mixed $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(t('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. * Remove a config element from the config file.
  135. *
  136. * @param string $setting Asked setting, keys separated with dots.
  137. * @param bool $write Write the new setting in the config file, default false.
  138. * @param bool $isLoggedIn User login state, default false.
  139. *
  140. * @throws \Exception Invalid
  141. */
  142. public function remove($setting, $write = false, $isLoggedIn = false)
  143. {
  144. if (empty($setting) || ! is_string($setting)) {
  145. throw new \Exception(t('Invalid setting key parameter. String expected, got: '). gettype($setting));
  146. }
  147. // During the ConfigIO transition, map legacy settings to the new ones.
  148. if ($this->configIO instanceof ConfigPhp && isset(ConfigPhp::$LEGACY_KEYS_MAPPING[$setting])) {
  149. $setting = ConfigPhp::$LEGACY_KEYS_MAPPING[$setting];
  150. }
  151. $settings = explode('.', $setting);
  152. self::removeConfig($settings, $this->loadedConfig);
  153. if ($write) {
  154. $this->write($isLoggedIn);
  155. }
  156. }
  157. /**
  158. * Check if a settings exists.
  159. *
  160. * Supports nested settings with dot separated keys.
  161. *
  162. * @param string $setting Asked setting, keys separated with dots.
  163. *
  164. * @return bool true if the setting exists, false otherwise.
  165. */
  166. public function exists($setting)
  167. {
  168. // During the ConfigIO transition, map legacy settings to the new ones.
  169. if ($this->configIO instanceof ConfigPhp && isset(ConfigPhp::$LEGACY_KEYS_MAPPING[$setting])) {
  170. $setting = ConfigPhp::$LEGACY_KEYS_MAPPING[$setting];
  171. }
  172. $settings = explode('.', $setting);
  173. $value = self::getConfig($settings, $this->loadedConfig);
  174. if ($value === self::$NOT_FOUND) {
  175. return false;
  176. }
  177. return true;
  178. }
  179. /**
  180. * Call the config writer.
  181. *
  182. * @param bool $isLoggedIn User login state.
  183. *
  184. * @return bool True if the configuration has been successfully written, false otherwise.
  185. *
  186. * @throws MissingFieldConfigException: a mandatory field has not been provided in $conf.
  187. * @throws UnauthorizedConfigException: user is not authorize to change configuration.
  188. * @throws \IOException: an error occurred while writing the new config file.
  189. */
  190. public function write($isLoggedIn)
  191. {
  192. // These fields are required in configuration.
  193. $mandatoryFields = array(
  194. 'credentials.login',
  195. 'credentials.hash',
  196. 'credentials.salt',
  197. 'security.session_protection_disabled',
  198. 'general.timezone',
  199. 'general.title',
  200. 'general.header_link',
  201. 'privacy.default_private_links',
  202. 'redirector.url',
  203. );
  204. // Only logged in user can alter config.
  205. if (is_file($this->getConfigFileExt()) && !$isLoggedIn) {
  206. throw new UnauthorizedConfigException();
  207. }
  208. // Check that all mandatory fields are provided in $conf.
  209. foreach ($mandatoryFields as $field) {
  210. if (! $this->exists($field)) {
  211. throw new MissingFieldConfigException($field);
  212. }
  213. }
  214. return $this->configIO->write($this->getConfigFileExt(), $this->loadedConfig);
  215. }
  216. /**
  217. * Set the config file path (without extension).
  218. *
  219. * @param string $configFile File path.
  220. */
  221. public function setConfigFile($configFile)
  222. {
  223. $this->configFile = $configFile;
  224. }
  225. /**
  226. * Return the configuration file path (without extension).
  227. *
  228. * @return string Config path.
  229. */
  230. public function getConfigFile()
  231. {
  232. return $this->configFile;
  233. }
  234. /**
  235. * Get the configuration file path with its extension.
  236. *
  237. * @return string Config file path.
  238. */
  239. public function getConfigFileExt()
  240. {
  241. return $this->configFile . $this->configIO->getExtension();
  242. }
  243. /**
  244. * Recursive function which find asked setting in the loaded config.
  245. *
  246. * @param array $settings Ordered array which contains keys to find.
  247. * @param array $conf Loaded settings, then sub-array.
  248. *
  249. * @return mixed Found setting or NOT_FOUND flag.
  250. */
  251. protected static function getConfig($settings, $conf)
  252. {
  253. if (!is_array($settings) || count($settings) == 0) {
  254. return self::$NOT_FOUND;
  255. }
  256. $setting = array_shift($settings);
  257. if (!isset($conf[$setting])) {
  258. return self::$NOT_FOUND;
  259. }
  260. if (count($settings) > 0) {
  261. return self::getConfig($settings, $conf[$setting]);
  262. }
  263. return $conf[$setting];
  264. }
  265. /**
  266. * Recursive function which find asked setting in the loaded config.
  267. *
  268. * @param array $settings Ordered array which contains keys to find.
  269. * @param mixed $value
  270. * @param array $conf Loaded settings, then sub-array.
  271. *
  272. * @return mixed Found setting or NOT_FOUND flag.
  273. */
  274. protected static function setConfig($settings, $value, &$conf)
  275. {
  276. if (!is_array($settings) || count($settings) == 0) {
  277. return self::$NOT_FOUND;
  278. }
  279. $setting = array_shift($settings);
  280. if (count($settings) > 0) {
  281. return self::setConfig($settings, $value, $conf[$setting]);
  282. }
  283. $conf[$setting] = $value;
  284. }
  285. /**
  286. * Recursive function which find asked setting in the loaded config and deletes it.
  287. *
  288. * @param array $settings Ordered array which contains keys to find.
  289. * @param array $conf Loaded settings, then sub-array.
  290. *
  291. * @return mixed Found setting or NOT_FOUND flag.
  292. */
  293. protected static function removeConfig($settings, &$conf)
  294. {
  295. if (!is_array($settings) || count($settings) == 0) {
  296. return self::$NOT_FOUND;
  297. }
  298. $setting = array_shift($settings);
  299. if (count($settings) > 0) {
  300. return self::removeConfig($settings, $conf[$setting]);
  301. }
  302. unset($conf[$setting]);
  303. }
  304. /**
  305. * Set a bunch of default values allowing Shaarli to start without a config file.
  306. */
  307. protected function setDefaultValues()
  308. {
  309. $this->setEmpty('resource.data_dir', 'data');
  310. $this->setEmpty('resource.config', 'data/config.php');
  311. $this->setEmpty('resource.datastore', 'data/datastore.php');
  312. $this->setEmpty('resource.ban_file', 'data/ipbans.php');
  313. $this->setEmpty('resource.updates', 'data/updates.txt');
  314. $this->setEmpty('resource.log', 'data/log.txt');
  315. $this->setEmpty('resource.update_check', 'data/lastupdatecheck.txt');
  316. $this->setEmpty('resource.history', 'data/history.php');
  317. $this->setEmpty('resource.raintpl_tpl', 'tpl/');
  318. $this->setEmpty('resource.theme', 'default');
  319. $this->setEmpty('resource.raintpl_tmp', 'tmp/');
  320. $this->setEmpty('resource.thumbnails_cache', 'cache');
  321. $this->setEmpty('resource.page_cache', 'pagecache');
  322. $this->setEmpty('security.ban_after', 4);
  323. $this->setEmpty('security.ban_duration', 1800);
  324. $this->setEmpty('security.session_protection_disabled', false);
  325. $this->setEmpty('security.open_shaarli', false);
  326. $this->setEmpty('security.allowed_protocols', ['ftp', 'ftps', 'magnet']);
  327. $this->setEmpty('general.header_link', '?');
  328. $this->setEmpty('general.links_per_page', 20);
  329. $this->setEmpty('general.enabled_plugins', self::$DEFAULT_PLUGINS);
  330. $this->setEmpty('general.default_note_title', 'Note: ');
  331. $this->setEmpty('updates.check_updates', false);
  332. $this->setEmpty('updates.check_updates_branch', 'stable');
  333. $this->setEmpty('updates.check_updates_interval', 86400);
  334. $this->setEmpty('feed.rss_permalinks', true);
  335. $this->setEmpty('feed.show_atom', true);
  336. $this->setEmpty('privacy.default_private_links', false);
  337. $this->setEmpty('privacy.hide_public_links', false);
  338. $this->setEmpty('privacy.force_login', false);
  339. $this->setEmpty('privacy.hide_timestamps', false);
  340. // default state of the 'remember me' checkbox of the login form
  341. $this->setEmpty('privacy.remember_user_default', true);
  342. $this->setEmpty('redirector.url', '');
  343. $this->setEmpty('redirector.encode_url', true);
  344. $this->setEmpty('translation.language', 'auto');
  345. $this->setEmpty('translation.mode', 'php');
  346. $this->setEmpty('translation.extensions', []);
  347. $this->setEmpty('plugins', array());
  348. }
  349. /**
  350. * Set only if the setting does not exists.
  351. *
  352. * @param string $key Setting key.
  353. * @param mixed $value Setting value.
  354. */
  355. public function setEmpty($key, $value)
  356. {
  357. if (! $this->exists($key)) {
  358. $this->set($key, $value);
  359. }
  360. }
  361. /**
  362. * @return ConfigIO
  363. */
  364. public function getConfigIO()
  365. {
  366. return $this->configIO;
  367. }
  368. /**
  369. * @param ConfigIO $configIO
  370. */
  371. public function setConfigIO($configIO)
  372. {
  373. $this->configIO = $configIO;
  374. }
  375. }