ConfigManager.php 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394
  1. <?php
  2. // FIXME! Namespaces...
  3. require_once 'ConfigIO.php';
  4. require_once 'ConfigJson.php';
  5. require_once 'ConfigPhp.php';
  6. /**
  7. * Class ConfigManager
  8. *
  9. * Manages all Shaarli's settings.
  10. * See the documentation for more information on settings:
  11. * - doc/Shaarli-configuration.html
  12. * - https://github.com/shaarli/Shaarli/wiki/Shaarli-configuration
  13. */
  14. class ConfigManager
  15. {
  16. /**
  17. * @var string Flag telling a setting is not found.
  18. */
  19. protected static $NOT_FOUND = 'NOT_FOUND';
  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. $this->loadedConfig = $this->configIO->read($this->getConfigFileExt());
  74. $this->setDefaultValues();
  75. }
  76. /**
  77. * Get a setting.
  78. *
  79. * Supports nested settings with dot separated keys.
  80. * Eg. 'config.stuff.option' will find $conf[config][stuff][option],
  81. * or in JSON:
  82. * { "config": { "stuff": {"option": "mysetting" } } } }
  83. *
  84. * @param string $setting Asked setting, keys separated with dots.
  85. * @param string $default Default value if not found.
  86. *
  87. * @return mixed Found setting, or the default value.
  88. */
  89. public function get($setting, $default = '')
  90. {
  91. // During the ConfigIO transition, map legacy settings to the new ones.
  92. if ($this->configIO instanceof ConfigPhp && isset(ConfigPhp::$LEGACY_KEYS_MAPPING[$setting])) {
  93. $setting = ConfigPhp::$LEGACY_KEYS_MAPPING[$setting];
  94. }
  95. $settings = explode('.', $setting);
  96. $value = self::getConfig($settings, $this->loadedConfig);
  97. if ($value === self::$NOT_FOUND) {
  98. return $default;
  99. }
  100. return $value;
  101. }
  102. /**
  103. * Set a setting, and eventually write it.
  104. *
  105. * Supports nested settings with dot separated keys.
  106. *
  107. * @param string $setting Asked setting, keys separated with dots.
  108. * @param string $value Value to set.
  109. * @param bool $write Write the new setting in the config file, default false.
  110. * @param bool $isLoggedIn User login state, default false.
  111. *
  112. * @throws Exception Invalid
  113. */
  114. public function set($setting, $value, $write = false, $isLoggedIn = false)
  115. {
  116. if (empty($setting) || ! is_string($setting)) {
  117. throw new Exception('Invalid setting key parameter. String expected, got: '. gettype($setting));
  118. }
  119. // During the ConfigIO transition, map legacy settings to the new ones.
  120. if ($this->configIO instanceof ConfigPhp && isset(ConfigPhp::$LEGACY_KEYS_MAPPING[$setting])) {
  121. $setting = ConfigPhp::$LEGACY_KEYS_MAPPING[$setting];
  122. }
  123. $settings = explode('.', $setting);
  124. self::setConfig($settings, $value, $this->loadedConfig);
  125. if ($write) {
  126. $this->write($isLoggedIn);
  127. }
  128. }
  129. /**
  130. * Check if a settings exists.
  131. *
  132. * Supports nested settings with dot separated keys.
  133. *
  134. * @param string $setting Asked setting, keys separated with dots.
  135. *
  136. * @return bool true if the setting exists, false otherwise.
  137. */
  138. public function exists($setting)
  139. {
  140. // During the ConfigIO transition, map legacy settings to the new ones.
  141. if ($this->configIO instanceof ConfigPhp && isset(ConfigPhp::$LEGACY_KEYS_MAPPING[$setting])) {
  142. $setting = ConfigPhp::$LEGACY_KEYS_MAPPING[$setting];
  143. }
  144. $settings = explode('.', $setting);
  145. $value = self::getConfig($settings, $this->loadedConfig);
  146. if ($value === self::$NOT_FOUND) {
  147. return false;
  148. }
  149. return true;
  150. }
  151. /**
  152. * Call the config writer.
  153. *
  154. * @param bool $isLoggedIn User login state.
  155. *
  156. * @return bool True if the configuration has been successfully written, false otherwise.
  157. *
  158. * @throws MissingFieldConfigException: a mandatory field has not been provided in $conf.
  159. * @throws UnauthorizedConfigException: user is not authorize to change configuration.
  160. * @throws IOException: an error occurred while writing the new config file.
  161. */
  162. public function write($isLoggedIn)
  163. {
  164. // These fields are required in configuration.
  165. $mandatoryFields = array(
  166. 'credentials.login',
  167. 'credentials.hash',
  168. 'credentials.salt',
  169. 'security.session_protection_disabled',
  170. 'general.timezone',
  171. 'general.title',
  172. 'general.header_link',
  173. 'privacy.default_private_links',
  174. 'redirector.url',
  175. );
  176. // Only logged in user can alter config.
  177. if (is_file($this->getConfigFileExt()) && !$isLoggedIn) {
  178. throw new UnauthorizedConfigException();
  179. }
  180. // Check that all mandatory fields are provided in $conf.
  181. foreach ($mandatoryFields as $field) {
  182. if (! $this->exists($field)) {
  183. throw new MissingFieldConfigException($field);
  184. }
  185. }
  186. return $this->configIO->write($this->getConfigFileExt(), $this->loadedConfig);
  187. }
  188. /**
  189. * Set the config file path (without extension).
  190. *
  191. * @param string $configFile File path.
  192. */
  193. public function setConfigFile($configFile)
  194. {
  195. $this->configFile = $configFile;
  196. }
  197. /**
  198. * Return the configuration file path (without extension).
  199. *
  200. * @return string Config path.
  201. */
  202. public function getConfigFile()
  203. {
  204. return $this->configFile;
  205. }
  206. /**
  207. * Get the configuration file path with its extension.
  208. *
  209. * @return string Config file path.
  210. */
  211. public function getConfigFileExt()
  212. {
  213. return $this->configFile . $this->configIO->getExtension();
  214. }
  215. /**
  216. * Recursive function which find asked setting in the loaded config.
  217. *
  218. * @param array $settings Ordered array which contains keys to find.
  219. * @param array $conf Loaded settings, then sub-array.
  220. *
  221. * @return mixed Found setting or NOT_FOUND flag.
  222. */
  223. protected static function getConfig($settings, $conf)
  224. {
  225. if (!is_array($settings) || count($settings) == 0) {
  226. return self::$NOT_FOUND;
  227. }
  228. $setting = array_shift($settings);
  229. if (!isset($conf[$setting])) {
  230. return self::$NOT_FOUND;
  231. }
  232. if (count($settings) > 0) {
  233. return self::getConfig($settings, $conf[$setting]);
  234. }
  235. return $conf[$setting];
  236. }
  237. /**
  238. * Recursive function which find asked setting in the loaded config.
  239. *
  240. * @param array $settings Ordered array which contains keys to find.
  241. * @param mixed $value
  242. * @param array $conf Loaded settings, then sub-array.
  243. *
  244. * @return mixed Found setting or NOT_FOUND flag.
  245. */
  246. protected static function setConfig($settings, $value, &$conf)
  247. {
  248. if (!is_array($settings) || count($settings) == 0) {
  249. return self::$NOT_FOUND;
  250. }
  251. $setting = array_shift($settings);
  252. if (count($settings) > 0) {
  253. return self::setConfig($settings, $value, $conf[$setting]);
  254. }
  255. $conf[$setting] = $value;
  256. }
  257. /**
  258. * Set a bunch of default values allowing Shaarli to start without a config file.
  259. */
  260. protected function setDefaultValues()
  261. {
  262. $this->setEmpty('resource.data_dir', 'data');
  263. $this->setEmpty('resource.config', 'data/config.php');
  264. $this->setEmpty('resource.datastore', 'data/datastore.php');
  265. $this->setEmpty('resource.ban_file', 'data/ipbans.php');
  266. $this->setEmpty('resource.updates', 'data/updates.txt');
  267. $this->setEmpty('resource.log', 'data/log.txt');
  268. $this->setEmpty('resource.update_check', 'data/lastupdatecheck.txt');
  269. $this->setEmpty('resource.raintpl_tpl', 'tpl/');
  270. $this->setEmpty('resource.raintpl_tmp', 'tmp/');
  271. $this->setEmpty('resource.thumbnails_cache', 'cache');
  272. $this->setEmpty('resource.page_cache', 'pagecache');
  273. $this->setEmpty('security.ban_after', 4);
  274. $this->setEmpty('security.ban_duration', 1800);
  275. $this->setEmpty('security.session_protection_disabled', false);
  276. $this->setEmpty('security.open_shaarli', false);
  277. $this->setEmpty('general.header_link', '?');
  278. $this->setEmpty('general.links_per_page', 20);
  279. $this->setEmpty('general.enabled_plugins', array('qrcode'));
  280. $this->setEmpty('updates.check_updates', false);
  281. $this->setEmpty('updates.check_updates_branch', 'stable');
  282. $this->setEmpty('updates.check_updates_interval', 86400);
  283. $this->setEmpty('feed.rss_permalinks', true);
  284. $this->setEmpty('feed.show_atom', false);
  285. $this->setEmpty('privacy.default_private_links', false);
  286. $this->setEmpty('privacy.hide_public_links', false);
  287. $this->setEmpty('privacy.hide_timestamps', false);
  288. $this->setEmpty('thumbnail.enable_thumbnails', true);
  289. $this->setEmpty('thumbnail.enable_localcache', true);
  290. $this->setEmpty('redirector.url', '');
  291. $this->setEmpty('redirector.encode_url', true);
  292. $this->setEmpty('plugins', array());
  293. }
  294. /**
  295. * Set only if the setting does not exists.
  296. *
  297. * @param string $key Setting key.
  298. * @param mixed $value Setting value.
  299. */
  300. public function setEmpty($key, $value)
  301. {
  302. if (! $this->exists($key)) {
  303. $this->set($key, $value);
  304. }
  305. }
  306. /**
  307. * @return ConfigIO
  308. */
  309. public function getConfigIO()
  310. {
  311. return $this->configIO;
  312. }
  313. /**
  314. * @param ConfigIO $configIO
  315. */
  316. public function setConfigIO($configIO)
  317. {
  318. $this->configIO = $configIO;
  319. }
  320. }
  321. /**
  322. * Exception used if a mandatory field is missing in given configuration.
  323. */
  324. class MissingFieldConfigException extends Exception
  325. {
  326. public $field;
  327. /**
  328. * Construct exception.
  329. *
  330. * @param string $field field name missing.
  331. */
  332. public function __construct($field)
  333. {
  334. $this->field = $field;
  335. $this->message = 'Configuration value is required for '. $this->field;
  336. }
  337. }
  338. /**
  339. * Exception used if an unauthorized attempt to edit configuration has been made.
  340. */
  341. class UnauthorizedConfigException extends Exception
  342. {
  343. /**
  344. * Construct exception.
  345. */
  346. public function __construct()
  347. {
  348. $this->message = 'You are not authorized to alter config.';
  349. }
  350. }