]> git.immae.eu Git - github/shaarli/Shaarli.git/blob - application/config/ConfigJson.php
Rename configuration keys and fix GLOBALS in templates
[github/shaarli/Shaarli.git] / application / config / ConfigJson.php
1 <?php
2
3 /**
4 * Class ConfigJson (ConfigIO implementation)
5 *
6 * Handle Shaarli's JSON configuration file.
7 */
8 class ConfigJson implements ConfigIO
9 {
10 /**
11 * @inheritdoc
12 */
13 function read($filepath)
14 {
15 if (! is_readable($filepath)) {
16 return array();
17 }
18 $data = file_get_contents($filepath);
19 $data = str_replace(self::getPhpHeaders(), '', $data);
20 $data = json_decode($data, true);
21 if ($data === null) {
22 $error = json_last_error();
23 throw new Exception('An error occured while parsing JSON file: error code #'. $error);
24 }
25 return $data;
26 }
27
28 /**
29 * @inheritdoc
30 */
31 function write($filepath, $conf)
32 {
33 // JSON_PRETTY_PRINT is available from PHP 5.4.
34 $print = defined('JSON_PRETTY_PRINT') ? JSON_PRETTY_PRINT : 0;
35 $data = self::getPhpHeaders() . json_encode($conf, $print);
36 if (!file_put_contents($filepath, $data)) {
37 throw new IOException(
38 $filepath,
39 'Shaarli could not create the config file.
40 Please make sure Shaarli has the right to write in the folder is it installed in.'
41 );
42 }
43 }
44
45 /**
46 * @inheritdoc
47 */
48 function getExtension()
49 {
50 return '.json.php';
51 }
52
53 /**
54 * The JSON data is wrapped in a PHP file for security purpose.
55 * This way, even if the file is accessible, credentials and configuration won't be exposed.
56 *
57 * Note: this isn't a static field because concatenation isn't supported in field declaration before PHP 5.6.
58 *
59 * @return string PHP start tag and comment tag.
60 */
61 public static function getPhpHeaders()
62 {
63 return '<?php /*'. PHP_EOL;
64 }
65 }