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